Skip to content

feat(query): execute structural and sequence predicates (#2006) - #2011

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/query-structural-exists-2006
Jun 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/query-structural-exists-2006

Conversation

@Sinity

@Sinity Sinity commented Jun 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds executable structural and sequence query predicates to the #2006 DSL path. exists message(...), exists action(...), and seq(action:a -> action:b) now parse into the typed predicate AST and lower into SQLite predicates against messages, blocks, the actions view, and the existing ordered action-sequence lowerer.

Problem

After #2010, Boolean predicates could combine session-level fields, but the DSL still could not ask archive-evidence questions such as “sessions with an assistant message mentioning timeout,” “sessions with a file edit under this path,” or “sessions where file edit happened before a shell run.” That left #2006's structural and sequence lowerers as parser-only target language instead of executable query behavior.

Solution

Introduced QueryExistsPredicate and QuerySequencePredicate, extended the Lark Boolean grammar with exists message(...), exists action(...), and seq(...), and wired storage lowering to correlated EXISTS clauses plus the archive's existing action-sequence SQL. Structural fields now cover message role/type/text/words and action tool/action/command/path/output/text, with typed unit-ownership and value validation so malformed structural fields cannot fall through to SQLite. Review feedback also tightened structural alternation and path handling: field:(a|b) preserves OR semantics inside correlated SQL, multi-term LIKE clauses are parenthesized, and structural path matching normalizes backslashes like the session-level path filter.

Verification

  • nix develop --command devtools test tests/unit/cli/test_query_expression.py -> 187 passed in 24.22s
  • nix develop --command devtools verify --quick -> exit_code: 0
  • pre-push devtools verify --quick on 32ea3acf -> exit_code: 0

Ref #2006

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds QueryExistsPredicate and QuerySequencePredicate dataclasses to the query predicate model, extends the Lark-backed Boolean DSL grammar and lowerer to parse and validate exists(message|action)(...) and seq(...) constructs, and adds corresponding SQL clause builders in ArchiveStore that emit session-scoped EXISTS subqueries and dispatch action-sequence SQL. Tests cover both AST compilation and end-to-end archive execution.

Changes

Structural query predicates: exists() and seq()

Layer / File(s) Summary
New predicate dataclasses and type union
polylogue/archive/query/predicate.py
Adds QueryExistsPredicate (unit + child predicate) and QuerySequencePredicate (ordered action terms) frozen dataclasses each with to_payload(); expands QueryPredicate TypeAlias and __all__.
Boolean grammar extensions and expression lowerer
polylogue/archive/query/expression.py
Extends the Lark grammar atom production with exists(...) and seq(...) rules; introduces structural field sets; reworks field validation and error messaging; adds exists_leaf and seq transformer methods with validation; broadens Boolean-expression detection regex; validates the produced predicate tree with unit="session" context.
SQL clause builders for exists() and seq()
polylogue/storage/sqlite/archive_tiers/archive.py
Adds internal helpers for equality/IN, numeric, and LIKE matching; message- and action-level predicate-to-SQL translators with EXISTS subqueries; recursive AND/OR/NOT composition; QueryExistsPredicate → session-scoped EXISTS subquery; QuerySequencePredicate dispatch; extends _boolean_predicate_clause dispatch.
AST and integration tests
tests/unit/cli/test_query_expression.py
Adds AST unit tests for exists message(...) and seq(...) predicate nodes and ExpressionCompileError rejection cases; adds end-to-end archive execution tests for exists message, exists action, and seq queries against seeded sessions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • feat(query): implement the full query DSL substrate #2006: This PR directly implements the exists(message|action)(...) and seq() structural query constructs, new predicate types (QueryExistsPredicate, QuerySequencePredicate), and the AST-based parser + SQL lowering pipeline described in that issue's Phase 1 scope.

Possibly related PRs

  • Sinity/polylogue#1861: This PR extends the same Boolean expression compiler in polylogue/archive/query/expression.py that was introduced in PR #1861, adding new grammar productions and lowering paths on top of that shared foundation.

Poem

🐇 Hippity-hop through the query tree,
exists(message) found what I wanted to see!
seq(action:start -> action:done) in a row,
SQL subqueries built, watch the sessions glow.
The rabbit parses grammar with Lark-powered cheer,
New predicates bloom — the results are right here! 🌸

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and concisely describes the main change: adding executable structural and sequence predicates to the query system, which is the primary objective of this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description covers all required template sections with substantial detail: Summary clearly states what changed, Problem explains the underlying need, Solution describes implementation approach across multiple modules, and Verification provides specific test commands with results.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/query-structural-exists-2006

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.

@Sinity
Sinity force-pushed the feature/feat/query-structural-exists-2006 branch from 6034958 to 7d70c05 Compare June 17, 2026 01:40
@Sinity Sinity changed the title feat(query): execute structural exists predicates (#2006) feat(query): execute structural and sequence predicates (#2006) Jun 17, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 60349589a3

ℹ️ 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".

Comment thread polylogue/archive/query/expression.py Resolved
@Sinity
Sinity force-pushed the feature/feat/query-structural-exists-2006 branch from 7d70c05 to 3752fef Compare June 17, 2026 01:42
@Sinity

Sinity commented Jun 17, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Sinity
Sinity force-pushed the feature/feat/query-structural-exists-2006 branch from 3752fef to 64645fb Compare June 17, 2026 01:45

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/archive/query/expression.py`:
- Around line 588-600: The current validation in _validate_predicate_context
function only checks if the field name is supported but does not validate the
actual predicate values. Add validation logic after the field membership check
to validate the predicate.value attribute, ensuring that structural values are
of the correct type (e.g., numeric values where required) and are not empty,
which would prevent invalid inputs from reaching the SQLite lowering phase and
causing failures like malformed SQL with dangling AND operators or type
conversion errors.

In `@polylogue/storage/sqlite/archive_tiers/archive.py`:
- Around line 4377-4382: The path filtering in the action_column dictionary for
the "path" key does not normalize path separators, which causes archived paths
with backslashes (Windows-style) to be missed when matching forward slash
predicates. Apply path normalization (converting backslashes to forward slashes)
in the COALESCE expression for the "path" field in the action_column dictionary
at line 4379, similar to how session-level path filters normalize paths. Also
apply the same normalization fix to the similar path comparison code at lines
4403-4404 to ensure consistent path matching across all structural predicate
clauses.
- Around line 4327-4332: The _like_clause function currently joins multiple LIKE
conditions with AND, but the documented behavior for field:(a|b) syntax requires
OR logic instead. Change the join operation in the return statement of
_like_clause from " AND ".join(clauses) to " OR ".join(clauses) so that
expressions like message(text:(timeout|failure)) will match text containing
either term rather than requiring both terms to be present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e57cf8d2-5d50-48ed-9f91-8fc969df9ef6

📥 Commits

Reviewing files that changed from the base of the PR and between 5fd1652 and 3752fef.

📒 Files selected for processing (4)
  • polylogue/archive/query/expression.py
  • polylogue/archive/query/predicate.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/cli/test_query_expression.py

Comment thread polylogue/archive/query/expression.py Resolved
@Sinity
Sinity force-pushed the feature/feat/query-structural-exists-2006 branch from 64645fb to 32ea3ac Compare June 17, 2026 01:55
@Sinity

Sinity commented Jun 17, 2026

Copy link
Copy Markdown
Owner Author

Review follow-up on CodeRabbit's final actionable set:

  • structural field scope/value validation: fixed via ; added compile-time rejection tests for top-level and non-numeric structural .
  • structural alternation OR semantics: fixed in ; added regression. This also found and fixed the SQL-precedence issue by parenthesizing multi-term LIKE clauses.
  • structural path normalization: fixed lowering for action/message structural predicates with ; added a backslash-path fixture.

Verification after these fixes: ============================= test session starts ==============================
platform linux -- Python 3.13.12, pytest-9.0.3, pluggy-1.6.0
cachedir: .cache/pytest
benchmark: 5.2.3 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
Using --randomly-seed=775090175
rootdir: /realm/project/polylogue
configfile: pyproject.toml
plugins: json-report-1.5.0, testmon-2.2.0, xdist-3.8.0, metadata-3.1.1, syrupy-5.1.0, benchmark-5.2.3, cov-7.1.0, anyio-4.13.0, randomly-4.1.0, hypothesis-6.152.8, asyncio-1.4.0, timeout-2.4.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
collected 187 items

tests/unit/cli/test_query_expression.py ................................ [ 17%]
........................................................................ [ 55%]
........................................................................ [ 94%]
........... [100%]

============================= 187 passed in 22.36s ============================= -> 187 passed; {
"timestamp": "2026-06-17T01:56:10.517515+00:00",
"git_head": "32ea3acf1a34120f2ea2a0aaa67ee414a627660a",
"tier": "quick",
"steps": [
{
"name": "ruff format",
"duration_s": 0.02,
"exit": 0
},
{
"name": "ruff check",
"duration_s": 0.01,
"exit": 0
},
{
"name": "mypy",
"duration_s": 0.62,
"exit": 0
},
{
"name": "render-all",
"duration_s": 2.19,
"exit": 0
},
{
"name": "verify-topology",
"duration_s": 0.39,
"exit": 0
},
{
"name": "verify-layering",
"duration_s": 1.02,
"exit": 0
},
{
"name": "verify-closure-matrix",
"duration_s": 0.26,
"exit": 0
},
{
"name": "verify-schema-roundtrip",
"duration_s": 0.85,
"exit": 0
},
{
"name": "verify-manifests",
"duration_s": 2.14,
"exit": 0
},
{
"name": "verify-ci-workflows",
"duration_s": 0.31,
"exit": 0
},
{
"name": "verify-doc-commands",
"duration_s": 1.51,
"exit": 0
},
{
"name": "verify-lane-assertions",
"duration_s": 0.89,
"exit": 0
},
{
"name": "verify-test-infra-currency",
"duration_s": 0.37,
"exit": 0
},
{
"name": "verify-test-clock-hygiene",
"duration_s": 1.38,
"exit": 0
},
{
"name": "public-surface-audit",
"duration_s": 0.07,
"exit": 0
}
],
"total_duration_s": 12.28,
"exit_code": 0
} -> exit_code 0; pre-push quick on 32ea3ac -> exit_code 0.

@Sinity

Sinity commented Jun 17, 2026

Copy link
Copy Markdown
Owner Author

Corrected review follow-up for CodeRabbit's final actionable set:

  • structural field scope/value validation: fixed via _validate_predicate_context; added compile-time rejection tests for top-level role: and non-numeric structural words:.
  • structural alternation OR semantics: fixed in _like_clause; added exists message(text:(timeout|panic)) regression. This also found and fixed the SQL-precedence issue by parenthesizing multi-term LIKE clauses.
  • structural path normalization: fixed path: lowering for action/message structural predicates with REPLACE(..., char(92), '/'); added a backslash-path fixture.

Verification after these fixes: devtools test tests/unit/cli/test_query_expression.py -> 187 passed; devtools verify --quick -> exit_code 0; pre-push quick on 32ea3acf -> exit_code 0.

@Sinity
Sinity merged commit def884e into master Jun 17, 2026
13 checks passed
@Sinity
Sinity deleted the feature/feat/query-structural-exists-2006 branch June 17, 2026 01:58
Sinity added a commit that referenced this pull request Jun 17, 2026
## Summary
Adds executable lexical predicates to the #2006 Boolean DSL. `~term` and
`~"quoted phrase"` now parse into a typed `QueryTextPredicate` and lower
into a correlated FTS5 filter against `messages_fts` joined through
`blocks`.

## Problem
After #2011, the DSL could execute session fields, structural
`exists(...)`, and action `seq(...)`, but lexical text inside Boolean
predicates was still not representable. That meant users could not write
queries such as `sessions where origin:chatgpt-export AND ~"timeout
failure"` without dropping back to the older flat ranked FTS path.

## Solution
Introduced `QueryTextPredicate`, extended the Lark Boolean grammar with
`~text` / `~"phrase"`, and wired the archive Boolean lowerer to
`messages_fts MATCH ?`. Because `messages_fts` is contentless and its
unindexed columns read back as NULL, the lowerer joins `blocks` by rowid
for session correlation, matching the existing search path's storage
reality. This PR gives Boolean FTS filter semantics; the existing flat
query-term path remains the ranked lexical search path.

## Verification
- `nix develop --command devtools test
tests/unit/cli/test_query_expression.py` -> `190 passed in 24.52s`
- `nix develop --command devtools verify --quick` -> `exit_code: 0`
- pre-push `devtools verify --quick` on pushed branch -> `exit_code: 0`

Ref #2006
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 59.F053 / P2: fixed-already at the checked revision: polylogue/archive/query/expression.py:1751-1764 validates session predicates against the session field set and raises ExpressionCompileError for fields outside it. Top-level role/text predicates are rejected at binding instead of reaching the session SQL lowerer.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 75.F036 / P2: fixed-already at the checked revision: The shared LIKE lowerer now defaults to OR at polylogue/storage/sqlite/archive_tiers/archive_query_reads.py:1689. Message text predicates invoke it without overriding that joiner at :1742, so text:(timeout|error) accepts either alternate instead of requiring both.

Only the rows listed above are dispositioned. Held findings remain open.

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