mlua-swarm 0.21.0

Swarm engine host built on mlua — long-running stateful runtime with Role/Verb gate, CapToken, 3-stage pipeline, and Middleware overlay.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! SQLite-backed [`ReplayStore`] using [`rusqlite-isle`].
//!
//! The [`crate::store::run::sqlite::SqliteRunStore`] pattern is the same:
//! the `Connection` is confined to a dedicated OS thread by `AsyncIsle`
//! and every call is a typed closure dispatched over a bounded channel.
//! `ctx_snapshot_json` and `step_output_json` are stored verbatim as
//! `TEXT`; the caller (the dispatcher) is what canonicalizes shape via
//! [`super::hash_input_value`].
//!
//! ## Schema
//!
//! ```sql
//! CREATE TABLE IF NOT EXISTS replay_log (
//!   seq                 INTEGER PRIMARY KEY AUTOINCREMENT,
//!   run_id              TEXT NOT NULL,
//!   step_ref            TEXT NOT NULL,
//!   input_hash          TEXT NOT NULL,
//!   occurrence          INTEGER NOT NULL,
//!   ctx_snapshot_json   TEXT NOT NULL,
//!   step_output_json    TEXT NOT NULL,
//!   created_at          INTEGER NOT NULL,
//!   UNIQUE (run_id, step_ref, input_hash, occurrence)
//! );
//! CREATE INDEX IF NOT EXISTS ix_replay_run ON replay_log(run_id, seq);
//! ```
//!
//! ## Schema versioning
//!
//! The current schema is tracked with SQLite's `PRAGMA user_version` as the
//! single source of truth (1 = the two-column split above). [`init_schema`]
//! reads the value on every open and dispatches:
//!
//! - `user_version = 0` (fresh DB, or a legacy file created by mse
//!   ≤ v0.10.0 / pre-Core-primitive that used a `value_json` single column):
//!   if a legacy `replay_log` table is present it is `DROP`ed before the
//!   current schema is created, then `user_version` is stamped to `1`.
//!   Legacy rows carry no `ctx_snapshot_json`, so they cannot be replayed
//!   against the current wire anyway — dropping them is safe.
//! - `user_version = 1`: the current schema; `CREATE ... IF NOT EXISTS` is
//!   still run defensively.
//! - `user_version > 1`: reject with an error — an older mse binary must
//!   never touch a store written by a newer one.
//!
//! Future migrations follow the same pattern: add a `1 => migrate_v1_to_v2`
//! arm and stamp `user_version = 2`.

use super::{ReplayEntry, ReplayStore, ReplayStoreError};
use crate::types::RunId;
use async_trait::async_trait;
use rusqlite::params;
use rusqlite_isle::{AsyncIsle, AsyncIsleDriver, IsleError};
use std::path::Path;

const SCHEMA_SQL: &str = "\
CREATE TABLE IF NOT EXISTS replay_log (\
  seq                 INTEGER PRIMARY KEY AUTOINCREMENT, \
  run_id              TEXT NOT NULL, \
  step_ref            TEXT NOT NULL, \
  input_hash          TEXT NOT NULL, \
  occurrence          INTEGER NOT NULL, \
  ctx_snapshot_json   TEXT NOT NULL, \
  step_output_json    TEXT NOT NULL, \
  created_at          INTEGER NOT NULL, \
  UNIQUE (run_id, step_ref, input_hash, occurrence)\
);\
CREATE INDEX IF NOT EXISTS ix_replay_run ON replay_log(run_id, seq);\
";

/// Latest schema version. Bumped whenever [`SCHEMA_SQL`] changes shape in a
/// way older binaries cannot read.
const CURRENT_SCHEMA_VERSION: i64 = 1;

