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 mut ranges = split_points_to_ranges(&split_points, bytes.len());
70
71        // Guard against degenerate splitter output that produces no ranges.
72        if ranges.is_empty() {
73            ranges.push(0..bytes.len());
74        }
75
76        let est_row = splitter
77            .estimate_bytes_per_row(&bytes[..bytes.len().min(65536)])
78            .max(512);
79        let results: Vec<Result<TableBuilder>> = ranges
80            .into_par_iter()
81            .map(|range| {
82                let t_chunk = Instant::now();
83                let result = catch_unwind(AssertUnwindSafe(|| {
84                    let est = if !range.is_empty() {
85                        (range.len() / est_row).max(64)
86                    } else {
87                        64
88                    };
89                    let mut sink = TableBuilder::with_plan(est, Arc::clone(&plan));
90                    parser.validate(&bytes[range.clone()])?;
91                    parser.parse_chunk_generic(&bytes[range.clone()], &mut sink)?;
92                    Ok(sink)
93                }))
94                .unwrap_or_else(|payload| {
95                    let msg = if let Some(s) = payload.downcast_ref::<&str>() {
96                        (*s).to_string()
97                    } else if let Some(s) = payload.downcast_ref::<String>() {
98                        s.clone()
99                    } else {
100                        "unknown panic".to_string()
101                    };
102                    Err(crate::Error::Parser(format!(
103                        "worker panicked during parallel parse: {msg}. \
104                         This usually indicates a bug in the parser (e.g., returning \
105                         Cow::Borrowed that outlives the input chunk, or an unwrap() \
106                         on None/Err during parsing). Check your RecordParser::parse_chunk \
107                         implementation for incorrect lifetime handling or missing error checks."
108                    )))
109                });
110                // Record chunk timing for get_par_profile()
111                let elapsed_ns = t_chunk.elapsed().as_nanos() as u64;
112                CHUNK_TIME_SUM_NS.fetch_add(elapsed_ns, Ordering::Relaxed);
113                CHUNK_COUNT.fetch_add(1, Ordering::Relaxed);
114                // Atomic max: CAS loop
115                loop {
116                    let prev = CHUNK_TIME_MAX_NS.load(Ordering::Relaxed);
117                    if elapsed_ns <= prev {
118                        break;
119                    }
120                    if CHUNK_TIME_MAX_NS
121                        .compare_exchange_weak(
122                            prev,
123                            elapsed_ns,
124                            Ordering::Relaxed,
125                            Ordering::Relaxed,
126                        )
127                        .is_ok()
128                    {
129                        break;
130                    }
131                }
132                result
133            })
134            .collect();
135
136        let mut engines: Vec<TableBuilder> = results.into_iter().collect::<Result<_>>()?;
137
138        if engines.is_empty() {
139            return Ok(Vec::new());
140        }
141
142        let plan = Arc::clone(&engines[0].plan);
143
144        // Fast path: no auto_dict and all chunks agree on column types.
145        // Compare filters are evaluated per-row during parse, so they do not
146        // force the merge path. Schema-inconsistent chunks fall through to the
147        // merge path, which surfaces a precise `Error::Merge` for irreconcilable
148        // type mismatches instead of an opaque Arrow schema error.
149        if !plan.auto_dict && schemas_consistent(&engines) {
150            return engines_to_record_batches(engines, &plan);
151        }
152
153        // Incremental dict path for auto_dict: per-chunk upgrade in parallel,
154        // then unify dictionaries (tiny serial) and remap, staying on fast path.
155        if plan.auto_dict {
156            // Per-chunk upgrade in parallel (was serial after merge)
157            engines.par_iter_mut().for_each(|e| e.auto_dict_upgrade());
158            if schemas_consistent(&engines) {
159                // Find first dict column that needs unification across chunks.
160                let mut unify_col: Option<String> = None;
161                for col_name in &engines[0].column_order {
162                    let first_idx = engines[0].field_index.get(col_name).copied();
163                    if let Some(idx) = first_idx {
164                        if engines[0].columns[idx].variant_key() == "dictionary" {
165                            let first_data = if let crate::columnar::ColumnBuilder::Dictionary {
166                                data,
167                                offsets,
168                                ..
169                            } = &engines[0].columns[idx]
170                            {
171                                (data, offsets)
172                            } else {
173                                continue;
174                            };
175                            for e in &engines[1..] {
176                                if let Some(&j) = e.field_index.get(col_name) {
177                                    if let crate::columnar::ColumnBuilder::Dictionary {
178                                        data,
179                                        offsets,
180                                        ..
181                                    } = &e.columns[j]
182                                    {
183                                        if data != first_data.0 || offsets != first_data.1 {
184                                            unify_col = Some(col_name.clone());
185                                            break;
186                                        }
187                                    }
188                                }
189                            }
190                            if unify_col.is_some() {
191                                break;
192                            }
193                        }
194                    }
195                }
196                if unify_col.is_none() {
197                    return engines_to_record_batches(engines, &plan);
198                }
199                let col_name = unify_col.unwrap();
200                // Build seed from first chunk, unify, remap.
201                let first_data = if let Some(&idx) = engines[0].field_index.get(&col_name) {
202                    if let crate::columnar::ColumnBuilder::Dictionary { data, offsets, .. } =
203                        &engines[0].columns[idx]
204                    {
205                        (data.clone(), offsets.clone())
206                    } else {
207                        return engines_to_record_batches(engines, &plan);
208                    }
209                } else {
210                    return engines_to_record_batches(engines, &plan);
211                };
212                // Build SeedDict from the contiguous buffer
213                let mut seed_values = Vec::new();
214                let mut seed_offsets = Vec::with_capacity(first_data.1.len());
215                seed_offsets.push(0);
216                for i in 0..(first_data.1.len() - 1) {
217                    let start = first_data.1[i] as usize;
218                    let end = first_data.1[i + 1] as usize;
219                    seed_values.extend_from_slice(&first_data.0[start..end]);
220                    seed_offsets.push(seed_values.len() as i32);
221                }
222                let seed = crate::dict::SeedDict {
223                    values: seed_values,
224                    offsets: seed_offsets,
225                    index: rustc_hash::FxHashMap::default(), // Will be populated by unify
226                };
227                let col_refs: Vec<&crate::columnar::ColumnBuilder> = engines
228                    .iter()
229                    .filter_map(|e| e.field_index.get(&col_name).map(|&idx| &e.columns[idx]))
230                    .collect();
231                let (unified_dict, remaps) = crate::dict::unify_dictionaries(&seed, &col_refs);
232                // Build unified data+offsets+index for replace_dict.
233                let mut new_index: rustc_hash::FxHashMap<Box<str>, i32> =
234                    rustc_hash::FxHashMap::default();
235                for i in 0..(unified_dict.offsets.len() - 1) {
236                    let start = unified_dict.offsets[i] as usize;
237                    let end = unified_dict.offsets[i + 1] as usize;
238                    let s = String::from_utf8_lossy(&unified_dict.data[start..end]);
239                    let k: Box<str> = s.into();
240                    new_index.insert(k, i as i32);
241                }
242                // Apply remap to each chunk, then replace dict.
243                for (e, remap) in engines.iter_mut().zip(remaps.iter()) {
244                    if let Some(idx) = e.field_index.get(&col_name).copied() {
245                        if let Some(codes) = e.columns[idx].dict_codes_mut() {
246                            codes.remap_codes(&remap.map);
247                        }
248                        e.columns[idx].replace_dict(
249                            unified_dict.data.clone(),
250                            unified_dict.offsets.clone(),
251                            new_index.clone(),
252                        );
253                    }
254                }
255                return engines_to_record_batches(engines, &plan);
256            }
257        }
258
259        // Merge path.
260        let mut merged = TableBuilder::with_plan(engines.len().max(64) * 512, Arc::clone(&plan));
261        for engine in engines {
262            merged.extend(engine)?;
263        }
264        let batch = merged.finish()?;
265        if let Some(ref filter) = plan.filter {
266            return Ok(vec![apply_compare_filter(batch, filter)?]);
267        }
268        Ok(vec![batch])
269    }
270}
271
272/// True when every chunk builder agrees on each column's storage variant.
273/// Chunks missing a column entirely are fine (the export path null-fills).
274fn schemas_consistent(engines: &[TableBuilder]) -> bool {
275    let Some(first) = engines.first() else {
276        return true;
277    };
278    let base: HashMap<&str, &str> = first
279        .field_index
280        .iter()
281        .map(|(name, &idx)| (name.as_str(), first.columns[idx].variant_key()))
282        .collect();
283    engines[1..].iter().all(|e| {
284        e.field_index.iter().all(|(name, &idx)| {
285            let b = &e.columns[idx];
286            match base.get(name.as_str()) {
287                Some(key) => *key == b.variant_key(),
288                None => true,
289            }
290        })
291    })
292}