turndb 0.1.2

A content-addressed columnar store for AI traces: byte-exact, embedded, and readable by the CLI and the npm package over the same directory.
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
//! The query lens: parts, read a column at a time, as Arrow.
//!
//! Everything below this module can address a whole row by index, which is the wrong shape for the
//! storage underneath it. A part keeps one section per column, independently compressed; asking for
//! one column of a million rows should touch one section, and asking for no content should touch the
//! fold zero times. That is what this module provides and what the row API cannot express.
//!
//! # Projection is the whole point
//!
//! Content reconstruction is the expensive operation in this system — it resolves piece references,
//! decompresses fold blocks, and concatenates. A query over attributes alone must never pay it. Here
//! `body` and `content.<name>` are ordinary projectable columns, so `SELECT model, tokens FROM t`
//! reads two attribute sections and **opens no fold block at all**. [`ScanStats::fold_reads`] records
//! this so the claim is measured rather than asserted.
//!
//! # Strings stay dictionary-encoded
//!
//! A part stores string columns as ordinals into a sorted distinct dictionary. Materialising them into
//! a flat `StringArray` at the Arrow boundary would throw that away exactly where a query engine can
//! most use it, so they surface as `Dictionary(Int32, Utf8)` and comparisons run on ordinals.
//!
//! # One row shape, from many parts
//!
//! Columns are keyed `(name, type)`, so a key carrying different types in different records yields
//! several homogeneous columns. The lens names them `key` when a key has exactly one type across the
//! scanned parts and `key#type` when it does not — never a silent merge of two types into one field.
//!
//! # One logical version, from many physical parts
//!
//! Parts may contain older versions and tombstones. The lens uses the store's committed read core to
//! resolve those before projection or filtering: the newest row for an id is the only eligible row,
//! and a newest tombstone makes the id absent. In particular, a predicate that rejects the newest
//! version can never fall through and reveal an older version that happens to match.

#[cfg(feature = "sql")]
pub mod sql;
#[cfg(feature = "sql")]
pub mod table;

use crate::fold::Fold;
use crate::part::{attrs, Part};
use crate::types::AttrValue;
use anyhow::{bail, Result};
use arrow::array::{
    ArrayRef, BinaryArray, BinaryBuilder, BooleanBuilder, Float64Builder, Int32Array, Int64Builder,
    StringArray, StringBuilder, TimestampNanosecondBuilder, UInt64Builder,
};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};
use arrow::record_batch::{RecordBatch, RecordBatchOptions};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

/// Rows per batch, when nothing bounds it sooner.
pub const BATCH_ROWS: usize = 8192;

/// Byte ceiling for a batch's reconstructed content.
///
/// Row count alone is the wrong bound for content columns: trace payloads here average ~97 KiB, so
/// 8192 of them is a 795 MiB batch. Records are unbounded in size and rows are not fungible, so a
/// batch closes on whichever limit is reached first. Attribute-only scans never come near this.
pub const BATCH_BYTES: usize = crate::scan::DEFAULT_MAX_RECONSTRUCTED_BYTES as usize;

/// Synthetic field names. `id` is always present; `body` appears only when at least one scanned part
/// declares conventional content with that name.
pub const F_ID: &str = "id";
pub const F_BODY: &str = "body";

fn type_name(tag: u8) -> &'static str {
    match tag {
        0 => "str",
        1 => "int",
        2 => "float",
        3 => "bool",
        4 => "uint",
        5 => "binary",
        6 => "timestamp_ns",
        7 => "null",
        _ => "unknown",
    }
}

fn arrow_type(tag: u8) -> DataType {
    match tag {
        0 => DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
        1 => DataType::Int64,
        2 => DataType::Float64,
        3 => DataType::Boolean,
        4 => DataType::UInt64,
        5 => DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Binary)),
        6 => DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
        // An explicit-null column is a presence marker: true means the attribute occurred with a
        // null value, Arrow null means it was missing. This preserves the distinction SQL needs.
        7 => DataType::Boolean,
        _ => DataType::Null,
    }
}

/// A comparison a scan can evaluate for itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cmp {
    Eq,
    Ne,
    Lt,
    LtEq,
    Gt,
    GtEq,
}

