camel-core 0.10.0

Core engine for rust-camel
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! Redb-backed runtime event journal.
//!
//! # Schema
//!
//! - Table `events`: `u64 → &[u8]`  (seq → serde_json bytes of `JournalEntry`)
//! - Table `command_ids`: `&str → ()`  (presence = alive)
//!
//! # Sequence numbers
//!
//! No autoincrement in redb. Each `append_batch` derives `next_seq` by reading
//! the last key via `iter().next_back()` and adding 1; defaults to 0 if empty.

use std::path::PathBuf;
use std::sync::Arc;

use async_trait::async_trait;
use redb::{
    Database, Durability, ReadableDatabase, ReadableTable, ReadableTableMetadata, TableDefinition,
};
use serde::{Deserialize, Serialize};

use camel_api::CamelError;

use crate::lifecycle::domain::{DomainError, RuntimeEvent};
use crate::lifecycle::ports::RuntimeEventJournalPort;

// ── Table definitions ─────────────────────────────────────────────────────────

const EVENTS_TABLE: TableDefinition<u64, &[u8]> = TableDefinition::new("events");
const COMMAND_IDS_TABLE: TableDefinition<&str, ()> = TableDefinition::new("command_ids");

// ── Public types ──────────────────────────────────────────────────────────────

/// Durability mode for journal writes.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum JournalDurability {
    /// fsync on every commit — protects against kernel crash and power loss (default).
    #[default]
    Immediate,
    /// No fsync — OS decides flush timing. Suitable for dev/test.
    Eventual,
}

/// Options for `RedbRuntimeEventJournal`.
#[derive(Debug, Clone)]
pub struct RedbJournalOptions {
    pub durability: JournalDurability,
    /// Trigger compaction after this many events in the table. Default: 10_000.
    pub compaction_threshold_events: u64,
}

impl Default for RedbJournalOptions {
    fn default() -> Self {
        Self {
            durability: JournalDurability::Immediate,
            compaction_threshold_events: 10_000,
        }
    }
}

/// Internal wire format stored as redb value bytes (serde_json).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JournalEntry {
    pub seq: u64,
    pub timestamp_ms: i64,
    pub event: RuntimeEvent,
}

/// Filter for `RedbRuntimeEventJournal::inspect`.
pub struct JournalInspectFilter {
    pub route_id: Option<String>,
    pub limit: usize,
}

// ── Adapter ───────────────────────────────────────────────────────────────────

/// Redb-backed implementation of `RuntimeEventJournalPort`.
///
/// `Arc<Database>` allows cheap cloning — all clones share the same underlying
/// redb file handle. `redb::Database` is `Send + Sync`.
#[derive(Clone)]
pub struct RedbRuntimeEventJournal {
    db: Arc<Database>,
    options: RedbJournalOptions,
}

impl RedbRuntimeEventJournal {
    /// Open (or create) the redb database at `path`.
    ///
    /// Parent directories are created if they do not exist.
    /// Both tables are initialised on first open.
    /// Uses `tokio::task::spawn_blocking` because `Database::open` is blocking.
    pub async fn new(
        path: impl Into<PathBuf>,
        options: RedbJournalOptions,
    ) -> Result<Self, CamelError> {
        let path = path.into();
        let db = tokio::task::spawn_blocking(move || {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    CamelError::Io(format!(
                        "failed to create journal directory '{}': {e}",
                        parent.display()
                    ))
                })?;
            }
            let db = Database::create(&path).map_err(|e| {
                CamelError::Io(format!(
                    "failed to open journal at '{}': {e}",
                    path.display()
                ))
            })?;
            // Initialise tables so they exist before any reads.
            let tx = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            tx.open_table(EVENTS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open events table: {e}")))?;
            tx.open_table(COMMAND_IDS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open command_ids table: {e}")))?;
            tx.commit()
                .map_err(|e| CamelError::Io(format!("redb commit init: {e}")))?;
            Ok::<_, CamelError>(db)
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;

        Ok(Self {
            db: Arc::new(db),
            options,
        })
    }

    /// Open an existing database at `path` and return entries (newest-first, up to `filter.limit`).
    ///
    /// Uses `Database::open` + `begin_read` — concurrent with a live writer on the same file.
    /// `inspect` is an offline utility: it does NOT require a live `RedbRuntimeEventJournal` instance.
    pub async fn inspect(
        path: impl Into<PathBuf>,
        filter: JournalInspectFilter,
    ) -> Result<Vec<JournalEntry>, CamelError> {
        let path = path.into();
        let limit = filter.limit;
        let route_id = filter.route_id;
        tokio::task::spawn_blocking(move || {
            if !path.exists() {
                return Err(CamelError::Io(format!(
                    "journal file not found: {}",
                    path.display()
                )));
            }
            let db = Database::open(&path)
                .map_err(|e| CamelError::Io(format!("invalid journal file: {e}")))?;
            let tx = db
                .begin_read()
                .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
            let table = tx
                .open_table(EVENTS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open events: {e}")))?;

            // Collect in descending order (newest first).
            // Filter by route_id FIRST, then apply limit — ensures we return
            // `limit` matching entries, not `limit` total entries where most may
            // not match the filter.
            let mut entries: Vec<JournalEntry> = Vec::new();
            for result in table
                .iter()
                .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
                .rev()
            {
                let (_k, v) = result.map_err(|e| CamelError::Io(format!("redb read: {e}")))?;
                let entry: JournalEntry = serde_json::from_slice(v.value())
                    .map_err(|e| CamelError::Io(format!("journal deserialize: {e}")))?;
                if let Some(ref rid) = route_id
                    && entry.event.route_id() != rid.as_str()
                {
                    continue;
                }
                if entries.len() >= limit {
                    break;
                }
                entries.push(entry);
            }
            Ok(entries)
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))?
    }

    // ── Internal helpers ──────────────────────────────────────────────────────

    fn redb_durability(&self) -> Durability {
        match self.options.durability {
            JournalDurability::Immediate => Durability::Immediate,
            JournalDurability::Eventual => Durability::None,
        }
    }

    /// Derive next sequence number from the last key in the events table.
    /// Must be called inside a write transaction with the table already open.
    fn next_seq(table: &redb::Table<u64, &[u8]>) -> Result<u64, CamelError> {
        match table
            .iter()
            .map_err(|e| CamelError::Io(format!("redb iter for seq: {e}")))?
            .next_back()
        {
            Some(Ok((k, _))) => Ok(k.value() + 1),
            Some(Err(e)) => Err(CamelError::Io(format!("redb seq read: {e}"))),
            None => Ok(0),
        }
    }

    /// Count rows in the events table (read transaction).
    fn event_count(&self) -> Result<u64, CamelError> {
        let tx = self
            .db
            .begin_read()
            .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
        let table = tx
            .open_table(EVENTS_TABLE)
            .map_err(|e| CamelError::Io(format!("redb open events: {e}")))?;
        table
            .len()
            .map_err(|e| CamelError::Io(format!("redb len: {e}")))
    }

    /// Compact the events table: remove events for routes that have been fully removed.
    fn compact(&self) -> Result<(), CamelError> {
        let tx = self
            .db
            .begin_write()
            .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
        {
            let mut table = tx
                .open_table(EVENTS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open events: {e}")))?;

            // Pass 1: read all events in key order, find last RouteRemoved seq per route.
            let mut last_removed_seq: std::collections::HashMap<String, u64> =
                std::collections::HashMap::new();
            for result in table
                .iter()
                .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
            {
                let (k, v) = result.map_err(|e| CamelError::Io(format!("redb read: {e}")))?;
                let seq = k.value();
                let entry: JournalEntry = serde_json::from_slice(v.value())
                    .map_err(|e| CamelError::Io(format!("journal deserialize: {e}")))?;
                if matches!(entry.event, RuntimeEvent::RouteRemoved { .. }) {
                    last_removed_seq.insert(entry.event.route_id().to_string(), seq);
                }
            }

            if last_removed_seq.is_empty() {
                drop(table);
                tx.commit()
                    .map_err(|e| CamelError::Io(format!("redb commit compact: {e}")))?;
                return Ok(());
            }

            // Pass 2: collect seqs to delete.
            let mut to_delete: Vec<u64> = Vec::new();
            for result in table
                .iter()
                .map_err(|e| CamelError::Io(format!("redb iter pass2: {e}")))?
            {
                let (k, v) = result.map_err(|e| CamelError::Io(format!("redb read: {e}")))?;
                let seq = k.value();
                let entry: JournalEntry = serde_json::from_slice(v.value())
                    .map_err(|e| CamelError::Io(format!("journal deserialize: {e}")))?;
                let route_id = entry.event.route_id().to_string();
                if let Some(&cutoff) = last_removed_seq.get(&route_id)
                    && seq <= cutoff
                {
                    to_delete.push(seq);
                }
            }

            for seq in to_delete {
                table
                    .remove(&seq)
                    .map_err(|e| CamelError::Io(format!("redb remove seq {seq}: {e}")))?;
            }
        }
        tx.commit()
            .map_err(|e| CamelError::Io(format!("redb commit compact: {e}")))?;
        Ok(())
    }
}

// ── RuntimeEvent helper ───────────────────────────────────────────────────────

/// Extension to extract the `route_id` field from any `RuntimeEvent` variant.
trait RuntimeEventExt {
    fn route_id(&self) -> &str;
}

impl RuntimeEventExt for RuntimeEvent {
    fn route_id(&self) -> &str {
        match self {
            RuntimeEvent::RouteRegistered { route_id }
            | RuntimeEvent::RouteStartRequested { route_id }
            | RuntimeEvent::RouteStarted { route_id }
            | RuntimeEvent::RouteFailed { route_id, .. }
            | RuntimeEvent::RouteStopped { route_id }
            | RuntimeEvent::RouteSuspended { route_id }
            | RuntimeEvent::RouteResumed { route_id }
            | RuntimeEvent::RouteReloaded { route_id }
            | RuntimeEvent::RouteRemoved { route_id } => route_id,
        }
    }
}

// ── RuntimeEventJournalPort impl ──────────────────────────────────────────────

#[async_trait]
impl RuntimeEventJournalPort for RedbRuntimeEventJournal {
    async fn append_batch(&self, events: &[RuntimeEvent]) -> Result<(), DomainError> {
        if events.is_empty() {
            return Ok(());
        }
        let db = Arc::clone(&self.db);
        let durability = self.redb_durability();
        let events = events.to_vec();
        let now_ms = chrono::Utc::now().timestamp_millis();

        tokio::task::spawn_blocking(move || {
            // NOTE: `mut` is required — `set_durability` takes `&mut self` in redb v2.
            let mut tx = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            tx.set_durability(durability)
                .map_err(|e| CamelError::Io(format!("redb set_durability: {e}")))?;
            {
                let mut table = tx
                    .open_table(EVENTS_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open events: {e}")))?;
                let start_seq = Self::next_seq(&table)?;
                for (next_seq, event) in (start_seq..).zip(events) {
                    let entry = JournalEntry {
                        seq: next_seq,
                        timestamp_ms: now_ms,
                        event,
                    };
                    let bytes = serde_json::to_vec(&entry)
                        .map_err(|e| CamelError::Io(format!("journal serialize: {e}")))?;
                    table
                        .insert(&next_seq, bytes.as_slice())
                        .map_err(|e| CamelError::Io(format!("redb insert: {e}")))?;
                }
            }
            tx.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<_, CamelError>(())
        })
        .await
        .map_err(|e| DomainError::InvalidState(format!("spawn_blocking join: {e}")))?
        .map_err(|e| DomainError::InvalidState(e.to_string()))?;

        // Trigger compaction if threshold exceeded. Non-fatal if it fails.
        // Both event_count() and compact() do blocking redb I/O — run in spawn_blocking.
        let journal_clone = self.clone();
        let threshold = self.options.compaction_threshold_events;
        tokio::task::spawn_blocking(move || match journal_clone.event_count() {
            Ok(count) if count >= threshold => {
                if let Err(e) = journal_clone.compact() {
                    tracing::warn!("journal compaction failed (non-fatal): {e}");
                }
            }
            Ok(_) => {}
            Err(e) => {
                tracing::warn!("journal event count check failed (non-fatal): {e}");
            }
        })
        .await
        .ok(); // Non-fatal: if spawn_blocking panics, we ignore it

        Ok(())
    }

    async fn load_all(&self) -> Result<Vec<RuntimeEvent>, DomainError> {
        let db = Arc::clone(&self.db);
        tokio::task::spawn_blocking(move || {
            let tx = db
                .begin_read()
                .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
            let table = tx
                .open_table(EVENTS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open events: {e}")))?;
            let mut events = Vec::new();
            for result in table
                .iter()
                .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
            {
                let (_k, v) = result.map_err(|e| CamelError::Io(format!("redb read: {e}")))?;
                let entry: JournalEntry = serde_json::from_slice(v.value())
                    .map_err(|e| CamelError::Io(format!("journal deserialize: {e}")))?;
                events.push(entry.event);
            }
            Ok(events)
        })
        .await
        .map_err(|e| DomainError::InvalidState(format!("spawn_blocking join: {e}")))?
        .map_err(|e: CamelError| DomainError::InvalidState(e.to_string()))
    }

    async fn append_command_id(&self, command_id: &str) -> Result<(), DomainError> {
        let db = Arc::clone(&self.db);
        let durability = self.redb_durability();
        let id = command_id.to_string();
        tokio::task::spawn_blocking(move || {
            // NOTE: `mut` required — `set_durability` takes `&mut self` in redb v2.
            let mut tx = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            tx.set_durability(durability)
                .map_err(|e| CamelError::Io(format!("redb set_durability: {e}")))?;
            {
                let mut table = tx
                    .open_table(COMMAND_IDS_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open command_ids: {e}")))?;
                table
                    .insert(id.as_str(), ())
                    .map_err(|e| CamelError::Io(format!("redb insert command_id: {e}")))?;
            }
            tx.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<_, CamelError>(())
        })
        .await
        .map_err(|e| DomainError::InvalidState(format!("spawn_blocking join: {e}")))?
        .map_err(|e| DomainError::InvalidState(e.to_string()))
    }

    async fn remove_command_id(&self, command_id: &str) -> Result<(), DomainError> {
        let db = Arc::clone(&self.db);
        let durability = self.redb_durability();
        let id = command_id.to_string();
        tokio::task::spawn_blocking(move || {
            // NOTE: `mut` required — `set_durability` takes `&mut self` in redb v2.
            let mut tx = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            tx.set_durability(durability)
                .map_err(|e| CamelError::Io(format!("redb set_durability: {e}")))?;
            {
                let mut table = tx
                    .open_table(COMMAND_IDS_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open command_ids: {e}")))?;
                table
                    .remove(id.as_str())
                    .map_err(|e| CamelError::Io(format!("redb remove command_id: {e}")))?;
            }
            tx.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<_, CamelError>(())
        })
        .await
        .map_err(|e| DomainError::InvalidState(format!("spawn_blocking join: {e}")))?
        .map_err(|e| DomainError::InvalidState(e.to_string()))
    }

    async fn load_command_ids(&self) -> Result<Vec<String>, DomainError> {
        let db = Arc::clone(&self.db);
        tokio::task::spawn_blocking(move || {
            let tx = db
                .begin_read()
                .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
            let table = tx
                .open_table(COMMAND_IDS_TABLE)
                .map_err(|e| CamelError::Io(format!("redb open command_ids: {e}")))?;
            let mut ids = Vec::new();
            for result in table
                .iter()
                .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
            {
                let (k, _) = result.map_err(|e| CamelError::Io(format!("redb read: {e}")))?;
                ids.push(k.value().to_string());
            }
            Ok(ids)
        })
        .await
        .map_err(|e| DomainError::InvalidState(format!("spawn_blocking join: {e}")))?
        .map_err(|e: CamelError| DomainError::InvalidState(e.to_string()))
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    async fn new_journal(dir: &tempfile::TempDir) -> RedbRuntimeEventJournal {
        RedbRuntimeEventJournal::new(dir.path().join("test.db"), RedbJournalOptions::default())
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn redb_journal_roundtrip() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        let events = vec![
            RuntimeEvent::RouteRegistered {
                route_id: "r1".to_string(),
            },
            RuntimeEvent::RouteStarted {
                route_id: "r1".to_string(),
            },
        ];
        journal.append_batch(&events).await.unwrap();

        let loaded = journal.load_all().await.unwrap();
        assert_eq!(loaded, events);
    }

    #[tokio::test]
    async fn redb_journal_command_id_lifecycle() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        journal.append_command_id("c1").await.unwrap();
        journal.append_command_id("c2").await.unwrap();
        journal.remove_command_id("c1").await.unwrap();

        let ids = journal.load_command_ids().await.unwrap();
        assert_eq!(ids, vec!["c2".to_string()]);
    }

    #[tokio::test]
    async fn redb_journal_compaction_removes_completed_routes() {
        let dir = tempdir().unwrap();
        // Threshold of 1 triggers compaction on every append.
        let journal = RedbRuntimeEventJournal::new(
            dir.path().join("compact.db"),
            RedbJournalOptions {
                durability: JournalDurability::Eventual,
                compaction_threshold_events: 1,
            },
        )
        .await
        .unwrap();

        // Removed route — full lifecycle.
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "old".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRemoved {
                route_id: "old".to_string(),
            }])
            .await
            .unwrap();

        // Active route — no RouteRemoved.
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "live".to_string(),
            }])
            .await
            .unwrap();

        let loaded = journal.load_all().await.unwrap();
        assert!(
            !loaded.iter().any(
                |e| matches!(e, RuntimeEvent::RouteRegistered { route_id } if route_id == "old")
            ),
            "old route events must be compacted"
        );
        assert!(
            loaded.iter().any(
                |e| matches!(e, RuntimeEvent::RouteRegistered { route_id } if route_id == "live")
            ),
            "live route events must survive compaction"
        );
    }

    #[tokio::test]
    async fn redb_journal_compaction_preserves_reregistered_route() {
        let dir = tempdir().unwrap();
        let journal = RedbRuntimeEventJournal::new(
            dir.path().join("rereg.db"),
            RedbJournalOptions {
                durability: JournalDurability::Eventual,
                compaction_threshold_events: 1,
            },
        )
        .await
        .unwrap();

        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "rereg".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRemoved {
                route_id: "rereg".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "rereg".to_string(),
            }])
            .await
            .unwrap();

        let loaded = journal.load_all().await.unwrap();
        let rereg_count = loaded
            .iter()
            .filter(
                |e| matches!(e, RuntimeEvent::RouteRegistered { route_id } if route_id == "rereg"),
            )
            .count();
        assert_eq!(
            rereg_count, 1,
            "re-registered route must have exactly one event after compaction"
        );
    }

