datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
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
use std::{
    alloc::{GlobalAlloc, Layout, System},
    env,
    hint::black_box,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

#[cfg(feature = "rocksdb")]
use std::{
    path::PathBuf,
    time::{SystemTime, UNIX_EPOCH},
};

use datum_persistence::{
    AppendOutcome, AtomicWrite, DurableStateStore, Effect, EventSourcedBehavior,
    EventSourcedHandle, EventSourcedRuntime, IdentityAdapter, Journal, MemoryDurableStateStore,
    MemoryJournal, MemorySnapshotStore, PersistenceError, PersistenceId, PersistenceResult,
    PersistenceSerializer, Revision, SequenceNr, SerializedPayload, SerializerCatalog,
    SerializerId, SnapshotCriteria, SnapshotMetadata, SnapshotStore, StoredEvent, Tag,
    query::{EventsByTagQuery, Offset, QueryMode},
};
use futures_util::{StreamExt, future::join_all};
use tokio::runtime::{Builder, Runtime};

#[cfg(feature = "rocksdb")]
use datum_persistence::RocksDbBackend;
#[cfg(feature = "cassandra")]
use datum_persistence::{CassandraPersistence, CassandraPersistenceConfig, CassandraWriteMode};
#[cfg(feature = "postgres")]
use datum_persistence::{PostgresPersistence, PostgresPersistenceConfig};

const WARMUP_SAMPLES: usize = 1;
const MEASUREMENT_SAMPLES: usize = 5;
const SINGLE_EVENTS: u64 = 1_000;
const PERSIST_ALL_BATCHES: u64 = 100;
const PERSIST_ALL_BATCH_SIZE: u64 = 10;
const RECOVERY_EVENTS: u64 = 10_000;
const QUERY_EVENTS: u64 = 10_000;
const CONCURRENCY: [usize; 5] = [1, 16, 64, 256, 1_024];

static NEXT_ID: AtomicU64 = AtomicU64::new(1);

// Counting global allocator, confined to this compare-runner binary (a
// separate crate root under `src/bin/`, not compiled into the
// `datum-persistence` library — the library stays free of any global
// allocator override). Mirrors the same pattern already used by
// `datum-core`'s `*_compare.rs` runners and `datum-net`'s `net_compare.rs`,
// extended here to also count allocation calls (not just bytes) so the
// rendered table can show both `alloc/op` and `bytes/op`.
struct CountingAllocator;

static ALLOCATED_BYTES: AtomicU64 = AtomicU64::new(0);
static ALLOCATED_COUNT: AtomicU64 = AtomicU64::new(0);

unsafe impl GlobalAlloc for CountingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = unsafe { System.alloc(layout) };
        if !ptr.is_null() {
            ALLOCATED_BYTES.fetch_add(layout.size() as u64, Ordering::Relaxed);
            ALLOCATED_COUNT.fetch_add(1, Ordering::Relaxed);
        }
        ptr
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        let ptr = unsafe { System.alloc_zeroed(layout) };
        if !ptr.is_null() {
            ALLOCATED_BYTES.fetch_add(layout.size() as u64, Ordering::Relaxed);
            ALLOCATED_COUNT.fetch_add(1, Ordering::Relaxed);
        }
        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) };
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        let new_ptr = unsafe { System.realloc(ptr, layout, new_size) };
        if !new_ptr.is_null() {
            ALLOCATED_COUNT.fetch_add(1, Ordering::Relaxed);
            // Deterministic accounting: charge the grown size regardless of
            // whether the allocator resized in place or moved, so bytes/op
            // does not depend on allocator luck.
            if new_ptr == ptr {
                if new_size > layout.size() {
                    ALLOCATED_BYTES.fetch_add((new_size - layout.size()) as u64, Ordering::Relaxed);
                }
            } else {
                ALLOCATED_BYTES.fetch_add(new_size as u64, Ordering::Relaxed);
            }
        }
        new_ptr
    }
}

#[global_allocator]
static GLOBAL: CountingAllocator = CountingAllocator;

#[derive(Clone, Copy)]
struct U64Serializer;

impl PersistenceSerializer<u64> for U64Serializer {
    fn serializer_id(&self) -> SerializerId {
        SerializerId::new(9_109)
    }

