Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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-<id>`, then `panopticon-config-<id>` — 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
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/panopticon/sessionservice/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
23 changes: 21 additions & 2 deletions src/panopticon/sessionservice/local_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
43 changes: 42 additions & 1 deletion src/panopticon/sessionservice/spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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``.
Expand Down Expand Up @@ -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
Expand Down
67 changes: 67 additions & 0 deletions tests/sessionservice/test_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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']}")

Expand All @@ -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] = []

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"])

Expand Down
19 changes: 19 additions & 0 deletions tests/sessionservice/test_local_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
LocalRunner,
base_image,
config_mount,
config_volume,
dind_volume,
)
from panopticon.sessionservice.runner import Runner

Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading