Skip to content

fix(storage): upgrade schema v2 archives in place - #742

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/schema-v2-upgrade
May 3, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/schema-v2-upgrade

Conversation

@Sinity

@Sinity Sinity commented May 3, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a narrow in-place schema v2 to v3 upgrade for the additive messages.message_type archive facet, and fixes a broken devtools manifest gate that required untracked .local demo state.

Problem

A live archive can be physically compatible with schema v3 while carrying PRAGMA user_version = 2 after an older binary rewrites only the version marker. Current schema bootstrap then rejects the database and scheduled runs can drift into expensive reimport/catch-up behavior instead of applying the small additive delta.

The publish gate was also not reproducible in clean worktrees: docs/plans/docs-media-coverage.yaml required .local/readme-demo/example.tape, which is machine-local state and not committed evidence.

Solution

  • Add a transactional v2-to-v3 upgrade path that adds messages.message_type, creates idx_messages_conversation_message_type, backfills message types from existing role/content-block flags, and updates PRAGMA user_version without deleting archive rows.
  • Keep unsupported schema versions and legacy raw layouts rejected with the reset/re-import diagnostic.
  • Update architecture/assurance docs and changelog to describe the explicit-upgrade posture.
  • Mark VHS tape coverage as absent from committed sources instead of requiring .local/readme-demo.

Verification

  • PYTHONPATH=. /realm/project/polylogue/.venv/bin/python -m pytest -q tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py -> 60 passed in 8.31s
  • PYTHONPATH=. /realm/project/polylogue/.venv/bin/ruff check polylogue/storage/backends/schema.py polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py -> All checks passed!
  • PYTHONPATH=. /realm/project/polylogue/.venv/bin/ruff format --check polylogue/storage/backends/schema.py polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py -> 4 files already formatted
  • git diff --check
  • /realm/project/sinnix/scripts/sinnix-scope build -- nix develop --command devtools verify --quick -> verify: all checks passed
  • Pre-push hook under the Polylogue devshell -> verify: all checks passed

Ref #618

Summary by CodeRabbit

  • New Features

    • Database archives can now upgrade in-place to the new schema format while preserving all existing data, rather than requiring a fresh import.
  • Documentation

    • Updated schema evolution policy to reflect a "fresh-first" approach with explicit upgrade paths.
    • Updated assurance and changelog documentation to clarify migration strategy.
  • Tests

    • Added comprehensive tests for in-place schema upgrade behavior and failure recovery with rollback.

Sinity added 2 commits May 3, 2026 03:19
Problem: schema v3 added the stored message_type facet, but older binaries could leave an otherwise-current archive marked as user_version 2. The current runtime then rejected the DB and scheduled runs could fall back into expensive reimport/catch-up behavior.\n\nWhat changed: add a narrow transactional v2-to-v3 upgrade that adds the message_type column/index, backfills it from existing role/content-block flags, and updates PRAGMA user_version without deleting archive rows. Unsupported versions and legacy raw layouts still block with a reset diagnostic.\n\nVerification: PYTHONPATH=. /realm/project/polylogue/.venv/bin/python -m pytest -q tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py; ruff check/format on changed Python files; git diff --check.\n\nRef #618
Problem: devtools verify --quick failed in clean worktrees because docs-media coverage declared .local/readme-demo/example.tape as a required path. That file is machine-local state, not committed repository evidence.\n\nWhat changed: mark VHS tape coverage as absent from committed sources and document .local/readme-demo as optional local experiment state.\n\nVerification: /realm/project/sinnix/scripts/sinnix-scope build -- nix develop --command devtools verify --quick.
Copilot AI review requested due to automatic review settings May 3, 2026 01:26
@coderabbitai

coderabbitai Bot commented May 3, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR adds support for upgrading SQLite schema from v2 to v3 in place, introducing a new messages.message_type column with automatic backfilling based on existing message content. The system now detects v2→v3 mismatches and applies the upgrade transactionally, preserving archive rows while rejecting unsupported transitions.

Changes

Schema v2 to v3 In-Place Upgrade

