Skip to main content

mj_controller/database/
schema.rs

1use super::*;
2use rusqlite::OpenFlags;
3
4const COMPATIBILITY_METADATA_VERSION: i64 = 30;
5
6pub(super) struct SchemaState {
7    pub(super) revision: i64,
8    minimum_compatible: Option<i64>,
9}
10
11impl SchemaState {
12    pub(super) fn ensure_supported(&self) -> Result<()> {
13        self.ensure_supported_by(SCHEMA_VERSION)
14    }
15
16    fn ensure_supported_by(&self, supported: i64) -> Result<()> {
17        let reason = if self.revision < supported {
18            StoreSchemaMismatchReason::NeedsMigration
19        } else if let Some(minimum_compatible) = self.minimum_compatible {
20            if minimum_compatible <= supported {
21                return Ok(());
22            }
23            StoreSchemaMismatchReason::Incompatible { minimum_compatible }
24        } else {
25            StoreSchemaMismatchReason::InvalidCompatibilityMetadata
26        };
27        Err(StoreSchemaMismatch {
28            found: self.revision,
29            supported,
30            reason,
31        }
32        .into())
33    }
34}
35
36/// The revision, ledger, and compatibility floor must describe one snapshot.
37/// A missing floor is only legitimate before compatibility was introduced.
38pub(super) fn read_schema_state(connection: &Connection) -> Result<SchemaState> {
39    let snapshot = connection
40        .unchecked_transaction()
41        .context("start database compatibility snapshot")?;
42    let revision: i64 = snapshot
43        .query_row("PRAGMA user_version", [], |row| row.get(0))
44        .context("read database migration revision")?;
45    let minimum_compatible = if revision >= COMPATIBILITY_METADATA_VERSION {
46        let invalid = || StoreSchemaMismatch {
47            found: revision,
48            supported: SCHEMA_VERSION,
49            reason: StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
50        };
51        let (count, singleton, floor, recorded): (i64, Option<i64>, Option<i64>, Option<i64>) =
52            snapshot
53                .query_row(
54                    "SELECT count(*), min(singleton), min(minimum_compatible_version),
55                    (SELECT max(version) FROM schema_migrations)
56             FROM schema_compatibility",
57                    [],
58                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
59                )
60                .map_err(|error| {
61                    // Missing tables/columns and invalid field types are
62                    // structural. Busy, I/O, and interruption errors are not
63                    // evidence of an incompatible migration.
64                    let structural = match &error {
65                        rusqlite::Error::SqliteFailure(code, _) => {
66                            code.code == rusqlite::ErrorCode::Unknown
67                        }
68                        _ => true,
69                    };
70                    let error = anyhow::Error::new(error);
71                    if structural {
72                        error.context(invalid())
73                    } else {
74                        error.context("read database compatibility metadata")
75                    }
76                })?;
77        if count != 1
78            || singleton != Some(1)
79            || recorded != Some(revision)
80            || !floor
81                .is_some_and(|floor| (COMPATIBILITY_METADATA_VERSION..=revision).contains(&floor))
82        {
83            return Err(invalid().into());
84        }
85        floor
86    } else {
87        None
88    };
89    snapshot
90        .commit()
91        .context("finish database compatibility snapshot")?;
92    Ok(SchemaState {
93        revision,
94        minimum_compatible,
95    })
96}
97
98pub fn database_path() -> PathBuf {
99    data_dir().join("mj.sqlite3")
100}
101
102/// Verify that this client can read the daemon's store without creating or
103/// migrating it. Startup must pass this gate before handing out a connection,
104/// even when an older daemon happens to speak the same wire protocol.
105pub fn check_read_compatibility() -> Result<()> {
106    open_reader_strict(&database_path()).map(drop)
107}
108
109/// A writer-capable connection whose transactions take the WAL write lock at
110/// `BEGIN`, where the busy handler applies. A DEFERRED transaction that has
111/// already read cannot wait: SQLite only calls the busy handler when the
112/// connection holds no transaction, so the upgrade to a write returns
113/// `SQLITE_BUSY` at once (issue 1117).
114pub(super) fn open_writer(path: &Path) -> Result<Connection> {
115    let mut connection = open_writable(path)?;
116    connection.set_transaction_behavior(rusqlite::TransactionBehavior::Immediate);
117    Ok(connection)
118}
119
120fn open_writable(path: &Path) -> Result<Connection> {
121    if let Some(parent) = path.parent() {
122        fs::create_dir_all(parent)
123            .with_context(|| format!("create Mjolnir data directory {}", parent.display()))?;
124    }
125    let connection = Connection::open(path)
126        .with_context(|| format!("open Mjolnir database {}", path.display()))?;
127    connection.busy_timeout(Duration::from_secs(5))?;
128    connection.execute_batch(
129        "PRAGMA foreign_keys = ON;
130         PRAGMA journal_mode = WAL;
131         PRAGMA synchronous = FULL;",
132    )?;
133    verify_schema_once(path, &connection)?;
134    Ok(connection)
135}
136
137pub(super) fn open(path: &Path) -> Result<Connection> {
138    open_writer(path)
139}
140
141/// Open an existing database without permitting schema or data mutation.
142/// Client processes use this path so an accidental write fails locally
143/// instead of competing with the daemon's writer.
144#[cfg(not(test))]
145pub(super) fn open_reader(path: &Path) -> Result<Connection> {
146    open_reader_strict(path)
147}
148
149#[cfg(test)]
150pub(super) fn open_reader(path: &Path) -> Result<Connection> {
151    // Path-taking database helpers are migration fixtures in unit tests: they
152    // intentionally open old or not-yet-created schemas. Production query
153    // entry points compile against the strict reader above. The connection is
154    // writable but keeps SQLite's DEFERRED default, so a fixture read does not
155    // take the write lock.
156    open_writable(path)
157}
158
159#[cfg_attr(test, allow(dead_code))]
160fn open_reader_strict(path: &Path) -> Result<Connection> {
161    let connection = Connection::open_with_flags(
162        path,
163        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
164    )
165    .with_context(|| format!("open Mjolnir database read-only {}", path.display()))?;
166    connection.busy_timeout(Duration::from_secs(5))?;
167    connection.execute_batch(
168        "PRAGMA foreign_keys = ON;
169         PRAGMA query_only = ON;",
170    )?;
171    read_schema_state(&connection)?.ensure_supported()?;
172    Ok(connection)
173}
174
175/// Databases this process has already migrated. A controller owns its store
176/// exclusively (`ControllerStoreGuard`), so a schema verified once stays
177/// verified and later connections skip the migration probes entirely.
178fn verified_schemas() -> &'static Mutex<HashSet<PathBuf>> {
179    static VERIFIED: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
180    VERIFIED.get_or_init(|| Mutex::new(HashSet::new()))
181}
182
183/// Stable cache identity for a database. The file itself may not exist yet, so
184/// the canonicalized parent directory carries the identity.
185fn schema_cache_key(path: &Path) -> PathBuf {
186    let Some(parent) = path
187        .parent()
188        .filter(|parent| !parent.as_os_str().is_empty())
189    else {
190        return path.to_owned();
191    };
192    match (fs::canonicalize(parent), path.file_name()) {
193        (Ok(canonical), Some(name)) => canonical.join(name),
194        _ => path.to_owned(),
195    }
196}
197
198/// Run the migration ladder the first time this process opens a database.
199/// Later opens confirm compatibility without repeating schema repairs. A
200/// database behind this build is migrated again, so a recreated file under a
201/// reused path still converges. Compatible future stores are never repaired.
202fn verify_schema_once(path: &Path, connection: &Connection) -> Result<()> {
203    let key = schema_cache_key(path);
204    let mut verified = verified_schemas()
205        .lock()
206        .unwrap_or_else(PoisonError::into_inner);
207    let state = read_schema_state(connection)?;
208    if state.revision > SCHEMA_VERSION
209        || (state.revision == SCHEMA_VERSION && verified.contains(&key))
210    {
211        // An older build must never run its repairs against a newer schema.
212        return state.ensure_supported();
213    }
214    // Holding the lock across the ladder keeps two first opens of the same
215    // database from running the additive migration steps against each other.
216    migrate_schema(connection)?;
217    read_schema_state(connection)?.ensure_supported()?;
218    verified.insert(key);
219    Ok(())
220}
221
222/// Forget that this process verified a database's schema. Only tests need it:
223/// they simulate a store written by an older build by editing the schema of a
224/// database this process has already opened, which no controller can do.
225#[cfg(test)]
226pub(super) fn forget_verified_schema(path: &Path) {
227    verified_schemas()
228        .lock()
229        .unwrap_or_else(PoisonError::into_inner)
230        .remove(&schema_cache_key(path));
231}
232
233/// New stores start at the revision Mjolnir 2.7.2 shipped. Existing stores
234/// retain the complete migration path, even when users skip many releases.
235const BASELINE_SCHEMA_VERSION: i64 = 33;
236
237/// The compatibility floor a baseline store records. Migration 32 (ZCode) was
238/// the last breaking change before the baseline.
239const BASELINE_MINIMUM_COMPATIBLE_VERSION: i64 = 32;
240
241fn migrate_schema(connection: &Connection) -> Result<()> {
242    let state = read_schema_state(connection)?;
243    let version = state.revision;
244    if version > SCHEMA_VERSION {
245        return state.ensure_supported();
246    }
247    if version == 0 {
248        create_baseline_schema(connection)?;
249    } else if version < BASELINE_SCHEMA_VERSION {
250        super::legacy_schema::migrate_to_baseline(connection)
251            .context("upgrade historical database schema")?;
252    }
253    // Compatible: adds one table. Older readers ignore it and treat read-write
254    // mounts as copy-on-write, a behaviour difference rather than lost data.
255    // Older writers rewrite `session_mounts` but never touch this table, so its
256    // rows survive their updates; a row only applies while a mount with the same
257    // source and destination is still not read-only, so an older build that
258    // makes the mount read-only or removes it keeps that choice. The
259    // compatibility floor stays where it is.
260    if version < 34 {
261        connection.execute_batch(
262            "BEGIN IMMEDIATE;
263             CREATE TABLE IF NOT EXISTS session_mount_access (
264                 session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
265                 source BLOB NOT NULL,
266                 destination BLOB NOT NULL,
267                 access TEXT NOT NULL CHECK(access IN ('rw')),
268                 PRIMARY KEY(session_id, destination)
269             ) STRICT;
270             INSERT INTO schema_migrations(version, applied_at)
271                 VALUES (34, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
272             PRAGMA user_version = 34;
273             COMMIT;",
274        )?;
275    }
276    // Compatible: adds one nullable column. Older readers ignore it, and the
277    // older writer's session upsert lists columns explicitly, so it preserves
278    // the value. An older executable launching such a session uses the shared
279    // `/workspace` instead of the recorded per-session path, which is a
280    // behaviour difference, not data loss. The compatibility floor stays where
281    // it is.
282    if version < 35 {
283        connection.execute_batch(
284            "BEGIN IMMEDIATE;
285             ALTER TABLE sessions ADD COLUMN container_workspace TEXT;
286             INSERT INTO schema_migrations(version, applied_at)
287                 VALUES (35, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
288             PRAGMA user_version = 35;
289             COMMIT;",
290        )?;
291    }
292    // Compatible: adds one nullable column. Older readers ignore it, and the
293    // older writer's session upsert lists columns explicitly, so it preserves
294    // the value. An older executable launching such a session runs it without
295    // the mbx build cache, which is a behaviour difference, not data loss. The
296    // compatibility floor stays where it is.
297    if version < 36 {
298        connection.execute_batch(
299            "BEGIN IMMEDIATE;
300             ALTER TABLE sessions ADD COLUMN build_cache_json TEXT;
301             INSERT INTO schema_migrations(version, applied_at)
302                 VALUES (36, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
303             PRAGMA user_version = 36;
304             COMMIT;",
305        )?;
306    }
307    // Compatible: adds one nullable column to `session_targets`. Only a
308    // container sub-agent child row ever carries a value, and older builds
309    // could never start such a child, so an older update that rewrites the row
310    // without the column loses nothing usable. Older readers ignore it. The
311    // compatibility floor stays where it is.
312    if version < 37 {
313        connection.execute_batch(
314            "BEGIN IMMEDIATE;
315             ALTER TABLE session_targets ADD COLUMN borrowed_from TEXT;
316             INSERT INTO schema_migrations(version, applied_at)
317                 VALUES (37, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
318             PRAGMA user_version = 37;
319             COMMIT;",
320        )?;
321    }
322    // Compatible: adds one table holding the dashboard's conversation pane
323    // arrangement per workspace. Older readers never select from it and older
324    // writers never touch it, so their updates leave its rows intact; a
325    // workspace deleted by an older build still removes them through the
326    // foreign key. Losing the table only means the conversation area opens as
327    // a single pane. The compatibility floor stays where it is.
328    if version < 38 {
329        connection.execute_batch(
330            "BEGIN IMMEDIATE;
331             CREATE TABLE IF NOT EXISTS workspace_layouts (
332                 workspace_id TEXT PRIMARY KEY REFERENCES workspaces(workspace_id) ON DELETE CASCADE,
333                 layout TEXT NOT NULL
334             ) STRICT;
335             INSERT INTO schema_migrations(version, applied_at)
336                 VALUES (38, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
337             PRAGMA user_version = 38;
338             COMMIT;",
339        )?;
340    }
341    // Breaking: persisted input_required API events can now omit the structured
342    // request. Older readers require it and fail to deserialize the event log;
343    // the shared read/write compatibility floor must advance with the revision.
344    if version < 39 {
345        connection.execute_batch(
346            "BEGIN IMMEDIATE;
347             UPDATE schema_compatibility SET minimum_compatible_version = 39 WHERE singleton = 1;
348             INSERT INTO schema_migrations(version, applied_at)
349                 VALUES (39, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
350             PRAGMA user_version = 39;
351             COMMIT;",
352        )?;
353    }
354    // Breaking: native child projections and relay observations must be preserved
355    // by every reader/writer; older builds cannot interpret their lifecycle.
356    if version < 40 {
357        connection.execute_batch(
358            "BEGIN IMMEDIATE;
359             CREATE TABLE native_agents (
360                 owner TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
361                 child TEXT NOT NULL,
362                 staging INTEGER NOT NULL CHECK(staging IN (0,1)),
363                 body TEXT NOT NULL CHECK(json_valid(body)),
364                 PRIMARY KEY(owner, child, staging)
365             ) STRICT;
366             CREATE TABLE native_agent_transcript (
367                 owner TEXT NOT NULL,
368                 child TEXT NOT NULL,
369                 staging INTEGER NOT NULL,
370                 stable_id TEXT NOT NULL,
371                 position INTEGER NOT NULL,
372                 body TEXT NOT NULL CHECK(json_valid(body)),
373                 PRIMARY KEY(owner, child, staging, stable_id),
374                 FOREIGN KEY(owner, child, staging) REFERENCES native_agents(owner, child, staging)
375                     ON DELETE CASCADE ON UPDATE CASCADE
376             ) STRICT;
377             CREATE INDEX native_agent_transcript_position ON native_agent_transcript(owner, child, staging, position);
378             CREATE TABLE native_agent_replay (
379                 owner TEXT PRIMARY KEY REFERENCES sessions(session_id) ON DELETE CASCADE
380             ) STRICT;
381             UPDATE schema_compatibility SET minimum_compatible_version = 40 WHERE singleton = 1;
382             INSERT INTO schema_migrations(version, applied_at)
383                 VALUES (40, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
384             PRAGMA user_version = 40;
385             COMMIT;",
386        )?;
387    }
388    // Breaking: clear-context relay commands/outcomes are persisted in event
389    // JSON. Older readers cannot decode them or honor the context boundary.
390    if version < 41 {
391        connection.execute_batch(
392            "BEGIN IMMEDIATE;
393             UPDATE schema_compatibility SET minimum_compatible_version = 41 WHERE singleton = 1;
394             INSERT INTO schema_migrations(version, applied_at)
395                 VALUES (41, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
396             PRAGMA user_version = 41;
397             COMMIT;",
398        )?;
399    }
400
401    // Breaking: older layout writers discard Browse identity and pin badges.
402    if version < 42 {
403        connection.execute_batch(
404            "BEGIN IMMEDIATE;
405             UPDATE schema_compatibility SET minimum_compatible_version = 42 WHERE singleton = 1;
406             INSERT INTO schema_migrations(version, applied_at)
407                 VALUES (42, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
408             PRAGMA user_version = 42;
409             COMMIT;",
410        )?;
411    }
412
413    // Breaking: durable steering commands/observations and native availability
414    // cannot be interpreted or preserved by older readers and writers.
415    if version < 43 {
416        connection.execute_batch("BEGIN IMMEDIATE;
417            UPDATE schema_compatibility SET minimum_compatible_version = 43 WHERE singleton = 1;
418            INSERT INTO schema_migrations(version, applied_at) VALUES (43, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
419            PRAGMA user_version = 43;
420            COMMIT;")?;
421    }
422
423    // Breaking: new quota recovery commands in stored relay JSON cannot be
424    // read or preserved by older binaries, even though the cache is additive.
425    if version < 44 {
426        connection.execute_batch("BEGIN IMMEDIATE;
427            CREATE TABLE quota_reset_cache (identity TEXT PRIMARY KEY, body TEXT NOT NULL);
428            UPDATE schema_compatibility SET minimum_compatible_version = 44 WHERE singleton = 1;
429            INSERT INTO schema_migrations(version, applied_at) VALUES (44, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
430            PRAGMA user_version = 44;
431            COMMIT;")?;
432    }
433
434    // Compatible: adds one nullable column. Older readers ignore it, and the
435    // older writer's session upsert lists columns explicitly, so it preserves
436    // the value. An older executable relaunching such a session starts it at
437    // HEAD or the remote default branch instead of the recorded revision,
438    // which is a behaviour difference, not data loss. The compatibility floor
439    // stays where it is.
440    if version < 45 {
441        // The column is added only when it is absent, the way migration 34
442        // creates its table only when absent: a store rolled back to an older
443        // revision still carries the column, and a second ALTER would refuse.
444        let add_column =
445            match super::legacy_schema::table_has_column(connection, "sessions", "launch_base")? {
446                true => "",
447                false => "ALTER TABLE sessions ADD COLUMN launch_base TEXT;",
448            };
449        connection.execute_batch(&format!(
450            "BEGIN IMMEDIATE;
451             {add_column}
452             INSERT INTO schema_migrations(version, applied_at)
453                 VALUES (45, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
454             PRAGMA user_version = 45;
455             COMMIT;"
456        ))?;
457    }
458
459    // Breaking: older writers can replace a target without updating its saved
460    // connection, leaving access metadata attached to the wrong resource.
461    // Refuse both older readers and writers before they operate that target.
462    if version < 46 {
463        let add_column = if super::legacy_schema::table_has_column(
464            connection,
465            "sessions",
466            "target_runtime_json",
467        )? {
468            ""
469        } else {
470            "ALTER TABLE sessions ADD COLUMN target_runtime_json TEXT;"
471        };
472        connection.execute_batch(&format!(
473            "BEGIN IMMEDIATE;
474             {add_column}
475             UPDATE schema_compatibility SET minimum_compatible_version = 46 WHERE singleton = 1;
476             INSERT INTO schema_migrations(version, applied_at)
477                 VALUES (46, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
478             PRAGMA user_version = 46;
479             COMMIT;"
480        ))?;
481    }
482
483    // Breaking: the managed checkout JSON can now describe an independent
484    // clone. Older readers reject its `kind`, and older writers cannot safely
485    // retain that clone's unpublished commits during lifecycle cleanup.
486    if version < 47 {
487        let add_branch =
488            if super::legacy_schema::table_has_column(connection, "sessions", "launch_branch")? {
489                ""
490            } else {
491                "ALTER TABLE sessions ADD COLUMN launch_branch TEXT;"
492            };
493        let add_publication = if super::legacy_schema::table_has_column(
494            connection,
495            "sessions",
496            "publication_json",
497        )? {
498            ""
499        } else {
500            "ALTER TABLE sessions ADD COLUMN publication_json TEXT;"
501        };
502        connection.execute_batch(&format!(
503            "BEGIN IMMEDIATE;
504             {add_branch}
505             {add_publication}
506             UPDATE schema_compatibility SET minimum_compatible_version = 47 WHERE singleton = 1;
507             INSERT INTO schema_migrations(version, applied_at)
508                 VALUES (47, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
509             PRAGMA user_version = 47;
510             COMMIT;",
511        ))?;
512    }
513
514    // Breaking: stored relay JSON can now hold the steering-returned outcome,
515    // and stored active-turn JSON the prompt a steer continued, which older
516    // readers reject and older writers would drop.
517    if version < 48 {
518        connection.execute_batch(
519            "BEGIN IMMEDIATE;
520             UPDATE schema_compatibility SET minimum_compatible_version = 48 WHERE singleton = 1;
521             INSERT INTO schema_migrations(version, applied_at)
522                 VALUES (48, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
523             PRAGMA user_version = 48;
524             COMMIT;",
525        )?;
526    }
527
528    // Breaking: a sub-agent record can now say its child has the `handback`
529    // tool, and older readers refuse the unknown field. The reports themselves
530    // live in their own table, because a full state save rewrites every
531    // sub-agent record from whatever copy the saving controller holds.
532    if version < 49 {
533        connection.execute_batch(
534            "BEGIN IMMEDIATE;
535             CREATE TABLE IF NOT EXISTS subagent_handbacks (
536                 child_session_id TEXT PRIMARY KEY,
537                 handback_command_id TEXT,
538                 handback_message TEXT,
539                 handback_recorded_at_ms INTEGER,
540                 reminder_command_id TEXT,
541                 reminder_for_command_id TEXT,
542                 reminder_sent_at_ms INTEGER,
543                 reminder_failed_for_command_id TEXT
544             );
545             UPDATE schema_compatibility SET minimum_compatible_version = 49 WHERE singleton = 1;
546             INSERT INTO schema_migrations(version, applied_at)
547                 VALUES (49, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
548             PRAGMA user_version = 49;
549             COMMIT;",
550        )?;
551    }
552
553    // Compatible: a new nullable column that only this build reads. Older
554    // readers ignore it, and older writers name their columns, so an update
555    // from one keeps it.
556    if version < 50 {
557        let add_column = if super::legacy_schema::table_has_column(
558            connection,
559            "subagent_handbacks",
560            "awaited_ordinal",
561        )? {
562            ""
563        } else {
564            "ALTER TABLE subagent_handbacks ADD COLUMN awaited_ordinal INTEGER;"
565        };
566        connection.execute_batch(&format!(
567            "BEGIN IMMEDIATE;
568             {add_column}
569             INSERT INTO schema_migrations(version, applied_at)
570                 VALUES (50, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
571             PRAGMA user_version = 50;
572             COMMIT;"
573        ))?;
574    }
575
576    let recorded: Option<i64> =
577        connection.query_row("SELECT max(version) FROM schema_migrations", [], |row| {
578            row.get(0)
579        })?;
580    if recorded != Some(SCHEMA_VERSION) {
581        bail!(
582            "Mjolnir database migration ledger {:?} does not match schema {}",
583            recorded,
584            SCHEMA_VERSION
585        );
586    }
587    Ok(())
588}
589
590/// Create an empty store at the baseline revision in one immediate transaction.
591/// The revision is read again under the write lock, so a second process that
592/// raced to create the same store finds it already created.
593fn create_baseline_schema(connection: &Connection) -> Result<()> {
594    connection.execute_batch("BEGIN IMMEDIATE;")?;
595    let created = (|| -> Result<()> {
596        let version: i64 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
597        if version != 0 {
598            return Ok(());
599        }
600        connection.execute_batch(include_str!("baseline.sql"))?;
601        connection.execute(
602            "INSERT INTO schema_compatibility(singleton, minimum_compatible_version) VALUES (1, ?1)",
603            [BASELINE_MINIMUM_COMPATIBLE_VERSION],
604        )?;
605        connection.execute(
606            "INSERT INTO schema_migrations(version, applied_at)
607             VALUES (?1, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
608            [BASELINE_SCHEMA_VERSION],
609        )?;
610        connection.pragma_update(None, "user_version", BASELINE_SCHEMA_VERSION)?;
611        Ok(())
612    })();
613    match created {
614        Ok(()) => connection
615            .execute_batch("COMMIT;")
616            .context("commit baseline database schema"),
617        Err(error) => {
618            if let Err(rollback) = connection.execute_batch("ROLLBACK;") {
619                tracing::warn!(%rollback, "could not roll back a failed baseline schema");
620            }
621            Err(error.context("create baseline database schema"))
622        }
623    }
624}
625
626#[cfg(test)]
627pub(super) fn advance_test_schema(path: &Path, revision: i64, minimum_compatible: i64) {
628    let connection = Connection::open(path).unwrap();
629    let transaction = connection.unchecked_transaction().unwrap();
630    transaction
631        .execute(
632            "UPDATE schema_compatibility SET minimum_compatible_version = ?1",
633            [minimum_compatible],
634        )
635        .unwrap();
636    transaction
637        .execute(
638            "INSERT INTO schema_migrations(version, applied_at) VALUES (?1, 'test')",
639            [revision],
640        )
641        .unwrap();
642    transaction
643        .pragma_update(None, "user_version", revision)
644        .unwrap();
645    transaction.commit().unwrap();
646    forget_verified_schema(path);
647}
648
649#[cfg(test)]
650mod reader_tests {
651    use super::*;
652
653    #[test]
654    fn every_historical_revision_upgrades_directly_and_preserves_user_data() {
655        for revision in 1..SCHEMA_VERSION {
656            let directory = tempfile::tempdir().unwrap();
657            let path = directory.path().join("mj.sqlite3");
658            let connection = Connection::open(&path).unwrap();
659            connection
660                .execute_batch(include_str!("legacy_v1.sql"))
661                .unwrap();
662            connection.execute_batch(
663                "INSERT INTO session_contexts VALUES ('old-session', 'project', '2026-01-01T00:00:00Z');
664                 INSERT INTO sessions(session_id, title, harness_kind, last_profile,
665                     target_template_id, state, updated_at, native_session_id)
666                     VALUES ('old-session', 'Keep my work', 'codex', 'codex', 'local', 'error',
667                         '2026-01-01T00:00:00Z', 'native-original');
668                 INSERT INTO prompt_history(session_id, event_sequence, submitted_at, text)
669                     VALUES ('old-session', 1, '2026-01-01T00:00:00Z', 'Keep my prompt');"
670            ).unwrap();
671            // Interrupt at each historical transaction boundary. Closing the
672            // connection rolls back the interrupted step, exactly as a killed
673            // updater would. Reopening must resume without manual cleanup.
674            connection
675                .execute_batch(&format!(
676                    "CREATE TRIGGER stop_at_revision BEFORE INSERT ON schema_migrations
677                 WHEN NEW.version > {revision}
678                 BEGIN SELECT RAISE(ABORT, 'fixture migration boundary'); END;"
679                ))
680                .unwrap();
681            if revision < BASELINE_SCHEMA_VERSION {
682                assert!(super::super::legacy_schema::migrate_to_baseline(&connection).is_err());
683            } else {
684                super::super::legacy_schema::migrate_to_baseline(&connection).unwrap();
685                assert!(migrate_schema(&connection).is_err());
686            }
687            drop(connection);
688            let connection = Connection::open(&path).unwrap();
689            let found: i64 = connection
690                .query_row("PRAGMA user_version", [], |row| row.get(0))
691                .unwrap();
692            assert_eq!(found, revision);
693            connection
694                .execute_batch("DROP TRIGGER stop_at_revision")
695                .unwrap();
696            drop(connection);
697
698            let writer =
699                open_writer(&path).unwrap_or_else(|error| panic!("revision {revision}: {error:#}"));
700            assert_eq!(read_schema_state(&writer).unwrap().revision, SCHEMA_VERSION);
701            assert_eq!(
702                writer
703                    .query_row("PRAGMA integrity_check", [], |row| row.get::<_, String>(0))
704                    .unwrap(),
705                "ok"
706            );
707            assert!(
708                !writer
709                    .prepare("PRAGMA foreign_key_check")
710                    .unwrap()
711                    .exists([])
712                    .unwrap()
713            );
714            drop(writer);
715            let reader = open_reader_strict(&path).unwrap();
716            let prompt: String = reader
717                .query_row("SELECT text FROM prompt_history", [], |row| row.get(0))
718                .unwrap();
719            assert_eq!(prompt, "Keep my prompt");
720            let state = load_state_from(&path).unwrap();
721            assert_eq!(state.sessions["old-session"].title, "Keep my work");
722            assert_eq!(
723                state.sessions["old-session"].native_session_id.as_deref(),
724                Some("native-original")
725            );
726            drop(reader);
727            // A fresh writer process must not apply any migration twice.
728            forget_verified_schema(&path);
729            drop(open_writer(&path).unwrap());
730        }
731    }
732
733    /// The oldest executable revision that can still read and write a store at
734    /// `SCHEMA_VERSION`. Migration 49 adds sub-agent handback records.
735    const MINIMUM_COMPATIBLE_VERSION: i64 = 49;
736
737    /// Rewrites a store's recorded schema version the way another build's
738    /// migration ladder would, and forgets that this process verified it.
739    fn stamp_schema_version(path: &Path, version: i64) {
740        if version > SCHEMA_VERSION {
741            advance_test_schema(path, version, version);
742            return;
743        }
744        let connection = Connection::open(path).unwrap();
745        connection
746            .execute_batch(&format!("PRAGMA user_version = {version};"))
747            .unwrap();
748        connection
749            .execute(
750                "DELETE FROM schema_migrations WHERE version > ?1",
751                [version],
752            )
753            .unwrap();
754        if version == 30 {
755            connection
756                .execute(
757                    "UPDATE schema_compatibility SET minimum_compatible_version = 30 WHERE singleton = 1",
758                    [],
759                )
760                .unwrap();
761        }
762        drop(connection);
763        forget_verified_schema(path);
764    }
765
766    #[test]
767    fn steering_migration_refuses_builds_that_cannot_read_returned_steers() {
768        let directory = tempfile::tempdir().unwrap();
769        let path = directory.path().join("steering-migration.sqlite3");
770        let record = super::super::tests::session("steered-session", "project");
771        save_session_to(&path, &record).unwrap();
772        let connection = Connection::open(&path).unwrap();
773        connection
774            .execute_batch(
775                "DELETE FROM schema_migrations WHERE version >= 48;
776             UPDATE schema_compatibility SET minimum_compatible_version = 47;
777             PRAGMA user_version = 47;",
778            )
779            .unwrap();
780        drop(connection);
781        forget_verified_schema(&path);
782        let upgraded = open_writer(&path).unwrap();
783        let schema = read_schema_state(&upgraded).unwrap();
784        assert_eq!(schema.revision, SCHEMA_VERSION);
785        assert_eq!(schema.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
786        let error = schema.ensure_supported_by(47).unwrap_err();
787        assert!(matches!(
788            error.downcast_ref::<StoreSchemaMismatch>().unwrap().reason,
789            StoreSchemaMismatchReason::Incompatible {
790                minimum_compatible: MINIMUM_COMPATIBLE_VERSION
791            }
792        ));
793        drop(upgraded);
794        assert_eq!(load_state_from(&path).unwrap().sessions[&record.id], record);
795    }
796
797    #[test]
798    fn durable_target_migration_preserves_sessions_and_refuses_previous_builds() {
799        let directory = tempfile::tempdir().unwrap();
800        let path = directory.path().join("target-migration.sqlite3");
801        let record = super::super::tests::session("preserved-session", "project");
802        save_session_to(&path, &record).unwrap();
803        let connection = Connection::open(&path).unwrap();
804        connection
805            .execute_batch(
806                "ALTER TABLE sessions DROP COLUMN target_runtime_json;
807             DELETE FROM schema_migrations WHERE version >= 46;
808             UPDATE schema_compatibility SET minimum_compatible_version = 44;
809             PRAGMA user_version = 45;",
810            )
811            .unwrap();
812        forget_verified_schema(&path);
813        let upgraded = open_writer(&path).unwrap();
814        let schema = read_schema_state(&upgraded).unwrap();
815        assert_eq!(schema.revision, SCHEMA_VERSION);
816        assert_eq!(schema.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
817        let error = schema.ensure_supported_by(45).unwrap_err();
818        assert!(matches!(
819            error.downcast_ref::<StoreSchemaMismatch>().unwrap().reason,
820            StoreSchemaMismatchReason::Incompatible {
821                minimum_compatible: MINIMUM_COMPATIBLE_VERSION
822            }
823        ));
824        drop(upgraded);
825        let restored = load_state_from(&path).unwrap();
826        assert_eq!(restored.sessions[&record.id], record);
827    }
828
829    #[test]
830    fn native_agents_and_unstructured_input_raise_the_store_compatibility_floor() {
831        let directory = tempfile::tempdir().unwrap();
832        let path = directory.path().join("mj.sqlite3");
833        let connection = open_writer(&path).unwrap();
834        connection
835            .execute_batch(
836                "BEGIN IMMEDIATE;
837             DROP TABLE quota_reset_cache;
838             DROP TABLE native_agent_transcript;
839             DROP TABLE native_agents;
840             DROP TABLE native_agent_replay;
841             DELETE FROM schema_migrations WHERE version >= 39;
842             UPDATE schema_compatibility SET minimum_compatible_version = 32;
843             PRAGMA user_version = 38;
844             COMMIT;",
845            )
846            .unwrap();
847        migrate_schema(&connection).unwrap();
848        let state = read_schema_state(&connection).unwrap();
849        assert_eq!(state.revision, SCHEMA_VERSION);
850        assert_eq!(state.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
851        let event = ApiEventData::InputRequired {
852            request: None,
853            turn_id: Some(1),
854        };
855        #[derive(serde::Deserialize)]
856        struct LegacyInputEvent {
857            #[serde(rename = "request")]
858            _request: mj_core::elicitation::ElicitationRequest,
859        }
860        let encoded = serde_json::to_value(&event).unwrap();
861        assert!(serde_json::from_value::<LegacyInputEvent>(encoded["data"].clone()).is_err());
862    }
863
864    #[test]
865    fn older_readers_and_reopened_writers_preserve_a_compatible_future_schema() {
866        let directory = tempfile::tempdir().unwrap();
867        let path = directory.path().join("mj.sqlite3");
868        let connection = open_writer(&path).unwrap();
869        connection
870            .execute_batch(
871                "CREATE TABLE future_feature(value TEXT NOT NULL);
872                 INSERT INTO future_feature VALUES ('preserve me');",
873            )
874            .unwrap();
875        drop(connection);
876        advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);
877
878        let reader = open_reader_strict(&path).unwrap();
879        assert_eq!(
880            reader
881                .query_row("SELECT value FROM future_feature", [], |row| row
882                    .get::<_, String>(0))
883                .unwrap(),
884            "preserve me"
885        );
886        assert!(reader.execute("DELETE FROM future_feature", []).is_err());
887        drop(reader);
888
889        // A repair would recreate this deliberately removed trigger. A future
890        // schema is authoritative even when it differs from our own repairs.
891        let raw = Connection::open(&path).unwrap();
892        raw.execute_batch("DROP TRIGGER api_session_error_updated;")
893            .unwrap();
894        drop(raw);
895        let writer = open_writer(&path).unwrap();
896        assert!(!writer.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name = 'api_session_error_updated')", [], |row| row.get::<_, bool>(0)).unwrap());
897        assert_eq!(
898            writer
899                .query_row("SELECT value FROM future_feature", [], |row| row
900                    .get::<_, String>(0))
901                .unwrap(),
902            "preserve me"
903        );
904        let state = read_schema_state(&writer).unwrap();
905        assert_eq!(state.revision, SCHEMA_VERSION + 1);
906        assert_eq!(state.minimum_compatible, Some(SCHEMA_VERSION));
907    }
908
909    #[test]
910    fn invalid_compatibility_metadata_refuses_readers_and_writers() {
911        for alteration in [
912            "DROP TABLE schema_compatibility",
913            "DELETE FROM schema_compatibility",
914            "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET minimum_compatible_version = 0",
915            "UPDATE schema_compatibility SET minimum_compatible_version = 99999",
916            "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET singleton = 2",
917            "PRAGMA ignore_check_constraints = ON; INSERT INTO schema_compatibility VALUES (2, 30)",
918            "DROP TABLE schema_compatibility; CREATE TABLE schema_compatibility(singleton, minimum_compatible_version); INSERT INTO schema_compatibility VALUES (1, 'invalid')",
919            "DELETE FROM schema_migrations WHERE version = (SELECT max(version) FROM schema_migrations)",
920        ] {
921            for future in [false, true] {
922                let directory = tempfile::tempdir().unwrap();
923                let path = directory.path().join("mj.sqlite3");
924                drop(open_writer(&path).unwrap());
925                if future {
926                    advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);
927                }
928                let raw = Connection::open(&path).unwrap();
929                raw.execute_batch(alteration).unwrap();
930                let before: i64 = raw
931                    .query_row("PRAGMA schema_version", [], |row| row.get(0))
932                    .unwrap();
933                // Exercise the cached path as well as a fresh writer open.
934                for error in [
935                    open_reader_strict(&path).unwrap_err(),
936                    open_writer(&path).unwrap_err(),
937                ] {
938                    let mismatch = error.downcast_ref::<StoreSchemaMismatch>().unwrap();
939                    assert_eq!(
940                        mismatch.reason,
941                        StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
942                        "{alteration}"
943                    );
944                }
945                forget_verified_schema(&path);
946                assert!(open_writer(&path).is_err(), "{alteration}");
947                let after: i64 = raw
948                    .query_row("PRAGMA schema_version", [], |row| row.get(0))
949                    .unwrap();
950                assert_eq!(
951                    before, after,
952                    "a rejected open repaired schema: {alteration}"
953                );
954            }
955        }
956    }
957
958    #[test]
959    fn a_failed_baseline_leaves_an_empty_store_that_a_retry_creates() {
960        let directory = tempfile::tempdir().unwrap();
961        let path = directory.path().join("mj.sqlite3");
962        let connection = Connection::open(&path).unwrap();
963        // A table the baseline also creates makes its batch fail part way.
964        connection
965            .execute_batch("CREATE TABLE workspaces(conflict TEXT)")
966            .unwrap();
967
968        let error = migrate_schema(&connection).unwrap_err();
969
970        assert!(format!("{error:#}").contains("create baseline database schema"));
971        assert!(
972            connection.is_autocommit(),
973            "the failed baseline left a transaction open"
974        );
975        assert_eq!(read_schema_state(&connection).unwrap().revision, 0);
976        let tables: i64 = connection
977            .query_row(
978                "SELECT count(*) FROM sqlite_schema WHERE type = 'table'",
979                [],
980                |row| row.get(0),
981            )
982            .unwrap();
983        assert_eq!(tables, 1, "only the conflicting table remains");
984
985        connection.execute_batch("DROP TABLE workspaces").unwrap();
986        drop(connection);
987        let writer = open_writer(&path).unwrap();
988        let state = read_schema_state(&writer).unwrap();
989        assert_eq!(state.revision, SCHEMA_VERSION);
990        assert_eq!(state.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
991    }
992
993    /// A store ahead of this build cannot be fixed by starting a daemon of
994    /// this build, so the reader must not say so. This is the message the
995    /// incident in #24 printed twice a second for an hour.
996    #[test]
997    fn strict_reader_reports_a_newer_store_without_blaming_the_daemon() {
998        let directory = tempfile::tempdir().unwrap();
999        let path = directory.path().join("mj.sqlite3");
1000        drop(open_writer(&path).unwrap());
1001        stamp_schema_version(&path, SCHEMA_VERSION + 1);
1002
1003        let error = open_reader_strict(&path).unwrap_err();
1004
1005        let mismatch = error
1006            .chain()
1007            .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
1008            .expect("the reader reports the mismatch as a typed cause");
1009        assert_eq!(mismatch.found, SCHEMA_VERSION + 1);
1010        assert_eq!(mismatch.supported, SCHEMA_VERSION);
1011        let message = mismatch.to_string();
1012        assert!(message.contains("upgrade Mjolnir"), "got {message}");
1013        assert!(
1014            !message.contains("start the Mjolnir daemon"),
1015            "got {message}"
1016        );
1017    }
1018
1019    /// A store behind this build keeps the advice that works, verbatim, so
1020    /// existing log greps and runbooks keep matching.
1021    #[test]
1022    fn strict_reader_keeps_the_migrate_advice_when_the_store_is_behind() {
1023        let directory = tempfile::tempdir().unwrap();
1024        let path = directory.path().join("mj.sqlite3");
1025        drop(open_writer(&path).unwrap());
1026        let raw = Connection::open(&path).unwrap();
1027        raw.execute_batch(&format!(
1028            "UPDATE schema_compatibility SET minimum_compatible_version = {0};
1029             DELETE FROM schema_migrations WHERE version > {0};
1030             INSERT OR IGNORE INTO schema_migrations(version, applied_at) VALUES ({0}, 'test');
1031             PRAGMA user_version = {0};",
1032            SCHEMA_VERSION - 1
1033        ))
1034        .unwrap();
1035        drop(raw);
1036
1037        let error = open_reader_strict(&path).unwrap_err();
1038
1039        let mismatch = error
1040            .chain()
1041            .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
1042            .expect("the reader reports the mismatch as a typed cause");
1043        assert_eq!(
1044            mismatch.to_string(),
1045            format!(
1046                "Mjolnir database schema {} is not the supported schema {SCHEMA_VERSION}; \
1047                 start the Mjolnir daemon to migrate it",
1048                SCHEMA_VERSION - 1
1049            )
1050        );
1051    }
1052
1053    #[test]
1054    fn strict_reader_rejects_mutation() {
1055        let directory = tempfile::tempdir().unwrap();
1056        let path = directory.path().join("mj.sqlite3");
1057        drop(open_writer(&path).unwrap());
1058
1059        let reader = open_reader_strict(&path).unwrap();
1060        let error = reader
1061            .execute("CREATE TABLE forbidden(value TEXT)", [])
1062            .unwrap_err();
1063        assert!(
1064            matches!(
1065                error.sqlite_error_code(),
1066                Some(rusqlite::ErrorCode::ReadOnly)
1067            ),
1068            "unexpected mutation error: {error}"
1069        );
1070    }
1071}