Skip to content

fix: Serve stale-gated session pages through the cli.query operation - #5102

Merged
Sinity merged 1 commit into
masterfrom
feat/cli-query-stale-gate-s1
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
feat/cli-query-stale-gate-s1

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Step S1 of the CLI unification (polylogue-9hgth). archive_query._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. 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_supported rejected cursors, sort/reverse, vector/hybrid retrieval, Boolean predicates, since_session_id, project, typed_only, message_type, conv_id and latest. The operation handler compiles its spec with the same SessionQuerySpec.from_params the 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, and tests/unit/cli/test_daemon_golden_parity.py:115 was red on master proving two of them (polylogue-v1mnm).

The companion defect was the forwarder. _daemon_session_query_params was a hand-maintained rename table that:

  • renamed filter_has_paste / filter_has_tool_use / filter_has_thinking to has_paste_evidence / has_tool_use / has_thinking, none of which SessionQuerySpec.from_params reads — so --has-paste, --has-tool-use and --has-thinking were silently dropped on the default (daemon) route and the page silently widened;
  • joined the query terms into one string, re-tokenising a quoted phrase;
  • carried none of the newly-ungated parameters, so deleting the refusals alone would have dropped them too.

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 by compiled_spec.session_id), list-mode cursors, and vector/hybrid retrieval.

Forwarder (_cli_query_operation_params). Now a projection of the root request onto SessionQuerySpec._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

# Mismatch Canonical answer Side fixed
1 total_unit: operation said "sessions (top-level and subagent/branch children)", direct said "top-level sessions" The label names the filter that ran. _archive_query_kwargs — which the operation itself calls — resolves root through resolve_default_root_filter; the label read the unresolved spec.root. session_count_unit_label's own docstring says it mirrors the resolved filter. operation (daemon_reads._query_payload)
2 items[].actions.*: operation serialized disabled_reason/inspect_path/repair_path as nulls, direct emitted the compact form Compact. The direct branch dumps the very same SessionListRowPayload with exclude_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's total: null is an honest "not reported". operation
3 (new) created_at/updated_at: operation emitted …+00:00, direct emitted …Z Z. ArchiveStore._iso_from_ms is what renders the archive's millisecond columns, and the CLI passes that string through; the operation's domain round-trip re-rendered it via datetime.isoformat(). operation
4 (new) words absent and terminal_state: null in every operation row words from the summary's word count; terminal_state resolved through the shared session_row projection, whose vocabulary has an explicit unknown member. A null there is indistinguishable from an absent field. operation
5 (new) --latest returned a full page through the operation latest is applied by query_spec_to_plan, which only the ranked path calls; the list path reaches list_summaries without it. operation
6 (new) --has-paste / --has-tool-use / --has-thinking silently dropped on the daemon route The CLI's parameter names are filter_has_*, which is what from_params reads. forwarder (CLI)
7 (new) ranked next_cursor discarded by the CLI's daemon-search renderer The operation mints it (build_search_envelope → build_search_cursor); _emit_daemon_search_payload hardcoded None, making ranked pages non-continuable by transport. CLI renderer
8 (new, unresolved) --exclude-text Three answers, none chosen: the operation applies the post-filter to a list page; on a ranked page it applies it to the count but not the hits, reporting a total smaller than the page it returned; the local branch ignores it everywhere. neither — the parameter is deliberately withheld from the forwarder so both routes keep today's behaviour, and a test pins that
9 (new, unresolved) vector/hybrid refusal contract The local branch raises click.UsageError with two distinct near:id:/near:"text" messages; the operation raises the typed EmbeddingRetrievalNotReadyError. Their ranked/fused hit order has also never been compared on a seeded embeddings corpus. neither — the rejection is kept rather than silently changing the CLI's refusal contract

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_PARAMS is imported under its private name instead of gaining a public alias in archive/query/spec.py.

Tests

