Skip to content

fix(storage): unify schema, FTS, cache, and write side effects #618

Closed

Description

@Sinity

Scope

Composite issue for archive-storage correctness and compactness around schema bootstrap, direct write paths, FTS/search side effects, legacy product payloads, and storage helper duplication.

Problem

Several storage issues share one root: archive writes and schema side effects are split across multiple paths that are not governed by one contract.

Already completed

Sync ingest FTS/cache side effects (#707 / fix(pipeline): commit sync ingest side effects)

  • _process_ingest_batch_sync() now restores FTS triggers, repairs changed-conversation message/action FTS rows, commits that teardown work, then invalidates the search cache when conversations changed.
  • Regression test: caches an empty search, sync-ingests a conversation through the direct sqlite batch path, then verifies from a fresh connection that FTS rows persisted and the same search query returns the new conversation.

Schema version mismatch (#709 / fix(storage): block schema version mismatch)

  • Schema-version mismatch now blocks with the reset/re-import diagnostic instead of running additive DDL and advancing PRAGMA user_version.
  • Sync and async schema setup share that behavior.
  • open_read_connection() performs a non-mutating compatibility check for mismatched versions and known legacy inline raw layouts.
  • Removed the unused metadata export/import path that belonged to the misleading in-place recreate story.

Force-write propagation (#711 / #714)

  • run --reparse propagates force_write through run workflow, pipeline execution, parsing services, and sync ingest writes.
  • _write_conversation(..., force_write=True) replaces same-hash message rows (corrected in fix(acquisition): harden live freshness and reparse writes #714 — earlier version left old message rows behind).

Remaining acceptance criteria

  1. Broader write-path unification: repository writes, sync ingest/batch writes, and other direct archive write paths should share a post-write contract for FTS repair, trigger restoration, cache invalidation, and product/readiness side effects.
  2. FTS trigger/table SQL single source of truth: FTS lifecycle SQL is still split across schema_ddl_archive.py and fts_lifecycle.py. Unify.
  3. Hot search readiness: exact row-count FTS readiness should not be on the hot search path. Exact counts belong in doctor/readiness/repair, or behind bounded freshness caching.
  4. Legacy session-product payload support: delete from hot read/write paths or move into an explicit documented migration/repair path.
  5. Unsafe asset IDs: accepted through the advertised asset_path() contract without failing in temp-file creation.
  6. Storage module consolidation: schema.py + schema_bootstrap.py are already coupled — consider merging. connection_profile.py cache pragmas should be verified against WAL mode across both sync and async paths.
  7. Write-path ownership clarity: function names/signatures should indicate whether they mutate, commit, invalidate cache, or expect the caller to do so.

Storage subsystem map

polylogue/storage/
├── backends/
│   ├── schema_ddl.py/archive.py        # schema definition, SCHEMA_VERSION
│   ├── schema.py                       # fresh-only init, version guard
│   ├── schema_bootstrap.py             # shared bootstrap + extension planning
│   ├── connection.py                   # read/write connection lifecycle
│   ├── connection_profile.py           # canonical PRAGMA/performance profiles
│   ├── async_sqlite.py                 # async SQLite runtime
│   ├── sync_sqlite.py                  # sync SQLite (CLI, schema tooling)
├── search_providers/
│   ├── fts5.py                         # lexical search
│   ├── hybrid.py                       # RRF fusion
│   ├── vector.py                       # vector search
├── repository/
│   ├── repository.py                   # 10-mixin composition facade
│   ├── insight/                        # session insight repositories
├── blob_store.py                       # content-addressed blob storage
├── run_state.py                        # run state tracking
├── repair.py                           # health/repair operations

Consolidated findings

This issue absorbs and supersedes:

Related but kept separate:

Ref #578

Activity

  1. changed the title [-]fix(storage): make schema mismatch handling explicit[/-] [+]fix(storage): unify schema, FTS, cache, and write side effects[/+] on May 1, 2026
  2. added
    type:fix
    area:core
    on May 1, 2026
  3. Sinity commented on May 1, 2026

    @Sinity
    OwnerAuthor

    Additional write-path audit detail from .agent/scratch/636-write-path-data-integrity-audit.md:

    The sync-ingest FTS finding is sharper than the current wording. In _process_ingest_batch_sync(), ingest rows are committed first, then finally restores triggers and calls repair_fts_index_sync() before closing the connection. A sqlite smoke check confirms the trigger DDL persists when no transaction is open, but the subsequent FTS repair DML opens an implicit transaction and is rolled back on close() unless committed. So the concrete bug is: sync ingest can persist conversation/message rows while losing the targeted FTS repair rows.

    The same audit also confirmed the cache side-effect split:

    • repository save/delete invalidates search cache after writes;
    • async indexing commits and invalidates after FTS work;
    • sync ingest writes conversations directly and does not call invalidate_search_cache().

    Suggested acceptance additions:

    • End-to-end sync-ingest test with suspended triggers: after the function returns and a fresh connection opens, all changed conversations have persisted messages_fts and action_events_fts rows.
    • Same-process cache law: cache an empty search, ingest matching content through the sync batch path, rerun the same search, and observe the new hit without relying on unrelated invalidation.
    • Make low-level mutating helpers explicit about ownership: either operation-level functions commit/invalidate consistently, or helper names/signatures make caller-owned commit/cache policy obvious.
  4. Sinity commented on May 1, 2026

    @Sinity
    OwnerAuthor

    Storage-side-effect guard: the close path should define who owns commit, FTS repair, and cache invalidation for every write family.

    Suggested acceptance split:

    • repository writes: post-write FTS/cache side effects happen in one owned path;
    • sync ingest/batch writes: either call the same repository/service side-effect path or explicitly own commit + FTS repair + cache invalidation before returning;
    • schema bootstrap/compatibility: read-only opens perform non-mutating compatibility checks and never silently initialize/upgrade;
    • helper functions: names/signatures indicate whether they mutate, commit, invalidate cache, or expect the caller to do so.

    The key bug class is not only duplicated SQL; it is rows being durable while their derived search/cache side effects are not.

  5. Sinity commented on May 1, 2026

    @Sinity
    OwnerAuthor

    Implementation anchors and acceptance additions from the 2026-05-01 follow-up audit.

    Code anchors to preserve:

    • polylogue/pipeline/services/ingest_batch.py:843-869: _process_ingest_batch_sync() suspends FTS triggers, starts BEGIN IMMEDIATE, writes/commits ingest rows, then in finally restores triggers and calls repair_fts_index_sync() before closing the connection.
    • polylogue/storage/fts/fts_lifecycle.py:159-168: trigger restore executes DDL but does not own commit.
    • polylogue/storage/fts/fts_lifecycle.py:217-228: repair_fts_index_sync() performs delete/insert FTS DML but does not own commit.
    • polylogue/storage/search/cache.py:74-87: cache invalidation primitive exists, but ingest_batch.py does not call it.

    Acceptance additions:

    • Post-ingest FTS trigger restoration and changed-conversation FTS repair run inside an explicit committed unit, followed by search cache invalidation. The owner of commit/invalidation is visible in function names or signatures.
    • Regression: suspend triggers, sync-ingest changed conversations, close the connection, open a fresh connection, and assert both messages_fts and action_events_fts contain rows for changed conversations.
    • Same-process cache law: cache an empty search, sync-ingest content that should match, rerun the same search in-process, and observe the new hit.

    Also fold the closed #619 performance edge into this issue: hot search should not do exact row-count FTS readiness by default. Exact counts belong in doctor/readiness/repair, or behind bounded freshness caching. #619 already contains the evidence that search calls exact readiness on the hot path and that derived status already has a verify_full knob.

  6. Sinity commented on May 1, 2026

    @Sinity
    OwnerAuthor

    Storage decision from 2026-05-01 bundle

    Integrated decisions:

    • Schema mismatch behavior can be deferred relative to naming/CLI/live/proof cleanup.
    • When addressed, mutation should block on unsupported schema and offer explicit rebuild preserving metadata.
    • Unsupported legacy session-product payload handling should be deleted, not kept as hot-path compatibility code.

    Acceptance refinements:

    • Legacy payload branches should be removed from normal read/write paths.
    • If any compatibility behavior survives, it belongs in an explicit migration/repair command, not in current hot storage paths.
    • Sync ingest FTS/cache side effects remain high priority for data/search correctness.

    Ref #635

  7. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    Storage subsystem map (2026-05-02)

    These are the key storage modules and their current sizes — useful for planning the unification work:

    polylogue/storage/
    ├── backends/
    │   ├── schema_ddl.py/archive.py        # schema definition, SCHEMA_VERSION
    │   ├── schema.py                       # fresh-only init, version guard
    │   ├── schema_bootstrap.py             # shared bootstrap + extension planning
    │   ├── connection.py                   # read/write connection lifecycle
    │   ├── connection_profile.py           # canonical PRAGMA/performance profiles
    │   ├── async_sqlite.py                 # async SQLite runtime
    │   ├── sync_sqlite.py                  # sync SQLite (CLI, schema tooling)
    ├── search_providers/
    │   ├── fts5.py                         # lexical search
    │   ├── hybrid.py                       # RRF fusion
    │   ├── vector.py                       # vector search
    ├── repository/
    │   ├── repository.py                   # 10-mixin composition facade
    │   ├── insight/                        # session insight repositories
    ├── blob_store.py                       # content-addressed blob storage
    ├── run_state.py                        # run state tracking
    ├── repair.py                           # health/repair operations
    

    The unification targets from the issue title (schema, FTS, cache, write side effects) suggest consolidating:

    1. Schema: merge schema.py + schema_bootstrap.py — they're already coupled (branching logic shared)
    2. FTS: fts5.py triggers currently live in schema_ddl_archive.py — FTS lifecycle split across two files
    3. Cache: check if connection_profile.py cache pragmas interact correctly with WAL mode across both sync and async paths
    4. Write side effects: repository.py mixin composition is powerful but hard to trace write ordering — document the commit sequence
  8. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    Landed first #618 implementation slice in #707.

    Scope completed:

    • _process_ingest_batch_sync() now restores FTS triggers, repairs changed-conversation message/action FTS rows, commits that teardown work, then invalidates the search cache when conversations changed.
    • Added a regression that caches an empty search, sync-ingests a conversation through the direct sqlite batch path, then verifies from a fresh connection that FTS triggers and message/action FTS rows persisted and that the same search query returns the new conversation.

    Verification recorded on the PR:

    • ruff check polylogue/pipeline/services/ingest_batch.py tests/unit/pipeline/test_ingest_batch.py
    • ruff format --check polylogue/pipeline/services/ingest_batch.py tests/unit/pipeline/test_ingest_batch.py
    • pytest -q tests/unit/pipeline/test_ingest_batch.py
    • pre-push devtools verify --quick

    Still open in this composite issue:

    • schema version mismatch semantics are still not explicit enough;
    • read-only connections still need non-mutating compatibility checks;
    • the broader write-path unification and hot search readiness work remain separate follow-up slices.
  9. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    Landed second #618 storage slice in #709.

    Scope completed:

    • schema-version mismatch now blocks with the reset/re-import diagnostic instead of running additive DDL and advancing PRAGMA user_version;
    • sync and async schema setup share that behavior;
    • open_read_connection() now performs a non-mutating compatibility check for mismatched versions and known legacy inline raw layouts;
    • removed the unused metadata export/import path that belonged to the misleading in-place recreate story;
    • updated architecture/assurance wording from wipe/migrate language to explicit block-and-rebuild semantics.

    Also incorporated unrelated timestamp fixes that were present in the worktree from another agent:

    • materialization sort keys now use parse_timestamp() for ISO timestamps;
    • ChatGPT ISO create_time values now participate in message ordering.

    Verification recorded on #709:

    • focused ruff/format checks for changed storage, parser, materialization, and tests;
    • pytest -q tests/unit/storage/test_backend.py tests/unit/pipeline/test_materialization_runtime.py;
    • pytest -q tests/unit/sources/test_parsers_chatgpt.py tests/unit/pipeline/test_materialization_runtime.py;
    • devtools verify-manifests;
    • devtools render-all --check;
    • pre-push devtools verify --quick.

    Still open in #618:

    • broader write-path unification;
    • hot search readiness/performance work;
    • full audit of remaining direct archive write paths and cache invalidation contracts.
  10. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    #711 also landed a small write-path correction that was present as in-progress work from another agent: run --reparse now propagates force_write through run workflow, pipeline execution, parsing services, and sync ingest writes. This means same-content-hash conversation rows are still replaced after parse status is explicitly reset, instead of being skipped by _check_content_unchanged().

    Regression added: _write_conversation(..., force_write=True) replaces same-hash message rows. This narrows the remaining #618 write-side drift to broader repository/sync-ingest unification and hot search readiness work.

  11. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    PR #714 incorporates the pending forced-reparse ingestion fix from the other-agent workstream, with an important correction.

    The uncommitted hunk had the right goal — force_write=True must replace same-hash rows instead of skipping by content hash — but it left old message rows behind during forced same-hash reparses. I corrected _write_conversation() so force-write remains a true replacement path and verified it with tests/unit/pipeline/test_ingest_batch.py::test_write_conversation_force_write_replaces_same_hash_rows as part of the full tests/unit/pipeline/test_ingest_batch.py run.

    I also fixed the sort-key SQL predicate placement while keeping the ingest file under its file-size budget.

  12. 1 remaining item

  13. Sinity commented on May 2, 2026

    @Sinity
    OwnerAuthor

    Implementation plan: storage write-path unification (from agent analysis 2026-05-03)

    Purely mechanical?

    Mostly. FTS DDL dedup and asset temp filename fix are mechanical. Legacy payload removal is dead code deletion. Hot search readiness is a parameter change on two call sites.

    Files touched

    • polylogue/storage/fts/sql.py — remove duplicated DDL, import from canonical schema_ddl modules
    • polylogue/storage/fts/fts_lifecycle.py — remove duplicated trigger DDL
    • polylogue/storage/insights/session/storage.py — delete legacy _with_legacy_payload_column, has_legacy_payload, payload_json branches
    • polylogue/storage/search/runtime.py line 57 — verify_total_rows=False
    • polylogue/assets.py line 49 — use sanitized temp filename prefix
    • polylogue/storage/post_write.py (new) — canonical commit_write_side_effects()

    Order of operations

    1. FTS DDL single-source (mechanical, no behavioral change)
    2. Asset temp filename sanitization (one-line fix)
    3. Hot search readiness (two call-site changes)
    4. Legacy session-product payload removal (dead code deletion)
    5. Write-path unification (shared post-write contract)
    6. Storage module consolidation (optional, deferrable)

    Estimated effort

    Medium — ~2.5 days. FTS DDL dedup 0.5 day, legacy payload 0.5 day, hot search 0.25 day, asset fix 0.1 day, write-path unification 1 day.

  14. Sinity commented on May 3, 2026

    @Sinity
    OwnerAuthor

    AC audit (2026-05-03)

    Hot search readiness is already done: polylogue/readiness/__init__.py:329-330 uses exact_index_counts = deep or not probe_only. When probe_only=True, verify_total_rows=False flows to FTS lifecycle, avoiding the expensive row-count check. This AC can be marked resolved.

    Remaining: FTS SQL single-source + legacy session-product payload removal + write-path unification.

  15. Sinity commented on May 3, 2026

    @Sinity
    OwnerAuthor

    Implementation slice published in PR #742: #742

    Scope realized:

    • explicit transactional schema v2 -> v3 upgrade for the additive messages.message_type column and idx_messages_conversation_message_type index;
    • backfill from existing v2 role/content-block/flag data without deleting archive rows;
    • unsupported versions and legacy raw layouts still block rather than falling back to destructive rebuild behavior;
    • docs/changelog updated to say Polylogue is fresh-first with explicit reviewed upgrades, not an arbitrary migration chain.

    Verification recorded in the PR:

    • focused storage suite: 60 passed in 8.31s;
    • ruff check/format on changed Python files;
    • git diff --check;
    • Polylogue devshell devtools verify --quick and pre-push hook both passed.

    Live motivation: the workstation archive had a physically v3-shaped messages.message_type schema while PRAGMA user_version was 2, caused by an older binary writing the version marker. The current runtime then rejected it and scheduled runs could drift into expensive catch-up/reimport behavior instead of applying the small additive delta.

  16. Sinity commented on May 3, 2026

    @Sinity
    OwnerAuthor

    Closed by #756. ArchiveWriteGateway is the canonical write path. commit_archive_write_effects consolidated in polylogue/archive/write_effects.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:storagetype:fix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions