Skip to main content

hawdb_storage/
branch_create_recovery.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Bounded recovery of interrupted child creation without admitting main.
16
17use crate::branch_catalog::{
18    self, BranchCreateError, BranchId, CreateOutcome, CreateRecoveryOutcome,
19};
20use crate::branch_head::{BranchHead, BranchHeadError};
21use crate::branch_project::{catalog_path, ProjectMetadata};
22use crate::file_io as fs;
23use crate::immutable_object::ImmutableObjectStore;
24use crate::ownership::DatabaseDirectoryLeaseError;
25use crate::sealed_root::SealedRoot;
26use hawdb_core::{HawDBError, Result, Uuid};
27use std::io;
28use std::path::Path;
29
30/// Aggregate work admitted by one scan. Repeated reads count separately.
31/// Catalog decoding retains its existing independent 16 MiB limit.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct BranchCreateRecoveryLimits {
34    pub max_creates: usize,
35    pub max_files: usize,
36    pub max_bytes: u64,
37}
38
39impl Default for BranchCreateRecoveryLimits {
40    fn default() -> Self {
41        Self {
42            max_creates: 64,
43            max_files: 10_000,
44            max_bytes: 256 * 1024 * 1024,
45        }
46    }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum BranchCreateRecoveryStatus {
51    Completed,
52    Aborted,
53    Busy,
54    Retained,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct BranchCreateRecoveryEntry {
59    pub branch_id: Uuid,
60    pub status: BranchCreateRecoveryStatus,
61    pub error: Option<String>,
62}
63
64/// Per-receipt results from a writable open or explicit retry. A retained or
65/// unattempted receipt is not ready. Healthy branches remain independently
66/// admissible, and the caller can inspect every incomplete recovery outcome.
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct BranchCreateRecoveryReport {
69    pub pending_at_start: usize,
70    pub entries: Vec<BranchCreateRecoveryEntry>,
71    pub unattempted: usize,
72    pub admitted_files: usize,
73    pub admitted_bytes: u64,
74    pub limit_exceeded: bool,
75}
76
77struct Budget {
78    limits: BranchCreateRecoveryLimits,
79    files: usize,
80    bytes: u64,
81    exceeded: bool,
82}
83
84impl Budget {
85    fn new(limits: BranchCreateRecoveryLimits) -> io::Result<Self> {
86        if limits.max_creates == 0 || limits.max_files == 0 || limits.max_bytes == 0 {
87            return Err(io::Error::new(
88                io::ErrorKind::InvalidInput,
89                "pending branch recovery limits must be positive",
90            ));
91        }
92        Ok(Self {
93            limits,
94            files: 0,
95            bytes: 0,
96            exceeded: false,
97        })
98    }
99
100    fn admit(&mut self, bytes: u64) -> io::Result<()> {
101        let total = self.bytes.checked_add(bytes);
102        if self.files >= self.limits.max_files
103            || total.is_none_or(|total| total > self.limits.max_bytes)
104        {
105            self.exceeded = true;
106            return Err(io::Error::other("pending branch recovery budget exceeded"));
107        }
108        self.files += 1;
109        self.bytes = total.expect("checked byte total");
110        Ok(())
111    }
112
113    fn admit_file(&mut self, path: &Path) -> io::Result<()> {
114        let bytes = match fs::symlink_metadata(path) {
115            Ok(metadata) if metadata.is_file() => metadata.len(),
116            Ok(_) => {
117                return Err(io::Error::other(
118                    "pending branch dependency is not a regular file",
119                ))
120            }
121            // The receipt kernel decides whether a known missing pair aborts.
122            Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
123            Err(error) => return Err(error),
124        };
125        self.admit(bytes)
126    }
127}
128
129/// Recover one matching request with the same closure validation as startup.
130/// The private WAL additionally obeys the caller's existing replay byte cap.
131pub fn recover_create_from_head_file(
132    catalog_path: &Path,
133    branch_id: BranchId,
134    head_path: &Path,
135    max_active_wal_bytes: u64,
136    limits: BranchCreateRecoveryLimits,
137) -> std::result::Result<CreateRecoveryOutcome, BranchCreateError> {
138    let mut budget = Budget::new(limits).map_err(dependency_error)?;
139    let directory = catalog_path
140        .parent()
141        .ok_or(BranchCreateError::InconsistentRequest(
142            "catalog has no directory",
143        ))?;
144    let objects = ImmutableObjectStore::open_existing(directory.join("objects"), limits.max_bytes);
145    recover_one(
146        catalog_path,
147        branch_id,
148        head_path,
149        max_active_wal_bytes,
150        &objects,
151        &mut budget,
152    )
153}
154
155fn recover_one(
156    catalog_path: &Path,
157    branch_id: BranchId,
158    head_path: &Path,
159    max_active_wal_bytes: u64,
160    objects: &ImmutableObjectStore,
161    budget: &mut Budget,
162) -> std::result::Result<CreateRecoveryOutcome, BranchCreateError> {
163    let remaining = budget.limits.max_bytes.saturating_sub(budget.bytes);
164    branch_catalog::recover_create_with_validation(
165        catalog_path,
166        branch_id,
167        head_path,
168        max_active_wal_bytes.min(remaining),
169        |head, path| {
170            budget.admit_file(path).map_err(dependency_error)?;
171            if let Some(head) = head {
172                verify_dependencies(objects, head, budget).map_err(dependency_error)?;
173            }
174            Ok(())
175        },
176    )
177}
178
179impl ProjectMetadata {
180    /// Repair only pending child receipts. No main runtime is admitted. Busy
181    /// or invalid children retain their evidence and appear in the report.
182    pub fn recover_pending_creates(
183        &self,
184        limits: BranchCreateRecoveryLimits,
185    ) -> Result<BranchCreateRecoveryReport> {
186        let mut budget =
187            Budget::new(limits).map_err(|error| HawDBError::Semantic(error.to_string()))?;
188        let pending: Vec<_> = self
189            .catalog()
190            .branches
191            .iter()
192            .filter(|branch| branch.create_outcome == CreateOutcome::Pending)
193            .map(|branch| branch.id)
194            .collect();
195        let mut report = BranchCreateRecoveryReport {
196            pending_at_start: pending.len(),
197            ..Default::default()
198        };
199        let root = self.file_descriptors().root();
200        let objects =
201            ImmutableObjectStore::open_existing(root.join("branches/objects"), limits.max_bytes);
202        for id in pending.into_iter().take(limits.max_creates) {
203            let head_path = root
204                .join("branches")
205                .join(id.as_uuid().to_string())
206                .join("branch.head");
207            let outcome = recover_one(
208                &catalog_path(root),
209                id,
210                &head_path,
211                limits.max_bytes,
212                &objects,
213                &mut budget,
214            );
215            let (status, error) = match outcome {
216                Ok(CreateRecoveryOutcome::Completed) => {
217                    (BranchCreateRecoveryStatus::Completed, None)
218                }
219                Ok(CreateRecoveryOutcome::Aborted) => (BranchCreateRecoveryStatus::Aborted, None),
220                Err(BranchCreateError::Lease(DatabaseDirectoryLeaseError::AlreadyOpen)) => {
221                    (BranchCreateRecoveryStatus::Busy, None)
222                }
223                Err(error) => (
224                    BranchCreateRecoveryStatus::Retained,
225                    Some(error.to_string()),
226                ),
227            };
228            report.entries.push(BranchCreateRecoveryEntry {
229                branch_id: id.as_uuid(),
230                status,
231                error,
232            });
233            if budget.exceeded {
234                break;
235            }
236        }
237        report.unattempted = report.pending_at_start - report.entries.len();
238        report.admitted_files = budget.files;
239        report.admitted_bytes = budget.bytes;
240        report.limit_exceeded = budget.exceeded || report.unattempted != 0;
241        Ok(report)
242    }
243}
244
245fn verify_dependencies(
246    objects: &ImmutableObjectStore,
247    head: &BranchHead,
248    budget: &mut Budget,
249) -> io::Result<()> {
250    // Sealed-root metadata is decoded in memory; its payload has a fixed
251    // decoder ceiling. Check it before the object reader allocates a buffer.
252    if head.sealed_root.byte_length > 64 * 1024 * 1024 {
253        return Err(io::Error::other(
254            "pending branch sealed root exceeds its metadata limit",
255        ));
256    }
257    budget.admit(head.sealed_root.byte_length)?;
258    let bytes = objects.read(head.sealed_root).map_err(io::Error::other)?;
259    let sealed = SealedRoot::decode(&bytes).map_err(io::Error::other)?;
260    if sealed.commit_epoch != head.logical_commit_epoch
261        || sealed.replay_end_lsn() != head.active_wal.replay_start_lsn
262    {
263        return Err(io::Error::other(
264            "pending branch sealed root does not match its head",
265        ));
266    }
267    drop(bytes);
268    for reference in std::iter::once(sealed.durable_manifest)
269        .chain(sealed.checkpoint_references)
270        .chain(sealed.sealed_wals.into_iter().map(|wal| wal.object))
271        .chain(std::iter::once(head.sealed_root))
272    {
273        budget.admit(reference.byte_length)?;
274        objects
275            .verify_and_sync(reference)
276            .map_err(io::Error::other)?;
277    }
278    Ok(())
279}
280
281fn dependency_error(source: io::Error) -> BranchCreateError {
282    BranchCreateError::Head(BranchHeadError::Io {
283        operation: "validate pending branch dependencies",
284        source,
285    })
286}