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
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
//! Batpak Substrate Closure reservation ledger: dimensionless `units`, opaque `subject_ref`,
//! closed structural states, explicit transition operations, deterministic findings, and
//! reconciliation buckets. This module does **not** import [`crate::store`] and encodes no payment,
//! inventory, capability, or workflow policy.

use crate::evidence::{content_hash, sort_findings, sorted_findings};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Schema version for [`ReservationLedgerReportBody`].
pub const RESERVATION_LEDGER_REPORT_SCHEMA_VERSION: u32 = 1;

/// Schema version for [`ReservationReconciliationReportBody`].
pub const RESERVATION_RECONCILIATION_REPORT_SCHEMA_VERSION: u32 = 1;

/// Schema version for [`ReservationTransition`] inputs understood by v1 helpers.
pub const RESERVATION_TRANSITION_SCHEMA_VERSION: u32 = 1;

/// Structural reservation state lane (closed set).
pub const RESERVATION_STATE_RESERVED: u32 = 0;
/// Reservation fulfilled and closed.
pub const RESERVATION_STATE_COMMITTED: u32 = 1;
/// Reservation released without commit.
pub const RESERVATION_STATE_REFUNDED: u32 = 2;
/// Reservation lapsed without commit.
pub const RESERVATION_STATE_EXPIRED: u32 = 3;
/// Reservation abandoned while still outstanding.
pub const RESERVATION_STATE_ORPHANED: u32 = 4;

/// Open a new reservation.
pub const RESERVATION_OP_RESERVE: u32 = 0;
/// Commit a reserved slot.
pub const RESERVATION_OP_COMMIT: u32 = 1;
/// Refund/release a reserved slot before commit.
pub const RESERVATION_OP_REFUND: u32 = 2;
/// Mark a reserved slot as expired.
pub const RESERVATION_OP_EXPIRE: u32 = 3;
/// Mark a reserved slot as orphaned (structural hygiene).
pub const RESERVATION_OP_ORPHAN: u32 = 4;

/// Attempted second commit on an already committed reservation.
pub const RESERVATION_REASON_DOUBLE_COMMIT: u32 = 1;
/// Commit when no reservation exists.
pub const RESERVATION_REASON_COMMIT_WITHOUT_RESERVE: u32 = 2;
/// Refund when not in reserved lane.
pub const RESERVATION_REASON_REFUND_INVALID_STATE: u32 = 3;
/// Refund after commit (terminal committed lane).
pub const RESERVATION_REASON_REFUND_AFTER_COMMIT: u32 = 4;
/// Expire when not reserved.
pub const RESERVATION_REASON_EXPIRE_INVALID_STATE: u32 = 5;
/// Orphan when not reserved.
pub const RESERVATION_REASON_ORPHAN_INVALID_STATE: u32 = 6;
/// Second reserve for the same id.
pub const RESERVATION_REASON_DUPLICATE_RESERVE: u32 = 7;
/// Reserve missing subject or zero units.
pub const RESERVATION_REASON_RESERVE_INVALID_SUBJECT_OR_UNITS: u32 = 8;
/// Transition applied to a terminal non-reserved lane.
pub const RESERVATION_REASON_TRANSITION_ON_TERMINAL: u32 = 9;

/// Structural state lane (`RESERVATION_STATE_*` constants).
pub type ReservationState = u32;

/// Stable reservation identity (digest-sized).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ReservationId(pub [u8; 32]);

/// Opaque subject reference (`key_bytes` are caller-defined bytes and are never reordered).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReservationSubjectRef {
    /// Caller-defined namespace discriminant.
    pub namespace: u32,
    /// Opaque subject key material.
    pub key_bytes: Vec<u8>,
}

impl PartialOrd for ReservationSubjectRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ReservationSubjectRef {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.namespace
            .cmp(&other.namespace)
            .then_with(|| self.key_bytes.cmp(&other.key_bytes))
    }
}

/// Dimensionless quantity (no currency or stock semantics).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ReservationQuantity {
    /// Count of abstract units held by the reservation.
    pub units: u64,
}

/// Opaque cause reference (sorted before canonical transition hashing).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ReservationCauseRef {
    /// Caller-defined lane.
    pub lane: u32,
    /// Opaque key bytes (lexicographic tie-break after `lane`).
    pub opaque_key: Vec<u8>,
}

