Skip to main content

rypipe_core/
dict.rs

1use std::sync::Arc;
2
3use rustc_hash::FxHashMap;
4
5use crate::columnar::ColumnBuilder;
6
7/// Immutable seed dictionary built from a sample.
8///
9/// Shared `Arc` across threads, read-only after construction.
10#[derive(Debug, Clone)]
11pub struct SeedDict {
12    pub values: Vec<u8>,
13    pub offsets: Vec<i32>,
14    pub index: FxHashMap<Box<str>, i32>,
15}
16
17impl SeedDict {
18    pub fn new(values: Vec<String>) -> Self {
19        let mut data = Vec::new();
20        let mut offsets = Vec::with_capacity(values.len() + 1);
21        offsets.push(0);
22        let mut index = FxHashMap::default();
23        for (i, s) in values.into_iter().enumerate() {
24            index.insert(s.clone().into_boxed_str(), i as i32);
25            data.extend_from_slice(s.as_bytes());
26            offsets.push(data.len() as i32);
27        }
28        Self {
29            values: data,
30            offsets,
31            index,
32        }
33    }
34
35    pub fn len(&self) -> usize {
36        self.offsets.len().saturating_sub(1)
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.len() == 0
41    }
42}
43
44/// Column plan from sampling.
45#[derive(Debug, Clone)]
46pub struct ColumnPlan {
47    pub encode_as_dict: bool,
48    pub seed: Option<Arc<SeedDict>>,
49    pub est_cardinality: usize,
50}
51
52/// Remap table for one chunk's codes.
53#[derive(Debug, Clone)]
54pub struct RemapTable {
55    pub map: Vec<i32>,
56    pub is_identity: bool,
57}
58
59impl RemapTable {
60    pub fn identity(len: usize) -> Self {
61        Self {
62            map: (0..len as i32).collect(),
63            is_identity: true,
64        }
65    }
66}
67
68/// Unified dictionary values.
69#[derive(Debug, Clone)]
70pub struct DictValues {
71    pub data: Vec<u8>,
72    pub offsets: Vec<i32>,
73}
74
75/// Unify per-chunk dictionaries with the seed.
76///
77/// Works with `ColumnBuilder::Dictionary { codes, data, offsets, index }`.
78/// Seed codes are `0..seed.len()`, overflow are `seed.len()..`.
79pub(crate) fn unify_dictionaries(
80    seed: &SeedDict,
81    locals: &[&ColumnBuilder],
82) -> (DictValues, Vec<RemapTable>) {
83    let mut global_index: FxHashMap<Box<str>, i32> = FxHashMap::default();
84    let mut global_data = seed.values.clone();
85    let mut global_offsets = seed.offsets.clone();
86    let mut next_code = seed.len() as i32;
87
88    for (k, &v) in &seed.index {
89        global_index.insert(k.clone(), v);
90    }
91
92    // Collect overflow values not in seed
93    for col in locals {
94        if let ColumnBuilder::Dictionary { data, offsets, .. } = col {
95            for i in seed.len()..(offsets.len() - 1) {
96                let start = offsets[i] as usize;
97                let end = offsets[i + 1] as usize;
98                let val = std::str::from_utf8(&data[start..end]).unwrap_or("");
99                let k: Box<str> = val.into();
100                if !global_index.contains_key(&k) {
101                    global_index.insert(k.clone(), next_code);
102                    global_data.extend_from_slice(val.as_bytes());
103                    global_offsets.push(global_data.len() as i32);
104                    next_code += 1;
105                }
106            }
107        }
108    }
109
110    let dict_values = DictValues {
111        data: global_data,
112        offsets: global_offsets,
113    };
114
115    // Build remap tables: local code -> global code
116    let mut remaps = Vec::with_capacity(locals.len());
117    for col in locals {
118        if let ColumnBuilder::Dictionary { data, offsets, index, .. } = col {
119            let local_len = offsets.len() - 1;
120            let mut map = Vec::with_capacity(local_len);
121            let mut is_identity = true;
122            for i in 0..local_len {
123                let start = offsets[i] as usize;
124                let end = offsets[i + 1] as usize;
125                let val = std::str::from_utf8(&data[start..end]).unwrap_or("");
126                let k: Box<str> = val.into();
127                let g = *global_index.get(&k).unwrap();
128                let local = *index.get(k.as_ref()).unwrap();
129                if g != local {
130                    is_identity = false;
131                }
132                map.push(g);
133            }
134            // If no overflow, it's essentially identity if dict == seed
135            if local_len == seed.len() && is_identity {
136                // All seed, identity
137            } else if local_len > seed.len() {
138                is_identity = false;
139            }
140            remaps.push(RemapTable { map, is_identity });
141        } else {
142            remaps.push(RemapTable::identity(0));
143        }
144    }
145
146    (dict_values, remaps)
147}
148
149/// Apply remap to codes in place (parallel, L1-resident).
150#[inline]
151pub fn apply_remap(codes: &mut [Option<i32>], remap: &RemapTable) {
152    if remap.is_identity {
153        return;
154    }
155    for v in codes.iter_mut().flatten() {
156        debug_assert!((*v as usize) < remap.map.len(), "code out of bounds");
157        unsafe {
158            *v = *remap.map.get_unchecked(*v as usize);
159        }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use crate::columnar::ColumnBuilder;
167    use crate::plan::FieldType;
168
169    fn make_dict(values: Vec<&str>) -> ColumnBuilder {
170        let mut b = ColumnBuilder::with_capacity(10, &FieldType::Dictionary);
171        for v in values {
172            b.push_str(Some(v));
173        }
174        b
175    }
176
177    #[test]
178    fn test_unify_no_overflow() {
179        let seed = SeedDict::new(vec!["a".into(), "b".into()]);
180        let col1 = make_dict(vec!["a", "b", "a"]);
181        let col2 = make_dict(vec!["b", "a"]);
182        let (dict, remaps) = unify_dictionaries(&seed, &[&col1, &col2]);
183        assert_eq!(dict.offsets.len(), 3);
184        // Both remaps should be identity or at least map correctly
185        assert_eq!(remaps.len(), 2);
186    }
187
188    #[test]
189    fn test_apply_remap_identity() {
190        let mut codes = vec![Some(0), Some(1), Some(0), None];
191        let remap = RemapTable::identity(2);
192        apply_remap(&mut codes, &remap);
193        assert_eq!(codes, vec![Some(0), Some(1), Some(0), None]);
194    }
195}