tests/infra/surface_differential.py gains the cli-direct surface (polylogue --no-daemon find …, the local ArchiveStore branch) beside the existing cli surface (the operation route), and SURFACE_NAMES/FULL_COVERAGE_SURFACES include 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.py is the per-flag differential: one seeded archive, one flag, both routes, whole-envelope comparison. test_flag_reaches_the_operation_route asserts the operation actually answered, so a case the gate still refuses cannot pass by self-comparison; test_every_case_changes_the_answer asserts 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.py assert the exact SQL kwargs the local branch builds (including its limit + 1 pagination probe). They are pinned to it with "no_daemon": True and a comment pointing at the differential, rather than being rewritten to assert the other route's kwargs.

Verification

devtools test tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_daemon_operation_transport.py \
             tests/unit/cli/test_daemon_golden_parity.py tests/unit/cli/test_query_route_differential.py \
             tests/unit/cli/test_archive_query.py tests/unit/cli/test_json_envelope_contract.py \
             tests/unit/cli/test_plain_cli_snapshots.py

→ 4 of 300 failed, all four red on 7f073d3d2 (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} and test_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_daemon was red on master and is green here — that is mismatches 1–4 closed.

devtools test tests/integration/test_reference_model_differential.py

→ PASSED. This is the load-bearing one: three seeded corpora, generated requests, five surfaces including the new cli-direct, compared to a computed oracle rather than to each other.

devtools verify --quick

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

devtools gate layering

→ "violations":[],"count":0, "status":"passed". Baseline unchanged; several entries shrank.

devtools render all --check | grep -i "out of sync"

→ no matches.

Anti-vacuity, checked by mutation

Each fix was reverted in place and devtools test tests/unit/cli/test_query_route_differential.py re-run. The unmutated selection is green; two reverts were completed before the workstation pytest pool became contended:

Reverted fix Result
forwarder back to the rename table (drop filter_has_thinking/filter_has_tool_use) selection goes red (exit=1) — the has-thinking/has-tool-use cases
stop forwarding sort/reverse/project selection goes red (exit=1) — the sort/reverse/project-refs cases

The remaining reverts (restore the stale rejections; unresolved root filter in total_unit; explicit nulls in the row; ignore spec.latest; forward exclude_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 whose breaks_if names it, and restoring the rejections is additionally caught structurally: test_flag_reaches_the_operation_route asserts source == "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 closure reports out for every file touched:

out  polylogue/cli/archive_query.py
out  polylogue/operations/daemon_reads.py
out  tests/unit/cli/test_query_exec_laws.py
out  tests/unit/cli/test_query_route_differential.py
out  tests/infra/surface_differential.py
out  tests/integration/test_reference_model_differential.py

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

  • The design's §1.4 is wrong about cursors and latest. It called both stale on the evidence of _search_payload and query_spec_to_plan. Both of those are the ranked path. The operation's list path has no cursor machinery at all and reached list_summaries without latest. latest is fixed here; list-mode cursors remain refused, and are a genuine gap S2 should declare alongside the others.
  • Vector/hybrid is not stale either (row 9). Kept refused, with the reason in code.
  • --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_hits does not apply negative_terms.
  • --latest still differs in next_cursor between routes: the local branch forces limit = 1 and then fetches limit + 1 for its pagination probe, so it mints a continuation cursor for a query meaning "exactly one". The operation's None is right; the case ignores those two keys with that reasoning stated.
  • message_type is un-gated but has no root CLI option, so nothing here exercises it directly; it reaches the spec only through internal callers.
  • Four inherited failures listed under Verification are untouched. test_json_read_all_snapshot's remaining drift is an outcome block 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

`_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
@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.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 17 minutes.

Check out review usage here.

View limit details

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

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 3efc579c-64c6-4245-8cd1-f52558655657

📥 Commits

Reviewing files that changed from the base of the PR and between 8047383 and 940078e.

📒 Files selected for processing (6)
  • polylogue/cli/archive_query.py
  • polylogue/operations/daemon_reads.py
  • tests/infra/surface_differential.py
  • tests/integration/test_reference_model_differential.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/cli/test_query_route_differential.py

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 513c887 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the feat/cli-query-stale-gate-s1 branch September 14, 2026 16:55
Sinity added a commit that referenced this pull request Sep 14, 2026
## 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]>
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