    fn manifest(&self, _value: &u64) -> String {
        "datum-bench-u64-v1".into()
    }

    fn serialize(&self, value: &u64) -> PersistenceResult<Vec<u8>> {
        Ok(value.to_be_bytes().to_vec())
    }

    fn deserialize(&self, manifest: &str, payload: &[u8]) -> PersistenceResult<u64> {
        if manifest != "datum-bench-u64-v1" || payload.len() != size_of::<u64>() {
            return Err(PersistenceError::Serialization(
                "invalid persistence comparison u64 frame".into(),
            ));
        }
        let mut bytes = [0_u8; size_of::<u64>()];
        bytes.copy_from_slice(payload);
        Ok(u64::from_be_bytes(bytes))
    }
}

fn catalog() -> SerializerCatalog<u64> {
    SerializerCatalog::new(U64Serializer)
}

fn next_persistence_id(scenario: &str) -> PersistenceId {
    let process = std::process::id();
    let unique = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    PersistenceId::new(
        "persistence-compare",
        format!("{scenario}-{process}-{unique}"),
    )
    .expect("comparison persistence id is valid")
}

fn counter_behavior<C, H>(
    persistence_id: PersistenceId,
    command_handler: H,
) -> EventSourcedBehavior<C, u64, u64>
where
    C: datum::actor::Message,
    H: Fn(&u64, C) -> Effect<C, u64, u64> + Send + Sync + 'static,
{
    EventSourcedBehavior::new(
        persistence_id,
        0_u64,
        command_handler,
        |state: &u64, event: &u64| state.wrapping_add(*event),
    )
    .with_event_adapter(IdentityAdapter, catalog())
    .with_state_adapter(IdentityAdapter, catalog())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let runtime = Builder::new_multi_thread()
        .worker_threads(4)
        .enable_all()
        .build()?;

    println!(
        "scenario\tbackend\titerations\tmean_us\twall_p50_us\twall_p99_us\tcpu_us_per_op\talloc_count_per_op\talloc_bytes_per_op\tthread_count\tpeak_rss_kib\tnotes"
    );

    let memory_journal = Arc::new(MemoryJournal::new());
    run_backend_scenarios(
        &runtime,
        "memory",
        "in-memory · reference backend",
        memory_journal.clone(),
        Arc::new(MemorySnapshotStore::new()),
        Arc::new(MemoryDurableStateStore::new()),
        memory_journal,
    )?;

    #[cfg(feature = "rocksdb")]
    {
        let directory = TemporaryDatabasePath::new("rocksdb");
        let backend = Arc::new(RocksDbBackend::open(directory.path())?);
        run_backend_scenarios(
            &runtime,
            "rocksdb",
            "embedded · Datum-only · synchronous WAL",
            backend.clone(),
            backend.clone(),
            backend.clone(),
            backend,
        )?;
        drop(directory);
    }
    #[cfg(not(feature = "rocksdb"))]
    eprintln!("SKIP rocksdb: rebuild with --features rocksdb");

    #[cfg(feature = "postgres")]
    match env::var("DATABASE_URL") {
        Ok(database_url) if !database_url.trim().is_empty() => {
            let mut config = PostgresPersistenceConfig::new(database_url);
            config.schema = "datum_persistence_bench".into();
            config.max_connections = 16;
            // Benchmark A/B toggle for the WP-P3 cross-entity group commit.
            if env::var("DATUM_PERSISTENCE_GROUP_COMMIT")
                .is_ok_and(|value| value.eq_ignore_ascii_case("off"))
            {
                config.group_commit.enabled = false;
            }
            // Benchmark toggle for the WP-P3 follow-up concurrency-threshold
            // bypass: overrides `bypass_below` (e.g. set to `0` to disable it
            // and force every write through the flusher, reproducing the
            // pre-bypass measurement).
            if let Ok(value) = env::var("DATUM_PERSISTENCE_GROUP_COMMIT_BYPASS_BELOW") {
                config.group_commit.bypass_below = value
                    .parse()
                    .expect("DATUM_PERSISTENCE_GROUP_COMMIT_BYPASS_BELOW must be a usize");
            }
            let backend = Arc::new(runtime.block_on(PostgresPersistence::connect(config))?);
            run_postgres_scenarios(&runtime, backend)?;
        }
        _ => eprintln!("SKIP postgres: DATABASE_URL is not set"),
    }
    #[cfg(not(feature = "postgres"))]
    eprintln!("SKIP postgres: rebuild with --features postgres");

    #[cfg(feature = "cassandra")]
    match env::var("CASSANDRA_NODE") {
        Ok(cassandra_node) if !cassandra_node.trim().is_empty() => {
            run_cassandra_scenarios(&runtime, cassandra_node)?;
        }
        _ => eprintln!("SKIP cassandra: CASSANDRA_NODE is not set"),
    }
    #[cfg(not(feature = "cassandra"))]
    eprintln!("SKIP cassandra: rebuild with --features cassandra");

    Ok(())
}

fn run_backend_scenarios<J, S, D, Q>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    journal: Arc<J>,
    snapshots: Arc<S>,
    durable: Arc<D>,
    query: Arc<Q>,
) -> PersistenceResult<()>
where
    J: Journal + 'static,
    S: SnapshotStore + 'static,
    D: DurableStateStore + 'static,
    Q: Journal + EventsByTagQuery + 'static,
{
    run_persist_scenarios(runtime, backend, note, journal.clone())?;
    run_recovery_scenario(runtime, backend, note, journal.clone(), snapshots.clone())?;
    run_concurrency_sweep(runtime, backend, note, journal)?;
    run_snapshot_scenario(runtime, backend, note, snapshots)?;
    run_durable_state_scenario(runtime, backend, note, durable)?;
    run_tag_query_scenario(runtime, backend, note, query)?;
    Ok(())
}

#[cfg(feature = "postgres")]
fn run_postgres_scenarios(
    runtime: &Runtime,
    backend: Arc<PostgresPersistence>,
) -> PersistenceResult<()> {
    const NOTE: &str = "PostgreSQL · synchronous commit · 16-connection pool";
    run_persist_scenarios(runtime, "postgres", NOTE, backend.clone())?;
    run_recovery_scenario(runtime, "postgres", NOTE, backend.clone(), backend.clone())?;
    run_concurrency_sweep(runtime, "postgres", NOTE, backend.clone())?;
    run_snapshot_scenario(runtime, "postgres", NOTE, backend.clone())?;
    run_durable_state_scenario(runtime, "postgres", NOTE, backend)?;
    Ok(())
}

#[cfg(feature = "cassandra")]
fn run_cassandra_scenarios(runtime: &Runtime, node: String) -> PersistenceResult<()> {
    const NOTE: &str = "Cassandra 5 · same node · Akka = akka-persistence-cassandra · LWT-guarded default (stricter guard than Akka's plain writes)";
    const SW_NOTE: &str = "Cassandra 5 · same node · Akka = akka-persistence-cassandra · single-writer fast path (guarantee-equivalent to Akka)";
    let config = CassandraPersistenceConfig::new(node.clone(), "datum_persistence_bench_cass");

    // Cassandra AtomicWrites may not cross a journal partition boundary. The
    // backend's default 100k-event partition safely contains every per-entity
    // fixture and all measured writes in this comparison.
    assert_eq!(config.partition_size, 100_000);
    assert!(RECOVERY_EVENTS <= config.partition_size);
    assert!(SINGLE_EVENTS * (WARMUP_SAMPLES + MEASUREMENT_SAMPLES) as u64 <= config.partition_size);
    assert!(
        PERSIST_ALL_BATCHES
            * PERSIST_ALL_BATCH_SIZE
            * (WARMUP_SAMPLES + MEASUREMENT_SAMPLES) as u64
            <= config.partition_size
    );

    let backend = Arc::new(runtime.block_on(CassandraPersistence::connect(config))?);
    run_persist_scenarios(runtime, "cassandra", NOTE, backend.clone())?;
    run_recovery_scenario(runtime, "cassandra", NOTE, backend.clone(), backend.clone())?;
    run_concurrency_sweep(runtime, "cassandra", NOTE, backend.clone())?;
    run_snapshot_scenario(runtime, "cassandra", NOTE, backend.clone())?;
    run_durable_state_scenario(runtime, "cassandra", NOTE, backend)?;

    // WP-PS11 follow-up: quantify the opt-in single-writer fast path against the
    // same Akka baseline (akka-persistence-cassandra issues plain writes under the
    // single-writer assumption, so this mode — not the LWT default — is the
    // guarantee-equivalent comparison). Write-path scenarios only: recovery,
    // snapshots, and durable state never touch the journal-head guard. The mode
    // gets its own keyspace so the two write strategies cannot interleave.
    let mut sw_config = CassandraPersistenceConfig::new(node, "datum_persistence_bench_cass_sw");
    sw_config.write_mode = CassandraWriteMode::SingleWriter;
    assert_eq!(sw_config.partition_size, 100_000);
    let sw_backend = Arc::new(runtime.block_on(CassandraPersistence::connect(sw_config))?);
    run_persist_scenarios(runtime, "cassandra_sw", SW_NOTE, sw_backend.clone())?;
    run_concurrency_sweep(runtime, "cassandra_sw", SW_NOTE, sw_backend)?;
    Ok(())
}

fn run_persist_scenarios<J>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    journal: Arc<J>,
) -> PersistenceResult<()>
where
    J: Journal + 'static,
{
    let single_name = format!("persist_single_1k_{backend}");
    if scenario_enabled(&single_name) {
        let handle = runtime.block_on(
            counter_behavior(next_persistence_id(&single_name), |_, event: u64| {
                Effect::persist(event)
            })
            .spawn(EventSourcedRuntime::new(journal.clone())),
        )?;
        runtime.block_on(handle.state())?;
        measure(&single_name, backend, note, || {
            runtime.block_on(persist_single(&handle, SINGLE_EVENTS))
        })?;
        handle.stop();
    }

    let batched_name = format!("persist_all_100x10_{backend}");
    if scenario_enabled(&batched_name) {
        let handle = runtime.block_on(
            counter_behavior(next_persistence_id(&batched_name), |_, events: Vec<u64>| {
                Effect::persist_all(events)
            })
            .spawn(EventSourcedRuntime::new(journal)),
        )?;
        runtime.block_on(handle.state())?;
        measure(&batched_name, backend, note, || {
            runtime.block_on(persist_all(
                &handle,
                PERSIST_ALL_BATCHES,
                PERSIST_ALL_BATCH_SIZE,
            ))
        })?;
        handle.stop();
    }
    Ok(())
}

async fn persist_single(
    handle: &EventSourcedHandle<u64, u64, u64>,
    events: u64,
) -> PersistenceResult<u64> {
    for _ in 0..events {
        handle.tell(1)?;
    }
    let state = handle.state().await?;
    Ok(state.state ^ state.sequence_nr.as_u64())
}

async fn persist_all(
    handle: &EventSourcedHandle<Vec<u64>, u64, u64>,
    batches: u64,
    batch_size: u64,
) -> PersistenceResult<u64> {
    for _ in 0..batches {
        handle.tell(vec![1; batch_size as usize])?;
    }
    let state = handle.state().await?;
    Ok(state.state ^ state.sequence_nr.as_u64())
}

fn run_recovery_scenario<J, S>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    journal: Arc<J>,
    snapshots: Arc<S>,
) -> PersistenceResult<()>
where
    J: Journal + 'static,
    S: SnapshotStore + 'static,
{
    let name = format!("recovery_replay_10k_{backend}");
    if !scenario_enabled(&name) {
        return Ok(());
    }
    let persistence_id = next_persistence_id(&name);
    runtime.block_on(seed_events(
        journal.as_ref(),
        &persistence_id,
        RECOVERY_EVENTS,
        false,
    ))?;
    measure(&name, backend, note, || {
        runtime.block_on(recover_once(
            persistence_id.clone(),
            journal.clone(),
            snapshots.clone(),
        ))
    })
}

async fn recover_once<J, S>(
    persistence_id: PersistenceId,
    journal: Arc<J>,
    snapshots: Arc<S>,
) -> PersistenceResult<u64>
where
    J: Journal + 'static,
    S: SnapshotStore + 'static,
{
    let handle = counter_behavior(persistence_id, |_, event: u64| Effect::persist(event))
        .spawn(
            EventSourcedRuntime::new(journal)
                .with_snapshot_store(snapshots as Arc<dyn SnapshotStore>),
        )
        .await?;
    let state = handle.state().await?;
    handle.stop();
    Ok(state.state ^ state.sequence_nr.as_u64())
}

fn run_concurrency_sweep<J>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    journal: Arc<J>,
) -> PersistenceResult<()>
where
    J: Journal + 'static,
{
    for entity_count in CONCURRENCY {
        let name = format!("concurrent_persist_{backend}_n_{entity_count}");
        if !scenario_enabled(&name) {
            continue;
        }
        let handles = runtime.block_on(spawn_entities(&name, entity_count, journal.clone()))?;
        measure(&name, backend, note, || {
            runtime.block_on(persist_concurrently(&handles))
        })?;
        for handle in handles {
            handle.stop();
        }
    }
    Ok(())
}

async fn spawn_entities<J>(
    scenario: &str,
    entity_count: usize,
    journal: Arc<J>,
) -> PersistenceResult<Vec<EventSourcedHandle<u64, u64, u64>>>
where
    J: Journal + 'static,
{
    let mut handles = Vec::with_capacity(entity_count);
    for entity in 0..entity_count {
        let handle = counter_behavior(
            next_persistence_id(&format!("{scenario}-{entity}")),
            |_, event: u64| Effect::persist(event),
        )
        .spawn(EventSourcedRuntime::new(journal.clone()))
        .await?;
        handles.push(handle);
    }
    for recovered in join_all(handles.iter().map(EventSourcedHandle::state)).await {
        recovered?;
    }
    Ok(handles)
}

async fn persist_concurrently(
    handles: &[EventSourcedHandle<u64, u64, u64>],
) -> PersistenceResult<u64> {
    for handle in handles {
        handle.tell(1)?;
    }
    let mut checksum = 0_u64;
    for state in join_all(handles.iter().map(EventSourcedHandle::state)).await {
        let state = state?;
        checksum = checksum.wrapping_add(state.state ^ state.sequence_nr.as_u64());
    }
    Ok(checksum)
}

fn run_snapshot_scenario<S>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    snapshots: Arc<S>,
) -> PersistenceResult<()>
where
    S: SnapshotStore + 'static,
{
    let name = format!("snapshot_save_load_{backend}");
    if !scenario_enabled(&name) {
        return Ok(());
    }
    let persistence_id = next_persistence_id(&name);
    let next_sequence = AtomicU64::new(1);
    measure(&name, backend, note, || {
        let sequence_nr = next_sequence.fetch_add(1, Ordering::Relaxed);
        runtime.block_on(async {
            snapshots
                .save(
                    SnapshotMetadata {
                        persistence_id: persistence_id.clone(),
                        sequence_nr: SequenceNr::new(sequence_nr),
                        timestamp_ms: sequence_nr as i64,
                    },
                    String::new(),
                    payload(sequence_nr),
                )
                .await?;
            let selected = snapshots
                .load(&persistence_id, &SnapshotCriteria::latest())
                .await?
                .ok_or_else(|| {
                    PersistenceError::Failure("saved benchmark snapshot was absent".into())
                })?;
            Ok(selected.metadata.sequence_nr.as_u64())
        })
    })
}

fn run_durable_state_scenario<D>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    durable: Arc<D>,
) -> PersistenceResult<()>
where
    D: DurableStateStore + 'static,
{
    let name = format!("durable_state_cas_upsert_{backend}");
    if !scenario_enabled(&name) {
        return Ok(());
    }
    let persistence_id = next_persistence_id(&name);
    let next_revision = AtomicU64::new(1);
    measure(&name, backend, note, || {
        let revision = next_revision.fetch_add(1, Ordering::Relaxed);
        runtime.block_on(async {
            durable
                .upsert(
                    &persistence_id,
                    Revision::new(revision),
                    payload(revision),
                    Some(Tag::new("compare")),
                )
                .await?;
            Ok(revision)
        })
    })
}

fn run_tag_query_scenario<Q>(
    runtime: &Runtime,
    backend: &str,
    note: &str,
    query: Arc<Q>,
) -> PersistenceResult<()>
where
    Q: Journal + EventsByTagQuery + 'static,
{
    let name = format!("tag_query_current_10k_{backend}");
    if !scenario_enabled(&name) {
        return Ok(());
    }
    let persistence_id = next_persistence_id(&name);
    runtime.block_on(seed_events(
        query.as_ref(),
        &persistence_id,
        QUERY_EVENTS,
        true,
    ))?;
    let tag = Tag::new("bench-tag");
    measure(&name, backend, note, || {
        runtime.block_on(collect_current_by_tag(query.as_ref(), &tag))
    })
}

async fn collect_current_by_tag<Q>(query: &Q, tag: &Tag) -> PersistenceResult<u64>
where
    Q: EventsByTagQuery,
{
    let mut stream = query
        .events_by_tag(tag, Offset::NoOffset, QueryMode::Current)
        .await?;
    let mut checksum = 0_u64;
    while let Some(envelope) = stream.next().await {
        let envelope = envelope?;
        checksum = checksum.wrapping_add(envelope.sequence_nr.as_u64());
    }
    Ok(checksum)
}

async fn seed_events<J>(
    journal: &J,
    persistence_id: &PersistenceId,
    count: u64,
    tagged: bool,
) -> PersistenceResult<()>
where
    J: Journal + ?Sized,
{
    if count == 0 {
        return Ok(());
    }
    // Load fixtures in bounded atomic writes: backends cap the events one
    // atomic write may carry (PostgreSQL: 65535 bind parameters per INSERT).
    const FIXTURE_CHUNK: u64 = 1_000;
    let mut next = 1u64;
    while next <= count {
        let end = (next + FIXTURE_CHUNK - 1).min(count);
        let events = (next..=end)
            .map(|sequence_nr| StoredEvent {
                persistence_id: persistence_id.clone(),
                sequence_nr: SequenceNr::new(sequence_nr),
                adapter_manifest: String::new(),
                writer_uuid: "datum-persistence-compare".into(),
                timestamp_ms: sequence_nr as i64,
                metadata: None,
                payload: payload(1),
                tags: tagged.then(|| Tag::new("bench-tag")).into_iter().collect(),
            })
            .collect();
        let outcome = journal.append_one(AtomicWrite::new(events)?).await?;
        if outcome != AppendOutcome::Accepted {
            return Err(PersistenceError::Failure(format!(
                "comparison fixture append was rejected: {outcome:?}"
            )));
        }
        next = end + 1;
    }
    Ok(())
}

fn payload(value: u64) -> SerializedPayload {
    SerializedPayload::new(
        SerializerId::new(9_109),
        "datum-bench-u64-v1",
        value.to_be_bytes().to_vec(),
    )
}

fn measure<F>(scenario: &str, backend: &str, notes: &str, mut run: F) -> PersistenceResult<()>
where
    F: FnMut() -> PersistenceResult<u64>,
{
    for _ in 0..WARMUP_SAMPLES {
        black_box(run()?);
    }

    let cpu_start = process_cpu_ns();
    let mut wall_samples = Vec::with_capacity(MEASUREMENT_SAMPLES);
    let mut peak_rss_kib = 0_u64;
    let mut thread_count = 0_u64;
    let mut checksum = 0_u64;
    let mut alloc_bytes_total = 0_u64;
    let mut alloc_count_total = 0_u64;
    for _ in 0..MEASUREMENT_SAMPLES {
        // Snapshot the allocation counters immediately around `run()` only, so
        // the proc-file reads in `process_snapshot()` below (which themselves
        // allocate a String or two) never leak into the measured delta.
        let alloc_bytes_before = ALLOCATED_BYTES.load(Ordering::Relaxed);
        let alloc_count_before = ALLOCATED_COUNT.load(Ordering::Relaxed);
        let started = Instant::now();
        checksum = checksum.wrapping_add(black_box(run()?));
        let elapsed = started.elapsed();
        alloc_bytes_total += ALLOCATED_BYTES
            .load(Ordering::Relaxed)
            .saturating_sub(alloc_bytes_before);
        alloc_count_total += ALLOCATED_COUNT
            .load(Ordering::Relaxed)
            .saturating_sub(alloc_count_before);
        wall_samples.push(elapsed);
        let snapshot = process_snapshot();
        peak_rss_kib = peak_rss_kib.max(snapshot.peak_rss_kib);
        thread_count = thread_count.max(snapshot.thread_count);
    }
    let cpu_ns = process_cpu_ns().saturating_sub(cpu_start);
    black_box(checksum);

    let mean_us = wall_samples.iter().map(duration_us).sum::<f64>() / wall_samples.len() as f64;
    let p50_us = duration_us(&percentile_duration(&mut wall_samples.clone(), 50));
    let p99_us = duration_us(&percentile_duration(&mut wall_samples, 99));
    let cpu_us_per_op = cpu_ns as f64 / 1_000.0 / MEASUREMENT_SAMPLES as f64;
    let alloc_count_per_op = alloc_count_total as f64 / MEASUREMENT_SAMPLES as f64;
    let alloc_bytes_per_op = alloc_bytes_total as f64 / MEASUREMENT_SAMPLES as f64;
    println!(
        "{scenario}\t{backend}\t{MEASUREMENT_SAMPLES}\t{mean_us:.3}\t{p50_us:.3}\t{p99_us:.3}\t{cpu_us_per_op:.3}\t{alloc_count_per_op:.3}\t{alloc_bytes_per_op:.3}\t{thread_count}\t{peak_rss_kib}\t{notes}"
    );
    Ok(())
}