/// One explicit ledger operation (apply in ascending [`ReservationTransition::sequence`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReservationTransition {
    /// Must be `1` for v1 transition encoding helpers.
    pub schema_version: u32,
    /// Monotonic sequence key chosen by the caller (ties broken by [`ReservationId`]).
    pub sequence: u64,
    /// Target reservation id.
    pub reservation_id: ReservationId,
    /// Operation discriminant (see [`RESERVATION_OP_RESERVE`] … [`RESERVATION_OP_ORPHAN`]).
    pub op: u32,
    /// Units for [`RESERVATION_OP_RESERVE`] only (ignored for other ops).
    pub quantity_units: u64,
    /// Required for reserve; omitted for other ops.
    pub subject: Option<ReservationSubjectRef>,
    /// Cause refs; normalized by sorting before hashing.
    pub cause_refs: Vec<ReservationCauseRef>,
}

/// One row in the simulated ledger.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReservationEntry {
    /// Stable id for this reservation.
    pub reservation_id: ReservationId,
    /// Subject the reservation is bound to.
    pub subject_ref: ReservationSubjectRef,
    /// Outstanding units (unchanged by commit/refund lanes in v1).
    pub quantity: ReservationQuantity,
    /// Structural state lane (see `RESERVATION_STATE_*`).
    pub state: ReservationState,
    /// Sequence of the opening reserve.
    pub opened_at_sequence: u64,
}

/// Structural ledger finding (sorted before report `body_hash`).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ReservationFinding {
    /// Illegal or inconsistent operation for the current lane.
    InvalidTransition {
        /// Target reservation id.
        reservation_id: ReservationId,
        /// State before the attempted op (best-effort `u32::MAX` when missing).
        from_state: u32,
        /// Attempted op ([`RESERVATION_OP_RESERVE`] …).
        attempted_op: u32,
        /// Stable reason code (see `RESERVATION_REASON_*`).
        reason_code: u32,
    },
    /// Transition schema version is not supported by these v1 helpers.
    UnsupportedTransitionSchemaVersion {
        /// Target reservation id.
        reservation_id: ReservationId,
        /// Observed transition schema version.
        observed: u32,
        /// Supported transition schema version.
        expected: u32,
    },
}

/// Canonical ledger report body after simulating normalized transitions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReservationLedgerReportBody {
    /// Must equal [`RESERVATION_LEDGER_REPORT_SCHEMA_VERSION`] for v1.
    pub schema_version: u32,
    /// Digest over canonical normalized transition bytes (see [`reservation_transition_log_digest`]).
    pub transition_log_digest: [u8; 32],
    /// Ledger rows sorted by [`ReservationId`].
    pub entries_sorted: Vec<ReservationEntry>,
    /// Structural findings (sorted before [`reservation_ledger_report_body_hash`]).
    pub findings_sorted: Vec<ReservationFinding>,
}

/// Reconciliation view over structural terminal and outstanding lanes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReservationReconciliationReportBody {
    /// Must equal [`RESERVATION_RECONCILIATION_REPORT_SCHEMA_VERSION`] for v1.
    pub schema_version: u32,
    /// Ids still in reserved lane.
    pub reserved_open_ids: Vec<ReservationId>,
    /// Ids in expired lane.
    pub expired_ids: Vec<ReservationId>,
    /// Ids in orphaned lane.
    pub orphaned_ids: Vec<ReservationId>,
    /// Ids in committed lane.
    pub committed_ids: Vec<ReservationId>,
    /// Ids in refunded lane.
    pub refunded_ids: Vec<ReservationId>,
}

/// Alias for evidence-style naming.
pub type ReservationReconciliationReport = ReservationReconciliationReportBody;

/// Digest width for reservation reports.
pub type ReservationDigest = [u8; 32];

/// Normalize subject ref.
///
/// `key_bytes` are opaque caller material and are preserved byte-for-byte.
#[must_use]
pub fn normalize_reservation_subject_ref(subject: &ReservationSubjectRef) -> ReservationSubjectRef {
    subject.clone()
}

/// Normalize transition for hashing (sorts `cause_refs`).
#[must_use]
pub fn normalize_reservation_transition(t: &ReservationTransition) -> ReservationTransition {
    let mut cause_refs = t.cause_refs.clone();
    cause_refs.sort();
    ReservationTransition {
        cause_refs,
        ..t.clone()
    }
}

/// Canonical bytes for a normalized transition.
///
/// # Errors
/// MessagePack encode failure from `rmp-serde`.
pub fn reservation_transition_bytes(
    t: &ReservationTransition,
) -> Result<Vec<u8>, rmp_serde::encode::Error> {
    let n = normalize_reservation_transition(t);
    crate::encoding::to_bytes(&n)
}

/// Sort transitions by `(sequence, reservation_id)` then normalize each.
#[must_use]
pub fn normalize_reservation_transition_list(
    transitions: &[ReservationTransition],
) -> Vec<ReservationTransition> {
    let mut out: Vec<ReservationTransition> = transitions
        .iter()
        .map(normalize_reservation_transition)
        .collect();
    out.sort_by(|a, b| {
        a.sequence
            .cmp(&b.sequence)
            .then_with(|| a.reservation_id.cmp(&b.reservation_id))
    });
    out
}

/// Digest over concatenated canonical transition bytes (deterministic for a normalized list).
///
/// # Errors
/// MessagePack encode failure from `rmp-serde`.
pub fn reservation_transition_log_digest(
    transitions_sorted: &[ReservationTransition],
) -> Result<ReservationDigest, rmp_serde::encode::Error> {
    let mut buf = Vec::new();
    for t in transitions_sorted {
        buf.extend_from_slice(&reservation_transition_bytes(t)?);
    }
    Ok(content_hash(&buf))
}

fn push_invalid(
    out: &mut Vec<ReservationFinding>,
    id: ReservationId,
    from: u32,
    op: u32,
    reason: u32,
) {
    out.push(ReservationFinding::InvalidTransition {
        reservation_id: id,
        from_state: from,
        attempted_op: op,
        reason_code: reason,
    });
}

/// Simulate transitions and return a canonical ledger report body.
///
/// # Errors
/// MessagePack encode failure while computing the transition log digest.
pub fn simulate_reservation_ledger(
    transitions: &[ReservationTransition],
) -> Result<ReservationLedgerReportBody, rmp_serde::encode::Error> {
    let sorted = normalize_reservation_transition_list(transitions);
    let digest = reservation_transition_log_digest(&sorted)?;
    let mut findings = Vec::new();
    let mut ledger: BTreeMap<ReservationId, ReservationEntry> = BTreeMap::new();

    for t in &sorted {
        if t.schema_version != RESERVATION_TRANSITION_SCHEMA_VERSION {
            findings.push(ReservationFinding::UnsupportedTransitionSchemaVersion {
                reservation_id: t.reservation_id,
                observed: t.schema_version,
                expected: RESERVATION_TRANSITION_SCHEMA_VERSION,
            });
            continue;
        }
        let id = t.reservation_id;
        match t.op {
            RESERVATION_OP_RESERVE => {
                if let Some(existing) = ledger.get(&id) {
                    push_invalid(
                        &mut findings,
                        id,
                        existing.state,
                        t.op,
                        RESERVATION_REASON_DUPLICATE_RESERVE,
                    );
                    continue;
                }
                let Some(subject) = t.subject.as_ref() else {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_RESERVE_INVALID_SUBJECT_OR_UNITS,
                    );
                    continue;
                };
                if t.quantity_units == 0 {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_RESERVE_INVALID_SUBJECT_OR_UNITS,
                    );
                    continue;
                }
                let subject_ref = normalize_reservation_subject_ref(subject);
                ledger.insert(
                    id,
                    ReservationEntry {
                        reservation_id: id,
                        subject_ref,
                        quantity: ReservationQuantity {
                            units: t.quantity_units,
                        },
                        state: RESERVATION_STATE_RESERVED,
                        opened_at_sequence: t.sequence,
                    },
                );
            }
            RESERVATION_OP_COMMIT => {
                let Some(entry) = ledger.get_mut(&id) else {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_COMMIT_WITHOUT_RESERVE,
                    );
                    continue;
                };
                match entry.state {
                    RESERVATION_STATE_RESERVED => entry.state = RESERVATION_STATE_COMMITTED,
                    RESERVATION_STATE_COMMITTED => {
                        push_invalid(
                            &mut findings,
                            id,
                            entry.state,
                            t.op,
                            RESERVATION_REASON_DOUBLE_COMMIT,
                        );
                    }
                    _ => {
                        push_invalid(
                            &mut findings,
                            id,
                            entry.state,
                            t.op,
                            RESERVATION_REASON_TRANSITION_ON_TERMINAL,
                        );
                    }
                }
            }
            RESERVATION_OP_REFUND => {
                let Some(entry) = ledger.get_mut(&id) else {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_REFUND_INVALID_STATE,
                    );
                    continue;
                };
                match entry.state {
                    RESERVATION_STATE_RESERVED => entry.state = RESERVATION_STATE_REFUNDED,
                    RESERVATION_STATE_COMMITTED => {
                        push_invalid(
                            &mut findings,
                            id,
                            entry.state,
                            t.op,
                            RESERVATION_REASON_REFUND_AFTER_COMMIT,
                        );
                    }
                    _ => {
                        push_invalid(
                            &mut findings,
                            id,
                            entry.state,
                            t.op,
                            RESERVATION_REASON_REFUND_INVALID_STATE,
                        );
                    }
                }
            }
            RESERVATION_OP_EXPIRE => {
                let Some(entry) = ledger.get_mut(&id) else {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_EXPIRE_INVALID_STATE,
                    );
                    continue;
                };
                if entry.state == RESERVATION_STATE_RESERVED {
                    entry.state = RESERVATION_STATE_EXPIRED;
                } else {
                    push_invalid(
                        &mut findings,
                        id,
                        entry.state,
                        t.op,
                        RESERVATION_REASON_EXPIRE_INVALID_STATE,
                    );
                }
            }
            RESERVATION_OP_ORPHAN => {
                let Some(entry) = ledger.get_mut(&id) else {
                    push_invalid(
                        &mut findings,
                        id,
                        u32::MAX,
                        t.op,
                        RESERVATION_REASON_ORPHAN_INVALID_STATE,
                    );
                    continue;
                };
                if entry.state == RESERVATION_STATE_RESERVED {
                    entry.state = RESERVATION_STATE_ORPHANED;
                } else {
                    push_invalid(
                        &mut findings,
                        id,
                        entry.state,
                        t.op,
                        RESERVATION_REASON_ORPHAN_INVALID_STATE,
                    );
                }
            }
            _ => {
                push_invalid(
                    &mut findings,
                    id,
                    u32::MAX,
                    t.op,
                    RESERVATION_REASON_TRANSITION_ON_TERMINAL,
                );
            }
        }
    }

    sort_findings(&mut findings);
    let mut entries_sorted: Vec<ReservationEntry> = ledger.into_values().collect();
    entries_sorted.sort_by(|a, b| a.reservation_id.cmp(&b.reservation_id));

    Ok(ReservationLedgerReportBody {
        schema_version: RESERVATION_LEDGER_REPORT_SCHEMA_VERSION,
        transition_log_digest: digest,
        entries_sorted,
        findings_sorted: findings,
    })
}