/// Does the zone `(min, max)` PROVE that `<op> val` matches nothing in it? `false` on any doubt —
/// a type mismatch, a NaN literal — because a zone may only ever widen a scan, never wrongly
/// narrow one. `Ne` is disproven only when the column is constant at exactly `val`.
fn zone_disproves(op: Cmp, val: &AttrValue, zone: &(AttrValue, AttrValue)) -> bool {
    use std::cmp::Ordering::{Equal, Greater, Less};
    fn ord(a: &AttrValue, b: &AttrValue) -> Option<std::cmp::Ordering> {
        match (a, b) {
            (AttrValue::Int(x), AttrValue::Int(y)) => Some(x.cmp(y)),
            (AttrValue::Float(x), AttrValue::Float(y)) => x.partial_cmp(y),
            (AttrValue::Bool(x), AttrValue::Bool(y)) => Some(x.cmp(y)),
            (AttrValue::UInt(x), AttrValue::UInt(y)) => Some(x.cmp(y)),
            (AttrValue::TimestampNs(x), AttrValue::TimestampNs(y)) => Some(x.cmp(y)),
            _ => None,
        }
    }
    let (min, max) = zone;
    let (Some(lo), Some(hi)) = (ord(val, min), ord(val, max)) else {
        return false;
    };
    match op {
        Cmp::Eq => lo == Less || hi == Greater,
        Cmp::Ne => lo == Equal && hi == Equal,
        Cmp::Lt => lo != Greater,   // every value >= min >= val
        Cmp::LtEq => lo == Less,    // every value >= min > val
        Cmp::Gt => hi != Less,      // every value <= max <= val
        Cmp::GtEq => hi == Greater, // every value <= max < val
    }
}

/// `field <op> value`, against a [`Lens`] schema field.
///
/// Pushed down as **Inexact**: the query engine re-applies the predicate above the scan, so this is
/// only ever allowed to return EXTRA rows, never to drop a row that should match. That asymmetry is
/// what makes it safe to be conservative — an unknown type, an absent column, a null all keep the row
/// and cost nothing but a little work upstream.
#[derive(Clone, Debug)]
pub struct Pred {
    pub field: usize,
    pub op: Cmp,
    pub val: AttrValue,
}

/// What a scan actually touched. Exists so that "projection avoids the fold" is a measurement.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ScanStats {
    /// Successful SQL planning and execution-stream startup time.
    pub planning_duration_ns: u64,
    /// Cumulative time spent actively pulling and encoding result batches, excluding consumer idle.
    pub execution_duration_ns: u64,
    pub rows: usize,
    pub batches: usize,
    /// Attribute column sections decoded. A projected scan should decode only what it projects.
    pub columns_decoded: usize,
    /// Present content values reconstructed out of the fold. Zero unless content was projected.
    pub fold_reads: usize,
    /// Rows a pushed-down predicate excluded before any array was built. Content among them was
    /// never reconstructed, which is the entire point.
    pub rows_filtered: usize,
    /// Physical rows hidden by a newer version or tombstone. These are resolved before predicates, so
    /// an older version can never reappear merely because the newest one fails a filter.
    pub rows_hidden: usize,
    /// Batches skipped whole because no row in them could match.
    pub batches_skipped: usize,
    /// Occurrences hidden by the flat column view: a row that names one key several times surfaces its
    /// FIRST value here. Counted, never silent — the full interleaved sequence stays available through
    /// [`Part::record`].
    pub shadowed_occurrences: usize,
}

impl ScanStats {
    /// What happened between `prev` and now. A lazy scan publishes progress by delta, so a query that
    /// stops early (LIMIT, an error, a dropped stream) reports what it actually touched.
    pub fn since(&self, prev: ScanStats) -> ScanStats {
        ScanStats {
            planning_duration_ns: self.planning_duration_ns - prev.planning_duration_ns,
            execution_duration_ns: self.execution_duration_ns - prev.execution_duration_ns,
            rows: self.rows - prev.rows,
            batches: self.batches - prev.batches,
            columns_decoded: self.columns_decoded - prev.columns_decoded,
            fold_reads: self.fold_reads - prev.fold_reads,
            rows_filtered: self.rows_filtered - prev.rows_filtered,
            rows_hidden: self.rows_hidden - prev.rows_hidden,
            batches_skipped: self.batches_skipped - prev.batches_skipped,
            shadowed_occurrences: self.shadowed_occurrences - prev.shadowed_occurrences,
        }
    }

    pub fn add(&mut self, o: ScanStats) {
        self.planning_duration_ns =
            self.planning_duration_ns.saturating_add(o.planning_duration_ns);
        self.execution_duration_ns =
            self.execution_duration_ns.saturating_add(o.execution_duration_ns);
        self.rows += o.rows;
        self.batches += o.batches;
        self.columns_decoded += o.columns_decoded;
        self.fold_reads += o.fold_reads;
        self.rows_filtered += o.rows_filtered;
        self.rows_hidden += o.rows_hidden;
        self.batches_skipped += o.batches_skipped;
        self.shadowed_occurrences += o.shadowed_occurrences;
    }
}

/// A stable row shape over a set of parts, and the machinery to read batches through it.
pub struct Lens {
    schema: SchemaRef,
    /// What each schema field means independently of its collision-safe display name.
    binding: Vec<Binding>,
    /// The committed newest-wins rows for each part in this lens.
    ///
    /// The `Arc<Part>` is retained so a scan can identify its mask by pointer identity without adding
    /// storage-format identity to `Part`'s public API.
    visible: Vec<(Arc<Part>, Arc<Vec<usize>>)>,
}