fn percentile_duration(samples: &mut [Duration], percentile: usize) -> Duration {
    if samples.is_empty() {
        return Duration::ZERO;
    }
    samples.sort_unstable();
    let rank = (samples.len() - 1) * percentile / 100;
    samples[rank]
}

fn duration_us(duration: &Duration) -> f64 {
    duration.as_nanos() as f64 / 1_000.0
}

fn process_cpu_ns() -> u128 {
    let Ok(stat) = std::fs::read_to_string("/proc/self/stat") else {
        return 0;
    };
    let Some(close) = stat.rfind(')') else {
        return 0;
    };
    let fields: Vec<&str> = stat[close + 1..].split_whitespace().collect();
    if fields.len() <= 12 {
        return 0;
    }
    let utime: u64 = fields[11].parse().unwrap_or(0);
    let stime: u64 = fields[12].parse().unwrap_or(0);
    (utime as u128 + stime as u128) * 10_000_000
}

struct ProcessSnapshot {
    peak_rss_kib: u64,
    thread_count: u64,
}

fn process_snapshot() -> ProcessSnapshot {
    let Ok(status) = std::fs::read_to_string("/proc/self/status") else {
        return ProcessSnapshot {
            peak_rss_kib: 0,
            thread_count: 0,
        };
    };
    let mut peak_rss_kib = 0_u64;
    let mut thread_count = 0_u64;
    for line in status.lines() {
        if let Some(rest) = line.strip_prefix("VmHWM:") {
            peak_rss_kib = first_u64(rest);
        } else if let Some(rest) = line.strip_prefix("Threads:") {
            thread_count = first_u64(rest);
        }
    }
    ProcessSnapshot {
        peak_rss_kib,
        thread_count,
    }
}

fn first_u64(input: &str) -> u64 {
    input
        .split_whitespace()
        .next()
        .and_then(|value| value.parse().ok())
        .unwrap_or(0)
}

fn scenario_enabled(name: &str) -> bool {
    static FILTER: OnceLock<Option<Vec<String>>> = OnceLock::new();
    FILTER
        .get_or_init(|| {
            env::var("DATUM_PERSISTENCE_COMPARE_FILTER")
                .ok()
                .map(|value| {
                    value
                        .split(',')
                        .map(str::trim)
                        .filter(|candidate| !candidate.is_empty())
                        .map(ToOwned::to_owned)
                        .collect::<Vec<_>>()
                })
                .filter(|candidates| !candidates.is_empty())
        })
        .as_ref()
        .is_none_or(|candidates| candidates.iter().any(|candidate| name.contains(candidate)))
}

#[cfg(feature = "rocksdb")]
struct TemporaryDatabasePath {
    path: PathBuf,
}

#[cfg(feature = "rocksdb")]
impl TemporaryDatabasePath {
    fn new(label: &str) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let path = env::temp_dir().join(format!(
            "datum-persistence-compare-{label}-{}-{timestamp}",
            std::process::id()
        ));
        Self { path }
    }

    fn path(&self) -> &std::path::Path {
        &self.path
    }
}

#[cfg(feature = "rocksdb")]
impl Drop for TemporaryDatabasePath {
    fn drop(&mut self) {
        if let Err(error) = std::fs::remove_dir_all(&self.path)
            && error.kind() != std::io::ErrorKind::NotFound
        {
            eprintln!(
                "warning: failed to remove temporary benchmark database {}: {error}",
                self.path.display()
            );
        }
    }
}