diff --git a/AGENTS.md b/AGENTS.md index 23c09a4f..802a537a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 @@ -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). diff --git a/docs/dashboard.md b/docs/dashboard.md index 09f842bb..2989d9c0 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -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 | @@ -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. diff --git a/src/panopticon/client.py b/src/panopticon/client.py index 7301d28c..95d4d7e7 100644 --- a/src/panopticon/client.py +++ b/src/panopticon/client.py @@ -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). @@ -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: diff --git a/src/panopticon/core/artifacts.py b/src/panopticon/core/artifacts.py index c3416434..60188d84 100644 --- a/src/panopticon/core/artifacts.py +++ b/src/panopticon/core/artifacts.py @@ -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" @@ -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 diff --git a/src/panopticon/sessionservice/spawner.py b/src/panopticon/sessionservice/spawner.py index de36fc55..274dd707 100644 --- a/src/panopticon/sessionservice/spawner.py +++ b/src/panopticon/sessionservice/spawner.py @@ -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: diff --git a/src/panopticon/taskservice/api.py b/src/panopticon/taskservice/api.py index 958bff90..3b102d47 100644 --- a/src/panopticon/taskservice/api.py +++ b/src/panopticon/taskservice/api.py @@ -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 ( @@ -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: @@ -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) diff --git a/src/panopticon/taskservice/artifacts_fs.py b/src/panopticon/taskservice/artifacts_fs.py index f3ab97b2..e4494a3b 100644 --- a/src/panopticon/taskservice/artifacts_fs.py +++ b/src/panopticon/taskservice/artifacts_fs.py @@ -13,6 +13,7 @@ import asyncio import builtins import os +from collections.abc import Iterable from pathlib import Path from panopticon.core.artifacts import ( @@ -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 ---------------------------------------------------- # # ``/repos//`` — the repo sibling of the ``tasks/`` namespace above, so diff --git a/src/panopticon/taskservice/service.py b/src/panopticon/taskservice/service.py index b3a0ef96..4633d150 100644 --- a/src/panopticon/taskservice/service.py +++ b/src/panopticon/taskservice/service.py @@ -14,12 +14,12 @@ import logging import os import uuid -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, replace from datetime import UTC, datetime from typing import Any -from panopticon.core.artifacts import ArtifactStore, decode_b64_artifact +from panopticon.core.artifacts import ArtifactStore, decode_b64_artifact, is_hidden from panopticon.core.dirs import credential_dir_path, secrets_file_path from panopticon.core.features import require_available_agent_cli from panopticon.core.layers import LayerStore @@ -51,6 +51,47 @@ def _uuid_hex() -> str: return uuid.uuid4().hex +def cap_terminal_tasks(tasks: list[Task], limit: int) -> list[Task]: + """Keep every active task and only the ``limit`` most recently updated terminal ones — + counted as trees: ``limit`` terminal *roots* (no governor in ``tasks``), each with its subtree. + + Terminal tasks pile up forever and are what a task list mostly consists of on a long-lived + host, yet a viewer only ever looks at the newest few. Two kinds of terminal task survive the + cap regardless, so a capped list still draws whole governance trees: + + - one with a non-terminal governor somewhere up its chain — the dashboard files it in the + *active* section under that governor, where its absence would look like a lost child; + - one governed (transitively) by a terminal task the cap kept, so a finished ensemble isn't + shown with only some of its members. + + Order is preserved (the input's), so the cap composes with any caller-side sort.""" + by_id = {t.id: t for t in tasks} + + def has_active_ancestor(task: Task) -> bool: + seen: set[str] = set() + gov = by_id.get(task.governor_task_id or "") + while gov is not None and gov.id not in seen: + if gov.state not in TERMINAL_LABELS: + return True + seen.add(gov.id) + gov = by_id.get(gov.governor_task_id or "") + return False + + terminal = [t for t in tasks if t.state in TERMINAL_LABELS and not has_active_ancestor(t)] + roots = [t for t in terminal if by_id.get(t.governor_task_id or "") is None] + kept = {t.id for t in sorted(roots, key=lambda t: t.updated_at or "", reverse=True)[:limit]} + # Pull each kept root's (terminal) descendants in with it. + grew = True + while grew: + grew = False + for t in terminal: + if t.id not in kept and t.governor_task_id in kept: + kept.add(t.id) + grew = True + capped = {t.id for t in terminal} - kept + return [t for t in tasks if t.id not in capped] + + class UnknownWorkflow(Exception): """Raised when a task references a workflow the service hasn't loaded.""" @@ -141,6 +182,13 @@ def __init__( # events into the same feed (``tasks_version`` adds it; ``_notify_change`` fires listeners). self._ephemeral_epoch = 0 self._change_listeners: list[Callable[[], None]] = [] + # The task list's artifact mark, memoised: every ``GET /tasks`` asks it of every row, and + # a directory scan per row per long-poll was most of the endpoint's cost. Coherent because + # this service is the artifact store's only writer (:meth:`put_artifact` sets ``True``) and + # nothing deletes an artifact. A ``False`` is only kept for a terminal task — nothing writes + # to one, whereas an active task's agent may (and an operator may drop a file into an active + # task's folder by hand), so those few rows are re-probed, in one batch, each time. + self._has_artifacts: dict[str, bool] = {} async def init(self) -> None: """Bootstrap the store's schema (idempotent). Called by the task service's lifespan.""" @@ -437,14 +485,21 @@ async def get_task(self, task_id: str) -> Task: async def list_tasks(self) -> list[Task]: return await self._store.list_tasks() - async def list_tasks_summary(self, *, terminal: bool | None = None) -> list[Task]: - """Return tasks without history. Optionally filter to terminal-only or active-only.""" + async def list_tasks_summary( + self, *, terminal: bool | None = None, terminal_limit: int | None = None + ) -> list[Task]: + """Return tasks without history. Optionally filter to terminal-only or active-only, and + cap the terminal tasks with ``terminal_limit`` (see :func:`cap_terminal_tasks`).""" tasks = await self._store.list_tasks_summary() - if terminal is None: - return tasks - return [t for t in tasks if (t.state in TERMINAL_LABELS) == terminal] - - async def _tasks_snapshot(self, *, terminal: bool | None = None) -> tuple[int, list[Task]]: + if terminal_limit is not None: # before the filter: the cap reads governors' states + tasks = cap_terminal_tasks(tasks, terminal_limit) + if terminal is not None: + tasks = [t for t in tasks if (t.state in TERMINAL_LABELS) == terminal] + return tasks + + async def _tasks_snapshot( + self, *, terminal: bool | None = None, terminal_limit: int | None = None + ) -> tuple[int, list[Task]]: """Read the version before the query so the reported version is a lower bound. If a mutation commits during the ``await``, the version we already captured is from before @@ -452,7 +507,7 @@ async def _tasks_snapshot(self, *, terminal: bool | None = None) -> tuple[int, l waiting for ``MAX_WAIT_SECONDS``. """ version = self.tasks_version() - tasks = await self.list_tasks_summary(terminal=terminal) + tasks = await self.list_tasks_summary(terminal=terminal, terminal_limit=terminal_limit) return version, tasks def tasks_version(self) -> int: @@ -624,6 +679,11 @@ async def set_turn(self, task_id: str, turn: Actor) -> Task: untouched, so a deliberate block survives turn flips. """ task = await self.get_task(task_id) + if task.turn == turn: + # The turn hooks fire on every prompt and every stop, so most calls restate the + # current turn. Saving one would bump the change feed and wake every long-poller to + # re-read the task list for nothing — the commonest no-op write the service sees. + return task task.turn = turn await self._save_task(task) return task @@ -631,6 +691,8 @@ async def set_turn(self, task_id: str, turn: Actor) -> Task: async def set_blocked(self, task_id: str, blocked: bool) -> Task: """Set/clear the task's deliberate ``blocked`` marker (orthogonal to the turn).""" task = await self.get_task(task_id) + if task.blocked == blocked: + return task # a restatement: no save, so no change-feed wake (as in set_turn) task.blocked = blocked await self._save_task(task) _log.debug("task %s: blocked=%s", task_id, blocked) @@ -827,6 +889,8 @@ async def record_push(self, task_id: str, *, status: PushStatus, detail: str | N async def put_artifact(self, task_id: str, name: str, content: bytes) -> None: await self.get_task(task_id) # ensure the task exists await self._artifacts.put(task_id, name, content) + if not is_hidden(name): + self._has_artifacts[task_id] = True # Artifacts live outside the store, so writing one bumps no version of its own — but the # task list reports whether a task *has* one, so a parked long-poll has to wake or the # first plan.md would go unnoticed until some unrelated mutation. Same treatment as the @@ -849,7 +913,24 @@ async def has_unhidden_artifacts(self, task_id: str) -> bool: tasks the caller has already read, once per row, and a task with no artifacts and a task that doesn't exist both answer ``False``. Paying for a store read per row to tell those apart would buy nothing.""" - return await self._artifacts.has_unhidden_artifacts(task_id) + return task_id in await self.tasks_with_unhidden_artifacts([task_id]) + + async def tasks_with_unhidden_artifacts(self, tasks: Iterable[Task | str]) -> set[str]: + """The ids among ``tasks`` that carry an artifact mark — memoised (see ``__init__``), with + every miss resolved in one batched artifact-store call. Accepts bare ids too; an id with no + task to say whether it's terminal is treated as active (its ``False`` isn't kept).""" + terminal: dict[str, bool] = {} + for t in tasks: + if isinstance(t, str): + terminal[t] = False + else: + terminal[t.id] = t.state in TERMINAL_LABELS + misses = [tid for tid in terminal if tid not in self._has_artifacts] + found = await self._artifacts.tasks_with_unhidden_artifacts(misses) if misses else set() + for tid in misses: + if tid in found or terminal[tid]: + self._has_artifacts[tid] = tid in found + return found | {tid for tid in terminal if self._has_artifacts.get(tid)} # -- repo artifacts ----------------------------------------------------------- # @@ -936,11 +1017,20 @@ async def report_lifecycle( ) -> ContainerLifecycle: """Record the runner's latest spawn phase for a task (an upsert; the newest wins).""" await self.get_task(task_id) # ensure the task exists + previous = self._lifecycles.get(task_id) lifecycle = ContainerLifecycle( task_id=task_id, runner_id=runner_id, phase=phase, detail=detail, at=self._clock() ) self._lifecycles[task_id] = lifecycle - self._notify_change() + # A runner re-reporting the phase it already holds (a heal/reconcile pass restating + # ``failed``, say) changes nothing the task list renders — record the fresher ``at`` but + # don't wake every long-poller over it. + if previous is None or (previous.phase, previous.detail, previous.runner_id) != ( + phase, + detail, + runner_id, + ): + self._notify_change() _log.debug("task %s: lifecycle phase=%s", task_id, phase.value) return lifecycle @@ -957,14 +1047,25 @@ def lifecycle(self, task_id: str) -> ContainerLifecycle | None: def container_status(self, task: Task) -> ContainerStatus: """The task's composed container-lifecycle status (the single string the dashboard shows): fold the reported phase together with registration presence + runner liveness.""" - lifecycle = self._lifecycles.get(task.id) - return compose_container_status( - terminal=task.state in TERMINAL_LABELS, - claimed=task.claimed_by is not None, - registered=bool(self.registrations(task.id)), - runner_live=task.claimed_by in self.live_runners(), - phase=lifecycle.phase if lifecycle is not None else None, - ) + return self.container_statuses([task])[task.id] + + def container_statuses(self, tasks: Iterable[Task]) -> dict[str, ContainerStatus]: + """:meth:`container_status` for many tasks at once, keyed by id. The registered-task and + live-runner sets are built once for the batch rather than rescanned per task, so a task + list costs O(tasks + registrations) instead of their product.""" + registered = {r.task_id for r in self._registrations.values()} + live = self.live_runners() + statuses: dict[str, ContainerStatus] = {} + for task in tasks: + lifecycle = self._lifecycles.get(task.id) + statuses[task.id] = compose_container_status( + terminal=task.state in TERMINAL_LABELS, + claimed=task.claimed_by is not None, + registered=task.id in registered, + runner_live=task.claimed_by in live, + phase=lifecycle.phase if lifecycle is not None else None, + ) + return statuses # -- host (runner) liveness + reclaim ------------------------------------------ # diff --git a/src/panopticon/terminal/__main__.py b/src/panopticon/terminal/__main__.py index 4f09a807..17ded652 100644 --- a/src/panopticon/terminal/__main__.py +++ b/src/panopticon/terminal/__main__.py @@ -90,6 +90,12 @@ def main( sub.add_parser( "host", help="start task service + runner in background tmux sessions (no console)" ) + mix = sub.add_parser( + "request-mix", help="tally the task service's log: writes vs long-polls vs full reads" + ) + mix.add_argument( + "log", nargs="?", help="the service log (default: /tmp/panopticon-service.log)" + ) start = sub.add_parser("start", help="start everything and open the dashboard supervisor") start.add_argument("task", nargs="?", help="task id or slug to join (attach to) on startup") sub.add_parser("stop", help="stop task containers and the panopticon tmux server") @@ -135,6 +141,10 @@ def main( from panopticon.terminal import doctor return doctor.report(doctor.run_checks()) + elif args.command == "request-mix": + from panopticon.terminal import request_mix + + return request_mix.report(args.log or request_mix.DEFAULT_LOG) elif args.command == "host": _run_migrate() start_sessions() diff --git a/src/panopticon/terminal/dashboard.py b/src/panopticon/terminal/dashboard.py index af944ed1..fb94097b 100644 --- a/src/panopticon/terminal/dashboard.py +++ b/src/panopticon/terminal/dashboard.py @@ -1905,6 +1905,11 @@ def binding(self) -> Binding: return Binding(self.key, self.action, self.label, show=self.show, key_display=self.display) +#: How many finished (COMPLETE/DROPPED) task trees the dashboard fetches and draws by default — +#: the newest by ``updated_at``. A long-lived host accumulates hundreds; drawing every one on every +#: change-feed tick was most of the dashboard's CPU. `D` lifts the cap. +TERMINAL_LIMIT = 50 + HOTKEYS: tuple[Hotkey, ...] = ( Hotkey("t", "attach", "Attach", "Attach to the task's container tmux session"), Hotkey("n", "new_task", "New task", "New task (pick repo → workflow → describe)"), @@ -1913,6 +1918,13 @@ def binding(self) -> Binding: Hotkey("d", "toggle_detail", "Detail", "Show the task detail (modal)"), Hotkey("o", "toggle_sort", "Sort order", "Toggle sort: created ↔ updated", show=False), Hotkey("r", "refresh", "Refresh", "Refresh from the task service now", show=False), + Hotkey( + "D", + "toggle_all_finished", + "All finished", + f"Toggle finished tasks: the newest {TERMINAL_LIMIT} ↔ all of them", + show=False, + ), Hotkey("R", "respawn", "Respawn", "Respawn a down task (release its claim)", show=False), Hotkey("p", "open_url", "Open URL", "Open the task's URL in the browser", show=False), Hotkey( @@ -2043,6 +2055,27 @@ def action_close(self) -> None: self.dismiss(None) +def _same_rows( + a: list[tuple[str, tuple[Text | str, ...]]], b: list[tuple[str, tuple[Text | str, ...]]] +) -> bool: + """Whether two task-table row lists (key + cells) render identically.""" + return len(a) == len(b) and all( + key_a == key_b + and len(cells_a) == len(cells_b) + and all(_same_cell(x, y) for x, y in zip(cells_a, cells_b, strict=True)) + for (key_a, cells_a), (key_b, cells_b) in zip(a, b, strict=True) + ) + + +def _same_cell(a: Text | str, b: Text | str) -> bool: + """Whether two task-table cells render identically. ``Text.__eq__`` alone won't do: it compares + the plain text and spans but not the base style, so a row dimmed by a snooze would compare + equal to its undimmed self and never be repainted.""" + if isinstance(a, Text) and isinstance(b, Text): + return a.plain == b.plain and a.style == b.style and a.spans == b.spans + return type(a) is type(b) and a == b + + def _setup_task_columns(table: DataTable[Any], *, multi_runner: bool) -> None: """Add the task table's columns. Includes a "runner" column when tasks span multiple hosts. @@ -2100,6 +2133,14 @@ def __init__( ) self._version = 0 # the change-feed cursor (X-Tasks-Version) the worker long-polls against self._refresh_failing = False # the last refresh's REST read failed (warn once per outage) + # How many finished task trees to fetch; None → all of them (`D` toggles). + self._terminal_limit: int | None = TERMINAL_LIMIT + # The last task list fetched, re-rendered when only the clock moved (a snooze ticking); + # None until a read has succeeded. + self._snapshot: list[JsonObj] | None = None + # The rows (key + cells) the table currently shows, so a render that would draw the same + # rows skips the table entirely. + self._rendered: list[tuple[str, tuple[Text | str, ...]]] = [] self._tasks: dict[str, JsonObj] = {} self._repo_names: dict[str, str] = {} # repo id → name; populated by _load_repo_names self._repo_clis: dict[ @@ -2169,21 +2210,27 @@ def _watch_feed(self) -> None: # first poll should wait for the *next* change rather than re-firing on the current version. # service not up yet — fall through; the loop retries with back-off with contextlib.suppress(Exception): - _, self._version = self._client.list_tasks_versioned() + _, self._version = self._client.list_tasks_versioned( + terminal_limit=self._terminal_limit + ) while not worker.is_cancelled: try: - _, version = self._client.list_tasks_versioned( - since=self._version, wait=self._refresh_interval + tasks, version = self._client.list_tasks_versioned( + since=self._version, + wait=self._refresh_interval, + terminal_limit=self._terminal_limit, ) except Exception: # transient feed error (service restart / blip) — back off, retry time.sleep(min(self._refresh_interval or 1.0, 1.0)) continue if worker.is_cancelled: return - if version != self._version: # a task changed past our cursor → rebuild the table + if version != self._version: # a task changed past our cursor → redraw from it previous, self._version = self._version, version try: - refreshed = self.call_from_thread(self._refresh) + # The long-poll already carries the fresh snapshot: draw it rather than + # fetching the whole list a second time. + refreshed = self.call_from_thread(self._refresh, tasks) except RuntimeError: # app shut down between the cancel check and the dispatch return if not refreshed: # the rebuild's read failed — rewind so the next poll retries it @@ -2205,16 +2252,24 @@ def _artifact_tmpdir(self) -> str: return self._artifact_tmp.name def action_refresh(self) -> None: + """Fetch the task list now and draw it (`r`, the first paint, and after a local action).""" self._refresh() - def _refresh(self) -> bool: - """Rebuild the table from the task service; False if its REST read failed. + def action_toggle_all_finished(self) -> None: + """Lift (or restore) the cap on how many finished tasks are fetched and drawn.""" + self._terminal_limit = None if self._terminal_limit is not None else TERMINAL_LIMIT + self.action_refresh() + + def _refresh(self, tasks: list[JsonObj] | None = None) -> bool: + """Draw ``tasks`` — or, when not given, a fresh fetch of the task list — and return False + if a REST read failed. Every read happens before the table is touched, so a failure (a 5xx, a timeout, the service down) leaves the last-drawn table in place rather than raising — an exception here would exit the app, whether it ran on the UI thread or in the feed worker.""" try: - tasks = self._client.list_tasks() + if tasks is None: + tasks = self._client.list_tasks(terminal_limit=self._terminal_limit) runners = self._client.live_runners() except httpx.HTTPError: if not self._refresh_failing: # one notice per outage, not one per retry @@ -2226,14 +2281,26 @@ def _refresh(self) -> bool: ) return False self._refresh_failing = False + self._render(tasks, runners) + return True + + def _render(self, tasks: list[JsonObj], runners: list[JsonObj]) -> None: + """Draw ``tasks`` (a ``GET /tasks`` snapshot) into the table, touching as little as it can. + + The rows are computed first and compared with what's on screen: when they're identical (a + change to something the table doesn't show — most change-feed ticks) the table is left + alone, since clearing and re-adding every row on every tick was the dashboard's main CPU + cost. Anything else rebuilds; patching only the changed cells was measured to cost the same + as a rebuild, the table's relayout dominating either way.""" + self._snapshot = tasks table = self.query_one("#tasks", DataTable) selected = self._current # keep the operator's highlight across the rebuild (feed refresh) display_now = self._now() # one clock read per repaint drives every snooze label/dimming - table.clear() ordered = sorted(tasks, key=_make_sort_key(self._sort_by_updated, display_now)) new_multi_runner = len({r.get("host") for r in runners if r.get("host")}) > 1 if new_multi_runner != self._multi_runner: - table.clear(columns=True) # rows already gone; also clears columns for rebuild + table.clear(columns=True) # drop the columns too — they're rebuilt with the runner one + self._rendered = [] self._multi_runner = new_multi_runner _setup_task_columns(table, multi_runner=self._multi_runner) # An actively snoozed task is muted, so it leaves both halves of the counter — the @@ -2246,8 +2313,13 @@ def _refresh(self) -> bool: ] agent_on = sum(1 for t in active if t.get("turn") == "agent") sort_label = "sort: updated" if self._sort_by_updated else "sort: created" + finished_label = ( + f" · finished: newest {self._terminal_limit} (D: all)" + if self._terminal_limit is not None + else "" + ) self.query_one(_StatusFooter).set_counter( - f"active agents {agent_on}/{len(active)} · {sort_label}" + f"active agents {agent_on}/{len(active)} · {sort_label}{finished_label}" ) # Inject repo_name so _matches can search on it without a separate lookup per task. # Also resolve the task's effective agent CLI (task override → repo default) for the detail view. @@ -2300,12 +2372,12 @@ def _refresh(self) -> bool: # Build the task index (real tasks only; ensemble placeholders are synthetic). self._tasks = {t["id"]: t for t, _ in visible if not t.get("_ensemble")} - def _add_row(task: JsonObj, prefix: str) -> None: + def _row(task: JsonObj, prefix: str) -> tuple[str, tuple[Text | str, ...]]: if task.get("_ensemble"): gov_id = task["_governor_id"] slug_cell = Text(f"{prefix}...", style="dim") runner_blank = (Text(""),) if self._multi_runner else () - table.add_row( + return f"{_ENSEMBLE_KEY_PREFIX}{gov_id}", ( Text(""), Text(""), Text(""), @@ -2313,7 +2385,6 @@ def _add_row(task: JsonObj, prefix: str) -> None: Text(""), Text(""), # marks: a placeholder stands for hidden rows, so it carries none slug_cell, - key=f"{_ENSEMBLE_KEY_PREFIX}{gov_id}", ) else: state_cell: Text | str = task["state"] @@ -2345,7 +2416,7 @@ def _add_row(task: JsonObj, prefix: str) -> None: marks_cell = _dim(marks_cell) slug_cell_real = _dim(slug_cell_real) runner_extra = (runner_cell,) if runner_cell is not None else () - table.add_row( + return task["id"], ( state_cell, turn_cell, status_cell, @@ -2353,19 +2424,19 @@ def _add_row(task: JsonObj, prefix: str) -> None: repo_cell, marks_cell, slug_cell_real, - key=task["id"], ) - for task, prefix in active_visible: - _add_row(task, prefix) - for task, prefix in terminal_visible: - _add_row(task, prefix) + rows = [_row(task, prefix) for task, prefix in visible] + if not _same_rows(rows, self._rendered): + table.clear() + for key, cells in rows: + table.add_row(*cells, key=key) + self._rendered = rows target = selected if selected in self._tasks else next(iter(self._tasks), None) - if target is not None: + if target is not None and table.cursor_row != table.get_row_index(target): table.move_cursor(row=table.get_row_index(target)) self._current = target # `d` opens the detail modal for whatever's highlighted self._schedule_snooze_refresh(display_now) - return True def _schedule_snooze_refresh(self, now: datetime) -> None: """(Re)arm a one-shot timer for the soonest finite-snooze display change. @@ -2387,7 +2458,7 @@ def _schedule_snooze_refresh(self, now: datetime) -> None: def _refresh_snooze_display(self) -> None: """Repaint when a finite snooze's label is due to change (fired by the one-shot timer).""" self._snooze_timer = None - self.action_refresh() + self._refresh(self._snapshot) # a clock-only change: redraw the last snapshot, no fetch def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None: key = event.row_key.value diff --git a/src/panopticon/terminal/request_mix.py b/src/panopticon/terminal/request_mix.py new file mode 100644 index 00000000..cb87b946 --- /dev/null +++ b/src/panopticon/terminal/request_mix.py @@ -0,0 +1,103 @@ +"""``panopticon request-mix`` — what the task service spends its requests on, read from its log. + +The control plane's load is shaped by three kinds of request: **writes** (each one bumps the change +feed and wakes every long-poller), **long-polls** (``GET /tasks?wait=…`` — parked, then a full list +read when woken) and **full reads** (an immediate ``GET /tasks``). Their ratio says where a load +problem comes from: many writes per minute fan out into that many list reads per long-poller. This +tallies them from the uvicorn access lines in the service's log (``make start`` writes it to +``/tmp/panopticon-service.log``), plus the busiest write endpoints with ids folded out, so the +chattiest writer stands out. +""" + +from __future__ import annotations + +import re +from collections import Counter +from collections.abc import Iterable +from dataclasses import dataclass, field +from urllib.parse import parse_qs, urlsplit + +DEFAULT_LOG = "/tmp/panopticon-service.log" + +#: A uvicorn access line: ``… "PUT /tasks//turn HTTP/1.1" 200 …``. Matched loosely (anywhere in +#: the line) so it reads both uvicorn's own format and one re-prefixed by ``logging.basicConfig``. +_ACCESS = re.compile(r'"(?P[A-Z]+) (?P\S+) HTTP/[\d.]+" (?P\d{3})') + +#: Path segments that are ids, not routes — folded to ``{id}`` so ``PUT /tasks/{id}/turn`` tallies +#: as one endpoint however many tasks call it. Task/registration ids are 32-hex uuids. +_ID_SEGMENT = re.compile(r"^[0-9a-f]{32}$") + +_WRITE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) + + +@dataclass +class RequestMix: + writes: int = 0 + long_polls: int = 0 + full_reads: int = 0 + other: int = 0 + errors: int = 0 # 5xx responses, any kind + write_endpoints: Counter[str] = field(default_factory=Counter) + + @property + def total(self) -> int: + return self.writes + self.long_polls + self.full_reads + self.other + + +def _route(path: str) -> str: + return "/".join("{id}" if _ID_SEGMENT.match(seg) else seg for seg in path.split("/")) + + +def tally(lines: Iterable[str]) -> RequestMix: + """Classify every access line in ``lines`` (non-access lines are skipped).""" + mix = RequestMix() + for line in lines: + match = _ACCESS.search(line) + if match is None: + continue + method, target = match["method"], match["target"] + url = urlsplit(target) + if match["status"].startswith("5"): + mix.errors += 1 + if method in _WRITE_METHODS: + mix.writes += 1 + mix.write_endpoints[f"{method} {_route(url.path)}"] += 1 + elif method == "GET" and url.path == "/tasks": + if "wait" in parse_qs(url.query): + mix.long_polls += 1 + else: + mix.full_reads += 1 + else: + mix.other += 1 + return mix + + +def render(mix: RequestMix, *, top: int = 10) -> str: + """The tally as a short plain-text report.""" + + def share(n: int) -> str: + return f"{100 * n / mix.total:5.1f}%" if mix.total else " –" + + lines = [ + f"requests {mix.total:>8}", + f" writes {mix.writes:>8} {share(mix.writes)}", + f" long-polls {mix.long_polls:>8} {share(mix.long_polls)}", + f" full reads {mix.full_reads:>8} {share(mix.full_reads)}", + f" other {mix.other:>8} {share(mix.other)}", + f"5xx {mix.errors:>8}", + ] + if mix.write_endpoints: + lines.append("busiest writes:") + lines += [f" {n:>8} {route}" for route, n in mix.write_endpoints.most_common(top)] + return "\n".join(lines) + + +def report(path: str) -> int: + """Print the request mix of the log at ``path``; 1 if it can't be read.""" + try: + with open(path, encoding="utf-8", errors="replace") as log: + print(render(tally(log))) + except OSError as exc: + print(f"panopticon request-mix: {exc}") + return 1 + return 0 diff --git a/tests/sessionservice/test_spawner.py b/tests/sessionservice/test_spawner.py index 3447d33a..06f788ea 100644 --- a/tests/sessionservice/test_spawner.py +++ b/tests/sessionservice/test_spawner.py @@ -1381,6 +1381,35 @@ def test_cleanup_waits_when_container_still_running() -> None: assert removed == [] # container still up — leave workspace alone +class _CountingRunner(_FakeRunner): + def __init__(self, *, running: bool) -> None: + super().__init__(running=running) + self.probes = 0 + + def is_running(self, task_id: str) -> bool: + self.probes += 1 + return super().is_running(task_id) + + +def test_cleanup_of_a_cleaned_up_task_asks_no_runner() -> None: + # A long-finished task with no checkout left and no claim of ours has nothing to clean up, so + # cleanup settles it with a stat — never the runner's ``is_running``, which forks a ``docker ps`` + # (hundreds of finished tasks × every host pass used to mean hundreds of forks per change). + runner = _CountingRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.cleanup({"id": "t1", "state": "COMPLETE", "claimed_by": None}) + spawner.cleanup({"id": "t2", "state": "DROPPED", "claimed_by": "another-host"}) + assert runner.probes == 0 + + +def test_cleanup_still_probes_a_task_this_host_claims() -> None: + # A claim of ours still needs releasing once the container is gone, checkout or not. + runner = _CountingRunner(running=False) + spawner = _cleanup_spawner(runner, workspace_exists=False) + spawner.cleanup({"id": "t1", "state": "COMPLETE", "claimed_by": "host-1"}) + assert runner.probes == 1 + + def test_cleanup_is_a_no_op_for_non_terminal_task() -> None: removed: list[str] = [] runner = _FakeRunner(running=False) diff --git a/tests/taskservice/test_client.py b/tests/taskservice/test_client.py index cefedf98..ae8a2546 100644 --- a/tests/taskservice/test_client.py +++ b/tests/taskservice/test_client.py @@ -55,6 +55,18 @@ def test_list_tasks_versioned_returns_snapshot_and_cursor(client: TaskServiceCli assert [t["id"] for t in tasks] == [task["id"]] and again == bumped +def test_list_calls_pass_the_terminal_limit(client: TaskServiceClient) -> None: + older = client.create_task("r1", "spike")["id"] + client.request_transition(older, "COMPLETE", trigger="finish") + newer = client.create_task("r1", "spike")["id"] + client.request_transition(newer, "COMPLETE", trigger="finish") + + assert {t["id"] for t in client.list_tasks()} == {older, newer} + assert [t["id"] for t in client.list_tasks(terminal_limit=1)] == [newer] + tasks, _ = client.list_tasks_versioned(terminal_limit=1) + assert [t["id"] for t in tasks] == [newer] + + def test_drives_slug_and_transition(client: TaskServiceClient) -> None: task_id = client.create_task("r1", "spike")["id"] client.set_slug(task_id, "fix-widget") diff --git a/tests/taskservice/test_list_cost.py b/tests/taskservice/test_list_cost.py new file mode 100644 index 00000000..4541a647 --- /dev/null +++ b/tests/taskservice/test_list_cost.py @@ -0,0 +1,227 @@ +"""What keeps ``GET /tasks`` cheap under load: the terminal-task cap, the memoised artifact mark, +the batched container status, and the restatement writes that no longer wake the change feed. + +A host that has run for weeks holds hundreds of finished tasks, and every long-poller (the host +daemon, the dashboard) re-reads the list on every change — so each of these is multiplied by the +list size *and* by the write rate. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from pathlib import Path + +import httpx + +from panopticon.core.models import Actor, LifecyclePhase, Repo +from panopticon.taskservice.api import create_app +from panopticon.taskservice.artifacts_fs import FilesystemArtifactStore +from panopticon.taskservice.service import TaskService +from panopticon.taskservice.store_sqlalchemy import SqlAlchemyStore +from panopticon.workflows import Spike + + +class _CountingArtifacts(FilesystemArtifactStore): + """The filesystem store, counting how many task ids reach the batched presence scan.""" + + def __init__(self, root: Path) -> None: + super().__init__(root) + self.scanned: list[str] = [] + + async def tasks_with_unhidden_artifacts(self, task_ids: Iterable[str]) -> set[str]: + ids = list(task_ids) + self.scanned.extend(ids) + return await super().tasks_with_unhidden_artifacts(ids) + + +async def _service(tmp_path: Path) -> tuple[TaskService, _CountingArtifacts]: + # A zero-padded clock so ``updated_at`` sorts the way time does (``t10`` would sort before + # ``t9``) — the terminal cap keeps the *newest* trees. + times: Iterator[str] = iter(f"t{i:05d}" for i in range(1, 100_000)) + artifacts = _CountingArtifacts(tmp_path) + svc = TaskService(SqlAlchemyStore(), {"spike": Spike()}, artifacts, clock=lambda: next(times)) + await svc.init() + await svc.create_repo(Repo(id="r1", name="acme/widgets", git_url="https://x/r1.git")) + return svc, artifacts + + +async def _finished(svc: TaskService, *, governor: str | None = None) -> str: + task = await svc.create_task("r1", "spike", governor_task_id=governor) + await svc.apply_operation(task.id, "drop") + return task.id + + +# -- the terminal cap ------------------------------------------------------------------------ + + +async def test_terminal_limit_keeps_every_active_task_and_the_newest_finished( + tmp_path: Path, +) -> None: + svc, _ = await _service(tmp_path) + old, mid, new = [await _finished(svc) for _ in range(3)] + active = (await svc.create_task("r1", "spike")).id + + ids = {t.id for t in await svc.list_tasks_summary(terminal_limit=2)} + assert ids == {active, mid, new} # the oldest finished task is the one capped away + assert old not in ids + assert len(await svc.list_tasks_summary()) == 4 # uncapped by default + + +async def test_terminal_limit_never_orphans_a_child_of_an_active_governor(tmp_path: Path) -> None: + # The dashboard files a finished child of an active governor in the *active* section, under + # it — however old the child is, the cap must not take it away. + svc, _ = await _service(tmp_path) + governor = (await svc.create_task("r1", "spike")).id + stale_child = await _finished(svc, governor=governor) + await _finished(svc) # a newer, unrelated finished task fills the cap + + ids = {t.id for t in await svc.list_tasks_summary(terminal_limit=1)} + assert stale_child in ids + + +async def test_terminal_limit_counts_finished_trees_not_rows(tmp_path: Path) -> None: + # A kept finished governor brings its whole finished ensemble with it, and the ensemble counts + # once against the cap — a capped list never shows a tree with members missing. + svc, _ = await _service(tmp_path) + loner = await _finished(svc) + governor = (await svc.create_task("r1", "spike")).id + children = [await _finished(svc, governor=governor) for _ in range(3)] + await svc.apply_operation(governor, "drop") # the newest root + + ids = {t.id for t in await svc.list_tasks_summary(terminal_limit=1)} + assert ids == {governor, *children} + assert loner not in ids + + +async def test_terminal_limit_composes_with_the_terminal_filter(tmp_path: Path) -> None: + svc, _ = await _service(tmp_path) + governor = (await svc.create_task("r1", "spike")).id + child = await _finished(svc, governor=governor) + newest = await _finished(svc) + + # The cap reads governors' states before the filter drops them, so the child of an active + # governor still survives a terminal-only, capped read. + ids = {t.id for t in await svc.list_tasks_summary(terminal=True, terminal_limit=1)} + assert ids == {child, newest} + + +async def test_api_takes_a_terminal_limit(tmp_path: Path) -> None: + svc, _ = await _service(tmp_path) + await _finished(svc) + newest = await _finished(svc) + active = (await svc.create_task("r1", "spike")).id + transport = httpx.ASGITransport(app=create_app(svc)) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as http: + capped = await http.get("/tasks", params={"terminal_limit": 1}) + assert {t["id"] for t in capped.json()} == {active, newest} + assert len((await http.get("/tasks")).json()) == 3 + assert (await http.get("/tasks", params={"terminal_limit": -1})).status_code == 422 + + +# -- the artifact mark --------------------------------------------------------------------- + + +async def test_artifact_marks_are_scanned_in_one_batch_and_then_remembered(tmp_path: Path) -> None: + svc, artifacts = await _service(tmp_path) + with_plan = await _finished(svc) + bare = await _finished(svc) + (tmp_path / "tasks" / with_plan).mkdir(parents=True) + (tmp_path / "tasks" / with_plan / "plan.md").write_text("# Plan") + tasks = await svc.list_tasks_summary() + + assert await svc.tasks_with_unhidden_artifacts(tasks) == {with_plan} + assert sorted(artifacts.scanned) == sorted([with_plan, bare]) # one batched scan of both + + artifacts.scanned.clear() + assert await svc.tasks_with_unhidden_artifacts(tasks) == {with_plan} + assert artifacts.scanned == [] # finished tasks: both answers are remembered + + +async def test_an_active_task_without_artifacts_is_re_probed(tmp_path: Path) -> None: + # An active task's agent may write an artifact at any moment, and an operator may drop one into + # its folder by hand (outside the service) — so its "no" isn't remembered, only its "yes". + svc, artifacts = await _service(tmp_path) + task = await svc.create_task("r1", "spike") + assert await svc.tasks_with_unhidden_artifacts([task]) == set() + + (tmp_path / "tasks" / task.id).mkdir(parents=True) + (tmp_path / "tasks" / task.id / "notes.md").write_text("by hand") + assert await svc.tasks_with_unhidden_artifacts([task]) == {task.id} + + artifacts.scanned.clear() + assert await svc.tasks_with_unhidden_artifacts([task]) == {task.id} + assert artifacts.scanned == [] # a "yes" is remembered (artifacts are never deleted) + + +async def test_put_artifact_updates_the_remembered_mark(tmp_path: Path) -> None: + svc, _ = await _service(tmp_path) + task_id = await _finished(svc) + assert not await svc.has_unhidden_artifacts(task_id) # remembered as "no" (finished) + + await svc.put_artifact(task_id, ".babysit-ci-state.json", b"{}") + assert not await svc.has_unhidden_artifacts(task_id) # a hidden artifact doesn't count + await svc.put_artifact(task_id, "plan.md", b"# Plan") + assert await svc.has_unhidden_artifacts(task_id) + + +# -- the batched container status ---------------------------------------------------------- + + +async def test_container_statuses_match_the_per_task_answer(tmp_path: Path) -> None: + svc, _ = await _service(tmp_path) + await svc.create_task("r1", "spike") # unclaimed → queued + live = await svc.create_task("r1", "spike") + building = await svc.create_task("r1", "spike") + lost = await svc.create_task("r1", "spike") + finished = await svc.create_task("r1", "spike") + await svc.apply_operation(finished.id, "drop") + await svc.register_runner("host-1") + for task in (live, building): + await svc.claim(task.id, "host-1") + await svc.claim(lost.id, "host-gone") # a runner that isn't connected + await svc.register(live.id, "c1", "host-1") + await svc.report_lifecycle(building.id, "host-1", LifecyclePhase.BUILDING) + + tasks = await svc.list_tasks_summary() + batch = svc.container_statuses(tasks) + assert batch == {t.id: svc.container_status(t) for t in tasks} + assert len(set(batch.values())) == 5 # queued/live/building/disconnected/–: all distinct + + +# -- restatements don't wake the feed ------------------------------------------------------ + + +async def test_restating_the_turn_or_blocked_neither_saves_nor_bumps(tmp_path: Path) -> None: + # The turn hooks fire on every prompt and every stop, so most calls restate the current turn; + # each used to bump the change feed and make every long-poller re-read the whole list. + svc, _ = await _service(tmp_path) + task = await svc.create_task("r1", "spike") + await svc.set_turn(task.id, Actor.AGENT) + stamped = (await svc.get_task(task.id)).updated_at + version = svc.tasks_version() + + await svc.set_turn(task.id, Actor.AGENT) + await svc.set_blocked(task.id, False) + assert svc.tasks_version() == version + assert (await svc.get_task(task.id)).updated_at == stamped # no save at all + + await svc.set_turn(task.id, Actor.USER) # a real flip still saves and wakes the feed + assert svc.tasks_version() > version + version = svc.tasks_version() + await svc.set_blocked(task.id, True) + assert svc.tasks_version() > version + + +async def test_re_reporting_the_same_lifecycle_phase_does_not_bump(tmp_path: Path) -> None: + svc, _ = await _service(tmp_path) + task = await svc.create_task("r1", "spike") + await svc.report_lifecycle(task.id, "host-1", LifecyclePhase.FAILED, "exit 1") + version = svc.tasks_version() + + await svc.report_lifecycle(task.id, "host-1", LifecyclePhase.FAILED, "exit 1") + assert svc.tasks_version() == version + lifecycle = svc.lifecycle(task.id) + assert lifecycle is not None and lifecycle.detail == "exit 1" # still recorded (fresher ``at``) + + await svc.report_lifecycle(task.id, "host-1", LifecyclePhase.FAILED, "OOM killed") + assert svc.tasks_version() > version # a new detail is a change the dashboard shows diff --git a/tests/terminal/test_dashboard.py b/tests/terminal/test_dashboard.py index d25e4544..fbad4626 100644 --- a/tests/terminal/test_dashboard.py +++ b/tests/terminal/test_dashboard.py @@ -14,6 +14,7 @@ import httpx import pytest +from rich.text import Text from textual.app import App from textual.css.query import NoMatches from textual.widgets import Checkbox, DataTable, Input, OptionList, Select, Static @@ -27,6 +28,7 @@ _LINK_MARK, _MARKS_LABEL, _SNOOZE_DURATION, + TERMINAL_LIMIT, Dashboard, SpaceCheckbox, TaskDetailScreen, @@ -37,6 +39,7 @@ _marks_cell, _matches, _repo_cell, + _same_cell, _slug_cell, _snooze_label, _status_cell, @@ -135,9 +138,14 @@ def __init__( # `signal_change()` to release a parked `list_tasks_versioned` (the producer "changed a task"). self._version = 0 self._change = threading.Event() - self.list_tasks_calls = 0 # how many times the table was (re)built — counts feed refreshes + self.list_tasks_calls = 0 # how many full fetches (`r`, first paint, after an action) + self.terminal_limits: list[int | None] = [] # the terminal_limit each list_tasks asked for # When set, list_tasks raises it (mimics the task service erroring/stalling mid-refresh). self.list_error: Exception | None = None + # Likewise for live_runners — the one read a refresh drawn from a snapshot it already holds + # (the feed's long-poll, the snooze timer's repaint) still makes. + self.runners_error: Exception | None = None + self.live_runners_calls = 0 self.created: list[tuple[str, str, str | None]] = [] self.created_artifacts_b64: list[dict[str, str] | None] = [] self.applied: list[tuple[str, str]] = [] @@ -153,14 +161,15 @@ def __init__( self.repo_fetched: list[tuple[str, str]] = [] # (repo_id, name) → get_repo_artifact self.put_repo_artifacts: list[tuple[str, str, bytes]] = [] # repo-scoped uploads - def list_tasks(self) -> list[dict[str, Any]]: + def list_tasks(self, *, terminal_limit: int | None = None) -> list[dict[str, Any]]: self.list_tasks_calls += 1 + self.terminal_limits.append(terminal_limit) if self.list_error is not None: raise self.list_error return self._tasks 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[dict[str, Any]], int]: """Mimic the block-until-change feed: park until a test arms `signal_change()` (then bump the cursor and return) or the park elapses (return the current, unchanged cursor). `wait=None` @@ -185,6 +194,9 @@ def list_registrations(self, task_id: str) -> list[dict[str, Any]]: return self._registrations.get(task_id, []) def live_runners(self) -> list[dict[str, Any]]: + self.live_runners_calls += 1 + if self.runners_error is not None: + raise self.runners_error return self._runners def list_artifacts(self, task_id: str) -> list[str]: @@ -716,7 +728,8 @@ async def test_dashboard_refreshes_when_the_feed_signals_a_change() -> None: fake.signal_change() # ...and the feed releases the worker's parked long-poll await _settle(pilot, lambda: table.row_count == 1) assert table.row_count == 1 - assert fake.list_tasks_calls == builds + 1 # exactly one feed-driven rebuild + # Drawn from the long-poll's own snapshot: no second full fetch of the task list. + assert fake.list_tasks_calls == builds async def test_dashboard_does_not_refresh_while_the_feed_is_idle() -> None: @@ -728,9 +741,19 @@ async def test_dashboard_does_not_refresh_while_the_feed_is_idle() -> None: ) # fast idle polls, but nothing changes # type: ignore[arg-type] async with app.run_test() as pilot: await pilot.pause() + renders = 0 + real_render = app._render + + def counting_render(tasks: list[dict[str, Any]], runners: list[dict[str, Any]]) -> None: + nonlocal renders + renders += 1 + real_render(tasks, runners) + + app._render = counting_render # type: ignore[method-assign] builds = fake.list_tasks_calls # first paint only await pilot.pause(0.2) # several idle long-poll cycles elapse - assert fake.list_tasks_calls == builds # the quiet feed triggered no rebuild + assert fake.list_tasks_calls == builds # the quiet feed triggered no fetch... + assert renders == 0 # ...and no redraw async def test_auto_refresh_preserves_the_highlighted_task() -> None: @@ -809,7 +832,8 @@ async def test_a_failing_service_warns_once_per_outage() -> None: async def test_a_failed_snooze_timer_refresh_keeps_running_and_retries() -> None: # The snooze-display timer fires a repaint on the UI thread; a failing read there must not exit - # the app, and the timer re-arms so the countdown resumes once the service is back. + # the app, and the timer re-arms so the countdown resumes once the service is back. (The repaint + # redraws the snapshot it already has, so its one read is the live-runner list.) task = {**_TASK, "snoozed_until": _at(2)} fake = _FakeClient([task]) app = Dashboard(fake, refresh_interval=0, now=lambda: _NOW) # type: ignore[arg-type] @@ -817,9 +841,11 @@ async def test_a_failed_snooze_timer_refresh_keeps_running_and_retries() -> None await pilot.pause() assert app._snooze_timer is not None # armed for the finite snooze app._snooze_timer.stop() - fake.list_error = httpx.ReadTimeout("stalled") + app._snooze_timer = None + reads = fake.live_runners_calls + fake.runners_error = httpx.ReadTimeout("stalled") app.set_timer(0.01, app._refresh_snooze_display) # the timer firing, as it does live - await _settle(pilot, lambda: fake.list_tasks_calls >= 2) + await _settle(pilot, lambda: fake.live_runners_calls > reads) await pilot.pause() assert app.is_running assert app.query_one("#tasks", DataTable).row_count == 1 @@ -828,27 +854,83 @@ async def test_a_failed_snooze_timer_refresh_keeps_running_and_retries() -> None async def test_a_failed_feed_refresh_keeps_running_and_retries_the_change() -> None: # The feed worker marshals the rebuild onto the UI thread; a failure there must neither kill - # the worker nor the app, and once the service recovers the missed change still lands. + # the worker nor the app, and once the service recovers the missed change still lands. (The + # long-poll carries the task list itself, so the read that fails is the live-runner list.) fake = _FakeClient([_TASK]) app = Dashboard(fake, refresh_interval=0.05) # type: ignore[arg-type] async with app.run_test() as pilot: await pilot.pause() notices = _record_notices(app) table = app.query_one("#tasks", DataTable) - builds = fake.list_tasks_calls - fake.list_error = _http_500() + reads = fake.live_runners_calls + fake.runners_error = _http_500() fake._tasks = [_TASK, {**_TASK, "id": "task-second9999", "slug": "other"}] fake.signal_change() - await _settle(pilot, lambda: fake.list_tasks_calls > builds) + await _settle(pilot, lambda: fake.live_runners_calls > reads) await pilot.pause() assert app.is_running assert table.row_count == 1 # the last-drawn table survives assert notices == ["Task service unreachable — retrying…"] - fake.list_error = None # the service recovers — no further change is signalled + fake.runners_error = None # the service recovers — no further change is signalled await _settle(pilot, lambda: table.row_count == 2, tries=200) assert table.row_count == 2 # the rewound cursor retried the missed change +async def test_render_leaves_the_table_alone_when_no_row_changed() -> None: + # Most change-feed ticks change nothing the table shows (a field it doesn't render); clearing + # and re-adding every row for those was most of the dashboard's CPU. + other = {**_TASK, "id": "task-second9999", "slug": "other"} + fake = _FakeClient([_TASK, other]) + app = Dashboard(fake, refresh_interval=0) # type: ignore[arg-type] + async with app.run_test() as pilot: + await pilot.pause() + table = app.query_one("#tasks", DataTable) + cleared: list[bool] = [] + real_clear = table.clear + + def counting_clear(columns: bool = False) -> DataTable[Any]: + cleared.append(columns) + return real_clear(columns) + + table.clear = counting_clear # type: ignore[method-assign] + + app._render([{**_TASK, "memo_unrendered": "x"}, other], []) # nothing visible differs + await pilot.pause() + assert cleared == [] + + app._render([{**_TASK, "turn": "user"}, other], []) # a visible cell differs: redraw + await pilot.pause() + assert cleared == [False] + assert "user" in str(table.get_row_at(0)[1]) + + app._render([{**_TASK, "turn": "user"}, other], []) # and settles again + await pilot.pause() + assert cleared == [False] + + +def test_same_cell_sees_a_style_only_change() -> None: + # ``Text.__eq__`` ignores the base style, so a row dimmed by a snooze would compare equal to + # its undimmed self and never be repainted. + assert not _same_cell(Text("repo", style="dim"), Text("repo")) + assert not _same_cell(_dim("repo"), Text("repo")) + assert not _same_cell("repo", Text("repo")) + assert _same_cell(_dim("repo"), _dim("repo")) + + +async def test_finished_tasks_are_capped_until_toggled() -> None: + fake = _FakeClient([_TASK]) + app = Dashboard(fake, refresh_interval=0) # type: ignore[arg-type] + async with app.run_test() as pilot: + await pilot.pause() + assert fake.terminal_limits[-1] == TERMINAL_LIMIT # the default fetch is capped + await pilot.press("D") + await pilot.pause() + assert fake.terminal_limits[-1] is None # `D` fetches every finished task... + await pilot.press("D") + await pilot.pause() + assert fake.terminal_limits[-1] == TERMINAL_LIMIT # ...and again restores the cap + + async def test_dashboard_with_no_tasks() -> None: app = Dashboard(_FakeClient([])) # type: ignore[arg-type] async with app.run_test() as pilot: @@ -3115,6 +3197,7 @@ def test_footer_shows_only_the_essential_keys() -> None: assert hidden == { "o", "r", + "D", "R", "p", "e", diff --git a/tests/terminal/test_request_mix.py b/tests/terminal/test_request_mix.py new file mode 100644 index 00000000..15884f3b --- /dev/null +++ b/tests/terminal/test_request_mix.py @@ -0,0 +1,47 @@ +"""``panopticon request-mix``: classifying the task service's access log.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from panopticon.terminal.__main__ import main +from panopticon.terminal.request_mix import render, tally + +_ID = "8460baaa6b7f457eb947f080e4927aad" +_OTHER = "0123456789abcdef0123456789abcdef" + +_LOG = [ + 'INFO: 172.17.0.5:43210 - "GET /tasks?since=41&wait=2.0 HTTP/1.1" 200 OK', + 'INFO: 172.17.0.5:43211 - "GET /tasks?since=0 HTTP/1.1" 200 OK', + 'INFO: 172.17.0.5:43212 - "GET /tasks HTTP/1.1" 200 OK', + f'INFO: 172.17.0.6:5000 - "PUT /tasks/{_ID}/turn HTTP/1.1" 200 OK', + f'INFO: 172.17.0.7:5000 - "PUT /tasks/{_OTHER}/turn HTTP/1.1" 200 OK', + f'INFO: 172.17.0.7:5000 - "PUT /tasks/{_OTHER}/lifecycle HTTP/1.1" 500 Internal Server Error', + f'2026-10-22 21:00:00,000 INFO uvicorn.access: 1.2.3.4:1 - "GET /tasks/{_ID} HTTP/1.1" 200', + "2026-10-22 21:00:00,000 INFO panopticon.taskservice.service: task x: slug → y", +] + + +def test_tally_splits_writes_long_polls_and_full_reads() -> None: + mix = tally(_LOG) + assert (mix.writes, mix.long_polls, mix.full_reads, mix.other) == (3, 1, 2, 1) + assert mix.errors == 1 + # Ids fold out of the route, so the chattiest writer tallies as one endpoint. + assert mix.write_endpoints.most_common(1) == [("PUT /tasks/{id}/turn", 2)] + + +def test_render_reports_shares_and_busiest_writes() -> None: + text = render(tally(_LOG)) + assert "writes 3 42.9%" in text + assert "PUT /tasks/{id}/turn" in text + assert render(tally([])).startswith("requests 0") # an empty log doesn't divide by 0 + + +def test_cli_reads_the_log(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + log = tmp_path / "service.log" + log.write_text("\n".join(_LOG)) + assert main(["request-mix", str(log)]) == 0 + assert "long-polls 1" in capsys.readouterr().out + assert main(["request-mix", str(tmp_path / "missing.log")]) == 1