rypipe-core 2.2.0

Format-agnostic ingestion framework with Arrow export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Parallel streaming executor: multi-core parsing with bounded memory.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::Arc;
use std::thread::{self, JoinHandle};

use arrow::record_batch::RecordBatch;

use std::sync::atomic::{AtomicU64, Ordering};

use crate::bounded::MemoryBudget;
use crate::consumer::BatchConsumer;
use crate::decoder::{RecordParser, Splitter};
use crate::engine::TableBuilder;
use crate::input::InputBuffer;
use crate::plan::ExecutionPlan;
use crate::schema::{DiscoveryOpts, FrozenSchema};
use crate::Result;

static DISCOVERY_NS: AtomicU64 = AtomicU64::new(0);

/// Return the elapsed time (in nanoseconds) spent in schema discovery.
pub fn discovery_profile() -> u64 {
    DISCOVERY_NS.load(Ordering::Relaxed)
}
/// Reset the discovery timer to zero.
pub fn reset_discovery_profile() {
    DISCOVERY_NS.store(0, Ordering::Relaxed);
}

/// Options for parallel streaming.
pub struct ParallelStreamOpts {
    /// Number of worker threads.
    pub threads: usize,
    /// Whether to preserve row order (default: true).
    pub ordered: bool,
    /// Maximum reorder buffer size (default: = threads).
    pub max_reorder: usize,
    /// Explicit schema.  If `Some`, no discovery pass is needed.
    /// Workers pre-size all columns from construction.
    pub schema: Option<FrozenSchema>,
}

impl Default for ParallelStreamOpts {
    fn default() -> Self {
        Self {
            threads: std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1),
            ordered: true,
            max_reorder: 0, // 0 = use threads value
            schema: None,
        }
    }
}

/// Discovery sink that collects raw field names in encounter order.
/// `needs_value=false` keeps the scanner in locate-only mode (no value
/// extraction), but we still need `resolve()` calls, so `needs_resolve`
/// stays true. Capture happens in `resolve()` via interior mutability.
struct DiscoverySink {
    seen: std::cell::RefCell<rustc_hash::FxHashSet<Box<str>>>,
    order: std::cell::RefCell<Vec<String>>,
}

impl DiscoverySink {
    fn new() -> Self {
        Self {
            seen: std::cell::RefCell::new(rustc_hash::FxHashSet::default()),
            order: std::cell::RefCell::new(Vec::new()),
        }
    }
    fn into_order(self) -> Vec<String> {
        self.order.into_inner()
    }
}

impl crate::decoder::ColumnarSink for DiscoverySink {
    #[inline]
    fn begin_row(&mut self) {}
    #[inline]
    fn put_field(&mut self, name: &str, _value: crate::value::Value<'_>) {
        // Full-value fallback (if needs_value were true); keep for completeness.
        let mut seen = self.seen.borrow_mut();
        if seen.insert(Box::from(name)) {
            self.order.borrow_mut().push(name.to_string());
        }
    }
    #[inline]
    fn end_row(&mut self) {}
    #[inline]
    fn wants(&self, _name: &str) -> bool {
        true
    }
    #[inline]
    fn resolve<'a>(&'a self, name: &'a str) -> Option<&'a str> {
        // Locate-only path calls `resolve` without `put_field`; capture here.
        let mut seen = self.seen.borrow_mut();
        if seen.insert(Box::from(name)) {
            self.order.borrow_mut().push(name.to_string());
        }
        Some(name)
    }
    #[inline]
    fn needs_value(&self) -> bool {
        false
    }
    // needs_resolve defaults to true → scanner calls resolve() for each field.
    fn finish(&mut self) -> crate::Result<arrow::record_batch::RecordBatch> {
        Ok(arrow::record_batch::RecordBatch::new_empty(
            std::sync::Arc::new(arrow::datatypes::Schema::empty()),
        ))
    }
}

fn discover_schema<P: crate::decoder::RecordParser>(
    bytes: &[u8],
    parser: &P,
    plan: &crate::plan::ExecutionPlan,
    splitter: &dyn crate::decoder::Splitter,
) -> (FrozenSchema, Vec<String>) {
    let t0 = std::time::Instant::now();
    // Explicit schema already handled by caller; this is auto-discovery.
    let opts = DiscoveryOpts::default();
    let order: Vec<String> = if (bytes.len() as u64) < opts.full_scan_threshold {
        let mut sink = DiscoverySink::new();
        let _ = parser.parse_chunk_generic(bytes, &mut sink);
        sink.into_order()
    } else {
        use rayon::prelude::*;
        let n = opts.windows;
        let wbytes = opts.window_bytes;
        // Parallelise windows: 16×2 MiB independent parses (~19 ms serial → ~2 ms on 16t)
        let per_window: Vec<Vec<String>> = (0..n)
            .into_par_iter()
            .map(|i| {
                let start = (bytes.len() as u64 * i as u64 / n as u64) as usize;
                let end = (start + wbytes).min(bytes.len());
                if start >= end {
                    return Vec::new();
                }
                let mut sink = DiscoverySink::new();
                let slice = &bytes[start..end];
                let _ = parser.parse_chunk_generic(slice, &mut sink);
                sink.into_order()
            })
            .collect();
        // Merge in file order, deduplicating, so global order approximates file order.
        let mut seen = rustc_hash::FxHashSet::<String>::default();
        let mut merged = Vec::new();
        for mut v in per_window {
            for name in v.drain(..) {
                if seen.insert(name.clone()) {
                    merged.push(name);
                }
            }
        }
        if merged.is_empty() && !bytes.is_empty() {
            let mut sink = DiscoverySink::new();
            let _ = parser.parse_chunk_generic(bytes, &mut sink);
            sink.into_order()
        } else {
            merged
        }
    };
    let elapsed = t0.elapsed().as_nanos() as u64;
    DISCOVERY_NS.store(elapsed, Ordering::Relaxed);
    let _ = splitter; // keep splitter in signature for future alignment
    let schema = if order.is_empty() {
        FrozenSchema::from_plan(&[], plan)
    } else {
        FrozenSchema::from_discovered(&order, plan)
    };
    (schema, order)
}

/// Public helper for batch workloads: discover the schema once and reuse.
/// Example:
/// ```ignore
/// let schema = discover_schema_for_path(path, &splitter, &parser, &plan);
/// for f in files { ParallelStreamingBatchIterator::new(..., schema.clone(), ...) }
/// ```
pub fn discover_schema_for_bytes<P: crate::decoder::RecordParser>(
    bytes: &[u8],
    splitter: &dyn crate::decoder::Splitter,
    parser: &P,
    plan: &crate::plan::ExecutionPlan,
) -> FrozenSchema {
    if !plan.schema_order.is_empty() {
        let names: Vec<&str> = plan.schema_order.iter().map(|s| s.as_str()).collect();
        return FrozenSchema::from_plan(&names, plan);
    }
    let opts = DiscoveryOpts::default();
    let sig = crate::schema::layout_signature(bytes, &opts);
    {
        let cache = crate::schema::SCHEMA_CACHE.read().unwrap();
        if let Some(order) = cache.get(&sig) {
            crate::schema::SCHEMA_CACHE_HITS.fetch_add(1, Ordering::Relaxed);
            return FrozenSchema::from_discovered(order, plan);
        }
    }
    crate::schema::SCHEMA_CACHE_MISSES.fetch_add(1, Ordering::Relaxed);
    let (schema, order) = discover_schema(bytes, parser, plan, splitter);
    if !order.is_empty() {
        crate::schema::insert_schema_cache(sig, Arc::new(order));
    }
    schema
}

/// Parallel streaming executor: parses chunks concurrently with bounded memory.
pub struct ParallelStreamingExecutor {
    budget: MemoryBudget,
    max_in_flight: usize,
}

impl ParallelStreamingExecutor {
    pub fn new(budget: MemoryBudget, max_in_flight: usize) -> Self {
        Self {
            budget,
            max_in_flight: max_in_flight.max(1),
        }
    }

