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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// 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.

use super::*;

/// Exact persistent-index lookup used while staging authoritative relational
/// constraints. Implementations must represent one immutable visibility epoch,
/// emit ordered and duplicate-free primary keys, stop when the visitor returns
/// `false`, and fail closed on errors.
pub trait RelationalConstraintIndex {
    fn visit_exact_primary_keys(
        &self,
        table: &str,
        index: &str,
        key: &RelationalKey,
        visit: &mut dyn FnMut(&RelationalKey) -> bool,
    ) -> Result<(), RelationalError>;
}

type ConstraintOverlayPostings<'a> = BTreeMap<&'a RelationalKey, RelationalIndexChangeKind>;
type ConstraintIndexOverlay<'a> = BTreeMap<&'a RelationalKey, ConstraintOverlayPostings<'a>>;
type ConstraintTableOverlay<'a> = BTreeMap<&'a str, ConstraintIndexOverlay<'a>>;

struct TransactionConstraintOverlay<'a> {
    postings: BTreeMap<&'a str, ConstraintTableOverlay<'a>>,
    deleted_keys: BTreeMap<&'a str, BTreeMap<&'a str, BTreeSet<&'a RelationalKey>>>,
}

impl<'a> TransactionConstraintOverlay<'a> {
    fn new(changes: &'a [RelationalIndexChange]) -> Result<Self, RelationalError> {
        let mut postings = BTreeMap::<_, ConstraintTableOverlay<'a>>::new();
        let mut deleted_keys = BTreeMap::<_, BTreeMap<_, BTreeSet<_>>>::new();
        for change in changes {
            if postings
                .entry(change.table.as_str())
                .or_default()
                .entry(change.index.as_str())
                .or_default()
                .entry(&change.index_key)
                .or_default()
                .insert(&change.primary_key, change.kind)
                .is_some()
            {
                return Err(RelationalError::Corruption(format!(
                    "authoritative transaction overlay contains duplicate changes for {}.{}",
                    change.table, change.index
                )));
            }
            if change.kind == RelationalIndexChangeKind::Delete {
                deleted_keys
                    .entry(change.table.as_str())
                    .or_default()
                    .entry(change.index.as_str())
                    .or_default()
                    .insert(&change.index_key);
            }
        }
        Ok(Self {
            postings,
            deleted_keys,
        })
    }

    fn postings(
        &self,
        table: &str,
        index: &str,
        key: &RelationalKey,
    ) -> Option<&ConstraintOverlayPostings<'a>> {
        self.postings.get(table)?.get(index)?.get(key)
    }

    fn deleted_keys(&self, table: &str, index: &str) -> Option<&BTreeSet<&'a RelationalKey>> {
        self.deleted_keys.get(table)?.get(index)
    }
}

pub(super) fn authoritative_conflict_primary_key(
    state: &RelationalState,
    table: &str,
    definition: &RelationalIndexDefinition,
    conflict_columns: &[String],
    conflict_key: &RelationalKey,
    changed_keys: &BTreeSet<RelationalKey>,
    context: RelationalConflictProbeContext<'_>,
) -> Result<Option<RelationalKey>, RelationalError> {
    let constraint_index = context
        .constraint_index
        .expect("authoritative conflict probe");
    let positions = column_positions_with_allocations(
        state.table_schema(table).expect("validated table"),
        conflict_columns,
        context.allocations,
    )?;
    let mut candidates = BTreeSet::new();
    let mut previous = None;
    let mut traversal_error = None;
    constraint_index.visit_exact_primary_keys(
        table,
        &definition.name,
        conflict_key,
        &mut |primary_key| {
            if previous
                .as_ref()
                .is_some_and(|previous| previous >= primary_key)
            {
                traversal_error = Some(RelationalError::Corruption(format!(
                    "authoritative index {table}.{} returned unordered or duplicate primary keys",
                    definition.name
                )));
                return false;
            }
            previous = match clone_key_with_allocations(primary_key, context.allocations) {
                Ok(key) => Some(key),
                Err(error) => {
                    traversal_error = Some(error);
                    return false;
                }
            };
            match state.row(table, primary_key) {
                Some(row) if row_matches_key(row, &positions, conflict_key) => {
                    if let Err(error) = insert_changed_key_with_allocations(
                        &mut candidates,
                        primary_key,
                        context.allocations,
                    ) {
                        traversal_error = Some(error);
                        return false;
                    }
                }
                Some(_) | None if !changed_keys.contains(primary_key) => {
                    traversal_error = Some(RelationalError::Corruption(format!(
                        "authoritative index {table}.{} returned a stale primary key",
                        definition.name
                    )));
                    return false;
                }
                Some(_) | None => {}
            }
            candidates.len() < 2
        },
    )?;
    if let Some(error) = traversal_error {
        return Err(error);
    }
    if candidates.len() > 1 {
        return Err(RelationalError::Corruption(format!(
            "authoritative unique index {} on table {table} has multiple visible rows",
            definition.name
        )));
    }
    Ok(candidates.into_iter().next())
}

