batpak 0.8.0

Event sourcing with causal graphs and caller-defined gates. Sync API, no async runtime.
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
// justifies: INV-TEST-PANIC-AS-ASSERTION; this contract-table harness uses panic! to make variant/source drift fail loudly and locally.
#![allow(clippy::panic)]
//! PROVES: representative `StoreError` variants preserve downstream handling
//! class, source forwarding, and diagnostic `Display` fields.
//! CATCHES: drift where a public `StoreError` arm drops identity, source, or
//! handling-class stability without an explicit table update.
//! SEEDED: deterministic contract table.
use batpak::coordinate::{Coordinate, CoordinateError};
use batpak::store::{
    HiddenRangesCorruption, HlcPoint, ProfileInvalidKind, StoreError, StoreInvariant,
    StoreLockMode, WatermarkKind,
};
use std::error::Error as _;
use std::io;
use std::path::PathBuf;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HandlingClass {
    Domain,
    RetryableOperational,
    FailClosedOperational,
}

struct Case {
    name: &'static str,
    error: StoreError,
    class: HandlingClass,
    source_needle: Option<&'static str>,
    display_needles: &'static [&'static str],
}

fn classify(error: &StoreError) -> HandlingClass {
    match error {
        StoreError::Io(_)
        | StoreError::CacheFailed(_)
        | StoreError::CheckpointWriteFailed { .. }
        | StoreError::WaitTimeout { .. } => HandlingClass::RetryableOperational,
        StoreError::StoreLocked { .. }
        | StoreError::Coordinate(_)
        | StoreError::NotFound(_)
        | StoreError::SequenceMismatch { .. }
        | StoreError::Configuration(_)
        | StoreError::IdempotencyRequired
        | StoreError::VisibilityFenceActive
        | StoreError::VisibilityFenceNotActive
        | StoreError::VisibilityFenceCancelled
        | StoreError::IdempotencyPartialBatch { .. }
        | StoreError::RangeMalformed { .. }
        | StoreError::InvalidCoordinate { .. }
        | StoreError::InvalidCausation { .. }
        | StoreError::InvalidCommitMetadata { .. }
        | StoreError::CoordinateNulByte
        | StoreError::CoordinatePathTraversal
        | StoreError::CoordinateControlChar
        | StoreError::BatchItemTooLarge { .. }
        | StoreError::EntityClockOverflow { .. }
        | StoreError::InvalidClock { .. } => HandlingClass::Domain,
        StoreError::BatchFailed { source, .. } | StoreError::BatchSyncFailed { source, .. } => {
            classify(source.as_ref())
        }
        StoreError::Serialization(_)
        | StoreError::CrcMismatch { .. }
        | StoreError::CorruptSegment { .. }
        | StoreError::PlatformProfileInvalid { .. }
        | StoreError::PlatformProfileMismatch { .. }
        | StoreError::PlatformAdmissionFailed { .. }
        | StoreError::WriterCrashed
        | StoreError::SequenceGateViolation { .. }
        | StoreError::CorruptFrame { .. }
        | StoreError::SegmentTooManyEntries { .. }
        | StoreError::DataDirMalformed { .. }
        | StoreError::AncestryCorrupt { .. }
        | StoreError::HiddenRangesCorrupt { .. }
        | StoreError::CursorCheckpointCorrupt { .. }
        | StoreError::CursorCheckpointRegionMismatch { .. }
        | StoreError::InvariantViolation { .. } => HandlingClass::FailClosedOperational,
        #[cfg(feature = "dangerous-test-hooks")]
        StoreError::FaultInjected(_) => HandlingClass::FailClosedOperational,
        _ => panic!(
            "STORE_ERROR CONTRACT TABLE OUT OF DATE: add an explicit handling class for {error:?}"
        ),
    }
}

