Skip to content

perf(coordination): bound the archive_evidence stage to a deadline - #3116

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/coordination-status-cache
Jul 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/coordination-status-cache

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner

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_envelope against the real (large,
currently mid-restore) archive found its archive_evidence stage — session
trees, 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_envelope paid this cost on every call,
including the live polylogue agents status CLI 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_stage helper, backed
    by the shared StatusComponentRegistry protocol from PR feat(daemon,status): budgeted component-snapshot protocol for status surfaces #3107, wraps
    archive_evidence with a 3s deadline and an explicit degraded fallback
    (surfaced in the envelope's advisories) instead of blocking however long
    the 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.
  • 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 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_coordination tool's ad-hoc
1s TTL-only cache onto CoordinationEnvelopeCache, mirroring PR #3107's
MCP-cache treatment. While rebasing onto master (which had moved past a
six-tool MCP surface cutover, feature/mcp/retire-legacy-registrars), I
found that tool is already dead code: register_tools() — the actual
live MCP server wiring in polylogue/mcp/server.py — only calls
register_cutover_read_tools/register_cutover_privileged_tools from
server_cutover.py, never register_read_tools (where agent_coordination
lives). 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") in server_cutover.py — and it has a
separate, pre-existing bug: every scope value except "operation" falls
through to the same generic archive.stats() projection, so
status(scope="coordination") silently returns archive stats, never
coordination data. Wiring CoordinationEnvelopeCache into that handler is
real, 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

devtools test tests/unit/coordination/ tests/unit/mcp/   # 199 passed
mypy --strict polylogue/coordination/envelope.py polylogue/coordination/__init__.py   # clean
devtools verify --quick   # green

Live-archive read-only measurement (provisional — archive mid-restore from
the 2026-07-18 incident):

Path Before After
archive_evidence stage (in-process) ~10.0s (unbounded) capped at the 3.0s deadline, degraded reason surfaced in advisories
polylogue agents status --format json (live CLI, no MCP) would be ~11s+ with the unbounded stage ~5.1s (import tax + bounded stages)

Ref polylogue-20d.17

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
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d84dc60a-60ea-4f18-a28c-4cb1b4c01be8

📥 Commits

Reviewing files that changed from the base of the PR and between c2d3f94 and 1ad674a.

📒 Files selected for processing (3)
  • polylogue/coordination/__init__.py
  • polylogue/coordination/envelope.py
  • tests/unit/coordination/test_envelope.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/coordination-status-cache

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit a92c828 into master Jul 18, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/coordination-status-cache branch July 18, 2026 17:15
Sinity added a commit that referenced this pull request Jul 18, 2026
## 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
Sinity added a commit that referenced this pull request Jul 18, 2026
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant