itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
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
//! The attribute index: one sorted `(value, row-list)` table
//! per indexed field, derived from one segment's documents. Any valid
//! rebuild is correct — nothing byte-compares two builds, same rule as the
//! dense and sparse indexes.
//!
//! # Layout
//!
//! All integers are little-endian.
//!
//! | Section | Contents |
//! |---|---|
//! | Header | magic `ITZT`, `format_version` u32, `rows` u32, `field_count` u32 |
//! | Field directory | `field_count` entries, sorted by name: `name_len` u16, name bytes, `kind` u8 (0=bool, 1=number, 2=text), `entry_count` u32 |
//! | Entries | for each field in directory order, `entry_count` `(value, row_count u32, rows)` records, value sorted ascending, rows within one entry sorted ascending |
//!
//! A value is 1 byte for `bool`, 8 bytes (`f64` bits) for `number`, or a
//! `u32` length plus UTF-8 bytes for `text`. A `set<string>`/`set<number>`
//! field is indexed by element: one entry per distinct element value, whose
//! row list is every row that holds it, so the value kind stored is the
//! element's kind (text or number), not a set kind of its own.
//!
//! The whole object is fetched and decoded at once (typically one or two
//! indexed fields, modest cardinality) — unlike the sparse inverted index,
//! there is no lazy per-term fetch.

use std::collections::BTreeMap;
use std::ops::Bound;

use bytes::{Bytes, BytesMut};
use object_store::path::Path;
use object_store::{GetOptions, GetRange, ObjectStore, ObjectStoreExt};

use crate::attrs::AttrType;
use crate::budget::ReadBudget;
use crate::error::{ItzmaError, Result};

const MAGIC: [u8; 4] = *b"ITZT";
pub(crate) const FORMAT_VERSION: u32 = 1;
/// Magic, format_version, rows, field_count.
const HEADER_LEN: usize = 4 + 4 + 4 + 4;

const OBJECT_PREFIX: &str = "attr-idx-";
const OBJECT_SUFFIX: &str = ".bin";

fn corrupt(path: &str, reason: impl Into<String>) -> ItzmaError {
    ItzmaError::CorruptAttrIndex {
        path: path.to_string(),
        reason: reason.into(),
    }
}

const MISSING: &str = "missing from the store";

/// The error for an attribute index the store does not have.
pub(crate) fn missing(path: &Path) -> ItzmaError {
    corrupt(path.as_ref(), MISSING)
}

/// Whether `err` is what [`missing`] builds.
pub(crate) fn is_missing(err: &ItzmaError) -> bool {
    matches!(err, ItzmaError::CorruptAttrIndex { reason, .. } if reason == MISSING)
}

/// Object key of a segment's attribute index:
/// `<namespace>/segments/<id>/attr-idx-<generation>.bin`.
pub(crate) fn attr_index_path(namespace: &str, id: &str, generation: u32) -> Path {
    Path::from(format!(
        "{namespace}/segments/{id}/{OBJECT_PREFIX}{generation}{OBJECT_SUFFIX}"
    ))
}

/// The generation in an `attr-idx-<n>.bin` name, or `None` for anything else
/// (mirrors `crate::sparse_index::generation_of`).
pub(crate) fn generation_of(file_name: &str) -> Option<u32> {
    let digits = file_name
        .strip_prefix(OBJECT_PREFIX)?
        .strip_suffix(OBJECT_SUFFIX)?;
    let generation: u32 = digits.parse().ok()?;
    (generation >= 1 && generation.to_string() == digits).then_some(generation)
}

/// One indexed field's value kind: which of `bool`/`number`/`text` its
/// entries hold. A `set<string>`/`set<number>` field is indexed by element,
/// so its kind is its element's kind (`Text`/`Number`), not a set kind of
/// its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
    Bool,
    Number,
    Text,
}

impl Kind {
    /// The value kind an `AttrType`'s entries are indexed as.
    pub(crate) fn of(ty: AttrType) -> Kind {
        match ty {
            AttrType::Bool => Kind::Bool,
            AttrType::Number | AttrType::NumberSet => Kind::Number,
            AttrType::Text | AttrType::TextSet => Kind::Text,
        }
    }

    fn to_u8(self) -> u8 {
        match self {
            Kind::Bool => 0,
            Kind::Number => 1,
            Kind::Text => 2,
        }
    }

    fn from_u8(byte: u8) -> Option<Kind> {
        match byte {
            0 => Some(Kind::Bool),
            1 => Some(Kind::Number),
            2 => Some(Kind::Text),
            _ => None,
        }
    }
}

/// One value an indexed field's entries are keyed by: a scalar field's
/// value, or one element of a set field.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Value {
    Bool(bool),
    /// Always finite — every stored attribute number came from JSON, which
    /// cannot represent NaN or infinity, so [`f64::total_cmp`] is a true
    /// total order here.
    Number(f64),
    Text(String),
}

impl Value {
    /// A number value, normalized so `-0.0` and `0.0` land on the same
    /// entry: `Predicate::matches` compares numbers with plain `==`, where
    /// they are equal, but `f64::total_cmp` (this index's sort and search
    /// order) treats them as distinct. Every `Value::Number` this module
    /// builds from a document's stored value or a predicate's literal goes
    /// through this constructor; `decode` never does, since it only ever
    /// reads back bytes this constructor already normalized.
    fn number(n: f64) -> Value {
        Value::Number(if n == 0.0 { 0.0 } else { n })
    }

