zeppelin-embed 0.2.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
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
#![allow(clippy::expect_used)]

use std::error::Error;
use std::path::PathBuf;
use std::sync::Arc;

use zeppelin_embed::epoch::{
    ComputeUnits, EmbedderError, EmbedderFailure, EmbedderTimeout, EmbeddingEpoch,
    EmbeddingRuntime, EmbeddingTower, EpochIdentity, EpochMismatch, EpochTransitionError,
    Normalization, StoreEpoch,
};
use zeppelin_embed::format::RegistryError;
use zeppelin_embed::format::frame::{FormatCheck, FormatError};
use zeppelin_embed::format::golden::HexError;
use zeppelin_embed::fts::bm25::Bm25Error;
use zeppelin_embed::fts::index::IndexError;
use zeppelin_embed::fts::postings::PostingsError;
use zeppelin_embed::fts::sealed::SealedSegmentError;
use zeppelin_embed::fts::snippet::SnippetError;
use zeppelin_embed::fts::tokenizer::vocab::VocabError;
use zeppelin_embed::fts::tokenizer::{TokenizerConfig, TokenizerError};
use zeppelin_embed::graph::block::GraphNodeError;
use zeppelin_embed::graph::build::GraphBuildError;
use zeppelin_embed::graph::search::{AdaptiveEfError, GraphSearchError};
use zeppelin_embed::ingest::wal_payload::PayloadError;
use zeppelin_embed::ingest::{DocId, IngestError, PurgeError, Revision, StoreLexicalError};
use zeppelin_embed::kernels::GatherShapeError;
use zeppelin_embed::lifecycle::{QueryError, StoreError};
use zeppelin_embed::manifest::ManifestError;
use zeppelin_embed::meta::{BuildError, ColumnId, ColumnType, DictionaryError, EvalError, Schema};
use zeppelin_embed::planner::{FilteredSearchError, LexicalFilterError, PlanError, SegmentBranch};
use zeppelin_embed::quant::{QuantError, QuantScheme, RescoreError};
use zeppelin_embed::scan::{Int8FactorsError, ScanError};
use zeppelin_embed::segment::layout::RegionKind;
use zeppelin_embed::segment::{SegmentError, SegmentId};
use zeppelin_embed::wal::header::WalHeaderError;
use zeppelin_embed::wal::record::{RecordEncodeError, RecordError};
use zeppelin_embed::wal::replay::{CorruptionLocation, CorruptionReason};
use zeppelin_embed::wal::{
    LogSeq, VisibleRecordError, WalReadError, WalRecoveryError, WalRetireError, WalWriteError,
};

fn store_epoch(model: &str, version: &str, tokenizer: TokenizerConfig) -> StoreEpoch {
    let document = EmbeddingTower {
        model_id: model.to_owned(),
        model_version: version.to_owned(),
        weights_digest: vec![0x24, model.len() as u8],
        dims: 4,
        normalization: Normalization::L2,
        prompt_prefix: "document: ".to_owned(),
        max_tokens: 32,
        runtime: EmbeddingRuntime::CpuReference,
        compute_units: ComputeUnits::Cpu,
        os_build: Some("24A24".to_owned()),
    };
    let mut query = document.clone();
    query.prompt_prefix = "query: ".to_owned();
    StoreEpoch {
        embedding: EmbeddingEpoch {
            document,
            query,
            alignment_digest: vec![0xa1, 0x24],
        },
        tokenizer: tokenizer.epoch(),
    }
}

fn assert_contract<E: Error>(error: E, expected: &str, source: Option<&str>) {
    assert_eq!(error.to_string(), expected);
    assert_eq!(error.source().map(ToString::to_string).as_deref(), source);
}

