Storq logoStorq
Architecture & Internals · HOW_IT_WORKS.md

How Storq Works

View HOW_IT_WORKS.md on GitHub

Storq is a Python SDK backed by a compiled C++20 native extension (storq._native) for database-format inspection, managed SQLite reliability, deterministic fault simulation, and recovery workflows.

text
Python Application
       │
       ▼
  storq (Python SDK)
   ├── ManagedSQLiteDatabase   (transactions, health checks, backups, journal, recovery)
   ├── Fault & Certification   (evidence workspaces, deterministic fault scenarios)
   ├── Workflows & Testing     (WorkflowBuilder, TestSuite)
   ├── Reporting & Benchmarks  (ReportBuilder, Benchmark, history & comparison)
   └── storq._native (C++20)   (format/page/WAL inspection, Storq format, workloads)

Install the package with:

shell
python -m pip install storq

Architecture Layers — Python SDK & Native C++20 Extension
Rendering diagram...
Component layout derived directly from HOW_IT_WORKS.md.

1. Read-Only Format Inspection and Diagnosis

  • storq.inspect_format(path) reads the file header (including SQLite magic bytes and page headers) without opening a SQLite write connection or modifying the file. It does not rely on file extensions—.db, .sqlite, or custom extensions all work.
  • storq.diagnose_database(path, ...) performs read-only format, bounded page, and optional SQLite WAL analysis, returning JSON-safe findings and SHA-256 hashes.

2. Managed SQLite Connections

Opening a database with storq.open_database(path, ...) wraps a file-backed SQLite connection in ManagedSQLiteDatabase:

  • Explicit transactions & bound parameters: Writes run inside explicit transactions (with db.transaction():) using parameterized SQL.
  • Health policies (ManagedHealthPolicy):
    • Pre-commit invariants: Custom Python callbacks run before commit; returning False or raising rolls back the transaction.
    • Post-commit checks: Optional quick, integrity, or custom health checks run after commit.
  • Failure tracking: If SQLite reports corruption or an uncertain I/O error, or if a health check fails, is_healthy becomes False and further writes are blocked on that connection.
  • External write detection: Around managed operations, Storq compares PRAGMA data_version to detect writes made by other connections outside Storq. Detected external writes mark recovery assumptions inconclusive and block automated recovery steps.

3. Crash Recovery Lifecycle

Crash Recovery Lifecycle (Backup-and-Replay)
Rendering diagram...
Five-stage isolated restore, journal replay, verification, and rollback-safe promotion flow from HOW_IT_WORKS.md.

Storq's crash recovery is backup-and-replay based—it never modifies or patches a damaged source database in place.

text
[1. Create Recovery Point] ──► Verified SQLite online backup + JSON manifest
         │
         ▼
[2. Transaction Journal]   ──► Opt-in append-only JSONL log of managed writes
         │
    (crash / corruption detected)
         │
         ▼
[3. Restore & Replay]      ──► Copy backup to isolated candidate + replay journal
         │
         ▼
[4. Verify Candidate]      ──► Read-only integrity_check, foreign_key_check, no sidecars
         │
         ▼
[5. Explicit Promotion]    ──► Close connection, save rollback, swap candidate in

Step 1: Verified Recovery Points

create_recovery_point() (or create_backup()) uses SQLite's online backup API to take a consistent snapshot (including WAL data), reopens it read-only to run PRAGMA quick_check or PRAGMA integrity_check, computes backup_sha256, and writes a JSON manifest. When a transaction journal is active, the manifest records highest_committed_transaction_sequence as a replay fence.

Step 2: Optional Transaction Journal

Passing transaction_journal="path/to/file.storq-journal" to open_database() enables an opt-in, append-only JSONL journal protected by an exclusive writer lock and a SHA-256 checksum chain:

  1. Before SQLite executes a managed transaction, Storq logs the intent and statements (within a deterministic subset of SELECT, INSERT, UPDATE, and DELETE) and flushes with fsync.
  2. After SQLite finishes, Storq appends the committed or rolled_back decision. If SQLite commits but persisting the decision fails, JournalDecisionError is raised and further writes are blocked.

Step 3: Isolated Restore and Journal Replay

restore_recovery_candidate() and prepare_recovery_candidate():

  1. Verify the selected backup's SHA-256 against its manifest.
  2. Copy the backup to a temporary file, strip any SQLite sidecars (-wal, -shm, -journal), run a read-only check, and move it to a separate candidate path.
  3. If transaction_journal is configured, replay_committed_transactions() replays all committed journal entries after the recovery point's sequence fence (skipping rolled-back transactions). Progress is stored in a __storq_replay_cursor table inside the candidate and updated atomically with each replayed transaction so interrupted replays can resume safely.

Step 4: Candidate Verification

verify_recovered_candidate() opens the candidate read-only and verifies:

  • No -wal, -shm, or -journal sidecars exist beside the candidate.
  • PRAGMA integrity_check (or quick_check) returns ok.
  • PRAGMA foreign_key_check reports zero violations (when enabled).

Results and SHA-256 hashes are written to a .storq-verification.json file.

Step 5: Explicit Promotion and Policies

promote_recovered_candidate() requires the managed connection to be closed. It blocks if verification failed, replay was incomplete, or an independent verification report did not pass. Before replacing the source, it copies the original source (and its sidecars) into a .storq-rollbacks directory and optionally archives the damaged source (preserve_damage=True).

RecoveryPolicy controls automated execution via execute_recovery_policy():

  • observe (default): detect and block writes only; never restores or promotes.
  • prepare_candidate: restores and verifies a candidate without promoting.
  • promote_verified: restores, verifies, and promotes once the connection is closed.
  • fail_closed: marks the connection unhealthy and requires manual operator action.

4. Fault Simulation and Evidence Workspaces

  • create_evidence_workspace() copies a database into a unique subdirectory, hashes it before and after, and records an append-only JSONL action log.
  • run_fault_scenario() runs a workload against an isolated disposable copy inside an evidence workspace—never the original file—and injects seeded, deterministic faults (none, truncate, corrupt, interrupt), then diagnoses the result.
  • run_recovery_certification() runs multiple deterministic fault scenarios across iterations and exports an aggregate report.

5. Experimental Storq Format, Workloads, Reporting, and Benchmarks

  • Experimental Storq format: create_storq_database(), inspect_storq_database(), RecordManager, HashIndex, and NativeWAL operate on .storq files separate from SQLite. Record operations are generation-aware (RecordID) but are not transactional.
  • Workloads: TransactionGenerator and TransactionOracle generate seeded transaction descriptions and track expected outcomes for external test harnesses; they do not execute SQL.
  • Workflows and tests: WorkflowBuilder and TestSuite orchestrate Python steps and built-in checks (currently page_integrity() runs native format inspection; other built-in test factories are capability placeholders).
  • Reports and benchmarks: ReportBuilder, ReportHistory, compare_reports(), Benchmark, BenchmarkHistory, and compare_benchmarks() normalize results, export JSON/CSV/HTML/PDF, measure caller-supplied callbacks, and detect performance regressions.

6. Key Boundaries

  • Backup required: Storq does not salvage raw corrupted pages when no verified recovery point exists.
  • Managed writes only: Direct SQLite connections or external edits bypass Storq's journal and health checks.
  • Separate journal commit: SQLite and the external transaction journal are separate files, not a single atomic storage commit.
  • Simulation scope: Fault scenarios run at the test-harness/storage-copy level; they do not intercept unrelated OS processes or guarantee physical power-loss durability.

Related Documentation