    /// The total order entries are sorted and searched by: `false` before
    /// `true`, `total_cmp` for numbers, byte order for text. Different
    /// kinds never compare inside one field's table, so the `_` arm is
    /// unreachable in practice and returns `Equal` rather than panicking.
    fn cmp(&self, other: &Value) -> std::cmp::Ordering {
        match (self, other) {
            (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
            (Value::Number(a), Value::Number(b)) => a.total_cmp(b),
            (Value::Text(a), Value::Text(b)) => a.cmp(b),
            _ => std::cmp::Ordering::Equal,
        }
    }
}

fn write_value(out: &mut BytesMut, value: &Value) {
    match value {
        Value::Bool(v) => out.extend_from_slice(&[u8::from(*v)]),
        Value::Number(v) => out.extend_from_slice(&v.to_bits().to_le_bytes()),
        Value::Text(v) => {
            let bytes = v.as_bytes();
            out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
            out.extend_from_slice(bytes);
        }
    }
}

/// One field's pre-sorted build input: its value kind and its
/// `(value, row-list)` entries, sorted ascending by [`Value::cmp`] with each
/// row list itself sorted ascending. [`group_sorted`] produces this shape
/// from unsorted `(value, row)` pairs.
pub(crate) struct FieldBuild {
    pub(crate) kind: Kind,
    pub(crate) entries: Vec<(Value, Vec<u32>)>,
}

/// Sort `pairs` by value (ties broken by row) and group equal values into
/// one entry each, its row list sorted ascending with no row repeated. Used
/// by `attr_indexer::index_segment` to turn one field's `(value, row)`
/// pairs, collected in row order, into [`FieldBuild::entries`]. A row can
/// arrive more than once for the same value — a set field's duplicate
/// element is a legal write, since a set's semantics ignore
/// duplicates — and the decoder requires a strictly ascending row list, so
/// a repeat is dropped rather than left to become an unreadable object.
pub(crate) fn group_sorted(mut pairs: Vec<(Value, u32)>) -> Vec<(Value, Vec<u32>)> {
    pairs.sort_by(|(a, ra), (b, rb)| a.cmp(b).then(ra.cmp(rb)));
    let mut out: Vec<(Value, Vec<u32>)> = Vec::new();
    for (value, row) in pairs {
        match out.last_mut() {
            Some((last, rows)) if last.cmp(&value) == std::cmp::Ordering::Equal => {
                if rows.last() != Some(&row) {
                    rows.push(row);
                }
            }
            _ => out.push((value, vec![row])),
        }
    }
    out
}

/// Build a whole `attr-idx-<gen>.bin` object from every indexed field's
/// pre-sorted entries. Used by `attr_indexer::index_segment`.
pub(crate) fn build(rows: u32, fields: &BTreeMap<String, FieldBuild>) -> Bytes {
    let mut dir = BytesMut::new();
    let mut body = BytesMut::new();
    for (name, field) in fields {
        let name_bytes = name.as_bytes();
        dir.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
        dir.extend_from_slice(name_bytes);
        dir.extend_from_slice(&[field.kind.to_u8()]);
        dir.extend_from_slice(&(field.entries.len() as u32).to_le_bytes());
        for (value, rows_for_value) in &field.entries {
            write_value(&mut body, value);
            body.extend_from_slice(&(rows_for_value.len() as u32).to_le_bytes());
            for row in rows_for_value {
                body.extend_from_slice(&row.to_le_bytes());
            }
        }
    }
    let mut out = BytesMut::with_capacity(HEADER_LEN + dir.len() + body.len());
    out.extend_from_slice(&MAGIC);
    out.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
    out.extend_from_slice(&rows.to_le_bytes());
    out.extend_from_slice(&(fields.len() as u32).to_le_bytes());
    out.extend_from_slice(&dir);
    out.extend_from_slice(&body);
    out.freeze()
}

/// A cursor over the object's bytes, bounds-checked, raising
/// `CorruptAttrIndex` (mirrors `sparse_index::Reader`).
struct Reader<'a> {
    path: &'a str,
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(path: &'a str, buf: &'a [u8]) -> Self {
        Self { path, buf, pos: 0 }
    }

    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        let out = self
            .buf
            .get(self.pos..)
            .and_then(|rest| rest.get(..n))
            .ok_or_else(|| corrupt(self.path, "object is truncated"))?;
        self.pos += n;
        Ok(out)
    }

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

    fn u16(&mut self) -> Result<u16> {
        let b = self.take(2)?;
        Ok(u16::from_le_bytes([b[0], b[1]]))
    }

    fn u32(&mut self) -> Result<u32> {
        let b = self.take(4)?;
        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn f64(&mut self) -> Result<f64> {
        let b = self.take(8)?;
        let mut a = [0u8; 8];
        a.copy_from_slice(b);
        Ok(f64::from_le_bytes(a))
    }

    fn text(&mut self, len: usize) -> Result<String> {
        let bytes = self.take(len)?;
        String::from_utf8(bytes.to_vec())
            .map_err(|_| corrupt(self.path, "a text value is not valid UTF-8"))
    }
}

/// One indexed field's decoded, in-memory lookup table: entries sorted
/// ascending by [`Value::cmp`], each row list sorted ascending.
#[derive(Debug)]
pub(crate) struct FieldIndex {
    entries: Vec<(Value, Vec<u32>)>,
}

impl FieldIndex {
    /// Rows whose value equals `value`, or empty if none do.
    pub(crate) fn rows_eq(&self, value: &Value) -> Vec<u32> {
        self.entries
            .binary_search_by(|(v, _)| v.cmp(value))
            .map(|at| self.entries[at].1.clone())
            .unwrap_or_default()
    }