#[test]
fn store_error_contract_table_stays_stable() {
    let cases = [
        Case {
            name: "io",
            error: StoreError::Io(io::Error::new(io::ErrorKind::TimedOut, "disk timed out")),
            class: HandlingClass::RetryableOperational,
            source_needle: Some("disk timed out"),
            display_needles: &["IO error", "disk timed out"],
        },
        Case {
            name: "store_locked",
            error: StoreError::StoreLocked {
                path: PathBuf::from("fixtures/locked-store"),
                mode: StoreLockMode::ReadOnly,
            },
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["fixtures/locked-store", "read-only", "locked"],
        },
        Case {
            name: "sequence_gate_violation",
            error: StoreError::SequenceGateViolation {
                operation: "publish_then_broadcast_unfenced",
                requested: 7,
                allocated: 5,
                visible: 4,
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &[
                "publish_then_broadcast_unfenced",
                "publish(7)",
                "allocated=5",
                "visible=4",
            ],
        },
        Case {
            name: "serialization",
            error: StoreError::Serialization(Box::new(io::Error::new(
                io::ErrorKind::InvalidData,
                "bad msgpack",
            ))),
            class: HandlingClass::FailClosedOperational,
            source_needle: Some("bad msgpack"),
            display_needles: &["serialization error", "bad msgpack"],
        },
        Case {
            name: "not_found",
            error: StoreError::NotFound(0xDEAD),
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["dead", "not found"],
        },
        Case {
            name: "sequence_mismatch",
            error: StoreError::SequenceMismatch {
                entity: "user:1".into(),
                expected: 5,
                actual: 3,
            },
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["user:1", "5", "3", "CAS failed"],
        },
        Case {
            name: "cache_failed",
            error: StoreError::CacheFailed(Box::new(io::Error::new(
                io::ErrorKind::TimedOut,
                "cache timed out",
            ))),
            class: HandlingClass::RetryableOperational,
            source_needle: Some("cache timed out"),
            display_needles: &["cache error", "cache timed out"],
        },
        Case {
            name: "wait_timeout",
            error: StoreError::WaitTimeout {
                watermark: WatermarkKind::Durable,
                target: HlcPoint {
                    wall_ms: 123,
                    global_sequence: 4,
                },
                waited_ms: 250,
            },
            class: HandlingClass::RetryableOperational,
            source_needle: None,
            display_needles: &["Durable", "123", "4", "250ms", "timed out"],
        },
        Case {
            name: "configuration",
            error: StoreError::Configuration("single_append_max_bytes must be > 0".into()),
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["invalid config", "single_append_max_bytes"],
        },
        Case {
            name: "batch_failed_wraps_inner_contract",
            error: StoreError::BatchFailed {
                item_index: 2,
                source: Box::new(StoreError::Io(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "flush timed out",
                ))),
            },
            class: HandlingClass::RetryableOperational,
            source_needle: Some("IO error: flush timed out"),
            display_needles: &["batch failed at item 2", "flush timed out"],
        },
        Case {
            name: "batch_sync_failed_wraps_inner_contract",
            error: StoreError::BatchSyncFailed {
                item_count: 3,
                source: Box::new(StoreError::Io(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "segment fsync timed out",
                ))),
            },
            class: HandlingClass::RetryableOperational,
            source_needle: Some("IO error: segment fsync timed out"),
            display_needles: &[
                "batch sync failed after writing 3 items",
                "segment fsync timed out",
            ],
        },
        Case {
            name: "crc_mismatch",
            error: StoreError::CrcMismatch {
                segment_id: 7,
                offset: 42,
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["CRC mismatch", "7", "42"],
        },
        Case {
            name: "corrupt_segment",
            error: StoreError::CorruptSegment {
                segment_id: 8,
                detail: "unsupported segment version: 99".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["corrupt segment", "8", "unsupported segment version"],
        },
        Case {
            name: "corrupt_frame",
            error: StoreError::CorruptFrame {
                segment_id: 9,
                offset: 128,
                reason: "bad crc region".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["corrupt frame", "9", "128", "bad crc region"],
        },
        Case {
            name: "hidden_ranges_corrupt",
            error: StoreError::HiddenRangesCorrupt {
                path: PathBuf::from("fixtures/hidden-ranges.json"),
                kind: HiddenRangesCorruption::ReadFailed(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected EOF",
                )),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: Some("unexpected EOF"),
            display_needles: &["fixtures/hidden-ranges.json", "unexpected EOF", "corrupt"],
        },
        Case {
            name: "invalid_coordinate",
            error: StoreError::InvalidCoordinate {
                index: Some(4),
                reason: "entity cannot be empty".into(),
            },
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &[
                "batch item 4",
                "entity cannot be empty",
                "invalid coordinate",
            ],
        },
        Case {
            name: "batch_item_too_large",
            error: StoreError::BatchItemTooLarge {
                index: 1,
                size: 4097,
                limit: 2048,
            },
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["batch item 1", "4097", "2048"],
        },
        Case {
            name: "invariant_violation",
            error: StoreError::InvariantViolation {
                kind: StoreInvariant::CloseHlcRegression {
                    previous: HlcPoint {
                        wall_ms: 2,
                        global_sequence: 2,
                    },
                    later: HlcPoint {
                        wall_ms: 1,
                        global_sequence: 3,
                    },
                },
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["invariant violation", "HLC regressed"],
        },
        Case {
            name: "invalid_clock",
            error: StoreError::InvalidClock {
                timestamp_us: -17,
                reason: "timestamp_us must be >= 0 microseconds since Unix epoch".into(),
            },
            class: HandlingClass::Domain,
            source_needle: None,
            display_needles: &["-17", "invalid", "timestamp_us"],
        },
        Case {
            name: "platform_profile_invalid",
            error: StoreError::PlatformProfileInvalid {
                path: PathBuf::from("fixtures/platform/bad.profile"),
                kind: ProfileInvalidKind::UnsupportedSchemaVersion {
                    observed: 2,
                    expected: 1,
                },
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["fixtures/platform/bad.profile", "invalid", "schema_version"],
        },
        Case {
            name: "platform_profile_mismatch",
            error: StoreError::PlatformProfileMismatch {
                path: PathBuf::from("fixtures/platform/linux_basic.profile"),
                reason: "expected AtomicNoFollow, observed BestEffortCheckThenOpen".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &[
                "fixtures/platform/linux_basic.profile",
                "does not match",
                "AtomicNoFollow",
            ],
        },
        Case {
            name: "platform_admission_failed",
            error: StoreError::PlatformAdmissionFailed {
                capability: "sealed segment mmap",
                reason: "mmap evidence Unknown is not admissible".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &["sealed segment mmap", "admission failed", "Unknown"],
        },
        Case {
            name: "checkpoint_write_failed",
            error: StoreError::CheckpointWriteFailed {
                id: "reactor-a".into(),
                source: io::Error::new(io::ErrorKind::TimedOut, "checkpoint fsync timed out"),
            },
            class: HandlingClass::RetryableOperational,
            source_needle: Some("checkpoint fsync timed out"),
            display_needles: &["reactor-a", "write failed", "checkpoint fsync timed out"],
        },
        Case {
            name: "cursor_checkpoint_corrupt",
            error: StoreError::CursorCheckpointCorrupt {
                path: PathBuf::from("fixtures/cursors/reactor-a.ckpt"),
                reason: "invalid msgpack".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &[
                "fixtures/cursors/reactor-a.ckpt",
                "invalid msgpack",
                "corrupt",
            ],
        },
        Case {
            name: "cursor_checkpoint_region_mismatch",
            error: StoreError::CursorCheckpointRegionMismatch {
                path: PathBuf::from("fixtures/cursors/reactor-a.ckpt"),
                stored: Some("entity_prefix=user:".into()),
                expected: "entity_prefix=order:".into(),
            },
            class: HandlingClass::FailClosedOperational,
            source_needle: None,
            display_needles: &[
                "fixtures/cursors/reactor-a.ckpt",
                "entity_prefix=user:",
                "entity_prefix=order:",
                "belongs to region",
            ],
        },
    ];

    for case in cases {
        let display = case.error.to_string();
        let source = case.error.source().map(std::string::ToString::to_string);

        assert_eq!(
            classify(&case.error),
            case.class,
            "STORE_ERROR CLASSIFICATION DRIFT: {} should stay {:?}, got {:?}. display={display}",
            case.name,
            case.class,
            classify(&case.error)
        );

        for needle in case.display_needles {
            assert!(
                display.contains(needle),
                "STORE_ERROR DISPLAY DRIFT: {} must include {:?}.\n\
                 display={display}",
                case.name,
                needle
            );
        }

        match case.source_needle {
            Some(needle) => {
                let Some(source) = source.as_deref() else {
                    panic!(
                        "STORE_ERROR SOURCE DRIFT: {} should expose an underlying source error",
                        case.name
                    );
                };
                assert!(
                    source.contains(needle),
                    "STORE_ERROR SOURCE DRIFT: {} should expose {:?}, got {:?}",
                    case.name,
                    needle,
                    source
                );
            }
            None => {
                assert!(
                    source.is_none(),
                    "STORE_ERROR SOURCE DRIFT: {} should not expose an underlying source, got {:?}",
                    case.name,
                    source
                );
            }
        }
    }
}

#[test]
fn coordinate_and_io_conversion_preserve_store_error_routing() {
    let hardening_cases = [
        (
            CoordinateError::NulByte,
            StoreError::CoordinateNulByte,
            "coordinate component contains forbidden NUL byte",
        ),
        (
            CoordinateError::ControlChar,
            StoreError::CoordinateControlChar,
            "coordinate component contains forbidden ASCII control character",
        ),
        (
            CoordinateError::PathTraversal,
            StoreError::CoordinatePathTraversal,
            "coordinate component contains forbidden path-traversal substring",
        ),
    ];

    for (coordinate_error, expected_store_error, expected_display) in hardening_cases {
        let actual = StoreError::from(coordinate_error.clone());
        assert!(
            std::mem::discriminant(&actual) == std::mem::discriminant(&expected_store_error),
            "COORDINATE ROUTING DRIFT: {coordinate_error:?} should route to {expected_store_error:?}, got {actual:?}"
        );
        assert_eq!(
            classify(&actual),
            HandlingClass::Domain,
            "COORDINATE ROUTING CLASS DRIFT: {:?} should stay a domain rejection",
            actual
        );
        assert!(
            actual.to_string().contains(expected_display),
            "COORDINATE ROUTING DISPLAY DRIFT: expected {:?} to contain {:?}",
            actual,
            expected_display
        );
    }

    let empty_entity = Coordinate::new("", "scope").expect_err("empty entity should be rejected");
    let routed = StoreError::from(empty_entity.clone());
    let StoreError::Coordinate(inner) = routed else {
        panic!(
            "COORDINATE ROUTING DRIFT: EmptyEntity should stay wrapped in StoreError::Coordinate"
        );
    };
    assert_eq!(
        inner, empty_entity,
        "COORDINATE ROUTING DRIFT: non-hardening coordinate errors should preserve the original payload"
    );
    assert_eq!(
        classify(&StoreError::Coordinate(inner)),
        HandlingClass::Domain,
        "COORDINATE ROUTING CLASS DRIFT: wrapped coordinate validation must stay a domain rejection"
    );

    let io_error = io::Error::new(io::ErrorKind::TimedOut, "fsync timed out");
    let routed = StoreError::from(io_error);
    let StoreError::Io(source) = routed else {
        panic!("IO ROUTING DRIFT: std::io::Error should stay wrapped in StoreError::Io");
    };
    assert_eq!(source.kind(), io::ErrorKind::TimedOut);
}