Layer / File(s) Summary
Policy & Documentation
CHANGELOG.md, docs/architecture.md, docs/plans/assurance-domains.yaml, docs/plans/docs-media-coverage.yaml
Updated documentation to reflect new "fresh-first" strategy that allows explicit, reviewed in-place upgrades for specific schema transitions; clarified v2→v3 preserves rows; removed reference to committed VHS tape fixture.
Upgrade Plan Definition
polylogue/storage/backends/schema_bootstrap.py
Added _MESSAGE_TYPE_EXTENSION_DESCRIPTORS defining the message_type column and index; introduced _V2_TO_V3_MESSAGE_TYPE_BACKFILL_SQL variants to populate types based on message content (role/tool/thinking classification); created build_v2_to_v3_upgrade_plan() to construct conditional upgrade statements; extended decide_schema_bootstrap() to detect v2→v3 transitions when messages table exists.
Upgrade Execution & Transactions
polylogue/storage/backends/schema.py
Added _apply_version_upgrade_plan() and _apply_version_upgrade_plan_async() to execute upgrade plans within BEGIN IMMEDIATE transactions with rollback on failure; extended _ensure_schema() and ensure_schema_async() to route upgrade_v2_to_v3 decisions through these new executors; ensures vec0 table and sets PRAGMA user_version atomically.
Test Fixtures & Verification
tests/unit/storage/test_backend.py, tests/unit/storage/test_schema_safety.py
Added _create_v2_message_type_fixture() to construct v2-schema databases; introduced sync/async tests verifying upgrade without row reimport and without overwriting pre-existing message_type values; added rollback safety test confirming failed upgrades leave user_version and schema unchanged; updated rejection-message assertions for version mismatch paths; extended schema catalog assertions to include idx_messages_conversation_message_type index.

Sequence Diagram

sequenceDiagram
    actor User
    participant Backend as Backend Process
    participant Bootstrap as Bootstrap Decision
    participant Executor as Upgrade Executor
    participant DB as SQLite Connection

    User->>Backend: open existing v2 archive
    Backend->>Bootstrap: decide_schema_bootstrap(snapshot={current_version:2})
    Bootstrap->>Bootstrap: Check version mismatch:<br/>v2 vs SCHEMA_VERSION=3
    alt v2 → v3 possible (messages table exists)
        Bootstrap->>Bootstrap: build_v2_to_v3_upgrade_plan()
        Bootstrap-->>Bootstrap: Return action="upgrade_v2_to_v3"<br/>+ extension_plan
    else Unsupported mismatch
        Bootstrap-->>Bootstrap: action="version_mismatch"
    end
    Bootstrap-->>Backend: decision (action, extension_plan)
    alt action == "upgrade_v2_to_v3"
        Backend->>Executor: _apply_version_upgrade_plan(plan)
        Executor->>DB: BEGIN IMMEDIATE
        Executor->>DB: ALTER TABLE messages<br/>ADD COLUMN message_type
        Executor->>DB: INSERT/UPDATE message_type<br/>via backfill SQL
        Executor->>DB: CREATE INDEX<br/>idx_messages_conversation_message_type
        Executor->>Executor: ensure_vec0_table()
        Executor->>DB: PRAGMA user_version = 3
        Executor->>DB: COMMIT
        Executor-->>Backend: ✓ upgrade complete
    else On failure
        Executor->>DB: ROLLBACK
        Executor-->>Backend: ✗ exception
    end
    Backend-->>User: v3 schema ready
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Hops with glee at schema's grace,
v2 to v3, in-place embrace!
Messages now typed, rows preserved true,
No re-imports, just upgrade anew!
Transactions rollback if things go wrong—
Safety and speed, together strong! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.33% 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 'fix(storage): upgrade schema v2 archives in place' accurately and concisely summarizes the main change: adding an in-place upgrade path for schema v2 archives to v3.
Description check ✅ Passed The description follows the required template with all major sections completed: Summary, Problem, Solution, Verification, Changelog, and Risks/Follow-ups, providing clear context and validation steps.
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/fix/schema-v2-upgrade

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 2bd6630 into master May 3, 2026
5 of 6 checks passed
@Sinity
Sinity deleted the feature/fix/schema-v2-upgrade branch May 3, 2026 01:29

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

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

Comment thread polylogue/storage/backends/schema.py Resolved
Sinity added a commit that referenced this pull request May 3, 2026
Summary