    /// Rows whose value falls within `(low, high)`, each bound independently
    /// included, excluded, or unbounded. Used for `Compare`'s
    /// `Lt`/`Le`/`Gt`/`Ge` (one bound) and `Between` (`Included` on both).
    pub(crate) fn rows_range(&self, low: Bound<&Value>, high: Bound<&Value>) -> Vec<u32> {
        use std::cmp::Ordering;
        let start = match low {
            Bound::Unbounded => 0,
            Bound::Included(v) => self
                .entries
                .partition_point(|(e, _)| e.cmp(v) == Ordering::Less),
            Bound::Excluded(v) => self
                .entries
                .partition_point(|(e, _)| e.cmp(v) != Ordering::Greater),
        };
        let end = match high {
            Bound::Unbounded => self.entries.len(),
            Bound::Included(v) => self
                .entries
                .partition_point(|(e, _)| e.cmp(v) != Ordering::Greater),
            Bound::Excluded(v) => self
                .entries
                .partition_point(|(e, _)| e.cmp(v) == Ordering::Less),
        };
        let mut out: Vec<u32> = self.entries[start..end.max(start)]
            .iter()
            .flat_map(|(_, rows)| rows.iter().copied())
            .collect();
        out.sort_unstable();
        out
    }
}

/// A segment's decoded attribute index: one [`FieldIndex`] per indexed
/// field.
#[derive(Debug)]
pub(crate) struct AttrIndex {
    fields: BTreeMap<String, FieldIndex>,
}

impl AttrIndex {
    /// The lookup table for `name`, if it is indexed in this segment.
    pub(crate) fn field(&self, name: &str) -> Option<&FieldIndex> {
        self.fields.get(name)
    }
}

/// Decode a whole object already in memory, checking it against `rows`: the
/// magic, the field directory's sort order and bounds, and every entry's
/// value order, row order and row range.
fn decode(path: &str, bytes: &[u8], rows: u64) -> Result<AttrIndex> {
    let mut r = Reader::new(path, bytes);
    if r.take(4)? != MAGIC {
        return Err(corrupt(path, "bad magic"));
    }
    match r.u32()? {
        FORMAT_VERSION => {}
        version => return Err(ItzmaError::UnsupportedFormat { version }),
    }
    let got_rows = u64::from(r.u32()?);
    if got_rows != rows {
        return Err(corrupt(
            path,
            format!("{got_rows} rows, the segment has {rows}"),
        ));
    }
    let field_count = r.u32()?;

    struct DirEntry {
        name: String,
        kind: Kind,
        entry_count: u32,
    }
    // Not `Vec::with_capacity(field_count as usize)`: field_count is read
    // straight off the wire, unchecked, and a corrupt object (one flipped
    // byte is enough) can claim billions of fields before a single byte of
    // any of them has been read. `Vec::new` grows only as an iteration
    // actually reads a real entry through `r`'s bounds-checked `take`, so
    // the eventual allocation is bounded by real bytes present, never by
    // an attacker-controlled count.
    let mut dir = Vec::new();
    let mut last_name: Option<String> = None;
    for _ in 0..field_count {
        let name_len = r.u16()? as usize;
        let name = r.text(name_len)?;
        if last_name.as_ref().is_some_and(|last| &name <= last) {
            return Err(corrupt(
                path,
                "field directory is not sorted by ascending name",
            ));
        }
        last_name = Some(name.clone());
        let kind = Kind::from_u8(r.u8()?).ok_or_else(|| corrupt(path, "unknown field kind"))?;
        let entry_count = r.u32()?;
        dir.push(DirEntry {
            name,
            kind,
            entry_count,
        });
    }

    let mut fields = BTreeMap::new();
    for entry in dir {
        // Same reasoning as `dir` above: `entry.entry_count` is unchecked.
        let mut values: Vec<(Value, Vec<u32>)> = Vec::new();
        let mut last_value: Option<Value> = None;
        for _ in 0..entry.entry_count {
            let value = match entry.kind {
                Kind::Bool => Value::Bool(r.u8()? != 0),
                Kind::Number => Value::Number(r.f64()?),
                Kind::Text => {
                    let len = r.u32()? as usize;
                    Value::Text(r.text(len)?)
                }
            };
            if last_value
                .as_ref()
                .is_some_and(|last| last.cmp(&value) != std::cmp::Ordering::Less)
            {
                return Err(corrupt(
                    path,
                    format!("{}'s entries are not sorted by ascending value", entry.name),
                ));
            }
            last_value = Some(value.clone());
            let row_count = r.u32()?;
            // Same reasoning as `dir` above: row_count is unchecked.
            let mut row_list = Vec::new();
            let mut last_row: Option<u32> = None;
            for _ in 0..row_count {
                let row = r.u32()?;
                if u64::from(row) >= rows {
                    return Err(corrupt(
                        path,
                        format!(
                            "{}'s entry names row {row}, the segment has {rows} rows",
                            entry.name
                        ),
                    ));
                }
                if last_row.is_some_and(|last| row <= last) {
                    return Err(corrupt(
                        path,
                        format!("{}'s rows are not sorted by ascending row", entry.name),
                    ));
                }
                last_row = Some(row);
                row_list.push(row);
            }
            values.push((value, row_list));
        }
        fields.insert(entry.name, FieldIndex { entries: values });
    }
    Ok(AttrIndex { fields })
}

/// Check that `bytes` decodes as a valid attribute index for a segment of
/// `rows` rows, without a store round trip — used when an object already
/// sits at the put-if-absent key.
pub(crate) fn open_bytes_for_check(path: &str, bytes: &[u8], rows: u64) -> Result<()> {
    decode(path, bytes, rows).map(|_| ())
}

/// How many bytes the first request asks for — enough for most segments'
/// whole object in one round trip (mirrors `sparse_index::HEAD_GUESS`).
const HEAD_GUESS: u64 = 64 * 1024;

