Skip to content

perf(insights): emit progress per table during full session-insight rebuild - #1653

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/atomic-session-insight-rebuild
May 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/atomic-session-insight-rebuild

Conversation

@Sinity

@Sinity Sinity commented May 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Surface DELETE-phase progress in rebuild_session_insights_sync so
the 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 SIGKILL
mid-rebuild does not leave the archive empty.

Ref #1607

Problem

From #1607:

polylogue/storage/insights/session/rebuild.py:667-673 runs seven
unconditional DELETE statements at the start of every full
insight rebuild [...] cumulative DELETE phase is on the order of
seconds of pure write-lock-under-trigger. On a future 10x archive,
this scales to minutes. During those seconds-to-minutes [...] there
is no progress reporting; the operator sees no output until the
first new row lands.

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-insights looked hung on the
production archive every time.

Solution

New helper _delete_tables_with_progress_sync loops the seven
DELETEs and emits one ProgressCallback event per table
(desc="rebuild: cleared <name>", amount=rowcount). The
rebuild_session_insights_sync(conversation_ids=None) full-rebuild
path and its async counterpart route DELETEs through the helper,
threading the existing progress_callback parameter through.
Targeted rebuilds (conversation_ids != None) are unchanged
because 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 (Python
    sqlite3 default isolation).
  • Every subsequent replace_*_bulk_sync runs DML without
    committing — they all stay in the same implicit tx.
  • The function commits exactly once at the bottom via
    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_profiles
which:

  1. Runs one rebuild to establish a baseline of session_profiles.
  2. Monkeypatches build_session_insight_record_bundles to raise
    RuntimeError from inside the chunk loop.
  3. Asserts that COUNT(session_profiles) after the failed rebuild
    equals 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:

  • Direct behavior ✓ —
    test_delete_tables_with_progress_emits_one_event_per_table
    exercises the helper with a 3-table scenario, asserts
    desc=... for each and amount= matching rowcount
    (including 0 for empty tables).
  • Direct integration ✓ —
    test_full_rebuild_emits_progress_for_each_deleted_table runs the
    real rebuild_session_insights_sync with a seeded conversation
    and asserts the seven cleared-table events fire in order.
  • Counterfactual / robustness ✓ —
    test_delete_tables_progress_callback_is_optional pins that
    progress_callback=None does not raise and still runs the
    DELETEs.
  • Atomicity invariant ✓ —
    test_full_rebuild_rolls_back_on_exception_keeping_prior_profiles
    proves the perf: rebuild_session_insights_sync runs 7 unconditional table DELETEs without progress or transaction scope #1607 "non-atomic" hypothesis wrong with executable
    evidence.
  • Existing-test compatibility ✓ —
    test_session_insight_rebuild_sync_reports_progress updated to
    filter "Materializing:" events from "rebuild: cleared" events;
    both sequences pinned.

Verification angles skipped:

  • Concurrency / lifecycle — N/A; the function is single-threaded
    inside one transaction.
  • Performance / amplification — the helper itself runs the same
    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_14 was asserting against an outdated
    constant. Schema is now 16. Renamed the test, updated the comment.
  • tests/unit/storage/test_query_mappers.py —
    test_maps_all_fields asserted source_name == "chatgpt" and
    source_name == "inbox" on the same row. Removed the
    duplicate-and-contradictory assertion; seed sets "inbox".

Commands run:

$ 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

Notes

Summary by CodeRabbit

  • New Features

    • Session rebuild operations now emit progress feedback events as tables are cleared, providing real-time visibility into ongoing operations.
  • Bug Fixes

    • Improved transaction error handling to ensure data integrity—failed rebuild operations now automatically roll back to preserve existing data.
  • Tests

    • Added comprehensive test coverage for progress event reporting and transaction atomicity during rebuild operations.

Review Change Stack

…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]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Session insights rebuild operations now emit progress callbacks during table deletion. A new _delete_tables_with_progress_sync helper deletes rebuild target tables with optional per-table progress reporting. Both sync and async rebuild paths are updated to use this pattern, and a comprehensive test module validates progress emission and transaction atomicity on rebuild failure.

Changes

Rebuild Progress Reporting & Atomicity

Layer / File(s) Summary
Delete helper and sync rebuild integration
polylogue/storage/insights/session/rebuild.py, tests/unit/cli/test_insights.py
New _delete_tables_with_progress_sync helper deletes rebuild target tables and conditionally emits one progress_callback per table with rowcount-derived amount. Sync rebuild updated to use this helper instead of silent DELETE statements, and progress test updated to verify the new "rebuild: cleared" events alongside existing materialize events.
Async rebuild progress emission
polylogue/storage/insights/session/rebuild.py
Async rebuild full-rebuild path updated to emit progress_callback after each table DELETE, deriving rowcount from async cursor.
Progress reporting and atomicity test suite
tests/unit/storage/test_session_insight_rebuild_progress.py
Four new tests: progress helper emits one event per table including zero-row tables; optional callback does not raise; full rebuild forwards DELETE progress matching expected table messages; transaction rolls back on exception keeping prior profiles intact.
Schema version and test data updates
tests/unit/storage/test_dead_schema_sweep.py, tests/unit/storage/test_query_mappers.py
Schema version contract test updated from 14 to 16; conversation source_name test data changed from "chatgpt" to "inbox".

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #1607: This PR directly implements per-table DELETE progress callbacks and atomicity guarantees for rebuild operations, addressing the same unconditional deletes and transaction concerns.

Poem

🐰 Tables fall like autumn leaves,
Progress whispers what the rebuild achieves,
Each cleared row sings a message true,
And when things fail, the rollback carries through!
🌿✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding per-table progress emission during session-insight rebuild, which aligns with the core PR objective and solution.
Description check ✅ Passed The description comprehensively covers all required template sections: Summary, Problem, Solution, Verification, Changelog, and Risks. It provides detailed context, implementation details, verification evidence, and test commands with results.
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.

✏️ 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/perf/atomic-session-insight-rebuild

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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f4941b and e2a78d4.

📒 Files selected for processing (5)
  • polylogue/storage/insights/session/rebuild.py
  • tests/unit/cli/test_insights.py
  • tests/unit/storage/test_dead_schema_sweep.py
  • tests/unit/storage/test_query_mappers.py
  • tests/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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@Sinity
Sinity merged commit 8d3555d into master May 27, 2026
6 checks passed
@Sinity
Sinity deleted the feature/perf/atomic-session-insight-rebuild branch May 27, 2026 08:12
Sinity added a commit that referenced this pull request May 27, 2026
… 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]>
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