#[derive(Clone)]
enum Binding {
    Id,
    Content(String),
    Attr(String, u8),
}

fn content_field(name: &str) -> String {
    if name == crate::types::BODY_CONTENT {
        F_BODY.to_string()
    } else {
        format!("content.{name}")
    }
}

impl Lens {
    /// Derive the row shape from the parts that will be scanned.
    pub fn new(parts: &[Arc<Part>]) -> Result<Lens> {
        let visibility = crate::store::read::visibility(parts)?;

        // Which types does each key carry, across every part?
        let mut tags: BTreeMap<String, BTreeSet<u8>> = BTreeMap::new();
        for p in parts {
            if !p.has_columns() {
                continue;
            }
            for (key, tag, _, _) in attrs::read_meta(p)? {
                tags.entry(key).or_default().insert(tag);
            }
        }

        let mut content_names = BTreeSet::new();
        for p in parts {
            for content in p.content_meta()?.iter() {
                content_names.insert(content.name.clone());
            }
        }

        let mut fields = vec![Field::new(F_ID, DataType::Utf8, false)];
        let mut binding = vec![Binding::Id];
        // Field names must be UNIQUE, and nothing about the data guarantees it. An attribute literally
        // named `id` or `body` collides with the synthesised columns; a key literally named `a#str`
        // collides with the disambiguation of a multi-typed `a`. DataFusion rejects a duplicate at
        // TABLE REGISTRATION, so either case made the whole store unqueryable — including
        // `select count(*)` — rather than affecting only the offending column.
        //
        // Resolved by construction instead of by hoping: take the natural name if it is free, fall
        // back to `key#type`, and only then to an ordinal. Renaming a column is a far smaller harm
        // than refusing to answer any query at all.
        let mut used: std::collections::HashSet<String> =
            [F_ID].into_iter().map(String::from).collect();
        for name in content_names {
            let field = content_field(&name);
            // Content names are unique and namespaced, so this can collide only with the synthetic id
            // when a future naming rule changes. Refuse internally rather than create an ambiguous
            // schema; attribute collisions below are renamed because their source keys remain bound.
            if !used.insert(field.clone()) {
                bail!("content {name:?} maps to duplicate query field {field:?}");
            }
            fields.push(Field::new(&field, DataType::Binary, true));
            binding.push(Binding::Content(name));
        }
        for (key, ts) in &tags {
            for &t in ts {
                // A key with one type keeps its name. A key with several is never silently merged.
                let mut name = if ts.len() == 1 && t != 7 {
                    key.clone()
                } else {
                    format!("{key}#{}", type_name(t))
                };
                if used.contains(&name) {
                    name = format!("{key}#{}", type_name(t));
                }
                let mut n = 2usize;
                while used.contains(&name) {
                    name = format!("{key}#{}#{n}", type_name(t));
                    n += 1;
                }
                used.insert(name.clone());
                fields.push(Field::new(&name, arrow_type(t), true));
                binding.push(Binding::Attr(key.clone(), t));
            }
        }
        let visible =
            parts.iter().cloned().zip(visibility.rows.into_iter().map(Arc::new)).collect();
        Ok(Lens { schema: Arc::new(Schema::new(fields)), binding, visible })
    }

    pub fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    /// Field indices for a projection given by name, in the order asked for.
    pub fn project(&self, names: &[&str]) -> Result<Vec<usize>> {
        names
            .iter()
            .map(|n| {
                self.schema
                    .index_of(n)
                    .map_err(|_| anyhow::anyhow!("no column {n:?} in this store"))
            })
            .collect()
    }

    pub(crate) fn projection_reads_content(&self, projection: &[usize]) -> bool {
        projection.iter().any(|&f| matches!(self.binding.get(f), Some(Binding::Content(_))))
    }

    /// Stream `part` as batches under `projection` (field indices into [`Lens::schema`]).
    ///
    /// `fold` is required only if the projection includes content; passing `None` otherwise makes it
    /// impossible for a scan to touch content by accident.
    pub fn scan(
        &self,
        part: &Arc<Part>,
        fold: Option<&Arc<Fold>>,
        projection: &[usize],
        preds: &[Pred],
    ) -> Result<PartScan> {
        let proj: Vec<usize> = projection.to_vec();
        for &f in &proj {
            if f >= self.binding.len() {
                bail!("projection names field {f}, past the end of the schema");
            }
        }
        if self.projection_reads_content(&proj) && fold.is_none() {
            bail!("a content column was projected but no fold was supplied to read it from");
        }
        let fields: Vec<Field> = proj.iter().map(|&f| self.schema.field(f).clone()).collect();
        let out_schema = Arc::new(Schema::new(fields));

        // Resolve each projected field to a part-local column ONCE, not per batch. A field this part
        // lacks resolves to None and yields nulls, which is how parts with different columns share a
        // schema.
        let meta = if part.has_columns() { attrs::read_meta(part)? } else { Vec::new() };
        let mut cols: Vec<Col> = Vec::with_capacity(proj.len());
        let mut decoded = 0usize;
        for &f in &proj {
            match &self.binding[f] {
                Binding::Id => cols.push(Col::Id),
                Binding::Content(name) => cols.push(Col::Content(name.clone())),
                Binding::Attr(key, tag) => {
                    let want = (key.clone(), *tag);
                    match meta.iter().position(|(k, t, _, _)| *k == want.0 && *t == want.1) {
                        Some(c) => {
                            let (_, tag, occ, kind) = meta[c].clone();
                            decoded += 1;
                            cols.push(Col::Attr {
                                tag,
                                rids: attrs::rids(part, c, occ, kind)?,
                                val: part.column_values(c)?,
                                dict: if tag == 0 {
                                    attrs::read_dict(part, c)?
                                } else {
                                    Default::default()
                                },
                                binary_dict: if tag == 5 {
                                    attrs::read_binary_dict(part, c)?
                                } else {
                                    Default::default()
                                },
                            });
                        }
                        None => cols.push(Col::Missing(self.schema.field(f).data_type().clone())),
                    }
                }
            }
        }

        // Ids are decoded once for the whole part and sliced per batch — the column is front-coded, so
        // there is no meaningful way to start decoding from the middle.
        // Resolve each predicate against THIS part's columns, once. A string literal is located in the
        // sorted dictionary here, so the per-row work is a u32 comparison rather than a string one —
        // the dictionary encoding earning its keep at exactly the point a query engine can use it.
        let mut tests: Vec<Test> = Vec::with_capacity(preds.len());
        for p_ in preds {
            let Some(Binding::Attr(key, tag)) = self.binding.get(p_.field).cloned() else {
                continue; // id/content: not evaluated here, the engine filters them
            };
            let Some(c) = meta.iter().position(|(k, t, _, _)| *k == key && *t == tag) else {
                // this part has no such column, so every row is null and none can match
                tests.push(Test::Never);
                continue;
            };
            // Zone pruning: when the column's recorded [min, max] PROVES this predicate can match
            // no row of the part, no section of the column is decoded at all — placed before the
            // rid decode on purpose. Conservative twice over: the zone reader resolves every doubt
            // to None, and the disproof compares only exactly-matching types.
            if let Some(zone) = part.zone(c)? {
                if zone_disproves(p_.op, &p_.val, &zone) {
                    tests.push(Test::Never);
                    continue;
                }
            }
            let (_, tag, occ, kind) = meta[c].clone();
            let rids = attrs::rids(part, c, occ, kind)?;
            let k = match (&p_.val, tag) {
                (AttrValue::Str(v), 0) => {
                    let dict = attrs::read_dict(part, c)?;
                    match dict.binary_search_by(|d| d.as_str().cmp(v.as_str())) {
                        Ok(i) => Key::Ord { k: i as u32, exact: true },
                        Err(i) => Key::Ord { k: i as u32, exact: false },
                    }
                }
                (AttrValue::Int(v), 1) => Key::Int(*v),
                (AttrValue::Float(v), 2) => Key::Float(*v),
                (AttrValue::Bool(v), 3) => Key::Bool(*v),
                (AttrValue::UInt(v), 4) => Key::UInt(*v),
                (AttrValue::Bytes(v), 5) => {
                    let dict = attrs::read_binary_dict(part, c)?;
                    match dict.binary_search(v) {
                        Ok(i) => Key::Ord { k: i as u32, exact: true },
                        Err(i) => Key::Ord { k: i as u32, exact: false },
                    }
                }
                (AttrValue::TimestampNs(v), 6) => Key::TimestampNs(*v),
                (AttrValue::Null, 7) => Key::Null,
                // Literal type does not match the column type. Keeping every row is the safe
                // direction under Inexact.
                _ => {
                    tests.push(Test::Present { rids });
                    continue;
                }
            };
            tests.push(Test::Col { tag, rids, val: part.column_values(c)?, op: p_.op, key: k });
        }

        let ids = if cols.iter().any(|c| matches!(c, Col::Id)) {
            part.ids()?
        } else {
            Arc::new(Vec::new())
        };
        let visible = self
            .visible
            .iter()
            .find(|(p, _)| Arc::ptr_eq(p, part))
            .map(|(_, rows)| rows.clone())
            .ok_or_else(|| anyhow::anyhow!("part is not a member of this lens snapshot"))?;

        Ok(PartScan {
            n: part.len(),
            part: part.clone(),
            fold: fold.cloned(),
            schema: out_schema,
            cols,
            ids,
            row: 0,
            stats: ScanStats { columns_decoded: decoded, ..ScanStats::default() },
            fetch: None,
            tests,
            visible,
        })
    }
}