/// One charged `GET` of `range`.
async fn get_range(
    store: &dyn ObjectStore,
    budget: &ReadBudget,
    path: &Path,
    range: std::ops::Range<u64>,
) -> Result<Bytes> {
    if range.end <= range.start {
        return Ok(Bytes::new());
    }
    budget.charge(path.as_ref(), range.end - range.start)?;
    match store.get_range(path, range).await {
        Ok(bytes) => Ok(bytes),
        Err(object_store::Error::NotFound { .. }) => Err(missing(path)),
        Err(e) => Err(e.into()),
    }
}

/// Fetch and decode a segment's attribute index, against its row count. Most
/// objects fit the first bounded request; a bigger one is extended with one
/// more ranged `GET` for the remainder.
///
/// # Errors
///
/// [`ItzmaError::CorruptAttrIndex`] for a missing object (see
/// [`is_missing`]) or anything [`decode`] rejects.
/// [`ItzmaError::UnsupportedFormat`] for a container version this build does
/// not read. [`ItzmaError::ReadBudgetExceeded`] before a fetch that would go
/// over.
pub(crate) async fn open(
    store: &dyn ObjectStore,
    budget: &ReadBudget,
    path: &Path,
    rows: u64,
) -> Result<AttrIndex> {
    let name = path.as_ref();
    budget.charge(name, HEAD_GUESS)?;
    let options = GetOptions {
        range: Some(GetRange::Bounded(0..HEAD_GUESS)),
        ..GetOptions::default()
    };
    let got = match store.get_opts(path, options).await {
        Ok(got) => got,
        Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
        Err(e) => return Err(e.into()),
    };
    let size = got.meta.size;
    let first = got.bytes().await?;
    if size <= first.len() as u64 {
        return decode(name, &first, rows);
    }
    let rest = get_range(store, budget, path, first.len() as u64..size).await?;
    let whole: Vec<u8> = first.iter().copied().chain(rest.iter().copied()).collect();
    decode(name, &whole, rows)
}

use std::collections::BTreeSet;

use crate::predicate::{AttrValue, Compare, Predicate, TextCompare};

fn intersect(a: &[u32], b: &[u32]) -> Vec<u32> {
    let a: BTreeSet<u32> = a.iter().copied().collect();
    b.iter().copied().filter(|r| a.contains(r)).collect()
}

fn union(a: &[u32], b: &[u32]) -> Vec<u32> {
    let mut out: BTreeSet<u32> = a.iter().copied().collect();
    out.extend(b.iter().copied());
    out.into_iter().collect()
}

fn attr_value_to_value(v: &AttrValue) -> Value {
    match v {
        AttrValue::Number(n) => Value::number(*n),
        AttrValue::Text(s) => Value::Text(s.clone()),
    }
}

/// Whether [`index_candidates`] could return `Some` for `predicate` against a
/// namespace whose indexed fields are exactly `indexed` — checked from field
/// names alone, no index bytes needed. A caller with a segment's attr-idx
/// entry but a predicate this returns `false` for should skip fetching and
/// decoding that object entirely: `index_candidates` would only ever answer
/// `None` for it, so the fetch is pure waste. Mirrors `index_candidates`'
/// per-node resolution rules exactly, including the operators (`Ne`,
/// `StartsWith`) that never resolve even on an indexed field.
pub(crate) fn could_resolve(predicate: &Predicate, indexed: &BTreeSet<&str>) -> bool {
    match predicate {
        Predicate::And(items) => items.iter().any(|item| could_resolve(item, indexed)),
        Predicate::Or(items) => items.iter().all(|item| could_resolve(item, indexed)),
        Predicate::Not(_)
        | Predicate::IsNull(_)
        | Predicate::IsNotNull(_)
        | Predicate::IsEmpty(_) => false,
        Predicate::IsTrue(field)
        | Predicate::IsFalse(field)
        | Predicate::NumberIn { field, .. }
        | Predicate::Between { field, .. }
        | Predicate::TextIn { field, .. }
        | Predicate::Contains { field, .. }
        | Predicate::ContainsAny { field, .. }
        | Predicate::ContainsAll { field, .. } => indexed.contains(field.as_str()),
        Predicate::Number { field, op, .. } => {
            *op != Compare::Ne && indexed.contains(field.as_str())
        }
        Predicate::Text { field, op, .. } => {
            *op == TextCompare::Eq && indexed.contains(field.as_str())
        }
    }
}

