Explicit persistence primitives and database adapters
Connection scopes, read-only query guards, SQLite lifecycle, transactional outbox, exact JSON caches, dialect portability, and plan analysis without implicit schemas or environment discovery.
The storage layer of recohut-kit is plain code around explicit connections, caller-owned schemas, and typed receipts. It opens SQLite, PostgreSQL, DuckDB, and Snowflake with DSNs or arguments you supply. It does not invent application tables, discover credentials from the environment, or ship a universal repository. Drivers keep native SQL, placeholders, and isolation rules. The shared guard permits one query and rejects stacked statements and side-effecting clauses before plan analysis or guarded reads run; it does not block server-side functions with external effects.
Import submodules directly. The package root recohut_kit.storage documents the layer’s role and exports no names. Persistence here is adapters, contracts, and operational helpers (outbox, FTS, CSV export, table transfer), not ORM models or migration authority beyond explicit Alembic wiring you own.
Purpose
A storage adapter connects the application to a database, but the application still owns what its records mean. Explicit connections and schemas make that boundary visible.
What it owns. Lifetime and transaction boundaries for DB-API style access (recohut_kit.storage.contracts, recohut_kit.storage.dbapi). Stdlib SQLite connect, bootstrap, migrations, provisioning, and WAL setup (recohut_kit.storage.sqlite). SQLAlchemy engine helpers for SQLite, sync and async session scopes, and portable column types (recohut_kit.storage.sqlalchemy, recohut_kit.storage.sqlalchemy_sqlite, recohut_kit.storage.sqlalchemy_async, recohut_kit.storage.sqlalchemy_types). Driver-specific adapters: PostgreSQL (sync, async, legacy psycopg2), DuckDB, Snowflake (recohut_kit.storage.postgres, recohut_kit.storage.postgres_async, recohut_kit.storage.psycopg2, recohut_kit.storage.duckdb, recohut_kit.storage.snowflake). Bounded, named PostgreSQL reads (recohut_kit.storage.postgres_search). Local disposable PostgreSQL clusters for tests (recohut_kit.storage.postgres_local). Exact JSON caches on disk and Redis (recohut_kit.storage.cache, recohut_kit.storage.redis, recohut_kit.storage.cache_contract). Transactional SQLite outbox and inbox with shared publish loop (recohut_kit.storage.outbox). Query plan explanation, classification, index advice text, before/after receipts, and regression guards (recohut_kit.storage.query_plans). SQL portability compilation across SQLite, PostgreSQL, and MySQL (recohut_kit.storage.dialects). One-off verified PostgreSQL-to-SQLite copy and vector BLOB encoding (recohut_kit.storage.transfer). FTS5 keyword search, digest ledgers, small row helpers, and immediate transactions for autocommit SQLite (recohut_kit.storage.sqlite_fts, recohut_kit.storage.sqlite_ledger, recohut_kit.storage.sqlite_rows, recohut_kit.storage.sqlite_tx). Verified CSV export through an object store (recohut_kit.storage.csv_export). Alembic configuration helpers pin migration paths and URLs (recohut_kit.storage.alembic).
What it deliberately does not own. Application schemas, revision history, and migration content stay in your repositories. recohut_kit.storage.dialects compiles statements; it does not translate arbitrary raw SQL text across dialects. recohut_kit.storage.query_plans advises index DDL as text and never creates indexes. recohut_kit.storage.readonly parses queries with SQLGlot; it is not a stored-function sandbox and does not replace database grants or row-level security. recohut_kit.storage.postgres_search runs reviewed, named queries; it does not accept model-supplied SQL. Caches fingerprint requests you define; the library does not decide replay eligibility or rewrite tool identifiers. Outbox delivery is historical admission, not fresh authorization. Nothing in this layer is a model call.
Public API
The table lists main public types and entry points per module. Private helpers and module internals are omitted.
| Name | Kind | What it does |
|---|---|---|
Database | Protocol | Synchronous connection scope with execute, fetch_all, fetch_one, and unwrap. |
AsyncDatabase | Protocol | Async counterpart with the same query intent. |
DBAPI | Class | Shared connect, transaction, and fetch mechanics over an injected native connector. |
OutsideTransactionError | Exception | Raised when a data-changing statement runs outside transaction() on drivers that would roll it back silently. |
require_query | Function | Rejects stacked, DML, or DDL statements; permits one read-only query. |
ReadOnlyQueryError | Exception | Refusal with a reason suitable for product error mapping. |
Cache | Protocol | get, put, delete, and unwrap for exact scoped JSON caches. |
SQLiteDatabase | Class | Database implementation over stdlib sqlite3. |
connect, open_connection | Function | Scoped or caller-owned SQLite connections with busy handling. |
bootstrap, apply_migrations, provision | Function | Schema bootstrap, versioned migration steps, snapshot copy. |
enable_wal, execute_script | Function | WAL pragma with busy retry; multi-statement scripts. |
row_connection | Context manager | Short-lived connection with sqlite3.Row rows, commit on success. |
immediate_transaction | Context manager | BEGIN IMMEDIATE on an autocommit connection; rolls back on any error. |
append_digest_row | Function | Append-only ledger insert with digest deduplication. |
create_fts, search, quote_query, rebuild_fts | Function | FTS5 external-content index, BM25 search, safe quoting, index recovery. |
PostgresDatabase | Class | Psycopg 3 adapter with explicit DSN. |
AsyncPostgresDatabase | Class | Async Psycopg 3 adapter on AsyncDatabase. |
Psycopg2Database | Class | Legacy Psycopg 2 adapter. |
PostgresSearch, NamedQuery | Class | Registered named queries and bounded reads with sanitized errors. |
OwnedCluster, free_loopback_port | Class, function | Temporary local cluster with explicit binaries; loopback port selection. |
DuckDBDatabase, open_connection | Class, function | DuckDB on Database; native connection for DataFrame registration. |
SnowflakeDatabase, open_connection | Class, function | Snowflake session from explicit args; native connector escape hatch. |
SQLAlchemyDatabase, session_scope | Class, function | Engine-bound SQL adapter; ORM session commit/rollback scope. |
query_dialect | Function | Maps SQLAlchemy dialect names to SQLGlot readers for the read-only guard. |
AsyncSQLAlchemyDatabase, session_scope | Class, function | Async engine adapter mirroring sync query contract. |
sqlite_engine, async_sqlite_engine, sqlite_url | Function | sqlite_engine and async_sqlite_engine create SQLite engines with SQLAlchemy-owned BEGIN and per-connection pragmas; sqlite_url only renders their URL. |
SQLiteSessions | Class | Caller-owned engine with deferred reads and immediate-write sessions. |
portable_bigint_pk, UTCDateTime, GUID, PortableJSON | Function, types | portable_bigint_pk() returns a BIGINT that is INTEGER on SQLite when called; UTCDateTime, GUID, and PortableJSON are built on first attribute access. |
JsonCache | Class | Disk cache of exact JSON keyed by scope, optional partition label, and request fingerprint. |
RedisCache | Class | Redis-backed cache with the same key semantics as JsonCache. |
TransactionalOutbox, TransactionalInbox | Class | SQLite outbox/inbox joined to the owner’s open transaction. |
publish_batch | Async function | Shared at-least-once publish loop with attempt, emit, and acknowledge callbacks. |
DeliveryRetryPolicy, DrainReceipt, RecoveryReceipt, PublishReceipt | Types | DeliveryRetryPolicy holds per-message retry bounds; DrainReceipt, RecoveryReceipt, and PublishReceipt are the drain, recovery, and publish receipts. |
QueryPlan, PlanNode, PlanFinding | Dataclass | Flattened plan tree and typed findings. |
explain_sqlite, explain_postgres, parse_postgres_plan | Function | Capture plans from SQLite EXPLAIN QUERY PLAN or PostgreSQL JSON explain. |
classify, advise_indexes, compare, build_receipt | Function | Turn plans into findings, suggested index DDL text, comparisons, and receipts. |
RegressionGuard, GuardResult | Class | RegressionGuard fails closed on large full scans for a named workload; GuardResult records whether that check passed and lists its violations. |
sqlite_table_rows, time_query, digest | Function | Row counts for guard input, timed runs, receipt digests. |
dialect_for, compile_for, portability_report, ddl_for | Function | dialect_for returns a driverless dialect; compile_for compiles one statement; portability_report builds the per-dialect report; ddl_for renders index DDL from IndexAdvice. |
copy_tables, copy_sqlite_to_lakebase | Function | Verified PostgreSQL-to-SQLite copy; snapshot promotion path. |
encode_vector, decode_vector | Function | Little-endian float32 vector BLOB for SQLite. |
CsvContract, csv_export, csv_readback | Types, function | Declared CSV shape, export to ObjectStore, verified readback. |
configuration, upgrade_sqlite, run_online | Function | Alembic config pinning, SQLite upgrade, online migration hook. |
How it composes
Storage modules mostly import the kit packages their docstrings name. postgres_search also imports JsonValue from recohut_kit.json without naming that package.
| Other kit package | Used for |
|---|---|
recohut_kit.json | JsonCache uses JsonValue and fingerprint; Redis adds canonical_json; the outbox uses JsonValue, as_json_value, and canonical_json; the ledger uses canonical_json and fingerprint; PostgreSQL reads use JsonValue. |
recohut_kit.files | atomic_private_json writes in JsonCache. |
recohut_kit.production.retry | Failure and RetryPolicy types for outbox delivery retry policy. |
recohut_kit.objects.contracts | ObjectStore for CSV export and readback. |
recohut_kit.operation_receipts | operation receipt wrapper around CSV readback. |
recohut_kit._lazy_build | resolve_lazy for deferred SQLAlchemy type construction. |
Several storage modules call other storage modules (for example query_plans uses readonly.require_query, outbox uses sqlite.bootstrap and sqlite.connect, and dialects references query_plans.IndexAdvice). RedisCache uses a JsonCache only to compute the same scope, version, and request key, and implements get, put, and delete on the injected client. SQLGlot is imported for read-only parsing and plans, and also by sqlalchemy.query_dialect, whose module docstring does not name SQLGlot. SQLAlchemy and Alembic support engines and migrations. sqlite3 is a normal import; psycopg, duckdb, and snowflake are imported when those adapters open a connection; the Redis client is passed in by the caller.
Minimal usage
Install the sqlalchemy extra with uv pip install '.[sqlalchemy]' to get SQLGlot, which validates the query before SQLite explains it. The example creates an in-memory table, explains a query before and after adding the suggested index, and checks the resulting plan.
import sqlite3
from recohut_kit.storage import query_plans as qp
STATUS_SQL = "SELECT id FROM tickets WHERE tenant_id = ? AND status = ? ORDER BY created_at"
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE tickets (id TEXT PRIMARY KEY, tenant_id, status, created_at)")
rows = qp.sqlite_table_rows(connection, ["tickets"])
params = ("tenant1", "open")
before = qp.explain_sqlite(connection, STATUS_SQL, params)
(advice,) = qp.advise_indexes(before, STATUS_SQL, table_rows=rows)
connection.execute(advice.ddl)
after = qp.explain_sqlite(connection, STATUS_SQL, params)
receipt = qp.build_receipt(before, after, params=params, change=advice.ddl, table_rows=rows)
guard = qp.RegressionGuard({"status": (STATUS_SQL, params)}, rows, max_scan_rows=100)
guard.check(lambda sql, values: qp.explain_sqlite(connection, sql, values))Non-query statements such as DELETE are rejected when explaining plans because explain_sqlite calls require_query first.
Limits and gotchas
- Package root. Import concrete modules; the root documents that storage uses no other kit imports at the package marker and is not itself re-exported.
- Read-only guard.
require_queryrejects multiple statements and side-effecting clauses. Server-side functions with external effects still need database roles and native read-only modes where available. - SQLite writes.
OutsideTransactionErrorsurfaces implicit write transactions that would be discarded when a scoped connection closes. LeadingWITHstatements whose main keyword is INSERT, UPDATE, DELETE, or REPLACE are refused outside a transaction because legacy sqlite3 does not mark them within_transaction. - Busy timeout.
sqlite.pyconnection helpers useRECOHUT_SQLITE_BUSY_SECONDS(default 30, floor 5);row_connectiondefaults to 0.5 seconds, and SQLAlchemy SQLite engines usebusy_timeout_ms(default 5000). - Outbox. One publisher per queue is the supported deployment;
require_transactioninsists the outbox join the same file’s open transaction.publish_batchtreats sink failures assink_unavailableand can raiseDeliveryInterruptedwhen simulating crash-after-emit. - Caches.
JsonCacheandRedisCacherequire a nonempty scope; optionalversionpartitions keys rather than invalidating entries. Corrupt cache files raiseValueError; misses returnNone, which cannot be stored as a cached value. - FTS5. Triggers do not see rows removed by
REPLACEunlessPRAGMA recursive_triggers = ON; stale tokens may corrupt the index untilrebuild_ftsruns. FTS5 must exist in the SQLite build. - Query plans. Requires the SQLAlchemy extra (SQLGlot); PostgreSQL live explain needs the postgres extra. Index advice is text only.
RegressionGuardfails closed on missing plans, empty plans, unexpected names, unknown relation row counts, and scans abovemax_scan_rows. - Dialect portability. A plain SQL string is wrapped in
sqlalchemy.textand markedtranslated=False; literal binds stay disabled, and the SQL text is not rewritten for another dialect. - Transfer.
copy_tablesreads PostgreSQL in one REPEATABLE READ, READ ONLY transaction; the caller supplies both engines, the SQLite schema, and SQLAlchemy metadata.copy_sqlite_to_lakebasereads a SQLite snapshot and writes PostgreSQL. - Postgres search.
NamedQueryis trusted configuration; identifiers belong in reviewed SQL, not interpolated parameters. - Alembic. Stock
fileConfiginenv.pycan disable existing loggers when Alembic runs in-process; the module docstring warns to skip or reconfigure logging when passing connections through attributes. - Local cluster.
OwnedClusterneeds explicitinitdbandpg_ctlpaths; missing binaries raiseClusterUnavailablefor caller fallback.
Verification
The example checks a local SQLite query plan and its recorded index change. See Verify the examples.
How is this page?
Last updated on