Repository navigation
feat: Serve read --view messages from the daemon and gate controlled reads - #5354
Conversation
`read --view messages` was the one read view that still computed its answer in this process: a healthy daemon paid for a local archive open and the `polylogue.api` facade import on every invocation, while every sibling view was served over UDS. `session.read` grows a `messages` kind -- the same bounded message window as `transcript`, projected in the full message-row envelope vocabulary the `read --view messages` document is made of. It is framed by `operations/transcript_window.py` rather than by `session.read`'s own framing, so a continuation minted by the Python API, MCP or HTTP still resumes on the CLI and vice versa; a filtered window has no reader here and is refused by name instead of answered with unfiltered rows. The verb now lowers and renders only. `--verbose` prints `served-by:` naming the executor the result's own authority reports, and the read-view registry moves `messages` off the shrink-only `IN_PROCESS_READ_VIEWS` ratchet onto `session-read-projection`. Two defects found on the way: - `RootModeRequest` had no owner for "which configuration am I reading": routes read `params["_config"]` directly, which is `None` for every invocation the root callback does not pin. `request.config()` falls back to the active configuration, as the one existing resolution already did. - A typed refusal lost its declared code in both executors -- the direct one flattened every `ValueError` to `invalid_request`, the daemon one used the whole message as the code. A stale or foreign continuation now reaches a caller by the same token on both legs. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
polylogue-vclez claimed "six production ArchiveStore.open_existing() reads outside the controlled boundary" and no artifact said which call sites those were, so the claim could not be audited and the work it gated could not be given disjoint ownership. The population is 26 direct opens at this head and it grows; a prose list of them is wrong the first time somebody adds one. The rule, written down: a direct archive open is either a declared read-boundary owner, or an explicit `read_only=False` writer-lease open with a stated writer role, and anything else is a read that escaped admission, snapshot pinning, cancellation and receipts. There are two boundary owners, not one, because read parity is an equivalence between two declared executors (6fcfe44) rather than convergence on one route. `devtools gate controlled-read` censuses every call site against `docs/plans/controlled-read-census.yaml`, which classifies all 26 with a reason each. The census verdict at this head: 3 read-boundary owners, 23 licensed writers, 0 uncontrolled reads -- vclez's six do not reproduce. Five sites carry a recorded `debt`: the four Python-API facade mutations take the writer lease in-process rather than admitting through the daemon write coordinator, and `active_index_generation_is_empty` takes it to answer a question that is a read. `tests/unit/archive/query/test_read_surface_control.py` is deleted: the gate enforces its rule and more. The test licensed any `read_only=False` open with no stated reason, which is exactly why the surviving population could not be audited. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
|
You have reached your Codex usage limits for security reviews. Please try again later. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Note Currently processing new changes in this PR. This may take a few minutes, please wait... ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (26)
✨ Finishing Touches📝 Generate docstrings
🧪 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: 421eda3c81
ℹ️ 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".
…#5356) ## Summary Three `o21` leaves on the query terminal-execution path. **This moves the index schema identity** — see the landing window below. ## polylogue-o21.5 — the 50k cap silently truncated, and it wasn't the only defect ### Pre-change behaviour at the boundary, measured not reasoned Probe with `_AGG_ROW_FETCH_CAP` monkeypatched to 2 over a 3-row population: ``` CAPPED metrics: [(None, 2, {'count': 2, 'sum_word_count': 8.0, 'avg_word_count': 4.0, ...})] CAPPED pipeline result: {..., 'exact': False, 'sampled_rows': 2} ``` **It silently truncates — it does not refuse** — and the truncation is only *partly* flagged. Metric values and per-group `count` describe the first N rows in time-ascending order. `pipeline.result.exact=false` and `sampled_rows` are set, but the terminal `outcome` stays `ok` and never `degraded`, `has_next` is computed over truncated groups, and `selected_rows_exact` becomes `None`. **A complete-looking envelope carrying sample numbers** — which is the outcome contract's `degraded`-outranks-`empty` rule violated at the other end. ### `percentile` lowered faithfully, and got *more* correct Nearest rank is an integer definition; the Python reducer computed `math.ceil(rank / 100 * n)` in binary floating point. Enumerated: **290 of 198,000 `(rank, n)` pairs for `n ≤ 2000` pick the wrong element** — e.g. `p7` over 100 distinct values selected the 8th smallest instead of the 7th. SQL uses exact integer arithmetic, `MAX(1, MIN(n, (rank * n + 99) / 100))`. Confirmed by mutation: replacing it with `CAST(CEIL(rank / 100.0 * n) AS INTEGER)` reproduces the float artifact in SQLite, so **the defect was the float, not the definition**. Deliberate behaviour change, stated in the commit message. ### The bead's concrete input is wrong twice `agg avg(duration_ms) by tool` cannot parse: the syntax is `| agg avg:FIELD`, and `duration_ms` is not in `action`'s `aggregate_metric_fields`. The entire non-count metric surface is **three** `(unit, field)` pairs — `message.word_count`, `action.is_error`, `action.exit_code`. A real input is `messages where role:assistant | agg avg:word_count`. ## polylogue-o21.8 — understated, not overstated The bead records that the audit tried to turn the duplicated field maps into a reachable wrong output and **failed**, so it is filed as consolidation. That holds for the bracket path it examined — but a reachable wrong output **does** exist on the aggregate path: `_AGGREGATE_ROW_FIELDS` had no `session.repo` entry for any unit, while `session.repo` is a declared `aggregate_group_fields` member for every SQL unit. Measured at base: `messages where role:assistant | group by session.repo | agg count, avg:word_count` returned **a single `[missing]` group over all rows**, while the `count` terminal on the same expression returned the two real repositories. A second divergence: `delegations | group by basis | agg count` grouped by raw `instruction_tool_use_block_id` values while the count terminal groups by the `edge`/`action` discriminator. The o21.8 commit stays framed as consolidation; the defect sits in the o21.5 commit, which is what fixes it. ## polylogue-o21.7 — the mirror was already broken at head The bead describes drift hypothetically. In fact `explanation_payload_to_ast` **rejected the producer's own output for any `| agg ...` expression** with 7 validation errors. It is a test-gate and published-schema defect rather than a live route failure — no production path calls it — but `docs/openapi/search.yaml` and `webui/src/api/generated.ts` described a shape the server does not emit. The existing parity test's corpus contained no `agg` case, which is why it survived. ### Byte-equivalence of the refactor Captured `explain_expression(...).to_payload()` for a 38-expression corpus covering every predicate kind, pipeline stage, clause kind, entry branch and conditional key. After converting all 28 producers to declaration-driven rendering: ``` IDENTICAL: 38 expressions, payloads equal after timestamp redaction ``` The only redaction is the `since:7d` relative-date resolution. `QUERY_DEFINITION_PROTOCOL_VERSION` untouched; `query_ref` identity cannot move, because predicate payloads are unchanged and `hash_payload` sorts keys. Wire change is additive plus one narrowing (`terminal.action` from `string` to `"rows" | "count" | "agg"`); nothing removed, nothing widened; no repository consumer reads these types. ## Anti-vacuity — nine mutations executed, all restored Including **G, the bead's exact o21.8 condition**: a *single* deletion of `"type": "message_type"` reddens **three** tests across both paths. Others: the `LIMIT 50000` restoration (`assert 50000 == 50001`), the float percentile (`{'p7_word_count': 8.0} != {'p7_word_count': 7.0}`), removing the progress handler (`DID NOT RAISE QueryWorkBudgetExceededError`), and `"avg": "SUM"` in the reducer map, caught by the cross-surface parity test. Mutation C reproduces the *observable* of the deleted lookup rather than literally restoring the Python reducer — **labelled as a proxy, not a literal restore**. Nothing material is reasoned-not-executed. ## Parity, pagination, cancellation - **Cancellation**: 20,000 rows through `InterruptibleSQLiteRead` with a 10,000-opcode budget; both the `agg` and `rows` branches raise with `receipt.interrupted is True`. - **Pagination**: a 5-group aggregate walked at offsets 0/2/4, asserting `selected_rows_exact == 5` on every page — the *total*, not the page. - **CLI/API/MCP/HTTP**: one grouped `agg` page walked through `Polylogue.query_units`, the daemon HTTP route and the MCP `query` tool, resuming by continuation between pages, all three compared against word counts the test computes itself. ## THE LANDING WINDOW **All three index fingerprints move; the index tier must reconverge. This must land before a fresh rebuild starts, never during one.** | | base `2bbecb9cd` | branch | | --- | --- | --- | | lowering | `74fafc04…` | `a9bdbc48…` | | materializer | `9dc1287d…` | `8216f7ff…` | | replay_routing | `eef8760e…` | `b14bb766…` | | **index identity** | `0356cac3…` | `1a1bda47…` | | ops identity | `3d18f2a0…` | unchanged | Closure membership is a **one-for-one swap, 555 → 555**: `payload_schema.py` enters, `query_ast_schema.py` leaves. **Two bead closure verdicts were wrong at my base**: `query_ast_schema.py` was recorded IN but measures **out** after the change (the schema module became downstream of the producers instead of upstream), and `render_openapi.py` is out. Neither `daemon/event_bus.py` nor `archive_tiers/ops_write.py` was touched. Useful for scheduling: **#5352, #5353 and #5354 did not move the identity** — `origin/master` read `0356cac3…` at 540228b, 51222af and 2bbecb9 alike. ## Verification (post-rebase) `devtools verify --quick` **exit 0**, all 25 gates including `schema-closure` and `controlled-read`. `devtools render all --check` exit 0, **0** lines matching `out of sync` (grepped, not inferred). Focused suites green across `tests/unit/archive`, the AST schema, field map, metadata, continuation parity, and the query exec laws. Broad selection of 2163 tests: **10 non-pass, all inherited**, proven by detached checkout of `origin/master` inside this worktree. One of those I'd have miscounted: `test_descriptor_runtime_transform_units_reject_aggregate_pipeline` is a **skip** (`got empty parameter set`), not a failure. ## Residuals - **`_LARGE_POPULATION` is pinned to the historically deleted bound (50,001), not to "any bound".** A future implementation introducing a cap *above* 50,000 would not be caught. No test can catch an unknown bound; the declared condition is the concrete one. - The 50k exactness test costs ~11 s. The size is deliberate — anything smaller stays green under mutation A. - `to_payload()` is derived, but four escape hatches remain in the declarations (`omit_when` callables ×2, read-only `payload_*` properties ×4). Declared per field, so no mirror exists, but they are hand-written logic. - `WithUnitWindow`, `SessionQueryPipeline` and `SessionQueryTerminalStage` keep hand-written `to_payload()` — not part of the published AST schema, so converting them would widen the diff without removing a mirror. Stated, not hidden. - Two follow-ups filed separately: `test_schema_closure.py`'s `IN_CLOSURE` roster is **stale at master** (`daemon/write_coordinator.py` left the closure and the test was not updated — 3 reds unrelated to this swap), and `analysis/orchestration_evidence.py:140` compares a possibly-`None` count with `>` (6 MCP reds, already filed as polylogue-w4hfb). Closes polylogue-o21.5, polylogue-o21.7, polylogue-o21.8. polylogue-o21.6 untouched. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added named aggregate metrics, including count, sum, average, minimum, maximum, and percentile calculations. * Added grouping support and paginated aggregate results across the Python API, HTTP API, MCP, and CLI. * Aggregate results are now exact across complete matching datasets, including large result sets and NULL values. * Added support for aggregate stages and metric results in API schemas and generated client types. * Expanded field resolution for grouping and bracket predicates across query unit types. * **Documentation** * Updated aggregate metric documentation with exact calculation and percentile behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
) ## Summary `events` and `raw` were the two `IN_PROCESS_READ_VIEWS` that **#5370 could not move for contract reasons rather than effort**. Both are fixed here; the ratchet drops **8 → 6**. Taken over directly after the lane died mid-run on a network error with uncommitted work. ## Why they could not move as they were **`events`** accepted `--limit` and reported the **clipped** row count as its own `total`. An evidence kind is answered whole, so lowering it unchanged would have made `session.read` report `complete=true` for a truncated body — which `SessionReadResult`'s validator refuses outright. Nothing in the payload separated a cut body from a finished one. **`raw`** is genuinely windowed, with a real limit/offset and a real total — but `operations/transcript_window.py` owns the **message** window vocabulary (`TRANSCRIPT_WINDOW_PROJECTION`, `session-owner-v1`). Minting artifact continuations into that family is exactly the mixing the family exists to prevent: **a token that resumes "artifacts 50..100" while carrying the message projection is readable by a reader that will compose messages with it.** ## The contract `operations/evidence_window.py` declares a **second continuation family, per relation rather than per surface**. A family names three things and nothing else: - the `session.read` kind it pages, - **its own projection token** — what makes a foreign continuation refusable *by name* instead of silently resumable, and - the stable order the relation is windowed in, because a continuation is only meaningful against an order the reader guarantees. It deliberately does **not** own the window arithmetic or the snapshot binding. `next_offset` / `complete` / token minting and the before-and-after epoch check come from `transcript_window`'s `window_result` / `bind_snapshot`, which take a transaction and know nothing about messages. **An off-by-one or a missing epoch revalidation therefore stays one defect across both families instead of two independent ones.** The separation that matters is the vocabulary. The bound is declared and reported, never silent: `total` is the relation's own row count, `returned` is the page's, and a page that does not reach the total mints a continuation instead of claiming completeness. ## Anti-vacuity — executed Make the events reader return the page length as the relation total (`return rows, len(rows)`) and **both** new tests go red with `assert None` on the continuation — because a page that believes it is whole mints no token. A `limit` at or above the relation's row count cannot witness this, so the window in the test is strictly smaller. The second test asserts the families refuse each other: a continuation minted for `events` is rejected when presented to `transcript`. ## Two doubles removed rather than repaired `tests/unit/cli/test_messages.py` drove `run_raw` and `run_session_events` through a `_FakeApi` with `patch("polylogue.api.Polylogue.open")`. Those functions no longer exist — both views route through the declared operation — and **per #5354's precedent a double could not have proven the route in any case.** Their subject is covered by the new contract tests and the existing golden-parity suite. ## Landing window **All changed production files measure `out`; the derived identity does not move** — this can land during a rebuild. That held because a new operation declaration goes in `read_contracts.py` (which exists precisely so it stays off the boundary) rather than in `surfaces/payloads.py`, which is **IN**. ## Verification `devtools verify --quick` — exit 0, all gates. `devtools render all --check` — exit 0, zero `out of sync`. `devtools test` over the evidence readers, the execution-route ratchet, continuation-surface parity and the daemon golden parity — exit 0. The evidence-reader module runs 5 passed including the two new contract tests. ## Residual **Six views remain in-process, and each needs its own operation declaration rather than a `session.read` kind**: `dialogue`, `temporal` and `chronicle` accept query sets rather than one exact reference; `effective_context` is a compaction-aware replay with `--at-position`; `neighbors` and `correlation` reach different subsystems. A harness note for anyone adding tests here: `tests/conftest.py` rewrites any nodeid over 100 characters into a digest form, so a long test name becomes **unselectable by id** and reports as `not found` while the module imports fine. Both new names are kept under the threshold. Advances polylogue-r3cuz (8 of 11 moved). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
|
Closing out open Codex review threads on this PR (evidence checked against master at ef10e59):
Resolving the fixed, stale and refuted threads; tracked threads stay open. |
|
Closing out open Codex review threads on this PR (evidence checked against master at c950478):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
|
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
Moves
read --view messagesonto the daemon, and makes the controlled-readboundary an executable gate rather than prose.
The bead's design was not implementable as written
fko9.3says to lower the messages view ontosession.read's transcriptkind. Doing that would have:
MessageRowEnveloperows (tokens, model, timestamp,attachment refs, ~32 fields) with the transcript kind's 5-field identity
projection — a silent output regression on
--format json; andoperation="session.read",projection
session-read-v1) than the one this view belongs to(
sessions.read/session-owner-v1), breakingtest_continuation_surface_parity.py, which requires a token minted byread_transcript_windowto resume on the CLI.Built instead:
session.readgains amessageskind whose handler is framedby
operations/transcript_window.py::read_transcript_window_sync— the sharedwindow owner — so both the continuation family and the rich row vocabulary are
preserved. It refuses a filtered window by name rather than answering with
unfiltered rows, because the pinned page reader has no filter vocabulary.
Two further bead claims did not hold:
run_read_messagesdid not compute viaapi.iter_messages(that was only the--to filewriter path), and the sibling--view summarydoes not printserved-by:on the cited input — line 924 isthe ordinary find/list page path, and
--id <sid> read --view summaryreturnsthrough
_emit_session_resultwell before it. No read view printedserved-by:at the base.
t46.11: the claimed defect does not reproduce, and the rule already half-existed
vclez's "six productionArchiveStore.open_existing()reads outside thecontrolled boundary" cannot be reproduced at any head measured — there are
zero. The guard that did exist licensed any
read_only=Falseopen with nostated reason, which is exactly why the survivors could not be audited and why a
count of "six" could be asserted without contradiction.
The rule, now a gate in the quick set
The load-bearing check is not "is this open read-only". It is that a site
declared a writer still passes
read_only=False— the realistic silentregression is a declared writer losing its explicit write mode and becoming an
uncontrolled read while its census row still reads "writer". Which module may own
the boundary is policy (
read_boundary_owners), so a new uncontrolled readcannot license itself by claiming to be the boundary.
Census — every survivor classified
26 direct opens: 3 read-boundary owners, 23 licensed writers, 0 uncontrolled
reads, 5 recorded debt. Reproduce with
devtools gate controlled-read --json.Debt named rather than licensed: four
api/archive.pyfacade mutations taking thewriter lease in-process instead of admitting through the daemon write coordinator
(sole-writer completion work, not an alternate write policy), and
cold_build.py::active_index_generation_is_empty, which takes the writer leaseto answer a question that is a read — its writable open is deliberate because it
bootstraps the durable tiers, but separating the bootstrap from the question would
let the question go through the read boundary.
Deleted
tests/unit/archive/query/test_read_surface_control.py: the gateenforces its rule and more, so keeping it would be a second, weaker restatement.
The doctrine sheet's open question "process-level sole writership is not proven by
the writer gate" is updated — the census is the evidence that question asked for,
while staying explicit that it records rather than enforces.
Two defects found and fixed on the way, both outside the bead text
RootModeRequesthad no owner for "which configuration am I reading".Routes read
request.params["_config"]directly, which isNonefor everyinvocation the root callback does not pin — i.e. every real
polylogue read.run_read_hookscarried the same latent bug.operation_kernel._execute_directlyflattened everyValueErrorto"invalid_request";daemon_executionusedcode=str(exc)— the whole messageas the code. A stale continuation therefore could not be reported as
query_continuation_stalethrough the operation route.Anti-vacuity — executed against the real tree
daemon_disabled = True)AssertionError: served-by: direct (23ms)served-byidentityAssertionError: served-by: daemon (uds, 28ms)— reds two testsopen_existingto an unlisted filecontrolled_read_site_undeclared, gate exit 1read_only=Falsefrom one declared writercontrolled_read_writer_is_not_explicit (declared a writer but opens without read_only=False, so it is an uncontrolled read), gate exit 1Five more are encoded as unit tests over synthetic trees (self-declared boundary,
stale declaration, no boundary at all, unknown role, renamed owner path). Nothing
is reasoned-not-executed.
Schema closure — all 25 changed files
out, measured at the real basepolylogue/surfaces/payloads.pyis IN and was deliberately not touched —read_contracts.pyexists precisely so a new operation declaration does not movethe identity, and the new kind lives there.
archive_tiers/archive.pyandwrite.pyare IN and were avoided by discovering thatArchiveSessionEnvelopealready carrieslineage_complete/lineage_truncation_reasonthroughread_archive_session_page, so the truncationsignal survives the move with no storage edit. That is what kept this leaf off
the rebuild boundary.
Verification
devtools verify --quick— exit 0, 25/25 gates, including the newgate controlled-read ... ok (4.4s)devtools render all --check— exit 0,grep -c "out of sync"= 0devtools gate controlled-read— exit 0, 26 observed, 0 violationstest_daemon_golden_parity.py5 passed (incl. the new messages parity testagainst a real UDS daemon),
test_messages.py18,test_verify_controlled_read.py11,test_archive_query.py111devtools test tests/unit/cli— 3166 passed / 37 failed, all inherited,proven by a detached checkout at the branch base inside the same worktree (406
passed / 38 failed, identical node-id set; the 38th is outside
tests/unit/cli)Two reds were mine and are fixed, not excused: a pinned read-view partition
that moved by design, and two
test_archive_query.pytests that appeared afterthe rebase (new from #5350–#5353) monkeypatching a symbol this branch renamed.
That is why the post-rebase full-directory rerun mattered.
Residuals
--format jsonblock payloads narrow slightly.content_blocksentrieslose explicit-null keys. Cause: the daemon route hydrates through
archive_block_to_domain, which deliberately dropsNoneso an absent fieldstays absent rather than becoming an explicit null in every public block payload;
the old async decode path emitted them. Measured empirically as the only
field difference between the two projections, and
render all --checkis cleanso no committed schema changed. Strictly narrowing and consistent with declared
policy — named rather than buried.
than the bound is a typed refusal naming the limit, where the in-process reader
had none.
--fulland any--limitabove 200 compose from bounded windows, sorealistic cases are unaffected; a single
--limit 1500on very large messagescould now refuse.
ArchiveStore.open_existing(...). An openreached through
getattr, an alias, or a stored callable is not resolved —stated in the module docstring, not hidden.
tests/unit/cli/test_messages.pylost its_FakeApimessage-path tests: theymocked
Polylogue.open, which the route no longer uses, so a double could nothave proven the route. Replaced with seeded real archives via
SessionBuilder,including a genuine prefix-sharing fork with a hard-deleted parent branch point.
Closes polylogue-fko9.3, polylogue-t46.11.
🤖 Generated with Claude Code
https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
Summary by CodeRabbit
New Features
Bug Fixes
Documentation