Skip to main content

uqa_operators/
base.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `Operator` trait, [`ExecutionContext`] holding storage backends, and
8//! the monoidal [`ComposedOperator`].
9
10use std::collections::BTreeMap;
11use std::sync::Arc;
12
13use uqa_core::{FieldName, IndexStats, PostingList};
14use uqa_storage::{
15    DocumentStore, InvertedIndex, StorageBackendError, StorageBackendResult, VectorIndex,
16};
17
18pub type OperatorResult = StorageBackendResult<PostingList>;
19
20pub(crate) fn missing_backend(backend: &str, operation: &str) -> StorageBackendError {
21    StorageBackendError::Other(format!(
22        "{operation} requires an execution-context {backend} backend"
23    ))
24}
25
26pub(crate) fn require_finite_score(score: f64, operation: &str) -> StorageBackendResult<()> {
27    if score.is_finite() {
28        Ok(())
29    } else {
30        Err(StorageBackendError::Other(format!(
31            "{operation} received a non-finite score {score}"
32        )))
33    }
34}
35
36pub(crate) fn require_probability(probability: f64, operation: &str) -> StorageBackendResult<()> {
37    if probability.is_finite() && (0.0..=1.0).contains(&probability) {
38        Ok(())
39    } else {
40        Err(StorageBackendError::Other(format!(
41            "{operation} requires probability scores in [0, 1], got {probability}"
42        )))
43    }
44}
45
46/// Storage handles passed to every operator's `execute` call.
47///
48/// Holding `Arc<dyn ...>` rather than borrows keeps the operator tree
49/// independent of how the engine owns its stores. The trade-off is one
50/// `Arc::clone` per operator at engine boundary; per-operator dispatch
51/// remains a single virtual call.
52#[derive(Default, Clone)]
53pub struct ExecutionContext {
54    pub vector_observer: Option<Arc<dyn crate::vector::diagnostics::VectorSearchObserver>>,
55    pub document_store: Option<Arc<dyn DocumentStore>>,
56    pub inverted_index: Option<Arc<dyn InvertedIndex>>,
57    pub vector_indexes: BTreeMap<FieldName, Arc<dyn VectorIndex>>,
58    pub stats: Option<IndexStats>,
59    /// Optional named graph (label-only neighbor lookup) for the
60    /// graph-aware deep-fusion layers (`Propagate`, `Conv`, `Pool`).
61    /// Held as a generic neighbor-lookup callback so this crate stays
62    /// independent of `uqa-graph`.
63    pub graph: Option<Arc<dyn GraphNeighborLookup>>,
64}
65
66/// Minimal trait capturing the only graph operation deep-fusion's
67/// graph layers need: enumerate the neighbors of a vertex along a
68/// label in a chosen direction.
69///
70/// An empty `label` is the explicit wildcard and must enumerate neighbors
71/// across every edge label. This lets IR nodes represent an omitted edge
72/// label without inventing a separate sentinel at each engine boundary.
73pub trait GraphNeighborLookup: Send + Sync {
74    fn neighbors(
75        &self,
76        vertex: u64,
77        label: &str,
78        direction: Direction,
79    ) -> StorageBackendResult<Vec<u64>>;
80}
81
82pub use uqa_core::retrieval::Direction;
83
84impl ExecutionContext {
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    pub fn with_inverted_index(mut self, idx: Arc<dyn InvertedIndex>) -> Self {
90        self.inverted_index = Some(idx);
91        self
92    }
93
94    pub fn with_document_store(mut self, ds: Arc<dyn DocumentStore>) -> Self {
95        self.document_store = Some(ds);
96        self
97    }
98
99    pub fn with_vector_index(
100        mut self,
101        field: impl Into<FieldName>,
102        idx: Arc<dyn VectorIndex>,
103    ) -> Self {
104        self.vector_indexes.insert(field.into(), idx);
105        self
106    }
107
108    pub fn with_stats(mut self, stats: IndexStats) -> Self {
109        self.stats = Some(stats);
110        self
111    }
112
113    pub fn with_graph(mut self, graph: Arc<dyn GraphNeighborLookup>) -> Self {
114        self.graph = Some(graph);
115        self
116    }
117}
118
119pub trait Operator: Send + Sync {
120    fn execute(&self, ctx: &ExecutionContext) -> OperatorResult;
121
122    fn cost_estimate(&self, stats: &IndexStats) -> f64 {
123        stats.total_docs as f64
124    }
125}
126
127/// Sequential composition: the right-hand operand's result wins. Used as
128/// the monoidal product for the operator monoid; the empty composition is
129/// the identity.
130pub struct ComposedOperator {
131    pub operands: Vec<Arc<dyn Operator>>,
132}
133
134impl ComposedOperator {
135    pub fn new(operands: Vec<Arc<dyn Operator>>) -> Self {
136        Self { operands }
137    }
138}
139
140impl Operator for ComposedOperator {
141    fn execute(&self, ctx: &ExecutionContext) -> OperatorResult {
142        let mut result = PostingList::new();
143        for op in &self.operands {
144            result = op.execute(ctx)?;
145        }
146        Ok(result)
147    }
148
149    fn cost_estimate(&self, stats: &IndexStats) -> f64 {
150        self.operands.iter().map(|op| op.cost_estimate(stats)).sum()
151    }
152}