Repository navigation
perf(coordination): bound the archive_evidence stage to a deadline - #3116
Conversation
Problem: polylogue-20d.17 — live measurement of build_coordination_envelope against the real (large, currently mid-restore) archive found its archive_evidence stage alone taking ~10s while every other stage stayed under 1s: an unbounded SQLite read (session trees, activity episodes, subagent exchanges, proof refs, context-flow refs) with no per-query timeout, unlike the daemon/archive status surface's now-bounded facts (PR #3107). Any caller of build_coordination_envelope — the live `polylogue agents status` CLI included — paid this cost on every call. What changed: - polylogue/coordination/envelope.py: new _bounded_stage helper (backed by the shared StatusComponentRegistry protocol from PR #3107) wraps the archive_evidence stage with a 3s deadline and an explicit degraded fallback (surfaced in the envelope's advisories), the same fresh/stale/timed_out/degraded/unavailable vocabulary daemon status uses. The underlying query keeps running on its own thread past the deadline (no cooperative cancellation for a blocking SQLite read), but the caller gets control back instead of waiting out however long it takes. - New CoordinationEnvelopeCache class (also StatusComponentRegistry-backed, fingerprint-invalidated on git HEAD/logs, .beads/issues.jsonl, and the active index db/WAL mtimes) is ready substrate for a warm-cached coordination-status consumer; not yet wired to a live surface in this PR (see below). Scope note: this PR originally also rewired the MCP `agent_coordination` tool's ad-hoc TTL-only cache onto CoordinationEnvelopeCache. That tool turned out to already be dead code: `register_tools()` (the live MCP server's actual wiring) only registers the six-tool cutover surface from server_cutover.py, not `register_read_tools` (where `agent_coordination` lives) — confirmed by tracing `register_tools()` and by the fact its dedicated test file was already deleted by the six-tool cutover (PR #3095) with no replacement coverage. The live cutover surface's `status(scope="coordination")` handler is the real, reachable path, and it has a separate, pre-existing bug: it never dispatches to coordination logic at all, always returning `archive.stats()` regardless of scope. Wiring CoordinationEnvelopeCache into that handler is real, valuable follow-up work, but it sits inside another lane's active six-tool cutover (`feature/mcp/retire-legacy-registrars`) and risks colliding with in-flight changes there — filed as a follow-up (polylogue-qink) rather than done here. Verification: - devtools test tests/unit/coordination/ tests/unit/mcp/ — 199 passed. - mypy --strict on touched files; devtools verify --quick green. - Live-archive read-only measurement (provisional, archive mid-restore from the 2026-07-18 incident): `polylogue agents status --format json` process wall time ~5.1s (import tax + bounded stages), vs. what would otherwise be ~11s+ with the unbounded archive_evidence stage included. Ref polylogue-20d.17
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 36 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
## Summary `status(scope="coordination")` on the six-tool MCP cutover surface silently returned generic `archive.stats()` instead of coordination status. ## Problem `register_cutover_read_tools`'s `status` verb dispatched every scope except `"operation"` to the same `archive.stats()` projection. An agent calling `status(scope="coordination")` got archive stats, not coordination data — discovered while porting polylogue-20d.17's budgeted component-snapshot protocol to coordination status (#3116). ## Solution - `status(scope="coordination")` now dispatches to real coordination logic: compact requests reuse a lazily-constructed `CoordinationEnvelopeCache` (fingerprint-invalidated on git HEAD/logs/`.beads/issues.jsonl`/index db-WAL mtimes, per #3116's substrate), `"detail"` requests bypass the cache and call `build_coordination_envelope` directly — matching the fresh/detail semantics the other status scopes already use. - The cache is constructed lazily inside `register_cutover_read_tools`'s closure so sessions that never call `status(scope="coordination")` don't pay `polylogue.coordination`'s import cost. ## Scope note (polylogue-qink AC-3) qink's AC also asked to "decide and act on `register_read_tools`/`agent_coordination`'s fate" (the old standalone MCP tool, unreachable from the live server). That deletion is Lane C's in-flight six-tool-cutover scope (polylogue-t46.8) and has since landed on master via #3118 (`refactor(mcp): delete dead legacy MCP registrar code`) — no action needed here. ## Verification - `devtools test tests/unit/mcp/test_status_scope_coordination.py` — 2 passed. Drives the live registered `status` tool function end-to-end (not a hand-built registrar): proves the response is coordination-shaped with no `"archive"` key (regression for the silent-fallthrough bug), and that a second compact call hits the warm cache (1 build call across 2 compact + 1 detail invocation) while detail always goes live. - `mypy --strict polylogue/mcp/server_cutover.py` — clean. - `devtools verify --quick` — exit 0 (ran pre-commit and pre-push). Ref polylogue-qink
## Summary `build_coordination_envelope`'s expensive `archive_evidence` sub-stage (bounded to a 3s deadline in #3116) could never actually finish under sustained polling — it was silently restarted from scratch on every refresh tick, forever. ## Problem `_bounded_stage` built a throwaway `StatusComponentRegistry` on every call. Live measurement found `archive_evidence` alone taking ~10s while bounded to 3s (#3116). `CoordinationEnvelopeCache`'s own outer envelope TTL is ~1s, so every refresh tick abandoned the previous attempt's still-running background thread (which kept executing, unobserved) and launched an equally-doomed new one — the query never got a chance to finish within any single attempt's window, and the coordination status MCP consumer (#3128) would degrade forever instead of eventually converging on the real answer. This is polylogue-20d.17 AC #6 ("exact expensive diagnostics are ... resumable"). ## Solution - `_bounded_stage` now accepts an optional persistent `registry`. When given, it's reused as-is (the `call` argument is ignored — the registry's own collector already knows how to recompute what it needs). - `CoordinationEnvelopeCache` owns one persistent `archive_evidence` `StatusComponentRegistry` per cwd (fingerprint-invalidated the same way as the outer envelope registry), threaded into `build_coordination_envelope` via a new `archive_evidence_registry` parameter. - A later tick that finds the registry's attempt still in flight now observes `refreshing` immediately instead of restarting the query; once the background attempt actually finishes, every subsequent tick reuses that real result until its own TTL/fingerprint expires. - Direct/CLI calls to `build_coordination_envelope` (detail requests, one-shot processes) are unaffected — they still get a fresh ephemeral registry, since a one-shot process has nothing to resume across. - Fixed a self-deadlock found during development: `get_or_build` held its own lock while calling the new `_archive_evidence_registry` helper, which re-acquired the same lock (`threading.Lock` isn't reentrant). Switched to `RLock`. The other two AC #6 properties were already satisfied, unchanged by this PR: "bounded" (existing `deadline_s`), and "limit constrains collection work" — the underlying archive_evidence SQL already uses `LIMIT ?` in every query (verified by reading `_archive_activity_rows` and siblings), not fetch-all-then-slice. "Cancellable" means the caller is never blocked past `deadline_s` (already true); Python cannot safely preempt a blocking SQLite call mid-query, so this does not attempt true thread cancellation. ## Verification - New test `test_coordination_envelope_cache_resumes_slow_archive_evidence_across_ticks` proves the collector is invoked exactly once across three ticks (timed out → refreshing → fresh) despite the query taking longer than the deadline — this fails on the pre-fix ephemeral-registry code (each tick would re-invoke the collector, incrementing the call counter each time). - `devtools test tests/unit/coordination/test_envelope.py tests/unit/mcp/test_status_scope_coordination.py` — 28 passed. - `mypy --strict polylogue/coordination/envelope.py` — clean. - `devtools verify --quick` — exit 0. Ref polylogue-20d.17
Summary
Second PR for polylogue-20d.17: extends the budgeted component-snapshot
protocol from PR #3107 (daemon/archive status) to the agent-coordination
envelope, bounding its one genuinely expensive, unbounded stage. Scope
narrowed mid-implementation after a real architectural discovery — see
"Scope note" below.
Problem
Live measurement of
build_coordination_envelopeagainst the real (large,currently mid-restore) archive found its
archive_evidencestage — sessiontrees, activity episodes, subagent exchanges, proof refs, and context-flow
refs, one read-only SQLite connection with no per-query timeout — taking
~10s, while every other stage (repo, process, self, work_item, beads,
peers, resources, archive, handoff, overlaps, advisories) stayed under 1s.
Any caller of
build_coordination_envelopepaid this cost on every call,including the live
polylogue agents statusCLI command — the same"one slow probe stalls the whole answer" failure shape PR #3107 fixed for
daemon status.
Solution
polylogue/coordination/envelope.py: new_bounded_stagehelper, backedby the shared
StatusComponentRegistryprotocol from PR feat(daemon,status): budgeted component-snapshot protocol for status surfaces #3107, wrapsarchive_evidencewith a 3s deadline and an explicit degraded fallback(surfaced in the envelope's
advisories) instead of blocking however longthe query takes. The query keeps running on its own thread past the
deadline (no cooperative cancellation for a blocking SQLite read), but the
caller gets control back.
CoordinationEnvelopeCacheclass (alsoStatusComponentRegistry-backed, fingerprint-invalidated on git HEAD/logs,
.beads/issues.jsonl,and the active index db/WAL mtimes) is ready substrate for a future
warm-cached coordination-status consumer. Not wired to a live surface in
this PR — see below.
Scope note (read this before reviewing the diff)
This PR originally also rewired the MCP
agent_coordinationtool's ad-hoc1s TTL-only cache onto
CoordinationEnvelopeCache, mirroring PR #3107'sMCP-cache treatment. While rebasing onto master (which had moved past a
six-tool MCP surface cutover,
feature/mcp/retire-legacy-registrars), Ifound that tool is already dead code:
register_tools()— the actuallive MCP server wiring in
polylogue/mcp/server.py— only callsregister_cutover_read_tools/register_cutover_privileged_toolsfromserver_cutover.py, neverregister_read_tools(whereagent_coordinationlives). Its dedicated test file was already deleted by the six-tool cutover
(#3095) with no replacement coverage, which is how this went unnoticed.
The live, reachable coordination-status path today is
status(scope="coordination")inserver_cutover.py— and it has aseparate, pre-existing bug: every scope value except
"operation"fallsthrough to the same generic
archive.stats()projection, sostatus(scope="coordination")silently returns archive stats, nevercoordination data. Wiring
CoordinationEnvelopeCacheinto that handler isreal, valuable follow-up work, but it sits inside another lane's actively
in-flight cutover and risks colliding with concurrent changes there. Filed
as polylogue-qink instead of attempted here.
Verification
Live-archive read-only measurement (provisional — archive mid-restore from
the 2026-07-18 incident):
archive_evidencestage (in-process)advisoriespolylogue agents status --format json(live CLI, no MCP)Ref polylogue-20d.17