"""The job engine: programs run as owned process groups, with their output. run(program, *args) in a cell starts one program without a shell. A job runs in its own session, so its program leads a process group and one signal reaches it plus every descendant that stayed in that group. The group is ended when the command ends, when its deadline passes, and at shutdown. What survives is reported, and unfinished work stays owned. When the command ends on its own, members a process that left the group still parents stay with it: ssh's ControlPersist master daemonizes out of the job 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 engine 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; 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. This module knows nothing of cells, hooks or the model's handles (albedo_plugins/run.py): everything it takes and gives is plain data keyed by job id. """ from __future__ import annotations from albedo_window import read_window from collections import OrderedDict from collections.abc import Callable, Coroutine from typing import cast import albedo_bundle import albedo_capture import albedo_proc import asyncio import base64 import contextlib import json import os import shlex import shutil import sys import tempfile import time import secrets from pathlib import Path import fcntl import functools import signal import struct PROTOCOL = 1 # the wire version in the hello; a peer on another one is not talked to IDLE_EXIT = ( 60.0 # seconds with nothing running and nothing owed before the helper exits ) MAX_FRAME = 8 * 1024 * 1024 SOCKET = "jobs.sock" loop: asyncio.AbstractEventLoop directory = "." # the helper's own directory: socket, lock, live.json, book.json, log remote = os.environ.get("ALBEDO_REMOTE_TARGET") or None # named in notices jobs: dict[str, Run] = {} # every job the session can address active: dict[str, Run] = {} # unfinished work: the bounded resource retained: OrderedDict[str, Run] = OrderedDict() # finished jobs, completion order owed: dict[str, Run] = {} # finished with results unread, in completion order announcer: asyncio.Task[None] | None = None peers: list[Peer] = [] sink: Peer | None = None # whoever takes wake notices idle_since: float | None = None ACTIVE_LIMIT = 64 # active jobs in one helper MAX_LISTED = 100 # jobs one `list` names, newest first RETAINED_LIMIT = 64 # finished jobs still addressable COMPLETION_GRACE = 0.1 # seconds to keep reading after the command exits SHUTDOWN_TERM = 0.25 # shared by every live group at shutdown SHUTDOWN_KILL = 1.0 NICENESS = 10 # A job that writes this much before anything pipes from it waits a moment for the # pipe (a `.pipe()` is a request after `run()`): half the retained start leaves room # for the largest read of the pipe, 256 KiB, on top. PIPE_WAIT_AT = albedo_capture.RETAIN // 2 PIPE_GRACE = 1.0 # seconds # macOS runs utility-QoS work below the interface, so a busy swarm yields. TASKPOLICY = shutil.which("taskpolicy") if sys.platform == "darwin" else None NOTICE_RETRY = 2.0 # seconds between wake attempts while the session runs NOTICE_GRACE = 0.2 # a kernel's await arrives a request after the job's end NOTICE_COMMAND_CAP = 200 # command characters a wake notice carries class Outlet: """A job's output on its way to other jobs' stdin, besides its capture.""" def __init__(self) -> None: self.feeds: list[Feed] = [] self.closed = False # the program's output ended; feeds get EOF self.reading: asyncio.ReadTransport | None = None self.held: set[Feed] = set() # readers whose stdin is full self.waiting: asyncio.TimerHandle | None = None # reading paused for a pipe self.waited = False # it paused once; a program is not held up twice def write(self, data: bytes) -> None: for feed in self.feeds: feed.write(data) def close(self) -> None: if not self.closed: self.closed = True for feed in self.feeds: feed.end() def cut(self) -> None: """Stop reading the program's output once nothing wants it, so its next write fails the way it would into a closed shell pipe.""" if self.reading is not None and not self.reading.is_closing(): self.reading.close() def hold(self, feed: Feed) -> None: self.held.add(feed) if self.reading is not None: self.reading.pause_reading() def release(self, feed: Feed) -> None: self.held.discard(feed) self.resume() def resume(self) -> None: if ( not self.held and self.waiting is None and self.reading is not None and not self.reading.is_closing() ): self.reading.resume_reading() def wait_for_pipe(self) -> None: """Stop reading just short of what a capture retains, so a pipe attached by the next request of the same expression still gets every byte; reading goes on when one attaches or the grace ends.""" if self.reading is not None and not self.waited: self.waited = True self.reading.pause_reading() self.waiting = loop.call_later(PIPE_GRACE, self.pipe_arrived) def pipe_arrived(self) -> None: if self.waiting is not None: self.waiting.cancel() self.waiting = None self.resume() class Feed: """One job's output into another's stdin, the way a shell pipe carries it: bytes wait until the reader starts, a full reader pauses the writer, and once every reader has stopped, the writer's next write fails (SIGPIPE).""" def __init__(self, writer: Run, retained: bytes) -> None: self.writer = writer self.pending = bytearray(retained) self.pipe: asyncio.WriteTransport | None = None self.ended = False self.broken = False def write(self, data: bytes) -> None: if self.broken: return if self.pipe is None: self.pending.extend(data) else: self.pipe.write(data) def end(self) -> None: self.ended = True if self.pipe is not None and not self.pipe.is_closing(): self.pipe.close() def connect(self, pipe: asyncio.WriteTransport) -> None: self.pipe = pipe pipe.write(bytes(self.pending)) self.pending.clear() if self.ended: pipe.close() def lost(self) -> None: """The reader's stdin closed before the writer's output ended.""" self.writer.outlet.release(self) if self.ended or self.broken: return self.broken = True if all(feed.broken for feed in self.writer.outlet.feeds): self.writer.outlet.cut() class Command(asyncio.SubprocessProtocol): """Separate command exit from pipe EOF, without a timer per running job.""" def __init__( self, capture: albedo_capture.Capture, outlet: Outlet, feed: Feed | None ) -> None: self.capture = capture self.outlet = outlet self.feed = feed # what fills this program's stdin, if a job does self.exited: asyncio.Future[int] = loop.create_future() self.drained: asyncio.Future[None] = loop.create_future() self.transport: asyncio.SubprocessTransport self.pid: int def connection_made(self, transport: asyncio.BaseTransport) -> None: self.transport = cast(asyncio.SubprocessTransport, transport) self.pid = self.transport.get_pid() self.outlet.reading = cast( asyncio.ReadTransport, self.transport.get_pipe_transport(1) ) @property def returncode(self) -> int | None: return self.transport.get_returncode() def pipe_data_received(self, fd: int, data: bytes) -> None: # Capture is bounded and synchronous; no unbounded reader queue. self.capture.write_bytes(data) self.outlet.write(data) if self.capture.seen >= PIPE_WAIT_AT and not self.outlet.feeds: self.outlet.wait_for_pipe() def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: if fd == 0: if self.feed is not None: self.feed.lost() return # stdin written and closed; output is still coming self.outlet.close() if not self.drained.done(): self.drained.set_result(None) if self.exited.done(): self.transport.close() def pause_writing(self) -> None: if self.feed is not None: self.feed.writer.outlet.hold(self.feed) def resume_writing(self) -> None: if self.feed is not None: self.feed.writer.outlet.release(self.feed) def process_exited(self) -> None: code = self.returncode assert code is not None self.exited.set_result(code) if self.drained.done(): self.transport.close() Data = str | bytes | os.PathLike[str] async def spawn( argv: list[str], capture: albedo_capture.Capture, cwd: str | None, env: dict[str, str] | None, stdin: Data | None, outlet: Outlet, feed: Feed | None, ) -> Command: """Start argv at a lower priority than the person at the machine, with stdin fed from text, bytes, a file, or another job, and stdout and stderr joined.""" if TASKPOLICY is not None: argv = [TASKPOLICY, "-c", "utility", *argv] file = open(stdin, "rb") if isinstance(stdin, os.PathLike) else None piped = stdin is not None or feed is not None source = file or (asyncio.subprocess.PIPE if piped else asyncio.subprocess.DEVNULL) try: _, process = await loop.subprocess_exec( lambda: Command(capture, outlet, feed), *argv, stdin=source, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, cwd=cwd, env=env, start_new_session=True, preexec_fn=_lower_priority, ) finally: if file is not None: file.close() pipe = cast(asyncio.WriteTransport | None, process.transport.get_pipe_transport(0)) if pipe is not None and feed is not None: feed.connect(pipe) elif pipe is not None and isinstance(stdin, (str, bytes)): pipe.write(stdin.encode() if isinstance(stdin, str) else stdin) pipe.close() return process def _lower_priority() -> None: try: os.nice(NICENESS) except OSError: pass class Run: """One background program and the process group it owns.""" def __init__( self, argv: list[str], timeout: float, *, cwd: str, env: dict[str, str], stdin: Data | Run | None, service: bool, cell: str | None, ) -> None: self.service = service # expected to run on; its end is not what we wait for self.source: Run | None = ( stdin if isinstance(stdin, Run) else None ) # whose output is our stdin self.feed = self.source._reader() if self.source is not None else None self.outlet = Outlet() self.id: str = secrets.token_hex(16) self.argv: list[str] = argv self.command: str = shlex.join(argv) # what ran, as one line to read self.process: Command | None = None self.group: albedo_proc.Group | None = None self.exit_code: int | None = None self.timed_out: bool = False self.timeout = timeout self.cell = cell # the cell that started it self.started: float = loop.time() self.duration: float | None = None # seconds it ran, once it ended self.termination: albedo_proc.Termination | None = None self.capture = albedo_capture.Capture(self.id, "job") self.ending: asyncio.Task[albedo_proc.Termination] | None = None 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._starting = ( False # the OS spawn began; from then on it must finish, not be cancelled ) data = None if isinstance(stdin, Run) else stdin self.spawning = loop.create_task(self._launch(cwd, env, data, self.feed)) self.task: asyncio.Future[Run] = loop.create_task(self._run(timeout)) self.task.add_done_callback(self._cancelled) active[self.id] = self jobs[self.id] = self async def _launch( self, cwd: str | None, env: dict[str, str] | None, stdin: Data | None, feed: Feed | None, ) -> Command: self._starting = True return await spawn(self.argv, self.capture, cwd, env, stdin, self.outlet, feed) def _reader(self) -> Feed: """A feed of this job's output for another job's stdin: what it wrote so far, then the rest as it comes. Piping it retires its own wake; the reader's notice names the pipeline.""" if self.capture.seen > len(self.capture.data): raise ValueError( f"job {self.id} wrote more than it retains ({len(self.capture.data)} bytes); " "pipe from it before it runs: run(...).pipe(...) in one expression" ) feed = Feed(self, bytes(self.capture.data)) self.outlet.feeds.append(feed) self.outlet.pipe_arrived() if self.outlet.closed: feed.end() self.read = True return feed @property def pipeline(self) -> str: """The command line this job ends, with every job piped into it.""" return ( f"{self.source.pipeline} | {self.command}" if self.source is not None else self.command ) def claim(self) -> albedo_proc.Group | None: """The group this job owns, derived again when a late spawn beat the assignment.""" if self.group is None and self.process is not None: self.group = albedo_proc.Group( self.process.pid, albedo_proc.leader_token(self.process.pid) ) write_live() emit("started", self) return self.group def _cancelled(self, task: asyncio.Task[Run]) -> None: if task.cancelled(): # Cancellation before _run starts skips its finally block. loop.create_task(self._stop()) async def _spawn(self) -> Command: process = await asyncio.shield(self.spawning) self.process = process self.claim() return process async def _run(self, timeout: float) -> Run: try: process = self.process = await self._spawn() await asyncio.wait_for(asyncio.shield(process.exited), timeout) self.exit_code = await self._drain(process) except asyncio.TimeoutError: self.timed_out = True except asyncio.CancelledError: pass except Exception as error: self.capture.write(f"{type(error).__name__}: {error}\n") finally: self.outlet.close() if self.feed is not None and self.feed.pipe is None: self.feed.lost() # never started, so never read ending = await self._stop(exited=self.exit_code is not None) if self.exit_code is None and self.process is not None: self.exit_code = await self._status(self.process) if self.process is not None and ending.gone: self.process.transport.close() self.duration = loop.time() - self.started if self.timed_out: self.capture.write( f"\n[deadline exceeded after {timeout:g}s; {ending.report()}]\n" ) elif not ending.gone: self.capture.write(f"\n[cleanup failed: {ending.report()}]\n") self.capture.end_spill() release(self) emit("ended", self) self.owe_unread() return self async def _drain(self, process: Command) -> int: """Read output while the command runs; a descendant holding the pipe does not extend it.""" code = await asyncio.shield(process.exited) await asyncio.wait({process.drained}, timeout=COMPLETION_GRACE) return code async def _status(self, process: Command, window: float = 1.0) -> int | None: """The command's exit status after its group is gone; bounded, never assumed.""" try: return await asyncio.wait_for(asyncio.shield(process.exited), window) except asyncio.TimeoutError: return process.returncode async def wait(self) -> Run: """Wait for the job. A wait cut short never delivered the result and did not stop the job, which 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 mark_read(self) -> None: """A read reached this job's output: a finished result is read.""" if self.exit_code is not None: self.read = True @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: """Queue the finished job's wake unless its result reached someone.""" if self.unreported: owe(self) def notice_facts(self) -> dict[str, object]: """What a wake notice says about this job.""" command = self.pipeline[:NOTICE_COMMAND_CAP] + ( "..." if len(self.pipeline) > NOTICE_COMMAND_CAP else "" ) outcome = ( "timed out" if self.timed_out else f"exit_code={self.exit_code}" if self.exit_code is not None else "exit status unknown" ) seconds = ( f"ran {self.duration:.1f}s" if self.duration is not None else "unknown duration" ) return { "id": self.id, "command": command, "where": f" on {remote}" if remote else "", "summary": f"{outcome}, {seconds}", "exit_code": self.exit_code, "timed_out": self.timed_out, "duration": self.duration, "host": remote, } async def stop(self) -> albedo_proc.Termination: """End the job's process group. A failed attempt stays retryable.""" self.read = True # an explicit stop is its own report; no wake is owed ending = await self._stop() if ending.gone and not self.task.done(): with contextlib.suppress(Exception, asyncio.CancelledError): await asyncio.shield(self.task) return ending async def _stop(self, exited: bool = False) -> albedo_proc.Termination: """End the group; once the command `exited` on its own, what a process that left the group still parents stays with that process.""" if self.termination is not None and self.termination.gone: return self.termination process = self.process if process is None: if not self._starting: self.spawning.cancel() try: process = await self._spawn() except (Exception, asyncio.CancelledError) as error: self.termination = albedo_proc.Termination( None, (), True, (f"spawn failed: {error}",) ) release(self) return self.termination if self.ending is None or self.ending.done(): group = self.claim() self.ending = loop.create_task( albedo_proc.end(group, exited) if group is not None else _unstarted() ) ending = await asyncio.shield(self.ending) self.termination = ending release(self) return ending def saved(self) -> dict[str, object] | None: """A finished job as the book keeps it, or None when its output cannot be kept.""" output = self.capture.persist() if output is None or self.duration is None: return None tail = output["tail"] return { **facts(self), "spill": output["spill"], "spilled": output["spilled"], "tail": base64.b64encode(tail).decode() if isinstance(tail, bytes) else None, } @classmethod def restored(cls, saved: dict[str, object], capture: albedo_capture.Capture) -> Run: """A finished job from an earlier helper: how it ended, with its output read back from disk.""" job = cls.__new__(cls) job.service = bool(saved["service"]) job.source, job.feed, job.outlet = None, None, Outlet() job.outlet.close() job.id, job.capture = str(saved["id"]), capture job.argv, job.command = [], str(saved["command"]) job.process, job.group, job.cell = None, None, cast("str | None", saved["cell"]) job.exit_code = cast("int | None", saved["exit_code"]) job.timed_out = bool(saved["timed_out"]) job.timeout = float(cast(float, saved["timeout"])) job.duration = float(cast(float, saved["duration"])) job.started = loop.time() - ( time.time() - int(cast(int, saved["started_ms"])) / 1000 ) job.termination = albedo_proc.Termination(None, (), True) job.ending = None job.awaited, job.waiters, job._starting = True, 0, False job.read = bool(saved["read"]) job.task = loop.create_future() job.task.set_result(job) return job async def _unstarted() -> albedo_proc.Termination: return albedo_proc.Termination(None, (), True, ("process never started",)) def release(job: Run) -> None: """Retire active work only when its group is gone.""" if ( job.termination is None or not job.termination.gone or active.pop(job.id, None) is None ): return write_live() retained.pop(job.id, None) retained[job.id] = job while len(retained) > RETAINED_LIMIT: _, evicted = retained.popitem(last=False) if jobs.get(evicted.id) is evicted: del jobs[evicted.id] class Refused(Exception): """A wake notice that was not taken; `code` says whether to try again.""" def __init__(self, code: str, message: str) -> None: super().__init__(message) self.code = code async def wake(notice: dict[str, object]) -> None: """Hand one notice to the sink. `busy` and `unknown` are retried by the caller.""" taker = sink if taker is None: raise Refused("unknown", "nothing takes wake notices yet") try: reply = await taker.request({"op": "wake", "notice": notice}) except ConnectionError as error: raise Refused("unknown", str(error)) from error if reply.get("ok") is not True: raise Refused( str(reply.get("code", "unavailable")), str(reply.get("error", "")) ) def owe(job: Run) -> None: """Queue a finished job's wake. One announcer carries every owed result, so jobs that finish during a turn wake the session once, not once each.""" owed[job.id] = job kick() def kick() -> None: global announcer if owed and (announcer is None or announcer.done()): announcer = loop.create_task(_announce()) async def _announce() -> None: """Wake the session for every owed result, retrying while it runs. A busy session answers with a refusal rather than queueing, so the notice retries until the run ends, naming whatever is still owed then; a read or await in the meantime retires that job, which is also the creating-cell barrier: a cell that will await its own job suppresses the wake before any turn can start. The first look comes a moment after the job's end, so an await still on its way (its request crosses a socket) is counted. """ await asyncio.sleep(NOTICE_GRACE) while True: for job in [job for job in owed.values() if not job.unreported]: del owed[job.id] if not owed: return batch = list(owed.values()) try: await wake(notice([job.notice_facts() for job in batch])) except Exception as error: if getattr(error, "code", "") in ("busy", "unknown"): await asyncio.sleep(NOTICE_RETRY) continue for job in batch: job.capture.write(f"\n[completion notice not delivered: {error}]\n") for job in batch: 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 = " if nothing else is needed, reply briefly and stay idle." if len(facts) == 1: [job] = facts reading = ( f" read its output with .tail() or await rem.output.read({job['id']!r})." if job["host"] else f" read its output with jobs[{job['id']!r}].tail() or output.read({job['id']!r})." ) text = ( "a background job finished" f"{job['where']} ({job['summary']}): {job['command']}." + reading + advice ) else: listed = "; ".join( f"{_name(job)}{job['where']} ({job['summary']}): {job['command']}" for job in facts ) remote = any(job["host"] for job in facts) text = ( f"{len(facts)} background jobs finished: {listed}." " read output with jobs[id].tail() or output.read(id)." + (REMOTE_READING if remote else "") + advice ) display = "\n".join( f"job finished{job['where']} ({job['summary']}): {job['command']}" for job in facts ) return {"display": display, "text": text, "jobs": facts} def facts(job: Run) -> dict[str, object]: """What the kernel's handles and the daemon's lists know of one job.""" begun = (time.time() - loop.time() + job.started) * 1000 process, group = job.process, job.group return { "id": job.id, "command": job.command, "pipeline": job.pipeline, "exit_code": job.exit_code, "timed_out": job.timed_out, "timeout": job.timeout, "duration": job.duration, "started_ms": int(begun), "ended_ms": None if job.duration is None else int(begun + job.duration * 1000), "state": "running" if job.duration is None else "exited", "done": job.task.done(), "service": job.service, "cell": job.cell, "seen": job.capture.seen, "retained": job.capture.retained, "spill": job.capture.spill, "pid": process.pid if process is not None else None, "pgid": group.pgid if group is not None else None, "leader": group.leader if group is not None else None, "source": job.source.id if job.source is not None else None, "read": job.read, } def atomically(name: str, value: object) -> None: """Write `value` as JSON to `name` in the helper's directory, all or nothing.""" fd, temporary = tempfile.mkstemp(dir=directory, prefix=".jobs.") try: with os.fdopen(fd, "w") as file: json.dump(value, file) os.replace(temporary, os.path.join(directory, name)) except BaseException: with contextlib.suppress(OSError): os.unlink(temporary) raise def write_live() -> None: """The groups still owned, for whoever must end them if this helper cannot.""" atomically( "live.json", { "helper": { "pid": os.getpid(), "pgid": os.getpgrp(), "leader": albedo_proc.leader_token(os.getpid()), }, "jobs": { job.id: { "pid": job.process.pid, "pgid": job.group.pgid, "leader": job.group.leader, "command": job.pipeline[:4096], "service": job.service, } for job in active.values() if job.group is not None and job.process is not None }, }, ) def save_book() -> None: """The finished jobs, newest first, each with the file its output is read from.""" book = [saved for job in reversed(retained.values()) if (saved := job.saved())] atomically("book.json", {"jobs": book}) def load_book() -> None: try: with open(os.path.join(directory, "book.json")) as file: book = json.load(file)["jobs"] except (OSError, ValueError, KeyError): return for saved in reversed(book): spill, tail = saved.get("spill"), saved.get("tail") if saved["id"] in jobs or ( isinstance(spill, str) and not os.path.exists(spill) ): continue capture = albedo_capture.Capture.revive( { "id": saved["id"], "kind": "job", "seen": saved["seen"], "spill": spill, "spilled": saved["spilled"], "tail": base64.b64decode(tail) if isinstance(tail, str) else None, } ) job = Run.restored(saved, capture) jobs[job.id] = retained[job.id] = job async def close() -> None: """End every live group inside one shared deadline.""" owned = list(active.values()) # Never spawn a pending command just to shut it down. In-flight OS spawns, # however, must finish transferring ownership before the shared ladder. for job in owned: if not job._starting: job.spawning.cancel() await asyncio.gather( *(job._spawn() for job in owned if job.process is None), return_exceptions=True ) live = [(job, group) for job in owned if (group := job.claim()) is not None] if not live: return endings = await albedo_proc.terminate( [group for _, group in live], SHUTDOWN_TERM, SHUTDOWN_KILL ) for (job, _), ending in zip(live, endings): job.termination = ending release(job) for ending in endings: if not ending.gone: log(f"cleanup failed: {ending.report()}") def log(text: str) -> None: print(f"{time.strftime('%H:%M:%S')} {text}", file=sys.stderr, flush=True) class Missing(Exception): """A request for a job this helper does not hold.""" class Peer: """One connection: a kernel or the daemon. Requests run as tasks, so a long one (`wait_begin` is not; `stop` is) never holds up the next; the peer's end cancels what it left running and releases the awaits it held.""" def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): self.reader, self.writer = reader, writer self.watching = False self.waiting: dict[str, int] = {} # awaits this peer holds open, by job self.tasks: set[asyncio.Task[None]] = set() self.asked: dict[int, asyncio.Future[dict[str, object]]] = {} self.numbered = 0 def push(self, frame: dict[str, object]) -> None: data = json.dumps(frame, separators=(",", ":")).encode() if not self.writer.is_closing(): self.writer.write(struct.pack(">I", len(data)) + data) async def request(self, frame: dict[str, object]) -> dict[str, object]: """Ask this peer something (the wake) and wait for its reply.""" self.numbered += 1 answer: asyncio.Future[dict[str, object]] = loop.create_future() self.asked[self.numbered] = answer self.push({**frame, "id": self.numbered}) return await answer async def serve(self) -> None: global sink self.push( { "hello": { "protocol": PROTOCOL, "bundle": bundle(), **IDENTITY, } } ) try: while True: size = struct.unpack(">I", await self.reader.readexactly(4))[0] if size > MAX_FRAME: break frame = json.loads(await self.reader.readexactly(size)) if "re" in frame: answer = self.asked.pop(frame["re"], None) if answer is not None and not answer.done(): answer.set_result(frame) continue task = loop.create_task(self.handle(frame)) self.tasks.add(task) task.add_done_callback(self.tasks.discard) except (asyncio.IncompleteReadError, ConnectionError, ValueError): pass finally: for task in self.tasks: task.cancel() for answer in self.asked.values(): if not answer.done(): answer.set_exception(ConnectionResetError("peer closed")) if self in peers: peers.remove(self) if sink is self: sink = None for id, count in self.waiting.items(): job = jobs.get(id) if job is not None: job.waiters -= count if job.task.done(): job.owe_unread() self.writer.close() async def handle(self, frame: dict[str, object]) -> None: number = frame.get("id") try: operation = OPERATIONS[str(frame.get("op"))] result = await operation(self, frame) reply: dict[str, object] = {"ok": True, **(result or {})} except ( Missing, LookupError, OverflowError, KeyError, ValueError, TypeError, OSError, ) as error: reply = {"ok": False, "code": failure_code(error), "error": str(error)} if number is not None: self.push({"re": number, **reply}) IDENTITY: dict[str, object] = {} @functools.cache def bundle() -> str: """The digest of the tree this helper runs from, read once.""" return albedo_bundle.digest() def failure_code(error: Exception) -> str: """How a failed request is named on the wire.""" for kind, code in ( (Missing, "missing"), (LookupError, "lost"), # output past what was kept (OverflowError, "limit"), # too many active jobs (OSError, "failed"), ): if isinstance(error, kind): return code return "invalid" def emit(event: str, job: Run) -> None: ending = job.termination for peer in peers: if peer.watching: peer.push( { "event": event, "job": {**facts(job), "done": True} if event == "ended" else facts(job), "cleanup": ending.as_json() if ending and event == "ended" else None, } ) def held(frame: dict[str, object]) -> Run: job = jobs.get(str(frame.get("job"))) if job is None: raise Missing( f"job {frame.get('job')} is no longer kept: only the {RETAINED_LIMIT} newest " "finished jobs stay readable, and this one was displaced; its output is gone" ) return job def stdin_of(spec: object) -> Data | Run | None: if spec is None: return None given = cast(dict[str, str], spec) if "job" in given: return held({"job": given["job"]}) if "text" in given: return given["text"] if "bytes" in given: return base64.b64decode(given["bytes"]) return Path(given["path"]) async def attach(peer: Peer, frame: dict[str, object]) -> dict[str, object]: global sink peer.watching = bool(frame.get("watch")) if frame.get("sink"): sink = peer kick() return { "live": [facts(job) for job in active.values()], "owed": list(owed), } def begin( argv: list[str], timeout: float, *, cwd: str | None = None, env: dict[str, str] | None = None, stdin: Data | Run | None = None, service: bool = False, cell: str | None = None, ) -> Run: """A job for argv, if the helper has room for another.""" if len(active) >= ACTIVE_LIMIT: raise OverflowError(f"{ACTIVE_LIMIT} jobs are active; await or stop one first") return Run( argv, timeout, cwd=cwd or os.getcwd(), env=env or dict(os.environ), stdin=stdin, service=service, cell=cell, ) async def start(peer: Peer, frame: dict[str, object]) -> dict[str, object]: job = begin( [str(word) for word in cast(list[str], frame["argv"])], float(cast(float, frame["timeout"])), cwd=str(frame["cwd"]), env=cast(dict[str, str], frame["env"]), stdin=stdin_of(frame.get("stdin")), service=bool(frame.get("service")), cell=cast("str | None", frame.get("cell")), ) # The OS spawn finishes before the reply, so the group is owned and visible. with contextlib.suppress(Exception): await job._spawn() return {"job": facts(job)} async def wait_begin(peer: Peer, frame: dict[str, object]) -> None: job = held(frame) job.waiters += 1 peer.waiting[job.id] = peer.waiting.get(job.id, 0) + 1 async def wait_end(peer: Peer, frame: dict[str, object]) -> None: job = held(frame) job.waiters -= 1 peer.waiting[job.id] -= 1 if frame.get("delivered"): job.awaited = True if job.task.done(): job.owe_unread() async def stop(peer: Peer, frame: dict[str, object]) -> dict[str, object]: return {"termination": (await held(frame).stop()).as_json()} async def shutdown() -> None: """End every job, keep the book, and leave.""" await close() if os.path.isdir(directory): write_live() save_book() for peer in peers: peer.push({"event": "idle"}) loop.call_later(0.05, loop.stop) async def end_all(peer: Peer, frame: dict[str, object]) -> None: await shutdown() async def window(peer: Peer, frame: dict[str, object]) -> dict[str, object]: job = held(frame) offset = cast("int | None", frame.get("offset")) start, end, text = read_window( job.capture, offset, int(cast(int, frame["limit"])), job.duration is not None ) return {"start": start, "end": end, "text": text, "job": facts(job)} async def mark_read(peer: Peer, frame: dict[str, object]) -> None: held(frame).mark_read() async def listing(peer: Peer, frame: dict[str, object]) -> dict[str, object]: newest = sorted(jobs.values(), key=lambda job: job.started, reverse=True) return {"jobs": [facts(job) for job in newest[:MAX_LISTED]]} def encoded(data: bytes) -> dict[str, object]: return {"data": base64.b64encode(data).decode()} OPERATIONS: dict[ str, Callable[ [Peer, dict[str, object]], Coroutine[object, object, dict[str, object] | None] ], ] = { "attach": attach, "start": start, "wait_begin": wait_begin, "wait_end": wait_end, "stop": stop, "end_all": end_all, "window": window, "mark_read": mark_read, "list": listing, } def operation( name: str, ) -> Callable[[Callable[[Run, dict[str, object]], dict[str, object]]], None]: """A request answered at once from one job's state.""" def register(read: Callable[[Run, dict[str, object]], dict[str, object]]) -> None: async def run(peer: Peer, frame: dict[str, object]) -> dict[str, object]: return read(held(frame), frame) OPERATIONS[name] = run return register @operation("facts") def _facts(job: Run, frame: dict[str, object]) -> dict[str, object]: return {"job": facts(job)} @operation("tail") def _tail(job: Run, frame: dict[str, object]) -> dict[str, object]: return encoded(job.capture.tail()) @operation("bytes") def _bytes(job: Run, frame: dict[str, object]) -> dict[str, object]: try: return encoded( job.capture.read_bytes( int(cast(int, frame["offset"])), int(cast(int, frame["size"])) ) ) except ValueError as error: # not retained raise LookupError(str(error)) from error @operation("append") def _append(job: Run, frame: dict[str, object]) -> dict[str, object]: job.capture.write(str(frame["text"])) return {} async def watch() -> None: """Leave when nothing is left to do, or when there is no one to do it for.""" global idle_since while True: await asyncio.sleep(1.0) busy = active or owed idle_since = None if busy else (idle_since or loop.time()) if not os.path.isdir(directory) or ( idle_since is not None and loop.time() - idle_since >= IDLE_EXIT ): await shutdown() return def main(argv: list[str]) -> None: global loop, directory directory, owner, spill = os.path.abspath(argv[1]), None, argv[2] if len(argv) > 3: owner = int(argv[3]) # a pipe whose end is the kernel's: EOF ends this helper if os.fork(): os._exit(0) # the kernel reaps this at once; the helper is nobody's child os.makedirs(directory, mode=0o700, exist_ok=True) os.chdir(directory) lock = os.open("helper.lock", os.O_CREAT | os.O_RDWR, 0o600) try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: sys.exit(0) # another helper owns this directory log_fd = os.open("jobs.log", os.O_CREAT | os.O_WRONLY | os.O_APPEND, 0o600) os.dup2(log_fd, 2) albedo_proc.set_name("jobs") albedo_capture.prune_spills(spill) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) albedo_proc.reap_stopped_safely(loop) IDENTITY.update( pid=os.getpid(), pgid=os.getpgrp(), leader=albedo_proc.leader_token(os.getpid()) ) with contextlib.suppress(OSError): os.unlink(SOCKET) server = loop.run_until_complete(asyncio.start_unix_server(connected, path=SOCKET)) os.chmod(SOCKET, 0o600) load_book() write_live() if owner is not None: loop.add_reader(owner, lambda: loop.create_task(shutdown())) for name in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(name, lambda: loop.create_task(shutdown())) loop.create_task(watch()) os.write(1, b"ready\n") os.close(1) loop.run_forever() server.close() with contextlib.suppress(OSError): os.unlink(SOCKET) async def connected(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: peer = Peer(reader, writer) peers.append(peer) await peer.serve() if __name__ == "__main__": main(sys.argv)