#[test]
fn embedding_and_epoch_transition_errors_preserve_every_actionable_value() {
    let epoch_a = store_epoch("model-a", "1", TokenizerConfig::text_default());
    let epoch_b = store_epoch("model-b", "2", TokenizerConfig::code());
    assert_eq!(epoch_a.embedding.document.model_label(), "model-a@1");
    assert_eq!(
        epoch_a.identity().embedding.to_hex(),
        epoch_a.identity().embedding.to_string()
    );

    let failure = EmbedderFailure::new("delegate rejected revision 7");
    assert_eq!(failure.detail(), "delegate rejected revision 7");
    let failure = EmbedderError::from(failure);
    assert_contract(
        failure,
        "embedding delegate failed: delegate rejected revision 7",
        Some("embedding delegate failed: delegate rejected revision 7"),
    );
    let timeout = EmbedderTimeout::new("deadline 25 ms");
    assert_eq!(timeout.detail(), "deadline 25 ms");
    let timeout = EmbedderError::from(timeout);
    assert_contract(
        timeout,
        "embedding delegate timed out: deadline 25 ms",
        Some("embedding delegate timed out: deadline 25 ms"),
    );

    let both = EpochMismatch {
        expected: epoch_a.identity(),
        declared: epoch_b.identity(),
    };
    assert!(
        both.to_string()
            .starts_with("embedding and tokenizer epochs differ:")
    );
    let embedding_only = EpochMismatch {
        expected: epoch_a.identity(),
        declared: EpochIdentity {
            embedding: epoch_b.identity().embedding,
            tokenizer: epoch_a.identity().tokenizer,
        },
    };
    assert!(
        embedding_only
            .to_string()
            .starts_with("embedding epoch differs:")
    );
    let tokenizer_only = EpochMismatch {
        expected: epoch_a.identity(),
        declared: EpochIdentity {
            embedding: epoch_a.identity().embedding,
            tokenizer: epoch_b.identity().tokenizer,
        },
    };
    assert!(
        tokenizer_only
            .to_string()
            .starts_with("tokenizer epoch differs:")
    );
    assert_eq!(
        EpochMismatch {
            expected: epoch_a.identity(),
            declared: epoch_a.identity(),
        }
        .to_string(),
        "embedding and tokenizer epochs match"
    );

    let target = epoch_b.identity();
    let segment_id = SegmentId::new(24, [0x24; 10]);
    let cases = vec![
        (
            EpochTransitionError::EpochUnavailable { target },
            format!(
                "epoch alias ({}, {}) has no retained segment set",
                target.embedding, target.tokenizer
            ),
        ),
        (
            EpochTransitionError::IncompleteEpoch {
                target,
                missing_documents: 2,
                unexpected_documents: 3,
            },
            format!(
                "epoch alias ({}, {}) is incomplete: 2 published revisions missing and 3 unexpected target revisions",
                target.embedding, target.tokenizer
            ),
        ),
        (
            EpochTransitionError::MissingDocumentIdentity {
                epoch: target.embedding,
                segment_id,
                row: 7,
            },
            format!(
                "embedding epoch {} segment {segment_id} live row 7 has no document identity",
                target.embedding
            ),
        ),
        (
            EpochTransitionError::EmbeddingEpochUnavailable {
                target: target.embedding,
            },
            format!("embedding epoch {} has no retained segments", target.embedding),
        ),
        (
            EpochTransitionError::PublishedEpoch {
                target: target.embedding,
            },
            format!(
                "published embedding epoch {} cannot be dropped",
                target.embedding
            ),
        ),
        (
            EpochTransitionError::UnsealedWrites {
                active_rows: 4,
                absorbed_through: 11,
                durable_end: 13,
            },
            "epoch transition requires a sealed WAL: active rows 4, manifest absorbed through 11, durable WAL end 13".to_owned(),
        ),
        (
            EpochTransitionError::ReclaimedBytesOverflow,
            "dropped epoch segment bytes exceed u64".to_owned(),
        ),
    ];
    for (error, expected) in cases {
        assert_contract(error, &expected, None);
    }
    assert_contract(
        EpochTransitionError::Store(StoreError::Closed),
        "store is closed",
        Some("store is closed"),
    );
}

#[test]
fn store_errors_name_the_failed_boundary_without_hiding_sources() {
    let path = PathBuf::from("store.ze");
    let simple = vec![
        (
            StoreError::NotDirectory { path: path.clone() },
            "store path is not a directory: store.ze".to_owned(),
        ),
        (
            StoreError::StoreBusy { path: path.clone() },
            "store already has a writer: store.ze".to_owned(),
        ),
        (
            StoreError::EpochUndeclared,
            "store epoch is persisted but the caller declared none".to_owned(),
        ),
        (
            StoreError::EpochUnstamped,
            "store manifest predates epoch identity and cannot adopt a declaration".to_owned(),
        ),
        (
            StoreError::BudgetExceeded {
                needed: 25,
                budget: 24,
                component: "active vectors",
            },
            "store active vectors allocation needs 25 bytes, budget is 24 bytes".to_owned(),
        ),
        (
            StoreError::AllocationFailed {
                needed: 25,
                component: "query pool",
            },
            "store query pool allocator rejected 25 bytes".to_owned(),
        ),
        (
            StoreError::DimensionMismatch {
                expected: 4,
                actual: 3,
            },
            "active vector dimension 3 does not match 4".to_owned(),
        ),
        (
            StoreError::EmptyActiveSegment,
            "active segment is empty".to_owned(),
        ),
        (
            StoreError::SealCancelled,
            "seal was cancelled before commit".to_owned(),
        ),
        (StoreError::ReadOnly, "store handle is read-only".to_owned()),
        (
            StoreError::GenerationOverflow,
            "store snapshot generation overflow".to_owned(),
        ),
        (
            StoreError::PurgeRecovery {
                detail: "intent checksum".to_owned(),
            },
            "physical purge recovery failed: intent checksum".to_owned(),
        ),
        (StoreError::Closing, "store is closing".to_owned()),
        (StoreError::Closed, "store is closed".to_owned()),
        (
            StoreError::BackgroundHandshake,
            "store lifecycle thread startup handshake failed".to_owned(),
        ),
        (
            StoreError::BackgroundThreadPanicked,
            "store lifecycle thread panicked".to_owned(),
        ),
        (
            StoreError::QueryPoolHandshake,
            "store query worker startup handshake failed".to_owned(),
        ),
        (
            StoreError::QueryPoolThreadPanicked,
            "store query worker panicked".to_owned(),
        ),
        (
            StoreError::QueryPoolCapacity {
                source: "no physical cores".to_owned(),
            },
            "store query worker capacity failed: no physical cores".to_owned(),
        ),
        (
            StoreError::Synchronization {
                component: "snapshot",
            },
            "store lifecycle synchronization poisoned: snapshot".to_owned(),
        ),
    ];
    for (error, expected) in simple {
        assert_contract(error, &expected, None);
    }

    assert_contract(
        StoreError::Io {
            path,
            source: std::io::Error::other("disk offline"),
        },
        "store I/O store.ze: disk offline",
        Some("disk offline"),
    );
    assert_contract(
        StoreError::Statistics {
            component: "resident bytes",
            source: std::io::Error::other("mincore failed"),
        },
        "store statistics resident bytes: mincore failed",
        Some("mincore failed"),
    );
    assert_contract(
        StoreError::QueryPoolStart {
            source: std::io::Error::other("thread quota"),
        },
        "store query worker could not start: thread quota",
        Some("thread quota"),
    );

    let schema = Schema::timestamp_only();
    let mismatch = StoreError::SchemaMismatch {
        persisted: schema.clone(),
        declared: schema,
    };
    assert!(mismatch.to_string().starts_with("declared store schema"));
    assert!(mismatch.source().is_none());
}

