Skip to main content

coip_builder/
schema_infer.rs

1//! Generic automatic Schema inference, dictionary normalization, and Geo-Locality row ordering.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4
5use coip_format::{
6    Codec, ColumnType, DictGroup, DictKind, DictSchema, IdWidth, PType, Schema, ShreddedMapEntry,
7    StructField, StructSchema, TableSchema, Value,
8};
9
10use crate::column_writer::{
11    ColumnData, ColumnRowRanges, FlatDictValues, encode_column_table, encode_flat_dict,
12    encode_list_dict,
13};
14use crate::error::Result;
15
16/// Output of schema inference + materialization ready to write into Sections 2, 8, and 9.
17pub struct BuiltColumnarData {
18    pub schema: Schema,
19    pub record_columns_blob: Vec<u8>,
20    pub dict_blobs: Vec<Vec<u8>>,
21    /// Maps original 1-based record index (`1..=N`) -> final geo-sorted 1-based `record_id` (`1..=N`).
22    pub old_to_new_rid: Vec<u32>,
23}
24
25/// Row ordering strategy for `RecordColumns` (affects both IP index delta locality and column compression).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum RowOrderStrategy {
28    /// Order records by their first appearance in IPv4/IPv6 space (maximizes IP index `rid` locality).
29    IpLocality,
30    /// Order records lexicographically by core geographic/dictionary hierarchy columns.
31    GeoLocality,
32    /// Order by core low-cardinality entity dicts (continent/country), then IP first-appearance order.
33    HybridGeoIp,
34}
35
36/// Configuration knobs for schema inference & columnar encoding.
37#[derive(Debug, Clone)]
38pub struct ColumnarBuildConfig {
39    pub row_group_size: u32,
40    pub struct_dict_row_group_size: u32,
41    pub dict_block_size: u32,
42    pub codec: Codec,
43    pub zstd_level: i32,
44    pub row_order: RowOrderStrategy,
45}
46
47impl Default for ColumnarBuildConfig {
48    fn default() -> Self {
49        Self {
50            row_group_size: 4096,
51            struct_dict_row_group_size: 2048,
52            dict_block_size: 4096,
53            codec: Codec::Zstd,
54            zstd_level: 9,
55            row_order: RowOrderStrategy::GeoLocality,
56        }
57    }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
61enum ValueKind {
62    Null,
63    Prim(PType),
64    Array,
65    Map,
66}
67
68fn value_kind(v: &Value) -> ValueKind {
69    match v {
70        Value::Null => ValueKind::Null,
71        Value::Bool(_) => ValueKind::Prim(PType::Bool),
72        Value::U8(_) => ValueKind::Prim(PType::U8),
73        Value::U16(_) => ValueKind::Prim(PType::U16),
74        Value::U32(_) => ValueKind::Prim(PType::U32),
75        Value::U64(_) => ValueKind::Prim(PType::U64),
76        Value::U128(_) => ValueKind::Prim(PType::U128),
77        Value::I32(_) => ValueKind::Prim(PType::I32),
78        Value::I64(_) => ValueKind::Prim(PType::I64),
79        Value::F32(_) => ValueKind::Prim(PType::F32),
80        Value::F64(_) => ValueKind::Prim(PType::F64),
81        Value::Utf8(_) => ValueKind::Prim(PType::Utf8),
82        Value::Bytes(_) => ValueKind::Prim(PType::Bytes),
83        Value::Array(_) => ValueKind::Array,
84        Value::Map(_) => ValueKind::Map,
85    }
86}
87
88/// Lookup handle produced during inference so we can materialize physical columns cleanly.
89enum BuiltDictLookup {
90    Flat {
91        lookup: HashMap<Value, u32>,
92    },
93    Struct {
94        lookup: HashMap<BTreeMap<String, Value>, u32>,
95    },
96    List {
97        lookup: HashMap<Vec<Value>, u32>,
98    },
99}
100
101enum BuiltDictData {
102    Flat {
103        values: FlatDictValues,
104        block_size: u32,
105        sorted_front_coded: bool,
106    },
107    Struct {
108        columns: Vec<ColumnData>,
109        row_ranges: Vec<ColumnRowRanges>,
110        row_count: usize,
111    },
112    List {
113        lists: Vec<Vec<u32>>,
114        id_width: IdWidth,
115    },
116}
117
118struct DictRegistry {
119    schemas: Vec<DictSchema>,
120    data: Vec<BuiltDictData>,
121    lookups: Vec<BuiltDictLookup>,
122    cfg: ColumnarBuildConfig,
123}
124
125impl DictRegistry {
126    fn new(cfg: ColumnarBuildConfig) -> Self {
127        Self {
128            schemas: Vec::new(),
129            data: Vec::new(),
130            lookups: Vec::new(),
131            cfg,
132        }
133    }
134
135    fn register_flat_dict(
136        &mut self,
137        name: String,
138        ptype: PType,
139        unique_values: Vec<Value>,
140    ) -> (u16, IdWidth) {
141        let count = unique_values.len();
142        let id_width = IdWidth::for_dict_len(count);
143        let mut sorted = unique_values;
144        sorted.sort();
145
146        let mut lookup = HashMap::with_capacity(count);
147        for (idx, v) in sorted.iter().enumerate() {
148            lookup.insert(v.clone(), (idx + 1) as u32);
149        }
150
151        let block_size = if count <= 8192 {
152            0
153        } else {
154            self.cfg.dict_block_size
155        };
156        let sorted_front_coded = block_size > 0 && matches!(ptype, PType::Utf8 | PType::Bytes);
157
158        let flat_vals = match ptype {
159            PType::Bool => FlatDictValues::Bool(
160                sorted
161                    .into_iter()
162                    .map(|v| match v {
163                        Value::Bool(x) => x,
164                        _ => unreachable!(),
165                    })
166                    .collect(),
167            ),
168            PType::U8 => FlatDictValues::U8(
169                sorted
170                    .into_iter()
171                    .map(|v| match v {
172                        Value::U8(x) => x,
173                        _ => unreachable!(),
174                    })
175                    .collect(),
176            ),
177            PType::U16 => FlatDictValues::U16(
178                sorted
179                    .into_iter()
180                    .map(|v| match v {
181                        Value::U16(x) => x,
182                        _ => unreachable!(),
183                    })
184                    .collect(),
185            ),
186            PType::U32 => FlatDictValues::U32(
187                sorted
188                    .into_iter()
189                    .map(|v| match v {
190                        Value::U32(x) => x,
191                        _ => unreachable!(),
192                    })
193                    .collect(),
194            ),
195            PType::U64 => FlatDictValues::U64(
196                sorted
197                    .into_iter()
198                    .map(|v| match v {
199                        Value::U64(x) => x,
200                        _ => unreachable!(),
201                    })
202                    .collect(),
203            ),
204            PType::U128 => FlatDictValues::U128(
205                sorted
206                    .into_iter()
207                    .map(|v| match v {
208                        Value::U128(x) => x,
209                        _ => unreachable!(),
210                    })
211                    .collect(),
212            ),
213            PType::I32 => FlatDictValues::I32(
214                sorted
215                    .into_iter()
216                    .map(|v| match v {
217                        Value::I32(x) => x,
218                        _ => unreachable!(),
219                    })
220                    .collect(),
221            ),
222            PType::I64 => FlatDictValues::I64(
223                sorted
224                    .into_iter()
225                    .map(|v| match v {
226                        Value::I64(x) => x,
227                        _ => unreachable!(),
228                    })
229                    .collect(),
230            ),
231            PType::F32 => FlatDictValues::F32(
232                sorted
233                    .into_iter()
234                    .map(|v| match v {
235                        Value::F32(x) => x,
236                        _ => unreachable!(),
237                    })
238                    .collect(),
239            ),
240            PType::F64 => FlatDictValues::F64(
241                sorted
242                    .into_iter()
243                    .map(|v| match v {
244                        Value::F64(x) => x,
245                        _ => unreachable!(),
246                    })
247                    .collect(),
248            ),
249            PType::Utf8 => FlatDictValues::Utf8(
250                sorted
251                    .into_iter()
252                    .map(|v| match v {
253                        Value::Utf8(x) => x,
254                        _ => unreachable!(),
255                    })
256                    .collect(),
257            ),
258            PType::Bytes => FlatDictValues::Bytes(
259                sorted
260                    .into_iter()
261                    .map(|v| match v {
262                        Value::Bytes(x) => x,
263                        _ => unreachable!(),
264                    })
265                    .collect(),
266            ),
267        };
268
269        let dict_id = self.schemas.len() as u16;
270        self.schemas.push(DictSchema {
271            name,
272            kind: DictKind::Flat {
273                ptype,
274                sorted_front_coded,
275                block_size,
276            },
277        });
278        self.data.push(BuiltDictData::Flat {
279            values: flat_vals,
280            block_size,
281            sorted_front_coded,
282        });
283        self.lookups.push(BuiltDictLookup::Flat { lookup });
284        (dict_id, id_width)
285    }
286
287    fn register_struct_dict(
288        &mut self,
289        name: String,
290        mut unique_maps: Vec<BTreeMap<String, Value>>,
291    ) -> (u16, IdWidth) {
292        unique_maps.sort();
293        let row_count = unique_maps.len();
294        let id_width = IdWidth::for_dict_len(row_count);
295
296        let mut lookup = HashMap::with_capacity(row_count);
297        for (idx, m) in unique_maps.iter().enumerate() {
298            lookup.insert(m.clone(), (idx + 1) as u32);
299        }
300
301        let refs: Vec<Option<&BTreeMap<String, Value>>> = unique_maps.iter().map(Some).collect();
302        let mut next_col = 0u16;
303        let root = infer_struct_schema(&name, &refs, false, false, &mut next_col, self);
304        let table_schema = TableSchema {
305            column_count: next_col,
306            root,
307        };
308
309        let (columns, row_ranges) = materialize_table(
310            &table_schema,
311            &unique_maps,
312            self,
313            self.cfg.struct_dict_row_group_size,
314        );
315
316        let dict_id = self.schemas.len() as u16;
317        self.schemas.push(DictSchema {
318            name,
319            kind: DictKind::Struct {
320                table: table_schema,
321            },
322        });
323        self.data.push(BuiltDictData::Struct {
324            columns,
325            row_ranges,
326            row_count,
327        });
328        self.lookups.push(BuiltDictLookup::Struct { lookup });
329        (dict_id, id_width)
330    }
331
332    fn register_list_dict(
333        &mut self,
334        name: String,
335        mut unique_lists: Vec<Vec<Value>>,
336        elem_dict_id: u16,
337        elem_id_width: IdWidth,
338    ) -> (u16, IdWidth) {
339        let mut id_lists_with_orig: Vec<(Vec<u32>, Vec<Value>)> =
340            Vec::with_capacity(unique_lists.len());
341        for list in unique_lists.drain(..) {
342            let mut ids = Vec::with_capacity(list.len());
343            for item in &list {
344                let id = match &self.lookups[elem_dict_id as usize] {
345                    BuiltDictLookup::Flat { lookup } => *lookup.get(item).unwrap_or(&0),
346                    BuiltDictLookup::Struct { lookup } => match item {
347                        Value::Map(m) => *lookup.get(m).unwrap_or(&0),
348                        _ => 0,
349                    },
350                    BuiltDictLookup::List { lookup } => match item {
351                        Value::Array(a) => *lookup.get(a).unwrap_or(&0),
352                        _ => 0,
353                    },
354                };
355                ids.push(id);
356            }
357            id_lists_with_orig.push((ids, list));
358        }
359        id_lists_with_orig.sort_by(|a, b| a.0.cmp(&b.0));
360
361        let count = id_lists_with_orig.len();
362        let id_width = IdWidth::for_dict_len(count);
363        let mut lookup = HashMap::with_capacity(count);
364        let mut lists = Vec::with_capacity(count);
365        for (idx, (ids, orig)) in id_lists_with_orig.into_iter().enumerate() {
366            lookup.insert(orig, (idx + 1) as u32);
367            lists.push(ids);
368        }
369
370        let dict_id = self.schemas.len() as u16;
371        self.schemas.push(DictSchema {
372            name,
373            kind: DictKind::List {
374                elem_dict_id,
375                id_width: elem_id_width,
376            },
377        });
378        self.data.push(BuiltDictData::List {
379            lists,
380            id_width: elem_id_width,
381        });
382        self.lookups.push(BuiltDictLookup::List { lookup });
383        (dict_id, id_width)
384    }
385
386    fn encode_all_dicts(&self) -> Result<Vec<Vec<u8>>> {
387        let mut blobs = Vec::with_capacity(self.data.len());
388        for d in &self.data {
389            let blob = match d {
390                BuiltDictData::Flat {
391                    values,
392                    block_size,
393                    sorted_front_coded,
394                } => encode_flat_dict(
395                    values,
396                    *block_size,
397                    *sorted_front_coded,
398                    self.cfg.codec,
399                    self.cfg.zstd_level,
400                )?,
401                BuiltDictData::Struct {
402                    columns,
403                    row_ranges,
404                    row_count,
405                } => encode_column_table(
406                    columns,
407                    row_ranges,
408                    *row_count,
409                    self.cfg.struct_dict_row_group_size,
410                    self.cfg.codec,
411                    self.cfg.zstd_level,
412                )?,
413                BuiltDictData::List { lists, id_width } => {
414                    encode_list_dict(lists, *id_width, self.cfg.codec, self.cfg.zstd_level)?
415                }
416            };
417            blobs.push(blob);
418        }
419        Ok(blobs)
420    }
421}
422
423/// Infer optimal generic Schema, normalize dictionaries, order records, and encode Sections 2/8/9.
424pub fn infer_and_encode_records(
425    records: &[BTreeMap<String, Value>],
426    ip_first_pos: &[u64],
427    cfg: &ColumnarBuildConfig,
428) -> Result<BuiltColumnarData> {
429    let n = records.len();
430    let mut registry = DictRegistry::new(cfg.clone());
431
432    let refs: Vec<Option<&BTreeMap<String, Value>>> = records.iter().map(Some).collect();
433    let mut next_col = 0u16;
434    let root_struct = infer_struct_schema("root", &refs, false, true, &mut next_col, &mut registry);
435    let root_table = TableSchema {
436        column_count: next_col,
437        root: root_struct,
438    };
439
440    // Materialize initially so we can compute optimal row ordering.
441    let (mut columns, mut row_ranges) =
442        materialize_table(&root_table, records, &registry, cfg.row_group_size);
443
444    let has_custom_ranges = row_ranges
445        .iter()
446        .any(|r| matches!(r, ColumnRowRanges::Custom(_)));
447
448    let old_to_new_rid: Vec<u32> = if n <= 1 {
449        let mut map = vec![0u32; n + 1];
450        if n == 1 {
451            map[1] = 1;
452        }
453        map
454    } else {
455        let perm = compute_row_permutation(
456            &root_table.root,
457            &registry.schemas,
458            &columns,
459            &row_ranges,
460            ip_first_pos,
461            n,
462            cfg.row_order,
463        );
464        let mut old_to_new = vec![0u32; n + 1];
465        for (new_idx, &old_idx) in perm.iter().enumerate() {
466            old_to_new[old_idx + 1] = (new_idx + 1) as u32;
467        }
468        if has_custom_ranges {
469            let sorted_records: Vec<BTreeMap<String, Value>> =
470                perm.iter().map(|&i| records[i].clone()).collect();
471            let (c2, r2) =
472                materialize_table(&root_table, &sorted_records, &registry, cfg.row_group_size);
473            columns = c2;
474            row_ranges = r2;
475        } else {
476            for col in &mut columns {
477                permute_column_in_place(col, &perm);
478            }
479        }
480        old_to_new
481    };
482
483    let record_columns_blob = encode_column_table(
484        &columns,
485        &row_ranges,
486        n,
487        cfg.row_group_size,
488        cfg.codec,
489        cfg.zstd_level,
490    )?;
491    let dict_blobs = registry.encode_all_dicts()?;
492
493    let schema = Schema {
494        dicts: registry.schemas,
495        root: root_table,
496    };
497
498    Ok(BuiltColumnarData {
499        schema,
500        record_columns_blob,
501        dict_blobs,
502        old_to_new_rid,
503    })
504}
505
506/// Field-type signature used to automatically share a `StructDict` across sibling fields
507/// with identical schemas (e.g., `country` and `registered_country`).
508type StructSignature = Vec<(String, BTreeSet<ValueKind>)>;
509
510fn infer_struct_schema(
511    scope_name: &str,
512    rows: &[Option<&BTreeMap<String, Value>>],
513    nullable: bool,
514    allow_struct_dict_promotion: bool,
515    next_col: &mut u16,
516    registry: &mut DictRegistry,
517) -> StructSchema {
518    let mut has_empty_map = false;
519    let mut field_names: BTreeSet<String> = BTreeSet::new();
520    for map in rows.iter().flatten() {
521        if map.is_empty() {
522            has_empty_map = true;
523        }
524        for k in map.keys() {
525            field_names.insert(k.clone());
526        }
527    }
528
529    let presence_col = if nullable && has_empty_map {
530        let c = *next_col;
531        *next_col += 1;
532        Some(c)
533    } else {
534        None
535    };
536
537    let field_list: Vec<String> = field_names.into_iter().collect();
538
539    // Step 1: Detect sibling StructDict candidates & pool identical-signature fields into shared StructDicts.
540    let mut preassigned_dict_refs: HashMap<String, (u16, IdWidth, bool)> = HashMap::new();
541    if allow_struct_dict_promotion {
542        struct CandInfo<'a> {
543            field_name: String,
544            nullable: bool,
545            sig: StructSignature,
546            maps: Vec<&'a BTreeMap<String, Value>>,
547        }
548
549        let mut cands: Vec<CandInfo<'_>> = Vec::new();
550        for fname in &field_list {
551            let mut non_null = 0usize;
552            let mut all_maps = true;
553            let mut has_empty = false;
554            let mut key_kinds: BTreeMap<String, BTreeSet<ValueKind>> = BTreeMap::new();
555            let mut maps = Vec::new();
556
557            for m in rows.iter().flatten() {
558                if let Some(val) = m.get(fname) {
559                    non_null += 1;
560                    if let Value::Map(sub) = val {
561                        if sub.is_empty() {
562                            has_empty = true;
563                        }
564                        maps.push(sub);
565                        for (sk, sv) in sub {
566                            key_kinds
567                                .entry(sk.clone())
568                                .or_default()
569                                .insert(value_kind(sv));
570                        }
571                    } else {
572                        all_maps = false;
573                        break;
574                    }
575                }
576            }
577
578            if !all_maps || non_null < 16 || key_kinds.is_empty() || key_kinds.len() > 64 {
579                continue;
580            }
581            // Skip ShreddedMap-like maps (uniform PType across >= 4 keys) and single-scalar-field structs
582            let is_uniform_shredded = key_kinds.len() >= 4
583                && key_kinds.values().all(|ks| {
584                    ks.len() == 1 && matches!(ks.iter().next(), Some(ValueKind::Prim(_)))
585                })
586                && {
587                    let first_k = key_kinds.values().next().unwrap();
588                    key_kinds.values().all(|ks| ks == first_k)
589                };
590            if is_uniform_shredded {
591                continue;
592            }
593            let has_nested_map = key_kinds.values().any(|ks| ks.contains(&ValueKind::Map));
594            if key_kinds.len() == 1 && !has_nested_map {
595                continue;
596            }
597
598            // Compute unique map count
599            let mut uniq: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
600            for &sub in &maps {
601                uniq.insert(sub, ());
602            }
603            let u = uniq.len();
604            if u == 0 || has_empty {
605                continue;
606            }
607            let low_card_win = u <= 4096 && non_null >= u * 2;
608            let heavy_entity_win = has_nested_map && u * 2 <= non_null;
609            if low_card_win || heavy_entity_win {
610                let sig: StructSignature = key_kinds.into_iter().collect();
611                cands.push(CandInfo {
612                    field_name: fname.clone(),
613                    nullable: non_null < rows.len(),
614                    sig,
615                    maps,
616                });
617            }
618        }
619
620        // Group candidates by exact signature to automatically share StructDicts (e.g. country + registered_country)
621        let mut by_sig: BTreeMap<StructSignature, Vec<CandInfo<'_>>> = BTreeMap::new();
622        for c in cands {
623            by_sig.entry(c.sig.clone()).or_default().push(c);
624        }
625        for (_sig, group) in by_sig {
626            let dict_name = if group.len() == 1 {
627                group[0].field_name.clone()
628            } else {
629                group
630                    .iter()
631                    .map(|g| g.field_name.as_str())
632                    .collect::<Vec<_>>()
633                    .join("_")
634            };
635            let mut uniq_set: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
636            for g in &group {
637                for &m in &g.maps {
638                    uniq_set.insert(m, ());
639                }
640            }
641            let unique_maps: Vec<BTreeMap<String, Value>> = uniq_set.into_keys().cloned().collect();
642            let (dict_id, id_width) = registry.register_struct_dict(dict_name, unique_maps);
643            for g in group {
644                preassigned_dict_refs.insert(g.field_name, (dict_id, id_width, g.nullable));
645            }
646        }
647    }
648
649    // Step 2: Detect joint floating-point DictGroups (e.g. (latitude, longitude) inside location)
650    let mut grouped_fields: BTreeSet<String> = BTreeSet::new();
651    let mut dict_groups: Vec<DictGroup> = Vec::new();
652    if allow_struct_dict_promotion {
653        let mut float_fields: Vec<String> = Vec::new();
654        for fname in &field_list {
655            if preassigned_dict_refs.contains_key(fname) {
656                continue;
657            }
658            let mut kinds = BTreeSet::new();
659            for m in rows.iter().flatten() {
660                if let Some(v) = m.get(fname) {
661                    kinds.insert(value_kind(v));
662                }
663            }
664            if kinds.len() == 1
665                && matches!(
666                    kinds.iter().next(),
667                    Some(ValueKind::Prim(PType::F64 | PType::F32))
668                )
669            {
670                float_fields.push(fname.clone());
671            }
672        }
673
674        if float_fields.len() >= 2 {
675            let mut non_empty_rows = 0usize;
676            let mut uniq_tuples: HashMap<BTreeMap<String, Value>, ()> = HashMap::new();
677            for m in rows.iter().flatten() {
678                let mut sub = BTreeMap::new();
679                for ff in &float_fields {
680                    if let Some(v) = m.get(ff) {
681                        sub.insert(ff.clone(), v.clone());
682                    }
683                }
684                if !sub.is_empty() {
685                    non_empty_rows += 1;
686                    uniq_tuples.insert(sub, ());
687                }
688            }
689            let u = uniq_tuples.len();
690            if u > 0 && non_empty_rows >= 16 && u * 2 <= non_empty_rows {
691                let unique_maps: Vec<BTreeMap<String, Value>> = uniq_tuples.into_keys().collect();
692                let group_name = format!("{scope_name}_{}", float_fields.join("_"));
693                let (dict_id, id_width) = registry.register_struct_dict(group_name, unique_maps);
694                let col_id = *next_col;
695                *next_col += 1;
696                for ff in &float_fields {
697                    grouped_fields.insert(ff.clone());
698                }
699                dict_groups.push(DictGroup {
700                    dict_id,
701                    id_width,
702                    col_id,
703                    field_names: float_fields,
704                });
705            }
706        }
707    }
708
709    // Step 3: Infer remaining fields
710    let mut fields = Vec::with_capacity(field_list.len());
711    for fname in field_list {
712        if grouped_fields.contains(&fname) {
713            continue;
714        }
715        if let Some((dict_id, id_width, field_nullable)) = preassigned_dict_refs.get(&fname) {
716            let col_id = *next_col;
717            *next_col += 1;
718            fields.push(StructField {
719                name: fname,
720                col_type: ColumnType::DictRef {
721                    dict_id: *dict_id,
722                    id_width: *id_width,
723                    nullable: *field_nullable,
724                    col_id,
725                },
726            });
727            continue;
728        }
729
730        let vals: Vec<Option<&Value>> =
731            rows.iter().map(|r| r.and_then(|m| m.get(&fname))).collect();
732        let child_scope = format!("{scope_name}_{fname}");
733        let col_type = infer_column_type(
734            &child_scope,
735            &vals,
736            allow_struct_dict_promotion,
737            next_col,
738            registry,
739        );
740        fields.push(StructField {
741            name: fname,
742            col_type,
743        });
744    }
745
746    StructSchema {
747        nullable,
748        presence_col,
749        fields,
750        dict_groups,
751    }
752}
753
754fn infer_column_type(
755    field_path: &str,
756    vals: &[Option<&Value>],
757    allow_dicts: bool,
758    next_col: &mut u16,
759    registry: &mut DictRegistry,
760) -> ColumnType {
761    let mut kinds: BTreeSet<ValueKind> = BTreeSet::new();
762    let mut non_null = 0usize;
763    for val in vals.iter().flatten() {
764        non_null += 1;
765        kinds.insert(value_kind(val));
766    }
767    let nullable = non_null < vals.len();
768
769    if kinds.is_empty() || kinds.len() > 1 || kinds.contains(&ValueKind::Null) {
770        let col_id = *next_col;
771        *next_col += 1;
772        return ColumnType::Dynamic { nullable, col_id };
773    }
774
775    match *kinds.iter().next().unwrap() {
776        ValueKind::Prim(ptype) => {
777            if allow_dicts && matches!(ptype, PType::Utf8 | PType::Bytes) && non_null >= 16 {
778                let mut uniq: HashMap<&Value, ()> = HashMap::new();
779                for v in vals.iter().flatten() {
780                    uniq.insert(*v, ());
781                }
782                let u = uniq.len();
783                let promote =
784                    (u <= 65_535 && non_null >= u * 2) || (u > 65_535 && non_null >= u * 3);
785                if promote && u > 0 {
786                    let unique_vals: Vec<Value> = uniq.into_keys().cloned().collect();
787                    let (dict_id, id_width) =
788                        registry.register_flat_dict(field_path.to_string(), ptype, unique_vals);
789                    let col_id = *next_col;
790                    *next_col += 1;
791                    return ColumnType::DictRef {
792                        dict_id,
793                        id_width,
794                        nullable,
795                        col_id,
796                    };
797                }
798            }
799            let col_id = *next_col;
800            *next_col += 1;
801            ColumnType::Primitive {
802                ptype,
803                nullable,
804                col_id,
805            }
806        }
807        ValueKind::Map => {
808            let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
809                .iter()
810                .map(|o| match o {
811                    Some(Value::Map(m)) => Some(m),
812                    _ => None,
813                })
814                .collect();
815
816            // Check if this Map should be ShreddedMap vs Struct vs Dynamic
817            let mut key_counts: BTreeMap<String, usize> = BTreeMap::new();
818            let mut val_kinds: BTreeSet<ValueKind> = BTreeSet::new();
819            let mut has_empty = false;
820            for m in map_rows.iter().flatten() {
821                if m.is_empty() {
822                    has_empty = true;
823                }
824                for (k, v) in *m {
825                    *key_counts.entry(k.clone()).or_insert(0) += 1;
826                    val_kinds.insert(value_kind(v));
827                }
828            }
829
830            let is_uniform_prim_map = key_counts.len() >= 4
831                && val_kinds.len() == 1
832                && matches!(val_kinds.iter().next(), Some(ValueKind::Prim(_)));
833
834            if is_uniform_prim_map {
835                let ptype = match *val_kinds.iter().next().unwrap() {
836                    ValueKind::Prim(p) => p,
837                    _ => unreachable!(),
838                };
839                // Shred frequent keys (all keys if <= 32, otherwise keys with >= 1% frequency, capped at 64)
840                let mut shredded_keys: Vec<String> = if key_counts.len() <= 32 {
841                    key_counts.keys().cloned().collect()
842                } else {
843                    let threshold = (non_null / 100).max(1);
844                    let mut freq: Vec<(String, usize)> = key_counts
845                        .iter()
846                        .filter(|&(_, &c)| c >= threshold)
847                        .map(|(k, &c)| (k.clone(), c))
848                        .collect();
849                    freq.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
850                    freq.truncate(64);
851                    let mut ks: Vec<String> = freq.into_iter().map(|(k, _)| k).collect();
852                    ks.sort();
853                    ks
854                };
855                shredded_keys.sort();
856                let has_overflow = shredded_keys.len() < key_counts.len();
857
858                let presence_col = if nullable && has_empty {
859                    let c = *next_col;
860                    *next_col += 1;
861                    Some(c)
862                } else {
863                    None
864                };
865                let overflow_col = if has_overflow {
866                    let c = *next_col;
867                    *next_col += 1;
868                    Some(c)
869                } else {
870                    None
871                };
872
873                let mut entries = Vec::with_capacity(shredded_keys.len());
874                for k in shredded_keys {
875                    let key_nullable = key_counts[&k] < vals.len();
876                    let col_id = *next_col;
877                    *next_col += 1;
878                    entries.push(ShreddedMapEntry {
879                        key: k,
880                        value_type: ColumnType::Primitive {
881                            ptype,
882                            nullable: key_nullable,
883                            col_id,
884                        },
885                    });
886                }
887
888                ColumnType::ShreddedMap {
889                    nullable,
890                    presence_col,
891                    overflow_col,
892                    entries,
893                }
894            } else if key_counts.len() > 128 {
895                let col_id = *next_col;
896                *next_col += 1;
897                ColumnType::Dynamic { nullable, col_id }
898            } else {
899                let s = infer_struct_schema(
900                    field_path,
901                    &map_rows,
902                    nullable,
903                    allow_dicts,
904                    next_col,
905                    registry,
906                );
907                ColumnType::Struct(s)
908            }
909        }
910        ValueKind::Array => {
911            // Inspect element types across all arrays
912            let mut elem_kinds: BTreeSet<ValueKind> = BTreeSet::new();
913            let mut all_elems: Vec<&Value> = Vec::new();
914            let mut uniq_lists: HashMap<&Vec<Value>, ()> = HashMap::new();
915            for v in vals.iter().flatten() {
916                if let Value::Array(arr) = v {
917                    uniq_lists.insert(arr, ());
918                    for item in arr {
919                        elem_kinds.insert(value_kind(item));
920                        all_elems.push(item);
921                    }
922                }
923            }
924
925            // Try ListDict normalization for low-cardinality homogeneous lists (e.g. subdivisions[])
926            let u_lists = uniq_lists.len();
927            if allow_dicts
928                && elem_kinds.len() == 1
929                && non_null >= 8
930                && u_lists > 0
931                && u_lists * 2 <= non_null
932                && (u_lists <= 65_535 || u_lists * 3 <= non_null)
933            {
934                match *elem_kinds.iter().next().unwrap() {
935                    ValueKind::Map => {
936                        let mut uniq_elems: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
937                        for item in &all_elems {
938                            if let Value::Map(m) = item {
939                                uniq_elems.insert(m, ());
940                            }
941                        }
942                        if !uniq_elems.is_empty() {
943                            let elem_maps: Vec<BTreeMap<String, Value>> =
944                                uniq_elems.into_keys().cloned().collect();
945                            let (elem_dict_id, elem_id_width) = registry
946                                .register_struct_dict(format!("{field_path}_elem"), elem_maps);
947                            let list_vec: Vec<Vec<Value>> =
948                                uniq_lists.into_keys().cloned().collect();
949                            let (list_dict_id, list_id_width) = registry.register_list_dict(
950                                format!("{field_path}_list"),
951                                list_vec,
952                                elem_dict_id,
953                                elem_id_width,
954                            );
955                            let col_id = *next_col;
956                            *next_col += 1;
957                            return ColumnType::DictRef {
958                                dict_id: list_dict_id,
959                                id_width: list_id_width,
960                                nullable,
961                                col_id,
962                            };
963                        }
964                    }
965                    ValueKind::Prim(ptype) => {
966                        let mut uniq_elems: HashMap<&Value, ()> = HashMap::new();
967                        for &item in &all_elems {
968                            uniq_elems.insert(item, ());
969                        }
970                        if !uniq_elems.is_empty() {
971                            let elem_vals: Vec<Value> = uniq_elems.into_keys().cloned().collect();
972                            let (elem_dict_id, elem_id_width) = registry.register_flat_dict(
973                                format!("{field_path}_elem"),
974                                ptype,
975                                elem_vals,
976                            );
977                            let list_vec: Vec<Vec<Value>> =
978                                uniq_lists.into_keys().cloned().collect();
979                            let (list_dict_id, list_id_width) = registry.register_list_dict(
980                                format!("{field_path}_list"),
981                                list_vec,
982                                elem_dict_id,
983                                elem_id_width,
984                            );
985                            let col_id = *next_col;
986                            *next_col += 1;
987                            return ColumnType::DictRef {
988                                dict_id: list_dict_id,
989                                id_width: list_id_width,
990                                nullable,
991                                col_id,
992                            };
993                        }
994                    }
995                    _ => {}
996                }
997            }
998
999            // High-cardinality List or empty arrays
1000            if elem_kinds.len() == 1 && !elem_kinds.contains(&ValueKind::Null) {
1001                let offsets_col = *next_col;
1002                *next_col += 1;
1003                let elem_opts: Vec<Option<&Value>> = all_elems.into_iter().map(Some).collect();
1004                let elem_type = infer_column_type(
1005                    &format!("{field_path}_item"),
1006                    &elem_opts,
1007                    false,
1008                    next_col,
1009                    registry,
1010                );
1011                ColumnType::List {
1012                    nullable,
1013                    offsets_col,
1014                    elem_type: Box::new(elem_type),
1015                }
1016            } else {
1017                let col_id = *next_col;
1018                *next_col += 1;
1019                ColumnType::Dynamic { nullable, col_id }
1020            }
1021        }
1022        ValueKind::Null => unreachable!(),
1023    }
1024}
1025
1026/// Materialize all physical columns (and custom per-RowGroup ranges for List children) of a `TableSchema`.
1027fn materialize_table(
1028    table: &TableSchema,
1029    records: &[BTreeMap<String, Value>],
1030    registry: &DictRegistry,
1031    row_group_size: u32,
1032) -> (Vec<ColumnData>, Vec<ColumnRowRanges>) {
1033    let kinds = table
1034        .physical_column_kinds(registry.schemas.len())
1035        .expect("inferred schema must be valid");
1036    let n = records.len();
1037    let mut columns: Vec<ColumnData> = kinds
1038        .iter()
1039        .map(|k| match k {
1040            coip_format::PhysicalColKind::Primitive(p) => ColumnData::empty_for_ptype(*p, n),
1041            coip_format::PhysicalColKind::Dynamic => ColumnData::Dynamic(Vec::with_capacity(n)),
1042        })
1043        .collect();
1044    let mut row_ranges: Vec<ColumnRowRanges> = vec![ColumnRowRanges::Uniform; kinds.len()];
1045
1046    let rg_size = row_group_size.max(1) as usize;
1047    let rg_count = if n == 0 { 0 } else { n.div_ceil(rg_size) };
1048    let root_rg_bounds: Vec<(usize, usize)> = (0..rg_count)
1049        .map(|rg| {
1050            let s = rg * rg_size;
1051            (s, (s + rg_size).min(n))
1052        })
1053        .collect();
1054
1055    let row_refs: Vec<Option<&BTreeMap<String, Value>>> = records.iter().map(Some).collect();
1056    fill_struct_columns(
1057        &table.root,
1058        &row_refs,
1059        &root_rg_bounds,
1060        false,
1061        registry,
1062        &mut columns,
1063        &mut row_ranges,
1064    );
1065
1066    (columns, row_ranges)
1067}
1068
1069fn fill_struct_columns(
1070    schema: &StructSchema,
1071    rows: &[Option<&BTreeMap<String, Value>>],
1072    rg_bounds: &[(usize, usize)],
1073    is_custom_rg: bool,
1074    registry: &DictRegistry,
1075    columns: &mut [ColumnData],
1076    row_ranges: &mut [ColumnRowRanges],
1077) {
1078    if let Some(c) = schema.presence_col {
1079        if is_custom_rg {
1080            row_ranges[c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1081        }
1082        if let ColumnData::Bool(vec) = &mut columns[c as usize] {
1083            for r in rows {
1084                vec.push(Some(r.is_some()));
1085            }
1086        }
1087    }
1088
1089    for g in &schema.dict_groups {
1090        if is_custom_rg {
1091            row_ranges[g.col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1092        }
1093        let lookup = match &registry.lookups[g.dict_id as usize] {
1094            BuiltDictLookup::Struct { lookup } => lookup,
1095            _ => panic!("DictGroup must reference StructDict"),
1096        };
1097        for r in rows {
1098            let id = match r {
1099                None => 0u32,
1100                Some(m) => {
1101                    let mut sub = BTreeMap::new();
1102                    for ff in &g.field_names {
1103                        if let Some(v) = m.get(ff) {
1104                            sub.insert(ff.clone(), v.clone());
1105                        }
1106                    }
1107                    if sub.is_empty() {
1108                        0
1109                    } else {
1110                        *lookup.get(&sub).expect("DictGroup entry must exist")
1111                    }
1112                }
1113            };
1114            push_dict_id(&mut columns[g.col_id as usize], id);
1115        }
1116    }
1117
1118    for f in &schema.fields {
1119        let vals: Vec<Option<&Value>> = rows
1120            .iter()
1121            .map(|r| r.and_then(|m| m.get(&f.name)))
1122            .collect();
1123        fill_col_type(
1124            &f.col_type,
1125            &vals,
1126            rg_bounds,
1127            is_custom_rg,
1128            registry,
1129            columns,
1130            row_ranges,
1131        );
1132    }
1133}
1134
1135fn fill_col_type(
1136    ct: &ColumnType,
1137    vals: &[Option<&Value>],
1138    rg_bounds: &[(usize, usize)],
1139    is_custom_rg: bool,
1140    registry: &DictRegistry,
1141    columns: &mut [ColumnData],
1142    row_ranges: &mut [ColumnRowRanges],
1143) {
1144    match ct {
1145        ColumnType::Primitive { ptype, col_id, .. } => {
1146            if is_custom_rg {
1147                row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1148            }
1149            push_prim_values(&mut columns[*col_id as usize], *ptype, vals);
1150        }
1151        ColumnType::DictRef {
1152            dict_id, col_id, ..
1153        } => {
1154            if is_custom_rg {
1155                row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1156            }
1157            let lookup = &registry.lookups[*dict_id as usize];
1158            for v in vals {
1159                let id = match v {
1160                    None => 0u32,
1161                    Some(val) => match lookup {
1162                        BuiltDictLookup::Flat { lookup } => {
1163                            *lookup.get(val).expect("FlatDict entry must exist")
1164                        }
1165                        BuiltDictLookup::Struct { lookup } => match val {
1166                            Value::Map(m) => *lookup.get(m).expect("StructDict entry must exist"),
1167                            _ => panic!("expected Map for StructDict"),
1168                        },
1169                        BuiltDictLookup::List { lookup } => match val {
1170                            Value::Array(a) => *lookup.get(a).expect("ListDict entry must exist"),
1171                            _ => panic!("expected Array for ListDict"),
1172                        },
1173                    },
1174                };
1175                push_dict_id(&mut columns[*col_id as usize], id);
1176            }
1177        }
1178        ColumnType::Struct(s) => {
1179            let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
1180                .iter()
1181                .map(|o| match o {
1182                    Some(Value::Map(m)) => Some(m),
1183                    _ => None,
1184                })
1185                .collect();
1186            fill_struct_columns(
1187                s,
1188                &map_rows,
1189                rg_bounds,
1190                is_custom_rg,
1191                registry,
1192                columns,
1193                row_ranges,
1194            );
1195        }
1196        ColumnType::ShreddedMap {
1197            presence_col,
1198            overflow_col,
1199            entries,
1200            ..
1201        } => {
1202            let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
1203                .iter()
1204                .map(|o| match o {
1205                    Some(Value::Map(m)) => Some(m),
1206                    _ => None,
1207                })
1208                .collect();
1209            if let Some(c) = presence_col {
1210                if is_custom_rg {
1211                    row_ranges[*c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1212                }
1213                if let ColumnData::Bool(vec) = &mut columns[*c as usize] {
1214                    for m in &map_rows {
1215                        vec.push(Some(m.is_some()));
1216                    }
1217                }
1218            }
1219            let known_keys: BTreeSet<&str> = entries.iter().map(|e| e.key.as_str()).collect();
1220            for e in entries {
1221                let key_vals: Vec<Option<&Value>> = map_rows
1222                    .iter()
1223                    .map(|m| m.and_then(|map| map.get(&e.key)))
1224                    .collect();
1225                fill_col_type(
1226                    &e.value_type,
1227                    &key_vals,
1228                    rg_bounds,
1229                    is_custom_rg,
1230                    registry,
1231                    columns,
1232                    row_ranges,
1233                );
1234            }
1235            if let Some(c) = overflow_col {
1236                if is_custom_rg {
1237                    row_ranges[*c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1238                }
1239                if let ColumnData::Dynamic(vec) = &mut columns[*c as usize] {
1240                    for m in &map_rows {
1241                        match m {
1242                            None => vec.push(None),
1243                            Some(map) => {
1244                                let mut extra = BTreeMap::new();
1245                                for (k, v) in *map {
1246                                    if !known_keys.contains(k.as_str()) {
1247                                        extra.insert(k.clone(), v.clone());
1248                                    }
1249                                }
1250                                if extra.is_empty() {
1251                                    vec.push(None);
1252                                } else {
1253                                    let mut buf = Vec::new();
1254                                    Value::Map(extra).encode(&mut buf);
1255                                    vec.push(Some(buf));
1256                                }
1257                            }
1258                        }
1259                    }
1260                }
1261            }
1262        }
1263        ColumnType::List {
1264            offsets_col,
1265            elem_type,
1266            ..
1267        } => {
1268            if is_custom_rg {
1269                row_ranges[*offsets_col as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1270            }
1271            let mut flat_elems: Vec<Option<&Value>> = Vec::new();
1272            let mut child_rg_bounds: Vec<(usize, usize)> = Vec::with_capacity(rg_bounds.len());
1273            for &(rg_s, rg_e) in rg_bounds {
1274                let child_start = flat_elems.len();
1275                for v in &vals[rg_s..rg_e] {
1276                    match v {
1277                        None => {
1278                            if let ColumnData::U32(vec) = &mut columns[*offsets_col as usize] {
1279                                vec.push(None);
1280                            }
1281                        }
1282                        Some(Value::Array(arr)) => {
1283                            if let ColumnData::U32(vec) = &mut columns[*offsets_col as usize] {
1284                                vec.push(Some(arr.len() as u32));
1285                            }
1286                            for item in arr {
1287                                flat_elems.push(Some(item));
1288                            }
1289                        }
1290                        _ => panic!("expected Array for List column"),
1291                    }
1292                }
1293                child_rg_bounds.push((child_start, flat_elems.len()));
1294            }
1295            fill_col_type(
1296                elem_type,
1297                &flat_elems,
1298                &child_rg_bounds,
1299                true,
1300                registry,
1301                columns,
1302                row_ranges,
1303            );
1304        }
1305        ColumnType::Dynamic { col_id, .. } => {
1306            if is_custom_rg {
1307                row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
1308            }
1309            if let ColumnData::Dynamic(vec) = &mut columns[*col_id as usize] {
1310                for v in vals {
1311                    match v {
1312                        None => vec.push(None),
1313                        Some(val) => {
1314                            let mut buf = Vec::new();
1315                            val.encode(&mut buf);
1316                            vec.push(Some(buf));
1317                        }
1318                    }
1319                }
1320            }
1321        }
1322    }
1323}
1324
1325#[inline]
1326fn push_dict_id(col: &mut ColumnData, id: u32) {
1327    match col {
1328        ColumnData::U8(v) => v.push(Some(id as u8)),
1329        ColumnData::U16(v) => v.push(Some(id as u16)),
1330        ColumnData::U32(v) => v.push(Some(id)),
1331        _ => panic!("DictRef column must be U8/U16/U32"),
1332    }
1333}
1334
1335fn push_prim_values(col: &mut ColumnData, ptype: PType, vals: &[Option<&Value>]) {
1336    match (col, ptype) {
1337        (ColumnData::Bool(vec), PType::Bool) => {
1338            for v in vals {
1339                vec.push(v.map(|x| match x {
1340                    Value::Bool(b) => *b,
1341                    _ => panic!("expected Bool"),
1342                }));
1343            }
1344        }
1345        (ColumnData::U8(vec), PType::U8) => {
1346            for v in vals {
1347                vec.push(v.map(|x| match x {
1348                    Value::U8(n) => *n,
1349                    _ => panic!("expected U8"),
1350                }));
1351            }
1352        }
1353        (ColumnData::U16(vec), PType::U16) => {
1354            for v in vals {
1355                vec.push(v.map(|x| match x {
1356                    Value::U16(n) => *n,
1357                    _ => panic!("expected U16"),
1358                }));
1359            }
1360        }
1361        (ColumnData::U32(vec), PType::U32) => {
1362            for v in vals {
1363                vec.push(v.map(|x| match x {
1364                    Value::U32(n) => *n,
1365                    _ => panic!("expected U32"),
1366                }));
1367            }
1368        }
1369        (ColumnData::U64(vec), PType::U64) => {
1370            for v in vals {
1371                vec.push(v.map(|x| match x {
1372                    Value::U64(n) => *n,
1373                    _ => panic!("expected U64"),
1374                }));
1375            }
1376        }
1377        (ColumnData::U128(vec), PType::U128) => {
1378            for v in vals {
1379                vec.push(v.map(|x| match x {
1380                    Value::U128(n) => *n,
1381                    _ => panic!("expected U128"),
1382                }));
1383            }
1384        }
1385        (ColumnData::I32(vec), PType::I32) => {
1386            for v in vals {
1387                vec.push(v.map(|x| match x {
1388                    Value::I32(n) => *n,
1389                    _ => panic!("expected I32"),
1390                }));
1391            }
1392        }
1393        (ColumnData::I64(vec), PType::I64) => {
1394            for v in vals {
1395                vec.push(v.map(|x| match x {
1396                    Value::I64(n) => *n,
1397                    _ => panic!("expected I64"),
1398                }));
1399            }
1400        }
1401        (ColumnData::F32(vec), PType::F32) => {
1402            for v in vals {
1403                vec.push(v.map(|x| match x {
1404                    Value::F32(n) => *n,
1405                    _ => panic!("expected F32"),
1406                }));
1407            }
1408        }
1409        (ColumnData::F64(vec), PType::F64) => {
1410            for v in vals {
1411                vec.push(v.map(|x| match x {
1412                    Value::F64(n) => *n,
1413                    _ => panic!("expected F64"),
1414                }));
1415            }
1416        }
1417        (ColumnData::Utf8(vec), PType::Utf8) => {
1418            for v in vals {
1419                vec.push(v.map(|x| match x {
1420                    Value::Utf8(s) => s.clone(),
1421                    _ => panic!("expected Utf8"),
1422                }));
1423            }
1424        }
1425        (ColumnData::Bytes(vec), PType::Bytes) => {
1426            for v in vals {
1427                vec.push(v.map(|x| match x {
1428                    Value::Bytes(b) => b.clone(),
1429                    _ => panic!("expected Bytes"),
1430                }));
1431            }
1432        }
1433        _ => panic!("mismatched ColumnData vs PType"),
1434    }
1435}
1436
1437/// Collect physical column IDs that reference a dictionary, paired with `(col_id, dict_id)`.
1438fn collect_dict_cols(s: &StructSchema, out: &mut Vec<(usize, u16)>) {
1439    for g in &s.dict_groups {
1440        out.push((g.col_id as usize, g.dict_id));
1441    }
1442    for f in &s.fields {
1443        match &f.col_type {
1444            ColumnType::DictRef {
1445                col_id, dict_id, ..
1446            } => {
1447                out.push((*col_id as usize, *dict_id));
1448            }
1449            ColumnType::Struct(sub) => collect_dict_cols(sub, out),
1450            _ => {}
1451        }
1452    }
1453}
1454
1455/// Compute row ordering permutation according to `strategy`.
1456fn compute_row_permutation(
1457    root: &StructSchema,
1458    dict_schemas: &[DictSchema],
1459    columns: &[ColumnData],
1460    row_ranges: &[ColumnRowRanges],
1461    ip_first_pos: &[u64],
1462    n: usize,
1463    strategy: RowOrderStrategy,
1464) -> Vec<usize> {
1465    if strategy == RowOrderStrategy::IpLocality && ip_first_pos.len() == n {
1466        let mut perm: Vec<usize> = (0..n).collect();
1467        perm.sort_unstable_by(|&a, &b| {
1468            ip_first_pos[a]
1469                .cmp(&ip_first_pos[b])
1470                .then_with(|| a.cmp(&b))
1471        });
1472        return perm;
1473    }
1474
1475    let mut raw_dict_cols = Vec::new();
1476    collect_dict_cols(root, &mut raw_dict_cols);
1477
1478    // Map each col_id -> is_large_flat_dict (chunked FlatDict with block_size > 0, e.g. postal.code)
1479    let mut col_is_large_flat: HashMap<usize, bool> = HashMap::new();
1480    for (col_id, dict_id) in raw_dict_cols {
1481        let is_large_flat = matches!(
1482            dict_schemas[dict_id as usize].kind,
1483            DictKind::Flat { block_size, .. } if block_size > 0
1484        );
1485        col_is_large_flat.insert(col_id, is_large_flat);
1486    }
1487
1488    // Tier 0: Dense (>50% non-zero) StructDict/ListDict/small-FlatDict columns ordered by ascending cardinality
1489    // Tier 1: Large chunked FlatDicts (e.g. postal.code)
1490    // Tier 2: Remaining scalar/sparse columns (accuracy_radius, metro_code, is_anycast, etc.)
1491    let mut tier0: Vec<(usize, usize)> = Vec::new();
1492    let mut tier1: Vec<(usize, usize)> = Vec::new();
1493    let mut tier2: Vec<(usize, usize)> = Vec::new();
1494    for (idx, (col, rr)) in columns.iter().zip(row_ranges.iter()).enumerate() {
1495        if !matches!(rr, ColumnRowRanges::Uniform) || col.len() != n {
1496            continue;
1497        }
1498        let card = column_cardinality(col);
1499        if card <= 1 {
1500            continue;
1501        }
1502        let non_zero = column_non_zero_count(col);
1503        match col_is_large_flat.get(&idx) {
1504            Some(&false) if non_zero * 2 >= n => tier0.push((card, idx)),
1505            Some(&true) if non_zero * 2 >= n => tier1.push((card, idx)),
1506            _ => tier2.push((card, idx)),
1507        }
1508    }
1509    tier0.sort_unstable();
1510    tier1.sort_unstable();
1511    tier2.sort_unstable();
1512
1513    if strategy == RowOrderStrategy::HybridGeoIp && ip_first_pos.len() == n {
1514        let coarse: Vec<usize> = tier0
1515            .iter()
1516            .filter(|&&(card, _)| card <= 512)
1517            .take(2)
1518            .map(|&(_, idx)| idx)
1519            .collect();
1520        let mut perm: Vec<usize> = (0..n).collect();
1521        perm.sort_unstable_by(|&a, &b| {
1522            for &c in &coarse {
1523                let ord = cmp_column_rows(&columns[c], a, b);
1524                if ord != std::cmp::Ordering::Equal {
1525                    return ord;
1526                }
1527            }
1528            ip_first_pos[a]
1529                .cmp(&ip_first_pos[b])
1530                .then_with(|| a.cmp(&b))
1531        });
1532        return perm;
1533    }
1534
1535    let mut sort_cols: Vec<usize> = tier0.into_iter().map(|(_, idx)| idx).collect();
1536    sort_cols.extend(tier1.into_iter().map(|(_, idx)| idx));
1537    sort_cols.extend(tier2.into_iter().map(|(_, idx)| idx));
1538
1539    let mut perm: Vec<usize> = (0..n).collect();
1540    perm.sort_unstable_by(|&a, &b| {
1541        for &c in &sort_cols {
1542            let ord = cmp_column_rows(&columns[c], a, b);
1543            if ord != std::cmp::Ordering::Equal {
1544                return ord;
1545            }
1546        }
1547        a.cmp(&b)
1548    });
1549    perm
1550}
1551
1552fn column_non_zero_count(col: &ColumnData) -> usize {
1553    match col {
1554        ColumnData::U8(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
1555        ColumnData::U16(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
1556        ColumnData::U32(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
1557        ColumnData::U64(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
1558        ColumnData::Bool(v) => v.iter().filter(|x| x.is_some()).count(),
1559        ColumnData::U128(v) => v.iter().filter(|x| x.is_some()).count(),
1560        ColumnData::I32(v) => v.iter().filter(|x| x.is_some()).count(),
1561        ColumnData::I64(v) => v.iter().filter(|x| x.is_some()).count(),
1562        ColumnData::F32(v) => v.iter().filter(|x| x.is_some()).count(),
1563        ColumnData::F64(v) => v.iter().filter(|x| x.is_some()).count(),
1564        ColumnData::Utf8(v) => v.iter().filter(|x| x.is_some()).count(),
1565        ColumnData::Bytes(v) | ColumnData::Dynamic(v) => v.iter().filter(|x| x.is_some()).count(),
1566    }
1567}
1568
1569fn column_cardinality(col: &ColumnData) -> usize {
1570    match col {
1571        ColumnData::Bool(v) => {
1572            let mut s = BTreeSet::new();
1573            for x in v {
1574                s.insert(*x);
1575            }
1576            s.len()
1577        }
1578        ColumnData::U8(v) => {
1579            let mut seen = [false; 257];
1580            let mut c = 0;
1581            for x in v {
1582                let slot = match x {
1583                    None => 256,
1584                    Some(n) => *n as usize,
1585                };
1586                if !seen[slot] {
1587                    seen[slot] = true;
1588                    c += 1;
1589                }
1590            }
1591            c
1592        }
1593        ColumnData::U16(v) => {
1594            let mut s = HashMap::new();
1595            for x in v {
1596                s.insert(*x, ());
1597            }
1598            s.len()
1599        }
1600        ColumnData::U32(v) => {
1601            let mut s = HashMap::new();
1602            for x in v {
1603                s.insert(*x, ());
1604            }
1605            s.len()
1606        }
1607        ColumnData::U64(v) => {
1608            let mut s = HashMap::new();
1609            for x in v {
1610                s.insert(*x, ());
1611            }
1612            s.len()
1613        }
1614        ColumnData::U128(v) => {
1615            let mut s = HashMap::new();
1616            for x in v {
1617                s.insert(*x, ());
1618            }
1619            s.len()
1620        }
1621        ColumnData::I32(v) => {
1622            let mut s = HashMap::new();
1623            for x in v {
1624                s.insert(*x, ());
1625            }
1626            s.len()
1627        }
1628        ColumnData::I64(v) => {
1629            let mut s = HashMap::new();
1630            for x in v {
1631                s.insert(*x, ());
1632            }
1633            s.len()
1634        }
1635        ColumnData::F32(v) => {
1636            let mut s = HashMap::new();
1637            for x in v {
1638                s.insert(x.map(f32::to_bits), ());
1639            }
1640            s.len()
1641        }
1642        ColumnData::F64(v) => {
1643            let mut s = HashMap::new();
1644            for x in v {
1645                s.insert(x.map(f64::to_bits), ());
1646            }
1647            s.len()
1648        }
1649        ColumnData::Utf8(v) => {
1650            let mut s: HashMap<Option<&str>, ()> = HashMap::new();
1651            for x in v {
1652                s.insert(x.as_deref(), ());
1653            }
1654            s.len()
1655        }
1656        ColumnData::Bytes(v) | ColumnData::Dynamic(v) => {
1657            let mut s: HashMap<Option<&[u8]>, ()> = HashMap::new();
1658            for x in v {
1659                s.insert(x.as_deref(), ());
1660            }
1661            s.len()
1662        }
1663    }
1664}
1665
1666#[inline]
1667fn cmp_column_rows(col: &ColumnData, a: usize, b: usize) -> std::cmp::Ordering {
1668    match col {
1669        ColumnData::Bool(v) => v[a].cmp(&v[b]),
1670        ColumnData::U8(v) => v[a].cmp(&v[b]),
1671        ColumnData::U16(v) => v[a].cmp(&v[b]),
1672        ColumnData::U32(v) => v[a].cmp(&v[b]),
1673        ColumnData::U64(v) => v[a].cmp(&v[b]),
1674        ColumnData::U128(v) => v[a].cmp(&v[b]),
1675        ColumnData::I32(v) => v[a].cmp(&v[b]),
1676        ColumnData::I64(v) => v[a].cmp(&v[b]),
1677        ColumnData::F32(v) => v[a].map(f32::to_bits).cmp(&v[b].map(f32::to_bits)),
1678        ColumnData::F64(v) => v[a].map(f64::to_bits).cmp(&v[b].map(f64::to_bits)),
1679        ColumnData::Utf8(v) => v[a].cmp(&v[b]),
1680        ColumnData::Bytes(v) | ColumnData::Dynamic(v) => v[a].cmp(&v[b]),
1681    }
1682}
1683
1684fn permute_vec<T: Clone>(v: &mut Vec<T>, perm: &[usize]) {
1685    let reordered: Vec<T> = perm.iter().map(|&i| v[i].clone()).collect();
1686    *v = reordered;
1687}
1688
1689fn permute_column_in_place(col: &mut ColumnData, perm: &[usize]) {
1690    match col {
1691        ColumnData::Bool(v) => permute_vec(v, perm),
1692        ColumnData::U8(v) => permute_vec(v, perm),
1693        ColumnData::U16(v) => permute_vec(v, perm),
1694        ColumnData::U32(v) => permute_vec(v, perm),
1695        ColumnData::U64(v) => permute_vec(v, perm),
1696        ColumnData::U128(v) => permute_vec(v, perm),
1697        ColumnData::I32(v) => permute_vec(v, perm),
1698        ColumnData::I64(v) => permute_vec(v, perm),
1699        ColumnData::F32(v) => permute_vec(v, perm),
1700        ColumnData::F64(v) => permute_vec(v, perm),
1701        ColumnData::Utf8(v) => permute_vec(v, perm),
1702        ColumnData::Bytes(v) | ColumnData::Dynamic(v) => permute_vec(v, perm),
1703    }
1704}