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