Skip to content

refactor(storage): consolidate session-insight writers onto replace_insight_rows - #1379

Merged
Sinity merged 2 commits into
masterfrom
refactor/insight-writer-helper
May 19, 2026
Merged

Sinity merged 2 commits into
masterfrom
refactor/insight-writer-helper

Conversation

@Sinity

@Sinity Sinity commented May 19, 2026

Copy link
Copy Markdown
Owner

Summary

  • Add replace_insight_rows helper in polylogue/storage/sqlite/queries/_bulk_replace.py — the canonical DELETE-WHERE-id-IN + executemany INSERT pattern, modeled on lynchpin's promote_rows.
  • Migrate 3 session-insight writers (profiles, work_events, phases) onto the helper.
  • The two summary writers (replace_session_tag_rollup_rows, replace_day_session_summaries) stay handwritten — see Solution.

Problem

Three replace_*_bulk functions in queries/session_insight_*_writes.py each spelled out the same DELETE-then-INSERT scaffold by hand: build placeholders for an IN (?, ?, …) clause, run the DELETE, look up has_legacy_payload via PRAGMA table_info, build the INSERT SQL via build_insert_sql, executemany, commit when transaction_depth == 0. The drift surface between these copies was the lifecycle contract itself — any of them could quietly skip the commit, skip the DELETE-empty guard, or miscount placeholders without the others noticing.

Solution

  • New module polylogue/storage/sqlite/queries/_bulk_replace.py exposes replace_insight_rows(conn, *, table, id_column, id_values, columns, records, extractor, transaction_depth). SQL output is byte-identical to the hand-rolled originals.
  • replace_session_profiles_bulk, replace_session_work_events_bulk, replace_session_phases_bulk now compute has_legacy_payload once and delegate. Each loses ~14 LoC of scaffolding.
  • The helper takes a single id_column + id_values for WHERE … IN (?, ?, …). Sites with a different predicate shape (replace_session_tag_rollup_rows and replace_day_session_summaries use composite provider_name = ? AND day/bucket_day = ?) are intentionally not migrated — generalising the helper's API for 2 sites at the cost of clarity for the 3 that already fit isn't worth it. Revisit if a 3rd composite-WHERE writer appears.

Verification

  • nix develop --command pytest tests/unit/storage -q → 760 passed plus the dedicated tests/unit/storage/test_bulk_replace.py (18 cases covering empty input, single, multi-record, idempotent re-insert, transaction-depth commit behavior).
  • 3 pre-existing failures on this branch's master baseline (verified pre-existing via stash-then-pytest): test_no_unaudited_string_interpolated_sql, test_search_unique_token_parity, test_search_shared_token_parity. Of these, test_no_unaudited_string_interpolated_sql actually now passes on this branch because the migration replaced inline f-string DELETE/INSERT SQL with the helper's audited template — accidental bonus fix.
  • devtools verify-topology clean (helper module added to topology-target.yaml, migrated files' LoC counts updated).

Files

  • polylogue/storage/sqlite/queries/_bulk_replace.py (+66, new)
  • tests/unit/storage/test_bulk_replace.py (+229, new)
  • polylogue/storage/sqlite/queries/session_insight_profile_writes.py (-9 net)
  • polylogue/storage/sqlite/queries/session_insight_timeline_writes.py (-18 net)
  • docs/plans/topology-target.yaml (+ entry for _bulk_replace.py, LoC counts updated)

@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 30 minutes and 48 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ed4133b-2dba-4780-b7fc-3cecb2adc9cb

📥 Commits

Reviewing files that changed from the base of the PR and between 9743e00 and 336b230.

📒 Files selected for processing (6)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/storage/sqlite/queries/_bulk_replace.py
  • polylogue/storage/sqlite/queries/session_insight_profile_writes.py
  • polylogue/storage/sqlite/queries/session_insight_timeline_writes.py
  • tests/unit/storage/test_bulk_replace.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/insight-writer-helper

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.

@Sinity
Sinity force-pushed the refactor/insight-writer-helper branch from 3d8d4b5 to 77c8fab Compare May 19, 2026 16:19
Sinity added a commit that referenced this pull request May 19, 2026
…#1384)

## Summary

PR #1370 (typed ranked-result envelope) changed `polylogue list --format
json` for search-mode queries to emit `{"hits": [...], "limit": N,
"next_cursor": ...}` rather than a bare JSON array. The CLI parity
adapter at `tests/infra/surfaces.py:307` still expected a bare array and
asserted `not isinstance(parsed, list)`, causing both
`test_search_unique_token_parity` and `test_search_shared_token_parity`
to fail on every search-mode case on master.

## Solution

When the parsed CLI output is a dict carrying a `hits` array (the typed
envelope shape), peel the `hits` and continue with the existing per-row
id extraction. The list-mode and search-hit-mode shapes still work
unchanged — they hit the same row loop directly.

Updated the inline doc to enumerate all three shapes the adapter now
handles.

## Verification

- `nix develop --command pytest
tests/unit/storage/test_surface_parity_adapters.py -q` → **10 passed**
(was 2 failures on master).
- No production code touched; test-infra only.

## Scope

Single-file, test-infra-only change. Should land before #1379 / #1380 /
#1382 (or alongside) so those PRs' CI runs are unmasked by this
pre-existing failure.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sinity and others added 2 commits May 19, 2026 18:26
Extract the DELETE-then-INSERT shape shared by every replace_*_bulk
function in polylogue/storage/sqlite/queries/ into a single helper.
Each call site builds its own column list and per-record extractor
(needed because session_*_insert_columns depend on a runtime
has_legacy_payload probe) and delegates the boilerplate.

The helper produces byte-identical SQL to the previous handwritten
sites: one DELETE ... WHERE id_col IN (?, ?, ...) when ids are present,
one build_insert_sql(table, columns) INSERT via executemany when
records are present, and a commit gated on transaction_depth == 0.

Mirrors lynchpin/substrate/_helpers.py::promote_rows, adjusted for
aiosqlite and polylogue's per-call dynamic column lists.

Co-Authored-By: Claude <[email protected]>
…ight_rows

Phase 2 of the polylogue symmetry sweep. Commit 9474f322 added the
shared replace_insight_rows helper; this commit migrates the three
call sites that fit its shape:

- session_insight_profile_writes.py:replace_session_profiles_bulk
- session_insight_timeline_writes.py:replace_session_work_events_bulk
- session_insight_timeline_writes.py:replace_session_phases_bulk

Each loses ~14 LoC of DELETE-then-executemany scaffolding; SQL output
is byte-identical. The has_legacy_payload column-discovery short-circuits
on empty input.

Sites NOT migrated, with reason:
- session_insight_summary_queries.py {replace_session_tag_rollup_rows,
  replace_day_session_summaries} use a 2-column composite WHERE
  (provider_name = ? AND day = ?), not a single-column IN list.
  Generalising replace_insight_rows for 2 sites at the cost of API
  surface isn't worth it. Skip; revisit if a third composite site
  appears.

The architectural read estimated 5 collapsible sites; reality was 3 +
2 different-shape. Truth-checking the audit pays off.

Verification:
- nix develop --command pytest tests/unit/storage -q
  → 760 passed; 3 pre-existing failures (verified on master via stash).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity
Sinity force-pushed the refactor/insight-writer-helper branch from 77c8fab to 336b230 Compare May 19, 2026 16:26
@Sinity
Sinity merged commit 12e8df5 into master May 19, 2026
3 of 5 checks passed
@Sinity
Sinity deleted the refactor/insight-writer-helper branch May 19, 2026 16:27
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