Skip to main content

khive_db/
migrations.rs

1//! Schema migration system for the SQLite storage layer.
2//!
3//! Two APIs coexist:
4//! - **Legacy per-service migrations** (`ServiceSchemaPlan` / `apply_schema_plan`):
5//!   used by pack-scoped schemas.
6//! - **Versioned migrations** (`MIGRATIONS` / `run_migrations`): the forward-only
7//!   migration pipeline for the core tables.
8//!
9//! Raw migration entry points require a connection opened by rusqlite;
10//! externally owned handles wrapped with `Connection::from_handle` are not
11//! supported. They reject inherited transactions. If rollback and close cannot
12//! establish an outcome, the original connection is retired before its volume
13//! lease is released and the caller receives `WriterSettlementUnknown`.
14
15use khive_storage::blob::ContentRef;
16use rusqlite::{Connection, OptionalExtension};
17use std::path::{Path, PathBuf};
18
19use crate::error::SqliteError;
20use crate::pool::WriteAdmission;
21use crate::stores::blob::{try_acquire_database_gc_owner_for_path, DatabaseGcOwnerGuard};
22
23#[path = "raw_migration_settlement.rs"]
24mod raw_migration_settlement;
25use raw_migration_settlement::{RawMigrationTransactions, RawMigrationWriteUnit};
26
27/// The write side of a migration run.
28///
29/// ADR-154 section 4 admits each migration transaction on its own: the volume
30/// lease is taken before the transaction begins and released once it has
31/// settled, so a multi-version upgrade never holds the volume for the whole
32/// run. Implementations own that per-call lease and settlement.
33pub(crate) trait MigrationTransactions {
34    /// Run one write transaction, or one autocommit write, under a fresh
35    /// admission.
36    fn admitted<T>(
37        &mut self,
38        operation: impl FnOnce(&mut Connection) -> Result<T, SqliteError>,
39    ) -> Result<T, SqliteError>;
40}
41
42/// Captured disk-guard settings and shared volume-lock directory for a SQLite
43/// writer.
44///
45/// Construction validates configuration without reading or writing a database.
46/// Cooperating callers must choose the same absolute volume-lock directory.
47#[derive(Clone, Debug)]
48pub struct MigrationWritePolicy {
49    disk_guard: crate::EffectiveDiskGuardConfig,
50    volume_lock_dir: PathBuf,
51}
52
53impl MigrationWritePolicy {
54    pub fn new(
55        disk_guard: crate::EffectiveDiskGuardConfig,
56        volume_lock_dir: impl Into<PathBuf>,
57    ) -> Result<Self, SqliteError> {
58        disk_guard.validate()?;
59        let volume_lock_dir = volume_lock_dir.into();
60        if !volume_lock_dir.is_absolute() {
61            return Err(SqliteError::InvalidConfig(
62                "migration volume-lock directory must be absolute".to_string(),
63            ));
64        }
65        Ok(Self {
66            disk_guard,
67            volume_lock_dir,
68        })
69    }
70
71    /// Resolve both settings from the process environment. The lock directory
72    /// follows [`crate::default_volume_lock_dir`], the same per-user default the
73    /// public SQLite constructors use.
74    pub fn from_environment() -> Result<Self, SqliteError> {
75        let disk_guard = crate::DiskGuardEnvironment::capture().resolve(None, None)?;
76        Self::new(disk_guard, crate::default_volume_lock_dir()?)
77    }
78
79    pub fn disk_guard_config(&self) -> crate::EffectiveDiskGuardConfig {
80        self.disk_guard
81    }
82
83    pub fn volume_lock_dir(&self) -> &Path {
84        &self.volume_lock_dir
85    }
86}
87
88#[path = "session_identity_migration.rs"]
89mod session_identity_migration;
90
91mod memory_visibility;
92
93// =============================================================================
94// Legacy per-service migration API (preserved for backward compatibility)
95// =============================================================================
96
97/// A single legacy migration step within a `ServiceSchemaPlan`.
98pub struct Migration {
99    /// Unique identifier for this migration.
100    pub id: &'static str,
101    /// SQL to apply (forward direction).
102    pub up_sql: &'static str,
103    /// SQL to revert (optional).
104    pub down_sql: Option<&'static str>,
105    /// Optional read-only predicate: returns true if migration was already
106    /// applied through a mechanism other than the migration tracker. It runs
107    /// while this connection holds the SQLite write lock.
108    pub is_already_applied: Option<fn(&Connection) -> bool>,
109}
110
111/// A pack-scoped schema plan containing migrations for SQLite and Postgres.
112pub struct ServiceSchemaPlan {
113    /// Service name used as a key in the `_schema_versions` tracking table.
114    pub service: &'static str,
115    /// SQLite-specific migration steps, applied in order.
116    pub sqlite: &'static [Migration],
117    /// Postgres-specific migration steps (reserved for future use).
118    pub postgres: &'static [Migration],
119}
120
121const SCHEMA_VERSION_TABLE: &str = include_str!("../sql/schema-version-table.sql");
122
123/// Apply a pack-scoped schema plan, tracking each migration in `_schema_versions`.
124/// A mutable connection lets the wrapper retire an unsettled original handle.
125pub fn apply_schema_plan(
126    conn: &mut Connection,
127    plan: &ServiceSchemaPlan,
128) -> Result<(), SqliteError> {
129    let admission = WriteAdmission::for_canonical_path(canonical_connection_database_path(conn)?)?;
130    apply_schema_plan_with_admission(
131        &mut RawMigrationTransactions::new(conn, &admission),
132        plan,
133        &admission,
134    )
135}
136
137/// Apply a raw connection's schema plan with a captured policy and lock path.
138pub fn apply_schema_plan_with_policy(
139    conn: &mut Connection,
140    plan: &ServiceSchemaPlan,
141    policy: &MigrationWritePolicy,
142) -> Result<(), SqliteError> {
143    let admission =
144        WriteAdmission::for_migration_policy(canonical_connection_database_path(conn)?, policy)?;
145    apply_schema_plan_with_admission(
146        &mut RawMigrationTransactions::new(conn, &admission),
147        plan,
148        &admission,
149    )
150}
151
152/// Apply a service schema plan. The tracking-table bootstrap and each
153/// migration are separate admitted write units (ADR-154 section 4).
154pub(crate) fn apply_schema_plan_with_admission(
155    writes: &mut impl MigrationTransactions,
156    plan: &ServiceSchemaPlan,
157    admission: &WriteAdmission,
158) -> Result<(), SqliteError> {
159    writes.admitted(|conn| {
160        admission.check()?;
161        conn.execute_batch(SCHEMA_VERSION_TABLE)?;
162        require_autocommit(conn, "schema-version bootstrap")
163    })?;
164
165    for migration in plan.sqlite {
166        writes.admitted(|conn| apply_service_migration(conn, plan, migration, admission))?;
167    }
168
169    Ok(())
170}
171
172/// Apply one service migration in its own IMMEDIATE transaction unless its
173/// predicate or the ledger says it has already been applied.
174fn apply_service_migration(
175    conn: &Connection,
176    plan: &ServiceSchemaPlan,
177    migration: &Migration,
178    admission: &WriteAdmission,
179) -> Result<(), SqliteError> {
180    // Serialize the admission decision with other writers. Checking the
181    // predicate or ledger before BEGIN IMMEDIATE lets a second opener see
182    // stale state and replay a migration after the first one commits.
183    let tx = rusqlite::Transaction::new_unchecked(conn, rusqlite::TransactionBehavior::Immediate)?;
184    if let Err(error) = admission.check() {
185        let rollback = tx.rollback();
186        return Err(capacity_refusal_after_rollback(
187            conn,
188            rollback,
189            error,
190            "service schema migration",
191        ));
192    }
193
194    // Check if custom predicate says it's already applied
195    if let Some(check) = migration.is_already_applied {
196        if check(&tx) {
197            return Ok(());
198        }
199    }
200
201    // Check if tracked as applied
202    let already: bool = tx.query_row(
203        "SELECT COUNT(*) > 0 FROM _schema_versions WHERE service = ?1 AND migration_id = ?2",
204        rusqlite::params![plan.service, migration.id],
205        |row| row.get(0),
206    )?;
207
208    if already {
209        return Ok(());
210    }
211
212    tx.execute_batch(migration.up_sql)?;
213
214    tx.execute(
215        "INSERT INTO _schema_versions (service, migration_id, applied_at) VALUES (?1, ?2, ?3)",
216        rusqlite::params![
217            plan.service,
218            migration.id,
219            chrono::Utc::now().timestamp_micros(),
220        ],
221    )?;
222    tx.commit()?;
223    Ok(())
224}
225
226fn require_autocommit(conn: &Connection, operation: &str) -> Result<(), SqliteError> {
227    if conn.is_autocommit() {
228        Ok(())
229    } else {
230        Err(SqliteError::InvalidData(format!(
231            "{operation} did not return the SQLite connection to autocommit"
232        )))
233    }
234}
235
236pub(crate) fn capacity_refusal_after_rollback(
237    conn: &Connection,
238    rollback: rusqlite::Result<()>,
239    refusal: SqliteError,
240    operation: &str,
241) -> SqliteError {
242    if let Err(error) = rollback {
243        return SqliteError::InvalidData(format!(
244            "{operation} capacity refusal could not roll back: {error}; \
245             initial refusal: {refusal}"
246        ));
247    }
248    if !conn.is_autocommit() {
249        return SqliteError::InvalidData(format!(
250            "{operation} capacity refusal rolled back without restoring autocommit; \
251             initial refusal: {refusal}"
252        ));
253    }
254    refusal
255}
256
257// =============================================================================
258// Versioned migration system
259// =============================================================================
260
261/// A single forward-only schema migration.
262///
263/// Migrations are applied in order from the current DB version to the target
264/// version. Each migration runs in its own transaction; a failure rolls back
265/// that migration and leaves the DB at the prior version.
266pub struct VersionedMigration {
267    /// Monotonically increasing version number, starting at 1.
268    pub version: u32,
269    /// Short human-readable name for the migration (used in the audit table).
270    pub name: &'static str,
271    /// SQL to apply this migration. May contain multiple statements separated
272    /// by semicolons; `execute_batch` runs them all.
273    pub up: &'static str,
274}
275
276// V1: complete schema, loaded from sql/schema.sql.
277// Fresh-start repo (v0.2.8) — all schema in one migration, no incremental versions.
278const V1_UP: &str = include_str!("../sql/schema.sql");
279
280const V2_UP: &str = include_str!("../sql/002-narrow-fts-sections-update-trigger.sql");
281
282const V3_UP: &str = include_str!("../sql/003-backfill-domain-mirror-atoms.sql");
283
284const V4_UP: &str = include_str!("../sql/004-fts-consolidation.sql");
285
286const V5_UP: &str = include_str!("../sql/005-unique-comm-external-id.sql");
287
288const V6_UP: &str = include_str!("../sql/006-brain-retune-driver.sql");
289
290const V7_UP: &str = include_str!("../sql/007-notes-seq.sql");
291
292const V8_UP: &str = include_str!("../sql/008-notes-seq-repair.sql");
293
294const V9_UP: &str = include_str!("../sql/009-entities-name-ci-index.sql");
295
296const V10_UP: &str = include_str!("../sql/010-entities-content-ref.sql");
297
298const V11_UP: &str = include_str!("../sql/011-ann-write-log.sql");
299
300const V12_UP: &str = include_str!("../sql/012-ann-write-log-model-seq-index.sql");
301
302const V13_UP: &str = include_str!("../sql/013-list-cursor-sequences.sql");
303
304const V14_UP: &str = include_str!("../sql/014-graph-edges-id-unique.sql");
305
306const V15_UP: &str = include_str!("../sql/015-serve-ledger-attribution.sql");
307
308const V16_UP: &str = include_str!("../sql/016-gtd-dependency-cycle-guards.sql");
309
310const V17_UP: &str = include_str!("../sql/017-agents-ddl.sql");
311
312const V18_UP: &str = include_str!("../sql/018-ann-consumer-pending.sql");
313
314const V19_UP: &str = include_str!("../sql/019-list-cursor-backfill-repair.sql");
315
316const V20_UP: &str = include_str!("../sql/020-blob-gc-claims.sql");
317
318const V22_UP: &str = include_str!("../sql/022-notes-unread-probe-recipient.sql");
319
320const V23_UP: &str = include_str!("../sql/023-fts-record-kind.sql");
321
322const V24_UP: &str = include_str!("../sql/024-fts-rowid-map.sql");
323
324const V25_UP: &str = include_str!("../sql/025-notes-unread-probe-recipient-direction.sql");
325
326const V26_UP: &str = include_str!("../sql/026-knowledge-fts-repair.sql");
327
328const V27_UP: &str = include_str!("../sql/027-notes-hot-property-indexes.sql");
329const V28_UP: &str = include_str!("../sql/028-notes-key.sql");
330
331const V29_UP: &str = include_str!("../sql/029-note-streams.sql");
332const V30_UP: &str = include_str!("../sql/030-tool-source-mounts.sql");
333const V31_UP: &str = include_str!("../sql/031-note-versions.sql");
334const V32_UP: &str = include_str!("../sql/032-knowledge-count-indexes.sql");
335const V33_UP: &str = include_str!("../sql/033-notes-message-recipient-direction.sql");
336const V34_UP: &str = include_str!("../sql/034-notes-namespace-created.sql");
337const V35_UP: &str = include_str!("../sql/035-notes-unread-probe-recipient-type-direction.sql");
338const V36_UP: &str = include_str!("../sql/036-events-operation-attribution.sql");
339const V37_UP: &str = include_str!("../sql/037-entity-versions.sql");
340const V38_UP: &str = include_str!("../sql/038-entities-legacy-type-index.sql");
341const V39_UP: &str = include_str!("../sql/039-knowledge-cursor-indexes.sql");
342const SESSION_IDENTITY_UP: &str = include_str!("../sql/040-session-source-scope.sql");
343const SESSION_IDENTITY_MIGRATION_NAME: &str = "session_source_scoped_identity";
344const V41_UP: &str = include_str!("../sql/041-sender-transport.sql");
345const V42_UP: &str = include_str!("../sql/042-comm-external-id-channel-scope.sql");
346const V43_UP: &str = include_str!("../sql/043-vector-provenance.sql");
347const V44_COLUMNS: &str = include_str!("../sql/044-comm-outbound-due-a-columns.sql");
348const V44_UP: &str = include_str!("../sql/044-comm-outbound-due-b-index.sql");
349
350/// V44 may follow a direct-store bootstrap, whose idempotent notes DDL
351/// already supplies the two columns. Backfill before building the index so
352/// existing future retries are excluded by its deadline range immediately.
353pub(crate) fn migrate_outbound_due_key(tx: &rusqlite::Transaction<'_>) -> rusqlite::Result<()> {
354    let has_column = |name: &str| -> rusqlite::Result<bool> {
355        tx.query_row(
356            "SELECT EXISTS(SELECT 1 FROM pragma_table_info('notes') WHERE name = ?1)",
357            [name],
358            |row| row.get(0),
359        )
360    };
361    match (has_column("strict_due_key")?, has_column("due_source")?) {
362        (false, false) => tx.execute_batch(V44_COLUMNS)?,
363        (true, true) => {}
364        _ => return Err(rusqlite::Error::InvalidQuery),
365    }
366
367    let mut after_id = String::new();
368    let mut first_page = true;
369    loop {
370        let rows: Vec<(String, String)> = {
371            let comparator = if first_page { ">=" } else { ">" };
372            let mut stmt = tx.prepare(&format!(
373                "SELECT id, json_extract(properties, '$.next_attempt_at') FROM notes \
374                 WHERE id {comparator} ?1 AND json_type(properties, '$.next_attempt_at') = 'text' \
375                 ORDER BY id LIMIT 500"
376            ))?;
377            let collected = stmt
378                .query_map([&after_id], |row| Ok((row.get(0)?, row.get(1)?)))?
379                .collect::<rusqlite::Result<_>>()?;
380            collected
381        };
382        if rows.is_empty() {
383            break;
384        }
385        after_id = rows.last().expect("nonempty V44 page").0.clone();
386        first_page = false;
387        for (id, source) in rows {
388            if let Some(key) = crate::pool::strict_rfc3339_key(&source) {
389                tx.execute(
390                    "UPDATE notes SET strict_due_key = ?1, due_source = ?2 \
391                     WHERE id = ?3 AND (strict_due_key IS NOT ?1 OR due_source IS NOT ?2)",
392                    rusqlite::params![key, source, id],
393                )?;
394            }
395        }
396    }
397    tx.execute_batch(V44_UP)
398}
399
400const RECIPIENT_TRANSPORT_VERSION: u32 = 45;
401const V45_UP: &str = include_str!("../sql/045-recipient-transport.sql");
402const V46_UP: &str = include_str!("../sql/046-memory-visibility-receipts.sql");
403const V47_UP: &str = include_str!("../sql/047-attachment-role-quarantine.sql");
404const V49_UP: &str = include_str!("../sql/049-git-note-property-indexes.sql");
405
406const V50_UP: &str = include_str!("../sql/050-entity-list-plans.sql");
407const V51_UP: &str = include_str!("../sql/051-schedule-core-indexes.sql");
408const V52_UP: &str = include_str!("../sql/052-comm-core-indexes.sql");
409const V53_UP: &str = include_str!("../sql/053-entity-kind-list-order.sql");
410const MEMORY_VISIBILITY_CUTOVER_VERSION: u32 = 54;
411const V54_UP: &str = include_str!("../sql/054-memory-visibility-epochs.sql");
412
413const V55_UP: &str = include_str!("../sql/055-knowledge-cursor-domain-tags.sql");
414const V56_UP: &str = include_str!("../sql/056-atom-weights.sql");
415const V57_UP: &str = include_str!("../sql/057-retrieval-snapshots.sql");
416const V58_UP: &str = include_str!("../sql/058-proposal-archive.sql");
417const V59_UP: &str = include_str!("../sql/059-comm-legacy-quarantine-index.sql");
418const V60_UP: &str = include_str!("../sql/060-note-stream-truncation.sql");
419const V61_UP: &str = include_str!("../sql/061-edge-governance.sql");
420const V62_UP: &str = include_str!("../sql/062-authority-store.sql");
421const V63_UP: &str = include_str!("../sql/063-pending-entity-indexes.sql");
422const V64_UP: &str = include_str!("../sql/064-node-confirmed-pins.sql");
423const V65_UP: &str = include_str!("../sql/065-graph-edges-target-relation-index.sql");
424const V66_UP: &str = include_str!("../sql/066-comm-undelivered-due-index.sql");
425const V67_UP: &str = include_str!("../sql/067-entity-keys.sql");
426
427/// DDL for entity keys (ADR-221): the `entity_keys` table and the triggers on
428/// `entities` that release, reclaim and drop its rows. Shared between
429/// migration V67 and the entity store's idempotent schema setup, so a store
430/// opened without the migration chain still has the table its triggers name.
431pub const ENTITY_KEYS_DDL: &str = V67_UP;
432
433const V68_UP: &str = include_str!("../sql/068-entity-aliases.sql");
434
435/// DDL for entity aliases (ADR-221): the `entity_aliases` table, its indexes
436/// and the trigger on `entities` that drops its rows on a hard delete. Shared
437/// between migration V68 and the entity store's idempotent schema setup, as
438/// [`ENTITY_KEYS_DDL`] is.
439pub const ENTITY_ALIASES_DDL: &str = V68_UP;
440
441const V69_UP: &str = include_str!("../sql/069-entity-key-kind-guard.sql");
442
443/// DDL for the trigger on `entities` that refuses a kind change of a live
444/// entity holding keys, and a restore under a kind other than the one its keys
445/// were released under (ADR-221 section 1). Shared between migration V69 and
446/// the entity store's idempotent schema setup, as [`ENTITY_KEYS_DDL`] is; it
447/// names `entity_keys`, so it runs after that DDL.
448pub const ENTITY_KEY_KIND_GUARD_DDL: &str = V69_UP;
449
450/// Retained V66 schema needs only its ledger restored, not an index rebuild.
451fn migrate_undelivered_due_index(tx: &rusqlite::Transaction<'_>) -> rusqlite::Result<()> {
452    let installed: Option<String> = tx
453        .query_row(
454            include_str!("../sql/comm-outbound-due-index-definition.sql"),
455            [],
456            |row| row.get(0),
457        )
458        .optional()?;
459    let (_, create) = V66_UP
460        .split_once("CREATE INDEX")
461        .ok_or(rusqlite::Error::InvalidQuery)?;
462    let expected = format!("CREATE INDEX{create}");
463    // SQLite omits the terminal semicolon. Preserve every interior byte,
464    // including whitespace in SQL string literals, when comparing definitions.
465    if installed.as_deref().is_some_and(|sql| {
466        sql.trim().trim_end_matches(';') == expected.trim().trim_end_matches(';')
467    }) {
468        return Ok(());
469    }
470    tx.execute_batch(V66_UP)
471}
472
473// Ledger-tail replay may retain the physical column; accept only its exact shape.
474fn migrate_proposal_archive(tx: &rusqlite::Transaction<'_>) -> Result<(), SqliteError> {
475    let migration_error = |error: rusqlite::Error| {
476        SqliteError::migration_with_cause(
477            58,
478            format!("proposals_open.archived_at migration failed: {error}"),
479            error,
480        )
481    };
482    let column = tx
483        .query_row(
484            include_str!("../sql/proposal-archive-column.sql"),
485            [],
486            |row| {
487                Ok((
488                    row.get::<_, String>(0)?,
489                    row.get::<_, i64>(1)?,
490                    row.get::<_, Option<String>>(2)?,
491                    row.get::<_, i64>(3)?,
492                    row.get::<_, i64>(4)?,
493                ))
494            },
495        )
496        .optional()
497        .map_err(migration_error)?;
498    match column {
499        None => tx.execute_batch(V58_UP).map_err(migration_error),
500        Some((declared_type, not_null, default, primary_key, hidden))
501            if declared_type.eq_ignore_ascii_case("INTEGER")
502                && not_null == 0
503                && default.is_none()
504                && primary_key == 0
505                && hidden == 0 =>
506        {
507            Ok(())
508        }
509        Some(_) => Err(SqliteError::migration_message(
510            58,
511            "incompatible proposals_open.archived_at: expected an ordinary nullable INTEGER column without a default or primary key",
512        )),
513    }
514}
515
516const V48_UP: &str = include_str!("../sql/048-acknowledgement-journal-a-table.sql");
517const ACKNOWLEDGEMENT_JOURNAL_INDEX: &str =
518    include_str!("../sql/048-acknowledgement-journal-b-index.sql");
519
520/// A ledger-tail replay keeps already-current journal state and retry metadata.
521pub(crate) fn migrate_acknowledgement_journal(
522    tx: &rusqlite::Transaction<'_>,
523) -> rusqlite::Result<()> {
524    let columns: i64 = tx.query_row(
525        "SELECT count(*) FROM pragma_table_info('comm_ack_work') \
526         WHERE name IN ('attempt_count','not_before','retirement_reason')",
527        [],
528        |row| row.get(0),
529    )?;
530    match columns {
531        0 => tx.execute_batch(V48_UP)?,
532        3 => {}
533        _ => return Err(rusqlite::Error::InvalidQuery),
534    }
535    tx.execute_batch(ACKNOWLEDGEMENT_JOURNAL_INDEX)
536}
537
538const V21_STAGE_UP: &str = include_str!("../sql/021-attachments-a-stage.sql");
539
540const V21_ATTACHMENT_FENCES_UP: &str = include_str!("../sql/021-attachments-b-claim-fences.sql");
541
542/// Core schema version reserved for ADR-121's attachments-first cutover.
543pub const ATTACHMENT_CUTOVER_VERSION: u32 = 21;
544
545/// The latest schema version this build's migration chain produces.
546///
547/// Terminal-version assertions belong on this, not on a hardcoded number:
548/// a literal decays into a wrong claim the next time a migration is added.
549pub fn latest_schema_version() -> u32 {
550    MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
551}
552
553/// DDL for the `ann_write_log` delta table.
554///
555/// Shared between migration V11 and the belt-and-suspenders creation in
556/// `StorageBackend::vectors_for_namespace` (same pattern as
557/// [`EMBEDDING_MODELS_DDL`]): every database that hosts `vec_*` tables must
558/// also have the write log, or vector writes would fail on databases opened
559/// without `run_migrations()`. The `.sql` file is `IF NOT EXISTS`-idempotent.
560pub const ANN_WRITE_LOG_DDL: &str = V11_UP;
561
562/// DDL for the `ann_write_log` model/kind/field-leading index (ADR-118 §"Cost
563/// bound"), shared between migration V12 and the belt-and-suspenders creation
564/// in `StorageBackend::vectors_for_namespace` for the same reason as
565/// [`ANN_WRITE_LOG_DDL`].
566pub const ANN_WRITE_LOG_MODEL_SEQ_INDEX_DDL: &str = V12_UP;
567
568/// Idempotent DDL for pending ANN-consumer lifecycle metadata (#1479).
569///
570/// The V18 migration additionally translates legacy zero-watermark rows once.
571/// This constant deliberately contains only idempotent DDL: vector-store open
572/// paths may execute it repeatedly and must never demote a valid active
573/// checkpoint at sequence zero back to pending.
574pub const ANN_CONSUMER_PENDING_DDL: &str = include_str!("../sql/ann-consumer-pending-ddl.sql");
575
576/// Sidecar DDL registered in the migration ledger. Direct vector-store
577/// construction leaves this schema to the versioned migration.
578pub const VECTOR_PROVENANCE_DDL: &str = V43_UP;
579
580/// DDL for the `_embedding_models` registry table.
581///
582/// Shared between the V1 schema and the belt-and-suspenders creation in
583/// `StorageBackend::vectors_for_namespace`. Both sites reference this constant so
584/// the schema cannot silently diverge if the registry evolves.
585pub const EMBEDDING_MODELS_DDL: &str = include_str!("../sql/embedding-models-ddl.sql");
586
587/// Canonical versioned migration ledger in ascending order.
588///
589/// [`run_migrations`] applies the ordinary prefix and may complete V21 through
590/// its zero-legacy-reference fast path. A legacy V20 database records V21 only
591/// when [`finalize_attachment_cutover`] commits the application-assisted
592/// cutover.
593pub const MIGRATIONS: &[VersionedMigration] = &[
594    VersionedMigration {
595        version: 1,
596        name: "initial_schema",
597        up: V1_UP,
598    },
599    VersionedMigration {
600        version: 2,
601        name: "narrow_fts_sections_update_trigger",
602        up: V2_UP,
603    },
604    VersionedMigration {
605        version: 3,
606        name: "backfill_domain_mirror_atoms",
607        up: V3_UP,
608    },
609    VersionedMigration {
610        version: 4,
611        name: "fts_consolidation",
612        up: V4_UP,
613    },
614    VersionedMigration {
615        version: 5,
616        name: "unique_comm_message_external_id",
617        up: V5_UP,
618    },
619    VersionedMigration {
620        version: 6,
621        name: "brain_retune_driver",
622        up: V6_UP,
623    },
624    VersionedMigration {
625        version: 7,
626        name: "notes_seq",
627        up: V7_UP,
628    },
629    VersionedMigration {
630        version: 8,
631        name: "notes_seq_repair",
632        up: V8_UP,
633    },
634    VersionedMigration {
635        version: 9,
636        name: "entities_name_ci_index",
637        up: V9_UP,
638    },
639    VersionedMigration {
640        version: 10,
641        name: "entities_content_ref",
642        up: V10_UP,
643    },
644    VersionedMigration {
645        version: 11,
646        name: "ann_write_log",
647        up: V11_UP,
648    },
649    VersionedMigration {
650        version: 12,
651        name: "ann_write_log_model_seq_index",
652        up: V12_UP,
653    },
654    VersionedMigration {
655        version: 13,
656        name: "list_cursor_sequences",
657        up: V13_UP,
658    },
659    VersionedMigration {
660        version: 14,
661        name: "graph_edges_id_unique",
662        up: V14_UP,
663    },
664    VersionedMigration {
665        version: 15,
666        name: "serve_ledger_attribution",
667        up: V15_UP,
668    },
669    VersionedMigration {
670        version: 16,
671        name: "gtd_dependency_cycle_guards",
672        up: V16_UP,
673    },
674    VersionedMigration {
675        version: 17,
676        name: "agents_ddl",
677        up: V17_UP,
678    },
679    VersionedMigration {
680        version: 18,
681        name: "ann_consumer_pending",
682        up: V18_UP,
683    },
684    VersionedMigration {
685        version: 19,
686        name: "list_cursor_backfill_repair",
687        up: V19_UP,
688    },
689    VersionedMigration {
690        version: 20,
691        name: "blob_gc_claims",
692        up: V20_UP,
693    },
694    VersionedMigration {
695        version: ATTACHMENT_CUTOVER_VERSION,
696        name: "attachments_first_class",
697        // V21 is coordinated rather than an unconditional SQL migration.
698        // The runner special-cases it below; exposing the stage DDL here keeps
699        // the ledger entry self-describing for migration inspection tooling.
700        up: V21_STAGE_UP,
701    },
702    VersionedMigration {
703        version: 22,
704        name: "notes_unread_probe_recipient",
705        up: V22_UP,
706    },
707    VersionedMigration {
708        version: 23,
709        name: "fts_record_kind",
710        up: V23_UP,
711    },
712    VersionedMigration {
713        version: 24,
714        name: "fts_rowid_map",
715        up: V24_UP,
716    },
717    VersionedMigration {
718        version: 25,
719        name: "notes_unread_probe_recipient_direction",
720        up: V25_UP,
721    },
722    VersionedMigration {
723        version: 26,
724        name: "knowledge_fts_repair",
725        up: V26_UP,
726    },
727    VersionedMigration {
728        version: 27,
729        name: "notes_hot_property_indexes",
730        up: V27_UP,
731    },
732    VersionedMigration {
733        version: 28,
734        name: "notes_key",
735        up: V28_UP,
736    },
737    VersionedMigration {
738        version: 29,
739        name: "note_streams",
740        up: V29_UP,
741    },
742    VersionedMigration {
743        version: 30,
744        name: "tool_source_mounts",
745        up: V30_UP,
746    },
747    VersionedMigration {
748        version: 31,
749        name: "note_versions",
750        up: V31_UP,
751    },
752    VersionedMigration {
753        version: 32,
754        name: "knowledge_count_indexes",
755        up: V32_UP,
756    },
757    VersionedMigration {
758        version: 33,
759        name: "notes_message_recipient_direction",
760        up: V33_UP,
761    },
762    VersionedMigration {
763        version: 34,
764        name: "notes_namespace_created",
765        up: V34_UP,
766    },
767    VersionedMigration {
768        version: 35,
769        name: "notes_unread_probe_recipient_type_direction",
770        up: V35_UP,
771    },
772    VersionedMigration {
773        version: 36,
774        name: "events_operation_attribution",
775        up: V36_UP,
776    },
777    VersionedMigration {
778        version: 37,
779        name: "entity_versions",
780        up: V37_UP,
781    },
782    VersionedMigration {
783        version: 38,
784        name: "entities_legacy_type_index",
785        up: V38_UP,
786    },
787    VersionedMigration {
788        version: 39,
789        name: "knowledge_cursor_indexes",
790        up: V39_UP,
791    },
792    VersionedMigration {
793        version: 40,
794        name: SESSION_IDENTITY_MIGRATION_NAME,
795        up: SESSION_IDENTITY_UP,
796    },
797    VersionedMigration {
798        version: 41,
799        name: "sender_transport",
800        up: V41_UP,
801    },
802    VersionedMigration {
803        version: 42,
804        name: "comm_external_id_channel_scope",
805        up: V42_UP,
806    },
807    VersionedMigration {
808        version: 43,
809        name: "vector_provenance",
810        up: V43_UP,
811    },
812    VersionedMigration {
813        version: 44,
814        name: "comm_outbound_due",
815        up: V44_UP,
816    },
817    VersionedMigration {
818        version: RECIPIENT_TRANSPORT_VERSION,
819        name: "recipient_transport",
820        up: V45_UP,
821    },
822    VersionedMigration {
823        version: 46,
824        name: "memory_visibility_receipts",
825        up: V46_UP,
826    },
827    VersionedMigration {
828        version: 47,
829        name: "attachment_role_quarantine",
830        up: V47_UP,
831    },
832    VersionedMigration {
833        version: 48,
834        name: "acknowledgement_journal",
835        up: V48_UP,
836    },
837    VersionedMigration {
838        version: 49,
839        name: "git_note_property_indexes",
840        up: V49_UP,
841    },
842    VersionedMigration {
843        version: 50,
844        name: "entity_list_plans",
845        up: V50_UP,
846    },
847    VersionedMigration {
848        version: 51,
849        name: "schedule_core_indexes",
850        up: V51_UP,
851    },
852    VersionedMigration {
853        version: 52,
854        name: "comm_core_indexes",
855        up: V52_UP,
856    },
857    VersionedMigration {
858        version: 53,
859        name: "entity_kind_list_order",
860        up: V53_UP,
861    },
862    VersionedMigration {
863        version: MEMORY_VISIBILITY_CUTOVER_VERSION,
864        name: "memory_visibility_epochs",
865        up: V54_UP,
866    },
867    VersionedMigration {
868        version: 55,
869        name: "knowledge_atom_cursor_all_live_tags",
870        up: V55_UP,
871    },
872    VersionedMigration {
873        version: 56,
874        name: "atom_weight_tables",
875        up: V56_UP,
876    },
877    VersionedMigration {
878        version: 57,
879        name: "retrieval_snapshot_tables",
880        up: V57_UP,
881    },
882    VersionedMigration {
883        version: 58,
884        name: "proposal_archive",
885        up: V58_UP,
886    },
887    VersionedMigration {
888        version: 59,
889        name: "comm_legacy_quarantine_index",
890        up: V59_UP,
891    },
892    VersionedMigration {
893        version: 60,
894        name: "note_stream_truncation",
895        up: V60_UP,
896    },
897    VersionedMigration {
898        version: 61,
899        name: "edge_governance",
900        up: V61_UP,
901    },
902    VersionedMigration {
903        version: 62,
904        name: "authority_store",
905        up: V62_UP,
906    },
907    VersionedMigration {
908        version: 63,
909        name: "pending_entity_indexes",
910        up: V63_UP,
911    },
912    VersionedMigration {
913        version: 64,
914        name: "node_confirmed_pins",
915        up: V64_UP,
916    },
917    VersionedMigration {
918        version: 65,
919        name: "graph_edges_target_relation_index",
920        up: V65_UP,
921    },
922    VersionedMigration {
923        version: 66,
924        name: "comm_undelivered_due_index",
925        up: V66_UP,
926    },
927    VersionedMigration {
928        version: 67,
929        name: "entity_keys",
930        up: V67_UP,
931    },
932    VersionedMigration {
933        version: 68,
934        name: "entity_aliases",
935        up: V68_UP,
936    },
937    VersionedMigration {
938        version: 69,
939        name: "entity_key_kind_guard",
940        up: V69_UP,
941    },
942];
943
944/// Durable state of ADR-121's boot-gated, two-stage attachment cutover.
945#[derive(Clone, Copy, Debug, Eq, PartialEq)]
946pub enum AttachmentCutoverStatus {
947    /// V20 is current and no stage marker has been committed.
948    Pending,
949    /// Stage 1 committed; boot must finish verified pack-owned attachments.
950    Incomplete,
951    /// V21, the attachment fences, and the attachment-only schema committed.
952    Complete,
953}
954
955fn schema_object_exists(
956    conn: &Connection,
957    object_type: &str,
958    name: &str,
959) -> Result<bool, SqliteError> {
960    conn.query_row(
961        "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = ?1 AND name = ?2",
962        rusqlite::params![object_type, name],
963        |row| row.get(0),
964    )
965    .map_err(Into::into)
966}
967
968fn schema_column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool, SqliteError> {
969    conn.query_row(
970        "SELECT COUNT(*) > 0 FROM pragma_table_info(?1) WHERE name = ?2",
971        rusqlite::params![table, column],
972        |row| row.get(0),
973    )
974    .map_err(Into::into)
975}
976
977fn require_attachment_schema_objects(
978    conn: &Connection,
979    objects: &[(&str, &str)],
980    phase: &str,
981) -> Result<(), SqliteError> {
982    for (object_type, name) in objects {
983        if !schema_object_exists(conn, object_type, name)? {
984            return Err(SqliteError::InvalidData(format!(
985                "attachment cutover {phase} state is missing {object_type} {name:?}"
986            )));
987        }
988    }
989    Ok(())
990}
991
992fn validate_incomplete_attachment_schema(conn: &Connection) -> Result<(), SqliteError> {
993    require_attachment_schema_objects(
994        conn,
995        &[
996            ("table", "attachments"),
997            ("index", "idx_attachments_content_ref"),
998        ],
999        "incomplete",
1000    )?;
1001    require_legacy_attachment_fences(conn)
1002}
1003
1004fn validate_complete_attachment_schema(conn: &Connection) -> Result<(), SqliteError> {
1005    require_attachment_schema_objects(
1006        conn,
1007        &[
1008            ("table", "attachments"),
1009            ("table", "blob_gc_claims"),
1010            ("index", "idx_attachments_content_ref"),
1011            ("index", "idx_blob_gc_claims_content_ref"),
1012            ("trigger", "attachments_reject_claimed_blob_insert"),
1013            ("trigger", "attachments_reject_claimed_blob_update"),
1014        ],
1015        "complete",
1016    )?;
1017    if schema_column_exists(conn, "entities", "content_ref")? {
1018        return Err(SqliteError::InvalidData(
1019            "attachment cutover is complete but entities.content_ref still exists".into(),
1020        ));
1021    }
1022    for (object_type, name) in [
1023        ("index", "idx_entities_content_ref"),
1024        ("trigger", "entities_reject_claimed_blob_insert"),
1025        ("trigger", "entities_reject_claimed_blob_update"),
1026    ] {
1027        if schema_object_exists(conn, object_type, name)? {
1028            return Err(SqliteError::InvalidData(format!(
1029                "attachment cutover is complete but legacy {object_type} {name:?} still exists"
1030            )));
1031        }
1032    }
1033    Ok(())
1034}
1035
1036/// Whether the migration chain would stop at [`ATTACHMENT_CUTOVER_VERSION`] and
1037/// leave the store for the host's application-assisted cutover, read without
1038/// mutating the connection.
1039///
1040/// `false` for a store already at or past the cutover version, since the chain
1041/// never reaches that step again. Below it, the answer is the chain's own
1042/// condition evaluated on the store as it is now: the cutover is `Incomplete`,
1043/// or an entity still holds a legacy `content_ref`. A store whose `entities`
1044/// table has no `content_ref` column yet (no table, or a store below V10) holds
1045/// no legacy reference. An impossible marker and ledger pair is an error, as it
1046/// is for the chain.
1047pub fn attachment_cutover_would_defer(conn: &Connection) -> Result<bool, SqliteError> {
1048    if read_schema_version(conn)? >= ATTACHMENT_CUTOVER_VERSION {
1049        return Ok(false);
1050    }
1051    cutover_defers(conn, attachment_cutover_status(conn)?)
1052}
1053
1054/// The V21 deferral condition, shared by the chain and
1055/// [`attachment_cutover_would_defer`] so there is one copy of it.
1056fn cutover_defers(conn: &Connection, status: AttachmentCutoverStatus) -> Result<bool, SqliteError> {
1057    let legacy_refs: i64 = if schema_column_exists(conn, "entities", "content_ref")? {
1058        conn.query_row(
1059            "SELECT COUNT(*) FROM entities WHERE content_ref IS NOT NULL",
1060            [],
1061            |row| row.get(0),
1062        )?
1063    } else {
1064        0
1065    };
1066    Ok(status == AttachmentCutoverStatus::Incomplete || legacy_refs != 0)
1067}
1068
1069/// Inspect the coordinated V21 state without mutating the connection.
1070///
1071/// The marker and migration ledger form one state machine. Impossible pairs
1072/// fail closed instead of being guessed into a resumable state.
1073pub fn attachment_cutover_status(
1074    conn: &Connection,
1075) -> Result<AttachmentCutoverStatus, SqliteError> {
1076    let version = read_schema_version(conn)?;
1077    let marker_table = schema_object_exists(conn, "table", "attachment_cutover_state")?;
1078    if !marker_table {
1079        if version >= ATTACHMENT_CUTOVER_VERSION {
1080            return Err(SqliteError::InvalidData(format!(
1081                "migration V{ATTACHMENT_CUTOVER_VERSION} is recorded but its attachment cutover marker is absent"
1082            )));
1083        }
1084        if schema_object_exists(conn, "table", "attachments")? {
1085            return Err(SqliteError::InvalidData(
1086                "attachments table exists without the durable attachment cutover marker".into(),
1087            ));
1088        }
1089        return Ok(AttachmentCutoverStatus::Pending);
1090    }
1091
1092    let marker: Option<(String, Option<i64>)> = conn
1093        .query_row(
1094            "SELECT state, completed_at FROM attachment_cutover_state WHERE singleton = 1",
1095            [],
1096            |row| Ok((row.get(0)?, row.get(1)?)),
1097        )
1098        .optional()?;
1099    match marker {
1100        Some((state, None)) if state == "incomplete" => {
1101            if version >= ATTACHMENT_CUTOVER_VERSION {
1102                Err(SqliteError::InvalidData(format!(
1103                    "attachment cutover is incomplete but migration V{ATTACHMENT_CUTOVER_VERSION} is already recorded"
1104                )))
1105            } else {
1106                validate_incomplete_attachment_schema(conn)?;
1107                Ok(AttachmentCutoverStatus::Incomplete)
1108            }
1109        }
1110        Some((state, Some(_))) if state == "complete" => {
1111            // Later migrations (V22+) are recorded on top of a completed
1112            // cutover in the normal course; only a ledger BELOW V21 beside a
1113            // complete marker is an impossible pair.
1114            if version >= ATTACHMENT_CUTOVER_VERSION {
1115                validate_complete_attachment_schema(conn)?;
1116                Ok(AttachmentCutoverStatus::Complete)
1117            } else {
1118                Err(SqliteError::InvalidData(format!(
1119                    "attachment cutover is complete but schema ledger is at V{version}, below V{ATTACHMENT_CUTOVER_VERSION}"
1120                )))
1121            }
1122        }
1123        Some((state, completed_at)) => Err(SqliteError::InvalidData(format!(
1124            "invalid attachment cutover marker state {state:?} with completed_at={completed_at:?}"
1125        ))),
1126        None => Err(SqliteError::InvalidData(
1127            "attachment cutover marker table exists without its singleton row".into(),
1128        )),
1129    }
1130}
1131
1132fn require_legacy_attachment_fences(conn: &Connection) -> Result<(), SqliteError> {
1133    if !schema_column_exists(conn, "entities", "content_ref")? {
1134        return Err(SqliteError::InvalidData(
1135            "attachment cutover requires legacy entities.content_ref until finalization".into(),
1136        ));
1137    }
1138    for (object_type, name) in [
1139        ("table", "blob_gc_claims"),
1140        ("index", "idx_blob_gc_claims_content_ref"),
1141        ("index", "idx_entities_content_ref"),
1142        ("trigger", "entities_reject_claimed_blob_insert"),
1143        ("trigger", "entities_reject_claimed_blob_update"),
1144    ] {
1145        if !schema_object_exists(conn, object_type, name)? {
1146            return Err(SqliteError::InvalidData(format!(
1147                "attachment cutover requires legacy {object_type} {name:?} until finalization"
1148            )));
1149        }
1150    }
1151    Ok(())
1152}
1153
1154// length() and GLOB both stop scanning at an embedded NUL, so a value of 64
1155// hex characters followed by a NUL and arbitrary trailing bytes would pass
1156// both. Deriving the canonical byte width from the connection's own text
1157// encoding (rather than assuming UTF-8) keeps this arm correct on a database
1158// pinned to UTF-16 and fails closed if the probe returns something else,
1159// matching the pattern already used by `validate_blob_gc_evidence`.
1160fn canonical_content_ref_byte_width(conn: &Connection) -> Result<i64, SqliteError> {
1161    let width: i64 = conn.query_row("SELECT length(CAST('x' AS BLOB))", [], |row| row.get(0))?;
1162    if !(1..=4).contains(&width) {
1163        return Err(SqliteError::InvalidData(format!(
1164            "the text-encoding width probe returned {width}; refusing canonicality validation"
1165        )));
1166    }
1167    Ok(width * 64)
1168}
1169
1170fn validate_canonical_legacy_refs(conn: &Connection) -> Result<(), SqliteError> {
1171    let canonical_bytes = canonical_content_ref_byte_width(conn)?;
1172    let invalid: Option<String> = conn
1173        .query_row(
1174            "SELECT id FROM entities \
1175             WHERE content_ref IS NOT NULL \
1176               AND (typeof(content_ref) <> 'text' \
1177                 OR length(content_ref) <> 64 \
1178                 OR length(CAST(content_ref AS BLOB)) <> ?1 \
1179                 OR content_ref GLOB '*[^0-9a-f]*') \
1180             LIMIT 1",
1181            [canonical_bytes],
1182            |row| row.get(0),
1183        )
1184        .optional()?;
1185    if let Some(id) = invalid {
1186        return Err(SqliteError::InvalidData(format!(
1187            "entities.content_ref for record {id:?} is not a canonical 64-character lowercase hexadecimal ContentRef"
1188        )));
1189    }
1190    Ok(())
1191}
1192
1193fn validate_canonical_attachment_and_claim_refs(conn: &Connection) -> Result<(), SqliteError> {
1194    let canonical_bytes = canonical_content_ref_byte_width(conn)?;
1195    for (table, identity) in [
1196        ("attachments", "record_uuid"),
1197        ("blob_gc_claims", "root_key"),
1198    ] {
1199        let sql = format!(
1200            "SELECT {identity} FROM {table} \
1201             WHERE typeof(content_ref) <> 'text' \
1202                OR length(content_ref) <> 64 \
1203                OR length(CAST(content_ref AS BLOB)) <> ?1 \
1204                OR content_ref GLOB '*[^0-9a-f]*' \
1205             LIMIT 1"
1206        );
1207        let invalid: Option<String> = conn
1208            .query_row(&sql, [canonical_bytes], |row| row.get(0))
1209            .optional()?;
1210        if let Some(owner) = invalid {
1211            return Err(SqliteError::InvalidData(format!(
1212                "{table}.content_ref for {identity} {owner:?} is not canonical"
1213            )));
1214        }
1215    }
1216    Ok(())
1217}
1218
1219fn validate_attachment_record_owners(conn: &Connection) -> Result<(), SqliteError> {
1220    let dangling: Option<(String, String)> = conn
1221        .query_row(
1222            "SELECT record_uuid, substrate FROM attachments AS attachment \
1223             WHERE (substrate = 'entity' AND NOT EXISTS ( \
1224                       SELECT 1 FROM entities WHERE id = attachment.record_uuid \
1225                   )) \
1226                OR (substrate = 'note' AND NOT EXISTS ( \
1227                       SELECT 1 FROM notes WHERE id = attachment.record_uuid \
1228                   )) \
1229             LIMIT 1",
1230            [],
1231            |row| Ok((row.get(0)?, row.get(1)?)),
1232        )
1233        .optional()?;
1234    if let Some((record_uuid, substrate)) = dangling {
1235        return Err(SqliteError::InvalidData(format!(
1236            "attachment role references absent {substrate} record {record_uuid:?}"
1237        )));
1238    }
1239    Ok(())
1240}
1241
1242fn validate_legacy_content_backfill(conn: &Connection) -> Result<(), SqliteError> {
1243    let conflict: Option<String> = conn
1244        .query_row(
1245            "SELECT entity.id FROM entities AS entity \
1246             LEFT JOIN attachments AS attachment \
1247               ON attachment.record_uuid = entity.id AND attachment.role = 'content' \
1248             WHERE entity.content_ref IS NOT NULL \
1249               AND (attachment.record_uuid IS NULL \
1250                 OR attachment.substrate <> 'entity' \
1251                 OR attachment.content_ref <> entity.content_ref) \
1252             LIMIT 1",
1253            [],
1254            |row| row.get(0),
1255        )
1256        .optional()?;
1257    if let Some(record_uuid) = conflict {
1258        return Err(SqliteError::InvalidData(format!(
1259            "legacy content attachment for entity {record_uuid:?} is missing or conflicts with entities.content_ref"
1260        )));
1261    }
1262    Ok(())
1263}
1264
1265fn stage_attachment_cutover_on_connection(conn: &Connection, now: i64) -> Result<(), SqliteError> {
1266    require_legacy_attachment_fences(conn)?;
1267    conn.execute_batch(V21_STAGE_UP)?;
1268    validate_canonical_legacy_refs(conn)?;
1269    validate_canonical_attachment_and_claim_refs(conn)?;
1270
1271    let conflict: Option<String> = conn
1272        .query_row(
1273            "SELECT entity.id FROM entities AS entity \
1274             JOIN attachments AS attachment \
1275               ON attachment.record_uuid = entity.id AND attachment.role = 'content' \
1276             WHERE entity.content_ref IS NOT NULL \
1277               AND (attachment.substrate <> 'entity' \
1278                 OR attachment.content_ref <> entity.content_ref) \
1279             LIMIT 1",
1280            [],
1281            |row| row.get(0),
1282        )
1283        .optional()?;
1284    if let Some(record_uuid) = conflict {
1285        return Err(SqliteError::InvalidData(format!(
1286            "existing content attachment for entity {record_uuid:?} conflicts with entities.content_ref"
1287        )));
1288    }
1289
1290    conn.execute(
1291        "INSERT INTO attachments \
1292         (record_uuid, substrate, role, content_ref, media_type, size_bytes, created_at) \
1293         SELECT id, 'entity', 'content', content_ref, NULL, NULL, created_at \
1294         FROM entities WHERE content_ref IS NOT NULL \
1295         ON CONFLICT(record_uuid, role) DO NOTHING",
1296        [],
1297    )?;
1298    validate_legacy_content_backfill(conn)?;
1299
1300    // The caller holds the canonical database GC owner, so every preexisting
1301    // claim is abandoned. Clearing happens before the durable incomplete
1302    // marker is exposed and remains inside this one transaction.
1303    conn.execute("DELETE FROM blob_gc_claims", [])?;
1304    conn.execute(
1305        "INSERT INTO attachment_cutover_state \
1306         (singleton, state, started_at, completed_at) \
1307         VALUES (1, 'incomplete', ?1, NULL) \
1308         ON CONFLICT(singleton) DO NOTHING",
1309        [now],
1310    )?;
1311    Ok(())
1312}
1313
1314/// Commit stage 1 of the coordinated V21 migration.
1315///
1316/// The caller must hold [`crate::stores::blob::DatabaseGcOwnerGuard`] for the
1317/// canonical database before entering this function and retain it through
1318/// application backfill and finalization. This function owns one IMMEDIATE
1319/// SQLite transaction; a failure leaves neither its DDL nor marker visible.
1320pub fn stage_attachment_cutover(conn: &mut Connection) -> Result<(), SqliteError> {
1321    let admission = WriteAdmission::for_canonical_path(canonical_connection_database_path(conn)?)?;
1322    RawMigrationWriteUnit::new(conn, &admission)?
1323        .run(|conn| stage_attachment_cutover_with_admission(conn, &admission))
1324}
1325
1326/// Stage attachment cutover with an explicit raw-connection policy.
1327pub fn stage_attachment_cutover_with_policy(
1328    conn: &mut Connection,
1329    policy: &MigrationWritePolicy,
1330) -> Result<(), SqliteError> {
1331    let admission =
1332        WriteAdmission::for_migration_policy(canonical_connection_database_path(conn)?, policy)?;
1333    RawMigrationWriteUnit::new(conn, &admission)?
1334        .run(|conn| stage_attachment_cutover_with_admission(conn, &admission))
1335}
1336
1337/// Stage attachment cutover using admission already held by a pooled caller.
1338pub(crate) fn stage_attachment_cutover_with_admission(
1339    conn: &mut Connection,
1340    admission: &WriteAdmission,
1341) -> Result<(), SqliteError> {
1342    match attachment_cutover_status(conn)? {
1343        AttachmentCutoverStatus::Complete => return Ok(()),
1344        AttachmentCutoverStatus::Pending | AttachmentCutoverStatus::Incomplete => {}
1345    }
1346    if read_schema_version(conn)? != ATTACHMENT_CUTOVER_VERSION - 1 {
1347        return Err(SqliteError::InvalidData(format!(
1348            "attachment cutover stage requires canonical V{} schema",
1349            ATTACHMENT_CUTOVER_VERSION - 1
1350        )));
1351    }
1352
1353    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
1354    if let Err(error) = admission.check() {
1355        let rollback = tx.rollback();
1356        return Err(capacity_refusal_after_rollback(
1357            conn,
1358            rollback,
1359            error,
1360            "attachment cutover stage",
1361        ));
1362    }
1363    let status = attachment_cutover_status(&tx)?;
1364    if status == AttachmentCutoverStatus::Complete {
1365        return Ok(());
1366    }
1367    stage_attachment_cutover_on_connection(&tx, chrono::Utc::now().timestamp_micros())?;
1368    tx.commit()?;
1369    Ok(())
1370}
1371
1372/// Add one host-verified pack-owned attachment during V21 stage 2.
1373///
1374/// This helper is deliberately transaction-neutral: it neither begins nor
1375/// commits a transaction. The boot coordinator can therefore apply the full
1376/// verified vector in one caller-owned IMMEDIATE transaction while retaining
1377/// the canonical database GC owner. Reapplying the same role and content is
1378/// idempotent; a different substrate or digest for that role fails closed.
1379#[allow(clippy::too_many_arguments)]
1380pub fn apply_generic_verified_attachment(
1381    conn: &Connection,
1382    record_uuid: &str,
1383    substrate: &str,
1384    role: &str,
1385    content_ref: &ContentRef,
1386    media_type: Option<&str>,
1387    size_bytes: Option<u64>,
1388    created_at: i64,
1389) -> Result<(), SqliteError> {
1390    if attachment_cutover_status(conn)? != AttachmentCutoverStatus::Incomplete {
1391        return Err(SqliteError::InvalidData(
1392            "verified application attachments may only be applied while V21 cutover is incomplete"
1393                .into(),
1394        ));
1395    }
1396    if role.is_empty() || role.chars().any(char::is_control) {
1397        return Err(SqliteError::InvalidData(
1398            "attachment role must be non-empty and contain no control characters".into(),
1399        ));
1400    }
1401    let size_bytes = size_bytes.map(i64::try_from).transpose().map_err(|_| {
1402        SqliteError::InvalidData("attachment size_bytes exceeds SQLite INTEGER".into())
1403    })?;
1404    let owner_table = match substrate {
1405        "entity" => "entities",
1406        "note" => "notes",
1407        other => {
1408            return Err(SqliteError::InvalidData(format!(
1409                "attachment substrate must be 'entity' or 'note', got {other:?}"
1410            )))
1411        }
1412    };
1413    let owner_sql = format!("SELECT COUNT(*) > 0 FROM {owner_table} WHERE id = ?1");
1414    let owner_exists: bool = conn.query_row(&owner_sql, [record_uuid], |row| row.get(0))?;
1415    if !owner_exists {
1416        return Err(SqliteError::InvalidData(format!(
1417            "cannot attach role {role:?}: {substrate} record {record_uuid:?} does not exist"
1418        )));
1419    }
1420    let claimed: bool = conn.query_row(
1421        "SELECT COUNT(*) > 0 FROM blob_gc_claims WHERE content_ref = ?1",
1422        [content_ref.as_str()],
1423        |row| row.get(0),
1424    )?;
1425    if claimed {
1426        return Err(SqliteError::InvalidData(format!(
1427            "cannot attach claimed content_ref {} during V21 cutover",
1428            content_ref.as_str()
1429        )));
1430    }
1431
1432    let changed = conn.execute(
1433        "INSERT INTO attachments \
1434         (record_uuid, substrate, role, content_ref, media_type, size_bytes, created_at) \
1435         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
1436         ON CONFLICT(record_uuid, role) DO UPDATE SET \
1437             media_type = excluded.media_type, \
1438             size_bytes = excluded.size_bytes, \
1439             created_at = excluded.created_at \
1440         WHERE attachments.substrate = excluded.substrate \
1441           AND attachments.content_ref = excluded.content_ref",
1442        rusqlite::params![
1443            record_uuid,
1444            substrate,
1445            role,
1446            content_ref.as_str(),
1447            media_type,
1448            size_bytes,
1449            created_at,
1450        ],
1451    )?;
1452    if changed == 0 {
1453        return Err(SqliteError::InvalidData(format!(
1454            "attachment role {role:?} for record {record_uuid:?} conflicts with an existing substrate or content_ref"
1455        )));
1456    }
1457    Ok(())
1458}
1459
1460fn finalize_attachment_cutover_on_connection(
1461    conn: &Connection,
1462    now: i64,
1463) -> Result<(), SqliteError> {
1464    require_legacy_attachment_fences(conn)?;
1465    validate_canonical_legacy_refs(conn)?;
1466    validate_canonical_attachment_and_claim_refs(conn)?;
1467    validate_attachment_record_owners(conn)?;
1468    validate_legacy_content_backfill(conn)?;
1469
1470    let remaining_claims: i64 =
1471        conn.query_row("SELECT COUNT(*) FROM blob_gc_claims", [], |row| row.get(0))?;
1472    if remaining_claims != 0 {
1473        return Err(SqliteError::InvalidData(format!(
1474            "attachment cutover cannot finalize while {remaining_claims} blob GC claim rows remain"
1475        )));
1476    }
1477
1478    let uncovered_model: Option<String> = conn
1479        .query_row(
1480            "SELECT model.id FROM entities AS model \
1481             WHERE model.entity_type = 'moodboard_model' \
1482               AND model.content_ref IS NOT NULL \
1483               AND NOT EXISTS ( \
1484                   SELECT 1 FROM attachments AS attachment \
1485                   WHERE attachment.record_uuid = model.id \
1486                     AND attachment.substrate = 'entity' \
1487                     AND attachment.role = 'fann-network' \
1488               ) \
1489             LIMIT 1",
1490            [],
1491            |row| row.get(0),
1492        )
1493        .optional()?;
1494    if let Some(record_uuid) = uncovered_model {
1495        return Err(SqliteError::InvalidData(format!(
1496            "moodboard_model {record_uuid:?} has legacy content but no verified 'fann-network' attachment"
1497        )));
1498    }
1499
1500    conn.execute_batch(V21_ATTACHMENT_FENCES_UP)?;
1501    conn.execute_batch(
1502        "DROP TRIGGER entities_reject_claimed_blob_insert; \
1503         DROP TRIGGER entities_reject_claimed_blob_update; \
1504         DROP INDEX idx_entities_content_ref; \
1505         ALTER TABLE entities DROP COLUMN content_ref;",
1506    )?;
1507    conn.execute(
1508        "UPDATE attachment_cutover_state \
1509         SET state = 'complete', completed_at = ?1 \
1510         WHERE singleton = 1 AND state = 'incomplete'",
1511        [now],
1512    )?;
1513    Ok(())
1514}
1515
1516fn record_attachment_cutover_migration(conn: &Connection, now: i64) -> Result<(), SqliteError> {
1517    let migration = MIGRATIONS
1518        .iter()
1519        .find(|migration| migration.version == ATTACHMENT_CUTOVER_VERSION)
1520        .expect("V21 migration must be registered");
1521    conn.execute(
1522        "INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?1, ?2, ?3)",
1523        rusqlite::params![migration.version, migration.name, now],
1524    )?;
1525    Ok(())
1526}
1527
1528/// Atomically switch an explicitly staged database to attachment-only V21.
1529///
1530/// The caller must still hold the canonical database GC owner. The exclusive
1531/// transition revalidates every legacy and attachment reference, verifies
1532/// moodboard model role coverage, replaces the claim fences, removes the old
1533/// column, marks the cutover complete, and records V21 in one transaction.
1534pub fn finalize_attachment_cutover(conn: &mut Connection) -> Result<(), SqliteError> {
1535    let admission = WriteAdmission::for_canonical_path(canonical_connection_database_path(conn)?)?;
1536    RawMigrationWriteUnit::new(conn, &admission)?
1537        .run(|conn| finalize_attachment_cutover_with_admission(conn, &admission))
1538}
1539
1540/// Finalize attachment cutover with an explicit raw-connection policy.
1541pub fn finalize_attachment_cutover_with_policy(
1542    conn: &mut Connection,
1543    policy: &MigrationWritePolicy,
1544) -> Result<(), SqliteError> {
1545    let admission =
1546        WriteAdmission::for_migration_policy(canonical_connection_database_path(conn)?, policy)?;
1547    RawMigrationWriteUnit::new(conn, &admission)?
1548        .run(|conn| finalize_attachment_cutover_with_admission(conn, &admission))
1549}
1550
1551/// Finalize attachment cutover using admission already held by a pooled caller.
1552pub(crate) fn finalize_attachment_cutover_with_admission(
1553    conn: &mut Connection,
1554    admission: &WriteAdmission,
1555) -> Result<(), SqliteError> {
1556    if attachment_cutover_status(conn)? == AttachmentCutoverStatus::Complete {
1557        return Ok(());
1558    }
1559    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Exclusive)?;
1560    if let Err(error) = admission.check() {
1561        let rollback = tx.rollback();
1562        return Err(capacity_refusal_after_rollback(
1563            conn,
1564            rollback,
1565            error,
1566            "attachment cutover finalization",
1567        ));
1568    }
1569    match attachment_cutover_status(&tx)? {
1570        AttachmentCutoverStatus::Complete => return Ok(()),
1571        AttachmentCutoverStatus::Pending => {
1572            return Err(SqliteError::InvalidData(
1573                "attachment cutover must complete stage 1 before finalization".into(),
1574            ))
1575        }
1576        AttachmentCutoverStatus::Incomplete => {}
1577    }
1578    let now = chrono::Utc::now().timestamp_micros();
1579    finalize_attachment_cutover_on_connection(&tx, now)?;
1580    record_attachment_cutover_migration(&tx, now)?;
1581    tx.commit()?;
1582    Ok(())
1583}
1584
1585/// Read the ordered migration ledger prefix without interpreting its rows.
1586fn read_applied_migration_ledger(
1587    conn: &Connection,
1588    through_version: u32,
1589) -> Result<Vec<(u32, String)>, SqliteError> {
1590    let mut stmt = conn.prepare(
1591        "SELECT version, name FROM _schema_migrations \
1592         WHERE version <= ?1 ORDER BY version ASC",
1593    )?;
1594    let rows = stmt
1595        .query_map([through_version], |row| {
1596            Ok((row.get::<_, u32>(0)?, row.get::<_, String>(1)?))
1597        })?
1598        .collect::<Result<Vec<_>, _>>()?;
1599    Ok(rows)
1600}
1601
1602/// Require the applied versions through `through_version` to be the exact
1603/// contiguous canonical prefix of [`MIGRATIONS`]. A matching `MAX(version)` is
1604/// insufficient: a missing middle row or foreign version can expose a
1605/// materially different schema while retaining the same maximum.
1606fn validate_applied_migration_versions(
1607    applied: &[(u32, String)],
1608    through_version: u32,
1609) -> Result<(), SqliteError> {
1610    let expected: Vec<&VersionedMigration> = MIGRATIONS
1611        .iter()
1612        .filter(|migration| migration.version <= through_version)
1613        .collect();
1614    let mut applied_index = 0;
1615
1616    for migration in expected {
1617        let Some((version, applied_name)) = applied.get(applied_index) else {
1618            return Err(SqliteError::InvalidData(format!(
1619                "migration history is missing version {} ('{}'); the applied ledger must be \
1620                 the exact contiguous canonical sequence through version {through_version}",
1621                migration.version, migration.name,
1622            )));
1623        };
1624        if *version < migration.version {
1625            return Err(SqliteError::InvalidData(format!(
1626                "migration history contains unknown version {version} recorded as \
1627                 '{applied_name}'; the applied ledger must contain only canonical versions"
1628            )));
1629        }
1630        if *version > migration.version {
1631            return Err(SqliteError::InvalidData(format!(
1632                "migration history is missing version {} ('{}'); found version {version} \
1633                 next instead",
1634                migration.version, migration.name,
1635            )));
1636        }
1637        applied_index += 1;
1638    }
1639
1640    if let Some((version, name)) = applied.get(applied_index) {
1641        return Err(SqliteError::InvalidData(format!(
1642            "migration history contains unknown version {version} recorded as '{name}'; \
1643             the applied ledger must contain only canonical versions"
1644        )));
1645    }
1646
1647    Ok(())
1648}
1649
1650fn validate_applied_migration_names(
1651    applied: &[(u32, String)],
1652    through_version: u32,
1653    allow_known_v19_repairs: bool,
1654) -> Result<(), SqliteError> {
1655    for ((version, applied_name), migration) in applied.iter().zip(
1656        MIGRATIONS
1657            .iter()
1658            .filter(|migration| migration.version <= through_version),
1659    ) {
1660        debug_assert_eq!(*version, migration.version);
1661        if migration.name != applied_name.as_str() {
1662            if allow_known_v19_repairs && matches!(*version, 13 | 14) {
1663                continue;
1664            }
1665            return Err(SqliteError::InvalidData(format!(
1666                "migration version {version} is recorded under name '{applied_name}', \
1667                 expected '{expected}'. This database's migration history does not match \
1668                 the current binary; recreate it from the current schema or repair the \
1669                 specific known divergence via a dedicated migration.",
1670                expected = migration.name,
1671            )));
1672        }
1673    }
1674
1675    Ok(())
1676}
1677
1678/// Confirm the complete applied ledger is the canonical prefix, including
1679/// names. The only historical V13/V14 name divergence is repaired by V19
1680/// before this validator runs for a pre-V19 database.
1681fn validate_applied_migration_ledger(
1682    conn: &Connection,
1683    through_version: u32,
1684) -> Result<(), SqliteError> {
1685    let applied = read_applied_migration_ledger(conn, through_version)?;
1686    validate_applied_migration_versions(&applied, through_version)?;
1687    validate_applied_migration_names(&applied, through_version, false)
1688}
1689
1690const MIGRATION_TRACKING_TABLE: &str = include_str!("../sql/schema-migrations-table.sql");
1691
1692const SCHEMA_VERSION_PROBE_SQL: &str = "SELECT COALESCE(MAX(version), 0) FROM _schema_migrations";
1693
1694/// Build the schema-ledger version query without opening a reader or decoding its result.
1695pub fn schema_version_probe() -> khive_storage::types::SqlStatement {
1696    khive_storage::types::SqlStatement::new(SCHEMA_VERSION_PROBE_SQL, Vec::new())
1697}
1698
1699/// Read the applied schema version from an open connection **without** running
1700/// migrations. Returns 0 when the `_schema_migrations` ledger is absent (an
1701/// un-migrated or empty database); any other failure (BUSY, IO) propagates —
1702/// collapsing it to 0 would misreport a live database as un-migrated. Never
1703/// writes.
1704pub fn read_schema_version(conn: &Connection) -> Result<u32, SqliteError> {
1705    match conn.query_row(SCHEMA_VERSION_PROBE_SQL, [], |row| row.get(0)) {
1706        Ok(version) => Ok(version),
1707        Err(rusqlite::Error::SqliteFailure(_, Some(ref msg)))
1708            if msg.contains("no such table: _schema_migrations") =>
1709        {
1710            Ok(0)
1711        }
1712        Err(e) => Err(e.into()),
1713    }
1714}
1715
1716/// Open `path` read-only and report its applied schema version without creating
1717/// or migrating the file. The caller must ensure `path` exists — opening a
1718/// missing file read-only errors rather than creating it. This is the path used
1719/// by schema-inspection commands that must not mutate the database.
1720pub fn inspect_schema_version(path: &std::path::Path) -> Result<u32, SqliteError> {
1721    let conn = crate::pool::open_read_only_snapshot_connection(path)?;
1722    read_schema_version(&conn)
1723}
1724
1725/// Open `path` read-only and require the exact canonical current ledger and
1726/// physical cutover state, without creating files or applying migrations.
1727pub fn inspect_schema_is_current(path: &std::path::Path) -> Result<u32, SqliteError> {
1728    let conn = crate::pool::open_read_only_snapshot_connection(path)?;
1729    validate_schema_is_current(&conn)
1730}
1731
1732/// Page accounting for one database file. Each value is a single pragma read,
1733/// so the cost does not grow with the file.
1734#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1735pub struct PageAccounting {
1736    /// `PRAGMA page_size`, in bytes.
1737    pub page_size: u64,
1738    /// `PRAGMA page_count`: every page in the database, free pages included.
1739    pub page_count: u64,
1740    /// `PRAGMA freelist_count`: pages that later writes can reuse but that stay
1741    /// in the file until a `VACUUM`.
1742    pub freelist_count: u64,
1743}
1744
1745/// Open `path` read-only and report its page accounting without creating,
1746/// migrating or walking the file. The caller must ensure `path` exists.
1747pub fn inspect_page_accounting(path: &std::path::Path) -> Result<PageAccounting, SqliteError> {
1748    let conn = crate::pool::open_read_only_snapshot_connection(path)?;
1749    let read = |pragma: &str| -> Result<u64, SqliteError> {
1750        let value: i64 = conn.query_row(pragma, [], |row| row.get(0))?;
1751        u64::try_from(value)
1752            .map_err(|_| SqliteError::InvalidData(format!("{pragma} returned {value}")))
1753    };
1754    Ok(PageAccounting {
1755        page_size: read("PRAGMA page_size")?,
1756        page_count: read("PRAGMA page_count")?,
1757        freelist_count: read("PRAGMA freelist_count")?,
1758    })
1759}
1760
1761/// Open `path` read-only and run `PRAGMA integrity_check` over the whole file,
1762/// returning every row SQLite reports: exactly `["ok"]` for a sound file. The
1763/// check reads every page, so its cost grows with the file. No error limit is
1764/// applied: the pragma's default stops at 100 rows, so the largest limit it
1765/// accepts is passed instead.
1766pub fn inspect_integrity(path: &std::path::Path) -> Result<Vec<String>, SqliteError> {
1767    let conn = crate::pool::open_read_only_snapshot_connection(path)?;
1768    let mut statement = conn.prepare(&format!("PRAGMA integrity_check({})", i32::MAX))?;
1769    let rows = statement
1770        .query_map([], |row| row.get::<_, String>(0))?
1771        .collect::<Result<Vec<_>, _>>()?;
1772    Ok(rows)
1773}
1774
1775/// Require an already-open database to match this build's latest core schema
1776/// without applying migrations.
1777///
1778/// A read-only snapshot behind the current migration set cannot be repaired in
1779/// place, while a snapshot ahead of the binary may contain schema this build
1780/// does not understand. Both directions fail with an actionable diagnostic; an
1781/// exact match performs no writes.
1782pub fn validate_schema_is_current(conn: &Connection) -> Result<u32, SqliteError> {
1783    let current_version = read_schema_version(conn)?;
1784    let latest_version = latest_schema_version();
1785
1786    if current_version < latest_version {
1787        return Err(SqliteError::InvalidData(format!(
1788            "read-only database schema version {current_version} is behind the latest known \
1789             migration {latest_version}; migrate a writable copy with this build before opening \
1790             the snapshot read-only"
1791        )));
1792    }
1793    if current_version > latest_version {
1794        return Err(SqliteError::InvalidData(format!(
1795            "read-only database schema version {current_version} is ahead of the latest known \
1796             migration {latest_version}; use a compatible newer build or recreate the snapshot"
1797        )));
1798    }
1799
1800    // Numeric equality alone is not enough: a database can carry the current
1801    // maximum version under renamed or foreign migration ledger entries while
1802    // exposing a materially different schema. Writable boot runs this same
1803    // closed-name validation in `bootstrap_migration_ledger`; snapshot inspection
1804    // must not accept a history that ordinary boot would reject merely because
1805    // it cannot repair it in place.
1806    validate_applied_migration_ledger(conn, current_version)?;
1807    // `>=`, not `==`: later migrations (V22+) record on top of a completed
1808    // cutover, and a ledger at the latest version must not exempt the
1809    // physical cutover state from validation.
1810    if current_version >= ATTACHMENT_CUTOVER_VERSION
1811        && attachment_cutover_status(conn)? != AttachmentCutoverStatus::Complete
1812    {
1813        return Err(SqliteError::InvalidData(
1814            "read-only database has not completed the V21 attachment cutover".into(),
1815        ));
1816    }
1817
1818    if current_version >= MEMORY_VISIBILITY_CUTOVER_VERSION {
1819        memory_visibility::validate_cutover(conn)?;
1820    }
1821
1822    Ok(current_version)
1823}
1824
1825/// Require the complete core migration ledger and readable memory provenance
1826/// schema without applying migrations or inferring an individual note's epoch.
1827pub fn validate_memory_visibility_cutover(conn: &Connection) -> Result<(), SqliteError> {
1828    validate_schema_is_current(conn).map(|_| ())
1829}
1830
1831#[cfg(test)]
1832pub(crate) mod test_sync {
1833    use std::sync::atomic::AtomicU32;
1834    use std::sync::{Arc, Barrier, Mutex};
1835
1836    /// When set, `run_versioned_migrations` parks after its initial (stale)
1837    /// ledger read until every racing thread has arrived — forcing the
1838    /// contended interleaving the concurrent-boot test asserts on.
1839    pub(crate) static STALE_READ_BARRIER: Mutex<Option<Arc<Barrier>>> = Mutex::new(None);
1840    /// Counts entries into the under-lock sibling fast-forward branch.
1841    pub(crate) static LOCKED_FAST_FORWARDS: AtomicU32 = AtomicU32::new(0);
1842    /// Set by the SQLite busy handler installed on participating connections:
1843    /// `true` means SQLite itself reported a blocked lock acquisition to the
1844    /// loser — actual contention, not merely an intended attempt.
1845    pub(crate) static BUSY_OBSERVED: std::sync::atomic::AtomicBool =
1846        std::sync::atomic::AtomicBool::new(false);
1847
1848    /// Busy handler for participating test connections: records that SQLite
1849    /// observed a busy acquisition, then keeps retrying.
1850    pub(crate) fn record_busy(_count: i32) -> bool {
1851        BUSY_OBSERVED.store(true, std::sync::atomic::Ordering::SeqCst);
1852        std::thread::sleep(std::time::Duration::from_millis(1));
1853        true
1854    }
1855
1856    /// Set by the winner immediately before committing its first migration
1857    /// transaction — i.e. before the write lock is first released.
1858    pub(crate) static WINNER_COMMITTED: std::sync::atomic::AtomicBool =
1859        std::sync::atomic::AtomicBool::new(false);
1860    /// Recorded by the loser when its first `BEGIN IMMEDIATE` returns: whether
1861    /// the winner had already committed at that moment. `true` is direct
1862    /// evidence the loser's lock acquisition blocked across the winner's held
1863    /// write lock rather than the two calls serializing by scheduler accident.
1864    pub(crate) static LOSER_SAW_WINNER_COMMIT: std::sync::atomic::AtomicBool =
1865        std::sync::atomic::AtomicBool::new(false);
1866
1867    std::thread_local! {
1868        /// Opt-in flag: only threads that set this participate in the barrier,
1869        /// so unrelated tests migrating in parallel are never parked.
1870        pub(crate) static PARTICIPATE: std::cell::Cell<bool> =
1871            const { std::cell::Cell::new(false) };
1872        /// Whether this thread has already instrumented its first BEGIN.
1873        pub(crate) static FIRST_BEGIN_DONE: std::cell::Cell<bool> =
1874            const { std::cell::Cell::new(false) };
1875    }
1876}
1877
1878/// Apply the ordinary unapplied migration prefix in order.
1879///
1880/// The operation is idempotent and each ordinary migration runs in its own
1881/// transaction. V21 is the application-assisted exception: a database with no
1882/// legacy content references may complete V21 atomically here, while a legacy
1883/// database stops successfully at V20 so the async host can stage, verify, and
1884/// finalize the attachment cutover. Errors on a non-contiguous migration array,
1885/// a non-canonical applied ledger, or a failed migration.
1886fn canonical_connection_database_path(conn: &Connection) -> Result<Option<PathBuf>, SqliteError> {
1887    let configured = conn.path().unwrap_or_default();
1888    let raw_path = if configured.is_empty() {
1889        conn.query_row(
1890            "SELECT file FROM pragma_database_list WHERE name = 'main'",
1891            [],
1892            |row| row.get::<_, String>(0),
1893        )?
1894    } else {
1895        configured.to_string()
1896    };
1897
1898    if raw_path.is_empty() {
1899        return Ok(None);
1900    }
1901    let canonical = std::fs::canonicalize(&raw_path).map_err(SqliteError::Io)?;
1902    #[cfg(any(unix, windows))]
1903    crate::pool::opened_sqlite_file_identity(conn, &canonical)?;
1904    Ok(Some(canonical))
1905}
1906
1907fn validate_database_gc_owner(
1908    conn: &Connection,
1909    owner: &DatabaseGcOwnerGuard,
1910) -> Result<(), SqliteError> {
1911    let connection_path = canonical_connection_database_path(conn)?;
1912    if owner.database_path() != connection_path.as_deref() {
1913        return Err(SqliteError::InvalidData(format!(
1914            "database GC owner targets {:?}, but migration connection targets {:?}",
1915            owner.database_path(),
1916            connection_path.as_deref(),
1917        )));
1918    }
1919    Ok(())
1920}
1921
1922pub fn run_migrations(conn: &mut Connection) -> Result<u32, SqliteError> {
1923    let database_path = canonical_connection_database_path(conn)?;
1924    let admission = WriteAdmission::for_canonical_path(database_path.clone())?;
1925    run_raw_migrations_with_admission(conn, database_path, &admission)
1926}
1927
1928/// Run migrations on a raw connection with a captured admission policy.
1929pub fn run_migrations_with_policy(
1930    conn: &mut Connection,
1931    policy: &MigrationWritePolicy,
1932) -> Result<u32, SqliteError> {
1933    let database_path = canonical_connection_database_path(conn)?;
1934    let admission = WriteAdmission::for_migration_policy(database_path.clone(), policy)?;
1935    run_raw_migrations_with_admission(conn, database_path, &admission)
1936}
1937
1938fn run_raw_migrations_with_admission(
1939    conn: &mut Connection,
1940    database_path: Option<PathBuf>,
1941    admission: &WriteAdmission,
1942) -> Result<u32, SqliteError> {
1943    if let Some(database_path) = database_path {
1944        // This raw API may have been handed a connection behind an opaque pool
1945        // writer guard. Never wait here and invert the canonical
1946        // owner-before-writer order; fail closed and direct production callers
1947        // to `StorageBackend::prepare_core_schema` instead.
1948        let owner = try_acquire_database_gc_owner_for_path(database_path).map_err(|error| {
1949            SqliteError::InvalidData(format!(
1950                "failed to acquire database GC owner before schema migration: {error}"
1951            ))
1952        })?;
1953        return run_migrations_with_database_gc_owner(
1954            &mut RawMigrationTransactions::new(conn, admission),
1955            &owner,
1956            admission,
1957        );
1958    }
1959
1960    // A raw in-memory connection has no durable/cross-process GC domain. The
1961    // production in-memory backend still uses the owner-aware path below.
1962    run_versioned_migrations(
1963        &mut RawMigrationTransactions::new(conn, admission),
1964        None,
1965        admission,
1966    )
1967}
1968
1969pub(crate) fn run_migrations_with_database_gc_owner(
1970    writes: &mut impl MigrationTransactions,
1971    owner: &DatabaseGcOwnerGuard,
1972    admission: &WriteAdmission,
1973) -> Result<u32, SqliteError> {
1974    run_versioned_migrations(writes, Some(owner), admission)
1975}
1976
1977/// Raise-only to a 5s busy_timeout floor for one admitted migration unit and
1978/// restore the caller's value after it. Concurrent boots (multiple processes
1979/// migrating the same file) contend on SQLite's write lock; a short hot-path
1980/// busy_timeout cannot wait out a sibling's migration, and a caller whose
1981/// configured timeout is already longer is never reduced.
1982fn with_migration_busy_timeout<T>(
1983    conn: &mut Connection,
1984    operation: impl FnOnce(&mut Connection) -> Result<T, SqliteError>,
1985) -> Result<T, SqliteError> {
1986    let prior_busy_ms: i64 = conn.query_row("PRAGMA busy_timeout", [], |row| row.get(0))?;
1987    let raised = prior_busy_ms < 5_000;
1988    if raised {
1989        conn.busy_timeout(std::time::Duration::from_secs(5))?;
1990    }
1991    let result = operation(conn);
1992    if raised {
1993        let _ = conn.busy_timeout(std::time::Duration::from_millis(prior_busy_ms.max(0) as u64));
1994    }
1995    result
1996}
1997
1998/// What one admitted versioned-migration transaction did.
1999enum MigrationStep {
2000    /// This transaction applied the migration and committed.
2001    Applied,
2002    /// A sibling had already recorded this version or later; the value is the
2003    /// ledger maximum read under the write lock.
2004    AppliedBySibling(u32),
2005    /// V21 on a legacy database: left for the application-assisted cutover.
2006    Deferred,
2007}
2008
2009/// Bring the core schema to the latest version.
2010///
2011/// ADR-154 section 4 admits each migration transaction on its own, so the
2012/// ledger bootstrap with the pre-lock ledger read is one admitted unit and
2013/// every migration that still has to run is another, re-reading the ledger
2014/// under the write lock. No volume lease is held from one version to the next.
2015fn run_versioned_migrations(
2016    writes: &mut impl MigrationTransactions,
2017    owner: Option<&DatabaseGcOwnerGuard>,
2018    admission: &WriteAdmission,
2019) -> Result<u32, SqliteError> {
2020    let current_version = writes.admitted(|conn| {
2021        if let Some(owner) = owner {
2022            validate_database_gc_owner(conn, owner)?;
2023        }
2024        with_migration_busy_timeout(conn, |conn| bootstrap_migration_ledger(conn, admission))
2025    })?;
2026
2027    // Deterministic-contention hook: parks every caller after the stale ledger
2028    // read (no SQLite lock and no volume lease held) until all racing test
2029    // threads have observed it, so they are then released to compete for the
2030    // IMMEDIATE write lock of their first migration.
2031    #[cfg(test)]
2032    if test_sync::PARTICIPATE.with(|p| p.get()) {
2033        let barrier = test_sync::STALE_READ_BARRIER.lock().unwrap().clone();
2034        if let Some(barrier) = barrier {
2035            barrier.wait();
2036        }
2037    }
2038    let latest_version = latest_schema_version();
2039
2040    let mut applied_version = current_version;
2041    // Floor advanced when a sibling's work is observed under the write lock,
2042    // so a losing process skips the remaining already-applied migrations
2043    // without opening a transaction for each.
2044    let mut skip_through = current_version;
2045
2046    for migration in MIGRATIONS {
2047        if migration.version <= skip_through {
2048            applied_version = applied_version.max(migration.version);
2049            continue;
2050        }
2051        let step = writes.admitted(|conn| {
2052            with_migration_busy_timeout(conn, |conn| {
2053                apply_versioned_migration(conn, migration, admission, latest_version)
2054            })
2055        })?;
2056        match step {
2057            MigrationStep::Applied => applied_version = migration.version,
2058            MigrationStep::AppliedBySibling(sibling_version) => {
2059                skip_through = sibling_version.min(latest_version);
2060                applied_version = applied_version.max(migration.version);
2061            }
2062            MigrationStep::Deferred => break,
2063        }
2064    }
2065
2066    // Validate again after the loop: our own commits and any under-lock
2067    // sibling fast-forward must both leave the exact canonical ledger, not
2068    // merely advance its maximum version.
2069    writes.admitted(|conn| validate_applied_migration_ledger(conn, applied_version))?;
2070
2071    Ok(applied_version)
2072}
2073
2074/// Create the migration ledger if it is missing and validate what it records,
2075/// returning the recorded version. The read is taken before any migration
2076/// write lock; each migration re-reads the ledger under that lock.
2077fn bootstrap_migration_ledger(
2078    conn: &mut Connection,
2079    admission: &WriteAdmission,
2080) -> Result<u32, SqliteError> {
2081    admission.check()?;
2082    conn.execute_batch(MIGRATION_TRACKING_TABLE)?;
2083    require_autocommit(conn, "migration-tracking bootstrap")?;
2084
2085    let current_version: u32 = read_schema_version(conn)?;
2086
2087    // A database whose recorded version is ahead of the latest known migration
2088    // predates the consolidated V1 baseline (ADR-015) — e.g. it still carries the
2089    // pre-consolidation V2..V22 ledger — or was written by a newer build. Either
2090    // way the baseline schema would be silently skipped, leaving the process on a
2091    // stale schema. Fail loudly instead of corrupting silently.
2092    let latest_version = latest_schema_version();
2093    if current_version > latest_version {
2094        return Err(SqliteError::InvalidData(format!(
2095            "database schema version {current_version} is ahead of the latest known migration \
2096             {latest_version}. This database predates the consolidated baseline (ADR-015) or was \
2097             written by a newer build. Recreate it from the current schema; in-place downgrade is \
2098             not supported."
2099        )));
2100    }
2101
2102    // Every writable upgrade starts from an exact canonical version sequence;
2103    // fail before applying new migrations if MAX(version) hides a missing or
2104    // foreign row. A pre-V19 database may still carry the V13/V14 name
2105    // divergence that V19 exists to repair. Name validation therefore permits
2106    // exactly those two rows before V19, while every unrelated mismatch still
2107    // fails before any new migration is applied.
2108    let applied = read_applied_migration_ledger(conn, current_version)?;
2109    validate_applied_migration_versions(&applied, current_version)?;
2110    validate_applied_migration_names(&applied, current_version, current_version < 19)?;
2111
2112    Ok(current_version)
2113}
2114
2115/// Apply one versioned migration in its own IMMEDIATE transaction, probing
2116/// capacity after BEGIN and before its first statement (ADR-154 section 4).
2117fn apply_versioned_migration(
2118    conn: &mut Connection,
2119    migration: &VersionedMigration,
2120    admission: &WriteAdmission,
2121    latest_version: u32,
2122) -> Result<MigrationStep, SqliteError> {
2123    // IMMEDIATE: take the write lock up front so concurrent boots serialize
2124    // here instead of failing mid-migration when a DEFERRED transaction
2125    // upgrades to a write.
2126    #[cfg(test)]
2127    let instrumented_first_begin =
2128        test_sync::PARTICIPATE.with(|p| p.get()) && !test_sync::FIRST_BEGIN_DONE.with(|f| f.get());
2129    #[cfg(test)]
2130    if instrumented_first_begin {
2131        test_sync::FIRST_BEGIN_DONE.with(|f| f.set(true));
2132    }
2133    // Replaces the busy_timeout raised for this unit on a participating test
2134    // connection: records SQLite-observed contention, then keeps retrying.
2135    #[cfg(test)]
2136    if test_sync::PARTICIPATE.with(|p| p.get()) {
2137        conn.busy_handler(Some(test_sync::record_busy))?;
2138    }
2139    let tx = conn
2140        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
2141        .map_err(|e| SqliteError::migration(migration.version, e))?;
2142    if let Err(error) = admission.check() {
2143        let rollback = tx.rollback();
2144        return Err(capacity_refusal_after_rollback(
2145            conn,
2146            rollback,
2147            error,
2148            "core schema migration",
2149        ));
2150    }
2151
2152    // Re-check under the write lock: a sibling process may have applied
2153    // this migration (and possibly later ones) while we waited. Running
2154    // its DDL again would fail; fast-forward past everything it applied.
2155    let sibling_version: u32 = tx
2156        .query_row(SCHEMA_VERSION_PROBE_SQL, [], |row| row.get(0))
2157        .map_err(|e| SqliteError::migration(migration.version, e))?;
2158    #[cfg(test)]
2159    if instrumented_first_begin {
2160        use std::sync::atomic::Ordering::SeqCst;
2161        if sibling_version == 0 {
2162            // Winner: hold the write lock until SQLite has reported a
2163            // busy acquisition to the loser (its busy handler fired) —
2164            // proof the loser's BEGIN is actually blocked on this held
2165            // lock, not merely intended. Bounded so a regression fails
2166            // the assertion instead of hanging the test.
2167            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2168            while !test_sync::BUSY_OBSERVED.load(SeqCst) && std::time::Instant::now() < deadline {
2169                std::thread::yield_now();
2170            }
2171        } else {
2172            // Loser: our first BEGIN just returned. Record whether the
2173            // winner had already committed — true means we blocked across
2174            // its held lock.
2175            test_sync::LOSER_SAW_WINNER_COMMIT
2176                .store(test_sync::WINNER_COMMITTED.load(SeqCst), SeqCst);
2177        }
2178    }
2179
2180    // The ahead-of-latest guard above ran on a pre-lock read; a newer
2181    // build may have committed a version past ours while we waited for
2182    // the write lock. Accepting it (clamped) would return Ok on a schema
2183    // this binary does not understand — reject it the same way.
2184    if sibling_version > latest_version {
2185        return Err(SqliteError::InvalidData(format!(
2186            "database schema version {sibling_version} is ahead of the latest known \
2187             migration {latest_version} (committed by a concurrent process while this \
2188             one waited for the migration write lock). This build cannot run against \
2189             the newer schema; upgrade the binary or recreate the database."
2190        )));
2191    }
2192
2193    if sibling_version >= migration.version {
2194        #[cfg(test)]
2195        test_sync::LOCKED_FAST_FORWARDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2196        return Ok(MigrationStep::AppliedBySibling(sibling_version));
2197    }
2198
2199    if migration.version == 46 {
2200        memory_visibility::capture_pre_v46(&tx)
2201            .map_err(|error| SqliteError::migration(migration.version, error))?;
2202        #[cfg(test)]
2203        memory_visibility::test_state::stop_at(memory_visibility::test_state::Stop::AfterCapture)?;
2204    }
2205
2206    if migration.version == ATTACHMENT_CUTOVER_VERSION {
2207        let status = attachment_cutover_status(&tx)
2208            .map_err(|e| SqliteError::migration(migration.version, e))?;
2209        let defers = cutover_defers(&tx, status)
2210            .map_err(|e| SqliteError::migration(migration.version, e))?;
2211
2212        // V21 belongs to the boot coordinator. Ordinary backend open may
2213        // finish the degenerate zero-ref case atomically, but it must not
2214        // expose a dual-source interval or eagerly stage a legacy DB.
2215        if defers {
2216            drop(tx);
2217            return Ok(MigrationStep::Deferred);
2218        }
2219        if status != AttachmentCutoverStatus::Pending {
2220            return Err(SqliteError::migration_message(
2221                migration.version,
2222                format!("unexpected attachment cutover state {status:?}"),
2223            ));
2224        }
2225
2226        let now = chrono::Utc::now().timestamp_micros();
2227        stage_attachment_cutover_on_connection(&tx, now)
2228            .map_err(|e| SqliteError::migration(migration.version, e))?;
2229        finalize_attachment_cutover_on_connection(&tx, now)
2230            .map_err(|e| SqliteError::migration(migration.version, e))?;
2231    } else if migration.version == 36 {
2232        // The events store DDL may already have added these columns.
2233        crate::stores::event::ensure_operation_attribution_columns(&tx)
2234            .map_err(|error| SqliteError::migration(migration.version, error))?;
2235    } else if migration.version == 44 {
2236        migrate_outbound_due_key(&tx)
2237            .map_err(|error| SqliteError::migration(migration.version, error))?;
2238    } else if migration.version == 48 {
2239        migrate_acknowledgement_journal(&tx)
2240            .map_err(|error| SqliteError::migration(migration.version, error))?;
2241    } else if migration.version == 58 {
2242        migrate_proposal_archive(&tx)?;
2243    } else if migration.version == 66 {
2244        migrate_undelivered_due_index(&tx)
2245            .map_err(|error| SqliteError::migration(migration.version, error))?;
2246    } else if migration.name == SESSION_IDENTITY_MIGRATION_NAME {
2247        tx.execute_batch(migration.up)
2248            .map_err(|error| SqliteError::migration(migration.version, error))?;
2249        session_identity_migration::apply(&tx)
2250            .map_err(|error| SqliteError::migration(migration.version, error))?;
2251    } else {
2252        tx.execute_batch(migration.up)
2253            .map_err(|e| SqliteError::migration(migration.version, e))?;
2254    }
2255
2256    let visibility_counts = if migration.version == MEMORY_VISIBILITY_CUTOVER_VERSION {
2257        Some(
2258            memory_visibility::cutover_counts(&tx)
2259                .map_err(|error| SqliteError::migration(migration.version, error))?,
2260        )
2261    } else {
2262        None
2263    };
2264
2265    // V19's repair contract includes normalizing the two known-divergent
2266    // recorded names. `_schema_migrations` is created and owned by this
2267    // runner (not by any migration file), so the normalization lives
2268    // here, in the same transaction that applies V19's SQL. Exact,
2269    // closed set — versions 13 and 14 only; any other (version, name)
2270    // mismatch still fails startup via validate_applied_migration_ledger.
2271    if migration.version == 19 {
2272        tx.execute_batch(
2273            "UPDATE _schema_migrations SET name = 'list_cursor_sequences' WHERE version = 13;\n\
2274             UPDATE _schema_migrations SET name = 'graph_edges_id_unique' WHERE version = 14;",
2275        )
2276        .map_err(|e| SqliteError::migration(migration.version, e))?;
2277    }
2278
2279    let now = chrono::Utc::now().timestamp_micros();
2280    tx.execute(
2281        "INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?1, ?2, ?3) \
2282         ON CONFLICT(version) DO NOTHING",
2283        rusqlite::params![migration.version, migration.name, now],
2284    )
2285    .map_err(|e| SqliteError::migration(migration.version, e))?;
2286
2287    #[cfg(test)]
2288    if instrumented_first_begin {
2289        test_sync::WINNER_COMMITTED.store(true, std::sync::atomic::Ordering::SeqCst);
2290    }
2291
2292    #[cfg(test)]
2293    if migration.version == MEMORY_VISIBILITY_CUTOVER_VERSION {
2294        memory_visibility::test_state::stop_at(
2295            memory_visibility::test_state::Stop::BeforeCutoverCommit,
2296        )?;
2297    }
2298    tx.commit()
2299        .map_err(|e| SqliteError::migration(migration.version, e))?;
2300    if let Some(counts) = visibility_counts {
2301        memory_visibility::log_counts(&counts, conn.path().unwrap_or(":memory:"));
2302    }
2303    #[cfg(test)]
2304    if migration.version == 46 {
2305        memory_visibility::test_state::stop_at(
2306            memory_visibility::test_state::Stop::AfterV46Commit,
2307        )?;
2308    }
2309
2310    Ok(MigrationStep::Applied)
2311}
2312
2313#[derive(Debug)]
2314pub struct EmbeddingModelRegistryRecord {
2315    /// Vector engine name (e.g. `"paraphrase"`).
2316    pub engine_name: String,
2317    /// Model identifier (e.g. `"all-minilm-l6-v2"`).
2318    pub model_id: String,
2319    /// Canonical deduplication key combining engine and model.
2320    pub key_version: String,
2321    /// Embedding dimensionality.
2322    pub dimensions: u32,
2323    /// Lifecycle status (`"active"` or `"superseded"`).
2324    pub status: String,
2325    /// Epoch timestamp when the model was activated.
2326    pub activated_at: Option<i64>,
2327    /// Epoch timestamp when the model was superseded.
2328    pub superseded_at: Option<i64>,
2329}
2330
2331/// Query the `_embedding_models` registry.
2332///
2333/// Opens the database at `db` (defaults to `~/.khive/khive.db`) and
2334/// returns all registry rows, optionally filtered by `engine_name`.
2335/// Returns an empty vec if the database or table does not exist.
2336pub fn query_embedding_models(
2337    db: Option<&std::path::Path>,
2338    engine_filter: Option<&str>,
2339) -> Result<Vec<EmbeddingModelRegistryRecord>, SqliteError> {
2340    let path = db.map(std::path::Path::to_path_buf).unwrap_or_else(|| {
2341        std::env::var("HOME")
2342            .map(std::path::PathBuf::from)
2343            .unwrap_or_else(|_| std::path::PathBuf::from("."))
2344            .join(".khive/khive.db")
2345    });
2346    if !path.exists() {
2347        return Ok(Vec::new());
2348    }
2349    let conn = Connection::open_with_flags(
2350        path,
2351        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY
2352            | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX
2353            | rusqlite::OpenFlags::SQLITE_OPEN_URI,
2354    )?;
2355    query_embedding_models_conn(&conn, engine_filter)
2356}
2357
2358/// Query `_embedding_models` from an existing connection (testable without a file).
2359///
2360/// Returns an empty vec if the table does not exist.
2361pub(crate) fn query_embedding_models_conn(
2362    conn: &Connection,
2363    engine_filter: Option<&str>,
2364) -> Result<Vec<EmbeddingModelRegistryRecord>, SqliteError> {
2365    let exists: bool = conn.query_row(
2366        "SELECT COUNT(*) > 0 FROM sqlite_master \
2367         WHERE type='table' AND name='_embedding_models'",
2368        [],
2369        |row| row.get(0),
2370    )?;
2371    if !exists {
2372        return Ok(Vec::new());
2373    }
2374
2375    let sql = if engine_filter.is_some() {
2376        "SELECT engine_name, model_id, key_version, dim, status, activated_at, superseded_at \
2377         FROM _embedding_models WHERE engine_name = ?1 \
2378         ORDER BY engine_name, activated_at IS NULL, activated_at"
2379    } else {
2380        "SELECT engine_name, model_id, key_version, dim, status, activated_at, superseded_at \
2381         FROM _embedding_models \
2382         ORDER BY engine_name, activated_at IS NULL, activated_at"
2383    };
2384    let mut stmt = conn.prepare(sql)?;
2385    let map_row = |row: &rusqlite::Row<'_>| {
2386        let dim_raw: i64 = row.get(3)?;
2387        let dimensions = u32::try_from(dim_raw).map_err(|_| {
2388            rusqlite::Error::FromSqlConversionFailure(
2389                3,
2390                rusqlite::types::Type::Integer,
2391                Box::new(std::io::Error::other(format!(
2392                    "_embedding_models.dim value {dim_raw} is outside the valid u32 range [0, {}]",
2393                    u32::MAX,
2394                ))),
2395            )
2396        })?;
2397        Ok(EmbeddingModelRegistryRecord {
2398            engine_name: row.get(0)?,
2399            model_id: row.get(1)?,
2400            key_version: row.get(2)?,
2401            dimensions,
2402            status: row.get(4)?,
2403            activated_at: row.get(5)?,
2404            superseded_at: row.get(6)?,
2405        })
2406    };
2407
2408    if let Some(engine) = engine_filter {
2409        stmt.query_map([engine], map_row)?
2410            .collect::<Result<Vec<_>, _>>()
2411            .map_err(Into::into)
2412    } else {
2413        stmt.query_map([], map_row)?
2414            .collect::<Result<Vec<_>, _>>()
2415            .map_err(Into::into)
2416    }
2417}
2418
2419// Test fixtures use the public policy constructor and a private lock namespace.
2420#[cfg(test)]
2421pub(crate) fn migration_test_policy() -> MigrationWritePolicy {
2422    MigrationWritePolicy::new(
2423        crate::DiskGuardEnvironment::capture()
2424            .resolve(None, None)
2425            .expect("test disk policy"),
2426        crate::PoolConfig::for_test()
2427            .volume_lock_dir
2428            .expect("test volume-lock directory"),
2429    )
2430    .expect("valid test migration policy")
2431}
2432
2433#[cfg(test)]
2434pub(crate) fn run_migrations_for_test(conn: &mut Connection) -> Result<u32, SqliteError> {
2435    run_migrations_with_policy(conn, &migration_test_policy())
2436}
2437
2438#[cfg(test)]
2439fn apply_schema_plan_for_test(
2440    conn: &mut Connection,
2441    plan: &ServiceSchemaPlan,
2442) -> Result<(), SqliteError> {
2443    apply_schema_plan_with_policy(conn, plan, &migration_test_policy())
2444}
2445
2446#[cfg(test)]
2447fn stage_attachment_cutover_for_test(conn: &mut Connection) -> Result<(), SqliteError> {
2448    stage_attachment_cutover_with_policy(conn, &migration_test_policy())
2449}
2450
2451#[cfg(test)]
2452fn finalize_attachment_cutover_for_test(conn: &mut Connection) -> Result<(), SqliteError> {
2453    finalize_attachment_cutover_with_policy(conn, &migration_test_policy())
2454}
2455
2456// =============================================================================
2457// Tests
2458// =============================================================================
2459
2460#[cfg(test)]
2461#[path = "entity_version_migration_measurement.rs"]
2462mod entity_version_measurement;
2463
2464#[cfg(test)]
2465#[path = "migrations_tests.rs"]
2466mod tests;
2467
2468#[cfg(test)]
2469#[path = "raw_migration_settlement_tests.rs"]
2470mod raw_settlement_tests;
2471
2472#[cfg(test)]
2473#[path = "git_note_index_migration_tests.rs"]
2474mod git_note_indexes;
2475
2476#[cfg(test)]
2477#[path = "entity_list_index_migration_tests.rs"]
2478mod entity_list_indexes;
2479
2480#[cfg(test)]
2481#[path = "schedule_core_index_migration_tests.rs"]
2482mod schedule_core_index_migration_tests;
2483
2484#[cfg(test)]
2485#[path = "comm_core_index_migration_tests.rs"]
2486mod comm_core_index_migration_tests;
2487
2488#[cfg(test)]
2489#[path = "knowledge_cursor_tag_migration_tests.rs"]
2490mod knowledge_cursor_tag_migration_tests;