1use hawdb_core::{HawDBError, Result, Value};
22use hawdb_search::{SearchProjectionDelta, SearchProjectionFreshness, SearchProjectionKind};
23use hawdb_storage::{
24 decode_relational_checkpoint, encode_relational_checkpoint, RelationalDecodeLimits,
25 RelationalState, StoreStableIdMapping,
26};
27use std::collections::{BTreeMap, BTreeSet};
28
29#[doc(hidden)]
30pub mod developer_json;
31#[doc(hidden)]
32pub mod developer_staging;
33#[doc(hidden)]
34pub mod developer_staging_gc;
35#[doc(hidden)]
36pub mod developer_staging_import;
37#[doc(hidden)]
38pub mod developer_staging_publish;
39#[doc(hidden)]
40pub mod developer_staging_verification;
41
42#[doc(hidden)]
43pub use developer_json::{
44 endpoint_violations_json, hawdb_lightning_bootstrap_bundle_json,
45 hawdb_lightning_bootstrap_bundle_json_with_optional_storage_recovery,
46 hawdb_lightning_bootstrap_manifest_json, hawdb_lightning_graph_stream_validation_json,
47 hawdb_lightning_relational_stream_validation_json, stable_identity_audit_json,
48};
49#[doc(hidden)]
50pub use developer_staging::{
51 hawdb_lightning_artifact_summary, stage_hawdb_lightning_bootstrap_export,
52 stage_hawdb_lightning_bootstrap_export_with_optional_storage_recovery,
53 sync_bootstrap_directory, write_bootstrap_atomic_file,
54 HAWDB_LIGHTNING_STAGING_CATALOG_PROTOCOL_VERSION,
55};
56#[doc(hidden)]
57pub use developer_staging_gc::hawdb_lightning_gc_staging_report;
58#[doc(hidden)]
59pub use developer_staging_import::{
60 hawdb_lightning_import_state_marker, hawdb_lightning_import_status,
61};
62#[doc(hidden)]
63pub use developer_staging_publish::{
64 publish_hawdb_lightning_staging_catalog, publish_hawdb_lightning_staging_catalog_with_options,
65 HawDBLightningPublishOptions,
66};
67#[doc(hidden)]
68pub use developer_staging_verification::{
69 read_hawdb_lightning_staging_artifact_json, verify_hawdb_lightning_published_manifest,
70 verify_hawdb_lightning_staging_catalog,
71};
72
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct CanonicalGraphSnapshotExport {
75 pub graph_commit_epoch: u64,
76 pub logical_checksum: u64,
77 pub stable_identity: CanonicalSnapshotIdentityAudit,
78 pub nodes: Vec<CanonicalSnapshotNode>,
79 pub relationships: Vec<CanonicalSnapshotRelationship>,
80}
81
82impl CanonicalGraphSnapshotExport {
83 pub fn from_rows(
89 graph_commit_epoch: u64,
90 nodes: Vec<CanonicalSnapshotNode>,
91 relationships: Vec<CanonicalSnapshotRelationship>,
92 ) -> Self {
93 let stable_identity = canonical_snapshot_identity_audit(&nodes, &relationships);
94 let logical_checksum = canonical_graph_snapshot_checksum(&nodes, &relationships);
95 Self {
96 graph_commit_epoch,
97 logical_checksum,
98 stable_identity,
99 nodes,
100 relationships,
101 }
102 }
103
104 pub fn with_stable_id_mapping(&self, mapping: &CanonicalStableIdMapping) -> Self {
105 let mut export = self.clone();
106 for node in &mut export.nodes {
107 if let Some(stable_id) = mapping.node_stable_ids.get(&node.node_id) {
108 node.stable_id = Some(stable_id.clone());
109 }
110 }
111 for relationship in &mut export.relationships {
112 if let Some(stable_id) = mapping
113 .relationship_stable_ids
114 .get(&relationship.relationship_id)
115 {
116 relationship.stable_id = Some(stable_id.clone());
117 }
118 }
119 export.stable_identity =
120 canonical_snapshot_identity_audit(&export.nodes, &export.relationships);
121 export.logical_checksum =
122 canonical_graph_snapshot_checksum(&export.nodes, &export.relationships);
123 export
124 }
125
126 pub fn hawdb_lightning_bootstrap_manifest(
127 &self,
128 relational_stream: &HawDBLightningRelationalStream,
129 ) -> HawDBLightningBootstrapManifest {
130 let validation = self.validate();
131 let graph_stream_body = encode_hawdb_lightning_graph_stream_body(self);
132 let graph_stream_checksum = checksum_bytes(graph_stream_body.as_bytes());
133 let graph_stream_byte_len =
134 graph_stream_body.len() + format!("checksum\t{graph_stream_checksum}\n").len();
135 let relational_validation = relational_stream.validate();
136 let mut manifest = HawDBLightningBootstrapManifest {
137 protocol_version: HAWDB_LIGHTNING_BOOTSTRAP_PROTOCOL_VERSION,
138 database_commit_epoch: self.graph_commit_epoch,
139 graph_commit_epoch: self.graph_commit_epoch,
140 logical_checksum: self.logical_checksum,
141 graph_stream_checksum,
142 graph_stream_byte_len,
143 relational_stream_format_version: relational_stream.format_version,
144 relational_stream_checksum: relational_stream.stream_checksum,
145 relational_stream_byte_len: relational_stream.byte_len,
146 relational_table_count: relational_stream.table_count,
147 relational_row_count: relational_stream.row_count,
148 relational_overflow_segment_count: relational_stream.overflow_segment_count,
149 schema_checksum: canonical_graph_snapshot_schema_checksum(
150 &self.nodes,
151 &self.relationships,
152 ),
153 node_count: self.nodes.len(),
154 relationship_count: self.relationships.len(),
155 label_count: self
156 .nodes
157 .iter()
158 .flat_map(|node| node.labels.iter().cloned())
159 .collect::<BTreeSet<_>>()
160 .len(),
161 relationship_type_count: self
162 .relationships
163 .iter()
164 .map(|relationship| relationship.rel_type.clone())
165 .collect::<BTreeSet<_>>()
166 .len(),
167 node_property_count: self.nodes.iter().map(|node| node.properties.len()).sum(),
168 relationship_property_count: self
169 .relationships
170 .iter()
171 .map(|relationship| relationship.properties.len())
172 .sum(),
173 validation,
174 relational_validation,
175 };
176 manifest.relational_validation = relational_stream.validate_against_manifest(&manifest);
177 manifest
178 }
179
180 pub fn hawdb_lightning_graph_stream(&self) -> HawDBLightningGraphStream {
181 let body = encode_hawdb_lightning_graph_stream_body(self);
182 let stream_checksum = checksum_bytes(body.as_bytes());
183 let encoded = format!("{body}checksum\t{stream_checksum}\n");
184 HawDBLightningGraphStream {
185 format_version: HAWDB_LIGHTNING_GRAPH_STREAM_FORMAT_VERSION,
186 graph_commit_epoch: self.graph_commit_epoch,
187 logical_checksum: self.logical_checksum,
188 stream_checksum,
189 byte_len: encoded.len(),
190 node_count: self.nodes.len(),
191 relationship_count: self.relationships.len(),
192 encoded,
193 }
194 }
195
196 pub fn validate(&self) -> CanonicalGraphSnapshotValidation {
197 let expected_logical_checksum =
198 canonical_graph_snapshot_checksum(&self.nodes, &self.relationships);
199 let expected_stable_identity =
200 canonical_snapshot_identity_audit(&self.nodes, &self.relationships);
201 let duplicate_node_ids = duplicate_u64s(self.nodes.iter().map(|node| node.node_id));
202 let duplicate_relationship_ids = duplicate_u64s(
203 self.relationships
204 .iter()
205 .map(|relationship| relationship.relationship_id),
206 );
207 let node_ids = self
208 .nodes
209 .iter()
210 .map(|node| node.node_id)
211 .collect::<BTreeSet<_>>();
212 let missing_sources = self
213 .relationships
214 .iter()
215 .filter(|relationship| !node_ids.contains(&relationship.source_node_id))
216 .map(|relationship| CanonicalSnapshotEndpointViolation {
217 relationship_id: relationship.relationship_id,
218 missing_node_id: relationship.source_node_id,
219 })
220 .collect::<Vec<_>>();
221 let missing_targets = self
222 .relationships
223 .iter()
224 .filter(|relationship| !node_ids.contains(&relationship.target_node_id))
225 .map(|relationship| CanonicalSnapshotEndpointViolation {
226 relationship_id: relationship.relationship_id,
227 missing_node_id: relationship.target_node_id,
228 })
229 .collect::<Vec<_>>();
230 let checksum_matches = self.logical_checksum == expected_logical_checksum;
231 let stable_identity_matches = self.stable_identity == expected_stable_identity;
232 let stable_identity_ready = !expected_stable_identity.requires_stable_id_mapping;
233 let is_valid = checksum_matches
234 && stable_identity_matches
235 && duplicate_node_ids.is_empty()
236 && duplicate_relationship_ids.is_empty()
237 && missing_sources.is_empty()
238 && missing_targets.is_empty();
239 let is_import_ready = is_valid && stable_identity_ready;
240 CanonicalGraphSnapshotValidation {
241 is_valid,
242 is_import_ready,
243 checksum_matches,
244 expected_logical_checksum,
245 stable_identity_matches,
246 stable_identity_ready,
247 expected_stable_identity,
248 duplicate_node_ids,
249 duplicate_relationship_ids,
250 missing_sources,
251 missing_targets,
252 }
253 }
254}
255
256impl HawDBLightningGraphStream {
257 pub fn validate_against_manifest(
258 &self,
259 manifest: &HawDBLightningBootstrapManifest,
260 ) -> HawDBLightningGraphStreamValidation {
261 validate_hawdb_lightning_graph_stream(&self.encoded, Some(manifest))
262 }
263}
264
265impl HawDBLightningRelationalStream {
266 pub fn from_state(database_commit_epoch: u64, state: &RelationalState) -> Result<Self> {
267 state
268 .require_materialized_rows("HawDB Lightning relational export")
269 .map_err(|error| HawDBError::Storage(error.to_string()))?;
270 let encoded = encode_relational_checkpoint(database_commit_epoch, state)
271 .map_err(|error| HawDBError::Storage(error.to_string()))?;
272 let table_count = state.table_schemas().count();
273 let row_count = state
274 .table_schemas()
275 .map(|schema| state.row_count(&schema.name))
276 .sum();
277 Ok(Self {
278 format_version: HAWDB_LIGHTNING_RELATIONAL_STREAM_FORMAT_VERSION,
279 database_commit_epoch,
280 stream_checksum: checksum_bytes(&encoded),
281 byte_len: encoded.len(),
282 table_count,
283 row_count,
284 overflow_segment_count: state.overflow_segment_count(),
285 encoded,
286 })
287 }
288
289 pub fn validate(&self) -> HawDBLightningRelationalStreamValidation {
290 validate_hawdb_lightning_relational_stream(&self.encoded, None)
291 }
292
293 pub fn validate_against_manifest(
294 &self,
295 manifest: &HawDBLightningBootstrapManifest,
296 ) -> HawDBLightningRelationalStreamValidation {
297 validate_hawdb_lightning_relational_stream(&self.encoded, Some(manifest))
298 }
299}
300
301pub const HAWDB_LIGHTNING_BOOTSTRAP_PROTOCOL_VERSION: u64 = 1;
302pub const HAWDB_LIGHTNING_GRAPH_STREAM_FORMAT_VERSION: u64 = 1;
303pub const HAWDB_LIGHTNING_RELATIONAL_STREAM_FORMAT_VERSION: u64 = 1;
304pub const HAWDB_LIGHTNING_INITIAL_IMPORT_DURABLE_STATE_PROTOCOL: &str =
305 "hawdb-lightning-initial-import-durable-state-v1";
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct HawDBLightningBootstrapExport {
309 pub snapshot: CanonicalGraphSnapshotExport,
310 pub manifest: HawDBLightningBootstrapManifest,
311 pub graph_stream: HawDBLightningGraphStream,
312 pub relational_stream: HawDBLightningRelationalStream,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct HawDBLightningBootstrapManifest {
317 pub protocol_version: u64,
318 pub database_commit_epoch: u64,
319 pub graph_commit_epoch: u64,
320 pub logical_checksum: u64,
321 pub graph_stream_checksum: u64,
322 pub graph_stream_byte_len: usize,
323 pub relational_stream_format_version: u64,
324 pub relational_stream_checksum: u64,
325 pub relational_stream_byte_len: usize,
326 pub relational_table_count: usize,
327 pub relational_row_count: usize,
328 pub relational_overflow_segment_count: usize,
329 pub schema_checksum: u64,
330 pub node_count: usize,
331 pub relationship_count: usize,
332 pub label_count: usize,
333 pub relationship_type_count: usize,
334 pub node_property_count: usize,
335 pub relationship_property_count: usize,
336 pub validation: CanonicalGraphSnapshotValidation,
337 pub relational_validation: HawDBLightningRelationalStreamValidation,
338}
339
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct HawDBLightningGraphStream {
342 pub format_version: u64,
343 pub graph_commit_epoch: u64,
344 pub logical_checksum: u64,
345 pub stream_checksum: u64,
346 pub byte_len: usize,
347 pub node_count: usize,
348 pub relationship_count: usize,
349 pub encoded: String,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct HawDBLightningRelationalStream {
354 pub format_version: u64,
355 pub database_commit_epoch: u64,
356 pub stream_checksum: u64,
357 pub byte_len: usize,
358 pub table_count: usize,
359 pub row_count: usize,
360 pub overflow_segment_count: usize,
361 pub encoded: Vec<u8>,
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub struct HawDBLightningRelationalStreamValidation {
366 pub is_valid: bool,
367 pub checksum_matches: bool,
368 pub format_version_matches: bool,
369 pub epoch_matches: bool,
370 pub count_matches: bool,
371 pub manifest_matches: bool,
372 pub expected_stream_checksum: Option<u64>,
373 pub actual_stream_checksum: u64,
374 pub database_commit_epoch: Option<u64>,
375 pub table_count: usize,
376 pub row_count: usize,
377 pub overflow_segment_count: usize,
378 pub errors: Vec<String>,
379}
380
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct HawDBLightningGraphStreamValidation {
383 pub is_valid: bool,
384 pub checksum_matches: bool,
385 pub format_version_matches: bool,
386 pub count_matches: bool,
387 pub endpoint_integrity: bool,
388 pub manifest_matches: bool,
389 pub expected_stream_checksum: Option<u64>,
390 pub actual_stream_checksum: u64,
391 pub format_version: Option<u64>,
392 pub graph_commit_epoch: Option<u64>,
393 pub logical_checksum: Option<u64>,
394 pub node_count: usize,
395 pub relationship_count: usize,
396 pub duplicate_node_ids: Vec<u64>,
397 pub duplicate_relationship_ids: Vec<u64>,
398 pub missing_sources: Vec<CanonicalSnapshotEndpointViolation>,
399 pub missing_targets: Vec<CanonicalSnapshotEndpointViolation>,
400 pub errors: Vec<String>,
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
404pub struct HawDBLightningInitialImportReadiness {
405 pub ready: bool,
406 pub manifest_import_ready: bool,
407 pub projection_present: bool,
408 pub graph_import_caught_up: bool,
409 pub projection_watermark_caught_up: bool,
410 pub projection_checkpointed: bool,
411 pub manifest_graph_commit_epoch: u64,
412 pub target_graph_commit_epoch: u64,
413 pub projection_source_graph_commit_epoch: Option<u64>,
414 pub projection_durable_source_graph_commit_epoch: Option<u64>,
415 pub blocker_codes: Vec<String>,
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct HawDBLightningInitialImportCheckpoint {
420 pub protocol_version: u64,
421 pub import_id: String,
422 pub task_id: String,
423 pub fencing_token: String,
424 pub object_digest: String,
425 pub schema_checksum: u64,
426 pub graph_stream_checksum: u64,
427 pub graph_stream_byte_len: usize,
428 pub relational_stream_checksum: u64,
429 pub relational_stream_byte_len: usize,
430 pub manifest_database_commit_epoch: u64,
431 pub manifest_graph_commit_epoch: u64,
432 pub applied_graph_commit_epoch: u64,
433 pub applied_search_projection_commit_epoch: Option<u64>,
434 pub durable_search_projection_commit_epoch: Option<u64>,
435 pub completed_batches: u64,
436 pub total_batches: u64,
437 pub document_identity_count: usize,
438}
439
440#[derive(Debug, Clone, PartialEq, Eq)]
441pub struct HawDBLightningInitialImportIdempotencyKey {
442 pub import_id: String,
443 pub task_id: String,
444 pub fencing_token: String,
445 pub object_digest: String,
446}
447
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub struct HawDBLightningInitialImportCheckpointReadiness {
450 pub ready: bool,
451 pub idempotency_key_present: bool,
452 pub idempotency_key: Option<HawDBLightningInitialImportIdempotencyKey>,
453 pub checkpoint_matches_manifest: bool,
454 pub graph_checkpoint_caught_up: bool,
455 pub search_projection_applied_caught_up: bool,
456 pub search_projection_durable_caught_up: bool,
457 pub batches_complete: bool,
458 pub document_identities_present: bool,
459 pub manifest_graph_commit_epoch: u64,
460 pub applied_graph_commit_epoch: u64,
461 pub applied_search_projection_commit_epoch: Option<u64>,
462 pub durable_search_projection_commit_epoch: Option<u64>,
463 pub completed_batches: u64,
464 pub total_batches: u64,
465 pub document_identity_count: usize,
466 pub blocker_codes: Vec<String>,
467}
468
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub struct HawDBLightningInitialImportCheckpointProgress {
471 pub applied_graph_commit_epoch: u64,
472 pub applied_search_projection_commit_epoch: Option<u64>,
473 pub durable_search_projection_commit_epoch: Option<u64>,
474 pub completed_batches: u64,
475 pub total_batches: u64,
476 pub document_identity_count: usize,
477}
478
479#[derive(Debug, Clone, PartialEq, Eq)]
480pub struct HawDBLightningInitialImportCheckpointProgressReport {
481 pub accepted: bool,
482 pub checkpoint: HawDBLightningInitialImportCheckpoint,
483 pub readiness: HawDBLightningInitialImportCheckpointReadiness,
484 pub resume_action: HawDBLightningInitialImportResumeAction,
485 pub blocker_codes: Vec<String>,
486}
487
488#[derive(Debug, Clone, PartialEq, Eq)]
489pub struct HawDBLightningInitialImportDocumentIdentity {
490 pub kind: SearchProjectionKind,
491 pub document_id: String,
492}
493
494#[derive(Debug, Clone, PartialEq, Eq)]
495pub struct HawDBLightningInitialImportDocumentIdentityKindReport {
496 pub kind: SearchProjectionKind,
497 pub document_count: usize,
498}
499
500#[derive(Debug, Clone, PartialEq, Eq)]
501pub struct HawDBLightningInitialImportDocumentIdentityCoverage {
502 pub ready: bool,
503 pub document_identity_count: usize,
504 pub unique_document_identity_count: usize,
505 pub expected_kinds: Vec<SearchProjectionKind>,
506 pub observed_kinds: Vec<SearchProjectionKind>,
507 pub kind_reports: Vec<HawDBLightningInitialImportDocumentIdentityKindReport>,
508 pub missing_kinds: Vec<SearchProjectionKind>,
509 pub duplicate_document_ids: Vec<String>,
510 pub empty_document_id_count: usize,
511 pub blocker_codes: Vec<String>,
512}
513
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515pub enum HawDBLightningInitialImportResumeActionKind {
516 Start,
517 Resume,
518 ReadyForCutover,
519 Quarantine,
520}
521
522#[derive(Debug, Clone, PartialEq, Eq)]
523pub struct HawDBLightningInitialImportResumeAction {
524 pub kind: HawDBLightningInitialImportResumeActionKind,
525 pub next_batch: Option<u64>,
526 pub idempotency_key: Option<HawDBLightningInitialImportIdempotencyKey>,
527 pub completed_batches: u64,
528 pub total_batches: u64,
529 pub blocker_codes: Vec<String>,
530}
531
532#[derive(Debug, Clone, PartialEq, Eq)]
533pub struct HawDBLightningInitialImportPlan {
534 pub ready_for_database_import: bool,
535 pub ready_for_graph_import: bool,
536 pub ready_for_cutover: bool,
537 pub graph_stream_validation: HawDBLightningGraphStreamValidation,
538 pub relational_stream_validation: HawDBLightningRelationalStreamValidation,
539 pub decoded_snapshot_import_ready: bool,
540 pub decoded_graph_commit_epoch: Option<u64>,
541 pub decoded_node_count: Option<usize>,
542 pub decoded_relationship_count: Option<usize>,
543 pub decoded_relational_table_count: Option<usize>,
544 pub decoded_relational_row_count: Option<usize>,
545 pub target_readiness: HawDBLightningInitialImportReadiness,
546 pub checkpoint_readiness: Option<HawDBLightningInitialImportCheckpointReadiness>,
547 pub document_identity_coverage: Option<HawDBLightningInitialImportDocumentIdentityCoverage>,
548 pub resume_action: HawDBLightningInitialImportResumeAction,
549 pub blocker_codes: Vec<String>,
550}
551
552#[derive(Debug, Clone, PartialEq, Eq)]
553pub struct HawDBLightningInitialImportApplyReport {
554 pub applied: bool,
555 pub ready_for_cutover: bool,
556 pub database_commit_epoch: u64,
557 pub node_count: usize,
558 pub relationship_count: usize,
559 pub relational_table_count: usize,
560 pub relational_row_count: usize,
561 pub plan: HawDBLightningInitialImportPlan,
562 pub blocker_codes: Vec<String>,
563}
564
565#[derive(Debug, Clone, PartialEq, Eq)]
566pub struct HawDBLightningInitialImportSearchProjectionBatchReport {
567 pub ready: bool,
568 pub checkpoint_present: bool,
569 pub checkpoint_matches_manifest: bool,
570 pub checkpoint_idempotency_key_present: bool,
571 pub total_batches_match_checkpoint: bool,
572 pub source_graph_commit_epoch_matches: bool,
573 pub batch_position_valid: bool,
574 pub operation_limit_ok: bool,
575 pub empty_batch: bool,
576 pub delete_count: usize,
577 pub document_identity_coverage: HawDBLightningInitialImportDocumentIdentityCoverage,
578 pub source_graph_commit_epoch: Option<u64>,
579 pub batch_index: u64,
580 pub total_batches: u64,
581 pub operation_count: usize,
582 pub checkpoint_progress: Option<HawDBLightningInitialImportCheckpointProgress>,
583 pub checkpoint_progress_accepted: bool,
584 pub checkpoint_progress_readiness: Option<HawDBLightningInitialImportCheckpointReadiness>,
585 pub checkpoint_resume_action: Option<HawDBLightningInitialImportResumeAction>,
586 pub checkpoint_progress_blocker_codes: Vec<String>,
587 pub blocker_codes: Vec<String>,
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub struct HawDBLightningInitialImportSourceBundleReadiness {
592 pub ready: bool,
593 pub database_source_import_ready: bool,
594 pub checkpoint_present: bool,
595 pub projection_batch_count: usize,
596 pub ready_projection_batch_count: usize,
597 pub total_batches: u64,
598 pub source_fingerprint: HawDBLightningInitialImportSourceFingerprint,
599 pub document_identity_coverage: HawDBLightningInitialImportDocumentIdentityCoverage,
600 pub batch_reports: Vec<HawDBLightningInitialImportSearchProjectionBatchReport>,
601 pub blocker_codes: Vec<String>,
602}
603
604#[derive(Debug, Clone, PartialEq, Eq)]
605pub struct HawDBLightningInitialImportSourceFingerprint {
606 pub protocol_version: u64,
607 pub database_commit_epoch: u64,
608 pub graph_commit_epoch: u64,
609 pub logical_checksum: u64,
610 pub graph_stream_checksum: u64,
611 pub graph_stream_byte_len: usize,
612 pub relational_stream_checksum: u64,
613 pub relational_stream_byte_len: usize,
614 pub schema_checksum: u64,
615 pub node_count: usize,
616 pub relationship_count: usize,
617 pub relational_table_count: usize,
618 pub relational_row_count: usize,
619}
620
621#[derive(Debug, Clone, PartialEq, Eq)]
622pub struct HawDBLightningInitialImportDurableState {
623 pub source_fingerprint: HawDBLightningInitialImportSourceFingerprint,
624 pub checkpoint: HawDBLightningInitialImportCheckpoint,
625 pub document_identities: Vec<HawDBLightningInitialImportDocumentIdentity>,
626 pub document_identity_coverage: HawDBLightningInitialImportDocumentIdentityCoverage,
627}
628
629#[derive(Debug, Clone, PartialEq, Eq)]
630pub struct HawDBLightningInitialImportDurableStateReport {
631 pub persistable: bool,
632 pub ready_for_cutover: bool,
633 pub state: Option<HawDBLightningInitialImportDurableState>,
634 pub checkpoint_readiness: HawDBLightningInitialImportCheckpointReadiness,
635 pub resume_action: HawDBLightningInitialImportResumeAction,
636 pub blocker_codes: Vec<String>,
637}
638
639#[derive(Debug, Clone, PartialEq, Eq)]
640pub struct HawDBLightningInitialImportDurableBatchAdvanceReport {
641 pub ready: bool,
642 pub idempotent_replay: bool,
643 pub batch_report: HawDBLightningInitialImportSearchProjectionBatchReport,
644 pub durable_state_report: HawDBLightningInitialImportDurableStateReport,
645 pub blocker_codes: Vec<String>,
646}
647
648#[derive(Debug, Clone, PartialEq, Eq)]
656pub struct HawDBLightningInitialImportStreamingBatchAdvanceReport {
657 pub accepted: bool,
658 pub idempotent_replay: bool,
659 pub completed: bool,
660 pub ready_for_cutover: bool,
661 pub durable_state_report: HawDBLightningInitialImportDurableStateReport,
662 pub blocker_codes: Vec<String>,
663}
664
665#[derive(Debug, Clone, PartialEq, Eq)]
666pub struct HawDBLightningInitialImportSessionReport {
667 pub ready_for_database_import: bool,
668 pub ready_for_cutover: bool,
669 pub durable_state_present: bool,
670 pub durable_state_source_matches_manifest: bool,
671 pub plan: HawDBLightningInitialImportPlan,
672 pub durable_state_report: Option<HawDBLightningInitialImportDurableStateReport>,
673 pub next_action: HawDBLightningInitialImportResumeAction,
674 pub blocker_codes: Vec<String>,
675}
676
677#[derive(Debug, Clone, PartialEq, Eq)]
678pub struct HawDBLightningInitialImportCutoverCatchUpReport {
679 pub ready: bool,
680 pub session_ready_for_cutover: bool,
681 pub durable_state_present: bool,
682 pub live_projection_present: bool,
683 pub import_graph_commit_epoch: Option<u64>,
684 pub import_durable_search_projection_commit_epoch: Option<u64>,
685 pub live_graph_commit_epoch: u64,
686 pub live_search_projection_commit_epoch: Option<u64>,
687 pub live_durable_search_projection_commit_epoch: Option<u64>,
688 pub graph_watermark_caught_up: bool,
689 pub search_projection_watermark_caught_up: bool,
690 pub live_projection_checkpointed: bool,
691 pub live_projection_healthy: bool,
692 pub cutover_watermark: Option<u64>,
693 pub blocker_codes: Vec<String>,
694}
695
696#[derive(Debug, Clone, PartialEq, Eq)]
697pub struct HawDBLightningInitialImportSessionBundleReadiness {
698 pub ready: bool,
699 pub resumable: bool,
700 pub ready_for_cutover: bool,
701 pub source_bundle_ready: bool,
702 pub session_ready_for_database_import: bool,
703 pub session_ready_for_cutover: bool,
704 pub durable_state_present: bool,
705 pub durable_state_source_matches_manifest: bool,
706 pub catch_up_required: bool,
707 pub catch_up_present: bool,
708 pub catch_up_ready: bool,
709 pub cutover_watermark: Option<u64>,
710 pub next_action: HawDBLightningInitialImportResumeAction,
711 pub blocker_codes: Vec<String>,
712}
713
714#[derive(Debug, Clone, Copy)]
721pub struct HawDBLightningInitialImportReadinessInputs<'a> {
722 pub encoded_graph_stream: &'a str,
723 pub encoded_relational_stream: &'a [u8],
724 pub manifest: &'a HawDBLightningBootstrapManifest,
725 pub projection_batches: &'a [SearchProjectionDelta],
726 pub target_projection_freshness: Option<&'a SearchProjectionFreshness>,
727 pub live_projection_freshness: Option<&'a SearchProjectionFreshness>,
728}
729
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct HawDBLightningInitialImportStartupReadinessReport {
732 pub ready: bool,
733 pub source_bundle: HawDBLightningInitialImportSourceBundleReadiness,
734 pub session: HawDBLightningInitialImportSessionReport,
735 pub cutover_catch_up: Option<HawDBLightningInitialImportCutoverCatchUpReport>,
736 pub readiness: HawDBLightningInitialImportSessionBundleReadiness,
737 pub blocker_codes: Vec<String>,
738}
739
740#[derive(Debug, Clone, PartialEq, Eq)]
741pub struct HawDBLightningInitialImportDurableStateCodecReport {
742 pub ready: bool,
743 pub protocol: String,
744 pub source_fingerprint_matches_manifest: bool,
745 pub state: Option<HawDBLightningInitialImportDurableState>,
746 pub blocker_codes: Vec<String>,
747}
748
749#[derive(Debug, Clone, PartialEq, Eq)]
750pub struct HawDBLightningInitialImportRecoveryReadinessReport {
751 pub ready: bool,
752 pub durable_state_payload_present: bool,
753 pub durable_state_codec: Option<HawDBLightningInitialImportDurableStateCodecReport>,
754 pub startup: HawDBLightningInitialImportStartupReadinessReport,
755 pub next_action: HawDBLightningInitialImportResumeAction,
756 pub blocker_codes: Vec<String>,
757}
758
759#[derive(Debug, Clone, PartialEq, Eq)]
760pub struct CanonicalGraphSnapshotValidation {
761 pub is_valid: bool,
762 pub is_import_ready: bool,
763 pub checksum_matches: bool,
764 pub expected_logical_checksum: u64,
765 pub stable_identity_matches: bool,
766 pub stable_identity_ready: bool,
767 pub expected_stable_identity: CanonicalSnapshotIdentityAudit,
768 pub duplicate_node_ids: Vec<u64>,
769 pub duplicate_relationship_ids: Vec<u64>,
770 pub missing_sources: Vec<CanonicalSnapshotEndpointViolation>,
771 pub missing_targets: Vec<CanonicalSnapshotEndpointViolation>,
772}
773
774#[derive(Debug, Clone, PartialEq, Eq, Default)]
775pub struct CanonicalStableIdMapping {
776 pub node_stable_ids: BTreeMap<u64, Value>,
777 pub relationship_stable_ids: BTreeMap<u64, Value>,
778}
779
780#[derive(Debug, Clone, PartialEq, Eq)]
781pub struct CanonicalSnapshotEndpointViolation {
782 pub relationship_id: u64,
783 pub missing_node_id: u64,
784}
785
786#[derive(Debug, Clone, PartialEq, Eq)]
787pub struct CanonicalSnapshotIdentityAudit {
788 pub requires_stable_id_mapping: bool,
789 pub nodes_without_stable_id: Vec<u64>,
790 pub relationships_without_stable_id: Vec<u64>,
791 pub duplicate_node_stable_ids: Vec<Value>,
792 pub duplicate_relationship_stable_ids: Vec<Value>,
793}
794
795impl From<StoreStableIdMapping> for CanonicalStableIdMapping {
796 fn from(mapping: StoreStableIdMapping) -> Self {
797 Self {
798 node_stable_ids: mapping
799 .node_stable_ids
800 .into_iter()
801 .map(|(id, stable_id)| (id.0, stable_id))
802 .collect(),
803 relationship_stable_ids: mapping
804 .relationship_stable_ids
805 .into_iter()
806 .map(|(id, stable_id)| (id.0, stable_id))
807 .collect(),
808 }
809 }
810}
811
812#[derive(Debug, Clone, PartialEq, Eq)]
813pub struct CanonicalSnapshotNode {
814 pub node_id: u64,
815 pub stable_id: Option<Value>,
816 pub labels: Vec<String>,
817 pub properties: BTreeMap<String, Value>,
818}
819
820#[derive(Debug, Clone, PartialEq, Eq)]
821pub struct CanonicalSnapshotRelationship {
822 pub relationship_id: u64,
823 pub stable_id: Option<Value>,
824 pub source_node_id: u64,
825 pub target_node_id: u64,
826 pub rel_type: String,
827 pub properties: BTreeMap<String, Value>,
828}
829
830fn canonical_snapshot_identity_audit(
831 nodes: &[CanonicalSnapshotNode],
832 relationships: &[CanonicalSnapshotRelationship],
833) -> CanonicalSnapshotIdentityAudit {
834 let nodes_without_stable_id = nodes
835 .iter()
836 .filter(|node| node.stable_id.is_none())
837 .map(|node| node.node_id)
838 .collect::<Vec<_>>();
839 let relationships_without_stable_id = relationships
840 .iter()
841 .filter(|relationship| relationship.stable_id.is_none())
842 .map(|relationship| relationship.relationship_id)
843 .collect::<Vec<_>>();
844 let duplicate_node_stable_ids =
845 duplicate_stable_ids(nodes.iter().filter_map(|node| node.stable_id.as_ref()));
846 let duplicate_relationship_stable_ids = duplicate_stable_ids(
847 relationships
848 .iter()
849 .filter_map(|relationship| relationship.stable_id.as_ref()),
850 );
851 let requires_stable_id_mapping = !nodes_without_stable_id.is_empty()
852 || !relationships_without_stable_id.is_empty()
853 || !duplicate_node_stable_ids.is_empty()
854 || !duplicate_relationship_stable_ids.is_empty();
855 CanonicalSnapshotIdentityAudit {
856 requires_stable_id_mapping,
857 nodes_without_stable_id,
858 relationships_without_stable_id,
859 duplicate_node_stable_ids,
860 duplicate_relationship_stable_ids,
861 }
862}
863
864fn duplicate_stable_ids<'a>(values: impl Iterator<Item = &'a Value>) -> Vec<Value> {
865 let mut counts = BTreeMap::<Value, usize>::new();
866 for value in values {
867 *counts.entry(value.clone()).or_default() += 1;
868 }
869 counts
870 .into_iter()
871 .filter_map(|(value, count)| (count > 1).then_some(value))
872 .collect()
873}
874
875fn duplicate_u64s(values: impl Iterator<Item = u64>) -> Vec<u64> {
876 let mut counts = BTreeMap::<u64, usize>::new();
877 for value in values {
878 *counts.entry(value).or_default() += 1;
879 }
880 counts
881 .into_iter()
882 .filter_map(|(value, count)| (count > 1).then_some(value))
883 .collect()
884}
885
886fn canonical_graph_snapshot_checksum(
887 nodes: &[CanonicalSnapshotNode],
888 relationships: &[CanonicalSnapshotRelationship],
889) -> u64 {
890 let mut body = String::new();
891 body.push_str("HAWDB_CANONICAL_GRAPH_SNAPSHOT_V1\n");
892 body.push_str(&format!("node_count\t{}\n", nodes.len()));
893 for node in nodes {
894 body.push_str(&format!("node\t{}\n", node.node_id));
895 append_optional_canonical_value(&mut body, "stable_id", node.stable_id.as_ref());
896 for label in &node.labels {
897 append_canonical_string(&mut body, "label", label);
898 }
899 append_canonical_properties(&mut body, &node.properties);
900 }
901 body.push_str(&format!("relationship_count\t{}\n", relationships.len()));
902 for relationship in relationships {
903 body.push_str(&format!(
904 "rel\t{}\t{}\t{}\n",
905 relationship.relationship_id, relationship.source_node_id, relationship.target_node_id
906 ));
907 append_optional_canonical_value(&mut body, "stable_id", relationship.stable_id.as_ref());
908 append_canonical_string(&mut body, "type", &relationship.rel_type);
909 append_canonical_properties(&mut body, &relationship.properties);
910 }
911 checksum_bytes(body.as_bytes())
912}
913
914fn canonical_graph_snapshot_schema_checksum(
915 nodes: &[CanonicalSnapshotNode],
916 relationships: &[CanonicalSnapshotRelationship],
917) -> u64 {
918 let labels = nodes
919 .iter()
920 .flat_map(|node| node.labels.iter())
921 .cloned()
922 .collect::<BTreeSet<_>>();
923 let relationship_types = relationships
924 .iter()
925 .map(|relationship| relationship.rel_type.clone())
926 .collect::<BTreeSet<_>>();
927 let node_properties = nodes
928 .iter()
929 .flat_map(|node| node.properties.keys())
930 .cloned()
931 .collect::<BTreeSet<_>>();
932 let relationship_properties = relationships
933 .iter()
934 .flat_map(|relationship| relationship.properties.keys())
935 .cloned()
936 .collect::<BTreeSet<_>>();
937 let mut body = String::new();
938 body.push_str("HAWDB_LIGHTNING_BOOTSTRAP_SCHEMA_V1\n");
939 body.push_str(&format!("label_count\t{}\n", labels.len()));
940 for label in labels {
941 append_canonical_string(&mut body, "label", &label);
942 }
943 body.push_str(&format!(
944 "relationship_type_count\t{}\n",
945 relationship_types.len()
946 ));
947 for relationship_type in relationship_types {
948 append_canonical_string(&mut body, "relationship_type", &relationship_type);
949 }
950 body.push_str(&format!(
951 "node_property_key_count\t{}\n",
952 node_properties.len()
953 ));
954 for property in node_properties {
955 append_canonical_string(&mut body, "node_property", &property);
956 }
957 body.push_str(&format!(
958 "relationship_property_key_count\t{}\n",
959 relationship_properties.len()
960 ));
961 for property in relationship_properties {
962 append_canonical_string(&mut body, "relationship_property", &property);
963 }
964 checksum_bytes(body.as_bytes())
965}
966
967fn encode_hawdb_lightning_graph_stream_body(snapshot: &CanonicalGraphSnapshotExport) -> String {
968 let node_stable_keys = snapshot
969 .nodes
970 .iter()
971 .map(|node| (node.node_id, canonical_stable_key(node.stable_id.as_ref())))
972 .collect::<BTreeMap<_, _>>();
973 let mut nodes = snapshot.nodes.iter().collect::<Vec<_>>();
974 nodes.sort_by_key(|node| {
975 (
976 node.labels.clone(),
977 canonical_stable_key(node.stable_id.as_ref()),
978 node.node_id,
979 )
980 });
981 let mut relationships = snapshot.relationships.iter().collect::<Vec<_>>();
982 relationships.sort_by_key(|relationship| {
983 (
984 relationship.rel_type.clone(),
985 node_stable_keys
986 .get(&relationship.source_node_id)
987 .cloned()
988 .unwrap_or_default(),
989 node_stable_keys
990 .get(&relationship.target_node_id)
991 .cloned()
992 .unwrap_or_default(),
993 canonical_stable_key(relationship.stable_id.as_ref()),
994 relationship.relationship_id,
995 )
996 });
997
998 let mut body = String::new();
999 body.push_str("HAWDB_LIGHTNING_GRAPH_STREAM_V1\n");
1000 body.push_str(&format!(
1001 "format_version\t{}\n",
1002 HAWDB_LIGHTNING_GRAPH_STREAM_FORMAT_VERSION
1003 ));
1004 body.push_str(&format!(
1005 "graph_commit_epoch\t{}\n",
1006 snapshot.graph_commit_epoch
1007 ));
1008 body.push_str(&format!(
1009 "logical_checksum\t{}\n",
1010 snapshot.logical_checksum
1011 ));
1012 body.push_str(&format!("node_count\t{}\n", nodes.len()));
1013 for node in nodes {
1014 body.push_str(&format!("node\t{}\n", node.node_id));
1015 append_optional_canonical_value(&mut body, "stable_id", node.stable_id.as_ref());
1016 body.push_str(&format!("label_count\t{}\n", node.labels.len()));
1017 for label in &node.labels {
1018 append_canonical_string(&mut body, "label", label);
1019 }
1020 append_canonical_properties(&mut body, &node.properties);
1021 }
1022 body.push_str(&format!("relationship_count\t{}\n", relationships.len()));
1023 for relationship in relationships {
1024 body.push_str(&format!(
1025 "relationship\t{}\t{}\t{}\n",
1026 relationship.relationship_id, relationship.source_node_id, relationship.target_node_id
1027 ));
1028 append_optional_canonical_value(&mut body, "stable_id", relationship.stable_id.as_ref());
1029 append_canonical_string(&mut body, "relationship_type", &relationship.rel_type);
1030 append_canonical_properties(&mut body, &relationship.properties);
1031 }
1032 body
1033}
1034
1035fn canonical_stable_key(value: Option<&Value>) -> String {
1036 let mut key = String::new();
1037 append_optional_canonical_value(&mut key, "stable_id", value);
1038 key
1039}
1040
1041pub fn validate_hawdb_lightning_graph_stream(
1042 encoded: &str,
1043 manifest: Option<&HawDBLightningBootstrapManifest>,
1044) -> HawDBLightningGraphStreamValidation {
1045 let (body, expected_stream_checksum, mut errors) = split_graph_stream_checksum(encoded);
1046 let actual_stream_checksum = checksum_bytes(body.as_bytes());
1047 let checksum_matches = expected_stream_checksum == Some(actual_stream_checksum);
1048 if !checksum_matches {
1049 errors.push("graph stream checksum mismatch".to_string());
1050 }
1051
1052 let mut parsed = parse_hawdb_lightning_graph_stream_body(body, &mut errors);
1053
1054 let duplicate_node_ids = duplicate_u64s(parsed.node_ids.iter().copied());
1055 let duplicate_relationship_ids = duplicate_u64s(parsed.relationship_ids.iter().copied());
1056 let node_id_set = parsed.node_ids.iter().copied().collect::<BTreeSet<_>>();
1057 let missing_sources = parsed
1058 .relationships
1059 .iter()
1060 .filter(|(_, source, _)| !node_id_set.contains(source))
1061 .map(
1062 |(relationship_id, source, _)| CanonicalSnapshotEndpointViolation {
1063 relationship_id: *relationship_id,
1064 missing_node_id: *source,
1065 },
1066 )
1067 .collect::<Vec<_>>();
1068 let missing_targets = parsed
1069 .relationships
1070 .iter()
1071 .filter(|(_, _, target)| !node_id_set.contains(target))
1072 .map(
1073 |(relationship_id, _, target)| CanonicalSnapshotEndpointViolation {
1074 relationship_id: *relationship_id,
1075 missing_node_id: *target,
1076 },
1077 )
1078 .collect::<Vec<_>>();
1079 let format_version_matches =
1080 parsed.format_version == Some(HAWDB_LIGHTNING_GRAPH_STREAM_FORMAT_VERSION);
1081 let count_matches = parsed.declared_node_count == Some(parsed.node_ids.len() as u64)
1082 && parsed.declared_relationship_count == Some(parsed.relationship_ids.len() as u64);
1083 let endpoint_integrity = duplicate_node_ids.is_empty()
1084 && duplicate_relationship_ids.is_empty()
1085 && missing_sources.is_empty()
1086 && missing_targets.is_empty();
1087 let manifest_matches = manifest.is_none_or(|manifest| {
1088 parsed.graph_commit_epoch == Some(manifest.graph_commit_epoch)
1089 && parsed.logical_checksum == Some(manifest.logical_checksum)
1090 && expected_stream_checksum == Some(manifest.graph_stream_checksum)
1091 && encoded.len() == manifest.graph_stream_byte_len
1092 && parsed.declared_node_count == Some(manifest.node_count as u64)
1093 && parsed.declared_relationship_count == Some(manifest.relationship_count as u64)
1094 });
1095 if !format_version_matches {
1096 errors.push("graph stream format version mismatch".to_string());
1097 }
1098 if !count_matches {
1099 errors.push("graph stream count mismatch".to_string());
1100 }
1101 if !endpoint_integrity {
1102 errors.push("graph stream endpoint integrity failed".to_string());
1103 }
1104 if !manifest_matches {
1105 errors.push("graph stream manifest mismatch".to_string());
1106 }
1107 let is_valid = checksum_matches
1108 && format_version_matches
1109 && count_matches
1110 && endpoint_integrity
1111 && manifest_matches
1112 && errors.is_empty();
1113
1114 HawDBLightningGraphStreamValidation {
1115 is_valid,
1116 checksum_matches,
1117 format_version_matches,
1118 count_matches,
1119 endpoint_integrity,
1120 manifest_matches,
1121 expected_stream_checksum,
1122 actual_stream_checksum,
1123 format_version: parsed.format_version.take(),
1124 graph_commit_epoch: parsed.graph_commit_epoch.take(),
1125 logical_checksum: parsed.logical_checksum.take(),
1126 node_count: parsed.node_ids.len(),
1127 relationship_count: parsed.relationship_ids.len(),
1128 duplicate_node_ids,
1129 duplicate_relationship_ids,
1130 missing_sources,
1131 missing_targets,
1132 errors,
1133 }
1134}
1135
1136pub fn validate_hawdb_lightning_relational_stream(
1137 encoded: &[u8],
1138 manifest: Option<&HawDBLightningBootstrapManifest>,
1139) -> HawDBLightningRelationalStreamValidation {
1140 let actual_stream_checksum = checksum_bytes(encoded);
1141 let expected_stream_checksum = manifest.map(|value| value.relational_stream_checksum);
1142 let checksum_matches =
1143 expected_stream_checksum.is_none_or(|value| value == actual_stream_checksum);
1144 let mut errors = Vec::new();
1145 if !checksum_matches {
1146 errors.push("relational stream checksum mismatch".to_string());
1147 }
1148
1149 let decoded = decode_relational_checkpoint(encoded, RelationalDecodeLimits::checkpoint());
1150 let (database_commit_epoch, table_count, row_count, overflow_segment_count) = match decoded {
1151 Ok(checkpoint) => {
1152 let table_count = checkpoint.state.table_schemas().count();
1153 let row_count = checkpoint
1154 .state
1155 .table_schemas()
1156 .map(|schema| checkpoint.state.row_count(&schema.name))
1157 .sum();
1158 (
1159 Some(checkpoint.epoch),
1160 table_count,
1161 row_count,
1162 checkpoint.state.overflow_segment_count(),
1163 )
1164 }
1165 Err(error) => {
1166 errors.push(format!("relational stream decode failed: {error}"));
1167 (None, 0, 0, 0)
1168 }
1169 };
1170 let format_version_matches = manifest.is_none_or(|value| {
1171 value.relational_stream_format_version == HAWDB_LIGHTNING_RELATIONAL_STREAM_FORMAT_VERSION
1172 });
1173 let epoch_matches = manifest.is_none_or(|value| {
1174 database_commit_epoch == Some(value.database_commit_epoch)
1175 && value.graph_commit_epoch == value.database_commit_epoch
1176 });
1177 let count_matches = manifest.is_none_or(|value| {
1178 table_count == value.relational_table_count
1179 && row_count == value.relational_row_count
1180 && overflow_segment_count == value.relational_overflow_segment_count
1181 });
1182 let manifest_matches = manifest.is_none_or(|value| {
1183 encoded.len() == value.relational_stream_byte_len
1184 && checksum_matches
1185 && format_version_matches
1186 && epoch_matches
1187 && count_matches
1188 });
1189 if !format_version_matches {
1190 errors.push("relational stream format version mismatch".to_string());
1191 }
1192 if !epoch_matches {
1193 errors.push("relational stream database epoch mismatch".to_string());
1194 }
1195 if !count_matches {
1196 errors.push("relational stream count mismatch".to_string());
1197 }
1198 if !manifest_matches {
1199 errors.push("relational stream manifest mismatch".to_string());
1200 }
1201 let is_valid = checksum_matches
1202 && format_version_matches
1203 && epoch_matches
1204 && count_matches
1205 && manifest_matches
1206 && errors.is_empty();
1207 HawDBLightningRelationalStreamValidation {
1208 is_valid,
1209 checksum_matches,
1210 format_version_matches,
1211 epoch_matches,
1212 count_matches,
1213 manifest_matches,
1214 expected_stream_checksum,
1215 actual_stream_checksum,
1216 database_commit_epoch,
1217 table_count,
1218 row_count,
1219 overflow_segment_count,
1220 errors,
1221 }
1222}
1223
1224pub fn parse_hawdb_lightning_graph_stream_export(
1225 encoded: &str,
1226 manifest: Option<&HawDBLightningBootstrapManifest>,
1227) -> Result<CanonicalGraphSnapshotExport> {
1228 let validation = validate_hawdb_lightning_graph_stream(encoded, manifest);
1229 if !validation.is_valid {
1230 return Err(HawDBError::Storage(format!(
1231 "HawDB Lightning graph stream is not import ready: {}",
1232 validation.errors.join("; ")
1233 )));
1234 }
1235 let (body, _, mut errors) = split_graph_stream_checksum(encoded);
1236 let parsed = parse_hawdb_lightning_graph_stream_body(body, &mut errors);
1237 if !errors.is_empty() {
1238 return Err(HawDBError::Storage(format!(
1239 "HawDB Lightning graph stream parse failed: {}",
1240 errors.join("; ")
1241 )));
1242 }
1243 let stable_identity =
1244 canonical_snapshot_identity_audit(&parsed.nodes, &parsed.snapshot_relationships);
1245 let logical_checksum =
1246 canonical_graph_snapshot_checksum(&parsed.nodes, &parsed.snapshot_relationships);
1247 let export = CanonicalGraphSnapshotExport {
1248 graph_commit_epoch: parsed.graph_commit_epoch.unwrap_or(0),
1249 logical_checksum,
1250 stable_identity,
1251 nodes: parsed.nodes,
1252 relationships: parsed.snapshot_relationships,
1253 };
1254 let snapshot_validation = export.validate();
1255 if !snapshot_validation.is_import_ready {
1256 return Err(HawDBError::Storage(
1257 "HawDB Lightning graph stream decoded to a snapshot that is not import ready"
1258 .to_string(),
1259 ));
1260 }
1261 Ok(export)
1262}
1263
1264pub fn hawdb_lightning_initial_import_plan(
1265 encoded_graph_stream: &str,
1266 encoded_relational_stream: &[u8],
1267 manifest: &HawDBLightningBootstrapManifest,
1268 target_graph_commit_epoch: u64,
1269 projection_freshness: Option<&SearchProjectionFreshness>,
1270 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
1271) -> HawDBLightningInitialImportPlan {
1272 hawdb_lightning_initial_import_plan_with_document_identities(
1273 encoded_graph_stream,
1274 encoded_relational_stream,
1275 manifest,
1276 target_graph_commit_epoch,
1277 projection_freshness,
1278 checkpoint,
1279 None,
1280 )
1281}
1282
1283pub fn hawdb_lightning_initial_import_plan_with_document_identities(
1284 encoded_graph_stream: &str,
1285 encoded_relational_stream: &[u8],
1286 manifest: &HawDBLightningBootstrapManifest,
1287 target_graph_commit_epoch: u64,
1288 projection_freshness: Option<&SearchProjectionFreshness>,
1289 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
1290 document_identities: Option<&[HawDBLightningInitialImportDocumentIdentity]>,
1291) -> HawDBLightningInitialImportPlan {
1292 let graph_stream_validation =
1293 validate_hawdb_lightning_graph_stream(encoded_graph_stream, Some(manifest));
1294 let relational_stream_validation =
1295 validate_hawdb_lightning_relational_stream(encoded_relational_stream, Some(manifest));
1296 let decoded_snapshot = if graph_stream_validation.is_valid {
1297 parse_hawdb_lightning_graph_stream_export(encoded_graph_stream, Some(manifest)).ok()
1298 } else {
1299 None
1300 };
1301 let decoded_snapshot_import_ready = decoded_snapshot
1302 .as_ref()
1303 .is_some_and(|snapshot| snapshot.validate().is_import_ready);
1304 let decoded_graph_commit_epoch = decoded_snapshot
1305 .as_ref()
1306 .map(|snapshot| snapshot.graph_commit_epoch);
1307 let decoded_node_count = decoded_snapshot
1308 .as_ref()
1309 .map(|snapshot| snapshot.nodes.len());
1310 let decoded_relationship_count = decoded_snapshot
1311 .as_ref()
1312 .map(|snapshot| snapshot.relationships.len());
1313 let decoded_relational_table_count = relational_stream_validation
1314 .is_valid
1315 .then_some(relational_stream_validation.table_count);
1316 let decoded_relational_row_count = relational_stream_validation
1317 .is_valid
1318 .then_some(relational_stream_validation.row_count);
1319 let target_readiness = hawdb_lightning_initial_import_readiness(
1320 manifest,
1321 target_graph_commit_epoch,
1322 projection_freshness,
1323 );
1324 let checkpoint_readiness = checkpoint.map(|checkpoint| {
1325 hawdb_lightning_initial_import_checkpoint_readiness(manifest, checkpoint)
1326 });
1327 let document_identity_coverage =
1328 document_identities.map(hawdb_lightning_initial_import_document_identity_coverage);
1329 let resume_action = hawdb_lightning_initial_import_resume_action(manifest, checkpoint);
1330 let ready_for_graph_import = graph_stream_validation.is_valid && decoded_snapshot_import_ready;
1331 let ready_for_database_import = ready_for_graph_import && relational_stream_validation.is_valid;
1332 let document_identities_ready = document_identity_coverage
1333 .as_ref()
1334 .map(|coverage| coverage.ready)
1335 .unwrap_or(true);
1336 let ready_for_cutover = ready_for_database_import
1337 && target_readiness.ready
1338 && checkpoint_readiness
1339 .as_ref()
1340 .map(|readiness| readiness.ready)
1341 .unwrap_or(false)
1342 && document_identities_ready
1343 && resume_action.kind == HawDBLightningInitialImportResumeActionKind::ReadyForCutover;
1344 let mut blocker_codes = BTreeSet::new();
1345 if !graph_stream_validation.is_valid {
1346 blocker_codes.insert("hawdb_lightning_graph_stream_invalid".to_string());
1347 }
1348 if graph_stream_validation.is_valid && !decoded_snapshot_import_ready {
1349 blocker_codes.insert("hawdb_lightning_graph_stream_decode_not_import_ready".to_string());
1350 }
1351 if !relational_stream_validation.is_valid {
1352 blocker_codes.insert("hawdb_lightning_relational_stream_invalid".to_string());
1353 }
1354 if !target_readiness.ready {
1355 blocker_codes.extend(target_readiness.blocker_codes.iter().cloned());
1356 }
1357 match &checkpoint_readiness {
1358 Some(readiness) => {
1359 if !readiness.ready {
1360 blocker_codes.extend(readiness.blocker_codes.iter().cloned());
1361 }
1362 }
1363 None => {
1364 blocker_codes.insert("initial_import_checkpoint_missing".to_string());
1365 }
1366 }
1367 if let Some(coverage) = &document_identity_coverage
1368 && !coverage.ready
1369 {
1370 blocker_codes.extend(coverage.blocker_codes.iter().cloned());
1371 }
1372 if ready_for_database_import && !ready_for_cutover {
1373 match resume_action.kind {
1374 HawDBLightningInitialImportResumeActionKind::Start => {
1375 blocker_codes.insert("initial_import_not_started".to_string());
1376 }
1377 HawDBLightningInitialImportResumeActionKind::Resume => {
1378 blocker_codes.insert("initial_import_checkpoint_incomplete".to_string());
1379 }
1380 HawDBLightningInitialImportResumeActionKind::Quarantine => {
1381 blocker_codes.insert("initial_import_checkpoint_quarantined".to_string());
1382 }
1383 HawDBLightningInitialImportResumeActionKind::ReadyForCutover => {}
1384 }
1385 }
1386 HawDBLightningInitialImportPlan {
1387 ready_for_database_import,
1388 ready_for_graph_import,
1389 ready_for_cutover,
1390 graph_stream_validation,
1391 relational_stream_validation,
1392 decoded_snapshot_import_ready,
1393 decoded_graph_commit_epoch,
1394 decoded_node_count,
1395 decoded_relationship_count,
1396 decoded_relational_table_count,
1397 decoded_relational_row_count,
1398 target_readiness,
1399 checkpoint_readiness,
1400 document_identity_coverage,
1401 resume_action,
1402 blocker_codes: blocker_codes.into_iter().collect(),
1403 }
1404}
1405
1406pub fn hawdb_lightning_initial_import_readiness(
1407 manifest: &HawDBLightningBootstrapManifest,
1408 target_graph_commit_epoch: u64,
1409 projection_freshness: Option<&SearchProjectionFreshness>,
1410) -> HawDBLightningInitialImportReadiness {
1411 let manifest_epoch_matches = manifest.database_commit_epoch == manifest.graph_commit_epoch;
1412 let manifest_import_ready = manifest.validation.is_import_ready
1413 && manifest.relational_validation.is_valid
1414 && manifest_epoch_matches;
1415 let graph_import_caught_up = target_graph_commit_epoch >= manifest.graph_commit_epoch;
1416 let projection_present = projection_freshness.is_some();
1417 let projection_source_graph_commit_epoch =
1418 projection_freshness.and_then(|freshness| freshness.source_graph_commit_epoch);
1419 let projection_durable_source_graph_commit_epoch =
1420 projection_freshness.and_then(|freshness| freshness.durable_source_graph_commit_epoch);
1421 let imported_projection_matches_manifest = projection_freshness.is_some_and(|freshness| {
1422 freshness.import_source_graph_commit_epoch == Some(manifest.graph_commit_epoch)
1423 });
1424 let projection_watermark_caught_up = if imported_projection_matches_manifest {
1425 projection_durable_source_graph_commit_epoch.is_some()
1429 } else {
1430 projection_durable_source_graph_commit_epoch
1431 .is_some_and(|epoch| epoch >= target_graph_commit_epoch)
1432 };
1433 let projection_checkpointed = projection_freshness
1434 .map(|freshness| !freshness.has_uncheckpointed_changes)
1435 .unwrap_or(false);
1436 let projection_healthy = projection_freshness
1437 .map(|freshness| !freshness.full_reindex_needed && !freshness.metadata_repair_needed)
1438 .unwrap_or(false);
1439 let mut blocker_codes = BTreeSet::new();
1440 if !manifest_import_ready {
1441 blocker_codes.insert("hawdb_lightning_manifest_not_import_ready".to_string());
1442 }
1443 if !manifest_epoch_matches {
1444 blocker_codes.insert("hawdb_lightning_manifest_epoch_mismatch".to_string());
1445 }
1446 if !graph_import_caught_up {
1447 blocker_codes.insert("graph_import_watermark_behind_manifest".to_string());
1448 }
1449 if !projection_present {
1450 blocker_codes.insert("search_projection_missing".to_string());
1451 }
1452 if projection_present && !projection_watermark_caught_up {
1453 blocker_codes.insert("search_projection_watermark_behind_graph".to_string());
1454 }
1455 if projection_present && !projection_checkpointed {
1456 blocker_codes.insert("search_projection_not_checkpointed".to_string());
1457 }
1458 if projection_present && !projection_healthy {
1459 blocker_codes.insert("search_projection_repair_required".to_string());
1460 }
1461 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
1462 HawDBLightningInitialImportReadiness {
1463 ready: blocker_codes.is_empty(),
1464 manifest_import_ready,
1465 projection_present,
1466 graph_import_caught_up,
1467 projection_watermark_caught_up,
1468 projection_checkpointed,
1469 manifest_graph_commit_epoch: manifest.graph_commit_epoch,
1470 target_graph_commit_epoch,
1471 projection_source_graph_commit_epoch,
1472 projection_durable_source_graph_commit_epoch,
1473 blocker_codes,
1474 }
1475}
1476
1477pub fn hawdb_lightning_initial_import_checkpoint_readiness(
1478 manifest: &HawDBLightningBootstrapManifest,
1479 checkpoint: &HawDBLightningInitialImportCheckpoint,
1480) -> HawDBLightningInitialImportCheckpointReadiness {
1481 let idempotency_key = hawdb_lightning_initial_import_idempotency_key(checkpoint);
1482 let idempotency_key_present = idempotency_key.is_some();
1483 let checkpoint_matches_manifest = checkpoint.protocol_version == 1
1484 && checkpoint.schema_checksum == manifest.schema_checksum
1485 && checkpoint.graph_stream_checksum == manifest.graph_stream_checksum
1486 && checkpoint.graph_stream_byte_len == manifest.graph_stream_byte_len
1487 && checkpoint.relational_stream_checksum == manifest.relational_stream_checksum
1488 && checkpoint.relational_stream_byte_len == manifest.relational_stream_byte_len
1489 && checkpoint.manifest_database_commit_epoch == manifest.database_commit_epoch
1490 && checkpoint.manifest_graph_commit_epoch == manifest.graph_commit_epoch;
1491 let graph_checkpoint_caught_up =
1492 checkpoint.applied_graph_commit_epoch >= manifest.graph_commit_epoch;
1493 let search_projection_applied_caught_up = checkpoint
1494 .applied_search_projection_commit_epoch
1495 .is_some_and(|epoch| epoch >= checkpoint.applied_graph_commit_epoch);
1496 let search_projection_durable_caught_up = checkpoint
1497 .durable_search_projection_commit_epoch
1498 .is_some_and(|epoch| epoch >= checkpoint.applied_graph_commit_epoch);
1499 let batches_complete =
1500 checkpoint.total_batches > 0 && checkpoint.completed_batches == checkpoint.total_batches;
1501 let document_identities_present = checkpoint.document_identity_count > 0;
1502 let mut blocker_codes = BTreeSet::new();
1503 if !idempotency_key_present {
1504 blocker_codes.insert("initial_import_checkpoint_idempotency_key_missing".to_string());
1505 }
1506 if !checkpoint_matches_manifest {
1507 blocker_codes.insert("initial_import_checkpoint_manifest_mismatch".to_string());
1508 }
1509 if !graph_checkpoint_caught_up {
1510 blocker_codes.insert("initial_import_graph_checkpoint_behind_manifest".to_string());
1511 }
1512 if !search_projection_applied_caught_up {
1513 blocker_codes.insert("initial_import_search_projection_apply_behind_graph".to_string());
1514 }
1515 if !search_projection_durable_caught_up {
1516 blocker_codes
1517 .insert("initial_import_search_projection_checkpoint_behind_graph".to_string());
1518 }
1519 if !batches_complete {
1520 blocker_codes.insert("initial_import_batches_incomplete".to_string());
1521 }
1522 if !document_identities_present {
1523 blocker_codes.insert("initial_import_document_identities_missing".to_string());
1524 }
1525 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
1526 HawDBLightningInitialImportCheckpointReadiness {
1527 ready: blocker_codes.is_empty(),
1528 idempotency_key_present,
1529 idempotency_key,
1530 checkpoint_matches_manifest,
1531 graph_checkpoint_caught_up,
1532 search_projection_applied_caught_up,
1533 search_projection_durable_caught_up,
1534 batches_complete,
1535 document_identities_present,
1536 manifest_graph_commit_epoch: manifest.graph_commit_epoch,
1537 applied_graph_commit_epoch: checkpoint.applied_graph_commit_epoch,
1538 applied_search_projection_commit_epoch: checkpoint.applied_search_projection_commit_epoch,
1539 durable_search_projection_commit_epoch: checkpoint.durable_search_projection_commit_epoch,
1540 completed_batches: checkpoint.completed_batches,
1541 total_batches: checkpoint.total_batches,
1542 document_identity_count: checkpoint.document_identity_count,
1543 blocker_codes,
1544 }
1545}
1546
1547pub fn hawdb_lightning_initial_import_advance_checkpoint(
1548 manifest: &HawDBLightningBootstrapManifest,
1549 checkpoint: &HawDBLightningInitialImportCheckpoint,
1550 progress: HawDBLightningInitialImportCheckpointProgress,
1551) -> HawDBLightningInitialImportCheckpointProgressReport {
1552 let previous_readiness =
1553 hawdb_lightning_initial_import_checkpoint_readiness(manifest, checkpoint);
1554 let mut blocker_codes = BTreeSet::new();
1555 if !previous_readiness.idempotency_key_present {
1556 blocker_codes.insert("initial_import_checkpoint_idempotency_key_missing".to_string());
1557 }
1558 if !previous_readiness.checkpoint_matches_manifest {
1559 blocker_codes.insert("initial_import_checkpoint_manifest_mismatch".to_string());
1560 }
1561 if progress.applied_graph_commit_epoch < checkpoint.applied_graph_commit_epoch {
1562 blocker_codes.insert("initial_import_graph_checkpoint_regressed".to_string());
1563 }
1564 if optional_epoch_regressed(
1565 checkpoint.applied_search_projection_commit_epoch,
1566 progress.applied_search_projection_commit_epoch,
1567 ) {
1568 blocker_codes.insert("initial_import_search_projection_apply_regressed".to_string());
1569 }
1570 if optional_epoch_regressed(
1571 checkpoint.durable_search_projection_commit_epoch,
1572 progress.durable_search_projection_commit_epoch,
1573 ) {
1574 blocker_codes.insert("initial_import_search_projection_checkpoint_regressed".to_string());
1575 }
1576 if progress.completed_batches < checkpoint.completed_batches {
1577 blocker_codes.insert("initial_import_completed_batches_regressed".to_string());
1578 }
1579 if progress.total_batches < checkpoint.total_batches {
1580 blocker_codes.insert("initial_import_total_batches_regressed".to_string());
1581 }
1582 if progress.completed_batches > progress.total_batches {
1583 blocker_codes.insert("initial_import_completed_batches_exceed_total".to_string());
1584 }
1585 if progress.document_identity_count < checkpoint.document_identity_count {
1586 blocker_codes.insert("initial_import_document_identities_regressed".to_string());
1587 }
1588
1589 if !blocker_codes.is_empty() {
1590 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
1591 return HawDBLightningInitialImportCheckpointProgressReport {
1592 accepted: false,
1593 checkpoint: checkpoint.clone(),
1594 readiness: previous_readiness,
1595 resume_action: hawdb_lightning_initial_import_resume_action(manifest, Some(checkpoint)),
1596 blocker_codes,
1597 };
1598 }
1599
1600 let advanced = HawDBLightningInitialImportCheckpoint {
1601 applied_graph_commit_epoch: progress.applied_graph_commit_epoch,
1602 applied_search_projection_commit_epoch: progress.applied_search_projection_commit_epoch,
1603 durable_search_projection_commit_epoch: progress.durable_search_projection_commit_epoch,
1604 completed_batches: progress.completed_batches,
1605 total_batches: progress.total_batches,
1606 document_identity_count: progress.document_identity_count,
1607 ..checkpoint.clone()
1608 };
1609 let readiness = hawdb_lightning_initial_import_checkpoint_readiness(manifest, &advanced);
1610 let resume_action = hawdb_lightning_initial_import_resume_action(manifest, Some(&advanced));
1611 HawDBLightningInitialImportCheckpointProgressReport {
1612 accepted: true,
1613 checkpoint: advanced,
1614 readiness,
1615 resume_action,
1616 blocker_codes: Vec::new(),
1617 }
1618}
1619
1620pub fn hawdb_lightning_initial_import_search_projection_batch_report(
1621 manifest: &HawDBLightningBootstrapManifest,
1622 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
1623 delta: &SearchProjectionDelta,
1624 batch_index: u64,
1625 total_batches: u64,
1626) -> HawDBLightningInitialImportSearchProjectionBatchReport {
1627 let document_identities = search_projection_delta_document_identities(delta);
1628 hawdb_lightning_initial_import_search_projection_batch_report_with_document_identities(
1629 manifest,
1630 checkpoint,
1631 delta,
1632 batch_index,
1633 total_batches,
1634 &document_identities,
1635 )
1636}
1637
1638pub fn hawdb_lightning_initial_import_source_bundle_readiness(
1639 manifest: &HawDBLightningBootstrapManifest,
1640 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
1641 projection_batches: &[SearchProjectionDelta],
1642) -> HawDBLightningInitialImportSourceBundleReadiness {
1643 let source_fingerprint = hawdb_lightning_initial_import_source_fingerprint(manifest);
1644 let total_batches = projection_batches.len() as u64;
1645 let document_identities = projection_batches
1646 .iter()
1647 .flat_map(search_projection_delta_document_identities)
1648 .collect::<Vec<_>>();
1649 let document_identity_coverage =
1650 hawdb_lightning_initial_import_document_identity_coverage(&document_identities);
1651 let batch_reports = projection_batches
1652 .iter()
1653 .enumerate()
1654 .map(|(batch_index, delta)| {
1655 hawdb_lightning_initial_import_search_projection_batch_report_with_document_identities(
1656 manifest,
1657 checkpoint,
1658 delta,
1659 batch_index as u64,
1660 total_batches,
1661 &document_identities,
1662 )
1663 })
1664 .collect::<Vec<_>>();
1665 let ready_projection_batch_count = batch_reports.iter().filter(|report| report.ready).count();
1666 let database_source_import_ready = manifest.validation.is_import_ready
1667 && manifest.relational_validation.is_valid
1668 && manifest.database_commit_epoch == manifest.graph_commit_epoch;
1669 let checkpoint_present = checkpoint.is_some();
1670 let mut blocker_codes = BTreeSet::new();
1671 if !database_source_import_ready {
1672 blocker_codes.insert("initial_import_source_bundle_database_not_import_ready".to_string());
1673 }
1674 if !checkpoint_present {
1675 blocker_codes.insert("initial_import_source_bundle_checkpoint_missing".to_string());
1676 }
1677 if projection_batches.is_empty() {
1678 blocker_codes.insert("initial_import_source_bundle_projection_batches_missing".to_string());
1679 }
1680 if !document_identity_coverage.ready {
1681 blocker_codes.extend(document_identity_coverage.blocker_codes.iter().cloned());
1682 }
1683 for report in &batch_reports {
1684 blocker_codes.extend(report.blocker_codes.iter().cloned());
1685 blocker_codes.extend(report.checkpoint_progress_blocker_codes.iter().cloned());
1686 }
1687 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
1688 let ready = blocker_codes.is_empty()
1689 && database_source_import_ready
1690 && checkpoint_present
1691 && !projection_batches.is_empty()
1692 && ready_projection_batch_count == projection_batches.len();
1693
1694 HawDBLightningInitialImportSourceBundleReadiness {
1695 ready,
1696 database_source_import_ready,
1697 checkpoint_present,
1698 projection_batch_count: projection_batches.len(),
1699 ready_projection_batch_count,
1700 total_batches,
1701 source_fingerprint,
1702 document_identity_coverage,
1703 batch_reports,
1704 blocker_codes,
1705 }
1706}
1707
1708pub fn hawdb_lightning_initial_import_search_projection_batch_report_with_document_identities(
1709 manifest: &HawDBLightningBootstrapManifest,
1710 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
1711 delta: &SearchProjectionDelta,
1712 batch_index: u64,
1713 total_batches: u64,
1714 document_identities: &[HawDBLightningInitialImportDocumentIdentity],
1715) -> HawDBLightningInitialImportSearchProjectionBatchReport {
1716 let source_graph_commit_epoch_matches =
1717 delta.source_graph_commit_epoch == Some(manifest.graph_commit_epoch);
1718 let batch_position_valid = total_batches > 0 && batch_index < total_batches;
1719 let operation_count = delta.operation_count();
1720 let operation_limit_ok = delta
1721 .max_operations
1722 .is_none_or(|limit| operation_count <= limit);
1723 let checkpoint_readiness = checkpoint.map(|checkpoint| {
1724 hawdb_lightning_initial_import_checkpoint_readiness(manifest, checkpoint)
1725 });
1726 let checkpoint_present = checkpoint.is_some();
1727 let checkpoint_matches_manifest = checkpoint_readiness
1728 .as_ref()
1729 .is_some_and(|readiness| readiness.checkpoint_matches_manifest);
1730 let checkpoint_idempotency_key_present = checkpoint_readiness
1731 .as_ref()
1732 .is_some_and(|readiness| readiness.idempotency_key_present);
1733 let total_batches_match_checkpoint = checkpoint
1734 .map(|checkpoint| checkpoint.total_batches == total_batches)
1735 .unwrap_or(false);
1736 let empty_batch = operation_count == 0;
1737 let delete_count = delta.deletes.len();
1738 let document_identity_coverage =
1739 hawdb_lightning_initial_import_document_identity_coverage(document_identities);
1740 let mut blocker_codes = BTreeSet::new();
1741 if !checkpoint_present {
1742 blocker_codes
1743 .insert("initial_import_search_projection_batch_checkpoint_missing".to_string());
1744 }
1745 if checkpoint_present && !checkpoint_matches_manifest {
1746 blocker_codes
1747 .insert("initial_import_search_projection_batch_checkpoint_mismatch".to_string());
1748 }
1749 if checkpoint_present && !checkpoint_idempotency_key_present {
1750 blocker_codes.insert(
1751 "initial_import_search_projection_batch_checkpoint_idempotency_missing".to_string(),
1752 );
1753 }
1754 if checkpoint_present && !total_batches_match_checkpoint {
1755 blocker_codes.insert("initial_import_search_projection_batch_total_mismatch".to_string());
1756 }
1757 if !source_graph_commit_epoch_matches {
1758 blocker_codes.insert("initial_import_search_projection_batch_epoch_mismatch".to_string());
1759 }
1760 if !batch_position_valid {
1761 blocker_codes.insert("initial_import_search_projection_batch_position_invalid".to_string());
1762 }
1763 if !operation_limit_ok {
1764 blocker_codes.insert("initial_import_search_projection_batch_limit_exceeded".to_string());
1765 }
1766 if empty_batch {
1767 blocker_codes.insert("initial_import_search_projection_batch_empty".to_string());
1768 }
1769 if delete_count > 0 {
1770 blocker_codes.insert("initial_import_search_projection_batch_has_deletes".to_string());
1771 }
1772 if !document_identity_coverage.ready {
1773 blocker_codes.extend(document_identity_coverage.blocker_codes.iter().cloned());
1774 }
1775 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
1776 let ready = blocker_codes.is_empty();
1777 let checkpoint_progress = if ready {
1778 checkpoint.map(|checkpoint| {
1779 let completed_batches = checkpoint
1780 .completed_batches
1781 .max(batch_index.saturating_add(1));
1782 HawDBLightningInitialImportCheckpointProgress {
1783 applied_graph_commit_epoch: checkpoint
1784 .applied_graph_commit_epoch
1785 .max(manifest.graph_commit_epoch),
1786 applied_search_projection_commit_epoch: Some(manifest.graph_commit_epoch),
1787 durable_search_projection_commit_epoch: checkpoint
1788 .durable_search_projection_commit_epoch,
1789 completed_batches,
1790 total_batches: checkpoint.total_batches.max(total_batches),
1791 document_identity_count: checkpoint
1792 .document_identity_count
1793 .max(document_identities.len()),
1794 }
1795 })
1796 } else {
1797 None
1798 };
1799 let checkpoint_progress_report = checkpoint_progress.as_ref().and_then(|progress| {
1800 checkpoint.map(|checkpoint| {
1801 hawdb_lightning_initial_import_advance_checkpoint(
1802 manifest,
1803 checkpoint,
1804 progress.clone(),
1805 )
1806 })
1807 });
1808 let checkpoint_progress_accepted = checkpoint_progress_report
1809 .as_ref()
1810 .is_some_and(|report| report.accepted);
1811 let checkpoint_progress_readiness = checkpoint_progress_report
1812 .as_ref()
1813 .map(|report| report.readiness.clone());
1814 let checkpoint_resume_action = checkpoint_progress_report
1815 .as_ref()
1816 .map(|report| report.resume_action.clone());
1817 let checkpoint_progress_blocker_codes = checkpoint_progress_report
1818 .map(|report| report.blocker_codes)
1819 .unwrap_or_default();
1820 HawDBLightningInitialImportSearchProjectionBatchReport {
1821 ready,
1822 checkpoint_present,
1823 checkpoint_matches_manifest,
1824 checkpoint_idempotency_key_present,
1825 total_batches_match_checkpoint,
1826 source_graph_commit_epoch_matches,
1827 batch_position_valid,
1828 operation_limit_ok,
1829 empty_batch,
1830 delete_count,
1831 document_identity_coverage,
1832 source_graph_commit_epoch: delta.source_graph_commit_epoch,
1833 batch_index,
1834 total_batches,
1835 operation_count,
1836 checkpoint_progress,
1837 checkpoint_progress_accepted,
1838 checkpoint_progress_readiness,
1839 checkpoint_resume_action,
1840 checkpoint_progress_blocker_codes,
1841 blocker_codes,
1842 }
1843}
1844
1845pub fn hawdb_lightning_initial_import_durable_state_report(
1846 manifest: &HawDBLightningBootstrapManifest,
1847 checkpoint: &HawDBLightningInitialImportCheckpoint,
1848 document_identities: &[HawDBLightningInitialImportDocumentIdentity],
1849) -> HawDBLightningInitialImportDurableStateReport {
1850 let checkpoint_readiness =
1851 hawdb_lightning_initial_import_checkpoint_readiness(manifest, checkpoint);
1852 let resume_action = hawdb_lightning_initial_import_resume_action(manifest, Some(checkpoint));
1853 let document_identity_coverage =
1854 hawdb_lightning_initial_import_document_identity_coverage(document_identities);
1855 let mut blocker_codes = BTreeSet::new();
1856 if !checkpoint_readiness.idempotency_key_present {
1857 blocker_codes.insert("initial_import_durable_state_idempotency_missing".to_string());
1858 }
1859 if !checkpoint_readiness.checkpoint_matches_manifest {
1860 blocker_codes.insert("initial_import_durable_state_manifest_mismatch".to_string());
1861 }
1862 if checkpoint.total_batches == 0 {
1863 blocker_codes.insert("initial_import_durable_state_total_batches_missing".to_string());
1864 }
1865 if checkpoint.completed_batches > checkpoint.total_batches {
1866 blocker_codes
1867 .insert("initial_import_durable_state_completed_batches_exceed_total".to_string());
1868 }
1869 if checkpoint.document_identity_count > document_identities.len() {
1870 blocker_codes
1871 .insert("initial_import_durable_state_document_identity_regressed".to_string());
1872 }
1873 let persistable = blocker_codes.is_empty();
1874 if !document_identity_coverage.ready {
1875 blocker_codes.extend(document_identity_coverage.blocker_codes.iter().cloned());
1876 }
1877 let ready_for_cutover =
1878 persistable && checkpoint_readiness.ready && document_identity_coverage.ready;
1879 let state = persistable.then(|| HawDBLightningInitialImportDurableState {
1880 source_fingerprint: hawdb_lightning_initial_import_source_fingerprint(manifest),
1881 checkpoint: checkpoint.clone(),
1882 document_identities: document_identities.to_vec(),
1883 document_identity_coverage: document_identity_coverage.clone(),
1884 });
1885 HawDBLightningInitialImportDurableStateReport {
1886 persistable,
1887 ready_for_cutover,
1888 state,
1889 checkpoint_readiness,
1890 resume_action,
1891 blocker_codes: blocker_codes.into_iter().collect(),
1892 }
1893}
1894
1895fn hawdb_lightning_initial_import_durable_state_json(
1896 state: &HawDBLightningInitialImportDurableState,
1897) -> serde_json::Value {
1898 serde_json::json!({
1899 "protocol": HAWDB_LIGHTNING_INITIAL_IMPORT_DURABLE_STATE_PROTOCOL,
1900 "source_fingerprint": hawdb_lightning_initial_import_source_fingerprint_json(&state.source_fingerprint),
1901 "checkpoint": hawdb_lightning_initial_import_checkpoint_json(&state.checkpoint),
1902 "document_identities": state
1903 .document_identities
1904 .iter()
1905 .map(hawdb_lightning_initial_import_document_identity_json)
1906 .collect::<Vec<_>>(),
1907 "document_identity_coverage": hawdb_lightning_initial_import_document_identity_coverage_json(&state.document_identity_coverage),
1908 })
1909}
1910
1911pub fn hawdb_lightning_initial_import_encode_durable_state(
1912 state: &HawDBLightningInitialImportDurableState,
1913) -> Result<String> {
1914 serde_json::to_string(&hawdb_lightning_initial_import_durable_state_json(state)).map_err(|_| {
1915 HawDBError::Execution(
1916 "initial import durable state serialization failed: invalid_json".to_string(),
1917 )
1918 })
1919}
1920
1921fn hawdb_lightning_initial_import_decode_durable_state_value(
1922 manifest: &HawDBLightningBootstrapManifest,
1923 value: &serde_json::Value,
1924) -> Result<HawDBLightningInitialImportDurableStateCodecReport> {
1925 let mut blocker_codes = BTreeSet::new();
1926 let protocol = required_json_string(value, "protocol")?.to_string();
1927 if protocol != HAWDB_LIGHTNING_INITIAL_IMPORT_DURABLE_STATE_PROTOCOL {
1928 blocker_codes.insert("initial_import_durable_state_codec_protocol_mismatch".to_string());
1929 }
1930 let source_fingerprint = parse_hawdb_lightning_initial_import_source_fingerprint(
1931 required_json_object(value, "source_fingerprint")?,
1932 )?;
1933 let source_fingerprint_matches_manifest =
1934 source_fingerprint == hawdb_lightning_initial_import_source_fingerprint(manifest);
1935 if !source_fingerprint_matches_manifest {
1936 blocker_codes.insert("initial_import_durable_state_codec_source_mismatch".to_string());
1937 }
1938 let checkpoint = parse_hawdb_lightning_initial_import_checkpoint(required_json_object(
1939 value,
1940 "checkpoint",
1941 )?)?;
1942 let document_identities = parse_hawdb_lightning_initial_import_document_identities(
1943 required_json_array(value, "document_identities")?,
1944 )?;
1945 let state_report = hawdb_lightning_initial_import_durable_state_report(
1946 manifest,
1947 &checkpoint,
1948 &document_identities,
1949 );
1950 if !state_report.persistable {
1951 blocker_codes.extend(state_report.blocker_codes.iter().cloned());
1952 }
1953 let ready = blocker_codes.is_empty();
1954 let state = (ready && source_fingerprint_matches_manifest)
1955 .then_some(state_report.state)
1956 .flatten();
1957 Ok(HawDBLightningInitialImportDurableStateCodecReport {
1958 ready,
1959 protocol,
1960 source_fingerprint_matches_manifest,
1961 state,
1962 blocker_codes: blocker_codes.into_iter().collect(),
1963 })
1964}
1965
1966pub fn hawdb_lightning_initial_import_decode_durable_state(
1967 manifest: &HawDBLightningBootstrapManifest,
1968 raw: &str,
1969) -> Result<HawDBLightningInitialImportDurableStateCodecReport> {
1970 let value = serde_json::from_str::<serde_json::Value>(raw).map_err(|_| {
1971 HawDBError::Semantic("initial import durable state parse failed: invalid_json".to_string())
1972 })?;
1973 hawdb_lightning_initial_import_decode_durable_state_value(manifest, &value)
1974}
1975
1976pub fn hawdb_lightning_initial_import_advance_durable_state_with_search_projection_batch(
1977 manifest: &HawDBLightningBootstrapManifest,
1978 state: &HawDBLightningInitialImportDurableState,
1979 delta: &SearchProjectionDelta,
1980 batch_index: u64,
1981 total_batches: u64,
1982) -> HawDBLightningInitialImportDurableBatchAdvanceReport {
1983 let document_identities = merge_initial_import_document_identities(
1984 &state.document_identities,
1985 &search_projection_delta_document_identities(delta),
1986 );
1987 let batch_report =
1988 hawdb_lightning_initial_import_search_projection_batch_report_with_document_identities(
1989 manifest,
1990 Some(&state.checkpoint),
1991 delta,
1992 batch_index,
1993 total_batches,
1994 &document_identities,
1995 );
1996 let idempotent_replay = batch_index < state.checkpoint.completed_batches;
1997 let durable_state_report = if let Some(progress) = batch_report.checkpoint_progress.as_ref() {
1998 let progress_report = hawdb_lightning_initial_import_advance_checkpoint(
1999 manifest,
2000 &state.checkpoint,
2001 progress.clone(),
2002 );
2003 if progress_report.accepted {
2004 hawdb_lightning_initial_import_durable_state_report(
2005 manifest,
2006 &progress_report.checkpoint,
2007 &document_identities,
2008 )
2009 } else {
2010 hawdb_lightning_initial_import_durable_state_report(
2011 manifest,
2012 &state.checkpoint,
2013 &state.document_identities,
2014 )
2015 }
2016 } else {
2017 hawdb_lightning_initial_import_durable_state_report(
2018 manifest,
2019 &state.checkpoint,
2020 &state.document_identities,
2021 )
2022 };
2023 let mut blocker_codes = BTreeSet::new();
2024 if !batch_report.ready {
2025 blocker_codes.extend(batch_report.blocker_codes.iter().cloned());
2026 }
2027 if !batch_report.checkpoint_progress_accepted {
2028 blocker_codes.extend(
2029 batch_report
2030 .checkpoint_progress_blocker_codes
2031 .iter()
2032 .cloned(),
2033 );
2034 if batch_report.checkpoint_progress.is_none() {
2035 blocker_codes
2036 .insert("initial_import_durable_batch_checkpoint_progress_missing".to_string());
2037 }
2038 }
2039 if !durable_state_report.persistable {
2040 blocker_codes.extend(durable_state_report.blocker_codes.iter().cloned());
2041 }
2042 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
2043 HawDBLightningInitialImportDurableBatchAdvanceReport {
2044 ready: blocker_codes.is_empty(),
2045 idempotent_replay,
2046 batch_report,
2047 durable_state_report,
2048 blocker_codes,
2049 }
2050}
2051
2052pub fn hawdb_lightning_initial_import_advance_durable_state_streaming(
2058 manifest: &HawDBLightningBootstrapManifest,
2059 state: &HawDBLightningInitialImportDurableState,
2060 delta: &SearchProjectionDelta,
2061 batch_index: u64,
2062 total_batches: u64,
2063) -> HawDBLightningInitialImportStreamingBatchAdvanceReport {
2064 let checkpoint_readiness =
2065 hawdb_lightning_initial_import_checkpoint_readiness(manifest, &state.checkpoint);
2066 let mut blocker_codes = BTreeSet::new();
2067 if !checkpoint_readiness.idempotency_key_present {
2068 blocker_codes.insert("initial_import_streaming_batch_idempotency_missing".to_string());
2069 }
2070 if !checkpoint_readiness.checkpoint_matches_manifest {
2071 blocker_codes.insert("initial_import_streaming_batch_checkpoint_mismatch".to_string());
2072 }
2073 if state.checkpoint.total_batches != total_batches {
2074 blocker_codes.insert("initial_import_streaming_batch_total_mismatch".to_string());
2075 }
2076 if delta.source_graph_commit_epoch != Some(manifest.graph_commit_epoch) {
2077 blocker_codes.insert("initial_import_streaming_batch_epoch_mismatch".to_string());
2078 }
2079 if total_batches == 0 || batch_index >= total_batches {
2080 blocker_codes.insert("initial_import_streaming_batch_position_invalid".to_string());
2081 }
2082 if delta.operation_count() == 0 {
2083 blocker_codes.insert("initial_import_streaming_batch_empty".to_string());
2084 }
2085 if !delta.deletes.is_empty() {
2086 blocker_codes.insert("initial_import_streaming_batch_has_deletes".to_string());
2087 }
2088 if delta
2089 .max_operations
2090 .is_some_and(|limit| delta.operation_count() > limit)
2091 {
2092 blocker_codes.insert("initial_import_streaming_batch_limit_exceeded".to_string());
2093 }
2094
2095 let idempotent_replay = batch_index < state.checkpoint.completed_batches;
2096 if !blocker_codes.is_empty() {
2097 let durable_state_report = hawdb_lightning_initial_import_durable_state_report(
2098 manifest,
2099 &state.checkpoint,
2100 &state.document_identities,
2101 );
2102 return HawDBLightningInitialImportStreamingBatchAdvanceReport {
2103 accepted: false,
2104 idempotent_replay,
2105 completed: state.checkpoint.completed_batches == state.checkpoint.total_batches,
2106 ready_for_cutover: durable_state_report.ready_for_cutover,
2107 durable_state_report,
2108 blocker_codes: blocker_codes.into_iter().collect(),
2109 };
2110 }
2111
2112 let document_identities = merge_initial_import_document_identities(
2113 &state.document_identities,
2114 &search_projection_delta_document_identities(delta),
2115 );
2116 let progress = HawDBLightningInitialImportCheckpointProgress {
2117 applied_graph_commit_epoch: state
2118 .checkpoint
2119 .applied_graph_commit_epoch
2120 .max(manifest.graph_commit_epoch),
2121 applied_search_projection_commit_epoch: Some(manifest.graph_commit_epoch),
2122 durable_search_projection_commit_epoch: Some(manifest.graph_commit_epoch),
2123 completed_batches: state
2124 .checkpoint
2125 .completed_batches
2126 .max(batch_index.saturating_add(1)),
2127 total_batches,
2128 document_identity_count: state
2129 .checkpoint
2130 .document_identity_count
2131 .max(document_identities.len()),
2132 };
2133 let progress_report =
2134 hawdb_lightning_initial_import_advance_checkpoint(manifest, &state.checkpoint, progress);
2135 if !progress_report.accepted {
2136 return HawDBLightningInitialImportStreamingBatchAdvanceReport {
2137 accepted: false,
2138 idempotent_replay,
2139 completed: state.checkpoint.completed_batches == state.checkpoint.total_batches,
2140 ready_for_cutover: false,
2141 durable_state_report: hawdb_lightning_initial_import_durable_state_report(
2142 manifest,
2143 &state.checkpoint,
2144 &state.document_identities,
2145 ),
2146 blocker_codes: progress_report.blocker_codes,
2147 };
2148 }
2149 let durable_state_report = hawdb_lightning_initial_import_durable_state_report(
2150 manifest,
2151 &progress_report.checkpoint,
2152 &document_identities,
2153 );
2154 let completed = progress_report.checkpoint.completed_batches == total_batches;
2155 HawDBLightningInitialImportStreamingBatchAdvanceReport {
2156 accepted: durable_state_report.persistable,
2157 idempotent_replay,
2158 completed,
2159 ready_for_cutover: completed && durable_state_report.ready_for_cutover,
2160 durable_state_report,
2161 blocker_codes: Vec::new(),
2162 }
2163}
2164
2165pub fn hawdb_lightning_initial_import_session_report(
2166 encoded_graph_stream: &str,
2167 encoded_relational_stream: &[u8],
2168 manifest: &HawDBLightningBootstrapManifest,
2169 target_graph_commit_epoch: u64,
2170 projection_freshness: Option<&SearchProjectionFreshness>,
2171 durable_state: Option<&HawDBLightningInitialImportDurableState>,
2172) -> HawDBLightningInitialImportSessionReport {
2173 let checkpoint = durable_state.map(|state| &state.checkpoint);
2174 let document_identities = durable_state.map(|state| state.document_identities.as_slice());
2175 let plan = hawdb_lightning_initial_import_plan_with_document_identities(
2176 encoded_graph_stream,
2177 encoded_relational_stream,
2178 manifest,
2179 target_graph_commit_epoch,
2180 projection_freshness,
2181 checkpoint,
2182 document_identities,
2183 );
2184 let durable_state_report = durable_state.map(|state| {
2185 hawdb_lightning_initial_import_durable_state_report(
2186 manifest,
2187 &state.checkpoint,
2188 &state.document_identities,
2189 )
2190 });
2191 let durable_state_source_matches_manifest = durable_state
2192 .map(|state| {
2193 state.source_fingerprint == hawdb_lightning_initial_import_source_fingerprint(manifest)
2194 })
2195 .unwrap_or(true);
2196 let mut blocker_codes = BTreeSet::new();
2197 blocker_codes.extend(plan.blocker_codes.iter().cloned());
2198 if !durable_state_source_matches_manifest {
2199 blocker_codes.insert("initial_import_durable_state_source_mismatch".to_string());
2200 }
2201 if let Some(report) = &durable_state_report
2202 && !report.persistable
2203 {
2204 blocker_codes.extend(report.blocker_codes.iter().cloned());
2205 }
2206
2207 let next_action = if !durable_state_source_matches_manifest {
2208 HawDBLightningInitialImportResumeAction {
2209 kind: HawDBLightningInitialImportResumeActionKind::Quarantine,
2210 next_batch: None,
2211 idempotency_key: None,
2212 completed_batches: durable_state
2213 .map(|state| state.checkpoint.completed_batches)
2214 .unwrap_or(0),
2215 total_batches: durable_state
2216 .map(|state| state.checkpoint.total_batches)
2217 .unwrap_or(0),
2218 blocker_codes: vec!["initial_import_durable_state_source_mismatch".to_string()],
2219 }
2220 } else {
2221 plan.resume_action.clone()
2222 };
2223 let ready_for_database_import =
2224 plan.ready_for_database_import && durable_state_source_matches_manifest;
2225 let ready_for_cutover = plan.ready_for_cutover
2226 && durable_state_source_matches_manifest
2227 && durable_state_report
2228 .as_ref()
2229 .is_some_and(|report| report.ready_for_cutover);
2230
2231 HawDBLightningInitialImportSessionReport {
2232 ready_for_database_import,
2233 ready_for_cutover,
2234 durable_state_present: durable_state.is_some(),
2235 durable_state_source_matches_manifest,
2236 plan,
2237 durable_state_report,
2238 next_action,
2239 blocker_codes: blocker_codes.into_iter().collect(),
2240 }
2241}
2242
2243pub fn hawdb_lightning_initial_import_cutover_catch_up_report(
2244 session: &HawDBLightningInitialImportSessionReport,
2245 live_graph_commit_epoch: u64,
2246 live_projection_freshness: Option<&SearchProjectionFreshness>,
2247) -> HawDBLightningInitialImportCutoverCatchUpReport {
2248 let durable_state = session
2249 .durable_state_report
2250 .as_ref()
2251 .and_then(|report| report.state.as_ref());
2252 let import_graph_commit_epoch =
2253 durable_state.map(|state| state.checkpoint.applied_graph_commit_epoch);
2254 let import_durable_search_projection_commit_epoch =
2255 durable_state.and_then(|state| state.checkpoint.durable_search_projection_commit_epoch);
2256 let live_projection_present = live_projection_freshness.is_some();
2257 let import_projection_provenance_matches = live_projection_freshness
2258 .zip(import_graph_commit_epoch)
2259 .is_some_and(|(freshness, import_epoch)| {
2260 freshness.import_source_graph_commit_epoch == Some(import_epoch)
2261 });
2262 let live_search_projection_commit_epoch =
2263 live_projection_freshness.and_then(|freshness| freshness.source_graph_commit_epoch);
2264 let live_durable_search_projection_commit_epoch =
2265 live_projection_freshness.and_then(|freshness| freshness.durable_source_graph_commit_epoch);
2266 let live_projection_checkpointed = live_projection_freshness
2267 .map(|freshness| !freshness.has_uncheckpointed_changes)
2268 .unwrap_or(false);
2269 let live_projection_healthy = live_projection_freshness
2270 .map(|freshness| !freshness.full_reindex_needed && !freshness.metadata_repair_needed)
2271 .unwrap_or(false);
2272 let graph_watermark_caught_up = session.ready_for_cutover
2277 && durable_state.is_some()
2278 && import_projection_provenance_matches;
2279 let search_projection_watermark_caught_up = live_durable_search_projection_commit_epoch
2280 .is_some_and(|live_epoch| live_epoch >= live_graph_commit_epoch);
2281 let cutover_watermark = if graph_watermark_caught_up
2282 && search_projection_watermark_caught_up
2283 && live_projection_checkpointed
2284 && live_projection_healthy
2285 {
2286 Some(live_graph_commit_epoch)
2287 } else {
2288 None
2289 };
2290
2291 let mut blocker_codes = BTreeSet::new();
2292 if !session.ready_for_cutover {
2293 blocker_codes.insert("initial_import_session_not_ready_for_cutover".to_string());
2294 }
2295 if durable_state.is_none() {
2296 blocker_codes.insert("initial_import_durable_state_missing".to_string());
2297 }
2298 if !live_projection_present {
2299 blocker_codes.insert("initial_import_live_projection_missing".to_string());
2300 }
2301 if !graph_watermark_caught_up {
2302 blocker_codes.insert("initial_import_live_graph_watermark_not_caught_up".to_string());
2303 }
2304 if live_projection_present && !import_projection_provenance_matches {
2305 blocker_codes.insert("initial_import_projection_provenance_mismatch".to_string());
2306 }
2307 if !search_projection_watermark_caught_up {
2308 blocker_codes
2309 .insert("initial_import_live_search_projection_watermark_not_caught_up".to_string());
2310 }
2311 if live_projection_present && !live_projection_checkpointed {
2312 blocker_codes.insert("initial_import_live_projection_not_checkpointed".to_string());
2313 }
2314 if live_projection_present && !live_projection_healthy {
2315 blocker_codes.insert("initial_import_live_projection_repair_required".to_string());
2316 }
2317
2318 HawDBLightningInitialImportCutoverCatchUpReport {
2319 ready: blocker_codes.is_empty(),
2320 session_ready_for_cutover: session.ready_for_cutover,
2321 durable_state_present: durable_state.is_some(),
2322 live_projection_present,
2323 import_graph_commit_epoch,
2324 import_durable_search_projection_commit_epoch,
2325 live_graph_commit_epoch,
2326 live_search_projection_commit_epoch,
2327 live_durable_search_projection_commit_epoch,
2328 graph_watermark_caught_up,
2329 search_projection_watermark_caught_up,
2330 live_projection_checkpointed,
2331 live_projection_healthy,
2332 cutover_watermark,
2333 blocker_codes: blocker_codes.into_iter().collect(),
2334 }
2335}
2336
2337pub fn hawdb_lightning_initial_import_session_bundle_readiness(
2338 source_bundle: &HawDBLightningInitialImportSourceBundleReadiness,
2339 session: &HawDBLightningInitialImportSessionReport,
2340 catch_up: Option<&HawDBLightningInitialImportCutoverCatchUpReport>,
2341) -> HawDBLightningInitialImportSessionBundleReadiness {
2342 let catch_up_required = session.ready_for_cutover;
2343 let catch_up_present = catch_up.is_some();
2344 let catch_up_ready = catch_up.is_some_and(|report| report.ready);
2345 let cutover_watermark = catch_up.and_then(|report| report.cutover_watermark);
2346 let resumable = source_bundle.ready
2347 && session.ready_for_database_import
2348 && session.durable_state_present
2349 && session.durable_state_source_matches_manifest
2350 && session.next_action.kind != HawDBLightningInitialImportResumeActionKind::Quarantine;
2351 let ready_for_cutover = resumable && session.ready_for_cutover && catch_up_ready;
2352 let mut blocker_codes = BTreeSet::new();
2353 if !source_bundle.ready {
2354 blocker_codes.extend(source_bundle.blocker_codes.iter().cloned());
2355 blocker_codes.insert("initial_import_session_bundle_source_not_ready".to_string());
2356 }
2357 if !session.ready_for_database_import {
2358 blocker_codes.insert("initial_import_session_bundle_database_import_not_ready".to_string());
2359 }
2360 if !session.durable_state_present {
2361 blocker_codes.insert("initial_import_session_bundle_durable_state_missing".to_string());
2362 }
2363 if !session.durable_state_source_matches_manifest {
2364 blocker_codes.insert("initial_import_session_bundle_source_mismatch".to_string());
2365 }
2366 if session.next_action.kind == HawDBLightningInitialImportResumeActionKind::Quarantine {
2367 blocker_codes.insert("initial_import_session_bundle_quarantine_required".to_string());
2368 }
2369 blocker_codes.extend(session.blocker_codes.iter().cloned());
2370 if catch_up_required {
2371 if !catch_up_present {
2372 blocker_codes
2373 .insert("initial_import_session_bundle_cutover_catch_up_missing".to_string());
2374 } else if !catch_up_ready {
2375 blocker_codes
2376 .insert("initial_import_session_bundle_cutover_catch_up_not_ready".to_string());
2377 }
2378 }
2379 if let Some(report) = catch_up
2380 && !report.ready
2381 {
2382 blocker_codes.extend(report.blocker_codes.iter().cloned());
2383 }
2384 HawDBLightningInitialImportSessionBundleReadiness {
2385 ready: blocker_codes.is_empty(),
2386 resumable,
2387 ready_for_cutover,
2388 source_bundle_ready: source_bundle.ready,
2389 session_ready_for_database_import: session.ready_for_database_import,
2390 session_ready_for_cutover: session.ready_for_cutover,
2391 durable_state_present: session.durable_state_present,
2392 durable_state_source_matches_manifest: session.durable_state_source_matches_manifest,
2393 catch_up_required,
2394 catch_up_present,
2395 catch_up_ready,
2396 cutover_watermark,
2397 next_action: session.next_action.clone(),
2398 blocker_codes: blocker_codes.into_iter().collect(),
2399 }
2400}
2401
2402pub fn hawdb_lightning_initial_import_startup_readiness(
2403 inputs: HawDBLightningInitialImportReadinessInputs<'_>,
2404 target_graph_commit_epoch: u64,
2405 durable_state: Option<&HawDBLightningInitialImportDurableState>,
2406) -> HawDBLightningInitialImportStartupReadinessReport {
2407 let checkpoint = durable_state.map(|state| &state.checkpoint);
2408 let source_bundle = hawdb_lightning_initial_import_source_bundle_readiness(
2409 inputs.manifest,
2410 checkpoint,
2411 inputs.projection_batches,
2412 );
2413 let session = hawdb_lightning_initial_import_session_report(
2414 inputs.encoded_graph_stream,
2415 inputs.encoded_relational_stream,
2416 inputs.manifest,
2417 target_graph_commit_epoch,
2418 inputs.target_projection_freshness,
2419 durable_state,
2420 );
2421 let cutover_catch_up = session.ready_for_cutover.then(|| {
2422 hawdb_lightning_initial_import_cutover_catch_up_report(
2423 &session,
2424 target_graph_commit_epoch,
2425 inputs.live_projection_freshness,
2426 )
2427 });
2428 let readiness = hawdb_lightning_initial_import_session_bundle_readiness(
2429 &source_bundle,
2430 &session,
2431 cutover_catch_up.as_ref(),
2432 );
2433 HawDBLightningInitialImportStartupReadinessReport {
2434 ready: readiness.ready,
2435 blocker_codes: readiness.blocker_codes.clone(),
2436 source_bundle,
2437 session,
2438 cutover_catch_up,
2439 readiness,
2440 }
2441}
2442
2443pub fn hawdb_lightning_initial_import_recovery_readiness(
2444 inputs: HawDBLightningInitialImportReadinessInputs<'_>,
2445 target_graph_commit_epoch: u64,
2446 durable_state_payload: Option<&str>,
2447) -> HawDBLightningInitialImportRecoveryReadinessReport {
2448 let durable_state_payload_present = durable_state_payload.is_some();
2449 let mut decode_blocker_codes = BTreeSet::new();
2450 let durable_state_codec = durable_state_payload.and_then(|payload| {
2451 match hawdb_lightning_initial_import_decode_durable_state(inputs.manifest, payload) {
2452 Ok(report) => {
2453 if !report.ready {
2454 decode_blocker_codes.extend(report.blocker_codes.iter().cloned());
2455 }
2456 Some(report)
2457 }
2458 Err(_) => {
2459 decode_blocker_codes
2460 .insert("initial_import_durable_state_codec_decode_failed".to_string());
2461 None
2462 }
2463 }
2464 });
2465 let durable_state = durable_state_codec
2466 .as_ref()
2467 .filter(|report| report.ready)
2468 .and_then(|report| report.state.as_ref());
2469 let startup = hawdb_lightning_initial_import_startup_readiness(
2470 inputs,
2471 target_graph_commit_epoch,
2472 durable_state,
2473 );
2474 let invalid_payload = durable_state_payload_present && durable_state.is_none();
2475 let next_action = if invalid_payload {
2476 HawDBLightningInitialImportResumeAction {
2477 kind: HawDBLightningInitialImportResumeActionKind::Quarantine,
2478 next_batch: None,
2479 idempotency_key: None,
2480 completed_batches: 0,
2481 total_batches: 0,
2482 blocker_codes: decode_blocker_codes.iter().cloned().collect(),
2483 }
2484 } else {
2485 startup.readiness.next_action.clone()
2486 };
2487 let mut blocker_codes = BTreeSet::new();
2488 blocker_codes.extend(startup.blocker_codes.iter().cloned());
2489 blocker_codes.extend(decode_blocker_codes);
2490 if invalid_payload {
2491 blocker_codes
2492 .insert("initial_import_recovery_durable_state_quarantine_required".to_string());
2493 }
2494 HawDBLightningInitialImportRecoveryReadinessReport {
2495 ready: !invalid_payload && startup.ready,
2496 durable_state_payload_present,
2497 durable_state_codec,
2498 startup,
2499 next_action,
2500 blocker_codes: blocker_codes.into_iter().collect(),
2501 }
2502}
2503
2504fn hawdb_lightning_initial_import_source_fingerprint_json(
2505 fingerprint: &HawDBLightningInitialImportSourceFingerprint,
2506) -> serde_json::Value {
2507 serde_json::json!({
2508 "protocol_version": fingerprint.protocol_version,
2509 "database_commit_epoch": fingerprint.database_commit_epoch,
2510 "graph_commit_epoch": fingerprint.graph_commit_epoch,
2511 "logical_checksum": fingerprint.logical_checksum,
2512 "graph_stream_checksum": fingerprint.graph_stream_checksum,
2513 "graph_stream_byte_len": fingerprint.graph_stream_byte_len,
2514 "relational_stream_checksum": fingerprint.relational_stream_checksum,
2515 "relational_stream_byte_len": fingerprint.relational_stream_byte_len,
2516 "schema_checksum": fingerprint.schema_checksum,
2517 "node_count": fingerprint.node_count,
2518 "relationship_count": fingerprint.relationship_count,
2519 "relational_table_count": fingerprint.relational_table_count,
2520 "relational_row_count": fingerprint.relational_row_count,
2521 })
2522}
2523
2524fn hawdb_lightning_initial_import_checkpoint_json(
2525 checkpoint: &HawDBLightningInitialImportCheckpoint,
2526) -> serde_json::Value {
2527 serde_json::json!({
2528 "protocol_version": checkpoint.protocol_version,
2529 "import_id": checkpoint.import_id,
2530 "task_id": checkpoint.task_id,
2531 "fencing_token": checkpoint.fencing_token,
2532 "object_digest": checkpoint.object_digest,
2533 "schema_checksum": checkpoint.schema_checksum,
2534 "graph_stream_checksum": checkpoint.graph_stream_checksum,
2535 "graph_stream_byte_len": checkpoint.graph_stream_byte_len,
2536 "relational_stream_checksum": checkpoint.relational_stream_checksum,
2537 "relational_stream_byte_len": checkpoint.relational_stream_byte_len,
2538 "manifest_database_commit_epoch": checkpoint.manifest_database_commit_epoch,
2539 "manifest_graph_commit_epoch": checkpoint.manifest_graph_commit_epoch,
2540 "applied_graph_commit_epoch": checkpoint.applied_graph_commit_epoch,
2541 "applied_search_projection_commit_epoch": checkpoint.applied_search_projection_commit_epoch,
2542 "durable_search_projection_commit_epoch": checkpoint.durable_search_projection_commit_epoch,
2543 "completed_batches": checkpoint.completed_batches,
2544 "total_batches": checkpoint.total_batches,
2545 "document_identity_count": checkpoint.document_identity_count,
2546 })
2547}
2548
2549fn hawdb_lightning_initial_import_document_identity_json(
2550 identity: &HawDBLightningInitialImportDocumentIdentity,
2551) -> serde_json::Value {
2552 serde_json::json!({
2553 "kind": identity.kind.as_str(),
2554 "document_id": identity.document_id,
2555 })
2556}
2557
2558fn hawdb_lightning_initial_import_document_identity_coverage_json(
2559 coverage: &HawDBLightningInitialImportDocumentIdentityCoverage,
2560) -> serde_json::Value {
2561 serde_json::json!({
2562 "ready": coverage.ready,
2563 "document_identity_count": coverage.document_identity_count,
2564 "unique_document_identity_count": coverage.unique_document_identity_count,
2565 "expected_kinds": coverage
2566 .expected_kinds
2567 .iter()
2568 .map(|kind| kind.as_str())
2569 .collect::<Vec<_>>(),
2570 "observed_kinds": coverage
2571 .observed_kinds
2572 .iter()
2573 .map(|kind| kind.as_str())
2574 .collect::<Vec<_>>(),
2575 "kind_reports": coverage
2576 .kind_reports
2577 .iter()
2578 .map(|report| {
2579 serde_json::json!({
2580 "kind": report.kind.as_str(),
2581 "document_count": report.document_count,
2582 })
2583 })
2584 .collect::<Vec<_>>(),
2585 "missing_kinds": coverage
2586 .missing_kinds
2587 .iter()
2588 .map(|kind| kind.as_str())
2589 .collect::<Vec<_>>(),
2590 "empty_document_id_count": coverage.empty_document_id_count,
2591 "blocker_codes": coverage.blocker_codes,
2592 })
2593}
2594
2595fn parse_hawdb_lightning_initial_import_source_fingerprint(
2596 value: &serde_json::Value,
2597) -> Result<HawDBLightningInitialImportSourceFingerprint> {
2598 Ok(HawDBLightningInitialImportSourceFingerprint {
2599 protocol_version: required_json_u64(value, "protocol_version")?,
2600 database_commit_epoch: required_json_u64(value, "database_commit_epoch")?,
2601 graph_commit_epoch: required_json_u64(value, "graph_commit_epoch")?,
2602 logical_checksum: required_json_u64(value, "logical_checksum")?,
2603 graph_stream_checksum: required_json_u64(value, "graph_stream_checksum")?,
2604 graph_stream_byte_len: required_json_usize(value, "graph_stream_byte_len")?,
2605 relational_stream_checksum: required_json_u64(value, "relational_stream_checksum")?,
2606 relational_stream_byte_len: required_json_usize(value, "relational_stream_byte_len")?,
2607 schema_checksum: required_json_u64(value, "schema_checksum")?,
2608 node_count: required_json_usize(value, "node_count")?,
2609 relationship_count: required_json_usize(value, "relationship_count")?,
2610 relational_table_count: required_json_usize(value, "relational_table_count")?,
2611 relational_row_count: required_json_usize(value, "relational_row_count")?,
2612 })
2613}
2614
2615fn parse_hawdb_lightning_initial_import_checkpoint(
2616 value: &serde_json::Value,
2617) -> Result<HawDBLightningInitialImportCheckpoint> {
2618 Ok(HawDBLightningInitialImportCheckpoint {
2619 protocol_version: required_json_u64(value, "protocol_version")?,
2620 import_id: required_json_string(value, "import_id")?.to_string(),
2621 task_id: required_json_string(value, "task_id")?.to_string(),
2622 fencing_token: required_json_string(value, "fencing_token")?.to_string(),
2623 object_digest: required_json_string(value, "object_digest")?.to_string(),
2624 schema_checksum: required_json_u64(value, "schema_checksum")?,
2625 graph_stream_checksum: required_json_u64(value, "graph_stream_checksum")?,
2626 graph_stream_byte_len: required_json_usize(value, "graph_stream_byte_len")?,
2627 relational_stream_checksum: required_json_u64(value, "relational_stream_checksum")?,
2628 relational_stream_byte_len: required_json_usize(value, "relational_stream_byte_len")?,
2629 manifest_database_commit_epoch: required_json_u64(value, "manifest_database_commit_epoch")?,
2630 manifest_graph_commit_epoch: required_json_u64(value, "manifest_graph_commit_epoch")?,
2631 applied_graph_commit_epoch: required_json_u64(value, "applied_graph_commit_epoch")?,
2632 applied_search_projection_commit_epoch: optional_json_u64(
2633 value,
2634 "applied_search_projection_commit_epoch",
2635 )?,
2636 durable_search_projection_commit_epoch: optional_json_u64(
2637 value,
2638 "durable_search_projection_commit_epoch",
2639 )?,
2640 completed_batches: required_json_u64(value, "completed_batches")?,
2641 total_batches: required_json_u64(value, "total_batches")?,
2642 document_identity_count: required_json_usize(value, "document_identity_count")?,
2643 })
2644}
2645
2646fn parse_hawdb_lightning_initial_import_document_identities(
2647 items: &[serde_json::Value],
2648) -> Result<Vec<HawDBLightningInitialImportDocumentIdentity>> {
2649 items
2650 .iter()
2651 .map(|value| {
2652 Ok(HawDBLightningInitialImportDocumentIdentity {
2653 kind: parse_search_projection_kind(required_json_string(value, "kind")?)?,
2654 document_id: required_json_string(value, "document_id")?.to_string(),
2655 })
2656 })
2657 .collect()
2658}
2659
2660fn parse_search_projection_kind(raw: &str) -> Result<SearchProjectionKind> {
2661 match raw {
2662 "memory" => Ok(SearchProjectionKind::Memory),
2663 "message" => Ok(SearchProjectionKind::Message),
2664 "entity" => Ok(SearchProjectionKind::Entity),
2665 "source" => Ok(SearchProjectionKind::Source),
2666 "source_chunk" => Ok(SearchProjectionKind::SourceChunk),
2667 "community" => Ok(SearchProjectionKind::Community),
2668 _ => Err(HawDBError::Semantic(
2669 "initial import durable state field kind is invalid".to_string(),
2670 )),
2671 }
2672}
2673
2674fn required_json_object<'a>(
2675 value: &'a serde_json::Value,
2676 field: &str,
2677) -> Result<&'a serde_json::Value> {
2678 let item = value
2679 .get(field)
2680 .ok_or_else(|| durable_state_codec_invalid_field(field, "object"))?;
2681 if item.is_object() {
2682 Ok(item)
2683 } else {
2684 Err(durable_state_codec_invalid_field(field, "object"))
2685 }
2686}
2687
2688fn required_json_array<'a>(
2689 value: &'a serde_json::Value,
2690 field: &str,
2691) -> Result<&'a [serde_json::Value]> {
2692 value
2693 .get(field)
2694 .and_then(serde_json::Value::as_array)
2695 .map(Vec::as_slice)
2696 .ok_or_else(|| durable_state_codec_invalid_field(field, "array"))
2697}
2698
2699fn required_json_string<'a>(value: &'a serde_json::Value, field: &str) -> Result<&'a str> {
2700 value
2701 .get(field)
2702 .and_then(serde_json::Value::as_str)
2703 .ok_or_else(|| durable_state_codec_invalid_field(field, "string"))
2704}
2705
2706fn required_json_u64(value: &serde_json::Value, field: &str) -> Result<u64> {
2707 value
2708 .get(field)
2709 .and_then(serde_json::Value::as_u64)
2710 .ok_or_else(|| durable_state_codec_invalid_field(field, "u64"))
2711}
2712
2713fn required_json_usize(value: &serde_json::Value, field: &str) -> Result<usize> {
2714 required_json_u64(value, field)?
2715 .try_into()
2716 .map_err(|_| durable_state_codec_invalid_field(field, "usize"))
2717}
2718
2719fn optional_json_u64(value: &serde_json::Value, field: &str) -> Result<Option<u64>> {
2720 match value.get(field) {
2721 Some(serde_json::Value::Null) | None => Ok(None),
2722 Some(item) => item
2723 .as_u64()
2724 .map(Some)
2725 .ok_or_else(|| durable_state_codec_invalid_field(field, "optional_u64")),
2726 }
2727}
2728
2729fn durable_state_codec_invalid_field(field: &str, expected: &str) -> HawDBError {
2730 HawDBError::Semantic(format!(
2731 "initial import durable state field {field} is invalid: expected_{expected}"
2732 ))
2733}
2734
2735pub fn hawdb_lightning_initial_import_source_fingerprint(
2736 manifest: &HawDBLightningBootstrapManifest,
2737) -> HawDBLightningInitialImportSourceFingerprint {
2738 HawDBLightningInitialImportSourceFingerprint {
2739 protocol_version: manifest.protocol_version,
2740 database_commit_epoch: manifest.database_commit_epoch,
2741 graph_commit_epoch: manifest.graph_commit_epoch,
2742 logical_checksum: manifest.logical_checksum,
2743 graph_stream_checksum: manifest.graph_stream_checksum,
2744 graph_stream_byte_len: manifest.graph_stream_byte_len,
2745 relational_stream_checksum: manifest.relational_stream_checksum,
2746 relational_stream_byte_len: manifest.relational_stream_byte_len,
2747 schema_checksum: manifest.schema_checksum,
2748 node_count: manifest.node_count,
2749 relationship_count: manifest.relationship_count,
2750 relational_table_count: manifest.relational_table_count,
2751 relational_row_count: manifest.relational_row_count,
2752 }
2753}
2754
2755fn merge_initial_import_document_identities(
2756 existing: &[HawDBLightningInitialImportDocumentIdentity],
2757 incoming: &[HawDBLightningInitialImportDocumentIdentity],
2758) -> Vec<HawDBLightningInitialImportDocumentIdentity> {
2759 let mut identities = Vec::with_capacity(existing.len().saturating_add(incoming.len()));
2760 let mut seen = BTreeSet::new();
2761 for identity in existing.iter().chain(incoming.iter()) {
2762 if seen.insert((identity.kind, identity.document_id.clone())) {
2763 identities.push(identity.clone());
2764 }
2765 }
2766 identities
2767}
2768
2769fn search_projection_delta_document_identities(
2770 delta: &SearchProjectionDelta,
2771) -> Vec<HawDBLightningInitialImportDocumentIdentity> {
2772 delta
2773 .upserts
2774 .iter()
2775 .map(|row| HawDBLightningInitialImportDocumentIdentity {
2776 kind: row.kind,
2777 document_id: format!("{}:{}", row.kind.as_str(), row.external_id),
2778 })
2779 .collect()
2780}
2781
2782pub fn hawdb_lightning_initial_import_document_identity_coverage(
2783 identities: &[HawDBLightningInitialImportDocumentIdentity],
2784) -> HawDBLightningInitialImportDocumentIdentityCoverage {
2785 let expected_kinds = hawdb_lightning_initial_import_required_search_projection_kinds();
2786 let mut document_ids = BTreeMap::<String, usize>::new();
2787 let mut kind_counts = BTreeMap::<SearchProjectionKind, usize>::new();
2788 let mut empty_document_id_count = 0;
2789 for identity in identities {
2790 if identity.document_id.is_empty() {
2791 empty_document_id_count += 1;
2792 } else {
2793 *document_ids
2794 .entry(identity.document_id.clone())
2795 .or_default() += 1;
2796 }
2797 *kind_counts.entry(identity.kind).or_default() += 1;
2798 }
2799 let observed_kinds = kind_counts.keys().copied().collect::<Vec<_>>();
2800 let kind_reports = kind_counts
2801 .iter()
2802 .map(
2803 |(kind, document_count)| HawDBLightningInitialImportDocumentIdentityKindReport {
2804 kind: *kind,
2805 document_count: *document_count,
2806 },
2807 )
2808 .collect::<Vec<_>>();
2809 let missing_kinds = expected_kinds
2810 .iter()
2811 .copied()
2812 .filter(|kind| !kind_counts.contains_key(kind))
2813 .collect::<Vec<_>>();
2814 let duplicate_document_ids = document_ids
2815 .iter()
2816 .filter(|(_, count)| **count > 1)
2817 .map(|(document_id, _)| document_id.clone())
2818 .collect::<Vec<_>>();
2819 let mut blocker_codes = BTreeSet::new();
2820 if !missing_kinds.is_empty() {
2821 blocker_codes.insert("initial_import_document_identity_kind_missing".to_string());
2822 }
2823 if empty_document_id_count > 0 {
2824 blocker_codes.insert("initial_import_document_identity_empty".to_string());
2825 }
2826 if !duplicate_document_ids.is_empty() {
2827 blocker_codes.insert("initial_import_document_identity_duplicate".to_string());
2828 }
2829 let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
2830 HawDBLightningInitialImportDocumentIdentityCoverage {
2831 ready: blocker_codes.is_empty(),
2832 document_identity_count: identities.len(),
2833 unique_document_identity_count: document_ids.len(),
2834 expected_kinds,
2835 observed_kinds,
2836 kind_reports,
2837 missing_kinds,
2838 duplicate_document_ids,
2839 empty_document_id_count,
2840 blocker_codes,
2841 }
2842}
2843
2844pub fn hawdb_lightning_initial_import_resume_action(
2845 manifest: &HawDBLightningBootstrapManifest,
2846 checkpoint: Option<&HawDBLightningInitialImportCheckpoint>,
2847) -> HawDBLightningInitialImportResumeAction {
2848 let Some(checkpoint) = checkpoint else {
2849 return HawDBLightningInitialImportResumeAction {
2850 kind: HawDBLightningInitialImportResumeActionKind::Start,
2851 next_batch: Some(0),
2852 idempotency_key: None,
2853 completed_batches: 0,
2854 total_batches: 0,
2855 blocker_codes: Vec::new(),
2856 };
2857 };
2858 let readiness = hawdb_lightning_initial_import_checkpoint_readiness(manifest, checkpoint);
2859 let hard_mismatch = readiness.blocker_codes.iter().any(|code| {
2860 code == "initial_import_checkpoint_manifest_mismatch"
2861 || code == "initial_import_checkpoint_idempotency_key_missing"
2862 });
2863 let kind = if hard_mismatch {
2864 HawDBLightningInitialImportResumeActionKind::Quarantine
2865 } else if readiness.ready {
2866 HawDBLightningInitialImportResumeActionKind::ReadyForCutover
2867 } else {
2868 HawDBLightningInitialImportResumeActionKind::Resume
2869 };
2870 let next_batch = match kind {
2871 HawDBLightningInitialImportResumeActionKind::Start => Some(0),
2872 HawDBLightningInitialImportResumeActionKind::Resume => {
2873 Some(checkpoint.completed_batches.min(checkpoint.total_batches))
2874 }
2875 HawDBLightningInitialImportResumeActionKind::ReadyForCutover
2876 | HawDBLightningInitialImportResumeActionKind::Quarantine => None,
2877 };
2878 HawDBLightningInitialImportResumeAction {
2879 kind,
2880 next_batch,
2881 idempotency_key: readiness.idempotency_key,
2882 completed_batches: checkpoint.completed_batches,
2883 total_batches: checkpoint.total_batches,
2884 blocker_codes: readiness.blocker_codes,
2885 }
2886}
2887
2888fn hawdb_lightning_initial_import_idempotency_key(
2889 checkpoint: &HawDBLightningInitialImportCheckpoint,
2890) -> Option<HawDBLightningInitialImportIdempotencyKey> {
2891 if checkpoint.import_id.is_empty()
2892 || checkpoint.task_id.is_empty()
2893 || checkpoint.fencing_token.is_empty()
2894 || checkpoint.object_digest.is_empty()
2895 {
2896 return None;
2897 }
2898 Some(HawDBLightningInitialImportIdempotencyKey {
2899 import_id: checkpoint.import_id.clone(),
2900 task_id: checkpoint.task_id.clone(),
2901 fencing_token: checkpoint.fencing_token.clone(),
2902 object_digest: checkpoint.object_digest.clone(),
2903 })
2904}
2905
2906fn optional_epoch_regressed(previous: Option<u64>, next: Option<u64>) -> bool {
2907 match (previous, next) {
2908 (Some(_), None) => true,
2909 (Some(previous), Some(next)) => next < previous,
2910 (None, _) => false,
2911 }
2912}
2913
2914fn hawdb_lightning_initial_import_required_search_projection_kinds() -> Vec<SearchProjectionKind> {
2915 vec![
2916 SearchProjectionKind::Memory,
2917 SearchProjectionKind::Message,
2918 SearchProjectionKind::Entity,
2919 SearchProjectionKind::Source,
2920 SearchProjectionKind::SourceChunk,
2921 SearchProjectionKind::Community,
2922 ]
2923}
2924
2925#[derive(Debug, Default)]
2926struct ParsedHawDBLightningGraphStream {
2927 format_version: Option<u64>,
2928 graph_commit_epoch: Option<u64>,
2929 logical_checksum: Option<u64>,
2930 declared_node_count: Option<u64>,
2931 declared_relationship_count: Option<u64>,
2932 node_ids: Vec<u64>,
2933 relationship_ids: Vec<u64>,
2934 relationships: Vec<(u64, u64, u64)>,
2935 nodes: Vec<CanonicalSnapshotNode>,
2936 snapshot_relationships: Vec<CanonicalSnapshotRelationship>,
2937}
2938
2939fn parse_hawdb_lightning_graph_stream_body(
2940 body: &str,
2941 errors: &mut Vec<String>,
2942) -> ParsedHawDBLightningGraphStream {
2943 let mut cursor = GraphStreamCursor::new(body);
2944 let mut parsed = ParsedHawDBLightningGraphStream::default();
2945
2946 match cursor.read_line() {
2947 Some("HAWDB_LIGHTNING_GRAPH_STREAM_V1") => {}
2948 Some(line) => {
2949 errors.push(format!("invalid graph stream header: {line}"));
2950 return parsed;
2951 }
2952 None => {
2953 errors.push("missing graph stream header".to_string());
2954 return parsed;
2955 }
2956 }
2957
2958 parsed.format_version =
2959 cursor.read_tagged_u64("format_version", "graph stream format version", errors);
2960 parsed.graph_commit_epoch =
2961 cursor.read_tagged_u64("graph_commit_epoch", "graph stream commit epoch", errors);
2962 parsed.logical_checksum =
2963 cursor.read_tagged_u64("logical_checksum", "graph stream logical checksum", errors);
2964 parsed.declared_node_count =
2965 cursor.read_tagged_u64("node_count", "graph stream node count", errors);
2966
2967 let node_count = parsed.declared_node_count.unwrap_or(0);
2968 for _ in 0..node_count {
2969 let node_id = cursor.read_node_id(errors);
2970 if let Some(node_id) = node_id {
2971 parsed.node_ids.push(node_id);
2972 }
2973 let stable_id = cursor.read_optional_canonical_value("stable_id", errors);
2974 let label_count = cursor
2975 .read_tagged_u64("label_count", "graph stream label count", errors)
2976 .unwrap_or(0);
2977 let mut labels = Vec::new();
2978 for _ in 0..label_count {
2979 if let Some(label) = cursor.read_canonical_string_line("label", errors) {
2980 labels.push(label);
2981 }
2982 }
2983 let properties = read_graph_stream_properties(&mut cursor, errors);
2984 if let Some(node_id) = node_id {
2985 parsed.nodes.push(CanonicalSnapshotNode {
2986 node_id,
2987 stable_id,
2988 labels,
2989 properties,
2990 });
2991 }
2992 }
2993
2994 parsed.declared_relationship_count = cursor.read_tagged_u64(
2995 "relationship_count",
2996 "graph stream relationship count",
2997 errors,
2998 );
2999 let relationship_count = parsed.declared_relationship_count.unwrap_or(0);
3000 for _ in 0..relationship_count {
3001 let relationship = cursor.read_relationship(errors);
3002 if let Some((relationship_id, source, target)) = relationship {
3003 parsed.relationship_ids.push(relationship_id);
3004 parsed.relationships.push((relationship_id, source, target));
3005 }
3006 let stable_id = cursor.read_optional_canonical_value("stable_id", errors);
3007 let rel_type = cursor
3008 .read_canonical_string_line("relationship_type", errors)
3009 .unwrap_or_default();
3010 let properties = read_graph_stream_properties(&mut cursor, errors);
3011 if let Some((relationship_id, source, target)) = relationship {
3012 parsed
3013 .snapshot_relationships
3014 .push(CanonicalSnapshotRelationship {
3015 relationship_id,
3016 stable_id,
3017 source_node_id: source,
3018 target_node_id: target,
3019 rel_type,
3020 properties,
3021 });
3022 }
3023 }
3024
3025 if !cursor.is_finished() {
3026 let remaining = cursor.remaining_preview();
3027 errors.push(format!("trailing graph stream data: {remaining}"));
3028 }
3029
3030 parsed.relationships = parsed
3031 .snapshot_relationships
3032 .iter()
3033 .map(|relationship| {
3034 (
3035 relationship.relationship_id,
3036 relationship.source_node_id,
3037 relationship.target_node_id,
3038 )
3039 })
3040 .collect();
3041 parsed
3042}
3043
3044fn read_graph_stream_properties(
3045 cursor: &mut GraphStreamCursor<'_>,
3046 errors: &mut Vec<String>,
3047) -> BTreeMap<String, Value> {
3048 let property_count = cursor
3049 .read_tagged_u64("property_count", "graph stream property count", errors)
3050 .unwrap_or(0);
3051 let mut properties = BTreeMap::new();
3052 for _ in 0..property_count {
3053 let property = cursor.read_canonical_string_line("property", errors);
3054 let value = cursor.read_canonical_value(errors);
3055 cursor.expect_byte(b'\n', "graph stream property value terminator", errors);
3056 if let (Some(property), Some(value)) = (property, value) {
3057 properties.insert(property, value);
3058 }
3059 }
3060 properties
3061}
3062
3063struct GraphStreamCursor<'a> {
3064 input: &'a str,
3065 offset: usize,
3066}
3067
3068impl<'a> GraphStreamCursor<'a> {
3069 fn new(input: &'a str) -> Self {
3070 Self { input, offset: 0 }
3071 }
3072
3073 fn is_finished(&self) -> bool {
3074 self.offset >= self.input.len()
3075 }
3076
3077 fn remaining_preview(&self) -> String {
3078 self.input[self.offset..]
3079 .chars()
3080 .take(64)
3081 .collect::<String>()
3082 .replace('\n', "\\n")
3083 }
3084
3085 fn read_line(&mut self) -> Option<&'a str> {
3086 if self.is_finished() {
3087 return None;
3088 }
3089 let remaining = &self.input[self.offset..];
3090 if let Some(line_len) = remaining.find('\n') {
3091 let start = self.offset;
3092 let end = start + line_len;
3093 self.offset = end + 1;
3094 Some(&self.input[start..end])
3095 } else {
3096 let start = self.offset;
3097 self.offset = self.input.len();
3098 Some(&self.input[start..])
3099 }
3100 }
3101
3102 fn read_tagged_u64(&mut self, tag: &str, name: &str, errors: &mut Vec<String>) -> Option<u64> {
3103 let Some(line) = self.read_line() else {
3104 errors.push(format!("missing {name}"));
3105 return None;
3106 };
3107 let Some(raw) = line
3108 .strip_prefix(tag)
3109 .and_then(|line| line.strip_prefix('\t'))
3110 else {
3111 errors.push(format!("expected {tag} line, found {line}"));
3112 return None;
3113 };
3114 parse_api_u64(raw, name, errors)
3115 }
3116
3117 fn read_node_id(&mut self, errors: &mut Vec<String>) -> Option<u64> {
3118 self.read_tagged_u64("node", "graph stream node id", errors)
3119 }
3120
3121 fn read_relationship(&mut self, errors: &mut Vec<String>) -> Option<(u64, u64, u64)> {
3122 let Some(line) = self.read_line() else {
3123 errors.push("missing graph stream relationship".to_string());
3124 return None;
3125 };
3126 let fields = line.split('\t').collect::<Vec<_>>();
3127 let ["relationship", raw_id, raw_source, raw_target] = fields.as_slice() else {
3128 errors.push(format!("invalid graph stream relationship line: {line}"));
3129 return None;
3130 };
3131 let id = parse_api_u64(raw_id, "graph stream relationship id", errors);
3132 let source = parse_api_u64(raw_source, "graph stream relationship source", errors);
3133 let target = parse_api_u64(raw_target, "graph stream relationship target", errors);
3134 match (id, source, target) {
3135 (Some(id), Some(source), Some(target)) => Some((id, source, target)),
3136 _ => None,
3137 }
3138 }
3139
3140 fn read_optional_canonical_value(
3141 &mut self,
3142 prefix: &str,
3143 errors: &mut Vec<String>,
3144 ) -> Option<Value> {
3145 if !self.expect_str(prefix, errors) {
3146 return None;
3147 }
3148 if !self.expect_byte(b'\t', "graph stream optional value separator", errors) {
3149 return None;
3150 }
3151 let value = if self.remaining().starts_with("missing") {
3152 self.offset += "missing".len();
3153 None
3154 } else {
3155 self.read_canonical_value(errors)
3156 };
3157 self.expect_byte(b'\n', "graph stream optional value terminator", errors);
3158 value
3159 }
3160
3161 fn read_canonical_string_line(
3162 &mut self,
3163 prefix: &str,
3164 errors: &mut Vec<String>,
3165 ) -> Option<String> {
3166 if !self.expect_str(prefix, errors) {
3167 return None;
3168 }
3169 if !self.expect_byte(b'\t', "graph stream canonical string separator", errors) {
3170 return None;
3171 }
3172 let value = self.read_length_prefixed_string("graph stream canonical string", errors);
3173 self.expect_byte(b'\n', "graph stream canonical string terminator", errors);
3174 value
3175 }
3176
3177 fn read_canonical_value(&mut self, errors: &mut Vec<String>) -> Option<Value> {
3178 if self.remaining().starts_with("null") {
3179 self.offset += "null".len();
3180 Some(Value::Null)
3181 } else if self.remaining().starts_with("bool:true") {
3182 self.offset += "bool:true".len();
3183 Some(Value::Bool(true))
3184 } else if self.remaining().starts_with("bool:false") {
3185 self.offset += "bool:false".len();
3186 Some(Value::Bool(false))
3187 } else if self.remaining().starts_with("int:") {
3188 self.offset += "int:".len();
3189 self.read_scalar_token()
3190 .and_then(|raw| match raw.parse::<i64>() {
3191 Ok(value) => Some(Value::Int(value)),
3192 Err(_) => {
3193 errors.push(format!("invalid graph stream int value: {raw}"));
3194 None
3195 }
3196 })
3197 } else if self.remaining().starts_with("float:") {
3198 self.offset += "float:".len();
3199 self.read_scalar_token()
3200 .and_then(|raw| match u64::from_str_radix(raw, 16) {
3201 Ok(bits) => Some(Value::Float(f64::from_bits(bits))),
3202 Err(_) => {
3203 errors.push(format!("invalid graph stream float value: {raw}"));
3204 None
3205 }
3206 })
3207 } else if self.remaining().starts_with("string:") {
3208 self.offset += "string:".len();
3209 self.read_length_prefixed_string("graph stream string value", errors)
3210 .map(Value::String)
3211 } else if self.remaining().starts_with("list:") {
3212 self.offset += "list:".len();
3213 let count = self.parse_decimal("graph stream list item count", errors);
3214 if !self.expect_byte(b':', "graph stream list count separator", errors)
3215 || !self.expect_byte(b'[', "graph stream list opener", errors)
3216 {
3217 return None;
3218 }
3219 let mut values = Vec::new();
3220 for _ in 0..count.unwrap_or(0) {
3221 if let Some(value) = self.read_canonical_value(errors) {
3222 values.push(value);
3223 }
3224 self.expect_byte(b';', "graph stream list item terminator", errors);
3225 }
3226 self.expect_byte(b']', "graph stream list closer", errors);
3227 Some(Value::List(values))
3228 } else if self.remaining().starts_with("map:") {
3229 self.offset += "map:".len();
3230 let count = self.parse_decimal("graph stream map item count", errors);
3231 if !self.expect_byte(b':', "graph stream map count separator", errors)
3232 || !self.expect_byte(b'{', "graph stream map opener", errors)
3233 {
3234 return None;
3235 }
3236 let mut values = BTreeMap::new();
3237 for _ in 0..count.unwrap_or(0) {
3238 let key = self.read_length_prefixed_string("graph stream map key", errors);
3239 if !self.expect_byte(b'=', "graph stream map key separator", errors) {
3240 return None;
3241 }
3242 let value = self.read_canonical_value(errors);
3243 self.expect_byte(b';', "graph stream map item terminator", errors);
3244 if let (Some(key), Some(value)) = (key, value) {
3245 values.insert(key, value);
3246 }
3247 }
3248 self.expect_byte(b'}', "graph stream map closer", errors);
3249 Some(Value::Map(values))
3250 } else {
3251 errors.push(format!(
3252 "invalid graph stream canonical value: {}",
3253 self.remaining_preview()
3254 ));
3255 None
3256 }
3257 }
3258
3259 fn read_length_prefixed_string(
3260 &mut self,
3261 name: &str,
3262 errors: &mut Vec<String>,
3263 ) -> Option<String> {
3264 let len = self.parse_decimal(name, errors)?;
3265 if !self.expect_byte(b':', "graph stream length separator", errors) {
3266 return None;
3267 }
3268 let end = self.offset.saturating_add(len as usize);
3269 if end > self.input.len() {
3270 errors.push(format!("{name} exceeds graph stream length"));
3271 self.offset = self.input.len();
3272 return None;
3273 }
3274 if !self.input.is_char_boundary(end) {
3275 errors.push(format!("{name} ends inside a UTF-8 codepoint"));
3276 self.offset = self.input.len();
3277 return None;
3278 }
3279 let value = self.input[self.offset..end].to_string();
3280 self.offset = end;
3281 Some(value)
3282 }
3283
3284 fn read_scalar_token(&mut self) -> Option<&'a str> {
3285 let start = self.offset;
3286 while let Some(byte) = self.current_byte() {
3287 if matches!(byte, b';' | b'\n' | b']' | b'}') {
3288 break;
3289 }
3290 self.offset += 1;
3291 }
3292 (start != self.offset).then_some(&self.input[start..self.offset])
3293 }
3294
3295 fn parse_decimal(&mut self, name: &str, errors: &mut Vec<String>) -> Option<u64> {
3296 let start = self.offset;
3297 while let Some(byte) = self.current_byte() {
3298 if !byte.is_ascii_digit() {
3299 break;
3300 }
3301 self.offset += 1;
3302 }
3303 if start == self.offset {
3304 errors.push(format!("missing {name}"));
3305 return None;
3306 }
3307 match self.input[start..self.offset].parse::<u64>() {
3308 Ok(value) => Some(value),
3309 Err(_) => {
3310 errors.push(format!(
3311 "invalid {name}: {}",
3312 &self.input[start..self.offset]
3313 ));
3314 None
3315 }
3316 }
3317 }
3318
3319 fn expect_str(&mut self, expected: &str, errors: &mut Vec<String>) -> bool {
3320 if self.remaining().starts_with(expected) {
3321 self.offset += expected.len();
3322 true
3323 } else {
3324 errors.push(format!(
3325 "expected {expected}, found {}",
3326 self.remaining_preview()
3327 ));
3328 false
3329 }
3330 }
3331
3332 fn expect_byte(&mut self, expected: u8, name: &str, errors: &mut Vec<String>) -> bool {
3333 if self.current_byte() == Some(expected) {
3334 self.offset += 1;
3335 true
3336 } else {
3337 errors.push(format!("expected {name}"));
3338 false
3339 }
3340 }
3341
3342 fn current_byte(&self) -> Option<u8> {
3343 self.input.as_bytes().get(self.offset).copied()
3344 }
3345
3346 fn remaining(&self) -> &'a str {
3347 &self.input[self.offset..]
3348 }
3349}
3350
3351fn split_graph_stream_checksum(encoded: &str) -> (&str, Option<u64>, Vec<String>) {
3352 let Some((body, footer)) = encoded.rsplit_once("checksum\t") else {
3353 return (
3354 encoded,
3355 None,
3356 vec!["graph stream missing checksum footer".to_string()],
3357 );
3358 };
3359 let raw = footer.trim();
3360 match raw.parse::<u64>() {
3361 Ok(checksum) => (body, Some(checksum), Vec::new()),
3362 Err(_) => (
3363 body,
3364 None,
3365 vec![format!("invalid graph stream checksum: {raw}")],
3366 ),
3367 }
3368}
3369
3370fn parse_api_u64(input: &str, name: &str, errors: &mut Vec<String>) -> Option<u64> {
3371 match input.parse::<u64>() {
3372 Ok(value) => Some(value),
3373 Err(_) => {
3374 errors.push(format!("invalid {name}: {input}"));
3375 None
3376 }
3377 }
3378}
3379
3380fn append_canonical_properties(body: &mut String, properties: &BTreeMap<String, Value>) {
3381 body.push_str(&format!("property_count\t{}\n", properties.len()));
3382 for (property, value) in properties {
3383 append_canonical_string(body, "property", property);
3384 append_canonical_value(body, value);
3385 body.push('\n');
3386 }
3387}
3388
3389fn append_canonical_string(body: &mut String, prefix: &str, value: &str) {
3390 body.push_str(prefix);
3391 body.push('\t');
3392 body.push_str(&value.len().to_string());
3393 body.push(':');
3394 body.push_str(value);
3395 body.push('\n');
3396}
3397
3398fn append_optional_canonical_value(body: &mut String, prefix: &str, value: Option<&Value>) {
3399 body.push_str(prefix);
3400 body.push('\t');
3401 match value {
3402 Some(value) => append_canonical_value(body, value),
3403 None => body.push_str("missing"),
3404 }
3405 body.push('\n');
3406}
3407
3408fn append_canonical_value(body: &mut String, value: &Value) {
3409 match value {
3410 Value::Null => body.push_str("null"),
3411 Value::Bool(value) => body.push_str(if *value { "bool:true" } else { "bool:false" }),
3412 Value::Int(value) => body.push_str(&format!("int:{value}")),
3413 Value::Float(value) => body.push_str(&format!("float:{:016x}", value.to_bits())),
3414 Value::String(value) => {
3415 body.push_str("string:");
3416 body.push_str(&value.len().to_string());
3417 body.push(':');
3418 body.push_str(value);
3419 }
3420 Value::Binary(value) => {
3421 body.push_str("binary:");
3422 body.push_str(&value.len().to_string());
3423 body.push(':');
3424 append_hex(body, value);
3425 }
3426 Value::Uuid(value) => body.push_str(&format!("uuid:{value}")),
3427 Value::List(values) => {
3428 body.push_str(&format!("list:{}:[", values.len()));
3429 for value in values {
3430 append_canonical_value(body, value);
3431 body.push(';');
3432 }
3433 body.push(']');
3434 }
3435 Value::Map(values) => {
3436 body.push_str(&format!("map:{}:{{", values.len()));
3437 for (key, value) in values {
3438 body.push_str(&key.len().to_string());
3439 body.push(':');
3440 body.push_str(key);
3441 body.push('=');
3442 append_canonical_value(body, value);
3443 body.push(';');
3444 }
3445 body.push('}');
3446 }
3447 }
3448}
3449
3450fn append_hex(output: &mut String, bytes: &[u8]) {
3451 const HEX: &[u8; 16] = b"0123456789abcdef";
3452 for byte in bytes {
3453 output.push(HEX[usize::from(byte >> 4)] as char);
3454 output.push(HEX[usize::from(byte & 0x0f)] as char);
3455 }
3456}
3457
3458fn checksum_bytes(bytes: &[u8]) -> u64 {
3459 hawdb_integrity::checksum_u64(bytes)
3460}