Skip to content

feat(query): explain zero-hit queries with predicate attribution (--why) - #3311

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/query-miss-diagnosis
Jul 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/query-miss-diagnosis

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Summary

A zero-hit query used to be a dead end. This adds bounded predicate
attribution to diagnose_query_miss() -- which top-level filter(s) zeroed
the result, a since/until relaxation suggestion, and an FTS-vs-structured
disagreement check -- surfaced via a new CLI --why flag and merged into
the existing MCP zero-hit diagnostics.

Problem

polylogue/archive/query/miss_diagnostics.py already checked readiness,
archive-empty, and raw-ingest-backlog on a zero-hit query, but nothing
named which predicate was responsible when a compound query (e.g.
origin:X repo:Y) matched nothing. The query DSL/field-descriptor
machinery (QUERY_FIELD_DESCRIPTORS) already declares every top-level
filter's active/inactive state and default value, but nothing re-ran the
query with individual filters dropped to attribute the miss.

Solution

  • polylogue/archive/query/miss_types.py (new): QueryMissReason/
    QueryMissDiagnostics moved out of miss_diagnostics.py verbatim so the
    new probe module can construct reasons without a circular import.
    miss_diagnostics.py re-exports both, no external import changes.
  • polylogue/archive/query/miss_predicates.py (new):
    • probe_predicate_zeroing: bounded clause-drop scan. For each active
      top-level field predicate on SessionQuerySpec (via
      QUERY_FIELD_DESCRIPTORS), re-runs SessionQuerySpec.count() with
      that one field cleared to its dataclass default. Capped at
      MAX_PREDICATE_PROBES = 6 COUNT-only probes. A query with a custom
      boolean_predicate tree (DSL AND/OR/NOT) is explicitly named
      out-of-scope rather than decomposed.
    • probe_date_relaxation_reasons: for a confirmed since/until
      culprit, one LIMIT 1 sorted probe (toward the boundary) names the
      actual nearest matching session's date, or explicitly reports "no
      cheap relaxation found" rather than fabricating a value.
    • probe_fts_structured_disagreement: two extra counts (FTS-only,
      structured-only, both via SessionQuerySpec.count) detect when the
      search text and the structured filters each independently match but
      never the same session -- reuses the real query engine, no parallel
      FTS path.
  • diagnose_query_miss() gains full: bool = False. Default still
    runs the clause-drop scan (names the culprit); full=True adds the
    relaxation and FTS-disagreement probes. Polylogue.diagnose_query_miss
    forwards full.
  • CLI: new root --why flag (click_option_groups.py,
    RootModeRequest.why). archive_query.py's find/root search path
    (otherwise a synchronous ArchiveStore-direct executor) bridges into
    env.polylogue.diagnose_query_miss(spec, full=why) via
    run_coroutine_sync on a zero-hit result. _emit_no_results renders a
    "Why this may have missed:" block for text output and embeds the
    diagnostics envelope for JSON/YAML. The daemon-HTTP CLI fast path now
    forwards the daemon's own diagnostics key verbatim instead of
    re-probing.
  • MCP: archive_search_payload's zero-hit path merges the same
    probes (always at the full breakdown -- there's no tty concept to gate
    verbosity on for an agent-facing surface) alongside the existing
    per-FTS-term diagnostics in _search_term_diagnostics.
  • docs/cli-reference.md and the topology projection regenerated for the
    new module and flag.

Deliberately out of scope

  • The two other diagnose_query_miss call sites
    (api/search_envelope_builder.py, daemon/http.py's _do_list) keep
    full=False. They're generic list/search infra shared by the web
    reader and Python API, not an agent-facing surface, so defaulting them
    to the heavier probe set wasn't part of this change -- a reasonable
    follow-up if the web reader UI wants the full breakdown too.
  • MCP's list-sessions payload (archive_session_list_payload) has no
    diagnostics at all, matching the CLI's existing "browse mode with 0
    rows is success, not a miss" decision for list vs. search modes.
  • Predicate attribution does not decompose a DSL boolean_predicate tree
    (arbitrary AND/OR/NOT/sequence nesting) -- it names that scope limit as
    its own reason instead of guessing at a subtree.
  • When more than MAX_PREDICATE_PROBES (6) predicates are active, only
    the first 6 in descriptor-declaration order are probed; the excess is
    not attributed. A real generality limit, not a combinatorial search.

Verification

devtools test tests/unit/archive/test_query_miss_predicates.py \
  tests/unit/archive/test_query_miss_diagnostics.py \
  tests/unit/mcp/test_archive_support_miss_predicates.py \
  tests/unit/mcp/test_query_request_contracts.py \
  tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_archive_query.py \
  tests/unit/ui/test_tui_read_surface.py tests/unit/api/test_search_envelope_builder.py \
  tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_web_reader.py
# 682 passed

devtools verify --quick
# ruff format/check, mypy --strict, render all --check, topology/layering/
# closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/
# test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/
# degrade-loudly all ok

New tests use real archive fixtures (SessionBuilder + Polylogue facade
against a live SQLite index, no mocks) to prove the predicate-attribution
counts and relaxation dates are correct on known data, not just that the
wiring compiles.

Ref polylogue-jnj.12

Problem: a zero-hit query was a dead end -- diagnose_query_miss() already
checked readiness/archive-empty/raw-backlog, but nothing said which
predicate actually zeroed the result set, whether a since/until window
was almost right, or whether an FTS term and a structured filter simply
never intersect. Ref polylogue-jnj.12.

What changed:
- polylogue/archive/query/miss_types.py: split QueryMissReason/
  QueryMissDiagnostics out of miss_diagnostics.py (no behavior change) so
  the new probe module can construct reasons without a circular import.
- polylogue/archive/query/miss_predicates.py: bounded clause-drop scan
  (probe_predicate_zeroing, <=6 COUNT-only probes over
  QUERY_FIELD_DESCRIPTORS, each re-running SessionQuerySpec.count with one
  top-level field cleared to its dataclass default); since/until nearest-
  boundary relaxation via one LIMIT-1 sorted probe
  (probe_date_relaxation_reasons); FTS-vs-structured disagreement via two
  extra counts reusing SessionQuerySpec.count itself, no parallel FTS path
  (probe_fts_structured_disagreement). Scoped explicitly to top-level
  ANDed field predicates -- a DSL boolean_predicate tree is named as
  out-of-scope, not guessed at.
- diagnose_query_miss() gains full: bool = False: default runs the
  clause-drop scan only (still names the culprit predicate(s)); full=True
  adds relaxation + FTS-disagreement. Existing reasons/behavior unchanged
  when config is None or full=False and no new predicate reasons fire.
- CLI: new root --why flag (RootModeRequest.why); the find/read search
  path (archive_query.py, otherwise a sync ArchiveStore-direct executor)
  bridges into env.polylogue.diagnose_query_miss(spec, full=why) via
  run_coroutine_sync on a zero-hit result. _emit_no_results renders a
  "Why this may have missed:" block for text output and embeds the
  diagnostics envelope for JSON/YAML; the daemon-HTTP CLI fast path
  forwards the daemon's own diagnostics verbatim instead of re-probing.
- MCP: archive_search_payload's zero-hit path merges the same probes
  (always at full breakdown -- there's no tty concept to gate on) into
  the existing per-FTS-term diagnostics.
- docs/cli-reference.md + topology projection regenerated.

Deliberately out of scope (kept honest rather than overclaimed):
- daemon HTTP's own two diagnose_query_miss call sites (search_envelope_
  builder.py, http.py _do_list) keep full=False -- they're generic
  list/search infra shared by the web reader and Python API, not just an
  agent-facing surface, so defaulting them to the heavier probe set was
  not part of this change.
- MCP's list-sessions payload (archive_session_list_payload) has no
  diagnostics at all, matching the CLI's existing "browse mode with 0
  rows is success, not a miss" decision for list vs. search.
- predicate attribution does not decompose a DSL boolean_predicate tree;
  it names the scope limit as its own reason instead of guessing a
  subtree.

Verification:
- devtools test tests/unit/archive/test_query_miss_predicates.py
  tests/unit/archive/test_query_miss_diagnostics.py
  tests/unit/mcp/test_archive_support_miss_predicates.py
  tests/unit/mcp/test_query_request_contracts.py
  tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_archive_query.py
  tests/unit/ui/test_tui_read_surface.py tests/unit/api/test_search_envelope_builder.py
  tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_web_reader.py
  -> 682 passed
- devtools verify --quick -> ruff format/check, mypy --strict, render all
  --check, topology/layering/closure-matrix/manifests/ci-workflows/
  doc-commands/docs-coverage/test-infra-currency/test-clock-hygiene/
  pytest-timeout-overrides/degrade-loudly all ok

Co-Authored-By: Claude <[email protected]>
@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, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@Sinity
Sinity merged commit 93f2982 into master Jul 27, 2026
2 checks passed
@Sinity
Sinity deleted the feature/feat/query-miss-diagnosis branch July 27, 2026 08:37
Sinity added a commit that referenced this pull request Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

Next review available in: 31 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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 reviews.

How do review limits work?

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

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, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 90c0f406-7d31-4021-97d8-d928eed02e02

📥 Commits

Reviewing files that changed from the base of the PR and between b769019 and 32b0538.

📒 Files selected for processing (15)
  • docs/cli-reference.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/archive/query/miss_diagnostics.py
  • polylogue/archive/query/miss_predicates.py
  • polylogue/archive/query/miss_types.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/click_app.py
  • polylogue/cli/click_option_groups.py
  • polylogue/cli/root_request.py
  • polylogue/mcp/archive_support.py
  • tests/unit/archive/test_query_miss_predicates.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/mcp/test_archive_support_miss_predicates.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/query-miss-diagnosis

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 added a commit that referenced this pull request Jul 29, 2026
Problem: three snapshot files pinned CLI help/output text and archive
diagnostics from before several unrelated, already-merged feature changes:
- #3311 (93f2982, "bounded predicate attribution for zero-hit queries")
  added the `--why` flag to query verbs.
- #3285 (f4cd341, "derive session timestamps from message evidence")
  added the `session_timestamp_backfill` maintenance target.
- SOURCE_SCHEMA_VERSION and INDEX_SCHEMA_VERSION advanced (13->14, 43->45)
  via already-landed additive durable/derived migrations on this branch.
- This session's schema-annotation fix (Ref polylogue-c66i, previous
  commits) changed synthetic-corpus generated content (real user/assistant
  text instead of `synthetic-<n>` placeholders), which legitimately changed
  demo-fixture token counts, evidence-ref ordering, and wall-clock
  distribution figures baked into these snapshots.

None of these are test bugs or production regressions -- the snapshots were
simply stale relative to already-merged, intentional changes.

What changed: regenerated via `pytest ... --snapshot-update`:
- tests/unit/cli/__snapshots__/test_help_snapshots.ambr
- tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr (--why help
  text, session_timestamp_backfill --target choice)
- tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr (token counts,
  evidence_refs ordering, wallclock distribution, source/index tier
  user_version, sqlite_stat1_rows)

Verification:
- devtools test tests/unit/cli/test_help_snapshots.py
  tests/unit/cli/test_terminal_snapshots.py
  tests/unit/cli/test_plain_cli_snapshots.py -> 34 passed (21 snapshots
  passed, 0 updated on the verification re-run).

Ref polylogue-c66i

Co-Authored-By: Claude <[email protected]>
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