hawdb-storage 0.14.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
// Copyright 2026 Nowledge
// Licensed under the Apache License, Version 2.0.

//! Precomputed Consumer selection and out-of-fence durability custody.

use super::*;
use crate::file_descriptors::DescriptorReservation;
use crate::file_io::{CapturedControlCandidate, PendingControlPublication};
use crate::immutable_object::ObjectKind;

/// Conservative admission for the bounded ledger decode, cloned recovery roots,
/// encoded replacement and retained selection metadata.
pub const CONSUMER_SELECTION_MEMORY_BOUND: u64 = 8 * MAX_BYTES as u64;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerSelectionReceipt {
    pub(super) selected: SelectedRoot,
}

impl ConsumerSelectionReceipt {
    pub fn generation_name(&self) -> &str {
        &self.selected.generation_name
    }

    pub fn source_epoch(&self) -> u64 {
        self.selected.seal.source_epoch
    }

    pub fn metadata_reference(&self) -> ObjectReference {
        ObjectReference {
            kind: ObjectKind::CheckpointArtifact,
            format_version: 1,
            byte_length: self.selected.seal.metadata_length,
            sha256: self
                .selected
                .seal
                .metadata_sha256
                .parse()
                .expect("validated candidate digest"),
        }
    }

    pub fn binding(&self) -> ConsumerReservationBinding<'_> {
        let root = &self.selected;
        ConsumerReservationBinding {
            source_branch: BranchId::parse(&root.branch_id).expect("validated source branch"),
            database_uuid: Uuid::parse_str(&root.database_uuid).expect("validated database UUID"),
            consumer_id: &root.consumer_id,
            target_locator: &root.target_locator,
            target_incarnation: NonZeroU64::new(root.target_incarnation)
                .expect("nonzero incarnation"),
            generation: NonZeroU64::new(root.generation).expect("nonzero generation"),
            operation: NonZeroU64::new(root.operation).expect("nonzero operation"),
            registration_uuid: Uuid::parse_str(&root.registration_uuid)
                .expect("validated registration UUID"),
            projection_uuid: Uuid::parse_str(&root.projection_uuid)
                .expect("validated projection UUID"),
            checkpoint_uuid: Uuid::parse_str(&root.checkpoint_uuid)
                .expect("validated checkpoint UUID"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConsumerSelectionResolution {
    Published(Box<ConsumerSelectionReceipt>),
    NotSelected,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
    Prepared,
    Rejected,
    Attempted,
    Published,
    NotSelected,
}

#[derive(Clone, Copy)]
pub(super) enum ExpectedOutcome {
    Either,
    Published,
    NotSelected,
}

/// Retains the original ledger file to prevent native identity reuse, a sealed
/// replacement. Fresh descriptor admission precedes each attempt. The host retains the actual born
/// target, reader and publication exclusion and validates source E before select.
#[doc(hidden)]
#[derive(Debug)]
#[must_use]
pub struct PreparedConsumerSelection {
    control: CapturedControlCandidate<'static>,
    expected: File,
    project: CapturedProject,
    _source: Arc<DatabaseDirectoryLease>,
    next: SelectedRoot,
    previous: Option<SelectedRoot>,
    phase: Phase,
}

/// The native selection has been attempted. Finish after releasing SourceOwner;
/// dropping this borrow neither acknowledges nor rolls back the operation.
#[doc(hidden)]
#[derive(Debug)]
#[must_use]
pub struct PendingConsumerSelection<'a> {
    control: PendingControlPublication<'a, 'static>,
    project: &'a CapturedProject,
    next: &'a SelectedRoot,
    previous: &'a Option<SelectedRoot>,
    phase: &'a mut Phase,
}

pub(super) fn prepare(
    allocation: &ReservedConsumerAllocation,
    remembered: &PublicationIntent,
    preparation_attempted: &mut bool,
) -> Result<PreparedConsumerSelection> {
    if *preparation_attempted {
        return Err(invalid(
            "Consumer selector preparation was already attempted",
        ));
    }
    // Covers the catalog lock/captures, original ledger and control candidate,
    // plus bounded transient native checks. It is acquired before target effects.
    let _descriptors = allocation
        ._project
        .file_descriptors()
        .reserve_admission(12)?;
    allocation
        ._project
        .with_locked_catalog(|root, context, catalog| {
            let mut ledger = check_source(
                &allocation._project,
                &allocation._source,
                allocation.source_branch,
                root,
                context,
                &catalog,
            )?;
            let row = ledger
                .pending
                .iter()
                .find(|row| row.operation == allocation.operation.0)
                .ok_or_else(|| invalid("selection reservation is missing"))?;
            allocation.require_row(row)?;
            if row.publication_intent.as_ref() != Some(remembered) || !remembered.pending() {
                return Err(invalid("selection requires its unresolved durable intent"));
            }
            let next = SelectedRoot::from_candidate(row)?;
            let lease = row.lease;
            let active = ledger
                .selected
                .iter()
                .find(|selected| selected.matches_consumer(row));
            if active != remembered.previous.as_ref() {
                return Err(invalid("selection base differs from publication intent"));
            }
            // Stabilize the intent before exposing a selectable replacement.
            let intent = root.open_mutable_child(context, LEDGER_FILE, false)?;
            intent.sync_all()?;
            root.sync(context)?;
            drop(intent);
            let expected = root.open_child(context, LEDGER_FILE)?;
            ledger
                .selected
                .retain(|selected| selected.consumer_key() != next.consumer_key());
            ledger.selected.push(next.clone());
            ledger
                .policies
                .retain(|policy| policy.key() != next.consumer_key());
            if let Some(lease) = lease {
                ledger.policies.push(RegistrationPolicy {
                    branch_id: next.branch_id.clone(),
                    database_uuid: next.database_uuid.clone(),
                    consumer_id: next.consumer_id.clone(),
                    registration_uuid: next.registration_uuid.clone(),
                    lease,
                });
                ledger.policies.sort_by(|a, b| a.key().cmp(&b.key()));
            }
            ledger
                .selected
                .sort_by(|a, b| a.consumer_key().cmp(&b.consumer_key()));
            validate(&ledger)?;
            let bytes = encode(&ledger)?;
            let name = format!("consumer-selector-{}.tmp", hawdb_core::generate_uuidv7()?);
            let mut control = allocation._project.create_owned_control_candidate(&name)?;
            let prepared = (|| {
                control.write_all(&bytes)?;
                control.seal()
            })();
            if let Err(error) = prepared {
                let _ = control.discard_unselected(context);
                return Err(error.into());
            }
            *preparation_attempted = true;
            Ok(PreparedConsumerSelection {
                control,
                expected,
                project: allocation._project.clone(),
                _source: Arc::clone(&allocation._source),
                next,
                previous: remembered.previous.clone(),
                phase: Phase::Prepared,
            })
        })
}

impl PreparedConsumerSelection {
    pub fn native_selection_attempted(&self) -> bool {
        self.phase != Phase::Prepared
    }

    pub fn previous_receipt(&self) -> Option<ConsumerSelectionReceipt> {
        self.previous
            .as_ref()
            .map(|selected| ConsumerSelectionReceipt {
                selected: selected.clone(),
            })
    }

    /// Settle a prepared selector that never entered native selection. This
    /// cannot turn a visible selected operation into a cancellation.
    pub fn cancel_unattempted(&mut self) -> Result<()> {
        if self.phase != Phase::Prepared {
            return Err(invalid("Consumer selector is no longer unattempted"));
        }
        let outcome = complete_outcome(
            &self.project,
            &self.next,
            &self.previous,
            ExpectedOutcome::NotSelected,
        )?;
        if !matches!(outcome, ConsumerSelectionResolution::NotSelected) {
            return Err(invalid("unattempted Consumer selector became selected"));
        }
        // Keep this terminal fact even if private-name cleanup fails. Other
        // operations may now compact its completed ledger row before retry.
        self.phase = Phase::NotSelected;
        self.discard_not_selected_control()
    }

    pub fn reserve_attempt_descriptors(&self) -> Result<DescriptorReservation> {
        self.project
            .file_descriptors()
            .reserve_admission(12)
            .map_err(Into::into)
    }

    /// Native atomic selection only. The caller must hold its source-E fence
    /// and actual target authority. No serialization or synchronization occurs.
    pub fn select(&mut self) -> Result<PendingConsumerSelection<'_>> {
        if self.phase != Phase::Prepared {
            return Err(invalid("Consumer selector is no longer selectable"));
        }
        let Self {
            control,
            expected,
            project,
            next,
            previous,
            phase,
            ..
        } = self;
        let control = project.with_locked_catalog(|root, context, _catalog| {
            if !root.matches_child_file(context, LEDGER_FILE, expected)? {
                *phase = Phase::Rejected;
                return Err(HawDBError::ProjectionBusy);
            }
            // Revoke before native code, including errors and unwinding.
            *phase = Phase::Attempted;
            control
                .select_head(context, LEDGER_FILE)
                .map_err(Into::into)
        })?;
        Ok(PendingConsumerSelection {
            control,
            project,
            next,
            previous,
            phase,
        })
    }

    /// Resolve the original operation without rechecking a later source epoch.
    /// Both possible roots remain in the durable intent through uncertainty.
    pub fn resolve(&mut self) -> Result<ConsumerSelectionResolution> {
        match self.phase {
            Phase::Prepared => return Err(invalid("Consumer selection was never attempted")),
            Phase::NotSelected => {
                self.discard_not_selected_control()?;
                return Ok(ConsumerSelectionResolution::NotSelected);
            }
            Phase::Published => {
                return Ok(ConsumerSelectionResolution::Published(Box::new(
                    ConsumerSelectionReceipt {
                        selected: self.next.clone(),
                    },
                )))
            }
            Phase::Attempted | Phase::Rejected => {}
        }
        let outcome = complete_outcome(
            &self.project,
            &self.next,
            &self.previous,
            ExpectedOutcome::Either,
        )?;
        self.phase = match outcome {
            ConsumerSelectionResolution::Published(_) => Phase::Published,
            ConsumerSelectionResolution::NotSelected => Phase::NotSelected,
        };
        if self.phase == Phase::NotSelected {
            self.discard_not_selected_control()?;
        }
        Ok(outcome)
    }

    fn discard_not_selected_control(&mut self) -> Result<()> {
        if !self.control.selection_attempted() {
            self.control
                .discard_unselected(&self.project.file_descriptors().io_context())?;
        }
        Ok(())
    }
}

impl PendingConsumerSelection<'_> {
    pub fn finish(self) -> Result<ConsumerSelectionReceipt> {
        self.control
            .finish(&self.project.file_descriptors().io_context())?;
        let outcome = complete_outcome(
            self.project,
            self.next,
            self.previous,
            ExpectedOutcome::Published,
        )?;
        match outcome {
            ConsumerSelectionResolution::Published(receipt) => {
                *self.phase = Phase::Published;
                Ok(*receipt)
            }
            ConsumerSelectionResolution::NotSelected => {
                Err(invalid("completed selector disappeared"))
            }
        }
    }
}

