Skip to Content
Recodocs

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.

8 min read

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.

NameKindWhat it does
DatabaseProtocolSynchronous connection scope with execute, fetch_all, fetch_one, and unwrap.
AsyncDatabaseProtocolAsync counterpart with the same query intent.
DBAPIClassShared connect, transaction, and fetch mechanics over an injected native connector.
OutsideTransactionErrorExceptionRaised when a data-changing statement runs outside transaction() on drivers that would roll it back silently.
require_queryFunctionRejects stacked, DML, or DDL statements; permits one read-only query.
ReadOnlyQueryErrorExceptionRefusal with a reason suitable for product error mapping.
CacheProtocolget, put, delete, and unwrap for exact scoped JSON caches.
SQLiteDatabaseClassDatabase implementation over stdlib sqlite3.
connect, open_connectionFunctionScoped or caller-owned SQLite connections with busy handling.
bootstrap, apply_migrations, provisionFunctionSchema bootstrap, versioned migration steps, snapshot copy.
enable_wal, execute_scriptFunctionWAL pragma with busy retry; multi-statement scripts.
row_connectionContext managerShort-lived connection with sqlite3.Row rows, commit on success.
immediate_transactionContext managerBEGIN IMMEDIATE on an autocommit connection; rolls back on any error.
append_digest_rowFunctionAppend-only ledger insert with digest deduplication.
create_fts, search, quote_query, rebuild_ftsFunctionFTS5 external-content index, BM25 search, safe quoting, index recovery.
PostgresDatabaseClassPsycopg 3 adapter with explicit DSN.
AsyncPostgresDatabaseClassAsync Psycopg 3 adapter on AsyncDatabase.
Psycopg2DatabaseClassLegacy Psycopg 2 adapter.
PostgresSearch, NamedQueryClassRegistered named queries and bounded reads with sanitized errors.
OwnedCluster, free_loopback_portClass, functionTemporary local cluster with explicit binaries; loopback port selection.
DuckDBDatabase, open_connectionClass, functionDuckDB on Database; native connection for DataFrame registration.
SnowflakeDatabase, open_connectionClass, functionSnowflake session from explicit args; native connector escape hatch.
SQLAlchemyDatabase, session_scopeClass, functionEngine-bound SQL adapter; ORM session commit/rollback scope.
query_dialectFunctionMaps SQLAlchemy dialect names to SQLGlot readers for the read-only guard.
AsyncSQLAlchemyDatabase, session_scopeClass, functionAsync engine adapter mirroring sync query contract.
sqlite_engine, async_sqlite_engine, sqlite_urlFunctionsqlite_engine and async_sqlite_engine create SQLite engines with SQLAlchemy-owned BEGIN and per-connection pragmas; sqlite_url only renders their URL.
SQLiteSessionsClassCaller-owned engine with deferred reads and immediate-write sessions.
portable_bigint_pk, UTCDateTime, GUID, PortableJSONFunction, typesportable_bigint_pk() returns a BIGINT that is INTEGER on SQLite when called; UTCDateTime, GUID, and PortableJSON are built on first attribute access.
JsonCacheClassDisk cache of exact JSON keyed by scope, optional partition label, and request fingerprint.
RedisCacheClassRedis-backed cache with the same key semantics as JsonCache.
TransactionalOutbox, TransactionalInboxClassSQLite outbox/inbox joined to the owner’s open transaction.
publish_batchAsync functionShared at-least-once publish loop with attempt, emit, and acknowledge callbacks.
DeliveryRetryPolicy, DrainReceipt, RecoveryReceipt, PublishReceiptTypesDeliveryRetryPolicy holds per-message retry bounds; DrainReceipt, RecoveryReceipt, and PublishReceipt are the drain, recovery, and publish receipts.
QueryPlan, PlanNode, PlanFindingDataclassFlattened plan tree and typed findings.
explain_sqlite, explain_postgres, parse_postgres_planFunctionCapture plans from SQLite EXPLAIN QUERY PLAN or PostgreSQL JSON explain.
classify, advise_indexes, compare, build_receiptFunctionTurn plans into findings, suggested index DDL text, comparisons, and receipts.
RegressionGuard, GuardResultClassRegressionGuard 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, digestFunctionRow counts for guard input, timed runs, receipt digests.
dialect_for, compile_for, portability_report, ddl_forFunctiondialect_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_lakebaseFunctionVerified PostgreSQL-to-SQLite copy; snapshot promotion path.
encode_vector, decode_vectorFunctionLittle-endian float32 vector BLOB for SQLite.
CsvContract, csv_export, csv_readbackTypes, functionDeclared CSV shape, export to ObjectStore, verified readback.
configuration, upgrade_sqlite, run_onlineFunctionAlembic 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 packageUsed for
recohut_kit.jsonJsonCache 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.filesatomic_private_json writes in JsonCache.
recohut_kit.production.retryFailure and RetryPolicy types for outbox delivery retry policy.
recohut_kit.objects.contractsObjectStore for CSV export and readback.
recohut_kit.operation_receiptsoperation receipt wrapper around CSV readback.
recohut_kit._lazy_buildresolve_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_query rejects 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. OutsideTransactionError surfaces implicit write transactions that would be discarded when a scoped connection closes. Leading WITH statements whose main keyword is INSERT, UPDATE, DELETE, or REPLACE are refused outside a transaction because legacy sqlite3 does not mark them with in_transaction.
  • Busy timeout. sqlite.py connection helpers use RECOHUT_SQLITE_BUSY_SECONDS (default 30, floor 5); row_connection defaults to 0.5 seconds, and SQLAlchemy SQLite engines use busy_timeout_ms (default 5000).
  • Outbox. One publisher per queue is the supported deployment; require_transaction insists the outbox join the same file’s open transaction. publish_batch treats sink failures as sink_unavailable and can raise DeliveryInterrupted when simulating crash-after-emit.
  • Caches. JsonCache and RedisCache require a nonempty scope; optional version partitions keys rather than invalidating entries. Corrupt cache files raise ValueError; misses return None, which cannot be stored as a cached value.
  • FTS5. Triggers do not see rows removed by REPLACE unless PRAGMA recursive_triggers = ON; stale tokens may corrupt the index until rebuild_fts runs. 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. RegressionGuard fails closed on missing plans, empty plans, unexpected names, unknown relation row counts, and scans above max_scan_rows.
  • Dialect portability. A plain SQL string is wrapped in sqlalchemy.text and marked translated=False; literal binds stay disabled, and the SQL text is not rewritten for another dialect.
  • Transfer. copy_tables reads PostgreSQL in one REPEATABLE READ, READ ONLY transaction; the caller supplies both engines, the SQLite schema, and SQLAlchemy metadata. copy_sqlite_to_lakebase reads a SQLite snapshot and writes PostgreSQL.
  • Postgres search. NamedQuery is trusted configuration; identifiers belong in reviewed SQL, not interpolated parameters.
  • Alembic. Stock fileConfig in env.py can disable existing loggers when Alembic runs in-process; the module docstring warns to skip or reconfigure logging when passing connections through attributes.
  • Local cluster. OwnedCluster needs explicit initdb and pg_ctl paths; missing binaries raise ClusterUnavailable for 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