hawdb-storage 0.13.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! One row-page/row grammar, specialized for ordinary and cooperative work.
//! Work hooks preserve the existing unit, comparison, copy and integrity paths.

use super::*;
use crate::background::{CheckpointWorkContext, CheckpointWorkUnit};

pub(super) trait EncodeUnit {
    fn finish(self);
}

pub(super) trait EncodeWork {
    type Unit: EncodeUnit;
    fn start_unit(&self) -> Result<Self::Unit, RelationalRowPageError>;
    fn checkpoint(&self) -> Result<(), RelationalRowPageError>;
    fn ordered_key(&self, key: &RelationalKey) -> Result<Vec<u8>, RelationalRowPageError>;
    fn compare(
        &self,
        left: &[u8],
        right: &[u8],
    ) -> Result<std::cmp::Ordering, RelationalRowPageError>;
    fn append(&self, output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), RelationalRowPageError>;
    fn integrity(&self, encoded: &mut [u8]) -> Result<(), RelationalRowPageError>;
    fn scratch_vector_capacity<T>(
        &self,
        capacity: usize,
    ) -> Result<Vec<T>, RelationalRowPageError> {
        Ok(Vec::with_capacity(capacity))
    }
    fn output_vector_capacity<T>(&self, capacity: usize) -> Result<Vec<T>, RelationalRowPageError> {
        Ok(Vec::with_capacity(capacity))
    }
}

pub(super) struct NoWork;
pub(super) struct NoWorkUnit;
impl EncodeUnit for NoWorkUnit {
    #[inline]
    fn finish(self) {}
}
impl EncodeWork for NoWork {
    type Unit = NoWorkUnit;
    #[inline]
    fn start_unit(&self) -> Result<NoWorkUnit, RelationalRowPageError> {
        Ok(NoWorkUnit)
    }
    #[inline]
    fn checkpoint(&self) -> Result<(), RelationalRowPageError> {
        Ok(())
    }
    fn ordered_key(&self, key: &RelationalKey) -> Result<Vec<u8>, RelationalRowPageError> {
        encode_ordered_relational_key(key)
            .map_err(|error| RelationalRowPageError::Admission(error.to_string()))
    }
    fn compare(
        &self,
        left: &[u8],
        right: &[u8],
    ) -> Result<std::cmp::Ordering, RelationalRowPageError> {
        Ok(left.cmp(right))
    }
    fn append(&self, output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), RelationalRowPageError> {
        output.extend_from_slice(bytes);
        Ok(())
    }
    fn integrity(&self, encoded: &mut [u8]) -> Result<(), RelationalRowPageError> {
        write_integrity(encoded);
        Ok(())
    }
}

pub(super) struct ControlledWork<'a>(pub(super) &'a CheckpointWorkContext);
impl EncodeUnit for CheckpointWorkUnit {
    fn finish(self) {
        CheckpointWorkUnit::finish(self);
    }
}
impl EncodeWork for ControlledWork<'_> {
    type Unit = CheckpointWorkUnit;
    fn start_unit(&self) -> Result<Self::Unit, RelationalRowPageError> {
        self.0.start_unit().map_err(checkpoint::work_error)
    }
    fn checkpoint(&self) -> Result<(), RelationalRowPageError> {
        self.0.checkpoint().map_err(checkpoint::work_error)
    }
    fn ordered_key(&self, key: &RelationalKey) -> Result<Vec<u8>, RelationalRowPageError> {
        checkpoint::ordered_key(key, self.0)
    }
    fn compare(
        &self,
        left: &[u8],
        right: &[u8],
    ) -> Result<std::cmp::Ordering, RelationalRowPageError> {
        checkpoint::compare(left, right, self.0)
    }
    fn append(&self, output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), RelationalRowPageError> {
        checkpoint::append(output, bytes, self.0)
    }
    fn integrity(&self, encoded: &mut [u8]) -> Result<(), RelationalRowPageError> {
        let work = self;
        let mut hasher = IntegrityHasher::new();
        for region in [
            &encoded[..INTEGRITY_PREFIX_BYTES],
            &encoded[ROW_PAGE_HEADER_BYTES..],
        ] {
            for block in region.chunks(64 * 1024) {
                let unit = work.start_unit()?;
                hasher.update(block);
                unit.finish();
            }
        }
        let unit = work.start_unit()?;
        let digest = hasher.finish();
        encoded[104..108].copy_from_slice(&digest.crc32c.get().to_le_bytes());
        encoded[108..140].copy_from_slice(digest.sha256.as_bytes());
        unit.finish();
        Ok(())
    }
}

pub(super) struct AllocatedRowWork<'a> {
    pub(super) output: &'a crate::background::CheckpointDecodeContext,
    pub(super) scratch: &'a crate::background::CheckpointDecodeContext,
}

impl EncodeWork for AllocatedRowWork<'_> {
    type Unit = CheckpointWorkUnit;
    fn start_unit(&self) -> Result<Self::Unit, RelationalRowPageError> {
        ControlledWork(self.output).start_unit()
    }
    fn checkpoint(&self) -> Result<(), RelationalRowPageError> {
        ControlledWork(self.output).checkpoint()
    }
    fn ordered_key(&self, key: &RelationalKey) -> Result<Vec<u8>, RelationalRowPageError> {
        ControlledWork(self.output).ordered_key(key)
    }
    fn compare(
        &self,
        left: &[u8],
        right: &[u8],
    ) -> Result<std::cmp::Ordering, RelationalRowPageError> {
        ControlledWork(self.output).compare(left, right)
    }
    fn append(&self, output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), RelationalRowPageError> {
        if bytes.len() > output.capacity() - output.len() {
            return Err(checkpoint::work_error(self.output.record_failure(
                crate::background::CheckpointWorkError::Allocation {
                    bytes: bytes.len() as u64,
                    reason: "row encoder exceeded admitted capacity".into(),
                },
            )));
        }
        ControlledWork(self.output).append(output, bytes)
    }
    fn integrity(&self, encoded: &mut [u8]) -> Result<(), RelationalRowPageError> {
        ControlledWork(self.output).integrity(encoded)
    }
    fn scratch_vector_capacity<T>(
        &self,
        capacity: usize,
    ) -> Result<Vec<T>, RelationalRowPageError> {
        self.scratch
            .vector_capacity(capacity)
            .map_err(|error| RelationalRowPageError::Admission(error.to_string()))
    }
    fn output_vector_capacity<T>(&self, capacity: usize) -> Result<Vec<T>, RelationalRowPageError> {
        self.output
            .vector_capacity(capacity)
            .map_err(|error| RelationalRowPageError::Admission(error.to_string()))
    }
}

pub(super) fn encode<W: EncodeWork>(
    page: &ImmutableRelationalRowPage,
    limits: RelationalRowPageLimits,
    work: &W,
) -> Result<Vec<u8>, RelationalRowPageError> {
    let unit = work.start_unit()?;
    validate_page_for_encode(page, limits)?;

    let mut slots = Vec::with_capacity(page.rows.len());
    let mut key_payload = Vec::new();
    let mut row_payload = Vec::new();
    let mut lower_bound: Option<Vec<u8>> = None;
    let mut previous_key: Option<Vec<u8>> = None;
    unit.finish();
    for entry in &page.rows {
        let key = work.ordered_key(&entry.primary_key)?;
        let unit = work.start_unit()?;
        if key.len() > limits.max_key_bytes.get() {
            return Err(RelationalRowPageError::Admission(format!(
                "primary key contains {} bytes, exceeding limit {}",
                key.len(),
                limits.max_key_bytes
            )));
        }
        unit.finish();
        if previous_key
            .as_ref()
            .map(|previous| work.compare(previous, &key))
            .transpose()?
            .is_some_and(|ordering| ordering != std::cmp::Ordering::Less)
        {
            return Err(RelationalRowPageError::Admission(
                "row primary keys are not strictly increasing".to_string(),
            ));
        }

        let row = encode_row(&entry.row, page.column_count, limits, work)?;
        let unit = work.start_unit()?;
        if row.len() > limits.max_row_bytes.get() {
            return Err(RelationalRowPageError::Admission(format!(
                "encoded row contains {} bytes, exceeding limit {}",
                row.len(),
                limits.max_row_bytes
            )));
        }
        let slot = RowSlot {
            key_offset: u32_len(key_payload.len(), "key offset")?,
            key_len: u32_len(key.len(), "key length")?,
            row_offset: u32_len(row_payload.len(), "row offset")?,
            row_len: u32_len(row.len(), "row length")?,
        };
        let next_key_bytes = key_payload.len().checked_add(key.len()).ok_or_else(|| {
            RelationalRowPageError::Admission("key payload length overflow".to_string())
        })?;
        let next_row_bytes = row_payload.len().checked_add(row.len()).ok_or_else(|| {
            RelationalRowPageError::Admission("row payload length overflow".to_string())
        })?;
        let directory_bytes = page.rows.len().checked_mul(ROW_SLOT_BYTES).ok_or_else(|| {
            RelationalRowPageError::Admission("row slot directory length overflow".to_string())
        })?;
        let lower_len = lower_bound.as_ref().map_or(key.len(), Vec::len);
        let projected_bytes = ROW_PAGE_HEADER_BYTES
            .checked_add(lower_len)
            .and_then(|bytes| bytes.checked_add(key.len()))
            .and_then(|bytes| bytes.checked_add(directory_bytes))
            .and_then(|bytes| bytes.checked_add(next_key_bytes))
            .and_then(|bytes| bytes.checked_add(next_row_bytes))
            .ok_or_else(|| {
                RelationalRowPageError::Admission("encoded page size overflow".to_string())
            })?;
        if projected_bytes > limits.max_page_bytes.get() {
            return Err(RelationalRowPageError::Admission(format!(
                "encoded page would contain {projected_bytes} bytes, exceeding limit {}",
                limits.max_page_bytes
            )));
        }
        unit.finish();
        work.append(&mut key_payload, &key)?;
        work.append(&mut row_payload, &row)?;
        let unit = work.start_unit()?;
        slots.push(slot);
        unit.finish();
        if lower_bound.is_none() {
            let mut lower = Vec::new();
            work.append(&mut lower, &key)?;
            lower_bound = Some(lower);
        }
        previous_key = Some(key);
    }

    let unit = work.start_unit()?;
    let lower_bound = lower_bound.expect("validated row page has a lower key bound");
    let upper_bound = previous_key.expect("validated row page has an upper key bound");
    let directory_len = slots.len().checked_mul(ROW_SLOT_BYTES).ok_or_else(|| {
        RelationalRowPageError::Admission("row slot directory length overflow".to_string())
    })?;
    let payload_len = lower_bound
        .len()
        .checked_add(upper_bound.len())
        .and_then(|bytes| bytes.checked_add(directory_len))
        .and_then(|bytes| bytes.checked_add(key_payload.len()))
        .and_then(|bytes| bytes.checked_add(row_payload.len()))
        .ok_or_else(|| {
            RelationalRowPageError::Admission("encoded page payload overflow".to_string())
        })?;
    let total_len = ROW_PAGE_HEADER_BYTES
        .checked_add(payload_len)
        .ok_or_else(|| {
            RelationalRowPageError::Admission("encoded page length overflow".to_string())
        })?;
    if total_len > limits.max_page_bytes.get() {
        return Err(RelationalRowPageError::Admission(format!(
            "encoded page contains {total_len} bytes, exceeding limit {}",
            limits.max_page_bytes
        )));
    }

    let mut encoded = Vec::with_capacity(total_len);
    encoded.extend_from_slice(ROW_PAGE_MAGIC);
    encoded.extend_from_slice(&ROW_PAGE_VERSION.to_le_bytes());
    encoded.extend_from_slice(&0u16.to_le_bytes());
    encoded.extend_from_slice(&page.generation.to_le_bytes());
    encoded.extend_from_slice(&page.source_commit_epoch.to_le_bytes());
    encoded.extend_from_slice(&page.page_id.get().to_le_bytes());
    encoded.extend_from_slice(&u32_len(page.rows.len(), "row count")?.to_le_bytes());
    encoded.extend_from_slice(&u32_len(page.column_count, "column count")?.to_le_bytes());
    encoded.extend_from_slice(&u32_len(lower_bound.len(), "lower key length")?.to_le_bytes());
    encoded.extend_from_slice(&u32_len(upper_bound.len(), "upper key length")?.to_le_bytes());
    encoded.extend_from_slice(&u32_len(directory_len, "directory length")?.to_le_bytes());
    encoded.extend_from_slice(&u64_len(key_payload.len(), "key payload length")?.to_le_bytes());
    encoded.extend_from_slice(&u64_len(row_payload.len(), "row payload length")?.to_le_bytes());
    encoded.extend_from_slice(page.schema_digest.as_bytes());
    debug_assert_eq!(encoded.len(), INTEGRITY_PREFIX_BYTES);
    encoded.extend_from_slice(&[0; 4 + SHA256_BYTES]);
    debug_assert_eq!(encoded.len(), ROW_PAGE_HEADER_BYTES);
    unit.finish();
    work.append(&mut encoded, &lower_bound)?;
    work.append(&mut encoded, &upper_bound)?;
    for slot in slots {
        let unit = work.start_unit()?;
        slot.encode(&mut encoded);
        unit.finish();
    }
    work.append(&mut encoded, &key_payload)?;
    work.append(&mut encoded, &row_payload)?;
    work.integrity(&mut encoded)?;
    work.checkpoint()?;
    Ok(encoded)
}

pub(super) fn encode_row<W: EncodeWork>(
    row: &RelationalRow,
    column_count: usize,
    limits: RelationalRowPageLimits,
    work: &W,
) -> Result<Vec<u8>, RelationalRowPageError> {
    let unit = work.start_unit()?;
    if row.values().len() != column_count {
        return Err(RelationalRowPageError::Admission(format!(
            "row contains {} values, expected {column_count}",
            row.values().len()
        )));
    }
    let directory_len = column_count.checked_mul(VALUE_SLOT_BYTES).ok_or_else(|| {
        RelationalRowPageError::Admission("value slot directory length overflow".to_string())
    })?;
    let header_len = 4usize.checked_add(directory_len).ok_or_else(|| {
        RelationalRowPageError::Admission("encoded row header length overflow".to_string())
    })?;
    if header_len > limits.max_row_bytes.get() {
        return Err(RelationalRowPageError::Admission(format!(
            "row directory contains {header_len} bytes, exceeding row limit {}",
            limits.max_row_bytes
        )));
    }
    // Count with the same value grammar before allocating payload backing.
    // Check each cumulative row extent in the same order as materialization.
    let mut count = value::CountingValueOutput::default();
    for value in row.values() {
        u32_len(count.length, "value offset")?;
        value::encode_value_with_work(&mut count, value, limits, &NoWork)?;
        let projected_len = header_len.checked_add(count.length).ok_or_else(|| {
            RelationalRowPageError::Admission("encoded row length overflow".to_string())
        })?;
        if projected_len > limits.max_row_bytes.get() {
            return Err(RelationalRowPageError::Admission(format!(
                "encoded row would contain {projected_len} bytes, exceeding limit {}",
                limits.max_row_bytes
            )));
        }
    }
    let mut slots = work.scratch_vector_capacity(column_count)?;
    let mut payload = work.scratch_vector_capacity(count.length)?;
    unit.finish();
    for value in row.values() {
        let unit = work.start_unit()?;
        let offset = u32_len(payload.len(), "value offset")?;
        let before = payload.len();
        unit.finish();
        value::encode_value_with_work(&mut payload, value, limits, work)?;
        let unit = work.start_unit()?;
        let length = payload.len().checked_sub(before).ok_or_else(|| {
            RelationalRowPageError::Admission("value length underflow".to_string())
        })?;
        slots.push((offset, u32_len(length, "value length")?));
        let projected_len = header_len.checked_add(payload.len()).ok_or_else(|| {
            RelationalRowPageError::Admission("encoded row length overflow".to_string())
        })?;
        if projected_len > limits.max_row_bytes.get() {
            return Err(RelationalRowPageError::Admission(format!(
                "encoded row would contain {projected_len} bytes, exceeding limit {}",
                limits.max_row_bytes
            )));
        }
        unit.finish();
    }
    let unit = work.start_unit()?;
    let mut encoded = work.output_vector_capacity(header_len + payload.len())?;
    encoded.extend_from_slice(&u32_len(column_count, "row value count")?.to_le_bytes());
    unit.finish();
    for (offset, length) in slots {
        let unit = work.start_unit()?;
        encoded.extend_from_slice(&offset.to_le_bytes());
        encoded.extend_from_slice(&length.to_le_bytes());
        unit.finish();
    }
    work.append(&mut encoded, &payload)?;
    work.checkpoint()?;
    Ok(encoded)
}