Skip to content

fix(query): rank near:id: and materialize lineage:id: projection - #3296

Merged
Sinity merged 2 commits into
masterfrom
feature/query/near-lineage-execution-materialize
Jul 27, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/query/near-lineage-execution-materialize

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes two pre-existing, execution-layer-only gaps in the generic find/read
CLI query route: near:id:<ref> silently fell back to an unfiltered session
list instead of real vector-similarity ranking, and lineage:id:<ref> never
materialized its declared parent_refs/child_refs/continuation
recursive-graph projection columns.

Problem

polylogue-z9gh.3's 2026-07-20 note narrowed the bead's remaining scope to
two "size S" residuals, confirmed via a spot-check against a seeded demo
archive: near:id: executes without error via the generic find/read CLI
route but does not perform real similarity ranking (falls back to an
unfiltered session list), and the declared recursive-page projection columns
are not materialized by that same route for lineage:id: queries.

I independently re-verified both against a live polylogue demo seed
archive before writing any fix:

  • polylogue find 'near:id:<seed>' --format json returned the exact same
    19-session list, in the same order, as a query with no filter at all.
  • polylogue find 'lineage:id:<parent>' --format json correctly narrowed to
    the 2-session lineage family (the SQL-level filter already worked), but
    neither row carried parent_refs, child_refs, or continuation.

