Skip to content

feat(search): typed ranked-result envelope + OpenAPI schema emission (#1266) - #1370

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/search-ranked-envelope-1266
May 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/search-ranked-envelope-1266

Conversation

@Sinity

@Sinity Sinity commented May 19, 2026

Copy link
Copy Markdown
Owner

Summary

Foundation slice (#873 slice A) for the shared ranked-result envelope. Introduces SearchEnvelope — a typed Pydantic model carrying hits + total + limit/offset + next_offset/next_cursor + query + sort + retrieval_lane + ranking_policy/version + diagnostics — and routes CLI JSON, MCP, the Python API, and daemon HTTP through one shared builder so all four surfaces emit semantically-equivalent envelopes. Also emits an OpenAPI 3.1 schema (docs/openapi/search.yaml) generated from the Pydantic models so external tooling can auto-discover the daemon's ranked-search contract.

Closes #1266.

Problem

Before this PR each surface emitted its own ad-hoc search shape. MCP exposed MCPPaginatedSearchResultPayload with {hits, total, limit, offset, next_offset, next_cursor, diagnostics}. Daemon HTTP _do_search_list built a hand-shaped dict with flat-row hits and a parallel match sub-object. CLI --format json emitted a bare list of ConversationSearchHitPayload. The Python API only returned the legacy SearchResult (a list[ConversationSearchHit] wrapper). None of these surfaces declared the ranking policy, version, or carried the query / retrieval_lane / sort metadata required by #873. Reader/MCP clients had no way to discover the daemon HTTP shape mechanically — there was no OpenAPI document.

Solution

  • polylogue/surfaces/payloads.py:
    • new SearchEnvelope model with all the required fields, plus RANKING_POLICY_MIXED / RANKING_POLICY_VERSION constants.
    • new helpers: build_search_envelope() (canonical builder with cursor/next_offset logic) and build_search_cursor().
  • polylogue/mcp/payloads.py: MCPPaginatedSearchResultPayload now aliases SearchEnvelope. conversation_search_result_payload() delegates to build_search_envelope and threads query / retrieval_lane / sort from MCPConversationQueryRequest.
  • polylogue/mcp/server_tools.py: search tool passes query/lane/sort into the envelope builder.
  • polylogue/daemon/http.py: _do_search_list builds the typed envelope and model_dumps it. The HTTP hits payload now uses the canonical ConversationSearchHitPayload shape ({conversation: {...}, match: {...}}) — the existing reader test was updated; no public clients besides the web reader consume this endpoint yet.
  • polylogue/cli/query_output.py: output_search_hits() emits the envelope for --format json (the format that feat(search): one typed ranked-result envelope across CLI/MCP/API/HTTP (#873 slice A) #1266 calls out); ndjson / yaml / csv keep streaming per-row payloads. New format_search_envelope() helper.
  • polylogue/api/archive.py + polylogue/api/search_envelope_builder.py: Polylogue.search_envelope() typed API method; build logic extracted to polylogue/api/search_envelope_builder.py (keeps archive.py under the per-file LOC budget).
  • devtools/render_openapi.py + docs/openapi/search.yaml: generated OpenAPI 3.1 description of the daemon HTTP search endpoint, derived from the Pydantic models with $defs hoisted into components/schemas. Wired into command_catalog, generated_surfaces, and therefore devtools render-all / --check.
  • devtools/render_cli_output_schemas.py: SearchEnvelope published as docs/schemas/cli-output/search-envelope.schema.json alongside the existing per-hit schema (reuses the feat(cli): output-assurance contract — stable JSON schemas + snapshot gate per command family (#958 slice B) #1272 pattern from PR feat(cli): output assurance contract + JSON schemas + NDJSON streaming (#1272) #1340).
  • tests/unit/surfaces/test_search_envelope_contract.py: cross-surface contract test that runs the same query through the Python helper, the MCP helper, and the CLI formatter and asserts the envelope-level metadata (limit, offset, query, retrieval_lane, ranking_policy, ranking_policy_version, hit ranks, hit lanes, hit conversation IDs) matches across all three. Also pins the SearchEnvelope field set and verifies the OpenAPI schema is committed.

The legacy MCPPaginatedSearchResultPayload export is retained as an alias so external imports keep working through the transition.

Verification

python -m pytest tests/unit/surfaces tests/unit/cli/test_query_fmt.py tests/unit/cli/test_query_exec_laws.py tests/unit/mcp tests/unit/daemon tests/unit/api -q
# → 1106 passed in 18.75s

python -m devtools verify --quick
# → exit_code: 0 (format + lint + mypy + render-all --check + manifest checks all pass)

python -m devtools render-all --check
# → all generated surfaces in sync (includes new render-openapi)

Cross-surface equivalence is verified by tests/unit/surfaces/test_search_envelope_contract.py::test_all_surfaces_emit_semantically_equivalent_envelope. The OpenAPI schema renders cleanly and tests/unit/surfaces/test_search_envelope_contract.py::test_openapi_schema_is_present_and_well_formed ensures it stays committed and references SearchEnvelope.

Follow-ups

This is the slice-A foundation. Slices B–E under #873 (lane-rank contribution preservation in hybrid RRF, cursor-based stable pagination wiring at the query plan level, scoped facets, surface convergence of the two ConversationSearchHit models) build on this envelope.

…1266)

Foundation slice (#873 slice A) for the shared ranked-result envelope.

* polylogue/surfaces/payloads.py: SearchEnvelope, build_search_envelope,
  build_search_cursor, RANKING_POLICY_MIXED / RANKING_POLICY_VERSION.
* polylogue/mcp/payloads.py: MCPPaginatedSearchResultPayload now aliases
  SearchEnvelope; conversation_search_result_payload routes through the
  shared builder and threads query/lane/sort.
* polylogue/daemon/http.py: _do_search_list returns the typed envelope.
* polylogue/cli/query_output.py: --format json wraps hits in the canonical
  envelope (ndjson/yaml/csv keep streaming per-row).
* polylogue/api/archive.py + polylogue/api/search_envelope_builder.py:
  Polylogue.search_envelope() returns the same shape.
* devtools/render_openapi.py: emit docs/openapi/search.yaml from the
  Pydantic models; registered in command_catalog + generated_surfaces.
* devtools/render_cli_output_schemas.py: publish search-envelope schema.
* tests/unit/surfaces/test_search_envelope_contract.py: cross-surface
  semantic equivalence + envelope field-set pin + OpenAPI sanity check.

Closes #1266.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity
Sinity enabled auto-merge (squash) May 19, 2026 07:51
@coderabbitai

coderabbitai Bot commented May 19, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 5 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5615ff49-97cf-4f97-9b75-b31ad259599d

📥 Commits

Reviewing files that changed from the base of the PR and between 311ff4b and 6b345fc.

📒 Files selected for processing (20)
  • AGENTS.md
  • devtools/command_catalog.py
  • devtools/generated_surfaces.py
  • devtools/render_cli_output_schemas.py
  • devtools/render_openapi.py
  • docs/devtools.md
  • docs/openapi/search.yaml
  • docs/plans/topology-target.yaml
  • docs/schemas/cli-output/README.md
  • docs/schemas/cli-output/search-envelope.schema.json
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/api/search_envelope_builder.py
  • polylogue/cli/query_output.py
  • polylogue/daemon/http.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_tools.py
  • polylogue/surfaces/payloads.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/surfaces/test_search_envelope_contract.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/search-ranked-envelope-1266

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.

@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: 6b345fc889

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

Comment on lines +530 to +534
query_text = getattr(output, "search_query", "") or ""
retrieval_lane = getattr(output, "retrieval_lane", "") or "auto"
limit_value = getattr(output, "limit", None) or len(hits)
offset_value = getattr(output, "offset", 0) or 0
sort_value = getattr(output, "sort", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Populate CLI envelopes from the query plan

In the actual CLI path, output_search_hits receives a QueryOutputSpec, which only carries formatting/destination settings and does not define search_query, retrieval_lane, limit, offset, or sort. As a result, polylogue --format json <query> always falls through these defaults and emits query: "", retrieval_lane: "auto", limit: len(hits), offset: 0, and no sort even when the user supplied a query or pagination flags, breaking the canonical envelope metadata and pagination contract. Thread the selection/page values from the execution plan instead of reading missing attributes from QueryOutputSpec.

Useful? React with 👍 / 👎.

Comment thread devtools/render_openapi.py Resolved
@Sinity
Sinity merged commit 20d7955 into master May 19, 2026
2 checks passed
@Sinity
Sinity deleted the feature/feat/search-ranked-envelope-1266 branch May 19, 2026 07:55
Sinity added a commit that referenced this pull request May 19, 2026
PR #1370 changed `polylogue list --format json` for search-mode
queries to emit a typed ranked-result envelope
(`{"hits": [...], "limit": N, "next_cursor": ...}`) rather than a
bare JSON array. The parity adapter at tests/infra/surfaces.py:307
still expected the bare array shape, causing
`test_search_unique_token_parity` and `test_search_shared_token_parity`
to fail on every search-mode case.

Fix: when the parsed CLI output is a dict carrying a `hits` array,
peel it and continue with the existing per-row id extraction. The
list-mode and search-hit-mode shapes still work unchanged (both go
through the same row loop).

Updates the docstring to enumerate all three shapes the adapter
now handles.

Verification:
- `nix develop --command pytest tests/unit/storage/test_surface_parity_adapters.py -q`
  → 10 passed (previously 2 failed).
- No production code touched; test-infra only.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request May 19, 2026
…#1384)

## Summary

PR #1370 (typed ranked-result envelope) changed `polylogue list --format
json` for search-mode queries to emit `{"hits": [...], "limit": N,
"next_cursor": ...}` rather than a bare JSON array. The CLI parity
adapter at `tests/infra/surfaces.py:307` still expected a bare array and
asserted `not isinstance(parsed, list)`, causing both
`test_search_unique_token_parity` and `test_search_shared_token_parity`
to fail on every search-mode case on master.

## Solution

When the parsed CLI output is a dict carrying a `hits` array (the typed
envelope shape), peel the `hits` and continue with the existing per-row
id extraction. The list-mode and search-hit-mode shapes still work
unchanged — they hit the same row loop directly.

Updated the inline doc to enumerate all three shapes the adapter now
handles.

## Verification

- `nix develop --command pytest
tests/unit/storage/test_surface_parity_adapters.py -q` → **10 passed**
(was 2 failures on master).
- No production code touched; test-infra only.

## Scope

Single-file, test-infra-only change. Should land before #1379 / #1380 /
#1382 (or alongside) so those PRs' CI runs are unmasked by this
pre-existing failure.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity

Sinity commented Oct 1, 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.

  • 55.F065 / P2: fixed-already at the checked revision: The current session-list/search operation documents both response shapes using oneOf with SearchEnvelope and SessionListResponse (devtools/render_openapi.py:613-615). A no-query request is no longer described only by the ranked-search schema.

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.

feat(search): one typed ranked-result envelope across CLI/MCP/API/HTTP (#873 slice A)

1 participant