#[test]
fn wal_errors_keep_framing_ranges_sequences_and_source_chains() {
    let record = RecordError::BodyTruncated {
        payload_length: 9,
        needed: 35,
        available: 30,
    };
    assert_contract(
        VisibleRecordError::Record(record),
        "visible WAL record: WAL payload length 9 needs 35 framed bytes, got 30",
        Some("WAL payload length 9 needs 35 framed bytes, got 30"),
    );
    assert_contract(
        VisibleRecordError::InvalidEncodedRange {
            start: 4,
            end: 17,
            available: 12,
        },
        "visible WAL encoded range 4..17 exceeds 12 bytes",
        None,
    );

    let writes = vec![
        (
            WalWriteError::NonEmptyWal { length: 41 },
            "WAL path is not empty: 41 bytes".to_owned(),
        ),
        (
            WalWriteError::RecoveredBytesOverflow,
            "recovered WAL record bytes overflow usize".to_owned(),
        ),
        (
            WalWriteError::GroupTooLarge {
                encoded_bytes: 25,
                max_group_bytes: 24,
            },
            "WAL group needs 25 bytes, exceeding 24".to_owned(),
        ),
        (
            WalWriteError::SequenceExhausted,
            "WAL sequence space exhausted".to_owned(),
        ),
        (
            WalWriteError::Header(RegistryError::UnknownFamily(99)),
            "WAL header: unknown format family 99".to_owned(),
        ),
        (
            WalWriteError::Record(RecordEncodeError::PayloadTooLarge(usize::MAX)),
            format!("WAL record: WAL payload length {} exceeds u32", usize::MAX),
        ),
        (
            WalWriteError::Poisoned("commit queue"),
            "commit queue poisoned".to_owned(),
        ),
        (
            WalWriteError::Failed {
                kind: std::io::ErrorKind::BrokenPipe,
                detail: Arc::<str>::from("flush broke"),
            },
            "WAL writer failed with BrokenPipe: flush broke".to_owned(),
        ),
    ];
    for (error, expected) in writes {
        assert_eq!(error.to_string(), expected);
    }

    assert_contract(
        WalRetireError::BeyondDurable {
            requested: LogSeq::new(9),
            durable_end: Some(LogSeq::new(8)),
        },
        "cannot retire WAL sequence 9 past durable end 8",
        None,
    );
    assert_contract(
        WalRetireError::BeyondDurable {
            requested: LogSeq::new(1),
            durable_end: None,
        },
        "cannot retire WAL sequence 1 before any sequence is durable",
        None,
    );
    assert_contract(
        WalRetireError::Writer(WalWriteError::SequenceExhausted),
        "cannot retire visible WAL records: WAL sequence space exhausted",
        Some("WAL sequence space exhausted"),
    );

    assert_contract(
        WalRecoveryError::MissingFile,
        "WAL recovery path is missing",
        None,
    );
    assert_contract(
        WalRecoveryError::InvalidHeader(WalHeaderError::Missing),
        "WAL recovery header: WAL file header is missing",
        Some("WAL file header is missing"),
    );
    let reason = CorruptionReason::SequenceGap {
        expected: LogSeq::new(4),
        actual: LogSeq::new(7),
        location: CorruptionLocation::Middle,
    };
    assert_contract(
        WalRecoveryError::CorruptAt { offset: 40, reason },
        &format!("WAL recovery stopped at byte 40: {reason:?}"),
        None,
    );

    assert_contract(
        WalReadError::Io(std::io::Error::other("read failed")),
        "WAL read: read failed",
        Some("read failed"),
    );
    assert_contract(
        WalReadError::Header(WalHeaderError::NonZeroFileLength { actual: 8 }),
        "WAL read header: WAL file length must be zero, got 8",
        Some("WAL file length must be zero, got 8"),
    );
    assert_contract(
        WalReadError::InvalidRecoveredRange {
            start: 40,
            end: 70,
            available: 64,
        },
        "WAL recovered range 40..70 exceeds 64 bytes",
        None,
    );
}

