Skip to main content

reddb_engine/storage/btree/
value_layout.rs

1//! Large-value layout for B-tree leaf cells (slice E of PRD #662).
2//!
3//! Wires the standalone slice modules together at the write/read boundary:
4//!
5//! - [`value_codec`] (slice A, #698) decides whether the bytes are worth
6//!   compressing.
7//! - [`OverflowChain`] (slice B, #699) owns the chain of dedicated overflow
8//!   pages.
9//! - `reddb-file` pins the persisted two-bit `(pointer, compressed)` cell
10//!   shape and pointer payload encoding.
11//!
12//! The function entry points are [`encode`] and [`decode`]. They persist
13//! opaque cell bytes whose on-disk shape is owned by `reddb-file`.
14//!
15//! Decision ladder applied by [`encode`]:
16//!
17//! 1. `value.len() > MAX_VALUE_SIZE` → [`ValueLayoutError::ValueTooLarge`]
18//!    (no allocation, no LZ4 work).
19//! 2. `value.len() <= OVERFLOW_THRESHOLD` → inline raw.
20//! 3. Else try LZ4. If the compressed bytes fit inline → inline compressed.
21//! 4. Else spill via [`OverflowChain`], storing only the pointer in the
22//!    leaf cell.
23//!
24//! Per ADR 0025 (overflow chain MVCC) the chain identity is anchored at
25//! the leaf cell, so this slice does not add any WAL records of its own
26//! — the overflow page writes go through the existing pager path.
27
28use crate::storage::overflow::{OverflowChain, OverflowError};
29use crate::storage::page_store::PageStore;
30use reddb_file::vector_value_codec as value_codec;
31use reddb_file::BTreeValueCell;
32
33/// At or below this length a value stores inline in the leaf, raw or
34/// compressed. Above it, the value spills via [`OverflowChain`]. Set per
35/// ADR 0023 — preserves leaf fanout regardless of page size.
36pub const OVERFLOW_THRESHOLD: usize = reddb_file::BTREE_VALUE_OVERFLOW_THRESHOLD;
37
38/// Hard upper bound on logical value size. Values above this are
39/// rejected before any LZ4 or overflow work runs.
40/// 2^28 = 256 MiB per ADR 0023.
41pub const MAX_VALUE_SIZE: usize = reddb_file::BTREE_VALUE_MAX_SIZE;
42
43/// Total stored bytes for a pointer cell — flag byte + payload.
44pub const POINTER_CELL_LEN: usize = reddb_file::BTREE_VALUE_POINTER_CELL_LEN;
45
46/// Errors returned by [`encode`] and [`decode`].
47#[derive(Debug)]
48pub enum ValueLayoutError {
49    /// Logical value length exceeds [`MAX_VALUE_SIZE`].
50    ValueTooLarge(usize),
51    /// Stored cell flag byte sets a reserved bit.
52    UnknownFlag(u8),
53    /// Stored bytes ended before the expected pointer payload.
54    TruncatedPointer { got: usize },
55    /// LZ4 decode failed.
56    Codec(value_codec::ValueCodecError),
57    /// Overflow chain operation failed.
58    Overflow(OverflowError),
59}
60
61impl std::fmt::Display for ValueLayoutError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Self::ValueTooLarge(n) => {
65                write!(f, "value too large: {} bytes (max {})", n, MAX_VALUE_SIZE)
66            }
67            Self::UnknownFlag(b) => write!(f, "unknown leaf-cell flag byte: 0b{:08b}", b),
68            Self::TruncatedPointer { got } => {
69                write!(
70                    f,
71                    "pointer cell truncated: need {} bytes after flag, got {}",
72                    POINTER_CELL_LEN - 1,
73                    got
74                )
75            }
76            Self::Codec(e) => write!(f, "value codec: {}", e),
77            Self::Overflow(e) => write!(f, "overflow chain: {}", e),
78        }
79    }
80}
81
82impl std::error::Error for ValueLayoutError {}
83
84impl From<value_codec::ValueCodecError> for ValueLayoutError {
85    fn from(e: value_codec::ValueCodecError) -> Self {
86        Self::Codec(e)
87    }
88}
89
90impl From<reddb_file::BTreeValueCellError> for ValueLayoutError {
91    fn from(e: reddb_file::BTreeValueCellError) -> Self {
92        match e {
93            reddb_file::BTreeValueCellError::UnknownFlag(flag) => Self::UnknownFlag(flag),
94            reddb_file::BTreeValueCellError::TruncatedPointer { got } => {
95                Self::TruncatedPointer { got }
96            }
97        }
98    }
99}
100
101impl From<OverflowError> for ValueLayoutError {
102    fn from(e: OverflowError) -> Self {
103        Self::Overflow(e)
104    }
105}
106
107/// Encode only when the result fits in a leaf, without allocating pages.
108pub(crate) fn encode_inline_without_pages(
109    value: &[u8],
110) -> Result<Option<Vec<u8>>, ValueLayoutError> {
111    if value.len() > MAX_VALUE_SIZE {
112        return Err(ValueLayoutError::ValueTooLarge(value.len()));
113    }
114    if value.len() <= OVERFLOW_THRESHOLD {
115        return Ok(Some(reddb_file::encode_btree_inline_raw(value)));
116    }
117    let (flag, bytes) = value_codec::encode(value);
118    if flag == value_codec::ValueFlag::Lz4 && bytes.len() <= OVERFLOW_THRESHOLD {
119        return Ok(Some(reddb_file::encode_btree_inline_compressed(&bytes)));
120    }
121    Ok(None)
122}
123
124/// Apply the decision ladder and return the bytes the B-tree should
125/// persist in the leaf cell value slot. May allocate overflow pages
126/// through `pager`.
127pub fn encode<P: PageStore>(pager: &P, value: &[u8]) -> Result<Vec<u8>, ValueLayoutError> {
128    if value.len() > MAX_VALUE_SIZE {
129        return Err(ValueLayoutError::ValueTooLarge(value.len()));
130    }
131
132    // Step 1: small values short-circuit to inline raw. No LZ4 work, no
133    // overflow allocation — preserves the legacy hot path for tiny
134    // values like entity IDs or short JSON.
135    if value.len() <= OVERFLOW_THRESHOLD {
136        return Ok(reddb_file::encode_btree_inline_raw(value));
137    }
138
139    // Step 2: above the threshold, try LZ4. The codec returns Raw when
140    // compression would not shrink the input.
141    let (codec_flag, codec_bytes) = value_codec::encode(value);
142
143    // Step 3: if compressed bytes (including their length header) fit
144    // inline, keep them in the leaf. Note this only fires when codec
145    // actually produced Lz4 bytes — Raw bytes ≥ original length > threshold
146    // by construction, so they cannot inline.
147    if codec_flag == value_codec::ValueFlag::Lz4 && codec_bytes.len() <= OVERFLOW_THRESHOLD {
148        return Ok(reddb_file::encode_btree_inline_compressed(&codec_bytes));
149    }
150
151    // Step 4: spill. We always store the bytes the codec produced —
152    // either Lz4 (with its 4-byte length header) so the reader can
153    // round-trip via the same codec, or Raw bytes when compression
154    // failed to shrink.
155    let is_compressed = codec_flag == value_codec::ValueFlag::Lz4;
156    let chain = OverflowChain::new(pager);
157    let (head, total_len) = chain.store(&codec_bytes)?;
158
159    Ok(reddb_file::encode_btree_pointer(
160        head,
161        total_len,
162        is_compressed,
163    ))
164}
165
166/// Inspect leaf-cell flags, follow the pointer if any, concatenate the
167/// chain, decode if compressed, return the materialised value.
168pub fn decode<P: PageStore>(pager: &P, stored: &[u8]) -> Result<Vec<u8>, ValueLayoutError> {
169    match reddb_file::decode_btree_value_cell(stored)? {
170        BTreeValueCell::Pointer {
171            is_compressed,
172            head_page_id,
173            total_len,
174        } => {
175            let chain = OverflowChain::new(pager);
176            let chain_bytes = chain.read(head_page_id, total_len)?;
177            if is_compressed {
178                Ok(value_codec::decode(
179                    value_codec::ValueFlag::Lz4,
180                    &chain_bytes,
181                )?)
182            } else {
183                Ok(chain_bytes)
184            }
185        }
186        BTreeValueCell::Inline {
187            is_compressed,
188            payload,
189        } => Ok(reddb_file::decode_btree_inline_payload(
190            is_compressed,
191            payload,
192        )?),
193    }
194}
195
196/// Return the head overflow page id when `stored` represents a pointer
197/// cell, else `None`. Returns `None` for inline (raw or compressed)
198/// cells and for empty/malformed cells. Callers use this from the
199/// B-tree delete and shrinking-update paths (slice F of PRD #662) to
200/// free the chain before the leaf cell goes away.
201pub fn pointer_head(stored: &[u8]) -> Option<u32> {
202    reddb_file::btree_value_pointer_head(stored)
203}
204
205/// `true` when [`encode`] would emit a spill pointer for a value of
206/// this length (without actually spilling). Used by the leaf-fit check
207/// in `bulk_insert_sorted` to size cells before allocation.
208#[inline]
209#[allow(dead_code)]
210pub fn projected_cell_len(input: &[u8]) -> usize {
211    let codec_len = value_codec::would_encode_to(input);
212    reddb_file::btree_projected_cell_len(input.len(), codec_len)
213}