/// A predicate resolved against one part's columns.
enum Test {
    /// No row in this part can match — the batch, and often the part, is skippable without reading.
    Never,
    /// Everything with a value matches; only nulls are excluded.
    Present {
        rids: Arc<Vec<u32>>,
    },
    Col {
        tag: u8,
        rids: Arc<Vec<u32>>,
        val: Arc<Vec<u8>>,
        op: Cmp,
        key: Key,
    },
}

#[derive(Clone, Copy)]
enum Key {
    /// A dictionary ordinal. `exact` is false when the literal is absent and `k` is its insertion
    /// point — which still answers every ORDER comparison, because the dictionary is sorted.
    Ord {
        k: u32,
        exact: bool,
    },
    Int(i64),
    Float(f64),
    Bool(bool),
    UInt(u64),
    TimestampNs(i64),
    Null,
}

#[inline]
fn cmp_ok<T: PartialOrd>(op: Cmp, v: T, k: T) -> bool {
    match op {
        Cmp::Eq => v == k,
        Cmp::Ne => v != k,
        Cmp::Lt => v < k,
        Cmp::LtEq => v <= k,
        Cmp::Gt => v > k,
        Cmp::GtEq => v >= k,
    }
}

/// The borrowed payload of a column comparison: `(tag, encoded values, operator, key)`.
type ColTest<'a> = (&'a u8, &'a Arc<Vec<u8>>, &'a Cmp, &'a Key);

impl Test {
    /// Mark rows in `lo..hi` that match. Rows with no value stay unmarked, which is correct: a
    /// comparison against NULL is NULL, and NULL does not pass a filter.
    fn mark(&self, lo: usize, hi: usize, out: &mut [bool]) {
        let (rids, body): (&Arc<Vec<u32>>, Option<ColTest<'_>>) = match self {
            Test::Never => return,
            Test::Present { rids } => (rids, None),
            Test::Col { tag, rids, val, op, key } => (rids, Some((tag, val, op, key))),
        };
        let mut k = rids.partition_point(|&x| (x as usize) < lo);
        while k < rids.len() && (rids[k] as usize) < hi {
            let slot = rids[k] as usize - lo;
            let ok = match body {
                None => true,
                Some((tag, val, op, key)) => {
                    let w = attrs::width(*tag);
                    let o = k * w;
                    if o + w > val.len() {
                        true // malformed: keep the row, Inexact lets the engine decide
                    } else {
                        match (*tag, key) {
                            (0, Key::Ord { k: kk, exact }) => {
                                let v = u32::from_le_bytes(val[o..o + 4].try_into().unwrap());
                                if *exact {
                                    cmp_ok(*op, v, *kk)
                                } else {
                                    // literal absent from the dictionary: equality cannot hold, and
                                    // every ordering question is answered by the insertion point
                                    match op {
                                        Cmp::Eq => false,
                                        Cmp::Ne => true,
                                        Cmp::Lt | Cmp::LtEq => v < *kk,
                                        Cmp::Gt | Cmp::GtEq => v >= *kk,
                                    }
                                }
                            }
                            (1, Key::Int(kk)) => cmp_ok(
                                *op,
                                i64::from_le_bytes(val[o..o + 8].try_into().unwrap()),
                                *kk,
                            ),
                            (2, Key::Float(kk)) => cmp_ok(
                                *op,
                                f64::from_bits(u64::from_le_bytes(
                                    val[o..o + 8].try_into().unwrap(),
                                )),
                                *kk,
                            ),
                            (3, Key::Bool(kk)) => cmp_ok(*op, val[o] != 0, *kk),
                            (4, Key::UInt(kk)) => cmp_ok(
                                *op,
                                u64::from_le_bytes(val[o..o + 8].try_into().unwrap()),
                                *kk,
                            ),
                            (5, Key::Ord { k: kk, exact }) => {
                                let v = u32::from_le_bytes(val[o..o + 4].try_into().unwrap());
                                if *exact {
                                    cmp_ok(*op, v, *kk)
                                } else {
                                    match op {
                                        Cmp::Eq => false,
                                        Cmp::Ne => true,
                                        Cmp::Lt | Cmp::LtEq => v < *kk,
                                        Cmp::Gt | Cmp::GtEq => v >= *kk,
                                    }
                                }
                            }
                            (6, Key::TimestampNs(kk)) => cmp_ok(
                                *op,
                                i64::from_le_bytes(val[o..o + 8].try_into().unwrap()),
                                *kk,
                            ),
                            (7, Key::Null) => matches!(op, Cmp::Eq),
                            _ => true, // type mismatch: keep it
                        }
                    }
                }
            };
            if ok {
                out[slot] = true;
            }
            k += 1;
        }
    }
}

