Skip to main content

uqa_execution/operator_tree/
runtime.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retrieval-tree optimization, active-statement checks and physical execution.
8
9use super::driver::{context::PhysicalDriverContext, PhysicalRetrievalDriver};
10use super::{OperatorOutput, PlanExecutor};
11use uqa_core::PostingList;
12use uqa_operators::{OperatorTree, TextScoringMode};
13use uqa_sql::{SQLError, SQLParam};
14
15type DriverResult<T> = Result<T, SQLError>;
16
17pub trait RetrievalPlanOptimizer: Sync {
18    fn optimize(&self, table: &str, tree: &OperatorTree) -> DriverResult<OperatorTree>;
19}
20
21pub trait RetrievalTransactionState: Sync {
22    fn transaction_depth(&self) -> usize;
23}
24
25#[derive(Clone, Copy)]
26pub struct TreeExecutionContext<'a> {
27    pub driver: PhysicalDriverContext<'a>,
28    pub optimizer: &'a dyn RetrievalPlanOptimizer,
29    pub transaction: &'a dyn RetrievalTransactionState,
30}
31
32/// Execute below an existing statement boundary; calibration must already have a transaction.
33pub fn execute_tree(
34    context: &TreeExecutionContext<'_>,
35    table: &str,
36    signal_table: &str,
37    params: &[SQLParam],
38    tree: &OperatorTree,
39) -> DriverResult<OperatorOutput> {
40    if context.transaction.transaction_depth() == 0 && tree_may_persist_calibration(tree) {
41        return Err(SQLError::Internal(
42            "calibrating operator execution requires an active statement transaction".into(),
43        ));
44    }
45    optimize_and_execute_tree(context, table, signal_table, params, tree)
46}
47
48pub fn optimize_and_execute_tree(
49    context: &TreeExecutionContext<'_>,
50    table: &str,
51    signal_table: &str,
52    params: &[SQLParam],
53    tree: &OperatorTree,
54) -> DriverResult<OperatorOutput> {
55    validate_text_top_k_placement(tree)?;
56    let optimized = context.optimizer.optimize(table, tree)?;
57    execute_physical_tree(context, table, signal_table, params, &optimized)
58}
59
60pub fn execute_preoptimized_tree(
61    context: &TreeExecutionContext<'_>,
62    table: &str,
63    signal_table: &str,
64    params: &[SQLParam],
65    tree: &OperatorTree,
66) -> DriverResult<OperatorOutput> {
67    if context.transaction.transaction_depth() == 0 && tree_may_persist_calibration(tree) {
68        return Err(SQLError::Internal(
69            "calibrating operator execution requires an active statement transaction".into(),
70        ));
71    }
72    execute_physical_tree(context, table, signal_table, params, tree)
73}
74
75fn execute_physical_tree(
76    context: &TreeExecutionContext<'_>,
77    table: &str,
78    signal_table: &str,
79    params: &[SQLParam],
80    tree: &OperatorTree,
81) -> DriverResult<OperatorOutput> {
82    validate_text_top_k_placement(tree)?;
83    let driver = PhysicalRetrievalDriver::new(context.driver, table, signal_table, params);
84    let mut executor = PlanExecutor::new(&driver);
85    executor.execute(tree)
86}
87
88fn validate_text_top_k_placement(tree: &OperatorTree) -> DriverResult<()> {
89    let root_is_physical_text = matches!(tree, OperatorTree::Term { top_k: Some(_), .. });
90    let mut physical_text_nodes = 0_usize;
91    tree.visit(&mut |node| {
92        if matches!(node, OperatorTree::Term { top_k: Some(_), .. }) {
93            physical_text_nodes += 1;
94        }
95    });
96    if physical_text_nodes == usize::from(root_is_physical_text) {
97        Ok(())
98    } else {
99        Err(SQLError::Internal(
100            "physical text top-k is valid only as the root retrieval leaf".into(),
101        ))
102    }
103}
104
105pub fn tree_may_persist_calibration(tree: &OperatorTree) -> bool {
106    let mut may_persist = false;
107    tree.visit(&mut |node| {
108        may_persist |= matches!(
109            node,
110            OperatorTree::BayesianScore { .. }
111                | OperatorTree::Term {
112                    scoring: Some(TextScoringMode::BayesianBM25),
113                    ..
114                }
115                | OperatorTree::Phrase {
116                    scoring: Some(TextScoringMode::BayesianBM25),
117                    ..
118                }
119                | OperatorTree::BayesianMatchWithPrior { .. }
120                | OperatorTree::MultiFieldSearch { .. }
121        );
122    });
123    may_persist
124}
125
126pub fn expect_posting_output(output: OperatorOutput, context: &str) -> DriverResult<PostingList> {
127    match output {
128        OperatorOutput::Posting(result) => Ok(result),
129        OperatorOutput::Graph(result) => Ok(result.to_posting_list()),
130        OperatorOutput::Generalized(_) => Err(SQLError::TypeMismatch(format!(
131            "{context} requires single-document rows, but the physical plan produced join tuples"
132        ))),
133    }
134}
135
136#[cfg(test)]
137mod tests;