Repository navigation
fix(query): pin session-scoped index for bounded action relation - #3200
Conversation
|
Warning Review limit reached
Next review available in: 56 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 (2)
✨ 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 |
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]>
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 | countvariant) could still plan an archive-wideidx_blocks_type_toolscan of everytool_use/tool_resultblock in the archive, instead of a cheap session-scoped index seek — even after PR #3018 (z9gh.2) replaced the old windowed-viewactionsrelation with theaction_pairs-backed one and added exact-session-id extraction from the query predicate.Problem
Investigation (
polylogue-z9ghevidence 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 asession.id:Xpredicate 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 freshArchiveStore-bootstrapped archive never seedssqlite_stat1—initialize_archive_tier(polylogue/storage/sqlite/archive_tiers/bootstrap.py) just runsconn.executescript(spec.ddl)with noANALYZE/stat seeding, unlike the separate connection-pool bootstrap inpolylogue/storage/sqlite/schema.py(_ensure_schema, which does seedPLANNER_STAT1_SEED_SQL— this is a genuinely different bootstrap path used elsewhere, not the oneArchiveStore()goes through). Without stats, SQLite's planner defaults to the low-cardinalityidx_blocks_type_tool (block_type=?)index for theblock_type = 'tool_use'predicate inside the bounded relation's ranking CTEs, regardless of how selective the session bound is. Empirically confirmed viaEXPLAIN QUERY PLANagainst a fresh archive: a single-session query planned the identical fullidx_blocks_type_toolscan as an unbounded one.Solution
action_relation_select_sqlnow pinsINDEXED BY idx_blocks_session_positionon everyblocksscan branch (ranked_uses,ranked_results, and the null-tool-id UNION ALL branch) whenever the relation is session-bounded (session_placeholdersis 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 flagshipactions where is_error:true | group by followup_class | countexample) 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 viaEXPLAIN QUERY PLAN(captured throughsqlite3.Connection.set_trace_callbackon the realquery_unit_countsproduction call) that everySEARCH u/SEARCH rstep in the bounded relation usesidx_blocks_session_position, neveridx_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 unmodifiedaction_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, andlineage: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) whennear: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_summariesdispatchesplan.similar_session_idbefore 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 asessions where ...scoping predicate at thequery_units/DSL pipeline level currently raisesExpressionCompileError("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 stalepolylogue-2qx.2bd state the evidence-matrix pass found and corrected.lineage:id:recursive-page columns: confirmed real.lineage:id:Xdoes correctly filter session/message membership throughQueryLineagePredicate/_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 realparent_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.action_relation.py— fails withSEARCH 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 unmodifiedorigin/master(unrelated to this change — tracked aspolylogue-1ldl, a stale>=50000 VM stepsanti-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 theactionsview backed by the small indexedaction_pairstable, plus aquery_unitsvsapi.query_unitscall-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