1use std::collections::BTreeMap;
16use std::str::FromStr;
17
18use hawdb_qos::{
19 BackgroundWorkDecision, BackgroundWorkHint, BackgroundWorkPlan, LocalQosPolicy,
20 LocalQosSnapshot, LocalQosState, QosAdmission, QosAdmissionCode, WorkClass, WorkPriority,
21 WorkRequest,
22};
23use hawdb_search::{
24 SearchCandidateSetReport, SearchFallbackReasonCode, SearchFusionWeights, SearchMatchedSpan,
25 SearchMode, SearchProjectionFreshness, SearchResultSet, SearchRetrieverCandidateSetReport,
26 SearchTruncationReasonCode,
27};
28
29use crate::{KnowledgeEntity, KnowledgeGraphContextPath};
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct KnowledgeRetrievalRequest {
33 pub query_text: String,
34 pub query_embedding: Option<Vec<f32>>,
35 pub mode: SearchMode,
36 pub limit: usize,
37 pub offset: usize,
38 pub rank_window: Option<usize>,
39 pub search_fusion_weights: SearchFusionWeights,
40 pub metadata_filters: BTreeMap<String, String>,
41 pub candidate_limit: Option<usize>,
42 pub candidate_scoring: KnowledgeCandidateScoringPolicy,
43 pub graph_seed_limit: usize,
44 pub graph_context_limit: usize,
45 pub graph_context_max_hops: usize,
46}
47
48pub const NOWLEDGE_DEEP_SEARCH_MIN_RANK_WINDOW: usize = 20;
49pub const NOWLEDGE_DEEP_SEARCH_RANK_WINDOW_MULTIPLIER: usize = 5;
50pub const NOWLEDGE_DEEP_SEARCH_FILTERED_RANK_WINDOW: usize = 200;
51pub const NOWLEDGE_DEEP_SEARCH_MIN_GRAPH_SEED_LIMIT: usize = 12;
52pub const NOWLEDGE_DEEP_SEARCH_MAX_GRAPH_SEED_LIMIT: usize = 40;
53pub const NOWLEDGE_DEEP_SEARCH_GRAPH_SEED_MULTIPLIER: usize = 2;
54pub const NOWLEDGE_DEEP_SEARCH_GRAPH_CONTEXT_MAX_HOPS: usize = 2;
55
56impl KnowledgeRetrievalRequest {
57 pub fn nowledge_deep(
58 query_text: impl Into<String>,
59 query_embedding: Option<Vec<f32>>,
60 mode: SearchMode,
61 limit: usize,
62 offset: usize,
63 metadata_filters: BTreeMap<String, String>,
64 ) -> Self {
65 let page_end = offset.saturating_add(limit);
66 let rank_window = nowledge_deep_search_rank_window(page_end, !metadata_filters.is_empty());
67 let graph_seed_limit = nowledge_deep_search_graph_seed_limit(page_end);
68 Self {
69 query_text: query_text.into(),
70 query_embedding,
71 mode,
72 limit,
73 offset,
74 rank_window: Some(rank_window),
75 search_fusion_weights: SearchFusionWeights::default(),
76 metadata_filters,
77 candidate_limit: Some(rank_window),
78 candidate_scoring: KnowledgeCandidateScoringPolicy::Max,
79 graph_seed_limit,
80 graph_context_limit: rank_window,
81 graph_context_max_hops: NOWLEDGE_DEEP_SEARCH_GRAPH_CONTEXT_MAX_HOPS,
82 }
83 }
84}
85
86pub fn nowledge_deep_search_rank_window(page_end: usize, has_filters: bool) -> usize {
87 if has_filters {
88 return NOWLEDGE_DEEP_SEARCH_FILTERED_RANK_WINDOW;
89 }
90 page_end
91 .saturating_mul(NOWLEDGE_DEEP_SEARCH_RANK_WINDOW_MULTIPLIER)
92 .max(NOWLEDGE_DEEP_SEARCH_MIN_RANK_WINDOW)
93}
94
95pub fn nowledge_deep_search_graph_seed_limit(page_end: usize) -> usize {
96 page_end
97 .saturating_mul(NOWLEDGE_DEEP_SEARCH_GRAPH_SEED_MULTIPLIER)
98 .clamp(
99 NOWLEDGE_DEEP_SEARCH_MIN_GRAPH_SEED_LIMIT,
100 NOWLEDGE_DEEP_SEARCH_MAX_GRAPH_SEED_LIMIT,
101 )
102}
103
104pub use hawdb_search::{
105 KnowledgeRetrievalPipelineReport, KnowledgeRetrievalStage, SearchProjectionChangeBatch,
106 SearchProjectionGraphDeltaRequest, SearchProjectionRelationalDelta,
107};
108
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct BackgroundMaintenanceOptions {
111 pub hint: BackgroundWorkHint,
112 pub include_storage_checkpoint: bool,
113 pub include_schema_maintenance: bool,
114 pub include_property_index_projection: bool,
115 pub include_optimizer_statistics_refresh: bool,
116 pub include_search_projection_graph_delta_freshness: bool,
117 pub include_search_projection_rebuild: bool,
118 pub include_search_projection_metadata_repair: bool,
119 pub include_hawdb_lightning_bootstrap_export: bool,
120 pub include_external_content_artifact_jobs: bool,
121 pub external_content_artifact_estimated_operations: usize,
122 pub search_projection_graph_delta: Option<SearchProjectionGraphDeltaRequest>,
123}
124
125impl Default for BackgroundMaintenanceOptions {
126 fn default() -> Self {
127 Self {
128 hint: BackgroundWorkHint::default(),
129 include_storage_checkpoint: true,
130 include_schema_maintenance: true,
131 include_property_index_projection: true,
132 include_optimizer_statistics_refresh: true,
133 include_search_projection_graph_delta_freshness: true,
134 include_search_projection_rebuild: true,
135 include_search_projection_metadata_repair: true,
136 include_hawdb_lightning_bootstrap_export: true,
137 include_external_content_artifact_jobs: true,
138 external_content_artifact_estimated_operations: 1,
139 search_projection_graph_delta: None,
140 }
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct BackgroundMaintenanceCandidate {
146 pub kind: BackgroundMaintenanceKind,
147 pub name: String,
148 pub plan: BackgroundWorkPlan,
149 pub search_projection_graph_delta: Option<SearchProjectionGraphDeltaRequest>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct RankedBackgroundMaintenance {
154 pub kind: BackgroundMaintenanceKind,
155 pub name: String,
156 pub plan: BackgroundWorkPlan,
157 pub decision: BackgroundWorkDecision,
158 pub search_projection_graph_delta: Option<SearchProjectionGraphDeltaRequest>,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Default)]
162pub struct BackgroundMaintenanceSummary {
163 pub total_candidates: usize,
164 pub admitted_count: usize,
165 pub deferred_count: usize,
166 pub rejected_count: usize,
167 pub total_estimated_operations: usize,
168 pub admitted_estimated_operations: usize,
169 pub deferred_estimated_operations: usize,
170 pub rejected_estimated_operations: usize,
171 pub executable_search_projection_graph_delta_count: usize,
172 pub admitted_search_projection_graph_delta_count: usize,
173 pub deferred_search_projection_graph_delta_count: usize,
174 pub rejected_search_projection_graph_delta_count: usize,
175 pub executable_search_projection_graph_delta_operations: usize,
176 pub admitted_search_projection_graph_delta_operations: usize,
177 pub max_search_projection_graph_delta_complete_through_graph_commit_epoch: Option<u64>,
178 pub foreground_admission_probe_ready: bool,
179 pub foreground_admission_probe_admission_name: Option<String>,
180 pub qos_snapshot: Option<LocalQosSnapshot>,
181 pub top_admitted_kind: Option<BackgroundMaintenanceKind>,
182 pub top_admitted_name: Option<String>,
183 pub ranked: Vec<BackgroundMaintenanceSummaryItem>,
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct BackgroundMaintenanceSummaryItem {
188 pub kind: BackgroundMaintenanceKind,
189 pub name: String,
190 pub work_class: WorkClass,
191 pub work_class_name: String,
192 pub priority: WorkPriority,
193 pub priority_name: String,
194 pub estimated_operations: usize,
195 pub hint_active_topic: bool,
196 pub hint_recent_delta_operations: usize,
197 pub hint_source_graph_commit_lag: u64,
198 pub hint_query_probability_per_million: u32,
199 pub hint_staleness_millis: u64,
200 pub hint_staleness_ttl_millis: Option<u64>,
201 pub hint_freshness_slo_millis: Option<u64>,
202 pub hint_tenant_budget_remaining_operations: Option<usize>,
203 pub admission: QosAdmission,
204 pub admission_name: String,
205 pub admission_code: Option<QosAdmissionCode>,
206 pub admission_code_name: Option<String>,
207 pub score: u64,
208 pub reason_code_names: Vec<String>,
209 pub reasons: Vec<String>,
210 pub has_executable_search_projection_graph_delta: bool,
211 pub search_projection_graph_delta_operation_count: Option<usize>,
212 pub search_projection_graph_delta_upsert_node_count: Option<usize>,
213 pub search_projection_graph_delta_delete_document_count: Option<usize>,
214 pub search_projection_graph_delta_complete_through_graph_commit_epoch: Option<u64>,
215 pub search_projection_graph_delta_max_operations: Option<usize>,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum BackgroundMaintenanceKind {
220 StorageCheckpoint,
221 SchemaMaintenance,
222 PropertyIndexProjection,
223 OptimizerStatisticsRefresh,
224 SearchProjectionGraphDelta,
225 SearchProjectionRebuild,
226 SearchProjectionMetadataRepair,
227 HawDBLightningBootstrapExport,
228 ExternalContentArtifactJob,
229}
230
231impl BackgroundMaintenanceKind {
232 pub fn as_str(self) -> &'static str {
233 match self {
234 BackgroundMaintenanceKind::StorageCheckpoint => "storage_checkpoint",
235 BackgroundMaintenanceKind::SchemaMaintenance => "schema_maintenance",
236 BackgroundMaintenanceKind::PropertyIndexProjection => "property_index_projection",
237 BackgroundMaintenanceKind::OptimizerStatisticsRefresh => "optimizer_statistics_refresh",
238 BackgroundMaintenanceKind::SearchProjectionGraphDelta => {
239 "search_projection_graph_delta"
240 }
241 BackgroundMaintenanceKind::SearchProjectionRebuild => "search_projection_rebuild",
242 BackgroundMaintenanceKind::SearchProjectionMetadataRepair => {
243 "search_projection_metadata_repair"
244 }
245 BackgroundMaintenanceKind::HawDBLightningBootstrapExport => {
246 "hawdb_lightning_bootstrap_export"
247 }
248 BackgroundMaintenanceKind::ExternalContentArtifactJob => {
249 "external_content_artifact_job"
250 }
251 }
252 }
253}
254
255impl FromStr for BackgroundMaintenanceKind {
256 type Err = &'static str;
257
258 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
259 match value {
260 "storage_checkpoint" => Ok(BackgroundMaintenanceKind::StorageCheckpoint),
261 "schema_maintenance" => Ok(BackgroundMaintenanceKind::SchemaMaintenance),
262 "property_index_projection" => Ok(BackgroundMaintenanceKind::PropertyIndexProjection),
263 "optimizer_statistics_refresh" => {
264 Ok(BackgroundMaintenanceKind::OptimizerStatisticsRefresh)
265 }
266 "search_projection_graph_delta" => {
267 Ok(BackgroundMaintenanceKind::SearchProjectionGraphDelta)
268 }
269 "search_projection_rebuild" => Ok(BackgroundMaintenanceKind::SearchProjectionRebuild),
270 "search_projection_metadata_repair" => {
271 Ok(BackgroundMaintenanceKind::SearchProjectionMetadataRepair)
272 }
273 "hawdb_lightning_bootstrap_export" => {
274 Ok(BackgroundMaintenanceKind::HawDBLightningBootstrapExport)
275 }
276 "external_content_artifact_job" => {
277 Ok(BackgroundMaintenanceKind::ExternalContentArtifactJob)
278 }
279 _ => Err("unknown background maintenance kind"),
280 }
281 }
282}
283
284impl BackgroundMaintenanceCandidate {
285 pub fn new(kind: BackgroundMaintenanceKind, plan: BackgroundWorkPlan) -> Self {
286 Self {
287 kind,
288 name: kind.as_str().to_string(),
289 plan,
290 search_projection_graph_delta: None,
291 }
292 }
293
294 pub fn with_search_projection_graph_delta(
295 mut self,
296 request: SearchProjectionGraphDeltaRequest,
297 ) -> Self {
298 self.search_projection_graph_delta = Some(request);
299 self
300 }
301}
302
303impl BackgroundMaintenanceSummary {
304 #[doc(hidden)]
305 pub fn from_ranked(
306 ranked: Vec<RankedBackgroundMaintenance>,
307 policy: &LocalQosPolicy,
308 state: &LocalQosState,
309 ) -> Self {
310 let foreground_admission = policy.admit(
311 state,
312 &WorkRequest::foreground(WorkClass::Query, usize::MAX),
313 );
314 let qos_snapshot = policy.snapshot(state);
315 let mut summary = Self {
316 total_candidates: ranked.len(),
317 foreground_admission_probe_ready: qos_snapshot.foreground_admitted,
318 foreground_admission_probe_admission_name: Some(
319 foreground_admission.as_str().to_string(),
320 ),
321 qos_snapshot: Some(qos_snapshot),
322 ..Self::default()
323 };
324
325 for ranked_item in ranked {
326 let item = BackgroundMaintenanceSummaryItem::from_ranked(ranked_item);
327 summary.total_estimated_operations = summary
328 .total_estimated_operations
329 .saturating_add(item.estimated_operations);
330 match item.admission {
331 QosAdmission::Admit => {
332 summary.admitted_count += 1;
333 summary.admitted_estimated_operations = summary
334 .admitted_estimated_operations
335 .saturating_add(item.estimated_operations);
336 if summary.top_admitted_kind.is_none() {
337 summary.top_admitted_kind = Some(item.kind);
338 summary.top_admitted_name = Some(item.name.clone());
339 }
340 if item.has_executable_search_projection_graph_delta {
341 summary.admitted_search_projection_graph_delta_count += 1;
342 summary.admitted_search_projection_graph_delta_operations = summary
343 .admitted_search_projection_graph_delta_operations
344 .saturating_add(
345 item.search_projection_graph_delta_operation_count
346 .unwrap_or_default(),
347 );
348 }
349 }
350 QosAdmission::Defer { .. } => {
351 summary.deferred_count += 1;
352 summary.deferred_estimated_operations = summary
353 .deferred_estimated_operations
354 .saturating_add(item.estimated_operations);
355 if item.has_executable_search_projection_graph_delta {
356 summary.deferred_search_projection_graph_delta_count += 1;
357 }
358 }
359 QosAdmission::Reject { .. } => {
360 summary.rejected_count += 1;
361 summary.rejected_estimated_operations = summary
362 .rejected_estimated_operations
363 .saturating_add(item.estimated_operations);
364 if item.has_executable_search_projection_graph_delta {
365 summary.rejected_search_projection_graph_delta_count += 1;
366 }
367 }
368 }
369 if item.has_executable_search_projection_graph_delta {
370 summary.executable_search_projection_graph_delta_count += 1;
371 summary.executable_search_projection_graph_delta_operations = summary
372 .executable_search_projection_graph_delta_operations
373 .saturating_add(
374 item.search_projection_graph_delta_operation_count
375 .unwrap_or_default(),
376 );
377 if let Some(epoch) =
378 item.search_projection_graph_delta_complete_through_graph_commit_epoch
379 {
380 summary.max_search_projection_graph_delta_complete_through_graph_commit_epoch =
381 Some(
382 summary
383 .max_search_projection_graph_delta_complete_through_graph_commit_epoch
384 .map_or(epoch, |current| current.max(epoch)),
385 );
386 }
387 }
388 summary.ranked.push(item);
389 }
390
391 summary
392 }
393}
394
395impl BackgroundMaintenanceSummaryItem {
396 fn from_ranked(ranked: RankedBackgroundMaintenance) -> Self {
397 let admission_code = ranked.decision.admission.code();
398 let search_projection_graph_delta = ranked.search_projection_graph_delta.as_ref();
399 Self {
400 kind: ranked.kind,
401 name: ranked.name,
402 work_class: ranked.plan.request.class,
403 work_class_name: ranked.plan.request.class.as_str().to_string(),
404 priority: ranked.plan.request.priority,
405 priority_name: ranked.plan.request.priority.as_str().to_string(),
406 estimated_operations: ranked.plan.request.estimated_operations,
407 hint_active_topic: ranked.plan.hint.active_topic,
408 hint_recent_delta_operations: ranked.plan.hint.recent_delta_operations,
409 hint_source_graph_commit_lag: ranked.plan.hint.source_graph_commit_lag,
410 hint_query_probability_per_million: ranked.plan.hint.query_probability_per_million,
411 hint_staleness_millis: ranked.plan.hint.staleness_millis,
412 hint_staleness_ttl_millis: ranked.plan.hint.staleness_ttl_millis,
413 hint_freshness_slo_millis: ranked.plan.hint.freshness_slo_millis,
414 hint_tenant_budget_remaining_operations: ranked
415 .plan
416 .hint
417 .tenant_budget_remaining_operations,
418 admission_name: ranked.decision.admission.as_str().to_string(),
419 admission_code,
420 admission_code_name: admission_code.map(|code| code.as_str().to_string()),
421 admission: ranked.decision.admission,
422 score: ranked.decision.score,
423 reason_code_names: ranked
424 .decision
425 .reason_codes
426 .iter()
427 .map(|code| code.as_str().to_string())
428 .collect(),
429 reasons: ranked.decision.reasons,
430 has_executable_search_projection_graph_delta: search_projection_graph_delta.is_some(),
431 search_projection_graph_delta_operation_count: search_projection_graph_delta
432 .map(SearchProjectionGraphDeltaRequest::operation_count),
433 search_projection_graph_delta_upsert_node_count: search_projection_graph_delta
434 .map(|request| request.upsert_node_ids.len()),
435 search_projection_graph_delta_delete_document_count: search_projection_graph_delta
436 .map(|request| request.delete_document_ids.len()),
437 search_projection_graph_delta_complete_through_graph_commit_epoch:
438 search_projection_graph_delta
439 .and_then(|request| request.complete_through_graph_commit_epoch),
440 search_projection_graph_delta_max_operations: search_projection_graph_delta
441 .and_then(|request| request.max_operations),
442 }
443 }
444}
445
446#[derive(Debug, Clone, PartialEq)]
447pub struct KnowledgeRetrievalOutput {
448 pub graph_commit_epoch: u64,
449 pub projection_freshness: SearchProjectionFreshness,
450 pub search: SearchResultSet,
451 pub retrievers: Vec<KnowledgeRetrieverReport>,
452 pub diagnostics: KnowledgeRetrievalDiagnostics,
453 pub candidates: Vec<KnowledgeCandidate>,
454 pub evidence: Vec<KnowledgeEvidence>,
455 pub graph_seeds: Vec<KnowledgeGraphSeed>,
456 pub graph_context_paths: Vec<KnowledgeGraphContextPath>,
457 pub fanout_reason_codes: Vec<KnowledgeFanoutReasonCode>,
458 pub fanout_reason_details: Vec<KnowledgeFanoutReasonDetail>,
459 pub fanout_reasons: Vec<String>,
460}
461
462#[derive(Debug, Clone, PartialEq)]
463pub struct KnowledgeRetrievalDiagnostics {
464 pub graph_commit_epoch: u64,
465 pub projection_source_graph_commit_epoch: Option<u64>,
466 pub projection_commit_lag: u64,
467 pub projection_stale: bool,
468 pub projection_full_reindex_needed: bool,
469 pub projection_full_reindex_reasons: Vec<String>,
470 pub projection_metadata_repair_needed: bool,
471 pub projection_metadata_repair_reasons: Vec<String>,
472 pub search_document_count: usize,
473 pub search_filtered_document_count: usize,
474 pub search_total_hits: usize,
475 pub search_candidate_set: SearchCandidateSetReport,
476 pub search_candidate_filtered_out_count: usize,
477 pub search_limit: usize,
478 pub search_truncated: bool,
479 pub search_truncation_reason_codes: Vec<SearchTruncationReasonCode>,
480 pub search_truncation_reasons: Vec<String>,
481 pub search_fallback_reason_codes: Vec<SearchFallbackReasonCode>,
482 pub search_fallback_reasons: Vec<String>,
483 pub rank_window: Option<usize>,
484 pub search_fusion_weights: SearchFusionWeights,
485 pub graph_seed_input_candidate_set: SearchCandidateSetReport,
486 pub graph_seed_candidate_set: SearchRetrieverCandidateSetReport,
487 pub graph_seed_candidate_count: usize,
488 pub graph_seed_returned_count: usize,
489 pub graph_seed_limit: usize,
490 pub graph_seed_truncated: bool,
491 pub graph_seed_truncation_reason_codes: Vec<KnowledgeTruncationReasonCode>,
492 pub graph_seed_truncation_reasons: Vec<String>,
493 pub graph_context_input_candidate_set: SearchCandidateSetReport,
494 pub graph_context_candidate_set: SearchRetrieverCandidateSetReport,
495 pub graph_context_path_count: usize,
496 pub graph_context_node_count: usize,
497 pub graph_context_relationship_count: usize,
498 pub graph_context_limit: usize,
499 pub graph_context_max_hops: usize,
500 pub graph_context_truncated: bool,
501 pub graph_context_truncation_reason_codes: Vec<KnowledgeTruncationReasonCode>,
502 pub graph_context_truncation_reasons: Vec<String>,
503 pub graph_context_fallback_reason_codes: Vec<KnowledgeFallbackReasonCode>,
504 pub graph_context_fallback_reasons: Vec<String>,
505 pub fanout_reason_count: usize,
506 pub fanout_reason_codes: Vec<KnowledgeFanoutReasonCode>,
507 pub fanout_reason_details: Vec<KnowledgeFanoutReasonDetail>,
508 pub fanout_reasons: Vec<String>,
509 pub candidate_count: usize,
510 pub candidate_total_count: usize,
511 pub candidate_limit: Option<usize>,
512 pub candidate_truncated: bool,
513 pub candidate_truncation_reason_codes: Vec<KnowledgeTruncationReasonCode>,
514 pub candidate_truncation_reasons: Vec<String>,
515 pub warnings: Vec<String>,
516 pub empty_reason_codes: Vec<KnowledgeRetrievalEmptyReasonCode>,
517 pub empty_reasons: Vec<String>,
518 pub pipeline: KnowledgeRetrievalPipelineReport,
519}
520
521#[derive(Debug, Clone, PartialEq, Eq)]
522pub struct KnowledgeFanoutReasonDetail {
523 pub code: KnowledgeFanoutReasonCode,
524 pub message: String,
525 pub operation: Option<String>,
526 pub limit: Option<usize>,
527 pub total: Option<usize>,
528 pub seed_hit_id: Option<String>,
529 pub node_id: Option<u64>,
530 pub relationship_type: Option<String>,
531 pub direction: Option<String>,
532 pub degree: Option<usize>,
533}
534
535impl KnowledgeFanoutReasonDetail {
536 #[doc(hidden)]
537 pub fn dense_adjacency(
538 operation: &str,
539 relationship_type: &str,
540 direction: &str,
541 node_id: u64,
542 degree: usize,
543 ) -> Self {
544 Self {
545 code: KnowledgeFanoutReasonCode::DenseAdjacency,
546 message: format!(
547 "{operation} dense_adjacency {relationship_type} {direction} node {node_id} degree {degree}"
548 ),
549 operation: Some(operation.to_string()),
550 limit: None,
551 total: None,
552 seed_hit_id: None,
553 node_id: Some(node_id),
554 relationship_type: Some(relationship_type.to_string()),
555 direction: Some(direction.to_string()),
556 degree: Some(degree),
557 }
558 }
559
560 #[doc(hidden)]
561 pub fn graph_context_limit(limit: usize, seed_hit_id: &str) -> Self {
562 Self {
563 code: KnowledgeFanoutReasonCode::GraphContextLimitReached,
564 message: format!(
565 "graph_context_limit {limit} reached while expanding hit {seed_hit_id}"
566 ),
567 operation: Some("graph_context".to_string()),
568 limit: Some(limit),
569 total: None,
570 seed_hit_id: Some(seed_hit_id.to_string()),
571 node_id: None,
572 relationship_type: None,
573 direction: None,
574 degree: None,
575 }
576 }
577
578 #[doc(hidden)]
579 pub fn graph_seed_limit(limit: usize, total: usize) -> Self {
580 Self {
581 code: KnowledgeFanoutReasonCode::GraphSeedLimitReached,
582 message: format!(
583 "knowledge_graph_seed_limit {limit} returned from {total} matching graph seeds"
584 ),
585 operation: Some("graph_seed".to_string()),
586 limit: Some(limit),
587 total: Some(total),
588 seed_hit_id: None,
589 node_id: None,
590 relationship_type: None,
591 direction: None,
592 degree: None,
593 }
594 }
595
596 #[doc(hidden)]
597 pub fn candidate_limit(limit: usize, total: usize) -> Self {
598 Self {
599 code: KnowledgeFanoutReasonCode::CandidateLimitReached,
600 message: format!(
601 "knowledge_candidate_limit {limit} returned from {total} merged candidates"
602 ),
603 operation: Some("candidate".to_string()),
604 limit: Some(limit),
605 total: Some(total),
606 seed_hit_id: None,
607 node_id: None,
608 relationship_type: None,
609 direction: None,
610 degree: None,
611 }
612 }
613
614 #[doc(hidden)]
615 pub fn path_limit(operation: &str, limit: usize, target: &str) -> Self {
616 Self {
617 code: KnowledgeFanoutReasonCode::PathLimitReached,
618 message: format!("{operation} limit {limit} reached while expanding {target}"),
619 operation: Some(operation.to_string()),
620 limit: Some(limit),
621 total: None,
622 seed_hit_id: None,
623 node_id: None,
624 relationship_type: None,
625 direction: None,
626 degree: None,
627 }
628 }
629
630 #[doc(hidden)]
631 pub fn node_limit(limit: usize) -> Self {
632 Self {
633 code: KnowledgeFanoutReasonCode::NodeLimitReached,
634 message: format!("knowledge_subgraph node_limit {limit} reached"),
635 operation: Some("knowledge_subgraph".to_string()),
636 limit: Some(limit),
637 total: None,
638 seed_hit_id: None,
639 node_id: None,
640 relationship_type: None,
641 direction: None,
642 degree: None,
643 }
644 }
645
646 #[doc(hidden)]
647 pub fn relationship_limit(limit: usize) -> Self {
648 Self {
649 code: KnowledgeFanoutReasonCode::RelationshipLimitReached,
650 message: format!("knowledge_subgraph relationship_limit {limit} reached"),
651 operation: Some("knowledge_subgraph".to_string()),
652 limit: Some(limit),
653 total: None,
654 seed_hit_id: None,
655 node_id: None,
656 relationship_type: None,
657 direction: None,
658 degree: None,
659 }
660 }
661}
662
663#[derive(Debug, Clone, Copy, PartialEq, Eq)]
664pub enum KnowledgeFanoutReasonCode {
665 DenseAdjacency,
666 GraphContextLimitReached,
667 GraphSeedLimitReached,
668 CandidateLimitReached,
669 PathLimitReached,
670 NodeLimitReached,
671 RelationshipLimitReached,
672}
673
674impl KnowledgeFanoutReasonCode {
675 pub fn as_str(self) -> &'static str {
676 match self {
677 Self::DenseAdjacency => "dense_adjacency",
678 Self::GraphContextLimitReached => "graph_context_limit_reached",
679 Self::GraphSeedLimitReached => "graph_seed_limit_reached",
680 Self::CandidateLimitReached => "candidate_limit_reached",
681 Self::PathLimitReached => "path_limit_reached",
682 Self::NodeLimitReached => "node_limit_reached",
683 Self::RelationshipLimitReached => "relationship_limit_reached",
684 }
685 }
686}
687
688impl FromStr for KnowledgeFanoutReasonCode {
689 type Err = &'static str;
690
691 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
692 match value {
693 "dense_adjacency" => Ok(Self::DenseAdjacency),
694 "graph_context_limit_reached" => Ok(Self::GraphContextLimitReached),
695 "graph_seed_limit_reached" => Ok(Self::GraphSeedLimitReached),
696 "candidate_limit_reached" => Ok(Self::CandidateLimitReached),
697 "path_limit_reached" => Ok(Self::PathLimitReached),
698 "node_limit_reached" => Ok(Self::NodeLimitReached),
699 "relationship_limit_reached" => Ok(Self::RelationshipLimitReached),
700 _ => Err("unknown knowledge fanout reason code"),
701 }
702 }
703}
704
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
706pub enum KnowledgeFallbackReasonCode {
707 GraphSeedLimitZero,
708 GraphContextLimitZero,
709 GraphContextMaxHopsZero,
710}
711
712impl KnowledgeFallbackReasonCode {
713 pub fn as_str(self) -> &'static str {
714 match self {
715 Self::GraphSeedLimitZero => "graph_seed_limit_zero",
716 Self::GraphContextLimitZero => "graph_context_limit_zero",
717 Self::GraphContextMaxHopsZero => "graph_context_max_hops_zero",
718 }
719 }
720}
721
722impl FromStr for KnowledgeFallbackReasonCode {
723 type Err = &'static str;
724
725 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
726 match value {
727 "graph_seed_limit_zero" => Ok(Self::GraphSeedLimitZero),
728 "graph_context_limit_zero" => Ok(Self::GraphContextLimitZero),
729 "graph_context_max_hops_zero" => Ok(Self::GraphContextMaxHopsZero),
730 _ => Err("unknown knowledge fallback reason code"),
731 }
732 }
733}
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub enum KnowledgeTruncationReasonCode {
737 RankWindowExceeded,
738 SearchLimitExceeded,
739 PartialCandidateReturn,
740 GraphSeedLimitExceeded,
741 GraphContextLimitExceeded,
742 CandidateLimitExceeded,
743}
744
745impl KnowledgeTruncationReasonCode {
746 pub fn as_str(self) -> &'static str {
747 match self {
748 Self::RankWindowExceeded => "rank_window_exceeded",
749 Self::SearchLimitExceeded => "search_limit_exceeded",
750 Self::PartialCandidateReturn => "partial_candidate_return",
751 Self::GraphSeedLimitExceeded => "graph_seed_limit_exceeded",
752 Self::GraphContextLimitExceeded => "graph_context_limit_exceeded",
753 Self::CandidateLimitExceeded => "candidate_limit_exceeded",
754 }
755 }
756}
757
758impl FromStr for KnowledgeTruncationReasonCode {
759 type Err = &'static str;
760
761 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
762 match value {
763 "rank_window_exceeded" => Ok(Self::RankWindowExceeded),
764 "search_limit_exceeded" => Ok(Self::SearchLimitExceeded),
765 "partial_candidate_return" => Ok(Self::PartialCandidateReturn),
766 "graph_seed_limit_exceeded" => Ok(Self::GraphSeedLimitExceeded),
767 "graph_context_limit_exceeded" => Ok(Self::GraphContextLimitExceeded),
768 "candidate_limit_exceeded" => Ok(Self::CandidateLimitExceeded),
769 _ => Err("unknown knowledge truncation reason code"),
770 }
771 }
772}
773
774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
775pub enum KnowledgeRetrievalEmptyReasonCode {
776 SearchProjectionEmpty,
777 SearchMetadataFilterEmpty,
778 SearchRetrieverNoHits,
779 SearchLimitExcludedAllHits,
780 GraphSeedLimitZero,
781 GraphSeedNoCandidates,
782 CandidateLimitExcludedAllCandidates,
783 NoCandidates,
784}
785
786impl KnowledgeRetrievalEmptyReasonCode {
787 pub fn as_str(self) -> &'static str {
788 match self {
789 Self::SearchProjectionEmpty => "search_projection_empty",
790 Self::SearchMetadataFilterEmpty => "search_metadata_filter_empty",
791 Self::SearchRetrieverNoHits => "search_retriever_no_hits",
792 Self::SearchLimitExcludedAllHits => "search_limit_excluded_all_hits",
793 Self::GraphSeedLimitZero => "graph_seed_limit_zero",
794 Self::GraphSeedNoCandidates => "graph_seed_no_candidates",
795 Self::CandidateLimitExcludedAllCandidates => "candidate_limit_excluded_all_candidates",
796 Self::NoCandidates => "no_candidates",
797 }
798 }
799}
800
801#[derive(Debug, Clone, PartialEq)]
802pub struct KnowledgeRetrieverReport {
803 pub name: String,
804 pub backend: String,
805 pub available: bool,
806 pub input_candidate_set: SearchCandidateSetReport,
807 pub candidate_count: usize,
808 pub candidate_set: SearchRetrieverCandidateSetReport,
809 pub limit: Option<usize>,
810 pub rank_window: Option<usize>,
811 pub fusion_weight: Option<f64>,
812 pub fallback_reason_codes: Vec<SearchFallbackReasonCode>,
813 pub knowledge_fallback_reason_codes: Vec<KnowledgeFallbackReasonCode>,
814 pub fallback_reasons: Vec<String>,
815 pub truncated: bool,
816 pub truncation_reason_codes: Vec<KnowledgeTruncationReasonCode>,
817 pub truncation_reasons: Vec<String>,
818 pub top_candidates: Vec<KnowledgeRetrieverCandidate>,
819}
820
821#[derive(Debug, Clone, PartialEq)]
822pub struct KnowledgeRetrieverCandidate {
823 pub id: String,
824 pub kind: Option<String>,
825 pub external_id: Option<String>,
826 pub source_id: Option<String>,
827 pub canonical_node_id: Option<u64>,
828 pub rank: usize,
829 pub score: f64,
830 pub matched_spans: Vec<SearchMatchedSpan>,
831 pub graph_context_path_count: usize,
832 pub projection_freshness: Option<SearchProjectionFreshness>,
833}
834
835#[derive(Debug, Clone, PartialEq)]
836pub struct KnowledgeCandidate {
837 pub id: String,
838 pub canonical_node_id: Option<u64>,
839 pub source: KnowledgeCandidateSource,
840 pub source_rank: usize,
841 pub merged_sources: Vec<KnowledgeCandidateSource>,
842 pub score: f64,
843 pub score_breakdown: KnowledgeCandidateScoreBreakdown,
844 pub entity: Option<KnowledgeEntity>,
845 pub evidence: Option<KnowledgeEvidence>,
846 pub matched_properties: Vec<String>,
847 pub graph_context_path_count: usize,
848}
849
850#[derive(Debug, Clone, PartialEq)]
851pub enum KnowledgeCandidateScoringPolicy {
852 Max,
853 WeightedSum {
854 search_weight: f64,
855 graph_seed_weight: f64,
856 },
857 Spec(ScoringSpec),
859}
860
861pub use hawdb_core::graph_rag::{
865 DecayTerm, ScoreFeature, ScoringEvaluation, ScoringFeatureSource, ScoringSpec,
866 ScoringSpecError, ScoringTerm,
867};
868
869#[derive(Debug, Clone, PartialEq)]
870pub struct KnowledgeCandidateScoreBreakdown {
871 pub search_score: Option<f64>,
872 pub graph_seed_score: Option<f64>,
873 pub combined_score: f64,
874 pub scoring_spec: Option<ScoringEvaluation>,
876}
877
878#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879pub enum KnowledgeCandidateSource {
880 SearchHit,
881 GraphSeed,
882}
883
884#[derive(Debug, Clone, PartialEq)]
885pub struct KnowledgeGraphSeed {
886 pub entity: KnowledgeEntity,
887 pub score: f64,
888 pub matched_properties: Vec<String>,
889}
890
891#[derive(Debug, Clone, PartialEq)]
892pub struct KnowledgeEvidence {
893 pub hit_id: String,
894 pub kind: Option<String>,
895 pub external_id: Option<String>,
896 pub source_id: Option<String>,
897 pub canonical_node_id: Option<u64>,
898 pub graph_context_path_count: usize,
899 pub matched_terms: Vec<String>,
900 pub matched_spans: Vec<SearchMatchedSpan>,
901 pub score: f64,
902 pub rrf_score: f64,
903 pub vector_rrf_score: f64,
904 pub text_rrf_score: f64,
905 pub vector_score: f64,
906 pub text_score: f64,
907 pub vector_rank: Option<usize>,
908 pub text_rank: Option<usize>,
909}
910
911#[cfg(test)]
912mod contract_tests {
913 use super::{KnowledgeRetrievalPipelineReport, KnowledgeRetrievalStage};
914 use std::any::TypeId;
915
916 #[test]
917 fn pipeline_contract_preserves_search_owner_identity() {
918 assert_eq!(
919 TypeId::of::<KnowledgeRetrievalStage>(),
920 TypeId::of::<hawdb_search::KnowledgeRetrievalStage>(),
921 );
922 assert_eq!(
923 TypeId::of::<KnowledgeRetrievalPipelineReport>(),
924 TypeId::of::<hawdb_search::KnowledgeRetrievalPipelineReport>(),
925 );
926 assert_eq!(
927 KnowledgeRetrievalStage::TopK.as_str(),
928 hawdb_search::KnowledgeRetrievalStage::TopK.as_str(),
929 );
930 }
931}