Skip to content

refactor(query): share terminal unit request wiring (#2177) - #2225

Merged
Sinity merged 3 commits into
masterfrom
feature/refactor/query-unit-request-normalization-2177
Jun 20, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/refactor/query-unit-request-normalization-2177

Conversation

@Sinity

@Sinity Sinity commented Jun 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a shared terminal query-unit request boundary in the archive query layer and routes the Python API, daemon, and MCP query-unit surfaces through it. Public parameters and payloads are unchanged; expression parsing, terminal-source rejection, session-scope normalization, and envelope execution now converge through QueryUnitRequest.

Problem

Polylogue.query_units(...), /api/query-units, and the MCP query_units tool all exposed the same terminal unit-query behavior, but each surface assembled the request independently before calling archive execution. That kept expression parsing, session-scope filter normalization, and envelope execution split across surface code instead of owned by the query substrate.

Solution

  • Added QueryUnitRequest, query_unit_request(), and query_unit_envelope() in polylogue/archive/query/unit_results.py.
  • Kept polylogue/mcp/archive_support.py::archive_query_unit_payload() as the MCP helper, but made it delegate to the shared archive request boundary.
  • Simplified polylogue/api/archive.py::query_units, polylogue/mcp/server_tools.py::query_units, and polylogue/daemon/http.py::_handle_query_units so they pass surface parameters into the shared request builder.
  • Added focused request-normalization coverage in tests/unit/core/test_query_unit_request.py; existing API, daemon, and MCP query-unit tests continue to prove cross-surface behavior.

Verification

  • nix develop --command devtools test tests/unit/core/test_query_unit_request.py tests/unit/api/test_facade_contracts.py -k 'query_units' tests/unit/daemon/test_web_reader.py -k 'query_units_endpoint' tests/unit/mcp/test_server_surfaces.py -k 'query_units_tool' -q → 7 passed, 420 deselected
  • nix develop --command devtools verify --quick → exit_code: 0
  • Push hook reran devtools verify --quick → exit_code: 0

Ref #2177

Problem: daemon and MCP query-unit surfaces each parsed terminal expressions and built session-scope filters by hand before reaching the shared archive executor.

What changed: add a QueryUnitRequest boundary in the archive query layer, route the MCP archive helper and daemon endpoint through it, and keep existing public parameters unchanged.

Verification: nix develop --command devtools test tests/unit/core/test_query_unit_request.py tests/unit/daemon/test_web_reader.py -k 'query_units_endpoint' tests/unit/mcp/test_server_surfaces.py -k 'query_units_tool' -q; nix develop --command devtools verify --quick
@coderabbitai

coderabbitai Bot commented Jun 20, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 49 minutes and 10 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 07f87429-f224-4292-ae5d-fdccc41be59a

📥 Commits

Reviewing files that changed from the base of the PR and between 7849c53 and ce4ff4a.

📒 Files selected for processing (2)
  • polylogue/api/archive.py
  • tests/unit/core/test_query_unit_request.py
📝 Walkthrough

Walkthrough

Introduces a frozen QueryUnitRequest dataclass, a query_unit_request() factory that compiles expressions into terminal QueryUnitSource objects and normalizes session filters, and a query_unit_envelope() executor in unit_results.py. The HTTP daemon handler, MCP archive support, and MCP server tools are then migrated to build and execute queries through this shared abstraction.

Changes

QueryUnitRequest abstraction and caller migration

Layer / File(s) Summary
QueryUnitRequest dataclass and query_unit_request/envelope functions
polylogue/archive/query/unit_results.py
Adds the frozen QueryUnitRequest dataclass (expression, source, limit, offset, session_filters), query_unit_request() to compile/validate expressions and normalize session filters, query_unit_envelope() to execute via query_unit_rows(), and expands __all__ with the three new exports.
HTTP daemon handler migration
polylogue/daemon/http.py
Refactors _handle_query_units to build a QueryUnitRequest from HTTP params and call query_unit_envelope(), removing the prior inline parse_unit_source_expression, terminal-source validation 400-branch, and direct query_unit_rows call.
MCP archive support and server tools migration
polylogue/mcp/archive_support.py, polylogue/mcp/server_tools.py
Updates archive_query_unit_payload to accept **filter_params and delegate to query_unit_request/query_unit_envelope; removes the pre-computed session_filters construction in server_tools and passes individual filter parameters directly to the payload builder.
Tests for query_unit_request normalization
tests/unit/core/test_query_unit_request.py
Adds three tests: happy-path compilation with session_filters derivation, rejection of session expressions via ExpressionCompileError, and preservation of a prebuilt session_filters object reference.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Sinity/polylogue#1861: Introduces the shared query-expression compiler in polylogue/archive/query/expression.py that query_unit_request() depends on for compiling and raising ExpressionCompileError.
  • Sinity/polylogue#2049: Introduces QueryUnitSource, parse_unit_source_expression, and the unit-row execution plumbing that QueryUnitRequest and query_unit_envelope are built on top of.
  • Sinity/polylogue#2198: Refactors terminal unit expression compilation/validation via terminal_query_source_list and descriptor registries that the query_unit_request compile-error path directly depends on.

Poem

🐇 Hoppity-hop, I've bundled the query,
No more repeated compiling in a flurry!
A frozen request holds source, page, and filter,
Envelope seals it — no logic to litter.
Daemon, MCP, all march in a line,
One tidy abstraction, everything fine! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: refactoring the query layer to centralize terminal unit request handling across daemon and MCP surfaces.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description comprehensively covers all required template sections with clear explanations of the problem, solution, verification steps, and risk considerations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/query-unit-request-normalization-2177

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 and usage tips.

Problem: Polylogue.query_units still parsed terminal expressions and normalized session filters locally after the daemon and MCP paths moved to QueryUnitRequest.

What changed: route the Python API facade through query_unit_request/query_unit_envelope and cover the API-style tuple filters accepted by the shared helper.

Verification: nix develop --command devtools test tests/unit/core/test_query_unit_request.py tests/unit/api/test_facade_contracts.py -k 'query_units' tests/unit/daemon/test_web_reader.py -k 'query_units_endpoint' tests/unit/mcp/test_server_surfaces.py -k 'query_units_tool' -q; nix develop --command devtools verify --quick

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7849c5369e

ℹ️ 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".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unit/core/test_query_unit_request.py (1)

39-49: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Use canonical session-filter shape in the prebuilt-filters test.

{"origin": ...} doesn’t match the normalized filter vocabulary used elsewhere ("origins" tuple). The identity assertion still passes, but this weakens contract coverage.

Suggested test fixture adjustment
-    filters = {"origin": "chatgpt-export"}
+    filters = {"origins": ("chatgpt-export",)}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/core/test_query_unit_request.py` around lines 39 - 49, The filters
variable in this test is using the non-canonical filter format with "origin" as
a string value, but the normalized filter vocabulary elsewhere uses "origins" as
a tuple. Update the filters dictionary assignment to use the canonical
session-filter shape by changing from a single "origin" key to "origins" key
with a tuple value instead of a string, ensuring consistent contract coverage
across the test suite.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tests/unit/core/test_query_unit_request.py`:
- Around line 39-49: The filters variable in this test is using the
non-canonical filter format with "origin" as a string value, but the normalized
filter vocabulary elsewhere uses "origins" as a tuple. Update the filters
dictionary assignment to use the canonical session-filter shape by changing from
a single "origin" key to "origins" key with a tuple value instead of a string,
ensuring consistent contract coverage across the test suite.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 97521bac-58a4-441e-b6a7-f88d390577e0

📥 Commits

Reviewing files that changed from the base of the PR and between 6d734cb and 7849c53.

📒 Files selected for processing (5)
  • polylogue/archive/query/unit_results.py
  • polylogue/daemon/http.py
  • polylogue/mcp/archive_support.py
  • polylogue/mcp/server_tools.py
  • tests/unit/core/test_query_unit_request.py

Problem: the new QueryUnitRequest test passed singular origin= but asserted the plural origins key. A review caught that the prior focused command had deselected the new test.

What changed: assert the singular origin key for origin= and keep the separate origins= tuple coverage for API-style plural filters.

Verification: nix develop --command devtools test tests/unit/core/test_query_unit_request.py -q; nix develop --command devtools test tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_web_reader.py tests/unit/mcp/test_server_surfaces.py -k 'query_units or query_units_endpoint or query_units_tool' -q; nix develop --command devtools verify --quick
@Sinity

Sinity commented Jun 20, 2026

Copy link
Copy Markdown
Owner Author

Addressed the Codex inline finding: origin= is now asserted against the singular session_filters["origin"] key, while plural origins= remains covered by the API-style tuple test.

Verified on the PR branch:

  • nix develop --command devtools test tests/unit/core/test_query_unit_request.py -q -> 4 passed
  • nix develop --command devtools test tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_web_reader.py tests/unit/mcp/test_server_surfaces.py -k 'query_units or query_units_endpoint or query_units_tool' -q -> 22 passed, 401 deselected
  • nix develop --command devtools verify --quick -> exit_code 0

@Sinity
Sinity merged commit 8316000 into master Jun 20, 2026
13 checks passed
@Sinity
Sinity deleted the feature/refactor/query-unit-request-normalization-2177 branch June 20, 2026 09:54
@Sinity

Sinity commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 78.F034 / P1: fixed-already at the checked revision: tests/unit/core/test_query_unit_request.py:27 now asserts the singular origin key for the singular origin argument. The plural origins behavior is tested separately rather than conflated with this assertion.

Only the rows listed above are dispositioned. Held findings remain open.

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