#[test]
fn persisted_registry_header_and_manifest_errors_are_exact_and_typed() {
    let registry = [
        (RegistryError::UnknownFamily(24), "unknown format family 24"),
        (
            RegistryError::UnsupportedVersion {
                family: 10,
                version: 3,
                minimum: 1,
                maximum: 2,
            },
            "format family 10 version 3 is outside accepted range 1..=2",
        ),
        (
            RegistryError::RetiredScheme(3),
            "quantization scheme id 3 is permanently retired",
        ),
        (
            RegistryError::UnknownScheme(9),
            "unknown quantization scheme 9",
        ),
    ];
    for (error, expected) in registry {
        assert_eq!(error.to_string(), expected);
    }

    let headers = vec![
        (
            WalHeaderError::Missing,
            "WAL file header is missing".to_owned(),
        ),
        (
            WalHeaderError::Truncated {
                needed: 40,
                available: 31,
            },
            "WAL file header needs 40 bytes, got 31".to_owned(),
        ),
        (
            WalHeaderError::WrongMagic {
                expected: *b"ZEPEMBED",
                actual: *b"NOPEMAGC",
            },
            format!(
                "WAL magic expected {:?}, got {:?}",
                *b"ZEPEMBED", *b"NOPEMAGC"
            ),
        ),
        (
            WalHeaderError::WrongFamily {
                expected: 11,
                actual: 10,
            },
            "WAL family expected 11, got 10".to_owned(),
        ),
        (
            WalHeaderError::UnsupportedVersion {
                family: 11,
                version: 2,
                minimum: 1,
                maximum: 1,
            },
            "WAL family 11 version 2 is outside accepted range 1..=1".to_owned(),
        ),
        (
            WalHeaderError::InvalidHeaderLength {
                expected: 40,
                actual: 32,
            },
            "WAL header length expected 40, got 32".to_owned(),
        ),
        (
            WalHeaderError::NonZeroFileLength { actual: 9 },
            "WAL file length must be zero, got 9".to_owned(),
        ),
        (
            WalHeaderError::InvalidSharedHeader {
                check: FormatCheck::HeaderLength,
            },
            "WAL shared header failed HeaderLength".to_owned(),
        ),
    ];
    for (error, expected) in headers {
        assert_eq!(error.to_string(), expected);
    }

    let epoch = store_epoch("manifest", "1", TokenizerConfig::text_default()).identity();
    let segment = SegmentId::new(25, [0x25; 10]);
    let manifests = vec![
        (
            ManifestError::Decode("epoch count overflow".to_owned()),
            "manifest decode failed: epoch count overflow".to_owned(),
        ),
        (
            ManifestError::AheadOfLog {
                snapshot: 9,
                durable: 8,
            },
            "manifest log sequence 9 is ahead of durable WAL end 8".to_owned(),
        ),
        (
            ManifestError::UnknownEpochAlias { alias: epoch },
            format!(
                "manifest epoch alias ({}, {}) does not name a registry entry",
                epoch.embedding, epoch.tokenizer
            ),
        ),
        (
            ManifestError::UnknownSegmentEpoch {
                segment,
                epoch: epoch.embedding,
            },
            format!(
                "manifest segment {segment} names unknown embedding epoch {}",
                epoch.embedding
            ),
        ),
    ];
    for (error, expected) in manifests {
        assert_contract(error, &expected, None);
    }
    assert_contract(
        ManifestError::Format(FormatError::new(
            "manifest.ze",
            FormatCheck::FileChecksum,
            "mismatch",
        )),
        "artifact manifest.ze failed FileChecksum: mismatch",
        Some("artifact manifest.ze failed FileChecksum: mismatch"),
    );
}

fn assert_error_fragment<E: Error>(error: E, fragment: &str, has_source: bool) {
    assert!(
        error.to_string().contains(fragment),
        "error did not preserve {fragment:?}: {error}"
    );
    assert_eq!(
        error.source().is_some(),
        has_source,
        "wrong source for {error}"
    );
}

