Repository navigation
fix: Serve stale-gated session pages through the cli.query operation - #5102
Conversation
`_daemon_session_page_supported` refused the declared `cli.query` read for thirteen groups of inputs and fell back to a second, local `ArchiveStore` implementation of the same query. Most of those refusals were stale: the operation handler compiles its spec with the same `SessionQuerySpec.from_params` the local branch uses, so cursors on ranked pages, sort/reverse, Boolean predicates, `since_session_id`, `project`, `typed_only`, `message_type`, `conv_id` and `latest` are all served there. Deleting the refusals exposed five real differences between the two routes, all fixed on the operation side: - `total_unit` named the unresolved `spec.root` instead of the root filter that actually ran, so a default `find` reported "sessions (top-level and subagent/branch children)" over a top-level-only page. - session rows serialized explicit nulls where every other CLI payload dumps the same `SessionListRowPayload` with `exclude_none=True`. - timestamps were re-rendered as `+00:00` by the domain round-trip where the archive (and the CLI) spell UTC as `Z`. - rows carried no `words` field at all and reported `terminal_state` as null rather than the vocabulary's `unknown`. - `spec.latest` was honoured only on the ranked path, so `--latest` returned a full page through the operation. The parameter forwarder is now a projection onto the recognised spec parameters rather than a hand-maintained rename table: the old table renamed `filter_has_paste`/`filter_has_tool_use`/`filter_has_thinking` to keys `from_params` does not read, silently dropping `--has-paste`, `--has-tool-use` and `--has-thinking`, and joined the query terms into one string, re-tokenising quoted phrases. Vector/hybrid retrieval, list-mode cursors, `exclude_text`, aggregates, `sample`, `with` projection, streaming and exact-ref reads keep executing locally; each remaining refusal now names the capability or the unresolved contract that holds it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reachedNext included review available in 17 minutes. View limit detailsLimit details: You’ve used the included review currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (6)
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
Step S2 of the CLI unification: declare the read operations the CLI
still has
no operation for, so no CLI read needs a local executor. Declaration
only —
S3 migrates the call sites.
- `query.aggregate` (count / stats / stats_by)
- `session.read` (windowed transcript reads with a snapshot-bound
continuation)
- `session.reference` (bare `from <ref>` operands)
- `cli.query` extensions: `sample`, `latest`, and the `with <units>`
projection
## Problem
Five of the thirteen rejection groups in
`_daemon_session_page_supported`
(`cli/archive_query.py:1293-1309`) name real gaps rather than stale
caution:
aggregates, exact-ref transcript reads, `--stream`, `--sample`, and the
`with`
projection have no declared operation, so those inputs are always served
by the
local `ArchiveStore` branch. The reference pipeline
(`archive_query.py:211-288`)
is a second local executor with no operation at all. Until those exist,
S3
cannot delete the local branch without losing capability.
## Solution
- `polylogue/operations/read_contracts.py` (new) holds the
request/result
models. It is **OUT** of the derived-schema identity closure (D5);
`surfaces/payloads.py` is IN, so declaring them there would have moved
the
archive's schema identity for a CLI-only change.
- Handlers in `daemon_reads.py` call the existing shared executors:
`archive.stats`/`stats_by`/`count_sessions`/`count_search_sessions`
behind
`spec_session_filter_kwargs` + `stats_filter_kwargs`,
`read_session_page` +
`session_detail_envelope_from_domain`, `fetch_attached_units`, and
`resolve_ref_operand` with `DurableRefResolver` over the pinned reader's
paths. No handler carries its own query logic.
- **8 MiB bound.** `session.read` is windowed by construction rather
than by
discovery: the handler composes only `[offset, offset+limit)` at the
storage
layer, mints a `QueryContinuation` bound to the archive epoch for the
next
window (reusing `archive/query/transaction.py`, which is IN the closure
and
is therefore only consumed, never edited), and refuses a window whose
serialized size exceeds `MAX_OPERATION_RESULT_BYTES` with a message
naming
the smaller limit. `complete`/`next_offset`/`continuation` are checked
against each other by the result model, so a truncated read cannot
report
itself whole.
- The `with <units>` projection rides beside the canonical list envelope
(`attached_units`) rather than inside it: `SessionListResponse` forbids
extras and lives in the closure. `QueryResult`'s validator (in
`daemon_protocol.py`, OUT) validates the projection's shape and hands
the
envelope the rest.
- `polylogue/cli/operation_bindings.py` (new) is the registry diff the
design
names: every `DaemonOperationSpec` is bound to a CLI lowering +
renderer,
listed as pending adoption with the step that adopts it, or listed as
CLI-external with the reason. The three new operations arrive bound, not
pending.
## Verification
```
devtools test tests/unit/daemon/test_daemon_operation_route.py tests/unit/operations/
-> PASSED exit=0 diagnosis=pytest_passed
devtools verify --quick -> all 15 gates ok, exit 0
devtools gate layering -> {"violations":[],"count":0}, exit 0
devtools render all --check -> exit 0, zero "out of sync" lines
```
Closure (`devtools schema closure`) for every file this PR touches:
```
out polylogue/operations/read_contracts.py
out polylogue/operations/daemon_protocol.py
out polylogue/operations/daemon_reads.py
out polylogue/cli/operation_bindings.py
```
No file in this change is in the closure; the derived schema identity
does not
move and no reconvergence is required.
Anti-vacuity, verified by reverting and observing the failure:
| Reverted | Observed |
| --- | --- |
| aggregates stop honouring an empty text selection (`empty_selection =
False`) |
`test_text_selection_scopes_the_aggregate_to_matched_sessions`: `assert
2 == 0` |
| `session.read` always mints a continuation |
`test_final_window_carries_no_continuation`: `TypeError: '<' not
supported between instances of 'NoneType' and 'int'` in
`QueryTransactionRequest.__post_init__` |
| drop `session.read` from the binding registry |
`test_every_declared_operation_is_classified_exactly_once`: `assert
('session.read',) == ()`;
`test_read_operations_declared_for_the_cli_are_bound_not_pending`:
`OperationBindingError: session.read is not classified` |
| drop the `SessionReadResult` completeness invariant |
`test_a_window_cannot_claim_completeness_and_a_next_offset`: `Failed:
DID NOT RAISE OperationResultContractError` |
`devtools test tests/unit/cli/test_archive_query.py
tests/unit/cli/test_daemon_operation_transport.py
tests/unit/cli/test_json_envelope_contract.py`
fails on exactly one test,
`test_confirmed_delete_uses_an_unbounded_daemon_wait`
(`auth_token` lambda vs `None`) — an inherited failure from #5043, owned
elsewhere and untouched here. (Checked pre-rebase; #5043's fix may since
have
landed.)
## Residuals
- Rebased onto `513c8873a` after S0 (#5094) and #5102 landed mid-flight.
The
aggregate and `cli.query` handlers go through the delegating
`_cli_query_spec`/`_lower_cli_query_params`, which S0 repointed at
`operations/query_lowering.py`, so there is one lowering, not two. The
conflict resolution dropped my duplicate `latest` clamp in favour of the
one
#5102 landed, and kept #5102's `_session_list_row`.
-
`tests/unit/daemon/test_daemon_operation_route.py::test_cancelled_long_delete_retains_writer_until_blocked_apply_releases`
failed once on a 25 ms `operation.await` deadline race and passed on
rerun
and on the file alone. Pre-existing timing flake, untouched by this
change.
- `session.reference` opens the durable user tier by path
(`archive.user_db_path`, `archive.index_db_path` from the pinned reader)
rather than through the pinned connection, mirroring the CLI route it
replaces. The generation is the pinned one; the connection is not.
- The `ProjectionSpec` → `ContentProjectionSpec` mapping covers the
block
kinds `body_policy` produces (tool calls, tool outputs, reasoning). The
full
read-view classification is D3/S8's table, not this step's.
- `session.lineage`, `context.compile` and the write operations in §2.3
are
not in this step (S9/S10).
- `completion` and `ingest` are declared but still unreached from the
CLI; they
are recorded in `CLI_PENDING_ADOPTION` with their adopting steps (S7,
S11).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
Step S1 of the CLI unification (
polylogue-9hgth).archive_query._daemon_session_page_supportedrefused the declaredcli.queryread for thirteen groups of inputs and fell back to a second, localArchiveStoreimplementation of the same query. Most of those refusals were stale. This deletes them, forwards the parameters the operation needs, and fixes every behavioural difference the deletion exposed — on the operation side in each case.Five refusals remain, each now naming the capability or the unresolved contract that holds it. Two the design called stale are not — see Residuals.
Problem
_daemon_session_page_supportedrejected cursors,sort/reverse, vector/hybrid retrieval, Boolean predicates,since_session_id,project,typed_only,message_type,conv_idandlatest. The operation handler compiles its spec with the sameSessionQuerySpec.from_paramsthe local branch uses, so most of those it already serves. Every refusal was also a place a behavioural difference between the two routes could hide, andtests/unit/cli/test_daemon_golden_parity.py:115was red onmasterproving two of them (polylogue-v1mnm).The companion defect was the forwarder.
_daemon_session_query_paramswas a hand-maintained rename table that:filter_has_paste/filter_has_tool_use/filter_has_thinkingtohas_paste_evidence/has_tool_use/has_thinking, none of whichSessionQuerySpec.from_paramsreads — so--has-paste,--has-tool-useand--has-thinkingwere silently dropped on the default (daemon) route and the page silently widened;Solution
Gate (
cli/archive_query.py). The stale refusals are gone. What remains, each with its reason in code: aggregates (stats_only/stats_by/count_only),open_result, mutations and--stream,sample,with-projected units, exact-ref reads (already refused above the gate bycompiled_spec.session_id), list-mode cursors, and vector/hybrid retrieval.Forwarder (
_cli_query_operation_params). Now a projection of the root request ontoSessionQuerySpec._RECOGNIZED_PARAMS, so the two routes compile one spec by construction rather than by a table someone has to maintain. Query terms go over as the tuple, not a joined string.Every mismatch found, and which side was fixed
total_unit: operation said "sessions (top-level and subagent/branch children)", direct said "top-level sessions"_archive_query_kwargs— which the operation itself calls — resolvesrootthroughresolve_default_root_filter; the label read the unresolvedspec.root.session_count_unit_label's own docstring says it mirrors the resolved filter.daemon_reads._query_payload)items[].actions.*: operation serializeddisabled_reason/inspect_path/repair_pathas nulls, direct emitted the compact formSessionListRowPayloadwithexclude_none=True(_summary_payload), as does every other CLI JSON producer. Applied to rows only — the search envelope keeps its explicit nulls, because a vector page'stotal: nullis an honest "not reported".created_at/updated_at: operation emitted…+00:00, direct emitted…ZZ.ArchiveStore._iso_from_msis what renders the archive's millisecond columns, and the CLI passes that string through; the operation's domain round-trip re-rendered it viadatetime.isoformat().wordsabsent andterminal_state: nullin every operation rowwordsfrom the summary's word count;terminal_stateresolved through the sharedsession_rowprojection, whose vocabulary has an explicitunknownmember. A null there is indistinguishable from an absent field.--latestreturned a full page through the operationlatestis applied byquery_spec_to_plan, which only the ranked path calls; the list path reacheslist_summarieswithout it.--has-paste/--has-tool-use/--has-thinkingsilently dropped on the daemon routefilter_has_*, which is whatfrom_paramsreads.next_cursordiscarded by the CLI's daemon-search rendererbuild_search_envelope→build_search_cursor);_emit_daemon_search_payloadhardcodedNone, making ranked pages non-continuable by transport.--exclude-textclick.UsageErrorwith two distinctnear:id:/near:"text"messages; the operation raises the typedEmbeddingRetrievalNotReadyError. Their ranked/fused hit order has also never been compared on a seeded embeddings corpus.Number 3 belongs in
surfaces/payloads.session_list_envelope_from_summary, which would fix it for every surface — but that file is IN the derived-schema identity closure, so it is applied at the operation boundary instead rather than forcing a reconvergence for a timestamp spelling. Same reason_RECOGNIZED_PARAMSis imported under its private name instead of gaining a public alias inarchive/query/spec.py.Tests
tests/infra/surface_differential.pygains thecli-directsurface (polylogue --no-daemon find …, the localArchiveStorebranch) beside the existingclisurface (the operation route), andSURFACE_NAMES/FULL_COVERAGE_SURFACESinclude it — so both CLI legs are now compared against the executable reference model on every generated request, rather than against each other.tests/unit/cli/test_query_route_differential.pyis the per-flag differential: one seeded archive, one flag, both routes, whole-envelope comparison.test_flag_reaches_the_operation_routeasserts the operation actually answered, so a case the gate still refuses cannot pass by self-comparison;test_every_case_changes_the_answerasserts each flag selects, orders or bounds something different from the unflagged page, so a forwarding bug that widened every filter back to the whole archive cannot pass either.Four tests in
test_query_exec_laws.pyassert the exact SQL kwargs the local branch builds (including itslimit + 1pagination probe). They are pinned to it with"no_daemon": Trueand a comment pointing at the differential, rather than being rewritten to assert the other route's kwargs.Verification
→
4 of 300failed, all four red on7f073d3d2(master) before this branch, verified by re-running there:test_plain_cli_snapshots.py::{test_json_read_all_snapshot,test_json_status_snapshot,test_facets_command_json_matches_analyze_facets}andtest_archive_query.py::TestEmitDeleteMachineModeNoPrompt::test_confirmed_delete_uses_an_unbounded_daemon_wait.test_daemon_golden_parity.py::test_find_list_json_parity_between_direct_and_daemonwas red on master and is green here — that is mismatches 1–4 closed.→
PASSED. This is the load-bearing one: three seeded corpora, generated requests, five surfaces including the newcli-direct, compared to a computed oracle rather than to each other.→ all 15 gates ok (format, lint, mypy, generated-surfaces, layering, patterns, doc-commands, schema-manifest, oracle-integrity, testmon-selection, consumer-reachability, test-packages, timestamp-doctrine, durable-enum-checks, schema-privacy).
→
"violations":[],"count":0,"status":"passed". Baseline unchanged; several entries shrank.→ no matches.
Anti-vacuity, checked by mutation
Each fix was reverted in place and
devtools test tests/unit/cli/test_query_route_differential.pyre-run. The unmutated selection is green; two reverts were completed before the workstation pytest pool became contended:filter_has_thinking/filter_has_tool_use)exit=1) — thehas-thinking/has-tool-usecasessort/reverse/projectexit=1) — thesort/reverse/project-refscasesThe remaining reverts (restore the stale rejections; unresolved root filter in
total_unit; explicit nulls in the row; ignorespec.latest; forwardexclude_text) were not run to completion — the sweep was still queued behind other sessions' runs and was stopped rather than left mutating the checkout. Each targets a case whosebreaks_ifnames it, and restoring the rejections is additionally caught structurally:test_flag_reaches_the_operation_routeassertssource == "daemon", which a refused request cannot produce. That is weaker evidence than the two measured reverts, and is stated as such.Closure
This PR does not move the derived-schema identity.
devtools schema closurereportsoutfor every file touched:No rebuild ordering constraint and no seeded-fixture-cache invalidation. Two fixes were deliberately applied at the operation boundary instead of their natural home (
surfaces/payloads.py,archive/query/spec.py) precisely to keep it that way; both are recorded above as work for S4, which owns row shape.Residuals
latest. It called both stale on the evidence of_search_payloadandquery_spec_to_plan. Both of those are the ranked path. The operation's list path has no cursor machinery at all and reachedlist_summarieswithoutlatest.latestis fixed here; list-mode cursors remain refused, and are a genuine gap S2 should declare alongside the others.--exclude-text(row 8) is a live product defect on both routes, pinned by a test and withheld from the forwarder. It needs the search-path owner:archive_search_hitsdoes not applynegative_terms.--lateststill differs innext_cursorbetween routes: the local branch forceslimit = 1and then fetcheslimit + 1for its pagination probe, so it mints a continuation cursor for a query meaning "exactly one". The operation'sNoneis right; the case ignores those two keys with that reasoning stated.message_typeis un-gated but has no root CLI option, so nothing here exercises it directly; it reaches the spec only through internal callers.test_json_read_all_snapshot's remaining drift is anoutcomeblock missing from the stored snapshot — unrelated to the null/total_unit/timestamp components this PR fixed, so the snapshot is left for whoever owns that drift.🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK