Repository navigation
feat(query): add parser-truthful discovery corpus and result semantics - #3066
Conversation
Add an executable corpus of query examples (106 positive, 18 negative) that teaches the real query DSL through production-parser-gated data instead of hand-authored strings, plus a shared result-semantics vocabulary (exhaustive/top-k/sample/aggregate/bounded-context/ recursive-page) bridged into the existing MCP declaration enum. Problem: MCP/CLI/docs teaching surfaces (cookbook prompts, search guide) shipped invalid query examples that fail against the real parser (confirmed: two MCP prompts and one docs snippet raised ExpressionCompileError at HEAD), and no discovery surface distinguished exact totals from ranked/sampled/aggregate/bounded results. Solution: - polylogue/archive/query/discovery.py: typed corpus (positive/negative rows with expression, parser route, unit source, projected columns, cost class) plus QUERY_DISCOVERY_GRAMMAR and RESULT_SEMANTICS_TEACHING. - polylogue/archive/query/transaction.py: shared QueryResultSemanticsContract coverage/total/continuation vocabulary. - polylogue/archive/query/completions.py: query_completions(kind= "example"|"error") now serve corpus-backed rows. - polylogue/mcp/server_prompts.py, server_resources.py: cookbook prompts and the query capability resource (now v2) render from the corpus and map its six classes onto the existing MCPResultSemantics enum without introducing a second taxonomy. - polylogue/cli/click_app.py, devtools/render_query_discovery.py, docs/search.md: root CLI help and a generated search-guide section render from stable corpus keys. - Every positive row is parsed by the real production route (compile_expression / parse_unit_source_expression) in tests/unit/archive/query/test_discovery.py; every negative row pins the exact ExpressionCompileError class/text/field and a corrected form that parses. This is the parser-gated discovery slice of polylogue-z9gh.3. It deliberately makes no grammar change (archive/query/expression.py is untouched) and does not implement typed structured-plan lowering, OpenAPI/JSON schema generation, live coverage/freshness/cardinality, current-value discovery, or the six-tool explain transaction — those remain open follow-on work. Reconciled against master drift (PR #3051, landed after this packet's 536a53e snapshot): regenerated docs/plans/topology-target.yaml and docs/topology-status.md, and updated one test assertion (test_agent_query_discovery_and_action_pages_share_one_registered_transaction) whose grammar.terminal_sources key moved to a top-level terminal_sources key as part of this same change's capability-resource v2 shape. Verification: - devtools render all --check (clean, no "out of sync") - devtools test tests/unit/archive/query/test_discovery.py tests/unit/archive/query/test_transaction.py tests/unit/archive/test_query_metadata.py tests/unit/cli/test_query_expression.py tests/unit/cli/test_completions_contract.py tests/unit/cli/test_query_discovery_help.py tests/unit/devtools/test_generated_surfaces.py tests/unit/devtools/test_query_teaching_surfaces.py tests/unit/devtools/test_render_query_discovery.py tests/unit/mcp/test_envelope_contracts.py tests/unit/mcp/test_server_surfaces.py -> 798 passed, 1 skipped - ruff format --check / ruff check / git diff --check: clean - mypy (strict) over the 9 changed production modules: clean (fixed a real loop-variable type collision in render_query_discovery.py that the source packet's own verification never ran) - Spot-checked 11 corpus rows across all six semantics classes against a seeded demo archive (polylogue demo seed): exhaustive/aggregate/ top-k/bounded-context executions matched their declared coverage semantics against real data (e.g. messages grouped by type: message=19, tool_use=14). Ref polylogue-z9gh.3 Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 38 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (20)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 36e629b541
ℹ️ 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".
Regenerate topology projections from the combined query discovery and current master source tree.
Problem Discovery taught exhaustive terminal-query totals as relation-wide even though QueryUnitEnvelope reports only the current page. Completion examples also omitted their route, so route-dependent semantics could not be reproduced by MCP clients. What changed Mark exhaustive totals as qualified and page-local, preserve declared routes on completion candidates, and expose the direct route vocabulary from the query capability resource. Regenerated query discovery docs and production-route tests pin both contracts. Compatibility/migration The capability resource drops its redundant corpus source string to remain inside the fixed MCP response budget while adding routes. Co-Authored-By: Claude <[email protected]>
Retain parser-validated discovery prompts while incorporating the merged continuity prompt updates.
…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]>
…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]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Adds an executable corpus of query examples (106 positive, 18 negative) that teaches the real query DSL through production-parser-gated data instead of hand-authored strings, plus a shared result-semantics vocabulary (
exhaustive/top-k/sample/aggregate/bounded-context/recursive-page) bridged into the existing MCP declaration enum. This is the parser-gated discovery slice ofpolylogue-z9gh.3.Problem
MCP/CLI/docs teaching surfaces shipped invalid query examples that fail against the real production parser:
polylogue/mcp/server_prompts.py:509(pre-patch):actions where session.repo:{repo}...since:{since} AND output:failed→ExpressionCompileError: invalid query expression near column 27(missingAND, missingsession.prefix onsince).polylogue/mcp/server_prompts.py:524(pre-patch):files where {repo_clause}path:{path}→field 'repo' is not supported for file predicates(repo is a session predicate, not a file predicate).docs/search.md:924(pre-patch): raw FTS5-styletext:css {...}: refactor→ unknown fieldtext(the DSL never exposedtextas a session field).Separately, no discovery surface distinguished exact totals (exhaustive) from ranked (top-k), sampled, aggregate-bucket, bounded-context, or recursive-page results, so a
limitcould be misread as totality.Solution
polylogue/archive/query/discovery.py— new typed corpus module: 106 positive rows (expression, parser route, unit source, one-sentence answer, semantics class, projected columns, cost class) + 18 negative rows (exactExpressionCompileErrorclass/text/field + a parser-valid correction).polylogue/archive/query/transaction.py— sharedQueryResultSemanticsContractcoverage/total/continuation vocabulary (six classes).polylogue/archive/query/completions.py—query_completions(kind="example"|"error")now serve corpus-backed rows instead of ad hoc strings.polylogue/mcp/server_prompts.py,server_resources.py— the four query-bearing cookbook prompts and the query capability resource (now v2) render from the corpus; the six generic semantics classes map onto the existingMCPResultSemanticsenum (exhaustive_page/top_k/sample/aggregate/bounded_context/recursive_graph) without introducing a second taxonomy.polylogue/cli/click_app.py,devtools/render_query_discovery.py,docs/search.md— root CLI help and a new generated search-guide section render from stable corpus keys.tests/unit/archive/query/test_discovery.py— anti-lying gate: every positive row is parsed through the real production route (compile_expressionfor session expressions,parse_unit_source_expressionfor terminal/pipeline expressions — this necessarily exercises the hand-written pipeline splitter); every negative row pins the exactExpressionCompileErrorand proves its correction parses.No grammar change:
polylogue/archive/query/expression.pyis untouched by this PR (verified:git diff --statagainst this file is empty).Scope — satisfied vs. deferred (polylogue-z9gh.3)
Satisfied by this slice:
query_completionsexample/error kinds, MCP query-capability resource.Explicitly not done here (remains open on
polylogue-z9gh.3/polylogue-z9gh.9.1/polylogue-t46.8.1):explaintransaction.z9gh.9.1's executor migration).Spot-checking against a seeded demo archive also surfaced (but this PR does not fix, since it's outside this corpus/discovery slice and touches unrelated execution code):
near:id:<ref>session-similarity queries execute without error but do not perform real similarity ranking through the genericfind/readCLI route (falls back to a plain unfiltered session list), and the declaredrecursive-pageprojection columns (parent_refs/child_refs/continuation) are not materialized by that same generic route forlineage:id:queries — both are pre-existing execution-layer gaps unrelated to this patch (confirmedarchive/query/expression.py,execution_control.py, andunit_results.pyare untouched by this diff), consistent with this corpus's own disclosed limitation that non-exhaustive/non-aggregate semantics classes are parser-valid but not execution-verified here.Provenance note
This PR lands external-agent (GPT Pro) packaged output (
mcp-04-discovery-corpus-r01.zip) generated against snapshot commit536a53efac0cbe4a2473ad379e4db49ef3fce74d, reviewed and reconciled against 13 commits of subsequent master drift, then verified independently in this repo (not merely re-run from the packet's own claims).Verification
git apply --checkagainst the snapshot commit's parent tree was clean except for two purely-generated files (docs/plans/topology-target.yaml,docs/topology-status.md); applied the rest and regenerated those two viadevtools render topology-projection && devtools render topology-status(repo convention for newpolylogue/modules).test_agent_query_discovery_and_action_pages_share_one_registered_transactionintests/unit/mcp/test_server_surfaces.pyasserting the old nestedgrammar["terminal_sources"]shape; this PR's capability-resource v2 moves that key to top-levelterminal_sources(as this PR's owntest_envelope_contracts.pyassertion already expects). Fixed the one assertion; no declarations/registry files were touched (polylogue/mcp/declarations/**andregistry.pyare untouched by this diff).devtools render all --check— clean (noout of sync).devtools test tests/unit/archive/query/test_discovery.py tests/unit/archive/query/test_transaction.py tests/unit/archive/test_query_metadata.py tests/unit/cli/test_query_expression.py tests/unit/cli/test_completions_contract.py tests/unit/cli/test_query_discovery_help.py tests/unit/devtools/test_generated_surfaces.py tests/unit/devtools/test_query_teaching_surfaces.py tests/unit/devtools/test_render_query_discovery.py tests/unit/mcp/test_envelope_contracts.py tests/unit/mcp/test_server_surfaces.py→ 798 passed, 1 skipped.ruff format --check/ruff check/git diff --checkover all changed files — clean.mypy(strict, whole repo:polylogue tests devtools) — clean. Found and fixed two real type errors the source packet's own verification never caught (a loop-variable type collision from reusingrowacross two differently-typed loops indevtools/render_query_discovery.pyand again intests/unit/archive/query/test_discovery.py, plus an unannotated polymorphic Pydantic-model dict needing an explicittype[SurfacePayloadModel]annotation).devtools verify --quick(format + lint + mypy +render all --check) — clean; this is what the pre-push hook runs and it now passes.polylogue demo seedarchive using the real production execution paths (find ... then read,query_unit_rows): exhaustive queries returned exact totals (including real zero-match cases), the aggregate query correctly bucketed real data (role:assistantmessages by type:message=19,tool_use=14), top-k returned a qualified/null total undermode: "search", and bounded-context correctly projected the declaredmessages(message_id,role,text)columns.Ref polylogue-z9gh.3