#[test]
fn planner_metadata_and_ingest_errors_preserve_the_rejected_values() {
    let column = ColumnId::new(24);
    let plan = vec![
        (
            PlanError::UnknownColumn(column),
            "unknown column 24".to_owned(),
        ),
        (
            PlanError::TypeMismatch {
                column,
                expected: ColumnType::U64,
                actual: ColumnType::RawString,
            },
            "column 24 expects U64, received RawString".to_owned(),
        ),
        (
            PlanError::RangeRequiresNumericColumn(column),
            "column 24 is not numeric".to_owned(),
        ),
        (
            PlanError::RowCountMismatch {
                columns: 3,
                alive: 2,
            },
            "column row count 3 differs from alive row count 2".to_owned(),
        ),
    ];
    for (error, expected) in plan {
        assert_contract(error, &expected, None);
    }

    let eval = vec![
        EvalError::RowCountMismatch {
            columns: 4,
            alive: 5,
        },
        EvalError::UnknownColumn(column),
        EvalError::TypeMismatch {
            column,
            expected: ColumnType::Bool,
            actual: ColumnType::I64,
        },
        EvalError::RangeRequiresNumericColumn(column),
    ];
    for error in eval {
        assert!(error.to_string().contains('4') || error.to_string().contains("column 24"));
    }

    assert_error_fragment(
        FilteredSearchError::Plan(PlanError::UnknownColumn(column)),
        "unknown column 24",
        true,
    );
    assert_error_fragment(
        FilteredSearchError::Query(QueryError::Cancelled { partial: false }),
        "query was cancelled (partial=false)",
        true,
    );
    assert_error_fragment(
        FilteredSearchError::ActiveMetadata("row 24".to_owned()),
        "active metadata construction failed: row 24",
        false,
    );
    assert_error_fragment(
        FilteredSearchError::PlanReportMismatch {
            reported: SegmentBranch::ExactAllowList,
            executed: SegmentBranch::MaskedScan,
        },
        "reported branch ExactAllowList differs from executed branch MaskedScan",
        false,
    );
    assert_error_fragment(
        FilteredSearchError::InvalidPlanNode("fusion entered vector execution"),
        "invalid vector plan node: fusion entered vector execution",
        false,
    );

    assert_error_fragment(
        LexicalFilterError::SegmentCount {
            expected: 3,
            actual: 2,
        },
        "supplied 2 segment bitmaps, expected 3",
        false,
    );
    assert_error_fragment(
        LexicalFilterError::RowOutOfRange {
            segment: 1,
            row: 9,
            row_count: 8,
        },
        "row 9 is outside segment 1 row count 8",
        false,
    );
    assert_error_fragment(
        LexicalFilterError::Index(IndexError::RowsNotAscending { row: 7 }),
        "documents must arrive in row order; got 7",
        true,
    );

    let build = vec![
        BuildError::UnknownColumn(column),
        BuildError::DuplicateColumn(column),
        BuildError::MissingRequiredColumn(column),
        BuildError::TimestampProvidedAsInput,
        BuildError::TypeMismatch {
            column,
            expected: ColumnType::F64,
            actual: ColumnType::Bool,
        },
        BuildError::TooManyRows,
    ];
    for error in build {
        assert!(!error.to_string().is_empty());
    }

    let epoch_a = store_epoch("ingest-a", "1", TokenizerConfig::text_default());
    let epoch_b = store_epoch("ingest-b", "2", TokenizerConfig::code());
    let ingest = vec![
        IngestError::Store(StoreError::ReadOnly),
        IngestError::EmptyBatch,
        IngestError::EpochMismatch(EpochMismatch {
            expected: epoch_a.identity(),
            declared: epoch_b.identity(),
        }),
        IngestError::EpochUndeclared,
        IngestError::EpochUnstamped,
        IngestError::StaleRevision {
            doc_id: DocId::new(24),
            current: Revision::new(7),
            attempted: Revision::new(6),
        },
        IngestError::Vector(QuantError::NonFinite { index: 3 }),
        IngestError::Lexical(IndexError::RowsNotAscending { row: 4 }),
        IngestError::Tokenizer(TokenizerError::InvalidUtf8 { offset: 5 }),
        IngestError::Columns(BuildError::DuplicateColumn(column)),
        IngestError::Payload(PayloadError::TrailingBytes(9)),
    ];
    for error in ingest {
        assert!(!error.to_string().is_empty());
        assert_eq!(
            error.source().is_some(),
            !matches!(
                error,
                IngestError::EmptyBatch
                    | IngestError::EpochUndeclared
                    | IngestError::EpochUnstamped
                    | IngestError::StaleRevision { .. }
            )
        );
    }

    let segment_id = SegmentId::new(24, [0x42; 10]);
    assert_error_fragment(
        StoreLexicalError::Query(QueryError::Timeout { partial: false }),
        "query deadline expired (partial=false)",
        true,
    );
    assert_error_fragment(
        StoreLexicalError::Lexical(LexicalFilterError::SegmentCount {
            expected: 2,
            actual: 1,
        }),
        "supplied 1 segment bitmaps, expected 2",
        true,
    );
    assert_error_fragment(
        StoreLexicalError::MissingDocumentIdentity { segment_id },
        &format!("sealed lexical segment {segment_id} has no document identity"),
        false,
    );
}