Root cause for near:id:: polylogue/cli/archive_query.py's hand-rolled
search-execution path (_query_hits, _daemon_session_page_supported,
_try_emit_daemon_session_page) only ever threaded similar_text through;
SessionQuerySpec.similar_session_id was never read anywhere in that file,
so a bare near:id: predicate (no FTS terms, no similar_text) fell through
every branch straight to the plain archive.list_summaries(**filter_kwargs)
call. (The separate SessionFilter/archive_execution.py route already had
correct vector-seeded ranking since PR #3018 — this bug was isolated to the
CLI's own parallel execution path.)

Root cause for lineage:id:: the SQL-level QueryLineagePredicate filter
(via boolean_predicate) was correct, but no code anywhere translated the
declared RECURSIVE_COLUMNS (session_id, parent_refs, child_refs,
continuation) from archive/query/discovery.py into actual payload fields.

Solution

  • polylogue/cli/archive_query.py: thread similar_session_id through
    _query_hits the same way similar_text already is. When set, it calls
    the existing VectorProvider.query_by_session mechanism (the same
    mechanism archive_execution.py's _session_seed_scored already uses for
    the SessionFilter route) rather than building new vector-search code.
    Raises a typed click.UsageError when no vector backend is configured or
    the seed session has no stored embeddings, matching the existing
    near:"text" error contract. Also excludes similar_session_id from the
    daemon session-page fast path (_daemon_session_page_supported), since
    that fast path's /api/sessions split-archive route has the identical gap
    and forcing local execution is the minimal fix within this file's scope.
  • polylogue/storage/sqlite/archive_tiers/archive.py: adds
    ArchiveStore.session_lineage_edges, a small bounded query over the
    existing sessions.parent_session_id column (the same column
    lineage:id: already filters on via root_session_id) returning direct
    one-hop parent/child ids for a page of session ids — no new recursive
    graph traversal.
  • polylogue/cli/archive_query.py + polylogue/surfaces/payloads.py: when a
    list page's boolean_predicate carries a QueryLineagePredicate
    (lineage:id:), look up per-page lineage edges and populate
    SessionListRowPayload.parent_refs/child_refs/continuation.
    continuation mirrors the page's own pagination cursor; edges are
    qualified per page, consistent with the "recursive-page" result-semantics
    contract already documented in archive/query/discovery.py
    (RESULT_SEMANTICS_TEACHING).
  • Regenerated docs/schemas/cli-output/session-list-row.schema.json,
    docs/openapi/search.yaml, and webui/src/api/generated.ts for the two
    new payload fields.

No grammar changes: polylogue/archive/query/expression.py is untouched.

Verification

  • Manual, against a seeded demo archive: near:id:<ref> now raises a typed
    error instead of returning the full session list; lineage:id:<ref> now
    emits parent_refs/child_refs per row.
  • devtools test tests/unit/cli/test_query_exec_laws.py — 88 passed (adds 3
    new tests: real vector-ranked near:id: through the CLI route with an
    assertion that list_summaries is never reached, a typed UsageError
    with no vector backend configured, and a real-archive lineage:id: test
    via SessionBuilder/write_parsed_session_to_archive proving
    parent_refs/child_refs materialize correctly against production
    ArchiveStore SQL, not a mock).
  • devtools test tests/unit/cli/test_archive_query.py tests/unit/cli/test_cli_output_schemas.py — 135 passed.
  • devtools test tests/unit/archive/test_near_session_seed_execution.py tests/unit/storage/test_vec_session_seed.py — 9 passed.
  • devtools test tests/unit/mcp/test_query_request_contracts.py tests/unit/cli/test_query_expression.py tests/unit/cli/test_select.py — 449 passed, 1 skipped.
  • mypy on all three changed source files — no issues.
  • ruff check + ruff format --check — clean.
  • devtools render all --check — sync OK, no "out of sync" lines.
  • devtools verify --quick — exit 0 (also ran automatically via the pre-push hook).

Not run: devtools verify --all/full suite — seeding pytest-testmon from
scratch triggered a large, apparently pre-existing failure spread across the
whole suite baseline unrelated to these three files; the targeted
devtools test runs above cover every file this change touches or could
plausibly affect.

Ref polylogue-z9gh.3

Problem: the generic find/read CLI route (cli/archive_query.py) never
checked SessionQuerySpec.similar_session_id at all. A near:id:<ref>
query silently fell through to a plain unfiltered list_summaries page
(verified against a live demo archive: identical 19-session order with
and without the near:id: predicate). Separately, lineage:id:<ref>
correctly filtered rows to their shared-root session family via SQL,
but the declared recursive-graph projection columns (parent_refs,
child_refs, continuation) were never populated on the emitted rows.

Both gaps were confirmed pre-existing, execution-layer-only (no grammar
change) residuals of polylogue-z9gh.3, scoped "size S" in its own notes.

Solution:
- cli/archive_query.py: thread similar_session_id through _query_hits
  (and the daemon-fast-path bail-out) the same way similar_text already
  is, reusing the existing VectorProvider.query_by_session mechanism
  that already backs archive_execution.py's session-seed ranking for
  the SessionFilter route. No new vector search was built; near:id:
  now raises a typed click.UsageError when no vector backend is
  configured or the seed session has no embeddings, matching the
  existing near:"text" error contract, instead of degrading silently.
- storage/sqlite/archive_tiers/archive.py: add ArchiveStore.session_lineage_edges,
  a small bounded query over the existing sessions.parent_session_id
  column (the same column lineage:id: already filters on) returning
  direct one-hop parent/child ids for a given set of session ids.
- cli/archive_query.py + surfaces/payloads.py: when a list page's
  boolean_predicate carries a QueryLineagePredicate (lineage:id:), look
  up per-page lineage edges and populate SessionListRowPayload.parent_refs/
  child_refs/continuation (continuation mirrors the page's own cursor;
  edges are qualified per page, matching the documented recursive-page
  result-semantics contract in archive/query/discovery.py).
- Regenerated docs/schemas/cli-output/session-list-row.schema.json,
  docs/openapi/search.yaml, and webui/src/api/generated.ts for the two
  new payload fields.

Verification:
- Manual: `polylogue find 'near:id:<ref>'` against a seeded demo archive
  now raises a typed error instead of returning the full session list;
  `polylogue find 'lineage:id:<ref>'` now emits parent_refs/child_refs
  per row.
- devtools test tests/unit/cli/test_query_exec_laws.py: 88 passed
  (adds 3 new tests: real vector-ranked near:id: through the CLI route
  with an assertion that list_summaries is never reached, a typed
  UsageError with no vector backend, and a real-archive lineage:id:
  test via SessionBuilder/write_parsed_session_to_archive proving
  parent_refs/child_refs materialize correctly, not just against a mock).
- devtools test tests/unit/cli/test_archive_query.py tests/unit/cli/test_cli_output_schemas.py: 135 passed
- devtools test tests/unit/archive/test_near_session_seed_execution.py tests/unit/storage/test_vec_session_seed.py: 9 passed
- devtools test tests/unit/mcp/test_query_request_contracts.py tests/unit/cli/test_query_expression.py tests/unit/cli/test_select.py: 449 passed, 1 skipped
- mypy --strict on all three changed source files: no issues
- ruff check + ruff format --check: clean
- devtools render all --check: sync OK, no "out of sync" lines
- devtools verify --quick: exit_code 0

Not run: devtools verify --all / full-suite (seeding testmon from
scratch triggered a large pre-existing, unrelated failure spread
across the whole suite baseline; targeted devtools test runs above
cover every file this change touches or could affect).

Ref polylogue-z9gh.3

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tc6qUpovdFFKtWH5AMSdZA
@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 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: 42 seconds

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: 5edfba85-76df-43b0-8f61-eb1ac3d40669

📥 Commits

Reviewing files that changed from the base of the PR and between 07b74da and 6d1d53c.

📒 Files selected for processing (7)
  • docs/openapi/search.yaml
  • docs/schemas/cli-output/session-list-row.schema.json
  • polylogue/cli/archive_query.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/surfaces/payloads.py
  • tests/unit/cli/test_query_exec_laws.py
  • webui/src/api/generated.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/query/near-lineage-execution-materialize

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.

Problem: _lineage_seed_from_predicate (added earlier in this branch to
materialize lineage:id:'s parent_refs/child_refs/continuation
projection) walked into every QueryBoolPredicate's children regardless
of the boolean operator. A query like "lineage:id:X or repo:foo" would
still detect X as the lineage seed and stamp X's lineage refs onto
every row in the result - including rows that only matched via the
unrelated `or` branch and were never actually part of X's lineage
family. An `and`-combined lineage clause is unaffected: AND only
narrows the result set further, so every remaining row genuinely is a
lineage-family member.

What changed: the QueryBoolPredicate branch now only recurses when
predicate.op == "and".

Verification: tests/unit/cli/test_query_exec_laws.py -
test_lineage_seed_from_predicate_ignores_or_combined_lineage_clause
directly exercises the function against synthetic and/or-combined
predicate trees (confirmed it fails without the fix - asserted a seed
where None was expected). Full file: 89 passed. mypy --strict clean.
ruff check + format clean.
@Sinity

Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner Author

Self-review finding + fix (CodeRabbit rate-limited on this PR's pushes, so I reviewed it myself): `_lineage_seed_from_predicate` recursed into every `QueryBoolPredicate` child regardless of the boolean operator. A query like `lineage:id:X or repo:foo` would still detect X as the seed and stamp X's parent_refs/child_refs onto every row in the result — including rows that only matched via the unrelated `or` branch and were never part of X's lineage family at all. Fixed by only recursing on `op == "and"` (AND only narrows further, so it's still correct there). Added a direct regression test against synthetic and/or-combined predicate trees.

@Sinity
Sinity merged commit 30f26fe into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the feature/query/near-lineage-execution-materialize branch July 27, 2026 03:42
Sinity added a commit that referenced this pull request Jul 27, 2026
…DSL (#3330)

## Summary

Adds a canonical, versioned Pydantic AST schema for the query DSL's
compiled
predicate tree, unit-source pipelines, and lowering plan, and wires it
into
`devtools render openapi` so the shape is published in
`docs/openapi/search.yaml` (and the derived `webui/src/api/generated.ts`
TypeScript client).

## Problem

`polylogue-z9gh.3`'s design explicitly calls for "typed structured-plan
lowering to one AST" and OpenAPI/JSON schema generation for the query
discovery vocabulary. Most of that program already shipped (#3018,
#3066,
#3296), but the bead's own notes named exactly one residual not yet
attempted: **"structured-plan -> canonical AST lowering + OpenAPI
generation"** (sized M). `explain_expression()` already computes a
compiled
predicate tree and per-branch `ast`/`lowering_plan` dicts (see

`polylogue/archive/query/expression.py:_ast_payload`/`_lowering_plan_payload`/
`QueryExpressionExplanation.to_payload`), but they were hand-rolled
`dict[str, object]` shapes: correct, but opaque to external tooling. An
MCP
client or an OpenAPI-generated SDK only ever saw an untyped dict with no
documented schema.

## Solution

- **New `polylogue/archive/query/query_ast_schema.py`**: Pydantic models
  mirroring every existing predicate/pipeline-stage/clause dataclass's
  `to_payload()` shape one-to-one — `QueryPredicateAst` (a discriminated
  union covering field/not/and-or/exists/sequence/fts/semantic/lineage
  predicates), clause/ref-operand/pipeline-stage projections, and the
  top-level `QueryExpressionExplanationAst`. This is deliberately a
  *validating projection*, not a second AST or a parallel IR:
  `predicate_to_ast()` / `explanation_payload_to_ast()` validate the
dataclasses' own existing `to_payload()` output against the schema, so
if
  a producer's payload shape ever drifts from what's declared here, a
  Pydantic `ValidationError` surfaces immediately in the new test file
  rather than the drift silently reaching an agent or generated client.
- Versioned as `polylogue.query-explain-ast.v1`
(`QUERY_AST_SCHEMA_VERSION`), kept a **distinct axis** from the existing
  `polylogue.query-definition.v1` content-hashing protocol version in
  `polylogue/core/query_identity.py` — the module docstring explains why
they must not be conflated (one versions the content-addressed predicate
  grammar used for query hashing/identity, the other versions this new
  broader discovery/explain envelope).
- `QueryExpressionExplanation.to_payload()` now stamps `schema_version`
—
  the only new key added to the existing payload shape. MCP
`explain(kind="query")` and `Polylogue.explain_query_expression()`
callers
  pick it up automatically with no call-site changes.
- **`devtools/render_openapi.py`**: publishes
`QueryExpressionExplanationAst`
  (with its full nested `$defs` graph — every predicate/pipeline-stage
variant) as a component schema in `docs/openapi/search.yaml`, plus a new
`x-polylogue-query-ast` vendor extension documenting the schema version,
  the root schema ref, and how to obtain a live instance (there's no
  existing daemon HTTP route for query explain, only the MCP `explain`
  operation and the Python facade, so the extension says that explicitly
  rather than implying a route that doesn't exist).
- Regenerated `docs/openapi/search.yaml`, `webui/src/api/generated.ts`
(the
  typed TS client derives from the OpenAPI doc), and
`docs/plans/topology-target.yaml` / `docs/topology-status.md` (new
module
  under `polylogue/`, per this repo's topology-projection convention).

### What's covered vs. deferred

Covered: a documented, versioned, round-trip-tested AST for the
`SessionQuerySpec.boolean_predicate` tree (the actual "structured plan"
a
compiled query lowers to), the
clause/pipeline/unit-source/reference-operand
projections `explain_expression()` already emits, and OpenAPI
publication of
all of it.

Deferred (explicitly out of scope for this residual, not silently
dropped):
no new HTTP route for query-explain was added (MCP + Python facade
remain
the only live surfaces); the `unit_source.pipeline_stages`
transform-stage
vocabulary member (`QueryUnitTransformStageAst`) is modeled but has no
producer yet (matches upstream's own "reserved vocabulary member" note
on
`QueryUnitTransformStage`); this PR does not touch execution-layer gaps
(those were already handled separately in #3296).

## Verification

- `devtools test tests/unit/archive/query/test_query_ast_schema.py` — 28
passed: predicate↔AST round trip over 11 representative predicate shapes
  (field/not/and/or/exists/sequence/fts/semantic/lineage), full
  explanation-payload validation over 13 representative DSL expressions
(compact field query, Boolean AND/OR, `near:"..."` semantic,
`lineage:id:`,
`exists`, `seq(...)`, pipeline stages sort/limit/offset, group-by-count
  aggregate, raw JSON spec, durable-reference pipeline
  `from result-set:... | ...`, terminal unit sources), a JSON-Schema
  buildability check, and two schema-drift rejection tests.
- Ad hoc sweep (not part of the committed test file, but run manually
before
  writing it) of all 106 positive rows in
`archive/query/discovery.py:QUERY_DISCOVERY_EXAMPLES` validated cleanly
  against the new schema with 0 failures.
- `devtools test tests/unit/cli/test_query_expression.py
  tests/unit/archive/query/test_predicate_payload_roundtrip.py
  tests/unit/devtools/test_render_openapi.py
  tests/unit/api/test_facade_contracts.py` — 751 passed, 1 skipped (no
  regressions in the explain/predicate/OpenAPI surfaces touched by this
  change).
- `mypy --strict` and `ruff check`/`format` clean on all touched files.
- `devtools render all --check` — sync OK on every generated surface
  (openapi, webui-client, topology-status, and the rest).
- Not run: the full non-slow test suite / `devtools verify
--seed-testmon`
  (it stalled 600s into an unrelated part of the corpus, after cleanly
  finishing every test in this PR's own file — consistent with heavy
concurrent test load from other agent worktrees sharing this host at the
  time, not a regression introduced here). The pre-push hook's
`devtools verify --quick` (format + lint + mypy + render-all-check) ran
  and passed on push.

Ref polylogue-z9gh.3


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added a versioned, canonical schema for query explanations and
compiled query ASTs.
* Query explanations now include a schema version and validated
predicate, pipeline, and lowering-plan details.
* Published the query AST schema through the OpenAPI specification for
external tooling.
* Added generated TypeScript types for query AST and pipeline
structures.

* **Documentation**
* Documented how to obtain query AST explanations and the schema’s
supported structures.

* **Tests**
* Added coverage for AST round trips, schema validation, serialization,
and rejection of invalid data.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 27, 2026
…LUMNS (#3350)

## Summary
Fixes a live, currently-red parity gap between the query discovery
corpus's declared session projection columns and the real
`SessionListRowPayload` model shape, discovered while auditing
`polylogue-z9gh.3`'s closure state.

## Problem
PR #3296 (near/lineage execution materialize) added
`parent_refs`/`child_refs`/`continuation` fields to
`SessionListRowPayload` (populated only for lineage-seeded
`lineage:id:<ref>` pages) but never updated the discovery corpus's
`SESSION_COLUMNS` declaration in `polylogue/archive/query/discovery.py`
to match.
`tests/unit/archive/query/test_discovery.py::test_declared_projection_columns_track_public_row_payload_models`
— an anti-vacuity parity check added in PR #3066 specifically to catch
this class of drift — is failing on current `master`:

```
AssertionError: assert ('id', 'origi...actions', ...) == ('id', 'origi...actions', ...)
Right contains 3 more items, first extra item: 'parent_refs'
```

This is exactly the drift class named in `polylogue-z9gh.3` AC7: "a
missing projection/registration/coverage/parity mapping fails one
actionable check" — the check fired correctly, but nobody had fixed the
drift it caught.

## Solution
Added `parent_refs`, `child_refs`, `continuation` to `SESSION_COLUMNS`
in `polylogue/archive/query/discovery.py` (present on every session row;
null except on lineage-seeded pages), keeping the `session-repository`
example's `projection_columns` byte-identical to the real payload model.
Regenerated `docs/search.md` via `devtools render query-discovery`
(mechanical: 3 new column names appended to the featured session
examples' projection cell). No grammar or payload-model change.

## Verification
- `devtools test tests/unit/archive/query/test_discovery.py
tests/unit/archive/query/test_query_ast_schema.py` → 159 passed (was 1
failed / 158 passed before this fix)
- `devtools render all --check` → exit 0, all surfaces sync OK
- `devtools verify --quick` → exit 0

Ref polylogue-z9gh.3

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