/// Detect and migrate the `replay_log` schema on open. See the module-level
/// `Schema versioning` doc for the state-machine.
///
/// Returns `rusqlite::Result<()>` so it plugs straight into
/// `AsyncIsle::spawn` / `AsyncIsle::open_in_memory`; errors surface via
/// [`map_isle_err`] as [`ReplayStoreError::Other`] with the message
/// preserved verbatim.
fn init_schema(conn: &mut rusqlite::Connection) -> rusqlite::Result<()> {
    // Read current schema version. Fresh DB reports 0.
    let user_version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;

    match user_version {
        0 => {
            // Detect legacy schema: a `replay_log` table exists but lacks
            // the `ctx_snapshot_json` column. If so, drop it — legacy rows
            // carry no Ctx snapshot, so resume cursor hits cannot use them
            // anyway; data loss is safe.
            let table_present: i64 = conn.query_row(
                "SELECT COUNT(*) FROM sqlite_master \
                 WHERE type = 'table' AND name = 'replay_log'",
                [],
                |r| r.get(0),
            )?;
            let has_ctx_column: i64 = if table_present > 0 {
                conn.query_row(
                    "SELECT COUNT(*) FROM pragma_table_info('replay_log') \
                     WHERE name = 'ctx_snapshot_json'",
                    [],
                    |r| r.get(0),
                )?
            } else {
                0
            };
            let is_legacy = table_present > 0 && has_ctx_column == 0;
            if is_legacy {
                conn.execute("DROP TABLE replay_log", [])?;
            }
            conn.execute_batch(SCHEMA_SQL)?;
            // PRAGMA cannot bind parameters; the value is a compile-time
            // constant, so string-substitute it directly.
            conn.execute_batch(&format!("PRAGMA user_version = {CURRENT_SCHEMA_VERSION}"))?;
            Ok(())
        }
        v if v == CURRENT_SCHEMA_VERSION => {
            // Current schema. Still run CREATE ... IF NOT EXISTS in case the
            // table was manually deleted while user_version stayed at 1.
            conn.execute_batch(SCHEMA_SQL)
        }
        v => Err(rusqlite::Error::SqliteFailure(
            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_ERROR),
            Some(format!(
                "replay_log schema version {v} is newer than supported \
                 ({CURRENT_SCHEMA_VERSION}); running an older mse binary \
                 against a store written by a newer one is not supported"
            )),
        )),
    }
}

/// SQLite-backed persistent [`ReplayStore`].
///
/// Open with [`SqliteReplayStore::open`] (file path) or
/// [`SqliteReplayStore::open_in_memory`] (tests). Both return the store
/// plus an [`AsyncIsleDriver`] the caller must `shutdown().await` when
/// done — dropping the driver without a shutdown call leaves the SQLite
/// thread as-is until the process exits.
pub struct SqliteReplayStore {
    isle: AsyncIsle,
}

impl SqliteReplayStore {
    /// Open (or create) a SQLite database file and run the schema
    /// migrations. See [`init_schema`] and the module-level `Schema
    /// versioning` doc.
    pub async fn open(path: impl AsRef<Path>) -> Result<(Self, AsyncIsleDriver), ReplayStoreError> {
        let (isle, driver) = AsyncIsle::spawn(path.as_ref().to_path_buf(), init_schema)
            .await
            .map_err(map_isle_err)?;
        Ok((Self { isle }, driver))
    }

    /// Open an ephemeral in-memory database (tests, doctests). In-memory
    /// databases start with `user_version = 0` and are always fresh, so
    /// [`init_schema`] takes the version-0 arm and stamps
    /// `CURRENT_SCHEMA_VERSION` immediately.
    pub async fn open_in_memory() -> Result<(Self, AsyncIsleDriver), ReplayStoreError> {
        let (isle, driver) = AsyncIsle::open_in_memory(init_schema)
            .await
            .map_err(map_isle_err)?;
        Ok((Self { isle }, driver))
    }
}

fn map_isle_err(e: IsleError) -> ReplayStoreError {
    ReplayStoreError::Other(format!("sqlite: {e}"))
}

#[async_trait]
impl ReplayStore for SqliteReplayStore {
    fn name(&self) -> &str {
        "sqlite"
    }

