diff --git a/python/albedo_api.py b/python/albedo_api.py index 242b9f8c1..55809c3c6 100644 --- a/python/albedo_api.py +++ b/python/albedo_api.py @@ -18,6 +18,7 @@ from albedo_protocol import ( Reply as Reply, Interrupt as Interrupt, Shutdown as Shutdown, + Chained as Chained, Invoke as Invoke, Introspect as Introspect, Release as Release, diff --git a/python/albedo_cells.py b/python/albedo_cells.py index 6cce68190..71cbaaf5e 100644 --- a/python/albedo_cells.py +++ b/python/albedo_cells.py @@ -2069,6 +2069,109 @@ async def _target_object(target: object) -> object | None: return None +def _method(base: object, name: str) -> object: + """The attribute path `name` names on a live or pending object.""" + parts = name.split(".") if name else [] + if not all(part.isidentifier() and not part.startswith("_") for part in parts): + raise ValueError(f"unaddressable owner invoke: {name!r}") + call = base + for part in parts: + call = getattr(call, part) + return call + + +def _mirror_base(base: object) -> None: + """A call such as text() can see its job end, and the owner reads + exit_code from the mirror, so the job's state goes ahead of the reply.""" + if isinstance(getattr(base, "capture", None), Capture): + key = next((key for key, held in LIVE.items() if held is base), None) + if key is not None: + send({"type": "mirror", "handle": key, **_mirror_state(base)}) + + +def _failed_reply(call_id: str, error: BaseException) -> dict[str, object]: + if isinstance(error, asyncio.CancelledError): + # The owner cancelled its wait; the remote effect may continue, and the + # live reference (a running job, for instance) stays addressable. + return { + "type": "invoked", + "id": call_id, + "ok": False, + "cancelled": True, + "error": { + "ename": "CancelledError", + "evalue": "the owner cancelled this wait; the remote effect " + "may continue and its reference stays addressable", + "traceback": [], + }, + } + return { + "type": "invoked", + "id": call_id, + "ok": False, + "error": { + "ename": type(error).__name__, + "evalue": str(error)[:8192], + "traceback": "".join(traceback.format_exception(error)).splitlines()[-8:], + }, + } + + +def _make_chain( + root_id: str, + root: tuple[bool, object], + chain: list[tuple[str, str, str, list[object], dict[str, object]]], +) -> list[tuple[str, bool, object, object]]: + """Make each chained call on the result it names, in order and without + yielding, so nothing the loop runs comes between them: a job's pipe is + attached before the job's first output is read.""" + made = {root_id: root} + outcomes: list[tuple[str, bool, object, object]] = [] + for call_id, target, name, args, kwargs in chain: + ok, base = made[target] + value = base + if ok: + try: + call = _method(base, name) + if not callable(call): + raise TypeError(f"owner invoke {name!r} is not callable") + value = call(*args, **kwargs) + except Exception as error: + ok, value = False, error + made[call_id] = (ok, value) + outcomes.append((call_id, ok, value, base)) + return outcomes + + +async def _finish_chained(call_id: str, ok: bool, value: object, base: object) -> None: + """Settle and answer one chained call, the way serve_invoke answers its own.""" + future = PENDING_OBJECTS.get(call_id) + failure: BaseException | None = None + result: object = None + try: + if not ok: + raise cast(BaseException, value) + result = value + if inspect.isawaitable(result) and not isinstance(result, tuple(HANDLES)): + result = await cast(Awaitable[object], result) + _mirror_base(base) + state = ( + _mirror_state(result) + if isinstance(getattr(result, "capture", None), Capture) + else None + ) + reply = _invoke_reply(call_id, result, state) + except BaseException as error: + failure = error + reply = _failed_reply(call_id, error) + finally: + if future is not None and not future.done(): + future.set_result( + (failure is None, failure if failure is not None else result) + ) + send(reply) + + async def serve_invoke(message: albedo_api.Invoke) -> None: """One owner tool call: resolve, call, await by the cell rule, answer one reference. @@ -2090,8 +2193,13 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: future: asyncio.Future[tuple[bool, object]] = LOOP.create_future() PENDING_OBJECTS[call_id] = future PENDING_OBJECTS.move_to_end(call_id) + entries = message.get("then", []) + for entry in entries: + PENDING_OBJECTS[entry["id"]] = LOOP.create_future() while len(PENDING_OBJECTS) > LIVE_LIMIT: PENDING_OBJECTS.popitem(last=False) + chain: list[tuple[str, str, str, list[object], dict[str, object]]] = [] + chained: list[tuple[str, bool, object, object]] | None = None reply: dict[str, object] result: object = None state: dict[str, object] | None = None @@ -2111,18 +2219,7 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: result = base else: name = message.get("name", "") - if base is None: - call = _resolve(name) - else: - parts = name.split(".") if name else [] - if not all( - part.isidentifier() and not part.startswith("_") - for part in parts - ): - raise ValueError(f"unaddressable owner invoke: {name!r}") - call = base - for part in parts: - call = getattr(call, part) + call = _resolve(name) if base is None else _method(base, name) args = [ await _owner_args(item) for item in cast(Sequence[object], message.get("args", ())) @@ -2131,6 +2228,21 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: key: await _owner_args(item) for key, item in message.get("kwargs", {}).items() } + # Chained arguments resolve first: once the call is made, its + # chain must follow with nothing awaited in between. + for entry in entries: + chain.append( + ( + entry["id"], + entry["target"]["pending"], + entry["name"], + [await _owner_args(item) for item in entry.get("args", ())], + { + key: await _owner_args(item) + for key, item in entry.get("kwargs", {}).items() + }, + ) + ) if not callable(call): raise TypeError(f"owner invoke {name!r} is not callable") result = call(*args, **kwargs) @@ -2138,44 +2250,13 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: result, tuple(HANDLES) ): result = await cast(Awaitable[object], result) - # A call such as text() can see its job end, and the owner reads - # exit_code from the mirror, so the job's state goes ahead of the reply. - if isinstance(getattr(base, "capture", None), Capture): - key = next( - (key for key, held in LIVE.items() if held is base), None - ) - if key is not None: - send({"type": "mirror", "handle": key, **_mirror_state(base)}) + _mirror_base(base) + chained = _make_chain(call_id, (True, result), chain) 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 - # live reference (a running job, for instance) stays addressable. - reply = { - "type": "invoked", - "id": call_id, - "ok": False, - "cancelled": True, - "error": { - "ename": "CancelledError", - "evalue": "the owner cancelled this wait; the remote effect " - "may continue and its reference stays addressable", - "traceback": [], - }, - } except BaseException as error: failure = error - reply = { - "type": "invoked", - "id": call_id, - "ok": False, - "error": { - "ename": type(error).__name__, - "evalue": str(error)[:8192], - "traceback": traceback.format_exc().splitlines()[-8:], - }, - } + reply = _failed_reply(call_id, error) else: reply = _invoke_reply(call_id, result, state) finally: @@ -2185,6 +2266,12 @@ async def serve_invoke(message: albedo_api.Invoke) -> None: (failure is None, failure if failure is not None else result) ) send(reply) + if chained is None: + # The call failed before its chain was made: each chained call fails + # with it, since what it was to be made on never existed. + chained = [(entry["id"], False, failure, None) for entry in entries] + for chained_id, ok, value, base in chained: + _ = LOOP.create_task(_finish_chained(chained_id, ok, value, base)) def cancel_cell(id: str, *, quiet: bool = False) -> bool: diff --git a/python/albedo_plugins/remote.py b/python/albedo_plugins/remote.py index d807b1856..3e8e7141a 100644 --- a/python/albedo_plugins/remote.py +++ b/python/albedo_plugins/remote.py @@ -273,6 +273,10 @@ async def ssh_run( return process.returncode, stdout, stderr.decode(errors="replace") +async def _raise(error: BaseException) -> Any: + raise error + + def _revive(value: Any) -> Any: """Pickle hook target: a reference with a crossed value saves as its value.""" return value @@ -577,6 +581,9 @@ class RemoteConnection: self._write_lock = asyncio.Lock() self._pending: dict[str, asyncio.Future[dict[str, Any]]] = {} self._placeholders: dict[str, RemoteRef] = {} + # Invoke frames built this step and not yet written, by every call id + # they carry; a call on one of those ids joins the frame's `then`. + self._unsent: dict[str, dict[str, Any]] = {} self._refs: dict[str, RemoteRef] = {} self._mirrors: dict[str, dict[str, Any]] = {} self._handshake: asyncio.Future[dict[str, Any]] | None = None @@ -836,22 +843,54 @@ class RemoteConnection: def start( self, call: "_RemoteCall", args: tuple[Any, ...], kwargs: dict[str, Any] ) -> RemoteRef: - """Fire one call and return its reference immediately; it settles on await.""" + """Fire one call and return its reference immediately; it settles on await. + + A call on a pending reference whose frame has not gone out yet rides + in that frame's `then` list, and the remote side makes it right after + the call it names, with nothing scheduled between them. So + run(...).pipe(...) attaches the pipe before the job's output can + outgrow the replay limit, as it does locally, however the two calls' + bytes cross the channel. + """ call_id = secrets.token_hex(16) reference = RemoteRef(self, call_id=call_id, label=call._label) + try: + frame = self._frame(call._name, call._handle, call._pending, args, kwargs) + except Exception as error: + reference._task = loop.create_task(_raise(error)) + return reference + frame["id"] = call_id + root = self._unsent.get(call._pending) if call._pending is not None else None + self._expect(call_id, reference) + if root is None: + self._unsent[call_id] = frame + outgoing: dict[str, Any] | None = frame + else: + del frame["type"] + root.setdefault("then", []).append(frame) + self._unsent[call_id] = root + outgoing = None reference._task = loop.create_task( - self.invoke( - name=call._name, - handle=call._handle, - pending=call._pending, - args=args, - kwargs=kwargs, - call_id=call_id, - placeholder=reference, + self._exchange( + call_id, outgoing, call._name, None, INVOKE_TIMEOUT, reference ) ) + if outgoing is not None: + reference._task.add_done_callback(lambda _: self._unsendable(frame)) return reference + def _unsendable(self, frame: dict[str, Any]) -> None: + """A frame whose call ended before writing it, cancelled before it + started, fails the calls riding in it.""" + if not any(held is frame for held in self._unsent.values()): + return + for key in [key for key, held in self._unsent.items() if held is frame]: + del self._unsent[key] + for entry in frame.get("then", ()): + waiting = self._pending.get(entry["id"]) + if waiting is not None and not waiting.done(): + waiting.set_exception(RemoteLost("the call it follows was never sent")) + async def invoke( self, name: str = "", @@ -872,16 +911,31 @@ class RemoteConnection: `placeholder` is the reference the caller already holds; a handle reply adopts into it rather than minting a second object. """ + frame = self._frame(name, handle, pending, args, kwargs or {}) + call_id = call_id or secrets.token_hex(16) + frame["id"] = call_id + if wait: + frame["await"] = True + self._expect(call_id, placeholder) + return await self._exchange(call_id, frame, name, handle, timeout, placeholder) + + def _frame( + self, + name: str, + handle: str | None, + pending: str | None, + args: tuple[Any, ...], + kwargs: dict[str, Any], + ) -> dict[str, Any]: + """An invoke frame without its id.""" if self.degraded is not None: raise RemoteError( f"degraded to ssh command mode ({self.degraded}); only rem.run() is available" ) - call_id = call_id or secrets.token_hex(16) frame: dict[str, Any] = { "type": "invoke", - "id": call_id, "args": [_encode_arg(item) for item in args], - "kwargs": {key: _encode_arg(item) for key, item in (kwargs or {}).items()}, + "kwargs": {key: _encode_arg(item) for key, item in kwargs.items()}, } if name: frame["name"] = name @@ -889,27 +943,56 @@ class RemoteConnection: frame["target"] = {"handle": handle} elif pending is not None: frame["target"] = {"pending": pending} - if wait: - frame["await"] = True - future: asyncio.Future[dict[str, Any]] = loop.create_future() - self._pending[call_id] = future + return frame + + def _expect(self, call_id: str, placeholder: RemoteRef | None) -> None: + self._pending[call_id] = loop.create_future() if placeholder is not None: self._placeholders[call_id] = placeholder - await self._send(frame) + + async def _exchange( + self, + call_id: str, + frame: dict[str, Any] | None, + name: str, + handle: str | None, + timeout: float, + placeholder: RemoteRef | None, + ) -> Any: + """Write `frame`, unless this call rides in another's, and await the + reply to `call_id`. A frame that never goes out fails every call it + carries, so none waits for a reply that cannot come.""" + future = self._pending[call_id] try: - reply = await asyncio.wait_for(future, timeout) - except asyncio.TimeoutError: - await self._interrupt(call_id) - raise RemoteTimeout( - f"remote call {name or ('await ' + str(handle))!r} did not answer " - f"in {timeout:g}s; an interrupt was sent" - ) from None - except asyncio.CancelledError: - await self._interrupt(call_id) - raise + if frame is not None: + for key in [key for key, held in self._unsent.items() if held is frame]: + del self._unsent[key] + try: + await self._send(frame) + except BaseException as error: + for entry in frame.get("then", ()): + waiting = self._pending.get(entry["id"]) + if waiting is not None and not waiting.done(): + waiting.set_exception( + RemoteLost(f"the call it follows was not sent: {error}") + ) + raise + try: + reply = await asyncio.wait_for(future, timeout) + except asyncio.TimeoutError: + await self._interrupt(call_id) + raise RemoteTimeout( + f"remote call {name or ('await ' + str(handle))!r} did not answer " + f"in {timeout:g}s; an interrupt was sent" + ) from None + except asyncio.CancelledError: + await self._interrupt(call_id) + raise finally: self._pending.pop(call_id, None) self._placeholders.pop(call_id, None) + if self._unsent.get(call_id) is frame and frame is not None: + del self._unsent[call_id] return self._result(reply, placeholder) def _result( diff --git a/python/albedo_protocol.py b/python/albedo_protocol.py index 5091f6124..f1d9d3e5f 100644 --- a/python/albedo_protocol.py +++ b/python/albedo_protocol.py @@ -79,10 +79,21 @@ Invoke = TypedDict( "args": NotRequired[list[object]], "kwargs": NotRequired[dict[str, object]], "await": NotRequired[bool], + # Calls on this call's result, or on an earlier one of these, made + # right after it: each an invoke without `type`, targeting a pending id. + "then": NotRequired[list["Chained"]], }, ) +class Chained(TypedDict): + id: str + name: str + target: dict[str, str] + args: NotRequired[list[object]] + kwargs: NotRequired[dict[str, object]] + + class Introspect(TypedDict): type: Literal["introspect"] id: str @@ -468,6 +479,29 @@ def parse_incoming(value: object) -> Incoming: raise ValueError( "invoke.target: expected exactly one handle or pending" ) + if "then" in message: + # Each chained call names the call or earlier chained call it + # follows, so the receiver can make them in order with no wait. + chain = message["then"] + if not isinstance(chain, list): + raise ValueError("invoke.then: invalid field type") + known = {cast(str, message["id"])} + for entry in cast(list[object], chain): + if not isinstance(entry, dict): + raise ValueError("invoke.then: invalid field type") + entry = cast(dict[str, object], entry) + _fields( + entry, + "invoke.then", + {"id": "str", "name": "str", "target": "str_dict"}, + {"args": "list", "kwargs": "dict"}, + ) + target = cast(dict[str, object], entry["target"]) + if set(target) != {"pending"} or target["pending"] not in known: + raise ValueError( + "invoke.then.target: expected a pending id this frame carries" + ) + known.add(cast(str, entry["id"])) elif kind == "introspect": _field(message, "id", "str", kind) elif kind == "release": diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 157c4dce9..bf428b35b 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -287,9 +287,14 @@ preview as complete output. The job and capture implementations are in [run.py](../python/albedo_plugins/run.py) and [albedo_capture.py](../python/albedo_capture.py). -Attach `run(...).pipe(...)` in one expression to stream from the start. A later -pipe can replay only the output still in memory, at most 1 MiB. This limit is -separate from disk retention. If the complete output is retained, use +Attach `run(...).pipe(...)` in one expression to stream from the start. This +holds for `rem.run` too. A method called on a pending remote reference in the +same step travels in that call's `invoke` frame as its `then` list. The remote +kernel makes the chained calls right after the call they follow, with no await +between them, so the pipe is attached before the job's output is read. A pipe +sent in its own frame could arrive after the job had already written 1 MiB. A +later pipe can replay only the output still in memory, at most 1 MiB. This limit +is separate from disk retention. If the complete output is retained, use `saved_path = await job.save(path)` after the job finishes. Pass the filename to a program on the same host. To stream it into another job, start with `run("cat", "--", saved_path).pipe(...)` locally or `rem.run` on the remote @@ -464,11 +469,12 @@ and `parse_remote` (remote replies and events) validate an untrusted frame against that contract with strict standard-library checks on `type` before it reaches an event loop: numbers are not booleans, booleans are not integers, and strings are never coerced. Unknown fields are kept, because frames such as -`done` and job views carry payloads their types only partly describe. Two -relationships need a check beside the shape: an `invoke` target names exactly -one handle or pending call, and an `invoked` result carries its error when it -failed and a value or handle when it succeeded. Validation imports no -third-party package, so importing the module and validating a kernel's first +`done` and job views carry payloads their types only partly describe. Three +relationships need a check beside the shape. An `invoke` target names exactly +one handle or pending call. Each call in an `invoke` frame's `then` list follows +the frame's own call or an earlier chained call. An `invoked` result carries its +error when it failed and a value or handle when it succeeded. Validation imports +no third-party package, so importing the module and validating a kernel's first frame in the kernel, spare, and zygote bootstraps do not pay for Pydantic's import or schema build. Pydantic stays bundled in the kernel environment for cells that import it, not for this wire. Do not route wire validation through diff --git a/test/harness/protocol_test.py b/test/harness/protocol_test.py index 3cc256fda..8b44ea3ed 100644 --- a/test/harness/protocol_test.py +++ b/test/harness/protocol_test.py @@ -49,6 +49,15 @@ VALID_INCOMING: list[dict[str, object]] = [ }, {"type": "invoke", "id": "i1", "target": {"handle": "h1"}}, {"type": "invoke", "id": "i1", "target": {"pending": "p1"}}, + { + "type": "invoke", + "id": "i1", + "name": "run", + "then": [ + {"id": "i2", "name": "pipe", "target": {"pending": "i1"}}, + {"id": "i3", "name": "pipe", "target": {"pending": "i2"}, "args": ["x"]}, + ], + }, {"type": "introspect", "id": "n1"}, {"type": "release", "handle": "h1"}, {"type": "snapshot", "id": "s1", "path": "/tmp/state"}, @@ -182,6 +191,26 @@ class ParseIncomingTest(unittest.TestCase): with self.assertRaises(ValueError): parse_incoming({"type": "invoke", "id": "i1", "target": target}) + def test_a_chained_call_follows_a_call_its_frame_carries(self) -> None: + # The receiver makes each chained call on a result it already has; one + # naming anything else could only wait, and the wait is the race the + # chain exists to remove. + call = {"id": "i2", "name": "pipe", "target": {"pending": "i1"}} + for then in ( + [{**call, "target": {"pending": "elsewhere"}}], + [{**call, "target": {"handle": "i1"}}], + [{**call, "id": "i3", "target": {"pending": "i2"}}, call], + [{"id": "i2", "target": {"pending": "i1"}}], + [{**call, "args": "x"}], + ["i2"], + call, + ): + with self.subTest(then=then): + with self.assertRaises(ValueError): + parse_incoming( + {"type": "invoke", "id": "i1", "name": "run", "then": then} + ) + def test_validation_errors_do_not_leak_input_values(self) -> None: # A frame can carry cell source or a host token; the ValueError a # caller logs must name the field, never echo the value it held. diff --git a/test/harness/remote_plugin_test.py b/test/harness/remote_plugin_test.py index eac2db33c..b43ace75f 100644 --- a/test/harness/remote_plugin_test.py +++ b/test/harness/remote_plugin_test.py @@ -1108,16 +1108,28 @@ class RemoteJobEquivalenceTest(unittest.TestCase): self.assertTrue(spills.is_dir() and set(spills.iterdir()) - earlier, spills) def test_a_pipe_attached_at_once_streams_past_retention(self): + # Remotely the pipes ride in the run call's frame and are attached + # before the job's output is read, however the frames cross the + # channel; a pipe sent on its own could arrive after 1 MiB was read. program = "print('s' * 2000000, end='')" for label in ("local", "remote"): with self.subTest(label): whole = self.workspace / f"whole-{label}.txt" - job = self.starts[label](sys.executable, "-c", program).pipe( - "tee", str(whole) + job = ( + self.starts[label](sys.executable, "-c", program) + .pipe("tee", str(whole)) + .pipe("wc", "-c") ) - self.run_async(job) + self.assertEqual(self.run_async(job.text()).strip(), "2000000") self.assertEqual(whole.read_bytes(), b"s" * 2000000) + def test_a_call_chained_on_a_failed_call_fails_with_it(self): + # run() without a program refuses at once; the pipe that rode in its + # frame must be answered with a failure, not left waiting an hour. + job = self.rem.run().pipe("cat") + with self.assertRaises(remote.RemoteError): + self.run_async(asyncio.wait_for(job, 10)) + def test_a_running_job_and_a_failed_rename_leave_the_destination(self): async def case(label): start = self.starts[label]