    /// Stream a file in parallel, calling `consumer` per batch in order.
    #[allow(clippy::too_many_arguments)]
    pub fn run_stream<P, C>(
        &self,
        path: &Path,
        splitter: &dyn Splitter,
        parser: P,
        plan: Arc<ExecutionPlan>,
        prefault: bool,
        opts: ParallelStreamOpts,
        consumer: &mut C,
    ) -> Result<()>
    where
        P: RecordParser + Clone + Send + Sync + 'static,
        C: BatchConsumer,
    {
        let input = InputBuffer::open(path, cfg!(feature = "mmap"), prefault)?;
        if input.is_empty() {
            return Ok(());
        }
        // Share the InputBuffer across workers via Arc to avoid
        // the O(file_size × threads) to_vec() clone.
        let shared = std::sync::Arc::new(input);
        self.run_bytes_stream_shared(shared, splitter, parser, plan, opts, consumer)
    }

    /// Stream from a shared InputBuffer (zero-copy on mmap).
    fn run_bytes_stream_shared<P, C>(
        &self,
        input: std::sync::Arc<InputBuffer>,
        splitter: &dyn Splitter,
        parser: P,
        plan: Arc<ExecutionPlan>,
        opts: ParallelStreamOpts,
        consumer: &mut C,
    ) -> Result<()>
    where
        P: RecordParser + Clone + Send + Sync + 'static,
        C: BatchConsumer,
    {
        // Safety: the Arc keeps the InputBuffer alive for the duration.
        // We pass a dummy &[u8] to satisfy the signature; run_bytes_stream_core
        // ignores it when input is Some and uses input.as_slice() instead.
        let dummy: &[u8] = &[];
        self.run_bytes_stream_core(dummy, Some(input), splitter, parser, plan, opts, consumer)
    }

    /// Stream bytes in parallel.
    pub fn run_bytes_stream<P, C>(
        &self,
        bytes: &[u8],
        splitter: &dyn Splitter,
        parser: P,
        plan: Arc<ExecutionPlan>,
        opts: ParallelStreamOpts,
        consumer: &mut C,
    ) -> Result<()>
    where
        P: RecordParser + Clone + Send + Sync + 'static,
        C: BatchConsumer,
    {
        self.run_bytes_stream_core(bytes, None, splitter, parser, plan, opts, consumer)
    }