/// A superset of the rows that can match `predicate`, using only fields
/// `index` has an entry for, or `None` when nothing about the predicate can
/// be resolved from indexed fields alone.
///
/// This is a pruning step, never a source of truth: the caller still runs
/// [`Predicate::matches`] against whatever rows come back (or every row, if
/// this returns `None`) before counting a hit. A conservative or
/// unresolved plan costs speed, never correctness.
pub(crate) fn index_candidates(predicate: &Predicate, index: &AttrIndex) -> Option<Vec<u32>> {
    match predicate {
        Predicate::And(items) => {
            let mut acc: Option<Vec<u32>> = None;
            for item in items {
                if let Some(rows) = index_candidates(item, index) {
                    acc = Some(match acc {
                        Some(existing) => intersect(&existing, &rows),
                        None => rows,
                    });
                }
            }
            acc
        }
        Predicate::Or(items) => {
            let mut acc: Option<Vec<u32>> = Some(Vec::new());
            for item in items {
                let rows = index_candidates(item, index)?;
                acc = acc.map(|existing| union(&existing, &rows));
            }
            acc
        }
        Predicate::Not(_)
        | Predicate::IsNull(_)
        | Predicate::IsNotNull(_)
        | Predicate::IsEmpty(_) => None,
        Predicate::IsTrue(field) => index.field(field).map(|f| f.rows_eq(&Value::Bool(true))),
        Predicate::IsFalse(field) => index.field(field).map(|f| f.rows_eq(&Value::Bool(false))),
        Predicate::Number { field, op, value } => {
            let f = index.field(field)?;
            let v = Value::number(*value);
            Some(match op {
                Compare::Eq => f.rows_eq(&v),
                Compare::Ne => return None,
                Compare::Lt => {
                    f.rows_range(std::ops::Bound::Unbounded, std::ops::Bound::Excluded(&v))
                }
                Compare::Le => {
                    f.rows_range(std::ops::Bound::Unbounded, std::ops::Bound::Included(&v))
                }
                Compare::Gt => {
                    f.rows_range(std::ops::Bound::Excluded(&v), std::ops::Bound::Unbounded)
                }
                Compare::Ge => {
                    f.rows_range(std::ops::Bound::Included(&v), std::ops::Bound::Unbounded)
                }
            })
        }
        Predicate::NumberIn { field, values } => {
            let f = index.field(field)?;
            Some(
                values
                    .iter()
                    .map(|v| f.rows_eq(&Value::number(*v)))
                    .fold(Vec::new(), |acc, rows| union(&acc, &rows)),
            )
        }
        Predicate::Between { field, low, high } => {
            let f = index.field(field)?;
            Some(f.rows_range(
                std::ops::Bound::Included(&Value::number(*low)),
                std::ops::Bound::Included(&Value::number(*high)),
            ))
        }
        Predicate::Text { field, op, value } => {
            let f = index.field(field)?;
            match op {
                TextCompare::Eq => Some(f.rows_eq(&Value::Text(value.clone()))),
                TextCompare::Ne | TextCompare::StartsWith => None,
            }
        }
        Predicate::TextIn { field, values } => {
            let f = index.field(field)?;
            Some(
                values
                    .iter()
                    .map(|v| f.rows_eq(&Value::Text(v.clone())))
                    .fold(Vec::new(), |acc, rows| union(&acc, &rows)),
            )
        }
        Predicate::Contains { field, value } => {
            let f = index.field(field)?;
            Some(f.rows_eq(&attr_value_to_value(value)))
        }
        Predicate::ContainsAny { field, values } => {
            let f = index.field(field)?;
            Some(
                values
                    .iter()
                    .map(|v| f.rows_eq(&attr_value_to_value(v)))
                    .fold(Vec::new(), |acc, rows| union(&acc, &rows)),
            )
        }
        Predicate::ContainsAll { field, values } => {
            let f = index.field(field)?;
            let mut iter = values.iter().map(|v| f.rows_eq(&attr_value_to_value(v)));
            let first = iter.next()?;
            Some(iter.fold(first, |acc, rows| intersect(&acc, &rows)))
        }
    }
}

/// A scalar field's value from a document's stored attributes, or `None` if
/// the field is missing, `null`, or the wrong JSON kind for `ty` (which
/// [`Predicate::matches`] also treats as null — excluding it here keeps the
/// index consistent with what a full scan would find). Not for a set type;
/// see [`field_elements`].
pub(crate) fn field_value(
    attrs: Option<&serde_json::Value>,
    field: &str,
    ty: AttrType,
) -> Option<Value> {
    let value = attrs?.get(field)?;
    if value.is_null() {
        return None;
    }
    match ty {
        AttrType::Bool => value.as_bool().map(Value::Bool),
        AttrType::Number => value.as_f64().map(Value::number),
        AttrType::Text => value.as_str().map(|s| Value::Text(s.to_string())),
        AttrType::TextSet | AttrType::NumberSet => None,
    }
}