pub(super) fn validate_authoritative_constraints(
    next: &RelationalState,
    changed_keys: &BTreeMap<String, BTreeSet<RelationalKey>>,
    changes: &[RelationalIndexChange],
    constraint_index: &dyn RelationalConstraintIndex,
) -> Result<(), RelationalError> {
    let transaction_overlay = TransactionConstraintOverlay::new(changes)?;
    for (table, indexes) in &transaction_overlay.postings {
        let schema = next.schemas.get(*table).ok_or_else(|| {
            RelationalError::Corruption(format!(
                "authoritative index change references unknown table {table}"
            ))
        })?;
        let definitions = schema.required_index_definitions();
        for (index, keys) in indexes {
            let definition = definitions
                .iter()
                .find(|definition| definition.name == **index)
                .ok_or_else(|| {
                    RelationalError::Corruption(format!(
                        "authoritative index change references unknown index {table}.{index}"
                    ))
                })?;
            if definition.role.is_unique() {
                for key in keys.keys() {
                    let postings = bounded_authoritative_postings_after_changes(
                        constraint_index,
                        table,
                        index,
                        key,
                        &transaction_overlay,
                        2,
                    )?;
                    if postings.len() > 1 {
                        return Err(RelationalError::Constraint(format!(
                            "unique index {index} on table {table} has a duplicate key"
                        )));
                    }
                    validate_authoritative_postings(
                        next,
                        table,
                        &definition.columns,
                        key,
                        &postings,
                    )?;
                }
            }
        }
    }
    validate_authoritative_foreign_keys(next, changed_keys, &transaction_overlay, constraint_index)
}

fn validate_authoritative_foreign_keys(
    next: &RelationalState,
    changed_keys: &BTreeMap<String, BTreeSet<RelationalKey>>,
    transaction_overlay: &TransactionConstraintOverlay<'_>,
    constraint_index: &dyn RelationalConstraintIndex,
) -> Result<(), RelationalError> {
    for schema in next.table_schemas() {
        let Some(segment) = next.segments.get(&schema.name) else {
            continue;
        };
        for (ordinal, foreign_key) in schema.foreign_keys.iter().enumerate() {
            let local_positions = column_positions(schema, &foreign_key.columns)?;
            let referenced_schema =
                next.schemas
                    .get(&foreign_key.referenced_table)
                    .ok_or_else(|| {
                        RelationalError::Schema(format!(
                            "foreign key references unknown table {}",
                            foreign_key.referenced_table
                        ))
                    })?;
            let referenced_positions =
                column_positions(referenced_schema, &foreign_key.referenced_columns)?;
            validate_foreign_key_shape(
                &schema.name,
                schema,
                foreign_key,
                referenced_schema,
                &local_positions,
                &referenced_positions,
            )?;
            let referenced_definition = referenced_schema
                .unique_index_definition(&foreign_key.referenced_columns)
                .expect("validated foreign key target is unique");

            if let Some(local_changes) = changed_keys.get(&schema.name) {
                let mut target_keys = BTreeSet::new();
                for primary_key in local_changes {
                    let Some(row) = segment.rows.get(primary_key) else {
                        continue;
                    };
                    let key = row_key(row, &local_positions);
                    if key_contains_null(&key) {
                        continue;
                    }
                    target_keys.insert(key);
                }
                for key in target_keys {
                    let targets = bounded_authoritative_postings_after_changes(
                        constraint_index,
                        &foreign_key.referenced_table,
                        &referenced_definition.name,
                        &key,
                        transaction_overlay,
                        2,
                    )?;
                    if targets.len() > 1 {
                        return Err(RelationalError::Corruption(format!(
                            "authoritative foreign-key target index {}.{} has multiple visible rows",
                            foreign_key.referenced_table, referenced_definition.name
                        )));
                    }
                    if targets.is_empty() {
                        return Err(RelationalError::Constraint(format!(
                            "foreign key from {} to {} has no visible target",
                            schema.name, foreign_key.referenced_table
                        )));
                    }
                    validate_authoritative_postings(
                        next,
                        &foreign_key.referenced_table,
                        &referenced_definition.columns,
                        &key,
                        &targets,
                    )?;
                }
            }

            let local_index = relational_foreign_key_index_name(ordinal);
            let Some(removed_targets) = transaction_overlay
                .deleted_keys(&foreign_key.referenced_table, &referenced_definition.name)
            else {
                continue;
            };
            for target in removed_targets {
                if !bounded_authoritative_postings_after_changes(
                    constraint_index,
                    &foreign_key.referenced_table,
                    &referenced_definition.name,
                    target,
                    transaction_overlay,
                    1,
                )?
                .is_empty()
                {
                    continue;
                }
                if !bounded_authoritative_postings_after_changes(
                    constraint_index,
                    &schema.name,
                    &local_index,
                    target,
                    transaction_overlay,
                    1,
                )?
                .is_empty()
                {
                    return Err(RelationalError::Constraint(format!(
                        "foreign key from {} to {} prevents removing a visible target",
                        schema.name, foreign_key.referenced_table
                    )));
                }
            }
        }
    }
    Ok(())
}

