Skip to main content

datafusion_datasource/
boundary_stream.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Streaming boundary-aligned wrapper for newline-delimited JSON and CSV range reads.
6//!
7//! [`AlignedBoundaryStream`] wraps a raw byte stream and lazily aligns to
8//! record (newline) boundaries, avoiding the need for separate `get_opts`
9//! calls to locate boundary positions.
10
11use std::pin::Pin;
12use std::sync::Arc;
13use std::task::{Context, Poll};
14
15use bytes::Bytes;
16use futures::stream::{BoxStream, Stream};
17use futures::{StreamExt, TryFutureExt};
18use object_store::{GetOptions, GetRange, GetResultPayload, ObjectStore};
19
20/// How far past `raw_end` the initial bounded fetch covers. If the terminating
21/// newline is not found within this window, `ScanningLastTerminator` issues
22/// successive same-sized GETs until the newline is located or EOF is reached.
23pub const END_SCAN_LOOKAHEAD: u64 = 16 * 1024; // 16 KiB
24
25/// Phase of the boundary alignment state machine.
26#[derive(Debug)]
27enum Phase {
28    /// Scanning for the first newline to align the start boundary.
29    ScanningFirstTerminator,
30    /// Passing through aligned data, tracking byte position.
31    FetchingChunks,
32    /// Past the end boundary, scanning for terminating newline.
33    ScanningLastTerminator,
34    /// Stream is exhausted.
35    Done,
36}
37
38/// A stream wrapper that lazily aligns byte boundaries to newline characters.
39///
40/// Given a raw byte stream starting from `fetch_start` (which is `start - 1`
41/// for non-zero starts, or `0`), this stream:
42///
43/// 1. Skips bytes until the first newline is found (start alignment)
44/// 2. Passes through data until the `end` boundary is reached
45/// 3. Continues past `end` to find the terminating newline (end alignment)
46///
47/// When the initial byte stream is exhausted during step 3 and the file has
48/// not been fully read, `ScanningLastTerminator` issues additional bounded
49/// `get_opts` calls (`END_SCAN_LOOKAHEAD` bytes each) until the newline is
50/// found or EOF is reached.
51pub struct AlignedBoundaryStream {
52    inner: BoxStream<'static, object_store::Result<Bytes>>,
53    terminator: u8,
54    /// Effective end boundary. Set to `u64::MAX` when `end >= file_size`
55    /// (last partition), so `FetchingChunks` never transitions to
56    /// `ScanningLastTerminator` and simply streams until EOF is reached.
57    end: u64,
58    /// Cumulative bytes consumed from `inner` (relative to `fetch_start`).
59    bytes_consumed: u64,
60    /// The offset where the current `inner` stream begins.
61    fetch_start: u64,
62    phase: Phase,
63    /// Remainder bytes from `ScanningFirstTerminator` that still need
64    /// end-boundary processing. Consumed by `FetchingChunks` before polling
65    /// `inner`.
66    pending: Option<Bytes>,
67    store: Arc<dyn ObjectStore>,
68    location: object_store::path::Path,
69    /// Total file size; overflow stops when `abs_pos() >= file_size`.
70    file_size: u64,
71}
72
73/// Fetch a bounded byte range from `store` and return it as a stream
74#[expect(
75    clippy::result_large_err,
76    reason = "error type is dictated by the object_store API"
77)]
78async fn get_stream(
79    store: Arc<dyn ObjectStore>,
80    location: object_store::path::Path,
81    range: std::ops::Range<u64>,
82) -> object_store::Result<BoxStream<'static, object_store::Result<Bytes>>> {
83    let opts = GetOptions {
84        range: Some(GetRange::Bounded(range.clone())),
85        ..Default::default()
86    };
87    let result = store.get_opts(&location, opts).await?;
88
89    #[cfg(not(target_arch = "wasm32"))]
90    if let GetResultPayload::File(mut file, _path) = result.payload {
91        use std::io::{Read, Seek, SeekFrom};
92        const CHUNK_SIZE: u64 = 8 * 1024;
93
94        file.seek(SeekFrom::Start(range.start)).map_err(|e| {
95            object_store::Error::Generic {
96                store: "local",
97                source: Box::new(e),
98            }
99        })?;
100
101        return Ok(futures::stream::try_unfold(
102            (file, range.end - range.start),
103            move |(mut file, remaining)| async move {
104                if remaining == 0 {
105                    return Ok(None);
106                }
107                let to_read = remaining.min(CHUNK_SIZE);
108                let cap = usize::try_from(to_read).map_err(|e| {
109                    object_store::Error::Generic {
110                        store: "local",
111                        source: Box::new(e),
112                    }
113                })?;
114
115                let mut buf = Vec::with_capacity(cap);
116                let read =
117                    (&mut file)
118                        .take(to_read)
119                        .read_to_end(&mut buf)
120                        .map_err(|e| object_store::Error::Generic {
121                            store: "local",
122                            source: Box::new(e),
123                        })?;
124                Ok(Some((Bytes::from(buf), (file, remaining - read as u64))))
125            },
126        )
127        .boxed());
128    }
129
130    Ok(result.into_stream())
131}
132
133impl AlignedBoundaryStream {
134    /// Open a ranged byte stream from `store` and return a ready-to-poll
135    /// `AlignedBoundaryStream`.
136    ///
137    /// Issues a single bounded `get_opts` call covering
138    /// `[fetch_start, raw_end + END_SCAN_LOOKAHEAD)`.  If the terminating
139    /// newline is not found within that window, `ScanningLastTerminator`
140    /// automatically issues additional `END_SCAN_LOOKAHEAD`-sized GETs
141    /// via `store` until the newline is found or EOF is reached.
142    #[expect(
143        clippy::result_large_err,
144        reason = "error type is dictated by the object_store API"
145    )]
146    pub async fn new(
147        store: Arc<dyn ObjectStore>,
148        location: object_store::path::Path,
149        raw_start: u64,
150        raw_end: u64,
151        file_size: u64,
152        terminator: u8,
153    ) -> object_store::Result<Self> {
154        if raw_start >= raw_end || raw_start >= file_size {
155            return Ok(Self {
156                inner: futures::stream::empty().boxed(),
157                terminator,
158                end: 0,
159                bytes_consumed: 0,
160                fetch_start: 0,
161                phase: Phase::Done,
162                pending: None,
163                store,
164                location,
165                file_size,
166            });
167        }
168
169        let (fetch_start, phase) = if raw_start == 0 {
170            (0, Phase::FetchingChunks)
171        } else {
172            (raw_start - 1, Phase::ScanningFirstTerminator)
173        };
174
175        let initial_fetch_end = raw_end.saturating_add(END_SCAN_LOOKAHEAD).min(file_size);
176
177        let inner = get_stream(
178            Arc::clone(&store),
179            location.clone(),
180            fetch_start..initial_fetch_end,
181        )
182        .await?;
183
184        // Last partition reads until EOF is reached — no end-boundary scanning needed.
185        let end = if raw_end >= file_size {
186            u64::MAX
187        } else {
188            raw_end
189        };
190
191        Ok(Self {
192            inner,
193            terminator,
194            end,
195            bytes_consumed: 0,
196            fetch_start,
197            phase,
198            pending: None,
199            store,
200            location,
201            file_size,
202        })
203    }
204
205    /// Current absolute position in the file.
206    fn abs_pos(&self) -> u64 {
207        self.fetch_start + self.bytes_consumed
208    }
209}
210
211impl Stream for AlignedBoundaryStream {
212    type Item = object_store::Result<Bytes>;
213
214    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
215        let this = self.get_mut();
216
217        loop {
218            match this.phase {
219                Phase::Done => return Poll::Ready(None),
220
221                Phase::ScanningFirstTerminator => {
222                    // Find the first terminator and skip everything up to
223                    // and including it. Store any remainder in `pending`
224                    // so `FetchingChunks` can apply end-boundary logic to it.
225                    match this.inner.poll_next_unpin(cx) {
226                        Poll::Pending => return Poll::Pending,
227                        Poll::Ready(None) => {
228                            this.phase = Phase::Done;
229                            return Poll::Ready(None);
230                        }
231                        Poll::Ready(Some(Err(e))) => {
232                            this.phase = Phase::Done;
233                            return Poll::Ready(Some(Err(e)));
234                        }
235                        Poll::Ready(Some(Ok(chunk))) => {
236                            this.bytes_consumed += chunk.len() as u64;
237                            if let Some(pos) =
238                                chunk.iter().position(|&b| b == this.terminator)
239                            {
240                                let remainder = chunk.slice((pos + 1)..);
241                                // The aligned start position is where
242                                // data begins after the newline.
243                                let aligned_start =
244                                    this.abs_pos() - remainder.len() as u64;
245                                if aligned_start >= this.end {
246                                    // Start alignment landed at or past
247                                    // the end boundary — no complete
248                                    // lines in this partition's range.
249                                    this.phase = Phase::Done;
250                                    return Poll::Ready(None);
251                                }
252                                if !remainder.is_empty() {
253                                    this.pending = Some(remainder);
254                                }
255                                this.phase = Phase::FetchingChunks;
256                            }
257                        }
258                    }
259                }
260
261                Phase::FetchingChunks => {
262                    // Get the next chunk: pending remainder or inner stream.
263                    let chunk = if let Some(pending) = this.pending.take() {
264                        pending
265                    } else {
266                        match this.inner.poll_next_unpin(cx) {
267                            Poll::Pending => return Poll::Pending,
268                            Poll::Ready(None) => {
269                                this.phase = Phase::Done;
270                                return Poll::Ready(None);
271                            }
272                            Poll::Ready(Some(Err(e))) => {
273                                this.phase = Phase::Done;
274                                return Poll::Ready(Some(Err(e)));
275                            }
276                            Poll::Ready(Some(Ok(chunk))) => {
277                                this.bytes_consumed += chunk.len() as u64;
278                                chunk
279                            }
280                        }
281                    };
282
283                    let pos_after = this.abs_pos();
284
285                    // When end == u64::MAX (last partition), this is always
286                    // true and we stream straight through until EOF is reached.
287                    if pos_after < this.end {
288                        return Poll::Ready(Some(Ok(chunk)));
289                    }
290
291                    if pos_after == this.end {
292                        // Chunk ends exactly at the boundary.
293                        if chunk.last() == Some(&this.terminator) {
294                            this.phase = Phase::Done;
295                        } else {
296                            // No terminator at boundary; any following data
297                            // is past end, so switch to end-scanning.
298                            this.phase = Phase::ScanningLastTerminator;
299                        }
300                        return Poll::Ready(Some(Ok(chunk)));
301                    }
302
303                    // Chunk crosses the end boundary (`pos_after > this.end`).
304                    // Find the first terminator at or after file position
305                    // `this.end - 1` and yield everything up to and
306                    // including it.
307                    //
308                    // `pos_before` is the absolute file position of chunk[0].
309                    // `chunk_in_range_len` is how many bytes of this chunk
310                    // fall within [pos_before, this.end), so chunk[0..
311                    // chunk_in_range_len] is the in-range portion.
312                    // `search_from` is the chunk index of the last in-range
313                    // byte (file position this.end - 1).
314                    //
315                    // Example A: "line1\nline2\nline3\n" (18 bytes), end=8,
316                    // one large chunk arriving with pos_after=18:
317                    //   pos_before         = 18 - 18 = 0
318                    //   chunk_in_range_len =  8 -  0 = 8
319                    //   search_from        = 7   (chunk[7] is file pos 7)
320                    //   chunk[7]='i', chunk[11]='\n' → rel=4
321                    //   yield chunk[..7+4+1] = chunk[..12] = "line1\nline2\n"
322                    //
323                    // Example B: same data, 3-byte chunks, end=8.
324                    // "lin"(pos 0-2) and "e1\n"(pos 3-5) yielded already.
325                    // Now chunk="lin" arrives with pos_after=9:
326                    //   pos_before         = 9 - 3 = 6
327                    //   chunk_in_range_len = 8 - 6 = 2
328                    //   search_from        = 1   (chunk[1] is file pos 7)
329                    //   chunk[1]='i', no '\n' in chunk[1..] → EndScan
330                    let pos_before = pos_after - chunk.len() as u64;
331                    let chunk_in_range_len = (this.end - pos_before) as usize;
332                    let search_from = chunk_in_range_len - 1;
333                    if let Some(rel) = chunk[search_from..]
334                        .iter()
335                        .position(|&b| b == this.terminator)
336                    {
337                        this.phase = Phase::Done;
338                        return Poll::Ready(Some(
339                            Ok(chunk.slice(..=(search_from + rel))),
340                        ));
341                    }
342
343                    // No terminator found; continue scanning in EndScan.
344                    this.phase = Phase::ScanningLastTerminator;
345                    return Poll::Ready(Some(Ok(chunk)));
346                }
347
348                Phase::ScanningLastTerminator => {
349                    match this.inner.poll_next_unpin(cx) {
350                        Poll::Pending => return Poll::Pending,
351                        Poll::Ready(None) => {
352                            // Inner exhausted. Issue the next overflow GET if
353                            // the file has not been fully read yet.
354                            let pos = this.abs_pos();
355                            if pos < this.file_size {
356                                let fetch_end = pos
357                                    .saturating_add(END_SCAN_LOOKAHEAD)
358                                    .min(this.file_size);
359                                let store = Arc::clone(&this.store);
360                                let location = this.location.clone();
361                                this.inner = get_stream(store, location, pos..fetch_end)
362                                    .try_flatten_stream()
363                                    .boxed();
364                                continue;
365                            }
366                            this.phase = Phase::Done;
367                            return Poll::Ready(None);
368                        }
369                        Poll::Ready(Some(Err(e))) => {
370                            this.phase = Phase::Done;
371                            return Poll::Ready(Some(Err(e)));
372                        }
373                        Poll::Ready(Some(Ok(chunk))) => {
374                            this.bytes_consumed += chunk.len() as u64;
375                            if let Some(pos) =
376                                chunk.iter().position(|&b| b == this.terminator)
377                            {
378                                this.phase = Phase::Done;
379                                return Poll::Ready(Some(Ok(chunk.slice(..=pos))));
380                            }
381                            // No terminator yet; yield and keep scanning.
382                            return Poll::Ready(Some(Ok(chunk)));
383                        }
384                    }
385                }
386            }
387        }
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use crate::test_util::{CHUNK_SIZES, make_chunked_store};
395    use futures::TryStreamExt;
396
397    async fn collect_stream(stream: AlignedBoundaryStream) -> Vec<u8> {
398        stream.try_collect::<Vec<Bytes>>().await.unwrap().concat()
399    }
400
401    #[tokio::test]
402    async fn test_start_at_zero_no_end_scan() {
403        // start=0, end >= file_size → pass through everything
404        static DATA: &[u8] = b"line1\nline2\nline3\n";
405        for &cs in CHUNK_SIZES {
406            let (store, path) = make_chunked_store(DATA, cs).await;
407            let s = AlignedBoundaryStream::new(store, path, 0, 100, 18, b'\n')
408                .await
409                .unwrap();
410            assert_eq!(collect_stream(s).await, DATA, "chunk_size={cs}");
411        }
412    }
413
414    #[tokio::test]
415    async fn test_start_aligned_on_newline() {
416        // Data: "line1\nline2\nline3\n"
417        //        0    5 6   11 12  17
418        // start=6 → fetch_start=5. Byte at offset 5 is '\n'.
419        // Should skip the leading '\n' and yield "line2\nline3\n".
420        static DATA: &[u8] = b"line1\nline2\nline3\n";
421        for &cs in CHUNK_SIZES {
422            let (store, path) = make_chunked_store(DATA, cs).await;
423            let s = AlignedBoundaryStream::new(store, path, 6, 100, 18, b'\n')
424                .await
425                .unwrap();
426            assert_eq!(
427                collect_stream(s).await,
428                b"line2\nline3\n",
429                "chunk_size={cs}"
430            );
431        }
432    }
433
434    #[tokio::test]
435    async fn test_start_mid_line() {
436        // start=3, fetch_start=2. Bytes from offset 2: "ne1\nline2\nline3\n".
437        // Should skip "ne1\n" and yield "line2\nline3\n".
438        static DATA: &[u8] = b"line1\nline2\nline3\n";
439        for &cs in CHUNK_SIZES {
440            let (store, path) = make_chunked_store(DATA, cs).await;
441            let s = AlignedBoundaryStream::new(store, path, 3, 100, 18, b'\n')
442                .await
443                .unwrap();
444            assert_eq!(
445                collect_stream(s).await,
446                b"line2\nline3\n",
447                "chunk_size={cs}"
448            );
449        }
450    }
451
452    #[tokio::test]
453    async fn test_end_boundary_mid_line() {
454        // Data: "line1\nline2\nline3\n"
455        //        0    5 6   11 12  17
456        // start=0, end=8. End is mid "line2".
457        // Should yield "line1\nline2\n" (continue past end to find newline).
458        static DATA: &[u8] = b"line1\nline2\nline3\n";
459        for &cs in CHUNK_SIZES {
460            let (store, path) = make_chunked_store(DATA, cs).await;
461            let s = AlignedBoundaryStream::new(store, path, 0, 8, 18, b'\n')
462                .await
463                .unwrap();
464            assert_eq!(
465                collect_stream(s).await,
466                b"line1\nline2\n",
467                "chunk_size={cs}"
468            );
469        }
470    }
471
472    #[tokio::test]
473    async fn test_end_at_eof() {
474        // end >= file_size → no end scanning, pass through everything.
475        static DATA: &[u8] = b"line1\nline2\n";
476        for &cs in CHUNK_SIZES {
477            let (store, path) = make_chunked_store(DATA, cs).await;
478            let s = AlignedBoundaryStream::new(store, path, 0, 12, 12, b'\n')
479                .await
480                .unwrap();
481            assert_eq!(collect_stream(s).await, DATA, "chunk_size={cs}");
482        }
483    }
484
485    #[tokio::test]
486    async fn test_no_newline_in_range() {
487        // start=2, fetch_start=1. Bytes from offset 1: "bcdef" — no newline.
488        // No complete line → empty output.
489        static DATA: &[u8] = b"abcdef";
490        for &cs in CHUNK_SIZES {
491            let (store, path) = make_chunked_store(DATA, cs).await;
492            let s = AlignedBoundaryStream::new(store, path, 2, 6, 6, b'\n')
493                .await
494                .unwrap();
495            assert!(collect_stream(s).await.is_empty(), "chunk_size={cs}");
496        }
497    }
498
499    #[tokio::test]
500    async fn test_start_and_end_alignment() {
501        // Data: "line1\nline2\nline3\nline4\n"
502        //        0    5 6   11 12  17 18  23
503        // start=3, end=14, file_size=24
504        // fetch_start=2, bytes from offset 2: "ne1\nline2\nline3\nline4\n"
505        // Start aligns past "ne1\n"; end=14 is mid "line3", scan to '\n'.
506        // Expected: "line2\nline3\n"
507        static DATA: &[u8] = b"line1\nline2\nline3\nline4\n";
508        for &cs in CHUNK_SIZES {
509            let (store, path) = make_chunked_store(DATA, cs).await;
510            let s = AlignedBoundaryStream::new(store, path, 3, 14, 24, b'\n')
511                .await
512                .unwrap();
513            assert_eq!(
514                collect_stream(s).await,
515                b"line2\nline3\n",
516                "chunk_size={cs}"
517            );
518        }
519    }
520
521    #[tokio::test]
522    async fn test_end_scan_across_chunks() {
523        // end boundary falls before a newline; the terminating newline must be
524        // found by scanning past the end in subsequent chunks.
525        // Data: "line1\nline2\nline3\n" (18 bytes)
526        // start=0, end=7 (mid "line2"), file_size=18 → "line1\nline2\n"
527        static DATA: &[u8] = b"line1\nline2\nline3\n";
528        for &cs in CHUNK_SIZES {
529            let (store, path) = make_chunked_store(DATA, cs).await;
530            let s = AlignedBoundaryStream::new(store, path, 0, 7, 18, b'\n')
531                .await
532                .unwrap();
533            assert_eq!(
534                collect_stream(s).await,
535                b"line1\nline2\n",
536                "chunk_size={cs}"
537            );
538        }
539    }
540
541    #[tokio::test]
542    async fn test_empty_range() {
543        // start >= end — no complete line can exist, regardless of data.
544        static DATA: &[u8] = b"line1\nline2\n";
545        for &cs in CHUNK_SIZES {
546            let (store, path) = make_chunked_store(DATA, cs).await;
547
548            // start > end (non-zero start)
549            let s = AlignedBoundaryStream::new(
550                Arc::clone(&store),
551                path.clone(),
552                10,
553                5,
554                20,
555                b'\n',
556            )
557            .await
558            .unwrap();
559            assert!(
560                collect_stream(s).await.is_empty(),
561                "start>end chunk_size={cs}"
562            );
563
564            // start == end == 0 (zero start, previously unguarded)
565            let s = AlignedBoundaryStream::new(
566                Arc::clone(&store),
567                path.clone(),
568                0,
569                0,
570                12,
571                b'\n',
572            )
573            .await
574            .unwrap();
575            assert!(
576                collect_stream(s).await.is_empty(),
577                "start==end==0 chunk_size={cs}"
578            );
579
580            // start == end (non-zero)
581            let s = AlignedBoundaryStream::new(
582                Arc::clone(&store),
583                path.clone(),
584                6,
585                6,
586                12,
587                b'\n',
588            )
589            .await
590            .unwrap();
591            assert!(
592                collect_stream(s).await.is_empty(),
593                "start==end==6 chunk_size={cs}"
594            );
595        }
596    }
597
598    #[tokio::test]
599    async fn test_start_align_across_chunks() {
600        // The newline needed for start alignment may arrive in any chunk.
601        // fetch_start=0 (start=1). Data: "abcdef\nline2\n" (13 bytes)
602        // Start aligns past "abcdef\n", yielding "line2\n".
603        static DATA: &[u8] = b"abcdef\nline2\n";
604        for &cs in CHUNK_SIZES {
605            let (store, path) = make_chunked_store(DATA, cs).await;
606            let s = AlignedBoundaryStream::new(store, path, 1, 100, 13, b'\n')
607                .await
608                .unwrap();
609            assert_eq!(collect_stream(s).await, b"line2\n", "chunk_size={cs}");
610        }
611    }
612
613    #[tokio::test]
614    async fn test_end_aligned_on_newline() {
615        // end falls right on a newline — line is complete, no end-scan needed.
616        // Data: "line1\nline2\nline3\n"
617        //        0    5 6   11 12  17
618        // start=0, end=6 → byte 5 is '\n' → yield only "line1\n".
619        static DATA: &[u8] = b"line1\nline2\nline3\n";
620        for &cs in CHUNK_SIZES {
621            let (store, path) = make_chunked_store(DATA, cs).await;
622            let s = AlignedBoundaryStream::new(store, path, 0, 6, 18, b'\n')
623                .await
624                .unwrap();
625            assert_eq!(collect_stream(s).await, b"line1\n", "chunk_size={cs}");
626        }
627    }
628
629    #[tokio::test]
630    async fn test_adjacent_partitions_no_overlap() {
631        // Three adjacent partitions over "line1\nline2\nline3\n".
632        // Partition 1: [0, 6), fetch_start=0  → stream full file
633        // Partition 2: [6, 12), fetch_start=5 → stream from offset 5
634        // Partition 3: [12, 18), fetch_start=11 → stream from offset 11
635        static DATA: &[u8] = b"line1\nline2\nline3\n"; // 18 bytes
636
637        for &cs in CHUNK_SIZES {
638            let (store, path) = make_chunked_store(DATA, cs).await;
639            let r1 = collect_stream(
640                AlignedBoundaryStream::new(
641                    Arc::clone(&store),
642                    path.clone(),
643                    0,
644                    6,
645                    18,
646                    b'\n',
647                )
648                .await
649                .unwrap(),
650            )
651            .await;
652            let r2 = collect_stream(
653                AlignedBoundaryStream::new(
654                    Arc::clone(&store),
655                    path.clone(),
656                    6,
657                    12,
658                    18,
659                    b'\n',
660                )
661                .await
662                .unwrap(),
663            )
664            .await;
665            let r3 = collect_stream(
666                AlignedBoundaryStream::new(
667                    Arc::clone(&store),
668                    path.clone(),
669                    12,
670                    18,
671                    18,
672                    b'\n',
673                )
674                .await
675                .unwrap(),
676            )
677            .await;
678
679            assert_eq!(r1, b"line1\n", "p1 chunk_size={cs}");
680            assert_eq!(r2, b"line2\n", "p2 chunk_size={cs}");
681            assert_eq!(r3, b"line3\n", "p3 chunk_size={cs}");
682
683            let mut combined = r1;
684            combined.extend(r2);
685            combined.extend(r3);
686            assert_eq!(combined, DATA, "combined chunk_size={cs}");
687        }
688    }
689
690    #[tokio::test]
691    async fn test_start_align_past_end_returns_empty() {
692        // The first aligned start lands at or past the end boundary.
693        // Data: "abcdefghij\nkl\n" (14 bytes)
694        //        0         10 11 13
695        // Partition [3, 6): start=3, end=6, fetch_start=2
696        // Bytes from offset 2: "cdefghij\nkl\n". First '\n' at offset 10;
697        // aligned start = 11, which is >= end = 6 → empty.
698        static DATA: &[u8] = b"abcdefghij\nkl\n";
699        for &cs in CHUNK_SIZES {
700            let (store, path) = make_chunked_store(DATA, cs).await;
701            let s = AlignedBoundaryStream::new(store, path, 3, 6, 14, b'\n')
702                .await
703                .unwrap();
704            assert!(collect_stream(s).await.is_empty(), "chunk_size={cs}");
705        }
706    }
707
708    #[tokio::test]
709    async fn test_unaligned_partitions_no_overlap() {
710        // Partitions that don't fall on line boundaries.
711        // Data: "aaa\nbbb\nccc\n" (12 bytes)
712        //        0  3 4  7 8  11
713        // Partitions: [0, 5), [5, 10), [10, 12)
714        static DATA: &[u8] = b"aaa\nbbb\nccc\n"; // 12 bytes
715
716        for &cs in CHUNK_SIZES {
717            let (store, path) = make_chunked_store(DATA, cs).await;
718
719            // [0, 5): no start alignment; end=5 mid "bbb", scans to '\n' at 7.
720            let r1 = collect_stream(
721                AlignedBoundaryStream::new(
722                    Arc::clone(&store),
723                    path.clone(),
724                    0,
725                    5,
726                    12,
727                    b'\n',
728                )
729                .await
730                .unwrap(),
731            )
732            .await;
733
734            // [5, 10): fetch_start=4, bytes from offset 4: "bbb\nccc\n".
735            // '\n' at pos 3 → aligned start=8 ("ccc\n"). End=10 mid "ccc",
736            // scans to '\n' at 11 → yields "ccc\n".
737            let r2 = collect_stream(
738                AlignedBoundaryStream::new(
739                    Arc::clone(&store),
740                    path.clone(),
741                    5,
742                    10,
743                    12,
744                    b'\n',
745                )
746                .await
747                .unwrap(),
748            )
749            .await;
750
751            // [10, 12): fetch_start=9, bytes from offset 9: "cc\n".
752            // '\n' at pos 2 → aligned start=12. end=12==file_size → end=MAX.
753            // Remainder after '\n' is empty; Passthrough polls inner → Done.
754            let r3 = collect_stream(
755                AlignedBoundaryStream::new(
756                    Arc::clone(&store),
757                    path.clone(),
758                    10,
759                    12,
760                    12,
761                    b'\n',
762                )
763                .await
764                .unwrap(),
765            )
766            .await;
767
768            assert_eq!(r1, b"aaa\nbbb\n", "p1 chunk_size={cs}");
769            assert_eq!(r2, b"ccc\n", "p2 chunk_size={cs}");
770            assert!(r3.is_empty(), "p3 chunk_size={cs}");
771
772            let mut combined = r1;
773            combined.extend(r2);
774            combined.extend(r3);
775            assert_eq!(combined, DATA, "combined chunk_size={cs}");
776        }
777    }
778
779    #[tokio::test]
780    async fn test_no_trailing_newline() {
781        // Last partition of a file that does not end with a newline.
782        // end >= file_size → this.end = u64::MAX, so Passthrough streams straight
783        // until EOF is reached and yields the final incomplete line as-is.
784        static DATA: &[u8] = b"line1\nline2"; // 11 bytes, no trailing '\n'
785        for &cs in CHUNK_SIZES {
786            let (store, path) = make_chunked_store(DATA, cs).await;
787
788            // Single partition covering the whole file.
789            let s = AlignedBoundaryStream::new(
790                Arc::clone(&store),
791                path.clone(),
792                0,
793                11,
794                11,
795                b'\n',
796            )
797            .await
798            .unwrap();
799            assert_eq!(collect_stream(s).await, DATA, "chunk_size={cs}");
800
801            // Last partition starting mid-file (start=6, fetch_start=5).
802            // Bytes from offset 5: "\nline2".
803            // StartAlign consumes '\n', remainder "line2" is yielded as-is.
804            let s = AlignedBoundaryStream::new(
805                Arc::clone(&store),
806                path.clone(),
807                6,
808                11,
809                11,
810                b'\n',
811            )
812            .await
813            .unwrap();
814            assert_eq!(collect_stream(s).await, b"line2", "tail chunk_size={cs}");
815        }
816    }
817
818    #[tokio::test]
819    async fn test_overflow_fetch() {
820        // First line is longer than 2 * END_SCAN_LOOKAHEAD so the initial
821        // bounded fetch [fetch_start, raw_end + END_SCAN_LOOKAHEAD) does not
822        // reach its newline.  ScanningLastTerminator must issue overflow GETs
823        // to find it.
824        //
825        // Partition [0, 1): raw_end=1, initial_fetch_end=1+16384=16385.
826        // The newline is at byte 32768 > 16385 → one overflow GET required.
827        // Partition [1, file_size): start=1 lands mid line-1; ScanningFirstTerminator
828        // skips to byte 32769, then yields "line2\nline3\n".
829        let long_line: Vec<u8> =
830            std::iter::repeat_n(b'A', 2 * END_SCAN_LOOKAHEAD as usize)
831                .chain(std::iter::once(b'\n'))
832                .collect();
833        let rest = b"line2\nline3\n";
834        let mut data = long_line.clone();
835        data.extend_from_slice(rest);
836        let file_size = data.len() as u64;
837
838        for &cs in CHUNK_SIZES {
839            let (store, path) = make_chunked_store(&data, cs).await;
840
841            let r1 = collect_stream(
842                AlignedBoundaryStream::new(
843                    Arc::clone(&store),
844                    path.clone(),
845                    0,
846                    1,
847                    file_size,
848                    b'\n',
849                )
850                .await
851                .unwrap(),
852            )
853            .await;
854
855            let r2 = collect_stream(
856                AlignedBoundaryStream::new(
857                    Arc::clone(&store),
858                    path.clone(),
859                    1,
860                    file_size,
861                    file_size,
862                    b'\n',
863                )
864                .await
865                .unwrap(),
866            )
867            .await;
868
869            assert_eq!(r1, long_line, "p1 chunk_size={cs}");
870            assert_eq!(r2, rest.as_slice(), "p2 chunk_size={cs}");
871
872            let mut combined = r1;
873            combined.extend(r2);
874            assert_eq!(combined, data, "combined chunk_size={cs}");
875        }
876    }
877}