/// A set field's elements from a document's stored attributes, skipping any
/// that are not the set's declared element type (the same "wrong type
/// counts as absent" rule as [`field_value`]). Empty if the field is
/// missing, `null`, or not an array.
pub(crate) fn field_elements(
    attrs: Option<&serde_json::Value>,
    field: &str,
    ty: AttrType,
) -> Vec<Value> {
    let Some(items) = attrs
        .and_then(|a| a.get(field))
        .and_then(serde_json::Value::as_array)
    else {
        return Vec::new();
    };
    items
        .iter()
        .filter_map(|item| match ty {
            AttrType::TextSet => item.as_str().map(|s| Value::Text(s.to_string())),
            AttrType::NumberSet => item.as_f64().map(Value::number),
            AttrType::Bool | AttrType::Number | AttrType::Text => None,
        })
        .collect()
}

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

    fn b(v: bool) -> Value {
        Value::Bool(v)
    }
    fn n(v: f64) -> Value {
        Value::Number(v)
    }
    fn t(v: &str) -> Value {
        Value::Text(v.into())
    }

    fn sample_fields() -> BTreeMap<String, FieldBuild> {
        let mut fields = BTreeMap::new();
        fields.insert(
            "active".to_string(),
            FieldBuild {
                kind: Kind::Bool,
                entries: vec![(b(false), vec![1]), (b(true), vec![0, 2])],
            },
        );
        fields.insert(
            "price".to_string(),
            FieldBuild {
                kind: Kind::Number,
                entries: vec![(n(1.5), vec![0]), (n(9.0), vec![1, 2])],
            },
        );
        fields.insert(
            "tags".to_string(),
            FieldBuild {
                kind: Kind::Text,
                entries: vec![(t("a"), vec![0, 1]), (t("b"), vec![1])],
            },
        );
        fields
    }

    #[test]
    fn build_open_and_lookups_round_trip() {
        let bytes = build(3, &sample_fields());
        let index = decode("p", &bytes, 3).expect("decode");

        let active = index.field("active").expect("active present");
        assert_eq!(active.rows_eq(&b(true)), vec![0, 2]);
        assert_eq!(active.rows_eq(&b(false)), vec![1]);

        let price = index.field("price").expect("price present");
        assert_eq!(price.rows_eq(&n(9.0)), vec![1, 2]);
        assert_eq!(price.rows_eq(&n(2.0)), Vec::<u32>::new());
        assert_eq!(
            price.rows_range(Bound::Included(&n(1.5)), Bound::Included(&n(9.0))),
            vec![0, 1, 2]
        );
        assert_eq!(
            price.rows_range(Bound::Excluded(&n(1.5)), Bound::Unbounded),
            vec![1, 2]
        );
        assert_eq!(
            price.rows_range(Bound::Unbounded, Bound::Excluded(&n(9.0))),
            vec![0]
        );

        let tags = index.field("tags").expect("tags present");
        assert_eq!(tags.rows_eq(&t("a")), vec![0, 1]);
        assert_eq!(tags.rows_eq(&t("z")), Vec::<u32>::new());

        assert!(index.field("nope").is_none());
    }

    #[test]
    fn group_sorted_groups_equal_values_and_sorts_rows_within_a_group() {
        let grouped = group_sorted(vec![(n(2.0), 5), (n(1.0), 1), (n(2.0), 0)]);
        assert_eq!(grouped, vec![(n(1.0), vec![1]), (n(2.0), vec![0, 5])]);
    }

    #[test]
    fn group_sorted_dedups_the_same_row_appearing_twice_for_one_value() {
        // A set field with a duplicate element ("tags": ["a", "a"]) is a
        // legal write (attrs.rs's set semantics ignore duplicates), and the
        // builder pushes (value, row) once per element, so the same row can
        // arrive twice for the same value. The row list decode requires is
        // strictly ascending, so a duplicate must collapse to one entry, not
        // become an unreadable `[0, 0]`.
        let grouped = group_sorted(vec![(t("a"), 3), (t("a"), 3), (t("a"), 1)]);
        assert_eq!(grouped, vec![(t("a"), vec![1, 3])]);
    }

    #[test]
    fn decode_rejects_a_row_count_mismatch() {
        let bytes = build(3, &sample_fields());
        let err = decode("p", &bytes, 4).unwrap_err();
        assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
    }

    #[test]
    fn decode_rejects_a_row_past_the_segment() {
        let mut fields = BTreeMap::new();
        fields.insert(
            "active".to_string(),
            FieldBuild {
                kind: Kind::Bool,
                entries: vec![(b(true), vec![5])],
            },
        );
        let bytes = build(3, &fields);
        let err = decode("p", &bytes, 3).unwrap_err();
        assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
    }

    #[test]
    fn every_truncation_and_bit_flip_is_refused_never_panics() {
        let bytes = build(3, &sample_fields());
        for len in 0..bytes.len() {
            let _ = decode("p", &bytes.slice(..len), 3); // must not panic
        }
        for i in 0..bytes.len() {
            let mut bad = bytes.to_vec();
            bad[i] ^= 0xFF;
            let _ = decode("p", &bad, 3); // must not panic
        }
    }

    /// `field_count`, `entry_count` and `row_count` are read straight off
    /// the wire, attacker-controlled, and each used to size a `Vec` before
    /// a single one of the elements it will hold has been read. A
    /// truncated object with a huge count must never turn into a
    /// multi-gigabyte allocation attempt just to then error on the first
    /// real byte it reads — the same hazard
    /// `wal_codec::tests::a_huge_claimed_body_len_is_refused_without_allocating`
    /// guards against for the WAL. This assertion alone cannot prove "no
    /// huge allocation" (a machine that overcommits virtual memory, like
    /// the one this was written on, never crashes on it either way, which
    /// is exactly how this bug escaped review), but it does pin the
    /// correctness end: a huge count is `CorruptAttrIndex`, not a hang or
    /// a decode that somehow succeeds.
    #[test]
    fn a_huge_field_count_is_refused_not_preallocated() {
        let mut bytes = BytesMut::new();
        bytes.extend_from_slice(&MAGIC);
        bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
        bytes.extend_from_slice(&3u32.to_le_bytes()); // rows
        bytes.extend_from_slice(&u32::MAX.to_le_bytes()); // field_count
        let err = decode("p", &bytes, 3).unwrap_err();
        assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
    }

    #[test]
    fn a_huge_entry_count_is_refused_not_preallocated() {
        let mut bytes = BytesMut::new();
        bytes.extend_from_slice(&MAGIC);
        bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
        bytes.extend_from_slice(&3u32.to_le_bytes()); // rows
        bytes.extend_from_slice(&1u32.to_le_bytes()); // field_count
        bytes.extend_from_slice(&1u16.to_le_bytes()); // name_len
        bytes.extend_from_slice(b"x"); // name
        bytes.extend_from_slice(&[0u8]); // kind: Bool
        bytes.extend_from_slice(&u32::MAX.to_le_bytes()); // entry_count
        let err = decode("p", &bytes, 3).unwrap_err();
        assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
    }

    #[test]
    fn a_huge_row_count_is_refused_not_preallocated() {
        let mut bytes = BytesMut::new();
        bytes.extend_from_slice(&MAGIC);
        bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
        bytes.extend_from_slice(&3u32.to_le_bytes()); // rows
        bytes.extend_from_slice(&1u32.to_le_bytes()); // field_count
        bytes.extend_from_slice(&1u16.to_le_bytes()); // name_len
        bytes.extend_from_slice(b"x"); // name
        bytes.extend_from_slice(&[0u8]); // kind: Bool
        bytes.extend_from_slice(&1u32.to_le_bytes()); // entry_count
        bytes.extend_from_slice(&[1u8]); // the one entry's bool value
        bytes.extend_from_slice(&u32::MAX.to_le_bytes()); // row_count
        let err = decode("p", &bytes, 3).unwrap_err();
        assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
    }

    #[tokio::test]
    async fn open_fetches_and_decodes_from_a_store() {
        let bytes = build(3, &sample_fields());
        let store = object_store::memory::InMemory::new();
        let path = Path::from("p");
        store.put(&path, bytes.into()).await.expect("put");
        let budget = ReadBudget::unlimited();

        let index = open(&store, &budget, &path, 3).await.expect("open");
        assert_eq!(index.field("price").unwrap().rows_eq(&n(9.0)), vec![1, 2]);
    }

    #[tokio::test]
    async fn open_of_a_missing_object_is_missing() {
        let store = object_store::memory::InMemory::new();
        let path = Path::from("p");
        let budget = ReadBudget::unlimited();
        let err = open(&store, &budget, &path, 3).await.unwrap_err();
        assert!(is_missing(&err));
    }

    #[test]
    fn only_the_exact_object_name_has_a_generation() {
        assert_eq!(generation_of("attr-idx-1.bin"), Some(1));
        assert_eq!(generation_of("attr-idx-42.bin"), Some(42));
        for name in [
            "data.bin",
            "sparse.bin",
            "index-1.bin",
            "attr-idx-0.bin",
            "attr-idx-.bin",
            "attr-idx-1",
        ] {
            assert_eq!(generation_of(name), None, "{name}");
        }
    }

    #[test]
    fn an_attr_index_lives_beside_its_segment() {
        assert_eq!(
            attr_index_path("docs", "0001-0002", 3).as_ref(),
            "docs/segments/0001-0002/attr-idx-3.bin"
        );
    }

    use crate::predicate::{AttrValue, Compare, Predicate, TextCompare};

    fn index_with(fields: BTreeMap<String, FieldBuild>) -> AttrIndex {
        let bytes = build(10, &fields);
        decode("p", &bytes, 10).unwrap()
    }

    fn two_field_index() -> AttrIndex {
        let mut fields = BTreeMap::new();
        fields.insert(
            "price".to_string(),
            FieldBuild {
                kind: Kind::Number,
                entries: vec![(n(1.0), vec![0]), (n(5.0), vec![1, 2]), (n(9.0), vec![3])],
            },
        );
        fields.insert(
            "tags".to_string(),
            FieldBuild {
                kind: Kind::Text,
                entries: vec![
                    (t("a"), vec![0, 1, 4]),
                    (t("b"), vec![1, 2]),
                    (t("c"), vec![2]),
                ],
            },
        );
        index_with(fields)
    }

    #[test]
    fn a_leaf_on_an_indexed_number_field_resolves_exactly() {
        let index = two_field_index();
        let p = Predicate::number("price", Compare::Eq, 5.0);
        assert_eq!(index_candidates(&p, &index), Some(vec![1, 2]));
    }

    #[test]
    fn compare_lt_le_gt_ge_all_resolve_via_range() {
        let index = two_field_index();
        let cases = [
            (Compare::Lt, 5.0, vec![0]),
            (Compare::Le, 5.0, vec![0, 1, 2]),
            (Compare::Gt, 5.0, vec![3]),
            (Compare::Ge, 5.0, vec![1, 2, 3]),
        ];
        for (op, at, want) in cases {
            let p = Predicate::number("price", op, at);
            assert_eq!(index_candidates(&p, &index), Some(want), "{op:?}");
        }
    }

    #[test]
    fn compare_ne_does_not_resolve() {
        let index = two_field_index();
        let p = Predicate::number("price", Compare::Ne, 5.0);
        assert_eq!(index_candidates(&p, &index), None);
    }

    #[test]
    fn between_and_number_in_resolve() {
        let index = two_field_index();
        let between = Predicate::Between {
            field: "price".into(),
            low: 1.0,
            high: 5.0,
        };
        assert_eq!(index_candidates(&between, &index), Some(vec![0, 1, 2]));
        let inn = Predicate::NumberIn {
            field: "price".into(),
            values: vec![1.0, 9.0],
        };
        assert_eq!(index_candidates(&inn, &index), Some(vec![0, 3]));
    }

    #[test]
    fn text_eq_resolves_but_ne_and_starts_with_do_not() {
        let index = two_field_index();
        let eq = Predicate::text("tags", TextCompare::Eq, "b");
        assert_eq!(index_candidates(&eq, &index), Some(vec![1, 2]));
        let ne = Predicate::text("tags", TextCompare::Ne, "b");
        assert_eq!(index_candidates(&ne, &index), None);
        let starts = Predicate::text("tags", TextCompare::StartsWith, "b");
        assert_eq!(index_candidates(&starts, &index), None);
    }

    #[test]
    fn text_in_resolves_as_a_union() {
        let index = two_field_index();
        let p = Predicate::TextIn {
            field: "tags".into(),
            values: vec!["a".into(), "c".into()],
        };
        assert_eq!(index_candidates(&p, &index), Some(vec![0, 1, 2, 4]));
    }

    #[test]
    fn contains_any_all_resolve_as_union_and_intersection() {
        let index = two_field_index();
        let any = Predicate::ContainsAny {
            field: "tags".into(),
            values: vec![AttrValue::Text("a".into()), AttrValue::Text("c".into())],
        };
        assert_eq!(index_candidates(&any, &index), Some(vec![0, 1, 2, 4]));
        let all = Predicate::ContainsAll {
            field: "tags".into(),
            values: vec![AttrValue::Text("a".into()), AttrValue::Text("b".into())],
        };
        assert_eq!(index_candidates(&all, &index), Some(vec![1]));
    }

    #[test]
    fn a_field_that_is_not_indexed_does_not_resolve() {
        let index = two_field_index();
        let p = Predicate::is_true("active"); // "active" has no entry in this index
        assert_eq!(index_candidates(&p, &index), None);
        let unresolvable = [
            Predicate::IsNull("price".into()),
            Predicate::IsNotNull("price".into()),
            Predicate::IsEmpty("tags".into()),
        ];
        for p in unresolvable {
            assert_eq!(index_candidates(&p, &index), None, "{p:?}");
        }
    }

    #[test]
    fn not_never_resolves() {
        let index = two_field_index();
        let p = Predicate::negate(Predicate::number("price", Compare::Eq, 5.0));
        assert_eq!(index_candidates(&p, &index), None);
    }

    /// `could_resolve` must agree with `index_candidates` on every one of
    /// these predicates without ever building an [`AttrIndex`] — it is the
    /// no-I/O precheck a caller runs before fetching one.
    #[test]
    fn could_resolve_agrees_with_index_candidates_but_needs_no_index() {
        let index = two_field_index();
        let indexed: BTreeSet<&str> = BTreeSet::from(["price", "tags"]);
        let cases = [
            Predicate::number("price", Compare::Eq, 5.0),
            Predicate::number("price", Compare::Lt, 5.0),
            Predicate::number("price", Compare::Ne, 5.0), // never resolves, even indexed
            Predicate::text("tags", TextCompare::Eq, "b"),
            Predicate::text("tags", TextCompare::StartsWith, "b"), // never resolves
            Predicate::is_true("active"),                          // not indexed
            Predicate::IsNull("price".into()),                     // never resolves
            Predicate::negate(Predicate::number("price", Compare::Eq, 5.0)),
            Predicate::and(vec![
                Predicate::number("price", Compare::Ge, 5.0),
                Predicate::is_true("active"),
            ]),
            Predicate::or(vec![
                Predicate::number("price", Compare::Eq, 1.0),
                Predicate::is_true("active"),
            ]),
            Predicate::or(vec![
                Predicate::number("price", Compare::Eq, 1.0),
                Predicate::text("tags", TextCompare::Eq, "c"),
            ]),
        ];
        for p in cases {
            assert_eq!(
                could_resolve(&p, &indexed),
                index_candidates(&p, &index).is_some(),
                "{p:?}"
            );
        }
    }

    #[test]
    fn could_resolve_is_false_with_no_indexed_fields_at_all() {
        // The case the fix is for: a predicate on a namespace's only
        // indexed field never appears, so no attr-idx object should ever
        // be fetched for it.
        let indexed: BTreeSet<&str> = BTreeSet::new();
        assert!(!could_resolve(&Predicate::is_true("active"), &indexed));
        assert!(!could_resolve(
            &Predicate::number("bucket", Compare::Eq, 7.0),
            &indexed
        ));
    }

    #[test]
    fn and_intersects_and_narrows_even_with_one_unresolved_side() {
        let index = two_field_index();
        let both = Predicate::and(vec![
            Predicate::number("price", Compare::Ge, 5.0), // rows 1,2,3
            Predicate::text("tags", TextCompare::Eq, "b"), // rows 1,2
        ]);
        assert_eq!(index_candidates(&both, &index), Some(vec![1, 2]));

        let one_side_indexed = Predicate::and(vec![
            Predicate::number("price", Compare::Ge, 5.0), // rows 1,2,3
            Predicate::is_true("active"),                 // unresolved
        ]);
        assert_eq!(
            index_candidates(&one_side_indexed, &index),
            Some(vec![1, 2, 3])
        );
    }

    #[test]
    fn or_resolves_only_when_both_sides_do() {
        let index = two_field_index();
        let both = Predicate::or(vec![
            Predicate::number("price", Compare::Eq, 1.0),  // row 0
            Predicate::text("tags", TextCompare::Eq, "c"), // row 2
        ]);
        assert_eq!(index_candidates(&both, &index), Some(vec![0, 2]));

        let one_side_unresolved = Predicate::or(vec![
            Predicate::number("price", Compare::Eq, 1.0),
            Predicate::is_true("active"),
        ]);
        assert_eq!(index_candidates(&one_side_unresolved, &index), None);
    }

    #[test]
    fn a_predicate_that_survives_check_but_resolves_to_no_rows_is_a_valid_empty_result() {
        let index = two_field_index();
        let p = Predicate::number("price", Compare::Eq, 404.0);
        assert_eq!(index_candidates(&p, &index), Some(Vec::new()));
    }

    #[test]
    fn negative_zero_and_positive_zero_are_the_same_row() {
        // A stored -0.0 must be found by a query for 0.0, and vice versa,
        // the same way `Predicate::matches` (plain `==`) already treats
        // them: IEEE equal, even though `f64::total_cmp` (used to sort and
        // search this index) orders them as distinct. `field_value` is the
        // one production path a stored document's attribute goes through
        // to become an indexed `Value`, so this exercises that, not a
        // hand-built entry (which would bypass the normalization entirely).
        let mut fields = BTreeMap::new();
        let stored = field_value(
            Some(&serde_json::json!({"price": -0.0})),
            "price",
            AttrType::Number,
        )
        .expect("a number field with a value");
        fields.insert(
            "price".to_string(),
            FieldBuild {
                kind: Kind::Number,
                entries: group_sorted(vec![(stored, 0), (n(1.0), 1)]),
            },
        );
        let index = index_with(fields);
        let eq_pos = Predicate::number("price", Compare::Eq, 0.0);
        assert_eq!(index_candidates(&eq_pos, &index), Some(vec![0]));
        let ge_pos = Predicate::number("price", Compare::Ge, 0.0);
        assert_eq!(index_candidates(&ge_pos, &index), Some(vec![0, 1]));
        // And the other direction: a query literal of -0.0 still finds a
        // row stored as plain 0.0.
        let eq_neg = Predicate::number("price", Compare::Eq, -0.0);
        assert_eq!(index_candidates(&eq_neg, &index), Some(vec![0]));
    }
}