    /// Core implementation shared by `run_bytes_stream` and `run_bytes_stream_shared`.
    #[allow(clippy::too_many_arguments)]
    fn run_bytes_stream_core<P, C>(
        &self,
        bytes: &[u8],
        input: Option<std::sync::Arc<InputBuffer>>,
        splitter: &dyn Splitter,
        parser: P,
        plan: Arc<ExecutionPlan>,
        opts: ParallelStreamOpts,
        consumer: &mut C,
    ) -> Result<()>
    where
        P: RecordParser + Clone + Send + Sync + 'static,
        C: BatchConsumer,
    {
        // Prefer the shared InputBuffer's slice over the passed-in bytes.
        let actual_bytes = match input {
            Some(ref inp) => inp.as_slice(),
            None => bytes,
        };
        let n = opts.threads.max(1);
        let max_reorder = if opts.max_reorder > 0 {
            opts.max_reorder
        } else {
            n
        };
        // Frozen schema: gates correct ParquetWriter / StreamWriter usage.
        // Without it, batch 2 can have different column order (FieldG vs Text20
        // last) even when the set is identical, breaking `write_batch`.
        // If opts.schema is None, auto-discover:
        //  - explicit plan.schema_order → from_plan (exact)
        //  - else sampled discovery (16×2 MiB windows for >128 MiB, else full)
        let schema: Option<FrozenSchema> = match opts.schema {
            Some(s) => Some(s),
            None => {
                if !plan.schema_order.is_empty() {
                    let names: Vec<&str> = plan.schema_order.iter().map(|s| s.as_str()).collect();
                    Some(FrozenSchema::from_plan(&names, &plan))
                } else {
                    let opts = DiscoveryOpts::default();
                    let sig = crate::schema::layout_signature(actual_bytes, &opts);
                    let cached = crate::schema::SCHEMA_CACHE
                        .read()
                        .unwrap()
                        .get(&sig)
                        .cloned();
                    let (schema, order) = if let Some(order) = cached {
                        crate::schema::SCHEMA_CACHE_HITS.fetch_add(1, Ordering::Relaxed);
                        (FrozenSchema::from_discovered(&order, &plan), order)
                    } else {
                        crate::schema::SCHEMA_CACHE_MISSES.fetch_add(1, Ordering::Relaxed);
                        let (schema, order) =
                            discover_schema(actual_bytes, &parser, &plan, splitter);
                        (schema, Arc::new(order))
                    };
                    if !order.is_empty() {
                        crate::schema::insert_schema_cache(sig, order);
                    }
                    Some(schema)
                }
            }
        };

        let bytes_per_row = splitter
            .estimate_bytes_per_row(&actual_bytes[..actual_bytes.len().min(65536)])
            .max(1);
        let chunk_size = (self.budget.bytes() / (n * 2))
            .max(bytes_per_row * 10)
            .max(64 * 1024);
        let num_chunks = (actual_bytes.len() / chunk_size).max(n).min(10000);
        let split_points = splitter.find_split_points(actual_bytes, num_chunks);
        let mut ranges = crate::decoder::split_points_to_ranges(&split_points, actual_bytes.len());
        if ranges.is_empty() {
            ranges.push(0..bytes.len());
        }

        let chunks_with_seq: Vec<(usize, std::ops::Range<usize>)> =
            ranges.into_iter().enumerate().collect();

        let (sender, receiver) = sync_channel(self.max_in_flight);
        let mut handles: Vec<JoinHandle<Result<()>>> = Vec::with_capacity(n);
        let chunk_queue = std::sync::Arc::new(std::sync::Mutex::new(chunks_with_seq));
        let plan_arc = plan;
        let schema_arc = schema.map(std::sync::Arc::new);
        let est_row = splitter
            .estimate_bytes_per_row(&bytes[..bytes.len().min(65536)])
            .max(512);

        // Pre-clone bytes for the fallback path (when input is None).
        let bytes_fallback = if input.is_none() {
            Some(actual_bytes.to_vec())
        } else {
            None
        };
        for _ in 0..n {
            let queue = std::sync::Arc::clone(&chunk_queue);
            let sender_clone: SyncSender<(usize, Result<RecordBatch>)> = sender.clone();
            let parser_clone = parser.clone();
            let plan_clone = std::sync::Arc::clone(&plan_arc);
            let schema_clone = schema_arc.clone();
            let input_clone = input.clone();
            let fallback_clone = bytes_fallback.clone();
            let handle = thread::spawn(move || -> Result<()> {
                // Use shared InputBuffer when available (zero-copy on mmap);
                // fall back to pre-cloned bytes for external callers.
                let bytes_ref: &[u8] = match input_clone {
                    Some(ref inp) => inp.as_slice(),
                    None => fallback_clone.as_deref().unwrap_or(&[]),
                };
                loop {
                    let next = {
                        let mut q = queue.lock().unwrap();
                        q.pop()
                    };
                    let Some((seq, range)) = next else { break };
                    let chunk_bytes = &bytes_ref[range.start..range.end];
                    let mut builder = TableBuilder::with_plan(
                        (chunk_bytes.len() / est_row).max(64),
                        plan_clone.clone(),
                    );
                    // If schema is provided, pre-size columns from it.
                    if let Some(ref schema) = schema_clone {
                        if let Err(e) = builder.ensure_schema(schema) {
                            let _ = sender_clone.send((seq, Err(e)));
                            break;
                        }
                    }
                    if let Err(e) = parser_clone.validate(chunk_bytes) {
                        let _ = sender_clone.send((seq, Err(e)));
                        break;
                    }
                    if let Err(e) = parser_clone.parse_chunk_generic(chunk_bytes, &mut builder) {
                        let _ = sender_clone.send((seq, Err(e)));
                        break;
                    }
                    let res = builder.finish();
                    if sender_clone.send((seq, res)).is_err() {
                        break;
                    }
                }
                Ok(())
            });
            handles.push(handle);
        }
        drop(sender);

        // Coordinator: order by seq and deliver.
        // If `ordered`, buffer out-of-order batches until the next-in-sequence arrives.
        // If unordered, deliver immediately.
        // When the reorder buffer overflows, fall back to unordered delivery.
        let mut pending: BTreeMap<usize, RecordBatch> = BTreeMap::new();
        let mut next_seq = 0usize;
        let mut reorder_bytes: usize = 0;
        let mut fallback_unordered = false;
        let reorder_limit = max_reorder * self.budget.bytes();
        for (seq, res) in receiver {
            match res {
                Ok(batch) => {
                    if opts.ordered && !fallback_unordered {
                        if seq == next_seq {
                            consumer.consume(batch)?;
                            next_seq += 1;
                            while let Some(b) = pending.remove(&next_seq) {
                                consumer.consume(b)?;
                                next_seq += 1;
                            }
                        } else {
                            reorder_bytes += batch.get_array_memory_size();
                            if reorder_bytes > reorder_limit {
                                // Buffer overflow: drain pending in arrival order
                                // (closest to correct), then deliver all remaining
                                // batches unordered.  This avoids a hard error when
                                // the memory budget is too small for the chunk count.
                                for (_, b) in std::mem::take(&mut pending) {
                                    consumer.consume(b)?;
                                }
                                consumer.consume(batch)?;
                                reorder_bytes = 0;
                                fallback_unordered = true;
                            } else {
                                pending.insert(seq, batch);
                            }
                        }
                    } else {
                        // Unordered (either opted out or fell back): deliver immediately.
                        consumer.consume(batch)?;
                    }
                }
                Err(_) => {
                    // Skip failed chunks (logged upstream).
                }
            }
        }
        // Drain remaining.
        if opts.ordered && !fallback_unordered {
            while let Some(b) = pending.remove(&next_seq) {
                consumer.consume(b)?;
                next_seq += 1;
            }
        }
        for h in handles {
            h.join()
                .map_err(|_| crate::Error::Merge("worker panicked".into()))??;
        }
        Ok(())
    }
}

