Skip to content

feat(search): explainable results with matched terms, rank-first default, lane scores (#873) - #932

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/explainable-search-873
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/explainable-search-873

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Explainable search with matched_terms, score_components, rank-first sort default. 13 files +194/-11.

Add explanation fields (matched_terms, score_components) to
ConversationSearchHit and wire them through FTS5, hybrid, and action
search paths. Fix default sort to be rank-first when search terms are
present — previously sort=None was silently replaced with sort="date",
destroying search provider rankings. Preserve per-lane rank contributions
(text, action, vector) in hybrid RRF search so callers can see WHY a
result matched. Add next_cursor to paginated search result envelopes
for stable keyset pagination of ranked results.

Ref #873

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 17:39
@Sinity
Sinity merged commit eacb282 into master May 7, 2026
@Sinity
Sinity deleted the feature/feat/explainable-search-873 branch May 7, 2026 17:39
@coderabbitai

coderabbitai Bot commented May 7, 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 47 minutes and 42 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits 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: 76a2181a-895e-467c-9112-c091269f202d

📥 Commits

Reviewing files that changed from the base of the PR and between 243717b and e9dd539.

📒 Files selected for processing (13)
  • polylogue/archive/query/plan.py
  • polylogue/archive/query/plan_execution.py
  • polylogue/archive/query/retrieval_candidates.py
  • polylogue/archive/query/retrieval_search.py
  • polylogue/archive/query/search_hits.py
  • polylogue/archive/query/sorting.py
  • polylogue/archive/query/spec.py
  • polylogue/daemon/http.py
  • polylogue/mcp/payloads.py
  • polylogue/storage/repository/archive/search.py
  • polylogue/storage/search/models.py
  • polylogue/surfaces/payloads.py
  • tests/unit/archive/test_query_search_runtime.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/explainable-search-873

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.

Copilot AI 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.

Pull request overview

This PR extends Polylogue’s search stack to return explainable ranked results (matched terms + score component breakdowns), adjusts default sorting to preserve provider ranking when search terms are present (“rank-first”), and enriches hybrid retrieval with per-lane rank contribution metadata.

Changes:

  • Add matched_terms and score_components to search-hit payloads/models and propagate them through repository/surface adapters.
  • Preserve search-provider ordering by default (skip date-based sorting) when FTS terms exist and no explicit sort is provided.
  • For hybrid retrieval, return per-conversation lane rank contributions and surface them as score components; add an MCP next_cursor field (cursor generation scaffolding).

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
tests/unit/archive/test_query_search_runtime.py Updates hybrid search test to assert returned per-lane rank contributions.
polylogue/surfaces/payloads.py Adds matched_terms + score_components to surface search-match payloads.
polylogue/storage/search/models.py Extends evidence-hit model with matched terms and scoring/ranking metadata fields.
polylogue/storage/repository/archive/search.py Propagates matched terms / score components from evidence hits into search-hit construction.
polylogue/mcp/payloads.py Adds next_cursor to paginated search payload and implements cursor construction.
polylogue/daemon/http.py Changes daemon list behavior to return ranked “hits” envelope for query/contains searches (with match evidence).
polylogue/archive/query/spec.py Removes implicit default sort, threads cursor into query plan.
polylogue/archive/query/sorting.py Updates sort-plan protocol typing to allow sort=None.
polylogue/archive/query/search_hits.py Adds evidence fields to ConversationSearchHit and special-cases hybrid to attach lane rank components.
polylogue/archive/query/retrieval_search.py Changes hybrid search to return (conversations, lane_ranks) and computes per-lane rank maps.
polylogue/archive/query/retrieval_candidates.py Adapts hybrid candidate fetching to the new return type.
polylogue/archive/query/plan.py Makes sort optional; adds cursor + ranking policy fields to the plan.
polylogue/archive/query/plan_execution.py Implements “rank-first default” by skipping sorting when FTS terms exist and sort is unset.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

since=parse_query_date("since", spec.since),
until=parse_query_date("until", spec.until),
sort=spec.sort or "date",
sort=spec.sort,
since_session_id=spec.since_session_id,
message_type=spec.message_type,
offset=spec.offset,
cursor=spec.cursor,
Comment on lines 96 to 102
conversation_id: str | None = None
parent_id: str | None = None
since: datetime | None = None
until: datetime | None = None
sort: SortField = "date"
sort: SortField | None = None
reverse: bool = False
limit: int | None = None
Comment thread polylogue/mcp/payloads.py
Comment on lines 244 to +245
next_offset = offset + len(hits) if len(hits) == limit and offset + limit < total else None
next_cursor = _build_search_cursor(hits) if len(hits) == limit else None
Comment thread polylogue/mcp/payloads.py
Comment on lines +225 to +233
def _build_search_cursor(hits: Sequence[ConversationSearchHit]) -> str | None:
"""Build an opaque cursor from the last hit for keyset pagination."""
if not hits:
return None
import base64

last = hits[-1]
payload = f"{last.rank}:{last.conversation_id}"
return base64.b64encode(payload.encode()).decode()
Comment thread polylogue/daemon/http.py
Comment on lines +503 to +506
# When search terms are present, return ranked result envelope with
# per-hit match evidence instead of plain row dicts.
if query_text and not query_params.get("similar_text"):
return await self._do_search_list(poly, spec, limit, offset)
Comment thread polylogue/daemon/http.py
Comment on lines +565 to +567
plan = spec.to_plan()
hits = await search_hits_for_plan(plan, poly.repository)
total = await spec.count(poly.repository)
Comment thread polylogue/daemon/http.py
Comment on lines +571 to +576
with contextlib.suppress(Exception):
try:
raw_diag = await poly.operations.diagnose_query_miss(spec)
diagnostics = MCPQueryMissDiagnosticsPayload.from_diagnostics(raw_diag)
except Exception:
pass
Sinity added a commit that referenced this pull request May 7, 2026
Polylogue had FTS hits, snippets, and hybrid retrieval, but no
stable shared contract for ranking explainability or pagination
across CLI, MCP, daemon HTTP, and reader. Hybrid RRF lane
contributions were also discarded before they reached the
surfaces, and default date sorting could silently override ranked
search order on non-hit paths.

- `archive/query/{plan,plan_execution,retrieval_candidates,
  retrieval_search,search_hits,sorting,spec}.py`: ranked result
  envelope with `matched_terms` and per-lane `score_components`
  so consumers can show why each hit matched and which lane
  contributed.
- Rank-first sort default on search paths; date sort only when
  the surface explicitly asks for it.
- `polylogue/daemon/http.py`: daemon API surfaces the same
  envelope so reader and external clients see one ranking
  contract.

Refs #873
Sinity added a commit that referenced this pull request May 7, 2026
Polylogue had FTS hits, snippets, and hybrid retrieval, but no
stable shared contract for ranking explainability or pagination
across CLI, MCP, daemon HTTP, and reader. Hybrid RRF lane
contributions were also discarded before they reached the
surfaces, and default date sorting could silently override ranked
search order on non-hit paths.

- `archive/query/{plan,plan_execution,retrieval_candidates,
  retrieval_search,search_hits,sorting,spec}.py`: ranked result
  envelope with `matched_terms` and per-lane `score_components`
  so consumers can show why each hit matched and which lane
  contributed.
- Rank-first sort default on search paths; date sort only when
  the surface explicitly asks for it.
- `polylogue/daemon/http.py`: daemon API surfaces the same
  envelope so reader and external clients see one ranking
  contract.

Refs #873
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.

2 participants