hakodb 0.20.8

Embedded & Cloud-native Document Engine
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
use crate::document::value::Value;
use crate::util::varint::*;
use std::sync::Arc;
use std::cell::RefCell;

const MAGIC: u8 = 0xF1;
const VERSION: u8 = 5; 

thread_local! {
    static ENCODE_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128 * 1024));
    // ponytail: Fx over std RandomState — interning hashes every field key
    // of every decoded doc on the hot path; SipHash was the single biggest
    // per-field cost (bench-lab get/decode split). fxhash is already a dep.
    static FIELD_NAMES: RefCell<fxhash::FxHashMap<String, Arc<str>>> = RefCell::new(fxhash::FxHashMap::default());
}

/// ponytail: field names repeat across every document ("tenant", "score",
/// ...) but `Arc::from` allocated per field per decode. Intern them in a
/// thread-local pool: hits are a hash + refcount bump, zero alloc. Capped so
/// pathological schemas (unbounded distinct keys) degrade to plain Arc
/// instead of growing a leak vector.
pub(crate) fn intern_field(key: &str) -> Arc<str> {
    FIELD_NAMES.with(|pool| {
        let mut p = pool.borrow_mut();
        if let Some(a) = p.get(key) {
            return a.clone();
        }
        if p.len() < 4096 {
            let a: Arc<str> = Arc::from(key);
            p.insert(key.to_string(), a.clone());
            a
        } else {
            Arc::from(key)
        }
    })
}

#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct HakoDoc {
    pub fields: Vec<(Arc<str>, Value)>,
    pub _time: i64,
}

/// One map entry as `(key, value tag, encoded value span)`.
type MapEntry<'a> = (&'a [u8], u8, &'a [u8]);

impl HakoDoc {
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.fields.binary_search_by(|(k, _)| k.as_ref().cmp(key))
            .ok()
            .map(|pos| &self.fields[pos].1)
    }

    /// Dotted-path fetch hook (hakodb#71 F2): `profile.address.city`
    /// descends through Map values only. Single-segment paths behave
    /// exactly like [`Self::get`]. None on any miss, on empty segments,
    /// or on descent into a non-Map value (arrays are F3 territory —
    /// fail-closed absent for now). Borrowed: zero decode, the doc is
    /// already materialized.
    pub fn get_path(&self, path: &str) -> Option<&Value> {
        let mut segs = path.split('.');
        let first = segs.next()?;
        if first.is_empty() {
            return None;
        }
        let mut cur = self.get(first)?;
        for seg in segs {
            if seg.is_empty() {
                return None;
            }
            match cur {
                Value::Map(m) => {
                    cur = &m.iter().find(|(k, _)| k.as_ref() == seg)?.1;
                }
                _ => return None,
            }
        }
        Some(cur)
    }

    pub fn insert(&mut self, key: impl Into<String>, value: Value) {
        let key_str = key.into();
        match self.fields.binary_search_by(|(k, _)| k.as_ref().cmp(&key_str)) {
            Ok(pos) => self.fields[pos].1 = value,
            Err(pos) => self.fields.insert(pos, (Arc::from(key_str), value)),
        }
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(512);
        self.encode_into(&mut out);
        out
    }

    pub fn encode_buffered(&self) -> Vec<u8> {
        ENCODE_BUF.with(|buf| {
            let mut b = buf.borrow_mut();
            b.clear();
            self.encode_into(&mut b);
            b.to_vec() 
        })
    }

    pub fn encode_into(&self, out: &mut Vec<u8>) {
        out.push(MAGIC);
        out.push(VERSION);
        out.extend_from_slice(&self._time.to_le_bytes()); 
        out.extend_from_slice(&(self.fields.len() as u16).to_le_bytes()); 
        
        for (key, value) in &self.fields {
            out.push(key.len() as u8);
            out.extend_from_slice(key.as_bytes());
            Self::encode_value_to(value, out);
        }
    }

    pub fn decode(bytes: &[u8]) -> Option<Self> {
        let view = HakoDocView::new(bytes)?;
        // ponytail: size the vec from the header count — the old push-grown
        // vec always paid one backing alloc (+ regrow for wide docs) per
        // decode. The count is right there in the view.
        let mut doc = HakoDoc {
            _time: view._time,
            fields: Vec::with_capacity(view.fields_count as usize),
        };
        let mut it = view.iter();
        for (key, tag, data) in it.by_ref() {
            doc.fields.push((intern_field(key), decode_value(tag, data)?));
        }
        // ponytail: strict framing — a buffer that ends mid-document or
        // carries trailing garbage decodes to None, never to a silently
        // short doc. All producers (WAL, segments, snapshots) store exact
        // slices, so well-formed data always consumes exactly.
        if it.remaining() != 0 || it.position() != bytes.len() {
            return None;
        }
        Some(doc)
    }

    pub fn decode_projected(bytes: &[u8], projection: &[String]) -> Option<Self> {
        let view = HakoDocView::new(bytes)?;
        let mut doc = HakoDoc {
            _time: view._time,
            fields: Vec::with_capacity(view.fields_count as usize),
        };
        let mut it = view.iter();
        let prefixes = crate::document::value::projection_prefixes(projection);
        for (key, tag, data) in it.by_ref() {
            // hakodb#71 F6: a dotted projection only needs its top-level
            // prefix decoded; the subtree is pruned in memory afterwards.
            let wanted = projection.is_empty() || prefixes.contains(&key);
            if wanted {
                let val = decode_value(tag, data)?;
                if projection.is_empty() {
                    doc.fields.push((intern_field(key), val));
                } else if let Some(pruned) =
                    crate::document::value::prune_field_value(&val, projection, key)
                {
                    doc.fields.push((intern_field(key), pruned));
                }
            }
        }
        if it.remaining() != 0 || it.position() != bytes.len() {
            return None;
        }
        Some(doc)
    }

    /// hakodb#71 F6: prune an already-decoded doc to a projection (dotted
    /// paths supported). Empty projection = full doc. Used by the pipeline
    /// `project` stage so it matches the query projection semantics.
    pub fn project_fields(&self, projection: &[String]) -> Vec<(Arc<str>, Value)> {
        if projection.is_empty() {
            return self.fields.clone();
        }
        let mut out = Vec::with_capacity(self.fields.len());
        for (k, v) in &self.fields {
            if let Some(pruned) = crate::document::value::prune_field_value(v, projection, k) {
                out.push((k.clone(), pruned));
            }
        }
        out
    }

    pub fn get_logical_time(&self) -> i64 { self._time }

    pub fn to_json(&self) -> serde_json::Value {
        let mut map = serde_json::Map::new();
        map.insert("_time".to_string(), serde_json::json!(self._time));
        for (k, v) in &self.fields {
            map.insert(k.to_string(), v.to_json());
        }
        serde_json::Value::Object(map)
    }

    /// Single-pass JSON serialization: the same bytes `to_json()` +
    /// `serde_json::to_vec` produce, without the intermediate Map, key
    /// Strings, and Value tree. One buffer append per piece; keys borrow
    /// the interned Arcs. Read-path only — storage stays binary.
    ///
    /// Byte-equality contract (pinned by tests): `serde_json::Map` is a
    /// BTreeMap, so `_time` merges at its sorted position among the
    /// (already sorted) fields; floats render through serde_json's own
    /// Number (exponent `e+`, non-finite as null); strings escape identically.
    pub fn write_json(&self, out: &mut Vec<u8>) {
        out.push(b'{');
        let mut first = true;
        let mut time_written = false;
        // BTreeMap<String> order is plain byte order; fields arrive sorted.
        for (k, v) in &self.fields {
            if !time_written && k.as_ref() > "_time" {
                Self::write_time(out, &mut first, self._time);
                time_written = true;
            }
            if !time_written && k.as_ref() == "_time" {
                // A literal "_time" field overwrites the timestamp in the
                // map (insert order loses); the ts is dropped, not doubled.
                time_written = true;
            }
            if !first {
                out.push(b',');
            }
            first = false;
            Self::write_json_str(out, k);
            out.push(b':');
            Self::write_json_value(out, v);
        }
        if !time_written {
            Self::write_time(out, &mut first, self._time);
        }
        out.push(b'}');
    }

    fn write_time(out: &mut Vec<u8>, first: &mut bool, ts: i64) {
        if !*first {
            out.push(b',');
        }
        *first = false;
        out.extend_from_slice(b"\"_time\":");
        Self::push_int(out, ts);
    }

    /// Owned convenience for response paths.
    pub fn to_json_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(128);
        self.write_json(&mut out);
        out
    }

