Skip to content

refactor(polylogue-dab): stop materializing run-projection cache rows - #2898

Merged
Sinity merged 7 commits into
masterfrom
feature/refactor/polylogue-dab-stop-run-projection-materialization
Jul 15, 2026
Merged

Sinity merged 7 commits into
masterfrom
feature/refactor/polylogue-dab-stop-run-projection-materialization

Conversation

@Sinity

@Sinity Sinity commented Jul 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Stops materializing session_runs/session_observed_events/session_context_snapshots — the run-projection/observed-event/context-snapshot query surfaces (CLI, MCP, agent-coordination) now read purely from source-derived CTEs over sessions/blocks, with no separate cache tables to write, drift, or rebuild.

Problem

The original commit dropped the schema and disabled the write path but left the surrounding system inconsistent with that change: a confirmed crash-risk write path, two silent-degradation bugs, a real correctness bug affecting every subagent run system-wide, a real query-selectivity bug, a fully dead 357-line write module, and 16+ files still documenting or querying the dropped tables. polylogue-itvd tracked closing that gap.

Solution

Crash fix: storage/insights/session/rebuild.py's _PER_SESSION_INSIGHT_TABLES still listed the 3 dropped tables in the orphan-pruning loop — every full rebuild crashed with sqlite3.OperationalError: no such table: session_runs. Removed; simplified SessionInsightRecordBundle to plain counts instead of building full record lists that were never used.

Silent-degradation fixes:

  • coordination/envelope.py: _archive_tables_present() gated all agent-coordination archive-evidence queries (session trees, activity, subagent exchanges, proof refs, context flow) on the 3 dropped tables existing — every one of these silently returned empty regardless of real data. Fixed to check only (sessions, session_links); rewrote 5 query functions to prepend the source-derived CTE via a new _combined_relation_sql() helper (SQLite allows only one WITH clause per statement).
  • storage/insights/session/status.py, insights/readiness.py: table_name pointed at the dropped tables, permanently gating counts/readiness to 0/false. Fixed to point at sessions.

Correctness bug (found via a genuine HTTP-level regression test, not a unit test that queried raw SQL and bypassed the hydration path): storage/sqlite/run_projection_relations.py's projected_run_from_row() hardcoded role="main" instead of reading the computed row["role"] column — every subagent run was silently reported as role="main" across the entire system (API, MCP, CLI), independent of any other fix here.

Query-selectivity bug: observed_event_source_pushdown()'s kind field predicate was marked is_selective=False, so "kind:tool_finished" alone (without an accompanying tool:/handler:/status: predicate) fell through to the "not selective" 0=1 fallback and silently returned zero rows despite real matching evidence. kind='tool_finished' discriminates against the session_started branch of the source_observed_events UNION, so it is itself selective.

Dead write path removed: storage/insights/session/storage.py (242 lines) and session_insight_run_projection_writes.py (115 lines) — the entire Python writer for the 3 dropped tables, unreachable since the write path was disabled. devtools/render_demo_corpus_datasheet.py and demo/constructs.py queried the dropped tables directly, breaking devtools render demo-corpus-datasheet; wired to the source-derived CTEs.

Stale docs/references corrected: run_projection_rows.py, query_models.py, timeline/records.py, query_store_insight_run_projection.py, insights/transforms.py, docs/search.md, docs/internals.md (backfilled 2 missing schema-version changelog entries for v36/v37 — v37 is this exact table drop, previously undocumented). devtools/temporal_archive_aggregates.py also had a real bug: source_updated_at is a zero-padded epoch-ms string, not ISO — month-bucketing needed CAST(.../1000, 'unixepoch'), not substr. devtools/scale_regression_probe.py called an already-deleted write function (replace_session_runs_bulk_sync); rewrote _check_run_ref_no_drop to test the real one-run-per-subagent-session invariant. devtools/validation_lane_catalog_contracts.py had a stale "session_runs" artifact label.

Test rewrites (old tests assumed the materialized-table model): test_envelope.py (full fixture rewrite — real subagent sessions via branch_type='subagent' instead of the deleted Task-report-parsing writer), test_insight_readiness.py, test_web_reader.py, test_temporal_archive_aggregates.py, test_session_insight_rebuild_progress.py, test_session_insight_status_descriptors.py, test_run_projection_materialization.py, test_demo_seed_verify.py, test_query_expression.py (7 tests), test_tool_usage.py, test_schema_safety.py, test_delegations_view.py — rewrote raw-table fixtures to seed real sessions/blocks and query through the source-derived CTEs, matching the new one-row-per-session model instead of the old N-rows-per-dispatch model. test_insights.py: corrected the exact-match "pruned orphans" heartbeat list to drop the 3 removed tables.

Verification

devtools test across all touched production + test files → 773 passed, 10 failed, 22 errors on the full sweep; every failure independently confirmed pre-existing by re-running the identical tests against clean origin/master with this branch's diff stashed away (test_tool_usage.py action_kind mismatch, test_query_expression.py::test_reference_resolver_rejects_a_cycle_before_materialization, test_query_exec_laws.py trigger-already-exists collision ×22, test_insights.py KeyError:'origin'/Unknown-query-field family) — zero regressions from this branch.

mypy --strict clean (991 files). devtools render all --check clean (topology projection regenerated). ruff check/format clean.

Not run

Full devtools verify --all — the testmon-affected/focused selection above is the relevant surface; the 4 pre-existing baseline failures (polylogue-p5li) are unrelated and independently confirmed as such.

Ref polylogue-itvd, polylogue-dab

Remove materialized union branches from run/observed-event/context-snapshot
relation CTEs and disable writes to session_runs, session_observed_events,
session_context_snapshots tables. All reads now use source-derived
construction from sessions/blocks.

- Simplify run_relation_sql/observed_event_relation_sql/context_snapshot_relation_sql
  to remove materialized cache paths; raise ValueError if include_materialized=True
- Add regression guards in projected_run_from_row/observed_event_from_row/
  context_snapshot_from_row to detect stray materialized rows
- Comment out replace_session_* write calls in async/sync rebuild paths
- Remove unused imports of replace_session_*_bulk_sync functions
- Drop DDL for three cache tables from index.py; bump INDEX_SCHEMA_VERSION to 37
- Remove unused run_projection enum imports from index.py

Verification: devtools verify --quick passes; all relation queries use
source-derived CTEs only.

Ref polylogue-dab

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GjyDHiwc5QfXGgDMGuFEB8
@coderabbitai

coderabbitai Bot commented Jul 14, 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: 16 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: 7dc67eb7-37b5-4168-95ae-00d7eee16790

📥 Commits

Reviewing files that changed from the base of the PR and between fc832fd and e8870d4.

📒 Files selected for processing (40)
  • devtools/render_demo_corpus_datasheet.py
  • devtools/scale_regression_probe.py
  • devtools/temporal_archive_aggregates.py
  • devtools/validation_lane_catalog_contracts.py
  • docs/internals.md
  • docs/plans/demo-corpus-construct-audit.md
  • docs/plans/topology-target.yaml
  • docs/search.md
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • polylogue/coordination/envelope.py
  • polylogue/demo/constructs.py
  • polylogue/insights/readiness.py
  • polylogue/insights/transforms.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/run_projection_rows.py
  • polylogue/storage/insights/session/status.py
  • polylogue/storage/insights/session/storage.py
  • polylogue/storage/insights/timeline/records.py
  • polylogue/storage/query_models.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/index.py
  • polylogue/storage/sqlite/queries/session_insight_run_projection_reads.py
  • polylogue/storage/sqlite/queries/session_insight_run_projection_writes.py
  • polylogue/storage/sqlite/query_store_insight_run_projection.py
  • polylogue/storage/sqlite/run_projection_relations.py
  • tests/unit/cli/test_insights.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/cli/test_query_expression.py
  • tests/unit/coordination/test_envelope.py
  • tests/unit/core/test_insight_readiness.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/demo/test_demo_seed_verify.py
  • tests/unit/devtools/test_temporal_archive_aggregates.py
  • tests/unit/insights/test_run_projection_materialization.py
  • tests/unit/insights/test_tool_usage.py
  • tests/unit/storage/test_delegations_view.py
  • tests/unit/storage/test_schema_safety.py
  • tests/unit/storage/test_session_insight_rebuild_progress.py
  • tests/unit/storage/test_session_insight_status_descriptors.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/polylogue-dab-stop-run-projection-materialization

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.

@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: 7ecf6860a4

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

@Sinity

Sinity commented Jul 14, 2026

Copy link
Copy Markdown
Owner Author

Holding this PR — not merging as-is. While resolving its merge conflict against master, I found the migration is significantly incomplete: dropping session_runs/session_observed_events/session_context_snapshots from the CREATE TABLE DDL (this PR's whole point) leaves at least 16 other files still referencing those table names directly, including confirmed write paths — e.g. polylogue/storage/sqlite/queries/session_insight_run_projection_writes.py::replace_session_runs_bulk still does table="session_runs". On a fresh or fully-rebuilt archive (no session_runs table at all), that write call would raise sqlite3.OperationalError: no such table: session_runs at runtime.

I fixed the one consumer that blocked devtools verify --quick (polylogue/demo/constructs.py's demo-construct queries, rewritten to use run_relation_sql()/observed_event_relation_sql()/context_snapshot_relation_sql()), but devtools/render_demo_corpus_datasheet.py's own _measure_archive hit the same no such table: session_runs error immediately after, and a full sweep found the remaining files below still reference these tables:

polylogue/coordination/envelope.py
polylogue/insights/readiness.py
polylogue/insights/transforms.py
polylogue/storage/query_models.py
polylogue/storage/insights/session/run_projection_rows.py
polylogue/storage/insights/session/status.py
polylogue/storage/insights/session/rebuild.py
polylogue/storage/insights/timeline/records.py
polylogue/storage/insights/session/storage.py
polylogue/storage/repository/insight/run_projection_reads.py
polylogue/storage/sqlite/query_store_insight_run_projection.py
polylogue/storage/sqlite/queries/session_insight_run_projection_writes.py
polylogue/storage/sqlite/queries/session_insight_run_projection_reads.py
polylogue/storage/sqlite/archive_tiers/archive.py (2 call sites still pass include_materialized=<table_exists check>, which now unconditionally raises ValueError per run_relation_sql()'s own new docstring if that check is ever True)
devtools/temporal_archive_aggregates.py
devtools/scale_regression_probe.py
devtools/validation_lane_catalog_contracts.py
devtools/render_demo_corpus_datasheet.py

This needs a proper sweep (likely per-file: is it a dead write path to delete, a read path to rewrite via the *_relation_sql() CTE pattern, or a table_exists-gated dual-path that's now safe to simplify) before this is mergeable. Filing that as its own follow-up bead rather than trying to complete it inside this PR review. Leaving this PR open; do not merge until the full sweep lands (either in this PR or a stacked one).

Sinity added 6 commits July 14, 2026 21:07
# Conflicts:
#	polylogue/storage/sqlite/archive_tiers/index.py
Problem: polylogue-dab (PR #2898) dropped session_runs/
session_observed_events/session_context_snapshots from the schema but
left polylogue/demo/constructs.py and devtools/render_demo_corpus_datasheet.py
querying those tables directly, breaking devtools render
demo-corpus-datasheet ("no such table: session_runs") -- discovered
while resolving #2898's merge conflict against master (polylogue-itvd).

Deeper gap found while fixing this: run_relation_sql() and
context_snapshot_relation_sql() hardcoded role="main"/boundary
session_start|resume, with no branch for BranchType.SUBAGENT
(core/enums.py) -- the session-level flag a parsed subagent session
already carries. The pre-polylogue-dab Python writer
(insights/run_projection.py) derived subagent role/boundary from
Task-tool report parsing; the source-derived CTE never replicated
that. Demo verification caught it immediately: subagent_context_snapshots
and subagent_run_rows both dropped to 0 (expected >=1) once demo/constructs.py
was wired to source-derived queries.

What changed:
- demo/constructs.py, render_demo_corpus_datasheet.py: rewrote the 5
  affected queries to prepend the WITH-clause from run_relation_sql()/
  observed_event_relation_sql()/context_snapshot_relation_sql() and
  SELECT against the resulting CTE, matching the pattern already used
  in archive_tiers/archive.py's structural-predicate query builder.
- run_projection_relations.py: both relation-SQL builders now branch
  on branch_type='subagent' for role/boundary/context_snapshot_ref
  (and agent_ref's /main vs /subagent suffix), matching what the old
  materialized writer computed for the row-count-level fields. The
  finer subagent_type segment (which Task tool_input spawned this
  session) is not reconstructed -- noted inline, out of scope for
  unblocking the row-count-level demo verification this fixes.

Verification:
- devtools render demo-corpus-datasheet --check: sync OK.
- docs/plans/demo-corpus-construct-audit.md: verifier result flips
  failed -> ok; subagent_context_snapshots and subagent_run_rows both
  1/1 ok (were 0/1 missing); non-subagent run/observed-event/context-
  snapshot counts stay non-zero and consistent (15/37/15 vs the old
  materialized 16/49/16 -- the small deltas are expected, the source-
  derived query counts distinct sessions/events differently than the
  old writer's per-report expansion, not a regression -- overall
  construct coverage is fully populated either way).
- devtools test tests/unit/demo/ -k construct: 4 passed.

Ref polylogue-itvd.
…e_materialized gating

Problem: polylogue-dab (PR #2898) dropped session_runs/
session_observed_events/session_context_snapshots from the schema but
left the write path and read-side table_exists gating fully intact:

1. session_insight_run_projection_reads.py's list_runs/
   list_observed_events/list_context_snapshots each called
   run_relation_sql(include_materialized=await _table_exists(conn,
   "session_runs")) (and the observed-event/context-snapshot
   equivalents). On any archive where the table still physically
   exists (any index.db not yet rebuilt since #2898 landed),
   _table_exists returns True, and run_relation_sql() now
   unconditionally raises ValueError when include_materialized=True
   (per its own docstring, added by #2898) -- these three core read
   functions would crash. archive_tiers/archive.py had 4 more call
   sites with the identical pattern, plus one direct
   `if _run_projection_table_exists(...): SELECT ... FROM session_runs`
   block in the delegation-card builder that was already permanently
   dead (silently returning run_ref=None) on any archive where the
   table doesn't exist.
2. session_insight_run_projection_writes.py (6 async functions) and
   storage.py's 6 sync replace_session_runs_sync-family functions plus
   their 3 insert-value helpers had zero callers anywhere outside their
   own now-deleted/rewritten test file -- confirmed via grep before
   deletion, not assumed.

What changed:
- session_insight_run_projection_reads.py + archive_tiers/archive.py
  (5 call sites total): removed the table_exists-gated
  include_materialized argument entirely; always call the relation-SQL
  builders with no materialized flag (source-derived only, matching
  what polylogue-dab actually shipped).
- archive_tiers/archive.py's delegation-card run lookup: rewritten to
  query run_relation_sql()'s CTE by native_session_id (the source-
  derived relation's own session-identity column), replacing the
  permanently-dead session_runs table lookup. The old evidence_refs_json
  block-id fallback (used when only tool-use/artifact block ids are
  known, no resolved child_session_id) has no equivalent in the new
  CTE, which only tracks the owning session id as evidence -- documented
  inline as an accepted gap, not silently dropped.
- Deleted session_insight_run_projection_writes.py entirely and the 6
  dead sync write functions + 3 insert-value helpers from
  storage.py (228 lines), confirmed zero external callers first.
- tests/unit/insights/test_run_projection_materialization.py:
  rewritten. Deleted test_run_projection_materialization_parity (its
  entire premise -- comparing materialized-writer output to source --
  is moot with no materialized writer). Removed the now-invalid
  DELETE FROM/DROP TABLE session_runs statements from the two
  source-read tests (those tables never exist now). Rewrote
  test_subagent_and_child_main_runs_do_not_collide: the old test
  exercised the deleted Python report-parsing writer
  (build_run_projection + replace_session_runs_bulk_sync); the new
  version seeds a real subagent session (branch_type='subagent',
  parent_session_id set) and asserts the CTE produces a distinct
  role='subagent' run row that cannot collide with the parent's own
  main run_ref -- the actual current invariant, proven directly against
  run_relation_sql() rather than against dead code. Trimmed the
  materialize-and-verify-idempotent tail off
  test_continuation_session_resume_boundary_read_through_source_and_materialized
  (renamed, dropping "_and_materialized").

Verification:
- devtools test tests/unit/insights/test_run_projection_materialization.py:
  5 passed (was 5 failed / 1 passed before this fix).
- mypy --strict on all 4 touched production files: no issues.
- ruff check: all clean, no unused imports left behind by the deletions.

Ref polylogue-itvd.
Problem: PR #2898 (polylogue-dab: stop materializing run-projection
cache rows) dropped session_runs/session_observed_events/
session_context_snapshots from the schema but left 16+ files still
referencing them or documenting the old model, including a confirmed
crash-risk write path and two silent-degradation bugs.

Crash fixes:
- storage/insights/session/rebuild.py: _PER_SESSION_INSIGHT_TABLES still
  listed the 3 dropped tables in the orphan-pruning loop, crashing every
  full rebuild with "no such table: session_runs". Removed; simplified
  SessionInsightRecordBundle to plain counts instead of full record
  lists (dead computation).

Silent-degradation fixes:
- coordination/envelope.py: _archive_tables_present() gated ALL
  coordination archive-evidence queries (session trees, activity,
  subagent exchanges, proof refs, context flow) on the 3 dropped tables
  existing, so every one of these silently returned empty. Fixed to
  check only (sessions, session_links); rewrote 5 query functions to
  prepend the source-derived CTE via a new _combined_relation_sql()
  helper (SQLite allows only one WITH clause per statement).
- storage/insights/session/status.py, insights/readiness.py:
  table_name pointed at the dropped tables, permanently gating
  counts/readiness to 0/false. Fixed to point at `sessions`.

Correctness bug (found via a genuine HTTP-level regression test, not a
unit test that queried raw SQL and bypassed the hydration path):
- storage/sqlite/run_projection_relations.py: projected_run_from_row()
  hardcoded role="main" instead of reading the computed row["role"]
  column -- every subagent run was silently reported as role="main"
  system-wide (API, MCP, CLI), independent of any other fix here.
- Separately, observed_event_source_pushdown()'s `kind` field predicate
  was marked is_selective=False, so "kind:tool_finished" alone (without
  an accompanying tool:/handler:/status: predicate) fell through to the
  "not selective" 0=1 fallback and silently returned zero rows despite
  real matching evidence -- found while rewriting a test that assumed
  the old materialized-table query shape. kind='tool_finished'
  discriminates against the session_started branch of the
  source_observed_events UNION, so it is itself selective.

Dead write path removed:
- storage/insights/session/storage.py (242 lines),
  session_insight_run_projection_writes.py (115 lines): the entire
  Python writer for the 3 dropped tables, unreachable since polylogue-dab
  disabled writes to them.
- devtools/render_demo_corpus_datasheet.py, demo/constructs.py: queried
  the dropped tables directly, breaking `devtools render
  demo-corpus-datasheet`. Wired to the source-derived CTEs.

Stale docstrings/dead references corrected: run_projection_rows.py,
query_models.py, timeline/records.py, query_store_insight_run_projection.py,
insights/transforms.py, docs/search.md, docs/internals.md (backfilled 2
missing changelog entries for index schema v36/v37 -- v37 is this exact
table drop, previously undocumented), devtools/temporal_archive_aggregates.py
(also fixed a real bug: source_updated_at is a zero-padded epoch-ms
string, not ISO -- month-bucketing needed CAST(.../1000, 'unixepoch')
not substr), devtools/scale_regression_probe.py (rewrote a broken
write-path call to already-deleted replace_session_runs_bulk_sync;
_check_run_ref_no_drop now tests the real one-run-per-subagent-session
invariant), devtools/validation_lane_catalog_contracts.py (renamed a
stale "session_runs" artifact label to "run_projection").

Test rewrites (old tests assumed a materialized-table model that no
longer exists): test_envelope.py (full fixture rewrite -- real subagent
sessions via branch_type='subagent' instead of the deleted
Task-report-parsing writer), test_insight_readiness.py,
test_web_reader.py, test_temporal_archive_aggregates.py,
test_session_insight_rebuild_progress.py,
test_session_insight_status_descriptors.py,
test_run_projection_materialization.py (from an earlier commit on this
branch). test_demo_seed_verify.py, test_query_expression.py (7 tests),
test_tool_usage.py, test_schema_safety.py, test_delegations_view.py:
rewrote raw-table INSERT/SELECT fixtures to seed real
sessions/blocks and query through the source-derived CTEs
(run_relation_sql/observed_event_relation_sql/
context_snapshot_relation_sql), matching the new one-row-per-session
model instead of the old N-rows-per-dispatch model. test_insights.py:
corrected the exact-match "pruned orphans" heartbeat list to drop the
3 removed tables.

Verification: devtools test across all touched production + test files
-> 773 passed, 10 failed, 22 errors on the full sweep; every failure
independently confirmed pre-existing by re-running against clean
origin/master with this branch's diff stashed away (test_tool_usage.py
action_kind mismatch, test_query_expression.py RefOperandCycleError,
test_query_exec_laws.py trigger-already-exists collision x22,
test_insights.py KeyError:'origin'/Unknown-query-field family) --
zero regressions from this branch. mypy --strict clean (991 files);
devtools render all --check clean.

Ref polylogue-itvd, polylogue-dab.
@Sinity
Sinity merged commit 5d99611 into master Jul 15, 2026
2 checks passed
@Sinity
Sinity deleted the feature/refactor/polylogue-dab-stop-run-projection-materialization branch July 15, 2026 02:09
Sinity added a commit that referenced this pull request Jul 15, 2026
…erifying

## Problem

polylogue-a7xr.9 flagged 36 duplicate `_table_exists` implementations
scattered across the codebase, all supposedly superseded by a canonical
`table_exists()`/`table_exists_async()` pair. That canonical pair had never
been tested and was broken: it bound `db` as a query parameter against
`sqlite_master`, which has no `db` column, so every call raised
`sqlite3.OperationalError`.

Verifying the fix (`devtools verify`) exposed two batches of pre-existing,
unrelated test failures that a full-suite run surfaces but the narrower
testmon-affected selection normally used in this repo hadn't caught:
27 failures from stale test fixtures/assertions trailing recent feature
landings, and a further 50 only visible once testmon fell back to a
near-full-suite selection. All were confirmed pre-existing via `git stash`
comparison against clean `origin/master` before being touched.

## Solution

**Canonical table-existence helper** (polylogue-a7xr.9): fixed the
`AND db=?` bug (dynamic schema-name interpolation instead, matching the two
call sites that already did this correctly), wrote real tests against actual
SQLite connections (including the attached-schema path), and placed the
module at `storage/table_existence.py` -- directly under `storage/`, not
nested under `storage/sqlite/`. This satisfies two constraints that first
looked incompatible: `docs/architecture.md`'s package-placement rules
require raw SQL to live under `storage/` (ruled out `core/`, where an
earlier draft of this PR briefly placed it -- caught by CodeRabbit review),
while `polylogue/storage/sqlite/__init__.py` eagerly imports the heavy async
backend stack, so a low-level module like `storage/blob_publication.py`
importing a sibling under `storage.sqlite` triggers that whole chain and
circles back through `insights/` -- a real circular import. `storage/__init__.py`
itself only exposes lazy `__getattr__`-based exports, so a module living
directly under `storage/` avoids that chain entirely. Consolidated 26 sites
with identical `type='table'` semantics onto the canonical import (a 27th,
`session_insight_run_projection_reads.py`, fell out of scope entirely during
the rebase onto master: #2898 landed concurrently and dropped its
`_table_exists`-gated materialized-table check along with the run-projection
materialization feature it belonged to). Left 8 sites alone that use
genuinely different semantics (`type IN ('table','view')`,
`('table','virtual table')`, or `('table','shadow')`) and one
(`cli/commands/status.py`) that already delegates to its own generic
multi-type helper.

**Test/fixture drift sweep** (found while verifying, fixed rather than
dismissed as unrelated): stale `provider=`/bare-provider-token usages across
CLI, MCP, benchmark, and facade-contract tests that predate the
provider->origin vocabulary migration (including one place a fixture needed
the opposite direction -- `insights status`'s `provider_coverage` field
still legitimately reports provider tokens via `_provider_for_origin_value`,
which a first pass of this fix incorrectly "corrected" to an origin token;
caught by Codex review); a repeated `initialize_archive_tier()` double-init
bug across 4 test files (fixtures already get a fully initialized `user.db`
via `ArchiveStore(...)`/`cli_workspace`, so the extra call re-runs DDL
against existing triggers and crashes); a hardcoded `captured_at` timestamp
in `test_status.py` that goes stale with wall-clock time (now uses the
`frozen_clock` fixture, matching this repo's own convention); a missing
`EMBEDDINGS_SCHEMA_VERSION` constant reference (test hardcoded `1`, real
schema is now `2`); missing CLI short-flag aliases (`-l`/`-f`) on two
recently-added subcommands; 4 `AssertionKind` enum members
(`secret_candidate`, `excision_record`, `excision_request`,
`comparative_judgment`) missing their `user_audit.py` surface entries; 7 new
async `Polylogue` facade methods missing `status.py` route-catalog entries;
a new `include_affordances` MCP field missing from the query-descriptor
parity exclusion set; a new `semantic_cards` visual test missing its
inventory entry; 3 doc references to source paths that moved
(`storage/insights/topology/derivation.py`) or no longer exist as a single
file (`storage/search_providers/fts5.py` -> `storage/search/query_builders.py`
now builds the lexical FTS5 query); and a legitimate production behavior
change in `continue_verb` (#2827 removed context-compile/`--format json`
support in favor of safe-resume-command-only output) whose unit tests were
rewritten to assert the new rejection behavior instead of the removed one.

**Real production bug fixed, not just test drift**: `normalize_insight_query_kwargs`
(`polylogue/cli/shared/insight_command_contracts.py`) was popping `"origin"`
and renaming it to `"provider"`, downgrading origin tokens
(e.g. `"codex-session"`) to bare provider tokens (`"codex"`) via
`provider_from_origin`. Both call sites (`insights_status_command`,
`insights_export_command`) still read `filters["origin"]` afterward -- a
`KeyError` on every invocation with an origin filter -- while the underlying
`InsightReadinessQuery`/`InsightExportBundleRequest` models only accept
`origin` (confirmed via their own `Unknown query field(s)` error listing
accepted fields). Removed the origin->provider downgrade entirely; the CLI
layer now speaks the same origin vocabulary as the rest of the public
surface.

## Deferred (filed as tracked debt, not guess-fixed)

- polylogue-hjpx (P1): 7 raw-materialization repair tests fail --
  `backfill_historical_revision_evidence` classifies a candidate as
  replayable but never replays it. Traced far enough to rule out the most
  recent commit touching `repair.py` (#2900) as the cause; genuinely older
  debt that needs a dedicated tracing session, not a blind patch to a
  data-materialization repair path.
- polylogue-866e (P0): Hypothesis finds 3 distinct falsifying examples in
  `test_write_path_state_machine.py` -- real invariant violations in the
  session-lineage write path (fork/resume/prefix-replay composition), the
  sharpest and most fragile part of this architecture. Needs a focused
  investigation session.
- polylogue-j9dt (P1): `continue --format json` was fully removed by #2827,
  but two `QueryActionWorkflow` product-doc registry entries
  (`find-then-successor-context`, `find-then-continue`) still document it in
  detail. Needs a product decision, not a unilateral rewrite.
- polylogue-enj7 (P2): `test_daemon_cli_remote_bind.py`'s loopback-pass tests
  hang/error against real (unmocked) background raw-materialization
  convergence, confirmed on a freshly rebooted host. The module's own
  docstring already flags full-startup-chain mocking as "out of scope."
- polylogue-oucx (P2): 3 `test_facade_contracts.py` run/OTel query-unit
  tests fail deterministically, unrelated to this PR's diff (confirmed via
  `git diff origin/master` showing zero change to the relevant production
  files, and via reproducing identically on the pre-fix pushed branch
  content). Possibly a real gap left by #2898.

## Verification

- `devtools test tests/unit/storage/test_table_existence.py` -- 6/6 passed.
- Every touched test file run directly together, minus 3 confirmed-unrelated
  pre-existing failures in `test_facade_contracts.py` (polylogue-oucx) --
  768+ passed.
- Original 27-failure set and the fuller 50-failure set both re-run directly
  against this branch: 27/27 and 37/50 pass (the remaining 13 are the four
  items filed above, all independently confirmed pre-existing and
  unrelated via `git stash` comparison against clean `origin/master`).
- `mypy --strict polylogue` -- clean, 991 files.
- `ruff format --check .` / `ruff check .` -- clean.
- `devtools render all --check` -- clean, no drift, after two full module
  relocations (`storage/sqlite/table_existence.py` -> `core/` ->
  `storage/table_existence.py`) each re-verified for zero circular import
  (`python3 -c "import polylogue.storage.blob_publication"` exits 0).
- `devtools verify --quick` -- clean (ran automatically via pre-push hook).
- Addressed both substantive automated-review findings from CodeRabbit
  (package-boundary placement) and Codex (provider/origin fixture
  correctness) before merge, per repo review-triage discipline.

Ref polylogue-a7xr.9

Co-Authored-By: Claude <[email protected]>
@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.

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.

  • 74.F062 / P1: fixed-already at the checked revision: The orphan-prune inventory at polylogue/storage/derived/session/rebuild.py:1671-1674 now contains only session_latency_profiles and session_profiles. session_runs, session_observed_events and session_context_snapshots are not pruned as physical tables, so full rebuilds no longer issue DELETE against the removed run-projection tables.

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