Skip to content

feat(query): default session-query results to the top-level unit - #3495

Merged
Sinity merged 1 commit into
masterfrom
feature/query/top-level-default-result-unit
Jul 31, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/query/top-level-default-result-unit

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

polylogue find/read/MCP query/daemon-proxied query now default to the
top-level session as the result unit. Subagent/branch children stay
fully queryable via the pre-existing explicit opt-in (--no-root /
root:false DSL field) — no evidence is hidden or deleted.

Problem

Measured 2026-07-29 (bead body): 8,614 of 18,871 sessions (45.6%) are
subagent children (8,824 session_links rows with link_type='subagent'),
and they ranked equal to real top-level sessions in every default result
list. Dogfood example from the bead:

$ polylogue find repo:polylogue
claude-code-session:5ecd  2026-07-27  5ecdb160-...-a3a24886af8cc:agent-af4e...  (342 msgs)
claude-code-session:5ecd  2026-07-27  5ecdb160-...-a3a24886af8cc:agent-ad73... (1098 msgs)
claude-code-session:5ecd  2026-07-28  5ecdb160-...-a3a24886af8cc:agent-ad68...  (499 msgs)

Three rows, one parent session, differing only by an agent suffix — this
shape filled the default result list.

Re-measured today (2026-07-31) against the live archive, repo:polylogue
matches 5,161 sessions total when root is unfiltered — 1,906 top-level,
3,255 subagent/branch children (1906 + 3255 = 5161, confirms honest,
mutually-exclusive SQL partitioning).

Solution