/// JSON string escaping, byte-identical to serde_json: `"`, `\` and
/// U+0000–U+001F escape (`\b \f \n \r \t` short, rest `\u00XX` lowercase);
/// all other bytes (including multi-byte UTF-8, never split: only ASCII
/// is special-cased) pass through raw.
fn write_json_str(out: &mut Vec<u8>, s: &str) {
    out.push(b'"');
    Self::write_json_raw(out, s);
    out.push(b'"');
}

/// Escaping core without quotes (lets Reference write `col/id` under one
/// open quote — byte-identical to escaping the joined string).
///
/// Runs of clean bytes are copied in bulk (`extend_from_slice`), one append
/// per escape instead of one per byte. Same shape as serde_json's
/// `format_escaped_str_contents`, which is why the old 512 B crossover arm
/// (whole-doc serde DOM fallback) is gone: this loop is fast at every size.
fn write_json_raw(out: &mut Vec<u8>, s: &str) {
    /// Escape byte to emit after `\`; `0` = clean, `u` = `\u00XX`.
    const ESCAPE: [u8; 256] = {
        let mut t = [0u8; 256];
        let mut i = 0usize;
        while i < 0x20 {
            t[i] = b'u';
            i += 1;
        }
        t[0x08] = b'b';
        t[0x09] = b't';
        t[0x0A] = b'n';
        t[0x0C] = b'f';
        t[0x0D] = b'r';
        t[b'"' as usize] = b'"';
        t[b'\\' as usize] = b'\\';
        t
    };
    let bytes = s.as_bytes();
    let mut start = 0usize;
    let mut i = 0usize;
    while i < bytes.len() {
        // Clean runs are the norm: skip 8 bytes at a time (SWAR) before
        // paying for the per-byte table lookup.
        if i + 8 <= bytes.len() {
            let mut w = [0u8; 8];
            w.copy_from_slice(&bytes[i..i + 8]);
            if !Self::needs_escape(u64::from_le_bytes(w)) {
                i += 8;
                continue;
            }
        }
        let b = bytes[i];
        let esc = ESCAPE[b as usize];
        if esc == 0 {
            i += 1;
            continue;
        }
        if start < i {
            out.extend_from_slice(&bytes[start..i]);
        }
        i += 1;
        start = i;
        out.push(b'\\');
        if esc == b'u' {
            out.extend_from_slice(b"u00");
            out.push(b"0123456789abcdef"[(b >> 4) as usize]);
            out.push(b"0123456789abcdef"[(b & 0xF) as usize]);
        } else {
            out.push(esc);
        }
    }
    if start < bytes.len() {
        out.extend_from_slice(&bytes[start..]);
    }
}