#[test]
fn scan_rescore_segment_graph_and_purge_errors_preserve_geometry_and_sources() {
    let scans = vec![
        ScanError::ZeroDimension,
        ScanError::RowDataLength {
            dimension: 4,
            actual: 7,
        },
        ScanError::SchemeMismatch {
            query: QuantScheme::F32,
            rows: QuantScheme::Bit4,
        },
        ScanError::FactorCount {
            expected: 3,
            actual: 2,
        },
        ScanError::NonFiniteInput { index: 5 },
        ScanError::NonFiniteScore { row_id: 6 },
        ScanError::Quant(QuantError::CodeLength {
            expected: 4,
            actual: 3,
        }),
        ScanError::ArithmeticOverflow,
        ScanError::WorkerPanicked,
        ScanError::CpuCount("no physical cores".to_owned()),
        ScanError::Timeout { partial: false },
        ScanError::Cancelled { partial: false },
        ScanError::ReadCancelled { partial: false },
    ];
    for error in scans {
        assert!(!error.to_string().is_empty());
    }

    let rescore = vec![
        RescoreError::ZeroDimension,
        RescoreError::QueryDimension {
            expected: 4,
            actual: 3,
        },
        RescoreError::RowDataLength {
            dimension: 4,
            actual: 7,
        },
        RescoreError::CoarseScoreCount {
            expected: 3,
            actual: 2,
        },
        RescoreError::CandidateRowCount {
            expected: 3,
            actual: 2,
        },
        RescoreError::CandidateRowOutOfRange {
            position: 1,
            row_index: 9,
            row_count: 8,
        },
        RescoreError::ZeroK,
        RescoreError::ZeroOversample,
        RescoreError::NonFiniteCoarseScore { index: 2 },
        RescoreError::NonFiniteExactScore { row_index: 3 },
        RescoreError::InsufficientCandidates {
            k: 4,
            candidates: 3,
        },
        RescoreError::ArithmeticOverflow,
    ];
    for error in rescore {
        assert!(!error.to_string().is_empty());
    }

    let segment_a = SegmentId::new(24, [0x24; 10]);
    let segment_b = SegmentId::new(25, [0x25; 10]);
    let segments = vec![
        SegmentError::Io {
            path: PathBuf::from("segment.ze"),
            source: std::io::Error::other("read failed"),
        },
        SegmentError::Format(FormatError::new(
            "segment.ze",
            FormatCheck::FileChecksum,
            "expected 24, got 25",
        )),
        SegmentError::WrongObject {
            artifact: "segment.ze".to_owned(),
            expected: segment_a,
            actual: segment_b,
        },
        SegmentError::MissingRegion(RegionKind::VectorRescore),
        SegmentError::Geometry("row stride 3".to_owned()),
        SegmentError::Columns("column count 2".to_owned()),
        SegmentError::Alive("row count 3".to_owned()),
        SegmentError::Graph(GraphNodeError::InvalidHeader("flags 1".to_owned())),
        SegmentError::Postings(SealedSegmentError::Geometry("span offset")),
    ];
    for error in segments {
        assert!(!error.to_string().is_empty());
        assert_eq!(
            error.source().is_some(),
            matches!(
                error,
                SegmentError::Io { .. }
                    | SegmentError::Format(_)
                    | SegmentError::Graph(_)
                    | SegmentError::Postings(_)
            )
        );
    }

    let adaptive = vec![
        AdaptiveEfError::ZeroK,
        AdaptiveEfError::KExceedsRows { k: 5, rows: 4 },
        AdaptiveEfError::ExplicitBelowK { k: 5, ef: 4 },
        AdaptiveEfError::ExplicitExceedsRows { ef: 6, rows: 5 },
        AdaptiveEfError::ArithmeticOverflow,
    ];
    for error in adaptive {
        assert!(!error.to_string().is_empty());
    }
    let searches = vec![
        GraphSearchError::Geometry("dimension 3".to_owned()),
        GraphSearchError::Graph(GraphNodeError::NodeIdOutOfRange {
            node_id: 5,
            node_count: 4,
        }),
        GraphSearchError::Quant(QuantError::EmptyVector),
        GraphSearchError::AdaptiveEf(AdaptiveEfError::ExplicitBelowK { k: 2, ef: 1 }),
        GraphSearchError::Rescore(RescoreError::ZeroK),
        GraphSearchError::VisitedCapExceeded {
            visited: 25,
            cap: 24,
        },
        GraphSearchError::Cancelled { partial: false },
        GraphSearchError::Timeout { partial: false },
        GraphSearchError::ReadCancelled { partial: false },
        GraphSearchError::Scan(ScanError::ArithmeticOverflow),
    ];
    for error in searches {
        assert!(!error.to_string().is_empty());
        assert_eq!(
            error.source().is_some(),
            matches!(
                error,
                GraphSearchError::Graph(_)
                    | GraphSearchError::Quant(_)
                    | GraphSearchError::AdaptiveEf(_)
                    | GraphSearchError::Rescore(_)
                    | GraphSearchError::Scan(_)
            )
        );
    }

    let builds = vec![
        GraphBuildError::CheckpointIo {
            path: PathBuf::from("graph.ckpt"),
            source: std::io::Error::other("write failed"),
        },
        GraphBuildError::CheckpointCorrupt("row 24".to_owned()),
        GraphBuildError::BudgetExhausted { rows_completed: 24 },
        GraphBuildError::Cancelled { partial: false },
        GraphBuildError::Timeout { partial: false },
        GraphBuildError::ReadCancelled { partial: false },
        GraphBuildError::Quant(QuantError::NonFinite { index: 2 }),
        GraphBuildError::NodeBlock(GraphNodeError::ArithmeticOverflow),
        GraphBuildError::Geometry("node count 0".to_owned()),
        GraphBuildError::NodeIdOutOfRange {
            node_id: 25,
            node_count: 24,
        },
        GraphBuildError::Store(StoreError::BudgetExceeded {
            needed: 25,
            budget: 24,
            component: "graph arena",
        }),
    ];
    for error in builds {
        assert!(!error.to_string().is_empty());
        assert_eq!(
            error.source().is_some(),
            matches!(
                error,
                GraphBuildError::CheckpointIo { .. }
                    | GraphBuildError::Quant(_)
                    | GraphBuildError::NodeBlock(_)
                    | GraphBuildError::Store(_)
            )
        );
    }

    let purges = vec![
        PurgeError::Store(StoreError::ReadOnly),
        PurgeError::InsufficientTempSpace {
            segment_bytes: 100,
            available_bytes: 119,
            required_bytes: 120,
        },
        PurgeError::PurgeInProgress,
        PurgeError::UnknownToken { token_id: 24 },
        PurgeError::IntentFormat(FormatError::new(
            "purge.ze",
            FormatCheck::Magic,
            "wrong magic",
        )),
        PurgeError::IntentDecode("unknown version 2".to_owned()),
        PurgeError::WalPayload(PayloadError::UnknownOperation(24)),
    ];
    for error in purges {
        assert!(!error.to_string().is_empty());
        assert_eq!(
            error.source().is_some(),
            matches!(
                error,
                PurgeError::Store(_) | PurgeError::IntentFormat(_) | PurgeError::WalPayload(_)
            )
        );
    }

    assert_eq!(
        PostingsError::BadMagic.to_string(),
        "posting stream magic did not match"
    );
}

