From bb2ab97705f759d771eb1e7bcdaacee5e38f6a21 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Mon, 5 Oct 2026 17:49:09 +0300 Subject: [PATCH] remote: an awaited job no longer wakes the session, and a failed call says so Awaiting a rem.run reference reached the remote kernel only after the reply to the call, so a quick job (systemctl is-active in a waiting loop) had already finished and owed a wake. With the cell backgrounded the session was idle, so every iteration became a turn. The reference now marks itself as soon as await starts, the same as a local job, and the owner drops a relayed jobs.completed for any job a reference on this side already awaited or read. The reply to the call that started a job now carries the job's state, so the notice can be matched before the first mirror frame lands. Remote notices stop pointing at jobs[id], which only exists in the remote kernel. A call that failed before anything awaited it (rem.run with timeout=7200) kept its error in a task nobody read, so id, tail() and poll() answered None forever. They now raise it, and the repr shows it. Jobs may run for up to a day instead of an hour. A job outlives the cell that started it, so the cell's limit never applied to it, and timeouts above a day still get the milliseconds hint. Signed-off-by: dawn <90008@klbr.net> --- priv/python/albedo_api.py | 12 ++-- priv/python/albedo_kernel.py | 12 ++-- priv/python/albedo_plugins/remote.py | 49 +++++++++++++++- priv/python/albedo_plugins/run.py | 32 +++++++++-- robot-docs/extensions.md | 2 + robot-docs/kernel.md | 2 +- .../harness/extensions/run/extension.gleam | 2 +- test/harness/remote_plugin_test.py | 57 +++++++++++++++++++ 8 files changed, 149 insertions(+), 19 deletions(-) diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index b1bbf3392..d4bb07020 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -83,12 +83,16 @@ class Record(dict): return _ready(self) +MAX_JOB_SECONDS = 86400 # a day: long builds fit, a deadline in ms does not + + def check_timeout(timeout: float) -> None: - """Raise unless a job timeout is within 0 < timeout <= 3600 seconds.""" - if not 0 < timeout <= 3600: + """Raise unless a job timeout is within 0 < timeout <= MAX_JOB_SECONDS.""" + if not 0 < timeout <= MAX_JOB_SECONDS: raise ValueError( - f"timeout is in seconds: 0 < timeout <= 3600 required, got {timeout:g}" - + (" (milliseconds?)" if timeout > 3600 else "") + f"timeout is in seconds: 0 < timeout <= {MAX_JOB_SECONDS} required," + f" got {timeout:g}" + + (" (milliseconds?)" if timeout > MAX_JOB_SECONDS else "") ) diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index 4b4b59923..3f4635187 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -1045,9 +1045,10 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: object as a live reference; `value` and `handle` are one concept. Awaitables run to completion unless their class is a registered handle, the same rule the local evaluator applies, so a tool's remote shape matches its local one. - An awaited object's reply carries its final state, so the owner's poll() is - never racy, and every call's result object is retained briefly as a pending - target for method calls that raced ahead of the reply. + A job's reply carries its state, final when awaited, so the owner's poll() is + never racy and the owner can match the job's wake to its reference before + any mirror frame arrives. Every call's result object is retained briefly as + a pending target for method calls that raced ahead of the reply. """ call_id = message["id"] OWNER_TASKS[call_id] = cast(asyncio.Task[object], asyncio.current_task()) @@ -1067,9 +1068,6 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: if base is None: raise ValueError("await needs a live or pending reference target") result = await cast(Awaitable[object], base) - state = ( - _mirror_state(result) if getattr(result, "capture", None) else None - ) else: name = message.get("name", "") if base is None: @@ -1099,6 +1097,8 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: result, tuple(HANDLES) ): result = await cast(Awaitable[object], result) + if isinstance(getattr(result, "capture", None), Capture): + state = _mirror_state(result) except asyncio.CancelledError as error: failure = error # The owner cancelled its wait; the remote effect may continue, and the diff --git a/priv/python/albedo_plugins/remote.py b/priv/python/albedo_plugins/remote.py index 001e81849..06c0fdcd8 100644 --- a/priv/python/albedo_plugins/remote.py +++ b/priv/python/albedo_plugins/remote.py @@ -33,6 +33,7 @@ import albedo_bundle from albedo_values import InvalidValue, decode import albedo_shell import albedo_ssh +from albedo_plugins.run import notice CONNECT_TIMEOUT = 60 # seconds before an unreachable target gives up HANDSHAKE_TIMEOUT = 60 # seconds for the remote kernel to say ready @@ -269,6 +270,7 @@ class RemoteRef: self._label = label self._settled: Any = _UNSET self._withdrawn: bool = False + self._awaited = False # awaited here, so its result reaches this cell # --- mirrored job state: sync, like the local handle --- @@ -314,6 +316,8 @@ class RemoteRef: return state.get("job") if state else None def _mirror(self) -> dict[str, Any] | None: + if (failure := self._failure()) is not None: + raise failure if self._handle is None: return None state = self._connection._mirrors.get(self._handle) @@ -331,9 +335,25 @@ class RemoteRef: pass # the loop is closing; the notice dies with the kernel return state + def _failure(self) -> BaseException | None: + """The error of a call that failed before anything awaited it. A ref + nobody awaits (a long build left to wake the session) has no other way + to say it never started.""" + task = self._task + if task is None or not task.done() or task.cancelled(): + return None + return task.exception() + + @property + def _claimed(self) -> bool: + """Its result reached this side, so the job's wake is not owed.""" + return self._awaited or self._withdrawn + # --- the value surface: identical output to the local tool --- def __repr__(self) -> str: + if (failure := self._failure()) is not None: + return f"" if self._value is not None: return repr(self._value) if self._handle is not None: @@ -403,6 +423,9 @@ 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__() async def _settle(self) -> Any: @@ -601,7 +624,10 @@ class RemoteConnection: async def _relay(self, frame: RemoteCall) -> None: """Answer one remote host-route call against this session's daemon.""" try: - value = await host_call(frame["method"], frame["args"]) + if frame["method"] == "jobs.completed": + value = await self._wake(frame["args"]) + else: + value = await host_call(frame["method"], frame["args"]) reply: dict[str, Any] = {"ok": True, "value": value} except HostErrorType as error: reply = { @@ -617,6 +643,25 @@ class RemoteConnection: } await self._send({"type": "reply", "id": frame["id"], "value": reply}) + async def _wake(self, args: Any) -> Any: + """Pass on a remote job's wake unless a reference here already awaited + or read the job, which the remote kernel may not have heard yet.""" + facts = [ + fact + for fact in args.get("jobs", []) + if not self._claimed_here(fact.get("id")) + ] + if not facts: + return None + return await host_call("jobs.completed", notice(facts)) + + def _claimed_here(self, job: object) -> bool: + return any( + reference._claimed + for handle, reference in self._refs.items() + if self._mirrors.get(handle, {}).get("job") == job + ) + async def _send(self, frame: dict[str, Any]) -> None: if self.closed or self._stdin is None: raise RemoteLost(f"the connection to {self.host} is closed") @@ -1135,7 +1180,7 @@ class FallbackJob: "a background command finished with its result unread on" f" {self._connection.host} (ssh command mode): {outcome}, {seconds}," f" command: {command}." - f" its handle is jobs[{self.id!r}] in python; jobs[{self.id!r}].tail() or" + " its handle is the job rem.run returned; its .tail() or" f" output.read({self.id!r}) reads its output." " no user sent this message; use the result if the session's work needs" " it, otherwise acknowledge briefly and stay idle." diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 16415715e..edeab5900 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -628,6 +628,19 @@ async def _announce() -> None: owed.pop(job.id, None) +# A job on a remote.connect() host lives in that kernel's `jobs`, not the +# model's, so its notice names the reference rem.run returned instead. +REMOTE_READING = ( + " a job on another host is read with .tail() on the reference rem.run" + " returned, or await rem.output.read(id) on that connection." +) + + +def _name(job: dict[str, object]) -> str: + """How a notice names a job: its `jobs` entry here, or a remote job's id.""" + return repr(job["id"]) if job["host"] else f"jobs[{job['id']!r}]" + + def notice(facts: list[dict[str, object]]) -> dict[str, object]: """The wake turn's display text, model text, and the facts behind both.""" advice = ( @@ -636,21 +649,29 @@ def notice(facts: list[dict[str, object]]) -> dict[str, object]: ) if len(facts) == 1: [job] = facts + reading = ( + " its handle is the reference rem.run returned; its .tail() or" + f" await rem.output.read({job['id']!r}) on that connection reads its output." + if job["host"] + else f" its handle is jobs[{job['id']!r}] in python; jobs[{job['id']!r}].tail() or" + f" output.read({job['id']!r}) reads its output." + ) text = ( "a background job finished with its result unread" f"{job['where']}: {job['summary']}, command: {job['command']}." - f" its handle is jobs[{job['id']!r}] in python; jobs[{job['id']!r}].tail() or" - f" output.read({job['id']!r}) reads its output." + advice + + reading + + advice ) else: listed = "; ".join( - f"jobs[{job['id']!r}]{job['where']}: {job['summary']}, command: {job['command']}" + f"{_name(job)}{job['where']}: {job['summary']}, command: {job['command']}" for job in facts ) + remote = any(job["host"] for job in facts) text = ( f"{len(facts)} background jobs finished with their results" f" unread: {listed}. jobs[id].tail() or output.read(id) reads one's" - " output." + advice + " output." + (REMOTE_READING if remote else "") + advice ) display = "\n".join( f"job finished{job['where']} ({job['summary']}): {job['command']}" @@ -670,7 +691,8 @@ def run( ) -> Job: """Start one program, without a shell, and return its handle immediately: run("go", "test", "./...", cwd="cli"). It starts at once, at low priority. - The timeout counts wall time after the program starts. + The timeout, in seconds and at most a day, counts wall time after the + program starts. `env` adds to the kernel's environment. `stdin` is text or bytes to feed the program, a path to read, or another job, whose output streams in like diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 7a9531627..dcf6356f5 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -205,6 +205,8 @@ 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. + 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. The remote reader checks replies and events before dispatch. Every reader exit fails unfinished handshake and call futures, including malformed input, EOF, unexpected exceptions, and cancellation. Cancellation still propagates from the reader task. `trace`, `done`, and `cleanup` events require valid identifying fields; their unused payloads are ignored. Known messages may contain extra fields. A reference target contains exactly one string `handle` or `pending`, and a method name may accompany that target. diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index e5a003818..354289747 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -10,7 +10,7 @@ session layer that neither loses nor repeats a message across a reconnect. Cells also see the common standard-library modules (`asyncio base64 collections datetime functools hashlib itertools json math os re shutil sys textwrap time`, and `Path`) without importing them; these live in the same session-private builtins, so they are not saved as user variables. `import albedo` and `from albedo import files` answer the injected bindings (`albedo_kernel.Bindings`). -A cell may not block the kernel with `time.sleep` of a second or more: `albedo_shell` refuses it through the same audit hook that refuses raw subprocess calls, and says to start the work with `run()` and do other useful work while it runs, and when nothing else is left to give the user a status report first, then wait with `await asyncio.sleep(n)`. Job timeouts are seconds (`albedo_api.check_timeout`). +A cell may not block the kernel with `time.sleep` of a second or more: `albedo_shell` refuses it through the same audit hook that refuses raw subprocess calls, and says to start the work with `run()` and do other useful work while it runs, and when nothing else is left to give the user a status report first, then wait with `await asyncio.sleep(n)`. Job timeouts are seconds, at most a day (`albedo_api.check_timeout`): a job outlives the cell that started it, so it is not held to the cell's hour. The kernel keeps injected helpers in cell globals and in a session-private copy of Python's builtins. An assignment such as `files = [...]` shadows the helper; diff --git a/src/albedo/harness/extensions/run/extension.gleam b/src/albedo/harness/extensions/run/extension.gleam index 7dddc53c4..ed71baee5 100644 --- a/src/albedo/harness/extensions/run/extension.gleam +++ b/src/albedo/harness/extensions/run/extension.gleam @@ -12,7 +12,7 @@ import gleam/json import gleam/option.{None} import gleam/result -const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean, and so is a time.sleep of a second or more: start the work with run() and do other useful work while it runs; if nothing else is left, give the user a status report first, then wait with await asyncio.sleep(n). Programs start at once at low priority and are never paused for admission. The timeout (seconds) counts wall time after the program starts. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code). A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." +const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean, and so is a time.sleep of a second or more: start the work with run() and do other useful work while it runs; if nothing else is left, give the user a status report first, then wait with await asyncio.sleep(n). Programs start at once at low priority and are never paused for admission. The timeout (seconds, at most a day) counts wall time after the program starts. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code). A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." pub fn extension() -> harness_extension.Extension { harness_extension.Extension( diff --git a/test/harness/remote_plugin_test.py b/test/harness/remote_plugin_test.py index e59cf2cc5..c1a8c0252 100644 --- a/test/harness/remote_plugin_test.py +++ b/test/harness/remote_plugin_test.py @@ -57,7 +57,13 @@ def fake_ssh_path() -> str: FAKE_SSH = fake_ssh_path() +notices = [] # every jobs.completed notice that reached the daemon + + async def daemon_host(method, args): + if method == "jobs.completed": + notices.append(args) + return None if method == "work.list": return [ { @@ -80,6 +86,7 @@ class RemotePluginTest(unittest.IsolatedAsyncioTestCase): def setUp(self): remote.configured.clear() remote.connections.clear() + notices.clear() self.home = tempfile.mkdtemp(prefix="albedo-remote-home-") self.workspace = tempfile.mkdtemp(prefix="albedo-remote-ws-") os.chdir(self.workspace) @@ -299,6 +306,56 @@ class RemotePluginTest(unittest.IsolatedAsyncioTestCase): ending = await job.stop # awaiting an uncalled method runs it self.assertTrue(ending.gone) + async def test_a_job_awaited_here_does_not_wake_the_session(self): + rem = await self.connect() + self.addCleanup(rem.close) + # The await crosses a round trip after the call's own reply; over a slow + # link a quick job is done by then, and its wake must not reach the + # idle session a backgrounded cell's waiting loop leaves behind. + send = rem._send + + async def slow_link(frame): + if frame.get("await"): + await asyncio.sleep(0.5) + await send(frame) + + with patch.object(rem, "_send", slow_link): + job = rem.run("true") + await job + self.assertEqual(job.exit_code, 0) + rem.run("echo", "left-unread") + for _ in range(100): + if notices: + break + await asyncio.sleep(0.05) + [notice] = notices + self.assertEqual( + [fact["command"] for fact in notice["jobs"]], ["echo left-unread"] + ) + # That job lives in the remote kernel's jobs, not the model's. + self.assertIn("rem.output.read(", notice["text"]) + self.assertNotIn("jobs[", notice["text"]) + + async def test_a_call_that_fails_unawaited_says_so_on_its_reference(self): + rem = await self.connect() + self.addCleanup(rem.close) + # Left to wake the session, a job that never started must not look + # pending forever. + job = rem.run("true", timeout=0) + for _ in range(100): + if "failed" in repr(job): + break + await asyncio.sleep(0.05) + self.assertIn("timeout is in seconds", repr(job)) + with self.assertRaisesRegex( + remote.RemoteExecutionError, "timeout is in seconds" + ): + _ = job.id + with self.assertRaisesRegex( + remote.RemoteExecutionError, "timeout is in seconds" + ): + await job + async def test_a_file_larger_than_a_command_line_writes_and_reads_back(self): rem = await self.connect() self.addCleanup(rem.close) -- knotmirror 0.0.1