/// Iterator wrapper for parallel streaming (pull-based).
pub struct ParallelStreamingBatchIterator {
    receiver: Receiver<Result<RecordBatch>>,
    handle: Option<JoinHandle<Result<()>>>,
    done: bool,
}

impl ParallelStreamingBatchIterator {
    pub fn new<P, S>(
        path: PathBuf,
        splitter: S,
        parser: P,
        plan: Arc<ExecutionPlan>,
        budget: MemoryBudget,
        prefault: bool,
        opts: ParallelStreamOpts,
    ) -> Self
    where
        P: RecordParser + Clone + Send + Sync + 'static,
        S: Splitter + Clone + Send + Sync + 'static,
    {
        let num_threads = opts.threads;
        let max_in_flight = 2 * num_threads;
        let (sender, receiver) = sync_channel(max_in_flight);
        let handle = thread::spawn(move || {
            let exec = ParallelStreamingExecutor::new(budget, max_in_flight);
            let mut consumer = ChannelConsumer {
                sender: sender.clone(),
            };
            let res = exec.run_stream(
                &path,
                &splitter,
                parser,
                plan,
                prefault,
                opts,
                &mut consumer,
            );
            if let Err(e) = res {
                let _ = sender.send(Err(e));
            }
            Ok(())
        });
        Self {
            receiver,
            handle: Some(handle),
            done: false,
        }
    }
}

struct ChannelConsumer {
    sender: SyncSender<Result<RecordBatch>>,
}
impl BatchConsumer for ChannelConsumer {
    fn consume(&mut self, batch: RecordBatch) -> Result<()> {
        let _ = self.sender.send(Ok(batch));
        Ok(())
    }
}

