canwu-sim 0.5.1

Deterministic simulation runtime, scheduling, persistence, replay, and plugins for Canwu
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
use super::{
    ADMISSION_CURSOR_FORMAT_VERSION, BoundaryRecord, COMMITMENT_FORMAT_VERSION, CanwuError,
    CauseRef, CommandAttemptOutcome, CommandAttemptRecord, DeterministicRng, ENGINE_VERSION,
    ErrorCode, EventKind, GENESIS_BOUNDARY_HASH, IngressPayload, IngressRecord, RandomDrawAddress,
    RandomDrawId, RandomDrawOutcome, RandomDrawProducer, RandomDrawRecord, RandomStreamState,
    RunConfigurationSnapshot, RunManifest, SNAPSHOT_FORMAT_VERSION, STATE_REVISION_FORMAT_VERSION,
    SimDuration, SimulationSnapshot, canonical_hash, compute_boundary_hash, invalid_snapshot,
    invalid_snapshot_error, is_canonical_hash, manifest, policy, random, snapshot_checkpoint_hash,
    snapshot_commitment_roots, snapshot_is_at_boundary_head, snapshot_state_hash,
};
use std::collections::{BTreeMap, BTreeSet};

pub(super) fn migrate_snapshot(
    mut snapshot: SimulationSnapshot,
) -> Result<SimulationSnapshot, CanwuError> {
    match snapshot.snapshot_format_version {
        SNAPSHOT_FORMAT_VERSION => {
            if snapshot.engine_version != ENGINE_VERSION {
                return Err(CanwuError::new(
                    ErrorCode::UnsupportedSnapshotVersion,
                    format!(
                        "snapshot format {} from engine {} requires an explicit migration to engine {}",
                        snapshot.snapshot_format_version, snapshot.engine_version, ENGINE_VERSION
                    ),
                ));
            }
            if snapshot.legacy_rng.is_some() {
                return invalid_snapshot("format 5 snapshots cannot contain the legacy global RNG");
            }
            hydrate_snapshot_run_configuration(&mut snapshot)?;
            migrate_snapshot_revision(&mut snapshot)?;
            migrate_snapshot_admission_cursors(&mut snapshot)?;
            migrate_snapshot_commitments(&mut snapshot)?;
            Ok(snapshot)
        }
        2 => {
            if snapshot.run_manifest.is_some()
                || !snapshot.run_manifest_hash.is_empty()
                || !snapshot.checkpoint_hash.is_empty()
                || snapshot.commitment_format_version != 0
                || snapshot.commitment_roots.is_some()
            {
                return invalid_snapshot(
                    "format 2 snapshots cannot contain current manifest or commitment data",
                );
            }
            validate_legacy_ingress_shape(&snapshot)?;
            let checkpoint_hash = canonical_hash("canwu.legacy-checkpoint.v1", &snapshot)?;
            if !snapshot.boundaries.is_empty() || !matches!(snapshot.next_boundary_id, 0 | 1) {
                return invalid_snapshot("format 2 snapshots cannot contain phased-boundary state");
            }
            snapshot.boundaries.clear();
            snapshot.next_boundary_id = 1;
            migrate_format_3_snapshot(snapshot, 2, checkpoint_hash)
        }
        3 => {
            if snapshot.run_manifest.is_some()
                || !snapshot.run_manifest_hash.is_empty()
                || !snapshot.checkpoint_hash.is_empty()
                || snapshot.commitment_format_version != 0
                || snapshot.commitment_roots.is_some()
            {
                return invalid_snapshot(
                    "format 3 snapshots cannot contain current manifest or commitment data",
                );
            }
            validate_legacy_ingress_shape(&snapshot)?;
            let checkpoint_hash = canonical_hash("canwu.legacy-checkpoint.v1", &snapshot)?;
            migrate_format_3_snapshot(snapshot, 3, checkpoint_hash)
        }
        _ => Err(CanwuError::new(
            ErrorCode::UnsupportedSnapshotVersion,
            format!(
                "snapshot format {} from engine {} is unsupported; this engine reads formats 2, 3, and {}",
                snapshot.snapshot_format_version, snapshot.engine_version, SNAPSHOT_FORMAT_VERSION
            ),
        )),
    }
}

fn migrate_snapshot_revision(snapshot: &mut SimulationSnapshot) -> Result<(), CanwuError> {
    match snapshot.revision_format_version {
        STATE_REVISION_FORMAT_VERSION => Ok(()),
        0 => {
            if snapshot.state_revision != 0 || snapshot.replay_revision_format_version != 0 {
                return invalid_snapshot(
                    "legacy revision snapshots cannot contain current revision or replay provenance",
                );
            }
            let legacy_checkpoint = snapshot_checkpoint_hash(snapshot)?;
            if !is_canonical_hash(&snapshot.checkpoint_hash)
                || legacy_checkpoint != snapshot.checkpoint_hash
            {
                return invalid_snapshot(
                    "legacy checkpoint hash does not bind the pre-migration state",
                );
            }
            validate_legacy_boundary_hash_chain(&snapshot.boundaries)?;
            migrate_command_attempt_revisions(
                &mut snapshot.command_attempts,
                &snapshot.boundaries,
            )?;
            migrate_ingress_command_revisions(
                &mut snapshot.ingress,
                &snapshot.command_attempts,
                &snapshot.boundaries,
            )?;
            if snapshot_is_at_boundary_head(snapshot) {
                let migrated_state_hash = snapshot_state_hash(snapshot)?;
                snapshot
                    .boundaries
                    .last_mut()
                    .expect("boundary-head snapshots have a final boundary")
                    .state_hash = Some(migrated_state_hash);
            }
            rehash_snapshot_boundaries(snapshot)?;
            snapshot.state_revision = authoritative_revision_count(
                snapshot.commands.len(),
                snapshot.command_attempts.len(),
                snapshot.boundaries.len(),
            )?;
            snapshot.revision_format_version = STATE_REVISION_FORMAT_VERSION;
            snapshot.checkpoint_hash = snapshot_checkpoint_hash(snapshot)?;
            Ok(())
        }
        version => Err(CanwuError::new(
            ErrorCode::UnsupportedSnapshotVersion,
            format!(
                "state revision format {version} is unsupported; this engine reads legacy format 0 and current format {STATE_REVISION_FORMAT_VERSION}"
            ),
        )),
    }
}

fn migrate_snapshot_admission_cursors(snapshot: &mut SimulationSnapshot) -> Result<(), CanwuError> {
    match snapshot.admission_cursor_format_version {
        ADMISSION_CURSOR_FORMAT_VERSION => Ok(()),
        0 => {
            if snapshot.admitted_attempt_count != 0
                || snapshot.admitted_command_count != 0
                || snapshot.admitted_event_count != 0
            {
                return invalid_snapshot(
                    "legacy admission-cursor snapshots cannot contain current cursor values",
                );
            }
            let cursors = admission_cursors_from_boundaries(&snapshot.boundaries)?;
            snapshot.admitted_attempt_count = cursors.attempts;
            snapshot.admitted_command_count = cursors.commands;
            snapshot.admitted_event_count = cursors.events;
            snapshot.admission_cursor_format_version = ADMISSION_CURSOR_FORMAT_VERSION;
            Ok(())
        }
        version => Err(CanwuError::new(
            ErrorCode::UnsupportedSnapshotVersion,
            format!(
                "admission cursor format {version} is unsupported; this engine reads legacy format 0 and current format {ADMISSION_CURSOR_FORMAT_VERSION}"
            ),
        )),
    }
}

fn migrate_snapshot_commitments(snapshot: &mut SimulationSnapshot) -> Result<(), CanwuError> {
    match snapshot.commitment_format_version {
        COMMITMENT_FORMAT_VERSION => {
            if snapshot.commitment_roots.is_none() {
                return invalid_snapshot(
                    "current commitment snapshot is missing its persisted domain roots",
                );
            }
            Ok(())
        }
        0 => {
            if snapshot.commitment_roots.is_some() {
                return invalid_snapshot(
                    "legacy commitment snapshot cannot contain current domain roots",
                );
            }
            let legacy_checkpoint = snapshot_checkpoint_hash(snapshot)?;
            if !is_canonical_hash(&snapshot.checkpoint_hash)
                || legacy_checkpoint != snapshot.checkpoint_hash
            {
                return invalid_snapshot(
                    "legacy checkpoint hash does not bind the pre-commitment state",
                );
            }
            snapshot.commitment_roots = Some(snapshot_commitment_roots(snapshot)?);
            snapshot.commitment_format_version = COMMITMENT_FORMAT_VERSION;
            snapshot.checkpoint_hash = snapshot_checkpoint_hash(snapshot)?;
            Ok(())
        }
        version => Err(CanwuError::new(
            ErrorCode::UnsupportedSnapshotVersion,
            format!(
                "commitment format {version} is unsupported; this engine reads legacy format 0 and current format {COMMITMENT_FORMAT_VERSION}"
            ),
        )),
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(super) struct PersistedAdmissionCursors {
    pub(super) attempts: u64,
    pub(super) commands: u64,
    pub(super) events: u64,
}

fn admission_cursors_from_boundaries(
    boundaries: &[BoundaryRecord],
) -> Result<PersistedAdmissionCursors, CanwuError> {
    let mut cursors = PersistedAdmissionCursors::default();
    for boundary in boundaries {
        cursors.attempts = cursors
            .attempts
            .checked_add(
                u64::try_from(boundary.admitted_attempts.len()).map_err(|_| {
                    invalid_snapshot_error("admitted attempt count exceeds cursor range")
                })?,
            )
            .ok_or_else(|| invalid_snapshot_error("admitted attempt cursor is exhausted"))?;
        cursors.commands = cursors
            .commands
            .checked_add(
                u64::try_from(boundary.admitted_commands.len()).map_err(|_| {
                    invalid_snapshot_error("admitted command count exceeds cursor range")
                })?,
            )
            .ok_or_else(|| invalid_snapshot_error("admitted command cursor is exhausted"))?;
        cursors.events =
            cursors
                .events
                .checked_add(u64::try_from(boundary.admitted_events.len()).map_err(|_| {
                    invalid_snapshot_error("admitted event count exceeds cursor range")
                })?)
                .ok_or_else(|| invalid_snapshot_error("admitted event cursor is exhausted"))?;
    }
    Ok(cursors)
}

pub(super) fn rehash_snapshot_boundaries(
    snapshot: &mut SimulationSnapshot,
) -> Result<(), CanwuError> {
    let mut previous_hash = GENESIS_BOUNDARY_HASH.to_owned();
    for boundary in &mut snapshot.boundaries {
        boundary.previous_hash.clone_from(&previous_hash);
        boundary.hash = compute_boundary_hash(boundary)?;
        previous_hash.clone_from(&boundary.hash);
    }
    Ok(())
}

fn validate_legacy_boundary_hash_chain(boundaries: &[BoundaryRecord]) -> Result<(), CanwuError> {
    let mut previous_hash = GENESIS_BOUNDARY_HASH.to_owned();
    for boundary in boundaries {
        if boundary.previous_hash != previous_hash
            || !is_canonical_hash(&boundary.hash)
            || boundary
                .state_hash
                .as_deref()
                .is_some_and(|hash| !is_canonical_hash(hash))
            || compute_boundary_hash(boundary)? != boundary.hash
        {
            return invalid_snapshot("legacy boundary hash chain is inconsistent");
        }
        previous_hash.clone_from(&boundary.hash);
    }
    Ok(())
}

fn migrate_ingress_command_revisions(
    ingress: &mut [IngressRecord],
    attempts: &[CommandAttemptRecord],
    boundaries: &[BoundaryRecord],
) -> Result<(), CanwuError> {
    let mut attempts_by_request = BTreeMap::new();
    for attempt in attempts {
        let Some(request_id) = attempt.request_id else {
            continue;
        };
        let expected_revision = attempt.expected_revision.ok_or_else(|| {
            invalid_snapshot_error("tracked command attempt is missing its revision guard")
        })?;
        if attempts_by_request
            .insert(request_id, expected_revision)
            .is_some()
        {
            return invalid_snapshot("command request ID is reused across attempt evidence");
        }
    }
    let (legacy_revision_by_cut, migrated_revision_by_cut) =
        revision_values_after_boundary_cuts(attempts, boundaries)?;
    let admitted_ingress: BTreeSet<_> = boundaries
        .iter()
        .flat_map(|boundary| boundary.admitted_ingress.iter().copied())
        .collect();
    for record in ingress {
        let IngressPayload::Command { request } = &mut record.payload else {
            continue;
        };
        if admitted_ingress.contains(&record.id) {
            request.expected_revision =
                *attempts_by_request
                    .get(&request.request_id)
                    .ok_or_else(|| {
                        invalid_snapshot_error(
                            "admitted command ingress is missing its deterministic attempt",
                        )
                    })?;
            continue;
        }
        let issue_cut = usize::try_from(record.eligible_boundary_count).map_err(|_| {
            invalid_snapshot_error("command ingress issue cut exceeds the platform index range")
        })?;
        let legacy_revision = *legacy_revision_by_cut.get(issue_cut).ok_or_else(|| {
            invalid_snapshot_error("command ingress issue cut exceeds boundary history")
        })?;
        let migrated_revision = migrated_revision_by_cut[issue_cut];
        request.expected_revision = translate_revision_guard(
            request.expected_revision,
            legacy_revision,
            migrated_revision,
        )?;
    }
    Ok(())
}

fn revision_values_after_boundary_cuts(
    attempts: &[CommandAttemptRecord],
    boundaries: &[BoundaryRecord],
) -> Result<(Vec<u64>, Vec<u64>), CanwuError> {
    let mut legacy = vec![0];
    let mut migrated = vec![0];
    let mut accepted_attempts = 0_u64;
    let mut admitted_attempts = 0_u64;
    for (boundary_index, boundary) in boundaries.iter().enumerate() {
        for attempt_id in &boundary.admitted_attempts {
            let attempt_index =
                usize::try_from(attempt_id.get().saturating_sub(1)).map_err(|_| {
                    invalid_snapshot_error("boundary attempt ID exceeds the journal index range")
                })?;
            let attempt = attempts.get(attempt_index).ok_or_else(|| {
                invalid_snapshot_error("boundary admits an unknown command attempt")
            })?;
            admitted_attempts = admitted_attempts.checked_add(1).ok_or_else(|| {
                invalid_snapshot_error("admitted attempt count exceeds revision space")
            })?;
            if matches!(attempt.outcome, CommandAttemptOutcome::Accepted { .. }) {
                accepted_attempts = accepted_attempts.checked_add(1).ok_or_else(|| {
                    invalid_snapshot_error("accepted attempt count exceeds revision space")
                })?;
            }
        }
        let completed_boundaries = u64::try_from(boundary_index)
            .ok()
            .and_then(|index| index.checked_add(1))
            .ok_or_else(|| invalid_snapshot_error("boundary count exceeds revision space"))?;
        legacy.push(
            accepted_attempts
                .checked_add(completed_boundaries)
                .ok_or_else(|| invalid_snapshot_error("legacy revision space is exhausted"))?,
        );
        migrated.push(
            admitted_attempts
                .checked_add(completed_boundaries)
                .ok_or_else(|| invalid_snapshot_error("migrated revision space is exhausted"))?,
        );
    }
    Ok((legacy, migrated))
}

fn migrate_command_attempt_revisions(
    attempts: &mut [CommandAttemptRecord],
    boundaries: &[BoundaryRecord],
) -> Result<(), CanwuError> {
    let boundaries_before = boundaries_before_attempts(attempts.len(), boundaries)?;
    let mut accepted_commands = 0_u64;
    for (index, attempt) in attempts.iter_mut().enumerate() {
        let attempt_index = u64::try_from(index)
            .map_err(|_| invalid_snapshot_error("command attempt index exceeds revision space"))?;
        let legacy_revision = accepted_commands
            .checked_add(boundaries_before[index])
            .ok_or_else(|| invalid_snapshot_error("legacy command revision space is exhausted"))?;
        let migrated_revision = attempt_index
            .checked_add(boundaries_before[index])
            .ok_or_else(|| invalid_snapshot_error("command revision space is exhausted"))?;
        if attempt.revision_before != legacy_revision {
            return invalid_snapshot("legacy command attempt revision is inconsistent");
        }
        if let Some(expected) = attempt.expected_revision {
            attempt.expected_revision = Some(translate_revision_guard(
                expected,
                legacy_revision,
                migrated_revision,
            )?);
        }
        attempt.revision_before = migrated_revision;
        match &mut attempt.outcome {
            CommandAttemptOutcome::Accepted { .. } => {
                if attempt
                    .expected_revision
                    .is_some_and(|expected| expected != migrated_revision)
                {
                    return invalid_snapshot(
                        "legacy accepted attempt has a stale expected revision",
                    );
                }
                accepted_commands = accepted_commands.checked_add(1).ok_or_else(|| {
                    invalid_snapshot_error("accepted command count exceeds revision space")
                })?;
            }
            CommandAttemptOutcome::Rejected { error }
                if error.code == ErrorCode::SimulationRevisionConflict =>
            {
                let expected = attempt.expected_revision.ok_or_else(|| {
                    invalid_snapshot_error("revision conflict is missing its expected revision")
                })?;
                error.message = format!(
                    "command expected revision {expected}, but simulation is at revision {migrated_revision}"
                );
            }
            CommandAttemptOutcome::Rejected { .. } => {}
        }
    }
    Ok(())
}

fn translate_revision_guard(
    expected: u64,
    legacy_revision: u64,
    migrated_revision: u64,
) -> Result<u64, CanwuError> {
    if expected >= legacy_revision {
        Ok(migrated_revision
            .checked_add(expected - legacy_revision)
            .unwrap_or(if migrated_revision == u64::MAX {
                0
            } else {
                u64::MAX
            }))
    } else {
        migrated_revision
            .checked_sub(legacy_revision - expected)
            .ok_or_else(|| invalid_snapshot_error("migrated expected revision underflowed"))
    }
}

pub(super) fn boundaries_before_attempts(
    attempt_count: usize,
    boundaries: &[BoundaryRecord],
) -> Result<Vec<u64>, CanwuError> {
    let boundary_count = u64::try_from(boundaries.len())
        .map_err(|_| invalid_snapshot_error("boundary count exceeds revision space"))?;
    let mut values = vec![boundary_count; attempt_count];
    for (boundary_index, boundary) in boundaries.iter().enumerate() {
        let prior_boundaries = u64::try_from(boundary_index)
            .map_err(|_| invalid_snapshot_error("boundary index exceeds revision space"))?;
        for attempt_id in &boundary.admitted_attempts {
            let attempt_index =
                usize::try_from(attempt_id.get().saturating_sub(1)).map_err(|_| {
                    invalid_snapshot_error("boundary attempt ID exceeds the journal index range")
                })?;
            let Some(value) = values.get_mut(attempt_index) else {
                return invalid_snapshot("boundary admits an unknown command attempt");
            };
            *value = prior_boundaries;
        }
    }
    Ok(values)
}

pub(super) fn authoritative_revision_count(
    command_count: usize,
    attempt_count: usize,
    boundary_count: usize,
) -> Result<u64, CanwuError> {
    let command_transactions = if attempt_count == 0 {
        command_count
    } else {
        attempt_count
    };
    u64::try_from(command_transactions)
        .ok()
        .and_then(|commands| {
            u64::try_from(boundary_count)
                .ok()
                .and_then(|boundaries| commands.checked_add(boundaries))
        })
        .ok_or_else(|| invalid_snapshot_error("authoritative revision space is exhausted"))
}

fn validate_legacy_ingress_shape(snapshot: &SimulationSnapshot) -> Result<(), CanwuError> {
    if snapshot.revision_format_version != 0
        || snapshot.state_revision != 0
        || snapshot.replay_revision_format_version != 0
        || snapshot.admission_cursor_format_version != 0
        || snapshot.admitted_attempt_count != 0
        || snapshot.admitted_command_count != 0
        || snapshot.admitted_event_count != 0
        || snapshot.run_configuration.is_some()
        || snapshot.initial_scenario.is_some()
        || !snapshot.command_attempts.is_empty()
        || !snapshot.ingress.is_empty()
        || !snapshot.domain_records.is_empty()
        || snapshot.next_command_attempt_id != 1
        || snapshot.next_ingress_id != 1
        || snapshot
            .commands
            .iter()
            .any(|record| record.attempt_id.is_some() || !record.emitted_events.is_empty())
        || snapshot.boundaries.iter().any(|record| {
            !record.admitted_attempts.is_empty()
                || !record.admitted_ingress.is_empty()
                || !record.generated_ingress.is_empty()
                || !record.record_changes.is_empty()
        })
    {
        return invalid_snapshot(
            "legacy snapshots cannot contain current run-policy or command-attempt evidence",
        );
    }
    Ok(())
}

fn migrate_format_3_snapshot(
    mut snapshot: SimulationSnapshot,
    source_snapshot_format: u32,
    checkpoint_hash: String,
) -> Result<SimulationSnapshot, CanwuError> {
    if !snapshot.plugin_descriptors.is_empty() {
        return Err(CanwuError::new(
            ErrorCode::PluginManifestMismatch,
            "legacy plugin snapshots lack executable semantic identities and cannot be safely migrated",
        ));
    }
    if !snapshot.random_streams.is_empty()
        || !snapshot.random_draws.is_empty()
        || snapshot.next_random_draw_id != 0
    {
        return invalid_snapshot("legacy snapshots cannot contain scoped random state");
    }
    let legacy_rng = snapshot
        .legacy_rng
        .take()
        .ok_or_else(|| invalid_snapshot_error("legacy snapshot is missing its global RNG state"))?;
    let dispatch_count = u64::try_from(
        snapshot
            .events
            .iter()
            .filter(|event| matches!(event.kind, EventKind::ReportDispatched { .. }))
            .count(),
    )
    .map_err(|_| invalid_snapshot_error("legacy random draw count exceeds identifier space"))?;
    let root_seed = DeterministicRng::seed_before(legacy_rng.state(), dispatch_count);
    let core_key = random::core_report_delay_stream();
    let mut core_state = RandomStreamState::initial(root_seed, core_key.clone());
    core_state.position = dispatch_count;
    core_state.generator_state = legacy_rng.state();

    let mut random_draws = Vec::new();
    for event in &snapshot.events {
        let EventKind::ReportDispatched {
            recipient,
            army,
            arrives_at,
        } = event.kind
        else {
            continue;
        };
        let jitter = arrives_at
            .as_minutes()
            .checked_sub(event.timestamp.as_minutes())
            .and_then(|duration| duration.checked_sub(SimDuration::hours(36).as_minutes()))
            .ok_or_else(|| {
                invalid_snapshot_error("legacy report timing exceeds the supported range")
            })?;
        let Ok(value) = u64::try_from(jitter) else {
            return invalid_snapshot("legacy report jitter is outside the scoped RNG contract");
        };
        let Some(CauseRef::Event(cause)) = &event.cause else {
            return invalid_snapshot("legacy report dispatch lacks its arrival-event cause");
        };
        if value >= 12 * 60 {
            return invalid_snapshot("legacy report jitter is outside the scoped RNG contract");
        }
        let id_value = u64::try_from(random_draws.len())
            .ok()
            .and_then(|value| value.checked_add(1))
            .ok_or_else(|| invalid_snapshot_error("legacy random draw IDs are exhausted"))?;
        random_draws.push(RandomDrawRecord {
            id: RandomDrawId::new(id_value),
            at: event.timestamp,
            stream: core_key.clone(),
            address: RandomDrawAddress::Sequential {
                position: id_value - 1,
            },
            operation_evidence: None,
            upper_exclusive: 12 * 60,
            value,
            purpose: "knowledge report delivery jitter".to_owned(),
            producer: RandomDrawProducer::CoreSystem {
                system: "canwu.core.knowledge-report-delay".to_owned(),
            },
            outcome: Some(RandomDrawOutcome::KnowledgeReportDelivery {
                recipient,
                army,
                dispatch_event: event.id,
                arrives_at,
            }),
            cause: CauseRef::Event(*cause),
            correlation_id: event.correlation_id,
        });
    }

    let mut streams = BTreeMap::from([(core_key, core_state)]);
    for key in snapshot
        .plugin_descriptors
        .iter()
        .flat_map(|descriptor| &descriptor.boundary_systems)
        .flat_map(|contract| &contract.random_streams)
    {
        streams
            .entry(key.clone())
            .or_insert_with(|| RandomStreamState::initial(root_seed, key.clone()));
    }
    snapshot.root_seed = root_seed;
    snapshot.random_streams = streams.into_values().collect();
    snapshot.random_draws = random_draws;
    snapshot.next_random_draw_id = dispatch_count.checked_add(1).ok_or_else(|| {
        invalid_snapshot_error("legacy random draw counter exceeds identifier space")
    })?;

    let mut previous_hash = GENESIS_BOUNDARY_HASH.to_owned();
    for boundary in &mut snapshot.boundaries {
        boundary.random_draws.clear();
        boundary.state_hash = None;
        boundary.previous_hash.clone_from(&previous_hash);
        boundary.hash = compute_boundary_hash(boundary)?;
        previous_hash.clone_from(&boundary.hash);
    }
    let source_engine_version = snapshot.engine_version.clone();
    let run_manifest = RunManifest::migrated_legacy(
        source_engine_version,
        source_snapshot_format,
        checkpoint_hash,
    );
    snapshot.run_manifest_hash = manifest::hash(&run_manifest)?;
    snapshot.run_manifest = Some(run_manifest);
    snapshot.run_configuration = Some(RunConfigurationSnapshot::LegacyUnspecified);
    snapshot.state_revision = authoritative_revision_count(
        snapshot.commands.len(),
        snapshot.command_attempts.len(),
        snapshot.boundaries.len(),
    )?;
    snapshot.revision_format_version = STATE_REVISION_FORMAT_VERSION;
    let admission_cursors = admission_cursors_from_boundaries(&snapshot.boundaries)?;
    snapshot.admitted_attempt_count = admission_cursors.attempts;
    snapshot.admitted_command_count = admission_cursors.commands;
    snapshot.admitted_event_count = admission_cursors.events;
    snapshot.admission_cursor_format_version = ADMISSION_CURSOR_FORMAT_VERSION;
    ENGINE_VERSION.clone_into(&mut snapshot.engine_version);
    snapshot.snapshot_format_version = SNAPSHOT_FORMAT_VERSION;
    snapshot.checkpoint_hash = snapshot_checkpoint_hash(&snapshot)?;
    migrate_snapshot_commitments(&mut snapshot)?;
    Ok(snapshot)
}

fn hydrate_snapshot_run_configuration(snapshot: &mut SimulationSnapshot) -> Result<(), CanwuError> {
    if snapshot.run_configuration.is_some() {
        return Ok(());
    }
    let Some(run_manifest) = &snapshot.run_manifest else {
        return Err(CanwuError::new(
            ErrorCode::InvalidRunManifest,
            "snapshot is missing its run manifest",
        ));
    };
    snapshot.run_configuration = Some(inferred_run_configuration(run_manifest)?);
    Ok(())
}

pub(super) fn inferred_run_configuration(
    run_manifest: &RunManifest,
) -> Result<RunConfigurationSnapshot, CanwuError> {
    Ok(match run_manifest {
        RunManifest::Declared {
            run_configuration, ..
        } if run_configuration.semantic_hash == policy::compatibility_configuration_hash()? => {
            RunConfigurationSnapshot::CompatibilityV1
        }
        RunManifest::Declared { .. } => RunConfigurationSnapshot::ManifestOnlyV1,
        RunManifest::MigratedLegacy { .. } => RunConfigurationSnapshot::LegacyUnspecified,
    })
}