Skip to main content

rypipe_core/
parallel.rs

1use std::panic::{catch_unwind, AssertUnwindSafe};
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::sync::Arc;
4use std::time::Instant;
5
6use arrow::record_batch::RecordBatch;
7use rayon::prelude::*;
8use rustc_hash::FxHashMap as HashMap;
9
10use crate::arrow_export::apply_compare_filter;
11use crate::decoder::{split_points_to_ranges, RecordParser, Splitter};
12use crate::engine::TableBuilder;
13use crate::merge::engines_to_record_batches;
14use crate::plan::ExecutionPlan;
15use crate::Result;
16
17// --- Chunk-time profiling ---
18// Reset before each parallel run; read via `chunk_profile()`.
19static CHUNK_TIME_SUM_NS: AtomicU64 = AtomicU64::new(0);
20static CHUNK_TIME_MAX_NS: AtomicU64 = AtomicU64::new(0);
21static CHUNK_COUNT: AtomicU64 = AtomicU64::new(0);
22static SPLIT_SCAN_NS: AtomicU64 = AtomicU64::new(0);
23
24/// Reset profiling counters (call before a parallel run).
25pub fn reset_chunk_profile() {
26    CHUNK_TIME_SUM_NS.store(0, Ordering::Relaxed);
27    CHUNK_TIME_MAX_NS.store(0, Ordering::Relaxed);
28    CHUNK_COUNT.store(0, Ordering::Relaxed);
29    SPLIT_SCAN_NS.store(0, Ordering::Relaxed);
30}
31
32/// Read the chunk-time profile as (split_scan_ns, sum_ns, max_ns, count).
33pub fn chunk_profile() -> (u64, u64, u64, u64) {
34    (
35        SPLIT_SCAN_NS.load(Ordering::Relaxed),
36        CHUNK_TIME_SUM_NS.load(Ordering::Relaxed),
37        CHUNK_TIME_MAX_NS.load(Ordering::Relaxed),
38        CHUNK_COUNT.load(Ordering::Relaxed),
39    )
40}
41
42/// Parallel executor that splits an input byte slice into chunks, parses each
43/// chunk independently, and returns the resulting Arrow record batches.
44pub struct ParallelExecutor;
45
46impl ParallelExecutor {
47    /// Parse `bytes` in parallel using `splitter` and `parser`.
48    ///
49    /// * Fast path (no `auto_dict`): each chunk is exported as its own
50    ///   `RecordBatch` and a vector of batches is returned. Row filters
51    ///   (`Equal`/`NotEqual`/`Compare`) are applied during parse per chunk.
52    /// * Merge path: chunk builders are merged sequentially so that
53    ///   auto-dictionary upgrades see the full cardinality, then a single
54    ///   `RecordBatch` is returned inside the vector.
55    pub fn parse<P>(
56        bytes: &[u8],
57        splitter: &dyn Splitter,
58        parser: P,
59        plan: Arc<ExecutionPlan>,
60        num_chunks: usize,
61    ) -> Result<Vec<RecordBatch>>
62    where
63        P: RecordParser + Clone + Send + Sync,
64    {
65        reset_chunk_profile();
66        let t_split = Instant::now();
67        let split_points = splitter.find_split_points(bytes, num_chunks);
68        SPLIT_SCAN_NS.store(t_split.elapsed().as_nanos() as u64, Ordering::Relaxed);
69        let ranges = split_points_to_ranges(&split_points, bytes.len());
70
71        let est_row = splitter
72            .estimate_bytes_per_row(&bytes[..bytes.len().min(65536)])
73            .max(512);
74        let results: Vec<Result<TableBuilder>> = ranges
75            .into_par_iter()
76            .map(|range| {
77                let t_chunk = Instant::now();
78                let result = catch_unwind(AssertUnwindSafe(|| {
79                    let est = if !range.is_empty() {
80                        (range.len() / est_row).max(64)
81                    } else {
82                        64
83                    };
84                    let mut sink = TableBuilder::with_plan(est, Arc::clone(&plan));
85                    parser.validate(&bytes[range.clone()])?;
86                    parser.parse_chunk_generic(&bytes[range.clone()], &mut sink)?;
87                    Ok(sink)
88                }))
89                .unwrap_or_else(|payload| {
90                    let msg = if let Some(s) = payload.downcast_ref::<&str>() {
91                        (*s).to_string()
92                    } else if let Some(s) = payload.downcast_ref::<String>() {
93                        s.clone()
94                    } else {
95                        "unknown panic".to_string()
96                    };
97                    Err(crate::Error::Parser(format!(
98                        "worker panicked during parallel parse: {msg}. \
99                         This usually indicates a bug in the parser (e.g., returning \
100                         Cow::Borrowed that outlives the input chunk, or an unwrap() \
101                         on None/Err during parsing). Check your RecordParser::parse_chunk \
102                         implementation for incorrect lifetime handling or missing error checks."
103                    )))
104                });
105                // Record chunk timing for get_par_profile()
106                let elapsed_ns = t_chunk.elapsed().as_nanos() as u64;
107                CHUNK_TIME_SUM_NS.fetch_add(elapsed_ns, Ordering::Relaxed);
108                CHUNK_COUNT.fetch_add(1, Ordering::Relaxed);
109                // Atomic max: CAS loop
110                loop {
111                    let prev = CHUNK_TIME_MAX_NS.load(Ordering::Relaxed);
112                    if elapsed_ns <= prev {
113                        break;
114                    }
115                    if CHUNK_TIME_MAX_NS
116                        .compare_exchange_weak(
117                            prev,
118                            elapsed_ns,
119                            Ordering::Relaxed,
120                            Ordering::Relaxed,
121                        )
122                        .is_ok()
123                    {
124                        break;
125                    }
126                }
127                result
128            })
129            .collect();
130
131        let mut engines: Vec<TableBuilder> = results.into_iter().collect::<Result<_>>()?;
132
133        if engines.is_empty() {
134            return Ok(Vec::new());
135        }
136
137        let plan = Arc::clone(&engines[0].plan);
138
139        // Fast path: no auto_dict and all chunks agree on column types.
140        // Compare filters are evaluated per-row during parse, so they do not
141        // force the merge path. Schema-inconsistent chunks fall through to the
142        // merge path, which surfaces a precise `Error::Merge` for irreconcilable
143        // type mismatches instead of an opaque Arrow schema error.
144        if !plan.auto_dict && schemas_consistent(&engines) {
145            return engines_to_record_batches(engines, &plan);
146        }
147
148        // Incremental dict path for auto_dict: per-chunk upgrade in parallel,
149        // then unify dictionaries (tiny serial) and remap, staying on fast path.
150        if plan.auto_dict {
151            // Per-chunk upgrade in parallel (was serial after merge)
152            engines.par_iter_mut().for_each(|e| e.auto_dict_upgrade());
153            if schemas_consistent(&engines) {
154                // Find first dict column that needs unification across chunks.
155                let mut unify_col: Option<String> = None;
156                for col_name in &engines[0].column_order.clone() {
157                    let first_idx = engines[0].field_index.get(col_name).copied();
158                    if let Some(idx) = first_idx {
159                        if engines[0].columns[idx].variant_key() == "dictionary" {
160                            let first_data = if let crate::columnar::ColumnBuilder::Dictionary {
161                                data,
162                                offsets,
163                                ..
164                            } = &engines[0].columns[idx]
165                            {
166                                (data, offsets)
167                            } else {
168                                continue;
169                            };
170                            for e in &engines[1..] {
171                                if let Some(&j) = e.field_index.get(col_name) {
172                                    if let crate::columnar::ColumnBuilder::Dictionary {
173                                        data,
174                                        offsets,
175                                        ..
176                                    } = &e.columns[j]
177                                    {
178                                        if data != first_data.0 || offsets != first_data.1 {
179                                            unify_col = Some(col_name.clone());
180                                            break;
181                                        }
182                                    }
183                                }
184                            }
185                            if unify_col.is_some() {
186                                break;
187                            }
188                        }
189                    }
190                }
191                if unify_col.is_none() {
192                    return engines_to_record_batches(engines, &plan);
193                }
194                let col_name = unify_col.unwrap();
195                // Build seed from first chunk, unify, remap.
196                let first_data =
197                    if let crate::columnar::ColumnBuilder::Dictionary { data, offsets, .. } =
198                        &engines[0].columns[engines[0].field_index[&col_name]]
199                    {
200                        (data.clone(), offsets.clone())
201                    } else {
202                        return engines_to_record_batches(engines, &plan);
203                    };
204                // Build SeedDict from the contiguous buffer
205                let mut seed_values = Vec::new();
206                let mut seed_offsets = Vec::with_capacity(first_data.1.len());
207                seed_offsets.push(0);
208                for i in 0..(first_data.1.len() - 1) {
209                    let start = first_data.1[i] as usize;
210                    let end = first_data.1[i + 1] as usize;
211                    seed_values.extend_from_slice(&first_data.0[start..end]);
212                    seed_offsets.push(seed_values.len() as i32);
213                }
214                let seed = crate::dict::SeedDict {
215                    values: seed_values,
216                    offsets: seed_offsets,
217                    index: rustc_hash::FxHashMap::default(), // Will be populated by unify
218                };
219                let col_refs: Vec<&crate::columnar::ColumnBuilder> = engines
220                    .iter()
221                    .filter_map(|e| e.field_index.get(&col_name).map(|&idx| &e.columns[idx]))
222                    .collect();
223                let (unified_dict, remaps) = crate::dict::unify_dictionaries(&seed, &col_refs);
224                // Build unified data+offsets+index for replace_dict.
225                let mut new_index: rustc_hash::FxHashMap<Box<str>, i32> =
226                    rustc_hash::FxHashMap::default();
227                for i in 0..(unified_dict.offsets.len() - 1) {
228                    let start = unified_dict.offsets[i] as usize;
229                    let end = unified_dict.offsets[i + 1] as usize;
230                    let s = std::str::from_utf8(&unified_dict.data[start..end]).unwrap_or("");
231                    let k: Box<str> = s.into();
232                    new_index.insert(k, i as i32);
233                }
234                // Apply remap to each chunk, then replace dict.
235                for (e, remap) in engines.iter_mut().zip(remaps.iter()) {
236                    if let Some(idx) = e.field_index.get(&col_name).copied() {
237                        if let Some(codes) = e.columns[idx].dict_codes_mut() {
238                            codes.remap_codes(&remap.map);
239                        }
240                        e.columns[idx].replace_dict(
241                            unified_dict.data.clone(),
242                            unified_dict.offsets.clone(),
243                            new_index.clone(),
244                        );
245                    }
246                }
247                return engines_to_record_batches(engines, &plan);
248            }
249        }
250
251        // Merge path.
252        let mut merged = TableBuilder::with_plan(engines.len().max(64) * 512, Arc::clone(&plan));
253        for engine in engines {
254            merged.extend(engine)?;
255        }
256        let batch = merged.finish()?;
257        if let Some(ref filter) = plan.filter {
258            return Ok(vec![apply_compare_filter(batch, filter)?]);
259        }
260        Ok(vec![batch])
261    }
262}
263
264/// True when every chunk builder agrees on each column's storage variant.
265/// Chunks missing a column entirely are fine (the export path null-fills).
266fn schemas_consistent(engines: &[TableBuilder]) -> bool {
267    let Some(first) = engines.first() else {
268        return true;
269    };
270    let base: HashMap<&str, &str> = first
271        .field_index
272        .iter()
273        .map(|(name, &idx)| (name.as_str(), first.columns[idx].variant_key()))
274        .collect();
275    engines[1..].iter().all(|e| {
276        e.field_index.iter().all(|(name, &idx)| {
277            let b = &e.columns[idx];
278            match base.get(name.as_str()) {
279                Some(key) => *key == b.variant_key(),
280                None => true,
281            }
282        })
283    })
284}