graphrefly-storage 0.0.9

GraphReFly storage tier dispatch + Node-side persistence (memory, file, redb)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! WAL frame substrate (Phase 14.6 — DS-14-storage Q1+Q3+Q5 locks, M4.A
//! 2026-05-10).
//!
//! On-disk frame format consumed by `Graph::restore_snapshot({ mode:"diff" })`
//! (M4.E). Each frame decomposes a single graph diff into one DS-14
//! [`BaseChange<T>`] envelope per structural-or-value change, scoped by
//! [`Lifecycle`] so callers can narrow rewinds.
//!
//! The TS reference impl lives at
//! `packages/pure-ts/src/extra/storage/wal.ts`. Field names + checksum
//! algorithm are parity-locked — both impls produce byte-identical hex SHA-256
//! over the same canonical-JSON encoding of a frame body.
//!
//! # Canonical-JSON parity
//!
//! TS's `stableJsonString` (`packages/pure-ts/src/extra/storage/core.ts:22-39`)
//! is "recursively sort object keys, then `JSON.stringify(_, undefined, 0)`".
//! The Rust port mirrors this by routing the frame body through
//! [`serde_json::to_value`] (lands in `serde_json::Map` which is `BTreeMap` by
//! default — sorted iteration) then [`serde_json::to_string`]. Output is
//! byte-identical to TS for the WAL frame schema: ASCII keys, integer
//! numerics, no floats.
//!
//! **Parity caveats** (lift when a real consumer surfaces):
//! - String VALUES containing surrogate-pair code points (≥ U+10000): JS sorts
//!   keys by UTF-16 code-unit order; Rust `BTreeMap` sorts by UTF-8 byte order.
//!   For ASCII keys these agree; for non-BMP keys they don't. The frame
//!   schema's keys are ASCII so this can only bite if `path` or
//!   `change.structure` contains non-BMP code points — neither is expected
//!   for graph identifiers.
//! - Float-typed user payloads: JS `JSON.stringify` uses IEEE 754 with
//!   shortest-decimal-round-trip; Rust's `serde_json` uses `ryu` which agrees
//!   on finite f64 in safe range but may diverge on subnormals. WAL frames
//!   typically carry integer-only data; if a user puts a float in
//!   `change.change`, document the constraint.
//!
//! # Checksum
//!
//! SHA-256 over canonical-JSON of the frame body (everything except the
//! `checksum` field itself), encoded as a 64-char lowercase hex string.
//! Spec-locked at `GRAPHREFLY-SPEC.md:1201-1206` — original BLAKE3 lock was
//! revised to SHA-256 so the TS impl could stay zero-dep (no BLAKE3 in
//! `WebCrypto`). Rust matches via `sha2` + `hex`.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use graphrefly_structures::{BaseChange, Lifecycle};

// ── WAL frame envelope ─────────────────────────────────────────────────────

/// On-disk WAL frame (DS-14-storage Q1 lock).
///
/// Two seq fields and two timestamp fields are intentional:
/// - [`Self::frame_seq`] ≠ `change.seq`: latter is the bundle's `mutations`
///   cursor (DS-14 T1); former is the WAL tier's own cursor (this record's
///   position in the WAL stream). Replay uses `frame_seq` for ordering;
///   `change.seq` is only relevant for bundle-level cursor restoration.
/// - [`Self::frame_t_ns`] ≠ `change.t_ns`: latter is wall-clock at mutation
///   entry; former is wall-clock at WAL-write time. Under debounced tiers
///   they differ by `debounce_ms`.
///
/// The bridge wire format (DS-14 PART 5 worker bridge) is the schema-narrowed
/// subset `{ t, lifecycle, path, change }` — this struct is the
/// persistence-tier superset (DS-14-storage L3 lock).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WALFrame<T> {
    /// Bridge tag — discriminator shared with the DS-14 worker-bridge wire
    /// format. Always `"c"`; allocated as `String` for parity with the TS
    /// wire shape (TS uses a literal `"c"` value).
    pub t: WalTag,
    /// Lifecycle scope (DS-14 PART 4). Determines replay phase ordering.
    pub lifecycle: Lifecycle,
    /// Target node / bundle path (per-graph qualified path).
    pub path: String,
    /// DS-14 universal [`BaseChange<T>`] envelope — structure-tagged delta.
    pub change: BaseChange<T>,
    /// WAL-tier monotonic cursor (uniquely owned by the WAL tier writer).
    pub frame_seq: u64,
    /// Wall-clock at WAL-write time (matches `wall_clock_ns()`).
    pub frame_t_ns: u64,
    /// SHA-256 over the canonical-JSON of the frame body sans `checksum`,
    /// encoded as a 64-char lowercase hex string. Hex (vs raw bytes) keeps
    /// the wire format JSON-codec-friendly. M4.A parity-fixture asserts
    /// byte-equivalence against the TS impl.
    #[serde(default)]
    pub checksum: String,
    /// Codec version tag. All M4.A frames are implicitly version 1
    /// (JSON codec). Defaults to `1` for backward-compatible deserialization
    /// of frames written before this field was added.
    #[serde(default = "default_format_version")]
    pub format_version: u32,
}

