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
use std::ops::Range;
use std::path::Path;
use std::sync::Arc;
use arrow::record_batch::RecordBatch;
use crate::budget::{BudgetLedger, StreamStats};
use crate::consumer::CollectingConsumer;
use crate::decoder::{split_points_to_ranges, RecordParser, Splitter};
use crate::engine::TableBuilder;
use crate::input::InputBuffer;
use crate::plan::ExecutionPlan;
use crate::spill::SpillSink;
use crate::Result;
/// A memory budget expressed in bytes.
#[derive(Clone, Copy, Debug)]
pub struct MemoryBudget {
bytes: usize,
strict: bool,
}
impl MemoryBudget {
pub fn new(bytes: usize) -> Self {
Self {
bytes,
strict: false,
}
}
pub fn bytes(&self) -> usize {
self.bytes
}
/// Fail when an executor memory check exceeds its allocation allowance.
/// This does not impose an OS limit on process RSS or adapter-owned memory.
pub fn with_strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn is_strict(&self) -> bool {
self.strict
}
pub(crate) fn share(self, count: usize) -> Self {
Self {
bytes: self.bytes / count.max(1),
..self
}
}
pub(crate) fn check(self, used: usize) -> Result<()> {
if self.strict && used > self.bytes {
return Err(crate::Error::Memory {
used,
limit: self.bytes,
});
}
Ok(())
}
}
/// Internal safeguard: never request more than this many split points, so a
/// pathological row-size estimate cannot explode per-chunk overhead. The
/// batch count is otherwise derived from the budget, input size, and
/// estimated bytes per row; batches may still exceed the budget when the
/// required count exceeds this cap. Increased for 64KB streaming (50GB/64KB
/// ≈ 800k batches); still bounded by file scan cost.
pub const MAX_SPLIT_CHUNKS: usize = 100_000;
/// Minimum rows per emitted batch when the memory budget cannot hold a
/// single row. Batches are oversize in that regime regardless (ordinary
/// mode permits this), and per-row batches would let batch count — and
/// consumer cost — grow linearly with row count.
pub const MIN_ROWS_OVERSIZE_BATCH: usize = 64;
/// Parse an input in bounded batches to stay within a memory budget.
pub struct BoundedExecutor {
budget: MemoryBudget,
split_cap: usize,
}
impl BoundedExecutor {
pub fn new(budget: MemoryBudget) -> Self {
Self {
budget,
split_cap: MAX_SPLIT_CHUNKS,
}
}
/// Override the split cap (default [`MAX_SPLIT_CHUNKS`]). Raising it may be
/// needed for very large files with small budgets, where capped batches
/// would otherwise overshoot the budget.
pub fn with_split_cap(mut self, cap: usize) -> Self {
self.split_cap = cap;
self
}
/// Payload bytes the executor targets per emitted batch. Exported
/// batches are exact-sized, so a single-record batch larger than this
/// is a flagged oversize batch (see [`StreamStats::oversize_batches`]).
fn batch_target_bytes(&self) -> usize {
(self.budget.bytes() / 64).max(1)
}
/// Derive chunk ranges and batch sizing from an in-memory sample of the
/// input. Returns `(chunk_ranges, rows_per_batch, bytes_per_row)`.
///
/// Retained as a planning utility (and exercised by the split-cap test);
/// the single-pass `run_slice_spill` path no longer calls it.
#[allow(dead_code)]
fn plan_chunks(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
min_chunk_bytes: usize,
) -> (Vec<Range<usize>>, usize, usize, bool) {
let bytes_per_row = splitter
.estimate_bytes_per_row(&bytes[..bytes.len().min(65536)])
.max(1);
// Input, growing columns, merge buffers and Arrow output overlap.
let batch_bytes = self.batch_target_bytes();
let total_rows_est = bytes.len() / bytes_per_row;
// When the budget cannot hold even one row, every batch is oversize
// anyway (permitted in ordinary mode), so per-row batches only
// explode the batch count — consumers concatenating thousands of
// single-row batches degrade quadratically. Floor at a minimum
// batch size in that regime, and report the regime so consume_chunks
// does not adapt it back down (the capacity-based adaptive estimate
// is inflated by builder preallocation and collapses to 1).
let oversize = batch_bytes < bytes_per_row;
let min_rows = if oversize { MIN_ROWS_OVERSIZE_BATCH } else { 1 };
let rows_per_batch = (batch_bytes / bytes_per_row)
.max(min_rows)
.min(total_rows_est.max(1));
let num_batches = bytes.len().div_ceil(batch_bytes).max(1);
let capped = num_batches.min(self.split_cap);
let t = std::time::Instant::now();
let split_points = splitter.find_split_points_with(bytes, capped, min_chunk_bytes);
crate::profiling::add(crate::profiling::SPLIT, t.elapsed().as_nanos() as u64);
let chunks = split_points_to_ranges(&split_points, bytes.len());
(chunks, rows_per_batch, bytes_per_row, oversize)
}
/// Parse a whole byte slice in one pass through `SpillSink`, flushing
/// batches to `consumer` as they fill. Replaces the chunked
/// parse-each-chunk-then-`extend` path: no split points, no merge copy.
#[allow(clippy::too_many_arguments)]
fn run_slice_spill<P, C>(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
parser: &P,
plan: Arc<ExecutionPlan>,
consumer: &mut C,
ledger: &mut BudgetLedger,
stats: &mut StreamStats,
) -> Result<()>
where
P: RecordParser,
C: crate::consumer::BatchConsumer,
{
if bytes.is_empty() {
return Ok(());
}
let sample = &bytes[..bytes.len().min(65536)];
let bytes_per_row = splitter.estimate_bytes_per_row(sample).max(1);
let batch_target = self.batch_target_bytes();
// Budget cannot hold one row: batches are oversize regardless, so
// floor the batch size (per-row batches explode consumer cost) and do
// not flush early on capacity.
let oversize = batch_target < bytes_per_row;
let total_rows_est = bytes.len() / bytes_per_row;
let min_rows = if oversize { MIN_ROWS_OVERSIZE_BATCH } else { 1 };
let rows_per_batch = (batch_target / bytes_per_row)
.max(min_rows)
.min(total_rows_est.max(1));
let soft_cap = (self.budget.bytes() / 4).max(1);
let budget = self.budget.share(4);
// The engine never holds more than one batch before spilling, so size
// its preallocation off the batch, not the whole input. Sizing off the
// input would trip a strict budget at construction time.
let mut engine = TableBuilder::with_plan(rows_per_batch.max(64), plan);
engine.set_memory_budget(budget)?;
ledger.set_builders(engine.capacity_bytes());
let mut sink = SpillSink::new(
engine,
consumer,
rows_per_batch,
batch_target,
soft_cap,
oversize,
self.budget,
ledger,
stats,
);
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let t = std::time::Instant::now();
parser.validate(bytes)?;
crate::profiling::add(crate::profiling::VALIDATE, t.elapsed().as_nanos() as u64);
let t = std::time::Instant::now();
let result = parser.parse_chunk_generic(bytes, &mut sink);
crate::profiling::add(crate::profiling::PARSE, t.elapsed().as_nanos() as u64);
result
}))
.unwrap_or_else(|payload| {
let msg = if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"unknown panic".to_string()
};
Err(crate::Error::Parser(format!(
"worker panicked during bounded parse: {msg}"
)))
})?;
sink.finish_run()
}
/// Parse an in-memory byte slice in bounded batches, calling `consumer` per batch.
///
/// Chunks are sliced directly from `bytes`; no file I/O occurs. This is
/// the streaming entry point for adapters holding decompressed data.
/// The budget controls batch sizing; allocator, parser, input, and Arrow
/// overhead can raise process RSS above this target.
pub fn run_bytes_stream<P, C>(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
consumer: &mut C,
) -> Result<()>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
self.run_bytes_stream_with_stats(bytes, splitter, parser, plan, consumer)
.map(|_| ())
}
/// Like [`BoundedExecutor::run_bytes_stream`], but reports a
/// [`StreamStats`] summary including the peak tracked engine memory.
///
/// The input slice is caller-owned, so it is not charged to the ledger;
/// `peak_tracked_bytes` covers builders and in-flight batches only.
pub fn run_bytes_stream_with_stats<P, C>(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
consumer: &mut C,
) -> Result<StreamStats>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
let mut ledger = BudgetLedger::new(self.budget);
let mut stats = StreamStats::default();
self.run_bytes_stream_inner(
bytes,
splitter,
parser,
plan,
consumer,
&mut ledger,
&mut stats,
)?;
stats.peak_tracked_bytes = ledger.peak();
Ok(stats)
}
#[allow(clippy::too_many_arguments)]
fn run_bytes_stream_inner<P, C>(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
consumer: &mut C,
ledger: &mut BudgetLedger,
stats: &mut StreamStats,
) -> Result<()>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
self.run_slice_spill(bytes, splitter, &parser, plan, consumer, ledger, stats)
}
/// Parse an in-memory byte slice in bounded batches, returning one
/// `RecordBatch` per batch.
///
/// Chunks are sliced directly from `bytes`; no file I/O occurs. This is
/// the entry point for adapters holding decompressed or streamed-in data.
pub fn run_bytes<P>(
&self,
bytes: &[u8],
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
) -> Result<Vec<RecordBatch>>
where
P: RecordParser + Clone + Send + Sync,
{
let batches = Vec::new();
let mut consumer = CollectingConsumer(batches);
self.run_bytes_stream(bytes, splitter, parser, plan, &mut consumer)?;
consumer.finish()
}
/// Parse `path` in batches, calling `consumer` per batch (streaming).
///
/// Compressed inputs are decompressed up front and served via
/// `run_bytes_stream`. Uncompressed inputs with `mmap` use the seek-based
/// path with a reusable chunk buffer to keep RSS constant.
pub fn run_stream<P, C>(
&self,
path: &Path,
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
prefault: bool,
consumer: &mut C,
) -> Result<()>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
self.run_stream_with_stats(path, splitter, parser, plan, prefault, consumer)
.map(|_| ())
}
/// Like [`BoundedExecutor::run_stream`], but reports a [`StreamStats`]
/// summary including the peak tracked engine memory.
pub fn run_stream_with_stats<P, C>(
&self,
path: &Path,
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
prefault: bool,
consumer: &mut C,
) -> Result<StreamStats>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
let mut ledger = BudgetLedger::new(self.budget);
let mut stats = StreamStats::default();
let use_mmap = cfg!(feature = "mmap");
let input = InputBuffer::open(path, use_mmap, prefault)?;
#[cfg(feature = "mmap")]
if matches!(input, InputBuffer::Mmap(_)) {
self.run_mapped_stream(
input,
splitter,
parser,
plan,
consumer,
&mut ledger,
&mut stats,
)?;
stats.peak_tracked_bytes = ledger.peak();
return Ok(stats);
}
self.budget.share(4).check(input.len())?;
ledger.set_input(input.len());
self.run_bytes_stream_inner(
input.as_slice(),
splitter,
parser,
plan,
consumer,
&mut ledger,
&mut stats,
)?;
stats.peak_tracked_bytes = ledger.peak();
Ok(stats)
}
/// Parse `path` in batches, returning one `RecordBatch` per batch.
///
/// The caller is responsible for concatenating the batches if a single
/// table is desired.
///
/// Compressed inputs (see [`InputBuffer::open`]) are decompressed up
/// front and served from memory via [`BoundedExecutor::run_bytes`].
/// Uncompressed inputs on platforms with the `mmap` feature retain the
/// seek-based path: the mapping is dropped after planning and each chunk
/// is read from disk on demand, keeping resident memory low.
pub fn run<P>(
&self,
path: &Path,
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
prefault: bool,
) -> Result<Vec<RecordBatch>>
where
P: RecordParser + Clone + Send + Sync,
{
let batches = Vec::new();
let mut consumer = CollectingConsumer(batches);
self.run_stream(path, splitter, parser, plan, prefault, &mut consumer)?;
consumer.finish()
}
/// Streaming path for mapped inputs: parse the mapping directly in one
/// pass. The mapping is retained (no drop-and-re-read copy); the operating
/// system can reclaim clean pages under pressure.
#[cfg(feature = "mmap")]
#[allow(clippy::too_many_arguments)]
fn run_mapped_stream<P, C>(
&self,
input: InputBuffer,
splitter: &dyn Splitter,
parser: P,
plan: Arc<ExecutionPlan>,
consumer: &mut C,
ledger: &mut BudgetLedger,
stats: &mut StreamStats,
) -> Result<()>
where
P: RecordParser + Clone + Send + Sync,
C: crate::consumer::BatchConsumer,
{
let bytes = input.as_slice();
self.run_slice_spill(bytes, splitter, &parser, plan, consumer, ledger, stats)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::decoder::Splitter;
use crate::ExecutionPlan;
struct NewlineSplitter;
impl Splitter for NewlineSplitter {
fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
if from == 0 && !bytes.is_empty() {
return Some(0);
}
bytes[from.saturating_sub(1)..]
.iter()
.position(|&b| b == b'\n')
.map(|i| from + i + 1)
.filter(|&p| p < bytes.len())
}
fn estimate_bytes_per_row(&self, sample: &[u8]) -> usize {
let newlines = sample.iter().filter(|&&b| b == b'\n').count().max(1);
(sample.len() / newlines).max(1)
}
}
fn rows(n: usize) -> Vec<u8> {
"abcdefghij\n".repeat(n).into_bytes()
}
#[test]
fn test_split_cap_limits_chunk_count() {
let data = rows(10_000);
let budget = MemoryBudget::new(1024);
let default_chunks = BoundedExecutor::new(budget)
.plan_chunks(&data, &NewlineSplitter, crate::decoder::MIN_CHUNK_BYTES)
.0
.len();
assert!(
default_chunks > 2,
"uncapped run must split: {default_chunks}"
);
for cap in [1, 2, 3] {
let chunks = BoundedExecutor::new(budget)
.with_split_cap(cap)
.plan_chunks(&data, &NewlineSplitter, crate::decoder::MIN_CHUNK_BYTES)
.0;
assert!(
chunks.len() <= cap.max(1),
"cap {cap} must bound chunk count, got {}",
chunks.len()
);
}
}
/// Newline-delimited `key=value` rows, for bounded-path tests.
#[derive(Clone)]
struct KeyValueParser;
impl crate::decoder::RecordParser for KeyValueParser {
fn validate(&self, bytes: &[u8]) -> crate::Result<()> {
simdutf8::basic::from_utf8(bytes)?;
Ok(())
}
fn parse_chunk(
&self,
bytes: &[u8],
sink: &mut dyn crate::decoder::ColumnarSink,
) -> crate::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_whitespace() {
if let Some((k, v)) = token.split_once('=') {
sink.put_field(k, crate::value::Value::Str(std::borrow::Cow::Borrowed(v)));
}
}
sink.end_row();
}
Ok(())
}
}
/// Records start exactly at every multiple of 12, so chunk boundaries
/// never land mid-record (unlike NewlineSplitter, which is off-by-one
/// for this purpose).
struct AlignedSplitter;
impl Splitter for AlignedSplitter {
fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
let start = from.div_ceil(12) * 12;
(start < bytes.len()).then_some(start)
}
fn estimate_bytes_per_row(&self, _sample: &[u8]) -> usize {
12
}
}
#[test]
fn tiny_budget_below_row_size_keeps_batch_count_bounded() {
// Budget (8 bytes) smaller than a single row (~11 bytes): without the
// oversize floor this emits one batch per row (10_000 batches), which
// degrades quadratically for consumers concatenating batches.
// ~12 bytes/row; budget (8 bytes) cannot hold a single row. Without
// the oversize floor this emits one batch per row (100_000 batches),
// which degrades quadratically for consumers concatenating batches.
let data = "a=1 b=2 c=3\n".repeat(100_000).into_bytes();
let mut consumer = crate::consumer::CollectingConsumer(Vec::new());
let stats = BoundedExecutor::new(MemoryBudget::new(8))
.run_bytes_stream_with_stats(
&data,
&AlignedSplitter,
KeyValueParser,
std::sync::Arc::new(ExecutionPlan::new()),
&mut consumer,
)
.unwrap();
assert_eq!(stats.rows, 100_000, "all rows must be delivered");
assert!(
stats.batches <= 2048,
"batch count must stay far below row count for pathological budgets, got {}",
stats.batches
);
}
#[test]
fn test_default_split_cap_is_max_split_chunks() {
assert_eq!(
BoundedExecutor::new(MemoryBudget::new(1)).split_cap,
MAX_SPLIT_CHUNKS
);
let plan = ExecutionPlan::new().with_max_split_chunks(7);
assert_eq!(plan.max_split_chunks, Some(7));
assert_eq!(ExecutionPlan::new().max_split_chunks, None);
}
}