enum Col {
    Id,
    Content(String),
    Attr {
        tag: u8,
        rids: Arc<Vec<u32>>,
        val: Arc<Vec<u8>>,
        dict: Arc<Vec<String>>,
        binary_dict: Arc<Vec<Vec<u8>>>,
    },
    /// This part has no such column; the batch contributes nulls of the right type.
    Missing(DataType),
}

/// A lazy batch stream over one part. Holds every column's decoded handles, so per-batch work is a
/// bounded scatter and nothing is re-decoded.
///
/// Owns its handles rather than borrowing them — everything it needs is already reference-counted, and
/// a borrowing scan could never become a `'static` stream, which is what a query engine requires.
pub struct PartScan {
    part: Arc<Part>,
    fold: Option<Arc<Fold>>,
    schema: SchemaRef,
    cols: Vec<Col>,
    ids: Arc<Vec<String>>,
    row: usize,
    n: usize,
    stats: ScanStats,
    /// Stop after this many rows. A LIMIT the query engine pushed down.
    fetch: Option<usize>,
    /// Pushed-down predicates, resolved to this part's columns. Conjunctive.
    tests: Vec<Test>,
    /// Rows that survive newest-wins resolution across the whole lens snapshot.
    visible: Arc<Vec<usize>>,
}

impl PartScan {
    pub fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    /// What this scan has touched so far. Grows as batches are pulled, because the scan is lazy.
    pub fn stats(&self) -> ScanStats {
        self.stats
    }

    pub fn rows_remaining(&self) -> usize {
        self.n - self.row
    }

    /// Bound this scan to `n` rows.
    ///
    /// Streaming alone bounds MEMORY, not WORK: a consumer that wants one row still triggers a whole
    /// batch, and a batch of bodies is BATCH_BYTES of fold reads — per part, since every partition
    /// executes. Carrying the limit down is what makes `LIMIT 1` cost one row instead of one batch
    /// times the part count.
    pub fn with_fetch(mut self, n: Option<usize>) -> Self {
        self.fetch = n;
        self
    }

    /// Row offsets within `lo..cap` that survive every pushed-down predicate.
    ///
    /// Conjunctive: a row must be marked by all of them. With no predicates this is every row, and the
    /// cost is one allocation.
    fn select(&self, lo: usize, cap: usize) -> Vec<usize> {
        let n = cap - lo;
        let start = self.visible.partition_point(|&row| row < lo);
        let visible: Vec<usize> = self.visible[start..]
            .iter()
            .take_while(|&&row| row < cap)
            .map(|&row| row - lo)
            .collect();
        if self.tests.is_empty() {
            return visible;
        }
        let mut keep = vec![false; n];
        for &row in &visible {
            keep[row] = true;
        }
        let mut scratch = vec![false; n];
        for t in &self.tests {
            if matches!(t, Test::Never) {
                return Vec::new();
            }
            scratch.iter_mut().for_each(|b| *b = false);
            t.mark(lo, cap, &mut scratch);
            for i in 0..n {
                keep[i] &= scratch[i];
            }
        }
        (0..n).filter(|&i| keep[i]).collect()
    }

    /// The next batch, or `None` at the end of the part.
    pub fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
        if self.fetch.is_some_and(|f| self.stats.rows >= f) {
            return Ok(None);
        }
        let end = self.n;
        if self.row >= end {
            return Ok(None);
        }
        // Find a window with at least one surviving row. Predicates are evaluated over ATTRIBUTE
        // columns only, so a batch that matches nothing is skipped without opening the fold — which is
        // the whole reason to push a filter down here rather than let the engine do it above.
        let (lo, take) = loop {
            if self.row >= end {
                return Ok(None);
            }
            let lo = self.row;
            let cap = (lo + BATCH_ROWS).min(end);
            let take = self.select(lo, cap);
            if take.is_empty() {
                // A skipped window is consumed whole, so its accounting is final here. A window
                // that produces a batch is NOT: fetch and byte ceilings can close the batch early,
                // and rows past the last consumed one are re-examined by the next call — counting
                // them now would double-count them then. Their accounting waits until the close
                // point is known.
                let first = self.visible.partition_point(|&row| row < lo);
                let visible = self.visible.partition_point(|&row| row < cap) - first;
                self.stats.rows_hidden += (cap - lo) - visible;
                self.stats.rows_filtered += visible;
                self.stats.batches_skipped += 1;
                self.row = cap;
                continue;
            }
            break (lo, take);
        };

