Skip to content

Commit c27af5e

Browse files
committed
Phase 2: SQLite migrations and local Qdrant storage
1 parent 7cee270 commit c27af5e

10 files changed

Lines changed: 1723 additions & 1 deletion

File tree

‎src/rag_platform/db/__init__.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""SQLite storage package (plan v2.4 Phase 2): contained WAL connections and
2+
versioned ``user_version`` migrations. Application startup never imports
3+
initialization here - opening a database is always an explicit decision."""
4+
5+
from __future__ import annotations
6+
7+
from rag_platform.db.migrations import (
8+
MIGRATIONS,
9+
SCHEMA_VERSION,
10+
Migration,
11+
MigrationError,
12+
UnsupportedSchemaVersionError,
13+
initialize,
14+
initialize_database,
15+
user_version,
16+
)
17+
from rag_platform.db.sqlite import (
18+
PathContainmentError,
19+
StorageError,
20+
fts5_available,
21+
open_db,
22+
resolve_under_project,
23+
)
24+
25+
__all__ = [
26+
"MIGRATIONS",
27+
"SCHEMA_VERSION",
28+
"Migration",
29+
"MigrationError",
30+
"PathContainmentError",
31+
"StorageError",
32+
"UnsupportedSchemaVersionError",
33+
"fts5_available",
34+
"initialize",
35+
"initialize_database",
36+
"open_db",
37+
"resolve_under_project",
38+
"user_version",
39+
]

‎src/rag_platform/db/migrations.py‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
"""Versioned schema migrations over ``PRAGMA user_version`` (plan v2.4
2+
Phase 2; section 6 "versioned SQL migrations", section 11 ``schema.sql``).
3+
4+
Mechanism - deterministic, repeatable, auditable:
5+
6+
- The DDL for schema v1 lives in ``schema.sql`` next to this module (the
7+
file name the plan's directory structure specifies) and is registered as
8+
migration v1. Future migrations append to :data:`MIGRATIONS` in version
9+
order; nothing is ever edited in place.
10+
- ``PRAGMA user_version`` is the single version marker. It is written
11+
**inside the same transaction** as its migration's DDL, so version and
12+
schema can never disagree after a failure.
13+
- Each migration executes as one explicit ``BEGIN IMMEDIATE ... COMMIT``
14+
script (autocommit connection, no implicit transactions). Any statement
15+
failure rolls the whole migration back: ``user_version`` is unchanged and
16+
no partial objects remain (:class:`MigrationError`).
17+
- A database whose ``user_version`` exceeds the supported set fails loudly
18+
with :class:`UnsupportedSchemaVersionError` - never a destructive reset,
19+
never a silent downgrade (Phase 2 task sections 3.5/3.6).
20+
- Running :func:`initialize` on an up-to-date database is a no-op
21+
(idempotent); a registry that is not contiguous from v1 is rejected before
22+
a single statement runs (invalid migration state).
23+
- Partial/half-initialized files (schema objects present while
24+
``user_version`` is still 0) fail loudly: baseline DDL uses plain
25+
``CREATE`` statements, so conflicts surface as :class:`MigrationError`
26+
instead of silently adopting unknown state.
27+
28+
Migration SQL is trusted code (reviewed, committed): it must not contain
29+
transaction-control statements - the runner owns BEGIN/COMMIT/ROLLBACK.
30+
"""
31+
32+
from __future__ import annotations
33+
34+
import sqlite3
35+
from collections.abc import Sequence
36+
from dataclasses import dataclass
37+
from pathlib import Path
38+
39+
from rag_platform.db.sqlite import StorageError, open_db
40+
41+
42+
class MigrationError(StorageError):
43+
"""A migration failed (and was rolled back) or the registry is invalid."""
44+
45+
46+
class UnsupportedSchemaVersionError(MigrationError):
47+
"""The database reports a schema version newer than this code supports."""
48+
49+
50+
@dataclass(frozen=True)
51+
class Migration:
52+
"""One schema migration: strictly increasing versions starting at 1."""
53+
54+
version: int
55+
name: str
56+
sql: str
57+
58+
59+
_SCHEMA_SQL_PATH = Path(__file__).with_name("schema.sql")
60+
61+
62+
def _load_baseline_sql() -> str:
63+
sql = _SCHEMA_SQL_PATH.read_text(encoding="utf-8")
64+
if not sql.strip():
65+
raise MigrationError(f"baseline schema file is empty: {_SCHEMA_SQL_PATH}")
66+
return sql
67+
68+
69+
#: The registry this code supports. v1 is the Phase 2 baseline.
70+
MIGRATIONS: tuple[Migration, ...] = (
71+
Migration(1, "baseline_schema", _load_baseline_sql()),
72+
)
73+
74+
#: Version of the newest migration in :data:`MIGRATIONS`.
75+
SCHEMA_VERSION = MIGRATIONS[-1].version
76+
77+
78+
def _validate_registry(registry: Sequence[Migration]) -> None:
79+
if not registry:
80+
raise MigrationError("migration registry is empty")
81+
for expected, migration in enumerate(registry, start=1):
82+
if migration.version != expected:
83+
raise MigrationError(
84+
"migration registry must be contiguous from v1; "
85+
f"expected v{expected}, got v{migration.version} ({migration.name})"
86+
)
87+
if not migration.sql.strip():
88+
raise MigrationError(
89+
f"migration v{migration.version} ({migration.name}) contains no SQL"
90+
)
91+
92+
93+
def user_version(conn: sqlite3.Connection) -> int:
94+
"""Current ``PRAGMA user_version`` of *conn* as ``int``."""
95+
return int(conn.execute("PRAGMA user_version").fetchone()[0])
96+
97+
98+
def initialize(
99+
conn: sqlite3.Connection,
100+
*,
101+
migrations: Sequence[Migration] | None = None,
102+
) -> int:
103+
"""Bring *conn* up to the newest supported schema version; return it.
104+
105+
With *migrations* omitted the shipped :data:`MIGRATIONS` registry is
106+
used; passing an explicit registry is the seam used by the migration
107+
tests to exercise sequencing and failure rollback.
108+
109+
Raises :class:`UnsupportedSchemaVersionError` when the database is newer
110+
than the registry, and :class:`MigrationError` when a step fails or the
111+
registry/state is invalid. Requires a connection with no open
112+
transaction (the runner owns transaction control).
113+
"""
114+
registry = tuple(migrations) if migrations is not None else MIGRATIONS
115+
_validate_registry(registry)
116+
if conn.in_transaction:
117+
raise MigrationError(
118+
"initialize() requires a connection with no open transaction"
119+
)
120+
current = user_version(conn)
121+
supported = registry[-1].version
122+
if current > supported:
123+
raise UnsupportedSchemaVersionError(
124+
f"database schema v{current} is newer than supported v{supported}; "
125+
"refusing to modify it (no downgrade, no reset)"
126+
)
127+
for migration in registry[current:]:
128+
script = (
129+
"BEGIN IMMEDIATE;\n"
130+
f"{migration.sql}\n"
131+
f"PRAGMA user_version = {migration.version};\n"
132+
"COMMIT;"
133+
)
134+
try:
135+
conn.executescript(script)
136+
except sqlite3.Error as exc:
137+
if conn.in_transaction:
138+
conn.execute("ROLLBACK")
139+
raise MigrationError(
140+
f"migration v{migration.version} ({migration.name}) failed and was "
141+
f"rolled back; user_version remains {user_version(conn)}"
142+
) from exc
143+
return user_version(conn)
144+
145+
146+
def initialize_database(
147+
path: str | Path,
148+
*,
149+
migrations: Sequence[Migration] | None = None,
150+
) -> sqlite3.Connection:
151+
"""Open *path* (contained, WAL pragmas) and migrate it; return the open connection.
152+
153+
The caller owns the connection and must close it. On migration failure
154+
the connection is closed before the error propagates - a failed
155+
initialization leaves no open handle and no partial schema state.
156+
"""
157+
conn = open_db(path)
158+
try:
159+
initialize(conn, migrations=migrations)
160+
except BaseException: # includes KeyboardInterrupt - never leak the handle
161+
conn.close()
162+
raise
163+
return conn

‎src/rag_platform/db/schema.sql‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
-- Phase 2 baseline schema - migration v1 (plan v2.4 sections 15 Phase 2,
2+
-- 6 storage choices, 4.2 trace design; D5: SQLite WAL + FTS5 approved).
3+
--
4+
-- Scope discipline: ONLY what the plan assigns to Phase 2 - the FTS5 keyword
5+
-- index structure and the trace tables. Document/chunk metadata, tenancy/ACL,
6+
-- audit, and cache tables belong to Phases 4 and M2/M4 and are deliberately
7+
-- NOT created here; they arrive as future versioned migrations.
8+
9+
-- Keyword (BM25) index target - plan section 6 "Keyword store: SQLite FTS5".
10+
-- Deliberately a standalone (non-external-content) FTS5 table: the chunk
11+
-- metadata table arrives with Phase 4 ingestion as its own migration, and a
12+
-- standalone index can be populated/rebuilt then without a content-table
13+
-- dependency. Keys are stored UNINDEXED so RRF fusion (Phase 5) can join on
14+
-- chunk_id/doc_id without tokenizing identifiers.
15+
CREATE VIRTUAL TABLE chunk_fts USING fts5(
16+
content,
17+
chunk_id UNINDEXED,
18+
doc_id UNINDEXED,
19+
tokenize = 'unicode61'
20+
);
21+
22+
-- One row per /query request - plan section 4.2 design point 1:
23+
-- request ID, timestamp, tenant (ID only), served_by, degradation reason,
24+
-- cache status. No content, no secrets (I6); tenant_id is populated once
25+
-- M2 server-derived identity exists (NULL before that - auth does not
26+
-- exist yet in this phase).
27+
CREATE TABLE traces (
28+
id INTEGER PRIMARY KEY,
29+
request_id TEXT NOT NULL UNIQUE,
30+
created_at TEXT NOT NULL,
31+
tenant_id TEXT,
32+
served_by TEXT,
33+
degradation_reason TEXT,
34+
cache_status TEXT
35+
);
36+
37+
-- One row per pipeline stage per trace - plan sections 4.2/5: the nine
38+
-- normative stage names (CHECK-enforced), start/end timing, outcome, bounded
39+
-- input/output digests, and stage scores. 'outcome' has no CHECK here: the
40+
-- Phase 8 trace recorder defines its enum; inventing values now would
41+
-- pre-empt the recorder. excerpt is capped at the I7/section 10.1 hard cap
42+
-- of 200 chars at the storage layer. UNIQUE(trace_id, stage) makes the
43+
-- plan's "one nine-stage trace per request" structurally enforceable.
44+
CREATE TABLE trace_stages (
45+
id INTEGER PRIMARY KEY,
46+
trace_id INTEGER NOT NULL REFERENCES traces(id) ON DELETE CASCADE,
47+
stage TEXT NOT NULL CHECK (stage IN (
48+
'authn', 'authz_filter', 'cache_lookup', 'retrieval',
49+
'post_verify', 'context_build', 'generation', 'ledger', 'response'
50+
)),
51+
outcome TEXT NOT NULL,
52+
timing_ms REAL CHECK (timing_ms IS NULL OR timing_ms >= 0),
53+
inputs_digest TEXT,
54+
outputs_digest TEXT,
55+
scores_json TEXT,
56+
excerpt TEXT CHECK (excerpt IS NULL OR length(excerpt) <= 200),
57+
UNIQUE (trace_id, stage)
58+
);
59+
60+
-- The authorization decision set for a trace - plan section 4.2:
61+
-- allowed/denied doc IDs, IDs only (I10: no denied-content excerpts, ever).
62+
CREATE TABLE trace_authz (
63+
id INTEGER PRIMARY KEY,
64+
trace_id INTEGER NOT NULL REFERENCES traces(id) ON DELETE CASCADE,
65+
doc_id TEXT NOT NULL,
66+
decision TEXT NOT NULL CHECK (decision IN ('allowed', 'denied')),
67+
UNIQUE (trace_id, doc_id)
68+
);

‎src/rag_platform/db/sqlite.py‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
"""SQLite connection layer (plan v2.4 Phase 2; D5, I9, Z9 path policy).
2+
3+
Phase 2 scope - connection configuration and path containment only:
4+
5+
- All database files, including SQLite ``-wal``/``-shm`` sidecars, live under
6+
the project root on D: (plan section 10.2/11: ``data\\sqlite\\``). Relative
7+
paths resolve against PROJECT_ROOT, never the process working directory.
8+
- Connections are configured deliberately: WAL journal mode (D5: SQLite
9+
WAL + FTS5 approved), enforced foreign keys, ``synchronous=NORMAL`` (the
10+
standard WAL pairing), and ``isolation_level=None`` so there are no
11+
implicit BEGINs - transactions are opened deliberately by callers and by
12+
the migration runner (auditable transaction behaviour).
13+
- FTS5 availability is detected against the existing stdlib SQLite runtime
14+
(plan section 12, FTS5 row): a plain in-memory probe, no extension
15+
installs, no network, no project code beyond this check.
16+
17+
Opening or initializing a database is always an explicit caller decision:
18+
this module is never invoked by application startup or ``/health`` (Phase 2
19+
task section 6 - initialization stays separate from startup).
20+
21+
Path containment (Z9) is mirrored from :mod:`rag_platform.config`: a path
22+
that resolves outside PROJECT_ROOT is rejected before any directory or file
23+
is created.
24+
"""
25+
26+
from __future__ import annotations
27+
28+
import sqlite3
29+
from pathlib import Path
30+
31+
from rag_platform.config import PROJECT_ROOT
32+
33+
34+
class StorageError(Exception):
35+
"""Base error for Phase 2 storage operations."""
36+
37+
38+
class PathContainmentError(StorageError):
39+
"""A storage path resolved outside the project root (Z9)."""
40+
41+
42+
def resolve_under_project(path: str | Path) -> Path:
43+
"""Resolve *path* against PROJECT_ROOT and require strict containment.
44+
45+
Relative inputs are anchored at PROJECT_ROOT (never the cwd). The project
46+
root itself is not an acceptable storage location - only paths strictly
47+
below it. Validation happens before any mkdir/connect, so a rejected path
48+
leaves no artifacts behind.
49+
"""
50+
candidate = Path(path)
51+
if not candidate.is_absolute():
52+
candidate = PROJECT_ROOT / candidate
53+
resolved = candidate.resolve()
54+
if not resolved.is_relative_to(PROJECT_ROOT) or resolved == PROJECT_ROOT:
55+
raise PathContainmentError(
56+
f"storage path must resolve strictly under {PROJECT_ROOT}; got {resolved}"
57+
)
58+
return resolved
59+
60+
61+
def open_db(path: str | Path, *, timeout: float = 5.0) -> sqlite3.Connection:
62+
"""Open a contained SQLite connection with the Phase 2 pragmas applied.
63+
64+
Creates the parent directory (which must itself be inside the project
65+
root). Failures raise :class:`StorageError` (or ``sqlite3.Error`` from
66+
the driver) with no half-open connection returned: pragma failures close
67+
the connection before raising so no leaked handle survives an error.
68+
"""
69+
resolved = resolve_under_project(path)
70+
if resolved.is_dir():
71+
raise StorageError(f"database path is a directory: {resolved}")
72+
resolved.parent.mkdir(parents=True, exist_ok=True)
73+
try:
74+
conn = sqlite3.connect(str(resolved), timeout=timeout, isolation_level=None)
75+
except sqlite3.Error as exc: # e.g. unopenable path - fail loud, no retry
76+
raise StorageError(f"failed to open database at {resolved}: {exc}") from exc
77+
conn.row_factory = sqlite3.Row
78+
try:
79+
journal = conn.execute("PRAGMA journal_mode=WAL").fetchone()[0]
80+
if str(journal).lower() != "wal":
81+
raise StorageError(
82+
f"WAL journal mode unavailable at {resolved} (got {journal!r})"
83+
)
84+
# The setters foreign_keys/synchronous return no rows - set first,
85+
# then read back via the query form to verify the setting took.
86+
conn.execute("PRAGMA foreign_keys=ON")
87+
if int(conn.execute("PRAGMA foreign_keys").fetchone()[0]) != 1:
88+
raise StorageError("foreign key enforcement could not be enabled")
89+
conn.execute("PRAGMA synchronous=NORMAL")
90+
synchronous = int(conn.execute("PRAGMA synchronous").fetchone()[0])
91+
if synchronous != 1: # 1 == NORMAL
92+
raise StorageError(f"expected synchronous=NORMAL, got {synchronous!r}")
93+
except BaseException:
94+
conn.close() # never leak a handle from a failed initialization
95+
raise
96+
return conn
97+
98+
99+
def fts5_available() -> bool:
100+
"""True when the runtime SQLite build can create FTS5 virtual tables.
101+
102+
Mirrors the plan section 12 Phase 0 check, against the same stdlib
103+
``sqlite3`` the application uses. No project database is touched.
104+
"""
105+
probe = sqlite3.connect(":memory:")
106+
try:
107+
probe.execute("CREATE VIRTUAL TABLE probe_fts USING fts5(x)")
108+
return True
109+
except sqlite3.OperationalError:
110+
return False
111+
finally:
112+
probe.close()

0 commit comments

Comments
 (0)