1use hawdb_analytics::ProjectedGraph;
21use hawdb_core::{HawDBError, RelationalErrorSurface, Result, Value};
22use hawdb_executor::{QueryOutput, Row};
23use std::collections::BTreeMap;
24
25mod primary;
26#[doc(hidden)]
27pub use primary::{CompatibilityPrimaryEngine, CompatibilityPrimarySession};
28
29mod external_shadow;
30mod external_shadow_gate;
31mod external_shadow_smoke;
32#[doc(hidden)]
33pub mod fixture_contract;
34mod inventory_gate;
35mod nowledge_fixture;
36#[doc(hidden)]
37pub mod nowledge_inventory;
38
39#[cfg(test)]
40use external_shadow::{
41 decode_external_projected_graph_response, decode_external_query_response,
42 decode_external_ready_response, decode_external_session_response,
43};
44pub use external_shadow::{
45 external_shadow_json_from_value, external_shadow_ready_missing_capabilities,
46 external_shadow_trace_health_from_bundle, external_shadow_trace_report_json,
47 external_shadow_value_from_json, ExternalShadowCommand, ExternalShadowProjectGraphReply,
48 ExternalShadowProjectGraphRequest, ExternalShadowProtocolBackend, ExternalShadowProtocolServer,
49 ExternalShadowReady, ExternalShadowStatementRequest, ExternalShadowTraceHealth,
50 ExternalShadowTraceSummary, REQUIRED_EXTERNAL_SHADOW_CAPABILITIES,
51};
52#[doc(hidden)]
53pub use external_shadow_gate::{
54 add_shadow_ready_report, add_shadow_run_report, add_shadow_trace_report,
55 assess_external_shadow_cutover_evidence, cutover_evidence_is_eligible,
56 ExternalShadowCutoverEvidence,
57};
58#[doc(hidden)]
59pub use external_shadow_smoke::{
60 enforce_external_shadow_adapter_smoke_requirements, external_shadow_adapter_smoke_fixture,
61 external_shadow_adapter_smoke_report_json, is_self_shadow_command, should_run_shadow_ready,
62};
63pub use inventory_gate::{
64 assess_compatibility_cypher_migration_gate_bundle,
65 assess_compatibility_cypher_migration_gate_bundle_with_rollback,
66 assess_compatibility_migration_gate, assess_compatibility_migration_gate_bundle,
67 assess_compatibility_migration_gate_with_rollback, assess_query_inventory_coverage,
68 assess_query_inventory_cypher_coverage, assess_query_inventory_gate,
69 build_compatibility_query_inventory, build_compatibility_query_inventory_from_json,
70 build_compatibility_query_inventory_from_json_str, compatibility_cutover_report_to_json,
71 compatibility_inventory_coverage_report_to_json, compatibility_inventory_gate_report_to_json,
72 compatibility_migration_gate_bundle_to_json, compatibility_migration_gate_report_to_json,
73 compatibility_query_inventory_to_json, CompatibilityCutoverDecision,
74 CompatibilityInventoryCoveragePolicy, CompatibilityInventoryCoverageReport,
75 CompatibilityInventoryGateReport, CompatibilityMigrationGateBundle,
76 CompatibilityMigrationGateReport, CompatibilityQueryCallSite, CompatibilityQueryInventory,
77 CompatibilityQueryInventoryItem, CompatibilityRollbackEvidence,
78};
79pub use nowledge_fixture::{nowledge_memory_core_fixture, nowledge_memory_core_inventory};
80pub use nowledge_inventory::{
81 scan_nowledge_query_inventory_cypher_coverage_detail_to_json,
82 scan_nowledge_query_inventory_cypher_coverage_to_json, NowledgeCypherMigrationGateJsonOptions,
83};
84
85const DEFAULT_FLOAT_ABS_TOLERANCE: f64 = 1.0e-9;
86pub const EXTERNAL_SHADOW_PROTOCOL_VERSION: u64 = 1;
87
88#[derive(Debug, Clone, PartialEq)]
89pub struct CompatibilityFixture {
90 pub name: String,
91 pub setup: Vec<CypherFixtureStatement>,
92 pub checks: Vec<CompatibilityCheck>,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct CypherFixtureStatement {
97 pub cypher: String,
98 pub parameters: BTreeMap<String, Value>,
99}
100
101#[derive(Debug, Clone, PartialEq)]
102pub enum CompatibilityCheck {
103 Cypher(CypherFixtureCheck),
104 ProjectedGraph(ProjectedGraphFixtureCheck),
105}
106
107#[derive(Debug, Clone, PartialEq)]
108pub struct CypherFixtureCheck {
109 pub name: String,
110 pub setup_queries: Vec<CypherFixtureStatement>,
111 pub statement: CypherFixtureStatement,
112 pub expected_rows: ExpectedRows,
113 pub expected_error: Option<ExpectedErrorClass>,
114 pub effect_query: Option<CypherFixtureStatement>,
115 pub effect_expected_rows: Option<ExpectedRows>,
116 pub expected_plan_contains: Vec<String>,
117 pub tolerance: CompatibilityTolerance,
118 pub execution_mode: CypherExecutionMode,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum ExpectedRows {
123 Exact(Vec<Row>),
124 Unordered(Vec<Row>),
125 RowCount(usize),
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum ExpectedErrorClass {
130 Parse,
131 Semantic,
132 Storage,
133 FileDescriptors,
134 Execution,
135 CapabilityUnavailable,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum CypherExecutionMode {
140 Database,
141 Session,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct CompatibilityTolerance {
146 pub float_abs: f64,
147}
148
149#[derive(Debug, Clone, PartialEq)]
150pub struct ProjectedGraphFixtureCheck {
151 pub name: String,
152 pub rel_type: Option<String>,
153 pub expected_node_count: usize,
154 pub expected_edge_count: usize,
155 pub expected_incoming: Vec<(u64, Vec<u64>)>,
156 pub expected_communities: Vec<(u64, u64)>,
157 pub expected_hierarchical_communities: Vec<(usize, u64, u64)>,
158 pub expected_page_rank_scores: Vec<(u64, f64)>,
159 pub page_rank_top_node: Option<u64>,
160 pub tolerance: CompatibilityTolerance,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct CompatibilityReport {
165 pub fixture: String,
166 pub checks: Vec<CompatibilityCheckReport>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct CompatibilityCheckReport {
171 pub name: String,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct CompatibilityShadowReport {
176 pub fixture: String,
177 pub shadow_engine: String,
178 pub primary_checks: Vec<CompatibilityCheckReport>,
179 pub shadow_checks: Vec<CompatibilityShadowCheckReport>,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct CompatibilityShadowCheckReport {
184 pub name: String,
185 pub status: CompatibilityShadowStatus,
186 pub primary_only_reason: Option<String>,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum CompatibilityShadowStatus {
191 Matched,
192 PrimaryOnly,
193}
194
195#[derive(Debug, Clone, PartialEq)]
196pub enum ProjectedGraphShadowResult {
197 Output(ProjectedGraphShadowOutput),
198 PrimaryOnly { reason: Option<String> },
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub struct CompatibilityCutoverPolicy {
203 pub require_shadow_for_all_checks: bool,
204 pub min_matched_checks: usize,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct CompatibilityCutoverReport {
209 pub fixture: String,
210 pub shadow_engine: String,
211 pub decision: CompatibilityCutoverDecision,
212 pub primary_check_count: usize,
213 pub total_checks: usize,
214 pub matched_checks: usize,
215 pub primary_only_checks: Vec<String>,
216 pub primary_only_reasons: BTreeMap<String, String>,
217 pub blockers: Vec<String>,
218}
219
220pub trait CompatibilityShadowEngine {
221 fn name(&self) -> &str;
222 fn execute(&mut self, statement: &CypherFixtureStatement) -> Result<QueryOutput>;
223 fn execute_with_context(
224 &mut self,
225 statement: &CypherFixtureStatement,
226 _context: ShadowRequestContext,
227 ) -> Result<QueryOutput> {
228 self.execute(statement)
229 }
230
231 fn execute_session(
232 &mut self,
233 statements: &[CypherFixtureStatement],
234 ) -> Result<Vec<QueryOutput>> {
235 statements
236 .iter()
237 .map(|statement| self.execute(statement))
238 .collect()
239 }
240 fn execute_session_with_context(
241 &mut self,
242 statements: &[CypherFixtureStatement],
243 _context: ShadowRequestContext,
244 ) -> Result<Vec<QueryOutput>> {
245 self.execute_session(statements)
246 }
247
248 fn project_graph(
249 &mut self,
250 _check: &ProjectedGraphFixtureCheck,
251 ) -> Result<Option<ProjectedGraphShadowOutput>> {
252 Ok(None)
253 }
254 fn project_graph_with_context(
255 &mut self,
256 check: &ProjectedGraphFixtureCheck,
257 _context: ShadowRequestContext,
258 ) -> Result<Option<ProjectedGraphShadowOutput>> {
259 self.project_graph(check)
260 }
261 fn project_graph_result_with_context(
262 &mut self,
263 check: &ProjectedGraphFixtureCheck,
264 context: ShadowRequestContext,
265 ) -> Result<ProjectedGraphShadowResult> {
266 match self.project_graph_with_context(check, context)? {
267 Some(output) => Ok(ProjectedGraphShadowResult::Output(output)),
268 None => Ok(ProjectedGraphShadowResult::PrimaryOnly { reason: None }),
269 }
270 }
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub struct ShadowRequestContext<'a> {
275 pub fixture: &'a str,
276 pub check: Option<&'a str>,
277 pub phase: ShadowRequestPhase,
278 pub statement_index: Option<usize>,
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub enum ShadowRequestPhase {
283 FixtureSetup,
284 CheckSetup,
285 Statement,
286 Session,
287 Effect,
288 ProjectGraph,
289}
290
291#[derive(Debug, Clone, PartialEq)]
292pub struct ProjectedGraphShadowOutput {
293 pub node_count: usize,
294 pub edge_count: usize,
295 pub incoming: Vec<(u64, Vec<u64>)>,
296 pub communities: Vec<(u64, u64)>,
297 pub hierarchical_communities: Vec<(usize, u64, u64)>,
298 pub page_rank_scores: Vec<(u64, f64)>,
299 pub page_rank_top_node: Option<u64>,
300}
301
302impl Default for CompatibilityTolerance {
303 fn default() -> Self {
304 Self {
305 float_abs: DEFAULT_FLOAT_ABS_TOLERANCE,
306 }
307 }
308}
309
310impl Default for CompatibilityCutoverPolicy {
311 fn default() -> Self {
312 Self {
313 require_shadow_for_all_checks: true,
314 min_matched_checks: 1,
315 }
316 }
317}
318fn is_mutation_statement(cypher: &str) -> bool {
319 let upper = cypher.to_ascii_uppercase();
320 upper.contains(" CREATE ")
321 || upper.starts_with("CREATE ")
322 || upper.contains(" MERGE ")
323 || upper.starts_with("MERGE ")
324 || upper.contains(" SET ")
325 || upper.starts_with("SET ")
326 || upper.contains(" DELETE ")
327 || upper.starts_with("DELETE ")
328 || upper.contains(" DETACH DELETE ")
329 || upper.contains(" ON CREATE SET ")
330 || upper.contains(" ON MATCH SET ")
331 || upper.contains("DROP ")
332}
333
334impl CypherFixtureStatement {
335 pub fn new(cypher: impl Into<String>) -> Self {
336 Self {
337 cypher: cypher.into(),
338 parameters: BTreeMap::new(),
339 }
340 }
341
342 pub fn with_parameters(cypher: impl Into<String>, parameters: BTreeMap<String, Value>) -> Self {
343 Self {
344 cypher: cypher.into(),
345 parameters,
346 }
347 }
348}
349
350impl CypherFixtureCheck {
351 pub fn expect_rows(
352 name: impl Into<String>,
353 statement: CypherFixtureStatement,
354 expected_rows: ExpectedRows,
355 ) -> Self {
356 Self {
357 name: name.into(),
358 setup_queries: Vec::new(),
359 statement,
360 expected_rows,
361 expected_error: None,
362 effect_query: None,
363 effect_expected_rows: None,
364 expected_plan_contains: Vec::new(),
365 tolerance: CompatibilityTolerance::default(),
366 execution_mode: CypherExecutionMode::Database,
367 }
368 }
369
370 pub fn expect_error(
371 name: impl Into<String>,
372 statement: CypherFixtureStatement,
373 expected_error: ExpectedErrorClass,
374 ) -> Self {
375 Self {
376 name: name.into(),
377 setup_queries: Vec::new(),
378 statement,
379 expected_rows: ExpectedRows::RowCount(0),
380 expected_error: Some(expected_error),
381 effect_query: None,
382 effect_expected_rows: None,
383 expected_plan_contains: Vec::new(),
384 tolerance: CompatibilityTolerance::default(),
385 execution_mode: CypherExecutionMode::Database,
386 }
387 }
388
389 pub fn with_plan_contains(mut self, expected_plan_contains: Vec<String>) -> Self {
390 self.expected_plan_contains = expected_plan_contains;
391 self
392 }
393
394 pub fn with_tolerance(mut self, tolerance: CompatibilityTolerance) -> Self {
395 self.tolerance = tolerance;
396 self
397 }
398
399 pub fn with_session_execution(mut self) -> Self {
400 self.execution_mode = CypherExecutionMode::Session;
401 self
402 }
403
404 pub fn with_setup_query(mut self, setup_query: CypherFixtureStatement) -> Self {
405 self.setup_queries.push(setup_query);
406 self
407 }
408
409 pub fn with_effect_query(
410 mut self,
411 effect_query: CypherFixtureStatement,
412 effect_expected_rows: ExpectedRows,
413 ) -> Self {
414 self.effect_query = Some(effect_query);
415 self.effect_expected_rows = Some(effect_expected_rows);
416 self
417 }
418}
419
420impl ExpectedErrorClass {
421 fn from_error(error: &HawDBError) -> Self {
422 match error {
423 HawDBError::Parse(_) => Self::Parse,
424 HawDBError::Semantic(_) => Self::Semantic,
425 HawDBError::FileDescriptors(_) => Self::FileDescriptors,
426 HawDBError::UnsupportedStorageFormat(_)
427 | HawDBError::Storage(_)
428 | HawDBError::Constraint {
429 surface: RelationalErrorSurface::Storage,
430 ..
431 }
432 | HawDBError::Schema {
433 surface: RelationalErrorSurface::Storage,
434 ..
435 }
436 | HawDBError::StorageIntegrity(_)
437 | HawDBError::WalRecoveryIo { .. }
438 | HawDBError::PublishOutcomeUnknown { .. }
439 | HawDBError::ProjectionBusy
440 | HawDBError::SearchProjectionMismatch { .. }
441 | HawDBError::AppendSequenceExhausted { .. }
442 | HawDBError::BranchBusy { .. }
443 | HawDBError::BranchReclamationBlocked { .. } => Self::Storage,
444 HawDBError::Execution(_)
445 | HawDBError::Constraint {
446 surface: RelationalErrorSurface::Execution,
447 ..
448 }
449 | HawDBError::Schema {
450 surface: RelationalErrorSurface::Execution,
451 ..
452 }
453 | HawDBError::BranchEvidenceBudgetExceeded { .. }
454 | HawDBError::ReadBudgetExceeded(_)
455 | HawDBError::WalRecordLimitExceeded(_)
456 | HawDBError::RuntimeAdmissionRefused(_)
457 | HawDBError::RuntimeIoWaveReservationExceeded { .. }
458 | HawDBError::RuntimeTaskStopped(_)
459 | HawDBError::ReadOnly { .. }
460 | HawDBError::ResourceBudgetExceeded(_)
461 | HawDBError::GraphExpansionCandidateLimitExceeded { .. }
462 | HawDBError::GraphExpansionPayloadLimitExceeded { .. }
463 | HawDBError::TransactionConflict { .. }
464 | HawDBError::TransactionRetryRequired(_)
465 | HawDBError::TransactionReadDependencyRefused { .. }
466 | HawDBError::BranchCommandUnsupported { .. }
467 | HawDBError::SearchProjectionRebuildRefused { .. }
468 | HawDBError::SearchProjectionOwnershipMarkerCorrupt { .. }
469 | HawDBError::SearchProjectionOwnershipMismatch { .. }
470 | HawDBError::SearchProjectionEpochAdvanceRefused { .. }
471 | HawDBError::SearchProjectionPrefixBehindSource { .. }
472 | HawDBError::SearchProjectionBatchBudgetExceeded { .. }
473 | HawDBError::SearchProductionQualificationGraphEpochMismatch { .. }
474 | HawDBError::SystemSchemaUpgradeRequired { .. }
475 | HawDBError::SearchProductionQualificationRefused { .. } => Self::Execution,
476 HawDBError::CapabilityUnavailable { .. } => Self::CapabilityUnavailable,
477 }
478 }
479}
480
481pub fn run_compatibility_fixture(
482 db: &mut impl CompatibilityPrimaryEngine,
483 fixture: &CompatibilityFixture,
484) -> Result<CompatibilityReport> {
485 run_primary_setup(db, fixture)?;
486
487 Ok(CompatibilityReport {
488 fixture: fixture.name.clone(),
489 checks: run_primary_checks(db, fixture)?
490 .into_iter()
491 .map(|check| check.report)
492 .collect(),
493 })
494}
495
496pub fn run_compatibility_fixture_with_shadow(
497 db: &mut impl CompatibilityPrimaryEngine,
498 fixture: &CompatibilityFixture,
499 shadow: &mut impl CompatibilityShadowEngine,
500) -> Result<CompatibilityShadowReport> {
501 run_primary_setup(db, fixture)?;
502 run_shadow_setup(fixture, shadow)?;
503
504 let mut primary_checks = Vec::new();
505 let mut shadow_checks = Vec::new();
506 for check in &fixture.checks {
507 match check {
508 CompatibilityCheck::Cypher(check) => {
509 let primary = run_cypher_check(db, fixture, check)?;
510 primary_checks.push(CompatibilityCheckReport {
511 name: check.name.clone(),
512 });
513 run_shadow_cypher_check(fixture, check, shadow, &primary)?;
514 shadow_checks.push(CompatibilityShadowCheckReport {
515 name: check.name.clone(),
516 status: CompatibilityShadowStatus::Matched,
517 primary_only_reason: None,
518 });
519 }
520 CompatibilityCheck::ProjectedGraph(check) => {
521 let primary = run_projected_graph_check(db, fixture, check)?;
522 primary_checks.push(CompatibilityCheckReport {
523 name: check.name.clone(),
524 });
525 let (status, primary_only_reason) = match shadow.project_graph_result_with_context(
526 check,
527 ShadowRequestContext {
528 fixture: &fixture.name,
529 check: Some(&check.name),
530 phase: ShadowRequestPhase::ProjectGraph,
531 statement_index: None,
532 },
533 )? {
534 ProjectedGraphShadowResult::Output(shadow_output) => {
535 compare_projected_graph_shadow(
536 fixture,
537 check,
538 shadow.name(),
539 &primary,
540 &shadow_output,
541 )?;
542 (CompatibilityShadowStatus::Matched, None)
543 }
544 ProjectedGraphShadowResult::PrimaryOnly { reason } => {
545 (CompatibilityShadowStatus::PrimaryOnly, reason)
546 }
547 };
548 shadow_checks.push(CompatibilityShadowCheckReport {
549 name: check.name.clone(),
550 status,
551 primary_only_reason,
552 });
553 }
554 }
555 }
556
557 Ok(CompatibilityShadowReport {
558 fixture: fixture.name.clone(),
559 shadow_engine: shadow.name().to_string(),
560 primary_checks,
561 shadow_checks,
562 })
563}
564
565pub fn assess_compatibility_cutover(
566 report: &CompatibilityShadowReport,
567 policy: CompatibilityCutoverPolicy,
568) -> CompatibilityCutoverReport {
569 let total_checks = report.shadow_checks.len();
570 let matched_checks = report
571 .shadow_checks
572 .iter()
573 .filter(|check| check.status == CompatibilityShadowStatus::Matched)
574 .count();
575 let primary_only_checks = report
576 .shadow_checks
577 .iter()
578 .filter(|check| check.status == CompatibilityShadowStatus::PrimaryOnly)
579 .map(|check| check.name.clone())
580 .collect::<Vec<_>>();
581 let primary_only_reasons = report
582 .shadow_checks
583 .iter()
584 .filter(|check| check.status == CompatibilityShadowStatus::PrimaryOnly)
585 .filter_map(|check| {
586 check
587 .primary_only_reason
588 .as_ref()
589 .map(|reason| (check.name.clone(), reason.clone()))
590 })
591 .collect::<BTreeMap<_, _>>();
592 let mut blockers = Vec::new();
593
594 if total_checks == 0 {
595 blockers.push("no compatibility checks were executed".to_string());
596 }
597 if report.primary_checks.len() != total_checks {
598 blockers.push(format!(
599 "primary check count {} does not match shadow check count {}",
600 report.primary_checks.len(),
601 total_checks
602 ));
603 }
604 if matched_checks < policy.min_matched_checks {
605 blockers.push(format!(
606 "matched check count {} is below required minimum {}",
607 matched_checks, policy.min_matched_checks
608 ));
609 }
610 if policy.require_shadow_for_all_checks && !primary_only_checks.is_empty() {
611 let primary_only_descriptions = report
612 .shadow_checks
613 .iter()
614 .filter(|check| check.status == CompatibilityShadowStatus::PrimaryOnly)
615 .map(|check| match &check.primary_only_reason {
616 Some(reason) => format!("{} ({})", check.name, reason),
617 None => check.name.clone(),
618 })
619 .collect::<Vec<_>>();
620 blockers.push(format!(
621 "shadow engine '{}' did not cover checks: {}",
622 report.shadow_engine,
623 primary_only_descriptions.join(", ")
624 ));
625 }
626
627 CompatibilityCutoverReport {
628 fixture: report.fixture.clone(),
629 shadow_engine: report.shadow_engine.clone(),
630 decision: if blockers.is_empty() {
631 CompatibilityCutoverDecision::Ready
632 } else {
633 CompatibilityCutoverDecision::Blocked
634 },
635 primary_check_count: report.primary_checks.len(),
636 total_checks,
637 matched_checks,
638 primary_only_checks,
639 primary_only_reasons,
640 blockers,
641 }
642}
643fn run_primary_setup(
644 db: &mut impl CompatibilityPrimaryEngine,
645 fixture: &CompatibilityFixture,
646) -> Result<()> {
647 for statement in &fixture.setup {
648 db.query_with_params(&statement.cypher, &statement.parameters)
649 .map_err(|error| {
650 HawDBError::or_stop(&error, || {
651 HawDBError::Execution(format!(
652 "fixture '{}' setup failed for '{}': {error}",
653 fixture.name, statement.cypher
654 ))
655 })
656 })?;
657 }
658 Ok(())
659}
660
661fn run_shadow_setup(
662 fixture: &CompatibilityFixture,
663 shadow: &mut impl CompatibilityShadowEngine,
664) -> Result<()> {
665 for statement in &fixture.setup {
666 shadow
667 .execute_with_context(
668 statement,
669 ShadowRequestContext {
670 fixture: &fixture.name,
671 check: None,
672 phase: ShadowRequestPhase::FixtureSetup,
673 statement_index: None,
674 },
675 )
676 .map_err(|error| {
677 HawDBError::or_stop(&error, || {
678 HawDBError::Execution(format!(
679 "fixture '{}' shadow engine '{}' setup failed for '{}': {error}",
680 fixture.name,
681 shadow.name(),
682 statement.cypher
683 ))
684 })
685 })?;
686 }
687 Ok(())
688}
689
690#[derive(Debug, Clone, PartialEq, Eq)]
691struct PrimaryCheckOutput {
692 report: CompatibilityCheckReport,
693}
694
695#[derive(Debug, Clone, PartialEq, Eq)]
696enum CypherCheckOutcome {
697 Rows {
698 output: QueryOutput,
699 effect: Option<QueryOutput>,
700 },
701 Error(ExpectedErrorClass),
702}
703
704fn run_primary_checks(
705 db: &mut impl CompatibilityPrimaryEngine,
706 fixture: &CompatibilityFixture,
707) -> Result<Vec<PrimaryCheckOutput>> {
708 let mut reports = Vec::new();
709 for check in &fixture.checks {
710 match check {
711 CompatibilityCheck::Cypher(check) => {
712 run_cypher_check(db, fixture, check)?;
713 reports.push(PrimaryCheckOutput {
714 report: CompatibilityCheckReport {
715 name: check.name.clone(),
716 },
717 });
718 }
719 CompatibilityCheck::ProjectedGraph(check) => {
720 run_projected_graph_check(db, fixture, check)?;
721 reports.push(PrimaryCheckOutput {
722 report: CompatibilityCheckReport {
723 name: check.name.clone(),
724 },
725 });
726 }
727 }
728 }
729 Ok(reports)
730}
731
732fn run_shadow_cypher_check(
733 fixture: &CompatibilityFixture,
734 check: &CypherFixtureCheck,
735 shadow: &mut impl CompatibilityShadowEngine,
736 primary: &CypherCheckOutcome,
737) -> Result<()> {
738 if check.execution_mode == CypherExecutionMode::Session {
739 return run_shadow_cypher_session_check(fixture, check, shadow, primary);
740 }
741 for setup_query in &check.setup_queries {
742 shadow
743 .execute_with_context(
744 setup_query,
745 ShadowRequestContext {
746 fixture: &fixture.name,
747 check: Some(&check.name),
748 phase: ShadowRequestPhase::CheckSetup,
749 statement_index: None,
750 },
751 )
752 .map_err(|error| {
753 HawDBError::or_stop(&error, || {
754 HawDBError::Execution(format!(
755 "fixture '{}' check '{}' shadow engine '{}' setup failed for '{}': {error}",
756 fixture.name,
757 check.name,
758 shadow.name(),
759 setup_query.cypher
760 ))
761 })
762 })?;
763 }
764 let shadow_output = shadow.execute_with_context(
765 &check.statement,
766 ShadowRequestContext {
767 fixture: &fixture.name,
768 check: Some(&check.name),
769 phase: ShadowRequestPhase::Statement,
770 statement_index: None,
771 },
772 );
773 match (primary, check.expected_error) {
774 (CypherCheckOutcome::Error(expected), Some(_)) => {
775 let Err(error) = shadow_output else {
776 return Err(HawDBError::Execution(format!(
777 "fixture '{}' check '{}' shadow engine '{}' expected {:?} error for '{}', got success",
778 fixture.name,
779 check.name,
780 shadow.name(),
781 expected,
782 check.statement.cypher
783 )));
784 };
785 let actual = ExpectedErrorClass::from_error(&error);
786 if actual != *expected {
787 return Err(HawDBError::Execution(format!(
788 "fixture '{}' check '{}' shadow engine '{}' expected {:?} error for '{}', got {:?}: {error}",
789 fixture.name,
790 check.name,
791 shadow.name(),
792 expected,
793 check.statement.cypher,
794 actual
795 )));
796 }
797 }
798 (
799 CypherCheckOutcome::Rows {
800 output: primary_output,
801 effect: primary_effect,
802 },
803 None,
804 ) => {
805 let shadow_output = shadow_output.map_err(|error| {
806 HawDBError::or_stop(&error, || {
807 HawDBError::Execution(format!(
808 "fixture '{}' check '{}' shadow engine '{}' failed for '{}': {error}",
809 fixture.name,
810 check.name,
811 shadow.name(),
812 check.statement.cypher
813 ))
814 })
815 })?;
816 check
817 .expected_rows
818 .assert_matches(
819 &fixture.name,
820 &format!("{} shadow {}", check.name, shadow.name()),
821 &check.statement.cypher,
822 &shadow_output,
823 check.tolerance,
824 )
825 .map_err(|error| {
826 HawDBError::or_stop(&error, || {
827 HawDBError::Execution(format!(
828 "fixture '{}' check '{}' shadow engine '{}' row validation failed: {error}",
829 fixture.name,
830 check.name,
831 shadow.name()
832 ))
833 })
834 })?;
835 check.expected_rows.assert_shadow_matches_primary(
836 &fixture.name,
837 &check.name,
838 shadow.name(),
839 primary_output,
840 &shadow_output,
841 check.tolerance,
842 )?;
843 if let Some(effect_query) = &check.effect_query {
844 let Some(primary_effect) = primary_effect else {
845 return Err(HawDBError::Execution(format!(
846 "fixture '{}' check '{}' missing primary effect output",
847 fixture.name, check.name
848 )));
849 };
850 let shadow_effect = shadow
851 .execute_with_context(
852 effect_query,
853 ShadowRequestContext {
854 fixture: &fixture.name,
855 check: Some(&check.name),
856 phase: ShadowRequestPhase::Effect,
857 statement_index: None,
858 },
859 )
860 .map_err(|error| HawDBError::or_stop(&error, || HawDBError::Execution(format!(
861 "fixture '{}' check '{}' shadow engine '{}' failed effect query '{}': {error}",
862 fixture.name,
863 check.name,
864 shadow.name(),
865 effect_query.cypher
866 ))))?;
867 let expected = check.effect_expected_rows.as_ref().ok_or_else(|| {
868 HawDBError::Execution(format!(
869 "fixture '{}' check '{}' effect query is missing expected rows",
870 fixture.name, check.name
871 ))
872 })?;
873 expected.assert_matches(
874 &fixture.name,
875 &format!("{} effect shadow {}", check.name, shadow.name()),
876 &effect_query.cypher,
877 &shadow_effect,
878 check.tolerance,
879 )?;
880 expected.assert_shadow_matches_primary(
881 &fixture.name,
882 &format!("{} effect", check.name),
883 shadow.name(),
884 primary_effect,
885 &shadow_effect,
886 check.tolerance,
887 )?;
888 }
889 }
890 _ => {
891 return Err(HawDBError::Execution(format!(
892 "fixture '{}' check '{}' has inconsistent primary outcome and expectation",
893 fixture.name, check.name
894 )));
895 }
896 }
897 Ok(())
898}
899
900fn run_shadow_cypher_session_check(
901 fixture: &CompatibilityFixture,
902 check: &CypherFixtureCheck,
903 shadow: &mut impl CompatibilityShadowEngine,
904 primary: &CypherCheckOutcome,
905) -> Result<()> {
906 let mut statements = check.setup_queries.clone();
907 statements.push(check.statement.clone());
908 if let Some(effect_query) = &check.effect_query {
909 statements.push(effect_query.clone());
910 }
911 let outputs = shadow
912 .execute_session_with_context(
913 &statements,
914 ShadowRequestContext {
915 fixture: &fixture.name,
916 check: Some(&check.name),
917 phase: ShadowRequestPhase::Session,
918 statement_index: None,
919 },
920 )
921 .map_err(|error| {
922 HawDBError::or_stop(&error, || {
923 HawDBError::Execution(format!(
924 "fixture '{}' check '{}' shadow engine '{}' session failed: {error}",
925 fixture.name,
926 check.name,
927 shadow.name()
928 ))
929 })
930 })?;
931 let statement_index = check.setup_queries.len();
932 let shadow_output = outputs.get(statement_index).ok_or_else(|| {
933 HawDBError::Execution(format!(
934 "fixture '{}' check '{}' shadow engine '{}' session returned no statement output",
935 fixture.name,
936 check.name,
937 shadow.name()
938 ))
939 })?;
940
941 let CypherCheckOutcome::Rows {
942 output: primary_output,
943 effect: primary_effect,
944 } = primary
945 else {
946 return Err(HawDBError::Execution(format!(
947 "fixture '{}' check '{}' has inconsistent session primary outcome",
948 fixture.name, check.name
949 )));
950 };
951
952 check.expected_rows.assert_matches(
953 &fixture.name,
954 &format!("{} shadow {}", check.name, shadow.name()),
955 &check.statement.cypher,
956 shadow_output,
957 check.tolerance,
958 )?;
959 check.expected_rows.assert_shadow_matches_primary(
960 &fixture.name,
961 &check.name,
962 shadow.name(),
963 primary_output,
964 shadow_output,
965 check.tolerance,
966 )?;
967
968 if let Some(effect_query) = &check.effect_query {
969 let Some(primary_effect) = primary_effect else {
970 return Err(HawDBError::Execution(format!(
971 "fixture '{}' check '{}' missing primary effect output",
972 fixture.name, check.name
973 )));
974 };
975 let effect_index = statements.len() - 1;
976 let shadow_effect = outputs.get(effect_index).ok_or_else(|| {
977 HawDBError::Execution(format!(
978 "fixture '{}' check '{}' shadow engine '{}' session returned no effect output",
979 fixture.name,
980 check.name,
981 shadow.name()
982 ))
983 })?;
984 let expected = check.effect_expected_rows.as_ref().ok_or_else(|| {
985 HawDBError::Execution(format!(
986 "fixture '{}' check '{}' effect query is missing expected rows",
987 fixture.name, check.name
988 ))
989 })?;
990 expected.assert_matches(
991 &fixture.name,
992 &format!("{} effect shadow {}", check.name, shadow.name()),
993 &effect_query.cypher,
994 shadow_effect,
995 check.tolerance,
996 )?;
997 expected.assert_shadow_matches_primary(
998 &fixture.name,
999 &format!("{} effect", check.name),
1000 shadow.name(),
1001 primary_effect,
1002 shadow_effect,
1003 check.tolerance,
1004 )?;
1005 }
1006
1007 Ok(())
1008}
1009
1010fn run_cypher_check(
1011 db: &mut impl CompatibilityPrimaryEngine,
1012 fixture: &CompatibilityFixture,
1013 check: &CypherFixtureCheck,
1014) -> Result<CypherCheckOutcome> {
1015 if check.execution_mode == CypherExecutionMode::Session {
1016 return run_cypher_session_check(db, fixture, check);
1017 }
1018 for setup_query in &check.setup_queries {
1019 db.query_with_params(&setup_query.cypher, &setup_query.parameters)
1020 .map_err(|error| {
1021 HawDBError::or_stop(&error, || {
1022 HawDBError::Execution(format!(
1023 "fixture '{}' check '{}' setup failed for '{}': {error}",
1024 fixture.name, check.name, setup_query.cypher
1025 ))
1026 })
1027 })?;
1028 }
1029 let output = db.query_with_params(&check.statement.cypher, &check.statement.parameters);
1030 if let Some(expected_error) = check.expected_error {
1031 let error = match output {
1032 Ok(output) => {
1033 return Err(HawDBError::Execution(format!(
1034 "fixture '{}' check '{}' expected {:?} error for '{}', got rows {:?}",
1035 fixture.name, check.name, expected_error, check.statement.cypher, output.rows
1036 )));
1037 }
1038 Err(error) => error,
1039 };
1040 let actual = ExpectedErrorClass::from_error(&error);
1041 if actual != expected_error {
1042 return Err(HawDBError::Execution(format!(
1043 "fixture '{}' check '{}' expected {:?} error for '{}', got {:?}: {error}",
1044 fixture.name, check.name, expected_error, check.statement.cypher, actual
1045 )));
1046 }
1047 return Ok(CypherCheckOutcome::Error(expected_error));
1048 }
1049
1050 let output = output?;
1051 check.expected_rows.assert_matches(
1052 &fixture.name,
1053 &check.name,
1054 &check.statement.cypher,
1055 &output,
1056 check.tolerance,
1057 )?;
1058
1059 if !check.expected_plan_contains.is_empty() {
1060 let plan =
1061 db.explain_plan_with_params(&check.statement.cypher, &check.statement.parameters)?;
1062 for needle in &check.expected_plan_contains {
1063 if !plan.contains(needle) {
1064 return Err(HawDBError::Execution(format!(
1065 "fixture '{}' check '{}' expected plan to contain '{}', got:\n{}",
1066 fixture.name, check.name, needle, plan
1067 )));
1068 }
1069 }
1070 }
1071
1072 let effect = if let Some(effect_query) = &check.effect_query {
1073 let effect = db.query_with_params(&effect_query.cypher, &effect_query.parameters)?;
1074 let expected = check.effect_expected_rows.as_ref().ok_or_else(|| {
1075 HawDBError::Execution(format!(
1076 "fixture '{}' check '{}' effect query is missing expected rows",
1077 fixture.name, check.name
1078 ))
1079 })?;
1080 expected.assert_matches(
1081 &fixture.name,
1082 &format!("{} effect", check.name),
1083 &effect_query.cypher,
1084 &effect,
1085 check.tolerance,
1086 )?;
1087 Some(effect)
1088 } else {
1089 None
1090 };
1091
1092 Ok(CypherCheckOutcome::Rows { output, effect })
1093}
1094
1095fn run_cypher_session_check(
1096 db: &mut impl CompatibilityPrimaryEngine,
1097 fixture: &CompatibilityFixture,
1098 check: &CypherFixtureCheck,
1099) -> Result<CypherCheckOutcome> {
1100 let mut session = db.session();
1101 for setup_query in &check.setup_queries {
1102 session
1103 .query_with_params(&setup_query.cypher, &setup_query.parameters)
1104 .map_err(|error| {
1105 HawDBError::or_stop(&error, || {
1106 HawDBError::Execution(format!(
1107 "fixture '{}' check '{}' session setup failed for '{}': {error}",
1108 fixture.name, check.name, setup_query.cypher
1109 ))
1110 })
1111 })?;
1112 }
1113
1114 let output = session.query_with_params(&check.statement.cypher, &check.statement.parameters)?;
1115 check.expected_rows.assert_matches(
1116 &fixture.name,
1117 &check.name,
1118 &check.statement.cypher,
1119 &output,
1120 check.tolerance,
1121 )?;
1122
1123 let effect = if let Some(effect_query) = &check.effect_query {
1124 let effect = session.query_with_params(&effect_query.cypher, &effect_query.parameters)?;
1125 let expected = check.effect_expected_rows.as_ref().ok_or_else(|| {
1126 HawDBError::Execution(format!(
1127 "fixture '{}' check '{}' effect query is missing expected rows",
1128 fixture.name, check.name
1129 ))
1130 })?;
1131 expected.assert_matches(
1132 &fixture.name,
1133 &format!("{} effect", check.name),
1134 &effect_query.cypher,
1135 &effect,
1136 check.tolerance,
1137 )?;
1138 Some(effect)
1139 } else {
1140 None
1141 };
1142
1143 Ok(CypherCheckOutcome::Rows { output, effect })
1144}
1145
1146fn run_projected_graph_check(
1147 db: &impl CompatibilityPrimaryEngine,
1148 fixture: &CompatibilityFixture,
1149 check: &ProjectedGraphFixtureCheck,
1150) -> Result<ProjectedGraphShadowOutput> {
1151 let graph = db.project_graph(check.rel_type.as_deref())?;
1152 let output = projected_graph_shadow_output(&graph, check);
1153 assert_projected_graph_matches_fixture(fixture, check, &output)?;
1154 Ok(output)
1155}
1156
1157#[doc(hidden)]
1158pub fn projected_graph_shadow_output(
1159 graph: &ProjectedGraph,
1160 check: &ProjectedGraphFixtureCheck,
1161) -> ProjectedGraphShadowOutput {
1162 let page_rank_scores = graph
1163 .page_rank(Default::default())
1164 .into_iter()
1165 .map(|score| (score.node.0, score.score))
1166 .collect::<Vec<_>>();
1167 ProjectedGraphShadowOutput {
1168 node_count: graph.node_count(),
1169 edge_count: graph.edge_count(),
1170 incoming: check
1171 .expected_incoming
1172 .iter()
1173 .map(|(node, _)| {
1174 let sources = graph
1175 .incoming_sources(hawdb_storage::NodeId(*node))
1176 .map(|sources| sources.map(|source| source.0).collect::<Vec<_>>())
1177 .unwrap_or_default();
1178 (*node, sources)
1179 })
1180 .collect(),
1181 communities: if check.expected_communities.is_empty() {
1182 Vec::new()
1183 } else {
1184 graph
1185 .louvain_communities(Default::default())
1186 .into_iter()
1187 .map(|assignment| (assignment.node.0, assignment.community.0))
1188 .collect()
1189 },
1190 hierarchical_communities: if check.expected_hierarchical_communities.is_empty() {
1191 Vec::new()
1192 } else {
1193 graph
1194 .hierarchical_louvain_communities(Default::default())
1195 .into_iter()
1196 .map(|assignment| (assignment.level, assignment.node.0, assignment.community.0))
1197 .collect()
1198 },
1199 page_rank_top_node: page_rank_scores.first().map(|(node, _)| *node),
1200 page_rank_scores,
1201 }
1202}
1203
1204fn assert_projected_graph_matches_fixture(
1205 fixture: &CompatibilityFixture,
1206 check: &ProjectedGraphFixtureCheck,
1207 output: &ProjectedGraphShadowOutput,
1208) -> Result<()> {
1209 if output.node_count != check.expected_node_count {
1210 return Err(HawDBError::Execution(format!(
1211 "fixture '{}' check '{}' expected {} projected nodes, got {}",
1212 fixture.name, check.name, check.expected_node_count, output.node_count
1213 )));
1214 }
1215 if output.edge_count != check.expected_edge_count {
1216 return Err(HawDBError::Execution(format!(
1217 "fixture '{}' check '{}' expected {} projected edges, got {}",
1218 fixture.name, check.name, check.expected_edge_count, output.edge_count
1219 )));
1220 }
1221 for (node, expected_sources) in &check.expected_incoming {
1222 let actual = output
1223 .incoming
1224 .iter()
1225 .find(|(candidate, _)| candidate == node)
1226 .map(|(_, sources)| sources.clone())
1227 .unwrap_or_default();
1228 if actual != *expected_sources {
1229 return Err(HawDBError::Execution(format!(
1230 "fixture '{}' check '{}' expected incoming sources {:?} for node {}, got {:?}",
1231 fixture.name, check.name, expected_sources, node, actual
1232 )));
1233 }
1234 }
1235
1236 if let Some(expected_node) = check.page_rank_top_node
1237 && output.page_rank_top_node != Some(expected_node)
1238 {
1239 return Err(HawDBError::Execution(format!(
1240 "fixture '{}' check '{}' expected PageRank top node {}, got {:?}",
1241 fixture.name, check.name, expected_node, output.page_rank_top_node
1242 )));
1243 }
1244 if !check.expected_communities.is_empty() {
1245 let communities = output
1246 .communities
1247 .iter()
1248 .copied()
1249 .collect::<BTreeMap<_, _>>();
1250 for (node, expected_community) in &check.expected_communities {
1251 let actual = communities.get(node).copied();
1252 if actual != Some(*expected_community) {
1253 return Err(HawDBError::Execution(format!(
1254 "fixture '{}' check '{}' expected community {} for node {}, got {:?}",
1255 fixture.name, check.name, expected_community, node, actual
1256 )));
1257 }
1258 }
1259 }
1260 if !check.expected_hierarchical_communities.is_empty() {
1261 let communities = output
1262 .hierarchical_communities
1263 .iter()
1264 .copied()
1265 .map(|(level, node, community)| ((level, node), community))
1266 .collect::<BTreeMap<_, _>>();
1267 for (level, node, expected_community) in &check.expected_hierarchical_communities {
1268 let actual = communities.get(&(*level, *node)).copied();
1269 if actual != Some(*expected_community) {
1270 return Err(HawDBError::Execution(format!(
1271 "fixture '{}' check '{}' expected level {} community {} for node {}, got {:?}",
1272 fixture.name, check.name, level, expected_community, node, actual
1273 )));
1274 }
1275 }
1276 }
1277 if !check.expected_page_rank_scores.is_empty() {
1278 let scores = output
1279 .page_rank_scores
1280 .iter()
1281 .copied()
1282 .collect::<BTreeMap<_, _>>();
1283 for (node, expected_score) in &check.expected_page_rank_scores {
1284 let actual = scores.get(node).copied();
1285 let Some(actual_score) = actual else {
1286 return Err(HawDBError::Execution(format!(
1287 "fixture '{}' check '{}' expected PageRank score for node {}, got none",
1288 fixture.name, check.name, node
1289 )));
1290 };
1291 if !float_matches(actual_score, *expected_score, check.tolerance.float_abs) {
1292 return Err(HawDBError::Execution(format!(
1293 "fixture '{}' check '{}' expected PageRank score {} for node {}, got {}",
1294 fixture.name, check.name, expected_score, node, actual_score
1295 )));
1296 }
1297 }
1298 }
1299
1300 Ok(())
1301}
1302
1303fn compare_projected_graph_shadow(
1304 fixture: &CompatibilityFixture,
1305 check: &ProjectedGraphFixtureCheck,
1306 shadow_engine: &str,
1307 primary: &ProjectedGraphShadowOutput,
1308 shadow: &ProjectedGraphShadowOutput,
1309) -> Result<()> {
1310 assert_projected_graph_matches_fixture(fixture, check, shadow).map_err(|error| {
1311 HawDBError::or_stop(&error, || {
1312 HawDBError::Execution(format!(
1313 "fixture '{}' check '{}' shadow engine '{}' projected graph validation failed: {error}",
1314 fixture.name, check.name, shadow_engine
1315 ))
1316 })
1317 })?;
1318 if !projected_graph_outputs_match(primary, shadow, check.tolerance) {
1319 return Err(HawDBError::Execution(format!(
1320 "fixture '{}' check '{}' shadow engine '{}' projected graph mismatch: primary {:?}, shadow {:?}",
1321 fixture.name, check.name, shadow_engine, primary, shadow
1322 )));
1323 }
1324 Ok(())
1325}
1326
1327impl ExpectedRows {
1328 fn assert_matches(
1329 &self,
1330 fixture_name: &str,
1331 check_name: &str,
1332 cypher: &str,
1333 output: &QueryOutput,
1334 tolerance: CompatibilityTolerance,
1335 ) -> Result<()> {
1336 match self {
1337 ExpectedRows::Exact(expected) => {
1338 let actual = output.rows.clone().into_rows();
1339 if !rows_match_ordered(expected, &actual, tolerance) {
1340 return Err(row_mismatch_error(
1341 fixture_name,
1342 check_name,
1343 cypher,
1344 expected,
1345 &actual,
1346 ));
1347 }
1348 }
1349 ExpectedRows::Unordered(expected) => {
1350 let mut actual = output.rows.clone().into_rows();
1351 let expected_matches = rows_match_unordered(expected, &actual, tolerance);
1352 if !expected_matches {
1353 let mut expected = expected.clone();
1354 expected.sort();
1355 actual.sort();
1356 return Err(row_mismatch_error(
1357 fixture_name,
1358 check_name,
1359 cypher,
1360 &expected,
1361 &actual,
1362 ));
1363 }
1364 }
1365 ExpectedRows::RowCount(expected) => {
1366 if output.rows.len() != *expected {
1367 return Err(HawDBError::Execution(format!(
1368 "fixture '{}' check '{}' expected {} rows for '{}', got {}",
1369 fixture_name,
1370 check_name,
1371 expected,
1372 cypher,
1373 output.rows.len()
1374 )));
1375 }
1376 }
1377 }
1378 Ok(())
1379 }
1380
1381 fn assert_shadow_matches_primary(
1382 &self,
1383 fixture_name: &str,
1384 check_name: &str,
1385 shadow_engine: &str,
1386 primary: &QueryOutput,
1387 shadow: &QueryOutput,
1388 tolerance: CompatibilityTolerance,
1389 ) -> Result<()> {
1390 match self {
1391 ExpectedRows::Exact(_) => {
1392 let primary_rows = primary.rows.clone().into_rows();
1393 let shadow_rows = shadow.rows.clone().into_rows();
1394 if !rows_match_ordered(&primary_rows, &shadow_rows, tolerance) {
1395 return Err(shadow_mismatch_error(
1396 fixture_name,
1397 check_name,
1398 shadow_engine,
1399 &primary_rows,
1400 &shadow_rows,
1401 ));
1402 }
1403 }
1404 ExpectedRows::Unordered(_) => {
1405 let mut primary_rows = primary.rows.clone().into_rows();
1406 let mut shadow_rows = shadow.rows.clone().into_rows();
1407 if !rows_match_unordered(&primary_rows, &shadow_rows, tolerance) {
1408 primary_rows.sort();
1409 shadow_rows.sort();
1410 return Err(shadow_mismatch_error(
1411 fixture_name,
1412 check_name,
1413 shadow_engine,
1414 &primary_rows,
1415 &shadow_rows,
1416 ));
1417 }
1418 }
1419 ExpectedRows::RowCount(_) => {
1420 if primary.rows.len() != shadow.rows.len() {
1421 return Err(HawDBError::Execution(format!(
1422 "fixture '{}' check '{}' shadow engine '{}' row count mismatch: primary {}, shadow {}",
1423 fixture_name,
1424 check_name,
1425 shadow_engine,
1426 primary.rows.len(),
1427 shadow.rows.len()
1428 )));
1429 }
1430 }
1431 }
1432 Ok(())
1433 }
1434}
1435
1436fn row_mismatch_error(
1437 fixture_name: &str,
1438 check_name: &str,
1439 cypher: &str,
1440 expected: &[Row],
1441 actual: &[Row],
1442) -> HawDBError {
1443 HawDBError::Execution(format!(
1444 "fixture '{}' check '{}' row mismatch for '{}': expected {:?}, got {:?}",
1445 fixture_name, check_name, cypher, expected, actual
1446 ))
1447}
1448
1449fn rows_match_ordered(expected: &[Row], actual: &[Row], tolerance: CompatibilityTolerance) -> bool {
1450 expected.len() == actual.len()
1451 && expected
1452 .iter()
1453 .zip(actual)
1454 .all(|(expected, actual)| rows_match(expected, actual, tolerance))
1455}
1456
1457fn rows_match_unordered(
1458 expected: &[Row],
1459 actual: &[Row],
1460 tolerance: CompatibilityTolerance,
1461) -> bool {
1462 if expected.len() != actual.len() {
1463 return false;
1464 }
1465 let mut used = vec![false; actual.len()];
1466 for expected_row in expected {
1467 let Some(index) = actual.iter().enumerate().position(|(index, actual_row)| {
1468 !used[index] && rows_match(expected_row, actual_row, tolerance)
1469 }) else {
1470 return false;
1471 };
1472 used[index] = true;
1473 }
1474 true
1475}
1476
1477fn rows_match(expected: &Row, actual: &Row, tolerance: CompatibilityTolerance) -> bool {
1478 expected.len() == actual.len()
1479 && expected.iter().all(|(key, expected_value)| {
1480 actual
1481 .get(key)
1482 .is_some_and(|actual_value| values_match(expected_value, actual_value, tolerance))
1483 })
1484}
1485
1486fn values_match(expected: &Value, actual: &Value, tolerance: CompatibilityTolerance) -> bool {
1487 match (expected, actual) {
1488 (Value::Float(expected), Value::Float(actual)) => {
1489 float_matches(*expected, *actual, tolerance.float_abs)
1490 }
1491 (Value::List(expected), Value::List(actual)) => {
1492 expected.len() == actual.len()
1493 && expected
1494 .iter()
1495 .zip(actual)
1496 .all(|(expected, actual)| values_match(expected, actual, tolerance))
1497 }
1498 (Value::Map(expected), Value::Map(actual)) => {
1499 expected.len() == actual.len()
1500 && expected.iter().all(|(key, expected)| {
1501 actual
1502 .get(key)
1503 .is_some_and(|actual| values_match(expected, actual, tolerance))
1504 })
1505 }
1506 _ => expected == actual,
1507 }
1508}
1509
1510fn float_matches(left: f64, right: f64, tolerance: f64) -> bool {
1511 if left == right {
1512 return true;
1513 }
1514 left.is_finite() && right.is_finite() && (left - right).abs() <= tolerance
1515}
1516
1517fn projected_graph_outputs_match(
1518 primary: &ProjectedGraphShadowOutput,
1519 shadow: &ProjectedGraphShadowOutput,
1520 tolerance: CompatibilityTolerance,
1521) -> bool {
1522 primary.node_count == shadow.node_count
1523 && primary.edge_count == shadow.edge_count
1524 && primary.incoming == shadow.incoming
1525 && primary.communities == shadow.communities
1526 && primary.hierarchical_communities == shadow.hierarchical_communities
1527 && primary.page_rank_top_node == shadow.page_rank_top_node
1528 && page_rank_scores_match(
1529 &primary.page_rank_scores,
1530 &shadow.page_rank_scores,
1531 tolerance,
1532 )
1533}
1534
1535fn page_rank_scores_match(
1536 primary: &[(u64, f64)],
1537 shadow: &[(u64, f64)],
1538 tolerance: CompatibilityTolerance,
1539) -> bool {
1540 primary.len() == shadow.len()
1541 && primary.iter().zip(shadow).all(
1542 |((primary_node, primary_score), (shadow_node, shadow_score))| {
1543 primary_node == shadow_node
1544 && float_matches(*primary_score, *shadow_score, tolerance.float_abs)
1545 },
1546 )
1547}
1548
1549fn shadow_mismatch_error(
1550 fixture_name: &str,
1551 check_name: &str,
1552 shadow_engine: &str,
1553 primary: &[Row],
1554 shadow: &[Row],
1555) -> HawDBError {
1556 HawDBError::Execution(format!(
1557 "fixture '{}' check '{}' shadow engine '{}' row mismatch: primary {:?}, shadow {:?}",
1558 fixture_name, check_name, shadow_engine, primary, shadow
1559 ))
1560}
1561
1562#[cfg(test)]
1563mod differential;
1564#[cfg(test)]
1565mod primary_tests;
1566#[cfg(test)]
1567mod test_support;
1568#[cfg(test)]
1569mod tests;