Skip to main content

coip_reader/
table_reader.rs

1//! ColumnTable & DictTables readers with rank-indexed validity bitmaps and LRU chunk caches.
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, OnceLock};
5
6use coip_format::{
7    ChunkHeader, ColumnTableHeader, ColumnType, Cursor, DictKind, EncMode, FlatDictHeader,
8    FormatError, IdWidth, ListDictHeader, NullMode, PType, PhysicalColKind, Schema, StructSchema,
9    TableSchema, Value, read_svarint, read_uvarint,
10};
11
12use crate::cache::ShardedLruCache;
13use crate::codec::decompress;
14use crate::error::{ReaderError, Result};
15use crate::projection::ProjectionNode;
16use crate::source::Backing;
17
18/// Zero-copy borrowed scalar reference directly into a cached `DecodedChunk` or `DecodedFlatBlock`.
19#[derive(Debug, Clone, Copy)]
20pub enum ScalarRef<'a> {
21    Bool(bool),
22    U8(u8),
23    U16(u16),
24    U32(u32),
25    U64(u64),
26    U128(u128),
27    I32(i32),
28    I64(i64),
29    F32(f32),
30    F64(f64),
31    Utf8(&'a str),
32    Bytes(&'a [u8]),
33    Dynamic(&'a [u8]),
34}
35
36/// Rank-indexed validity storage for O(1) dense-index lookup inside a RowGroup chunk.
37enum Validity {
38    AllValid,
39    AllNull,
40    Bitmap {
41        words: Vec<u64>,
42        word_ranks: Vec<u32>,
43    },
44}
45
46impl Validity {
47    fn from_bytes(bytes: &[u8]) -> Self {
48        let word_count = bytes.len().div_ceil(8);
49        let mut words = Vec::with_capacity(word_count);
50        let mut word_ranks = Vec::with_capacity(word_count);
51        let mut rank = 0u32;
52        for w in 0..word_count {
53            let start = w * 8;
54            let end = (start + 8).min(bytes.len());
55            let mut arr = [0u8; 8];
56            arr[..end - start].copy_from_slice(&bytes[start..end]);
57            let word = u64::from_le_bytes(arr);
58            words.push(word);
59            word_ranks.push(rank);
60            rank += word.count_ones();
61        }
62        Self::Bitmap { words, word_ranks }
63    }
64
65    #[inline]
66    fn valid_count(&self, total_rows: usize) -> usize {
67        match self {
68            Self::AllValid => total_rows,
69            Self::AllNull => 0,
70            Self::Bitmap { words, word_ranks } => {
71                if words.is_empty() {
72                    0
73                } else {
74                    let last = words.len() - 1;
75                    (word_ranks[last] + words[last].count_ones()) as usize
76                }
77            }
78        }
79    }
80
81    /// Map logical row `idx` -> dense value index, or `None` if row is null.
82    #[inline]
83    fn dense_index(&self, idx: usize) -> Option<usize> {
84        match self {
85            Self::AllValid => Some(idx),
86            Self::AllNull => None,
87            Self::Bitmap { words, word_ranks } => {
88                let w = idx >> 6;
89                let b = idx & 63;
90                let word = *words.get(w)?;
91                if ((word >> b) & 1) == 0 {
92                    return None;
93                }
94                let mask = (1u64 << b) - 1;
95                let rank = word_ranks[w] + (word & mask).count_ones();
96                Some(rank as usize)
97            }
98        }
99    }
100}
101
102/// Zero-per-string-allocation decoded dense values array.
103enum DecodedValues {
104    Empty,
105    ConstBool(bool),
106    ConstU8(u8),
107    ConstU16(u16),
108    ConstU32(u32),
109    ConstU64(u64),
110    ConstU128(u128),
111    ConstI32(i32),
112    ConstI64(i64),
113    ConstF32(f32),
114    ConstF64(f64),
115    ConstBytes(Vec<u8>),
116    Bool(Vec<u8>),
117    U8(Vec<u8>),
118    U16(Vec<u16>),
119    U32(Vec<u32>),
120    U64(Vec<u64>),
121    U128(Vec<u128>),
122    I32(Vec<i32>),
123    I64(Vec<i64>),
124    F32(Vec<f32>),
125    F64(Vec<f64>),
126    VarBytes { offsets: Vec<u32>, data: Vec<u8> },
127}
128
129impl DecodedValues {
130    #[inline]
131    fn get_scalar_ref(&self, dense_idx: usize, kind: PhysicalColKind) -> Result<ScalarRef<'_>> {
132        match (self, kind) {
133            (Self::ConstBool(v), _) => Ok(ScalarRef::Bool(*v)),
134            (Self::ConstU8(v), _) => Ok(ScalarRef::U8(*v)),
135            (Self::ConstU16(v), _) => Ok(ScalarRef::U16(*v)),
136            (Self::ConstU32(v), _) => Ok(ScalarRef::U32(*v)),
137            (Self::ConstU64(v), _) => Ok(ScalarRef::U64(*v)),
138            (Self::ConstU128(v), _) => Ok(ScalarRef::U128(*v)),
139            (Self::ConstI32(v), _) => Ok(ScalarRef::I32(*v)),
140            (Self::ConstI64(v), _) => Ok(ScalarRef::I64(*v)),
141            (Self::ConstF32(v), _) => Ok(ScalarRef::F32(*v)),
142            (Self::ConstF64(v), _) => Ok(ScalarRef::F64(*v)),
143            (Self::ConstBytes(b), PhysicalColKind::Primitive(PType::Utf8)) => {
144                let s = std::str::from_utf8(b).map_err(|_| FormatError::InvalidUtf8)?;
145                Ok(ScalarRef::Utf8(s))
146            }
147            (Self::ConstBytes(b), PhysicalColKind::Primitive(PType::Bytes)) => {
148                Ok(ScalarRef::Bytes(b))
149            }
150            (Self::ConstBytes(b), PhysicalColKind::Dynamic) => Ok(ScalarRef::Dynamic(b)),
151            (Self::Bool(bits), _) => {
152                let byte = *bits
153                    .get(dense_idx >> 3)
154                    .ok_or_else(|| ReaderError::Corrupt("bool index OOB".into()))?;
155                Ok(ScalarRef::Bool(((byte >> (dense_idx & 7)) & 1) != 0))
156            }
157            (Self::U8(v), _) => Ok(ScalarRef::U8(v[dense_idx])),
158            (Self::U16(v), _) => Ok(ScalarRef::U16(v[dense_idx])),
159            (Self::U32(v), _) => Ok(ScalarRef::U32(v[dense_idx])),
160            (Self::U64(v), _) => Ok(ScalarRef::U64(v[dense_idx])),
161            (Self::U128(v), _) => Ok(ScalarRef::U128(v[dense_idx])),
162            (Self::I32(v), _) => Ok(ScalarRef::I32(v[dense_idx])),
163            (Self::I64(v), _) => Ok(ScalarRef::I64(v[dense_idx])),
164            (Self::F32(v), _) => Ok(ScalarRef::F32(v[dense_idx])),
165            (Self::F64(v), _) => Ok(ScalarRef::F64(v[dense_idx])),
166            (Self::VarBytes { offsets, data }, PhysicalColKind::Primitive(PType::Utf8)) => {
167                let s = offsets[dense_idx] as usize;
168                let e = offsets[dense_idx + 1] as usize;
169                let str_slice =
170                    std::str::from_utf8(&data[s..e]).map_err(|_| FormatError::InvalidUtf8)?;
171                Ok(ScalarRef::Utf8(str_slice))
172            }
173            (Self::VarBytes { offsets, data }, PhysicalColKind::Primitive(PType::Bytes)) => {
174                let s = offsets[dense_idx] as usize;
175                let e = offsets[dense_idx + 1] as usize;
176                Ok(ScalarRef::Bytes(&data[s..e]))
177            }
178            (Self::VarBytes { offsets, data }, PhysicalColKind::Dynamic) => {
179                let s = offsets[dense_idx] as usize;
180                let e = offsets[dense_idx + 1] as usize;
181                Ok(ScalarRef::Dynamic(&data[s..e]))
182            }
183            _ => Err(ReaderError::Corrupt(
184                "decoded chunk value kind mismatch".into(),
185            )),
186        }
187    }
188
189    #[inline]
190    fn get_as_value(&self, dense_idx: usize, kind: PhysicalColKind) -> Result<Value> {
191        match self.get_scalar_ref(dense_idx, kind)? {
192            ScalarRef::Bool(v) => Ok(Value::Bool(v)),
193            ScalarRef::U8(v) => Ok(Value::U8(v)),
194            ScalarRef::U16(v) => Ok(Value::U16(v)),
195            ScalarRef::U32(v) => Ok(Value::U32(v)),
196            ScalarRef::U64(v) => Ok(Value::U64(v)),
197            ScalarRef::U128(v) => Ok(Value::U128(v)),
198            ScalarRef::I32(v) => Ok(Value::I32(v)),
199            ScalarRef::I64(v) => Ok(Value::I64(v)),
200            ScalarRef::F32(v) => Ok(Value::F32(v)),
201            ScalarRef::F64(v) => Ok(Value::F64(v)),
202            ScalarRef::Utf8(s) => Ok(Value::Utf8(s.to_owned())),
203            ScalarRef::Bytes(b) => Ok(Value::Bytes(b.to_vec())),
204            ScalarRef::Dynamic(b) => Ok(Value::decode_exact(b)?),
205        }
206    }
207
208    #[inline]
209    fn get_u32_id(&self, dense_idx: usize) -> Result<u32> {
210        match self {
211            Self::ConstU8(v) => Ok(*v as u32),
212            Self::ConstU16(v) => Ok(*v as u32),
213            Self::ConstU32(v) => Ok(*v),
214            Self::U8(v) => Ok(v[dense_idx] as u32),
215            Self::U16(v) => Ok(v[dense_idx] as u32),
216            Self::U32(v) => Ok(v[dense_idx]),
217            _ => Err(ReaderError::Corrupt(
218                "expected U8/U16/U32 dict ID column".into(),
219            )),
220        }
221    }
222
223    #[inline]
224    fn get_bool(&self, dense_idx: usize) -> Result<bool> {
225        match self {
226            Self::ConstBool(v) => Ok(*v),
227            Self::Bool(bits) => Ok(((bits[dense_idx >> 3] >> (dense_idx & 7)) & 1) != 0),
228            _ => Err(ReaderError::Corrupt("expected Bool presence column".into())),
229        }
230    }
231}
232
233pub struct DecodedChunk {
234    validity: Validity,
235    values: DecodedValues,
236    kind: PhysicalColKind,
237}
238
239impl DecodedChunk {
240    #[inline]
241    pub fn get_scalar_ref(&self, row_in_rg: usize) -> Result<Option<ScalarRef<'_>>> {
242        let Some(dense) = self.validity.dense_index(row_in_rg) else {
243            return Ok(None);
244        };
245        Ok(Some(self.values.get_scalar_ref(dense, self.kind)?))
246    }
247
248    #[inline]
249    pub fn get_value(&self, row_in_rg: usize) -> Result<Option<Value>> {
250        let Some(dense) = self.validity.dense_index(row_in_rg) else {
251            return Ok(None);
252        };
253        Ok(Some(self.values.get_as_value(dense, self.kind)?))
254    }
255
256    #[inline]
257    pub fn get_u32(&self, row_in_rg: usize) -> Result<Option<u32>> {
258        let Some(dense) = self.validity.dense_index(row_in_rg) else {
259            return Ok(None);
260        };
261        Ok(Some(self.values.get_u32_id(dense)?))
262    }
263
264    #[inline]
265    pub fn get_bool(&self, row_in_rg: usize) -> Result<Option<bool>> {
266        let Some(dense) = self.validity.dense_index(row_in_rg) else {
267            return Ok(None);
268        };
269        Ok(Some(self.values.get_bool(dense)?))
270    }
271
272    /// For a `List` offsets column (`U32`), compute `(start_elem_in_rg, len, total_elems_in_rg)`.
273    pub fn list_range_in_rg(
274        &self,
275        row_in_rg: usize,
276        rows_in_rg: usize,
277    ) -> Result<Option<(usize, usize, usize)>> {
278        let Some(target_len) = self.get_u32(row_in_rg)? else {
279            return Ok(None);
280        };
281        let mut start = 0usize;
282        let mut total = 0usize;
283        for r in 0..rows_in_rg {
284            if let Some(len) = self.get_u32(r)? {
285                if r < row_in_rg {
286                    start += len as usize;
287                }
288                total += len as usize;
289            }
290        }
291        Ok(Some((start, target_len as usize, total)))
292    }
293}
294
295/// Shared 16-shard LRU cache for decoded `ColumnTable` chunks across `RecordColumns` and all `StructDict`s.
296pub struct ChunkCache {
297    inner: ShardedLruCache<(u32, u16, u32), Arc<DecodedChunk>>,
298}
299
300impl ChunkCache {
301    pub fn new(cap: usize) -> Self {
302        Self {
303            inner: ShardedLruCache::new(cap),
304        }
305    }
306
307    pub fn clear(&self) {
308        self.inner.clear();
309    }
310}
311
312/// Reader for a single `ColumnTable` (`Section 8: RecordColumns` or a `StructDict`).
313pub struct ColumnTableReader {
314    table_id: u32,
315    pub header: ColumnTableHeader,
316    col_kinds: Vec<PhysicalColKind>,
317    chunk_offsets: Vec<u64>,
318    chunks_base_offset: u64,
319    /// Lock-free `OnceLock` cache used for tiny single-RowGroup tables (e.g. `continent`, `country`).
320    single_rg_cache: Option<Vec<OnceLock<Arc<DecodedChunk>>>>,
321}
322
323impl ColumnTableReader {
324    pub fn parse(
325        table_id: u32,
326        backing: &Backing<'_>,
327        offset: u64,
328        len: u64,
329        table_schema: &TableSchema,
330        dict_count: usize,
331    ) -> Result<Self> {
332        let hdr_bytes = backing.read_slice(offset, coip_format::COLUMN_TABLE_HEADER_SIZE)?;
333        let mut c = Cursor::new(&hdr_bytes);
334        let header = ColumnTableHeader::decode(&mut c)?;
335        if header.column_count != table_schema.column_count {
336            return Err(ReaderError::Corrupt(format!(
337                "ColumnTable column_count {} != schema {}",
338                header.column_count, table_schema.column_count
339            )));
340        }
341        let col_kinds = table_schema.physical_column_kinds(dict_count)?;
342        let offsets_count = (header.column_count as usize) * (header.row_group_count as usize + 1);
343        let offsets_bytes_len = offsets_count * 8;
344        let offsets_pos = offset + (coip_format::COLUMN_TABLE_HEADER_SIZE as u64);
345        if (coip_format::COLUMN_TABLE_HEADER_SIZE as u64) + (offsets_bytes_len as u64) > len {
346            return Err(FormatError::UnexpectedEof.into());
347        }
348        let off_bytes = backing.read_slice(offsets_pos, offsets_bytes_len)?;
349        let mut oc = Cursor::new(&off_bytes);
350        let mut chunk_offsets = Vec::with_capacity(offsets_count);
351        for _ in 0..offsets_count {
352            chunk_offsets.push(oc.read_u64()?);
353        }
354        let chunks_base_offset = offsets_pos + (offsets_bytes_len as u64);
355        let single_rg_cache = if header.row_group_count == 1 && header.row_count <= 4096 {
356            Some(
357                (0..header.column_count as usize)
358                    .map(|_| OnceLock::new())
359                    .collect(),
360            )
361        } else {
362            None
363        };
364        Ok(Self {
365            table_id,
366            header,
367            col_kinds,
368            chunk_offsets,
369            chunks_base_offset,
370            single_rg_cache,
371        })
372    }
373
374    /// Decode or fetch from cache chunk `(col_id, rg)` expecting `rows_in_chunk` logical rows.
375    pub fn get_chunk(
376        &self,
377        backing: &Backing<'_>,
378        cache: &ChunkCache,
379        col_id: u16,
380        rg: u32,
381        rows_in_chunk: usize,
382    ) -> Result<Arc<DecodedChunk>> {
383        if let Some(slots) = &self.single_rg_cache {
384            let slot = &slots[col_id as usize];
385            if let Some(hit) = slot.get() {
386                return Ok(Arc::clone(hit));
387            }
388            let decoded =
389                Arc::new(self.decode_chunk_uncached(backing, col_id, rg, rows_in_chunk)?);
390            let stored = slot.get_or_init(|| decoded);
391            return Ok(Arc::clone(stored));
392        }
393
394        let key = (self.table_id, col_id, rg);
395        if let Some(hit) = cache.inner.get(&key) {
396            return Ok(hit);
397        }
398
399        let decoded = Arc::new(self.decode_chunk_uncached(backing, col_id, rg, rows_in_chunk)?);
400        cache.inner.put(key, Arc::clone(&decoded));
401        Ok(decoded)
402    }
403
404    fn decode_chunk_uncached(
405        &self,
406        backing: &Backing<'_>,
407        col_id: u16,
408        rg: u32,
409        rows_in_chunk: usize,
410    ) -> Result<DecodedChunk> {
411        let stride = self.header.row_group_count as usize + 1;
412        let idx = (col_id as usize) * stride + (rg as usize);
413        let rel_start = self.chunk_offsets[idx];
414        let rel_end = self.chunk_offsets[idx + 1];
415        let chunk_len = (rel_end - rel_start) as usize;
416        let raw = backing.read_slice(self.chunks_base_offset + rel_start, chunk_len)?;
417        let kind = self.col_kinds[col_id as usize];
418        decode_chunk(&raw, rows_in_chunk, kind)
419    }
420
421    #[inline]
422    pub fn row_group_of(&self, row_idx: usize) -> (u32, usize, usize) {
423        let rg_size = self.header.row_group_size as usize;
424        let rg = (row_idx / rg_size) as u32;
425        let row_in_rg = row_idx % rg_size;
426        let rows_in_rg = self.header.rows_in_rg(rg);
427        (rg, row_in_rg, rows_in_rg)
428    }
429}
430
431fn decode_chunk(raw: &[u8], rows_in_chunk: usize, kind: PhysicalColKind) -> Result<DecodedChunk> {
432    let hdr = ChunkHeader::decode(raw)?;
433    if hdr.null_mode == NullMode::AllNull {
434        return Ok(DecodedChunk {
435            validity: Validity::AllNull,
436            values: DecodedValues::Empty,
437            kind,
438        });
439    }
440
441    let body = decompress(hdr.codec, &raw[3..], None)?;
442    let mut pos = 0usize;
443    let validity = match hdr.null_mode {
444        NullMode::AllValid => Validity::AllValid,
445        NullMode::AllNull => unreachable!(),
446        NullMode::ValidityBitmap => {
447            let bm_len = rows_in_chunk.div_ceil(8);
448            if pos + bm_len > body.len() {
449                return Err(FormatError::UnexpectedEof.into());
450            }
451            let v = Validity::from_bytes(&body[pos..pos + bm_len]);
452            pos += bm_len;
453            v
454        }
455    };
456    let valid_count = validity.valid_count(rows_in_chunk);
457    let val_bytes = &body[pos..];
458
459    let values = if valid_count == 0 {
460        DecodedValues::Empty
461    } else {
462        decode_values(val_bytes, valid_count, hdr.enc_mode, kind)?
463    };
464
465    Ok(DecodedChunk {
466        validity,
467        values,
468        kind,
469    })
470}
471
472fn decode_values(
473    buf: &[u8],
474    count: usize,
475    enc_mode: EncMode,
476    kind: PhysicalColKind,
477) -> Result<DecodedValues> {
478    let mut c = Cursor::new(buf);
479    match enc_mode {
480        EncMode::Constant => match kind {
481            PhysicalColKind::Primitive(PType::Bool) => {
482                Ok(DecodedValues::ConstBool(c.read_u8()? != 0))
483            }
484            PhysicalColKind::Primitive(PType::U8) => Ok(DecodedValues::ConstU8(c.read_u8()?)),
485            PhysicalColKind::Primitive(PType::U16) => Ok(DecodedValues::ConstU16(c.read_u16()?)),
486            PhysicalColKind::Primitive(PType::U32) => Ok(DecodedValues::ConstU32(c.read_u32()?)),
487            PhysicalColKind::Primitive(PType::U64) => Ok(DecodedValues::ConstU64(c.read_u64()?)),
488            PhysicalColKind::Primitive(PType::U128) => Ok(DecodedValues::ConstU128(c.read_u128()?)),
489            PhysicalColKind::Primitive(PType::I32) => Ok(DecodedValues::ConstI32(c.read_i32()?)),
490            PhysicalColKind::Primitive(PType::I64) => Ok(DecodedValues::ConstI64(c.read_i64()?)),
491            PhysicalColKind::Primitive(PType::F32) => Ok(DecodedValues::ConstF32(c.read_f32()?)),
492            PhysicalColKind::Primitive(PType::F64) => Ok(DecodedValues::ConstF64(c.read_f64()?)),
493            PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
494                let len = c.read_uvarint()? as usize;
495                Ok(DecodedValues::ConstBytes(c.read_bytes(len)?.to_vec()))
496            }
497        },
498        EncMode::Plain => decode_plain_values(&mut c, count, kind),
499        EncMode::Delta => decode_delta_values(buf, count, kind),
500        EncMode::Rle => decode_rle_values(&mut c, count, kind),
501    }
502}
503
504fn decode_plain_values(
505    c: &mut Cursor<'_>,
506    count: usize,
507    kind: PhysicalColKind,
508) -> Result<DecodedValues> {
509    match kind {
510        PhysicalColKind::Primitive(PType::Bool) => {
511            let bytes = c.read_bytes(count.div_ceil(8))?.to_vec();
512            Ok(DecodedValues::Bool(bytes))
513        }
514        PhysicalColKind::Primitive(PType::U8) => {
515            Ok(DecodedValues::U8(c.read_bytes(count)?.to_vec()))
516        }
517        PhysicalColKind::Primitive(PType::U16) => {
518            let raw = c.read_bytes(count * 2)?;
519            let v = raw
520                .chunks_exact(2)
521                .map(|b| u16::from_le_bytes([b[0], b[1]]))
522                .collect();
523            Ok(DecodedValues::U16(v))
524        }
525        PhysicalColKind::Primitive(PType::U32) => {
526            let raw = c.read_bytes(count * 4)?;
527            let v = raw
528                .chunks_exact(4)
529                .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
530                .collect();
531            Ok(DecodedValues::U32(v))
532        }
533        PhysicalColKind::Primitive(PType::U64) => {
534            let raw = c.read_bytes(count * 8)?;
535            let v = raw
536                .chunks_exact(8)
537                .map(|b| u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
538                .collect();
539            Ok(DecodedValues::U64(v))
540        }
541        PhysicalColKind::Primitive(PType::U128) => {
542            let raw = c.read_bytes(count * 16)?;
543            let v = raw
544                .chunks_exact(16)
545                .map(|b| u128::from_le_bytes(b.try_into().unwrap()))
546                .collect();
547            Ok(DecodedValues::U128(v))
548        }
549        PhysicalColKind::Primitive(PType::I32) => {
550            let raw = c.read_bytes(count * 4)?;
551            let v = raw
552                .chunks_exact(4)
553                .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
554                .collect();
555            Ok(DecodedValues::I32(v))
556        }
557        PhysicalColKind::Primitive(PType::I64) => {
558            let raw = c.read_bytes(count * 8)?;
559            let v = raw
560                .chunks_exact(8)
561                .map(|b| i64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
562                .collect();
563            Ok(DecodedValues::I64(v))
564        }
565        PhysicalColKind::Primitive(PType::F32) => {
566            let raw = c.read_bytes(count * 4)?;
567            let v = raw
568                .chunks_exact(4)
569                .map(|b| f32::from_bits(u32::from_le_bytes([b[0], b[1], b[2], b[3]])))
570                .collect();
571            Ok(DecodedValues::F32(v))
572        }
573        PhysicalColKind::Primitive(PType::F64) => {
574            let raw = c.read_bytes(count * 8)?;
575            let v = raw
576                .chunks_exact(8)
577                .map(|b| {
578                    f64::from_bits(u64::from_le_bytes([
579                        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
580                    ]))
581                })
582                .collect();
583            Ok(DecodedValues::F64(v))
584        }
585        PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
586            let mut offsets = Vec::with_capacity(count + 1);
587            let mut total = 0u32;
588            offsets.push(0);
589            for _ in 0..count {
590                let len = c.read_uvarint()? as u32;
591                total = total
592                    .checked_add(len)
593                    .ok_or_else(|| ReaderError::Corrupt("varbytes offset overflow".into()))?;
594                offsets.push(total);
595            }
596            let data = c.read_bytes(total as usize)?.to_vec();
597            Ok(DecodedValues::VarBytes { offsets, data })
598        }
599    }
600}
601
602fn decode_delta_values(buf: &[u8], count: usize, kind: PhysicalColKind) -> Result<DecodedValues> {
603    let signed = matches!(kind, PhysicalColKind::Primitive(PType::I32 | PType::I64));
604    let mut pos = 0usize;
605    let mut cur: u64 = if signed {
606        let (v, u) = read_svarint(&buf[pos..])?;
607        pos += u;
608        v as u64
609    } else {
610        let (v, u) = read_uvarint(&buf[pos..])?;
611        pos += u;
612        v
613    };
614
615    macro_rules! decode_int_delta {
616        ($variant:ident, $ty:ty) => {{
617            let mut v = Vec::with_capacity(count);
618            v.push(cur as $ty);
619            for _ in 1..count {
620                let (d, u) = read_svarint(&buf[pos..])?;
621                pos += u;
622                cur = cur.wrapping_add(d as u64);
623                v.push(cur as $ty);
624            }
625            Ok(DecodedValues::$variant(v))
626        }};
627    }
628
629    match kind {
630        PhysicalColKind::Primitive(PType::U8) => decode_int_delta!(U8, u8),
631        PhysicalColKind::Primitive(PType::U16) => decode_int_delta!(U16, u16),
632        PhysicalColKind::Primitive(PType::U32) => decode_int_delta!(U32, u32),
633        PhysicalColKind::Primitive(PType::U64) => decode_int_delta!(U64, u64),
634        PhysicalColKind::Primitive(PType::I32) => decode_int_delta!(I32, i32),
635        PhysicalColKind::Primitive(PType::I64) => decode_int_delta!(I64, i64),
636        _ => Err(ReaderError::Corrupt(
637            "Delta encoding on non-integer column".into(),
638        )),
639    }
640}
641
642fn decode_rle_values(
643    c: &mut Cursor<'_>,
644    count: usize,
645    kind: PhysicalColKind,
646) -> Result<DecodedValues> {
647    macro_rules! decode_fixed_rle {
648        ($variant:ident, $read_fn:ident) => {{
649            let mut v = Vec::with_capacity(count);
650            while v.len() < count {
651                let val = c.$read_fn()?;
652                let run = c.read_uvarint()? as usize;
653                if v.len() + run > count {
654                    return Err(ReaderError::Corrupt("RLE run overflow".into()));
655                }
656                v.resize(v.len() + run, val);
657            }
658            Ok(DecodedValues::$variant(v))
659        }};
660    }
661
662    match kind {
663        PhysicalColKind::Primitive(PType::Bool) => {
664            let mut bits = vec![0u8; count.div_ceil(8)];
665            let mut idx = 0usize;
666            while idx < count {
667                let val = c.read_u8()? != 0;
668                let run = c.read_uvarint()? as usize;
669                if idx + run > count {
670                    return Err(ReaderError::Corrupt("Bool RLE overflow".into()));
671                }
672                if val {
673                    for i in idx..idx + run {
674                        bits[i >> 3] |= 1u8 << (i & 7);
675                    }
676                }
677                idx += run;
678            }
679            Ok(DecodedValues::Bool(bits))
680        }
681        PhysicalColKind::Primitive(PType::U8) => decode_fixed_rle!(U8, read_u8),
682        PhysicalColKind::Primitive(PType::U16) => decode_fixed_rle!(U16, read_u16),
683        PhysicalColKind::Primitive(PType::U32) => decode_fixed_rle!(U32, read_u32),
684        PhysicalColKind::Primitive(PType::U64) => decode_fixed_rle!(U64, read_u64),
685        PhysicalColKind::Primitive(PType::U128) => decode_fixed_rle!(U128, read_u128),
686        PhysicalColKind::Primitive(PType::I32) => decode_fixed_rle!(I32, read_i32),
687        PhysicalColKind::Primitive(PType::I64) => decode_fixed_rle!(I64, read_i64),
688        PhysicalColKind::Primitive(PType::F32) => decode_fixed_rle!(F32, read_f32),
689        PhysicalColKind::Primitive(PType::F64) => decode_fixed_rle!(F64, read_f64),
690        PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
691            let mut offsets = Vec::with_capacity(count + 1);
692            let mut data = Vec::new();
693            offsets.push(0);
694            let mut seen = 0usize;
695            while seen < count {
696                let len = c.read_uvarint()? as usize;
697                let bytes = c.read_bytes(len)?;
698                let run = c.read_uvarint()? as usize;
699                if seen + run > count {
700                    return Err(ReaderError::Corrupt("VarBytes RLE overflow".into()));
701                }
702                for _ in 0..run {
703                    data.extend_from_slice(bytes);
704                    offsets.push(data.len() as u32);
705                }
706                seen += run;
707            }
708            Ok(DecodedValues::VarBytes { offsets, data })
709        }
710    }
711}
712
713/// Decoded single block of a `FlatDict`.
714pub struct DecodedFlatBlock {
715    values: DecodedValues,
716    ptype: PType,
717}
718
719impl DecodedFlatBlock {
720    #[inline]
721    pub fn get_scalar_ref(&self, idx: usize) -> Result<ScalarRef<'_>> {
722        self.values
723            .get_scalar_ref(idx, PhysicalColKind::Primitive(self.ptype))
724    }
725
726    #[inline]
727    fn get(&self, idx: usize) -> Result<Value> {
728        self.values
729            .get_as_value(idx, PhysicalColKind::Primitive(self.ptype))
730    }
731}
732
733/// Reader for a `FlatDict`.
734pub struct FlatDictReader {
735    header: FlatDictHeader,
736    ptype: PType,
737    block_offsets: Vec<u64>,
738    blocks_base_offset: u64,
739    /// Used when `block_size == 0` (single-block small dictionary, zero lock overhead after first load).
740    single_block: OnceLock<Arc<DecodedFlatBlock>>,
741    /// Used when `block_size > 0` (chunked large dictionary).
742    block_cache: Option<ShardedLruCache<u32, Arc<DecodedFlatBlock>>>,
743}
744
745impl FlatDictReader {
746    fn parse(
747        backing: &Backing<'_>,
748        offset: u64,
749        len: u64,
750        ptype: PType,
751        cache_blocks: usize,
752    ) -> Result<Self> {
753        let hdr_bytes = backing.read_slice(offset, coip_format::FLAT_DICT_HEADER_SIZE)?;
754        let mut c = Cursor::new(&hdr_bytes);
755        let header = FlatDictHeader::decode(&mut c)?;
756        let offsets_bytes_len = (header.block_count as usize + 1) * 8;
757        let off_pos = offset + (coip_format::FLAT_DICT_HEADER_SIZE as u64);
758        if (coip_format::FLAT_DICT_HEADER_SIZE as u64) + (offsets_bytes_len as u64) > len {
759            return Err(FormatError::UnexpectedEof.into());
760        }
761        let off_bytes = backing.read_slice(off_pos, offsets_bytes_len)?;
762        let mut oc = Cursor::new(&off_bytes);
763        let mut block_offsets = Vec::with_capacity(header.block_count as usize + 1);
764        for _ in 0..=header.block_count {
765            block_offsets.push(oc.read_u64()?);
766        }
767        let blocks_base_offset = off_pos + (offsets_bytes_len as u64);
768        let block_cache = if header.block_size > 0 {
769            Some(ShardedLruCache::new(cache_blocks))
770        } else {
771            None
772        };
773        Ok(Self {
774            header,
775            ptype,
776            block_offsets,
777            blocks_base_offset,
778            single_block: OnceLock::new(),
779            block_cache,
780        })
781    }
782
783    pub fn entry_count(&self) -> u64 {
784        self.header.entry_count
785    }
786
787    pub fn clear_cache(&self) {
788        if let Some(cache) = &self.block_cache {
789            cache.clear();
790        }
791    }
792
793    /// Return `(block, local_idx)` so callers can borrow `&str` / `&[u8]` directly without cloning.
794    pub fn get_block_and_index(
795        &self,
796        backing: &Backing<'_>,
797        entry_idx: usize,
798    ) -> Result<(Arc<DecodedFlatBlock>, usize)> {
799        if (entry_idx as u64) >= self.header.entry_count {
800            return Err(ReaderError::Corrupt("FlatDict entry_idx OOB".into()));
801        }
802        if self.header.block_size == 0 {
803            if let Some(blk) = self.single_block.get() {
804                return Ok((Arc::clone(blk), entry_idx));
805            }
806            let decoded = Arc::new(self.decode_block(backing, 0)?);
807            let blk = self.single_block.get_or_init(|| decoded);
808            return Ok((Arc::clone(blk), entry_idx));
809        }
810
811        let bs = self.header.block_size as usize;
812        let block_idx = (entry_idx / bs) as u32;
813        let local_idx = entry_idx % bs;
814        let cache = self.block_cache.as_ref().unwrap();
815        if let Some(hit) = cache.get(&block_idx) {
816            return Ok((hit, local_idx));
817        }
818        let decoded = Arc::new(self.decode_block(backing, block_idx)?);
819        cache.put(block_idx, Arc::clone(&decoded));
820        Ok((decoded, local_idx))
821    }
822
823    pub fn get(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<Value> {
824        let (blk, local_idx) = self.get_block_and_index(backing, entry_idx)?;
825        blk.get(local_idx)
826    }
827
828    fn decode_block(&self, backing: &Backing<'_>, block_idx: u32) -> Result<DecodedFlatBlock> {
829        let b = block_idx as usize;
830        let rel_start = self.block_offsets[b];
831        let rel_end = self.block_offsets[b + 1];
832        let raw = backing.read_slice(
833            self.blocks_base_offset + rel_start,
834            (rel_end - rel_start) as usize,
835        )?;
836        let decomp = decompress(self.header.codec, &raw, None)?;
837        let count = self.header.entries_in_block(block_idx);
838
839        let values =
840            if self.header.sorted_front_coded && matches!(self.ptype, PType::Utf8 | PType::Bytes) {
841                decode_front_coded(&decomp, count)?
842            } else {
843                let mut c = Cursor::new(&decomp);
844                decode_plain_values(&mut c, count, PhysicalColKind::Primitive(self.ptype))?
845            };
846        Ok(DecodedFlatBlock {
847            values,
848            ptype: self.ptype,
849        })
850    }
851}
852
853fn decode_front_coded(buf: &[u8], count: usize) -> Result<DecodedValues> {
854    let mut c = Cursor::new(buf);
855    let mut offsets = Vec::with_capacity(count + 1);
856    let mut data = Vec::with_capacity(buf.len() * 2);
857    offsets.push(0u32);
858    if count == 0 {
859        return Ok(DecodedValues::VarBytes { offsets, data });
860    }
861    let first_len = c.read_uvarint()? as usize;
862    let first = c.read_bytes(first_len)?;
863    data.extend_from_slice(first);
864    offsets.push(data.len() as u32);
865    let mut prev_start = 0usize;
866    let mut prev_end = first_len;
867
868    for _ in 1..count {
869        let shared = c.read_uvarint()? as usize;
870        let suffix_len = c.read_uvarint()? as usize;
871        let suffix = c.read_bytes(suffix_len)?;
872        if shared > prev_end - prev_start {
873            return Err(ReaderError::Corrupt("front-coded shared prefix OOB".into()));
874        }
875        let cur_start = data.len();
876        data.reserve(shared + suffix_len);
877        // Copy shared prefix from previous entry inside `data`
878        data.extend_from_within(prev_start..prev_start + shared);
879        data.extend_from_slice(suffix);
880        let cur_end = data.len();
881        offsets.push(cur_end as u32);
882        prev_start = cur_start;
883        prev_end = cur_end;
884    }
885
886    Ok(DecodedValues::VarBytes { offsets, data })
887}
888
889struct DecodedListDict {
890    offsets: Vec<u32>,
891    elems: Vec<u32>,
892}
893
894/// Reader for a `ListDict` (lazily loaded once via `OnceLock`).
895pub struct ListDictReader {
896    header: ListDictHeader,
897    pub elem_dict_id: u16,
898    blob_offset: u64,
899    blob_len: u64,
900    loaded: OnceLock<Arc<DecodedListDict>>,
901}
902
903impl ListDictReader {
904    fn parse(backing: &Backing<'_>, offset: u64, len: u64, elem_dict_id: u16) -> Result<Self> {
905        let hdr_bytes = backing.read_slice(offset, coip_format::LIST_DICT_HEADER_SIZE)?;
906        let mut c = Cursor::new(&hdr_bytes);
907        let header = ListDictHeader::decode(&mut c)?;
908        Ok(Self {
909            header,
910            elem_dict_id,
911            blob_offset: offset,
912            blob_len: len,
913            loaded: OnceLock::new(),
914        })
915    }
916
917    pub fn entry_count(&self) -> u64 {
918        self.header.entry_count
919    }
920
921    fn get_loaded(&self, backing: &Backing<'_>) -> Result<&Arc<DecodedListDict>> {
922        if let Some(d) = self.loaded.get() {
923            return Ok(d);
924        }
925        let body_start = self.blob_offset + (coip_format::LIST_DICT_HEADER_SIZE as u64);
926        let body_len = (self.blob_len as usize)
927            .checked_sub(coip_format::LIST_DICT_HEADER_SIZE)
928            .ok_or(FormatError::UnexpectedEof)?;
929        let raw = backing.read_slice(body_start, body_len)?;
930        let off_len = self.header.offsets_len as usize;
931        if off_len > raw.len() {
932            return Err(FormatError::OutOfBounds("ListDict offsets_len").into());
933        }
934        let raw_offs = decompress(self.header.codec, &raw[..off_len], None)?;
935        let raw_elems = decompress(self.header.codec, &raw[off_len..], None)?;
936
937        let count = self.header.entry_count as usize;
938        let mut offsets = Vec::with_capacity(count + 1);
939        offsets.push(0u32);
940        let mut pos = 0usize;
941        let mut acc = 0u32;
942        for _ in 0..count {
943            let (len, u) = read_uvarint(&raw_offs[pos..])?;
944            pos += u;
945            acc += len as u32;
946            offsets.push(acc);
947        }
948
949        let total = self.header.total_elems as usize;
950        let mut ec = Cursor::new(&raw_elems);
951        let mut elems = Vec::with_capacity(total);
952        for _ in 0..total {
953            let id = match self.header.id_width {
954                IdWidth::U8 => ec.read_u8()? as u32,
955                IdWidth::U16 => ec.read_u16()? as u32,
956                IdWidth::U32 => ec.read_u32()?,
957            };
958            elems.push(id);
959        }
960
961        let decoded = Arc::new(DecodedListDict { offsets, elems });
962        Ok(self.loaded.get_or_init(|| decoded))
963    }
964
965    /// Borrow the element ID slice directly from the lazily loaded `OnceLock` cache (zero allocation).
966    pub fn get_elem_slice(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<&[u32]> {
967        let data = self.get_loaded(backing)?;
968        if entry_idx + 1 >= data.offsets.len() {
969            return Err(ReaderError::Corrupt("ListDict entry_idx OOB".into()));
970        }
971        let s = data.offsets[entry_idx] as usize;
972        let e = data.offsets[entry_idx + 1] as usize;
973        Ok(&data.elems[s..e])
974    }
975
976    pub fn get_elem_ids(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<Vec<u32>> {
977        Ok(self.get_elem_slice(backing, entry_idx)?.to_vec())
978    }
979}
980
981pub enum DictReader {
982    Flat(Box<FlatDictReader>),
983    Struct {
984        table: ColumnTableReader,
985        schema: TableSchema,
986    },
987    List(ListDictReader),
988}
989
990impl DictReader {
991    pub fn entry_count(&self) -> u64 {
992        match self {
993            Self::Flat(f) => f.entry_count(),
994            Self::Struct { table, .. } => table.header.row_count,
995            Self::List(l) => l.entry_count(),
996        }
997    }
998
999    pub fn clear_cache(&self) {
1000        if let Self::Flat(f) = self {
1001            f.clear_cache();
1002        }
1003    }
1004}
1005
1006/// All parsed dictionary readers from `Section 9: DictTables`.
1007pub struct DictTablesReader {
1008    pub dicts: Vec<DictReader>,
1009}
1010
1011impl DictTablesReader {
1012    pub fn empty() -> Self {
1013        Self { dicts: Vec::new() }
1014    }
1015
1016    pub fn parse(
1017        backing: &Backing<'_>,
1018        section_offset: u64,
1019        section_len: u64,
1020        schema: &Schema,
1021        flat_dict_cache_blocks: usize,
1022    ) -> Result<Self> {
1023        let hdr_bytes = backing.read_slice(section_offset, 8)?;
1024        let dict_count = u16::from_le_bytes([hdr_bytes[0], hdr_bytes[1]]) as usize;
1025        if dict_count != schema.dicts.len() {
1026            return Err(ReaderError::Corrupt(format!(
1027                "DictTables count {dict_count} != schema {}",
1028                schema.dicts.len()
1029            )));
1030        }
1031        let dir_len = dict_count * 16;
1032        if 8 + (dir_len as u64) > section_len {
1033            return Err(FormatError::UnexpectedEof.into());
1034        }
1035        let dir_bytes = backing.read_slice(section_offset + 8, dir_len)?;
1036        let mut c = Cursor::new(&dir_bytes);
1037        let mut entries = Vec::with_capacity(dict_count);
1038        for _ in 0..dict_count {
1039            let off = c.read_u64()?;
1040            let len = c.read_u64()?;
1041            entries.push((off, len));
1042        }
1043        let blobs_base = section_offset + 8 + (dir_len as u64);
1044
1045        let mut dicts = Vec::with_capacity(dict_count);
1046        for (idx, (rel_off, blob_len)) in entries.into_iter().enumerate() {
1047            let abs_off = blobs_base + rel_off;
1048            let ds = &schema.dicts[idx];
1049            let reader = match &ds.kind {
1050                DictKind::Flat { ptype, .. } => DictReader::Flat(Box::new(FlatDictReader::parse(
1051                    backing,
1052                    abs_off,
1053                    blob_len,
1054                    *ptype,
1055                    flat_dict_cache_blocks,
1056                )?)),
1057                DictKind::Struct { table } => DictReader::Struct {
1058                    table: ColumnTableReader::parse(
1059                        (idx + 1) as u32,
1060                        backing,
1061                        abs_off,
1062                        blob_len,
1063                        table,
1064                        schema.dicts.len(),
1065                    )?,
1066                    schema: table.clone(),
1067                },
1068                DictKind::List { elem_dict_id, .. } => DictReader::List(ListDictReader::parse(
1069                    backing,
1070                    abs_off,
1071                    blob_len,
1072                    *elem_dict_id,
1073                )?),
1074            };
1075            dicts.push(reader);
1076        }
1077
1078        Ok(Self { dicts })
1079    }
1080}
1081
1082/// Materialize one row of a `StructSchema` from `table` respecting `proj`.
1083#[allow(clippy::too_many_arguments)]
1084pub fn read_struct_row(
1085    backing: &Backing<'_>,
1086    table: &ColumnTableReader,
1087    dicts: &DictTablesReader,
1088    chunk_cache: &ChunkCache,
1089    schema: &StructSchema,
1090    rg: u32,
1091    row_in_rg: usize,
1092    rows_in_rg: usize,
1093    proj: &ProjectionNode,
1094) -> Result<Option<BTreeMap<String, Value>>> {
1095    let explicit_present = if let Some(pcol) = schema.presence_col {
1096        let chunk = table.get_chunk(backing, chunk_cache, pcol, rg, rows_in_rg)?;
1097        let is_present = chunk.get_bool(row_in_rg)?.unwrap_or(false);
1098        if !is_present {
1099            return Ok(None);
1100        }
1101        true
1102    } else {
1103        false
1104    };
1105
1106    let mut map = BTreeMap::new();
1107
1108    // Unpack requested DictGroups
1109    for g in &schema.dict_groups {
1110        if !proj.selects_any_of(&g.field_names) {
1111            continue;
1112        }
1113        let chunk = table.get_chunk(backing, chunk_cache, g.col_id, rg, rows_in_rg)?;
1114        let id = chunk.get_u32(row_in_rg)?.unwrap_or(0);
1115        if id == 0 {
1116            continue;
1117        }
1118        let dict_row = (id - 1) as usize;
1119        match &dicts.dicts[g.dict_id as usize] {
1120            DictReader::Struct {
1121                table: dict_table,
1122                schema: dict_schema,
1123            } => {
1124                let (d_rg, d_row, d_rows) = dict_table.row_group_of(dict_row);
1125                if let Some(sub_map) = read_struct_row(
1126                    backing,
1127                    dict_table,
1128                    dicts,
1129                    chunk_cache,
1130                    &dict_schema.root,
1131                    d_rg,
1132                    d_row,
1133                    d_rows,
1134                    proj,
1135                )? {
1136                    for (k, v) in sub_map {
1137                        map.insert(k, v);
1138                    }
1139                }
1140            }
1141            _ => {
1142                return Err(ReaderError::Corrupt(
1143                    "DictGroup does not reference a StructDict".into(),
1144                ));
1145            }
1146        }
1147    }
1148
1149    // Read requested fields
1150    for f in &schema.fields {
1151        let Some(child_proj) = proj.child(&f.name) else {
1152            continue;
1153        };
1154        if let Some(val) = read_column_value(
1155            backing,
1156            table,
1157            dicts,
1158            chunk_cache,
1159            &f.col_type,
1160            rg,
1161            row_in_rg,
1162            rows_in_rg,
1163            child_proj,
1164        )? {
1165            map.insert(f.name.clone(), val);
1166        }
1167    }
1168
1169    if schema.nullable && !explicit_present && map.is_empty() {
1170        Ok(None)
1171    } else {
1172        Ok(Some(map))
1173    }
1174}
1175
1176#[allow(clippy::too_many_arguments)]
1177fn read_column_value(
1178    backing: &Backing<'_>,
1179    table: &ColumnTableReader,
1180    dicts: &DictTablesReader,
1181    chunk_cache: &ChunkCache,
1182    col_type: &ColumnType,
1183    rg: u32,
1184    row_in_rg: usize,
1185    rows_in_rg: usize,
1186    proj: &ProjectionNode,
1187) -> Result<Option<Value>> {
1188    match col_type {
1189        ColumnType::Primitive { col_id, .. } | ColumnType::Dynamic { col_id, .. } => {
1190            let chunk = table.get_chunk(backing, chunk_cache, *col_id, rg, rows_in_rg)?;
1191            chunk.get_value(row_in_rg)
1192        }
1193        ColumnType::DictRef {
1194            dict_id, col_id, ..
1195        } => {
1196            let chunk = table.get_chunk(backing, chunk_cache, *col_id, rg, rows_in_rg)?;
1197            let id = chunk.get_u32(row_in_rg)?.unwrap_or(0);
1198            if id == 0 {
1199                return Ok(None);
1200            }
1201            read_dict_entry(
1202                backing,
1203                dicts,
1204                chunk_cache,
1205                *dict_id,
1206                (id - 1) as usize,
1207                proj,
1208            )
1209        }
1210        ColumnType::Struct(s) => {
1211            let opt = read_struct_row(
1212                backing,
1213                table,
1214                dicts,
1215                chunk_cache,
1216                s,
1217                rg,
1218                row_in_rg,
1219                rows_in_rg,
1220                proj,
1221            )?;
1222            Ok(opt.map(Value::Map))
1223        }
1224        ColumnType::ShreddedMap {
1225            nullable,
1226            presence_col,
1227            overflow_col,
1228            entries,
1229        } => {
1230            let explicit_present = if let Some(pcol) = presence_col {
1231                let chunk = table.get_chunk(backing, chunk_cache, *pcol, rg, rows_in_rg)?;
1232                let present = chunk.get_bool(row_in_rg)?.unwrap_or(false);
1233                if !present {
1234                    return Ok(None);
1235                }
1236                true
1237            } else {
1238                false
1239            };
1240
1241            let mut map = BTreeMap::new();
1242            for e in entries {
1243                let Some(child_proj) = proj.child(&e.key) else {
1244                    continue;
1245                };
1246                if let Some(v) = read_column_value(
1247                    backing,
1248                    table,
1249                    dicts,
1250                    chunk_cache,
1251                    &e.value_type,
1252                    rg,
1253                    row_in_rg,
1254                    rows_in_rg,
1255                    child_proj,
1256                )? {
1257                    map.insert(e.key.clone(), v);
1258                }
1259            }
1260
1261            if let Some(ocol) = overflow_col {
1262                // Only read overflow if All or if some requested field isn't in known shredded entries
1263                let need_overflow = match proj {
1264                    ProjectionNode::All => true,
1265                    ProjectionNode::Fields(req) => {
1266                        req.keys().any(|k| !entries.iter().any(|e| e.key == *k))
1267                    }
1268                };
1269                if need_overflow {
1270                    let chunk = table.get_chunk(backing, chunk_cache, *ocol, rg, rows_in_rg)?;
1271                    if let Some(Value::Map(extra)) = chunk.get_value(row_in_rg)? {
1272                        for (k, v) in extra {
1273                            if proj.child(&k).is_some() {
1274                                map.insert(k, v);
1275                            }
1276                        }
1277                    }
1278                }
1279            }
1280
1281            if *nullable && !explicit_present && map.is_empty() {
1282                Ok(None)
1283            } else {
1284                Ok(Some(Value::Map(map)))
1285            }
1286        }
1287        ColumnType::List {
1288            offsets_col,
1289            elem_type,
1290            ..
1291        } => {
1292            let off_chunk = table.get_chunk(backing, chunk_cache, *offsets_col, rg, rows_in_rg)?;
1293            let Some((start, len, total_elems)) =
1294                off_chunk.list_range_in_rg(row_in_rg, rows_in_rg)?
1295            else {
1296                return Ok(None);
1297            };
1298            let mut arr = Vec::with_capacity(len);
1299            for elem_idx in start..start + len {
1300                let item = read_column_value(
1301                    backing,
1302                    table,
1303                    dicts,
1304                    chunk_cache,
1305                    elem_type,
1306                    rg,
1307                    elem_idx,
1308                    total_elems,
1309                    proj,
1310                )?
1311                .unwrap_or(Value::Null);
1312                arr.push(item);
1313            }
1314            Ok(Some(Value::Array(arr)))
1315        }
1316    }
1317}
1318
1319fn read_dict_entry(
1320    backing: &Backing<'_>,
1321    dicts: &DictTablesReader,
1322    chunk_cache: &ChunkCache,
1323    dict_id: u16,
1324    entry_idx: usize,
1325    proj: &ProjectionNode,
1326) -> Result<Option<Value>> {
1327    match &dicts.dicts[dict_id as usize] {
1328        DictReader::Flat(flat) => Ok(Some(flat.get(backing, entry_idx)?)),
1329        DictReader::Struct { table, schema } => {
1330            let (rg, row_in_rg, rows_in_rg) = table.row_group_of(entry_idx);
1331            let opt = read_struct_row(
1332                backing,
1333                table,
1334                dicts,
1335                chunk_cache,
1336                &schema.root,
1337                rg,
1338                row_in_rg,
1339                rows_in_rg,
1340                proj,
1341            )?;
1342            Ok(opt.map(Value::Map))
1343        }
1344        DictReader::List(list) => {
1345            let elem_ids = list.get_elem_ids(backing, entry_idx)?;
1346            let mut arr = Vec::with_capacity(elem_ids.len());
1347            for eid in elem_ids {
1348                if eid == 0 {
1349                    arr.push(Value::Null);
1350                } else if let Some(v) = read_dict_entry(
1351                    backing,
1352                    dicts,
1353                    chunk_cache,
1354                    list.elem_dict_id,
1355                    (eid - 1) as usize,
1356                    proj,
1357                )? {
1358                    arr.push(v);
1359                }
1360            }
1361            Ok(Some(Value::Array(arr)))
1362        }
1363    }
1364}