fn bounded_authoritative_postings_after_changes(
    constraint_index: &dyn RelationalConstraintIndex,
    table: &str,
    index: &str,
    key: &RelationalKey,
    transaction_overlay: &TransactionConstraintOverlay<'_>,
    max_results: usize,
) -> Result<BTreeSet<RelationalKey>, RelationalError> {
    debug_assert!(max_results > 0);
    let empty_overlay = BTreeMap::new();
    let mut overlay = transaction_overlay
        .postings(table, index, key)
        .unwrap_or(&empty_overlay)
        .iter()
        .peekable();
    let mut postings = BTreeSet::new();
    let mut previous = None;
    let mut traversal_error = None;
    let mut stopped_early = false;
    constraint_index.visit_exact_primary_keys(table, index, key, &mut |primary_key| {
        if previous
            .as_ref()
            .is_some_and(|previous| previous >= primary_key)
        {
            traversal_error = Some(RelationalError::Corruption(format!(
                "authoritative index {table}.{index} returned unordered or duplicate primary keys"
            )));
            return false;
        }
        previous = Some(primary_key.clone());
        while let Some((overlay_primary_key, kind)) = overlay.peek().copied() {
            match (*overlay_primary_key).cmp(primary_key) {
                Ordering::Less => {
                    overlay.next();
                    match kind {
                        RelationalIndexChangeKind::Delete => {
                            traversal_error = Some(RelationalError::Corruption(format!(
                                "authoritative index {table}.{index} omitted a deleted posting"
                            )));
                            return false;
                        }
                        RelationalIndexChangeKind::Insert => {
                            postings.insert((*overlay_primary_key).clone());
                            if postings.len() >= max_results {
                                stopped_early = true;
                                return false;
                            }
                        }
                    }
                }
                Ordering::Equal => {
                    overlay.next();
                    return match kind {
                        RelationalIndexChangeKind::Delete => true,
                        RelationalIndexChangeKind::Insert => {
                            traversal_error = Some(RelationalError::Corruption(format!(
                                "authoritative transaction overlay inserts an existing posting for {table}.{index}"
                            )));
                            false
                        }
                    };
                }
                Ordering::Greater => break,
            }
        }
        postings.insert(primary_key.clone());
        if postings.len() >= max_results {
            stopped_early = true;
            return false;
        }
        true
    })?;
    if let Some(error) = traversal_error {
        return Err(error);
    }
    if stopped_early {
        return Ok(postings);
    }
    for (primary_key, kind) in overlay {
        match kind {
            RelationalIndexChangeKind::Delete => {
                return Err(RelationalError::Corruption(format!(
                    "authoritative index {table}.{index} omitted a deleted posting"
                )));
            }
            RelationalIndexChangeKind::Insert => {
                postings.insert((*primary_key).clone());
                if postings.len() >= max_results {
                    break;
                }
            }
        }
    }
    Ok(postings)
}

fn validate_authoritative_postings(
    state: &RelationalState,
    table: &str,
    columns: &[String],
    expected_key: &RelationalKey,
    postings: &BTreeSet<RelationalKey>,
) -> Result<(), RelationalError> {
    let schema = state
        .schemas
        .get(table)
        .ok_or_else(|| RelationalError::Corruption(format!("unknown indexed table {table}")))?;
    let positions = column_positions(schema, columns)?;
    for primary_key in postings {
        let row = state.row(table, primary_key).ok_or_else(|| {
            RelationalError::Corruption(format!(
                "authoritative index posting for {table} references a missing row"
            ))
        })?;
        if row_key(row, &positions) != *expected_key {
            return Err(RelationalError::Corruption(format!(
                "authoritative index posting for {table} references a row with a different key"
            )));
        }
    }
    Ok(())
}