lora-store 0.33.1

In-memory graph store with property indexes for LoraDB.
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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! Dependency-free binary codecs for store-owned values that must cross
//! crate boundaries.
//!
//! `lora-wal` and `lora-snapshot` own their container formats, but the
//! byte shape for core store types belongs here so catalog DDL, property
//! values, and snapshot index metadata do not drift apart.

use std::collections::BTreeMap;
use std::fmt;

use crate::{
    ConstraintBacking, ConstraintDefinition, ConstraintRequest, IndexConfigValue, IndexDefinition,
    IndexRequest, LoraBinary, LoraDate, LoraDateTime, LoraDuration, LoraLocalDateTime,
    LoraLocalTime, LoraPoint, LoraTime, LoraVector, PropertyValue, StoredConstraintKind,
    StoredIndexEntity, StoredIndexKind, StoredIndexState, StoredPropertyType,
    StoredPropertyTypeTerm, StoredScalarType, StoredVectorCoordType, VectorValues, ZoneId,
};

type Result<T> = std::result::Result<T, StoreCodecError>;

/// The most lists and maps a property or index-config value may nest.
/// Decoding recurses once per level, so a crafted value nested a hundred
/// thousand deep would overflow the stack; encoding refuses the same
/// depth so nothing written becomes unreadable.
pub const MAX_VALUE_NESTING: usize = lora_ast::limits::MAX_VALUE_NESTING;

fn nesting_error(kind: fn(String) -> StoreCodecError) -> StoreCodecError {
    kind(format!(
        "value nests lists and maps more than {MAX_VALUE_NESTING} deep"
    ))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreCodecError {
    Encode(String),
    Decode(String),
}

impl fmt::Display for StoreCodecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Encode(message) => write!(f, "store value encode failed: {message}"),
            Self::Decode(message) => write!(f, "store value decode failed: {message}"),
        }
    }
}

impl std::error::Error for StoreCodecError {}

pub fn encode_property_value(value: &PropertyValue) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_property_value(&mut out, value, 0, MAX_VALUE_NESTING)?;
    Ok(out)
}

pub fn decode_property_value(bytes: &[u8]) -> Result<PropertyValue> {
    let mut reader = Reader::new(bytes);
    let value = reader.read_property_value()?;
    reader.finish()?;
    Ok(value)
}

/// [`encode_property_value`] without the nesting limit, for the in-memory
/// record encoding: a value the graph accepted is stored however deep it
/// is, as it was before the limit, and read back with
/// [`decode_stored_property_value`].
pub(crate) fn encode_stored_property_value(value: &PropertyValue) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_property_value(&mut out, value, 0, usize::MAX)?;
    Ok(out)
}

/// [`decode_property_value`] without the nesting limit, for bytes this
/// process encoded with [`encode_stored_property_value`].
pub(crate) fn decode_stored_property_value(bytes: &[u8]) -> Result<PropertyValue> {
    let mut reader = Reader::new(bytes);
    reader.max_depth = usize::MAX;
    let value = reader.read_property_value()?;
    reader.finish()?;
    Ok(value)
}

pub fn encode_index_request(request: &IndexRequest) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_index_request(&mut out, request)?;
    Ok(out)
}

pub fn decode_index_request(bytes: &[u8]) -> Result<IndexRequest> {
    let mut reader = Reader::new(bytes);
    let request = reader.read_index_request()?;
    reader.finish()?;
    Ok(request)
}

pub fn encode_constraint_request(request: &ConstraintRequest) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_constraint_request(&mut out, request)?;
    Ok(out)
}

pub fn decode_constraint_request(bytes: &[u8]) -> Result<ConstraintRequest> {
    let mut reader = Reader::new(bytes);
    let request = reader.read_constraint_request()?;
    reader.finish()?;
    Ok(request)
}

pub fn encode_constraint_definitions(defs: &[ConstraintDefinition]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_len(&mut out, defs.len())?;
    for def in defs {
        write_constraint_definition(&mut out, def)?;
    }
    Ok(out)
}

pub fn decode_constraint_definitions(bytes: &[u8]) -> Result<Vec<ConstraintDefinition>> {
    let mut reader = Reader::new(bytes);
    let len = reader.read_len_bounded("constraint definition")?;
    let mut defs = reader.vec_with_capacity(len, "constraint definition")?;
    for _ in 0..len {
        defs.push(reader.read_constraint_definition()?);
    }
    reader.finish()?;
    Ok(defs)
}

pub fn encode_index_definitions(defs: &[IndexDefinition]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write_len(&mut out, defs.len())?;
    for def in defs {
        write_index_definition(&mut out, def)?;
    }
    Ok(out)
}

pub fn decode_index_definitions(bytes: &[u8]) -> Result<Vec<IndexDefinition>> {
    let mut reader = Reader::new(bytes);
    let len = reader.read_len_bounded("index definition")?;
    let mut defs = reader.vec_with_capacity(len, "index definition")?;
    for _ in 0..len {
        defs.push(reader.read_index_definition()?);
    }
    reader.finish()?;
    Ok(defs)
}

const VALUE_NULL: u8 = 0;
const VALUE_BOOL: u8 = 1;
const VALUE_INT: u8 = 2;
const VALUE_FLOAT: u8 = 3;
const VALUE_STRING: u8 = 4;
const VALUE_LIST: u8 = 5;
const VALUE_MAP: u8 = 6;
const VALUE_DATE: u8 = 7;
const VALUE_TIME: u8 = 8;
const VALUE_LOCAL_TIME: u8 = 9;
const VALUE_DATE_TIME: u8 = 10;
const VALUE_LOCAL_DATE_TIME: u8 = 11;
const VALUE_DURATION: u8 = 12;
const VALUE_POINT: u8 = 13;
const VALUE_VECTOR: u8 = 14;
const VALUE_BINARY: u8 = 15;
/// A DATETIME with a named zone: the `VALUE_DATE_TIME` fields, then the
/// zone's name. A DATETIME without one keeps `VALUE_DATE_TIME`, so data
/// written before zones existed decodes unchanged.
const VALUE_ZONED_DATE_TIME: u8 = 16;

const VECTOR_FLOAT64: u8 = 1;
const VECTOR_FLOAT32: u8 = 2;
const VECTOR_INTEGER64: u8 = 3;
const VECTOR_INTEGER32: u8 = 4;
const VECTOR_INTEGER16: u8 = 5;
const VECTOR_INTEGER8: u8 = 6;

const INDEX_KIND_RANGE: u8 = 1;
const INDEX_KIND_TEXT: u8 = 2;
const INDEX_KIND_POINT: u8 = 3;
const INDEX_KIND_LOOKUP: u8 = 4;
const INDEX_KIND_VECTOR: u8 = 5;
const INDEX_KIND_FULLTEXT: u8 = 6;

const INDEX_ENTITY_NODE: u8 = 1;
const INDEX_ENTITY_RELATIONSHIP: u8 = 2;

const INDEX_STATE_ONLINE: u8 = 1;
const INDEX_STATE_POPULATING: u8 = 2;

const CONFIG_NUMBER: u8 = 1;
const CONFIG_INTEGER: u8 = 2;
const CONFIG_STRING: u8 = 3;
const CONFIG_BOOL: u8 = 4;
const CONFIG_LIST: u8 = 5;
const CONFIG_MAP: u8 = 6;
const CONFIG_NULL: u8 = 7;

const CONSTRAINT_KIND_UNIQUE: u8 = 1;
const CONSTRAINT_KIND_EXISTENCE: u8 = 2;
const CONSTRAINT_KIND_NODE_KEY: u8 = 3;
const CONSTRAINT_KIND_RELATIONSHIP_KEY: u8 = 4;
const CONSTRAINT_KIND_PROPERTY_TYPE: u8 = 5;
/// Set on a uniqueness or key tag for a hash-backed constraint
/// ([`ConstraintBacking::Hash`]); records without it decode as before.
const CONSTRAINT_BACKING_HASH: u8 = 0x80;

const PROPERTY_TYPE_TERM_SCALAR: u8 = 1;
const PROPERTY_TYPE_TERM_LIST: u8 = 2;
const PROPERTY_TYPE_TERM_VECTOR: u8 = 3;

const SCALAR_BOOLEAN: u8 = 1;
const SCALAR_STRING: u8 = 2;
const SCALAR_INTEGER: u8 = 3;
const SCALAR_FLOAT: u8 = 4;
const SCALAR_DATE: u8 = 5;
const SCALAR_LOCAL_TIME: u8 = 6;
const SCALAR_ZONED_TIME: u8 = 7;
const SCALAR_LOCAL_DATETIME: u8 = 8;
const SCALAR_ZONED_DATETIME: u8 = 9;
const SCALAR_DURATION: u8 = 10;
const SCALAR_POINT: u8 = 11;
const SCALAR_MAP: u8 = 12;
const SCALAR_ANY: u8 = 13;

const VCOORD_INT8: u8 = 1;
const VCOORD_INT16: u8 = 2;
const VCOORD_INT32: u8 = 3;
const VCOORD_INT64: u8 = 4;
const VCOORD_FLOAT32: u8 = 5;
const VCOORD_FLOAT64: u8 = 6;

fn write_index_request(out: &mut Vec<u8>, request: &IndexRequest) -> Result<()> {
    write_optional_string(out, request.explicit_name.as_deref())?;
    write_index_kind(out, request.kind);
    write_index_entity(out, request.entity);
    write_optional_string(out, request.label.as_deref())?;
    write_string_vec(out, &request.additional_labels)?;
    write_string_vec(out, &request.properties)?;
    write_config_map(out, &request.options)
}

fn write_index_definition(out: &mut Vec<u8>, def: &IndexDefinition) -> Result<()> {
    write_string(out, &def.name)?;
    write_index_kind(out, def.kind);
    write_index_entity(out, def.entity);
    write_optional_string(out, def.label.as_deref())?;
    write_string_vec(out, &def.additional_labels)?;
    write_string_vec(out, &def.properties)?;
    write_config_map(out, &def.options)?;
    write_index_state(out, def.state);
    Ok(())
}

fn write_index_kind(out: &mut Vec<u8>, kind: StoredIndexKind) {
    out.push(match kind {
        StoredIndexKind::Range => INDEX_KIND_RANGE,
        StoredIndexKind::Text => INDEX_KIND_TEXT,
        StoredIndexKind::Point => INDEX_KIND_POINT,
        StoredIndexKind::Lookup => INDEX_KIND_LOOKUP,
        StoredIndexKind::Vector => INDEX_KIND_VECTOR,
        StoredIndexKind::Fulltext => INDEX_KIND_FULLTEXT,
    });
}

fn write_index_entity(out: &mut Vec<u8>, entity: StoredIndexEntity) {
    out.push(match entity {
        StoredIndexEntity::Node => INDEX_ENTITY_NODE,
        StoredIndexEntity::Relationship => INDEX_ENTITY_RELATIONSHIP,
    });
}

fn write_index_state(out: &mut Vec<u8>, state: StoredIndexState) {
    out.push(match state {
        StoredIndexState::Online => INDEX_STATE_ONLINE,
        StoredIndexState::Populating => INDEX_STATE_POPULATING,
    });
}

fn write_constraint_request(out: &mut Vec<u8>, request: &ConstraintRequest) -> Result<()> {
    write_string(out, &request.name)?;
    write_constraint_kind(out, &request.kind, request.backing)?;
    write_index_entity(out, request.entity);
    write_string(out, &request.label)?;
    write_string_vec(out, &request.properties)
}

fn write_constraint_definition(out: &mut Vec<u8>, def: &ConstraintDefinition) -> Result<()> {
    write_string(out, &def.name)?;
    write_constraint_kind(out, &def.kind, def.backing)?;
    write_index_entity(out, def.entity);
    write_string(out, &def.label)?;
    write_string_vec(out, &def.properties)?;
    write_optional_string(out, def.owned_index.as_deref())
}

fn write_constraint_kind(
    out: &mut Vec<u8>,
    kind: &StoredConstraintKind,
    backing: ConstraintBacking,
) -> Result<()> {
    let hash = match backing {
        ConstraintBacking::Range => 0,
        ConstraintBacking::Hash => CONSTRAINT_BACKING_HASH,
    };
    match kind {
        StoredConstraintKind::Unique => out.push(CONSTRAINT_KIND_UNIQUE | hash),
        StoredConstraintKind::Existence => out.push(CONSTRAINT_KIND_EXISTENCE),
        StoredConstraintKind::NodeKey => out.push(CONSTRAINT_KIND_NODE_KEY | hash),
        StoredConstraintKind::RelationshipKey => out.push(CONSTRAINT_KIND_RELATIONSHIP_KEY | hash),
        StoredConstraintKind::PropertyType(t) => {
            out.push(CONSTRAINT_KIND_PROPERTY_TYPE);
            write_property_type(out, t)?;
        }
    }
    Ok(())
}

fn write_property_type(out: &mut Vec<u8>, t: &StoredPropertyType) -> Result<()> {
    write_len(out, t.alternatives.len())?;
    for term in &t.alternatives {
        write_property_type_term(out, term)?;
    }
    Ok(())
}

fn write_property_type_term(out: &mut Vec<u8>, term: &StoredPropertyTypeTerm) -> Result<()> {
    match term {
        StoredPropertyTypeTerm::Scalar(s) => {
            out.push(PROPERTY_TYPE_TERM_SCALAR);
            out.push(scalar_tag(*s));
        }
        StoredPropertyTypeTerm::List { inner, not_null } => {
            out.push(PROPERTY_TYPE_TERM_LIST);
            out.push(u8::from(*not_null));
            write_property_type_term(out, inner)?;
        }
        StoredPropertyTypeTerm::Vector { coord, dimension } => {
            out.push(PROPERTY_TYPE_TERM_VECTOR);
            out.push(vector_coord_tag(*coord));
            write_u32(out, *dimension);
        }
    }
    Ok(())
}

fn scalar_tag(s: StoredScalarType) -> u8 {
    match s {
        StoredScalarType::Boolean => SCALAR_BOOLEAN,
        StoredScalarType::String => SCALAR_STRING,
        StoredScalarType::Integer => SCALAR_INTEGER,
        StoredScalarType::Float => SCALAR_FLOAT,
        StoredScalarType::Date => SCALAR_DATE,
        StoredScalarType::LocalTime => SCALAR_LOCAL_TIME,
        StoredScalarType::ZonedTime => SCALAR_ZONED_TIME,
        StoredScalarType::LocalDateTime => SCALAR_LOCAL_DATETIME,
        StoredScalarType::ZonedDateTime => SCALAR_ZONED_DATETIME,
        StoredScalarType::Duration => SCALAR_DURATION,
        StoredScalarType::Point => SCALAR_POINT,
        StoredScalarType::Map => SCALAR_MAP,
        StoredScalarType::Any => SCALAR_ANY,
    }
}

fn vector_coord_tag(c: StoredVectorCoordType) -> u8 {
    match c {
        StoredVectorCoordType::Int8 => VCOORD_INT8,
        StoredVectorCoordType::Int16 => VCOORD_INT16,
        StoredVectorCoordType::Int32 => VCOORD_INT32,
        StoredVectorCoordType::Int64 => VCOORD_INT64,
        StoredVectorCoordType::Float32 => VCOORD_FLOAT32,
        StoredVectorCoordType::Float64 => VCOORD_FLOAT64,
    }
}

fn write_config_map(out: &mut Vec<u8>, values: &BTreeMap<String, IndexConfigValue>) -> Result<()> {
    write_config_map_at(out, values, 0)
}

fn write_config_map_at(
    out: &mut Vec<u8>,
    values: &BTreeMap<String, IndexConfigValue>,
    depth: usize,
) -> Result<()> {
    write_len(out, values.len())?;
    for (key, value) in values {
        write_string(out, key)?;
        write_config_value(out, value, depth)?;
    }
    Ok(())
}

/// `depth`: lists and maps around `value`.
fn write_config_value(out: &mut Vec<u8>, value: &IndexConfigValue, depth: usize) -> Result<()> {
    if matches!(value, IndexConfigValue::List(_) | IndexConfigValue::Map(_))
        && depth >= MAX_VALUE_NESTING
    {
        return Err(nesting_error(StoreCodecError::Encode));
    }
    match value {
        IndexConfigValue::Number(value) => {
            out.push(CONFIG_NUMBER);
            write_f64(out, *value);
        }
        IndexConfigValue::Integer(value) => {
            out.push(CONFIG_INTEGER);
            write_i64(out, *value);
        }
        IndexConfigValue::String(value) => {
            out.push(CONFIG_STRING);
            write_string(out, value)?;
        }
        IndexConfigValue::Bool(value) => {
            out.push(CONFIG_BOOL);
            out.push(u8::from(*value));
        }
        IndexConfigValue::List(values) => {
            out.push(CONFIG_LIST);
            write_len(out, values.len())?;
            for value in values {
                write_config_value(out, value, depth + 1)?;
            }
        }
        IndexConfigValue::Map(values) => {
            out.push(CONFIG_MAP);
            write_config_map_at(out, values, depth + 1)?;
        }
        IndexConfigValue::Null => out.push(CONFIG_NULL),
    }
    Ok(())
}

/// `depth`: lists and maps around `value`; at most `max_depth`.
fn write_property_value(
    out: &mut Vec<u8>,
    value: &PropertyValue,
    depth: usize,
    max_depth: usize,
) -> Result<()> {
    if matches!(value, PropertyValue::List(_) | PropertyValue::Map(_)) && depth >= max_depth {
        return Err(nesting_error(StoreCodecError::Encode));
    }
    match value {
        PropertyValue::Null => out.push(VALUE_NULL),
        PropertyValue::Bool(value) => {
            out.push(VALUE_BOOL);
            out.push(u8::from(*value));
        }
        PropertyValue::Int(value) => {
            out.push(VALUE_INT);
            write_i64(out, *value);
        }
        PropertyValue::Float(value) => {
            out.push(VALUE_FLOAT);
            write_f64(out, *value);
        }
        PropertyValue::String(value) => {
            out.push(VALUE_STRING);
            write_string(out, value)?;
        }
        PropertyValue::List(values) => {
            out.push(VALUE_LIST);
            write_len(out, values.len())?;
            for value in values {
                write_property_value(out, value, depth + 1, max_depth)?;
            }
        }
        PropertyValue::Map(values) => {
            out.push(VALUE_MAP);
            write_len(out, values.len())?;
            for (key, value) in values {
                write_string(out, key)?;
                write_property_value(out, value, depth + 1, max_depth)?;
            }
        }
        PropertyValue::Date(value) => {
            out.push(VALUE_DATE);
            write_i32(out, value.year);
            write_u32(out, value.month);
            write_u32(out, value.day);
        }
        PropertyValue::Time(value) => {
            out.push(VALUE_TIME);
            write_time_fields(
                out,
                value.hour,
                value.minute,
                value.second,
                value.nanosecond,
            );
            write_i32(out, value.offset_seconds);
        }
        PropertyValue::LocalTime(value) => {
            out.push(VALUE_LOCAL_TIME);
            write_time_fields(
                out,
                value.hour,
                value.minute,
                value.second,
                value.nanosecond,
            );
        }
        PropertyValue::DateTime(value) => {
            out.push(if value.zone.is_some() {
                VALUE_ZONED_DATE_TIME
            } else {
                VALUE_DATE_TIME
            });
            write_date_fields(out, value.year, value.month, value.day);
            write_time_fields(
                out,
                value.hour,
                value.minute,
                value.second,
                value.nanosecond,
            );
            write_i32(out, value.offset_seconds);
            if let Some(zone) = value.zone {
                write_string(out, zone.name())?;
            }
        }
        PropertyValue::LocalDateTime(value) => {
            out.push(VALUE_LOCAL_DATE_TIME);
            write_date_fields(out, value.year, value.month, value.day);
            write_time_fields(
                out,
                value.hour,
                value.minute,
                value.second,
                value.nanosecond,
            );
        }
        PropertyValue::Duration(value) => {
            out.push(VALUE_DURATION);
            write_i64(out, value.months);
            write_i64(out, value.days);
            write_i64(out, value.seconds);
            write_i64(out, value.nanoseconds);
        }
        PropertyValue::Point(value) => {
            out.push(VALUE_POINT);
            write_f64(out, value.x);
            write_f64(out, value.y);
            match value.z {
                Some(z) => {
                    out.push(1);
                    write_f64(out, z);
                }
                None => out.push(0),
            }
            write_u32(out, value.srid);
        }
        PropertyValue::Vector(value) => {
            out.push(VALUE_VECTOR);
            write_vector(out, value)?;
        }
        PropertyValue::Binary(value) => {
            out.push(VALUE_BINARY);
            write_len(out, value.segments().len())?;
            for segment in value.segments() {
                write_bytes(out, segment)?;
            }
        }
    }
    Ok(())
}

fn write_date_fields(out: &mut Vec<u8>, year: i32, month: u32, day: u32) {
    write_i32(out, year);
    write_u32(out, month);
    write_u32(out, day);
}

fn write_time_fields(out: &mut Vec<u8>, hour: u32, minute: u32, second: u32, nanosecond: u32) {
    write_u32(out, hour);
    write_u32(out, minute);
    write_u32(out, second);
    write_u32(out, nanosecond);
}

fn write_vector(out: &mut Vec<u8>, vector: &LoraVector) -> Result<()> {
    // The coordinates decide the dimension. A vector built with another
    // `dimension` (its fields are public) would otherwise encode bytes the
    // decoder rejects, and a stored record would fail on every read.
    write_len(out, vector.values.len())?;
    match &vector.values {
        VectorValues::Float64(values) => {
            out.push(VECTOR_FLOAT64);
            write_len(out, values.len())?;
            for value in values {
                write_f64(out, *value);
            }
        }
        VectorValues::Float32(values) => {
            out.push(VECTOR_FLOAT32);
            write_len(out, values.len())?;
            for value in values {
                write_f32(out, *value);
            }
        }
        VectorValues::Integer64(values) => {
            out.push(VECTOR_INTEGER64);
            write_len(out, values.len())?;
            for value in values {
                write_i64(out, *value);
            }
        }
        VectorValues::Integer32(values) => {
            out.push(VECTOR_INTEGER32);
            write_len(out, values.len())?;
            for value in values {
                write_i32(out, *value);
            }
        }
        VectorValues::Integer16(values) => {
            out.push(VECTOR_INTEGER16);
            write_len(out, values.len())?;
            for value in values {
                write_i16(out, *value);
            }
        }
        VectorValues::Integer8(values) => {
            out.push(VECTOR_INTEGER8);
            write_len(out, values.len())?;
            for value in values {
                out.push(*value as u8);
            }
        }
    }
    Ok(())
}

fn write_optional_string(out: &mut Vec<u8>, value: Option<&str>) -> Result<()> {
    match value {
        Some(value) => {
            out.push(1);
            write_string(out, value)?;
        }
        None => out.push(0),
    }
    Ok(())
}

fn write_len(out: &mut Vec<u8>, len: usize) -> Result<()> {
    write_u64(
        out,
        u64::try_from(len)
            .map_err(|_| StoreCodecError::Encode("length does not fit in u64".into()))?,
    );
    Ok(())
}

fn write_bytes(out: &mut Vec<u8>, bytes: &[u8]) -> Result<()> {
    write_len(out, bytes.len())?;
    out.extend_from_slice(bytes);
    Ok(())
}

fn write_string(out: &mut Vec<u8>, value: &str) -> Result<()> {
    write_bytes(out, value.as_bytes())
}

fn write_string_vec(out: &mut Vec<u8>, values: &[String]) -> Result<()> {
    write_len(out, values.len())?;
    for value in values {
        write_string(out, value)?;
    }
    Ok(())
}

fn write_i16(out: &mut Vec<u8>, value: i16) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_i32(out: &mut Vec<u8>, value: i32) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_u32(out: &mut Vec<u8>, value: u32) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_i64(out: &mut Vec<u8>, value: i64) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_u64(out: &mut Vec<u8>, value: u64) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_f32(out: &mut Vec<u8>, value: f32) {
    out.extend_from_slice(&value.to_bits().to_le_bytes());
}

fn write_f64(out: &mut Vec<u8>, value: f64) {
    out.extend_from_slice(&value.to_bits().to_le_bytes());
}

struct Reader<'a> {
    bytes: &'a [u8],
    offset: usize,
    /// Lists and maps open around the value being read.
    depth: usize,
    /// The most `depth` may reach.
    max_depth: usize,
}

impl<'a> Reader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            offset: 0,
            depth: 0,
            max_depth: MAX_VALUE_NESTING,
        }
    }

    /// Open a list or map; [`MAX_VALUE_NESTING`] bounds the recursion.
    fn enter(&mut self) -> Result<()> {
        if self.depth >= self.max_depth {
            return Err(nesting_error(StoreCodecError::Decode));
        }
        self.depth += 1;
        Ok(())
    }

    fn finish(&self) -> Result<()> {
        if self.offset == self.bytes.len() {
            Ok(())
        } else {
            Err(StoreCodecError::Decode(format!(
                "trailing bytes: {}",
                self.bytes.len() - self.offset
            )))
        }
    }

    fn read_exact(&mut self, len: usize) -> Result<&'a [u8]> {
        let end = self
            .offset
            .checked_add(len)
            .ok_or_else(|| StoreCodecError::Decode("offset overflow".into()))?;
        if end > self.bytes.len() {
            return Err(StoreCodecError::Decode("truncated input".into()));
        }
        let out = &self.bytes[self.offset..end];
        self.offset = end;
        Ok(out)
    }

    fn read_array<const N: usize>(&mut self) -> Result<[u8; N]> {
        self.read_exact(N)?
            .try_into()
            .map_err(|_| StoreCodecError::Decode("fixed-width field truncated".into()))
    }

    fn read_u8(&mut self) -> Result<u8> {
        Ok(self.read_exact(1)?[0])
    }

    fn read_i8(&mut self) -> Result<i8> {
        Ok(self.read_u8()? as i8)
    }

    fn read_i16(&mut self) -> Result<i16> {
        Ok(i16::from_le_bytes(self.read_array()?))
    }

    fn read_i32(&mut self) -> Result<i32> {
        Ok(i32::from_le_bytes(self.read_array()?))
    }

    fn read_u32(&mut self) -> Result<u32> {
        Ok(u32::from_le_bytes(self.read_array()?))
    }

    fn read_i64(&mut self) -> Result<i64> {
        Ok(i64::from_le_bytes(self.read_array()?))
    }

    fn read_u64(&mut self) -> Result<u64> {
        Ok(u64::from_le_bytes(self.read_array()?))
    }

    fn read_f32(&mut self) -> Result<f32> {
        Ok(f32::from_bits(self.read_u32()?))
    }

    fn read_f64(&mut self) -> Result<f64> {
        Ok(f64::from_bits(self.read_u64()?))
    }

    fn read_len(&mut self) -> Result<usize> {
        usize::try_from(self.read_u64()?)
            .map_err(|_| StoreCodecError::Decode("length overflows usize".into()))
    }

    fn remaining(&self) -> usize {
        self.bytes.len().saturating_sub(self.offset)
    }

    fn read_len_bounded(&mut self, label: &str) -> Result<usize> {
        let len = self.read_len()?;
        if len > self.remaining() {
            return Err(StoreCodecError::Decode(format!(
                "{label} count {len} exceeds remaining input"
            )));
        }
        Ok(len)
    }

    fn vec_with_capacity<T>(&self, len: usize, label: &str) -> Result<Vec<T>> {
        let mut values = Vec::new();
        values.try_reserve(len).map_err(|_| {
            StoreCodecError::Decode(format!("{label} count {len} is too large to allocate"))
        })?;
        Ok(values)
    }

    fn read_bytes(&mut self) -> Result<&'a [u8]> {
        let len = self.read_len()?;
        self.read_exact(len)
    }

    fn read_string(&mut self) -> Result<String> {
        let bytes = self.read_bytes()?;
        std::str::from_utf8(bytes)
            .map(|value| value.to_string())
            .map_err(|e| StoreCodecError::Decode(format!("invalid UTF-8 string: {e}")))
    }

    fn read_string_vec(&mut self) -> Result<Vec<String>> {
        let len = self.read_len_bounded("string")?;
        let mut values = self.vec_with_capacity(len, "string")?;
        for _ in 0..len {
            values.push(self.read_string()?);
        }
        Ok(values)
    }

    fn read_optional_string(&mut self) -> Result<Option<String>> {
        match self.read_u8()? {
            0 => Ok(None),
            1 => Ok(Some(self.read_string()?)),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid optional string tag {tag}"
            ))),
        }
    }

    fn read_index_request(&mut self) -> Result<IndexRequest> {
        Ok(IndexRequest {
            explicit_name: self.read_optional_string()?,
            kind: self.read_index_kind()?,
            entity: self.read_index_entity()?,
            label: self.read_optional_string()?,
            additional_labels: self.read_string_vec()?,
            properties: self.read_string_vec()?,
            options: self.read_config_map()?,
        })
    }

    fn read_index_definition(&mut self) -> Result<IndexDefinition> {
        Ok(IndexDefinition {
            name: self.read_string()?,
            kind: self.read_index_kind()?,
            entity: self.read_index_entity()?,
            label: self.read_optional_string()?,
            additional_labels: self.read_string_vec()?,
            properties: self.read_string_vec()?,
            options: self.read_config_map()?,
            state: self.read_index_state()?,
        })
    }

    fn read_index_kind(&mut self) -> Result<StoredIndexKind> {
        match self.read_u8()? {
            INDEX_KIND_RANGE => Ok(StoredIndexKind::Range),
            INDEX_KIND_TEXT => Ok(StoredIndexKind::Text),
            INDEX_KIND_POINT => Ok(StoredIndexKind::Point),
            INDEX_KIND_LOOKUP => Ok(StoredIndexKind::Lookup),
            INDEX_KIND_VECTOR => Ok(StoredIndexKind::Vector),
            INDEX_KIND_FULLTEXT => Ok(StoredIndexKind::Fulltext),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid index kind tag {tag}"
            ))),
        }
    }

    fn read_index_entity(&mut self) -> Result<StoredIndexEntity> {
        match self.read_u8()? {
            INDEX_ENTITY_NODE => Ok(StoredIndexEntity::Node),
            INDEX_ENTITY_RELATIONSHIP => Ok(StoredIndexEntity::Relationship),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid index entity tag {tag}"
            ))),
        }
    }

    fn read_index_state(&mut self) -> Result<StoredIndexState> {
        match self.read_u8()? {
            INDEX_STATE_ONLINE => Ok(StoredIndexState::Online),
            INDEX_STATE_POPULATING => Ok(StoredIndexState::Populating),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid index state tag {tag}"
            ))),
        }
    }

    fn read_constraint_request(&mut self) -> Result<ConstraintRequest> {
        let name = self.read_string()?;
        let (kind, backing) = self.read_constraint_kind()?;
        Ok(ConstraintRequest {
            name,
            kind,
            entity: self.read_index_entity()?,
            label: self.read_string()?,
            properties: self.read_string_vec()?,
            backing,
        })
    }

    fn read_constraint_definition(&mut self) -> Result<ConstraintDefinition> {
        let name = self.read_string()?;
        let (kind, backing) = self.read_constraint_kind()?;
        Ok(ConstraintDefinition {
            name,
            kind,
            entity: self.read_index_entity()?,
            label: self.read_string()?,
            properties: self.read_string_vec()?,
            owned_index: self.read_optional_string()?,
            backing,
        })
    }

    fn read_constraint_kind(&mut self) -> Result<(StoredConstraintKind, ConstraintBacking)> {
        let tag = self.read_u8()?;
        let backing = if tag & CONSTRAINT_BACKING_HASH != 0
            && matches!(
                tag & !CONSTRAINT_BACKING_HASH,
                CONSTRAINT_KIND_UNIQUE
                    | CONSTRAINT_KIND_NODE_KEY
                    | CONSTRAINT_KIND_RELATIONSHIP_KEY
            ) {
            ConstraintBacking::Hash
        } else {
            ConstraintBacking::Range
        };
        let tag = match backing {
            ConstraintBacking::Hash => tag & !CONSTRAINT_BACKING_HASH,
            ConstraintBacking::Range => tag,
        };
        let kind = match tag {
            CONSTRAINT_KIND_UNIQUE => Ok(StoredConstraintKind::Unique),
            CONSTRAINT_KIND_EXISTENCE => Ok(StoredConstraintKind::Existence),
            CONSTRAINT_KIND_NODE_KEY => Ok(StoredConstraintKind::NodeKey),
            CONSTRAINT_KIND_RELATIONSHIP_KEY => Ok(StoredConstraintKind::RelationshipKey),
            CONSTRAINT_KIND_PROPERTY_TYPE => Ok(StoredConstraintKind::PropertyType(
                self.read_property_type()?,
            )),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid constraint kind tag {tag}"
            ))),
        }?;
        Ok((kind, backing))
    }

    fn read_property_type(&mut self) -> Result<StoredPropertyType> {
        let len = self.read_len_bounded("property type alternative")?;
        let mut alternatives = self.vec_with_capacity(len, "property type alternative")?;
        for _ in 0..len {
            alternatives.push(self.read_property_type_term()?);
        }
        Ok(StoredPropertyType { alternatives })
    }

    fn read_property_type_term(&mut self) -> Result<StoredPropertyTypeTerm> {
        match self.read_u8()? {
            PROPERTY_TYPE_TERM_SCALAR => {
                Ok(StoredPropertyTypeTerm::Scalar(self.read_scalar_type()?))
            }
            PROPERTY_TYPE_TERM_LIST => {
                let not_null = self.read_u8()? != 0;
                let inner = Box::new(self.read_property_type_term()?);
                Ok(StoredPropertyTypeTerm::List { inner, not_null })
            }
            PROPERTY_TYPE_TERM_VECTOR => {
                let coord = self.read_vector_coord_type()?;
                let dimension = self.read_u32()?;
                Ok(StoredPropertyTypeTerm::Vector { coord, dimension })
            }
            tag => Err(StoreCodecError::Decode(format!(
                "invalid property-type term tag {tag}"
            ))),
        }
    }

    fn read_scalar_type(&mut self) -> Result<StoredScalarType> {
        match self.read_u8()? {
            SCALAR_BOOLEAN => Ok(StoredScalarType::Boolean),
            SCALAR_STRING => Ok(StoredScalarType::String),
            SCALAR_INTEGER => Ok(StoredScalarType::Integer),
            SCALAR_FLOAT => Ok(StoredScalarType::Float),
            SCALAR_DATE => Ok(StoredScalarType::Date),
            SCALAR_LOCAL_TIME => Ok(StoredScalarType::LocalTime),
            SCALAR_ZONED_TIME => Ok(StoredScalarType::ZonedTime),
            SCALAR_LOCAL_DATETIME => Ok(StoredScalarType::LocalDateTime),
            SCALAR_ZONED_DATETIME => Ok(StoredScalarType::ZonedDateTime),
            SCALAR_DURATION => Ok(StoredScalarType::Duration),
            SCALAR_POINT => Ok(StoredScalarType::Point),
            SCALAR_MAP => Ok(StoredScalarType::Map),
            SCALAR_ANY => Ok(StoredScalarType::Any),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid scalar type tag {tag}"
            ))),
        }
    }

    fn read_vector_coord_type(&mut self) -> Result<StoredVectorCoordType> {
        match self.read_u8()? {
            VCOORD_INT8 => Ok(StoredVectorCoordType::Int8),
            VCOORD_INT16 => Ok(StoredVectorCoordType::Int16),
            VCOORD_INT32 => Ok(StoredVectorCoordType::Int32),
            VCOORD_INT64 => Ok(StoredVectorCoordType::Int64),
            VCOORD_FLOAT32 => Ok(StoredVectorCoordType::Float32),
            VCOORD_FLOAT64 => Ok(StoredVectorCoordType::Float64),
            tag => Err(StoreCodecError::Decode(format!(
                "invalid vector coord type tag {tag}"
            ))),
        }
    }

    fn read_config_map(&mut self) -> Result<BTreeMap<String, IndexConfigValue>> {
        let len = self.read_len_bounded("index config map entry")?;
        let mut values = BTreeMap::new();
        for _ in 0..len {
            values.insert(self.read_string()?, self.read_config_value()?);
        }
        Ok(values)
    }

    fn read_config_value(&mut self) -> Result<IndexConfigValue> {
        Ok(match self.read_u8()? {
            CONFIG_NUMBER => IndexConfigValue::Number(self.read_f64()?),
            CONFIG_INTEGER => IndexConfigValue::Integer(self.read_i64()?),
            CONFIG_STRING => IndexConfigValue::String(self.read_string()?),
            CONFIG_BOOL => IndexConfigValue::Bool(self.read_u8()? != 0),
            CONFIG_LIST => {
                self.enter()?;
                let len = self.read_len_bounded("index config list value")?;
                let mut values = self.vec_with_capacity(len, "index config list value")?;
                for _ in 0..len {
                    values.push(self.read_config_value()?);
                }
                self.depth -= 1;
                IndexConfigValue::List(values)
            }
            CONFIG_MAP => {
                self.enter()?;
                let values = self.read_config_map()?;
                self.depth -= 1;
                IndexConfigValue::Map(values)
            }
            CONFIG_NULL => IndexConfigValue::Null,
            tag => {
                return Err(StoreCodecError::Decode(format!(
                    "invalid index config value tag {tag}"
                )));
            }
        })
    }

    fn read_property_value(&mut self) -> Result<PropertyValue> {
        Ok(match self.read_u8()? {
            VALUE_NULL => PropertyValue::Null,
            VALUE_BOOL => PropertyValue::Bool(self.read_u8()? != 0),
            VALUE_INT => PropertyValue::Int(self.read_i64()?),
            VALUE_FLOAT => PropertyValue::Float(self.read_f64()?),
            VALUE_STRING => PropertyValue::String(self.read_string()?),
            VALUE_LIST => {
                self.enter()?;
                let len = self.read_len_bounded("property list value")?;
                let mut values = self.vec_with_capacity(len, "property list value")?;
                for _ in 0..len {
                    values.push(self.read_property_value()?);
                }
                self.depth -= 1;
                PropertyValue::List(values)
            }
            VALUE_MAP => {
                self.enter()?;
                let len = self.read_len_bounded("property map entry")?;
                let mut values = BTreeMap::new();
                for _ in 0..len {
                    values.insert(self.read_string()?, self.read_property_value()?);
                }
                self.depth -= 1;
                PropertyValue::Map(values)
            }
            VALUE_DATE => PropertyValue::Date(LoraDate {
                year: self.read_i32()?,
                month: self.read_u32()?,
                day: self.read_u32()?,
            }),
            VALUE_TIME => PropertyValue::Time(LoraTime {
                hour: self.read_u32()?,
                minute: self.read_u32()?,
                second: self.read_u32()?,
                nanosecond: self.read_u32()?,
                offset_seconds: self.read_i32()?,
            }),
            VALUE_LOCAL_TIME => PropertyValue::LocalTime(LoraLocalTime {
                hour: self.read_u32()?,
                minute: self.read_u32()?,
                second: self.read_u32()?,
                nanosecond: self.read_u32()?,
            }),
            tag @ (VALUE_DATE_TIME | VALUE_ZONED_DATE_TIME) => {
                let mut value = LoraDateTime {
                    year: self.read_i32()?,
                    month: self.read_u32()?,
                    day: self.read_u32()?,
                    hour: self.read_u32()?,
                    minute: self.read_u32()?,
                    second: self.read_u32()?,
                    nanosecond: self.read_u32()?,
                    offset_seconds: self.read_i32()?,
                    zone: None,
                };
                if tag == VALUE_ZONED_DATE_TIME {
                    let name = self.read_string()?;
                    value.zone = Some(ZoneId::lookup(&name).ok_or_else(|| {
                        StoreCodecError::Decode(format!("unknown time zone `{name}`"))
                    })?);
                }
                PropertyValue::DateTime(value)
            }
            VALUE_LOCAL_DATE_TIME => PropertyValue::LocalDateTime(LoraLocalDateTime {
                year: self.read_i32()?,
                month: self.read_u32()?,
                day: self.read_u32()?,
                hour: self.read_u32()?,
                minute: self.read_u32()?,
                second: self.read_u32()?,
                nanosecond: self.read_u32()?,
            }),
            VALUE_DURATION => PropertyValue::Duration(LoraDuration {
                months: self.read_i64()?,
                days: self.read_i64()?,
                seconds: self.read_i64()?,
                nanoseconds: self.read_i64()?,
            }),
            VALUE_POINT => {
                let x = self.read_f64()?;
                let y = self.read_f64()?;
                let z = match self.read_u8()? {
                    0 => None,
                    1 => Some(self.read_f64()?),
                    tag => {
                        return Err(StoreCodecError::Decode(format!(
                            "invalid point z-presence tag {tag}"
                        )));
                    }
                };
                PropertyValue::Point(LoraPoint {
                    x,
                    y,
                    z,
                    srid: self.read_u32()?,
                })
            }
            VALUE_VECTOR => PropertyValue::Vector(self.read_vector()?),
            VALUE_BINARY => PropertyValue::Binary(self.read_binary()?),
            tag => {
                return Err(StoreCodecError::Decode(format!(
                    "invalid property value tag {tag}"
                )));
            }
        })
    }

    fn read_vector(&mut self) -> Result<LoraVector> {
        let dimension = self.read_len()?;
        let values = match self.read_u8()? {
            VECTOR_FLOAT64 => {
                read_vec(self, |reader| reader.read_f64()).map(VectorValues::Float64)?
            }
            VECTOR_FLOAT32 => {
                read_vec(self, |reader| reader.read_f32()).map(VectorValues::Float32)?
            }
            VECTOR_INTEGER64 => {
                read_vec(self, |reader| reader.read_i64()).map(VectorValues::Integer64)?
            }
            VECTOR_INTEGER32 => {
                read_vec(self, |reader| reader.read_i32()).map(VectorValues::Integer32)?
            }
            VECTOR_INTEGER16 => {
                read_vec(self, |reader| reader.read_i16()).map(VectorValues::Integer16)?
            }
            VECTOR_INTEGER8 => {
                read_vec(self, |reader| reader.read_i8()).map(VectorValues::Integer8)?
            }
            tag => {
                return Err(StoreCodecError::Decode(format!(
                    "unknown vector value tag {tag}"
                )))
            }
        };
        if values.len() != dimension {
            return Err(StoreCodecError::Decode(format!(
                "vector dimension mismatch: declared {dimension}, got {}",
                values.len()
            )));
        }
        Ok(LoraVector { dimension, values })
    }

    fn read_binary(&mut self) -> Result<LoraBinary> {
        let len = self.read_len_bounded("binary segment")?;
        let mut segments = self.vec_with_capacity(len, "binary segment")?;
        for _ in 0..len {
            segments.push(self.read_bytes()?.to_vec());
        }
        Ok(LoraBinary::from_segments(segments))
    }
}