        // Content is reconstructed FIRST, because it is what decides how many rows this batch can hold
        // — and only for rows that survived the filter.
        let mut content_values: Vec<Option<Vec<Option<Vec<u8>>>>> =
            self.cols.iter().map(|c| matches!(c, Col::Content(_)).then(Vec::new)).collect();
        let mut take = take;
        if let Some(fetch) = self.fetch {
            take.truncate(fetch - self.stats.rows);
        }
        if self.cols.iter().any(|c| matches!(c, Col::Content(_))) {
            let fold = self.fold.as_ref().expect("checked when the scan was built");
            let mut bytes = 0usize;
            for (i, &r) in take.iter().enumerate() {
                for (c, values) in self.cols.iter().zip(&mut content_values) {
                    let Col::Content(name) = c else { continue };
                    let value = self.part.reconstruct_content(lo + r, name, fold)?;
                    if let Some(b) = &value {
                        // Arrow's Binary array indexes with i32 offsets, so 2 GiB is a hard ceiling
                        // on one value. Refuse rather than overflow the builder's offsets.
                        if b.len() > i32::MAX as usize {
                            bail!(
                                "content {name:?} at row {} is {} bytes; an Arrow binary column \
                                 cannot exceed 2 GiB. Read it through Store::reconstruct_content.",
                                lo + r,
                                b.len()
                            );
                        }
                        bytes += b.len();
                        self.stats.fold_reads += 1;
                    }
                    values.as_mut().expect("content column allocated above").push(value);
                }
                // At least one row always lands, however large it is — otherwise a single record
                // bigger than the ceiling could never be read at all.
                if bytes >= BATCH_BYTES {
                    take.truncate(i + 1);
                    break;
                }
            }
        }
        // Resume after the last row consumed, not after the last row examined.
        let hi = lo + take.last().copied().map_or(0, |r| r + 1);
        let len = take.len();
        // Deferred window accounting, over exactly [lo, hi): what this batch consumed. Selected
        // rows past `hi` were examined but will be selected again next call; hidden and filtered
        // rows past `hi` will be re-derived then. Counting to `cap` here made both counters drift
        // upward whenever fetch or the byte ceiling closed a batch early.
        let first = self.visible.partition_point(|&row| row < lo);
        let consumed_visible = self.visible.partition_point(|&row| row < hi) - first;
        self.stats.rows_hidden += (hi - lo) - consumed_visible;
        self.stats.rows_filtered += consumed_visible - len;
        let mut arrays: Vec<ArrayRef> = Vec::with_capacity(self.cols.len());

        for (column, values) in self.cols.iter().zip(&content_values) {
            arrays.push(match column {
                Col::Id => Arc::new(StringArray::from(
                    take.iter().map(|&r| self.ids[lo + r].as_str()).collect::<Vec<_>>(),
                )) as ArrayRef,
                Col::Content(_) => {
                    let mut b = BinaryBuilder::new();
                    for value in values.as_ref().expect("built above when content is projected") {
                        match value {
                            Some(v) => b.append_value(v),
                            None => b.append_null(),
                        }
                    }
                    Arc::new(b.finish()) as ArrayRef
                }
                Col::Missing(t) => arrow::array::new_null_array(t, len),
                Col::Attr { tag, rids, val, dict, binary_dict } => scatter(
                    *tag,
                    rids,
                    val,
                    dict,
                    binary_dict,
                    lo,
                    hi,
                    &take,
                    &mut self.stats.shadowed_occurrences,
                )?,
            });
        }

        self.row = hi;
        self.stats.rows += len;
        self.stats.batches += 1;
        // The row count is carried explicitly because a projection can legitimately be EMPTY —
        // `SELECT count(*)` needs the cardinality and nothing else, and a batch with no columns has
        // no other way to say how many rows it stands for.
        Ok(Some(RecordBatch::try_new_with_options(
            self.schema.clone(),
            arrays,
            &RecordBatchOptions::new().with_row_count(Some(len)),
        )?))
    }
}

