Skip to main content

rudb_native/
section.rs

1//! The section table: one general mechanism for carrying a graph structure in a rudb file.
2//!
3//! spec/graph/03-the-file-format.md section 3.2 asks for one mechanism and three section kinds
4//! rather than three mechanisms. A section is an opaque payload with a kind, an identity, a
5//! generation stamp and a list of extents, and this module is the whole of what the format knows
6//! about one. What a key map or a forward link *means* lives in `rudb-graph` at rank 5, which is
7//! below the format on purpose: a key map that could see a page would be a key map that could only
8//! be tested through a file.
9//!
10//! Three rules make the mechanism the last one the format needs.
11//!
12//! A reader ignores a kind it does not know. That is what [`Section::kind`] being eight opaque
13//! bytes rather than an enum is for: a build that meets `RUDBAJ1\0` before backward adjacency
14//! exists carries the entry through, does not read the payload, and answers the query without it.
15//! Section 3.1 guarantees the answer is the same either way, so ignoring is always available and no
16//! future section kind needs another format bump.
17//!
18//! A section is a list of extents of at most [`MAX_EXTENT`] bytes, each independently checksummed
19//! and readable. Issue #745 is what this rule is for: a single buffer works until it does not, and
20//! an SF100 `lineitem` neighbour array is two gigabytes. Splitting is not an optimization here, it
21//! is the difference between a structure that exists at scale and one that does not.
22//!
23//! Sections are written before the directory and committed by the two-generation header swap the
24//! format already performs. So a crash during a section build leaves unreferenced trailing bytes in
25//! the file and nothing else, and there is no new recovery path to write or to test.
26
27use rudb_common::{Error, Result};
28
29/// Bytes one section table entry takes on disk.
30///
31/// Fifty six, per section 3.2, and fixed rather than variable because the entry list is walked at
32/// open to decide which sections this build understands and a fixed stride makes that a multiply.
33pub(crate) const ENTRY_BYTES: usize = 56;
34
35/// The largest one extent may be.
36///
37/// Sixty four megabytes. Small enough that a reader can hold one while it checksums it, and large
38/// enough that even an SF100 `lineitem` forward link is tens of extents rather than thousands.
39pub const MAX_EXTENT: u32 = 64 * 1024 * 1024;
40
41/// The most extents one section may have.
42///
43/// Sixty four megabytes each, so this bounds a section at a terabyte. The bound exists so that a
44/// torn directory naming four billion extents is refused at decode rather than turned into an
45/// allocation.
46pub const MAX_EXTENTS: u32 = 16 * 1024;
47
48/// A key map, per section 3.3.
49pub const KEY_MAP: &[u8; 8] = b"RUDBKM1\0";
50
51/// A forward link column, per section 3.4.
52pub const FORWARD_LINK: &[u8; 8] = b"RUDBFL1\0";
53
54/// A backward adjacency list, per section 3.5.
55pub const ADJACENCY: &[u8; 8] = b"RUDBAJ1\0";
56
57/// A column summary, per `spec/stats/03-the-file-format.md` section 3.3.
58///
59/// The first kind here that is not from the graph document, which is the point of the mechanism
60/// rather than a complication of it. A statistics section is carried, stamped, split and ignored by
61/// exactly the rules above, and adding it took two constants and one arm below.
62pub const SUMMARY: &[u8; 8] = b"RUDBCS1\0";
63
64/// A column's sketches, per `spec/stats/03-the-file-format.md` section 3.4.
65pub const SKETCHES: &[u8; 8] = b"RUDBSK1\0";
66
67/// The kinds the graph document owns, which share its ten percent of the column bytes.
68pub const GRAPH_KINDS: &[&[u8; 8]] = &[KEY_MAP, FORWARD_LINK, ADJACENCY];
69
70/// The kinds the statistics document owns, which share its two percent.
71///
72/// Two lists rather than one because the two budgets are separate, and separate means each counts
73/// only what it owns. A statistics build that counted the key maps as already spent would be a
74/// statistics budget the graph layer eats: a TPC-H SF10 file's key maps are 7.7 MB against a two
75/// percent allowance of 54 MB, so a seventh of the statistics budget would go to sections that have
76/// their own.
77///
78/// A kind in neither list is one a later build wrote, and it counts against neither. There is no
79/// better answer available, since this build cannot know which document invented it, and charging
80/// it to both would make every budget here tighter than the document says by an amount that depends
81/// on what some other build did.
82pub const STATISTICS_KINDS: &[&[u8; 8]] = &[SUMMARY, SKETCHES];
83
84/// One entry in a table's section table.
85///
86/// The payload is not here. This is the entry that says where the payload is, what it is, and
87/// whether it is still current, and it is all a reader needs to decide whether to read the payload
88/// at all.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct Section {
91    /// Which kind of structure this is: one of [`KEY_MAP`], [`FORWARD_LINK`], [`ADJACENCY`], or
92    /// something a later build wrote that this one carries through untouched.
93    pub kind: [u8; 8],
94    /// Which structure of that kind. For a key map this identifies the column, for a forward link
95    /// the relationship. The format does not interpret it; `rudb-graph` assigns it.
96    pub id: u64,
97    /// The table generation this section was built against.
98    ///
99    /// A section whose stamp does not match the table's is stale, and section 3.1 says stale means
100    /// ignored rather than repaired. So this field is the whole of the maintenance story: there is
101    /// no repair path in this crate because a mismatch here removes the section from consideration
102    /// and the query runs the way it ran before the section existed.
103    pub generation: u64,
104    /// How many extents the payload is split into.
105    pub extents: u32,
106    /// Where the extent table starts.
107    pub extent_page: u64,
108    /// How many bytes the extent table takes.
109    pub extent_bytes: u32,
110    /// Checksum over the extent table, so a torn one is found before it is believed.
111    pub hash: u64,
112    /// Kind-specific flags. For a key map this carries which of the three forms was chosen, which
113    /// is why a reader never has to guess a form.
114    pub flags: u32,
115    /// Bytes of kind-specific header at the front of the first extent.
116    pub header_bytes: u32,
117}
118
119impl Section {
120    /// Appends this entry's fifty six bytes.
121    ///
122    /// # Errors
123    ///
124    /// If the entry describes something that cannot exist: more extents than [`MAX_EXTENTS`], or an
125    /// extent table larger than one extent. Both are caught here rather than at decode because a
126    /// writer that produced one has a bug, and the bug should stop at the write.
127    pub(crate) fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
128        if self.extents > MAX_EXTENTS {
129            return Err(malformed(format!(
130                "a section of {} extents exceeds the bound of {MAX_EXTENTS}",
131                self.extents
132            )));
133        }
134        if self.extent_bytes > MAX_EXTENT {
135            return Err(malformed("a section's extent table is larger than one extent"));
136        }
137        let before = out.len();
138        out.extend_from_slice(&self.kind);
139        out.extend_from_slice(&self.id.to_le_bytes());
140        out.extend_from_slice(&self.generation.to_le_bytes());
141        out.extend_from_slice(&self.extents.to_le_bytes());
142        out.extend_from_slice(&self.extent_page.to_le_bytes());
143        out.extend_from_slice(&self.extent_bytes.to_le_bytes());
144        out.extend_from_slice(&self.hash.to_le_bytes());
145        out.extend_from_slice(&self.flags.to_le_bytes());
146        out.extend_from_slice(&self.header_bytes.to_le_bytes());
147        debug_assert_eq!(out.len() - before, ENTRY_BYTES, "a section entry is fifty six bytes");
148        Ok(())
149    }
150
151    /// Reads one entry from exactly [`ENTRY_BYTES`] bytes.
152    ///
153    /// # Errors
154    ///
155    /// If the slice is the wrong length, or if the entry names more extents than [`MAX_EXTENTS`] or
156    /// an extent table larger than one extent. A bad entry is an error and not a panic because the
157    /// caller's answer to one is to drop the section and open the table anyway.
158    pub(crate) fn decode(bytes: &[u8]) -> Result<Self> {
159        if bytes.len() != ENTRY_BYTES {
160            return Err(malformed("a section entry is not fifty six bytes"));
161        }
162        let section = Self {
163            kind: bytes[0..8].try_into().expect("eight bytes"),
164            id: u64::from_le_bytes(bytes[8..16].try_into().expect("eight bytes")),
165            generation: u64::from_le_bytes(bytes[16..24].try_into().expect("eight bytes")),
166            extents: u32::from_le_bytes(bytes[24..28].try_into().expect("four bytes")),
167            extent_page: u64::from_le_bytes(bytes[28..36].try_into().expect("eight bytes")),
168            extent_bytes: u32::from_le_bytes(bytes[36..40].try_into().expect("four bytes")),
169            hash: u64::from_le_bytes(bytes[40..48].try_into().expect("eight bytes")),
170            flags: u32::from_le_bytes(bytes[48..52].try_into().expect("four bytes")),
171            header_bytes: u32::from_le_bytes(bytes[52..56].try_into().expect("four bytes")),
172        };
173        if section.extents > MAX_EXTENTS {
174            return Err(malformed("a section names more extents than the bound allows"));
175        }
176        if section.extent_bytes > MAX_EXTENT {
177            return Err(malformed("a section's extent table is larger than one extent"));
178        }
179        Ok(section)
180    }
181
182    /// Whether this build understands this section's kind.
183    ///
184    /// The five it knows are the three the graph document's section 3.2 names and the two the
185    /// statistics document's sections 3.3 and 3.4 name. Everything else is a section a later build
186    /// wrote, and the answer is to leave it alone: the entry is carried through a rewrite so that
187    /// opening a file with an old build and closing it does not silently discard work, and the
188    /// payload is never read.
189    #[must_use]
190    pub fn known(&self) -> bool {
191        matches!(&self.kind, KEY_MAP | FORWARD_LINK | ADJACENCY | SUMMARY | SKETCHES)
192    }
193
194    /// Whether this section's kind is one of these, which is how a budget finds what it owns.
195    #[must_use]
196    pub fn among(&self, kinds: &[&[u8; 8]]) -> bool {
197        kinds.iter().any(|kind| self.kind == **kind)
198    }
199
200    /// Whether this section was built against this table generation.
201    #[must_use]
202    pub fn current(&self, generation: u64) -> bool {
203        self.generation == generation
204    }
205
206    /// Whether this section is one this build should read: a kind it knows, at the current
207    /// generation.
208    #[must_use]
209    pub fn usable(&self, generation: u64) -> bool {
210        self.known() && self.current(generation)
211    }
212}
213
214/// One section to be written into a file, handed to [`crate::attach`].
215///
216/// The payload is bytes and the format keeps it that way. Which of the three key map forms is in
217/// `flags`, and what the first `header_bytes` bytes mean, are questions `rudb-graph` answers and
218/// this crate never asks, which is what makes the first of section 3.2's three rules true rather
219/// than intended: a mechanism that had to understand a payload could not carry one it had never
220/// heard of.
221#[derive(Debug, Clone, Copy)]
222pub struct Attachment<'a> {
223    /// Which kind of structure this is, usually one of [`KEY_MAP`], [`FORWARD_LINK`],
224    /// [`ADJACENCY`].
225    pub kind: [u8; 8],
226    /// Which structure of that kind. An attachment replaces any section already in the table with
227    /// the same kind and id, which is what makes rebuilding a key map a write rather than a
228    /// question about what to do with the old one.
229    pub id: u64,
230    /// Kind-specific flags, copied into the entry and not interpreted.
231    pub flags: u32,
232    /// How many bytes at the front of `bytes` are the kind's own header.
233    pub header_bytes: u32,
234    /// The payload. Empty is legal and is how section 3.7 records a relationship that did not fit
235    /// the budget: an entry with no extents, its size reported by `rudb_links()`, and nothing in
236    /// the file to read.
237    pub bytes: &'a [u8],
238}
239
240/// Where one extent of a section's payload lives.
241///
242/// Each carries its own checksum, which is the second of section 3.2's three rules: an extent is
243/// independently readable, so a reduction that only needs the third extent of a forward link reads
244/// and verifies one extent rather than two gigabytes.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub struct Extent {
247    /// Where the extent's bytes start.
248    pub offset: u64,
249    /// How many bytes it holds, at most [`MAX_EXTENT`].
250    pub length: u32,
251    /// Checksum over those bytes.
252    pub hash: u64,
253    /// How many logical elements precede this extent, so that a random access can find the extent
254    /// holding an element without reading any of them.
255    pub first: u64,
256}
257
258/// Bytes one extent entry takes in an extent table.
259pub const EXTENT_BYTES: usize = 28;
260
261impl Extent {
262    /// Appends this extent's twenty eight bytes.
263    ///
264    /// # Errors
265    ///
266    /// If the extent is larger than [`MAX_EXTENT`], which is the rule the split exists to keep.
267    pub(crate) fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
268        if self.length > MAX_EXTENT {
269            return Err(malformed(format!(
270                "an extent of {} bytes exceeds the maximum of {MAX_EXTENT}",
271                self.length
272            )));
273        }
274        out.extend_from_slice(&self.offset.to_le_bytes());
275        out.extend_from_slice(&self.length.to_le_bytes());
276        out.extend_from_slice(&self.hash.to_le_bytes());
277        out.extend_from_slice(&self.first.to_le_bytes());
278        Ok(())
279    }
280
281    /// Reads one extent from exactly [`EXTENT_BYTES`] bytes.
282    ///
283    /// # Errors
284    ///
285    /// If the slice is the wrong length or the extent is oversized.
286    pub(crate) fn decode(bytes: &[u8]) -> Result<Self> {
287        if bytes.len() != EXTENT_BYTES {
288            return Err(malformed("an extent entry is not twenty eight bytes"));
289        }
290        let extent = Self {
291            offset: u64::from_le_bytes(bytes[0..8].try_into().expect("eight bytes")),
292            length: u32::from_le_bytes(bytes[8..12].try_into().expect("four bytes")),
293            hash: u64::from_le_bytes(bytes[12..20].try_into().expect("eight bytes")),
294            first: u64::from_le_bytes(bytes[20..28].try_into().expect("eight bytes")),
295        };
296        if extent.length > MAX_EXTENT {
297            return Err(malformed("an extent is larger than the maximum extent"));
298        }
299        Ok(extent)
300    }
301}
302
303/// Encodes a whole extent table, checking that it describes a contiguous run of elements.
304///
305/// # Errors
306///
307/// If an extent is oversized, if the `first` counts are not increasing, or if there are more
308/// extents than [`MAX_EXTENTS`]. The increasing check is what makes a binary search over the table
309/// meaningful, and an unchecked one would be a search that silently returned the wrong extent.
310pub fn encode_extents(extents: &[Extent], out: &mut Vec<u8>) -> Result<()> {
311    if extents.len() > MAX_EXTENTS as usize {
312        return Err(malformed("a section names more extents than the bound allows"));
313    }
314    for (at, extent) in extents.iter().enumerate() {
315        if at == 0 {
316            if extent.first != 0 {
317                return Err(malformed("a section's first extent does not start at element zero"));
318            }
319        } else if extent.first <= extents[at - 1].first {
320            return Err(malformed("a section's extents are not in element order"));
321        }
322        extent.encode(out)?;
323    }
324    Ok(())
325}
326
327/// Decodes a whole extent table.
328///
329/// # Errors
330///
331/// If the byte count is not a multiple of an entry, if an entry is malformed, or if the entries are
332/// not in element order.
333pub fn decode_extents(bytes: &[u8]) -> Result<Vec<Extent>> {
334    if bytes.len() % EXTENT_BYTES != 0 {
335        return Err(malformed("an extent table is not a whole number of entries"));
336    }
337    let mut extents: Vec<Extent> = Vec::with_capacity(bytes.len() / EXTENT_BYTES);
338    for chunk in bytes.chunks(EXTENT_BYTES) {
339        let extent = Extent::decode(chunk)?;
340        match extents.last() {
341            None if extent.first != 0 => {
342                return Err(malformed("a section's first extent does not start at element zero"));
343            }
344            Some(previous) if extent.first <= previous.first => {
345                return Err(malformed("a section's extents are not in element order"));
346            }
347            _ => {}
348        }
349        extents.push(extent);
350    }
351    Ok(extents)
352}
353
354/// Which extent holds a given logical element, by binary search over the table.
355///
356/// Returns the index into `extents` and the element's offset within that extent's elements, or
357/// `None` when there are no extents at all, which is the not-built entry of section 3.7.
358///
359/// It does not bound the element from above, because an extent table cannot: the last extent's
360/// length is in bytes and only the caller knows how many elements a byte holds. So an element past
361/// the end answers with an offset past the end of the last extent, and the caller checks that
362/// against the count it already has. `None` rather than an error for the empty case because a
363/// stale link may name a structure that is no longer there, and section 3.1 wants staleness
364/// ignored.
365#[must_use]
366pub fn locate(extents: &[Extent], element: u64) -> Option<(usize, u64)> {
367    let at = extents.partition_point(|extent| extent.first <= element);
368    if at == 0 {
369        return None;
370    }
371    Some((at - 1, element - extents[at - 1].first))
372}
373
374fn malformed(message: impl Into<String>) -> Error {
375    Error::invalid_input(format!("invalid rudb section table: {}", message.into()))
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    fn entry() -> Section {
383        Section {
384            kind: *KEY_MAP,
385            id: 7,
386            generation: 42,
387            extents: 3,
388            extent_page: 1 << 20,
389            extent_bytes: 84,
390            hash: 0xdead_beef_cafe_f00d,
391            flags: 2,
392            header_bytes: 24,
393        }
394    }
395
396    #[test]
397    fn an_entry_takes_fifty_six_bytes_and_round_trips() {
398        let mut bytes = Vec::new();
399        entry().encode(&mut bytes).expect("encode");
400        assert_eq!(bytes.len(), ENTRY_BYTES, "section 3.2 says fifty six");
401        assert_eq!(Section::decode(&bytes).expect("decode"), entry());
402    }
403
404    #[test]
405    fn an_unknown_kind_is_carried_and_not_read() {
406        // The rule that makes this the last bump the mechanism needs. A build that met this entry
407        // before the kind existed has to be able to hold it, report it as not understood, and open
408        // the table anyway.
409        let mut unknown = entry();
410        unknown.kind = *b"RUDBZZ9\0";
411        let mut bytes = Vec::new();
412        unknown.encode(&mut bytes).expect("an unknown kind still encodes");
413        let read = Section::decode(&bytes).expect("an unknown kind still decodes");
414        assert_eq!(read, unknown, "the entry survives a build that does not know it");
415        assert!(!read.known());
416        assert!(!read.usable(42), "a kind this build does not know is never read");
417    }
418
419    #[test]
420    fn the_kinds_the_two_documents_name_are_known() {
421        for kind in [KEY_MAP, FORWARD_LINK, ADJACENCY, SUMMARY, SKETCHES] {
422            let mut section = entry();
423            section.kind = *kind;
424            assert!(section.known(), "{}", String::from_utf8_lossy(kind));
425        }
426    }
427
428    #[test]
429    fn no_two_kinds_share_a_tag() {
430        // Worth a test now that two documents assign them. A collision would mean one kind's payload
431        // read by the other's decoder, which is the one thing an opaque payload cannot defend
432        // against by itself.
433        let all = [KEY_MAP, FORWARD_LINK, ADJACENCY, SUMMARY, SKETCHES];
434        for (at, one) in all.iter().enumerate() {
435            for other in &all[at + 1..] {
436                assert_ne!(one, other, "{}", String::from_utf8_lossy(*one));
437            }
438        }
439    }
440
441    #[test]
442    fn a_stale_section_is_ignored_rather_than_repaired() {
443        // Section 3.1's staleness rule, which is the whole of the maintenance story: the generation
444        // stamp not matching removes the section from consideration, and there is no third state
445        // between usable and ignored for a repair path to live in.
446        let section = entry();
447        assert!(section.usable(42));
448        assert!(!section.usable(43), "a rewrite invalidates rather than corrupts");
449        assert!(section.known(), "staleness is not the same question as familiarity");
450    }
451
452    #[test]
453    fn an_entry_naming_more_extents_than_the_bound_is_refused_at_both_ends() {
454        let mut oversized = entry();
455        oversized.extents = MAX_EXTENTS + 1;
456        assert!(oversized.encode(&mut Vec::new()).is_err(), "a writer's bug stops at the write");
457
458        let mut bytes = Vec::new();
459        entry().encode(&mut bytes).expect("encode");
460        bytes[24..28].copy_from_slice(&(MAX_EXTENTS + 1).to_le_bytes());
461        assert!(Section::decode(&bytes).is_err(), "a torn count is not turned into an allocation");
462    }
463
464    #[test]
465    fn a_short_entry_is_refused_rather_than_read_past() {
466        let mut bytes = Vec::new();
467        entry().encode(&mut bytes).expect("encode");
468        bytes.pop();
469        assert!(Section::decode(&bytes).is_err());
470        assert!(Section::decode(&[]).is_err());
471    }
472
473    #[test]
474    fn an_extent_at_the_maximum_is_allowed_and_one_past_it_is_not() {
475        // The bound is the point of the split, so the boundary is the case worth pinning: sixty
476        // four megabytes exactly has to work, because a payload that is a multiple of it would
477        // otherwise be unwritable.
478        let at_bound = Extent { offset: 4096, length: MAX_EXTENT, hash: 9, first: 0 };
479        let mut bytes = Vec::new();
480        at_bound.encode(&mut bytes).expect("an extent at the bound encodes");
481        assert_eq!(bytes.len(), EXTENT_BYTES);
482        assert_eq!(Extent::decode(&bytes).expect("decode"), at_bound);
483
484        let past = Extent { offset: 4096, length: MAX_EXTENT + 1, hash: 9, first: 0 };
485        assert!(past.encode(&mut Vec::new()).is_err());
486    }
487
488    fn table() -> Vec<Extent> {
489        vec![
490            Extent { offset: 1024, length: MAX_EXTENT, hash: 1, first: 0 },
491            Extent {
492                offset: 1024 + u64::from(MAX_EXTENT),
493                length: MAX_EXTENT,
494                hash: 2,
495                first: 100,
496            },
497            Extent { offset: 1024 + 2 * u64::from(MAX_EXTENT), length: 512, hash: 3, first: 250 },
498        ]
499    }
500
501    #[test]
502    fn an_extent_table_round_trips() {
503        let mut bytes = Vec::new();
504        encode_extents(&table(), &mut bytes).expect("encode");
505        assert_eq!(bytes.len(), 3 * EXTENT_BYTES);
506        assert_eq!(decode_extents(&bytes).expect("decode"), table());
507    }
508
509    #[test]
510    fn an_extent_table_out_of_element_order_is_refused() {
511        // The order is what makes the binary search in `locate` mean anything, so an unordered
512        // table has to be refused rather than searched: a search over one would return a plausible
513        // extent holding the wrong elements.
514        let mut out_of_order = table();
515        out_of_order.swap(1, 2);
516        assert!(encode_extents(&out_of_order, &mut Vec::new()).is_err());
517
518        let mut bytes = Vec::new();
519        encode_extents(&table(), &mut bytes).expect("encode");
520        bytes[EXTENT_BYTES + 20..EXTENT_BYTES + 28].copy_from_slice(&0_u64.to_le_bytes());
521        assert!(decode_extents(&bytes).is_err(), "a torn element order is refused");
522    }
523
524    #[test]
525    fn an_extent_table_not_starting_at_element_zero_is_refused() {
526        let mut shifted = table();
527        shifted[0].first = 1;
528        assert!(encode_extents(&shifted, &mut Vec::new()).is_err());
529    }
530
531    #[test]
532    fn a_partial_extent_table_is_refused_rather_than_truncated() {
533        let mut bytes = Vec::new();
534        encode_extents(&table(), &mut bytes).expect("encode");
535        bytes.truncate(bytes.len() - 1);
536        assert!(decode_extents(&bytes).is_err());
537    }
538
539    #[test]
540    fn an_empty_extent_table_is_a_section_with_no_payload() {
541        // A relationship recorded as not built, per section 3.7, is an entry with no extents. It
542        // has to be legal, because that is how `rudb_links()` reports what a larger budget would
543        // buy.
544        let mut bytes = Vec::new();
545        encode_extents(&[] as &[Extent], &mut bytes).expect("encode");
546        assert!(bytes.is_empty());
547        assert!(decode_extents(&bytes).expect("decode").is_empty());
548        assert_eq!(locate(&[], 0), None);
549    }
550
551    #[test]
552    fn an_element_resolves_to_the_extent_holding_it() {
553        let extents = table();
554        assert_eq!(locate(&extents, 0), Some((0, 0)));
555        assert_eq!(locate(&extents, 99), Some((0, 99)));
556        assert_eq!(locate(&extents, 100), Some((1, 0)), "the first element of the second extent");
557        assert_eq!(locate(&extents, 249), Some((1, 149)));
558        assert_eq!(locate(&extents, 250), Some((2, 0)));
559        assert_eq!(locate(&extents, 1_000_000), Some((2, 999_750)), "past the end of the elements");
560    }
561
562    #[test]
563    fn a_two_gigabyte_payload_is_tens_of_extents_and_not_one_buffer() {
564        // The arithmetic issue #745 is about, and the reason the split is a rule rather than an
565        // option. An SF100 lineitem forward link is 600,037,902 rows at 28 bits, which is 2.10 GB,
566        // and no reader should be asked to hold that in one buffer to checksum it.
567        let payload = 600_037_902_u64 * 28 / 8;
568        let extents = payload.div_ceil(u64::from(MAX_EXTENT));
569        assert!(extents > 30, "{extents} extents");
570        assert!(extents < u64::from(MAX_EXTENTS), "{extents} extents is inside the bound");
571    }
572}