batpak 0.7.0

Event sourcing with causal graphs and policy gates. Sync API, zero async.
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
// justifies: INV-TEST-PANIC-AS-ASSERTION, ADR-0010; test body in tests/event_payload_surface.rs exercises precondition-holds invariants; .unwrap is acceptable in test code where a panic is a test failure.
#![allow(clippy::unwrap_used, clippy::panic, clippy::cast_possible_truncation)]
//! Integration tests for the EventPayload typed API surface (ADR-0010).
//!
//! Covers every new public item introduced by the payload-binding layer:
//! EventPayload, append_typed, append_typed_with_options, submit_typed,
//! try_submit_typed, append_reaction_typed, submit_reaction_typed,
//! try_submit_reaction_typed, by_fact_typed, BatchAppendItem::typed,
//! Transition::from_payload.
//!
//! PROVES: LAW-003 (No Orphan Infrastructure), INV-OBS (every pub API has witness).
//! CATCHES: typed payload public surface drift and clean-registry validator regressions.
//! SEEDED: deterministic / no randomness.

use batpak::prelude::*;
use batpak::store::{AppendOptions, BatchAppendItem, CausationRef, Store};
use batpak::typestate::transition::{StateMarker, Transition};

#[path = "support/bounded_writer_reply.rs"]
mod bounded_writer_reply;
#[path = "support/small_store.rs"]
mod small_store_support;
use bounded_writer_reply::writer_reply;
use small_store_support::small_segment_store;

// ─── test payload type ────────────────────────────────────────────────────────
//
// Uses `#[derive(EventPayload)]` from `batpak-macros` (ADR-0010).
// This file doubles as the in-workspace path-hygiene check: the derive
// expands `::batpak::...` paths while compiling inside the batpak
// workspace itself.

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, EventPayload)]
#[batpak(category = 1, type_id = 1)]
struct ThingHappened {
    value: u64,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, EventPayload)]
#[batpak(category = 1, type_id = 2)]
struct OtherThingHappened {
    label: String,
}

mod left_payload_module {
    #[derive(
        Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, batpak::EventPayload,
    )]
    #[batpak(category = 1, type_id = 3)]
    pub(super) struct SharedPayloadName {
        pub value: u64,
    }
}

mod right_payload_module {
    #[derive(
        Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, batpak::EventPayload,
    )]
    #[batpak(category = 1, type_id = 4)]
    pub(super) struct SharedPayloadName {
        pub value: u64,
    }
}

// ─── typestate helpers (minimal) ─────────────────────────────────────────────

#[derive(Debug, Clone, Copy)]
struct Open;
#[derive(Debug, Clone, Copy)]
struct Closed;

impl batpak::typestate::transition::sealed::Sealed for Open {}
impl batpak::typestate::transition::sealed::Sealed for Closed {}
impl StateMarker for Open {}
impl StateMarker for Closed {}

// ─── helpers ─────────────────────────────────────────────────────────────────

fn test_store() -> (Store, tempfile::TempDir) {
    small_segment_store().unwrap()
}

fn coord() -> Coordinate {
    Coordinate::new("entity:payload-test", "scope:test").unwrap()
}

#[test]
fn derive_private_registry_surface_is_available_to_test_binaries() {
    let mut seen = Vec::new();
    for item in batpak::__private::inventory::iter::<batpak::__private::EventPayloadRegistration> {
        seen.push((item.kind_bits, item.type_name));
    }

    assert!(
        seen.iter().any(|(_, name)| name.contains("ThingHappened")),
        "PROPERTY: derive-generated EventPayload registrations must be visible through batpak::__private::inventory in test binaries"
    );
    assert!(
        seen.iter()
            .any(|(_, name)| name.contains("OtherThingHappened")),
        "PROPERTY: multiple derived payload types must each contribute a registration item"
    );

    // With the two payloads in this file using distinct kind bits, the
    // shared collision scanner must be callable and must not panic.
    batpak::__private::scan_for_kind_collisions();
    batpak::__private::assert_no_kind_collisions();
}