/// True iff any byte of `w` needs JSON escaping: `< 0x20`, `"` or `\`.
/// SWAR (Hacker's Delight hasless/haszero): boolean-exact, may set extra
/// lanes on borrow but never misses — callers only use it to skip 8 clean
/// bytes, then fall back to the exact table lookup.
#[inline]
fn needs_escape(w: u64) -> bool {
    const ONES: u64 = 0x0101_0101_0101_0101;
    const HIGH: u64 = 0x8080_8080_8080_8080;
    let lt_0x20 = w.wrapping_sub(ONES.wrapping_mul(0x20)) & !w & HIGH;
    let q = w ^ ONES.wrapping_mul(0x22);
    let s = w ^ ONES.wrapping_mul(0x5C);
    let eq = ((q.wrapping_sub(ONES)) & !q & HIGH) | ((s.wrapping_sub(ONES)) & !s & HIGH);
    (lt_0x20 | eq) != 0
}

fn push_int(out: &mut Vec<u8>, n: i64) {
    out.extend_from_slice(itoa::Buffer::new().format(n).as_bytes());
}

/// Single-pass Value writer: mirrors `Value::to_json` arm for arm
/// (including nested-map key sorting and BlobLink/Reference shapes).
fn write_json_value(out: &mut Vec<u8>, v: &Value) {
    use crate::document::value::Value::*;
    match v {
        Null | ServerTimestamp => out.extend_from_slice(b"null"),
        Bool(true) => out.extend_from_slice(b"true"),
        Bool(false) => out.extend_from_slice(b"false"),
        Int(n) => Self::push_int(out, *n),
        Float(f) => {
            // Delegate to serde_json's own float rendering (ryu-finite with
            // exponent post-processing like `1e+100`, non-finite as null).
            // One small alloc per float, floats are rare; byte-equality by
            // construction instead of by careful imitation.
            match serde_json::Number::from_f64(*f) {
                Some(n) => out.extend_from_slice(n.to_string().as_bytes()),
                None => out.extend_from_slice(b"null"),
            }
        }
        String(s) => Self::write_json_str(out, s),
        Binary(bytes) => {
            out.push(b'[');
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                out.extend_from_slice(itoa::Buffer::new().format(*b).as_bytes());
            }
            out.push(b']');
        }
        Timestamp(micros) => Self::push_int(out, *micros),
        Reference { collection, doc_id } => {
            // Escaping is char-local and '/' never escapes: writing the
            // parts under one open quote equals escaping "col/id" whole
            // (what to_json formats first), with zero alloc.
            out.extend_from_slice(b"{\"__ref__\":\"");
            Self::write_json_raw(out, collection);
            out.push(b'/');
            Self::write_json_raw(out, doc_id);
            out.extend_from_slice(b"\"}");
        }
        BlobLink { offset, len } => {
            // Shape mirrors to_json exactly: {"__blob__":{"len":N,"offset":N}}
            // (BTreeMap order at both levels: "__blob__" sole key; "len" < "offset").
            out.extend_from_slice(b"{\"__blob__\":{\"len\":");
            out.extend_from_slice(itoa::Buffer::new().format(*len).as_bytes());
            out.extend_from_slice(b",\"offset\":");
            out.extend_from_slice(itoa::Buffer::new().format(*offset).as_bytes());
            out.extend_from_slice(b"}}");
        }
        Map(fields) => Self::write_json_map(out, fields),
        Array(values) => {
            out.push(b'[');
            for (i, v) in values.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                Self::write_json_value(out, v);
            }
            out.push(b']');
        }
    }
}

    /// Write a map in BTreeMap key order. Most maps are small, so sorting
    /// borrowed refs in a stack array avoids a Vec per nested map.
    fn write_json_map(out: &mut Vec<u8>, fields: &[(Arc<str>, Value)]) {
        const STACK: usize = 32;
        if fields.len() <= STACK {
            let mut items: [Option<(&str, &Value)>; STACK] = [None; STACK];
            for (slot, (k, v)) in items.iter_mut().zip(fields) {
                *slot = Some((k.as_ref(), v));
            }
            let items = &mut items[..fields.len()];
            items.sort_unstable_by(|a, b| a.unwrap().0.cmp(b.unwrap().0));
            Self::write_json_map_items(out, items.iter().map(|i| i.unwrap()));
        } else {
            let mut items: Vec<(&str, &Value)> =
                fields.iter().map(|(k, v)| (k.as_ref(), v)).collect();
            items.sort_unstable_by(|a, b| a.0.cmp(b.0));
            Self::write_json_map_items(out, items);
        }
    }

    fn write_json_map_items<'a, I>(out: &mut Vec<u8>, items: I)
    where
        I: IntoIterator<Item = (&'a str, &'a Value)>,
    {
        out.push(b'{');
        let mut first = true;
        for (k, v) in items {
            if !first {
                out.push(b',');
            }
            first = false;
            Self::write_json_str(out, k);
            out.push(b':');
            Self::write_json_value(out, v);
        }
        out.push(b'}');
    }

    /// Raw-span JSON writer: same output as [`Self::write_json_value`], but
    /// reads the encoded span directly (no `Value` tree, no String allocs).
    /// `None` means the span is not valid framing; callers treat it as a
    /// missing/corrupt document, matching `HakoDoc::decode`.
    fn write_view_value(out: &mut Vec<u8>, v: &BorrowedValue<'_>) -> Option<()> {
        let tag = v.tag;
        let data = v.data;
        if tag == 0xC0 || tag == 0xC1 {
            out.extend_from_slice(b"null");
            return Some(());
        }
        if tag == 0xC2 {
            out.extend_from_slice(b"true");
            return Some(());
        }
        if tag == 0xC3 {
            out.extend_from_slice(b"false");
            return Some(());
        }
        if (tag & 0xF0) == 0x10 {
            Self::push_int(out, (tag & 0x0F) as i64);
            return Some(());
        }
        if (tag & 0xF8) == 0x40 {
            let len = (tag & 0x07) as usize;
            let s = std::str::from_utf8(data.get(..len)?).ok()?;
            Self::write_json_str(out, s);
            return Some(());
        }
        match tag {
            3 | 7 => {
                let mut p = 4;
                let val = decode_varint(data, &mut p)?;
                Self::push_int(out, zigzag_decode(val));
            }
            4 => {
                let f = f64::from_le_bytes(data.get(4..12)?.try_into().ok()?);
                match serde_json::Number::from_f64(f) {
                    Some(n) => out.extend_from_slice(n.to_string().as_bytes()),
                    None => out.extend_from_slice(b"null"),
                }
            }
            5 => {
                let len = u32::from_le_bytes(data.get(..4)?.try_into().ok()?) as usize;
                let s = std::str::from_utf8(data.get(4..4 + len)?).ok()?;
                Self::write_json_str(out, s);
            }
            6 => {
                let len = u32::from_le_bytes(data.get(..4)?.try_into().ok()?) as usize;
                let bytes = data.get(4..4 + len)?;
                out.push(b'[');
                for (i, b) in bytes.iter().enumerate() {
                    if i > 0 {
                        out.push(b',');
                    }
                    Self::push_int(out, *b as i64);
                }
                out.push(b']');
            }
            8 => Self::write_view_map(out, data)?,
            9 => {
                let count = u32::from_le_bytes(data.get(4..8)?.try_into().ok()?) as usize;
                let mut p = 8usize;
                out.push(b'[');
                for i in 0..count {
                    let t = *data.get(p)?;
                    p += 1;
                    let start = p;
                    skip_value(t, data, &mut p)?;
                    if i > 0 {
                        out.push(b',');
                    }
                    Self::write_view_value(out, &BorrowedValue { tag: t, data: &data[start..p] })?;
                }
                if p != data.len() {
                    return None;
                }
                out.push(b']');
            }
            10 => {
                let c_len = *data.get(4)? as usize;
                let c = std::str::from_utf8(data.get(5..5 + c_len)?).ok()?;
                let d_len = *data.get(5 + c_len)? as usize;
                let d = std::str::from_utf8(data.get(6 + c_len..6 + c_len + d_len)?).ok()?;
                out.extend_from_slice(b"{\"__ref__\":\"");
                Self::write_json_raw(out, c);
                out.push(b'/');
                Self::write_json_raw(out, d);
                out.extend_from_slice(b"\"}");
            }
            11 => {
                let offset = u64::from_le_bytes(data.get(4..12)?.try_into().ok()?);
                let len = u32::from_le_bytes(data.get(12..16)?.try_into().ok()?);
                out.extend_from_slice(b"{\"__blob__\":{\"len\":");
                out.extend_from_slice(itoa::Buffer::new().format(len).as_bytes());
                out.extend_from_slice(b",\"offset\":");
                out.extend_from_slice(itoa::Buffer::new().format(offset).as_bytes());
                out.extend_from_slice(b"}}");
            }
            _ => out.extend_from_slice(b"null"),
        }
        Some(())
    }

    fn write_view_map(out: &mut Vec<u8>, data: &[u8]) -> Option<()> {
        const STACK: usize = 32;
        let count = u16::from_le_bytes(data.get(4..6)?.try_into().ok()?) as usize;
        let mut p = 6usize;
        if count <= STACK {
            let mut items: [Option<MapEntry>; STACK] = [None; STACK];
            for slot in items.iter_mut().take(count) {
                let k_len = *data.get(p)? as usize;
                p += 1;
                let key = data.get(p..p + k_len)?;
                p += k_len;
                let tag = *data.get(p)?;
                p += 1;
                let start = p;
                skip_value(tag, data, &mut p)?;
                *slot = Some((key, tag, &data[start..p]));
            }
            if p != data.len() {
                return None;
            }
            let items = &mut items[..count];
            items.sort_unstable_by(|a, b| a.unwrap().0.cmp(b.unwrap().0));
            Self::write_view_map_items(out, items.iter().map(|i| i.unwrap()))
        } else {
            let mut items: Vec<MapEntry> = Vec::with_capacity(count);
            for _ in 0..count {
                let k_len = *data.get(p)? as usize;
                p += 1;
                let key = data.get(p..p + k_len)?;
                p += k_len;
                let tag = *data.get(p)?;
                p += 1;
                let start = p;
                skip_value(tag, data, &mut p)?;
                items.push((key, tag, &data[start..p]));
            }
            if p != data.len() {
                return None;
            }
            items.sort_unstable_by(|a, b| a.0.cmp(b.0));
            Self::write_view_map_items(out, items)
        }
    }

    fn write_view_map_items<'a, I>(out: &mut Vec<u8>, items: I) -> Option<()>
    where
        I: IntoIterator<Item = MapEntry<'a>>,
    {
        out.push(b'{');
        let mut first = true;
        for (key, tag, span) in items {
            if !first {
                out.push(b',');
            }
            first = false;
            let k = std::str::from_utf8(key).ok()?;
            Self::write_json_str(out, k);
            out.push(b':');
            Self::write_view_value(out, &BorrowedValue { tag, data: span })?;
        }
        out.push(b'}');
        Some(())
    }

    pub fn to_json_with_id(&self, id: &str) -> serde_json::Value {
        let mut json = self.to_json();
        if let Some(obj) = json.as_object_mut() {
            obj.insert("id".to_string(), serde_json::Value::String(id.to_string()));
        }
        json
    }

    pub(crate) fn encode_value_to(v: &Value, out: &mut Vec<u8>) {
        match v {
            // --- SUPER TAGS (1 Byte Total) ---
            Value::Null => out.push(0xC0),
            Value::ServerTimestamp => out.push(0xC1),
            Value::Bool(true) => out.push(0xC2),
            Value::Bool(false) => out.push(0xC3),
            
            Value::Int(v) if *v >= 0 && *v <= 15 => {
                out.push(0x10 | (*v as u8));
            }

            Value::String(s) if s.len() <= 7 => {
                out.push(0x40 | (s.len() as u8));
                out.extend_from_slice(s.as_bytes());
            }

            // --- STANDARD TAGS ---
            Value::Int(v) => {
                out.push(3);
                let start = out.len();
                out.extend_from_slice(&[0u8; 4]); 
                encode_varint(zigzag_encode(*v), out);
                let len = (out.len() - start - 4) as u32;
                out[start..start+4].copy_from_slice(&len.to_le_bytes());
            }
            Value::Float(v) => {
                out.push(4);
                out.extend_from_slice(&8u32.to_le_bytes());
                out.extend_from_slice(&v.to_le_bytes());
            }
            Value::String(v) => {
                out.push(5);
                out.extend_from_slice(&(v.len() as u32).to_le_bytes());
                out.extend_from_slice(v.as_bytes());
            }
            Value::Binary(v) => {
                out.push(6);
                out.extend_from_slice(&(v.len() as u32).to_le_bytes());
                out.extend_from_slice(v);
            }
            Value::Timestamp(v) => {
                out.push(7);
                let start = out.len();
                out.extend_from_slice(&[0u8; 4]); 
                encode_varint(zigzag_encode(*v), out);
                let len = (out.len() - start - 4) as u32;
                out[start..start+4].copy_from_slice(&len.to_le_bytes());
            }
            Value::Map(fields) => {
                out.push(8);
                let start = out.len();
                out.extend_from_slice(&[0u8; 4]); 
                let body_start = out.len();
                out.extend_from_slice(&(fields.len() as u16).to_le_bytes());
                for (k, v) in fields {
                    out.push(k.len() as u8);
                    out.extend_from_slice(k.as_bytes());
                    Self::encode_value_to(v, out);
                }
                let len = (out.len() - body_start) as u32;
                out[start..start+4].copy_from_slice(&len.to_le_bytes());
            }
            Value::Array(items) => {
                out.push(9);
                let start = out.len();
                out.extend_from_slice(&[0u8; 4]);
                let body_start = out.len();
                out.extend_from_slice(&(items.len() as u32).to_le_bytes());
                for item in items { Self::encode_value_to(item, out); }
                let len = (out.len() - body_start) as u32;
                out[start..start+4].copy_from_slice(&len.to_le_bytes());
            }
            Value::Reference { collection, doc_id } => {
                out.push(10);
                let start = out.len();
                out.extend_from_slice(&[0u8; 4]);
                let body_start = out.len();
                out.push(collection.len() as u8);
                out.extend_from_slice(collection.as_bytes());
                out.push(doc_id.len() as u8);
                out.extend_from_slice(doc_id.as_bytes());
                let len = (out.len() - body_start) as u32;
                out[start..start+4].copy_from_slice(&len.to_le_bytes());
            }
            Value::BlobLink { offset, len } => {
                out.push(11);
                out.extend_from_slice(&12u32.to_le_bytes());
                out.extend_from_slice(&offset.to_le_bytes());
                out.extend_from_slice(&len.to_le_bytes());
            }
        }
    }
}