The root field/DSL clause/--root/--no-root CLI flag already existed
(SessionQuerySpec.root: bool | None, None = both, unfiltered). This
change resolves the unset case to root-only via a new
resolve_default_root_filter() helper
(polylogue/archive/query/spec.py), applied at the point each surface
builds its SQL filter-kwargs — not by mutating spec.root/plan.root
themselves, which stay None-by-default. Those fields feed has_filters(),
which several surfaces treat as a safety/routing signal (unscoped-delete
guards in query_actions.py/query_contracts.py, "bare invocation shows
stats" detection in root_request.py, latest resolution) — defaulting
spec.root itself would have made every unfiltered query look "filtered"
to those consumers and silently bypassed an unscoped-mutation guard.

Four parallel filter-kwargs builders needed the fix, three of which were
missing root entirely (not just missing the default — the field
wasn't SQL-pushed at all, or was post-filtered after LIMIT/OFFSET had
already truncated the page):

  • polylogue/cli/archive_query.py — the CLI find/read hot path. Its
    _ArchiveFilterKwargs["root"] already existed but was never defaulted.
    _emit_list/_emit_search gain a total_unit envelope field naming
    the counted unit (AC2); _emit_daemon_list_payload/
    _emit_daemon_search_payload propagate the daemon's total_unit.
  • polylogue/mcp/archive_support.py — ArchiveQueryFilters was missing
    root entirely. MCP query/list never filtered by session structure at
    all, not even on an explicit root: clause.
  • polylogue/archive/query/archive_execution.py — the Python-API/
    SessionFilter path's _ArchiveFilterKwargs was also missing root
    (post-filter only, after SQL LIMIT/OFFSET — a pagination/count
    honesty bug for any consumer of SessionFilter.list()/.count()).
  • polylogue/daemon/http.py — the daemon HTTP session-list route
    (_archive_filter_kwargs_from_spec) was a fourth parallel filter-kwargs
    builder, also missing root. The deployed daemon (the normal runtime
    path per this repo's CLAUDE.md) would have silently kept the old
    unfiltered default even after the CLI/MCP fix landed — caught by the
    existing test_daemon_golden_parity.py::test_find_list_json_parity_between_direct_and_daemon
    regression test, which failed until this route got the same fix.

A lineage:id:<ref> predicate is itself an explicit request for one
session's whole family (root plus descendants), so
resolve_default_root_filter() exempts it via a new
lineage_seed_from_predicate() helper
(polylogue/archive/query/predicate.py) — otherwise the root-only default
would silently drop the children a lineage-seeded query explicitly asked
for. Caught by the existing
test_lineage_id_cli_query_materializes_parent_child_refs regression test.

AC matrix

  1. Default result unit is the top-level session; children reachable via
    explicit projection
    — satisfied. resolve_default_root_filter
    resolves the SQL root filter to top-level-only whenever the query
    left root unset, across CLI find/read, MCP query, the Python-API
    SessionFilter, and the daemon HTTP session-list route. --no-root /
    root:false (pre-existing) remains the explicit opt-in back onto
    children, and stays a real SQL predicate (not a post-fetch slice), so
    a bounded page still reports an honest total.
  2. Session counts state which unit they count — satisfied on the
    surfaces this lane touches (CLI find/read total_unit envelope field;
    MCP/daemon inherit the same resolution feeding their total).
    --root/--no-root help text and the root: DSL field description
    were updated to state the new default explicitly. A full count-label
    audit across every surface (e.g. polylogue analyze/stats-only
    surfaces untouched by this lane) is out of scope per the coordinator's
    non-goals and can be a follow-up if it balloons.
  3. Subagent evidence remains fully queryable/citable — satisfied.
    --no-root / root:false is unchanged plumbing, now confirmed to be a
    real SQL predicate rather than a post-filter, and MCP's root: DSL
    field now actually filters (previously a no-op). Verified live:
    find repo:polylogue --no-root returns 3,255 sessions, all
    agent-*-suffixed children.
  4. Re-run the exact dogfood commands, show before/after — satisfied,
    see below.

Verification

  • mypy --strict on every touched file: clean.

  • devtools test tests/unit/cli/ tests/unit/archive/ tests/unit/mcp/ tests/unit/daemon/ tests/unit/api/ tests/unit/storage/test_topology_edges.py tests/unit/storage/test_session_topology.py: only pre-existing
    failures remain, confirmed against master e8a23cc31 via an isolated
    detached worktree (title-fallback drift in
    test_cli_output_schemas.py/test_plain_cli_snapshots.py/
    test_assertion_candidate_evidence_disclosure.py, origin-enum
    completion drift in test_command_aux_runtime.py, and unrelated
    facade-route/PTY/clock/materialization-bootstrap failures — none touch
    session listing/query defaults). Genuinely new failures from the
    default flip were all fixed: test_bounded_pages_report_indexed_total's
    stale total==2 assertion updated to the now-correct root-only
    total==1, a new companion
    test_no_root_flag_recovers_the_subagent_child_and_honest_total, and
    the test_daemon_golden_parity.py parity gap described above.

  • devtools render all --check: sync OK (docs/cli-reference.md
    regenerated for the changed --root/--no-root help text; a
    __snapshots__/test_terminal_snapshots.ambr update was needed and is
    included).

  • git push ran the pre-push devtools verify --quick hook
    (format+lint+mypy+render-all-check): exit 0.

  • AC4 live dogfood (read-only against /realm/db/polylogue, run via each
    worktree's own interpreter to avoid the documented shared-venv-.pth
    hazard — python3 -c "...; from polylogue.cli import main; main()"
    from a detached worktree pinned at e8a23cc31 for "before" and this
    branch for "after"):

    Before (e8a23cc31, unpatched) — find repo:polylogue --limit 5 -f json:

    total_unit: None   total: 5161   n_items: 5
    claude-code-session:38baa1de-...:agent-a9347188628f8900c   315 msgs
    claude-code-session:38baa1de-...:agent-a6609f08a0ae4d8a7   164 msgs
    claude-code-session:38baa1de-...:agent-aa320a9df0dd977a3    20 msgs
    claude-code-session:38baa1de-...                          3225 msgs
    claude-code-session:38baa1de-...:agent-a512997ff76a012fe   382 msgs
    

    After (this branch) — same command:

    total_unit: top-level sessions   total: 1906   n_items: 5
    claude-code-session:38baa1de-9715-48fa-8175-f2a29d92800e     3225 msgs
    claude-code-session:f9dd2630-26b2-491a-b8dc-073d554e145a     1450 msgs
    claude-code-session:0c1de80e-ebf1-4dcf-9e19-42699cc975c6      505 msgs
    claude-code-session:53e64853-1793-43d2-80ac-a41a8c5a56a2     1493 msgs
    claude-code-session:d6f4b0c3-840b-47b6-bd57-5f1bd6c9c7d4     6059 msgs
    

    After, explicit children projection — find repo:polylogue --no-root --limit 5 -f json:

    total_unit: subagent/branch child sessions   total: 3255   n_items: 5
    (all 5 rows are agent-*-suffixed children of claude-code-session:38baa1de-...)
    

    1906 (root) + 3255 (children) = 5161 (unfiltered before-total) — exact,
    confirming SQL-level, mutually-exclusive partitioning.

    Before — read --all --limit 5 -f json:

    total_unit: None   total: 23496   n_items: 5
    (all 5 rows agent-*-suffixed children of the same parent session)
    

    After — same command:

    total_unit: top-level sessions   total: 15425   n_items: 5
    (all 5 rows top-level: 3 claude-code-session, 2 chatgpt-export)
    

Anti-vacuity statement

  • resolve_default_root_filter()'s production caller is
    polylogue/cli/archive_query.py::_execute_archive_query_stdout (the
    live polylogue find/read implementation exercised above against the
    real archive), plus polylogue/mcp/archive_support.py::archive_query_filters
    (MCP query/list tools), polylogue/archive/query/archive_execution.py::_plan_filter_kwargs
    (SessionFilter/Python API), and polylogue/daemon/http.py::_archive_filter_kwargs_from_spec
    (daemon HTTP session-list route, exercised by
    test_daemon_golden_parity.py against a real UDS server).
  • Reverting the root key from any of those four filter-kwargs
    dictionaries (or reverting resolve_default_root_filter to
    return root, dropping the default) makes
    test_no_root_flag_recovers_the_subagent_child_and_honest_total and
    test_bounded_pages_report_indexed_total fail (total reverts to the
    unfiltered structural count) and reintroduces the
    test_daemon_golden_parity.py parity gap.
  • Removing the lineage_seed_from_predicate exemption makes
    test_lineage_id_cli_query_materializes_parent_child_refs fail (the
    seeded family's child row disappears from the result set).

Ref polylogue-j8u2

Problem: subagent/branch children are 45.6% of the archive (8,614 of
18,871 sessions; 8,824 session_links rows with link_type='subagent',
measured 2026-07-29) and previously ranked equal to real top-level
sessions in every default result list. `polylogue find repo:polylogue`
returned rows like one parent session repeated 3x under different
agent-suffixed child ids, making the default result unreadable.

Solution: the `root` field/DSL clause/`--root`/`--no-root` flag already
existed (spec.root: bool | None, None = both). This change resolves the
unset case to root-only (top-level sessions) at the SQL-filter-kwargs
boundary via the new `resolve_default_root_filter()` helper
(polylogue/archive/query/spec.py), applied consistently across every
session-list/count/search entry point that was missing `root` pushdown
entirely or relying on an in-memory post-filter after LIMIT/OFFSET had
already truncated the page (pagination/count dishonesty):

  - polylogue/cli/archive_query.py: the CLI find/read hot path (its
    `_ArchiveFilterKwargs["root"]` already existed but was never
    defaulted); `_emit_list`/`_emit_search` gain a `total_unit` envelope
    field naming the counted unit (AC2); `_emit_daemon_list_payload`/
    `_emit_daemon_search_payload` propagate the daemon's `total_unit`.
  - polylogue/mcp/archive_support.py: `ArchiveQueryFilters` was missing
    `root` entirely -- MCP query/list never filtered by session
    structure at all, not even on an explicit `root:` clause.
  - polylogue/archive/query/archive_execution.py: the Python-API/
    SessionFilter path's `_ArchiveFilterKwargs` was also missing `root`
    (post-filter only, after SQL LIMIT).
  - polylogue/daemon/http.py: the daemon HTTP session-list route
    (`_archive_filter_kwargs_from_spec`) was a fourth parallel filter-kwargs
    builder, also missing `root` -- the deployed daemon (the normal
    runtime path per CLAUDE.md) would have silently kept the old
    unfiltered default even after the CLI/MCP fix landed.

The default is deliberately NOT written into `SessionQuerySpec.root`/
`SessionQueryPlan.root` themselves (which stay `None`-by-default,
reflecting genuine unset user intent) -- those fields feed
`has_filters()`, which many surfaces treat as a safety/routing signal
(unscoped-delete guards in query_actions.py/query_contracts.py, "bare
invocation shows stats" detection in root_request.py, `latest`
resolution). Silently defaulting `spec.root` itself to `True` would have
made every unfiltered query look "filtered" to those consumers,
bypassing an unscoped-mutation guard. `resolve_default_root_filter()` is
applied only at the point each surface builds its SQL filter-kwargs dict.

A `lineage:id:<ref>` predicate is itself an explicit request for one
session's whole family (root plus descendants), so
`resolve_default_root_filter()` exempts it via the new
`lineage_seed_from_predicate()` helper (polylogue/archive/query/predicate.py)
-- otherwise the root-only default would silently drop the children a
lineage-seeded query explicitly asked for (caught by an existing
regression test, test_lineage_id_cli_query_materializes_parent_child_refs).

Non-goals (per scope): no schema change, no storage/lineage semantic
change (polylogue-4ts territory) -- this is read-side query
planning/filtering/rendering only. fcyf's fanout-as-first-class-view
stays untouched.

Verification:
  - mypy --strict on every touched file: clean.
  - devtools test tests/unit/cli/ tests/unit/archive/ tests/unit/mcp/
    tests/unit/daemon/ tests/unit/api/ tests/unit/storage/test_topology_edges.py
    tests/unit/storage/test_session_topology.py: only pre-existing
    failures remain (confirmed against master e8a23cc via an isolated
    detached worktree -- title-fallback drift in
    test_cli_output_schemas.py/test_plain_cli_snapshots.py/
    test_assertion_candidate_evidence_disclosure.py, origin-enum
    completion drift in test_command_aux_runtime.py, unrelated
    facade-route/PTY/clock/materialization-bootstrap failures). All
    genuinely new failures from the default-flip were fixed: two
    intentional test updates (test_bounded_pages_report_indexed_total's
    stale total==2 assertion, now root-only total==1, plus a new
    companion test_no_root_flag_recovers_the_subagent_child_and_honest_total)
    and a real daemon/CLI parity gap (test_daemon_golden_parity.py) that
    surfaced the missing daemon-side root pushdown above.
  - devtools render all --check: sync OK (docs/cli-reference.md
    regenerated for the changed --root/--no-root help text; a
    __snapshots__/test_terminal_snapshots.ambr update was needed and
    included).

Ref polylogue-j8u2

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.

@coderabbitai

coderabbitai Bot commented Jul 31, 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: 23 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: 05dc14c1-d257-4989-81e6-1c06450a6a87

📥 Commits

Reviewing files that changed from the base of the PR and between d8d6a37 and 782c652.

📒 Files selected for processing (11)
  • docs/cli-reference.md
  • polylogue/archive/query/archive_execution.py
  • polylogue/archive/query/metadata.py
  • polylogue/archive/query/predicate.py
  • polylogue/archive/query/spec.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/click_option_groups.py
  • polylogue/daemon/http.py
  • polylogue/mcp/archive_support.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_query_exec_laws.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 21a0467 into master Jul 31, 2026
3 checks passed
@Sinity
Sinity deleted the feature/query/top-level-default-result-unit branch July 31, 2026 22:43
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