#[test]
fn derive_registry_type_names_are_fully_qualified() {
    let expected_left = std::any::type_name::<left_payload_module::SharedPayloadName>();
    let expected_right = std::any::type_name::<right_payload_module::SharedPayloadName>();

    let seen = batpak::__private::inventory::iter::<batpak::__private::EventPayloadRegistration>
        .into_iter()
        .map(|item| item.type_name)
        .collect::<Vec<_>>();

    assert!(
        seen.contains(&expected_left),
        "PROPERTY: registry type names must match std::any::type_name for module-qualified payloads, missing {expected_left}; got {seen:?}"
    );
    assert!(
        seen.contains(&expected_right),
        "PROPERTY: registry type names must distinguish same-ident payloads in different modules, missing {expected_right}; got {seen:?}"
    );
}

// ─── append_typed ─────────────────────────────────────────────────────────────

#[test]
fn append_typed_round_trip() {
    let (store, _dir) = test_store();
    let payload = ThingHappened { value: 42 };
    let receipt = store
        .append_typed(&coord(), &payload)
        .expect("append_typed");
    assert_ne!(
        receipt.event_id, 0,
        "PROPERTY: append_typed must return a non-zero event_id"
    );

    let hits = store.by_fact_typed::<ThingHappened>();
    assert_eq!(
        hits.len(),
        1,
        "PROPERTY: by_fact_typed::<ThingHappened>() must return exactly the one appended event"
    );
    assert_eq!(
        hits[0].event_id, receipt.event_id,
        "PROPERTY: by_fact_typed must return the correct event_id"
    );
    store.close().unwrap();
}

// ─── append_typed_with_options ────────────────────────────────────────────────

#[test]
fn append_typed_with_options_idempotency() {
    let (store, _dir) = test_store();
    let payload = ThingHappened { value: 7 };
    let opts = AppendOptions::new().with_idempotency(0xDEAD_BEEF);

    let r1 = store
        .append_typed_with_options(&coord(), &payload, opts)
        .expect("first append_typed_with_options");
    let r2 = store
        .append_typed_with_options(&coord(), &payload, opts)
        .expect("idempotent second append_typed_with_options");
    assert_eq!(
        r1.event_id, r2.event_id,
        "PROPERTY: append_typed_with_options with the same idempotency key must return the same event_id"
    );
    store.close().unwrap();
}

// ─── submit_typed ─────────────────────────────────────────────────────────────

#[test]
fn submit_typed_wait_returns_receipt() {
    let (store, _dir) = test_store();
    let payload = ThingHappened { value: 99 };
    let ticket = store
        .submit_typed(&coord(), &payload)
        .expect("submit_typed");
    let receipt = writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    assert_ne!(
        receipt.event_id, 0,
        "PROPERTY: submit_typed ticket must resolve to a non-zero event_id"
    );
    store.close().unwrap();
}

// ─── try_submit_typed ─────────────────────────────────────────────────────────

#[test]
fn try_submit_typed_ok_path() {
    let (store, _dir) = test_store();
    let payload = ThingHappened { value: 1 };
    let outcome = store
        .try_submit_typed(&coord(), &payload)
        .expect("try_submit_typed");
    let ticket = outcome.into_result().expect("outcome is Ok");
    writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    store.close().unwrap();
}

// ─── append_reaction_typed ────────────────────────────────────────────────────

#[test]
fn append_reaction_typed_links_causation() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 0 })
        .expect("root append_typed");

    let reaction_coord = Coordinate::new("entity:payload-reaction", "scope:test").unwrap();
    let receipt = store
        .append_reaction_typed(
            &reaction_coord,
            &OtherThingHappened {
                label: "caused".into(),
            },
            root.event_id,
            root.event_id,
        )
        .expect("append_reaction_typed");

    assert_ne!(
        receipt.event_id, 0,
        "PROPERTY: append_reaction_typed must return a non-zero event_id"
    );
    let hits = store.by_fact_typed::<OtherThingHappened>();
    assert_eq!(
        hits.len(),
        1,
        "PROPERTY: by_fact_typed must find the reaction event"
    );
    store.close().unwrap();
}

