Skip to content

fix: make SQLite migrations atomic and repair partial 029/030 states - #576

Open
enyst wants to merge 5 commits into
mainfrom
fix/sqlite-atomic-migrations
Open

enyst wants to merge 5 commits into
mainfrom
fix/sqlite-atomic-migrations

Conversation

@enyst

@enyst enyst commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

AGENT:

Summary

SQLite startup → BEGIN IMMEDIATE (already on main via #592)
  repair the remaining partial 030 state
  run migrations (schema + KV data + revision)
  ├─ success → COMMIT
  └─ wrong/missing secret or other failure → ROLLBACK everything

partial 030 + non-empty new table → refuse; leave data unchanged

Retries can recover the released partial states using the original KV secret.

Why

Main now fixes transaction atomicity and partial-029 retries via #592. This PR adds recovery for the partial-030 tables left by older releases.

Issue Number

Fixes #575. Part of OpenHands/OpenHands#18299. Companion KV pinning: OpenHands/OpenHands#18307.

How to Test

Recorded: 10 focused migration/history tests passed; the old migration code failed seven of nine KV tests. Released-code broken databases recovered with the original key; PostgreSQL 16 and the real Canvas launcher were also checked.

Previously recorded verification

New tests in tests/test_kv_migration.py build disposable SQLite databases:

  • Failed upgrades from 028 and from 029, each with a missing and with a wrong secret. A snapshot of the schema, revision and every KV row must be identical after the failure, and a retry with the right secret must fan the document out with its values and $version. The pre-existing 028/missing-secret test is folded into this one.
  • Repair of both partial states, using the exact DDL released 029/030 produce.
  • Refusal of a partial 030 state whose new table has rows.

Run against this branch:

uv run python -m pytest tests/test_kv_migration.py tests/test_migration_history.py
10 passed

The same test file against main's migrations fails 7 of the 9 KV tests. The 028/missing-secret case fails on the schema snapshot because 029's column survived. The repair tests fail with the two errors above.

Real-database checks beyond the unit tests:

  1. Databases broken by the released code. I broke databases with main (028 and 029 starts, wrong key), then started this branch on them:
    • with the wrong key again, it failed and left the broken state as it was (same revision, column and tables);
    • with the original key, it upgraded to 032 with the values and $version intact.
  2. PostgreSQL 16 (local cluster). Wrong-key failures from 028 and 029 roll back fully, and the retry with the right key succeeds. A fresh database with no secret upgrades to head, downgrades to 028 and upgrades again. The 029/030 checks are no-ops there.
  3. Through Agent Canvas's real launcher. I ran scripts/dev-with-automation.mjs with OH_AUTOMATION_LOCAL_PATH pointing at this branch. A database at 028 holding KV data written under the session key started cleanly (028 → 032, "SQLite database migrations applied successfully") and kept its values.

Full suite: uv run python -m pytest tests/ -n 4 gave 1376 passed, 0 failed, 520 errors. All 520 errors are docker.errors.DockerException from the PostgreSQL/MinIO container fixtures, because my environment had no Docker daemon. Those fixtures build their schema with create_all, not migrations, and CI will run them. ruff format, ruff check, pycodestyle and pyright are clean on the changed files.

Video/Screenshots

Not applicable: verification tooling or migration behavior; recorded proof is above.

Type

  • Bug fix

Notes

Every SQLite startup briefly takes a write lock, with the driver’s default 5 s wait. Recovery requires the original AUTOMATION_KV_SECRET and a backup first; a lost secret cannot be reconstructed. The full local suite had 1,376 passes and 520 Docker-fixture setup errors because no daemon was available—not a green full suite. No dedicated concurrency test was claimed.

Visual explanation by Codex using HumanLayer show-me.

Before/after evidence (re-verified 13 November on main 949c001)

Same script both times: build a SQLite DB to 029, seed one legacy KV document encrypted with the original secret, apply exactly the DDL released 030 leaves behind after a failed decrypt, then retry alembic upgrade head with the original AUTOMATION_KV_SECRET.

Before (main 949c001) After (this PR, merged with main)
before after

I merged current main into this branch (migrations now end at 037). tests/test_kv_migration.py + tests/test_migration_history.py: 13 passed on the branch. The same test_kv_migration.py run against main's migrations: 5 failed, 7 passed. The screenshots live in .pr/, which the release PR removes.

This update was made by an AI agent (OpenHands) on behalf of Graham Neubig.

Jev-Fast-Audit

⚡ Jev fast audit · estimates · 0.31s · commit f2bef0b
Strongest signal: No primary concern selected.
Evidence: No primary concern to locate.
Coverage: ⚠️ reduced context — partial coverage; 11/11 hunks, 5/5 files (missing patch: 2).

All estimates and evidence
Estimate Likelihood / value Direct evidence
SQL injection 49.0% F005H004 · tests/test_kv_migration.py:129–156
Command injection 21.0% No direct hunk selected
Weakened authentication 6.0% No direct hunk selected
Weakened authorization 7.0% No direct hunk selected
Contract regression 15.0% No direct hunk selected
Data loss 22.0% F004H003 · migrations/versions/030_kv_per_key_rows.py:127–168
Sensitive data disclosure 8.0% No direct hunk selected
Unexpected data transfer 3.0% No direct hunk selected
Credential misuse 8.0% No direct hunk selected
Untrusted instruction authority 3.0% No direct hunk selected
Package source redirection 4.0% No direct hunk selected
Unverified remote execution 3.0% No direct hunk selected
Privileged environment access 7.0% No direct hunk selected
Security assessment bypass 4.0% No direct hunk selected
Prohibited workload 2.0% No direct hunk selected
Primary concern None selected; confidence 45.0% No primary concern to locate

Current verification (25 October)

Updated with current main and preserved the already-merged #592 transaction control, SQLite-only 029 repair, and newer PostgreSQL startup/engine handling. The remaining diff covers partial-030 recovery, clearer decryption errors, recovery documentation, and broader regression tests. Expected head revisions now come from Alembic rather than a literal.

Focused migration/history/SQLite/KV tests: 29 passed. Ruff, formatting, pycodestyle, and pyright pass on changed Python files. A broader startup suite had 34 passes and 11 Docker-fixture setup errors because no Docker daemon is available; that is not a passing PostgreSQL suite. Updated the documented startup log message to match current main. Fresh CI and review are requested.

Python's sqlite3 driver only opens a transaction before INSERT/UPDATE/DELETE,
so DDL that ran first committed on its own. When migration 030 failed to
decrypt legacy KV state (wrong or missing AUTOMATION_KV_SECRET), the revision
rolled back but the schema did not: from 028 the 029 column survived, from 029
the 030 rename and new tables survived, and every retry then failed on them
(OpenHands/OpenHands#18299, #575).

- migrations/env.py: on SQLite, disable the driver's implicit BEGIN and issue
  BEGIN IMMEDIATE when the migration transaction begins (SQLAlchemy's
  documented pysqlite recipe). The whole upgrade is now one transaction, and
  a second migrator waits for the write lock.
- 029: skip the column if an earlier failed run already added it.
- 030: if automation_kv_legacy is present next to empty new tables (what a
  failed run left behind), drop the empty tables and rename the legacy table
  back before running. Non-empty tables are refused and left untouched.
- 030: name AUTOMATION_KV_SECRET in the decryption error.
- app.py: stop claiming the database may be inconsistent after a failure.

Tests cover failed upgrades from 028 and 029 with missing and wrong secrets
(schema, revision and every KV row unchanged, then retry succeeds), repair of
both partial states, and refusal of an ambiguous one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MetmkfA8Cb49iE8tJb8GNp
@github-actions github-actions Bot added the type: fix A bug fix label Oct 12, 2026
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Warning

Your comment is too long (maximum is 65536 characters), so the coverage report was not added. See the job log for how to reduce it.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This review was posted by an AI agent (OpenHands).

Assessment

Scope is correct for this repository: OpenHands/automation owns the Alembic migrations and the SQLite auto-migration startup path (migrations/env.py, openhands/automation/app.py). Linked issue #575 is open with ready-for-dev and priority:low, and the change addresses the migration atomicity plus the two partial states it describes. The Canvas secret decoupling is correctly left to OpenHands/OpenHands#18307.

Verified on head e96fd9a:

  • migrations/env.py applies SQLAlchemy's documented pysqlite recipe (isolation_level=None plus a begin listener issuing BEGIN IMMEDIATE) to the SQLite migration engine only. The production startup path reaches it: settings.db_url comes from AUTOMATION_DB_URL, which is_sqlite() reads, so BEGIN IMMEDIATE wraps the whole engine.begin() upgrade and rolls schema, data and alembic_version back together.
  • 029 is idempotent (skips an existing column) and 030 repairs a leftover automation_kv_legacy beside the empty new tables. The non-empty-new-table case raises before any drop, and the check-before-drop ordering is correct. The combined 028-start state (029 column present and 030 rename/tables present) is also handled: 029 skips and 030 repairs.
  • The app.py message change is accurate under the single-transaction upgrade, and startup still aborts on failure.

Checks: I ran tests/test_kv_migration.py and tests/test_migration_history.py (10 passed) and tests/test_db.py::TestSqliteMigrations (3 passed) against this head; ruff check/format are clean on the changed files. GitHub Actions for the head are green (unit-tests, backend, image build).

Two non-blocking notes, not merge blockers:

  • Issue #575 asks for the recovery procedure and its backup/validation steps to be documented. The code's error messages and the PR description cover it, but nothing lands in-repo (e.g. docs/kv-store-design.md); a short recovery note would help operators of already-broken installs.
  • The explicit two-concurrent-migrator test the issue lists is not added. The PR's reasoning is sound: a naive held-lock test also passes on the old code, and the rollback tests prove the transaction begins before the first DDL. I do not consider this blocking.

✅ APPROVED

Issue #575 asks for the recovery procedure, with its backup and validation
steps, to be documented. Add it to the migration section of the KV design
doc: what a failed 030 leaves behind now that SQLite upgrades are one
transaction, how to recover with the original secret, how the half-migrated
states from earlier releases are repaired, and what a lost secret costs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MetmkfA8Cb49iE8tJb8GNp
@enyst

enyst commented Oct 12, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review. On the two notes:

  1. Recovery procedure in the repo: agreed. Commit 8721933 adds it to the "Migration From Single-Document State" section of docs/kv-store-design.md. It covers what a failed 030 leaves behind now, the recovery steps (back up, restart with the original AUTOMATION_KV_SECRET, check the log line and alembic_version), the repair of the half-migrated states from releases up to 1.19.3, and the cost of a lost secret. That section already called 030 "transactional", which is only true on SQLite with this PR. The lost-secret step matches what I ran against databases broken by 1.19.3: delete the KV rows, then this branch upgrades to head and keeps the automations. Agent Canvas users get the step-by-step version in docs(agent-canvas): recover automations after the API key changed docs#928.
  2. Concurrency test: leaving it as is, for the reason you gave.

Generated by Claude Code

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This review was posted by an AI agent (OpenHands).

Assessment

Scope is correct for this repository: OpenHands/automation owns the Alembic migrations and the SQLite auto-migration startup path (migrations/env.py, migrations/versions/029_*, 030_*, openhands/automation/app.py). Linked issue #575 is open with ready-for-dev and priority:low. CI for this head is green (unit-tests, backend, image build, PR title/description all success; no failing checks).

Since the previous APPROVED on e96fd9a, the only code change on this head is the added docs/kv-store-design.md recovery section; I confirmed the diff e96fd9a..8721933 touches only that file. I re-ran the focused suite on this exact head:

  • tests/test_kv_migration.py tests/test_migration_history.py -> 10 passed
  • tests/test_db.py tests/test_kv_per_key.py -> 42 passed
  • ruff check and ruff format --check clean on the changed files; pyright clean on the migration files.

Findings

The change is correct and well-tested:

  • _use_explicit_sqlite_transactions applies SQLAlchemy's documented pysqlite recipe (disable the driver's implicit BEGIN, emit BEGIN IMMEDIATE on SQLAlchemy's begin). I exercised the listener directly across repeated engine.begin(), a second pooled connection, and a rollback of a nested savepoint inside an open transaction; isolation is preserved. This makes the whole upgrade one real transaction, so schema, data and alembic_version roll back together, and it takes the write lock up front so a second migrator serializes.
  • 029 skips consecutive_auth_failures when present, and 030's _undo_partial_upgrade only reverts the exact empty-table shape a failed run leaves, refusing with a message when a new table holds rows. Both are gated on this being the only writer of those objects, matching the reproduction in #575.
  • The 030 decryption error now names AUTOMATION_KV_SECRET and states the stored state was not modified; app.py's message now matches the new transactional guarantee.
  • The docs/kv-store-design.md recovery steps (back up, set the original secret, restart; repair of half-migrated databases; lost-secret cost including Git Sync tokens wrapped with AUTOMATION_KV_SECRET) are consistent with the code and with the secret_store fallback described in AGENTS.md.

No blocking or non-blocking defects found. PostgreSQL behavior is unaffected (the listener is only registered for SQLite; the 029/030 recovery paths are no-ops there).

✅ APPROVED

Co-authored-by: openhands <openhands@all-hands.dev>
@enyst
enyst requested a review from all-hands-bot October 25, 2026 03:39

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This review was posted by an AI agent (OpenHands).

Assessment

Scope is correct for this repository: OpenHands/automation owns the KV store and its Alembic migrations. All three changed files (migrations/versions/030_kv_per_key_rows.py, docs/kv-store-design.md, tests/test_kv_migration.py) are in scope; no product or architecture decision is needed.

The head 71a54f0 merges current main into the branch; the PR's own diff against main remains +216/−13 across the three files above, and the only change to the PR's own files since the last approved head (8721933) is the one-line docs update aligning the recovery log string with the code (app.py now logs "Database migrations applied successfully", which this PR's docs now match — verified against the current app.py:92).

Verification

  • uv run python -m pytest tests/test_kv_migration.py tests/test_migration_history.py at this exact head: 13 passed (parametrized failure/repair matrix expands the 10 focused cases described in the PR).
  • Migration chain is linear with a single head (034); 029 → 030 → 031 → 032 → 033 → 034 is a complete upgrade path from the released schema.
  • _undo_partial_upgrade only fires when automation_kv_legacy exists, refuses to touch a partial 030 state whose automation_kv/automation_kv_meta rows are non-empty (RuntimeError mid-transaction rolls back — nothing changed), and otherwise drops the empty tables and renames the legacy table back, all inside the single BEGIN IMMEDIATE transaction that migrations/env.py opens for SQLite. On PostgreSQL the repair is a no-op, and PG already gets full rollback from its engine.begin() migration transaction, so parity is preserved.
  • The docs' recovery procedure matches the implementation: a retry with the original secret re-runs 030 inside one transaction; a lost secret is documented as unrecoverable except by deliberately deleting KV rows.

CI on this head: backend and both image builds green; unit-tests was still running at review time. No failing checks on 71a54f0.

No material correctness, security, or design findings. The failure-path snapshot tests prove the atomicity claim, and the repair tests use the exact DDL released 029/030 produce, so the recovery path is exercised against real broken states rather than idealized ones.

✅ APPROVED

@neubig
neubig requested a review from malhotra5 November 9, 2026 18:16
@github-actions

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR adds or changes temporary PR-specific documents under .pr/. They stay on this branch for review. After this PR merges, the next release PR removes them from main.

@neubig
neubig requested a review from all-hands-bot November 13, 2026 23:22

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This review was posted by an AI agent (OpenHands). (re-review requested via all-hands-bot event 36083982300; this head f2bef0b is new since the previous approvals on 71a54f0, so a fresh review was performed)

Assessment

Scope is correct for this repository: OpenHands/automation owns the Alembic migrations and their SQLite/PostgreSQL parity (AGENTS.md "Database" section and the repo review guide's "Database and migration parity" checkpoint). The PR is a focused follow-up to the already-merged #592 transaction control: it repairs the remaining partial-030 state that releases before the single-transaction migration runner left on SQLite.

What was verified

Repair preconditions hold. The docstring premise that the new tables are empty in the partial state is confirmed by the pre-#592 migrations/env.py (209f74b): under the old SQLite connection settings, the rename and CREATE TABLE DDL persisted while the row inserts and the alembic_version bump rolled back together. The original ciphertext therefore remains intact in automation_kv_legacy, which is what _undo_partial_upgrade relies on when it drops the empty new tables and renames the legacy table back before the normal flow re-runs.

The guard is sound. Rows committed without the version bump cannot result from the released code (the DML and version bump committed in the same deferred transaction), so the non-empty-table refusal in migrations/versions/030_kv_per_key_rows.py is a conservative tripwire for unexpected shapes, and it changes nothing when it fires. All shapes the released code could leave are handled: legacy with empty new tables, and legacy with no new tables at all (the partial list is empty and the rename-back alone restores the 029 state).

Composition with transactional rollback is correct. On a retry that fails again (still wrong or missing secret), BEGIN IMMEDIATE + rollback restores the partial state exactly, so the repair is re-runnable; the next attempt with the right secret completes. The refusal and rollback paths do not mutate data.

PostgreSQL is unaffected. automation_kv_legacy cannot survive a failed 030 on PostgreSQL (transactional DDL), so _undo_partial_upgrade returns immediately there; the PR's PG verification and the early-return guard agree.

Tests exercise real paths. The new tests drive real alembic subprocess runs against real SQLite files and snapshot schema, revision, and every KV row across failures — no mocks. I ran tests/test_kv_migration.py and tests/test_migration_history.py on this head: 13 passed, matching the PR's claim. All GitHub Actions checks on f2bef0b are green, including the required unit-tests job.

Docs match the code. The recovery steps added to docs/kv-store-design.md reference the actual startup log line (Database migrations applied successfully, openhands/automation/app.py:93), and the .pr/ evidence images follow the repository's PR-artifacts convention with SHA-pinned links in the description.

No material correctness, security, compatibility, or acceptance-criterion findings on this head.

✅ APPROVED

This branch has not been deployed

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

Labels

type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLite migrations leave partial schema after KV decryption failure; make rollback and recovery safe

5 participants