Skip to main content

itzma_core/
fetch.rs

1//! The shared fetch planner: one policy, one place, that decides
2//! how many requests a ranged read sends and how big each one is.
3//!
4//! Every reader in this crate used to make this call on its own —
5//! `RangedSegment::vectors_of`'s fixed 8 KiB coalescing, `sq8::scan_object`'s
6//! "only merge touching partitions", `index::open`'s fixed 32 KiB guess —
7//! each tuned for `InMemory`/`LocalFileSystem`, where a request costs about
8//! as much as reading its bytes. On real object storage a request has a
9//! time to first byte of tens of milliseconds, so merging nearby ranges and
10//! splitting huge ones into parallel parts is worth far more bytes of slack
11//! than that. `plan` decides the shape; `execute` sends it.
12
13use std::ops::Range;
14
15use bytes::Bytes;
16use futures::stream::{self, StreamExt, TryStreamExt};
17use object_store::path::Path;
18use object_store::{ObjectStore, ObjectStoreExt};
19
20use crate::budget::ReadBudget;
21use crate::error::{ItzmaError, Result};
22
23/// How a ranged read turns "these pieces of this object" into requests.
24/// Chosen per store kind (see [`FetchPolicy::local`], [`FetchPolicy::object_store`])
25/// and set on a [`Namespace`](crate::Namespace) with
26/// [`with_fetch_policy`](crate::Namespace::with_fetch_policy).
27#[non_exhaustive]
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct FetchPolicy {
30    /// Merge two ranges when the gap between them is at most
31    /// `clamp(wanted_so_far / gap_divisor, min_gap, max_gap)`. The floor of
32    /// that clamp.
33    pub min_gap: u64,
34    /// The ceiling of the gap clamp (see [`min_gap`](Self::min_gap)).
35    pub max_gap: u64,
36    /// How much of what has been merged so far the gap limit scales down
37    /// by (see [`min_gap`](Self::min_gap)).
38    pub gap_divisor: u64,
39    /// A merged range longer than this is split into `part_size`-sized grid
40    /// cells (aligned to multiples of `part_size` from the object start),
41    /// fetched concurrently.
42    pub split_above: u64,
43    /// The width of a split grid cell (see [`split_above`](Self::split_above)).
44    pub part_size: u64,
45    /// Round a merged, unsplit range out to a multiple of this, so nearby
46    /// reads from different queries land on the same cache keys. A
47    /// [`Namespace`](crate::Namespace) uses it only after
48    /// [`with_cache`](crate::Namespace::with_cache); without a cache the
49    /// widened bytes would be read again by the next block and shared by
50    /// nothing.
51    pub align: u64,
52}
53
54impl FetchPolicy {
55    /// Tuned for `InMemory` and `LocalFileSystem`, where a request costs
56    /// about as much as the bytes it reads: merge within 8 KiB, never
57    /// split, no extra alignment.
58    pub fn local() -> Self {
59        Self {
60            min_gap: 8 * 1024,
61            max_gap: 64 * 1024,
62            gap_divisor: 8,
63            split_above: u64::MAX,
64            part_size: 1,
65            align: 1,
66        }
67    }
68
69    /// The default: tuned for S3 and other real object stores, where a
70    /// request has tens of milliseconds of time to first byte. `min_gap`
71    /// was measured against MinIO: with a decoded cache it beat 256 KiB on
72    /// requests and bytes at once. The other numbers are starting points that
73    /// still need a run with real latency.
74    pub fn object_store() -> Self {
75        Self {
76            min_gap: 64 * 1024,
77            max_gap: 4 * 1024 * 1024,
78            gap_divisor: 8,
79            split_above: 16 * 1024 * 1024,
80            part_size: 8 * 1024 * 1024,
81            align: 64 * 1024,
82        }
83    }
84
85    /// Set [`min_gap`](Self::min_gap). `#[non_exhaustive]` means no crate
86    /// outside this one can build a `FetchPolicy` with a struct literal
87    /// (even `..base` update syntax), so a caller that wants to tweak one
88    /// field of a default — the Python bridge's `fetch=` kwargs, for
89    /// instance — goes through setters like this one instead.
90    #[must_use]
91    pub fn min_gap(mut self, min_gap: u64) -> Self {
92        self.min_gap = min_gap;
93        self
94    }
95
96    /// Set [`max_gap`](Self::max_gap).
97    #[must_use]
98    pub fn max_gap(mut self, max_gap: u64) -> Self {
99        self.max_gap = max_gap;
100        self
101    }
102
103    /// Set [`gap_divisor`](Self::gap_divisor).
104    #[must_use]
105    pub fn gap_divisor(mut self, gap_divisor: u64) -> Self {
106        self.gap_divisor = gap_divisor;
107        self
108    }
109
110    /// Set [`split_above`](Self::split_above).
111    #[must_use]
112    pub fn split_above(mut self, split_above: u64) -> Self {
113        self.split_above = split_above;
114        self
115    }
116
117    /// Set [`part_size`](Self::part_size).
118    #[must_use]
119    pub fn part_size(mut self, part_size: u64) -> Self {
120        self.part_size = part_size;
121        self
122    }
123
124    /// Set [`align`](Self::align).
125    #[must_use]
126    pub fn align(mut self, align: u64) -> Self {
127        self.align = align;
128        self
129    }
130}
131
132impl Default for FetchPolicy {
133    fn default() -> Self {
134        Self::object_store()
135    }
136}
137
138/// One physical request this plan will send.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub(crate) struct Req {
141    pub(crate) range: Range<u64>,
142}
143
144/// One candidate shape for a plan: the requests it would send, for each
145/// wanted range (same order, same length as the `Plan`'s own `wanted`)
146/// which request(s) in `requests` cover it, and the total bytes it would
147/// cost. Almost always one request per wanted range; more than one only
148/// when that wanted range's own group was split because it was longer
149/// than `split_above` (the whole-object read case, see `whole_object`).
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub(crate) struct Candidate {
152    /// In object order.
153    pub(crate) requests: Vec<Req>,
154    /// `owners[i]` is the (in-order) list of indices into `requests` that
155    /// together cover `wanted[i]`.
156    pub(crate) owners: Vec<Vec<usize>>,
157    pub(crate) total_bytes: u64,
158}
159
160/// The merged way to fetch `wanted` (nearby ranges share a request), and
161/// the means to build the unmerged way on demand. Pure, deterministic, no
162/// I/O — the choice between the two needs a real, atomic reservation
163/// against the budget to be race-free under concurrent callers sharing one
164/// (see `choose`), so it isn't made here. The unmerged candidate is built
165/// only when the merged one doesn't fit, which is the rare case: building
166/// both up front cost every small read a second candidate it almost never
167/// used (the copy and overhead work after the first measurement).
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub(crate) struct Plan {
170    pub(crate) merged: Candidate,
171    pub(crate) unmerged: Unmerged,
172    /// The original wanted ranges, same order both candidates' `owners`
173    /// index by. A physical request is almost always bigger than the
174    /// wanted range it covers (that's the whole point of merging), so
175    /// `execute` needs this to know where inside the fetched bytes the
176    /// wanted slice starts.
177    pub(crate) wanted: Vec<Range<u64>>,
178}
179
180/// What [`Plan::unmerged`] needs to build the unmerged candidate later:
181/// the policy, the wanted ranges' sorted visiting order, and the object's
182/// size. Owned, so it can outlive the borrow `plan` was built from.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub(crate) struct Unmerged {
185    policy: FetchPolicy,
186    order: Vec<usize>,
187    object_size: u64,
188}
189
190impl Unmerged {
191    /// The unmerged candidate for `wanted`, the same ranges the `Plan` was
192    /// built from.
193    pub(crate) fn build(&self, wanted: &[Range<u64>]) -> Candidate {
194        build_candidate(&self.policy, wanted, &self.order, self.object_size, false)
195    }
196}
197
198fn gap_limit(policy: &FetchPolicy, wanted_so_far: u64) -> u64 {
199    // Order-tolerant: `u64::clamp` panics if its own min exceeds its max,
200    // and a misconfigured policy (min_gap above max_gap) is reachable from
201    // outside this crate — FetchPolicy's setters are public, and the
202    // Python bridge builds one from six independent kwargs with no
203    // cross-field validation. Degrade to the narrower of the two instead
204    // of panicking.
205    let (lo, hi) = (
206        policy.min_gap.min(policy.max_gap),
207        policy.min_gap.max(policy.max_gap),
208    );
209    (wanted_so_far / policy.gap_divisor.max(1)).clamp(lo, hi)
210}
211
212/// Merge `wanted` (visited in `order`) into non-overlapping groups,
213/// proportionally, per `gap_limit`. Returns the groups and, for each
214/// position in `order`, which group it landed in.
215fn merge(
216    policy: &FetchPolicy,
217    wanted: &[Range<u64>],
218    order: &[usize],
219) -> (Vec<Range<u64>>, Vec<usize>) {
220    let mut groups: Vec<Range<u64>> = Vec::new();
221    let mut owner_of_sorted = Vec::with_capacity(order.len());
222    let mut wanted_so_far = 0u64;
223    for &i in order {
224        let r = wanted[i].clone();
225        wanted_so_far += r.end.saturating_sub(r.start);
226        let limit = gap_limit(policy, wanted_so_far);
227        match groups.last_mut() {
228            Some(last) if r.start.saturating_sub(last.end) <= limit => {
229                last.end = last.end.max(r.end);
230                owner_of_sorted.push(groups.len() - 1);
231            }
232            _ => {
233                groups.push(r);
234                owner_of_sorted.push(groups.len() - 1);
235            }
236        }
237    }
238    (groups, owner_of_sorted)
239}
240
241/// Grid-aligned parts of `range`, each `part_size` wide and aligned to a
242/// multiple of `part_size` measured from object offset 0, clipped to
243/// `range`. The grid (not the range's own start) decides the boundaries, so
244/// two different reads of overlapping regions land on the same parts.
245fn split(range: &Range<u64>, part_size: u64) -> Vec<Range<u64>> {
246    if part_size == 0 || range.end <= range.start {
247        return vec![range.clone()];
248    }
249    let first_cell = range.start / part_size;
250    let last_cell = (range.end - 1) / part_size;
251    (first_cell..=last_cell)
252        .map(|cell| {
253            let start = (cell * part_size).max(range.start);
254            let end = ((cell + 1) * part_size).min(range.end);
255            start..end
256        })
257        .collect()
258}
259
260fn align_out(range: &Range<u64>, align: u64, object_size: u64) -> Range<u64> {
261    if align <= 1 {
262        return range.clone();
263    }
264    let start = (range.start / align) * align;
265    let end = (range.end.div_ceil(align) * align).min(object_size);
266    start..end
267}
268
269/// Coalesce already-sorted, aligned groups that now touch or overlap: each
270/// is widened independently by [`align_out`], so when `align` is bigger
271/// than the gap [`merge`] used to keep two groups apart, their aligned
272/// extents can collide into two physical requests for the same or
273/// overlapping bytes. Returns the coalesced groups and, for each input
274/// group's position, which output group it landed in — the same shape
275/// [`merge`] returns, so a caller remaps through it the same way.
276fn coalesce_aligned(aligned: &[Range<u64>]) -> (Vec<Range<u64>>, Vec<usize>) {
277    let mut groups: Vec<Range<u64>> = Vec::with_capacity(aligned.len());
278    let mut remap = Vec::with_capacity(aligned.len());
279    for g in aligned {
280        match groups.last_mut() {
281            Some(last) if g.start <= last.end => {
282                last.end = last.end.max(g.end);
283                remap.push(groups.len() - 1);
284            }
285            _ => {
286                groups.push(g.clone());
287                remap.push(groups.len() - 1);
288            }
289        }
290    }
291    (groups, remap)
292}
293
294/// Both candidate shapes for fetching `wanted` (any order, may overlap):
295/// merged (nearby ranges share a request) and unmerged (only exactly
296/// touching ones do). Never merges across `object_size`. Pure,
297/// deterministic, no I/O, no budget involved — `execute` chooses between
298/// the two candidates atomically against the real budget.
299///
300/// # Panics
301///
302/// Debug builds panic if a wanted range runs past `object_size`: that is a
303/// caller bug (every reader must clip to its own object's size first), not
304/// something the planner should paper over.
305pub(crate) fn plan(policy: &FetchPolicy, wanted: &[Range<u64>], object_size: u64) -> Plan {
306    if wanted.is_empty() {
307        let empty = Candidate {
308            requests: Vec::new(),
309            owners: Vec::new(),
310            total_bytes: 0,
311        };
312        return Plan {
313            merged: empty,
314            unmerged: Unmerged {
315                policy: *policy,
316                order: Vec::new(),
317                object_size,
318            },
319            wanted: Vec::new(),
320        };
321    }
322    debug_assert!(
323        wanted.iter().all(|r| r.end <= object_size),
324        "a wanted range runs past the object's own size"
325    );
326
327    let mut order: Vec<usize> = (0..wanted.len()).collect();
328    order.sort_unstable_by_key(|&i| (wanted[i].start, wanted[i].end));
329
330    Plan {
331        merged: build_candidate(policy, wanted, &order, object_size, true),
332        unmerged: Unmerged {
333            policy: *policy,
334            order,
335            object_size,
336        },
337        wanted: wanted.to_vec(),
338    }
339}
340
341/// One candidate shape for `wanted`, visited in `order`: merged (nearby
342/// ranges share a request, aligned out, split when long) or unmerged (each
343/// wanted range its own group, only exactly touching ones combined).
344fn build_candidate(
345    policy: &FetchPolicy,
346    wanted: &[Range<u64>],
347    order: &[usize],
348    object_size: u64,
349    merge_groups: bool,
350) -> Candidate {
351    let (groups, owner_of_sorted) = if merge_groups {
352        merge(policy, wanted, order)
353    } else {
354        // "Unmerged": each wanted range is its own group, only exactly
355        // touching ones combined (gap 0), no proportional growth.
356        let flat = FetchPolicy {
357            min_gap: 0,
358            max_gap: 0,
359            gap_divisor: 1,
360            ..*policy
361        };
362        merge(&flat, wanted, order)
363    };
364    // `group_remap[g]` is where `merge`'s original group `g` ended up
365    // after alignment: identity when nothing was aligned, but when it
366    // was, two originally separate groups can collide once widened
367    // (Finding 9) and `coalesce_aligned` folds them into one, which
368    // `owners` below must follow through `group_remap`, not the raw
369    // `owner_of_sorted` index.
370    let (aligned, group_remap): (Vec<Range<u64>>, Vec<usize>) = if merge_groups {
371        let raw: Vec<Range<u64>> = groups
372            .iter()
373            .map(|g| align_out(g, policy.align, object_size))
374            .collect();
375        coalesce_aligned(&raw)
376    } else {
377        let identity = (0..groups.len()).collect();
378        (groups, identity)
379    };
380    let mut requests = Vec::new();
381    // Each group's requests are a contiguous run of `requests`, so a
382    // range of indices says which ones, with no `Vec` per group.
383    let mut group_to_requests: Vec<Range<usize>> = Vec::with_capacity(aligned.len());
384    for g in &aligned {
385        let parts = if g.end - g.start > policy.split_above {
386            split(g, policy.part_size)
387        } else {
388            vec![g.clone()]
389        };
390        let start_idx = requests.len();
391        requests.extend(parts.into_iter().map(|range| Req { range }));
392        group_to_requests.push(start_idx..requests.len());
393    }
394    // Each wanted range's owner is only the part(s) of its group it
395    // actually overlaps, not the whole group: the common case is one
396    // request (no split), and a wanted range whose own group was split
397    // owns just the one or two parts its own bytes fall into — not
398    // every part of that group, which execute() would otherwise
399    // concatenate per wanted range regardless of how little of it that
400    // range needed.
401    let mut owners = vec![Vec::new(); wanted.len()];
402    for (pos, &i) in order.iter().enumerate() {
403        let group = group_remap[owner_of_sorted[pos]];
404        let w = &wanted[i];
405        // Strict overlap for a real (non-empty) wanted range — `<` on
406        // both sides, so a range merely touching a part's boundary
407        // isn't wrongly counted as overlapping it. A zero-row SQ8
408        // partition's byte range is legitimately empty (`start ==
409        // end`), and no part strictly overlaps a point, so that case
410        // falls back to inclusive point containment instead — every
411        // such group collapses to exactly one part covering it (an
412        // empty range can't be split), so this never picks more than
413        // what's already there.
414        let overlaps = |req: &Range<u64>| {
415            if w.start == w.end {
416                req.start <= w.start && w.start <= req.end
417            } else {
418                req.start < w.end && w.start < req.end
419            }
420        };
421        owners[i] = group_to_requests[group]
422            .clone()
423            .filter(|&r| overlaps(&requests[r].range))
424            .collect();
425    }
426    let total_bytes = requests.iter().map(|r| r.range.end - r.range.start).sum();
427    Candidate {
428        requests,
429        owners,
430        total_bytes,
431    }
432}
433
434/// How many requests one reader keeps in flight at once.
435pub(crate) const FETCH_CONCURRENCY: usize = 16;
436
437/// Pick between `plan`'s two candidates, send the winner's requests
438/// (concurrently), and return one slice per originally wanted range, in
439/// wanted order — zero-copy when that range's own group was not split,
440/// one concatenation when it was (see `whole_object`).
441///
442/// The choice is one atomic reservation against `budget`
443/// ([`ReadBudget::try_reserve`]), not a snapshot-then-decide: merging
444/// nearby ranges is tried first (fewer requests), falling back to the
445/// unmerged shape if that alone doesn't fit — a read never fails for the
446/// planner's sake — and if *neither* fits, a real [`ReadBudget::charge`]
447/// for the (smaller) unmerged total reports an honest, accurate refusal.
448/// Deciding from a `remaining()` snapshot and charging later would leave a
449/// window where a concurrent caller sharing the same budget charges in
450/// between, making the snapshot the decision was made on already stale by
451/// the time it is acted on — reserving atomically closes that window: at
452/// most one concurrent decision can ever win a given byte of budget.
453///
454/// A missing object is [`ItzmaError::Storage`] here; callers that need it
455/// reported as damage (`segment::missing`, `index::missing`, ...) do that
456/// translation themselves, as they do today for every other fetch.
457pub(crate) async fn execute(
458    store: &dyn ObjectStore,
459    budget: &ReadBudget,
460    path: &Path,
461    plan: Plan,
462) -> Result<Vec<Bytes>> {
463    if plan.wanted.is_empty() {
464        return Ok(Vec::new());
465    }
466    let Plan {
467        merged,
468        unmerged,
469        wanted,
470    } = plan;
471    let chosen = choose(budget, path, merged, || unmerged.build(&wanted))?;
472    if chosen.requests.is_empty() {
473        return Ok(Vec::new());
474    }
475    let fetched = fetch_parts(store, path, &chosen.requests).await?;
476    chosen
477        .owners
478        .iter()
479        .zip(&wanted)
480        .map(|(parts, w)| {
481            let base = chosen.requests[parts[0]].range.start;
482            let local_start = (w.start - base) as usize;
483            let local_len = (w.end - w.start) as usize;
484            let whole = if parts.len() == 1 {
485                fetched[parts[0]].clone()
486            } else {
487                let pieces: Vec<Bytes> = parts.iter().map(|&p| fetched[p].clone()).collect();
488                concat(&pieces)
489            };
490            // Checked, not a direct `Bytes::slice` (which panics out of
491            // bounds): a store that returns fewer bytes than its own
492            // response claimed is a store bug, and library code never
493            // panics on one (library code does not `unwrap`, decoders
494            // never panic).
495            if local_start + local_len > whole.len() {
496                return Err(short_read(path, whole.len(), local_start + local_len));
497            }
498            Ok(whole.slice(local_start..local_start + local_len))
499        })
500        .collect()
501}
502
503/// [`execute`], but each response's body is handed to `sink` as it arrives
504/// instead of being collected: `sink(wanted, offset, bytes)` gets the bytes of
505/// wanted range `wanted` that start `offset` bytes into it. A caller that
506/// decodes as it goes holds its decoded result and one chunk, not the fetched
507/// bytes beside it. The requests run concurrently and `sink` is called from
508/// one at a time, in no particular order across requests; every byte of every
509/// wanted range is handed over exactly once, unless an error comes back.
510///
511/// # Errors
512///
513/// As for [`execute`]; a store that sends fewer or more bytes than a
514/// request's range is [`short_read`].
515pub(crate) async fn execute_into<F>(
516    store: &dyn ObjectStore,
517    budget: &ReadBudget,
518    path: &Path,
519    plan: Plan,
520    sink: F,
521) -> Result<()>
522where
523    F: FnMut(usize, usize, &[u8]) + Send,
524{
525    if plan.wanted.is_empty() {
526        return Ok(());
527    }
528    let Plan {
529        merged,
530        unmerged,
531        wanted,
532    } = plan;
533    let chosen = choose(budget, path, merged, || unmerged.build(&wanted))?;
534    // Each request's wanted ranges, by start, so a chunk visits only the
535    // ones that can overlap it.
536    let mut covers: Vec<Vec<usize>> = vec![Vec::new(); chosen.requests.len()];
537    for (w, parts) in chosen.owners.iter().enumerate() {
538        for &r in parts {
539            covers[r].push(w);
540        }
541    }
542    for list in &mut covers {
543        list.sort_by_key(|&w| wanted[w].start);
544    }
545    let sink = std::sync::Mutex::new(sink);
546    let ranges: Vec<Range<u64>> = chosen.requests.iter().map(|r| r.range.clone()).collect();
547    stream::iter(0..ranges.len())
548        .map(|r| stream_into(store, path, &ranges[r], &covers[r], &wanted, &sink))
549        .buffer_unordered(FETCH_CONCURRENCY)
550        .try_collect::<()>()
551        .await
552}
553
554/// One request of [`execute_into`]: stream `range` and hand each chunk's
555/// overlap with the wanted ranges in `covers` to `sink`.
556async fn stream_into<F>(
557    store: &dyn ObjectStore,
558    path: &Path,
559    range: &Range<u64>,
560    covers: &[usize],
561    wanted: &[Range<u64>],
562    sink: &std::sync::Mutex<F>,
563) -> Result<()>
564where
565    F: FnMut(usize, usize, &[u8]) + Send,
566{
567    if range.end <= range.start {
568        return Ok(());
569    }
570    let options = object_store::GetOptions {
571        range: Some(range.clone().into()),
572        ..object_store::GetOptions::default()
573    };
574    let mut body = store
575        .get_opts(path, options)
576        .await
577        .map_err(ItzmaError::from)?
578        .into_stream();
579    let need = range.end - range.start;
580    let mut pos = range.start;
581    // Every wanted range before `first` ended before `pos`: chunks arrive in
582    // order, so it only moves forward.
583    let mut first = 0;
584    while let Some(chunk) = body.next().await {
585        let chunk = chunk.map_err(ItzmaError::from)?;
586        let end = pos + chunk.len() as u64;
587        if end > range.end {
588            return Err(short_read(
589                path,
590                (end - range.start) as usize,
591                need as usize,
592            ));
593        }
594        while first < covers.len() && wanted[covers[first]].end <= pos {
595            first += 1;
596        }
597        let mut sink = sink
598            .lock()
599            .unwrap_or_else(std::sync::PoisonError::into_inner);
600        for &w in covers[first..]
601            .iter()
602            .take_while(|&&w| wanted[w].start < end)
603        {
604            let from = wanted[w].start.max(pos);
605            let to = wanted[w].end.min(end);
606            if from < to {
607                let bytes = &chunk[(from - pos) as usize..(to - pos) as usize];
608                sink(w, (from - wanted[w].start) as usize, bytes);
609            }
610        }
611        drop(sink);
612        pos = end;
613    }
614    if pos != range.end {
615        return Err(short_read(
616            path,
617            (pos - range.start) as usize,
618            need as usize,
619        ));
620    }
621    Ok(())
622}
623
624/// Pick between a merged and an unmerged candidate and reserve its bytes.
625/// The choice is one atomic reservation against `budget`
626/// ([`ReadBudget::try_reserve`]), not a snapshot-then-decide: merging is
627/// tried first (fewer requests), falling back to the unmerged shape if that
628/// alone doesn't fit — a read never fails for the planner's sake — and if
629/// *neither* fits, a real [`ReadBudget::charge`] for the (smaller) unmerged
630/// total reports an honest, accurate refusal. Deciding from a `remaining()`
631/// snapshot and charging later would leave a window where a concurrent
632/// caller sharing the same budget charges in between, making the snapshot
633/// the decision was made on already stale by the time it is acted on.
634fn choose(
635    budget: &ReadBudget,
636    path: &Path,
637    merged: Candidate,
638    unmerged: impl FnOnce() -> Candidate,
639) -> Result<Candidate> {
640    if budget.try_reserve(merged.total_bytes) {
641        return Ok(merged);
642    }
643    let unmerged = unmerged();
644    if budget.try_reserve(unmerged.total_bytes) {
645        return Ok(unmerged);
646    }
647    // Neither fits on its own: charge the true minimum (the unmerged total
648    // can never exceed the merged one) for an honest refusal, sticky like
649    // every other charge in this crate. This can only succeed if budget
650    // freed up between the two `try_reserve` calls above and this one, in
651    // which case the unmerged plan genuinely does fit now and proceeding
652    // with it is correct.
653    budget.charge(path.as_ref(), unmerged.total_bytes)?;
654    Ok(unmerged)
655}
656
657/// Send `requests` concurrently and return their bytes in request order.
658/// No per-request `budget.charge` here: the whole total was already
659/// reserved by [`choose`], specifically so this loop can run concurrently
660/// without each request racing a sibling task's charges.
661pub(crate) async fn fetch_parts(
662    store: &dyn ObjectStore,
663    path: &Path,
664    requests: &[Req],
665) -> Result<Vec<Bytes>> {
666    // Collected into an owned Vec before the stream, not `.iter().map(...)`
667    // taken straight into `stream::iter`: a closure whose parameter borrows
668    // from `requests` inline like that is inferred higher-ranked, which
669    // then fails "Send is not general enough" at every caller that spawns
670    // the future this builds (see `segment::read_all`'s own comment on the
671    // same shape of fix).
672    let ranges: Vec<Range<u64>> = requests.iter().map(|r| r.range.clone()).collect();
673    stream::iter(ranges)
674        .map(|range| async move {
675            if range.end <= range.start {
676                return Ok(Bytes::new());
677            }
678            store.get_range(path, range).await.map_err(ItzmaError::from)
679        })
680        .buffered(FETCH_CONCURRENCY)
681        .try_collect()
682        .await
683}
684
685/// One copy of `parts`, concatenated in order. A single part is returned
686/// as is, without a copy.
687fn concat(parts: &[Bytes]) -> Bytes {
688    if let [only] = parts {
689        return only.clone();
690    }
691    let mut out = Vec::with_capacity(parts.iter().map(Bytes::len).sum());
692    for part in parts {
693        out.extend_from_slice(part);
694    }
695    Bytes::from(out)
696}
697
698/// The error for a store that returned fewer bytes than its own response
699/// claimed. Library code never panics on a store bug, so this is an error.
700fn short_read(path: &Path, have: usize, need: usize) -> ItzmaError {
701    ItzmaError::Storage(object_store::Error::Generic {
702        store: "fetch",
703        source: format!(
704            "{}: the store returned {have} bytes, fewer than the {need} a ranged read needed",
705            path.as_ref()
706        )
707        .into(),
708    })
709}
710
711/// The discovery probe's floor, regardless of policy: `policy.part_size`
712/// alone would make `local()` (`part_size: 1`) send a second request for
713/// the head of any object bigger than a single byte, defeating `local()`'s
714/// whole purpose of matching the earlier one-GET behavior. Matches
715/// `RangedSegment::open`'s own `TAIL_GUESS` — the same trick, the same
716/// reasoning: most test- and namespace-sized objects fit in one response.
717const DISCOVERY_PROBE_FLOOR: u64 = 64 * 1024;
718
719/// Fetch a whole object, learning its size from the first request instead
720/// of a separate HEAD — the same trick `RangedSegment::open` already uses
721/// for a segment's trailer: a suffix request returns the object's real
722/// size in its response even when the object is smaller than asked, in
723/// which case that one response already holds everything. Otherwise the
724/// rest (`0..size - probe`) is planned and executed like any other wanted
725/// range, splitting into parallel parts if it is big enough, and the two
726/// pieces are concatenated in object order.
727pub(crate) async fn whole_object(
728    store: &dyn ObjectStore,
729    budget: &ReadBudget,
730    policy: &FetchPolicy,
731    path: &Path,
732) -> Result<Bytes> {
733    use object_store::{GetOptions, GetRange};
734
735    let probe = policy.part_size.max(DISCOVERY_PROBE_FLOOR);
736    let options = GetOptions {
737        range: Some(GetRange::Suffix(probe)),
738        ..GetOptions::default()
739    };
740    // Charged after the request, not before: its real cost (the response's
741    // own range, which can be smaller than `probe` for a small object) is
742    // only known once the headers are in hand, and a missing object — the
743    // common, unexceptional case for an optional object — must cost nothing, the same way every other fetch in this crate
744    // charges nothing for an object that was never there to read.
745    let got = store
746        .get_opts(path, options)
747        .await
748        .map_err(ItzmaError::from)?;
749    let size = got.meta.size;
750    let tail_start = got.range.start;
751    budget.charge(path.as_ref(), got.range.end - tail_start)?;
752    // The tail's chunks are kept as they arrive, not collected into one
753    // buffer first: the final object is assembled below with one copy of
754    // each byte, instead of one copy into a tail buffer and another into
755    // the object.
756    let mut pieces: Vec<Bytes> = got
757        .into_stream()
758        .try_collect()
759        .await
760        .map_err(ItzmaError::from)?;
761
762    if tail_start == 0 {
763        // The probe already covered the whole object.
764        return assemble(path, pieces, size);
765    }
766
767    #[allow(clippy::single_range_in_vec_init)] // one wanted range: the head before the tail
768    let wanted = [0..tail_start];
769    // Bounded by `tail_start`, not the object's real `size`: the merged
770    // candidate's own alignment (`align_out`) clips a group's end to
771    // whatever "object size" it is given, so planning against the real,
772    // bigger `size` here let an aligned head group round its end straight
773    // into the tail region the probe above already fetched — re-fetching
774    // and re-charging the overlap even though the answer stayed correct
775    // (Finding 8). The head's own address space ends at `tail_start` by
776    // construction, so that is its true bound.
777    let planned = plan(policy, &wanted, tail_start);
778    let chosen = choose(budget, path, planned.merged, || {
779        planned.unmerged.build(&wanted)
780    })?;
781    // The chosen requests cover exactly `0..tail_start`: the head is
782    // planned against `tail_start` (see above), so every part is inside it
783    // and in object order, and concatenating them is the head.
784    let head = fetch_parts(store, path, &chosen.requests).await?;
785    let mut all = head;
786    all.append(&mut pieces);
787    assemble(path, all, size)
788}
789
790/// Concatenate `parts` (object order) into one object of `size` bytes,
791/// copying each byte once. A single part is returned without a copy. A
792/// store that delivers a different number of bytes than it declared is
793/// [`short_read`], not a panic.
794fn assemble(path: &Path, parts: Vec<Bytes>, size: u64) -> Result<Bytes> {
795    let have: usize = parts.iter().map(Bytes::len).sum();
796    if have as u64 != size {
797        return Err(short_read(path, have, size as usize));
798    }
799    Ok(concat(&parts))
800}
801
802#[cfg(test)]
803#[allow(clippy::single_range_in_vec_init)] // a one-range `wanted` slice is a normal, valid test case here, not a mistake
804mod tests {
805    use super::*;
806
807    fn policy(
808        min_gap: u64,
809        max_gap: u64,
810        gap_divisor: u64,
811        split_above: u64,
812        part_size: u64,
813        align: u64,
814    ) -> FetchPolicy {
815        FetchPolicy {
816            min_gap,
817            max_gap,
818            gap_divisor,
819            split_above,
820            part_size,
821            align,
822        }
823    }
824
825    #[test]
826    fn object_store_merges_within_64_kib() {
827        // Measured against MinIO: with a
828        // decoded cache and fresh queries, a 64 KiB floor beat 256 KiB on
829        // requests and bytes at once in every configuration measured.
830        assert_eq!(
831            FetchPolicy::object_store(),
832            policy(64 << 10, 4 << 20, 8, 16 << 20, 8 << 20, 64 << 10)
833        );
834    }
835
836    #[test]
837    fn two_ranges_within_the_gap_merge_into_one_request() {
838        // min_gap 8, so a gap of exactly 8 merges, one more byte does not.
839        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
840        let touching = plan(&p, &[0..4, 12..16], 1000);
841        assert_eq!(touching.merged.requests.len(), 1);
842        assert_eq!(touching.merged.requests[0].range, 0..16);
843
844        let apart = plan(&p, &[0..4, 13..16], 1000);
845        assert_eq!(apart.merged.requests.len(), 2);
846    }
847
848    #[test]
849    fn a_request_never_crosses_the_object_end() {
850        let p = policy(1024, 1024, 1, u64::MAX, 1, 1);
851        let plan = plan(&p, &[0..10], 10);
852        assert_eq!(plan.merged.requests[0].range, 0..10);
853    }
854
855    #[test]
856    fn a_misconfigured_policy_with_min_gap_above_max_gap_never_panics() {
857        // Reachable from outside this crate (FetchPolicy's setters are
858        // public, and the Python bridge builds one from six independent
859        // optional kwargs with no cross-field validation), so this must
860        // degrade gracefully, not panic — `u64::clamp` panics if its own
861        // min exceeds its max.
862        let p = policy(1 << 20, 8, 1, u64::MAX, 1, 1); // min_gap way above max_gap
863        let plan = plan(&p, &[0..4, 1_000_000..1_000_004], 2_000_000);
864        assert!(!plan.merged.requests.is_empty());
865    }
866
867    #[test]
868    fn an_empty_wanted_range_still_gets_an_owner_not_an_empty_list() {
869        // A zero-row SQ8 partition's byte range is legitimately empty
870        // (start == end). A strict overlap test (`start < end`) never
871        // matches an empty range against anything, including its own
872        // single-part group, leaving `owners[i]` empty — which panics in
873        // `execute` on `parts[0]`. Caught by a real integration test
874        // (tests/index.rs's `a_segment_with_no_documents_is_indexed_when_asked`)
875        // going through sq8::fetch_wave with a genuinely empty partition.
876        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
877        let plan = plan(&p, &[5..5], 10);
878        assert_eq!(plan.merged.owners, vec![vec![0]]);
879    }
880
881    #[test]
882    fn a_small_wanted_range_owns_only_the_parts_it_overlaps_not_the_whole_group() {
883        // Four tiny ranges, far enough apart that nothing would merge under
884        // a tight policy, forced into one group by a huge gap limit. That
885        // group is wider than split_above (100) with part_size 40, so it
886        // splits into 4 grid cells: 0..40, 40..80, 80..120, 120..130. Each
887        // tiny wanted range sits entirely inside exactly one cell and must
888        // own only that cell — not all 4, which is what execute() would
889        // otherwise concatenate per wanted range.
890        let p = policy(1 << 20, 1 << 20, 1, 100, 40, 1);
891        let wanted = [5..6, 45..46, 85..86, 125..126];
892        let plan = plan(&p, &wanted, 130);
893        // The merged group spans only the wanted extent (5..126), grid-split
894        // into cells 0..40, 40..80, 80..120, 120..160 clipped to that span.
895        let cells: Vec<_> = plan
896            .merged
897            .requests
898            .iter()
899            .map(|r| r.range.clone())
900            .collect();
901        assert_eq!(cells, vec![5..40, 40..80, 80..120, 120..126]);
902        assert_eq!(plan.merged.owners, vec![vec![0], vec![1], vec![2], vec![3]]);
903    }
904
905    #[test]
906    fn a_range_above_split_above_is_cut_into_part_sized_grid_cells() {
907        let p = policy(0, 0, 1, 100, 40, 1);
908        let plan = plan(&p, &[0..130], 130);
909        let ranges: Vec<_> = plan
910            .merged
911            .requests
912            .iter()
913            .map(|r| r.range.clone())
914            .collect();
915        assert_eq!(ranges, vec![0..40, 40..80, 80..120, 120..130]);
916    }
917
918    #[test]
919    fn merged_ranges_are_rounded_out_to_align() {
920        let p = policy(0, 0, 1, u64::MAX, 1, 64);
921        let plan = plan(&p, &[10..20], 1000);
922        assert_eq!(plan.merged.requests[0].range, 0..64);
923    }
924
925    #[test]
926    fn alignment_never_crosses_the_object_end() {
927        let p = policy(0, 0, 1, u64::MAX, 1, 64);
928        let plan = plan(&p, &[10..20], 50);
929        assert_eq!(plan.merged.requests[0].range, 0..50);
930    }
931
932    #[test]
933    fn empty_wanted_makes_no_requests() {
934        let p = FetchPolicy::local();
935        let plan = plan(&p, &[], 1000);
936        assert!(plan.merged.requests.is_empty());
937        assert!(plan.merged.owners.is_empty());
938        let unmerged = plan.unmerged.build(&[]);
939        assert!(unmerged.requests.is_empty());
940        assert!(unmerged.owners.is_empty());
941    }
942
943    #[test]
944    fn overlapping_and_duplicate_wanted_ranges_map_to_the_right_request() {
945        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
946        let wanted = [4..8, 0..4, 4..8];
947        let plan = plan(&p, &wanted, 1000);
948        assert_eq!(plan.merged.requests.len(), 1);
949        assert_eq!(plan.merged.owners, vec![vec![0], vec![0], vec![0]]);
950    }
951
952    #[test]
953    fn plan_returns_both_shapes_without_a_budget_and_the_unmerged_one_on_demand() {
954        // `plan` takes no budget at all: it is pure, builds the merged shape
955        // up front and the unmerged one only when asked, leaving the choice
956        // to `choose`'s atomic reservation against a real `ReadBudget`
957        // (see the `execute_*` tests below for that choice itself).
958        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
959        let wanted = [0..1, 999..1000];
960        let planned = plan(&p, &wanted, 1000);
961        assert_eq!(planned.merged.requests.len(), 1);
962        assert_eq!(planned.merged.total_bytes, 1000);
963        let unmerged = planned.unmerged.build(&wanted);
964        assert_eq!(unmerged.requests.len(), 2);
965        assert_eq!(unmerged.requests[0].range, 0..1);
966        assert_eq!(unmerged.requests[1].range, 999..1000);
967        assert_eq!(unmerged.total_bytes, 2);
968    }
969
970    #[tokio::test]
971    async fn execute_falls_back_to_the_unmerged_plan_when_merging_would_exceed_the_budget() {
972        // The scenario Finding 3 was about: the merged plan (1000 bytes)
973        // does not fit a budget of 2, but the unmerged plan (2 bytes) does
974        // — and the choice is made atomically inside `execute`, not from a
975        // `remaining()` snapshot passed into `plan`.
976        use object_store::ObjectStoreExt;
977        use object_store::memory::InMemory;
978        let store = InMemory::new();
979        let path = Path::from("obj.bin");
980        store.put(&path, vec![0u8; 1000].into()).await.expect("put");
981
982        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
983        let wanted = [0..1, 999..1000];
984        let planned = plan(&p, &wanted, 1000);
985        assert_eq!(planned.merged.total_bytes, 1000);
986        assert_eq!(planned.unmerged.build(&wanted).total_bytes, 2);
987
988        let budget = ReadBudget::new(2); // exactly the unmerged floor, far under the merged total
989        let got = execute(&store, &budget, &path, planned)
990            .await
991            .expect("execute falls back to the unmerged plan");
992        assert_eq!(got.len(), 2);
993        assert_eq!(budget.used(), 2);
994    }
995
996    #[tokio::test]
997    async fn execute_refuses_honestly_when_neither_plan_fits() {
998        use object_store::ObjectStoreExt;
999        use object_store::memory::InMemory;
1000        let store = InMemory::new();
1001        let path = Path::from("obj.bin");
1002        store.put(&path, vec![0u8; 1000].into()).await.expect("put");
1003
1004        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
1005        let wanted = [0..1, 999..1000];
1006        let planned = plan(&p, &wanted, 1000);
1007        let budget = ReadBudget::new(1); // one byte short of even the unmerged floor (2)
1008        let err = execute(&store, &budget, &path, planned)
1009            .await
1010            .expect_err("neither plan fits a budget of 1");
1011        assert!(
1012            matches!(err, ItzmaError::ReadBudgetExceeded { .. }),
1013            "{err:?}"
1014        );
1015    }
1016
1017    #[test]
1018    fn aligned_groups_that_now_overlap_are_coalesced_into_one_request() {
1019        // Finding 9: align_out expands each merge() group independently of
1020        // its neighbors, so when `align` is bigger than the gap merge()
1021        // itself used to keep two groups apart, their aligned extents can
1022        // collide — two physical requests for the same or overlapping
1023        // bytes instead of one. object_store() reaches this (min_gap and
1024        // align are both 64 KiB, so two groups just over 64 KiB apart can
1025        // align onto the same boundary); local() cannot (align 1).
1026        let p = policy(0, 0, 1, u64::MAX, 1, 2048);
1027        let wanted = [0..1, 1000..1001]; // gap of 999, too wide for merge()'s min_gap of 0
1028        let plan = plan(&p, &wanted, 3000);
1029        assert_eq!(
1030            plan.merged.requests.len(),
1031            1,
1032            "two groups whose aligned extents collide must coalesce into one request"
1033        );
1034        assert_eq!(plan.merged.requests[0].range, 0..2048);
1035        assert_eq!(plan.merged.owners, vec![vec![0], vec![0]]);
1036    }
1037
1038    #[test]
1039    fn requests_are_sent_in_object_order_and_results_come_back_in_wanted_order() {
1040        let p = policy(0, 0, 1, u64::MAX, 1, 1);
1041        let wanted = [50..60, 0..10];
1042        let plan = plan(&p, &wanted, 1000);
1043        let starts: Vec<u64> = plan.merged.requests.iter().map(|r| r.range.start).collect();
1044        assert_eq!(starts, vec![0, 50]);
1045        assert_eq!(plan.merged.owners.len(), 2);
1046    }
1047
1048    // Property test: every wanted byte is inside the request(s) its owner
1049    // names, and total fetched is at most wanted + gaps + alignment.
1050    #[test]
1051    fn every_wanted_byte_is_covered_by_its_owner_and_waste_is_bounded() {
1052        let mut lcg = 12345u64;
1053        let mut next = |bound: u64| {
1054            lcg = lcg.wrapping_mul(6364136223846793005).wrapping_add(1);
1055            (lcg >> 33) % bound.max(1)
1056        };
1057        for _ in 0..200 {
1058            let object_size = 1000 + next(100_000);
1059            let p = FetchPolicy::object_store();
1060            let n = 1 + next(20) as usize;
1061            let mut wanted: Vec<Range<u64>> = Vec::new();
1062            for _ in 0..n {
1063                let start = next(object_size.saturating_sub(1));
1064                let len = 1 + next((object_size - start).max(1));
1065                wanted.push(start..(start + len).min(object_size));
1066            }
1067            let plan = plan(&p, &wanted, object_size);
1068            let wanted_bytes: u64 = wanted.iter().map(|r| r.end - r.start).sum();
1069            let fetched_bytes: u64 = plan
1070                .merged
1071                .requests
1072                .iter()
1073                .map(|r| r.range.end - r.range.start)
1074                .sum();
1075            for (i, w) in wanted.iter().enumerate() {
1076                let parts = &plan.merged.owners[i];
1077                let covering_start = plan.merged.requests[parts[0]].range.start;
1078                let covering_end = plan.merged.requests[*parts.last().unwrap()].range.end;
1079                assert!(
1080                    covering_start <= w.start && w.end <= covering_end,
1081                    "{w:?} not covered by {parts:?}"
1082                );
1083            }
1084            let allowed_waste = wanted.len() as u64 * (p.max_gap + p.align) + p.part_size;
1085            assert!(
1086                fetched_bytes <= wanted_bytes + allowed_waste,
1087                "fetched {fetched_bytes} > wanted {wanted_bytes} + waste {allowed_waste}"
1088            );
1089        }
1090    }
1091
1092    #[tokio::test]
1093    async fn execute_returns_one_slice_per_wanted_range_in_wanted_order() {
1094        use object_store::ObjectStoreExt;
1095        use object_store::memory::InMemory;
1096        let store = InMemory::new();
1097        let path = Path::from("obj.bin");
1098        let bytes: Vec<u8> = (0u8..100).collect();
1099        store.put(&path, bytes.clone().into()).await.expect("put");
1100
1101        let p = FetchPolicy::local();
1102        let wanted = [50..60, 0..10, 50..60];
1103        let budget = ReadBudget::unlimited();
1104        let planned = plan(&p, &wanted, 100);
1105        let got = execute(&store, &budget, &path, planned)
1106            .await
1107            .expect("execute");
1108        assert_eq!(got.len(), 3);
1109        assert_eq!(&got[0][..], &bytes[50..60]);
1110        assert_eq!(&got[1][..], &bytes[0..10]);
1111        assert_eq!(&got[2][..], &bytes[50..60]);
1112    }
1113
1114    #[tokio::test]
1115    async fn execute_on_a_split_group_returns_correct_bytes_for_each_small_wanted_range() {
1116        use object_store::ObjectStoreExt;
1117        use object_store::memory::InMemory;
1118        let store = InMemory::new();
1119        let path = Path::from("obj.bin");
1120        let bytes: Vec<u8> = (0u32..130).map(|i| (i % 256) as u8).collect();
1121        store.put(&path, bytes.clone().into()).await.expect("put");
1122
1123        let p = policy(1 << 20, 1 << 20, 1, 100, 40, 1);
1124        let wanted = [5..6, 45..46, 85..86, 125..126];
1125        let budget = ReadBudget::unlimited();
1126        let planned = plan(&p, &wanted, 130);
1127        let got = execute(&store, &budget, &path, planned)
1128            .await
1129            .expect("execute");
1130        assert_eq!(got.len(), 4);
1131        for (i, w) in wanted.iter().enumerate() {
1132            assert_eq!(
1133                &got[i][..],
1134                &bytes[w.start as usize..w.end as usize],
1135                "wanted[{i}]"
1136            );
1137        }
1138    }
1139
1140    #[tokio::test]
1141    async fn execute_charges_every_request_before_sending_it() {
1142        use object_store::ObjectStoreExt;
1143        use object_store::memory::InMemory;
1144        let store = InMemory::new();
1145        let path = Path::from("obj.bin");
1146        store.put(&path, vec![0u8; 100].into()).await.expect("put");
1147
1148        let p = FetchPolicy::local();
1149        let planned = plan(&p, &[0..10], 100);
1150        let tiny = ReadBudget::new(5);
1151        let err = execute(&store, &tiny, &path, planned)
1152            .await
1153            .expect_err("refused");
1154        assert!(matches!(err, ItzmaError::ReadBudgetExceeded { .. }));
1155    }
1156
1157    /// An in-memory store that counts every `get_opts` call, so a test can
1158    /// say how many requests `whole_object` made. Not shared with the
1159    /// similarly-named type in other modules (see `segment/ranged.rs`'s doc
1160    /// comment on why).
1161    #[derive(Debug, Default)]
1162    struct CountingStore {
1163        inner: object_store::memory::InMemory,
1164        served: std::sync::atomic::AtomicUsize,
1165    }
1166
1167    impl CountingStore {
1168        fn requests(&self) -> usize {
1169            self.served.load(std::sync::atomic::Ordering::SeqCst)
1170        }
1171    }
1172
1173    impl std::fmt::Display for CountingStore {
1174        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1175            write!(f, "CountingStore")
1176        }
1177    }
1178
1179    #[async_trait::async_trait]
1180    impl ObjectStore for CountingStore {
1181        async fn put_opts(
1182            &self,
1183            location: &Path,
1184            payload: object_store::PutPayload,
1185            opts: object_store::PutOptions,
1186        ) -> object_store::Result<object_store::PutResult> {
1187            self.inner.put_opts(location, payload, opts).await
1188        }
1189
1190        async fn put_multipart_opts(
1191            &self,
1192            location: &Path,
1193            opts: object_store::PutMultipartOptions,
1194        ) -> object_store::Result<Box<dyn object_store::MultipartUpload>> {
1195            self.inner.put_multipart_opts(location, opts).await
1196        }
1197
1198        async fn get_opts(
1199            &self,
1200            location: &Path,
1201            options: object_store::GetOptions,
1202        ) -> object_store::Result<object_store::GetResult> {
1203            let got = self.inner.get_opts(location, options).await?;
1204            self.served
1205                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1206            Ok(got)
1207        }
1208
1209        fn delete_stream(
1210            &self,
1211            locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
1212        ) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
1213            self.inner.delete_stream(locations)
1214        }
1215
1216        fn list(
1217            &self,
1218            prefix: Option<&Path>,
1219        ) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
1220        {
1221            self.inner.list(prefix)
1222        }
1223
1224        async fn list_with_delimiter(
1225            &self,
1226            prefix: Option<&Path>,
1227        ) -> object_store::Result<object_store::ListResult> {
1228            self.inner.list_with_delimiter(prefix).await
1229        }
1230
1231        async fn copy_opts(
1232            &self,
1233            from: &Path,
1234            to: &Path,
1235            options: object_store::CopyOptions,
1236        ) -> object_store::Result<()> {
1237            self.inner.copy_opts(from, to, options).await
1238        }
1239    }
1240
1241    #[tokio::test]
1242    async fn whole_object_of_a_missing_object_charges_nothing() {
1243        let budget = ReadBudget::new(0);
1244        let store = object_store::memory::InMemory::new();
1245        let p = FetchPolicy::object_store(); // part_size is 8 MiB — would blow a 0-byte budget if charged speculatively
1246        let err = whole_object(&store, &budget, &p, &Path::from("missing.bin"))
1247            .await
1248            .expect_err("missing");
1249        assert!(
1250            matches!(
1251                err,
1252                ItzmaError::Storage(object_store::Error::NotFound { .. })
1253            ),
1254            "{err:?}"
1255        );
1256        assert_eq!(budget.used(), 0, "a missing object must cost nothing");
1257    }
1258
1259    #[tokio::test]
1260    async fn whole_object_under_local_is_still_one_request_for_a_small_object() {
1261        // local()'s part_size is 1 (it never splits), but that same number
1262        // must not become the discovery probe's size too — a 1-byte probe
1263        // would force a second request for the head of any object bigger
1264        // than 1 byte, contradicting local()'s whole purpose: matching the
1265        // earlier single-GET behavior on InMemory/LocalFileSystem.
1266        use object_store::ObjectStoreExt;
1267        let store = CountingStore::default();
1268        let path = Path::from("small.bin");
1269        let bytes: Vec<u8> = (0u8..200).collect();
1270        store.put(&path, bytes.clone().into()).await.expect("put");
1271
1272        let budget = ReadBudget::unlimited();
1273        let got = whole_object(&store, &budget, &FetchPolicy::local(), &path)
1274            .await
1275            .expect("whole_object");
1276        assert_eq!(&got[..], &bytes[..]);
1277        assert_eq!(store.requests(), 1);
1278    }
1279
1280    #[tokio::test]
1281    async fn whole_object_smaller_than_the_probe_is_one_request() {
1282        use object_store::ObjectStoreExt;
1283        let store = CountingStore::default();
1284        let path = Path::from("small.bin");
1285        let bytes: Vec<u8> = (0u8..50).collect();
1286        store.put(&path, bytes.clone().into()).await.expect("put");
1287
1288        let budget = ReadBudget::unlimited();
1289        let p = FetchPolicy::object_store(); // part_size is 8 MiB, far bigger than this object
1290        let got = whole_object(&store, &budget, &p, &path)
1291            .await
1292            .expect("whole_object");
1293        assert_eq!(&got[..], &bytes[..]);
1294        assert_eq!(store.requests(), 1);
1295    }
1296
1297    #[tokio::test]
1298    async fn whole_object_bigger_than_the_probe_is_head_plus_tail_reassembled_in_order() {
1299        use object_store::ObjectStoreExt;
1300        let store = CountingStore::default();
1301        let path = Path::from("big.bin");
1302        // Bigger than DISCOVERY_PROBE_FLOOR (64 KiB), so the probe here is
1303        // genuinely policy.part_size, not the floor stepping in.
1304        let bytes: Vec<u8> = (0u32..250_000).map(|i| (i % 256) as u8).collect();
1305        store.put(&path, bytes.clone().into()).await.expect("put");
1306
1307        let budget = ReadBudget::unlimited();
1308        let p = FetchPolicy {
1309            split_above: u64::MAX,
1310            part_size: 100_000,
1311            ..FetchPolicy::local()
1312        }; // probe = part_size
1313        let got = whole_object(&store, &budget, &p, &path)
1314            .await
1315            .expect("whole_object");
1316        assert_eq!(&got[..], &bytes[..]);
1317        assert!(store.requests() >= 2);
1318    }
1319
1320    #[tokio::test]
1321    async fn whole_object_with_a_split_head_reassembles_every_part_in_order() {
1322        // The head (about 234 KB) is above split_above, so it goes out as
1323        // several parallel parts; the result must still be the exact bytes.
1324        use object_store::ObjectStoreExt;
1325        let store = CountingStore::default();
1326        let path = Path::from("split.bin");
1327        let size: u32 = 300_000;
1328        let bytes: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
1329        store.put(&path, bytes.clone().into()).await.expect("put");
1330
1331        let p = FetchPolicy {
1332            split_above: 100_000,
1333            part_size: 50_000,
1334            ..FetchPolicy::local()
1335        }; // probe = 64 KiB floor, so the head is 0..(300_000 - 65_536)
1336        let budget = ReadBudget::unlimited();
1337        let got = whole_object(&store, &budget, &p, &path)
1338            .await
1339            .expect("whole_object");
1340        assert_eq!(&got[..], &bytes[..]);
1341        assert!(store.requests() > 2, "the head should have been split");
1342    }
1343
1344    #[tokio::test]
1345    async fn whole_object_never_double_charges_bytes_the_tail_probe_already_fetched() {
1346        // Finding 8: the head's own plan used to be built against the
1347        // object's full size, so `align_out` could round the head group's
1348        // end past `tail_start` — straight into bytes the tail probe
1349        // already fetched, re-fetching and re-charging them. The head must
1350        // be planned against `tail_start`, not `size`, so its own aligned
1351        // extent can never cross into the tail's region. A budget set to
1352        // exactly the real object size must suffice; under the bug it did
1353        // not, because the double-counted overlap pushed the real total
1354        // charged past that size.
1355        use object_store::ObjectStoreExt;
1356        let store = CountingStore::default();
1357        let path = Path::from("obj.bin");
1358        let size: u32 = 70_000;
1359        let bytes: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
1360        store.put(&path, bytes.clone().into()).await.expect("put");
1361
1362        // part_size doubles as the probe size here (DISCOVERY_PROBE_FLOOR is
1363        // 64 KiB, matched exactly so tail_start lands at size - 65536 =
1364        // 4464), and align (128 KiB) is far bigger than that head region —
1365        // big enough that an unclipped align_out would round the head's end
1366        // out past the whole object, deep into the tail. An unlimited
1367        // budget (not a tight one) is what forces execute() to pick the
1368        // merged, aligned head candidate instead of silently falling back
1369        // to the unaligned unmerged one — the fallback that would otherwise
1370        // paper over this bug without the budget even noticing.
1371        let p = policy(0, 0, 1, u64::MAX, 65_536, 131_072);
1372        let budget = ReadBudget::unlimited();
1373        let got = whole_object(&store, &budget, &p, &path)
1374            .await
1375            .expect("whole_object");
1376        assert_eq!(&got[..], &bytes[..]);
1377        assert_eq!(
1378            budget.used(),
1379            u64::from(size),
1380            "the head must never be planned past tail_start, or its \
1381             aligned-out extent re-fetches and re-charges bytes the tail \
1382             probe already covered"
1383        );
1384    }
1385
1386    /// A store that always serves a truncated response, shorter than
1387    /// whatever range was requested — standing in for a buggy or
1388    /// misbehaving backend. Library code must never panic on this (CLAUDE.md's
1389    /// "decoders never panic"), it must error.
1390    #[derive(Debug, Default)]
1391    struct TruncatingStore {
1392        inner: object_store::memory::InMemory,
1393    }
1394
1395    impl std::fmt::Display for TruncatingStore {
1396        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1397            write!(f, "TruncatingStore")
1398        }
1399    }
1400
1401    #[async_trait::async_trait]
1402    impl ObjectStore for TruncatingStore {
1403        async fn put_opts(
1404            &self,
1405            location: &Path,
1406            payload: object_store::PutPayload,
1407            opts: object_store::PutOptions,
1408        ) -> object_store::Result<object_store::PutResult> {
1409            self.inner.put_opts(location, payload, opts).await
1410        }
1411
1412        async fn put_multipart_opts(
1413            &self,
1414            location: &Path,
1415            opts: object_store::PutMultipartOptions,
1416        ) -> object_store::Result<Box<dyn object_store::MultipartUpload>> {
1417            self.inner.put_multipart_opts(location, opts).await
1418        }
1419
1420        async fn get_opts(
1421            &self,
1422            location: &Path,
1423            options: object_store::GetOptions,
1424        ) -> object_store::Result<object_store::GetResult> {
1425            let got = self.inner.get_opts(location, options).await?;
1426            let (meta, range, attributes) =
1427                (got.meta.clone(), got.range.clone(), got.attributes.clone());
1428            let full = got.bytes().await?;
1429            let short = full.slice(..full.len() / 2);
1430            Ok(object_store::GetResult {
1431                payload: object_store::GetResultPayload::Stream(Box::pin(futures::stream::once(
1432                    async move { Ok(short) },
1433                ))),
1434                meta,
1435                range,
1436                attributes,
1437                extensions: Default::default(),
1438            })
1439        }
1440
1441        fn delete_stream(
1442            &self,
1443            locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
1444        ) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
1445            self.inner.delete_stream(locations)
1446        }
1447
1448        fn list(
1449            &self,
1450            prefix: Option<&Path>,
1451        ) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
1452        {
1453            self.inner.list(prefix)
1454        }
1455
1456        async fn list_with_delimiter(
1457            &self,
1458            prefix: Option<&Path>,
1459        ) -> object_store::Result<object_store::ListResult> {
1460            self.inner.list_with_delimiter(prefix).await
1461        }
1462
1463        async fn copy_opts(
1464            &self,
1465            from: &Path,
1466            to: &Path,
1467            options: object_store::CopyOptions,
1468        ) -> object_store::Result<()> {
1469            self.inner.copy_opts(from, to, options).await
1470        }
1471    }
1472
1473    #[tokio::test]
1474    async fn a_short_response_is_an_error_not_a_panic() {
1475        use object_store::ObjectStoreExt;
1476        let store = TruncatingStore::default();
1477        let path = Path::from("obj.bin");
1478        store.put(&path, vec![0u8; 100].into()).await.expect("put");
1479
1480        let p = FetchPolicy::local();
1481        let budget = ReadBudget::unlimited();
1482        let planned = plan(&p, &[0..100], 100);
1483        let err = execute(&store, &budget, &path, planned)
1484            .await
1485            .expect_err("a truncated response must error, not panic");
1486        assert!(matches!(err, ItzmaError::Storage(_)), "{err:?}");
1487    }
1488}