Skip to content

fix(query): pin session-scoped index for bounded action relation - #3200

Merged
Sinity merged 1 commit into
masterfrom
fix/query/z9gh-execution-residuals
Jul 20, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/query/z9gh-execution-residuals

Conversation

@Sinity

@Sinity Sinity commented Jul 20, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the polylogue-z9gh.2 F-006/F-007 residual: a session-scoped action/delegation query (e.g. actions where session.id:X AND is_error:true, or the | group by followup_class | count variant) could still plan an archive-wide idx_blocks_type_tool scan of every tool_use/tool_result block in the archive, instead of a cheap session-scoped index seek — even after PR #3018 (z9gh.2) replaced the old windowed-view actions relation with the action_pairs-backed one and added exact-session-id extraction from the query predicate.

Problem

Investigation (polylogue-z9gh evidence matrix) flagged this residual as "unconfirmed-fixed." Root-causing it found the predicate-lowering side was already correct: _exact_session_ids_from_predicate / _action_relation_for_query (polylogue/storage/sqlite/archive_tiers/archive.py) already narrow a session.id:X predicate to an exact session bound for both the plain-count and the follow-up-relation-needing (followup_class) paths.

The residual was physical, not logical: action_relation_select_sql (polylogue/storage/sqlite/action_relation.py) had no way to force SQLite onto the session-scoped index, and a fresh ArchiveStore-bootstrapped archive never seeds sqlite_stat1 — initialize_archive_tier (polylogue/storage/sqlite/archive_tiers/bootstrap.py) just runs conn.executescript(spec.ddl) with no ANALYZE/stat seeding, unlike the separate connection-pool bootstrap in polylogue/storage/sqlite/schema.py (_ensure_schema, which does seed PLANNER_STAT1_SEED_SQL — this is a genuinely different bootstrap path used elsewhere, not the one ArchiveStore() goes through). Without stats, SQLite's planner defaults to the low-cardinality idx_blocks_type_tool (block_type=?) index for the block_type = 'tool_use' predicate inside the bounded relation's ranking CTEs, regardless of how selective the session bound is. Empirically confirmed via EXPLAIN QUERY PLAN against a fresh archive: a single-session query planned the identical full idx_blocks_type_tool scan as an unbounded one.

Solution

action_relation_select_sql now pins INDEXED BY idx_blocks_session_position on every blocks scan branch (ranked_uses, ranked_results, and the null-tool-id UNION ALL branch) whenever the relation is session-bounded (session_placeholders is set). The exact session id(s) are already known at SQL-generation time in this code path, so the correct index isn't a matter of cost estimation — it's pinned directly. The unbounded branch (used by the intentionally archive-wide flagship actions where is_error:true | group by followup_class | count example) is untouched.

New regression test test_bounded_action_relation_plans_session_index_not_archive_wide_tool_scan (tests/unit/storage/test_archive_tiers_archive.py) asserts via EXPLAIN QUERY PLAN (captured through sqlite3.Connection.set_trace_callback on the real query_unit_counts production call) that every SEARCH u/SEARCH r step in the bounded relation uses idx_blocks_session_position, never idx_blocks_type_tool. Anti-vacuity: verified the test fails with the exact pre-fix symptom (SEARCH u USING INDEX idx_blocks_type_tool (block_type=?)) when run against the unmodified action_relation.py.

Investigated but not implemented: z9gh.3's near:/lineage: execution-layer gaps

The z9gh.3 bead (as narrowed) also names two find/read-route gaps: near:"..." similarity falling back to an unfiltered list, and lineage:id: recursive-page projection columns (parent_refs/child_refs/continuation) going unmaterialized. Both were investigated in depth (not skipped):

  • near:id:/near:"text": traced the full execution path (polylogue/archive/query/archive_execution.py). Current master already fails loudly (ExpressionCompileError) when near:id:<ref> needs a vector backend that isn't configured or a seed session with no stored embeddings (_session_seed_scored's explicit docstring contract), and gracefully degrades to an empty semantic leg — not an unfiltered list — when no vector provider exists for a pure-near:"text" query (_semantic_hits's documented Archive storage: clean-sheet current archive implementation #1743 graceful-degradation contract). _archive_summaries dispatches plan.similar_session_id before the text-semantic leg, correctly. A real end-to-end CLI test exists for the text-seeded leg (test_async_execute_query_archive_uses_vector_provider_for_semantic_search) but not for the session-seeded leg — a test-coverage gap, not a reproduced execution bug. Separately, near:id: used inside a sessions where ... scoping predicate at the query_units/DSL pipeline level currently raises ExpressionCompileError("field 'near' is not supported inside Boolean SQL predicates yet") — again fail-loud, not silent. Could not reproduce the "falls back to an unfiltered session list" symptom against current master through any of these paths; it may already have been fixed by since-landed work, similar to the stale polylogue-2qx.2 bd state the evidence-matrix pass found and corrected.
  • lineage:id: recursive-page columns: confirmed real. lineage:id:X does correctly filter session/message membership through QueryLineagePredicate/_lineage_predicate_clause (polylogue/storage/sqlite/archive_tiers/archive.py), but the declared "recursive-page" result semantics in the discovery corpus (polylogue/archive/query/discovery.py, RECURSIVE_COLUMNS = ("session_id", "parent_refs", "child_refs", "continuation")) promise graph-navigation columns and independent recursive pagination that the actual route never materializes — it returns a flat, non-recursively-paged row set. Building real parent_refs/child_refs/continuation-cursor graph pagination is a genuinely large, separate feature (new response shape, cycle-aware traversal, continuation state), not a surgical fix — sizing it S/M would be dishonest. Per the coordinator's explicit stop condition, this item is reported rather than force-fixed here.

No changes were made for either near:/lineage: item; recommend the polylogue-z9gh.3 bead be re-verified against current master (the near: gap) and, if still wanted, split into its own properly-scoped feature bead (the lineage: recursive-page projection) rather than carried as this residual's scope.

Verification

  • devtools test tests/unit/storage/test_archive_tiers_archive.py -k test_bounded_action_relation_plans_session_index_not_archive_wide_tool_scan — 1 passed.
  • Anti-vacuity: same test against unmodified action_relation.py — fails with SEARCH u USING INDEX idx_blocks_type_tool (block_type=?) (the exact regression this test guards).
  • devtools test tests/unit/storage/test_archive_tiers_archive.py tests/unit/storage/test_planner_statistics_seed.py tests/unit/storage/test_delegation_facts_bulk_rebuild.py tests/unit/archive/query/test_execution_control.py — 65 passed, 4 pre-existing failures confirmed identical on unmodified origin/master (unrelated to this change — tracked as polylogue-1ldl, a stale >=50000 VM steps anti-vacuity threshold in two other tests whose "archive-wide fallback" mutation stopped being expensive once PR feat(query): bound agent-facing archive reads #3018 made the actions view backed by the small indexed action_pairs table, plus a query_units vs api.query_units call-log naming mismatch in two more).
  • mypy --strict polylogue/storage/sqlite/action_relation.py tests/unit/storage/test_archive_tiers_archive.py — clean.
  • devtools verify --quick — exit 0, all 16 steps green.

Ref polylogue-z9gh.3, polylogue-z9gh.7

@coderabbitai

coderabbitai Bot commented Jul 20, 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: 56 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

Run ID: 87f79681-3644-4f5a-8e37-4ba8cb475bed

📥 Commits

Reviewing files that changed from the base of the PR and between 6ed0738 and f69cd87.

📒 Files selected for processing (2)
  • polylogue/storage/sqlite/action_relation.py
  • tests/unit/storage/test_archive_tiers_archive.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/query/z9gh-execution-residuals

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 a87c530 into master Jul 20, 2026
3 checks passed
@Sinity
Sinity deleted the fix/query/z9gh-execution-residuals branch July 20, 2026 09:51
Sinity added a commit that referenced this pull request Jul 20, 2026
Problem: CodeRabbit flagged (PR #3202) that POLYLOGUE_MCP_WRITE_ENABLED=flase
(or any nonempty non-boolean string, or a quoted TOML value) passed through
_coerce_env_value's bool branch unchanged as a raw string, and the
mcp_write_enabled/mcp_judge_enabled/mcp_maintenance_enabled properties did
bool(self._data.get(...)) -- bool("flase") is True, so a typo silently
opened a capability boundary instead of leaving it closed. Same shape for
every other _BOOL_CONFIG_KEYS entry (not special-cased to the new keys).

What changed:
- _coerce_env_value's boolean branch now raises ConfigError naming the env
  var, offending value, and config key when the string isn't one of the
  canonical 1/true/yes/on / 0/false/no/off tokens (case-insensitive),
  instead of silently passing the raw string through. This applies to every
  _BOOL_CONFIG_KEYS entry via the one shared coercion path, not a
  capability-only special case.
- New _require_bool_config_value() (shared by all three capability
  properties) additionally closes the TOML-layer version of the same gap: a
  quoted TOML value (`write_enabled = "flase"`) bypasses env coercion
  entirely, so the property getter itself now validates the resolved value
  is a genuine bool or a canonical token string, raising ConfigError
  otherwise. Token-parsing logic is shared via _parse_bool_token() between
  the env-coercion path and this property-level guard.

Verification:
- devtools test tests/unit/core/test_config_inventory.py tests/unit/core/test_config.py
  -> 155 passed, including the new TestMCPCapabilityBooleanFailsClosed
  (typo raises, false/0/no/off/case-insensitive disables, true/1/yes/on/
  case-insensitive enables, TOML true works, quoted TOML string raises).
- devtools test tests/unit/mcp/test_cli.py tests/unit/cli/test_config_command.py
  -> 15 passed.
- devtools verify --quick -> ruff format/check, mypy --strict, render all,
  topology, layering, docs-coverage, etc. all exit 0.
- devtools test tests/unit/core -> 2327 passed; 4 failed / 6 errored, all in
  test_sync_surface_runtime.py/test_verification.py/test_models.py/
  test_schema_generation.py over artifact-taxonomy/schema-generation
  naming (agent_transcript vs subagent_session_stream) -- no reference to
  config.py, load_polylogue_config, or boolean coercion in any of them;
  pre-existing drift from the concurrent master rebase (#3196-#3200 landed
  mid-session), unrelated to this fix.

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