Repository navigation
perf(insights): emit progress per table during full session-insight rebuild - #1653
Conversation
…ebuild A full ``rebuild_session_insights_sync`` issues seven unconditional DELETEs against the session insight tables. On the production baseline (~7,955 session_profiles, ~15,939 work_events, ~13,354 phases, plus tag rollups and the new latency table) the DELETE phase holds the write lock for seconds; on a 10x archive it scales to minutes. Previously this phase ran with no progress reporting, so operators tailing the log saw "rebuild started" and then nothing until the first chunk inserted — easy to mistake for a hung process. Changes: - New ``_delete_tables_with_progress_sync`` helper that loops the seven DELETEs and emits one ``ProgressCallback`` event per table (``desc="rebuild: cleared <name>"``, ``amount=rowcount``). The async branch of ``rebuild_session_insights_async`` gets the same table-by-table progress emission. - ``rebuild_session_insights_sync(conversation_ids=None)`` and the async counterpart route their full-rebuild DELETEs through the helper, threading the existing ``progress_callback`` parameter through. Targeted rebuilds (``conversation_ids != None``) are unchanged — their DELETEs are already per-conversation and finish quickly. Atomicity note (#1607 hypothesis): The issue posited that DELETEs and the subsequent rebuild loop are "non-transactional" and that a SIGKILL between DELETE and the first INSERT leaves session insights empty. Tracing the code shows this is not the case: the implicit transaction started by the first DELETE spans every subsequent DML through the eventual ``conn.commit()`` at the bottom of the function. WAL mode + a single explicit COMMIT means a SIGKILL mid-rebuild rolls back the WAL on next open, leaving prior insights intact rather than emptying them. Pinned by the new test ``test_full_rebuild_rolls_back_on_exception_keeping_prior_profiles`` which monkeypatches the inner loop to raise after the DELETEs and asserts that ``COUNT(session_profiles)`` equals the pre-failure baseline. AC1 (declared op-spec contract) and AC4 (refuse-or-pause live ingest) require new infrastructure and remain open against #1607. Inherited test failures fixed alongside (CLAUDE.md S19a): - ``tests/unit/storage/test_dead_schema_sweep.py``: schema version has rolled past 14 to 16; rename test and update the constant comment. - ``tests/unit/storage/test_query_mappers.py``: ``test_maps_all_fields`` asserted ``source_name == "chatgpt"`` and ``source_name == "inbox"`` on the same row — impossible. The seed sets "inbox", so removed the duplicate-and-contradictory assertion. Verification: ``` $ nix develop -c pytest tests/unit/storage/test_session_insight_rebuild_progress.py \ tests/unit/cli/test_insights.py::test_session_insight_rebuild_sync_reports_progress 5 passed in 0.21s $ nix develop -c devtools verify --quick exit_code: 0 ``` Ref #1607 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
📝 WalkthroughWalkthroughSession insights rebuild operations now emit progress callbacks during table deletion. A new ChangesRebuild Progress Reporting & Atomicity
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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.
Actionable comments posted: 1
🤖 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/storage/insights/session/rebuild.py`:
- Line 670: The DELETE uses a dynamically interpolated identifier (variable
"table") in conn.execute(f"DELETE FROM {table}") which is an SQL injection risk;
add a strict validation step (e.g., a validate_table_name(table) helper) or map
incoming table values through a fixed whitelist/dict of allowed table names
before any string interpolation, and raise on invalid names; apply the same
validation to the other occurrence that interpolates "table" (around the second
occurrence noted at line ~874) so only known safe identifiers are used before
calling conn.execute or constructing SQL strings.
🪄 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: 7f5c1373-da29-47ea-a5b4-51458de221cb
📒 Files selected for processing (5)
polylogue/storage/insights/session/rebuild.pytests/unit/cli/test_insights.pytests/unit/storage/test_dead_schema_sweep.pytests/unit/storage/test_query_mappers.pytests/unit/storage/test_session_insight_rebuild_progress.py
💤 Files with no reviewable changes (1)
- tests/unit/storage/test_query_mappers.py
| about table-step granularity can ignore it. | ||
| """ | ||
| for table in tables: | ||
| deleted = conn.execute(f"DELETE FROM {table}").rowcount |
There was a problem hiding this comment.
Guard dynamic table-name SQL before DELETE execution.
Line 670 and Line 874 build SQL with interpolated identifiers. Even with current constant callers, this is a latent SQL-injection sink if reused with non-constant input. Validate table identifiers (or map through a fixed whitelist) before string interpolation.
🔒 Proposed hardening
+import re
+
+_SQLITE_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+def _validated_table_name(table: str) -> str:
+ if not _SQLITE_IDENTIFIER_RE.fullmatch(table):
+ raise ValueError(f"Unsafe table identifier: {table!r}")
+ return table
+
def _delete_tables_with_progress_sync(
conn: sqlite3.Connection,
*,
tables: Sequence[str],
progress_callback: ProgressCallback | None,
) -> None:
@@
for table in tables:
- deleted = conn.execute(f"DELETE FROM {table}").rowcount
+ safe_table = _validated_table_name(table)
+ deleted = conn.execute(f'DELETE FROM "{safe_table}"').rowcount
if progress_callback is not None:
progress_callback(
int(max(deleted, 0)),
desc=f"rebuild: cleared {table}",
)
@@
- for table in (
+ for table in (
"session_work_events",
"session_phases",
"session_latency_profiles",
"session_profiles",
"session_tag_rollups",
"conversation_repo_observations",
"repo_identities",
):
- cursor = await conn.execute(f"DELETE FROM {table}")
+ safe_table = _validated_table_name(table)
+ cursor = await conn.execute(f'DELETE FROM "{safe_table}"')
if progress_callback is not None:
rowcount = getattr(cursor, "rowcount", 0) or 0
progress_callback(int(rowcount if rowcount > 0 else 0), desc=f"rebuild: cleared {table}")Also applies to: 874-874
🧰 Tools
🪛 OpenGrep (1.22.0)
[ERROR] 670-670: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.
(coderabbit.sql-injection.python-fstring-execute)
🤖 Prompt for 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.
In `@polylogue/storage/insights/session/rebuild.py` at line 670, The DELETE uses a
dynamically interpolated identifier (variable "table") in conn.execute(f"DELETE
FROM {table}") which is an SQL injection risk; add a strict validation step
(e.g., a validate_table_name(table) helper) or map incoming table values through
a fixed whitelist/dict of allowed table names before any string interpolation,
and raise on invalid names; apply the same validation to the other occurrence
that interpolates "table" (around the second occurrence noted at line ~874) so
only known safe identifiers are used before calling conn.execute or constructing
SQL strings.
… stale column, renamed index) (#1660) Three small fixes for pre-existing test failures discovered during the 2026-05-27 backlog sweep ([#1657](#1657)). Each was a stale-test issue rather than a production-code bug. ## Changes - **\`tests/unit/storage/test_schema_safety.py\`** — required-index list named the pre-#635 \`idx_conversations_provider\` index, which was renamed to \`idx_conversations_source_name\` during the provider->source storage-column vocabulary transition. Updated the test, added a one-line comment explaining the rename. - **\`tests/unit/storage/test_repair_blobs.py\`** — \`_reference_blob\` helper's INSERT into \`raw_conversations\` passed seven VALUES against a six-column list, tripping \`OperationalError: 7 values for 6 columns\`. The extra \`'referenced.json'\` literal pre-dated a schema column removal. - **\`tests/unit/storage/test_fts5.py\`** — \`test_search_includes_conversation_metadata\` asserted both \`hit.source_name == "claude-ai"\` and \`hit.source_name == "my-source"\` on the same row (impossible). Same shape as the duplicate-column failures fixed in PR #1651/#1652/#1653. Removed the contradictory second assertion. ## Verification \`\`\` $ nix develop -c pytest tests/unit/storage/test_repair_blobs.py \\ tests/unit/storage/test_schema_safety.py tests/unit/storage/test_fts5.py 96 passed in 3.01s $ nix develop -c devtools verify --quick exit_code: 0 \`\`\` ## Out of scope The order-dependent flake in \`test_daemon_http_contracts.py\` (KeyError 'fts_readiness' / 'component_state' under specific pytest-randomly seeds) is tracked separately under #1657. It needs a cross-test mock-state-leak investigation that doesn't fit this PR's small-cleanup shape. Ref #1657. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Surface DELETE-phase progress in
rebuild_session_insights_syncsothe operator log shows forward motion at table granularity instead of
"hang" until the first chunk inserts. The seven unconditional DELETEs
hold the write lock for seconds at production scale, minutes at 10x.
Also pin the atomicity invariant that #1607 questioned — the implicit
transaction started by the first DELETE actually does span every
subsequent DML through the eventual
conn.commit(), so a SIGKILLmid-rebuild does not leave the archive empty.
Ref #1607
Problem
From #1607:
The "non-transactional" framing in the issue is wrong (see Solution
below), but the silent DELETE phase is a real operator-experience
gap.
polylogue qa --rebuild-insightslooked hung on theproduction archive every time.
Solution
New helper
_delete_tables_with_progress_syncloops the sevenDELETEs and emits one
ProgressCallbackevent per table(
desc="rebuild: cleared <name>",amount=rowcount). Therebuild_session_insights_sync(conversation_ids=None)full-rebuildpath and its async counterpart route DELETEs through the helper,
threading the existing
progress_callbackparameter through.Targeted rebuilds (
conversation_ids != None) are unchangedbecause their DELETEs are per-conversation and finish quickly.
The CLI progress sink already attached to
rebuild_session_insights_sync(
make_session_insight_progress_callback) now naturally surfaces a"rebuild: cleared session_work_events" → ... → "rebuild: cleared
repo_identities" sequence before the materialize loop's "Materializing:
1/N" output. No CLI changes required.
Atomicity (AC2)
#1607 claims the DELETEs and the rebuild loop are non-transactional
and that a SIGKILL between them leaves the archive empty. Tracing
the code shows otherwise:
conn.execute("DELETE ...")opens an implicit transaction (Pythonsqlite3 default isolation).
replace_*_bulk_syncruns DML withoutcommitting — they all stay in the same implicit tx.
conn.commit().In WAL mode, the DELETEs are not durable until COMMIT. A SIGKILL
between DELETE and INSERT rolls back the WAL on next open. Pinned
by
test_full_rebuild_rolls_back_on_exception_keeping_prior_profileswhich:
build_session_insight_record_bundlesto raiseRuntimeErrorfrom inside the chunk loop.COUNT(session_profiles)after the failed rebuildequals the baseline (not zero).
The "AC1 declared op-spec contract" and "AC4 refuse-or-pause live
ingest" branches require new infrastructure and stay open against
#1607.
Verification
Verification angles considered:
test_delete_tables_with_progress_emits_one_event_per_tableexercises the helper with a 3-table scenario, asserts
desc=...for each andamount=matchingrowcount(including 0 for empty tables).
test_full_rebuild_emits_progress_for_each_deleted_tableruns thereal
rebuild_session_insights_syncwith a seeded conversationand asserts the seven cleared-table events fire in order.
test_delete_tables_progress_callback_is_optionalpins thatprogress_callback=Nonedoes not raise and still runs theDELETEs.
test_full_rebuild_rolls_back_on_exception_keeping_prior_profilesproves the perf:
rebuild_session_insights_syncruns 7 unconditional table DELETEs without progress or transaction scope #1607 "non-atomic" hypothesis wrong with executableevidence.
test_session_insight_rebuild_sync_reports_progressupdated tofilter "Materializing:" events from "rebuild: cleared" events;
both sequences pinned.
Verification angles skipped:
inside one transaction.
seven DELETEs as before; the extra callback invocation is constant
overhead per table.
Inherited test failures fixed alongside (CLAUDE.md §19a):
tests/unit/storage/test_dead_schema_sweep.py—test_schema_version_is_14was asserting against an outdatedconstant. Schema is now 16. Renamed the test, updated the comment.
tests/unit/storage/test_query_mappers.py—test_maps_all_fieldsassertedsource_name == "chatgpt"andsource_name == "inbox"on the same row. Removed theduplicate-and-contradictory assertion; seed sets "inbox".
Commands run:
Notes
test_repair_blobs.py,test_fts5.py,test_schema_safety.py, the cross-test orderflake in
test_daemon_http_contracts.pymentioned in perf(daemon): downgrade FTS trigger drift to INFO during fresh bulk catch-up (#1613) #1652)are out of scope here. They reproduce on master too. Will be
tracked as a follow-up sweep.
Summary by CodeRabbit
New Features
Bug Fixes
Tests