/// Build a reconciliation report from ledger entries (each bucket sorted by id).
#[must_use]
pub fn reservation_reconciliation_report(
    entries: &[ReservationEntry],
) -> ReservationReconciliationReportBody {
    let mut reserved_open_ids = Vec::new();
    let mut expired_ids = Vec::new();
    let mut orphaned_ids = Vec::new();
    let mut committed_ids = Vec::new();
    let mut refunded_ids = Vec::new();
    for e in entries {
        match e.state {
            RESERVATION_STATE_RESERVED => reserved_open_ids.push(e.reservation_id),
            RESERVATION_STATE_EXPIRED => expired_ids.push(e.reservation_id),
            RESERVATION_STATE_ORPHANED => orphaned_ids.push(e.reservation_id),
            RESERVATION_STATE_COMMITTED => committed_ids.push(e.reservation_id),
            RESERVATION_STATE_REFUNDED => refunded_ids.push(e.reservation_id),
            _ => {}
        }
    }
    reserved_open_ids.sort();
    expired_ids.sort();
    orphaned_ids.sort();
    committed_ids.sort();
    refunded_ids.sort();
    ReservationReconciliationReportBody {
        schema_version: RESERVATION_RECONCILIATION_REPORT_SCHEMA_VERSION,
        reserved_open_ids,
        expired_ids,
        orphaned_ids,
        committed_ids,
        refunded_ids,
    }
}

/// Deterministic digest over [`ReservationLedgerReportBody`] (sorts `findings_sorted` clone).
///
/// # Errors
/// MessagePack encode failure from `rmp-serde`.
pub fn reservation_ledger_report_body_hash(
    body: &ReservationLedgerReportBody,
) -> Result<ReservationDigest, rmp_serde::encode::Error> {
    let findings_sorted = sorted_findings(&body.findings_sorted);
    let mut entries_sorted = body.entries_sorted.clone();
    entries_sorted.sort_by(|a, b| a.reservation_id.cmp(&b.reservation_id));
    let normalized = ReservationLedgerReportBody {
        findings_sorted,
        entries_sorted,
        ..body.clone()
    };
    let bytes = crate::encoding::to_bytes(&normalized)?;
    Ok(content_hash(&bytes))
}

/// Deterministic digest over [`ReservationReconciliationReportBody`].
///
/// # Errors
/// MessagePack encode failure from `rmp-serde`.
pub fn reservation_reconciliation_report_body_hash(
    body: &ReservationReconciliationReportBody,
) -> Result<ReservationDigest, rmp_serde::encode::Error> {
    let bytes = crate::encoding::to_bytes(body)?;
    Ok(content_hash(&bytes))
}