pub struct HakoDocView<'a> {
    bytes: &'a [u8],
    fields_count: u16,
    pub _time: i64,
}

impl<'a> HakoDocView<'a> {
    pub fn new(bytes: &'a [u8]) -> Option<Self> {
        if bytes.len() < 12 || bytes[0] != MAGIC || bytes[1] != VERSION { return None; }
        let _time = i64::from_le_bytes(bytes[2..10].try_into().ok()?);
        let fields_count = u16::from_le_bytes(bytes[10..12].try_into().ok()?);
        Some(Self { bytes, fields_count, _time })
    }
    pub fn iter(&self) -> HakoDocIter<'a> {
        HakoDocIter { bytes: self.bytes, pos: 12, remaining: self.fields_count }
    }
    /// Raw framing walk: yields key BYTES without UTF-8 validation, plus
    /// tag and value slice. For filter matching only — byte-compare keys,
    /// never materialize. Skipped (non-matching) fields cost pointer bumps
    /// alone; validation happens exactly once, on the owned-decode path
    /// that accepted rows take anyway (so corrupt keys still reject: the
    /// body scan below fails them, same outcome as validating here).
    pub fn iter_raw(&self) -> HakoDocRawIter<'a> {
        HakoDocRawIter { bytes: self.bytes, pos: 12, remaining: self.fields_count }
    }
    /// Field count from the header, without walking the framing.
    pub(crate) fn field_count(&self) -> usize {
        self.fields_count as usize
    }

    /// Dotted-path fetch hook, borrowed cursor flavor (hakodb#71 F2).
    /// Same contract as [`DocView::get_path`]: Map-only descent, None on
    /// any miss / empty segment / non-Map mid-path, no decode of skipped
    /// subtrees, terminal decodes once.
    pub fn get_path(&self, path: &str) -> Option<Value> {
        let mut segs = path.split('.');
        let first = segs.next()?;
        if first.is_empty() {
            return None;
        }
        let bytes: &[u8] = self.bytes;
        let mut pos = 12usize;
        let mut cur: Option<(u8, &[u8])> = None;
        for _ in 0..self.fields_count {
            let k_len = *bytes.get(pos)? as usize;
            pos += 1;
            let key = std::str::from_utf8(bytes.get(pos..pos + k_len)?).ok()?;
            pos += k_len;
            let tag = *bytes.get(pos)?;
            pos += 1;
            let start = pos;
            skip_value(tag, bytes, &mut pos)?;
            if key == first {
                cur = Some((tag, &bytes[start..pos]));
                break;
            }
        }
        let (mut tag, mut span) = cur?;
        for seg in segs {
            if seg.is_empty() || tag != 8 {
                return None;
            }
            let count = u16::from_le_bytes(span.get(4..6)?.try_into().ok()?) as usize;
            let mut p = 6usize;
            let mut hit = None;
            for _ in 0..count {
                let k_len = *span.get(p)? as usize;
                p += 1;
                let key = span.get(p..p + k_len)?;
                p += k_len;
                let t = *span.get(p)?;
                p += 1;
                let s = p;
                let mut q = s;
                skip_value(t, span, &mut q)?;
                std::str::from_utf8(key).ok()?;
                if key == seg.as_bytes() {
                    hit = Some((t, &span[s..q]));
                    break;
                }
                p = q;
            }
            (tag, span) = hit?;
        }
        decode_value(tag, span)
    }
}