pub(super) fn complete_outcome(
    project: &CapturedProject,
    next: &SelectedRoot,
    previous: &Option<SelectedRoot>,
    expected: ExpectedOutcome,
) -> Result<ConsumerSelectionResolution> {
    project.with_locked_catalog(|root, context, _catalog| {
        let mut ledger = read(root, context)?;
        if selector(&ledger)? != project.allocation_identity() {
            return Err(invalid("selection recovery project differs"));
        }
        let index = ledger
            .pending
            .iter()
            .position(|row| row.operation == next.operation)
            .ok_or_else(|| invalid("selection recovery reservation is missing"))?;
        let row = &ledger.pending[index];
        if SelectedRoot::from_candidate(row)? != *next {
            return Err(invalid("selection recovery candidate differs"));
        }
        let intent = row
            .publication_intent
            .as_ref()
            .ok_or_else(|| invalid("selection recovery intent is missing"))?;
        if intent.previous != *previous {
            return Err(invalid("selection recovery previous root differs"));
        }
        let active = ledger
            .selected
            .iter()
            .find(|selected| selected.matches_consumer(row));
        let published = if intent.receipt_complete {
            true
        } else if intent.not_selected {
            false
        } else if active == Some(next) {
            true
        } else if !matches!(expected, ExpectedOutcome::Published) && active == previous.as_ref() {
            false
        } else {
            return Err(invalid("Consumer selector outcome is uncertain"));
        };
        if matches!(expected, ExpectedOutcome::Published) && !published {
            return Err(invalid("Consumer selector was not selected"));
        }
        if matches!(expected, ExpectedOutcome::NotSelected) && published {
            return Err(invalid("unattempted Consumer selector became selected"));
        }
        if intent.pending() {
            let intent = ledger.pending[index]
                .publication_intent
                .as_mut()
                .expect("checked intent");
            intent.receipt_complete = published;
            intent.not_selected = !published;
            compact_completed(&mut ledger, Some(next.operation));
            validate(&ledger)?;
            let bytes = encode(&ledger)?;
            let name = format!("consumer-receipt-{}.tmp", hawdb_core::generate_uuidv7()?);
            publish_ledger(root, context, &name, &bytes, &mut false)?;
        } else {
            // A complete image with a lost barrier still needs real barriers.
            let file = root.open_mutable_child(context, LEDGER_FILE, false)?;
            file.sync_all()?;
            root.sync(context)?;
        }
        Ok(if published {
            ConsumerSelectionResolution::Published(Box::new(ConsumerSelectionReceipt {
                selected: next.clone(),
            }))
        } else {
            ConsumerSelectionResolution::NotSelected
        })
    })
}