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