pub struct BorrowedValue<'a> {
    pub tag: u8,
    pub data: &'a [u8],
}
impl<'a> BorrowedValue<'a> {
    pub fn to_owned_value(&self) -> Option<Value> { decode_value(self.tag, self.data) }
    /// Borrowed UTF-8 for String values (inline or tag 5), no decode.
    pub fn as_str(&self) -> Option<&'a str> {
        if (self.tag & 0xF8) == 0x40 {
            return std::str::from_utf8(self.data.get(..(self.tag & 0x07) as usize)?).ok();
        }
        if self.tag == 5 {
            let len = u32::from_le_bytes(self.data.get(..4)?.try_into().ok()?) as usize;
            return std::str::from_utf8(self.data.get(4..4usize.checked_add(len)?)?).ok();
        }
        None
    }
    /// Borrowed bytes for Binary values (tag 6), no decode.
    pub fn as_bytes(&self) -> Option<&'a [u8]> {
        if self.tag != 6 {
            return None;
        }
        let len = u32::from_le_bytes(self.data.get(..4)?.try_into().ok()?) as usize;
        self.data.get(4..4usize.checked_add(len)?)
    }
    pub fn as_f64(&self) -> Option<f64> {
        if (self.tag & 0xF0) == 0x10 { return Some((self.tag & 0x0F) as f64); }
        match self.tag {
            3 => { 
                let mut p = 4; // Skip length header
                let v = decode_varint(self.data, &mut p)?;
                Some(zigzag_decode(v) as f64)
            }
            4 => Some(f64::from_le_bytes(self.data.get(4..12)?.try_into().ok()?)),
            _ => None,
        }
    }
}

