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