fn default_format_version() -> u32 {
    1
}

/// Singleton-string discriminator for the bridge wire-format tag. Always
/// serializes / deserializes as `"c"`; rejects any other value at parse time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WalTag;

impl WalTag {
    pub const VALUE: &'static str = "c";
}

impl Serialize for WalTag {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(Self::VALUE)
    }
}

impl<'de> Deserialize<'de> for WalTag {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        if s == Self::VALUE {
            Ok(WalTag)
        } else {
            Err(serde::de::Error::custom(format!(
                "WALFrame.t must be {:?}, got {:?}",
                Self::VALUE,
                s
            )))
        }
    }
}

// ── Key format (Q5) ────────────────────────────────────────────────────────

/// Default WAL prefix segment relative to a `graph.name`. Frames land at
/// `${graph.name}/${WAL_KEY_SEGMENT}/${frame_seq:020}`.
pub const WAL_KEY_SEGMENT: &str = "wal";

/// Pad width for `frame_seq` in WAL keys. 20 digits keeps lex-ASC string sort
/// = numeric ASC up to `frame_seq < 10^20` (well past `u64::MAX`).
pub const WAL_FRAME_SEQ_PAD: usize = 20;

/// Build the canonical WAL frame key. `prefix` is the WAL-prefix portion (e.g.
/// `"my-graph/wal"`); `frame_seq` is the per-frame cursor. Zero-padded so
/// lex-ASC string sort equals numeric ASC sort.
#[must_use]
pub fn wal_frame_key(prefix: &str, frame_seq: u64) -> String {
    format!("{prefix}/{frame_seq:020}")
}

/// Default WAL key prefix for a graph by its `name`.
#[must_use]
pub fn graph_wal_prefix(graph_name: &str) -> String {
    format!("{graph_name}/{WAL_KEY_SEGMENT}")
}

// ── Replay order (Q2) ──────────────────────────────────────────────────────

/// Cross-scope replay order (DS-14 PART 4 lock — `Spec → Data → Ownership`).
/// Exported so the replay implementation and parity tests share one source of
/// truth.
pub const REPLAY_ORDER: [Lifecycle; 3] = [Lifecycle::Spec, Lifecycle::Data, Lifecycle::Ownership];

// ── Checksum ───────────────────────────────────────────────────────────────

/// Errors surfaced by checksum compute / verify.
#[derive(Debug, thiserror::Error)]
pub enum ChecksumError {
    /// `serde_json` rejected the frame body — typically a non-serializable
    /// payload (e.g. a `Map` with non-string keys, an `f64::NAN`).
    #[error("canonical JSON encoding failed: {0}")]
    CanonicalJsonFailed(#[from] serde_json::Error),
    /// Frame body contains content that cannot round-trip cross-impl through
    /// canonical JSON. Specifically: non-ASCII object keys (JS sorts by UTF-16
    /// code-unit order; Rust `BTreeMap` sorts by UTF-8 byte order — these
    /// diverge for keys containing surrogate-pair code points), or subnormal
    /// f64 values (JS `JSON.stringify` and Rust `serde_json` via `ryu` may
    /// diverge on denormalized floats). Banned at the WAL encode boundary
    /// (B1 — option a) rather than allowed-with-silent-divergence.
    #[error("non-canonical content rejected by WAL encoder: {reason}")]
    NonCanonicalContent { reason: String },
}

/// Body fields contributing to the checksum, in the shape TS computes over
/// (TS's `canonicalFrameBody` at `wal.ts:141`). The `checksum` field of the
/// outer [`WALFrame`] is deliberately excluded.
#[derive(Serialize)]
struct ChecksumBody<'a, T: Serialize> {
    t: &'static str,
    lifecycle: &'a Lifecycle,
    path: &'a str,
    change: &'a BaseChange<T>,
    frame_seq: u64,
    frame_t_ns: u64,
}

