Skip to main content

hawdb_readiness/
query_runtime_preflight_report.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Stable result contract for query-runtime preflight execution.
16//!
17//! Hosts open databases and execute probes. This module owns the redacted result
18//! model and JSON encoding so readiness consumers do not depend on the embedded facade.
19
20use crate::embedded_query_report::scan_pruning_report_json;
21use crate::query_runtime_preflight::NowledgeQueryRuntimePreflightProbe;
22use hawdb_core::{HawDBError, RelationalErrorSurface};
23use hawdb_evidence::inventory::REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES;
24use hawdb_route_ownership::graph::REQUIRED_BOUNDED_READ_ROUTES;
25use hawdb_storage::scan::ScanPruningReport;
26use std::collections::{BTreeMap, BTreeSet};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct NowledgeQueryRuntimePreflightReport {
30    pub protocol: String,
31    pub ready: bool,
32    pub database_opened: bool,
33    pub redaction: NowledgeQueryRuntimePreflightRedactionSummary,
34    pub probe_count: usize,
35    pub passed_probe_count: usize,
36    pub failed_probe_count: usize,
37    pub required_route_count: usize,
38    pub covered_route_count: usize,
39    pub covered_routes: Vec<String>,
40    pub missing_required_routes: Vec<String>,
41    pub required_routes_covered: bool,
42    pub unknown_routes: Vec<String>,
43    pub duplicate_routes: Vec<String>,
44    pub route_catalog_version: String,
45    pub route_catalog_digest: String,
46    pub route_coverage_ready: bool,
47    pub route_coverage_blocker_codes: Vec<String>,
48    pub blocker_codes: Vec<String>,
49    pub probes: Vec<NowledgeQueryRuntimePreflightProbeReport>,
50}
51
52impl NowledgeQueryRuntimePreflightReport {
53    pub fn json(&self) -> serde_json::Value {
54        serde_json::json!({
55            "protocol": self.protocol,
56            "ready": self.ready,
57            "database_opened": self.database_opened,
58            "redaction": self.redaction.json(),
59            "probe_count": self.probe_count,
60            "passed_probe_count": self.passed_probe_count,
61            "failed_probe_count": self.failed_probe_count,
62            "required_route_count": self.required_route_count,
63            "covered_route_count": self.covered_route_count,
64            "covered_routes": self.covered_routes,
65            "missing_required_routes": self.missing_required_routes,
66            "required_routes_covered": self.required_routes_covered,
67            "unknown_routes": self.unknown_routes,
68            "duplicate_routes": self.duplicate_routes,
69            "route_catalog_version": self.route_catalog_version,
70            "route_catalog_digest": self.route_catalog_digest,
71            "route_coverage_ready": self.route_coverage_ready,
72            "route_coverage_blocker_codes": self.route_coverage_blocker_codes,
73            "blocker_codes": self.blocker_codes,
74            "probes": self.probes.iter().map(NowledgeQueryRuntimePreflightProbeReport::json).collect::<Vec<_>>(),
75        })
76    }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Default)]
80pub struct NowledgeQueryRuntimePreflightRedactionSummary {
81    pub rows_copied: bool,
82    pub parameters_copied: bool,
83    pub local_paths_copied: bool,
84    pub raw_errors_copied: bool,
85}
86
87impl NowledgeQueryRuntimePreflightRedactionSummary {
88    pub const fn ready(&self) -> bool {
89        !self.rows_copied
90            && !self.parameters_copied
91            && !self.local_paths_copied
92            && !self.raw_errors_copied
93    }
94
95    pub fn json(&self) -> serde_json::Value {
96        serde_json::json!({
97            "ready": self.ready(),
98            "rows_copied": self.rows_copied,
99            "parameters_copied": self.parameters_copied,
100            "local_paths_copied": self.local_paths_copied,
101            "raw_errors_copied": self.raw_errors_copied,
102        })
103    }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct NowledgeQueryRuntimePreflightProbeReport {
108    pub name: String,
109    pub route: Option<String>,
110    pub query_family: Option<String>,
111    pub ready: bool,
112    pub success: bool,
113    pub output_row_count: usize,
114    pub selected_plan_fingerprint: Option<String>,
115    pub search_mode: Option<String>,
116    pub selected_plan_operator_counts: BTreeMap<String, usize>,
117    pub selected_plan_class_counts: BTreeMap<String, usize>,
118    pub optimizer_decision_count: usize,
119    pub optimizer_rule_event_count: usize,
120    pub plan_cache_lookup: Option<String>,
121    pub plan_cache_bypass_reason: Option<String>,
122    pub plan_cache_cacheable: bool,
123    pub plan_cache_hit: bool,
124    pub plan_cache_miss: bool,
125    pub plan_cache_bypassed: bool,
126    pub work_priority: Option<String>,
127    pub work_class: Option<String>,
128    pub estimated_operations: Option<usize>,
129    pub max_rows: Option<usize>,
130    pub detection_row_cap: Option<usize>,
131    pub row_limit_enforced_before_output: bool,
132    pub operator_row_cap_enabled: bool,
133    pub blocking_operator_kinds: Vec<String>,
134    pub scan_pruning_reports: Vec<ScanPruningReport>,
135    pub pruned_scan_count: usize,
136    pub error_class: Option<String>,
137    pub blocker_codes: Vec<String>,
138}
139
140impl NowledgeQueryRuntimePreflightProbeReport {
141    pub fn json(&self) -> serde_json::Value {
142        let mut value = serde_json::json!({
143            "name": self.name,
144            "route": self.route,
145            "query_family": self.query_family,
146            "ready": self.ready,
147            "success": self.success,
148            "blocker_codes": self.blocker_codes,
149        });
150        let object = value
151            .as_object_mut()
152            .expect("query runtime preflight probe report is an object");
153        if self.success {
154            object.insert(
155                "output_row_count".to_string(),
156                serde_json::json!(self.output_row_count),
157            );
158            object.insert(
159                "selected_plan_fingerprint".to_string(),
160                serde_json::json!(self.selected_plan_fingerprint),
161            );
162            object.insert(
163                "search_mode".to_string(),
164                serde_json::json!(self.search_mode),
165            );
166            object.insert(
167                "selected_plan_operator_counts".to_string(),
168                serde_json::json!(self.selected_plan_operator_counts),
169            );
170            object.insert(
171                "selected_plan_class_counts".to_string(),
172                serde_json::json!(self.selected_plan_class_counts),
173            );
174            object.insert(
175                "optimizer_decision_count".to_string(),
176                serde_json::json!(self.optimizer_decision_count),
177            );
178            object.insert(
179                "optimizer_rule_event_count".to_string(),
180                serde_json::json!(self.optimizer_rule_event_count),
181            );
182            object.insert(
183                "plan_cache_lookup".to_string(),
184                serde_json::json!(self.plan_cache_lookup),
185            );
186            object.insert(
187                "plan_cache".to_string(),
188                serde_json::json!({
189                    "lookup": self.plan_cache_lookup,
190                    "bypass_reason": self.plan_cache_bypass_reason,
191                    "cacheable": self.plan_cache_cacheable,
192                    "hit": self.plan_cache_hit,
193                    "miss": self.plan_cache_miss,
194                    "bypassed": self.plan_cache_bypassed,
195                }),
196            );
197            object.insert(
198                "work_request".to_string(),
199                serde_json::json!({
200                    "priority": self.work_priority,
201                    "class": self.work_class,
202                    "estimated_operations": self.estimated_operations,
203                }),
204            );
205            object.insert(
206                "execution_profile".to_string(),
207                serde_json::json!({
208                    "max_rows": self.max_rows,
209                    "detection_row_cap": self.detection_row_cap,
210                    "row_limit_enforced_before_output": self.row_limit_enforced_before_output,
211                    "operator_row_cap_enabled": self.operator_row_cap_enabled,
212                    "blocking_operator_kinds": self.blocking_operator_kinds,
213                    "scan_pruning_report_count": self.scan_pruning_reports.len(),
214                    "pruned_scan_count": self.pruned_scan_count,
215                    "scan_pruning_reports": self.scan_pruning_reports.iter().map(scan_pruning_report_json).collect::<Vec<_>>(),
216                }),
217            );
218        } else {
219            object.insert(
220                "error_class".to_string(),
221                serde_json::json!(self.error_class),
222            );
223        }
224        value
225    }
226}
227
228#[doc(hidden)]
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct NowledgeQueryRuntimeRouteCoverage {
231    pub required_route_count: usize,
232    pub covered_route_count: usize,
233    pub covered_routes: Vec<String>,
234    pub missing_required_routes: Vec<String>,
235    pub required_routes_covered: bool,
236    pub unknown_routes: Vec<String>,
237    pub duplicate_routes: Vec<String>,
238    pub ready: bool,
239    pub blocker_codes: Vec<String>,
240}
241
242#[doc(hidden)]
243pub fn nowledge_query_runtime_route_coverage(
244    probes: &[NowledgeQueryRuntimePreflightProbe],
245) -> NowledgeQueryRuntimeRouteCoverage {
246    let required_routes = REQUIRED_BOUNDED_READ_ROUTES
247        .iter()
248        .copied()
249        .collect::<BTreeSet<_>>();
250    let mut route_counts = BTreeMap::<&str, usize>::new();
251    for route in probes.iter().filter_map(|probe| probe.route.as_deref()) {
252        *route_counts.entry(route).or_default() += 1;
253    }
254    let observed_routes = route_counts.keys().copied().collect::<BTreeSet<_>>();
255    let covered_routes = REQUIRED_BOUNDED_READ_ROUTES
256        .iter()
257        .copied()
258        .filter(|route| observed_routes.contains(route))
259        .map(str::to_string)
260        .collect::<Vec<_>>();
261    let missing_required_routes = REQUIRED_BOUNDED_READ_ROUTES
262        .iter()
263        .copied()
264        .filter(|route| !observed_routes.contains(route))
265        .map(str::to_string)
266        .collect::<Vec<_>>();
267    let unknown_routes = observed_routes
268        .iter()
269        .filter(|route| !required_routes.contains(**route))
270        .map(|route| (*route).to_string())
271        .collect::<Vec<_>>();
272    let duplicate_routes = route_counts
273        .iter()
274        .filter(|(_, count)| **count > 1)
275        .map(|(route, _)| (*route).to_string())
276        .collect::<Vec<_>>();
277    let required_routes_covered = missing_required_routes.is_empty();
278    let mut blocker_codes = Vec::new();
279    if !required_routes_covered {
280        blocker_codes.push("query_runtime_route_coverage_missing".to_string());
281    }
282    if !unknown_routes.is_empty() {
283        blocker_codes.push("query_runtime_unknown_routes".to_string());
284    }
285
286    NowledgeQueryRuntimeRouteCoverage {
287        required_route_count: REQUIRED_BOUNDED_READ_ROUTES.len(),
288        covered_route_count: covered_routes.len(),
289        covered_routes,
290        missing_required_routes,
291        required_routes_covered,
292        unknown_routes,
293        duplicate_routes,
294        ready: blocker_codes.is_empty(),
295        blocker_codes,
296    }
297}
298
299#[doc(hidden)]
300pub fn query_runtime_preflight_blocker_codes(
301    probe_count: usize,
302    failed_probe_count: usize,
303    route_coverage: &NowledgeQueryRuntimeRouteCoverage,
304) -> Vec<String> {
305    let mut blockers = Vec::new();
306    if probe_count == 0 {
307        blockers.push("query_runtime_probes_missing".to_string());
308    }
309    if failed_probe_count > 0 {
310        blockers.push("query_runtime_probe_failed".to_string());
311    }
312    blockers.extend(route_coverage.blocker_codes.iter().cloned());
313    blockers
314}
315
316#[doc(hidden)]
317pub fn query_runtime_probe_blocker_codes(
318    probe: &NowledgeQueryRuntimePreflightProbe,
319    scan_pruning_report_count: usize,
320    pruned_scan_count: usize,
321    output_row_count: usize,
322) -> Vec<String> {
323    let mut blockers = query_runtime_probe_identity_blocker_codes(probe);
324    if probe.require_scan_pruning && scan_pruning_report_count < probe.min_scan_pruning_reports {
325        blockers.push("scan_pruning_report_missing".to_string());
326    }
327    if probe.require_pruned && pruned_scan_count == 0 {
328        blockers.push("scan_pruning_not_pruned".to_string());
329    }
330    if let Some(max_output_rows) = probe.max_output_rows
331        && output_row_count > max_output_rows
332    {
333        blockers.push("output_row_count_exceeded".to_string());
334    }
335    blockers
336}
337
338fn query_runtime_probe_identity_blocker_codes(
339    probe: &NowledgeQueryRuntimePreflightProbe,
340) -> Vec<String> {
341    let mut blockers = Vec::new();
342    if probe.name.trim().is_empty() || probe.name == "unnamed" {
343        blockers.push("query_runtime_probe_name_missing".to_string());
344    }
345    match probe.route.as_deref() {
346        Some(route) if REQUIRED_BOUNDED_READ_ROUTES.contains(&route) => {}
347        Some(_) => blockers.push("query_runtime_probe_unknown_route".to_string()),
348        None => blockers.push("query_runtime_probe_route_missing".to_string()),
349    }
350    match probe.query_family.as_deref() {
351        Some(family) if REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES.contains(&family) => {}
352        Some(_) => blockers.push("query_runtime_probe_unknown_query_family".to_string()),
353        None => blockers.push("query_runtime_probe_query_family_missing".to_string()),
354    }
355    blockers
356}
357
358#[doc(hidden)]
359pub const fn hawdb_error_class(error: &HawDBError) -> &'static str {
360    match error {
361        HawDBError::UnsupportedStorageFormat(_) => "unsupported_storage_format",
362        HawDBError::Parse(_) => "parse",
363        HawDBError::Semantic(_) => "semantic",
364        HawDBError::Storage(_)
365        | HawDBError::Constraint {
366            surface: RelationalErrorSurface::Storage,
367            ..
368        }
369        | HawDBError::Schema {
370            surface: RelationalErrorSurface::Storage,
371            ..
372        }
373        | HawDBError::FileDescriptors(_)
374        | HawDBError::StorageIntegrity(_)
375        | HawDBError::WalRecoveryIo { .. }
376        | HawDBError::PublishOutcomeUnknown { .. }
377        | HawDBError::ProjectionBusy
378        | HawDBError::SearchProjectionMismatch { .. }
379        | HawDBError::AppendSequenceExhausted { .. }
380        | HawDBError::BranchBusy { .. }
381        | HawDBError::BranchReclamationBlocked { .. } => "storage",
382        HawDBError::Execution(_)
383        | HawDBError::Constraint {
384            surface: RelationalErrorSurface::Execution,
385            ..
386        }
387        | HawDBError::Schema {
388            surface: RelationalErrorSurface::Execution,
389            ..
390        }
391        | HawDBError::BranchEvidenceBudgetExceeded { .. }
392        | HawDBError::ReadBudgetExceeded(_)
393        | HawDBError::WalRecordLimitExceeded(_)
394        | HawDBError::RuntimeAdmissionRefused(_)
395        | HawDBError::RuntimeIoWaveReservationExceeded { .. }
396        | HawDBError::RuntimeTaskStopped(_)
397        | HawDBError::ReadOnly { .. }
398        | HawDBError::ResourceBudgetExceeded(_)
399        | HawDBError::GraphExpansionCandidateLimitExceeded { .. }
400        | HawDBError::GraphExpansionPayloadLimitExceeded { .. }
401        | HawDBError::TransactionConflict { .. }
402        | HawDBError::TransactionRetryRequired(_)
403        | HawDBError::TransactionReadDependencyRefused { .. }
404        | HawDBError::BranchCommandUnsupported { .. }
405        | HawDBError::SearchProjectionRebuildRefused { .. }
406        | HawDBError::SearchProjectionOwnershipMarkerCorrupt { .. }
407        | HawDBError::SearchProjectionOwnershipMismatch { .. }
408        | HawDBError::SearchProjectionEpochAdvanceRefused { .. }
409        | HawDBError::SearchProjectionPrefixBehindSource { .. }
410        | HawDBError::SearchProjectionBatchBudgetExceeded { .. }
411        | HawDBError::SearchProductionQualificationGraphEpochMismatch { .. }
412        | HawDBError::SystemSchemaUpgradeRequired { .. }
413        | HawDBError::SearchProductionQualificationRefused { .. } => "execution",
414        HawDBError::CapabilityUnavailable { .. } => "capability_unavailable",
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    #[test]
423    fn failed_probe_never_serializes_execution_details() {
424        let report = NowledgeQueryRuntimePreflightProbeReport {
425            name: "malformed".to_string(),
426            route: Some("graph-overview".to_string()),
427            query_family: None,
428            ready: false,
429            success: false,
430            output_row_count: 1,
431            selected_plan_fingerprint: Some("plan".to_string()),
432            search_mode: Some("disabled".to_string()),
433            selected_plan_operator_counts: BTreeMap::new(),
434            selected_plan_class_counts: BTreeMap::new(),
435            optimizer_decision_count: 1,
436            optimizer_rule_event_count: 1,
437            plan_cache_lookup: Some("hit".to_string()),
438            plan_cache_bypass_reason: None,
439            plan_cache_cacheable: true,
440            plan_cache_hit: true,
441            plan_cache_miss: false,
442            plan_cache_bypassed: false,
443            work_priority: Some("interactive".to_string()),
444            work_class: Some("query".to_string()),
445            estimated_operations: Some(1),
446            max_rows: Some(1),
447            detection_row_cap: Some(2),
448            row_limit_enforced_before_output: true,
449            operator_row_cap_enabled: true,
450            blocking_operator_kinds: Vec::new(),
451            scan_pruning_reports: Vec::new(),
452            pruned_scan_count: 0,
453            error_class: Some("parse".to_string()),
454            blocker_codes: vec!["query_runtime_probe_failed".to_string()],
455        };
456
457        assert_eq!(
458            report.json(),
459            serde_json::json!({
460                "name": "malformed",
461                "route": "graph-overview",
462                "query_family": null,
463                "ready": false,
464                "success": false,
465                "blocker_codes": ["query_runtime_probe_failed"],
466                "error_class": "parse",
467            })
468        );
469    }
470
471    #[test]
472    fn redaction_is_ready_only_without_raw_execution_data() {
473        assert!(NowledgeQueryRuntimePreflightRedactionSummary::default().ready());
474        assert!(NowledgeQueryRuntimePreflightRedactionSummary {
475            rows_copied: true,
476            ..NowledgeQueryRuntimePreflightRedactionSummary::default()
477        }
478        .json()["ready"]
479            .as_bool()
480            .is_some_and(|ready| !ready));
481    }
482
483    #[test]
484    fn route_coverage_rejects_missing_and_unknown_routes_without_rejecting_duplicates() {
485        let probe = NowledgeQueryRuntimePreflightProbe::new("overview", "MATCH (n) RETURN n")
486            .with_route(REQUIRED_BOUNDED_READ_ROUTES[0])
487            .with_query_family(REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES[0]);
488        let duplicate = probe.clone();
489        let unknown = NowledgeQueryRuntimePreflightProbe::new("unknown", "MATCH (n) RETURN n")
490            .with_route("unknown-route")
491            .with_query_family(REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES[0]);
492
493        let coverage = nowledge_query_runtime_route_coverage(&[probe, duplicate, unknown]);
494
495        assert!(!coverage.ready);
496        assert_eq!(coverage.duplicate_routes.len(), 1);
497        assert_eq!(coverage.unknown_routes, vec!["unknown-route"]);
498        assert!(coverage
499            .blocker_codes
500            .contains(&"query_runtime_route_coverage_missing".to_string()));
501        assert!(coverage
502            .blocker_codes
503            .contains(&"query_runtime_unknown_routes".to_string()));
504    }
505}