diff --git a/AGENTS.md b/AGENTS.md index 23c09a4f..c1fb1573 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,9 @@ src/panopticon/ # git_url names one, ADR 0011 §1c); spawner.py = the spawn loop (claim an unclaimed task → spawn its # container; prefills claude's input box with the task memo on a first spawn; # `pause` stops a snoozed task's container + releases its claim, and the same - # snooze gate keeps spawn/reconcile/heal off it until the deadline lapses); + # snooze gate keeps spawn/reconcile/heal off it until the deadline lapses; + # `sweep` removes a terminal, exited task's dind + config docker volumes — once + # per process, never on a respawn, which needs the nested image cache); # prefill.py = the detached input-box prefill # poller (mirrors cloude-cade: pipe-pane watch for ESC[?2004h → paste-buffer the # description, unsent); daemon.py = the provision-only pull loop; @@ -219,7 +221,7 @@ on every PR (the same commands the Makefile wraps). the truth table folding the session service's reported `LifecyclePhase` with registration presence + runner liveness into the displayed `ContainerStatus` (queued/…/live/down/failed/ disconnected), order-of-precedence and all. -- `tests/test_spawner.py` — the spawn loop (ADR 0008): unit tests pin `spawn_one` (claim → spawn, +- `tests/sessionservice/test_spawner.py` — the spawn loop (ADR 0008): unit tests pin `spawn_one` (claim → spawn, skip terminal/claimed, skip on a 409 lost claim), the **reported phase sequence** (claiming → preparing → building → starting → awaiting, and `failed` with the error when a step raises), the `reconcile` down-detection (a claimed-by-us in-flight task whose container is gone → clear the @@ -230,12 +232,16 @@ on every PR (the same commands the Makefile wraps). with a press-R detail — + survivor-window budget reset), `pause` **snooze → stop** (a snoozed task's container is stopped and its claim released — even mid-turn; no-op when unclaimed/terminal/ shell/awake/already stopped — and the matching gates that keep `spawn_one`/`reconcile`/`heal` off a - paused task within the same pass), and the `spawnable_tasks` filter; integration tests claim + + paused task within the same pass), `sweep` **volume removal** (a terminal task whose container + has exited → its container, then `panopticon-dind-`, then `panopticon-config-` — claimed + or not; skips non-terminal/still-running/shell/already-swept tasks; each volume's failure is + logged without skipping the other or being retried every pass), and the `spawnable_tasks` filter; integration tests claim + spawn against the real task service over REST (fake git/runner) and drive the whole snooze cycle (stopped + `queued` → the deadline lapses on an injected clock → claimed + respawned). -- `tests/test_host.py` — the unified per-host daemon (ADR 0008/0011): a unit test isolates a +- `tests/sessionservice/test_host.py` — the unified per-host daemon (ADR 0008/0011): a unit test isolates a failing task, another pins that each pass also `heal`s every task, and another that it `pause`s - every task **before** spawning it (so nothing re-spawns what a snooze just stopped); an integration test drives + every task **before** spawning it (so nothing re-spawns what a snooze just stopped), and another + that it `sweep`s every task right after `cleanup`; an integration test drives spawn → set slug → provision against the real task service over REST (claimed + spawned, then branched, no re-spawn). - `tests/test_daemon.py` — the observe-and-provision loop + its launch: unit tests drive @@ -247,10 +253,11 @@ on every PR (the same commands the Makefile wraps). resource reads back. No LLM, no HTTP (HTTP hosting is the runnable server, Slice 7a). - `tests/test_skeleton.py` — the end-to-end walking skeleton (create → register → slug → transition → history) over the REST API, no Docker. -- `tests/test_local_runner.py` / `tests/test_entrypoint.py` — the runner's emitted docker/tmux +- `tests/sessionservice/test_local_runner.py` / `tests/container/test_entrypoint.py` — the runner's emitted docker/tmux commands (incl. the ADR 0011 `/workspace` mount + the CLI's spawn-prep→spawn flow, `is_running`'s `docker ps` probe + `has_session`'s `tmux list-sessions` probe for self-heal, `exit_reason`'s - `docker inspect` of a stopped container — OOM-kill before exit code) and the container + `docker inspect` of a stopped container — OOM-kill before exit code, `remove_volume`'s + `docker volume rm --force`, and that the volume names it's handed match what `spawn` mounts) and the container entrypoint loop (fakes; no Docker/LLM), plus a `skipif` docker integration test. - `tests/test_spawn.py` — spawn-prep (ADR 0011): unit tests pin the `clone --local` of the per-task checkout and the idempotency gate (skips when the checkout already exists), plus the diff --git a/src/panopticon/sessionservice/host.py b/src/panopticon/sessionservice/host.py index 4fabd265..048f8b64 100644 --- a/src/panopticon/sessionservice/host.py +++ b/src/panopticon/sessionservice/host.py @@ -82,6 +82,10 @@ def tick(self, tasks: list[JsonObj]) -> None: ``publish`` runs **before** ``cleanup``: a task can request its push and reach a terminal state in the same breath, and cleanup deletes the per-task clone the push reads from. + ``sweep`` runs **after** ``cleanup``: a terminal task whose container has exited also gets its + dind + config volumes removed (once per process). Respawns never reach it — they skip + terminal tasks, so the image cache a respawn relies on survives. + A cheap REST-only **pre-pass flags every orphan ``healing`` first**, before any respawn. The respawn loop below is serial (each :meth:`Spawner.heal` blocks on ``docker run`` + the tmux session), so marking inside it would surface only the orphan currently coming back and leave @@ -101,6 +105,7 @@ def tick(self, tasks: list[JsonObj]) -> None: self._spawner.reconcile(task) self._spawner.heal(task) self._spawner.cleanup(task) + self._spawner.sweep(task) # terminal + exited → remove its docker volumes except Exception: # a transient git/REST/FS error on one task must not stall the others _log.warning("host pass failed for task %s", task.get("id"), exc_info=True) continue diff --git a/src/panopticon/sessionservice/local_runner.py b/src/panopticon/sessionservice/local_runner.py index b94abdbe..4b03711f 100644 --- a/src/panopticon/sessionservice/local_runner.py +++ b/src/panopticon/sessionservice/local_runner.py @@ -80,6 +80,19 @@ def session_name(task_id: str) -> str: return f"panopticon-{task_id}" +def dind_volume(task_id: str) -> str: + """The named volume holding ``task_id``'s nested Docker daemon store (``/var/lib/docker``) — the + repo's whole pulled image stack, tens of GB. Kept across respawns (it's what makes one fast); + removed by the host daemon's sweep once the task is terminal.""" + return f"panopticon-dind-{task_id}" + + +def config_volume(task_id: str) -> str: + """The named volume holding ``task_id``'s CLI config dir (its resumable session history, see + :func:`config_mount`). Kept across respawns; removed by the sweep once the task is terminal.""" + return f"panopticon-config-{task_id}" + + #: Where a task's per-task clone is mounted — the one stable, writable path the agent works in #: for the whole task (ADR 0011): planning, then coding on its branch once provisioned. WORKSPACE_MOUNT = "/workspace" @@ -337,7 +350,7 @@ def _report(phase: LifecyclePhase) -> None: docker_in_docker ): # privileged nested Docker daemon (repo capability); entrypoint starts it docker_run.append("--privileged") - docker_run += ["--volume", f"panopticon-dind-{task_id}:/var/lib/docker"] + docker_run += ["--volume", f"{dind_volume(task_id)}:/var/lib/docker"] env["PANOPTICON_DOCKER_IN_DOCKER"] = "1" if env_path := secrets_file_path(env_file, secrets_dir=self._secrets_dir): docker_run += ["--env-file", env_path] # per-repo secrets, resolved host-locally @@ -356,7 +369,7 @@ def _report(phase: LifecyclePhase) -> None: # Per-task config volume: persists the CLI's session history across respawn/recreate (the # transcripts live in the config dir, which is otherwise thrown away with the container). The # mount path is the resolved CLI's config dir, or resume silently breaks (ADR 0014 §4a). - docker_run += ["--volume", f"panopticon-config-{task_id}:{config_mount(agent_cli)}"] + docker_run += ["--volume", f"{config_volume(task_id)}:{config_mount(agent_cli)}"] for key, value in env.items(): docker_run += ["--env", f"{key}={value}"] docker_run.append( @@ -483,6 +496,12 @@ def delete_workspace_contents(self, path: str) -> None: ] ) + def remove_volume(self, name: str) -> None: + """Remove the named Docker volume ``name`` (one of a terminal task's :func:`dind_volume` / + :func:`config_volume`). ``--force`` makes an already-gone volume a no-op, but a volume still + mounted by a container is refused — so a real failure raises for the caller to log.""" + self._run(["docker", "volume", "rm", "--force", name]) + def stop(self, container_id: str) -> None: # Idempotent: tolerate an already-gone session/container. self._run(self._tmux("kill-session", "-t", container_id), check=False) diff --git a/src/panopticon/sessionservice/spawner.py b/src/panopticon/sessionservice/spawner.py index de36fc55..fb06c280 100644 --- a/src/panopticon/sessionservice/spawner.py +++ b/src/panopticon/sessionservice/spawner.py @@ -33,7 +33,13 @@ from panopticon.sessionservice.clones import CloneCache from panopticon.sessionservice.executions import WorkflowExecutions from panopticon.sessionservice.images import ImageBuilder -from panopticon.sessionservice.local_runner import LocalRunner, base_image, session_name +from panopticon.sessionservice.local_runner import ( + LocalRunner, + base_image, + config_volume, + dind_volume, + session_name, +) from panopticon.sessionservice.shell_runner import ShellRunner from panopticon.sessionservice.spawn import cleanup_workspace, prepare_workspace @@ -145,6 +151,9 @@ def __init__( #: task_id → (respawns in the current burst, monotonic time of the last respawn), the #: crash-loop guard state for :meth:`heal`. self._respawns: dict[str, tuple[int, float]] = {} + #: Terminal tasks whose volumes :meth:`sweep` has already tried to remove this process — so it + #: runs docker at most once per task (a restart re-sweeps each once, harmlessly). + self._swept: set[str] = set() def spawn_one(self, task: JsonObj) -> str | None: """Claim + spawn ``task`` if it's a fresh unclaimed, non-terminal task; else ``None``. @@ -550,6 +559,38 @@ def cleanup(self, task: JsonObj) -> None: docker_cleanup=self._docker_cleanup, ) + def sweep(self, task: JsonObj) -> None: + """Remove a terminal task's Docker volumes once its container has exited. + + A ``docker_in_docker`` task's :func:`dind_volume` holds the nested daemon's whole image + store (tens of GB), and every container task has a :func:`config_volume`; nothing else ever + removes them. They must outlive a *respawn* (heal, snooze wake, ``R``) — the image cache and + the CLI session history are what make one fast and resumable — but a terminal task never + respawns, so here they go. + + Gated like :meth:`cleanup` — terminal, and no container running on this host — and **not** + on the claim: the container agent releases its own claim on exit, and :meth:`cleanup` + releases any it left, so a claim gate would almost never fire. (A host that never ran the + task just no-ops.) Shell tasks have no volumes. A stopped container still references its + volumes (they're spawned without ``--rm``), so it is removed first. The two volumes are + removed independently — a config-volume failure can't skip the dind one — and each failure + is logged, never raised. The task is recorded as swept whatever the outcome, so a failure + isn't retried (and re-logged) every pass; a runner restart retries it once.""" + task_id = task["id"] + if task["state"] not in TERMINAL_LABELS or task_id in self._swept: + return + if self._executions.is_shell(task.get("workflow")): + return # no container, no volumes + if self._runner.is_running(task_id): + return # still up — wait for it to exit, as cleanup does + self._swept.add(task_id) + self._runner.stop(session_name(task_id)) # a stopped container pins its volumes + for volume in (dind_volume(task_id), config_volume(task_id)): + try: + self._runner.remove_volume(volume) + except Exception: # best-effort — never let one volume (or task) stall the pass + _log.warning("task %s: removing volume %s failed", task_id, volume, exc_info=True) + def _compose_image(self, workflow: str, repo: JsonObj, agent_cli: str) -> str: """Compose the task's image (the CLI's base → workflow → repo layers, ADR 0005 + ADR 0014 §4) and return its tag; when neither tier contributes a layer, the per-CLI base image itself diff --git a/tests/sessionservice/test_host.py b/tests/sessionservice/test_host.py index 780a4bdb..a5a6ed05 100644 --- a/tests/sessionservice/test_host.py +++ b/tests/sessionservice/test_host.py @@ -128,6 +128,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -160,6 +163,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: healed.append(task["id"]) + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -195,6 +201,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: events.append(f"heal:{task['id']}") + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -230,6 +239,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -265,6 +277,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: events.append(f"cleanup:{task['id']}") @@ -282,6 +297,43 @@ def publish(self, task: JsonObj) -> None: assert events == ["publish:t1", "cleanup:t1", "publish:t2", "cleanup:t2"] +def test_tick_sweeps_each_task_after_cleaning_it_up() -> None: + # Every pass offers every task to `sweep` (it self-gates on terminal + exited), right after + # `cleanup` — the step that removes a terminal task's dind + config volumes. + events: list[str] = [] + + class _Spawner: + def mark_healing(self, task: JsonObj) -> None: + return None + + def pause(self, task: JsonObj) -> None: + return None + + def spawn_one(self, task: JsonObj) -> None: + return None + + def reconcile(self, task: JsonObj) -> None: + return None + + def heal(self, task: JsonObj) -> None: + return None + + def cleanup(self, task: JsonObj) -> None: + events.append(f"cleanup:{task['id']}") + + def sweep(self, task: JsonObj) -> None: + events.append(f"sweep:{task['id']}") + + class _Provisioner: + def provision(self, task: JsonObj) -> None: + return None + + daemon = HostDaemon(_FakeClient([]), _Spawner(), _Provisioner(), _NoopPublisher()) # type: ignore[arg-type] + daemon.tick([{"id": "t1"}, {"id": "t2"}]) + daemon.tick([{"id": "t1"}]) # and again on the next pass — sweep's own gate makes it cheap + assert events == ["cleanup:t1", "sweep:t1", "cleanup:t2", "sweep:t2", "cleanup:t1", "sweep:t1"] + + def test_tick_isolates_a_failing_publish_from_the_other_tasks() -> None: published: list[str] = [] @@ -301,6 +353,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -345,6 +400,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -394,6 +452,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -439,6 +500,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: return None @@ -605,6 +669,9 @@ def reconcile(self, task: JsonObj) -> None: def heal(self, task: JsonObj) -> None: return None + def sweep(self, task: JsonObj) -> None: + return None + def cleanup(self, task: JsonObj) -> None: cleaned.append(task["id"]) diff --git a/tests/sessionservice/test_local_runner.py b/tests/sessionservice/test_local_runner.py index e0783169..8bd79647 100644 --- a/tests/sessionservice/test_local_runner.py +++ b/tests/sessionservice/test_local_runner.py @@ -19,6 +19,8 @@ LocalRunner, base_image, config_mount, + config_volume, + dind_volume, ) from panopticon.sessionservice.runner import Runner @@ -527,6 +529,23 @@ def test_stop_kills_session_and_force_removes_container_idempotently() -> None: assert (["docker", "rm", "--force", "panopticon-t1"], False) in rec.calls +def test_remove_volume_force_removes_the_named_volume() -> None: + # `--force` turns an already-gone volume into a no-op; check=True so a real failure (a volume + # still mounted by a container) raises for the spawner's sweep to log. + rec = _Recorder() + LocalRunner("http://svc", run=rec).remove_volume("panopticon-dind-t1") + assert rec.calls == [(["docker", "volume", "rm", "--force", "panopticon-dind-t1"], True)] + + +def test_volume_names_match_what_spawn_mounts() -> None: + rec = _Recorder() + LocalRunner("http://svc", run=rec).spawn("t1", docker_in_docker=True) + docker_run = next(args for args, _check in rec.calls if args[:2] == ["docker", "run"]) + mounts = [docker_run[i + 1] for i, arg in enumerate(docker_run) if arg == "--volume"] + assert any(m.startswith(f"{dind_volume('t1')}:") for m in mounts) + assert any(m.startswith(f"{config_volume('t1')}:") for m in mounts) + + def test_delete_workspace_contents_runs_root_container_to_empty_directory() -> None: rec = _Recorder() LocalRunner("http://svc", image="panopticon-base", run=rec).delete_workspace_contents( diff --git a/tests/sessionservice/test_spawner.py b/tests/sessionservice/test_spawner.py index 3447d33a..f6d4044b 100644 --- a/tests/sessionservice/test_spawner.py +++ b/tests/sessionservice/test_spawner.py @@ -41,6 +41,8 @@ def __init__( ) -> None: self.spawned: list[dict[str, object]] = [] self.stopped: list[str] = [] + self.removed_volumes: list[str] = [] + self.failing_volumes: set[str] = set() # remove_volume raises for these names self._running = running self._session = session self._exit_reason = exit_reason @@ -94,6 +96,11 @@ def stop(self, container_id: str) -> None: def delete_workspace_contents(self, path: str) -> None: pass + def remove_volume(self, name: str) -> None: + self.removed_volumes.append(name) # recorded even when it fails — the attempt is the point + if name in self.failing_volumes: + raise RuntimeError(f"cannot remove {name}") + class _FakeClient: """Captures claims + reported lifecycle phases; serves one repo. `claim` 409s when already held @@ -729,6 +736,7 @@ def test_heal_respawns_an_orphan_claimed_by_us_with_no_session() -> None: assert cid == "panopticon-t1" assert [s["task_id"] for s in runner.spawned] == ["t1"] # respawned assert client.claims == [] # already ours — heal doesn't re-claim + assert runner.removed_volumes == [] # a respawn keeps the dind image cache + session history def test_heal_skips_a_task_whose_session_is_alive() -> None: @@ -1639,3 +1647,70 @@ def _spawner_at() -> Spawner: assert woken.spawn_one(client.get_task(task_id)) == f"panopticon-{task_id}" assert client.get_task(task_id)["claimed_by"] == "host-1" assert len(runner.spawned) == 2 # respawned — same clone, same config volume + + +def test_sweep_removes_a_terminal_tasks_container_then_its_dind_and_config_volumes() -> None: + runner = _FakeRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.sweep({"id": "t1", "state": "COMPLETE", "claimed_by": "host-1"}) + # The stopped container goes first — it would otherwise pin its volumes ("volume is in use"). + assert runner.stopped == ["panopticon-t1"] + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"] + + +def test_sweep_sweeps_an_unclaimed_terminal_task() -> None: + # The agent releases its claim on exit (and cleanup releases any it left), so the sweep can't + # gate on the claim — an unclaimed DROPPED task's volumes must still go. + runner = _FakeRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.sweep({"id": "t1", "state": "DROPPED", "claimed_by": None}) + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"] + + +def test_sweep_runs_docker_once_per_task() -> None: + runner = _FakeRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + task = {"id": "t1", "state": "COMPLETE"} + spawner.sweep(task) + spawner.sweep(task) # already swept → no second stop / volume rm + assert runner.stopped == ["panopticon-t1"] + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"] + + +def test_sweep_skips_a_non_terminal_task() -> None: + runner = _FakeRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.sweep({"id": "t1", "state": "ITERATING", "claimed_by": "host-1"}) + assert runner.stopped == [] + assert runner.removed_volumes == [] + + +def test_sweep_waits_while_the_container_is_still_running() -> None: + runner = _FakeRunner(running=True) + spawner = _cleanup_spawner(runner, workspace_exists=False) + task = {"id": "t1", "state": "COMPLETE"} + spawner.sweep(task) + assert runner.removed_volumes == [] + runner._running = False # the agent exits → the next pass sweeps (it wasn't marked swept) + spawner.sweep(task) + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"] + + +def test_sweep_skips_a_shell_task() -> None: + runner = _FakeRunner(running=False) + client = _FakeClient(repo=_REPO, runner_type="shell", shell_script="echo hi") + spawner = _shell_spawner(client, runner, _FakeShellRunner()) + spawner.sweep({"id": "t1", "state": "COMPLETE", "workflow": "setup-repo"}) + assert runner.stopped == [] + assert runner.removed_volumes == [] + + +def test_sweep_removes_each_volume_independently_of_the_others_failure() -> None: + for failing in ("panopticon-dind-t1", "panopticon-config-t1"): + runner = _FakeRunner(running=False) + runner.failing_volumes = {failing} + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.sweep({"id": "t1", "state": "COMPLETE"}) # logs, never raises + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"] + spawner.sweep({"id": "t1", "state": "COMPLETE"}) # a failure isn't retried every pass + assert runner.removed_volumes == ["panopticon-dind-t1", "panopticon-config-t1"]