// ─── submit_reaction_typed ────────────────────────────────────────────────────

#[test]
fn submit_reaction_typed_ticket_resolves() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 0 })
        .expect("root");

    let reaction_coord = Coordinate::new("entity:payload-submit-reaction", "scope:test").unwrap();
    let ticket = store
        .submit_reaction_typed(
            &reaction_coord,
            &OtherThingHappened {
                label: "submitted".into(),
            },
            root.event_id,
            root.event_id,
        )
        .expect("submit_reaction_typed");
    writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    store.close().unwrap();
}

// ─── try_submit_reaction_typed ────────────────────────────────────────────────

#[test]
fn try_submit_reaction_typed_ok_path() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 0 })
        .expect("root");

    let reaction_coord = Coordinate::new("entity:payload-try-reaction", "scope:test").unwrap();
    let outcome = store
        .try_submit_reaction_typed(
            &reaction_coord,
            &OtherThingHappened {
                label: "try-reaction".into(),
            },
            root.event_id,
            root.event_id,
        )
        .expect("try_submit_reaction_typed");
    let ticket = outcome.into_result().expect("outcome is Ok");
    writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    store.close().unwrap();
}

// ─── by_fact_typed ────────────────────────────────────────────────────────────

#[test]
fn by_fact_typed_filters_by_kind() {
    let (store, _dir) = test_store();
    store
        .append_typed(&coord(), &ThingHappened { value: 1 })
        .unwrap();
    store
        .append_typed(&coord(), &ThingHappened { value: 2 })
        .unwrap();

    let other_coord = Coordinate::new("entity:other", "scope:test").unwrap();
    store
        .append_typed(
            &other_coord,
            &OtherThingHappened {
                label: "noise".into(),
            },
        )
        .unwrap();

    let thing_hits = store.by_fact_typed::<ThingHappened>();
    let other_hits = store.by_fact_typed::<OtherThingHappened>();

    assert_eq!(
        thing_hits.len(),
        2,
        "PROPERTY: by_fact_typed must return only ThingHappened events"
    );
    assert_eq!(
        other_hits.len(),
        1,
        "PROPERTY: by_fact_typed must return only OtherThingHappened events"
    );
    store.close().unwrap();
}

// ─── BatchAppendItem::typed ───────────────────────────────────────────────────

#[test]
fn batch_append_item_typed_constructor() {
    let (store, _dir) = test_store();
    let item = BatchAppendItem::typed(
        coord(),
        &ThingHappened { value: 55 },
        AppendOptions::new(),
        CausationRef::None,
    )
    .expect("BatchAppendItem::typed");

    let receipts = store.append_batch(vec![item]).expect("append_batch");
    assert_eq!(
        receipts.len(),
        1,
        "PROPERTY: batch of one typed item must produce one receipt"
    );

    let hits = store.by_fact_typed::<ThingHappened>();
    assert_eq!(
        hits.len(),
        1,
        "PROPERTY: typed batch item must produce a queryable event"
    );
    assert_eq!(
        hits[0].event_id, receipts[0].event_id,
        "PROPERTY: batch receipt event_id must match by_fact_typed result"
    );
    store.close().unwrap();
}

// ─── Transition::from_payload ─────────────────────────────────────────────────

#[test]
fn transition_from_payload_uses_kind_constant() {
    let payload = ThingHappened { value: 77 };
    let transition: Transition<Open, Closed, ThingHappened> = Transition::from_payload(payload);
    assert_eq!(
        transition.kind(),
        ThingHappened::KIND,
        "PROPERTY: Transition::from_payload must set kind to T::KIND"
    );
    assert_eq!(
        transition.payload().value,
        77,
        "PROPERTY: Transition::from_payload must preserve the payload"
    );
}

#[test]
fn transition_from_payload_store_round_trip() {
    let (store, _dir) = test_store();
    let payload = ThingHappened { value: 13 };
    let transition: Transition<Open, Closed, ThingHappened> = Transition::from_payload(payload);

    let receipt = store
        .apply_transition(&coord(), transition)
        .expect("apply_transition with from_payload");
    assert_ne!(receipt.event_id, 0);

    let hits = store.by_fact_typed::<ThingHappened>();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].event_id, receipt.event_id);
    store.close().unwrap();
}

// ─── Outbox::stage_typed family (Dispatch Chapter T5) ────────────────────────

#[test]
fn outbox_stage_typed_smoke() {
    let (store, _dir) = test_store();
    let mut outbox = store.outbox();
    outbox
        .stage_typed(coord(), &ThingHappened { value: 1 })
        .expect("stage_typed");
    let receipts = outbox.flush().expect("flush");
    assert_eq!(
        receipts.len(),
        1,
        "PROPERTY: stage_typed produces one receipt per staged item"
    );
    let hits = store.by_fact_typed::<ThingHappened>();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].event_id, receipts[0].event_id);
    store.close().unwrap();
}

#[test]
fn outbox_stage_typed_with_options_smoke() {
    let (store, _dir) = test_store();
    let opts = AppendOptions::new().with_idempotency(0xDEAD_BEEF);
    let mut outbox = store.outbox();
    outbox
        .stage_typed_with_options(coord(), &ThingHappened { value: 2 }, opts)
        .expect("stage_typed_with_options");
    let receipts = outbox.flush().expect("flush");
    assert_eq!(receipts.len(), 1);
    store.close().unwrap();
}

#[test]
fn outbox_stage_typed_with_causation_smoke() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 3 })
        .expect("root");
    let mut outbox = store.outbox();
    outbox
        .stage_typed_with_causation(
            coord(),
            &OtherThingHappened {
                label: "caused".into(),
            },
            CausationRef::Absolute(root.event_id),
        )
        .expect("stage_typed_with_causation");
    let receipts = outbox.flush().expect("flush");
    assert_eq!(receipts.len(), 1);
    store.close().unwrap();
}

#[test]
fn outbox_stage_typed_with_options_and_causation_smoke() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 4 })
        .expect("root");
    let opts = AppendOptions::new().with_idempotency(0xCAFE_F00D);
    let mut outbox = store.outbox();
    outbox
        .stage_typed_with_options_and_causation(
            coord(),
            &OtherThingHappened {
                label: "caused+opts".into(),
            },
            opts,
            CausationRef::Absolute(root.event_id),
        )
        .expect("stage_typed_with_options_and_causation");
    let receipts = outbox.flush().expect("flush");
    assert_eq!(receipts.len(), 1);
    store.close().unwrap();
}

// ─── VisibilityFence typed submit family (Dispatch Chapter T5) ───────────────

#[test]
fn fence_submit_typed_smoke() {
    let (store, _dir) = test_store();
    let fence = store.begin_visibility_fence().expect("begin fence");
    let ticket = fence
        .submit_typed(&coord(), &ThingHappened { value: 5 })
        .expect("submit_typed");
    fence.commit().expect("commit fence");
    let receipt = writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    assert_ne!(receipt.event_id, 0);
    let hits = store.by_fact_typed::<ThingHappened>();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].event_id, receipt.event_id);
    store.close().unwrap();
}

#[test]
fn fence_submit_reaction_typed_smoke() {
    let (store, _dir) = test_store();
    let root = store
        .append_typed(&coord(), &ThingHappened { value: 6 })
        .expect("root");
    let reaction_coord = Coordinate::new("entity:payload-fence-reaction", "scope:test").unwrap();
    let fence = store.begin_visibility_fence().expect("begin fence");
    let ticket = fence
        .submit_reaction_typed(
            &reaction_coord,
            &OtherThingHappened {
                label: "fenced-reaction".into(),
            },
            root.event_id,
            root.event_id,
        )
        .expect("submit_reaction_typed");
    fence.commit().expect("commit fence");
    let receipt = writer_reply(ticket.receiver(), "typed writer ticket").expect("ticket.wait");
    assert_ne!(receipt.event_id, 0);
    store.close().unwrap();
}