Skip to main content

hawdb_storage/store/
doctor.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
15use super::format_admission::{validate_checkpoint_formats, validate_sealed_formats};
16
17use super::{
18    file_checksum, DurableManifest, WalCursorEvent, WalOpenOutcome, WalRecordCursor, MANIFEST_FILE,
19};
20use crate::error::{HawDBError, Result};
21use crate::file_io::{self as fs, File, OpenOptions};
22use hawdb_integrity::IntegrityHasher;
23pub use hawdb_storage::{
24    doctor::{
25        WalDoctorOptions, WalRepairAcknowledgement, WalTailRepairPlan, WalTailRepairReason,
26        WalTailRepairReport, WAL_DOCTOR_REPAIR_PROTOCOL,
27    },
28    ownership::DatabaseDirectoryLease,
29};
30use serde::{Deserialize, Serialize};
31use std::io::{self, Read, Seek, SeekFrom, Write};
32use std::path::{Path, PathBuf};
33
34const DOCTOR_DIRECTORY: &str = "doctor";
35const DOCTOR_QUARANTINE_DIRECTORY: &str = "quarantine";
36const MAX_DOCTOR_AUDIT_BYTES: u64 = 1024 * 1024;
37
38/// A repair is bound to the authoritative selector, rather than the disposable
39/// branch runtime manifest. The existing plan's manifest identity fields bind
40/// the legacy manifest or, for a branch, the exact branch head bytes.
41struct WalRepairBoundary {
42    selector_path: PathBuf,
43    wal_generation: u64,
44    wal_replay_start_lsn: u64,
45    published_prefix_len: u64,
46    commit_epoch: u64,
47}
48
49/// Missing selectors still belong to their project's branch namespace. Never
50/// classify them as legacy stores or give them an independent FD domain.
51fn is_branch_directory(path: &Path) -> Result<bool> {
52    if fs::try_exists(path.join("branch.head"))? {
53        return Ok(true);
54    }
55    let Some(parent) = path
56        .parent()
57        .filter(|parent| parent.file_name().is_some_and(|name| name == "branches"))
58    else {
59        return Ok(false);
60    };
61    Ok(fs::try_exists(parent.join("catalog.hawdb"))?)
62}
63
64impl WalRepairBoundary {
65    fn load(path: &Path, options: WalDoctorOptions) -> Result<Self> {
66        let mut format_limits = crate::config::WalReplayConfig {
67            max_bytes: options.max_wal_bytes,
68            max_record_bytes: options.max_record_bytes,
69            max_batch_operations: options.max_batch_operations,
70            max_entries: None,
71            ..Default::default()
72        };
73        let head_path = path.join("branch.head");
74        if !is_branch_directory(path)? {
75            let manifest_path = path.join(MANIFEST_FILE);
76            let manifest = DurableManifest::load(&manifest_path)?;
77            manifest.validate()?;
78            validate_checkpoint_boundary(path, manifest)?;
79            validate_checkpoint_formats(manifest, format_limits, |name| Ok(path.join(name)))?;
80            return Ok(Self {
81                selector_path: manifest_path,
82                wal_generation: manifest.wal_generation,
83                wal_replay_start_lsn: manifest.wal_replay_start_lsn,
84                published_prefix_len: 0,
85                commit_epoch: manifest.checkpoint_commit_epoch,
86            });
87        }
88        let head =
89            crate::branch_head::read_branch_head(&head_path).map_err(|error| match error {
90                crate::branch_head::BranchHeadError::Io { source, .. }
91                    if source.kind() == io::ErrorKind::NotFound =>
92                {
93                    HawDBError::StorageIntegrity(
94                        "WAL repair branch head is missing; retain its recovery evidence".into(),
95                    )
96                }
97                error => HawDBError::from_storage_error(error),
98            })?;
99        let branch_id =
100            crate::branch_catalog::BranchId::new(hawdb_core::Uuid::from_bytes(head.branch_id))
101                .map_err(HawDBError::from_storage_error)?;
102        if path.file_name().and_then(|name| name.to_str())
103            != Some(branch_id.as_uuid().to_string().as_str())
104        {
105            return Err(HawDBError::StorageIntegrity(
106                "WAL repair branch directory differs from its UUID".into(),
107            ));
108        }
109        let metadata_directory = path.parent().ok_or_else(|| {
110            HawDBError::StorageIntegrity("WAL repair branch has no project directory".into())
111        })?;
112        let catalog_path = metadata_directory.join("catalog.hawdb");
113        let catalog = crate::branch_catalog::read_catalog(&catalog_path)
114            .map_err(HawDBError::from_storage_error)?;
115        let revision = catalog
116            .branches
117            .iter()
118            .find(|record| record.id == branch_id)
119            .ok_or_else(|| {
120                HawDBError::StorageIntegrity("WAL repair branch is absent from its catalog".into())
121            })?
122            .metadata_revision;
123        let record = super::immutable_root::ready_branch_record(&catalog_path, branch_id, revision)
124            .map_err(HawDBError::from_storage_error)?;
125        let objects =
126            crate::immutable_object::ImmutableObjectStore::open(metadata_directory.join("objects"))
127                .map_err(HawDBError::from_storage_error)?;
128        let root = crate::sealed_root::SealedRoot::decode(
129            &objects
130                .read(head.sealed_root)
131                .map_err(HawDBError::from_storage_error)?,
132        )
133        .map_err(HawDBError::from_storage_error)?;
134        super::immutable_root::validate_admission_binding(
135            &record,
136            &head,
137            &root,
138            root.object_reference()
139                .map_err(HawDBError::from_storage_error)?,
140        )
141        .map_err(HawDBError::from_storage_error)?;
142        let manifest_bytes = objects
143            .read(root.durable_manifest)
144            .map_err(HawDBError::from_storage_error)?;
145        let manifest_text = std::str::from_utf8(&manifest_bytes).map_err(|_| {
146            HawDBError::StorageIntegrity("WAL repair sealed manifest is not UTF-8".into())
147        })?;
148        let manifest = DurableManifest::decode(manifest_text)?;
149        manifest.validate()?;
150        if manifest.checkpoint_commit_epoch != root.checkpoint_epoch
151            || manifest.wal_replay_start_lsn != root.wal_replay_start_lsn
152        {
153            return Err(HawDBError::StorageIntegrity(
154                "WAL repair root differs from its checkpoint boundary".into(),
155            ));
156        }
157        // Retain the entire immutable recovery closure. No repair may discard
158        // or substitute a sealed generation or proceed from damaged evidence.
159        for reference in root
160            .checkpoint_references
161            .iter()
162            .copied()
163            .chain(root.sealed_wals.iter().map(|interval| interval.object))
164        {
165            objects
166                .verify_stored(reference)
167                .map_err(HawDBError::from_storage_error)?;
168        }
169        validate_sealed_formats(&objects, &root, manifest, &mut format_limits)?;
170        let wal_path = path.join(crate::artifact_files::wal_generation_file(
171            head.active_wal.generation,
172        ));
173        crate::branch_head::validate_active_wal_prefix_from_file(
174            &wal_path,
175            head.active_wal,
176            options.max_wal_bytes.unwrap_or(u64::MAX),
177        )
178        .map_err(HawDBError::from_storage_error)?;
179        Ok(Self {
180            selector_path: head_path,
181            wal_generation: head.active_wal.generation,
182            wal_replay_start_lsn: head.active_wal.replay_start_lsn,
183            published_prefix_len: head.active_wal.byte_length,
184            commit_epoch: root.commit_epoch,
185        })
186    }
187
188    fn wal_path(&self, directory: &Path) -> PathBuf {
189        directory.join(crate::artifact_files::wal_generation_file(
190            self.wal_generation,
191        ))
192    }
193}
194
195pub(super) fn repair_directory(path: &Path) -> Result<PathBuf> {
196    // A project-level doctor operation repairs its default main. A caller may
197    // also provide an exact UUID directory; both paths acquire the UUID lease.
198    if is_branch_directory(path)? {
199        return Ok(path.to_path_buf());
200    }
201    match crate::branch_project::inspect_project_manifest(path)? {
202        crate::branch_project::ProjectManifest::Branch(selector) => Ok(path
203            .join("branches")
204            .join(selector.main_branch_id().as_uuid().to_string())),
205        _ => Ok(path.to_path_buf()),
206    }
207}
208
209pub(super) fn repair_file_descriptors(
210    path: &Path,
211) -> Result<crate::file_descriptors::ProjectFileDescriptors> {
212    // A missing head is corrupt publication evidence, not a reason to create
213    // an independent descriptor domain below the containing project's limit.
214    let project = if is_branch_directory(path)? {
215        path.parent().and_then(Path::parent).ok_or_else(|| {
216            HawDBError::StorageIntegrity("WAL repair branch has no project root".into())
217        })?
218    } else {
219        path
220    };
221    let project = fs::canonicalize(project)?;
222    match crate::file_descriptors::ProjectFileDescriptors::containing(&project)? {
223        Some(files) => Ok(files),
224        None => crate::file_descriptors::ProjectFileDescriptors::acquire_existing(
225            &project,
226            crate::file_descriptors::DEFAULT_MAX_OPEN_FILES,
227        ),
228    }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[doc(hidden)]
233pub struct WalRepairAuditRecord {
234    protocol: String,
235    state: WalRepairAuditState,
236    plan: WalTailRepairPlan,
237    quarantine_file: String,
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(rename_all = "snake_case")]
242enum WalRepairAuditState {
243    Prepared,
244    Applied,
245}
246
247pub struct DatabaseDoctor;
248
249impl DatabaseDoctor {
250    pub fn plan_wal_tail_repair(
251        path: impl AsRef<Path>,
252        options: WalDoctorOptions,
253    ) -> Result<WalTailRepairPlan> {
254        let path = path.as_ref();
255        validate_existing_database_directory(path)?;
256        let _files = repair_file_descriptors(path)?;
257        let directory = repair_directory(path)?;
258        let _lease =
259            DatabaseDirectoryLease::acquire(&directory).map_err(HawDBError::from_storage_error)?;
260        inspect_wal_tail_locked(&directory, options)
261    }
262
263    pub fn apply_wal_tail_repair(
264        path: impl AsRef<Path>,
265        plan: &WalTailRepairPlan,
266        acknowledgement: WalRepairAcknowledgement,
267        options: WalDoctorOptions,
268    ) -> Result<WalTailRepairReport> {
269        validate_acknowledgement(plan, &acknowledgement)?;
270        let path = path.as_ref();
271        validate_existing_database_directory(path)?;
272        let _files = repair_file_descriptors(path)?;
273        let directory = repair_directory(path)?;
274        let _lease =
275            DatabaseDirectoryLease::acquire(&directory).map_err(HawDBError::from_storage_error)?;
276        apply_wal_tail_repair_locked(&directory, plan, options)
277    }
278}
279
280pub(super) fn reject_pending_wal_doctor_repair(path: &Path) -> Result<()> {
281    let pending = pending_repair_records(path)?;
282    if pending.is_empty() {
283        return Ok(());
284    }
285    Err(HawDBError::Storage(format!(
286        "database has {} interrupted WAL doctor repair record(s); finish the repair with DatabaseDoctor before opening the database",
287        pending.len()
288    )))
289}
290
291// Callers hold the same directory lease used by explicit doctor operations.
292pub(super) fn resume_automatic_wal_tail_repair_locked(
293    path: &Path,
294    config: hawdb_storage::config::WalReplayConfig,
295) -> Result<Option<WalTailRepairReport>> {
296    if pending_repair_records(path)?.is_empty() {
297        return Ok(None);
298    }
299    automatic_wal_tail_repair_locked(path, config).map(Some)
300}
301
302pub(super) fn automatic_wal_tail_repair_locked(
303    path: &Path,
304    config: hawdb_storage::config::WalReplayConfig,
305) -> Result<WalTailRepairReport> {
306    let options = WalDoctorOptions {
307        max_wal_bytes: config.max_bytes,
308        max_record_bytes: config.max_record_bytes,
309        max_batch_operations: config.max_batch_operations,
310    };
311    let plan = inspect_wal_tail_locked(path, options)?;
312    if config
313        .max_bytes
314        .is_some_and(|limit| plan.original_wal_len > limit)
315    {
316        return Err(HawDBError::Storage(
317            "automatic WAL repair exceeds the configured replay byte limit".to_string(),
318        ));
319    }
320    let directory = doctor_directory(path).join(DOCTOR_QUARANTINE_DIRECTORY);
321    let mut retained_bytes = 0u64;
322    if directory.exists() {
323        for entry in fs::read_dir(&directory)? {
324            let entry = entry?;
325            if entry.path()
326                == directory
327                    .join(quarantine_file_name(&plan))
328                    .with_extension("tail.tmp")
329            {
330                continue;
331            }
332            retained_bytes = retained_bytes
333                .checked_add(entry.metadata()?.len())
334                .ok_or_else(|| {
335                    HawDBError::Storage("doctor quarantine size overflow".to_string())
336                })?;
337        }
338    }
339    if !directory.join(quarantine_file_name(&plan)).exists() {
340        retained_bytes = retained_bytes
341            .checked_add(plan.discarded_wal_tail_bytes)
342            .ok_or_else(|| HawDBError::Storage("doctor quarantine size overflow".to_string()))?;
343    }
344    // Automatic recovery must preserve prior audit evidence, even when the
345    // quarantine budget is exhausted. Explicit doctor repair remains available.
346    if retained_bytes > config.max_quarantine_bytes {
347        return Err(HawDBError::Storage(format!(
348            "automatic WAL repair quarantine byte limit exceeded: required={retained_bytes}, max_wal_quarantine_bytes={}",
349            config.max_quarantine_bytes
350        )));
351    }
352    apply_wal_tail_repair_locked(path, &plan, options)
353}
354
355fn validate_existing_database_directory(path: &Path) -> Result<()> {
356    if !path.exists() {
357        return Err(HawDBError::Storage(format!(
358            "database doctor path does not exist: {}",
359            path.display()
360        )));
361    }
362    if !path.is_dir() {
363        return Err(HawDBError::Storage(format!(
364            "database doctor path is not a directory: {}",
365            path.display()
366        )));
367    }
368    Ok(())
369}
370
371fn validate_acknowledgement(
372    plan: &WalTailRepairPlan,
373    acknowledgement: &WalRepairAcknowledgement,
374) -> Result<()> {
375    if !acknowledgement.accepts(plan) {
376        return Err(HawDBError::Storage(
377            "WAL doctor repair requires explicit acknowledgement of the exact plan and potential data loss"
378                .to_string(),
379        ));
380    }
381    Ok(())
382}
383
384fn inspect_wal_tail_locked(path: &Path, options: WalDoctorOptions) -> Result<WalTailRepairPlan> {
385    let boundary = WalRepairBoundary::load(path, options)?;
386    let wal_path = boundary.wal_path(path);
387    let wal_len = fs::metadata(&wal_path)
388        .map_err(|error| {
389            HawDBError::or_stop(&error, || {
390                HawDBError::Storage(format!(
391                    "failed to inspect WAL generation {}: {error}",
392                    boundary.wal_generation
393                ))
394            })
395        })?
396        .len();
397    if options.max_wal_bytes.is_some_and(|limit| wal_len > limit) {
398        return Err(HawDBError::Storage(format!(
399            "WAL doctor byte limit exceeded: max_wal_bytes={}",
400            options.max_wal_bytes.unwrap_or_default()
401        )));
402    }
403
404    let mut cursor = match WalRecordCursor::open(&wal_path, options.max_record_bytes)? {
405        WalOpenOutcome::Cursor(cursor) => cursor,
406        WalOpenOutcome::MissingHeader => {
407            return Err(HawDBError::Storage(format!(
408                "WAL generation {} is missing its header",
409                boundary.wal_generation
410            )));
411        }
412        WalOpenOutcome::HeaderTorn { .. } => {
413            return Err(HawDBError::Storage(
414                "WAL doctor rejected an incomplete WAL header".to_string(),
415            ));
416        }
417        WalOpenOutcome::HeaderCorrupt { reason } => {
418            return Err(HawDBError::Storage(format!(
419                "WAL doctor rejected corruption at byte offset 0: {reason}"
420            )));
421        }
422    };
423    if cursor.generation() != boundary.wal_generation
424        || cursor.start_lsn() != boundary.wal_replay_start_lsn
425    {
426        return Err(HawDBError::Storage(format!(
427            "WAL header generation/start ({}, {}) does not match manifest ({}, {})",
428            cursor.generation(),
429            cursor.start_lsn(),
430            boundary.wal_generation,
431            boundary.wal_replay_start_lsn
432        )));
433    }
434    let fence = super::wal_fence::WalRecoveryFence::load(
435        &wal_path,
436        boundary.wal_generation,
437        boundary.wal_replay_start_lsn,
438    )?;
439    let mut valid_end = super::WAL_BINARY_FILE_HEADER_BYTES as u64;
440    let mut expected_lsn = boundary.wal_replay_start_lsn;
441    let mut epoch = boundary.commit_epoch;
442    loop {
443        let event = cursor.next()?;
444        let event = match event {
445            WalCursorEvent::Entry {
446                ref entry,
447                start_offset,
448                ..
449            } if entry.lsn != expected_lsn => WalCursorEvent::Corrupt {
450                offset: start_offset,
451                reason: format!(
452                    "WAL LSN sequence mismatch: expected {expected_lsn}, got {}",
453                    entry.lsn
454                ),
455            },
456            event => event,
457        };
458        let damage = match &event {
459            WalCursorEvent::TornTail {
460                valid_prefix_len, ..
461            } => Some((
462                *valid_prefix_len,
463                WalTailRepairReason::IncompleteFinalRecord,
464            )),
465            WalCursorEvent::Corrupt { .. }
466                if fence.is_some_and(|fence| {
467                    fence.validate_retained(valid_end, expected_lsn).is_ok()
468                }) =>
469            {
470                Some((valid_end, WalTailRepairReason::UnsynchronizedSuffix))
471            }
472            _ => None,
473        };
474        if let Some((retained, reason)) = damage {
475            if retained < boundary.published_prefix_len {
476                return Err(HawDBError::StorageIntegrity(
477                    "WAL repair would discard a published branch prefix".into(),
478                ));
479            }
480            if let Some(fence) = fence {
481                fence.validate_retained(retained, expected_lsn)?;
482            }
483            let mut plan = build_plan(
484                &boundary.selector_path,
485                &wal_path,
486                &boundary,
487                expected_lsn,
488                retained,
489                wal_len,
490            )?;
491            plan.reason = reason;
492            plan.plan_id = plan_identity(&plan);
493            if let Some(pending) = load_matching_pending_record(path, &plan.plan_id)?
494                && pending.plan != plan
495            {
496                return Err(HawDBError::StorageIntegrity(
497                    "pending WAL repair differs from current plan".into(),
498                ));
499            }
500            return Ok(plan);
501        }
502        let (entry, record_end) = match event {
503            WalCursorEvent::Eof => break,
504            WalCursorEvent::TornTail { .. } => unreachable!("torn tail handled above"),
505            WalCursorEvent::Corrupt { offset, reason } => {
506                return Err(HawDBError::Storage(format!(
507                    "WAL doctor rejected corruption at byte offset {offset}: {reason}"
508                )));
509            }
510            WalCursorEvent::Entry {
511                entry,
512                start_offset,
513                encoded_len,
514                ..
515            } => (entry, start_offset + encoded_len),
516        };
517        epoch = epoch.checked_add(1).ok_or_else(|| {
518            HawDBError::StorageIntegrity("WAL transaction epoch overflow during doctor scan".into())
519        })?;
520        super::immutable_root::validate_source_wal_op(
521            &entry.op,
522            epoch,
523            options.max_batch_operations,
524        )?;
525        valid_end = record_end;
526        expected_lsn = expected_lsn.checked_add(1).ok_or_else(|| {
527            HawDBError::Storage("WAL LSN overflow during doctor scan".to_string())
528        })?;
529    }
530
531    if let Some(fence) = fence {
532        fence.validate_retained(wal_len, expected_lsn)?;
533    }
534    if let Some(record) = load_single_pending_record(path)? {
535        validate_pending_truncated_wal(path, &record)?;
536        return Ok(record.plan);
537    }
538    Err(HawDBError::Storage(
539        "WAL doctor found no repairable incomplete final record".to_string(),
540    ))
541}
542
543fn build_plan(
544    manifest_path: &Path,
545    wal_path: &Path,
546    boundary: &WalRepairBoundary,
547    next_lsn_after_repair: u64,
548    retained_wal_len: u64,
549    original_wal_len: u64,
550) -> Result<WalTailRepairPlan> {
551    let (manifest_len, manifest_crc32c, manifest_sha256) = file_checksum(manifest_path)?;
552    let (actual_wal_len, original_wal_crc32c, original_wal_sha256) = file_checksum(wal_path)?;
553    if actual_wal_len != original_wal_len {
554        return Err(HawDBError::Storage(
555            "WAL changed while the doctor repair plan was being generated".to_string(),
556        ));
557    }
558    let (retained_len, retained_wal_crc32c, retained_wal_sha256) =
559        file_prefix_checksum(wal_path, retained_wal_len)?;
560    let mut plan = WalTailRepairPlan {
561        protocol: WAL_DOCTOR_REPAIR_PROTOCOL.to_string(),
562        plan_id: String::new(),
563        wal_generation: boundary.wal_generation,
564        wal_replay_start_lsn: boundary.wal_replay_start_lsn,
565        next_lsn_after_repair,
566        manifest_len,
567        manifest_crc32c,
568        manifest_sha256: manifest_sha256.to_string(),
569        original_wal_len,
570        original_wal_crc32c,
571        original_wal_sha256: original_wal_sha256.to_string(),
572        retained_wal_len: retained_len,
573        retained_wal_crc32c,
574        retained_wal_sha256: retained_wal_sha256.to_string(),
575        discarded_wal_tail_bytes: original_wal_len.saturating_sub(retained_len),
576        reason: WalTailRepairReason::IncompleteFinalRecord,
577        data_loss_possible: true,
578    };
579    plan.plan_id = plan_identity(&plan);
580    Ok(plan)
581}
582
583fn plan_identity(plan: &WalTailRepairPlan) -> String {
584    let identity = format!(
585        "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{:?}\n{}",
586        plan.protocol,
587        plan.wal_generation,
588        plan.wal_replay_start_lsn,
589        plan.next_lsn_after_repair,
590        plan.manifest_len,
591        plan.manifest_crc32c,
592        plan.manifest_sha256,
593        plan.original_wal_len,
594        plan.original_wal_crc32c,
595        plan.original_wal_sha256,
596        plan.retained_wal_len,
597        plan.retained_wal_crc32c,
598        plan.retained_wal_sha256,
599        plan.discarded_wal_tail_bytes,
600        plan.reason,
601        plan.data_loss_possible
602    );
603    hawdb_integrity::integrity_digest(identity.as_bytes())
604        .sha256
605        .to_string()
606}
607
608fn apply_wal_tail_repair_locked(
609    path: &Path,
610    requested_plan: &WalTailRepairPlan,
611    options: WalDoctorOptions,
612) -> Result<WalTailRepairReport> {
613    if requested_plan.protocol != WAL_DOCTOR_REPAIR_PROTOCOL
614        || requested_plan.plan_id != plan_identity(requested_plan)
615        || !requested_plan.data_loss_possible
616        || requested_plan.discarded_wal_tail_bytes == 0
617    {
618        return Err(HawDBError::Storage(
619            "WAL doctor repair plan identity is invalid".to_string(),
620        ));
621    }
622
623    let boundary = WalRepairBoundary::load(path, options)?;
624    if boundary.wal_generation != requested_plan.wal_generation
625        || boundary.wal_replay_start_lsn != requested_plan.wal_replay_start_lsn
626    {
627        return Err(HawDBError::Storage(
628            "WAL generation changed after the doctor repair plan was created".to_string(),
629        ));
630    }
631    let wal_path = boundary.wal_path(path);
632    validate_manifest_identity(path, requested_plan)?;
633    let pending = load_matching_pending_record(path, &requested_plan.plan_id)?;
634    let current = file_checksum(&wal_path)?;
635    let original_matches = file_identity_matches(
636        current,
637        requested_plan.original_wal_len,
638        requested_plan.original_wal_crc32c,
639        &requested_plan.original_wal_sha256,
640    );
641    let retained_matches = file_identity_matches(
642        current,
643        requested_plan.retained_wal_len,
644        requested_plan.retained_wal_crc32c,
645        &requested_plan.retained_wal_sha256,
646    );
647    if retained_matches {
648        let pending = pending.ok_or_else(|| {
649            HawDBError::Storage(
650                "WAL already matches the retained prefix without a pending doctor audit record"
651                    .to_string(),
652            )
653        })?;
654        if pending.plan != *requested_plan {
655            return Err(HawDBError::Storage(
656                "pending WAL doctor repair record does not match the requested plan".to_string(),
657            ));
658        }
659        // The retained prefix may have been prepared by a different reader.
660        // Revalidate its capabilities before publishing a resumed repair.
661        inspect_wal_tail_locked(path, options)?;
662        return finalize_repair(path, pending, true);
663    }
664    if !original_matches {
665        return Err(HawDBError::Storage(
666            "WAL changed after the doctor repair plan was created; no files were modified"
667                .to_string(),
668        ));
669    }
670
671    let current_plan = inspect_wal_tail_locked(path, options)?;
672    if current_plan != *requested_plan {
673        return Err(HawDBError::Storage(
674            "WAL doctor repair plan no longer matches the current database state".to_string(),
675        ));
676    }
677    validate_manifest_identity(path, requested_plan)?;
678
679    let prepared = match pending {
680        Some(record) => {
681            if record.plan != *requested_plan {
682                return Err(HawDBError::Storage(
683                    "pending WAL doctor repair record does not match the requested plan"
684                        .to_string(),
685                ));
686            }
687            validate_quarantine(path, &record)?;
688            // A previous audit rename can be visible even if its directory
689            // barrier failed. Re-establish evidence and audit durability.
690            prepare_repair(path, &wal_path, requested_plan)?
691        }
692        None => prepare_repair(path, &wal_path, requested_plan)?,
693    };
694    validate_quarantine(path, &prepared)?;
695    super::process_crash_failpoint("after_wal_repair_prepare");
696
697    protect_repaired_prefix(path, requested_plan)?;
698    validate_manifest_identity(path, requested_plan)?;
699    let before_truncate = file_checksum(&wal_path)?;
700    if !file_identity_matches(
701        before_truncate,
702        requested_plan.original_wal_len,
703        requested_plan.original_wal_crc32c,
704        &requested_plan.original_wal_sha256,
705    ) {
706        return Err(HawDBError::Storage(
707            "WAL changed after the doctor repair was prepared; pending audit was retained"
708                .to_string(),
709        ));
710    }
711    let wal = repair_io(
712        "open WAL for repair",
713        OpenOptions::new().read(true).write(true).open(&wal_path),
714    )?;
715    repair_io("truncate WAL", wal.set_len(requested_plan.retained_wal_len))?;
716    super::process_crash_failpoint("after_wal_repair_set_len");
717    repair_io("synchronize repaired WAL", wal.sync_all())?;
718    repair_io(
719        "synchronize WAL directory",
720        crate::durability::sync_parent_directory(&wal_path),
721    )?;
722    super::process_crash_failpoint("after_wal_repair_truncate");
723    let after_truncate = file_checksum(&wal_path)?;
724    if !file_identity_matches(
725        after_truncate,
726        requested_plan.retained_wal_len,
727        requested_plan.retained_wal_crc32c,
728        &requested_plan.retained_wal_sha256,
729    ) {
730        return Err(HawDBError::Storage(
731            "WAL doctor repair produced an unexpected retained WAL identity; pending audit was retained"
732                .to_string(),
733        ));
734    }
735    finalize_repair(path, prepared, false)
736}
737
738#[doc(hidden)]
739pub fn prepare_repair(
740    path: &Path,
741    wal_path: &Path,
742    plan: &WalTailRepairPlan,
743) -> Result<WalRepairAuditRecord> {
744    let doctor_dir = doctor_directory(path);
745    let quarantine_dir = doctor_dir.join(DOCTOR_QUARANTINE_DIRECTORY);
746    repair_io(
747        "create evidence directory",
748        fs::create_dir_all(&quarantine_dir),
749    )?;
750    repair_io(
751        "synchronize doctor directory",
752        crate::durability::sync_parent_directory(&doctor_dir),
753    )?;
754    repair_io(
755        "synchronize quarantine directory",
756        crate::durability::sync_parent_directory(&quarantine_dir),
757    )?;
758    let quarantine_file = quarantine_file_name(plan);
759    let quarantine_path = quarantine_dir.join(&quarantine_file);
760    if !quarantine_path.exists() {
761        let temporary = quarantine_path.with_extension("tail.tmp");
762        let mut source = repair_io("open WAL suffix", File::open(wal_path))?;
763        repair_io(
764            "seek WAL suffix",
765            source.seek(SeekFrom::Start(plan.retained_wal_len)),
766        )?;
767        {
768            let mut output = repair_io("create suffix evidence", File::create(&temporary))?;
769            let copied = repair_io("write suffix evidence", io::copy(&mut source, &mut output))?;
770            if copied != plan.discarded_wal_tail_bytes {
771                return Err(HawDBError::StorageIntegrity(
772                    "WAL changed while preserving the discarded suffix".into(),
773                ));
774            }
775            repair_io("flush suffix evidence", output.flush())?;
776            repair_io("synchronize suffix evidence", output.sync_all())?;
777        }
778        super::process_crash_failpoint("after_wal_repair_evidence_sync");
779        repair_io(
780            "publish suffix evidence",
781            hawdb_storage::durability::durable_replace_file(&temporary, &quarantine_path),
782        )?;
783        super::process_crash_failpoint("after_wal_repair_evidence_publish");
784    }
785    // A visible suffix may come from an interrupted rename. Its data and
786    // namespace must be durable even when this retry did not create it.
787    let evidence = repair_io(
788        "reopen suffix evidence",
789        OpenOptions::new()
790            .read(true)
791            .write(true)
792            .open(&quarantine_path),
793    )?;
794    repair_io("finish suffix evidence barrier", evidence.sync_all())?;
795    repair_io(
796        "synchronize suffix directory",
797        crate::durability::sync_parent_directory(&quarantine_path),
798    )?;
799    drop(evidence);
800    let record = WalRepairAuditRecord {
801        protocol: WAL_DOCTOR_REPAIR_PROTOCOL.to_string(),
802        state: WalRepairAuditState::Prepared,
803        plan: plan.clone(),
804        quarantine_file,
805    };
806    validate_quarantine(path, &record)?;
807    write_audit_record(&pending_record_path(path, plan), &record)?;
808    Ok(record)
809}
810
811fn finalize_repair(
812    path: &Path,
813    mut record: WalRepairAuditRecord,
814    resumed_interrupted_repair: bool,
815) -> Result<WalTailRepairReport> {
816    validate_quarantine(path, &record)?;
817    protect_repaired_prefix(path, &record.plan)?;
818    let wal_path = path.join(crate::artifact_files::wal_generation_file(
819        record.plan.wal_generation,
820    ));
821    let wal = repair_io(
822        "reopen repaired WAL",
823        OpenOptions::new().read(true).write(true).open(&wal_path),
824    )?;
825    repair_io("finish repaired WAL barrier", wal.sync_all())?;
826    repair_io(
827        "synchronize WAL directory",
828        crate::durability::sync_parent_directory(&wal_path),
829    )?;
830    record.state = WalRepairAuditState::Applied;
831    let applied_path = applied_record_path(path, &record.plan);
832    write_audit_record(&applied_path, &record)?;
833    super::process_crash_failpoint("after_wal_repair_applied");
834    let pending_path = pending_record_path(path, &record.plan);
835    if pending_path.exists() {
836        repair_io("retire pending audit", fs::remove_file(&pending_path))?;
837        repair_io(
838            "synchronize retired audit",
839            crate::durability::sync_parent_directory(&pending_path),
840        )?;
841    }
842    Ok(WalTailRepairReport {
843        protocol: WAL_DOCTOR_REPAIR_PROTOCOL.to_string(),
844        plan_id: record.plan.plan_id.clone(),
845        wal_generation: record.plan.wal_generation,
846        retained_wal_len: record.plan.retained_wal_len,
847        discarded_wal_tail_bytes: record.plan.discarded_wal_tail_bytes,
848        next_lsn_after_repair: record.plan.next_lsn_after_repair,
849        quarantine_file: record.quarantine_file,
850        repair_record_file: file_name(&applied_path)?,
851        resumed_interrupted_repair,
852        reason: record.plan.reason,
853        evidence_directory: doctor_directory(path),
854    })
855}
856
857fn validate_manifest_identity(path: &Path, plan: &WalTailRepairPlan) -> Result<()> {
858    let boundary = WalRepairBoundary::load(path, WalDoctorOptions::default())?;
859    let identity = file_checksum(&boundary.selector_path)?;
860    if file_identity_matches(
861        identity,
862        plan.manifest_len,
863        plan.manifest_crc32c,
864        &plan.manifest_sha256,
865    ) {
866        Ok(())
867    } else {
868        Err(HawDBError::Storage(
869            "durable manifest changed after the WAL doctor repair plan was created".to_string(),
870        ))
871    }
872}
873
874fn validate_checkpoint_boundary(path: &Path, manifest: DurableManifest) -> Result<()> {
875    let Some(generation) = manifest.checkpoint_generation else {
876        return Ok(());
877    };
878    let expected_len = manifest
879        .checkpoint_encoded_len
880        .ok_or_else(|| HawDBError::Storage("manifest checkpoint length is missing".to_string()))?;
881    let expected_crc32c = manifest
882        .checkpoint_encoded_checksum
883        .ok_or_else(|| HawDBError::Storage("manifest checkpoint CRC32C is missing".to_string()))?;
884    let expected_sha256 = manifest
885        .checkpoint_encoded_sha256
886        .ok_or_else(|| HawDBError::Storage("manifest checkpoint SHA-256 is missing".to_string()))?;
887    let identity = file_checksum(&manifest.checkpoint_path(path))?;
888    if identity.0 != expected_len || identity.1 != expected_crc32c || identity.2 != expected_sha256
889    {
890        return Err(HawDBError::Storage(format!(
891            "WAL doctor rejected checkpoint generation {generation} because its published identity does not match the manifest"
892        )));
893    }
894    Ok(())
895}
896
897fn validate_pending_truncated_wal(path: &Path, record: &WalRepairAuditRecord) -> Result<()> {
898    if record.state != WalRepairAuditState::Prepared {
899        return Err(HawDBError::Storage(
900            "pending WAL doctor record has an invalid state".to_string(),
901        ));
902    }
903    validate_manifest_identity(path, &record.plan)?;
904    let boundary = WalRepairBoundary::load(path, WalDoctorOptions::default())?;
905    let identity = file_checksum(&boundary.wal_path(path))?;
906    if !file_identity_matches(
907        identity,
908        record.plan.retained_wal_len,
909        record.plan.retained_wal_crc32c,
910        &record.plan.retained_wal_sha256,
911    ) {
912        return Err(HawDBError::Storage(
913            "pending WAL doctor repair does not match the current WAL identity".to_string(),
914        ));
915    }
916    validate_quarantine(path, record)
917}
918
919fn validate_quarantine(path: &Path, record: &WalRepairAuditRecord) -> Result<()> {
920    let wal_path = path.join(crate::artifact_files::wal_generation_file(
921        record.plan.wal_generation,
922    ));
923    let mut prefix = repair_io("open retained prefix", File::open(&wal_path))?
924        .take(record.plan.retained_wal_len);
925    let evidence = doctor_directory(path)
926        .join(DOCTOR_QUARANTINE_DIRECTORY)
927        .join(&record.quarantine_file);
928    let tail = repair_io("open suffix for validation", File::open(evidence))?;
929    if repair_io("inspect suffix evidence", tail.metadata())?.len()
930        != record.plan.discarded_wal_tail_bytes
931    {
932        return Err(HawDBError::StorageIntegrity(
933            "WAL repair suffix has the wrong length".into(),
934        ));
935    }
936    // Reconstruct the original identity without retaining a second copy of
937    // the valid prefix. This works before and after the WAL truncation.
938    let mut hasher = IntegrityHasher::new();
939    let mut buffer = [0u8; 64 * 1024];
940    let mut total = 0;
941    loop {
942        let read = repair_io("read retained prefix", prefix.read(&mut buffer))?;
943        if read == 0 {
944            break;
945        }
946        hasher.update(&buffer[..read]);
947        total += read as u64;
948    }
949    if total != record.plan.retained_wal_len {
950        return Err(HawDBError::StorageIntegrity(
951            "WAL repair lost its retained prefix".into(),
952        ));
953    }
954    let mut tail = tail;
955    loop {
956        let read = repair_io("read suffix evidence", tail.read(&mut buffer))?;
957        if read == 0 {
958            break;
959        }
960        hasher.update(&buffer[..read]);
961        total += read as u64;
962    }
963    let digest = hasher.finish();
964    let identity = (total, digest.crc32c.as_u64(), digest.sha256);
965    if file_identity_matches(
966        identity,
967        record.plan.original_wal_len,
968        record.plan.original_wal_crc32c,
969        &record.plan.original_wal_sha256,
970    ) {
971        Ok(())
972    } else {
973        Err(HawDBError::Storage(
974            "WAL doctor quarantine file does not match the original WAL identity".to_string(),
975        ))
976    }
977}
978
979fn file_prefix_checksum(
980    path: &Path,
981    limit: u64,
982) -> Result<(u64, u64, hawdb_integrity::Sha256Digest)> {
983    let mut file = File::open(path)?;
984    file.seek(SeekFrom::Start(0))?;
985    let mut integrity = IntegrityHasher::new();
986    let mut total = 0u64;
987    let mut buffer = vec![0u8; 1024 * 1024];
988    while total < limit {
989        let remaining = limit.saturating_sub(total).min(buffer.len() as u64) as usize;
990        let read = file.read(&mut buffer[..remaining])?;
991        if read == 0 {
992            break;
993        }
994        integrity.update(&buffer[..read]);
995        total = total.saturating_add(read as u64);
996    }
997    if total != limit {
998        return Err(HawDBError::Storage(
999            "WAL ended before the planned retained prefix".to_string(),
1000        ));
1001    }
1002    let digest = integrity.finish();
1003    Ok((total, digest.crc32c.as_u64(), digest.sha256))
1004}
1005
1006fn file_identity_matches(
1007    identity: (u64, u64, hawdb_integrity::Sha256Digest),
1008    expected_len: u64,
1009    expected_crc32c: u64,
1010    expected_sha256: &str,
1011) -> bool {
1012    identity.0 == expected_len
1013        && identity.1 == expected_crc32c
1014        && identity.2.to_string() == expected_sha256
1015}
1016
1017fn write_audit_record(path: &Path, record: &WalRepairAuditRecord) -> Result<()> {
1018    let parent = path.parent().ok_or_else(|| {
1019        HawDBError::Storage("WAL doctor audit path has no parent directory".to_string())
1020    })?;
1021    repair_io("create audit directory", fs::create_dir_all(parent))?;
1022    let encoded = serde_json::to_vec_pretty(record).map_err(|error| {
1023        HawDBError::or_stop(&error, || {
1024            HawDBError::Storage(format!("failed to encode WAL doctor audit record: {error}"))
1025        })
1026    })?;
1027    let temp_path = path.with_extension("json.tmp");
1028    {
1029        let mut file = repair_io(
1030            "create audit",
1031            OpenOptions::new()
1032                .write(true)
1033                .create(true)
1034                .truncate(true)
1035                .open(&temp_path),
1036        )?;
1037        repair_io("write audit", file.write_all(&encoded))?;
1038        repair_io("synchronize audit", file.sync_all())?;
1039    }
1040    repair_io(
1041        "publish audit",
1042        hawdb_storage::durability::durable_replace_file(&temp_path, path),
1043    )
1044}
1045
1046#[doc(hidden)]
1047pub fn pending_repair_records(path: &Path) -> Result<Vec<PathBuf>> {
1048    let doctor_dir = doctor_directory(path);
1049    if !doctor_dir.exists() {
1050        return Ok(Vec::new());
1051    }
1052    let mut pending = Vec::new();
1053    for entry in fs::read_dir(&doctor_dir)? {
1054        let path = entry?.path();
1055        if path
1056            .file_name()
1057            .and_then(|name| name.to_str())
1058            .is_some_and(|name| name.ends_with(".repair.pending.json"))
1059        {
1060            pending.push(path);
1061        }
1062    }
1063    pending.sort();
1064    Ok(pending)
1065}
1066
1067fn load_single_pending_record(path: &Path) -> Result<Option<WalRepairAuditRecord>> {
1068    let records = pending_repair_records(path)?;
1069    match records.as_slice() {
1070        [] => Ok(None),
1071        [record] => load_audit_record(record).map(Some),
1072        _ => Err(HawDBError::Storage(
1073            "database has multiple pending WAL doctor repair records".to_string(),
1074        )),
1075    }
1076}
1077
1078fn load_matching_pending_record(
1079    path: &Path,
1080    plan_id: &str,
1081) -> Result<Option<WalRepairAuditRecord>> {
1082    let Some(record) = load_single_pending_record(path)? else {
1083        return Ok(None);
1084    };
1085    if record.plan.plan_id == plan_id {
1086        Ok(Some(record))
1087    } else {
1088        Err(HawDBError::Storage(
1089            "database has a pending WAL doctor repair for a different plan".to_string(),
1090        ))
1091    }
1092}
1093
1094fn load_audit_record(path: &Path) -> Result<WalRepairAuditRecord> {
1095    let encoded_len = fs::metadata(path)?.len();
1096    if encoded_len > MAX_DOCTOR_AUDIT_BYTES {
1097        return Err(HawDBError::Storage(format!(
1098            "WAL doctor audit record exceeds the {MAX_DOCTOR_AUDIT_BYTES} byte limit"
1099        )));
1100    }
1101    let encoded = fs::read(path)?;
1102    let record = serde_json::from_slice::<WalRepairAuditRecord>(&encoded).map_err(|error| {
1103        HawDBError::or_stop(&error, || {
1104            HawDBError::Storage(format!("invalid WAL doctor audit record: {error}"))
1105        })
1106    })?;
1107    if record.protocol != WAL_DOCTOR_REPAIR_PROTOCOL
1108        || record.plan.protocol != WAL_DOCTOR_REPAIR_PROTOCOL
1109        || record.plan.plan_id != plan_identity(&record.plan)
1110        || record.quarantine_file != quarantine_file_name(&record.plan)
1111    {
1112        return Err(HawDBError::Storage(
1113            "WAL doctor audit record identity is invalid".to_string(),
1114        ));
1115    }
1116    Ok(record)
1117}
1118
1119#[doc(hidden)]
1120pub fn doctor_directory(path: &Path) -> PathBuf {
1121    path.join(DOCTOR_DIRECTORY)
1122}
1123
1124#[doc(hidden)]
1125pub fn pending_record_path(path: &Path, plan: &WalTailRepairPlan) -> PathBuf {
1126    doctor_directory(path).join(format!(
1127        "wal.{}.{}.repair.pending.json",
1128        plan.wal_generation, plan.plan_id
1129    ))
1130}
1131
1132#[doc(hidden)]
1133pub fn applied_record_path(path: &Path, plan: &WalTailRepairPlan) -> PathBuf {
1134    doctor_directory(path).join(format!(
1135        "wal.{}.{}.repair.applied.json",
1136        plan.wal_generation, plan.plan_id
1137    ))
1138}
1139
1140fn quarantine_file_name(plan: &WalTailRepairPlan) -> String {
1141    format!(
1142        "wal.{}.{}.discarded-tail.hawdb",
1143        plan.wal_generation, plan.plan_id
1144    )
1145}
1146
1147fn file_name(path: &Path) -> Result<String> {
1148    path.file_name()
1149        .and_then(|name| name.to_str())
1150        .map(str::to_string)
1151        .ok_or_else(|| HawDBError::Storage("WAL doctor path has no valid file name".to_string()))
1152}
1153
1154#[cfg(test)]
1155#[path = "doctor/format_tests.rs"]
1156mod format_tests;
1157
1158fn repair_io<T>(operation: &'static str, result: io::Result<T>) -> Result<T> {
1159    #[cfg(test)]
1160    let result = result.and_then(|value| {
1161        REPAIR_FAILURE.with(|failure| {
1162            if failure
1163                .borrow()
1164                .as_ref()
1165                .is_some_and(|(stage, _)| *stage == operation)
1166            {
1167                return Err(io::Error::from(
1168                    failure.borrow_mut().take().expect("matching failure").1,
1169                ));
1170            }
1171            Ok(())
1172        })?;
1173        Ok(value)
1174    });
1175    result.map_err(|error| {
1176        if let Some(resource) = hawdb_core::error::file_descriptor_error(&error) {
1177            HawDBError::FileDescriptors(resource)
1178        } else {
1179            HawDBError::WalRecoveryIo {
1180                operation,
1181                kind: error.kind(),
1182                os_code: error.raw_os_error(),
1183                message: error.to_string(),
1184            }
1185        }
1186    })
1187}
1188
1189fn protect_repaired_prefix(path: &Path, plan: &WalTailRepairPlan) -> Result<()> {
1190    let wal = path.join(crate::artifact_files::wal_generation_file(
1191        plan.wal_generation,
1192    ));
1193    if let Some(mut fence) = super::wal_fence::WalRecoveryFence::load(
1194        &wal,
1195        plan.wal_generation,
1196        plan.wal_replay_start_lsn,
1197    )? {
1198        fence.validate_retained(plan.retained_wal_len, plan.next_lsn_after_repair)?;
1199        if fence.protected_bytes != plan.retained_wal_len
1200            || fence.next_lsn != plan.next_lsn_after_repair
1201        {
1202            fence.protected_bytes = plan.retained_wal_len;
1203            fence.next_lsn = plan.next_lsn_after_repair;
1204            let directory = crate::file_io::SourceDirectory::capture_for_path(path)?;
1205            fence.publish(&wal, &directory)?;
1206        }
1207    }
1208    Ok(())
1209}
1210
1211#[cfg(test)]
1212#[path = "doctor/recovery_tests.rs"]
1213mod recovery_tests;
1214
1215#[cfg(test)]
1216thread_local! {
1217    static REPAIR_FAILURE: std::cell::RefCell<Option<(&'static str, io::ErrorKind)>> = const { std::cell::RefCell::new(None) };
1218}