Repository navigation
refactor: Share one query lowering and type daemon client errors - #5094
Conversation
Move the --lexical/--semantic desugaring and the terms-to-expression step into polylogue/operations/query_lowering.py so the Click root request and the daemon's in-process reads lower one parameter map identically, and extract the daemon client exception types into polylogue/operations/daemon_errors.py so OperationKernel.execute branches on isinstance instead of comparing type(exc).__name__. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Cover the two branches that replaced type(exc).__name__ matching: a subclass of DaemonMutationIndeterminateError under a different name must still be typed indeterminate, and a size protocol error must still report result_too_large. 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 33 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 (9)
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]>
The rebase of this branch onto master dropped the whole polylogue/daemon_client.py hunk, taking _reject_foreign_peer, the connect() call site and DaemonSocketOwnershipError with it. The test module still imported that name, so it failed to import: devtools test returned exit=2 with zero tests selected, and none of the six assertions had ever run. Restores the client half against the layout #5094 introduced: the exception is declared in polylogue/operations/daemon_errors.py alongside its siblings and re-exported from daemon_client, rather than reintroducing a definition in the transport module and re-splitting the seam that PR unified. The test fakes in tests/unit/cli/test_daemon_client.py already grew their connect() method on master, so the inherited failure this branch previously carried a fix for is gone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Summary
Step S0 of the CLI unification: one shared lowering for CLI-shaped query
params, and typed daemon-client exceptions the operation kernel can import.
Problem
--lexical/--semanticdesugaring and the terms→expression step existedtwice:
cli/root_request.py:37-62(Click root) andoperations/daemon_reads.py:_lower_cli_query_params. Two copies of oneselection contract: a change to either gives the two surfaces different rows
for the same parameter map, silently. Nothing tested that they agreed.
cli/operation_kernel.py:117-124classified daemon transport failures bytype(exc).__name__ == "DaemonMutationIndeterminateError". A renamed orsubclassed exception demotes an accepted-but-unreceipted mutation to a
retryable
daemon_transport_error— the CLI would then be free to re-issuea write that may already have landed. Reverting to the name match and running
the new test shows exactly that:
polylogue.cli.operation_kernel.OperationFailedError: daemon_transport_error: daemon outcome is indeterminate after POST /api/operation.The kernel could not import the classes because they lived in
daemon_client.py, which it must not pull in.Solution
polylogue/operations/query_lowering.pyownscoerce_terms,desugar_retrieval_flags,lower_query_params,lower_cli_query_params,cli_query_spec, and re-exportsexpression_from_query_terms. Refusalsraise
QueryLoweringError(ValueError)carrying a separatecli_message, sothe Click root keeps its flag-named
UsageErrorwording and protocol callerskeep the transport-neutral
ValueErrortext they had. No message changed.RootModeRequest._from_normalized_paramsanddaemon_reads._lower_cli_query_params/_cli_query_specnow delegate; theduplicate bodies are deleted.
daemon/http.pyimportsexpression_from_query_termsfrom the new module instead of the privatecli.root_request._expression_from_query_termsalias, which is gone.polylogue/operations/daemon_errors.pyholdsDaemonResponseError,DaemonMutationIndeterminateError,DaemonOperationProtocolError,DaemonOperationRejectedError(+ theDaemonOperationRejectedalias).daemon_client.pyre-exports them, so every existing import keeps working.OperationKernel.executenow hasexcept DaemonMutationIndeterminateError/except DaemonOperationProtocolErrorclauses; the name matching is deleted.Verification
Exact commands, run in this worktree:
devtools test tests/unit/cli/test_query_surface_lowering_parity.py tests/unit/cli/test_archive_query.py tests/unit/daemon/test_daemon_operation_route.py tests/unit/cli/test_operation_kernel.py tests/unit/cli/test_daemon_client.py tests/unit/operations/test_daemon_reads.py tests/unit/cli/test_mutation_operation_contract.py→
3 failed, 282 passed, 1 warning in 54.50s.The same three fail at the base commit
7f073d3d2with no change applied(
3 failed, 139 passedover the two files that carry them), so they areinherited, not caused here:
test_archive_query.py::TestEmitDeleteMachineModeNoPrompt::test_confirmed_delete_uses_an_unbounded_daemon_wait(asserts
initialized == [{"auth_token": None}], gets a lambda),test_daemon_client.py::test_daemon_mutation_timeout_is_typed_indeterminateand
..._interrupt_after_connect_is_typed_indeterminate(
AttributeError: 'TimedOutConnection' object has no attribute 'connect'—test doubles behind
daemon_client.py:136).devtools verify --quick→ exit 0, every gate ok.devtools gate layering→"status":"passed","count":0, no new violations.devtools render all --check→ exit 0, zeroout of synclines.New laws and their verified anti-vacuity:
test_root_request_and_daemon_reads_lower_identically(hypothesis) assertsRootModeRequest.from_params(p).query_spec() == _cli_query_spec(p)overgenerated
lexical/semantic/similar_text/terms combinations, and thateither both surfaces refuse or neither does. Verified by mutation: adding
params.pop("retrieval_lane", None)after the CLI's delegation givesAssertionError: ... Differing attributes: ['retrieval_lane'] ... retrieval_lane: 'auto' != 'dialogue'.test_a_raised_indeterminate_mutation_is_typed_by_class_not_by_nameraises asubclass named
_RenamedError. Verified by reverting the kernel to thename match:
OperationFailedError: daemon_transport_error: daemon outcome is indeterminate after POST /api/operation.test_a_raised_size_protocol_error_is_reported_as_an_oversized_resultkeepsthe
result_too_largemapping that the"size" in str(exc)condition owns.Schema closure
devtools schema closureon all seven touched files reportsoutfor everyone:
operations/query_lowering.py,operations/daemon_errors.py,cli/root_request.py,cli/operation_kernel.py,operations/daemon_reads.py,daemon_client.py,daemon/http.py. Nothing here moves the derived-tierschema identity, so no archive rebuild ordering constraint applies. This
confirms the design's "none (
root_lowering.pyunchecked)" note.Residuals
tests/unit/daemon/test_operation_protocol.py; no such fileexists at head. The operation-protocol coverage is
tests/unit/daemon/test_daemon_operation_route.pyplustests/unit/cli/test_operation_kernel.py, both run above.coerce_termsin the new module is slightly stricter than the CLI'scoerce_query_terms(which accepts any iterable); the Click path still usesits own coercion before delegating, so no surface behavior changed. Folding
the two coercions together is deliberately left to a later step.
daemon/http.pystill importscli.root_requestat runtime forRootModeRequest; only the lowering symbol moved. Its docstring at line 685still cites
cli/archive_query.py, which the design assigns to S5.🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK