1use super::doctor::DatabaseDoctor;
16use super::{
17 file_checksum, load_published_canonical_adjacency, load_published_property_projection,
18 store_id_for_path, DurableManifest, GraphManifestOpenBudget, GraphStore, RecoveryMode,
19 SegmentCache, StorageResidencyMode, WalReplayConfig, MANIFEST_FILE,
20};
21use crate::error::{HawDBError, Result};
22use hawdb_storage::derived_repair::{plan_identity, validate_options, validate_plan};
23pub use hawdb_storage::derived_repair::{
24 DerivedArtifactBranchSource, DerivedArtifactHealth, DerivedArtifactHealthReport,
25 DerivedArtifactHealthState, DerivedArtifactKind, DerivedArtifactRebuildOptions,
26 DerivedArtifactRepairPlan, DerivedArtifactRepairReport, DERIVED_ARTIFACT_REPAIR_PROTOCOL,
27};
28use std::path::{Path, PathBuf};
29use std::sync::Arc;
30
31#[path = "derived_repair/audit.rs"]
32#[doc(hidden)]
33pub mod audit;
34#[path = "derived_repair/publication.rs"]
35pub(super) mod publication;
36use audit::{
37 finalize_repair, load_matching_pending_record, load_single_pending_record, prepare_repair,
38 validate_pending_record,
39};
40
41struct DerivedInspection {
42 store: GraphStore,
43 recovered_catalog: crate::schema::Catalog,
44 health: DerivedArtifactHealthReport,
45 manifest: DurableManifest,
46}
47
48impl DatabaseDoctor {
49 pub fn derived_artifact_health(
50 path: impl AsRef<Path>,
51 options: DerivedArtifactRebuildOptions,
52 ) -> Result<DerivedArtifactHealthReport> {
53 validate_options(options)?;
54 let directory = super::doctor::repair_directory(path.as_ref())?;
55 let path = directory.as_path();
56 let _files = super::doctor::repair_file_descriptors(path)?;
57 if let Some(record) = load_single_pending_record(path)? {
58 validate_pending_record(path, &record)?;
59 let inspection = inspect(path, record.plan.options)?;
60 return Ok(inspection.health);
61 }
62 Ok(inspect(path, options)?.health)
63 }
64
65 pub fn plan_derived_artifact_rebuild(
66 path: impl AsRef<Path>,
67 options: DerivedArtifactRebuildOptions,
68 ) -> Result<DerivedArtifactRepairPlan> {
69 validate_options(options)?;
70 let directory = super::doctor::repair_directory(path.as_ref())?;
71 let path = directory.as_path();
72 let _files = super::doctor::repair_file_descriptors(path)?;
73 if let Some(record) = load_single_pending_record(path)? {
74 validate_pending_record(path, &record)?;
75 return Ok(record.plan);
76 }
77 let inspection = inspect(path, options)?;
78 plan_from_inspection(&inspection, options)
79 }
80
81 pub fn apply_derived_artifact_rebuild(
82 path: impl AsRef<Path>,
83 plan: &DerivedArtifactRepairPlan,
84 ) -> Result<DerivedArtifactRepairReport> {
85 validate_plan(plan)?;
86 let directory = super::doctor::repair_directory(path.as_ref())?;
87 let path = directory.as_path();
88 let _files = super::doctor::repair_file_descriptors(path)?;
89 let pending = load_matching_pending_record(path, &plan.plan_id)?;
90 if let Some(record) = &pending {
91 validate_pending_record(path, record)?;
92 if record.plan != *plan {
93 return Err(HawDBError::Storage(
94 "pending derived repair plan differs from the requested plan".into(),
95 ));
96 }
97 }
98 let mut inspection = inspect(path, plan.options)?;
99 if let Some(record) = &pending
100 && inspection.manifest.checkpoint_epoch == record.plan.target_generation
101 && inspection.manifest.checkpoint_commit_epoch == plan.source_commit_epoch
102 && inspection.store.commit_epoch == plan.source_commit_epoch
103 && !inspection.health.repair_required
104 {
105 return finalize_repair(path, record.clone(), true);
107 }
108 if pending.is_none() && plan_from_inspection(&inspection, plan.options)? != *plan {
109 return Err(HawDBError::Storage(
110 "derived artifact repair plan no longer matches the current database state"
111 .to_string(),
112 ));
113 }
114 validate_source_identity(path, plan)?;
115 if inspection.manifest.checkpoint_epoch != plan.source_generation
116 || inspection.store.commit_epoch != plan.source_commit_epoch
117 || inspection.health.source_node_count != plan.source_node_count
118 || inspection.health.source_relationship_count != plan.source_relationship_count
119 || inspection.health.source_logical_bytes != plan.source_logical_bytes
120 || inspection
121 .store
122 .durable
123 .as_ref()
124 .unwrap()
125 .next_checkpoint_generation()?
126 != plan.target_generation
127 {
128 return Err(HawDBError::Storage(
129 "derived repair source no longer matches the planned recovery".into(),
130 ));
131 }
132 let resumed = pending.is_some();
133 let prepared = match pending {
134 Some(record) => record,
135 None => prepare_repair(path, plan)?,
136 };
137 validate_pending_record(path, &prepared)?;
138 if resumed && plan.branch.is_some() {
139 audit::archive_unpublished_checkpoint(
140 path,
141 &prepared,
142 inspection.store.durable.as_ref().unwrap().root_path(),
143 )?;
144 }
145 if plan.branch.is_some() {
146 inspection
147 .store
148 .authorize_derived_repair_publication(Arc::new(
149 publication::DerivedRepairPublication::from_prepared(path, prepared.clone()),
150 ))?;
151 }
152 inspection.store.enable_derived_repair_writes()?;
153 let build_config = build_config(plan.options)?;
154 inspection
155 .store
156 .checkpoint_with_reader_epoch_and_build_config(
157 &inspection.recovered_catalog,
158 None,
159 build_config,
160 )?;
161 let durable = inspection.store.durable.as_ref().unwrap();
162 let manifest = match &plan.branch {
163 Some(source) => DurableManifest::load(&published_branch(path, source)?.manifest_path)?,
164 None => DurableManifest::load(durable.manifest_path())?,
165 };
166 if manifest.checkpoint_epoch != plan.target_generation
167 || manifest.checkpoint_commit_epoch != plan.source_commit_epoch
168 || assess_artifacts(
169 durable.root_path(),
170 &inspection.store,
171 manifest,
172 plan.options,
173 )?
174 .iter()
175 .any(|artifact| artifact.state == DerivedArtifactHealthState::RepairRequired)
176 {
177 return Err(HawDBError::Storage(
178 "derived artifact rebuild did not publish one healthy target generation; pending audit was retained"
179 .to_string(),
180 ));
181 }
182 let prepared = if plan.branch.is_some() {
183 load_matching_pending_record(path, &plan.plan_id)?.ok_or_else(|| {
184 HawDBError::Storage("published branch repair lost its pending audit".into())
185 })?
186 } else {
187 prepared
188 };
189 finalize_repair(path, prepared, resumed)
190 }
191}
192
193pub(crate) fn reject_pending_derived_artifact_repair(path: &Path) -> Result<()> {
194 let pending = audit::pending_record_paths_at_directory(path)?;
195 if pending.is_empty() {
196 return Ok(());
197 }
198 Err(HawDBError::Storage(format!(
199 "database has {} interrupted derived artifact repair record(s); finish the repair with DatabaseDoctor before opening the database",
200 pending.len()
201 )))
202}
203
204fn inspect(path: &Path, options: DerivedArtifactRebuildOptions) -> Result<DerivedInspection> {
205 let replay = WalReplayConfig {
206 recovery_mode: RecoveryMode::Strict,
207 max_entries: Some(options.max_wal_replay_entries),
208 max_bytes: Some(options.max_wal_replay_bytes),
209 segment_cache_capacity_bytes: options.segment_cache_capacity_bytes,
210 max_graph_manifest_open_bytes: options.max_graph_manifest_open_bytes,
211 residency_mode: StorageResidencyMode::OutOfCore,
212 max_out_of_core_delta_bytes: Some(options.max_source_logical_bytes),
213 ..WalReplayConfig::default()
214 };
215 let (store, recovered_catalog) = GraphStore::open_for_derived_repair(path, replay)?;
216 let durable = store.durable.as_ref().expect("repair source is durable");
217 let manifest = DurableManifest::load(durable.manifest_path())?;
218 manifest.validate()?;
219 let (node_count, relationship_count, logical_bytes) =
220 validate_canonical_source(&store, options)?;
221 let artifacts = assess_artifacts(durable.root_path(), &store, manifest, options)?;
222 let repair_required = artifacts
223 .iter()
224 .any(|artifact| artifact.state == DerivedArtifactHealthState::RepairRequired);
225 Ok(DerivedInspection {
226 store,
227 recovered_catalog,
228 health: DerivedArtifactHealthReport {
229 protocol: DERIVED_ARTIFACT_REPAIR_PROTOCOL.to_string(),
230 checkpoint_generation: manifest.checkpoint_epoch,
231 checkpoint_commit_epoch: manifest.checkpoint_commit_epoch,
232 canonical_source_validated: true,
233 source_node_count: node_count,
234 source_relationship_count: relationship_count,
235 source_logical_bytes: logical_bytes,
236 artifacts,
237 repair_required,
238 },
239 manifest,
240 })
241}
242
243fn validate_canonical_source(
244 store: &GraphStore,
245 options: DerivedArtifactRebuildOptions,
246) -> Result<(u64, u64, u64)> {
247 let logical_bytes = store.estimated_logical_record_bytes();
248 if logical_bytes > options.max_source_logical_bytes {
249 return Err(HawDBError::Storage(format!(
250 "derived repair source byte admission rejected {logical_bytes} bytes under the {} byte limit",
251 options.max_source_logical_bytes
252 )));
253 }
254 let mut node_count = 0u64;
255 for node in store.node_records_owned() {
256 node.map_err(|error| HawDBError::StorageIntegrity(error.to_string()))?;
257 node_count = node_count.saturating_add(1);
258 if node_count > options.max_source_records {
259 return Err(HawDBError::Storage(format!(
260 "derived repair source record admission exceeded {} records",
261 options.max_source_records
262 )));
263 }
264 }
265 let mut relationship_count = 0u64;
266 for relationship in store.relationship_records_owned() {
267 relationship.map_err(|error| HawDBError::StorageIntegrity(error.to_string()))?;
268 relationship_count = relationship_count.saturating_add(1);
269 if node_count.saturating_add(relationship_count) > options.max_source_records {
270 return Err(HawDBError::Storage(format!(
271 "derived repair source record admission exceeded {} records",
272 options.max_source_records
273 )));
274 }
275 }
276 Ok((node_count, relationship_count, logical_bytes))
277}
278
279fn assess_artifacts(
280 path: &Path,
281 store: &GraphStore,
282 manifest: DurableManifest,
283 options: DerivedArtifactRebuildOptions,
284) -> Result<Vec<DerivedArtifactHealth>> {
285 if manifest.checkpoint_generation.is_none() {
286 return Ok(Vec::new());
287 }
288 let canonical_relationship_count = store
289 .canonical_base
290 .as_ref()
291 .map(|reader| reader.manifest().relationship_count)
292 .unwrap_or_default();
293 Ok(vec![
294 assess_one(DerivedArtifactKind::CanonicalAdjacency, || {
295 validate_branch_derived_objects(store, DerivedArtifactKind::CanonicalAdjacency)?;
296 let cache = Arc::new(SegmentCache::new(options.segment_cache_capacity_bytes));
297 let mut open_budget =
298 GraphManifestOpenBudget::new(options.max_graph_manifest_open_bytes);
299 let reader = load_published_canonical_adjacency(
300 path,
301 manifest,
302 cache,
303 store_id_for_path(path)?,
304 &mut open_budget,
305 )?
306 .ok_or_else(|| {
307 HawDBError::Storage("canonical adjacency publication is missing".to_string())
308 })?;
309 if reader.relationship_count() != canonical_relationship_count {
310 return Err(HawDBError::Storage(
311 "canonical adjacency relationship count mismatch".to_string(),
312 ));
313 }
314 reader
315 .deep_scrub()
316 .map(|_| ())
317 .map_err(|error| HawDBError::StorageIntegrity(error.to_string()))
318 })?,
319 assess_one(DerivedArtifactKind::PersistentPropertyProjection, || {
320 validate_branch_derived_objects(
321 store,
322 DerivedArtifactKind::PersistentPropertyProjection,
323 )?;
324 let cache = Arc::new(SegmentCache::new(options.segment_cache_capacity_bytes));
325 let mut open_budget =
326 GraphManifestOpenBudget::new(options.max_graph_manifest_open_bytes);
327 let reader = load_published_property_projection(
328 path,
329 manifest,
330 cache,
331 store_id_for_path(path)?,
332 &mut open_budget,
333 )?
334 .ok_or_else(|| {
335 HawDBError::Storage(
336 "persistent property projection publication is missing".to_string(),
337 )
338 })?;
339 reader
340 .deep_scrub()
341 .map(|_| ())
342 .map_err(|error| HawDBError::StorageIntegrity(error.to_string()))
343 })?,
344 ])
345}
346
347pub(super) fn rebuildable_artifact_kind(
348 path: &str,
349 generation: u64,
350) -> Option<DerivedArtifactKind> {
351 [
352 DerivedArtifactKind::CanonicalAdjacency,
353 DerivedArtifactKind::PersistentPropertyProjection,
354 ]
355 .into_iter()
356 .find(|kind| {
357 audit::target_files(*kind, generation)
358 .iter()
359 .any(|name| name == path)
360 })
361}
362
363fn validate_branch_derived_objects(store: &GraphStore, kind: DerivedArtifactKind) -> Result<()> {
364 let durable = store.durable.as_ref().expect("repair source is durable");
365 let Some(branch) = &durable.branch_runtime else {
366 return Ok(());
367 };
368 let objects =
369 crate::immutable_object::ImmutableObjectStore::open(branch.immutable_store_root())
370 .map_err(HawDBError::from_storage_error)?;
371 let references = branch
372 .root()
373 .checkpoint_bindings
374 .iter()
375 .filter(|binding| {
376 audit::target_files(
377 kind,
378 match kind {
379 DerivedArtifactKind::CanonicalAdjacency => durable.adjacency_generation(),
380 DerivedArtifactKind::PersistentPropertyProjection => durable.graph_generation(),
381 },
382 )
383 .contains(&binding.relative_path)
384 })
385 .map(|binding| binding.reference)
386 .collect::<std::collections::BTreeSet<_>>();
387 for reference in references {
388 objects
389 .verify_stored(reference)
390 .map_err(HawDBError::from_storage_error)?;
391 }
392 Ok(())
393}
394
395fn assess_one(
396 kind: DerivedArtifactKind,
397 check: impl FnOnce() -> Result<()>,
398) -> Result<DerivedArtifactHealth> {
399 match check() {
400 Ok(()) => Ok(DerivedArtifactHealth {
401 kind,
402 state: DerivedArtifactHealthState::Healthy,
403 reason_code: None,
404 }),
405 Err(error @ HawDBError::FileDescriptors(_)) => Err(error),
406 Err(_) => Ok(DerivedArtifactHealth {
407 kind,
408 state: DerivedArtifactHealthState::RepairRequired,
409 reason_code: Some("artifact_missing_corrupt_or_inconsistent".to_string()),
410 }),
411 }
412}
413
414fn plan_from_inspection(
415 inspection: &DerivedInspection,
416 options: DerivedArtifactRebuildOptions,
417) -> Result<DerivedArtifactRepairPlan> {
418 let targets = inspection
419 .health
420 .artifacts
421 .iter()
422 .filter(|artifact| artifact.state == DerivedArtifactHealthState::RepairRequired)
423 .map(|artifact| artifact.kind)
424 .collect::<Vec<_>>();
425 if targets.is_empty() {
426 return Err(HawDBError::Storage(
427 "derived artifact doctor found no repair-required artifact".to_string(),
428 ));
429 }
430 let estimated_temporary_bytes = inspection
431 .health
432 .source_logical_bytes
433 .saturating_mul(8)
434 .max(64 * 1024 * 1024);
435 if estimated_temporary_bytes > options.max_temporary_bytes {
436 return Err(HawDBError::Storage(format!(
437 "derived repair temporary byte admission rejected {estimated_temporary_bytes} estimated bytes under the {} byte limit",
438 options.max_temporary_bytes
439 )));
440 }
441 let durable = inspection
442 .store
443 .durable
444 .as_ref()
445 .expect("repair source is durable");
446 let manifest_identity = file_checksum(durable.manifest_path())?;
447 let wal_identity = file_checksum(&durable.wal_path)?;
448 let branch = durable
449 .branch_runtime
450 .as_ref()
451 .map(|branch| {
452 let head = file_checksum(branch.head_path())?;
453 Ok::<_, HawDBError>(DerivedArtifactBranchSource {
454 project_id: hawdb_core::Uuid::from_bytes(branch.head.project_id),
455 branch_id: hawdb_core::Uuid::from_bytes(branch.head.branch_id),
456 metadata_revision: branch.metadata_revision(),
457 head_len: head.0,
458 head_crc32c: head.1,
459 head_sha256: head.2.to_string(),
460 })
461 })
462 .transpose()?;
463 let mut plan = DerivedArtifactRepairPlan {
464 protocol: DERIVED_ARTIFACT_REPAIR_PROTOCOL.to_string(),
465 plan_id: String::new(),
466 branch,
467 source_generation: inspection.manifest.checkpoint_epoch,
468 target_generation: durable.next_checkpoint_generation()?,
469 source_commit_epoch: inspection.store.commit_epoch,
470 manifest_len: manifest_identity.0,
471 manifest_crc32c: manifest_identity.1,
472 manifest_sha256: manifest_identity.2.to_string(),
473 wal_len: wal_identity.0,
474 wal_crc32c: wal_identity.1,
475 wal_sha256: wal_identity.2.to_string(),
476 source_node_count: inspection.health.source_node_count,
477 source_relationship_count: inspection.health.source_relationship_count,
478 source_logical_bytes: inspection.health.source_logical_bytes,
479 estimated_temporary_bytes,
480 targets,
481 options,
482 };
483 plan.plan_id = plan_identity(&plan);
484 Ok(plan)
485}
486
487pub(crate) use hawdb_storage::derived_repair::build_config;
488
489fn validate_source_identity(path: &Path, plan: &DerivedArtifactRepairPlan) -> Result<()> {
490 let (manifest_path, wal_path) = match &plan.branch {
491 Some(source) => {
492 let published = published_branch(path, source)?;
493 let head = file_checksum(&path.join("branch.head"))?;
494 if head.0 != source.head_len
495 || head.1 != source.head_crc32c
496 || head.2.to_string() != source.head_sha256
497 {
498 return Err(HawDBError::Storage(
499 "derived artifact repair branch head changed after planning".into(),
500 ));
501 }
502 (published.manifest_path, published.wal_path)
503 }
504 None => {
505 let manifest_path = path.join(MANIFEST_FILE);
506 let manifest = DurableManifest::load(&manifest_path)?;
507 (manifest_path, manifest.wal_path(path))
508 }
509 };
510 let manifest = file_checksum(&manifest_path)?;
511 let wal = file_checksum(&wal_path)?;
512 if manifest.0 != plan.manifest_len
513 || manifest.1 != plan.manifest_crc32c
514 || manifest.2.to_string() != plan.manifest_sha256
515 || wal.0 != plan.wal_len
516 || wal.1 != plan.wal_crc32c
517 || wal.2.to_string() != plan.wal_sha256
518 {
519 return Err(HawDBError::Storage(
520 "derived artifact repair source identity changed after planning".to_string(),
521 ));
522 }
523 Ok(())
524}
525
526struct PublishedRepairBranch {
527 head: crate::branch_head::BranchHead,
528 root: crate::sealed_root::SealedRoot,
529 objects: crate::immutable_object::ImmutableObjectStore,
530 manifest_path: PathBuf,
531 wal_path: PathBuf,
532}
533
534fn published_branch(
537 path: &Path,
538 source: &DerivedArtifactBranchSource,
539) -> Result<PublishedRepairBranch> {
540 let id = source.branch_id.to_string();
541 let branches = path
542 .parent()
543 .filter(|parent| {
544 parent.file_name().is_some_and(|name| name == "branches")
545 && path.file_name().is_some_and(|name| name == id.as_str())
546 })
547 .ok_or_else(|| {
548 HawDBError::StorageIntegrity("repair path does not identify its branch UUID".into())
549 })?;
550 let catalog = crate::branch_catalog::read_catalog(&branches.join("catalog.hawdb"))?;
551 let record = catalog
552 .branches
553 .iter()
554 .find(|record| record.id.as_uuid() == source.branch_id)
555 .ok_or_else(|| {
556 HawDBError::StorageIntegrity("repair branch is absent from the catalog".into())
557 })?;
558 if catalog.project_id.as_uuid() != source.project_id
559 || record.metadata_revision != source.metadata_revision
560 || record.state != crate::branch_catalog::BranchState::Ready
561 {
562 return Err(HawDBError::StorageIntegrity(
563 "repair branch catalog identity changed".into(),
564 ));
565 }
566 let head = crate::branch_head::read_branch_head(&path.join("branch.head"))
567 .map_err(HawDBError::from_storage_error)?;
568 if head.project_id != *source.project_id.as_bytes()
569 || head.branch_id != *source.branch_id.as_bytes()
570 {
571 return Err(HawDBError::StorageIntegrity(
572 "repair branch head identity changed".into(),
573 ));
574 }
575 let objects = crate::immutable_object::ImmutableObjectStore::open(branches.join("objects"))
576 .map_err(HawDBError::from_storage_error)?;
577 let root = crate::sealed_root::SealedRoot::decode(
578 &objects
579 .read(head.sealed_root)
580 .map_err(HawDBError::from_storage_error)?,
581 )
582 .map_err(HawDBError::from_storage_error)?;
583 if root.commit_epoch != head.logical_commit_epoch
584 || root.replay_end_lsn() != head.active_wal.replay_start_lsn
585 {
586 return Err(HawDBError::StorageIntegrity(
587 "repair branch root does not match its head".into(),
588 ));
589 }
590 objects
591 .read(root.durable_manifest)
592 .map_err(HawDBError::from_storage_error)?;
593 let manifest_path = objects.object_path(root.durable_manifest);
594 let wal_path = path.join(crate::artifact_files::wal_generation_file(
595 head.active_wal.generation,
596 ));
597 Ok(PublishedRepairBranch {
598 head,
599 root,
600 objects,
601 manifest_path,
602 wal_path,
603 })
604}