Storq logoStorq
docsmanaged-sqlite-contract.md
Edit / View on GitHub

Managed SQLite Contract (Phases 1-4)

This document records the managed SQLite design contract. The implementation includes the initial open_database() connection surface and generation-based online backups. Phase 2 adds named recovery points, verified manifests, per-source retention, and opt-in checkpoint policies. Phase 3 adds bounded in-memory operation history, pre-commit invariants, and opt-in post-commit health checks. Phase 4 adds an opt-in, separate append-only transaction journal, a strict replay subset, and a candidate replay cursor. Automatic corruption detection and recovery remain future phases.

Scope and compatibility

  • The initial managed adapter targets local, file-backed SQLite databases. In-memory databases, remote filesystems, and URI/shared-cache connection modes are out of scope for the first release.
  • The target minimum SQLite version is 3.35.0. A release must test the actual SQLite library linked by the native extension; the Python interpreter's separately bundled SQLite version does not establish native compatibility.
  • The first managed release supports rollback-journal mode and WAL mode for persistent databases. It must detect and report the active mode rather than silently changing an existing database's journal mode. OFF and MEMORY journal modes are unsupported for protected operation and consistent backups.
  • Opening an existing database must not silently create a new file. Database creation, if offered, is an explicit operation.

Connection and transaction behavior

  • Applications receive protection only for reads/writes performed through a Storq-managed connection. Direct SQLite connections, other processes, and external file changes bypass Storq's write checks and activity tracking.
  • A connection is owned by one process and one calling thread at a time; it is not safe to share a live connection across threads or fork it into a child process. Separate connections may coordinate through SQLite's locking and transaction behavior.
  • SQL values use bound parameters; callers must not interpolate untrusted values into SQL strings.
  • Writes execute in explicit SQLite transactions. A transaction context commits on normal exit and attempts rollback when the body raises. Commit, rollback, and close errors are surfaced. Storq does not silently retry writes, because retrying a non-idempotent operation can duplicate effects.
  • If SQLite reports an I/O or corruption error that makes the transaction outcome uncertain, Storq reports that uncertainty and blocks further managed writes on that connection until it is closed and the database is re-inspected. It does not claim that rollback succeeded unless SQLite confirms it.
  • The managed connection exposes is_healthy and health_error. An unhealthy connection rejects new write statements and transactions; reads remain available for diagnostics where SQLite permits them. quick_check() and integrity_check() preserve their findings and mark the connection unhealthy when the result is not exactly ["ok"].
  • A failed transaction-context commit attempts rollback when SQLite still reports an active transaction. Commit and rollback errors are surfaced; uncertain outcomes mark the connection unhealthy.
  • SQLite constraints and transaction semantics remain authoritative for database consistency. Optional application invariants may be evaluated at commit, but cannot replace constraints or verify arbitrary application semantics automatically.
  • Managed operation and transaction histories are bounded, in-memory diagnostics, not durable audit or replay records. SQL parameters are omitted by default; enabling parameter capture may retain secrets.
  • Application invariants run before managed transaction commit. Returning False or raising rejects the commit and triggers rollback. Direct managed writes are wrapped in a transaction when invariant hooks are configured.

Health checks and write protection

  • A successful commit means SQLite reported that transaction committed; it does not prove that the file is immune to later corruption or physical storage failure.
  • Do not run full PRAGMA integrity_check after each commit. It may scan the whole database and impose substantial overhead.
  • Expose a lightweight health check (PRAGMA quick_check) on demand or on a configured schedule. Offer full integrity_check as an explicit deeper validation. Both return their findings and whether the check completed.
  • When a health check reports corruption or an unrecoverable SQLite error, mark the managed connection unhealthy, reject new writes on it, and preserve the diagnostic result. Reopening or restoring requires a separate explicit action; a passing check must not automatically clear prior corruption evidence.
  • The default commit health policy is none. quick and integrity run their respective SQLite check after successful managed commits; custom invokes a caller-provided, read-only health callback. Any failed post-commit check reports that the SQL transaction already committed and marks the connection unhealthy. A post-commit check is not a durability guarantee.
  • Operation records capture a sequence, transaction ID, SQL category, timestamp, commit state, and affected-row count when available. They classify observed busy, locked, I/O, and corruption errors, but are not persisted and do not enable transaction replay.

Durable journal and replay boundary

  • Journaling is opt-in through open_database(..., transaction_journal=...). The journal path must be separate from the protected database. One managed writer holds an exclusive lock; other managed writers using that journal are rejected.
  • Journal records are append-only JSONL with a sequence and SHA-256 checksum chain. Records are flushed with fsync before proceeding. POSIX journal and lock files are restricted to owner-only permissions; Windows relies on the parent directory's access-control policy.
  • A transaction intent and each replayable statement with its bound values are recorded before SQLite executes them. The committed or rolled-back decision is recorded after SQLite reports its outcome. SQLite and the journal are separate resources and cannot be committed atomically together. A failure to make a decision durable is surfaced as unacknowledged/uncertain and fences further journaled writes.
  • An unresolved intent, uncertain decision, malformed/torn record, checksum failure, or sequence gap blocks journal writes and replay. The wrapper does not guess whether an unresolved SQLite commit took effect.
  • Replay supports only a strict subset of deterministic SELECT, INSERT, UPDATE, and DELETE SQL and scalar bound values. Unsupported syntax, unsafe schema features, nondeterministic functions, triggers, and external side effects are not replayed. SQL and parameter values are stored in cleartext; checksums are not cryptographic authentication.
  • Replay is explicit and targets an existing candidate distinct from the source. A reserved cursor table records progress atomically with replayed transactions, so rerunning replay can resume safely. Replay does not itself verify or promote the candidate, and cannot protect writes made outside the managed connection.
  • Journal retention, compaction, encryption, key management, and arbitrary-SQL replay are not implemented. The journal therefore grows without bound and may contain sensitive application data; deployments must protect and manage its storage externally.