pub struct HakoDocIter<'a> {
    bytes: &'a [u8],
    pos: usize,
    remaining: u16,
}

/// Owned handle to a borrowed document (v0.8.10+): pins the storage bytes
/// with an Arc and parses field values LAZILY on access. The sqlite3_stmt
/// analog — a cursor position plus pull-on-touch reads, with none of the
/// owned-decode cost (no fields Vec, no interning, no value allocs until
/// a field is actually pulled).
///
/// Get one via `Hako::get_view` (point read) or `Hako::walk_view`
/// (scan). `get` walks the framing with `skip_value` (no decode of
/// skipped fields); `to_owned_doc` fully decodes when you want it all.
#[derive(Clone)]
pub struct DocView {
    bytes: Arc<Vec<u8>>,
    time: i64,
    fields_count: u16,
}

impl DocView {
    /// Pin already-resident bytes. Validates the framing header (magic,
    /// version, length floor) — full field walks happen per access, all
    /// bounds-checked, with strict decode ruling in `to_owned_doc`.
    /// (A full up-front validation pass cost a second framing walk per
    /// row, ~2x on scans, for corrupt data storage never holds.)
    pub fn new(bytes: Arc<Vec<u8>>) -> Option<Self> {
        let view = HakoDocView::new(&bytes)?;
        Some(Self { time: view._time, fields_count: view.fields_count, bytes })
    }

    /// Number of top-level fields.
    pub fn len(&self) -> usize {
        self.fields_count as usize
    }

    pub fn is_empty(&self) -> bool {
        self.fields_count == 0
    }

    /// Logical timestamp carried by the encoding.
    pub fn time(&self) -> i64 {
        self.time
    }

    /// Raw storage bytes (opaque encoding — hash/count/export freely).
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Pull one field by name: linear framing walk, decode on hit only.
    /// Skipped fields cost a `skip_value` pointer bump each, never a decode.
    pub fn get(&self, field: &str) -> Option<Value> {
        let mut pos = 12usize;
        let bytes: &[u8] = &self.bytes;
        for _ in 0..self.fields_count {
            let k_len = *bytes.get(pos)? as usize;
            pos += 1;
            let key = std::str::from_utf8(bytes.get(pos..pos + k_len)?).ok()?;
            pos += k_len;
            let tag = *bytes.get(pos)?;
            pos += 1;
            let start = pos;
            skip_value(tag, bytes, &mut pos)?;
            if key == field {
                return decode_value(tag, &bytes[start..pos]);
            }
        }
        None
    }

    /// Pull a nested value by dotted path (`profile.sub_03`): descends
    /// through Map values only, decoding nothing but the terminal —
    /// siblings, ancestors, and skipped subtrees cost framing skips.
    /// Single-segment paths behave exactly like [`Self::get`]. Returns
    /// None on any miss, on descent into a non-Map value, on empty
    /// segments, or on corrupt framing.
    pub fn get_path(&self, path: &str) -> Option<Value> {
        self.get_path_span(path)?.to_owned_value()
    }

    /// Borrowed String for `key` (literal top-level field, no dotted path).
    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.iter()
            .find(|(k, _)| *k == key)
            .and_then(|(_, v)| v.as_str())
    }

    /// Borrowed bytes for `key` (literal top-level Binary field).
    pub fn get_bytes(&self, key: &str) -> Option<&[u8]> {
        self.iter()
            .find(|(k, _)| *k == key)
            .and_then(|(_, v)| v.as_bytes())
    }

    /// Borrowed String at a dotted path (`a.b.c`), no terminal decode.
    pub fn get_path_str(&self, path: &str) -> Option<&str> {
        self.get_path_span(path)?.as_str()
    }

    /// Borrowed Binary at a dotted path, no terminal decode.
    pub fn get_path_bytes(&self, path: &str) -> Option<&[u8]> {
        self.get_path_span(path)?.as_bytes()
    }

    /// Raw terminal span for a dotted path; `get_path` decodes it, the
    /// borrowed getters read it in place.
    fn get_path_span(&self, path: &str) -> Option<BorrowedValue<'_>> {
        let mut segs = path.split('.');
        let first = segs.next()?;
        if first.is_empty() {
            return None;
        }
        // Top level uses the same walk as `get`, but keeps the raw value
        // span so descent avoids a decode-then-re-encode round trip.
        let bytes: &[u8] = &self.bytes;
        let mut pos = 12usize;
        let mut cur: Option<(u8, &[u8])> = None;
        for _ in 0..self.fields_count {
            let k_len = *bytes.get(pos)? as usize;
            pos += 1;
            let key = std::str::from_utf8(bytes.get(pos..pos + k_len)?).ok()?;
            pos += k_len;
            let tag = *bytes.get(pos)?;
            pos += 1;
            let start = pos;
            skip_value(tag, bytes, &mut pos)?;
            if key == first {
                cur = Some((tag, &bytes[start..pos]));
                break;
            }
        }
        let (mut tag, mut span) = cur?;
        // One Map level per remaining segment; the terminal decodes once.
        // Key validation mirrors `get`: every key the traversal touches
        // must be valid UTF-8, corrupt keys reject.
        for seg in segs {
            if seg.is_empty() || tag != 8 {
                return None;
            }
            // Map body: [len u32][count u16][entries].
            let count = u16::from_le_bytes(span.get(4..6)?.try_into().ok()?) as usize;
            let mut p = 6usize;
            let mut hit = None;
            for _ in 0..count {
                let k_len = *span.get(p)? as usize;
                p += 1;
                let key = span.get(p..p + k_len)?;
                p += k_len;
                let t = *span.get(p)?;
                p += 1;
                let s = p;
                let mut q = s;
                skip_value(t, span, &mut q)?;
                std::str::from_utf8(key).ok()?;
                if key == seg.as_bytes() {
                    hit = Some((t, &span[s..q]));
                    break;
                }
                p = q;
            }
            (tag, span) = hit?;
        }
        Some(BorrowedValue { tag, data: span })
    }

    /// True when a top-level field points at blob storage that `get` would
    /// inflate. `offset == u64::MAX` is the deferred placeholder and needs
    /// no read, so it stays on the zero-decode path.
    pub fn has_blob_links(&self) -> bool {
        self.iter().any(|(_, v)| {
            v.tag == 11
                && v.data
                    .get(4..12)
                    .and_then(|b| <[u8; 8]>::try_from(b).ok())
                    .map(|b| u64::from_le_bytes(b) != u64::MAX)
                    .unwrap_or(true)
        })
    }

    /// Single-pass JSON serialization from the pinned bytes: same byte
    /// contract as [`HakoDoc::write_json`], no owned decode. `None` means
    /// corrupt framing, matching `HakoDoc::decode`'s missing-document result.
    pub fn write_json(&self, out: &mut Vec<u8>) -> Option<()> {
        let view = HakoDocView::new(&self.bytes)?;
        out.push(b'{');
        let mut first = true;
        let mut time_written = false;
        let mut it = view.iter();
        for (k, tag, data) in it.by_ref() {
            if !time_written && k > "_time" {
                HakoDoc::write_time(out, &mut first, self.time);
                time_written = true;
            }
            if !time_written && k == "_time" {
                time_written = true;
            }
            if !first {
                out.push(b',');
            }
            first = false;
            HakoDoc::write_json_str(out, k);
            out.push(b':');
            HakoDoc::write_view_value(out, &BorrowedValue { tag, data })?;
        }
        if it.remaining() != 0 || it.position() != self.bytes.len() {
            return None;
        }
        if !time_written {
            HakoDoc::write_time(out, &mut first, self.time);
        }
        out.push(b'}');
        Some(())
    }

    /// Owned convenience for response paths.
    pub fn to_json_bytes(&self) -> Option<Vec<u8>> {
        let mut out = Vec::with_capacity(self.bytes.len() + 16);
        self.write_json(&mut out).map(|_| out)
    }

    /// Iterate `(key, borrowed value)` pairs without materializing.
    pub fn iter(&self) -> impl Iterator<Item = (&str, BorrowedValue<'_>)> + '_ {
        let bytes: &[u8] = &self.bytes;
        let mut pos = 12usize;
        let mut remaining = self.fields_count;
        std::iter::from_fn(move || {
            if remaining == 0 {
                return None;
            }
            let k_len = *bytes.get(pos)? as usize;
            pos += 1;
            let key = std::str::from_utf8(bytes.get(pos..pos + k_len)?).ok()?;
            pos += k_len;
            let tag = *bytes.get(pos)?;
            pos += 1;
            let start = pos;
            skip_value(tag, bytes, &mut pos)?;
            remaining -= 1;
            Some((key, BorrowedValue { tag, data: &bytes[start..pos] }))
        })
    }

    /// Escape hatch: full owned decode.
    pub fn to_owned_doc(&self) -> Option<HakoDoc> {
        HakoDoc::decode(&self.bytes)
    }
}

impl<'a> HakoDocIter<'a> {
    /// Fields not yet consumed. After a full pass this must be 0 —
    /// `decode` rejects buffers that end mid-document instead of
    /// returning a silently short doc.
    pub fn remaining(&self) -> u16 {
        self.remaining
    }
    /// Byte offset after the last consumed value. A well-formed buffer is
    /// consumed exactly (`decode` rejects trailing garbage the same way).
    pub fn position(&self) -> usize {
        self.pos
    }
}

impl<'a> Iterator for HakoDocIter<'a> {
    type Item = (&'a str, u8, &'a [u8]);    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 { return None; }
        let k_len = *self.bytes.get(self.pos)? as usize;
        self.pos += 1;
        let key = std::str::from_utf8(self.bytes.get(self.pos..self.pos + k_len)?).ok()?;
        self.pos += k_len;
        let tag = *self.bytes.get(self.pos)?;
        self.pos += 1;