/// Encode a typed value to canonical JSON (sorted keys, no whitespace).
/// Routes through [`serde_json::Value`] so the resulting `serde_json::Map<
/// String, Value>` (BTreeMap-backed by default) iterates in sorted-key order
/// — byte-identical to TS `stableJsonString` on the WAL schema.
///
/// **Cross-impl encode guard (B1 — option a).** After conversion to
/// [`serde_json::Value`], the tree is walked once and rejected via
/// [`ChecksumError::NonCanonicalContent`] if it contains any input that
/// cannot round-trip byte-identically through TS canonical JSON:
///
/// - **Non-ASCII object keys** — JS sorts by UTF-16 code-unit order; Rust
///   `BTreeMap` sorts by UTF-8 byte order. For keys containing surrogate-pair
///   code points (≥ U+10000) these diverge. WAL frame schema keys are ASCII
///   by spec; user-supplied identifiers in `path` or `change.structure`
///   are NOT — this guard surfaces the divergence at write time rather than
///   letting checksums silently mismatch on cross-impl replay.
/// - **Subnormal f64** — JS `JSON.stringify` and Rust `serde_json` (via `ryu`)
///   may format denormalized floats differently; subnormals are vanishingly
///   rare in graphrefly payloads (integer counters dominate) but the
///   divergence is theoretical, so the strict guard refuses them.
/// - **NaN / ±Infinity** — already rejected at `serde_json::Number::from_f64`
///   conversion (returns `None`); the resulting `serde_json::Error` flows
///   through the existing `CanonicalJsonFailed` variant.
fn canonical_json<T: Serialize>(value: &T) -> Result<String, ChecksumError> {
    let v = serde_json::to_value(value)?;
    validate_canonical(&v, 0)?;
    serde_json::to_string(&v).map_err(ChecksumError::from)
}

/// /qa G2.6 (2026-05-22): depth cap. graphrefly payloads are bounded
/// (`BaseChange<T>` envelopes), but `serde_json::Value` is the escape
/// hatch — a misbehaving binding could synthesize a deeply-nested tree
/// and overflow the recursion stack inside this validator. 128 levels
/// matches `serde_json::de::Deserializer`'s default recursion limit; a
/// value tree exceeding it cannot have been parsed from JSON and is
/// rejected at the canonical-encode boundary instead of crashing the
/// process.
const VALIDATE_CANONICAL_MAX_DEPTH: u32 = 128;

/// Recursively validate a `Value` tree against the canonical-encode guard.
/// See [`canonical_json`] for the rejection criteria.
fn validate_canonical(v: &serde_json::Value, depth: u32) -> Result<(), ChecksumError> {
    if depth > VALIDATE_CANONICAL_MAX_DEPTH {
        return Err(ChecksumError::NonCanonicalContent {
            reason: format!(
                "JSON nesting depth exceeds {VALIDATE_CANONICAL_MAX_DEPTH} \
                 (matches serde_json's default deserialization recursion limit; \
                 deeper trees cannot round-trip through standard JSON parsers)"
            ),
        });
    }
    match v {
        serde_json::Value::Object(map) => {
            for (k, child) in map {
                if !k.is_ascii() {
                    return Err(ChecksumError::NonCanonicalContent {
                        reason: format!(
                            "non-ASCII object key {k:?} \
                             (JS sorts UTF-16 code units, Rust sorts UTF-8 bytes — \
                             divergent for code points ≥ U+10000)"
                        ),
                    });
                }
                validate_canonical(child, depth + 1)?;
            }
            Ok(())
        }
        serde_json::Value::Array(arr) => arr
            .iter()
            .try_for_each(|child| validate_canonical(child, depth + 1)),
        serde_json::Value::Number(n) => {
            if let Some(f) = n.as_f64() {
                // `serde_json::Number::from_f64` already rejects NaN/Inf, so
                // any f64 reaching this point is finite. Subnormals slip
                // through finite checks but format-differ between TS and Rust.
                //
                // /qa G2.5 (2026-05-22): the prior guard `f != 0.0 && !f.is_normal()`
                // accepted `-0.0` because `-0.0 == 0.0` is true — but
                // `JSON.stringify(-0.0)` is `"0"` while `serde_json` emits
                // `"-0.0"`. That is EXACTLY the divergence the guard exists
                // to catch. Discriminate via the raw bit pattern: positive
                // zero is `0x0000_0000_0000_0000`; any other bit pattern
                // (including `0x8000_0000_0000_0000` for `-0.0` and all
                // subnormals) is rejected.
                let bits = f.to_bits();
                if bits != 0 && !f.is_normal() {
                    return Err(ChecksumError::NonCanonicalContent {
                        reason: format!(
                            "non-canonical f64 {f:e} (bits={bits:#018x}) \
                             (rejects -0.0 + subnormals — JS `JSON.stringify` \
                             and Rust `serde_json` may format these differently)"
                        ),
                    });
                }
            }
            Ok(())
        }
        // String values can carry arbitrary UTF-8 — the canonical-JSON rule
        // only constrains *keys* (which control sort order); string values
        // serialize identically across impls via `\uXXXX` for non-ASCII.
        serde_json::Value::String(_) | serde_json::Value::Bool(_) | serde_json::Value::Null => {
            Ok(())
        }
    }
}