    async fn append(&self, entry: ReplayEntry) -> Result<(), ReplayStoreError> {
        let ReplayEntry {
            run_id,
            step_ref,
            input_hash,
            occurrence,
            ctx_snapshot_json,
            step_output_json,
            created_at,
        } = entry;
        let run_id_for_err = run_id.clone();
        let step_ref_for_err = step_ref.clone();
        let input_hash_for_err = input_hash.clone();
        let run_id_str = run_id.to_string();

        self.isle
            .call(move |conn| {
                conn.execute(
                    "INSERT INTO replay_log \
                     (run_id, step_ref, input_hash, occurrence, ctx_snapshot_json, \
                      step_output_json, created_at) \
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                    params![
                        run_id_str,
                        step_ref,
                        input_hash,
                        occurrence as i64,
                        ctx_snapshot_json,
                        step_output_json,
                        created_at as i64,
                    ],
                )?;
                Ok(())
            })
            .await
            .map_err(|e| match &e {
                IsleError::Sqlite(rusqlite::Error::SqliteFailure(err, _))
                    if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
                        || err.code == rusqlite::ErrorCode::ConstraintViolation =>
                {
                    ReplayStoreError::Duplicate {
                        run_id: run_id_for_err.clone(),
                        step_ref: step_ref_for_err.clone(),
                        input_hash: input_hash_for_err.clone(),
                        occurrence,
                    }
                }
                _ => map_isle_err(e),
            })
    }

    async fn list_by_run(&self, run_id: &RunId) -> Result<Vec<ReplayEntry>, ReplayStoreError> {
        let run_id_str = run_id.to_string();
        let run_id_owned = run_id.clone();
        let rows: Vec<(String, String, i64, String, String, i64)> = self
            .isle
            .call(move |conn| {
                let mut stmt = conn.prepare(
                    "SELECT step_ref, input_hash, occurrence, ctx_snapshot_json, \
                     step_output_json, created_at FROM replay_log \
                     WHERE run_id = ?1 ORDER BY seq ASC",
                )?;
                let iter = stmt.query_map(params![run_id_str], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, i64>(2)?,
                        row.get::<_, String>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, i64>(5)?,
                    ))
                })?;
                let mut out = Vec::new();
                for r in iter {
                    out.push(r?);
                }
                Ok(out)
            })
            .await
            .map_err(map_isle_err)?;

        Ok(rows
            .into_iter()
            .map(
                |(
                    step_ref,
                    input_hash,
                    occurrence,
                    ctx_snapshot_json,
                    step_output_json,
                    created_at,
                )| {
                    ReplayEntry {
                        run_id: run_id_owned.clone(),
                        step_ref,
                        input_hash,
                        occurrence: occurrence as u32,
                        ctx_snapshot_json,
                        step_output_json,
                        created_at: created_at as u64,
                    }
                },
            )
            .collect())
    }

    async fn delete_from(
        &self,
        run_id: &RunId,
        from_index: usize,
    ) -> Result<usize, ReplayStoreError> {
        let run_id_str = run_id.to_string();
        let deleted: usize = self
            .isle
            .call(move |conn| {
                // Collect the seq values in the same order list_by_run uses
                // (`ORDER BY seq ASC`), skip the first `from_index` rows,
                // and delete the rest in a single statement. `LIMIT -1
                // OFFSET n` in SQLite returns "all rows after skipping n"
                // — this is the shape we want.
                let mut stmt = conn.prepare(
                    "SELECT seq FROM replay_log WHERE run_id = ?1 \
                     ORDER BY seq ASC LIMIT -1 OFFSET ?2",
                )?;
                let seqs: Vec<i64> = stmt
                    .query_map(params![run_id_str, from_index as i64], |row| {
                        row.get::<_, i64>(0)
                    })?
                    .collect::<rusqlite::Result<Vec<_>>>()?;
                drop(stmt);

                if seqs.is_empty() {
                    return Ok(0usize);
                }

                // Build a parameterized IN (...) clause. All seqs came from
                // the same replay_log table so the row count IS the deleted
                // row count; no need to consult the driver's changes counter.
                let placeholders = std::iter::repeat("?")
                    .take(seqs.len())
                    .collect::<Vec<_>>()
                    .join(",");
                let sql = format!("DELETE FROM replay_log WHERE seq IN ({placeholders})");
                let params_dyn: Vec<&dyn rusqlite::ToSql> =
                    seqs.iter().map(|s| s as &dyn rusqlite::ToSql).collect();
                conn.execute(&sql, params_dyn.as_slice())?;
                Ok(seqs.len())
            })
            .await
            .map_err(map_isle_err)?;
        Ok(deleted)
    }
}

