Skip to content

refactor: Share one query lowering and type daemon client errors - #5094

Merged
Sinity merged 2 commits into
masterfrom
cli-s0-query-lowering
Sep 14, 2026
Merged

Sinity merged 2 commits into
masterfrom
cli-s0-query-lowering

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

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

  • The --lexical/--semantic desugaring and the terms→expression step existed
    twice: cli/root_request.py:37-62 (Click root) and
    operations/daemon_reads.py:_lower_cli_query_params. Two copies of one
    selection 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-124 classified daemon transport failures by
    type(exc).__name__ == "DaemonMutationIndeterminateError". A renamed or
    subclassed exception demotes an accepted-but-unreceipted mutation to a
    retryable daemon_transport_error — the CLI would then be free to re-issue
    a 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

  • New polylogue/operations/query_lowering.py owns coerce_terms,
    desugar_retrieval_flags, lower_query_params, lower_cli_query_params,
    cli_query_spec, and re-exports expression_from_query_terms. Refusals
    raise QueryLoweringError(ValueError) carrying a separate cli_message, so
    the Click root keeps its flag-named UsageError wording and protocol callers
    keep the transport-neutral ValueError text they had. No message changed.
  • RootModeRequest._from_normalized_params and
    daemon_reads._lower_cli_query_params / _cli_query_spec now delegate; the
    duplicate bodies are deleted. daemon/http.py imports
    expression_from_query_terms from the new module instead of the private
    cli.root_request._expression_from_query_terms alias, which is gone.
  • New polylogue/operations/daemon_errors.py holds DaemonResponseError,
    DaemonMutationIndeterminateError, DaemonOperationProtocolError,
    DaemonOperationRejectedError (+ the DaemonOperationRejected alias).
    daemon_client.py re-exports them, so every existing import keeps working.
    OperationKernel.execute now has except DaemonMutationIndeterminateError /
    except DaemonOperationProtocolError clauses; 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 7f073d3d2 with no change applied
    (3 failed, 139 passed over the two files that carry them), so they are
    inherited, 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_indeterminate
    and ..._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, zero out of sync lines.

New laws and their verified anti-vacuity:

  • test_root_request_and_daemon_reads_lower_identically (hypothesis) asserts
    RootModeRequest.from_params(p).query_spec() == _cli_query_spec(p) over
    generated lexical/semantic/similar_text/terms combinations, and that
    either both surfaces refuse or neither does. Verified by mutation: adding
    params.pop("retrieval_lane", None) after the CLI's delegation gives
    AssertionError: ... Differing attributes: ['retrieval_lane'] ... retrieval_lane: 'auto' != 'dialogue'.
  • test_a_raised_indeterminate_mutation_is_typed_by_class_not_by_name raises a
    subclass named _RenamedError. Verified by reverting the kernel to the
    name match: OperationFailedError: daemon_transport_error: daemon outcome is indeterminate after POST /api/operation.
  • test_a_raised_size_protocol_error_is_reported_as_an_oversized_result keeps
    the result_too_large mapping that the "size" in str(exc) condition owns.

Schema closure

devtools schema closure on all seven touched files reports out for every
one: 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-tier
schema identity, so no archive rebuild ordering constraint applies. This
confirms the design's "none (root_lowering.py unchecked)" note.

Residuals

  • The design cited tests/unit/daemon/test_operation_protocol.py; no such file
    exists at head. The operation-protocol coverage is
    tests/unit/daemon/test_daemon_operation_route.py plus
    tests/unit/cli/test_operation_kernel.py, both run above.
  • The three inherited failures above are untouched and still red on master.
  • coerce_terms in the new module is slightly stricter than the CLI's
    coerce_query_terms (which accepts any iterable); the Click path still uses
    its own coercion before delegating, so no surface behavior changed. Folding
    the two coercions together is deliberately left to a later step.
  • daemon/http.py still imports cli.root_request at runtime for
    RootModeRequest; only the lowering symbol moved. Its docstring at line 685
    still cites cli/archive_query.py, which the design assigns to S5.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Sinity and others added 2 commits September 14, 2026 18:15
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
@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 33 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: 82816b7c-0c52-4f24-86b8-3d54ecf67133

📥 Commits

Reviewing files that changed from the base of the PR and between 2b093b1 and 310bf44.

📒 Files selected for processing (9)
  • polylogue/cli/operation_kernel.py
  • polylogue/cli/root_request.py
  • polylogue/daemon/http.py
  • polylogue/daemon_client.py
  • polylogue/operations/daemon_errors.py
  • polylogue/operations/daemon_reads.py
  • polylogue/operations/query_lowering.py
  • tests/unit/cli/test_operation_kernel.py
  • tests/unit/cli/test_query_surface_lowering_parity.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 5276836 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the cli-s0-query-lowering branch September 14, 2026 16:50
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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
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
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