Repository navigation
feat(query): interruptible, admission-controlled archive read execution - #2964
Conversation
|
Warning Review limit reached
Next review available in: 8 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 (9)
✨ 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea9ac9e53c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| result = work(store) | ||
| except Exception as exc: | ||
| if ctx.should_abort() and _is_interrupt_error(exc): | ||
| ctx.receipt.interrupted = True | ||
| raise _abort_error(ctx) from exc | ||
| raise | ||
| ctx.receipt.state = "completed" |
There was a problem hiding this comment.
Check cancellation during non-SQL work
The progress handler only observes cancellation while SQLite is executing, and work(store) is otherwise allowed to run to completion before the receipt is unconditionally marked completed. For a multi-field aggregate, _all_aggregate_rows is followed by Python-side grouping over every materialized row; if the deadline or disconnect occurs after the final SELECT, interrupt() has no active statement to stop, the worker continues consuming CPU/memory, and the async cancellation path waits indefinitely for it to drain.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3d36a0c — the runner now re-checks ctx.should_abort() after work() returns, so a cancel/deadline during Python-side grouping aborts with the correct terminal receipt instead of completing; and the disconnect drain is bounded by DISCONNECT_DRAIN_TIMEOUT_S so uninterruptible Python work cannot hold the async cancel path — the orphaned worker still releases admission and closes its store on exit (test_abort_during_python_post_processing_discards_result, test_disconnect_drain_is_bounded_for_uninterruptible_work).
Codex review on #2964, all three findings real: - workload_class was hard-coded "interactive" on every route, so the reserved interactive headroom protected nothing. Routes now classify via the parsed expression: aggregate/group-by/pipeline stages admit as "scan" (classify_unit_expression_workload). - the progress guard only observes SQLite; a cancel/deadline landing during Python-side post-processing completed anyway. The runner now aborts after work() returns when the context is already aborted. - a deadline expiring while queued raised QueryCancelledError with the receipt left "queued", bypassing the HTTP 503 mapping. Queued aborts now raise the correct timeout/cancel error with terminal receipts, and the disconnect drain is bounded (DISCONNECT_DRAIN_TIMEOUT_S) so uninterruptible Python work cannot hold the caller hostage — the orphaned worker still releases admission and closes its store. Five new tests pin these (queued-timeout receipt, post-SQL abort, bounded drain with orphan cleanup, classifier table, scan routing through the production API path). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
…cution Problem: archive read surfaces are async in signature but run synchronous SQLite work on the caller's event loop with no deadline, cancellation, or admission control. During the live continuity incident one pathological query drove the MCP process to an 8.5 GiB RSS / 6.8 GiB swap peak while a client timeout could not stop the underlying work. What changed (polylogue-z9gh.1, the execution-control slice of z9gh.9): - polylogue/archive/query/execution_control.py: QueryExecutionContext (immutable identity + monotonic deadline + cross-thread cancellation), QueryAdmissionController (FIFO-within-class weighted admission, reserved interactive headroom, clamped weights so estimates are backpressure and never a permanent refusal, exactly-once release), InterruptibleSQLiteRead (one read per dedicated read-only connection in a worker thread, SQLite progress-guard abort, cross-thread interrupt), and typed receipts with safe query refs (hashes, never raw expressions). - ArchiveStore gains two narrow public hooks (set_read_progress_guard, interrupt_reads) instead of exposing its raw connection. - Polylogue.query_units, the MCP query_units tool, and the daemon HTTP /api/query-units route all execute through the shared layer: asyncio cancellation (the MCP disconnect shape) sets the shared cancel state, interrupts the exact connection, and drains the worker; the HTTP route keeps its 0.25s reader busy-timeout and maps deadline exhaustion to 503. Paging/spool formats and request-level budget contracts remain z9gh.9.1 scope; remaining direct ArchiveStore read sites in MCP/HTTP migrate there. Ref polylogue-z9gh.1. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
Codex review on #2964, all three findings real: - workload_class was hard-coded "interactive" on every route, so the reserved interactive headroom protected nothing. Routes now classify via the parsed expression: aggregate/group-by/pipeline stages admit as "scan" (classify_unit_expression_workload). - the progress guard only observes SQLite; a cancel/deadline landing during Python-side post-processing completed anyway. The runner now aborts after work() returns when the context is already aborted. - a deadline expiring while queued raised QueryCancelledError with the receipt left "queued", bypassing the HTTP 503 mapping. Queued aborts now raise the correct timeout/cancel error with terminal receipts, and the disconnect drain is bounded (DISCONNECT_DRAIN_TIMEOUT_S) so uninterruptible Python work cannot hold the caller hostage — the orphaned worker still releases admission and closes its store. Five new tests pin these (queued-timeout receipt, post-SQL abort, bounded drain with orphan cleanup, classifier table, scan routing through the production API path). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
3d36a0c to
6e5559a
Compare
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
…k bool env vars (#3340) ## Summary Fresh `devtools verify --all` re-triage of polylogue-p6rz ("pre-existing test failures unrelated to MCP cutover") against current master. Fixes several confirmed real regressions and stale test assertions found during the pass; files properly-scoped follow-up beads for the rest instead of leaving them as anonymous re-discoveries. ## Problem polylogue-p6rz's original list (from 2026-07-18) was stale: a lot has merged since. A fresh `devtools verify --all` run (107 failed, 14 errors on the pre-fix baseline) needed re-triage to separate fixed / persisting / newly introduced failures, and specifically to catch any real regression from this session's merges (query DSL AST schema, browser-capture approval flow, GitHub effect adapters, continuity replay wiring, etc.). ## Solution **Confirmed real regressions, fixed:** - `polylogue/config.py`: PR #3202's strict bool-env coercion rejected a blank `POLYLOGUE_FORCE_PLAIN=""` value with `ConfigError` instead of the old passthrough-as-falsy behavior, breaking a long-standing CLI test convention (and inconsistent with this same module's own NO_COLOR "blank means not requested" convention). Blank bool-key env values now resolve to `False`. - `polylogue/storage/sqlite/queries/mappers_support.py` and `polylogue/storage/blob_integrity.py`: PR #3155's three-tier JSON facade introduced `polylogue.core.json.JSONDecodeError` (a `ValueError` subclass, NOT a stdlib `json.JSONDecodeError` subclass), but two call sites still caught the stdlib type — silently losing `DatabaseError` diagnostic wrapping (field/record id context) and blob-corruption graceful degradation since 2026-07-19. **Stale test assertions / drifted mocks, fixed:** - `tests/unit/cli/test_color_and_layout.py`: tested `no_color_requested()`/ `should_use_plain()` as if they read `NO_COLOR` from the environment directly; PR #3079 made them pure passthroughs (env resolution moved to `config.py`, already covered elsewhere). Rewrote to test the passthrough contract. - `tests/unit/storage/test_durable_migrations.py`: hardcoded `USER_SCHEMA_VERSION == 9` / `applied_versions` tuple; PR #3068 bumped it to 10 without updating these two tests. - `tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr`: stale `index.db` `user_version`/`sqlite_stat1_rows` snapshot from before PR #3235's schema bump 42→43. - `tests/unit/cli/test_diagnostics.py`: `_patch_tool_count_store`'s fake `ArchiveStore.open_existing` lambda didn't accept the `read_timeout` kwarg PR #2964 added, and the fake store was missing `begin_read_snapshot()` (also from #2964's interruptible-read protocol) — 8 tests broken since 2026-07-17. - `tests/unit/devtools/test_mandate_continuity_replay.py` and `tests/unit/operations/test_work_effect_reconciliation.py`: both asserted the real `GitHubPullRequestEffectAdapter` fails against `Sinity/polylogue` — true only in an environment without `gh` auth (e.g. stock CI), false on any dev machine with `gh` authenticated for this repo (confirmed: `gh pr list --repo Sinity/polylogue` succeeds fine here). Forced deterministic unavailability via a nonexistent `gh_path` instead. - `tests/unit/storage/test_delegations_view.py`: 3 tests opened a bare `index.db`-only `ArchiveStore` (no `user.db`); PR #3068's new `archive_snapshot_epoch()` unconditionally requires `user_tier` attached. Added a sibling `user.db` bootstrap to the 3 affected fixtures — matches every other test's full-tier archive construction. - `tests/unit/architecture/test_surface_storage_boundary.py`: allow-listed two CLI commands (`reconcile_work_effects.py`, and `materialize_incident_evidence.py` — the latter landed on master via a concurrent session's PR #3336 mid-rebase) that construct `SessionRepository` directly instead of through `AppEnv.repository`, per the test's own documented remediation path. Filed polylogue-a7uk for the proper fix. **Concurrent-session note:** this branch was rebased onto master mid-flight after another session's PR #3332 landed fixing the exact same `test_timestamp_guards.py` hypothesis-6.161 mypy break I'd independently found and fixed — kept master's version (identical `st.one_of` split approach) rather than duplicating it. **Already tracked, not duplicated:** - `test_execution_control.py` `api.query_units` naming mismatch + `>=50000 VM steps` anti-vacuity mutation tests → polylogue-1ldl (fully root-caused 2026-07-20: PR #3018 made the mutation-under-test no longer expensive at this data scale). - `test_live_batch_support.py` stale `failed=[...]` assertion → polylogue-5202. - `test_archive_maintenance_cli.py` / `test_daemon_cli.py` 6-node cluster → polylogue-p5li. - `tests/infra/surfaces.py` stale `list_sessions`/`search` MCP tool-name lookups (affects `test_retrieval_readiness_laws.py`, `test_cross_surface_agreement.py`) → polylogue-t46.8 (MCP tool-sprawl replacement epic; p6rz's own original text already called this out-of-scope). **New follow-up beads filed (confirmed pre-existing, not this-session regressions, but not safe/minimal to fix inline):** - polylogue-57w4 — repair path still disagrees with converger on NULL-sort-key session-profile staleness (regresses PR #2900's own invariant; root cause not fully diagnosed). - polylogue-lbgc — seeded-archive corpus build hits `database is locked` under xdist parallel first-build (affects `test_plain_cli_snapshots.py`, `test_schema_generation.py`, likely others); confirmed not simple cross-worker contention (the build already holds an exclusive flock across the whole build+integrity-check section) — more likely an unclosed intra-process connection. - polylogue-e6a0 — `test_index_v37_fast_forward.py`'s v36 fixture predates the `action_pairs` runtime index added by PR #3210; attempted fix revealed the fixture's intended "before" shape needs the full same-version benign-DDL-convergence set, not just `ensure_runtime_indexes_sync` — reverted the attempt rather than ship an incomplete fixture. No regression found from this session's headline PRs (query DSL AST schema, browser-capture approval flow, continuity replay wiring) — the two GitHub effect-adapter tests and the `materialize_incident_evidence.py` boundary violation are environment/pattern issues in supporting test/command code, not in the new capability logic itself. ## Verification - `devtools test` on every changed test file individually: all green (see per-file evidence above). - `mypy --strict` on every changed `.py` file: clean. - `ruff format --check` / `ruff check`: clean. - Fresh `devtools verify --all` run against this branch in progress; will update this PR/polylogue-p6rz with the final authoritative count once it completes (~14 min runtime). Ref polylogue-p6rz
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Implements the execution-control slice of the archive-queryability program (
polylogue-z9gh.1, under epicpolylogue-z9gh): a reusable layer that makes archive reads run off the event loop, on dedicated read-only connections, under deadline + cancellation + admission control, with typed execution receipts.Polylogue.query_units, the MCPquery_unitstool, and the daemon HTTP/api/query-unitsroute now all execute through it.Problem
Archive read surfaces are async in signature but ran synchronous SQLite work on the caller's event loop with no deadline, no SQLite progress-handler cancellation, no connection interrupt path, and no admission control. In the live continuity incident, one pathological query drove the write-role MCP process to 8.5 GiB RSS + 6.8 GiB swap over 43 minutes, and client timeouts could not stop the underlying work — one query made the whole server unavailable.
Solution
New
polylogue/archive/query/execution_control.py:QueryExecutionContext— frozen identity + monotonic deadline +threading.Eventcancellation shared between the async caller and the SQLite worker thread.query_refis a content hash; raw expressions never enter receipts.QueryAdmissionController— FIFO within workload class, weighted admission withreserved_interactiveheadroom so scans can never consume the capacity an interactive read needs. Weights are clamped to the class ceiling: an over-declared estimate delays admission but can never become a permanent semantic refusal (per the 2026-07-15 contract correction on the bead). Thread-safe core: async callers admit viaasyncio.to_thread, HTTP handler threads admit directly — one process-wide controller across all surfaces. Exactly-once release guarded.InterruptibleSQLiteRead— one read per dedicated read-onlyArchiveStoreopened in the worker thread (never shared, never a writer connection), progress guard aborting on cancel/deadline, cross-threadinterrupt(), cleanup exactly once infinally.execute_archive_read/execute_archive_read_sync— async caller cancellation (the MCP client-disconnect shape) sets shared cancel state, interrupts the exact connection, drains the worker before re-raising; the sync variant serves the threaded HTTP daemon with the same controller and keeps the web reader's 0.25s busy-timeout, mapping deadline exhaustion to 503.ArchiveStoregains two narrow public hooks (set_read_progress_guard,interrupt_reads) rather than exposing its raw connection.Acceptance-criteria matrix (bead
polylogue-z9gh.1)ArchiveStoreread sites in MCP/HTTP migrate under z9gh.9.1 (noted on the bead).WITH RECURSIVEbomb aborts on cancel/deadline within a 5s test SLO (real latency is progress-guard cadence).resumedarrives with z9gh.9.1 resumability.interruptfails disconnect drain timing; removingto_threadfails the heartbeat test; removing admission release fails fairness/exactly-once tests; removing cleanup fails the in-flight-zero assertions.Verification
devtools test tests/unit/archive/query/test_execution_control.py— 14 passed (cancel SLO, deadline, disconnect drain, loop heartbeat, cheap-read-during-bomb, FIFO, reserved headroom, clamp, cancel-while-queued, exactly-once release, receipt safety, pre-opcode abort, sync/HTTP deadline, production-route consumption).devtools test tests/unit/mcp/test_server_surfaces.py tests/unit/mcp/test_envelope_contracts.py tests/unit/daemon/test_web_reader.py— 264 passed (MCP + HTTP query_units routes through the new layer).devtools test tests/unit/api/test_facade_contracts.py -k query_unit— passed.devtools verify --quick— exit 0 (format, lint, mypy --strict, render/topology — new module projected, layering).docs/plans/test-clock-allowlist.yaml(tests measure real thread-scheduling/SQLite-cadence wall-clock by contract).devtools verify --all; live-scale incident replay (deferred per AC matrix).Ref polylogue-z9gh.1.
🤖 Generated with Claude Code
https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