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
434const FETCH_CONCURRENCY: usize = 16;
435
436/// Pick between `plan`'s two candidates, send the winner's requests
437/// (concurrently), and return one slice per originally wanted range, in
438/// wanted order — zero-copy when that range's own group was not split,
439/// one concatenation when it was (see `whole_object`).
440///
441/// The choice is one atomic reservation against `budget`
442/// ([`ReadBudget::try_reserve`]), not a snapshot-then-decide: merging
443/// nearby ranges is tried first (fewer requests), falling back to the
444/// unmerged shape if that alone doesn't fit — a read never fails for the
445/// planner's sake — and if *neither* fits, a real [`ReadBudget::charge`]
446/// for the (smaller) unmerged total reports an honest, accurate refusal.
447/// Deciding from a `remaining()` snapshot and charging later would leave a
448/// window where a concurrent caller sharing the same budget charges in
449/// between, making the snapshot the decision was made on already stale by
450/// the time it is acted on — reserving atomically closes that window: at
451/// most one concurrent decision can ever win a given byte of budget.
452///
453/// A missing object is [`ItzmaError::Storage`] here; callers that need it
454/// reported as damage (`segment::missing`, `index::missing`, ...) do that
455/// translation themselves, as they do today for every other fetch.
456pub(crate) async fn execute(
457    store: &dyn ObjectStore,
458    budget: &ReadBudget,
459    path: &Path,
460    plan: Plan,
461) -> Result<Vec<Bytes>> {
462    if plan.wanted.is_empty() {
463        return Ok(Vec::new());
464    }
465    let Plan {
466        merged,
467        unmerged,
468        wanted,
469    } = plan;
470    let chosen = choose(budget, path, merged, || unmerged.build(&wanted))?;
471    if chosen.requests.is_empty() {
472        return Ok(Vec::new());
473    }
474    let fetched = fetch_parts(store, path, &chosen.requests).await?;
475    chosen
476        .owners
477        .iter()
478        .zip(&wanted)
479        .map(|(parts, w)| {
480            let base = chosen.requests[parts[0]].range.start;
481            let local_start = (w.start - base) as usize;
482            let local_len = (w.end - w.start) as usize;
483            let whole = if parts.len() == 1 {
484                fetched[parts[0]].clone()
485            } else {
486                let pieces: Vec<Bytes> = parts.iter().map(|&p| fetched[p].clone()).collect();
487                concat(&pieces)
488            };
489            // Checked, not a direct `Bytes::slice` (which panics out of
490            // bounds): a store that returns fewer bytes than its own
491            // response claimed is a store bug, and library code never
492            // panics on one (library code does not `unwrap`, decoders
493            // never panic).
494            if local_start + local_len > whole.len() {
495                return Err(short_read(path, whole.len(), local_start + local_len));
496            }
497            Ok(whole.slice(local_start..local_start + local_len))
498        })
499        .collect()
500}
501
502/// Pick between a merged and an unmerged candidate and reserve its bytes.
503/// The choice is one atomic reservation against `budget`
504/// ([`ReadBudget::try_reserve`]), not a snapshot-then-decide: merging is
505/// tried first (fewer requests), falling back to the unmerged shape if that
506/// alone doesn't fit — a read never fails for the planner's sake — and if
507/// *neither* fits, a real [`ReadBudget::charge`] for the (smaller) unmerged
508/// total reports an honest, accurate refusal. Deciding from a `remaining()`
509/// snapshot and charging later would leave a window where a concurrent
510/// caller sharing the same budget charges in between, making the snapshot
511/// the decision was made on already stale by the time it is acted on.
512fn choose(
513    budget: &ReadBudget,
514    path: &Path,
515    merged: Candidate,
516    unmerged: impl FnOnce() -> Candidate,
517) -> Result<Candidate> {
518    if budget.try_reserve(merged.total_bytes) {
519        return Ok(merged);
520    }
521    let unmerged = unmerged();
522    if budget.try_reserve(unmerged.total_bytes) {
523        return Ok(unmerged);
524    }
525    // Neither fits on its own: charge the true minimum (the unmerged total
526    // can never exceed the merged one) for an honest refusal, sticky like
527    // every other charge in this crate. This can only succeed if budget
528    // freed up between the two `try_reserve` calls above and this one, in
529    // which case the unmerged plan genuinely does fit now and proceeding
530    // with it is correct.
531    budget.charge(path.as_ref(), unmerged.total_bytes)?;
532    Ok(unmerged)
533}
534
535/// Send `requests` concurrently and return their bytes in request order.
536/// No per-request `budget.charge` here: the whole total was already
537/// reserved by [`choose`], specifically so this loop can run concurrently
538/// without each request racing a sibling task's charges.
539pub(crate) async fn fetch_parts(
540    store: &dyn ObjectStore,
541    path: &Path,
542    requests: &[Req],
543) -> Result<Vec<Bytes>> {
544    // Collected into an owned Vec before the stream, not `.iter().map(...)`
545    // taken straight into `stream::iter`: a closure whose parameter borrows
546    // from `requests` inline like that is inferred higher-ranked, which
547    // then fails "Send is not general enough" at every caller that spawns
548    // the future this builds (see `segment::read_all`'s own comment on the
549    // same shape of fix).
550    let ranges: Vec<Range<u64>> = requests.iter().map(|r| r.range.clone()).collect();
551    stream::iter(ranges)
552        .map(|range| async move {
553            if range.end <= range.start {
554                return Ok(Bytes::new());
555            }
556            store.get_range(path, range).await.map_err(ItzmaError::from)
557        })
558        .buffered(FETCH_CONCURRENCY)
559        .try_collect()
560        .await
561}
562
563/// One copy of `parts`, concatenated in order. A single part is returned
564/// as is, without a copy.
565fn concat(parts: &[Bytes]) -> Bytes {
566    if let [only] = parts {
567        return only.clone();
568    }
569    let mut out = Vec::with_capacity(parts.iter().map(Bytes::len).sum());
570    for part in parts {
571        out.extend_from_slice(part);
572    }
573    Bytes::from(out)
574}
575
576/// The error for a store that returned fewer bytes than its own response
577/// claimed. Library code never panics on a store bug, so this is an error.
578fn short_read(path: &Path, have: usize, need: usize) -> ItzmaError {
579    ItzmaError::Storage(object_store::Error::Generic {
580        store: "fetch",
581        source: format!(
582            "{}: the store returned {have} bytes, fewer than the {need} a ranged read needed",
583            path.as_ref()
584        )
585        .into(),
586    })
587}
588
589/// The discovery probe's floor, regardless of policy: `policy.part_size`
590/// alone would make `local()` (`part_size: 1`) send a second request for
591/// the head of any object bigger than a single byte, defeating `local()`'s
592/// whole purpose of matching the earlier one-GET behavior. Matches
593/// `RangedSegment::open`'s own `TAIL_GUESS` — the same trick, the same
594/// reasoning: most test- and namespace-sized objects fit in one response.
595const DISCOVERY_PROBE_FLOOR: u64 = 64 * 1024;
596
597/// Fetch a whole object, learning its size from the first request instead
598/// of a separate HEAD — the same trick `RangedSegment::open` already uses
599/// for a segment's trailer: a suffix request returns the object's real
600/// size in its response even when the object is smaller than asked, in
601/// which case that one response already holds everything. Otherwise the
602/// rest (`0..size - probe`) is planned and executed like any other wanted
603/// range, splitting into parallel parts if it is big enough, and the two
604/// pieces are concatenated in object order.
605pub(crate) async fn whole_object(
606    store: &dyn ObjectStore,
607    budget: &ReadBudget,
608    policy: &FetchPolicy,
609    path: &Path,
610) -> Result<Bytes> {
611    use object_store::{GetOptions, GetRange};
612
613    let probe = policy.part_size.max(DISCOVERY_PROBE_FLOOR);
614    let options = GetOptions {
615        range: Some(GetRange::Suffix(probe)),
616        ..GetOptions::default()
617    };
618    // Charged after the request, not before: its real cost (the response's
619    // own range, which can be smaller than `probe` for a small object) is
620    // only known once the headers are in hand, and a missing object — the
621    // common, unexceptional case for an optional object — must cost nothing, the same way every other fetch in this crate
622    // charges nothing for an object that was never there to read.
623    let got = store
624        .get_opts(path, options)
625        .await
626        .map_err(ItzmaError::from)?;
627    let size = got.meta.size;
628    let tail_start = got.range.start;
629    budget.charge(path.as_ref(), got.range.end - tail_start)?;
630    // The tail's chunks are kept as they arrive, not collected into one
631    // buffer first: the final object is assembled below with one copy of
632    // each byte, instead of one copy into a tail buffer and another into
633    // the object.
634    let mut pieces: Vec<Bytes> = got
635        .into_stream()
636        .try_collect()
637        .await
638        .map_err(ItzmaError::from)?;
639
640    if tail_start == 0 {
641        // The probe already covered the whole object.
642        return assemble(path, pieces, size);
643    }
644
645    #[allow(clippy::single_range_in_vec_init)] // one wanted range: the head before the tail
646    let wanted = [0..tail_start];
647    // Bounded by `tail_start`, not the object's real `size`: the merged
648    // candidate's own alignment (`align_out`) clips a group's end to
649    // whatever "object size" it is given, so planning against the real,
650    // bigger `size` here let an aligned head group round its end straight
651    // into the tail region the probe above already fetched — re-fetching
652    // and re-charging the overlap even though the answer stayed correct
653    // (Finding 8). The head's own address space ends at `tail_start` by
654    // construction, so that is its true bound.
655    let planned = plan(policy, &wanted, tail_start);
656    let chosen = choose(budget, path, planned.merged, || {
657        planned.unmerged.build(&wanted)
658    })?;
659    // The chosen requests cover exactly `0..tail_start`: the head is
660    // planned against `tail_start` (see above), so every part is inside it
661    // and in object order, and concatenating them is the head.
662    let head = fetch_parts(store, path, &chosen.requests).await?;
663    let mut all = head;
664    all.append(&mut pieces);
665    assemble(path, all, size)
666}
667
668/// Concatenate `parts` (object order) into one object of `size` bytes,
669/// copying each byte once. A single part is returned without a copy. A
670/// store that delivers a different number of bytes than it declared is
671/// [`short_read`], not a panic.
672fn assemble(path: &Path, parts: Vec<Bytes>, size: u64) -> Result<Bytes> {
673    let have: usize = parts.iter().map(Bytes::len).sum();
674    if have as u64 != size {
675        return Err(short_read(path, have, size as usize));
676    }
677    Ok(concat(&parts))
678}
679
680#[cfg(test)]
681#[allow(clippy::single_range_in_vec_init)] // a one-range `wanted` slice is a normal, valid test case here, not a mistake
682mod tests {
683    use super::*;
684
685    fn policy(
686        min_gap: u64,
687        max_gap: u64,
688        gap_divisor: u64,
689        split_above: u64,
690        part_size: u64,
691        align: u64,
692    ) -> FetchPolicy {
693        FetchPolicy {
694            min_gap,
695            max_gap,
696            gap_divisor,
697            split_above,
698            part_size,
699            align,
700        }
701    }
702
703    #[test]
704    fn object_store_merges_within_64_kib() {
705        // Measured against MinIO: with a
706        // decoded cache and fresh queries, a 64 KiB floor beat 256 KiB on
707        // requests and bytes at once in every configuration measured.
708        assert_eq!(
709            FetchPolicy::object_store(),
710            policy(64 << 10, 4 << 20, 8, 16 << 20, 8 << 20, 64 << 10)
711        );
712    }
713
714    #[test]
715    fn two_ranges_within_the_gap_merge_into_one_request() {
716        // min_gap 8, so a gap of exactly 8 merges, one more byte does not.
717        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
718        let touching = plan(&p, &[0..4, 12..16], 1000);
719        assert_eq!(touching.merged.requests.len(), 1);
720        assert_eq!(touching.merged.requests[0].range, 0..16);
721
722        let apart = plan(&p, &[0..4, 13..16], 1000);
723        assert_eq!(apart.merged.requests.len(), 2);
724    }
725
726    #[test]
727    fn a_request_never_crosses_the_object_end() {
728        let p = policy(1024, 1024, 1, u64::MAX, 1, 1);
729        let plan = plan(&p, &[0..10], 10);
730        assert_eq!(plan.merged.requests[0].range, 0..10);
731    }
732
733    #[test]
734    fn a_misconfigured_policy_with_min_gap_above_max_gap_never_panics() {
735        // Reachable from outside this crate (FetchPolicy's setters are
736        // public, and the Python bridge builds one from six independent
737        // optional kwargs with no cross-field validation), so this must
738        // degrade gracefully, not panic — `u64::clamp` panics if its own
739        // min exceeds its max.
740        let p = policy(1 << 20, 8, 1, u64::MAX, 1, 1); // min_gap way above max_gap
741        let plan = plan(&p, &[0..4, 1_000_000..1_000_004], 2_000_000);
742        assert!(!plan.merged.requests.is_empty());
743    }
744
745    #[test]
746    fn an_empty_wanted_range_still_gets_an_owner_not_an_empty_list() {
747        // A zero-row SQ8 partition's byte range is legitimately empty
748        // (start == end). A strict overlap test (`start < end`) never
749        // matches an empty range against anything, including its own
750        // single-part group, leaving `owners[i]` empty — which panics in
751        // `execute` on `parts[0]`. Caught by a real integration test
752        // (tests/index.rs's `a_segment_with_no_documents_is_indexed_when_asked`)
753        // going through sq8::fetch_wave with a genuinely empty partition.
754        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
755        let plan = plan(&p, &[5..5], 10);
756        assert_eq!(plan.merged.owners, vec![vec![0]]);
757    }
758
759    #[test]
760    fn a_small_wanted_range_owns_only_the_parts_it_overlaps_not_the_whole_group() {
761        // Four tiny ranges, far enough apart that nothing would merge under
762        // a tight policy, forced into one group by a huge gap limit. That
763        // group is wider than split_above (100) with part_size 40, so it
764        // splits into 4 grid cells: 0..40, 40..80, 80..120, 120..130. Each
765        // tiny wanted range sits entirely inside exactly one cell and must
766        // own only that cell — not all 4, which is what execute() would
767        // otherwise concatenate per wanted range.
768        let p = policy(1 << 20, 1 << 20, 1, 100, 40, 1);
769        let wanted = [5..6, 45..46, 85..86, 125..126];
770        let plan = plan(&p, &wanted, 130);
771        // The merged group spans only the wanted extent (5..126), grid-split
772        // into cells 0..40, 40..80, 80..120, 120..160 clipped to that span.
773        let cells: Vec<_> = plan
774            .merged
775            .requests
776            .iter()
777            .map(|r| r.range.clone())
778            .collect();
779        assert_eq!(cells, vec![5..40, 40..80, 80..120, 120..126]);
780        assert_eq!(plan.merged.owners, vec![vec![0], vec![1], vec![2], vec![3]]);
781    }
782
783    #[test]
784    fn a_range_above_split_above_is_cut_into_part_sized_grid_cells() {
785        let p = policy(0, 0, 1, 100, 40, 1);
786        let plan = plan(&p, &[0..130], 130);
787        let ranges: Vec<_> = plan
788            .merged
789            .requests
790            .iter()
791            .map(|r| r.range.clone())
792            .collect();
793        assert_eq!(ranges, vec![0..40, 40..80, 80..120, 120..130]);
794    }
795
796    #[test]
797    fn merged_ranges_are_rounded_out_to_align() {
798        let p = policy(0, 0, 1, u64::MAX, 1, 64);
799        let plan = plan(&p, &[10..20], 1000);
800        assert_eq!(plan.merged.requests[0].range, 0..64);
801    }
802
803    #[test]
804    fn alignment_never_crosses_the_object_end() {
805        let p = policy(0, 0, 1, u64::MAX, 1, 64);
806        let plan = plan(&p, &[10..20], 50);
807        assert_eq!(plan.merged.requests[0].range, 0..50);
808    }
809
810    #[test]
811    fn empty_wanted_makes_no_requests() {
812        let p = FetchPolicy::local();
813        let plan = plan(&p, &[], 1000);
814        assert!(plan.merged.requests.is_empty());
815        assert!(plan.merged.owners.is_empty());
816        let unmerged = plan.unmerged.build(&[]);
817        assert!(unmerged.requests.is_empty());
818        assert!(unmerged.owners.is_empty());
819    }
820
821    #[test]
822    fn overlapping_and_duplicate_wanted_ranges_map_to_the_right_request() {
823        let p = policy(8, 1024, 8, u64::MAX, 1, 1);
824        let wanted = [4..8, 0..4, 4..8];
825        let plan = plan(&p, &wanted, 1000);
826        assert_eq!(plan.merged.requests.len(), 1);
827        assert_eq!(plan.merged.owners, vec![vec![0], vec![0], vec![0]]);
828    }
829
830    #[test]
831    fn plan_returns_both_shapes_without_a_budget_and_the_unmerged_one_on_demand() {
832        // `plan` takes no budget at all: it is pure, builds the merged shape
833        // up front and the unmerged one only when asked, leaving the choice
834        // to `choose`'s atomic reservation against a real `ReadBudget`
835        // (see the `execute_*` tests below for that choice itself).
836        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
837        let wanted = [0..1, 999..1000];
838        let planned = plan(&p, &wanted, 1000);
839        assert_eq!(planned.merged.requests.len(), 1);
840        assert_eq!(planned.merged.total_bytes, 1000);
841        let unmerged = planned.unmerged.build(&wanted);
842        assert_eq!(unmerged.requests.len(), 2);
843        assert_eq!(unmerged.requests[0].range, 0..1);
844        assert_eq!(unmerged.requests[1].range, 999..1000);
845        assert_eq!(unmerged.total_bytes, 2);
846    }
847
848    #[tokio::test]
849    async fn execute_falls_back_to_the_unmerged_plan_when_merging_would_exceed_the_budget() {
850        // The scenario Finding 3 was about: the merged plan (1000 bytes)
851        // does not fit a budget of 2, but the unmerged plan (2 bytes) does
852        // — and the choice is made atomically inside `execute`, not from a
853        // `remaining()` snapshot passed into `plan`.
854        use object_store::ObjectStoreExt;
855        use object_store::memory::InMemory;
856        let store = InMemory::new();
857        let path = Path::from("obj.bin");
858        store.put(&path, vec![0u8; 1000].into()).await.expect("put");
859
860        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
861        let wanted = [0..1, 999..1000];
862        let planned = plan(&p, &wanted, 1000);
863        assert_eq!(planned.merged.total_bytes, 1000);
864        assert_eq!(planned.unmerged.build(&wanted).total_bytes, 2);
865
866        let budget = ReadBudget::new(2); // exactly the unmerged floor, far under the merged total
867        let got = execute(&store, &budget, &path, planned)
868            .await
869            .expect("execute falls back to the unmerged plan");
870        assert_eq!(got.len(), 2);
871        assert_eq!(budget.used(), 2);
872    }
873
874    #[tokio::test]
875    async fn execute_refuses_honestly_when_neither_plan_fits() {
876        use object_store::ObjectStoreExt;
877        use object_store::memory::InMemory;
878        let store = InMemory::new();
879        let path = Path::from("obj.bin");
880        store.put(&path, vec![0u8; 1000].into()).await.expect("put");
881
882        let p = policy(1000, 1000, 1, u64::MAX, 1, 1);
883        let wanted = [0..1, 999..1000];
884        let planned = plan(&p, &wanted, 1000);
885        let budget = ReadBudget::new(1); // one byte short of even the unmerged floor (2)
886        let err = execute(&store, &budget, &path, planned)
887            .await
888            .expect_err("neither plan fits a budget of 1");
889        assert!(
890            matches!(err, ItzmaError::ReadBudgetExceeded { .. }),
891            "{err:?}"
892        );
893    }
894
895    #[test]
896    fn aligned_groups_that_now_overlap_are_coalesced_into_one_request() {
897        // Finding 9: align_out expands each merge() group independently of
898        // its neighbors, so when `align` is bigger than the gap merge()
899        // itself used to keep two groups apart, their aligned extents can
900        // collide — two physical requests for the same or overlapping
901        // bytes instead of one. object_store() reaches this (min_gap and
902        // align are both 64 KiB, so two groups just over 64 KiB apart can
903        // align onto the same boundary); local() cannot (align 1).
904        let p = policy(0, 0, 1, u64::MAX, 1, 2048);
905        let wanted = [0..1, 1000..1001]; // gap of 999, too wide for merge()'s min_gap of 0
906        let plan = plan(&p, &wanted, 3000);
907        assert_eq!(
908            plan.merged.requests.len(),
909            1,
910            "two groups whose aligned extents collide must coalesce into one request"
911        );
912        assert_eq!(plan.merged.requests[0].range, 0..2048);
913        assert_eq!(plan.merged.owners, vec![vec![0], vec![0]]);
914    }
915
916    #[test]
917    fn requests_are_sent_in_object_order_and_results_come_back_in_wanted_order() {
918        let p = policy(0, 0, 1, u64::MAX, 1, 1);
919        let wanted = [50..60, 0..10];
920        let plan = plan(&p, &wanted, 1000);
921        let starts: Vec<u64> = plan.merged.requests.iter().map(|r| r.range.start).collect();
922        assert_eq!(starts, vec![0, 50]);
923        assert_eq!(plan.merged.owners.len(), 2);
924    }
925
926    // Property test: every wanted byte is inside the request(s) its owner
927    // names, and total fetched is at most wanted + gaps + alignment.
928    #[test]
929    fn every_wanted_byte_is_covered_by_its_owner_and_waste_is_bounded() {
930        let mut lcg = 12345u64;
931        let mut next = |bound: u64| {
932            lcg = lcg.wrapping_mul(6364136223846793005).wrapping_add(1);
933            (lcg >> 33) % bound.max(1)
934        };
935        for _ in 0..200 {
936            let object_size = 1000 + next(100_000);
937            let p = FetchPolicy::object_store();
938            let n = 1 + next(20) as usize;
939            let mut wanted: Vec<Range<u64>> = Vec::new();
940            for _ in 0..n {
941                let start = next(object_size.saturating_sub(1));
942                let len = 1 + next((object_size - start).max(1));
943                wanted.push(start..(start + len).min(object_size));
944            }
945            let plan = plan(&p, &wanted, object_size);
946            let wanted_bytes: u64 = wanted.iter().map(|r| r.end - r.start).sum();
947            let fetched_bytes: u64 = plan
948                .merged
949                .requests
950                .iter()
951                .map(|r| r.range.end - r.range.start)
952                .sum();
953            for (i, w) in wanted.iter().enumerate() {
954                let parts = &plan.merged.owners[i];
955                let covering_start = plan.merged.requests[parts[0]].range.start;
956                let covering_end = plan.merged.requests[*parts.last().unwrap()].range.end;
957                assert!(
958                    covering_start <= w.start && w.end <= covering_end,
959                    "{w:?} not covered by {parts:?}"
960                );
961            }
962            let allowed_waste = wanted.len() as u64 * (p.max_gap + p.align) + p.part_size;
963            assert!(
964                fetched_bytes <= wanted_bytes + allowed_waste,
965                "fetched {fetched_bytes} > wanted {wanted_bytes} + waste {allowed_waste}"
966            );
967        }
968    }
969
970    #[tokio::test]
971    async fn execute_returns_one_slice_per_wanted_range_in_wanted_order() {
972        use object_store::ObjectStoreExt;
973        use object_store::memory::InMemory;
974        let store = InMemory::new();
975        let path = Path::from("obj.bin");
976        let bytes: Vec<u8> = (0u8..100).collect();
977        store.put(&path, bytes.clone().into()).await.expect("put");
978
979        let p = FetchPolicy::local();
980        let wanted = [50..60, 0..10, 50..60];
981        let budget = ReadBudget::unlimited();
982        let planned = plan(&p, &wanted, 100);
983        let got = execute(&store, &budget, &path, planned)
984            .await
985            .expect("execute");
986        assert_eq!(got.len(), 3);
987        assert_eq!(&got[0][..], &bytes[50..60]);
988        assert_eq!(&got[1][..], &bytes[0..10]);
989        assert_eq!(&got[2][..], &bytes[50..60]);
990    }
991
992    #[tokio::test]
993    async fn execute_on_a_split_group_returns_correct_bytes_for_each_small_wanted_range() {
994        use object_store::ObjectStoreExt;
995        use object_store::memory::InMemory;
996        let store = InMemory::new();
997        let path = Path::from("obj.bin");
998        let bytes: Vec<u8> = (0u32..130).map(|i| (i % 256) as u8).collect();
999        store.put(&path, bytes.clone().into()).await.expect("put");
1000
1001        let p = policy(1 << 20, 1 << 20, 1, 100, 40, 1);
1002        let wanted = [5..6, 45..46, 85..86, 125..126];
1003        let budget = ReadBudget::unlimited();
1004        let planned = plan(&p, &wanted, 130);
1005        let got = execute(&store, &budget, &path, planned)
1006            .await
1007            .expect("execute");
1008        assert_eq!(got.len(), 4);
1009        for (i, w) in wanted.iter().enumerate() {
1010            assert_eq!(
1011                &got[i][..],
1012                &bytes[w.start as usize..w.end as usize],
1013                "wanted[{i}]"
1014            );
1015        }
1016    }
1017
1018    #[tokio::test]
1019    async fn execute_charges_every_request_before_sending_it() {
1020        use object_store::ObjectStoreExt;
1021        use object_store::memory::InMemory;
1022        let store = InMemory::new();
1023        let path = Path::from("obj.bin");
1024        store.put(&path, vec![0u8; 100].into()).await.expect("put");
1025
1026        let p = FetchPolicy::local();
1027        let planned = plan(&p, &[0..10], 100);
1028        let tiny = ReadBudget::new(5);
1029        let err = execute(&store, &tiny, &path, planned)
1030            .await
1031            .expect_err("refused");
1032        assert!(matches!(err, ItzmaError::ReadBudgetExceeded { .. }));
1033    }
1034
1035    /// An in-memory store that counts every `get_opts` call, so a test can
1036    /// say how many requests `whole_object` made. Not shared with the
1037    /// similarly-named type in other modules (see `segment/ranged.rs`'s doc
1038    /// comment on why).
1039    #[derive(Debug, Default)]
1040    struct CountingStore {
1041        inner: object_store::memory::InMemory,
1042        served: std::sync::atomic::AtomicUsize,
1043    }
1044
1045    impl CountingStore {
1046        fn requests(&self) -> usize {
1047            self.served.load(std::sync::atomic::Ordering::SeqCst)
1048        }
1049    }
1050
1051    impl std::fmt::Display for CountingStore {
1052        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1053            write!(f, "CountingStore")
1054        }
1055    }
1056
1057    #[async_trait::async_trait]
1058    impl ObjectStore for CountingStore {
1059        async fn put_opts(
1060            &self,
1061            location: &Path,
1062            payload: object_store::PutPayload,
1063            opts: object_store::PutOptions,
1064        ) -> object_store::Result<object_store::PutResult> {
1065            self.inner.put_opts(location, payload, opts).await
1066        }
1067
1068        async fn put_multipart_opts(
1069            &self,
1070            location: &Path,
1071            opts: object_store::PutMultipartOptions,
1072        ) -> object_store::Result<Box<dyn object_store::MultipartUpload>> {
1073            self.inner.put_multipart_opts(location, opts).await
1074        }
1075
1076        async fn get_opts(
1077            &self,
1078            location: &Path,
1079            options: object_store::GetOptions,
1080        ) -> object_store::Result<object_store::GetResult> {
1081            let got = self.inner.get_opts(location, options).await?;
1082            self.served
1083                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1084            Ok(got)
1085        }
1086
1087        fn delete_stream(
1088            &self,
1089            locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
1090        ) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
1091            self.inner.delete_stream(locations)
1092        }
1093
1094        fn list(
1095            &self,
1096            prefix: Option<&Path>,
1097        ) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
1098        {
1099            self.inner.list(prefix)
1100        }
1101
1102        async fn list_with_delimiter(
1103            &self,
1104            prefix: Option<&Path>,
1105        ) -> object_store::Result<object_store::ListResult> {
1106            self.inner.list_with_delimiter(prefix).await
1107        }
1108
1109        async fn copy_opts(
1110            &self,
1111            from: &Path,
1112            to: &Path,
1113            options: object_store::CopyOptions,
1114        ) -> object_store::Result<()> {
1115            self.inner.copy_opts(from, to, options).await
1116        }
1117    }
1118
1119    #[tokio::test]
1120    async fn whole_object_of_a_missing_object_charges_nothing() {
1121        let budget = ReadBudget::new(0);
1122        let store = object_store::memory::InMemory::new();
1123        let p = FetchPolicy::object_store(); // part_size is 8 MiB — would blow a 0-byte budget if charged speculatively
1124        let err = whole_object(&store, &budget, &p, &Path::from("missing.bin"))
1125            .await
1126            .expect_err("missing");
1127        assert!(
1128            matches!(
1129                err,
1130                ItzmaError::Storage(object_store::Error::NotFound { .. })
1131            ),
1132            "{err:?}"
1133        );
1134        assert_eq!(budget.used(), 0, "a missing object must cost nothing");
1135    }
1136
1137    #[tokio::test]
1138    async fn whole_object_under_local_is_still_one_request_for_a_small_object() {
1139        // local()'s part_size is 1 (it never splits), but that same number
1140        // must not become the discovery probe's size too — a 1-byte probe
1141        // would force a second request for the head of any object bigger
1142        // than 1 byte, contradicting local()'s whole purpose: matching the
1143        // earlier single-GET behavior on InMemory/LocalFileSystem.
1144        use object_store::ObjectStoreExt;
1145        let store = CountingStore::default();
1146        let path = Path::from("small.bin");
1147        let bytes: Vec<u8> = (0u8..200).collect();
1148        store.put(&path, bytes.clone().into()).await.expect("put");
1149
1150        let budget = ReadBudget::unlimited();
1151        let got = whole_object(&store, &budget, &FetchPolicy::local(), &path)
1152            .await
1153            .expect("whole_object");
1154        assert_eq!(&got[..], &bytes[..]);
1155        assert_eq!(store.requests(), 1);
1156    }
1157
1158    #[tokio::test]
1159    async fn whole_object_smaller_than_the_probe_is_one_request() {
1160        use object_store::ObjectStoreExt;
1161        let store = CountingStore::default();
1162        let path = Path::from("small.bin");
1163        let bytes: Vec<u8> = (0u8..50).collect();
1164        store.put(&path, bytes.clone().into()).await.expect("put");
1165
1166        let budget = ReadBudget::unlimited();
1167        let p = FetchPolicy::object_store(); // part_size is 8 MiB, far bigger than this object
1168        let got = whole_object(&store, &budget, &p, &path)
1169            .await
1170            .expect("whole_object");
1171        assert_eq!(&got[..], &bytes[..]);
1172        assert_eq!(store.requests(), 1);
1173    }
1174
1175    #[tokio::test]
1176    async fn whole_object_bigger_than_the_probe_is_head_plus_tail_reassembled_in_order() {
1177        use object_store::ObjectStoreExt;
1178        let store = CountingStore::default();
1179        let path = Path::from("big.bin");
1180        // Bigger than DISCOVERY_PROBE_FLOOR (64 KiB), so the probe here is
1181        // genuinely policy.part_size, not the floor stepping in.
1182        let bytes: Vec<u8> = (0u32..250_000).map(|i| (i % 256) as u8).collect();
1183        store.put(&path, bytes.clone().into()).await.expect("put");
1184
1185        let budget = ReadBudget::unlimited();
1186        let p = FetchPolicy {
1187            split_above: u64::MAX,
1188            part_size: 100_000,
1189            ..FetchPolicy::local()
1190        }; // probe = part_size
1191        let got = whole_object(&store, &budget, &p, &path)
1192            .await
1193            .expect("whole_object");
1194        assert_eq!(&got[..], &bytes[..]);
1195        assert!(store.requests() >= 2);
1196    }
1197
1198    #[tokio::test]
1199    async fn whole_object_with_a_split_head_reassembles_every_part_in_order() {
1200        // The head (about 234 KB) is above split_above, so it goes out as
1201        // several parallel parts; the result must still be the exact bytes.
1202        use object_store::ObjectStoreExt;
1203        let store = CountingStore::default();
1204        let path = Path::from("split.bin");
1205        let size: u32 = 300_000;
1206        let bytes: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
1207        store.put(&path, bytes.clone().into()).await.expect("put");
1208
1209        let p = FetchPolicy {
1210            split_above: 100_000,
1211            part_size: 50_000,
1212            ..FetchPolicy::local()
1213        }; // probe = 64 KiB floor, so the head is 0..(300_000 - 65_536)
1214        let budget = ReadBudget::unlimited();
1215        let got = whole_object(&store, &budget, &p, &path)
1216            .await
1217            .expect("whole_object");
1218        assert_eq!(&got[..], &bytes[..]);
1219        assert!(store.requests() > 2, "the head should have been split");
1220    }
1221
1222    #[tokio::test]
1223    async fn whole_object_never_double_charges_bytes_the_tail_probe_already_fetched() {
1224        // Finding 8: the head's own plan used to be built against the
1225        // object's full size, so `align_out` could round the head group's
1226        // end past `tail_start` — straight into bytes the tail probe
1227        // already fetched, re-fetching and re-charging them. The head must
1228        // be planned against `tail_start`, not `size`, so its own aligned
1229        // extent can never cross into the tail's region. A budget set to
1230        // exactly the real object size must suffice; under the bug it did
1231        // not, because the double-counted overlap pushed the real total
1232        // charged past that size.
1233        use object_store::ObjectStoreExt;
1234        let store = CountingStore::default();
1235        let path = Path::from("obj.bin");
1236        let size: u32 = 70_000;
1237        let bytes: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
1238        store.put(&path, bytes.clone().into()).await.expect("put");
1239
1240        // part_size doubles as the probe size here (DISCOVERY_PROBE_FLOOR is
1241        // 64 KiB, matched exactly so tail_start lands at size - 65536 =
1242        // 4464), and align (128 KiB) is far bigger than that head region —
1243        // big enough that an unclipped align_out would round the head's end
1244        // out past the whole object, deep into the tail. An unlimited
1245        // budget (not a tight one) is what forces execute() to pick the
1246        // merged, aligned head candidate instead of silently falling back
1247        // to the unaligned unmerged one — the fallback that would otherwise
1248        // paper over this bug without the budget even noticing.
1249        let p = policy(0, 0, 1, u64::MAX, 65_536, 131_072);
1250        let budget = ReadBudget::unlimited();
1251        let got = whole_object(&store, &budget, &p, &path)
1252            .await
1253            .expect("whole_object");
1254        assert_eq!(&got[..], &bytes[..]);
1255        assert_eq!(
1256            budget.used(),
1257            u64::from(size),
1258            "the head must never be planned past tail_start, or its \
1259             aligned-out extent re-fetches and re-charges bytes the tail \
1260             probe already covered"
1261        );
1262    }
1263
1264    /// A store that always serves a truncated response, shorter than
1265    /// whatever range was requested — standing in for a buggy or
1266    /// misbehaving backend. Library code must never panic on this (CLAUDE.md's
1267    /// "decoders never panic"), it must error.
1268    #[derive(Debug, Default)]
1269    struct TruncatingStore {
1270        inner: object_store::memory::InMemory,
1271    }
1272
1273    impl std::fmt::Display for TruncatingStore {
1274        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1275            write!(f, "TruncatingStore")
1276        }
1277    }
1278
1279    #[async_trait::async_trait]
1280    impl ObjectStore for TruncatingStore {
1281        async fn put_opts(
1282            &self,
1283            location: &Path,
1284            payload: object_store::PutPayload,
1285            opts: object_store::PutOptions,
1286        ) -> object_store::Result<object_store::PutResult> {
1287            self.inner.put_opts(location, payload, opts).await
1288        }
1289
1290        async fn put_multipart_opts(
1291            &self,
1292            location: &Path,
1293            opts: object_store::PutMultipartOptions,
1294        ) -> object_store::Result<Box<dyn object_store::MultipartUpload>> {
1295            self.inner.put_multipart_opts(location, opts).await
1296        }
1297
1298        async fn get_opts(
1299            &self,
1300            location: &Path,
1301            options: object_store::GetOptions,
1302        ) -> object_store::Result<object_store::GetResult> {
1303            let got = self.inner.get_opts(location, options).await?;
1304            let (meta, range, attributes) =
1305                (got.meta.clone(), got.range.clone(), got.attributes.clone());
1306            let full = got.bytes().await?;
1307            let short = full.slice(..full.len() / 2);
1308            Ok(object_store::GetResult {
1309                payload: object_store::GetResultPayload::Stream(Box::pin(futures::stream::once(
1310                    async move { Ok(short) },
1311                ))),
1312                meta,
1313                range,
1314                attributes,
1315                extensions: Default::default(),
1316            })
1317        }
1318
1319        fn delete_stream(
1320            &self,
1321            locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
1322        ) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
1323            self.inner.delete_stream(locations)
1324        }
1325
1326        fn list(
1327            &self,
1328            prefix: Option<&Path>,
1329        ) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
1330        {
1331            self.inner.list(prefix)
1332        }
1333
1334        async fn list_with_delimiter(
1335            &self,
1336            prefix: Option<&Path>,
1337        ) -> object_store::Result<object_store::ListResult> {
1338            self.inner.list_with_delimiter(prefix).await
1339        }
1340
1341        async fn copy_opts(
1342            &self,
1343            from: &Path,
1344            to: &Path,
1345            options: object_store::CopyOptions,
1346        ) -> object_store::Result<()> {
1347            self.inner.copy_opts(from, to, options).await
1348        }
1349    }
1350
1351    #[tokio::test]
1352    async fn a_short_response_is_an_error_not_a_panic() {
1353        use object_store::ObjectStoreExt;
1354        let store = TruncatingStore::default();
1355        let path = Path::from("obj.bin");
1356        store.put(&path, vec![0u8; 100].into()).await.expect("put");
1357
1358        let p = FetchPolicy::local();
1359        let budget = ReadBudget::unlimited();
1360        let planned = plan(&p, &[0..100], 100);
1361        let err = execute(&store, &budget, &path, planned)
1362            .await
1363            .expect_err("a truncated response must error, not panic");
1364        assert!(matches!(err, ItzmaError::Storage(_)), "{err:?}");
1365    }
1366}