fn read_vec<T>(
    reader: &mut Reader<'_>,
    mut read_one: impl FnMut(&mut Reader<'_>) -> Result<T>,
) -> Result<Vec<T>> {
    let len = reader.read_len()?;
    if len > reader.remaining() {
        return Err(StoreCodecError::Decode(format!(
            "vector value count {len} exceeds remaining input"
        )));
    }
    let mut values = reader.vec_with_capacity(len, "vector value")?;
    for _ in 0..len {
        values.push(read_one(reader)?);
    }
    Ok(values)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{IndexConfigValue, StoredIndexEntity, StoredIndexKind};

    /// A hash-backed constraint (G-64) round-trips, and a record written
    /// before backings existed (no high bit) still reads as range-backed.
    #[test]
    fn constraint_backing_round_trips_and_old_records_read_as_range() {
        for (kind, backing) in [
            (StoredConstraintKind::Unique, ConstraintBacking::Hash),
            (StoredConstraintKind::NodeKey, ConstraintBacking::Hash),
            (
                StoredConstraintKind::RelationshipKey,
                ConstraintBacking::Hash,
            ),
            (StoredConstraintKind::Unique, ConstraintBacking::Range),
            (StoredConstraintKind::Existence, ConstraintBacking::Range),
        ] {
            let request = ConstraintRequest {
                name: "c".into(),
                kind: kind.clone(),
                entity: StoredIndexEntity::Node,
                label: "R".into(),
                properties: vec!["k".into()],
                backing,
            };
            let bytes = encode_constraint_request(&request).unwrap();
            assert_eq!(decode_constraint_request(&bytes).unwrap(), request);
            let def = ConstraintDefinition {
                name: "c".into(),
                kind,
                entity: StoredIndexEntity::Node,
                label: "R".into(),
                properties: vec!["k".into()],
                owned_index: Some("c".into()),
                backing,
            };
            let bytes = encode_constraint_definitions(std::slice::from_ref(&def)).unwrap();
            assert_eq!(decode_constraint_definitions(&bytes).unwrap(), vec![def]);
        }
        // The bytes 0.32 wrote for a uniqueness constraint.
        let mut old = Vec::new();
        write_string(&mut old, "c").unwrap();
        old.push(CONSTRAINT_KIND_UNIQUE);
        write_index_entity(&mut old, StoredIndexEntity::Node);
        write_string(&mut old, "R").unwrap();
        write_string_vec(&mut old, &["k".to_string()]).unwrap();
        let read = decode_constraint_request(&old).unwrap();
        assert_eq!(read.kind, StoredConstraintKind::Unique);
        assert_eq!(read.backing, ConstraintBacking::Range);
    }

    fn nested_list(depth: usize) -> PropertyValue {
        (0..depth).fold(PropertyValue::Null, |inner, _| {
            PropertyValue::List(vec![inner])
        })
    }

    /// Bytes for `depth` one-element containers around a null, written
    /// directly so they can exceed what the encoder accepts.
    fn nested_bytes(depth: usize, tag: u8, null: u8, map: bool) -> Vec<u8> {
        let mut out = Vec::new();
        for _ in 0..depth {
            out.push(tag);
            write_len(&mut out, 1).unwrap();
            if map {
                write_string(&mut out, "k").unwrap();
            }
        }
        out.push(null);
        out
    }

    /// A crafted value nested far past the limit fails to decode instead
    /// of overflowing the stack; the limit itself round-trips, and the
    /// encoder refuses one level more.
    #[test]
    fn nesting_is_bounded_on_decode_and_encode() {
        for map in [false, true] {
            let tag = if map { VALUE_MAP } else { VALUE_LIST };
            let err =
                decode_property_value(&nested_bytes(100_000, tag, VALUE_NULL, map)).unwrap_err();
            assert!(err.to_string().contains("more than 128 deep"), "{err}");
            assert!(
                decode_property_value(&nested_bytes(MAX_VALUE_NESTING, tag, VALUE_NULL, map))
                    .is_ok()
            );
            assert!(decode_property_value(&nested_bytes(
                MAX_VALUE_NESTING + 1,
                tag,
                VALUE_NULL,
                map
            ))
            .is_err());
        }
        let deepest = nested_list(MAX_VALUE_NESTING);
        let bytes = encode_property_value(&deepest).unwrap();
        assert_eq!(decode_property_value(&bytes).unwrap(), deepest);
        let err = encode_property_value(&nested_list(MAX_VALUE_NESTING + 1)).unwrap_err();
        assert!(matches!(err, StoreCodecError::Encode(_)), "{err}");

        for map in [false, true] {
            let tag = if map { CONFIG_MAP } else { CONFIG_LIST };
            let mut reader = Reader::new(&[]);
            let bytes = nested_bytes(100_000, tag, CONFIG_NULL, map);
            reader.bytes = &bytes;
            assert!(reader.read_config_value().is_err());
        }
        let config = (0..MAX_VALUE_NESTING + 1).fold(IndexConfigValue::Null, |inner, _| {
            IndexConfigValue::List(vec![inner])
        });
        let mut out = Vec::new();
        assert!(write_config_value(&mut out, &config, 0).is_err());
    }

    /// The in-memory record encoding keeps no limit: a deep value the
    /// graph accepted stays readable instead of failing (or panicking) on
    /// its way in or out.
    #[test]
    fn stored_values_nest_without_a_limit() {
        let deep = nested_list(MAX_VALUE_NESTING + 50);
        let bytes = encode_stored_property_value(&deep).unwrap();
        assert_eq!(decode_stored_property_value(&bytes).unwrap(), deep);

        let mut g = crate::InMemoryGraph::new();
        let mut props = crate::Properties::new();
        props.insert(crate::intern("deep"), deep.clone());
        let id = crate::GraphStorageMut::create_node(&mut g, vec!["N".into()], props).id;
        assert_eq!(
            crate::GraphStorage::node_property(&g, id, "deep"),
            Some(deep)
        );
    }

    #[test]
    fn property_value_roundtrips_nested_values() {
        let value = PropertyValue::Map(BTreeMap::from([
            ("name".into(), PropertyValue::String("Ada".into())),
            (
                "scores".into(),
                PropertyValue::List(vec![PropertyValue::Int(1), PropertyValue::Float(-2.5)]),
            ),
        ]));

        let bytes = encode_property_value(&value).unwrap();
        assert_eq!(decode_property_value(&bytes).unwrap(), value);
    }

    #[test]
    fn datetimes_roundtrip_with_and_without_a_zone() {
        let fixed = LoraDateTime::parse("2026-07-01T12:00:00+02:00").unwrap();
        let zoned = LoraDateTime::parse("2026-07-01T12:00:00+02:00[Europe/Amsterdam]").unwrap();
        for value in [fixed.clone(), zoned] {
            let value = PropertyValue::DateTime(value);
            let bytes = encode_property_value(&value).unwrap();
            assert_eq!(decode_property_value(&bytes).unwrap(), value);
        }
        // A DATETIME without a zone keeps its pre-zone encoding, so data
        // written by earlier versions decodes unchanged.
        let bytes = encode_property_value(&PropertyValue::DateTime(fixed)).unwrap();
        assert_eq!(bytes[0], VALUE_DATE_TIME);
        assert_eq!(bytes.len(), 1 + 8 * 4);
        let mut unknown = vec![VALUE_ZONED_DATE_TIME];
        unknown.extend_from_slice(&bytes[1..]);
        write_string(&mut unknown, "Mars/Olympus").unwrap();
        assert!(decode_property_value(&unknown)
            .unwrap_err()
            .to_string()
            .contains("Mars/Olympus"));
    }

    #[test]
    fn property_value_rejects_oversized_list_length() {
        let mut bytes = vec![VALUE_LIST];
        bytes.extend_from_slice(&u64::MAX.to_le_bytes());

        let err = decode_property_value(&bytes).unwrap_err();
        assert!(matches!(err, StoreCodecError::Decode(_)));
        assert!(err.to_string().contains("exceeds remaining input"));
    }

    #[test]
    fn index_request_roundtrips_options() {
        let request = IndexRequest {
            explicit_name: Some("idx_person_name".into()),
            kind: StoredIndexKind::Text,
            entity: StoredIndexEntity::Node,
            label: Some("Person".into()),
            additional_labels: Vec::new(),
            properties: vec!["name".into()],
            options: BTreeMap::from([(
                "indexConfig".into(),
                IndexConfigValue::Map(BTreeMap::from([(
                    "trigram.min".into(),
                    IndexConfigValue::Integer(3),
                )])),
            )]),
        };

        let bytes = encode_index_request(&request).unwrap();
        assert_eq!(decode_index_request(&bytes).unwrap(), request);
    }

    #[test]
    fn index_definition_vec_roundtrips_state() {
        let defs = vec![IndexDefinition {
            name: "idx_person_age".into(),
            kind: StoredIndexKind::Range,
            entity: StoredIndexEntity::Node,
            label: Some("Person".into()),
            additional_labels: Vec::new(),
            properties: vec!["age".into()],
            options: BTreeMap::new(),
            state: StoredIndexState::Online,
        }];

        let bytes = encode_index_definitions(&defs).unwrap();
        assert_eq!(decode_index_definitions(&bytes).unwrap(), defs);
    }
}