Skip to content

feat(query): interruptible, admission-controlled archive read execution - #2964

Merged
Sinity merged 2 commits into
masterfrom
feature/query/execution-control
Jul 17, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/query/execution-control

Conversation

@Sinity

@Sinity Sinity commented Jul 17, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the execution-control slice of the archive-queryability program (polylogue-z9gh.1, under epic polylogue-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 MCP query_units tool, and the daemon HTTP /api/query-units route 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.Event cancellation shared between the async caller and the SQLite worker thread. query_ref is a content hash; raw expressions never enter receipts.
  • QueryAdmissionController — FIFO within workload class, weighted admission with reserved_interactive headroom 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 via asyncio.to_thread, HTTP handler threads admit directly — one process-wide controller across all surfaces. Exactly-once release guarded.
  • InterruptibleSQLiteRead — one read per dedicated read-only ArchiveStore opened in the worker thread (never shared, never a writer connection), progress guard aborting on cancel/deadline, cross-thread interrupt(), cleanup exactly once in finally.
  • 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.

ArchiveStore gains two narrow public hooks (set_read_progress_guard, interrupt_reads) rather than exposing its raw connection.

Acceptance-criteria matrix (bead polylogue-z9gh.1)

  1. Production types consumed by a real query_units path — satisfied: API, MCP tool, and HTTP route all execute through the layer; none defines parallel deadline/cancellation state for this route. Remaining direct ArchiveStore read sites in MCP/HTTP migrate under z9gh.9.1 (noted on the bead).
  2. Off-loop execution, exact-connection interrupt, abort SLO — satisfied and tested: a WITH RECURSIVE bomb aborts on cancel/deadline within a 5s test SLO (real latency is progress-guard cadence).
  3. Loop responsiveness under load — satisfied and tested: heartbeat max-gap assertion fails if synchronous SQLite returns to the loop; an unrelated cheap read completes in <1s while the bomb runs.
  4. Weighted fairness — partially satisfied: FIFO-within-class, reserved interactive headroom, queue position, and clamp-never-refuse are implemented and tested. Cross-class aging under sustained interactive saturation (strict eventual admission for scans) is deferred to z9gh.9.1's scheduler, recorded on the bead.
  5. Exactly-once cleanup — satisfied for cancel-before-admission, during-SQLite, disconnect, and worker-failure paths (tested; admission weight returns to 0 in every test). Page/spool-production cleanup is n/a until z9gh.9.1 introduces spooling. Incident-scale RSS-envelope verification deferred (needs the live 4.85M-block archive; recorded on the bead).
  6. Receipts — satisfied: queued/admitted/running/completed/cancelled/timed_out/disconnected/failed with safe refs (leak-tested); resumed arrives with z9gh.9.1 resumability.
  7. Mutation kill-map — removing the progress guard hangs the abort tests past SLO; removing interrupt fails disconnect drain timing; removing to_thread fails 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).
  • New test file allowlisted in docs/plans/test-clock-allowlist.yaml (tests measure real thread-scheduling/SQLite-cadence wall-clock by contract).
  • Not run: full 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

@coderabbitai

coderabbitai Bot commented Jul 17, 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: 8 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: 708a4d4d-be63-4214-afcb-1c71c9828ff8

📥 Commits

Reviewing files that changed from the base of the PR and between c202864 and 6e5559a.

📒 Files selected for processing (9)
  • docs/plans/test-clock-allowlist.yaml
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/archive/query/execution_control.py
  • polylogue/daemon/http.py
  • polylogue/mcp/server_tools.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/archive/query/test_execution_control.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/query/execution-control

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/mcp/server_tools.py Resolved
Comment on lines +334 to +340
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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Sinity added a commit that referenced this pull request Jul 17, 2026
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
Sinity and others added 2 commits July 17, 2026 02:38
…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
@Sinity
Sinity force-pushed the feature/query/execution-control branch from 3d36a0c to 6e5559a Compare July 17, 2026 00:39
@Sinity
Sinity merged commit fd7b354 into master Jul 17, 2026
2 checks passed
@Sinity
Sinity deleted the feature/query/execution-control branch July 17, 2026 00:40
Sinity added a commit that referenced this pull request Jul 27, 2026
…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
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 59.F046 / P2: fixed-already at the checked revision: polylogue/archive/query/execution_control.py:436-437 routes queued aborts through _abort_error. Lines 653-660 distinguish explicit cancellation from deadline expiry and set terminal cancelled or timed_out receipts, returning QueryTimeoutError for the latter.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 68.F022 / P1: fixed-already at the checked revision: polylogue/api/archive.py:3822 classifies query-unit work from its expression before admission. polylogue/archive/query/execution_control.py:679-680 classifies aggregate, grouped and pipeline queries as scan work, and the MCP dispatcher calls that API rather than forcing interactive capacity.

Only the rows listed above are dispositioned. Held findings remain open.

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