#[test]
fn lexical_payload_and_kernel_error_matrices_name_every_rejected_boundary() {
    let payloads = vec![
        PayloadError::UnknownOperation(24),
        PayloadError::LengthOverflow,
        PayloadError::Truncated,
        PayloadError::Version(2),
        PayloadError::Flags(0x24),
        PayloadError::Reserved(0x24),
        PayloadError::EmptyVector,
        PayloadError::EmptyDelete,
        PayloadError::NonFiniteVector { index: 3 },
        PayloadError::ValueKind(9),
        PayloadError::ValueLength {
            kind: 2,
            expected: 8,
            actual: 7,
        },
        PayloadError::Boolean(2),
        PayloadError::Utf8,
        PayloadError::TrailingBytes(5),
        PayloadError::FieldBitmap(0x8000_0000),
        PayloadError::Lexical("bad position".to_owned()),
        PayloadError::Columns("duplicate column".to_owned()),
    ];
    let payload_fragments = [
        "operation 24",
        "length overflow",
        "truncated",
        "version 2",
        "0x0024",
        "0x000024",
        "vector is empty",
        "document list is empty",
        "coordinate 3",
        "kind 9",
        "needs 8 bytes, got 7",
        "Boolean byte 2",
        "not valid UTF-8",
        "5 trailing bytes",
        "0x80000000",
        "bad position",
        "duplicate column",
    ];
    for (error, fragment) in payloads.into_iter().zip(payload_fragments) {
        assert_error_fragment(error, fragment, false);
    }

    let postings = vec![
        PostingsError::Truncated {
            needed: 8,
            available: 7,
        },
        PostingsError::BadMagic,
        PostingsError::UnsupportedVersion { found: 3 },
        PostingsError::BitWidthTooLarge { bits: 33 },
        PostingsError::ZeroBlockSize,
        PostingsError::DocidsNotAscending { docid: 24 },
        PostingsError::PositionsNotAscending { position: 25 },
        PostingsError::ZeroTermFrequency,
        PostingsError::InconsistentPostingCount {
            declared: 8,
            described: 7,
        },
    ];
    let posting_fragments = [
        "needed 8 bytes, had 7",
        "magic did not match",
        "version 3",
        "bit width 33",
        "block size was zero",
        "ascending at 24",
        "ascending at 25",
        "zero term frequency",
        "declares 8 postings, blocks describe 7",
    ];
    for (error, fragment) in postings.into_iter().zip(posting_fragments) {
        assert_error_fragment(error, fragment, false);
    }

    let indexes = vec![
        IndexError::Postings(PostingsError::BadMagic),
        IndexError::Stats(Bm25Error::NoTokens),
        IndexError::RowsNotAscending { row: 24 },
        IndexError::LiveRowOutOfRange {
            segment: 2,
            row: 9,
            row_count: 8,
        },
        IndexError::LiveLengthMissing { segment: 3, row: 7 },
    ];
    let index_fragments = [
        "postings rejected",
        "at least one analyzed token",
        "got 24",
        "row 9 is outside segment 2 row count 8",
        "row 7 has no length counter in segment 3",
    ];
    for (error, fragment) in indexes.into_iter().zip(index_fragments) {
        assert_error_fragment(error, fragment, false);
    }

    let vocab = vec![
        VocabError::EmptyCanonicalTerm,
        VocabError::EmptySurfaceForm {
            canonical: "zed".to_owned(),
        },
        VocabError::SurfaceFormTooLong {
            canonical: "zed".to_owned(),
            terms: 9,
        },
        VocabError::ConflictingSurfaceForm {
            surface: "z e".to_owned(),
            existing: "zed".to_owned(),
            attempted: "zee".to_owned(),
        },
    ];
    for error in vocab {
        assert!(!error.to_string().is_empty());
    }

    for (error, expected) in [
        (
            SnippetError::FieldNotStored,
            "field is not stored, so it has no match offsets",
        ),
        (
            SnippetError::ZeroWindow,
            "snippet window length must be positive",
        ),
    ] {
        assert_contract(error, expected, None);
    }
    for (error, expected) in [
        (
            HexError::OddLength,
            "golden hex has an odd number of nibbles",
        ),
        (
            HexError::InvalidDigit(b'x'),
            "golden hex contains invalid byte 120",
        ),
    ] {
        assert_contract(error, expected, None);
    }
    for error in [
        GatherShapeError::DimensionTooLarge {
            actual: 65_536,
            maximum: 65_535,
        },
        GatherShapeError::RowBytes {
            expected: 64,
            actual: 63,
        },
        GatherShapeError::RowLength {
            index: 3,
            expected: 64,
            actual: 63,
        },
    ] {
        assert!(!error.to_string().is_empty());
    }
    for (error, expected) in [
        (
            Int8FactorsError::NonFiniteScale,
            "Int8 row scale must be finite",
        ),
        (
            Int8FactorsError::NegativeScale,
            "Int8 row scale must not be negative",
        ),
        (
            Int8FactorsError::NonFiniteOffset,
            "Int8 row offset must be finite",
        ),
    ] {
        assert_contract(error, expected, None);
    }
    for (error, expected) in [
        (
            DictionaryError::CardinalityOverflow,
            "dictionary cardinality exceeds u32",
        ),
        (
            DictionaryError::StringStorageOverflow,
            "string storage exceeds u32",
        ),
    ] {
        assert_contract(error, expected, None);
    }
}

