use std::collections::{BTreeMap, BTreeSet, HashMap};
use coip_format::{
Codec, ColumnType, DictGroup, DictKind, DictSchema, IdWidth, PType, Schema, ShreddedMapEntry,
StructField, StructSchema, TableSchema, Value,
};
use crate::column_writer::{
ColumnData, ColumnRowRanges, FlatDictValues, encode_column_table, encode_flat_dict,
encode_list_dict,
};
use crate::error::Result;
pub struct BuiltColumnarData {
pub schema: Schema,
pub record_columns_blob: Vec<u8>,
pub dict_blobs: Vec<Vec<u8>>,
pub old_to_new_rid: Vec<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowOrderStrategy {
IpLocality,
GeoLocality,
HybridGeoIp,
}
#[derive(Debug, Clone)]
pub struct ColumnarBuildConfig {
pub row_group_size: u32,
pub struct_dict_row_group_size: u32,
pub dict_block_size: u32,
pub codec: Codec,
pub zstd_level: i32,
pub row_order: RowOrderStrategy,
}
impl Default for ColumnarBuildConfig {
fn default() -> Self {
Self {
row_group_size: 4096,
struct_dict_row_group_size: 2048,
dict_block_size: 4096,
codec: Codec::Zstd,
zstd_level: 9,
row_order: RowOrderStrategy::GeoLocality,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum ValueKind {
Null,
Prim(PType),
Array,
Map,
}
fn value_kind(v: &Value) -> ValueKind {
match v {
Value::Null => ValueKind::Null,
Value::Bool(_) => ValueKind::Prim(PType::Bool),
Value::U8(_) => ValueKind::Prim(PType::U8),
Value::U16(_) => ValueKind::Prim(PType::U16),
Value::U32(_) => ValueKind::Prim(PType::U32),
Value::U64(_) => ValueKind::Prim(PType::U64),
Value::U128(_) => ValueKind::Prim(PType::U128),
Value::I32(_) => ValueKind::Prim(PType::I32),
Value::I64(_) => ValueKind::Prim(PType::I64),
Value::F32(_) => ValueKind::Prim(PType::F32),
Value::F64(_) => ValueKind::Prim(PType::F64),
Value::Utf8(_) => ValueKind::Prim(PType::Utf8),
Value::Bytes(_) => ValueKind::Prim(PType::Bytes),
Value::Array(_) => ValueKind::Array,
Value::Map(_) => ValueKind::Map,
}
}
enum BuiltDictLookup {
Flat {
lookup: HashMap<Value, u32>,
},
Struct {
lookup: HashMap<BTreeMap<String, Value>, u32>,
},
List {
lookup: HashMap<Vec<Value>, u32>,
},
}
enum BuiltDictData {
Flat {
values: FlatDictValues,
block_size: u32,
sorted_front_coded: bool,
},
Struct {
columns: Vec<ColumnData>,
row_ranges: Vec<ColumnRowRanges>,
row_count: usize,
},
List {
lists: Vec<Vec<u32>>,
id_width: IdWidth,
},
}
struct DictRegistry {
schemas: Vec<DictSchema>,
data: Vec<BuiltDictData>,
lookups: Vec<BuiltDictLookup>,
cfg: ColumnarBuildConfig,
}
impl DictRegistry {
fn new(cfg: ColumnarBuildConfig) -> Self {
Self {
schemas: Vec::new(),
data: Vec::new(),
lookups: Vec::new(),
cfg,
}
}
fn register_flat_dict(
&mut self,
name: String,
ptype: PType,
unique_values: Vec<Value>,
) -> (u16, IdWidth) {
let count = unique_values.len();
let id_width = IdWidth::for_dict_len(count);
let mut sorted = unique_values;
sorted.sort();
let mut lookup = HashMap::with_capacity(count);
for (idx, v) in sorted.iter().enumerate() {
lookup.insert(v.clone(), (idx + 1) as u32);
}
let block_size = if count <= 8192 {
0
} else {
self.cfg.dict_block_size
};
let sorted_front_coded = block_size > 0 && matches!(ptype, PType::Utf8 | PType::Bytes);
let flat_vals = match ptype {
PType::Bool => FlatDictValues::Bool(
sorted
.into_iter()
.map(|v| match v {
Value::Bool(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::U8 => FlatDictValues::U8(
sorted
.into_iter()
.map(|v| match v {
Value::U8(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::U16 => FlatDictValues::U16(
sorted
.into_iter()
.map(|v| match v {
Value::U16(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::U32 => FlatDictValues::U32(
sorted
.into_iter()
.map(|v| match v {
Value::U32(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::U64 => FlatDictValues::U64(
sorted
.into_iter()
.map(|v| match v {
Value::U64(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::U128 => FlatDictValues::U128(
sorted
.into_iter()
.map(|v| match v {
Value::U128(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::I32 => FlatDictValues::I32(
sorted
.into_iter()
.map(|v| match v {
Value::I32(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::I64 => FlatDictValues::I64(
sorted
.into_iter()
.map(|v| match v {
Value::I64(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::F32 => FlatDictValues::F32(
sorted
.into_iter()
.map(|v| match v {
Value::F32(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::F64 => FlatDictValues::F64(
sorted
.into_iter()
.map(|v| match v {
Value::F64(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::Utf8 => FlatDictValues::Utf8(
sorted
.into_iter()
.map(|v| match v {
Value::Utf8(x) => x,
_ => unreachable!(),
})
.collect(),
),
PType::Bytes => FlatDictValues::Bytes(
sorted
.into_iter()
.map(|v| match v {
Value::Bytes(x) => x,
_ => unreachable!(),
})
.collect(),
),
};
let dict_id = self.schemas.len() as u16;
self.schemas.push(DictSchema {
name,
kind: DictKind::Flat {
ptype,
sorted_front_coded,
block_size,
},
});
self.data.push(BuiltDictData::Flat {
values: flat_vals,
block_size,
sorted_front_coded,
});
self.lookups.push(BuiltDictLookup::Flat { lookup });
(dict_id, id_width)
}
fn register_struct_dict(
&mut self,
name: String,
mut unique_maps: Vec<BTreeMap<String, Value>>,
) -> (u16, IdWidth) {
unique_maps.sort();
let row_count = unique_maps.len();
let id_width = IdWidth::for_dict_len(row_count);
let mut lookup = HashMap::with_capacity(row_count);
for (idx, m) in unique_maps.iter().enumerate() {
lookup.insert(m.clone(), (idx + 1) as u32);
}
let refs: Vec<Option<&BTreeMap<String, Value>>> = unique_maps.iter().map(Some).collect();
let mut next_col = 0u16;
let root = infer_struct_schema(&name, &refs, false, false, &mut next_col, self);
let table_schema = TableSchema {
column_count: next_col,
root,
};
let (columns, row_ranges) = materialize_table(
&table_schema,
&unique_maps,
self,
self.cfg.struct_dict_row_group_size,
);
let dict_id = self.schemas.len() as u16;
self.schemas.push(DictSchema {
name,
kind: DictKind::Struct {
table: table_schema,
},
});
self.data.push(BuiltDictData::Struct {
columns,
row_ranges,
row_count,
});
self.lookups.push(BuiltDictLookup::Struct { lookup });
(dict_id, id_width)
}
fn register_list_dict(
&mut self,
name: String,
mut unique_lists: Vec<Vec<Value>>,
elem_dict_id: u16,
elem_id_width: IdWidth,
) -> (u16, IdWidth) {
let mut id_lists_with_orig: Vec<(Vec<u32>, Vec<Value>)> =
Vec::with_capacity(unique_lists.len());
for list in unique_lists.drain(..) {
let mut ids = Vec::with_capacity(list.len());
for item in &list {
let id = match &self.lookups[elem_dict_id as usize] {
BuiltDictLookup::Flat { lookup } => *lookup.get(item).unwrap_or(&0),
BuiltDictLookup::Struct { lookup } => match item {
Value::Map(m) => *lookup.get(m).unwrap_or(&0),
_ => 0,
},
BuiltDictLookup::List { lookup } => match item {
Value::Array(a) => *lookup.get(a).unwrap_or(&0),
_ => 0,
},
};
ids.push(id);
}
id_lists_with_orig.push((ids, list));
}
id_lists_with_orig.sort_by(|a, b| a.0.cmp(&b.0));
let count = id_lists_with_orig.len();
let id_width = IdWidth::for_dict_len(count);
let mut lookup = HashMap::with_capacity(count);
let mut lists = Vec::with_capacity(count);
for (idx, (ids, orig)) in id_lists_with_orig.into_iter().enumerate() {
lookup.insert(orig, (idx + 1) as u32);
lists.push(ids);
}
let dict_id = self.schemas.len() as u16;
self.schemas.push(DictSchema {
name,
kind: DictKind::List {
elem_dict_id,
id_width: elem_id_width,
},
});
self.data.push(BuiltDictData::List {
lists,
id_width: elem_id_width,
});
self.lookups.push(BuiltDictLookup::List { lookup });
(dict_id, id_width)
}
fn encode_all_dicts(&self) -> Result<Vec<Vec<u8>>> {
let mut blobs = Vec::with_capacity(self.data.len());
for d in &self.data {
let blob = match d {
BuiltDictData::Flat {
values,
block_size,
sorted_front_coded,
} => encode_flat_dict(
values,
*block_size,
*sorted_front_coded,
self.cfg.codec,
self.cfg.zstd_level,
)?,
BuiltDictData::Struct {
columns,
row_ranges,
row_count,
} => encode_column_table(
columns,
row_ranges,
*row_count,
self.cfg.struct_dict_row_group_size,
self.cfg.codec,
self.cfg.zstd_level,
)?,
BuiltDictData::List { lists, id_width } => {
encode_list_dict(lists, *id_width, self.cfg.codec, self.cfg.zstd_level)?
}
};
blobs.push(blob);
}
Ok(blobs)
}
}
pub fn infer_and_encode_records(
records: &[BTreeMap<String, Value>],
ip_first_pos: &[u64],
cfg: &ColumnarBuildConfig,
) -> Result<BuiltColumnarData> {
let n = records.len();
let mut registry = DictRegistry::new(cfg.clone());
let refs: Vec<Option<&BTreeMap<String, Value>>> = records.iter().map(Some).collect();
let mut next_col = 0u16;
let root_struct = infer_struct_schema("root", &refs, false, true, &mut next_col, &mut registry);
let root_table = TableSchema {
column_count: next_col,
root: root_struct,
};
let (mut columns, mut row_ranges) =
materialize_table(&root_table, records, ®istry, cfg.row_group_size);
let has_custom_ranges = row_ranges
.iter()
.any(|r| matches!(r, ColumnRowRanges::Custom(_)));
let old_to_new_rid: Vec<u32> = if n <= 1 {
let mut map = vec![0u32; n + 1];
if n == 1 {
map[1] = 1;
}
map
} else {
let perm = compute_row_permutation(
&root_table.root,
®istry.schemas,
&columns,
&row_ranges,
ip_first_pos,
n,
cfg.row_order,
);
let mut old_to_new = vec![0u32; n + 1];
for (new_idx, &old_idx) in perm.iter().enumerate() {
old_to_new[old_idx + 1] = (new_idx + 1) as u32;
}
if has_custom_ranges {
let sorted_records: Vec<BTreeMap<String, Value>> =
perm.iter().map(|&i| records[i].clone()).collect();
let (c2, r2) =
materialize_table(&root_table, &sorted_records, ®istry, cfg.row_group_size);
columns = c2;
row_ranges = r2;
} else {
for col in &mut columns {
permute_column_in_place(col, &perm);
}
}
old_to_new
};
let record_columns_blob = encode_column_table(
&columns,
&row_ranges,
n,
cfg.row_group_size,
cfg.codec,
cfg.zstd_level,
)?;
let dict_blobs = registry.encode_all_dicts()?;
let schema = Schema {
dicts: registry.schemas,
root: root_table,
};
Ok(BuiltColumnarData {
schema,
record_columns_blob,
dict_blobs,
old_to_new_rid,
})
}
type StructSignature = Vec<(String, BTreeSet<ValueKind>)>;
fn infer_struct_schema(
scope_name: &str,
rows: &[Option<&BTreeMap<String, Value>>],
nullable: bool,
allow_struct_dict_promotion: bool,
next_col: &mut u16,
registry: &mut DictRegistry,
) -> StructSchema {
let mut has_empty_map = false;
let mut field_names: BTreeSet<String> = BTreeSet::new();
for map in rows.iter().flatten() {
if map.is_empty() {
has_empty_map = true;
}
for k in map.keys() {
field_names.insert(k.clone());
}
}
let presence_col = if nullable && has_empty_map {
let c = *next_col;
*next_col += 1;
Some(c)
} else {
None
};
let field_list: Vec<String> = field_names.into_iter().collect();
let mut preassigned_dict_refs: HashMap<String, (u16, IdWidth, bool)> = HashMap::new();
if allow_struct_dict_promotion {
struct CandInfo<'a> {
field_name: String,
nullable: bool,
sig: StructSignature,
maps: Vec<&'a BTreeMap<String, Value>>,
}
let mut cands: Vec<CandInfo<'_>> = Vec::new();
for fname in &field_list {
let mut non_null = 0usize;
let mut all_maps = true;
let mut has_empty = false;
let mut key_kinds: BTreeMap<String, BTreeSet<ValueKind>> = BTreeMap::new();
let mut maps = Vec::new();
for m in rows.iter().flatten() {
if let Some(val) = m.get(fname) {
non_null += 1;
if let Value::Map(sub) = val {
if sub.is_empty() {
has_empty = true;
}
maps.push(sub);
for (sk, sv) in sub {
key_kinds
.entry(sk.clone())
.or_default()
.insert(value_kind(sv));
}
} else {
all_maps = false;
break;
}
}
}
if !all_maps || non_null < 16 || key_kinds.is_empty() || key_kinds.len() > 64 {
continue;
}
let is_uniform_shredded = key_kinds.len() >= 4
&& key_kinds.values().all(|ks| {
ks.len() == 1 && matches!(ks.iter().next(), Some(ValueKind::Prim(_)))
})
&& {
let first_k = key_kinds.values().next().unwrap();
key_kinds.values().all(|ks| ks == first_k)
};
if is_uniform_shredded {
continue;
}
let has_nested_map = key_kinds.values().any(|ks| ks.contains(&ValueKind::Map));
if key_kinds.len() == 1 && !has_nested_map {
continue;
}
let mut uniq: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
for &sub in &maps {
uniq.insert(sub, ());
}
let u = uniq.len();
if u == 0 || has_empty {
continue;
}
let low_card_win = u <= 4096 && non_null >= u * 2;
let heavy_entity_win = has_nested_map && u * 2 <= non_null;
if low_card_win || heavy_entity_win {
let sig: StructSignature = key_kinds.into_iter().collect();
cands.push(CandInfo {
field_name: fname.clone(),
nullable: non_null < rows.len(),
sig,
maps,
});
}
}
let mut by_sig: BTreeMap<StructSignature, Vec<CandInfo<'_>>> = BTreeMap::new();
for c in cands {
by_sig.entry(c.sig.clone()).or_default().push(c);
}
for (_sig, group) in by_sig {
let dict_name = if group.len() == 1 {
group[0].field_name.clone()
} else {
group
.iter()
.map(|g| g.field_name.as_str())
.collect::<Vec<_>>()
.join("_")
};
let mut uniq_set: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
for g in &group {
for &m in &g.maps {
uniq_set.insert(m, ());
}
}
let unique_maps: Vec<BTreeMap<String, Value>> = uniq_set.into_keys().cloned().collect();
let (dict_id, id_width) = registry.register_struct_dict(dict_name, unique_maps);
for g in group {
preassigned_dict_refs.insert(g.field_name, (dict_id, id_width, g.nullable));
}
}
}
let mut grouped_fields: BTreeSet<String> = BTreeSet::new();
let mut dict_groups: Vec<DictGroup> = Vec::new();
if allow_struct_dict_promotion {
let mut float_fields: Vec<String> = Vec::new();
for fname in &field_list {
if preassigned_dict_refs.contains_key(fname) {
continue;
}
let mut kinds = BTreeSet::new();
for m in rows.iter().flatten() {
if let Some(v) = m.get(fname) {
kinds.insert(value_kind(v));
}
}
if kinds.len() == 1
&& matches!(
kinds.iter().next(),
Some(ValueKind::Prim(PType::F64 | PType::F32))
)
{
float_fields.push(fname.clone());
}
}
if float_fields.len() >= 2 {
let mut non_empty_rows = 0usize;
let mut uniq_tuples: HashMap<BTreeMap<String, Value>, ()> = HashMap::new();
for m in rows.iter().flatten() {
let mut sub = BTreeMap::new();
for ff in &float_fields {
if let Some(v) = m.get(ff) {
sub.insert(ff.clone(), v.clone());
}
}
if !sub.is_empty() {
non_empty_rows += 1;
uniq_tuples.insert(sub, ());
}
}
let u = uniq_tuples.len();
if u > 0 && non_empty_rows >= 16 && u * 2 <= non_empty_rows {
let unique_maps: Vec<BTreeMap<String, Value>> = uniq_tuples.into_keys().collect();
let group_name = format!("{scope_name}_{}", float_fields.join("_"));
let (dict_id, id_width) = registry.register_struct_dict(group_name, unique_maps);
let col_id = *next_col;
*next_col += 1;
for ff in &float_fields {
grouped_fields.insert(ff.clone());
}
dict_groups.push(DictGroup {
dict_id,
id_width,
col_id,
field_names: float_fields,
});
}
}
}
let mut fields = Vec::with_capacity(field_list.len());
for fname in field_list {
if grouped_fields.contains(&fname) {
continue;
}
if let Some((dict_id, id_width, field_nullable)) = preassigned_dict_refs.get(&fname) {
let col_id = *next_col;
*next_col += 1;
fields.push(StructField {
name: fname,
col_type: ColumnType::DictRef {
dict_id: *dict_id,
id_width: *id_width,
nullable: *field_nullable,
col_id,
},
});
continue;
}
let vals: Vec<Option<&Value>> =
rows.iter().map(|r| r.and_then(|m| m.get(&fname))).collect();
let child_scope = format!("{scope_name}_{fname}");
let col_type = infer_column_type(
&child_scope,
&vals,
allow_struct_dict_promotion,
next_col,
registry,
);
fields.push(StructField {
name: fname,
col_type,
});
}
StructSchema {
nullable,
presence_col,
fields,
dict_groups,
}
}
fn infer_column_type(
field_path: &str,
vals: &[Option<&Value>],
allow_dicts: bool,
next_col: &mut u16,
registry: &mut DictRegistry,
) -> ColumnType {
let mut kinds: BTreeSet<ValueKind> = BTreeSet::new();
let mut non_null = 0usize;
for val in vals.iter().flatten() {
non_null += 1;
kinds.insert(value_kind(val));
}
let nullable = non_null < vals.len();
if kinds.is_empty() || kinds.len() > 1 || kinds.contains(&ValueKind::Null) {
let col_id = *next_col;
*next_col += 1;
return ColumnType::Dynamic { nullable, col_id };
}
match *kinds.iter().next().unwrap() {
ValueKind::Prim(ptype) => {
if allow_dicts && matches!(ptype, PType::Utf8 | PType::Bytes) && non_null >= 16 {
let mut uniq: HashMap<&Value, ()> = HashMap::new();
for v in vals.iter().flatten() {
uniq.insert(*v, ());
}
let u = uniq.len();
let promote =
(u <= 65_535 && non_null >= u * 2) || (u > 65_535 && non_null >= u * 3);
if promote && u > 0 {
let unique_vals: Vec<Value> = uniq.into_keys().cloned().collect();
let (dict_id, id_width) =
registry.register_flat_dict(field_path.to_string(), ptype, unique_vals);
let col_id = *next_col;
*next_col += 1;
return ColumnType::DictRef {
dict_id,
id_width,
nullable,
col_id,
};
}
}
let col_id = *next_col;
*next_col += 1;
ColumnType::Primitive {
ptype,
nullable,
col_id,
}
}
ValueKind::Map => {
let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
.iter()
.map(|o| match o {
Some(Value::Map(m)) => Some(m),
_ => None,
})
.collect();
let mut key_counts: BTreeMap<String, usize> = BTreeMap::new();
let mut val_kinds: BTreeSet<ValueKind> = BTreeSet::new();
let mut has_empty = false;
for m in map_rows.iter().flatten() {
if m.is_empty() {
has_empty = true;
}
for (k, v) in *m {
*key_counts.entry(k.clone()).or_insert(0) += 1;
val_kinds.insert(value_kind(v));
}
}
let is_uniform_prim_map = key_counts.len() >= 4
&& val_kinds.len() == 1
&& matches!(val_kinds.iter().next(), Some(ValueKind::Prim(_)));
if is_uniform_prim_map {
let ptype = match *val_kinds.iter().next().unwrap() {
ValueKind::Prim(p) => p,
_ => unreachable!(),
};
let mut shredded_keys: Vec<String> = if key_counts.len() <= 32 {
key_counts.keys().cloned().collect()
} else {
let threshold = (non_null / 100).max(1);
let mut freq: Vec<(String, usize)> = key_counts
.iter()
.filter(|&(_, &c)| c >= threshold)
.map(|(k, &c)| (k.clone(), c))
.collect();
freq.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
freq.truncate(64);
let mut ks: Vec<String> = freq.into_iter().map(|(k, _)| k).collect();
ks.sort();
ks
};
shredded_keys.sort();
let has_overflow = shredded_keys.len() < key_counts.len();
let presence_col = if nullable && has_empty {
let c = *next_col;
*next_col += 1;
Some(c)
} else {
None
};
let overflow_col = if has_overflow {
let c = *next_col;
*next_col += 1;
Some(c)
} else {
None
};
let mut entries = Vec::with_capacity(shredded_keys.len());
for k in shredded_keys {
let key_nullable = key_counts[&k] < vals.len();
let col_id = *next_col;
*next_col += 1;
entries.push(ShreddedMapEntry {
key: k,
value_type: ColumnType::Primitive {
ptype,
nullable: key_nullable,
col_id,
},
});
}
ColumnType::ShreddedMap {
nullable,
presence_col,
overflow_col,
entries,
}
} else if key_counts.len() > 128 {
let col_id = *next_col;
*next_col += 1;
ColumnType::Dynamic { nullable, col_id }
} else {
let s = infer_struct_schema(
field_path,
&map_rows,
nullable,
allow_dicts,
next_col,
registry,
);
ColumnType::Struct(s)
}
}
ValueKind::Array => {
let mut elem_kinds: BTreeSet<ValueKind> = BTreeSet::new();
let mut all_elems: Vec<&Value> = Vec::new();
let mut uniq_lists: HashMap<&Vec<Value>, ()> = HashMap::new();
for v in vals.iter().flatten() {
if let Value::Array(arr) = v {
uniq_lists.insert(arr, ());
for item in arr {
elem_kinds.insert(value_kind(item));
all_elems.push(item);
}
}
}
let u_lists = uniq_lists.len();
if allow_dicts
&& elem_kinds.len() == 1
&& non_null >= 8
&& u_lists > 0
&& u_lists * 2 <= non_null
&& (u_lists <= 65_535 || u_lists * 3 <= non_null)
{
match *elem_kinds.iter().next().unwrap() {
ValueKind::Map => {
let mut uniq_elems: HashMap<&BTreeMap<String, Value>, ()> = HashMap::new();
for item in &all_elems {
if let Value::Map(m) = item {
uniq_elems.insert(m, ());
}
}
if !uniq_elems.is_empty() {
let elem_maps: Vec<BTreeMap<String, Value>> =
uniq_elems.into_keys().cloned().collect();
let (elem_dict_id, elem_id_width) = registry
.register_struct_dict(format!("{field_path}_elem"), elem_maps);
let list_vec: Vec<Vec<Value>> =
uniq_lists.into_keys().cloned().collect();
let (list_dict_id, list_id_width) = registry.register_list_dict(
format!("{field_path}_list"),
list_vec,
elem_dict_id,
elem_id_width,
);
let col_id = *next_col;
*next_col += 1;
return ColumnType::DictRef {
dict_id: list_dict_id,
id_width: list_id_width,
nullable,
col_id,
};
}
}
ValueKind::Prim(ptype) => {
let mut uniq_elems: HashMap<&Value, ()> = HashMap::new();
for &item in &all_elems {
uniq_elems.insert(item, ());
}
if !uniq_elems.is_empty() {
let elem_vals: Vec<Value> = uniq_elems.into_keys().cloned().collect();
let (elem_dict_id, elem_id_width) = registry.register_flat_dict(
format!("{field_path}_elem"),
ptype,
elem_vals,
);
let list_vec: Vec<Vec<Value>> =
uniq_lists.into_keys().cloned().collect();
let (list_dict_id, list_id_width) = registry.register_list_dict(
format!("{field_path}_list"),
list_vec,
elem_dict_id,
elem_id_width,
);
let col_id = *next_col;
*next_col += 1;
return ColumnType::DictRef {
dict_id: list_dict_id,
id_width: list_id_width,
nullable,
col_id,
};
}
}
_ => {}
}
}
if elem_kinds.len() == 1 && !elem_kinds.contains(&ValueKind::Null) {
let offsets_col = *next_col;
*next_col += 1;
let elem_opts: Vec<Option<&Value>> = all_elems.into_iter().map(Some).collect();
let elem_type = infer_column_type(
&format!("{field_path}_item"),
&elem_opts,
false,
next_col,
registry,
);
ColumnType::List {
nullable,
offsets_col,
elem_type: Box::new(elem_type),
}
} else {
let col_id = *next_col;
*next_col += 1;
ColumnType::Dynamic { nullable, col_id }
}
}
ValueKind::Null => unreachable!(),
}
}
fn materialize_table(
table: &TableSchema,
records: &[BTreeMap<String, Value>],
registry: &DictRegistry,
row_group_size: u32,
) -> (Vec<ColumnData>, Vec<ColumnRowRanges>) {
let kinds = table
.physical_column_kinds(registry.schemas.len())
.expect("inferred schema must be valid");
let n = records.len();
let mut columns: Vec<ColumnData> = kinds
.iter()
.map(|k| match k {
coip_format::PhysicalColKind::Primitive(p) => ColumnData::empty_for_ptype(*p, n),
coip_format::PhysicalColKind::Dynamic => ColumnData::Dynamic(Vec::with_capacity(n)),
})
.collect();
let mut row_ranges: Vec<ColumnRowRanges> = vec![ColumnRowRanges::Uniform; kinds.len()];
let rg_size = row_group_size.max(1) as usize;
let rg_count = if n == 0 { 0 } else { n.div_ceil(rg_size) };
let root_rg_bounds: Vec<(usize, usize)> = (0..rg_count)
.map(|rg| {
let s = rg * rg_size;
(s, (s + rg_size).min(n))
})
.collect();
let row_refs: Vec<Option<&BTreeMap<String, Value>>> = records.iter().map(Some).collect();
fill_struct_columns(
&table.root,
&row_refs,
&root_rg_bounds,
false,
registry,
&mut columns,
&mut row_ranges,
);
(columns, row_ranges)
}
fn fill_struct_columns(
schema: &StructSchema,
rows: &[Option<&BTreeMap<String, Value>>],
rg_bounds: &[(usize, usize)],
is_custom_rg: bool,
registry: &DictRegistry,
columns: &mut [ColumnData],
row_ranges: &mut [ColumnRowRanges],
) {
if let Some(c) = schema.presence_col {
if is_custom_rg {
row_ranges[c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
if let ColumnData::Bool(vec) = &mut columns[c as usize] {
for r in rows {
vec.push(Some(r.is_some()));
}
}
}
for g in &schema.dict_groups {
if is_custom_rg {
row_ranges[g.col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
let lookup = match ®istry.lookups[g.dict_id as usize] {
BuiltDictLookup::Struct { lookup } => lookup,
_ => panic!("DictGroup must reference StructDict"),
};
for r in rows {
let id = match r {
None => 0u32,
Some(m) => {
let mut sub = BTreeMap::new();
for ff in &g.field_names {
if let Some(v) = m.get(ff) {
sub.insert(ff.clone(), v.clone());
}
}
if sub.is_empty() {
0
} else {
*lookup.get(&sub).expect("DictGroup entry must exist")
}
}
};
push_dict_id(&mut columns[g.col_id as usize], id);
}
}
for f in &schema.fields {
let vals: Vec<Option<&Value>> = rows
.iter()
.map(|r| r.and_then(|m| m.get(&f.name)))
.collect();
fill_col_type(
&f.col_type,
&vals,
rg_bounds,
is_custom_rg,
registry,
columns,
row_ranges,
);
}
}
fn fill_col_type(
ct: &ColumnType,
vals: &[Option<&Value>],
rg_bounds: &[(usize, usize)],
is_custom_rg: bool,
registry: &DictRegistry,
columns: &mut [ColumnData],
row_ranges: &mut [ColumnRowRanges],
) {
match ct {
ColumnType::Primitive { ptype, col_id, .. } => {
if is_custom_rg {
row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
push_prim_values(&mut columns[*col_id as usize], *ptype, vals);
}
ColumnType::DictRef {
dict_id, col_id, ..
} => {
if is_custom_rg {
row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
let lookup = ®istry.lookups[*dict_id as usize];
for v in vals {
let id = match v {
None => 0u32,
Some(val) => match lookup {
BuiltDictLookup::Flat { lookup } => {
*lookup.get(val).expect("FlatDict entry must exist")
}
BuiltDictLookup::Struct { lookup } => match val {
Value::Map(m) => *lookup.get(m).expect("StructDict entry must exist"),
_ => panic!("expected Map for StructDict"),
},
BuiltDictLookup::List { lookup } => match val {
Value::Array(a) => *lookup.get(a).expect("ListDict entry must exist"),
_ => panic!("expected Array for ListDict"),
},
},
};
push_dict_id(&mut columns[*col_id as usize], id);
}
}
ColumnType::Struct(s) => {
let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
.iter()
.map(|o| match o {
Some(Value::Map(m)) => Some(m),
_ => None,
})
.collect();
fill_struct_columns(
s,
&map_rows,
rg_bounds,
is_custom_rg,
registry,
columns,
row_ranges,
);
}
ColumnType::ShreddedMap {
presence_col,
overflow_col,
entries,
..
} => {
let map_rows: Vec<Option<&BTreeMap<String, Value>>> = vals
.iter()
.map(|o| match o {
Some(Value::Map(m)) => Some(m),
_ => None,
})
.collect();
if let Some(c) = presence_col {
if is_custom_rg {
row_ranges[*c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
if let ColumnData::Bool(vec) = &mut columns[*c as usize] {
for m in &map_rows {
vec.push(Some(m.is_some()));
}
}
}
let known_keys: BTreeSet<&str> = entries.iter().map(|e| e.key.as_str()).collect();
for e in entries {
let key_vals: Vec<Option<&Value>> = map_rows
.iter()
.map(|m| m.and_then(|map| map.get(&e.key)))
.collect();
fill_col_type(
&e.value_type,
&key_vals,
rg_bounds,
is_custom_rg,
registry,
columns,
row_ranges,
);
}
if let Some(c) = overflow_col {
if is_custom_rg {
row_ranges[*c as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
if let ColumnData::Dynamic(vec) = &mut columns[*c as usize] {
for m in &map_rows {
match m {
None => vec.push(None),
Some(map) => {
let mut extra = BTreeMap::new();
for (k, v) in *map {
if !known_keys.contains(k.as_str()) {
extra.insert(k.clone(), v.clone());
}
}
if extra.is_empty() {
vec.push(None);
} else {
let mut buf = Vec::new();
Value::Map(extra).encode(&mut buf);
vec.push(Some(buf));
}
}
}
}
}
}
}
ColumnType::List {
offsets_col,
elem_type,
..
} => {
if is_custom_rg {
row_ranges[*offsets_col as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
let mut flat_elems: Vec<Option<&Value>> = Vec::new();
let mut child_rg_bounds: Vec<(usize, usize)> = Vec::with_capacity(rg_bounds.len());
for &(rg_s, rg_e) in rg_bounds {
let child_start = flat_elems.len();
for v in &vals[rg_s..rg_e] {
match v {
None => {
if let ColumnData::U32(vec) = &mut columns[*offsets_col as usize] {
vec.push(None);
}
}
Some(Value::Array(arr)) => {
if let ColumnData::U32(vec) = &mut columns[*offsets_col as usize] {
vec.push(Some(arr.len() as u32));
}
for item in arr {
flat_elems.push(Some(item));
}
}
_ => panic!("expected Array for List column"),
}
}
child_rg_bounds.push((child_start, flat_elems.len()));
}
fill_col_type(
elem_type,
&flat_elems,
&child_rg_bounds,
true,
registry,
columns,
row_ranges,
);
}
ColumnType::Dynamic { col_id, .. } => {
if is_custom_rg {
row_ranges[*col_id as usize] = ColumnRowRanges::Custom(rg_bounds.to_vec());
}
if let ColumnData::Dynamic(vec) = &mut columns[*col_id as usize] {
for v in vals {
match v {
None => vec.push(None),
Some(val) => {
let mut buf = Vec::new();
val.encode(&mut buf);
vec.push(Some(buf));
}
}
}
}
}
}
}
#[inline]
fn push_dict_id(col: &mut ColumnData, id: u32) {
match col {
ColumnData::U8(v) => v.push(Some(id as u8)),
ColumnData::U16(v) => v.push(Some(id as u16)),
ColumnData::U32(v) => v.push(Some(id)),
_ => panic!("DictRef column must be U8/U16/U32"),
}
}
fn push_prim_values(col: &mut ColumnData, ptype: PType, vals: &[Option<&Value>]) {
match (col, ptype) {
(ColumnData::Bool(vec), PType::Bool) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::Bool(b) => *b,
_ => panic!("expected Bool"),
}));
}
}
(ColumnData::U8(vec), PType::U8) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::U8(n) => *n,
_ => panic!("expected U8"),
}));
}
}
(ColumnData::U16(vec), PType::U16) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::U16(n) => *n,
_ => panic!("expected U16"),
}));
}
}
(ColumnData::U32(vec), PType::U32) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::U32(n) => *n,
_ => panic!("expected U32"),
}));
}
}
(ColumnData::U64(vec), PType::U64) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::U64(n) => *n,
_ => panic!("expected U64"),
}));
}
}
(ColumnData::U128(vec), PType::U128) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::U128(n) => *n,
_ => panic!("expected U128"),
}));
}
}
(ColumnData::I32(vec), PType::I32) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::I32(n) => *n,
_ => panic!("expected I32"),
}));
}
}
(ColumnData::I64(vec), PType::I64) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::I64(n) => *n,
_ => panic!("expected I64"),
}));
}
}
(ColumnData::F32(vec), PType::F32) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::F32(n) => *n,
_ => panic!("expected F32"),
}));
}
}
(ColumnData::F64(vec), PType::F64) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::F64(n) => *n,
_ => panic!("expected F64"),
}));
}
}
(ColumnData::Utf8(vec), PType::Utf8) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::Utf8(s) => s.clone(),
_ => panic!("expected Utf8"),
}));
}
}
(ColumnData::Bytes(vec), PType::Bytes) => {
for v in vals {
vec.push(v.map(|x| match x {
Value::Bytes(b) => b.clone(),
_ => panic!("expected Bytes"),
}));
}
}
_ => panic!("mismatched ColumnData vs PType"),
}
}
fn collect_dict_cols(s: &StructSchema, out: &mut Vec<(usize, u16)>) {
for g in &s.dict_groups {
out.push((g.col_id as usize, g.dict_id));
}
for f in &s.fields {
match &f.col_type {
ColumnType::DictRef {
col_id, dict_id, ..
} => {
out.push((*col_id as usize, *dict_id));
}
ColumnType::Struct(sub) => collect_dict_cols(sub, out),
_ => {}
}
}
}
fn compute_row_permutation(
root: &StructSchema,
dict_schemas: &[DictSchema],
columns: &[ColumnData],
row_ranges: &[ColumnRowRanges],
ip_first_pos: &[u64],
n: usize,
strategy: RowOrderStrategy,
) -> Vec<usize> {
if strategy == RowOrderStrategy::IpLocality && ip_first_pos.len() == n {
let mut perm: Vec<usize> = (0..n).collect();
perm.sort_unstable_by(|&a, &b| {
ip_first_pos[a]
.cmp(&ip_first_pos[b])
.then_with(|| a.cmp(&b))
});
return perm;
}
let mut raw_dict_cols = Vec::new();
collect_dict_cols(root, &mut raw_dict_cols);
let mut col_is_large_flat: HashMap<usize, bool> = HashMap::new();
for (col_id, dict_id) in raw_dict_cols {
let is_large_flat = matches!(
dict_schemas[dict_id as usize].kind,
DictKind::Flat { block_size, .. } if block_size > 0
);
col_is_large_flat.insert(col_id, is_large_flat);
}
let mut tier0: Vec<(usize, usize)> = Vec::new();
let mut tier1: Vec<(usize, usize)> = Vec::new();
let mut tier2: Vec<(usize, usize)> = Vec::new();
for (idx, (col, rr)) in columns.iter().zip(row_ranges.iter()).enumerate() {
if !matches!(rr, ColumnRowRanges::Uniform) || col.len() != n {
continue;
}
let card = column_cardinality(col);
if card <= 1 {
continue;
}
let non_zero = column_non_zero_count(col);
match col_is_large_flat.get(&idx) {
Some(&false) if non_zero * 2 >= n => tier0.push((card, idx)),
Some(&true) if non_zero * 2 >= n => tier1.push((card, idx)),
_ => tier2.push((card, idx)),
}
}
tier0.sort_unstable();
tier1.sort_unstable();
tier2.sort_unstable();
if strategy == RowOrderStrategy::HybridGeoIp && ip_first_pos.len() == n {
let coarse: Vec<usize> = tier0
.iter()
.filter(|&&(card, _)| card <= 512)
.take(2)
.map(|&(_, idx)| idx)
.collect();
let mut perm: Vec<usize> = (0..n).collect();
perm.sort_unstable_by(|&a, &b| {
for &c in &coarse {
let ord = cmp_column_rows(&columns[c], a, b);
if ord != std::cmp::Ordering::Equal {
return ord;
}
}
ip_first_pos[a]
.cmp(&ip_first_pos[b])
.then_with(|| a.cmp(&b))
});
return perm;
}
let mut sort_cols: Vec<usize> = tier0.into_iter().map(|(_, idx)| idx).collect();
sort_cols.extend(tier1.into_iter().map(|(_, idx)| idx));
sort_cols.extend(tier2.into_iter().map(|(_, idx)| idx));
let mut perm: Vec<usize> = (0..n).collect();
perm.sort_unstable_by(|&a, &b| {
for &c in &sort_cols {
let ord = cmp_column_rows(&columns[c], a, b);
if ord != std::cmp::Ordering::Equal {
return ord;
}
}
a.cmp(&b)
});
perm
}
fn column_non_zero_count(col: &ColumnData) -> usize {
match col {
ColumnData::U8(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
ColumnData::U16(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
ColumnData::U32(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
ColumnData::U64(v) => v.iter().filter(|x| matches!(x, Some(n) if *n != 0)).count(),
ColumnData::Bool(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::U128(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::I32(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::I64(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::F32(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::F64(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::Utf8(v) => v.iter().filter(|x| x.is_some()).count(),
ColumnData::Bytes(v) | ColumnData::Dynamic(v) => v.iter().filter(|x| x.is_some()).count(),
}
}
fn column_cardinality(col: &ColumnData) -> usize {
match col {
ColumnData::Bool(v) => {
let mut s = BTreeSet::new();
for x in v {
s.insert(*x);
}
s.len()
}
ColumnData::U8(v) => {
let mut seen = [false; 257];
let mut c = 0;
for x in v {
let slot = match x {
None => 256,
Some(n) => *n as usize,
};
if !seen[slot] {
seen[slot] = true;
c += 1;
}
}
c
}
ColumnData::U16(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::U32(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::U64(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::U128(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::I32(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::I64(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(*x, ());
}
s.len()
}
ColumnData::F32(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(x.map(f32::to_bits), ());
}
s.len()
}
ColumnData::F64(v) => {
let mut s = HashMap::new();
for x in v {
s.insert(x.map(f64::to_bits), ());
}
s.len()
}
ColumnData::Utf8(v) => {
let mut s: HashMap<Option<&str>, ()> = HashMap::new();
for x in v {
s.insert(x.as_deref(), ());
}
s.len()
}
ColumnData::Bytes(v) | ColumnData::Dynamic(v) => {
let mut s: HashMap<Option<&[u8]>, ()> = HashMap::new();
for x in v {
s.insert(x.as_deref(), ());
}
s.len()
}
}
}
#[inline]
fn cmp_column_rows(col: &ColumnData, a: usize, b: usize) -> std::cmp::Ordering {
match col {
ColumnData::Bool(v) => v[a].cmp(&v[b]),
ColumnData::U8(v) => v[a].cmp(&v[b]),
ColumnData::U16(v) => v[a].cmp(&v[b]),
ColumnData::U32(v) => v[a].cmp(&v[b]),
ColumnData::U64(v) => v[a].cmp(&v[b]),
ColumnData::U128(v) => v[a].cmp(&v[b]),
ColumnData::I32(v) => v[a].cmp(&v[b]),
ColumnData::I64(v) => v[a].cmp(&v[b]),
ColumnData::F32(v) => v[a].map(f32::to_bits).cmp(&v[b].map(f32::to_bits)),
ColumnData::F64(v) => v[a].map(f64::to_bits).cmp(&v[b].map(f64::to_bits)),
ColumnData::Utf8(v) => v[a].cmp(&v[b]),
ColumnData::Bytes(v) | ColumnData::Dynamic(v) => v[a].cmp(&v[b]),
}
}
fn permute_vec<T: Clone>(v: &mut Vec<T>, perm: &[usize]) {
let reordered: Vec<T> = perm.iter().map(|&i| v[i].clone()).collect();
*v = reordered;
}
fn permute_column_in_place(col: &mut ColumnData, perm: &[usize]) {
match col {
ColumnData::Bool(v) => permute_vec(v, perm),
ColumnData::U8(v) => permute_vec(v, perm),
ColumnData::U16(v) => permute_vec(v, perm),
ColumnData::U32(v) => permute_vec(v, perm),
ColumnData::U64(v) => permute_vec(v, perm),
ColumnData::U128(v) => permute_vec(v, perm),
ColumnData::I32(v) => permute_vec(v, perm),
ColumnData::I64(v) => permute_vec(v, perm),
ColumnData::F32(v) => permute_vec(v, perm),
ColumnData::F64(v) => permute_vec(v, perm),
ColumnData::Utf8(v) => permute_vec(v, perm),
ColumnData::Bytes(v) | ColumnData::Dynamic(v) => permute_vec(v, perm),
}
}