impl Iterator for ParallelStreamingBatchIterator {
    type Item = Result<RecordBatch>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        // This is a simplified version that just receives in order as sent,
        // not handling seq ordering for now. For true ordered, need BTreeMap logic as in run_stream.
        // For first version, we will just receive and yield.
        match self.receiver.recv() {
            Ok(Ok(batch)) => Some(Ok(batch)),
            Ok(Err(e)) => {
                self.done = true;
                Some(Err(e))
            }
            Err(_) => {
                self.done = true;
                if let Some(h) = self.handle.take() {
                    if let Err(p) = h.join() {
                        let msg = if let Some(s) = p.downcast_ref::<&str>() {
                            (*s).to_string()
                        } else if let Some(s) = p.downcast_ref::<String>() {
                            s.clone()
                        } else {
                            "worker panicked".to_string()
                        };
                        return Some(Err(crate::Error::Merge(format!(
                            "parallel streaming worker panicked: {msg}"
                        ))));
                    }
                }
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;
    use crate::decoder::{ColumnarSink, RecordParser, Splitter};
    use crate::plan::ExecutionPlan;
    use crate::schema::{clear_schema_cache, schema_cache_stats};
    use crate::value::Value;

    /// Minimal parser: newline-separated rows of `key=value\t...` tokens.
    #[derive(Clone, Debug, Default)]
    struct NameValueParser;

    impl RecordParser for NameValueParser {
        fn validate(&self, _bytes: &[u8]) -> Result<()> {
            Ok(())
        }

        fn parse_chunk(&self, bytes: &[u8], sink: &mut dyn ColumnarSink) -> Result<()> {
            let text = std::str::from_utf8(bytes).map_err(|e| crate::Error::Plan(e.to_string()))?;
            for line in text.lines() {
                if line.is_empty() {
                    continue;
                }
                sink.begin_row();
                for token in line.split('\t') {
                    if let Some((k, v)) = token.split_once('=') {
                        sink.resolve_and_put(k, Value::Str(Cow::Borrowed(v)));
                    }
                }
                sink.end_row();
            }
            Ok(())
        }
    }

    /// Trivial splitter: one chunk covering the whole input.
    struct NullSplitter;

    impl Splitter for NullSplitter {
        fn next_record_start(&self, _bytes: &[u8], _from: usize) -> Option<usize> {
            None
        }

        fn find_split_points(&self, bytes: &[u8], _max_chunks: usize) -> Vec<usize> {
            vec![0, bytes.len()]
        }

        fn estimate_bytes_per_row(&self, sample: &[u8]) -> usize {
            let n = sample.iter().filter(|&&b| b == b'\n').count().max(1);
            sample.len() / n
        }
    }

    fn names(schema: &FrozenSchema) -> Vec<&str> {
        schema.column_names().iter().map(|s| s.as_ref()).collect()
    }

    #[test]
    fn schema_cache_hits_misses_and_plan_changes() {
        clear_schema_cache();
        let splitter = NullSplitter;
        let parser = NameValueParser;

        // First layout: miss.
        let bytes = b"a=1\tb=2\na=3\tb=4\n";
        let plan = ExecutionPlan::new();
        let s1 = discover_schema_for_bytes(bytes, &splitter, &parser, &plan);
        assert_eq!(names(&s1), vec!["a", "b"]);
        assert_eq!(schema_cache_stats(), (0, 1));

        // Same layout: hit.
        let s2 = discover_schema_for_bytes(bytes, &splitter, &parser, &plan);
        assert_eq!(names(&s2), vec!["a", "b"]);
        assert_eq!(schema_cache_stats(), (1, 1));

        // Different layout: new miss.
        let bytes2 = b"c=1\td=2\n";
        let s3 = discover_schema_for_bytes(bytes2, &splitter, &parser, &plan);
        assert_eq!(names(&s3), vec!["c", "d"]);
        assert_eq!(schema_cache_stats(), (1, 2));

        // Same layout as the first parse but with a different plan:
        // cache hit, but the applied schema differs.
        let mut renamed = ExecutionPlan::new();
        renamed.field_map.insert("a".to_string(), "x".to_string());
        let s4 = discover_schema_for_bytes(bytes, &splitter, &parser, &renamed);
        assert_eq!(names(&s4), vec!["x", "b"]);
        assert_eq!(schema_cache_stats(), (2, 2));
    }
}