// ──────────────────────────────────────────────────────────────────────────
// Tests.
// ──────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ctx::Ctx;
    use crate::store::replay::ReplayCursor;
    use crate::types::StepId;
    use serde_json::json;

    fn mk_ctx() -> Ctx {
        let mut ctx = Ctx::new(StepId::new(), 1, "step-a");
        ctx.meta.observer.insert("k".into(), json!("v"));
        ctx
    }

    #[tokio::test]
    async fn sqlite_append_and_list() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();

        let e0 = ReplayEntry::from_completion(
            run_id.clone(),
            "step-a",
            "hash-a",
            0,
            &ctx,
            &json!({ "n": 1 }),
        )
        .unwrap();
        store.append(e0).await.unwrap();

        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].step_ref, "step-a");
        assert_eq!(listed[0].occurrence, 0);
        assert_eq!(listed[0].decode_step_output().unwrap(), json!({ "n": 1 }));

        // Ctx round-trip through the SQLite backend.
        let restored = listed[0].decode_ctx_snapshot().unwrap();
        assert_eq!(restored.agent, ctx.agent);
        assert_eq!(restored.attempt, ctx.attempt);
        assert_eq!(restored.meta.observer.get("k"), Some(&json!("v")));

        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_unique_4_tuple_is_enforced() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();

        let e0 = ReplayEntry::from_completion(
            run_id.clone(),
            "step-a",
            "hash-a",
            0,
            &ctx,
            &json!("first"),
        )
        .unwrap();
        store.append(e0.clone()).await.unwrap();

        // Same 4-tuple → Duplicate.
        let dup_err = store.append(e0).await.unwrap_err();
        assert!(
            matches!(dup_err, ReplayStoreError::Duplicate { .. }),
            "same (run_id, step_ref, input_hash, occurrence) must collide"
        );

        // occurrence=1 must NOT collide with occurrence=0 (loop replay
        // discipline).
        let e1 = ReplayEntry::from_completion(
            run_id.clone(),
            "step-a",
            "hash-a",
            1,
            &ctx,
            &json!("second"),
        )
        .unwrap();
        store
            .append(e1)
            .await
            .expect("occurrence=1 must not collide with occurrence=0");

        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 2);
        let cursor = ReplayCursor::from_entries(listed);
        assert_eq!(cursor.find("step-a", "hash-a", 0), Some(json!("first")));
        assert_eq!(cursor.find("step-a", "hash-a", 1), Some(json!("second")));

        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_list_by_run_returns_in_seq_order() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();

        for (i, (step, occ)) in [("a", 0), ("b", 0), ("a", 1)].iter().enumerate() {
            store
                .append(
                    ReplayEntry::from_completion(
                        run_id.clone(),
                        *step,
                        "h",
                        *occ,
                        &ctx,
                        &json!({ "idx": i }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
        }

        let listed = store.list_by_run(&run_id).await.unwrap();
        let steps: Vec<(String, u32)> = listed
            .iter()
            .map(|e| (e.step_ref.clone(), e.occurrence))
            .collect();
        assert_eq!(
            steps,
            vec![
                ("a".to_string(), 0),
                ("b".to_string(), 0),
                ("a".to_string(), 1),
            ]
        );

        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_name() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        assert_eq!(store.name(), "sqlite");
        driver.shutdown().await.unwrap();
    }

    // ──────────────────────────────────────────────────────────────────────
    // Schema-migration tests (see `init_schema`).
    // ──────────────────────────────────────────────────────────────────────

    /// Read `PRAGMA user_version` from a raw synchronous rusqlite handle so
    /// we can inspect the file after the isle driver has been shut down.
    fn read_user_version(path: &std::path::Path) -> i64 {
        let conn = rusqlite::Connection::open(path).unwrap();
        conn.query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap()
    }

    #[tokio::test]
    async fn sqlite_fresh_open_stamps_current_schema_version() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("replay.sqlite");

        let (store, driver) = SqliteReplayStore::open(&path).await.unwrap();

        // The new schema is usable: round-trip an entry through it.
        let run_id = RunId::new();
        let ctx = mk_ctx();
        let entry = ReplayEntry::from_completion(
            run_id.clone(),
            "step-a",
            "hash-a",
            0,
            &ctx,
            &json!({ "n": 1 }),
        )
        .unwrap();
        store.append(entry).await.unwrap();
        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].decode_step_output().unwrap(), json!({ "n": 1 }));

        driver.shutdown().await.unwrap();

        assert_eq!(read_user_version(&path), CURRENT_SCHEMA_VERSION);
    }

    #[tokio::test]
    async fn sqlite_legacy_schema_is_dropped_and_rebuilt() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("replay.sqlite");

        // Seed a legacy-shape DB: single `value_json` column and
        // `user_version = 0` (default). Populate one row so we can prove
        // the migration drops the whole legacy log.
        {
            let conn = rusqlite::Connection::open(&path).unwrap();
            conn.execute_batch(
                "CREATE TABLE replay_log (\
                    seq         INTEGER PRIMARY KEY AUTOINCREMENT, \
                    run_id      TEXT NOT NULL, \
                    step_ref    TEXT NOT NULL, \
                    input_hash  TEXT NOT NULL, \
                    occurrence  INTEGER NOT NULL, \
                    value_json  TEXT NOT NULL, \
                    created_at  INTEGER NOT NULL, \
                    UNIQUE (run_id, step_ref, input_hash, occurrence)\
                );",
            )
            .unwrap();
            conn.execute(
                "INSERT INTO replay_log \
                 (run_id, step_ref, input_hash, occurrence, value_json, created_at) \
                 VALUES ('legacy-run', 'legacy-step', 'legacy-hash', 0, 'legacy-value', 0)",
                [],
            )
            .unwrap();
            // `user_version` stays at 0 (the default), which is what a real
            // legacy file would carry.
        }

        assert_eq!(read_user_version(&path), 0, "seed sanity: user_version=0");

        // Open — should drop the legacy table, create the new schema, and
        // stamp `user_version = 1`.
        let (store, driver) = SqliteReplayStore::open(&path).await.unwrap();

        // The new schema accepts writes that the legacy schema could not
        // have held (the `ctx_snapshot_json` column exists).
        let run_id = RunId::new();
        let ctx = mk_ctx();
        let entry = ReplayEntry::from_completion(
            run_id.clone(),
            "step-a",
            "hash-a",
            0,
            &ctx,
            &json!({ "n": 42 }),
        )
        .unwrap();
        store.append(entry).await.unwrap();
        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 1);

        driver.shutdown().await.unwrap();

        assert_eq!(read_user_version(&path), CURRENT_SCHEMA_VERSION);

        // Legacy row must be gone (whole table was dropped).
        let conn = rusqlite::Connection::open(&path).unwrap();
        let legacy_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM replay_log WHERE run_id = 'legacy-run'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(legacy_count, 0, "legacy rows must be dropped");

        // And the new-shape column exists.
        let ctx_col_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM pragma_table_info('replay_log') \
                 WHERE name = 'ctx_snapshot_json'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(ctx_col_count, 1, "ctx_snapshot_json column must be present");
    }

    #[tokio::test]
    async fn sqlite_current_schema_open_is_idempotent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("replay.sqlite");

        // First open: creates the schema and stamps user_version = 1.
        let run_id = {
            let (store, driver) = SqliteReplayStore::open(&path).await.unwrap();
            let run_id = RunId::new();
            let ctx = mk_ctx();
            let entry = ReplayEntry::from_completion(
                run_id.clone(),
                "step-a",
                "hash-a",
                0,
                &ctx,
                &json!({ "n": 7 }),
            )
            .unwrap();
            store.append(entry).await.unwrap();
            driver.shutdown().await.unwrap();
            run_id
        };

        assert_eq!(read_user_version(&path), CURRENT_SCHEMA_VERSION);

        // Second open: should be a no-op migration-wise; prior rows must
        // survive.
        let (store, driver) = SqliteReplayStore::open(&path).await.unwrap();
        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 1, "prior rows must survive re-open");
        assert_eq!(listed[0].step_ref, "step-a");
        assert_eq!(listed[0].decode_step_output().unwrap(), json!({ "n": 7 }));
        driver.shutdown().await.unwrap();

        // Still at the current schema version.
        assert_eq!(read_user_version(&path), CURRENT_SCHEMA_VERSION);
    }

    #[tokio::test]
    async fn sqlite_delete_from_truncates_and_returns_count() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();
        for (step, occ) in [("a", 0), ("b", 0), ("c", 0), ("d", 0)] {
            store
                .append(
                    ReplayEntry::from_completion(
                        run_id.clone(),
                        step,
                        "h",
                        occ,
                        &ctx,
                        &json!({ "s": step }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
        }

        let dropped = store.delete_from(&run_id, 2).await.unwrap();
        assert_eq!(dropped, 2);

        let listed = store.list_by_run(&run_id).await.unwrap();
        let refs: Vec<String> = listed.iter().map(|e| e.step_ref.clone()).collect();
        assert_eq!(refs, vec!["a", "b"]);

        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_delete_from_past_length_is_noop() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();
        store
            .append(
                ReplayEntry::from_completion(run_id.clone(), "a", "h", 0, &ctx, &json!(1)).unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(store.delete_from(&run_id, 1).await.unwrap(), 0);
        assert_eq!(store.delete_from(&run_id, 99).await.unwrap(), 0);
        assert_eq!(store.list_by_run(&run_id).await.unwrap().len(), 1);

        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_delete_from_missing_run_is_noop() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        assert_eq!(store.delete_from(&run_id, 0).await.unwrap(), 0);
        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_delete_from_isolates_runs() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let r1 = RunId::new();
        let r2 = RunId::new();
        let ctx = mk_ctx();
        for step in ["a", "b"] {
            store
                .append(
                    ReplayEntry::from_completion(r1.clone(), step, "h", 0, &ctx, &json!(step))
                        .unwrap(),
                )
                .await
                .unwrap();
            store
                .append(
                    ReplayEntry::from_completion(r2.clone(), step, "h", 0, &ctx, &json!(step))
                        .unwrap(),
                )
                .await
                .unwrap();
        }
        assert_eq!(store.delete_from(&r1, 0).await.unwrap(), 2);
        assert!(store.list_by_run(&r1).await.unwrap().is_empty());
        assert_eq!(store.list_by_run(&r2).await.unwrap().len(), 2);
        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_delete_from_frees_slots_for_reappend() {
        let (store, driver) = SqliteReplayStore::open_in_memory().await.unwrap();
        let run_id = RunId::new();
        let ctx = mk_ctx();
        for step in ["a", "b"] {
            store
                .append(
                    ReplayEntry::from_completion(
                        run_id.clone(),
                        step,
                        "hash",
                        0,
                        &ctx,
                        &json!({ "v": step }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
        }
        assert_eq!(store.delete_from(&run_id, 1).await.unwrap(), 1);
        store
            .append(
                ReplayEntry::from_completion(
                    run_id.clone(),
                    "b",
                    "hash",
                    0,
                    &ctx,
                    &json!({ "v": "b-fresh" }),
                )
                .unwrap(),
            )
            .await
            .expect("re-append after delete_from must not collide with UNIQUE");
        let listed = store.list_by_run(&run_id).await.unwrap();
        assert_eq!(listed.len(), 2);
        assert_eq!(listed[0].step_ref, "a");
        assert_eq!(listed[1].step_ref, "b");
        assert_eq!(
            listed[1].decode_step_output().unwrap(),
            json!({ "v": "b-fresh" })
        );
        driver.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sqlite_future_schema_version_is_rejected() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("replay.sqlite");

        // Seed a file whose `user_version` is one ahead of what this binary
        // knows how to read.
        {
            let conn = rusqlite::Connection::open(&path).unwrap();
            conn.execute_batch(&format!(
                "PRAGMA user_version = {}",
                CURRENT_SCHEMA_VERSION + 1
            ))
            .unwrap();
        }

        let res = SqliteReplayStore::open(&path).await;
        let err = res
            .err()
            .expect("future user_version must be rejected by init_schema");
        // The error should carry the migration message verbatim through
        // `map_isle_err`.
        let msg = err.to_string();
        assert!(
            msg.contains("newer than supported"),
            "unexpected error message: {msg}"
        );
    }
}