        let start = self.pos;
        skip_value(tag, self.bytes, &mut self.pos)?;
        let data = &self.bytes[start..self.pos];

        self.remaining -= 1;
        Some((key, tag, data))
    }
}

/// Unvalidating framing cursor: identical traversal to [`HakoDocIter`]
/// minus the per-key UTF-8 check. Match-only callers (filter byte-compare)
/// use this; any row they accept is validated downstream by the owned
/// decode, so skipping validation here changes no outcome.
pub struct HakoDocRawIter<'a> {
    bytes: &'a [u8],
    pos: usize,
    remaining: u16,
}

impl<'a> Iterator for HakoDocRawIter<'a> {
    type Item = (&'a [u8], u8, &'a [u8]);
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 { return None; }
        let k_len = *self.bytes.get(self.pos)? as usize;
        self.pos += 1;
        let key = self.bytes.get(self.pos..self.pos + k_len)?;
        self.pos += k_len;
        let tag = *self.bytes.get(self.pos)?;
        self.pos += 1;

        let start = self.pos;
        skip_value(tag, self.bytes, &mut self.pos)?;
        let data = &self.bytes[start..self.pos];

        self.remaining -= 1;
        Some((key, tag, data))
    }
}

pub(crate) fn skip_value(tag: u8, bytes: &[u8], pos: &mut usize) -> Option<()> {
    if (0xC0..=0xC3).contains(&tag) { return Some(()); }
    if (tag & 0xF0) == 0x10 { return Some(()); }
    if (tag & 0xF8) == 0x40 {
        *pos += (tag & 0x07) as usize;
        // ponytail: the inline-length arm above is the only unchecked
        // advance — a corrupt tag can overshoot the buffer, and every
        // caller slices [start..pos] afterwards. Fail here instead of
        // panicking there (found via dotted-path fuzzing).
        if *pos > bytes.len() { return None; }
        return Some(());
    }

    match tag {
        3..=11 => {
            // let v_len = u32::from_le_bytes(bytes.get(*pos..*pos + 4)?.try_into().ok()?) as usize;
            // *pos += 4 + v_len;
            // Some(())
            if *pos + 4 > bytes.len() { return None; }
            let v_len = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
            *pos += 4;
            // Ensure the claimed length actually exists in the buffer
            if *pos + v_len > bytes.len() { return None; }
            *pos += v_len;
            Some(())
        }
        _ => None,
    }
}

pub(crate) fn decode_value(tag: u8, bytes: &[u8]) -> Option<Value> {
    if tag == 0xC0 { return Some(Value::Null); }
    if tag == 0xC1 { return Some(Value::ServerTimestamp); }
    if tag == 0xC2 { return Some(Value::Bool(true)); }
    if tag == 0xC3 { return Some(Value::Bool(false)); }
    if (tag & 0xF0) == 0x10 { return Some(Value::Int((tag & 0x0F) as i64)); }
    if (tag & 0xF8) == 0x40 {
        let len = (tag & 0x07) as usize;
        return Some(Value::String(String::from_utf8(bytes.get(..len)?.to_vec()).ok()?));
    }

    match tag {
        3 | 7 => {
            let mut p = 4; 
            let val = decode_varint(bytes, &mut p)?;
            if tag == 3 { Some(Value::Int(zigzag_decode(val))) } 
            else { Some(Value::Timestamp(zigzag_decode(val))) }
        }
        4 => Some(Value::Float(f64::from_le_bytes(bytes.get(4..12)?.try_into().ok()?))),
        5 => {
            let v_len = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?) as usize;
            Some(Value::String(String::from_utf8(bytes.get(4..4+v_len)?.to_vec()).ok()?))
        }
        6 => {
            let v_len = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?) as usize;
            Some(Value::Binary(bytes.get(4..4+v_len)?.to_vec()))
        }
        8 => {
            let mut p = 4;
            let count = u16::from_le_bytes(bytes.get(p..p + 2)?.try_into().ok()?);
            p += 2;
            let mut fields = Vec::with_capacity(count as usize);
            for _ in 0..count {
                let k_len = *bytes.get(p)? as usize;
                p += 1;
                let key = std::str::from_utf8(bytes.get(p..p + k_len)?).ok()?;
                p += k_len;
                let inner_tag = *bytes.get(p)?;
                p += 1;
                let start = p;
                skip_value(inner_tag, bytes, &mut p)?;
                fields.push((intern_field(key), decode_value(inner_tag, &bytes[start..p])?));
            }
            Some(Value::Map(fields))
        }
        9 => {
            let mut p = 4;
            let count = u32::from_le_bytes(bytes.get(p..p + 4)?.try_into().ok()?) as usize;
            p += 4;
            let mut items = Vec::with_capacity(count);
            for _ in 0..count {
                let tag = *bytes.get(p)?;
                p += 1;
                let start = p;
                skip_value(tag, bytes, &mut p)?;
                items.push(decode_value(tag, &bytes[start..p])?);
            }
            Some(Value::Array(items))
        }
        10 => {
            let mut p = 4;
            let c_len = *bytes.get(p)? as usize;
            p += 1;
            let collection = std::str::from_utf8(bytes.get(p..p+c_len)?).ok()?.to_string();
            p += c_len;
            let d_len = *bytes.get(p)? as usize;
            p += 1;
            let doc_id = std::str::from_utf8(bytes.get(p..p+d_len)?).ok()?.to_string();
            Some(Value::Reference { collection, doc_id })
        }
        11 => {
            let offset = u64::from_le_bytes(bytes.get(4..12)?.try_into().ok()?);
            let len = u32::from_le_bytes(bytes.get(12..16)?.try_into().ok()?);
            Some(Value::BlobLink { offset, len })
        }
        _ => Some(Value::Null),
    }
}