/// Compute the SHA-256 checksum over a frame's body (sans `checksum`),
/// returning a 64-char lowercase hex string. Parity-locked with TS
/// `walFrameChecksum`.
pub fn wal_frame_checksum<T: Serialize>(frame: &WALFrame<T>) -> Result<String, ChecksumError> {
    let body = ChecksumBody {
        t: WalTag::VALUE,
        lifecycle: &frame.lifecycle,
        path: frame.path.as_str(),
        change: &frame.change,
        frame_seq: frame.frame_seq,
        frame_t_ns: frame.frame_t_ns,
    };
    let canonical = canonical_json(&body)?;
    let digest = Sha256::digest(canonical.as_bytes());
    Ok(hex::encode(digest))
}

/// Verify a frame's `checksum` field matches its body. Replay invokes this at
/// the WAL tail (drop on mismatch by default) and mid-stream (abort on
/// mismatch by default) per Q3.
pub fn verify_wal_frame_checksum<T: Serialize>(frame: &WALFrame<T>) -> Result<bool, ChecksumError> {
    let expected = wal_frame_checksum(frame)?;
    Ok(frame.checksum == expected)
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use graphrefly_structures::Version;

    fn sample_frame() -> WALFrame<u64> {
        WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "root/state".into(),
            change: BaseChange {
                structure: "graphValue".into(),
                version: Version::Counter(1),
                t_ns: 1_700_000_000_000,
                seq: Some(0),
                lifecycle: Lifecycle::Data,
                change: 42,
            },
            frame_seq: 17,
            frame_t_ns: 1_700_000_001_000,
            checksum: String::new(),
            format_version: 1,
        }
    }

    #[test]
    fn wal_frame_key_zero_pads_to_20_digits() {
        assert_eq!(wal_frame_key("g/wal", 0), "g/wal/00000000000000000000",);
        assert_eq!(wal_frame_key("g/wal", 17), "g/wal/00000000000000000017",);
        assert_eq!(
            wal_frame_key("g/wal", u64::MAX),
            format!("g/wal/{:020}", u64::MAX),
        );
    }

    #[test]
    fn wal_frame_key_lex_sort_equals_numeric_sort() {
        // Build keys for 0, 1, 10, 100, u64::MAX. Sort lex; assert numeric
        // order is preserved (the core invariant `frame_seq` ASC = lex ASC).
        let seqs = [0u64, 1, 10, 100, 1_000_000, u64::MAX];
        let mut keys: Vec<String> = seqs.iter().map(|s| wal_frame_key("g/wal", *s)).collect();
        keys.sort();
        for (k, expected) in keys.iter().zip(seqs.iter()) {
            assert!(
                k.ends_with(&format!("{expected:020}")),
                "lex-sort key {k} did not match numeric order for {expected}",
            );
        }
    }

    #[test]
    fn graph_wal_prefix_joins_with_segment() {
        assert_eq!(graph_wal_prefix("my-graph"), "my-graph/wal");
    }

    #[test]
    fn checksum_roundtrip_verifies() {
        let mut frame = sample_frame();
        frame.checksum = wal_frame_checksum(&frame).unwrap();
        assert!(verify_wal_frame_checksum(&frame).unwrap());
    }

    #[test]
    fn checksum_tamper_change_payload_fails_verify() {
        let mut frame = sample_frame();
        frame.checksum = wal_frame_checksum(&frame).unwrap();
        frame.change.change = 43; // tamper the user payload
        assert!(!verify_wal_frame_checksum(&frame).unwrap());
    }

    #[test]
    fn checksum_tamper_path_fails_verify() {
        let mut frame = sample_frame();
        frame.checksum = wal_frame_checksum(&frame).unwrap();
        frame.path = "different/path".into();
        assert!(!verify_wal_frame_checksum(&frame).unwrap());
    }

    #[test]
    fn checksum_tamper_frame_seq_fails_verify() {
        let mut frame = sample_frame();
        frame.checksum = wal_frame_checksum(&frame).unwrap();
        frame.frame_seq = 18;
        assert!(!verify_wal_frame_checksum(&frame).unwrap());
    }

    #[test]
    fn checksum_excludes_checksum_field_itself() {
        let mut frame = sample_frame();
        frame.checksum = "deadbeef".repeat(8);
        let first = wal_frame_checksum(&frame).unwrap();
        frame.checksum = "00".repeat(32);
        let second = wal_frame_checksum(&frame).unwrap();
        assert_eq!(
            first, second,
            "wal_frame_checksum must not depend on the existing checksum field",
        );
    }

    #[test]
    fn checksum_is_64_char_lowercase_hex() {
        let mut frame = sample_frame();
        frame.checksum = wal_frame_checksum(&frame).unwrap();
        assert_eq!(frame.checksum.len(), 64);
        assert!(
            frame
                .checksum
                .chars()
                .all(|c| matches!(c, '0'..='9' | 'a'..='f')),
            "checksum must be lowercase hex: {}",
            frame.checksum,
        );
    }

    #[test]
    fn wal_tag_serializes_as_string_c() {
        let s = serde_json::to_string(&WalTag).unwrap();
        assert_eq!(s, "\"c\"");
    }

    #[test]
    fn wal_tag_rejects_other_values() {
        let r: Result<WalTag, _> = serde_json::from_str("\"x\"");
        assert!(r.is_err(), "WalTag must reject non-c discriminators");
    }

    #[test]
    fn canonical_json_sorts_keys() {
        // Canonical-JSON sanity check on a struct with declaration order
        // OPPOSITE to alphabetical: `zebra, monkey, apple`. The emitted JSON
        // must list keys in alphabetical order regardless of declaration
        // order (mirrors TS `stableJsonString` recursive key sort). Single
        // level only so `find` matches unambiguously.
        #[derive(Serialize)]
        struct Flat {
            zebra: u32,
            monkey: u32,
            apple: u32,
        }
        let json = canonical_json(&Flat {
            zebra: 1,
            monkey: 2,
            apple: 3,
        })
        .unwrap();
        assert_eq!(json, "{\"apple\":3,\"monkey\":2,\"zebra\":1}");
    }

    /// Cross-impl parity fixture.
    ///
    /// This is the parity-or-bust check: a hand-computed canonical-JSON +
    /// SHA-256 fixture sourced from running TS's `walFrameChecksum` on the
    /// same input. If the Rust impl drifts from byte-identical TS output,
    /// this test fails loudly.
    ///
    /// Fixture inputs are deliberately minimal (single `u64` change payload)
    /// so the expected canonical bytes are auditable by hand.
    #[test]
    fn checksum_parity_fixture_minimal_frame() {
        // Frame body:
        //   { t:"c", lifecycle:"data", path:"p",
        //     change:{ change:0, lifecycle:"data", structure:"s", t_ns:0, version:0 },
        //     frame_seq:0, frame_t_ns:0 }
        //
        // Canonical (sorted-key, no whitespace) form:
        //   {"change":{"change":0,"lifecycle":"data","structure":"s","t_ns":0,"version":0},"frame_seq":0,"frame_t_ns":0,"lifecycle":"data","path":"p","t":"c"}
        //
        // SHA-256 over those bytes is checked below. Regenerate via:
        //   python3 -c 'import hashlib; print(hashlib.sha256(b\'{"change":...}\').hexdigest())'
        let frame: WALFrame<u64> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: 0,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let computed = wal_frame_checksum(&frame).unwrap();

        // Sanity: confirm the canonical body the Rust impl is hashing.
        let body = ChecksumBody {
            t: WalTag::VALUE,
            lifecycle: &frame.lifecycle,
            path: frame.path.as_str(),
            change: &frame.change,
            frame_seq: frame.frame_seq,
            frame_t_ns: frame.frame_t_ns,
        };
        let canonical = canonical_json(&body).unwrap();
        let expected_canonical = "{\"change\":{\"change\":0,\"lifecycle\":\"data\",\"structure\":\"s\",\"t_ns\":0,\"version\":0},\"frame_seq\":0,\"frame_t_ns\":0,\"lifecycle\":\"data\",\"path\":\"p\",\"t\":\"c\"}";
        assert_eq!(
            canonical, expected_canonical,
            "canonical JSON drifted from TS-side stableJsonString shape",
        );

        // SHA-256 hex of the canonical bytes above (computed via shell:
        // `printf '<canonical>' | shasum -a 256`).
        let expected_sha = "d00054d7886e1d73c07a0086e5cbccddf62de3c0cadae31e75d78215b3293ece";
        assert_eq!(
            computed, expected_sha,
            "SHA-256 hex drifted; canonical bytes were:\n  {canonical}",
        );
    }

    /// /qa A5 (2026-05-10): parity-fixture for `Lifecycle::Spec` — locks
    /// the canonical-JSON byte shape and SHA-256 for the `"spec"` discriminant.
    #[test]
    fn checksum_parity_fixture_lifecycle_spec() {
        let frame: WALFrame<u64> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Spec,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Spec,
                change: 0,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let expected_sha = "7e857f0862bd429d7d144980a2580da732e0d4b420a03d73d63462368f896c3b";
        assert_eq!(wal_frame_checksum(&frame).unwrap(), expected_sha);
    }

    /// /qa A5 (2026-05-10): parity-fixture for `Lifecycle::Ownership`.
    #[test]
    fn checksum_parity_fixture_lifecycle_ownership() {
        let frame: WALFrame<u64> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Ownership,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Ownership,
                change: 0,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let expected_sha = "901d3d70d38d954864243bdee5a88cb6d204e5e9823598606d38c10e604c3af4";
        assert_eq!(wal_frame_checksum(&frame).unwrap(), expected_sha);
    }

    /// /qa A6 (2026-05-10): parity-fixture for `seq: Some(0)`. The
    /// `skip_serializing_if` attribute means `None` omits the field; `Some(0)`
    /// emits `"seq":0`. Both round-trip cleanly. Distinct SHA from the
    /// `seq: None` fixture above proves the canonical body differs.
    #[test]
    fn checksum_parity_fixture_seq_some_zero() {
        let frame: WALFrame<u64> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: Some(0),
                lifecycle: Lifecycle::Data,
                change: 0,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let expected_sha = "da42bdfa3eff9dbb7ffc60b04c7478cbe7cbb7015ba48963b4ea4661f678c387";
        assert_eq!(wal_frame_checksum(&frame).unwrap(), expected_sha);
    }

    /// /qa A7 (2026-05-10): `WalTag` deserialization rejects non-string JSON
    /// tokens (null, number, array, object) with a clear error — not just
    /// other string values.
    #[test]
    fn wal_tag_rejects_non_string_tokens() {
        for bad in ["null", "42", "[]", "{}", "true"] {
            let r: Result<WalTag, _> = serde_json::from_str(bad);
            assert!(r.is_err(), "WalTag must reject {bad}");
        }
    }

    /// /qa A13 (2026-05-10): sanity-check the `WALFrame<T>` shape for two
    /// non-trivial payload types — unit `()` and `serde_json::Value` (the
    /// "any JSON" escape hatch). Both must round-trip with stable checksums.
    #[test]
    fn wal_frame_unit_payload_round_trips() {
        let frame: WALFrame<()> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "unit".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: (),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let mut f = frame.clone();
        f.checksum = wal_frame_checksum(&frame).unwrap();
        assert!(verify_wal_frame_checksum(&f).unwrap());
    }

    #[test]
    fn wal_frame_value_payload_round_trips() {
        use serde_json::json;
        let payload = json!({"kind": "set", "key": "k1", "value": [1, 2, 3]});
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "node/state".into(),
            change: BaseChange {
                structure: "graphValue".into(),
                version: Version::Counter(1),
                t_ns: 100,
                seq: Some(7),
                lifecycle: Lifecycle::Data,
                change: payload,
            },
            frame_seq: 17,
            frame_t_ns: 200,
            checksum: String::new(),
            format_version: 1,
        };
        let mut f = frame.clone();
        f.checksum = wal_frame_checksum(&frame).unwrap();
        assert!(verify_wal_frame_checksum(&f).unwrap());
    }

    /// /qa F5 (2026-05-12): backward-compatible deserialization of
    /// pre-`format_version` frames. Old frames serialized WITHOUT the
    /// `format_version` field must deserialize successfully with
    /// `format_version` defaulting to `1`.
    #[test]
    fn format_version_defaults_on_old_frame_json() {
        // JSON from a pre-format_version frame (no `format_version` key).
        let old_json = r#"{
            "t": "c",
            "lifecycle": "data",
            "path": "p",
            "change": {
                "structure": "s",
                "version": 0,
                "t_ns": 0,
                "lifecycle": "data",
                "change": 0
            },
            "frame_seq": 0,
            "frame_t_ns": 0,
            "checksum": ""
        }"#;
        let frame: WALFrame<u64> = serde_json::from_str(old_json).unwrap();
        assert_eq!(
            frame.format_version, 1,
            "missing format_version must default to 1"
        );
    }

    /// /qa F5 (2026-05-12): new frames with explicit `format_version`
    /// round-trip correctly.
    #[test]
    fn format_version_round_trips() {
        let frame = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: 0u64,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 2,
        };
        let json = serde_json::to_string(&frame).unwrap();
        let deser: WALFrame<u64> = serde_json::from_str(&json).unwrap();
        assert_eq!(deser.format_version, 2);
    }

    /// B1 (2026-05-22, /porting-to-rs storage-honest-error batch): the WAL
    /// canonical-JSON encode guard rejects non-ASCII object keys with a
    /// `ChecksumError::NonCanonicalContent` rather than silently producing
    /// JSON that diverges from TS `stableJsonString` (UTF-16 vs UTF-8 sort
    /// order for keys with code points ≥ U+10000). The frame's user-supplied
    /// `change.structure` field carries arbitrary string content; this test
    /// uses the structure field to inject a non-ASCII key into the encoded
    /// `change` body via a nested map payload.
    #[test]
    fn canonical_json_rejects_non_ascii_object_keys() {
        use serde_json::json;
        // Carry a nested-object payload whose KEY (not value) contains a
        // non-ASCII code point. The guard rejects at frame_checksum-encode
        // time (before SHA-256), surfacing the divergence vector.
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                // Note the KEY contains "café" (non-ASCII 'é').
                change: json!({ "café": 1 }),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let err = wal_frame_checksum(&frame).expect_err("B1 guard must reject");
        let msg = err.to_string();
        assert!(
            matches!(err, ChecksumError::NonCanonicalContent { .. }),
            "expected NonCanonicalContent, got: {err:?}"
        );
        assert!(
            msg.contains("café"),
            "diagnostic must name the offending key, got: {msg}"
        );
    }

    /// B1 companion: subnormal f64 values are rejected. `serde_json::Number`
    /// rejects NaN/Inf at construction (those flow through the
    /// `CanonicalJsonFailed` variant), but subnormals (denormalized floats)
    /// slip through finite checks while still formatting divergently between
    /// JS `JSON.stringify` and Rust `serde_json` via `ryu` — so the guard
    /// also rejects them at encode time.
    #[test]
    fn canonical_json_rejects_subnormal_f64() {
        use serde_json::json;
        // f64::MIN_POSITIVE.next_down() is in the subnormal range (smaller
        // than the smallest normal positive f64). `is_normal()` returns
        // false; `is_finite()` returns true. The guard rejects.
        let subnormal: f64 = f64::MIN_POSITIVE / 2.0;
        assert!(!subnormal.is_normal());
        assert!(subnormal.is_finite());
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: json!({ "tiny": subnormal }),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let err = wal_frame_checksum(&frame).expect_err("B1 subnormal guard must reject");
        assert!(
            matches!(err, ChecksumError::NonCanonicalContent { .. }),
            "expected NonCanonicalContent, got: {err:?}"
        );
        assert!(
            err.to_string().contains("subnormal"),
            "diagnostic must mention subnormal, got: {err}"
        );
    }

    /// B1 negative control: ASCII-only keys + normal f64 + integers pass
    /// the guard unchanged (no regression on the existing happy path).
    #[test]
    fn canonical_json_guard_passes_ascii_and_normal_floats() {
        use serde_json::json;
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: json!({ "ascii_key": 42, "float": 1.5, "zero": 0.0 }),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        // Just assert it doesn't error — exact hash isn't load-bearing here.
        wal_frame_checksum(&frame).expect("ASCII keys + normal floats must pass the guard");
    }

    /// /qa G2.5 (2026-05-22): `-0.0` is rejected because
    /// `JSON.stringify(-0.0) === "0"` but Rust `serde_json` emits `-0.0` —
    /// exactly the divergence the canonical-JSON guard is meant to catch.
    /// The pre-/qa guard `f != 0.0 && !f.is_normal()` accepted `-0.0`
    /// because `-0.0 == 0.0` is true; the bit-pattern discriminator added
    /// in this /qa pass closes the gap.
    #[test]
    fn canonical_json_rejects_negative_zero() {
        use serde_json::json;
        // serde_json::Number won't deserialize -0.0 from `{ "z": -0.0 }`
        // literals, but `Number::from_f64(-0.0)` succeeds — construct via
        // the typed entry point.
        let neg_zero = -0.0_f64;
        assert_eq!(neg_zero.to_bits(), 0x8000_0000_0000_0000);
        let mut map = serde_json::Map::new();
        map.insert(
            "neg_zero".to_owned(),
            serde_json::Value::Number(serde_json::Number::from_f64(neg_zero).expect("finite")),
        );
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: serde_json::Value::Object(map),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let err = wal_frame_checksum(&frame).expect_err("B1 / G2.5 guard must reject -0.0");
        assert!(
            matches!(err, ChecksumError::NonCanonicalContent { .. }),
            "expected NonCanonicalContent, got: {err:?}"
        );
        // Positive zero stays accepted — sanity check that the bit-pattern
        // discriminator didn't over-broaden into the legitimate zero case.
        let frame_pos_zero: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: json!({ "pos_zero": 0.0 }),
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        wal_frame_checksum(&frame_pos_zero).expect("positive +0.0 must continue to pass the guard");
    }

    /// /qa G2.6 (2026-05-22): the validator's recursion is depth-capped
    /// (128) so adversarial deeply-nested user payloads can't blow the
    /// stack at WAL write time. A value tree exceeding the cap is
    /// rejected as `NonCanonicalContent` (same channel as the other
    /// divergence-class rejections) rather than crashing the process.
    #[test]
    fn canonical_json_rejects_excessive_nesting_depth() {
        // Build a deeply-nested object tree programmatically (can't be
        // parsed from JSON literals at this depth without serde's own
        // recursion guard tripping first — exactly the point of the cap).
        let mut deep = serde_json::Value::Number(serde_json::Number::from(0_u64));
        for _ in 0..200 {
            let mut map = serde_json::Map::new();
            map.insert("n".to_owned(), deep);
            deep = serde_json::Value::Object(map);
        }
        let frame: WALFrame<serde_json::Value> = WALFrame {
            t: WalTag,
            lifecycle: Lifecycle::Data,
            path: "p".into(),
            change: BaseChange {
                structure: "s".into(),
                version: Version::Counter(0),
                t_ns: 0,
                seq: None,
                lifecycle: Lifecycle::Data,
                change: deep,
            },
            frame_seq: 0,
            frame_t_ns: 0,
            checksum: String::new(),
            format_version: 1,
        };
        let err = wal_frame_checksum(&frame).expect_err("G2.6 depth cap must reject");
        assert!(
            matches!(err, ChecksumError::NonCanonicalContent { .. }),
            "expected NonCanonicalContent, got: {err:?}"
        );
        assert!(
            err.to_string().contains("depth"),
            "diagnostic must mention depth, got: {err}"
        );
    }

    /// /qa A10 (2026-05-10): canary detecting `serde_json/preserve_order`
    /// feature unification. The canonical-JSON parity invariant requires
    /// `serde_json::Map<String, Value>` to be `BTreeMap`-backed (sorted on
    /// iter). If any workspace consumer enables `preserve_order` via Cargo
    /// feature unification, `Map` swaps to `IndexMap` (insertion-order) and
    /// this test fails loudly with a diff.
    #[test]
    fn preserve_order_feature_is_not_enabled() {
        // Build a Value::Object with INSERTION ORDER = reverse-alphabetical.
        // BTreeMap-backed Map iterates in alphabetical order on `to_string`.
        // IndexMap-backed Map preserves insertion order.
        let mut map = serde_json::Map::new();
        map.insert("z".into(), serde_json::json!(1));
        map.insert("a".into(), serde_json::json!(2));
        let serialized = serde_json::to_string(&serde_json::Value::Object(map)).unwrap();
        assert_eq!(
            serialized, r#"{"a":2,"z":1}"#,
            "serde_json `preserve_order` feature appears to be enabled \
             workspace-wide via Cargo feature unification — this BREAKS the \
             WAL checksum canonical-JSON parity invariant. Find the offending \
             dep with `cargo tree -e features | grep preserve_order` and \
             either disable it or pin to a non-preserve-order codec route.",
        );
    }
}