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