/// Scatter a sparse `(rid, val)` column into a dense array over rows `lo..hi`.
///
/// Rows absent from `rid` become null. A row present more than once keeps its FIRST occurrence and
/// counts the rest as shadowed — a flat column cannot represent a repeated key, and dropping them
/// silently would be a lie about the data.
// Same reasoning as `part::build_full`: eight independent inputs describing one scatter, not a
// bag of options that wants a struct.
#[allow(clippy::too_many_arguments)]
fn scatter(
    tag: u8,
    rids: &[u32],
    val: &[u8],
    dict: &[String],
    binary_dict: &[Vec<u8>],
    lo: usize,
    hi: usize,
    take: &[usize],
    shadowed: &mut usize,
) -> Result<ArrayRef> {
    let span = hi - lo;
    let start = rids.partition_point(|&x| (x as usize) < lo);
    let mut by_row: Vec<Option<usize>> = vec![None; span];
    let mut k = start;
    while k < rids.len() && (rids[k] as usize) < hi {
        let slot = rids[k] as usize - lo;
        if by_row[slot].is_none() {
            by_row[slot] = Some(k);
        } else {
            *shadowed += 1;
        }
        k += 1;
    }
    // Compact to the rows that survived the filter, in order.
    let len = take.len();
    let taken: Vec<Option<usize>> = take.iter().map(|&r| by_row[r]).collect();

    let w = attrs::width(tag);
    let at = |k: usize| -> Result<&[u8]> {
        let o = k * w;
        if o + w > val.len() {
            bail!("column value {k} runs past its section");
        }
        Ok(&val[o..o + w])
    };

    Ok(match tag {
        // Ordinals stay ordinals: the part's sorted distinct dictionary IS an Arrow dictionary, so the
        // encoding survives the boundary instead of being flattened into repeated strings.
        0 => {
            let keys: Vec<Option<i32>> = taken
                .iter()
                .map(|t| match *t {
                    Some(k) => {
                        let o = k * 4;
                        if o + 4 > val.len() {
                            None
                        } else {
                            Some(u32::from_le_bytes(val[o..o + 4].try_into().unwrap()) as i32)
                        }
                    }
                    None => None,
                })
                .collect();
            let values = StringArray::from(dict.iter().map(|s| s.as_str()).collect::<Vec<_>>());
            Arc::new(arrow::array::DictionaryArray::try_new(
                Int32Array::from(keys),
                Arc::new(values),
            )?) as ArrayRef
        }
        1 => {
            let mut b = Int64Builder::with_capacity(len);
            for t in &taken {
                match *t {
                    Some(k) => b.append_value(i64::from_le_bytes(at(k)?.try_into().unwrap())),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        2 => {
            let mut b = Float64Builder::with_capacity(len);
            for t in &taken {
                match *t {
                    // from_bits, not from a float parse: -0.0 and NaN payloads round-trip exactly
                    Some(k) => b.append_value(f64::from_bits(u64::from_le_bytes(
                        at(k)?.try_into().unwrap(),
                    ))),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        3 => {
            let mut b = BooleanBuilder::with_capacity(len);
            for t in &taken {
                match *t {
                    Some(k) => b.append_value(at(k)?[0] != 0),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        4 => {
            let mut b = UInt64Builder::with_capacity(len);
            for t in &taken {
                match *t {
                    Some(k) => b.append_value(u64::from_le_bytes(at(k)?.try_into().unwrap())),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        5 => {
            let keys: Vec<Option<i32>> = taken
                .iter()
                .map(|t| match *t {
                    Some(k) => {
                        let bytes = at(k).ok()?;
                        Some(u32::from_le_bytes(bytes.try_into().ok()?) as i32)
                    }
                    None => None,
                })
                .collect();
            let values = BinaryArray::from_iter_values(binary_dict.iter().map(Vec::as_slice));
            Arc::new(arrow::array::DictionaryArray::try_new(
                Int32Array::from(keys),
                Arc::new(values),
            )?)
        }
        6 => {
            let mut b = TimestampNanosecondBuilder::with_capacity(len).with_timezone("UTC");
            for t in &taken {
                match *t {
                    Some(k) => b.append_value(i64::from_le_bytes(at(k)?.try_into().unwrap())),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        7 => {
            let mut b = BooleanBuilder::with_capacity(len);
            for t in &taken {
                match *t {
                    Some(_) => b.append_value(true),
                    None => b.append_null(),
                }
            }
            Arc::new(b.finish())
        }
        t => bail!("unknown attribute type tag {t}"),
    })
}

/// Materialise every batch of a projection over many parts. Convenience for tests and small scans;
/// large scans should drive [`PartScan`] directly, or go through DataFusion.
pub fn collect(
    parts: &[Arc<Part>],
    fold: Option<&Arc<Fold>>,
    lens: &Lens,
    projection: &[usize],
) -> Result<(Vec<RecordBatch>, ScanStats)> {
    collect_where(parts, fold, lens, projection, &[])
}

/// [`collect`] with pushed-down predicates.
pub fn collect_where(
    parts: &[Arc<Part>],
    fold: Option<&Arc<Fold>>,
    lens: &Lens,
    projection: &[usize],
    preds: &[Pred],
) -> Result<(Vec<RecordBatch>, ScanStats)> {
    let mut stats = ScanStats::default();
    let mut out = Vec::new();
    for p in parts {
        let mut sc = lens.scan(p, fold, projection, preds)?;
        while let Some(b) = sc.next_batch()? {
            out.push(b);
        }
        stats.add(sc.stats());
    }
    Ok((out, stats))
}

/// A `StringBuilder`-based flat view of a dictionary column, for callers that want plain strings.
pub fn flatten_strings(a: &ArrayRef) -> Result<ArrayRef> {
    use arrow::array::{Array, AsArray};
    let d = a
        .as_any()
        .downcast_ref::<arrow::array::DictionaryArray<arrow::datatypes::Int32Type>>()
        .ok_or_else(|| anyhow::anyhow!("not a dictionary column"))?;
    let values = d.values().as_string::<i32>();
    let mut b = StringBuilder::new();
    for i in 0..d.len() {
        match d.key(i) {
            Some(k) => b.append_value(values.value(k)),
            None => b.append_null(),
        }
    }
    Ok(Arc::new(b.finish()))
}