diff --git a/AGENTS.md b/AGENTS.md index f78894f..80164a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,6 +86,25 @@ linters it shares. handle for `POLLERR` with `poll` after its callback on Linux, and watches it again; macOS reports no such error, and its `poll`, at 6 µs, would cost more than an event. +- libuv counts a timer in whole milliseconds from `uv_now`, its clock rounded + down, and uvloop rounds the delay to them, so a timer, as `asyncio.sleep`, + was due up to a millisecond before its time by `time.monotonic`, where the + loop of asyncio is never early, and the tests of Pyjoyment that measure a + sleep with `time.monotonic`, as `t/Pyjo/Steps.py`, failed now and then. + `call_later` of `_Loop`, which `call_at` of uvloop calls too, rounds the + delay up to a millisecond and adds the one that the clock loses, as + MagicStack/uvloop#755 does in uvloop, until it is released; a delay of no + time stays a `call_soon` of uvloop. +- `Pyjo.Reactor._finalize` defers the cleanup of a finalizer that runs below a + frame of a reactor or of its event loop, since pyjoyment/Pyjoyment#534, + which takes the file of the module of the class of the reactor, + `Pyjo/Reactor/Uvloop.py` with `_Loop`, wherever it is installed, and the + modules of `event_loop_modules`. The reactor inherits + `('asyncio', 'selectors')` and names no `uvloop`: the loop of uvloop is + compiled with Cython and makes no frames of Python, and below the code that + `uvloop.run` runs, the one place with frames of `uvloop/__init__.py`, is + `asyncio/runners.py`. A probe of `_finalize` over the suite of Pyjoyment on + the reactor found no frame of uvloop below any of its calls (#7). - `PYJO_ASYNCIO_SLOW_CALLBACK` sets the `slow_callback_duration` of a loop of its own, as for `Pyjo.Reactor.Asyncio`, which the loop of uvloop has too. - uvloop has wheels for CPython on Linux and macOS, not for PyPy or Windows, so @@ -194,7 +213,8 @@ uvloop: a loop of its own, a given loop, a loop that is running, of asyncio and of uvloop, a coroutine, `PYJO_ASYNCIO_SLOW_CALLBACK`, the child of a fork and its exit, the wakeup fd of the signals, the finalizer of an async generator in the debug mode, a stop in a callback of I/O, the blocking mode -of a handle and the writer of a pipe whose reader has closed it. +of a handle, the writer of a pipe whose reader has closed it and a timer +that is not due before its time. `t/docs/Reactor_Uvloop.py` runs the synopsis of the module, in both forms, as `t/docs` of Pyjoyment does. diff --git a/Pyjo/Reactor/Uvloop.py b/Pyjo/Reactor/Uvloop.py index bb1af0b..44bce69 100644 --- a/Pyjo/Reactor/Uvloop.py +++ b/Pyjo/Reactor/Uvloop.py @@ -64,7 +64,9 @@ def timeout(reactor): signals that a program sets with :func:`signal.set_wakeup_fd`, as the workers of :mod:`Pyjo.Server.Prefork` do, is written to on a signal while a loop of its own runs, as with the loop of :mod:`asyncio`, although uvloop sets one of -its own. +its own. A timer of a loop of its own, as :func:`asyncio.sleep`, is never due +before its time, as with the loop of :mod:`asyncio`, although libuv counts it +in whole milliseconds, so it may be up to two milliseconds late. uvloop runs on Linux and macOS, not on Windows, and on CPython, not on PyPy. The ``PYJO_ASYNCIO_SLOW_CALLBACK`` environment variable sets the @@ -89,6 +91,7 @@ def timeout(reactor): import asyncio import importlib.metadata +import math import os import select import signal @@ -154,6 +157,17 @@ def _halting(self) -> None: self._halt = None self._halted = True + # libuv counts a timer in whole milliseconds from its clock, which it rounds down, and uvloop rounds the delay, so + # that a timer, as asyncio.sleep, is due up to a millisecond before its time by time.monotonic, where the loop of + # asyncio is never early; the delay is rounded up, with the millisecond that the clock loses (MagicStack/uvloop#755). + # call_at of uvloop calls it too + def call_later( + self, delay: float, callback: Callable[..., Any], *args: Any, context: Any = None + ) -> asyncio.TimerHandle: + if 0 < delay < math.inf: + delay = (math.ceil(delay * 1000) + 1) / 1000 + return super().call_later(delay, callback, *args, context=context) + def __init__(self) -> None: super().__init__() self._rearm: set[int] = set() diff --git a/t/Reactor_Uvloop.py b/t/Reactor_Uvloop.py index 853351e..67852ce 100644 --- a/t/Reactor_Uvloop.py +++ b/t/Reactor_Uvloop.py @@ -681,4 +681,54 @@ def writer(reactor, writable): reactor.remove(write) os.close(write) +# Not in Mojolicious: libuv counts a timer in whole milliseconds of a clock that it rounds down, so that a timer of uvloop +# is due up to a millisecond before its time, by the clock of time.monotonic, where the loop of asyncio is never early +with subtest('Timer not due before its time'): + with Pyjo.Reactor.Uvloop.new() as reactor: + early = [] + + def timers(after, schedule, count=150): + # A start anywhere within a millisecond, which a start right after a timer is not + deadline = time.monotonic() + (count % 10) / 10000 + while time.monotonic() < deadline: + pass + start = time.monotonic() + + def due(*args): + if (elapsed := time.monotonic() - start) < after: + early.append(elapsed) + if count > 1: + timers(after, schedule, count - 1) + else: + reactor.stop() + + schedule(after, due) + + timers(0.002, lambda after, due: reactor.timer(after, due)) + reactor.start() + is_deeply_ok(early, [], 'timer of the reactor') + early.clear() + timers(0.002, lambda after, due: reactor.loop.call_later(after, due)) + reactor.start() + is_deeply_ok(early, [], 'call_later') + early.clear() + timers(0.002, lambda after, due: reactor.loop.call_at(reactor.loop.time() + after, due)) + reactor.start() + is_deeply_ok(early, [], 'call_at') + early.clear() + + async def sleeps(): + for i in range(150): + deadline = time.monotonic() + (i % 10) / 10000 + while time.monotonic() < deadline: + pass + start = time.monotonic() + await asyncio.sleep(0.002) + if (elapsed := time.monotonic() - start) < 0.002: + early.append(elapsed) + + reactor.run_coroutine(sleeps(), lambda value: reactor.stop(), lambda err: (early.append(err), reactor.stop())) + reactor.start() + is_deeply_ok(early, [], 'asyncio.sleep') + done_testing() diff --git a/uv.lock b/uv.lock index ccbcb8c..6b19ebf 100644 --- a/uv.lock +++ b/uv.lock @@ -372,7 +372,7 @@ docs = [{ name = "sphinx", marker = "python_full_version >= '3.14'", specifier = [[package]] name = "pyjoyment" version = "0.2.1.dev1" -source = { git = "https://github.com/pyjoyment/Pyjoyment?branch=main#5fe4702612d360ff5fd33c58f634de68c5abec64" } +source = { git = "https://github.com/pyjoyment/Pyjoyment?branch=main#b6d623eda74c341d9d1ff90ce054bdc22520bb27" } [[package]] name = "requests"