Recovery detection boundary

  • Managed SQL errors indicating corruption or uncertain I/O, and failed explicit health checks, mark the in-memory recovery status as recovery_required. This is a detection result, not an automatic repair.
  • Around managed statements Storq compares PRAGMA data_version values to detect commits from another SQLite connection. A detected external write marks recovery assumptions inconclusive and blocks further managed writes. If the version cannot be read, health is inconclusive unless a separate operation identifies corruption or uncertainty.
  • prepare_recovery_candidate() is an explicit operation. It selects the newest verified point, restores it to a new candidate, verifies the candidate, and reports the selected point, elapsed interval, verification evidence, and in-memory action log. It never replaces the source.
  • This phase does not detect every raw database-file edit, validate all WAL sidecars, replay transactions newer than the selected point, or promote a candidate. Those remain limitations or later-phase work. A candidate that passes checks is not proof of semantic correctness.

Backup policy

  • Backups are explicit or scheduled only when the caller configures a backup policy. No backup is made on every commit by default.
  • Use SQLite's online backup API (or a separately validated SQLite-supported equivalent) so the backup is consistent while the source is active, including WAL mode. A raw copy of only the live main database file is not a supported backup method.
  • Active source state records journal_mode and hashes all present WAL, SHM, and rollback-journal sidecars in manifests. Sidecar metadata is evidence only; it is never copied as an independent database state.
  • Snapshot creation rejects OFF and MEMORY journal modes and fences PRAGMA data_version before and after native snapshot creation. A change during snapshot creation blocks the backup as untrusted.
  • Write each backup to a new generation. Verify it by reopening read-only and running at least quick_check; make full integrity verification configurable. A failed or interrupted backup is not marked verified and cannot replace an older recovery point.
  • Keep multiple generations by default (target retention: seven verified generations, configurable). Retention must never delete the last verified recovery point before a replacement has completed and passed verification.
  • Record a manifest with database identity, generation ID, timestamp, SQLite/Storq versions, source/backup sizes, backup method, and verification result. Backup storage location, permissions, and retention of potentially sensitive data are caller-visible configuration.
  • Retention applies per source database and only to generations whose manifest, backup path, and backup hash verify. Publish a manifest only after the snapshot passes its configured check. Failed attempts must remove their temporary and unpublished artifacts.
  • A named recovery point is created only outside a managed transaction. The manifest records the caller's checkpoint label or transaction ID when supplied. A source-file hash is observational metadata; the backup hash identifies the exact consistent snapshot, including data captured from WAL.
  • Automatic point policies are opt-in. checkpoint is the default; transaction and interval may create frequent snapshots and consume substantial I/O and storage. Time-based interval thresholds are evaluated after a managed commit, not by a background timer.

Recovery and promotion boundary

  • The first recovery release restores a verified backup into a new candidate path. It does not overwrite the damaged source and does not promise salvage of unrecoverable pages. Salvage is a later, separately scoped capability for explicitly supported corruption cases.
  • Report the selected backup generation, its timestamp/recovery point, and the elapsed interval since that point as the potential data-loss window. Storq cannot guarantee that all transactions since a backup are recoverable.
  • Validate the candidate read-only before use. inconclusive, failed checks, or omitted data block automatic promotion.
  • Promotion is an explicit caller/application operation after verification. It must account for open connections and WAL/SHM sidecars and retain a rollback path. Storq does not silently switch or replace the source.
  • Candidate restore copies only a standalone verified backup. Raw source WAL, SHM, or rollback-journal files are not copied into the candidate. Candidate verification rejects a candidate with any such sidecar.
  • Promotion preserves copies of source WAL, SHM, and rollback-journal sidecars beside the main-file rollback, removes source/candidate sidecars before replacement, and restores copied sidecars if promotion fails.
  • Phase 7 provides restore_recovery_candidate() to restore a selected point, replay later acknowledged transactions, and verify the candidate. The returned result must be complete before promotion when a transaction journal is active.
  • promote_recovered_candidate() accepts explicit preserve_damage and recovery_result inputs. It blocks incomplete replay/verification results, requires the managed connection to be closed, creates a source rollback, optionally archives the damaged source and sidecars, and never promotes automatically.
  • Phase 8 adds RecoveryPolicy with default observe. prepare_candidate creates and verifies but does not promote; promote_verified promotes only a verified candidate with complete replay and an explicitly closed managed connection; fail_closed blocks managed writes. The default and observation policies never replace the source.
  • Phase 9 evidence workspaces can write machine-readable verification reports with SHA-256 hashes and append-only action logs. A supplied independent report must have status="passed" before promotion; inconclusive or failed reports block promotion. Reports distinguish observations from limitations and do not claim reconstruction or semantic correctness.
  • Phase 10 provides run_recovery_certification() for repeatable disposable fault runs. It exports deterministic scenario identities and source hashes, preserves the original source, and does not perform automatic promotion. Certification results are observations, not physical durability or production-recovery guarantees.

Phase 1 decision summary

The initial target is a thread/process-owned, file-backed SQLite connection with explicit transactions, bound parameters, rollback and WAL journal-mode support, opt-in/scheduled generation-based backups, and no per-commit full integrity scan. Recovery begins with verified-backup restore to a separate candidate; salvage and automatic recovery remain later phases. Phase 4 replay is explicit, limited to its documented SQL subset, and does not recover or promote a damaged database on its own.