    #[tokio::test]
    async fn redb_journal_durability_eventual() {
        let dir = tempdir().unwrap();
        let journal = RedbRuntimeEventJournal::new(
            dir.path().join("eventual.db"),
            RedbJournalOptions {
                durability: JournalDurability::Eventual,
                compaction_threshold_events: 10_000,
            },
        )
        .await
        .unwrap();

        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "ev".to_string(),
            }])
            .await
            .unwrap();
        let loaded = journal.load_all().await.unwrap();
        assert_eq!(loaded.len(), 1);
    }

    #[tokio::test]
    async fn redb_journal_clone_shares_db() {
        let dir = tempdir().unwrap();
        let j1 = new_journal(&dir).await;
        let j2 = j1.clone();

        j1.append_batch(&[RuntimeEvent::RouteRegistered {
            route_id: "shared".to_string(),
        }])
        .await
        .unwrap();

        // j2 must see j1's write since they share the same Arc<Database>.
        let loaded = j2.load_all().await.unwrap();
        assert_eq!(loaded.len(), 1);
    }

    #[tokio::test]
    async fn redb_journal_append_empty_batch_is_noop() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        journal.append_batch(&[]).await.unwrap();
        let loaded = journal.load_all().await.unwrap();
        assert!(loaded.is_empty());
    }

    #[tokio::test]
    async fn redb_journal_sequence_numbers_across_batches() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        journal
            .append_batch(&[
                RuntimeEvent::RouteRegistered {
                    route_id: "r1".to_string(),
                },
                RuntimeEvent::RouteStarted {
                    route_id: "r1".to_string(),
                },
            ])
            .await
            .unwrap();

        journal
            .append_batch(&[RuntimeEvent::RouteStopped {
                route_id: "r1".to_string(),
            }])
            .await
            .unwrap();

        let loaded = journal.load_all().await.unwrap();
        assert_eq!(loaded.len(), 3);

        // Drop journal to release redb lock before inspect.
        drop(journal);

        // Verify sequence numbers are monotonic.
        let entries = RedbRuntimeEventJournal::inspect(
            dir.path().join("test.db"),
            JournalInspectFilter {
                route_id: None,
                limit: 10,
            },
        )
        .await
        .unwrap();
        let seqs: Vec<u64> = entries.iter().map(|e| e.seq).collect();
        // inspect returns newest-first.
        assert_eq!(seqs, vec![2, 1, 0]);
    }

    #[tokio::test]
    async fn redb_journal_load_all_empty() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;
        let loaded = journal.load_all().await.unwrap();
        assert!(loaded.is_empty());
    }

    #[tokio::test]
    async fn redb_journal_inspect_file_not_found() {
        let dir = tempdir().unwrap();
        let result = RedbRuntimeEventJournal::inspect(
            dir.path().join("nonexistent.db"),
            JournalInspectFilter {
                route_id: None,
                limit: 10,
            },
        )
        .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("journal file not found"));
    }

    #[tokio::test]
    async fn redb_journal_inspect_with_route_id_filter() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        journal
            .append_batch(&[
                RuntimeEvent::RouteRegistered {
                    route_id: "alpha".to_string(),
                },
                RuntimeEvent::RouteRegistered {
                    route_id: "beta".to_string(),
                },
                RuntimeEvent::RouteStarted {
                    route_id: "alpha".to_string(),
                },
            ])
            .await
            .unwrap();

        drop(journal);

        let entries = RedbRuntimeEventJournal::inspect(
            dir.path().join("test.db"),
            JournalInspectFilter {
                route_id: Some("alpha".to_string()),
                limit: 10,
            },
        )
        .await
        .unwrap();

        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|e| {
            matches!(&e.event, RuntimeEvent::RouteRegistered { route_id } | RuntimeEvent::RouteStarted { route_id } if route_id == "alpha")
        }));
    }

    #[tokio::test]
    async fn redb_journal_inspect_limit_enforcement() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        for i in 0..5 {
            journal
                .append_batch(&[RuntimeEvent::RouteRegistered {
                    route_id: format!("r{i}"),
                }])
                .await
                .unwrap();
        }

        drop(journal);

        let entries = RedbRuntimeEventJournal::inspect(
            dir.path().join("test.db"),
            JournalInspectFilter {
                route_id: None,
                limit: 2,
            },
        )
        .await
        .unwrap();

        assert_eq!(entries.len(), 2);
        // Newest first: r4, r3
        assert!(
            matches!(&entries[0].event, RuntimeEvent::RouteRegistered { route_id } if route_id == "r4")
        );
        assert!(
            matches!(&entries[1].event, RuntimeEvent::RouteRegistered { route_id } if route_id == "r3")
        );
    }

    #[tokio::test]
    async fn redb_journal_inspect_limit_with_filter_returns_matching_count() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        // Interleave alpha and beta events.
        for i in 0..4 {
            let rid = if i % 2 == 0 { "alpha" } else { "beta" };
            journal
                .append_batch(&[RuntimeEvent::RouteRegistered {
                    route_id: rid.to_string(),
                }])
                .await
                .unwrap();
        }

        drop(journal);

        // limit=1 but 2 alpha events exist — should return exactly 1 alpha.
        let entries = RedbRuntimeEventJournal::inspect(
            dir.path().join("test.db"),
            JournalInspectFilter {
                route_id: Some("alpha".to_string()),
                limit: 1,
            },
        )
        .await
        .unwrap();

        assert_eq!(entries.len(), 1);
        assert!(
            matches!(&entries[0].event, RuntimeEvent::RouteRegistered { route_id } if route_id == "alpha")
        );
    }

    #[test]
    fn redb_journal_durability_default_is_immediate() {
        assert_eq!(JournalDurability::default(), JournalDurability::Immediate);
    }

    #[test]
    fn redb_journal_options_default() {
        let opts = RedbJournalOptions::default();
        assert_eq!(opts.durability, JournalDurability::Immediate);
        assert_eq!(opts.compaction_threshold_events, 10_000);
    }

    #[test]
    fn redb_journal_entry_serialization_roundtrip() {
        let entry = JournalEntry {
            seq: 42,
            timestamp_ms: 1_700_000_000_000,
            event: RuntimeEvent::RouteFailed {
                route_id: "fail-route".to_string(),
                error: "boom".to_string(),
            },
        };

        let bytes = serde_json::to_vec(&entry).unwrap();
        let decoded: JournalEntry = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(decoded.seq, 42);
        assert_eq!(decoded.timestamp_ms, 1_700_000_000_000);
        assert_eq!(decoded.event, entry.event);
    }

    #[test]
    fn redb_journal_runtime_event_ext_all_variants() {
        let events = [
            RuntimeEvent::RouteRegistered {
                route_id: "a".into(),
            },
            RuntimeEvent::RouteStartRequested {
                route_id: "b".into(),
            },
            RuntimeEvent::RouteStarted {
                route_id: "c".into(),
            },
            RuntimeEvent::RouteFailed {
                route_id: "d".into(),
                error: "err".into(),
            },
            RuntimeEvent::RouteStopped {
                route_id: "e".into(),
            },
            RuntimeEvent::RouteSuspended {
                route_id: "f".into(),
            },
            RuntimeEvent::RouteResumed {
                route_id: "g".into(),
            },
            RuntimeEvent::RouteReloaded {
                route_id: "h".into(),
            },
            RuntimeEvent::RouteRemoved {
                route_id: "i".into(),
            },
        ];
        let expected = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
        for (event, expected_id) in events.iter().zip(expected.iter()) {
            assert_eq!(event.route_id(), *expected_id);
        }
    }

    #[tokio::test]
    async fn redb_journal_compaction_no_removed_routes_early_return() {
        let dir = tempdir().unwrap();
        let journal = RedbRuntimeEventJournal::new(
            dir.path().join("no_remove.db"),
            RedbJournalOptions {
                durability: JournalDurability::Eventual,
                compaction_threshold_events: 1,
            },
        )
        .await
        .unwrap();

        // Only registered and started — no RouteRemoved.
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "active".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteStarted {
                route_id: "active".to_string(),
            }])
            .await
            .unwrap();

        let loaded = journal.load_all().await.unwrap();
        assert_eq!(loaded.len(), 2);
    }

    #[tokio::test]
    async fn redb_journal_command_ids_multiple_and_remove_nonexistent() {
        let dir = tempdir().unwrap();
        let journal = new_journal(&dir).await;

        journal.append_command_id("cmd1").await.unwrap();
        journal.append_command_id("cmd2").await.unwrap();
        journal.append_command_id("cmd3").await.unwrap();

        // Remove a non-existent command — should not error.
        journal.remove_command_id("nonexistent").await.unwrap();

        let ids = journal.load_command_ids().await.unwrap();
        assert_eq!(ids.len(), 3);
        assert!(ids.contains(&"cmd1".to_string()));
        assert!(ids.contains(&"cmd2".to_string()));
        assert!(ids.contains(&"cmd3".to_string()));
    }

    #[tokio::test]
    async fn redb_journal_multiple_routes_compaction() {
        let dir = tempdir().unwrap();
        let journal = RedbRuntimeEventJournal::new(
            dir.path().join("multi_compact.db"),
            RedbJournalOptions {
                durability: JournalDurability::Eventual,
                compaction_threshold_events: 1,
            },
        )
        .await
        .unwrap();

        // Two removed routes, one active.
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "removed1".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRemoved {
                route_id: "removed1".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "removed2".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRemoved {
                route_id: "removed2".to_string(),
            }])
            .await
            .unwrap();
        journal
            .append_batch(&[RuntimeEvent::RouteRegistered {
                route_id: "kept".to_string(),
            }])
            .await
            .unwrap();

        let loaded = journal.load_all().await.unwrap();
        assert!(
            !loaded.iter().any(|e| matches!(e, RuntimeEvent::RouteRegistered { route_id } if route_id == "removed1" || route_id == "removed2")),
            "removed routes must be compacted"
        );
        assert!(
            loaded.iter().any(
                |e| matches!(e, RuntimeEvent::RouteRegistered { route_id } if route_id == "kept")
            ),
            "kept route must survive"
        );
    }
}