From 98b4a51589c00a8dd02082b203c75f6411230332 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Tue, 6 Oct 2026 18:56:53 +0300 Subject: [PATCH] run: an await cut short leaves the job's wake owed an interrupted or timed-out `await job` marked the job awaited forever, so it never woke the session when it finished (vents 12, 13). awaits are now counted while they wait and only a returning one claims the result; the same for remote references (whose interrupt cancels the remote await) and ssh command-mode jobs. Signed-off-by: dawn <90008@klbr.net> --- priv/python/albedo_plugins/remote.py | 62 ++++++++++++++++++++++------ priv/python/albedo_plugins/run.py | 35 ++++++++++++---- robot-docs/extensions.md | 4 +- test/e2e/job_wake_test.py | 30 ++++++++++++-- test/harness/remote_plugin_test.py | 19 +++++++++ 5 files changed, 124 insertions(+), 26 deletions(-) diff --git a/priv/python/albedo_plugins/remote.py b/priv/python/albedo_plugins/remote.py index ff4d54e3f..16d147433 100644 --- a/priv/python/albedo_plugins/remote.py +++ b/priv/python/albedo_plugins/remote.py @@ -270,7 +270,8 @@ class RemoteRef: self._label = label self._settled: Any = _UNSET self._withdrawn: bool = False - self._awaited = False # awaited here, so its result reaches this cell + self._awaited = False # an await here returned, so its result reached this cell + self._waiters = 0 # awaits here still waiting on it # --- mirrored job state: sync, like the local handle --- @@ -346,8 +347,9 @@ class RemoteRef: @property def _claimed(self) -> bool: - """Its result reached this side, so the job's wake is not owed.""" - return self._awaited or self._withdrawn + """Its result reached this side, or an await here is about to take it, + so the job's wake is not owed.""" + return self._awaited or self._waiters > 0 or self._withdrawn # --- the value surface: identical output to the local tool --- @@ -423,10 +425,20 @@ class RemoteRef: ) def __await__(self): - # Marked now, like a local job: the await crosses the connection only - # after the reply to the call, and a quick job is done before that. - self._awaited = True - return self._settle().__await__() + return self._wait().__await__() + + async def _wait(self) -> Any: + # Counted now, like a local job: the await crosses the connection only + # after the reply to the call, and a quick job is done before that. An + # await cut short interrupts the remote one too, so the remote job owes + # its wake again and this reference no longer claims it. + self._waiters += 1 + try: + result = await self._settle() + self._awaited = True + finally: + self._waiters -= 1 + return result async def _settle(self) -> Any: """Resolve the in-flight call; awaiting a live object awaits the object.""" @@ -1090,8 +1102,10 @@ class FallbackJob: self.started: float = loop.time() self.duration: float | None = None self.capture = capture_factory(self.id) - self._awaited = False + self._awaited = False # an await returned this job; its result reached them + self._waiters = 0 # awaits still waiting; one cut short leaves the wake owed self._read = False + self._announcer: asyncio.Task[None] | None = None self._connection = connection _fallback_live.add(self.id) _report_live() @@ -1148,13 +1162,24 @@ class FallbackJob: self.duration = loop.time() - self.started _fallback_live.discard(self.id) _report_live() - if host_call is not None and not self._awaited: - _ = loop.create_task(self._announce()) + self._owe_unread() return self + @property + def _unreported(self) -> bool: + """Finished, and its result has reached no one yet.""" + return not self._read and not self._awaited and not self._waiters + + def _owe_unread(self) -> None: + """Start the finished command's wake unless its result reached someone.""" + if host_call is None or not self._unreported: + return + if self._announcer is None or self._announcer.done(): + self._announcer = loop.create_task(self._announce()) + async def _announce(self) -> None: """Wake the session for this command, retrying while it runs.""" - while not self._read and not self._awaited: + while self._unreported: try: await host_call("jobs.completed", self._notice()) return @@ -1206,8 +1231,19 @@ class FallbackJob: self.capture.write_bytes(chunk) def __await__(self): - self._awaited = True - return asyncio.shield(self._task).__await__() + return self._wait().__await__() + + async def _wait(self) -> "FallbackJob": + """Wait for the command; an await cut short leaves its wake owed.""" + self._waiters += 1 + try: + await asyncio.shield(self._task) + self._awaited = True + finally: + self._waiters -= 1 + if self._task.done(): + self._owe_unread() + return self def poll(self) -> int | None: if self.exit_code is not None: diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 7e016e307..d4cada96f 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -12,8 +12,9 @@ but leaves its ProxyCommand in the group, and ending that ends the master. A job that finishes with its result unread wakes the session: the kernel tells the host, the host submits a user turn naming the job, and the model never has to poll or await. Reading the result (tail, poll, await, output.read) or -stopping the job withdraws the wake, and a busy session is retried until it -goes idle, so a notice can never overtake the read that satisfies it. Jobs +stopping the job withdraws the wake; an await cut short by an interrupt or a +deadline read nothing, so it leaves the wake owed. A busy session is retried +until it goes idle, so a notice can never overtake the read that satisfies it. Jobs still owed when the retry lands share one notice, and so one turn. """ @@ -285,7 +286,8 @@ class Job: self.termination: albedo_proc.Termination | None = None self.capture: OutputCapture = capture_factory(self.id) self.ending: asyncio.Task[albedo_proc.Termination] | None = None - self._awaited = False # someone awaited this job; its result reached them + self._awaited = False # an await returned this job; its result reached them + self._waiters = 0 # awaits still waiting; one cut short leaves the wake owed self._read = False # the finished result was read; no wake is owed self._remote = os.environ.get("ALBEDO_REMOTE_TARGET") or None self._starting = ( @@ -417,8 +419,7 @@ class Job: } ) release(self) - if host is not None and not self._awaited: - owe(self) + self._owe_unread() return self async def _drain(self, process: Command) -> int: @@ -435,8 +436,21 @@ class Job: return process.returncode def __await__(self) -> Generator[object, None, Job]: - self._awaited = True - return asyncio.shield(self.task).__await__() + return self._wait().__await__() + + async def _wait(self) -> Job: + """Wait for the job. An await cut short (an interrupted cell, a + wait_for deadline) never delivered the result, so the job still wakes + the session when it ends.""" + self._waiters += 1 + try: + await asyncio.shield(self.task) + self._awaited = True + finally: + self._waiters -= 1 + if self.task.done(): + self._owe_unread() + return self def poll(self): if self.exit_code is not None: @@ -471,7 +485,12 @@ class Job: @property def _unreported(self) -> bool: """Finished, and its result has reached no one yet.""" - return not self._read and not self._awaited + return not self._read and not self._awaited and not self._waiters + + def _owe_unread(self) -> None: + """Queue the finished job's wake unless its result reached someone.""" + if host is not None and self._unreported: + owe(self) def _facts(self) -> dict[str, object]: """What a wake notice says about this job.""" diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 7e1dcaa32..51a45d7b0 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -159,7 +159,7 @@ no heavy-job admission or process pausing; deadlines count wall time after spawn Output read watchers use weak references to bound job methods. They remain registered across early reads, so a read after completion still retires the notice. Forgetting or evicting an output channel removes its watcher. Job handles and output channels keep their separate retention order and existing limits. A retained output watcher does not keep an evicted job alive, and an explicitly held job keeps its own output after archive eviction. -`run(program, *args, cwd=, env=, stdin=, timeout=, service=)` starts one program, without a shell, as a supervised job that owns its process group: a deadline, a stop or kernel shutdown ends the whole group, and so does the command's own exit, except for members a process that moved out of the group still parents (`albedo_proc.adopted`). that keeps ssh's ControlPersist masters working from jobs: the master daemonizes out of the group but leaves its ProxyCommand in it, and ending the proxy ends the master, so every later ssh (and every hardware-key touch) would start over. a parent started after the job's leader came from the job; orphans, adopted by init or a subreaper that was running before, still go. `run` is synchronous and returns the handle; awaiting the handle waits for the program, so the instructions teach `job = run(...)` then `await job` — `job = await run(...)` would leave nothing bound when a cell deadline interrupts the wait, and the model would recover the running job through `jobs` or start it twice; output stays on the handle (`job.tail()`, `output.read(job.id)`) and finished handles stay addressable in `jobs`. a job that finishes with its result unread wakes the session: the kernel reports the completion through the `jobs` host route, and the session submits a user turn naming the job, its exit, and how to read it, so the model never polls or awaits a handle just to learn it finished. awaiting the job, reading its result, or stopping it retires the wake. a busy session is retried, not queued in gleam: the kernel retries the notice until the run ends or the result is read. live jobs pin the kernel against the idle sweep — a detached session is not released while background work still runs, local or remote, because releasing it would kill the job and the wake it owes. remote `run` jobs wake the same way — the remote kernel's host calls relay over the ssh connection into this session's route, and the notice names the host — and a mirror read (`rem_job.tail()`) tells the remote job it was read through one `poll` round trip. +`run(program, *args, cwd=, env=, stdin=, timeout=, service=)` starts one program, without a shell, as a supervised job that owns its process group: a deadline, a stop or kernel shutdown ends the whole group, and so does the command's own exit, except for members a process that moved out of the group still parents (`albedo_proc.adopted`). that keeps ssh's ControlPersist masters working from jobs: the master daemonizes out of the group but leaves its ProxyCommand in it, and ending the proxy ends the master, so every later ssh (and every hardware-key touch) would start over. a parent started after the job's leader came from the job; orphans, adopted by init or a subreaper that was running before, still go. `run` is synchronous and returns the handle; awaiting the handle waits for the program, so the instructions teach `job = run(...)` then `await job` — `job = await run(...)` would leave nothing bound when a cell deadline interrupts the wait, and the model would recover the running job through `jobs` or start it twice; output stays on the handle (`job.tail()`, `output.read(job.id)`) and finished handles stay addressable in `jobs`. a job that finishes with its result unread wakes the session: the kernel reports the completion through the `jobs` host route, and the session submits a user turn naming the job, its exit, and how to read it, so the model never polls or awaits a handle just to learn it finished. awaiting the job, reading its result, or stopping it retires the wake. an await cut short (the cell's deadline, an interrupt, a `wait_for` timeout) read nothing, so it leaves the wake owed, and one cut short after the job ended queues the wake itself: a model whose cell timed out on `await job` is told the job is still running and rightly waits for its notice. a busy session is retried, not queued in gleam: the kernel retries the notice until the run ends or the result is read. live jobs pin the kernel against the idle sweep — a detached session is not released while background work still runs, local or remote, because releasing it would kill the job and the wake it owes. remote `run` jobs wake the same way — the remote kernel's host calls relay over the ssh connection into this session's route, and the notice names the host — and a mirror read (`rem_job.tail()`) tells the remote job it was read through one `poll` round trip. `service=True` marks a program meant to keep running (a dev server, a watcher): it is recorded on the job and reported with the kernel's running jobs, and `warm` does not keep the cache warm for it ([cache warming](cache-warming.md)). a job written to disk with its group survives a daemon restart with the flag. @@ -207,7 +207,7 @@ the ssh options, control path, agent socket discovery, login-shell wrapper and b machine tools run on the remote kernel: `rem.run(program, *args)` starts a supervised job on the host immediately and synchronously, like local run — the handle exists right away, `job.tail()`, `job.id`, `job.exit_code`, `job.duration`, and `job.timed_out` answer synchronously from the mirrored output stream, `await job` waits for completion, and `await job.stop()` stops it. pipes run entirely on the host, chained before the one await: `job = rem.run("journalctl", "-u", "nginx", "--no-pager").pipe("rg", "error")`, `await job`, then `job.tail(lines=40)`. `tail(lines=)` and `exit_code` answer from the mirror; other job methods, like `head(lines=)`, are remote calls to await, and properties such as `job.pipeline` do not cross. session tools run where the daemon runs: `await rem.work.*` and `await rem.skills.*` relay over the connection to the local daemon's ledger and catalog. both kernels load the same content-hashed bundle, so a tool's remote shape matches its local one. every other call returns a reference that settles on its first await: values cross as real objects — dataclasses and list subclasses are rebuilt, so remote output prints exactly like local output — and a result that cannot cross comes back as a live reference whose methods are further remote calls. references passed back into remote calls stay references, not copies, including ones still in flight. one rule remains: a call whose local counterpart is synchronous (`rem.files.read`) still needs `await`, because the value itself crosses the network; handles and their state never do. -a remote job that finishes with its result unread wakes the session like a local one: the remote kernel's notice relays over the connection, and the owner drops it when a reference on this side already awaited or read the job. the mark is made when `await` starts, as for a local job, because the await reaches the remote kernel only after the call's own reply, and a quick job (`systemctl is-active` in a waiting loop) is done by then. the reply to the call that started a job carries its state, so a notice matches its reference before any mirror frame lands. the notice names the reference and `rem.output.read(id)`, since the job is in the remote kernel's `jobs`, not the model's. a call that fails before anything awaits it (`rem.run` with a bad argument) raises its error from the reference's synchronous accessors (`id`, `tail()`, `poll()`) and shows it in its repr, so a job left to wake the session cannot silently never start. +a remote job that finishes with its result unread wakes the session like a local one: the remote kernel's notice relays over the connection, and the owner drops it when a reference on this side already awaited or read the job. the mark is made when `await` starts, as for a local job, because the await reaches the remote kernel only after the call's own reply, and a quick job (`systemctl is-active` in a waiting loop) is done by then. an await cut short drops the mark, and its interrupt cancels the remote kernel's await too, so the remote job owes its wake again. the reply to the call that started a job carries its state, so a notice matches its reference before any mirror frame lands. the notice names the reference and `rem.output.read(id)`, since the job is in the remote kernel's `jobs`, not the model's. a call that fails before anything awaits it (`rem.run` with a bad argument) raises its error from the reference's synchronous accessors (`id`, `tail()`, `poll()`) and shows it in its repr, so a job left to wake the session cannot silently never start. images are the exception to "every harness tool runs remotely": a remote call is not a cell, so the remote kernel has no result to carry one. `await rem.show_image(path_or_bytes)` runs locally instead: it reads a remote path over the control connection (at most one byte past the 5 MiB a cell may carry) and attaches the bytes to the local cell through `api.attach_image`, so the image meets the same format, count, size and edge checks as `show_image`. it works in degraded mode too. diff --git a/test/e2e/job_wake_test.py b/test/e2e/job_wake_test.py index ca8625752..8d1fb3f48 100644 --- a/test/e2e/job_wake_test.py +++ b/test/e2e/job_wake_test.py @@ -6,7 +6,7 @@ import time import unittest import urllib.error -from harness import Albedo, Provider, exclusive, python, release_fifo, text +from harness import Albedo, Provider, Reply, exclusive, python, release_fifo, text # A daemon under this limit sweeps every half second, so the detached job # below outlives several sweeps. @@ -54,6 +54,14 @@ class JobWakeCase(unittest.TestCase): f"import sys\njob = run(sys.executable, '-c', {program!r})\njob.id" ) return python(code) + if last.get("role") == "user" and "await a slow job past its cell" in user: + program = ( + f"open({str(self.job_gate)!r}, 'rb').read(1); print('wake-done')" + ) + code = f"import sys\njob = run(sys.executable, '-c', {program!r})\nawait job" + return Reply( + "python", tool_arguments={"code": code, "timeout_ms": 1500} + ) return text("finished") def prepare(app): @@ -139,11 +147,11 @@ class JobWakeTests(JobWakeCase): time.sleep(2.5) self.assertEqual(len(self.users()), 3) - def start_blocked_job(self): + def start_blocked_job(self, prompt="start a slow job"): session = self.app.session() self.job_gate = self.app.workspace / "job-release" os.mkfifo(self.job_gate) - self.app.prompt(session, "start a slow job").close() + self.app.prompt(session, prompt).close() self.app.idle(session) self.assertEqual(len(self.users()), 2) return session @@ -210,6 +218,22 @@ class JobWakeTests(JobWakeCase): self.assertEqual(after["running_jobs"], []) self.assertEqual(self.jobs_resource(session)["items"], []) + def test_an_await_cut_short_by_the_cell_deadline_still_wakes(self): + session = self.start_blocked_job("await a slow job past its cell deadline") + statuses = [ + json.loads(part["value"])["status"] + for entry in self.app.history(session)["items"] + if entry["kind"] == "tool_result" + for part in entry["content"] + if part["kind"] == "json" and part["field"] == "result" + ] + self.assertEqual(statuses, ["interrupted"]) + gate = self.job_gate + assert gate is not None + wait_for(lambda: release_fifo(gate)) + wait_for(lambda: len(self.users()) >= 3) + self.assertIn("background job finished", self.users()[2]) + def test_stopping_one_job_and_rejecting_unknown_job(self): session = self.start_blocked_job() resource = self.jobs_resource(session) diff --git a/test/harness/remote_plugin_test.py b/test/harness/remote_plugin_test.py index 768e0bfbc..ffd7e6f17 100644 --- a/test/harness/remote_plugin_test.py +++ b/test/harness/remote_plugin_test.py @@ -337,6 +337,25 @@ class RemotePluginTest(unittest.IsolatedAsyncioTestCase): self.assertIn("rem.output.read(", notice["text"]) self.assertNotIn("jobs[", notice["text"]) + async def test_an_await_cut_short_leaves_the_job_waking_the_session(self): + rem = await self.connect() + self.addCleanup(rem.close) + # A cell deadline cancels the await here; the interrupt must reach the + # remote kernel's await too, or neither side ever sends the wake. + job = rem.run(sys.executable, "-c", "import time; time.sleep(1)") + for _ in range(100): + if job.id is not None: + break + await asyncio.sleep(0.05) + with self.assertRaises(asyncio.TimeoutError): + await asyncio.wait_for(job, 0.2) + for _ in range(100): + if notices: + break + await asyncio.sleep(0.05) + [notice] = notices + self.assertEqual([fact["id"] for fact in notice["jobs"]], [job.id]) + async def test_a_call_that_fails_unawaited_says_so_on_its_reference(self): rem = await self.connect() self.addCleanup(rem.close) -- knotmirror 0.0.1