Avoids an unnecessary archive-wide message-type backfill when a schema v2 archive already has the v3 `messages.message_type` column.

Problem

PR #742 added the right v2-to-v3 upgrade path, but the upgrade plan still appended the message-type backfill whenever `messages` existed. That is wasteful for the live failure shape: a physically v3-shaped DB whose `PRAGMA user_version` was rewritten to 2 by an older binary. Running the backfill there would scan the archive even though the column already exists.

Solution

Only append the message-type backfill when `messages.message_type` is absent. Already-extended v2 archives now repair missing version/index state without rereading all messages/content blocks.

Verification

- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/python -m pytest -q tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py` -> `61 passed in 8.72s`
- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/ruff check polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py` -> `All checks passed!`
- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/ruff format --check polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py` -> `2 files already formatted`
- `git diff --check`
- Pre-push hook under the Polylogue devshell -> `verify: all checks passed`

Ref #618
@Sinity
Sinity removed the request for review from Copilot May 3, 2026 01:50
Sinity added a commit that referenced this pull request May 7, 2026
Summary

Adds a narrow in-place schema v2 to v3 upgrade for the additive `messages.message_type` archive facet, and fixes a broken devtools manifest gate that required untracked `.local` demo state.

Problem

A live archive can be physically compatible with schema v3 while carrying `PRAGMA user_version = 2` after an older binary rewrites only the version marker. Current schema bootstrap then rejects the database and scheduled runs can drift into expensive reimport/catch-up behavior instead of applying the small additive delta.

The publish gate was also not reproducible in clean worktrees: `docs/plans/docs-media-coverage.yaml` required `.local/readme-demo/example.tape`, which is machine-local state and not committed evidence.

Solution

- Add a transactional v2-to-v3 upgrade path that adds `messages.message_type`, creates `idx_messages_conversation_message_type`, backfills message types from existing role/content-block flags, and updates `PRAGMA user_version` without deleting archive rows.
- Keep unsupported schema versions and legacy raw layouts rejected with the reset/re-import diagnostic.
- Update architecture/assurance docs and changelog to describe the explicit-upgrade posture.
- Mark VHS tape coverage as absent from committed sources instead of requiring `.local/readme-demo`.

Verification

- `PYTHONPATH=. /realm/project/polylogue/.venv/bin/python -m pytest -q tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py` -> `60 passed in 8.31s`
- `PYTHONPATH=. /realm/project/polylogue/.venv/bin/ruff check polylogue/storage/backends/schema.py polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py` -> `All checks passed!`
- `PYTHONPATH=. /realm/project/polylogue/.venv/bin/ruff format --check polylogue/storage/backends/schema.py polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py` -> `4 files already formatted`
- `git diff --check`
- `/realm/project/sinnix/scripts/sinnix-scope build -- nix develop --command devtools verify --quick` -> `verify: all checks passed`
- Pre-push hook under the Polylogue devshell -> `verify: all checks passed`

Ref #618
Sinity added a commit that referenced this pull request May 7, 2026
Summary

Avoids an unnecessary archive-wide message-type backfill when a schema v2 archive already has the v3 `messages.message_type` column.

Problem

PR #742 added the right v2-to-v3 upgrade path, but the upgrade plan still appended the message-type backfill whenever `messages` existed. That is wasteful for the live failure shape: a physically v3-shaped DB whose `PRAGMA user_version` was rewritten to 2 by an older binary. Running the backfill there would scan the archive even though the column already exists.

Solution

Only append the message-type backfill when `messages.message_type` is absent. Already-extended v2 archives now repair missing version/index state without rereading all messages/content blocks.

Verification

- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/python -m pytest -q tests/unit/storage/test_backend.py tests/unit/storage/test_schema_safety.py` -> `61 passed in 8.72s`
- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/ruff check polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py` -> `All checks passed!`
- `PYTHONPATH=. /realm/project/polylogue-schema-v2-upgrade/.venv/bin/ruff format --check polylogue/storage/backends/schema_bootstrap.py tests/unit/storage/test_backend.py` -> `2 files already formatted`
- `git diff --check`
- Pre-push hook under the Polylogue devshell -> `verify: all checks passed`

Ref #618
@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.

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