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
11 changes: 10 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,10 @@ proof. The `dashboard` is opt-in (restarting it drops an attached supervisor bac
rejoin with `panopticon console`).
Spawning needs the base image — `make build`
first. `make dashboard` runs the dashboard once without the attach loop (talks to
`PANOPTICON_SERVICE_URL`).
`PANOPTICON_SERVICE_URL`). `panopticon request-mix [LOG]` tallies the task service's access log
(default `/tmp/panopticon-service.log`) into writes vs long-polls vs full reads, plus the busiest
write endpoints — the first look when the control plane is under load (every write wakes every
long-poller into a full list read).

Lint + format is **Ruff** (`make lint` / `make format`); the ruleset lives under `[tool.ruff]` in
`pyproject.toml` (a curated best-practices `select`, incl. `F401` unused-import — the rule that keeps
Expand Down Expand Up @@ -242,6 +245,12 @@ on every PR (the same commands the Makefile wraps).
`tick`/`run` with fakes (branch watched tasks, skip a provisioned one, isolate a failing one,
poll until a stop condition); integration tests over REST cover the loop (slug-set → branched →
no-op), the unprovisioned-only watch-set, and `run_daemon` provisioning a slugged task.
- `tests/taskservice/test_list_cost.py` — what keeps `GET /tasks` cheap under load: the
`terminal_limit` cap (the newest N finished *trees*; a finished child of an active governor and
every member of a kept finished ensemble always survive), the memoised artifact mark (scanned in
one batch; a finished task's "no" remembered, an active task's re-probed), the batched container
status matching the per-task one, and the restatement writes (same turn/blocked/lifecycle phase)
that neither save nor bump the change feed.
- `tests/test_mcp.py` — the MCP server surface, exercised **in-memory** via the MCP
client (`create_connected_server_and_client_session`) — tools mutate the task, the artifact
resource reads back. No LLM, no HTTP (HTTP hosting is the runnable server, Slice 7a).
Expand Down
7 changes: 7 additions & 0 deletions docs/dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ kept in sync with the `HOTKEYS` keymap and the modal `BINDINGS` in
| `d` | Show the task's detail in a modal |
| `o` | Toggle sort order: created ↔ updated |
| `r` | Refresh from the task service now |
| `D` | Toggle finished tasks: the newest 50 (the default) ↔ all of them |
| `R` | Respawn a down task (releases its claim so the runner re-spawns it) |
| `p` | Open the task's URL in the browser |
| `w` | Open the task's workdir (its per-task clone) in the host's file manager |
Expand All @@ -30,6 +31,12 @@ kept in sync with the `HOTKEYS` keymap and the modal `BINDINGS` in
| `?` | Help — a modal listing every key |
| `q` | Quit |

Finished (COMPLETE/DROPPED) tasks are capped at the **newest 50 trees** by `updated_at` — a
long-lived host accumulates hundreds, and drawing them all on every change was most of the
dashboard's CPU. A finished task under a still-active governor is always shown, as is every member
of a kept finished ensemble. The counter on the right of the footer reads `finished: newest 50` while
the cap is on; `D` lifts it.

`x` (drop) is the only state transition the dashboard drives; every other transition starts a new
agentic turn and is triggered from inside the container.

Expand Down
14 changes: 11 additions & 3 deletions src/panopticon/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,14 @@ def repo_image_layer(self, repo_id: str) -> str:
def list_repos(self) -> list[JsonObj]:
return cast("list[JsonObj]", self._json(self._http.get("/repos")))

def list_tasks(self) -> list[JsonObj]:
return cast("list[JsonObj]", self._json(self._http.get("/tasks")))
def list_tasks(self, *, terminal_limit: int | None = None) -> list[JsonObj]:
"""Every task (summary shape); ``terminal_limit`` keeps only the N most recently updated
finished task trees — see :meth:`list_tasks_versioned`."""
params = {} if terminal_limit is None else {"terminal_limit": terminal_limit}
return cast("list[JsonObj]", self._json(self._http.get("/tasks", params=params)))

def list_tasks_versioned(
self, *, since: int = 0, wait: float | None = None
self, *, since: int = 0, wait: float | None = None, terminal_limit: int | None = None
) -> tuple[list[JsonObj], int]:
"""Block-until-change ``GET /tasks``: return ``(tasks, version)`` where ``version`` is the
store's change-feed cursor (the ``X-Tasks-Version`` header).
Expand All @@ -76,8 +79,13 @@ def list_tasks_versioned(
current snapshot + version. Without ``wait`` it's an immediate snapshot + version. Feed the
returned ``version`` back as ``since`` on the next call to wait for the *next* change —
replacing a ``list_tasks()`` + ``sleep`` poll loop with one event-driven call.

``terminal_limit`` caps the terminal tasks to the N most recently updated trees (every
active task still comes back) — for a viewer that only shows the newest finished work.
"""
params: dict[str, Any] = {"since": since}
if terminal_limit is not None:
params["terminal_limit"] = terminal_limit
if wait is None:
resp = self._http.get("/tasks", params=params)
else:
Expand Down
9 changes: 9 additions & 0 deletions src/panopticon/core/artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import builtins
from abc import ABC, abstractmethod
from base64 import b64decode
from collections.abc import Iterable
from urllib.parse import quote, unquote

MCP_URI_SCHEME = "panopticon"
Expand Down Expand Up @@ -135,6 +136,14 @@ async def has_unhidden_artifacts(self, task_id: str) -> bool:
directory scan that stops at the first hit)."""
return any(not is_hidden(name) for name in await self.list(task_id))

async def tasks_with_unhidden_artifacts(self, task_ids: Iterable[str]) -> set[str]:
"""The subset of ``task_ids`` that :meth:`has_unhidden_artifacts` answers ``True`` for.

The bulk form the task list resolves its marks with, so an adapter can answer a whole
page in one round-trip instead of one per row. The default just asks each id in turn; the
filesystem store overrides it to scan every directory in a single worker-thread hop."""
return {task_id for task_id in task_ids if await self.has_unhidden_artifacts(task_id)}

# -- repo-scoped artifacts ----------------------------------------------------
#
# The same file-backed documents, owned by a **repo** rather than a task: shared by every task
Expand Down
7 changes: 7 additions & 0 deletions src/panopticon/sessionservice/spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,13 @@ def cleanup(self, task: JsonObj) -> None:
container could clean up)."""
if task["state"] not in TERMINAL_LABELS:
return
if task.get("claimed_by") != self._runner_id and not self._exists(
f"{self._tasks_root.rstrip('/')}/{task['id']}"
):
# Nothing left to do: no claim of ours to release and no checkout to remove. Settle
# that with a stat before asking the runner, whose ``is_running`` forks a ``docker ps``
# — once per long-finished task per pass adds up to hundreds of forks on every change.
return
if self._runner_for(task).is_running(task["id"]):
return # container/session still up — wait for it to exit naturally
if task.get("claimed_by") == self._runner_id:
Expand Down
39 changes: 32 additions & 7 deletions src/panopticon/taskservice/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@

from panopticon import __version__
from panopticon.core.artifacts import ArtifactError
from panopticon.core.models import Actor, LifecyclePhase, PushStatus, Repo, Status, Task
from panopticon.core.models import (
Actor,
ContainerStatus,
LifecyclePhase,
PushStatus,
Repo,
Status,
Task,
)
from panopticon.core.store import AlreadyExists, NotFound, StoreError
from panopticon.core.workflow import IllegalTransition, InvalidWorkflow, ResponsibilitiesNotMet
from panopticon.taskservice.service import (
Expand Down Expand Up @@ -428,14 +436,17 @@ def _task_out(task: Task) -> TaskOut:
out.runner_host = service.runner_host(task.claimed_by)
return out

def _task_summary_out(task: Task, *, has_artifacts: bool = False) -> TaskSummaryOut:
def _task_summary_out(
task: Task, *, has_artifacts: bool = False, status: ContainerStatus | None = None
) -> TaskSummaryOut:
"""Serialize a task to the cheap summary shape (no history), with computed status fields.

``has_artifacts`` is passed in rather than read here: it lives in the artifact store,
not on the task, so resolving it needs an await this synchronous serializer can't do."""
not on the task, so resolving it needs an await this synchronous serializer can't do.
``status`` lets a list pass in a status it computed for the whole batch at once."""
out = TaskSummaryOut.model_validate(task)
out.has_artifacts = has_artifacts
out.container_status = service.container_status(task).value
out.container_status = (status or service.container_status(task)).value
lifecycle = service.lifecycle(task.id)
out.lifecycle_detail = lifecycle.detail if lifecycle is not None else None
if task.claimed_by is not None:
Expand Down Expand Up @@ -582,19 +593,33 @@ async def list_tasks(
description="Filter to terminal tasks only (true) or active tasks only (false). "
"Omit to return all tasks.",
),
terminal_limit: int | None = Query(
default=None,
ge=0,
description="Return only the N most recently updated terminal task trees (every "
"active task is still returned, and so is a terminal task under an active governor). "
"Omit for every terminal task.",
),
) -> list[TaskSummaryOut]:
# Every response carries the current version in X-Tasks-Version so a client can echo it
# back as ?since=. With ?wait the request parks until the version moves past ?since (or
# the cap elapses); without it, it's an immediate snapshot — today's behaviour.
if wait is not None:
version = await feed.wait(since=since, timeout=min(wait, MAX_WAIT_SECONDS))
tasks_raw = await service.list_tasks_summary(terminal=terminal)
tasks_raw = await service.list_tasks_summary(
terminal=terminal, terminal_limit=terminal_limit
)
else:
# Read version and snapshot in a single thread call so no event-loop yield can
# interleave a mutation between them — preserving the original atomicity invariant.
version, tasks_raw = await service._tasks_snapshot(terminal=terminal)
version, tasks_raw = await service._tasks_snapshot(
terminal=terminal, terminal_limit=terminal_limit
)
# Both resolved for the whole batch: one artifact-store call, one pass over registrations.
with_artifacts = await service.tasks_with_unhidden_artifacts(tasks_raw)
statuses = service.container_statuses(tasks_raw)
tasks = [
_task_summary_out(t, has_artifacts=await service.has_unhidden_artifacts(t.id))
_task_summary_out(t, has_artifacts=t.id in with_artifacts, status=statuses[t.id])
for t in tasks_raw
]
response.headers[TASKS_VERSION_HEADER] = str(version)
Expand Down
7 changes: 7 additions & 0 deletions src/panopticon/taskservice/artifacts_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import asyncio
import builtins
import os
from collections.abc import Iterable
from pathlib import Path

from panopticon.core.artifacts import (
Expand Down Expand Up @@ -107,6 +108,12 @@ async def has_unhidden_artifacts(self, task_id: str) -> bool:
"""
return await asyncio.to_thread(self._has_artifacts_sync, task_id)

async def tasks_with_unhidden_artifacts(self, task_ids: Iterable[str]) -> set[str]:
"""One worker-thread hop for the whole batch, not one per task: the task list asks this
for every row it serves, and a thread hand-off apiece dominated the scans themselves."""
ids = list(task_ids)
return await asyncio.to_thread(lambda: {t for t in ids if self._has_artifacts_sync(t)})

# -- repo-scoped artifacts ----------------------------------------------------
#
# ``<root>/repos/<repo_id>/<name…>`` — the repo sibling of the ``tasks/`` namespace above, so
Expand Down
Loading
Loading