#[test]
fn public_error_conversions_keep_their_original_typed_causes() {
    assert!(matches!(
        BuildError::from(DictionaryError::StringStorageOverflow),
        BuildError::Dictionary(DictionaryError::StringStorageOverflow)
    ));
    assert!(matches!(
        TokenizerError::from(VocabError::EmptyCanonicalTerm),
        TokenizerError::Vocab(VocabError::EmptyCanonicalTerm)
    ));
    assert!(matches!(
        IndexError::from(PostingsError::BadMagic),
        IndexError::Postings(PostingsError::BadMagic)
    ));
    assert!(matches!(
        IndexError::from(Bm25Error::EmptyCorpus),
        IndexError::Stats(Bm25Error::EmptyCorpus)
    ));
    assert!(matches!(
        SealedSegmentError::from(PostingsError::ZeroBlockSize),
        SealedSegmentError::Postings(PostingsError::ZeroBlockSize)
    ));
    assert!(matches!(
        SegmentError::from(FormatError::new("x", FormatCheck::Length, "short")),
        SegmentError::Format(_)
    ));
    assert!(matches!(
        SegmentError::from(GraphNodeError::ArithmeticOverflow),
        SegmentError::Graph(GraphNodeError::ArithmeticOverflow)
    ));
    assert!(matches!(
        SegmentError::from(SealedSegmentError::Geometry("short")),
        SegmentError::Postings(SealedSegmentError::Geometry("short"))
    ));

    assert!(matches!(
        GraphSearchError::from(GraphNodeError::ArithmeticOverflow),
        GraphSearchError::Graph(GraphNodeError::ArithmeticOverflow)
    ));
    assert!(matches!(
        GraphSearchError::from(QuantError::EmptyVector),
        GraphSearchError::Quant(QuantError::EmptyVector)
    ));
    assert!(matches!(
        GraphSearchError::from(GatherShapeError::RowBytes {
            expected: 2,
            actual: 1,
        }),
        GraphSearchError::Gather(GatherShapeError::RowBytes {
            expected: 2,
            actual: 1,
        })
    ));
    assert!(matches!(
        GraphSearchError::from(AdaptiveEfError::ZeroK),
        GraphSearchError::AdaptiveEf(AdaptiveEfError::ZeroK)
    ));
    assert!(matches!(
        GraphSearchError::from(RescoreError::ZeroK),
        GraphSearchError::Rescore(RescoreError::ZeroK)
    ));

    assert!(matches!(
        GraphBuildError::from(SegmentError::Geometry("rows".to_owned())),
        GraphBuildError::Segment(SegmentError::Geometry(_))
    ));
    assert!(matches!(
        GraphBuildError::from(QuantError::EmptyVector),
        GraphBuildError::Quant(QuantError::EmptyVector)
    ));
    assert!(matches!(
        GraphBuildError::from(GraphNodeError::ArithmeticOverflow),
        GraphBuildError::NodeBlock(GraphNodeError::ArithmeticOverflow)
    ));
    assert!(matches!(
        GraphBuildError::from(StoreError::ReadOnly),
        GraphBuildError::Store(StoreError::ReadOnly)
    ));

    assert!(matches!(
        FilteredSearchError::from(PlanError::UnknownColumn(ColumnId::new(9))),
        FilteredSearchError::Plan(PlanError::UnknownColumn(column))
            if column == ColumnId::new(9)
    ));
    assert!(matches!(
        FilteredSearchError::from(QueryError::Cancelled { partial: false }),
        FilteredSearchError::Query(QueryError::Cancelled { partial: false })
    ));
    assert!(matches!(
        PurgeError::from(StoreError::ReadOnly),
        PurgeError::Store(StoreError::ReadOnly)
    ));
    assert!(matches!(
        IngestError::from(StoreError::ReadOnly),
        IngestError::Store(StoreError::ReadOnly)
    ));
    assert!(matches!(
        StoreLexicalError::from(QueryError::Timeout { partial: false }),
        StoreLexicalError::Query(QueryError::Timeout { partial: false })
    ));
    assert!(matches!(
        StoreLexicalError::from(StoreError::ReadOnly),
        StoreLexicalError::Query(QueryError::Store(StoreError::ReadOnly))
    ));
    assert!(matches!(
        StoreLexicalError::from(LexicalFilterError::SegmentCount {
            expected: 2,
            actual: 1,
        }),
        StoreLexicalError::Lexical(LexicalFilterError::SegmentCount {
            expected: 2,
            actual: 1,
        })
    ));
}