uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Predicate eligibility, NULL handling and evaluated-key retention for column and expression accelerators.
//!
//! An accelerator holds the stored value of its field for every row. A search key also orders its non-null values in a B-tree for predicates. A column that an index only carries beside its key holds the values alone: it answers the projection of an index-only read and no predicate, and a write maintains no value bucket for it.

use std::collections::BTreeMap;
use uqa_core::{DocId, Payload, PostingEntry, PostingList, Predicate, Value};
use uqa_storage::BTreeIndex;

mod cache;
mod comparison;
pub use cache::{apply_cached_values, visit_stored_fields, ValueIndexBuilder, ValueIndexCache};

/// Per-column index: the stored value of every row, and for a search key
/// the non-null scalar keys in a B-tree plus the doc ids whose field is
/// missing or SQL NULL.
#[derive(Clone)]
pub struct ColumnValueIndex {
    /// `None` for a column that an index only carries.
    index: Option<BTreeIndex>,
    values: BTreeMap<DocId, Value>,
    /// Sorted doc ids with a missing or `Value::Null` field, kept for a search key.
    nulls: Vec<DocId>,
    /// Set when any indexed key is temporal; disables acceleration
    /// because string-vs-temporal comparisons need parsing.
    has_temporal: bool,
    comparison: comparison::StoredComparison,
    /// Set when any indexed key is a row value, whose null test inspects its fields; the null set cannot answer it, as `PostgreSQL` never indexes a row-type null test.
    has_row_values: bool,
}

fn value_is_row(value: &Value) -> bool {
    // A physical value can be a composite whose NULL bitmap differs from the scalar null posting. Catalog-free eligibility cannot classify it as a scalar.
    matches!(value, Value::Row(_) | Value::Record(_) | Value::Datum(_))
}

fn value_is_temporal(value: &Value) -> bool {
    matches!(value, Value::Temporal(_))
}

fn value_is_nan(value: &Value) -> bool {
    matches!(value, Value::Float(f) if f.is_nan())
}

pub(crate) fn field_is_index_safe(value: &Value) -> bool {
    !value_is_temporal(value)
        && !value_is_nan(value)
        && !comparison::field_needs_typed_comparison(value)
        && !uqa_sql::expr::value_comparison_can_fail(value)
}

fn predicate_targets_are_index_safe(predicate: &Predicate) -> bool {
    let safe = |v: &Value| !value_is_temporal(v) && !value_is_nan(v);
    match predicate {
        Predicate::Equals(v)
        | Predicate::NotEquals(v)
        | Predicate::GreaterThan(v)
        | Predicate::GreaterThanOrEqual(v)
        | Predicate::LessThan(v)
        | Predicate::LessThanOrEqual(v) => safe(v),
        Predicate::InSet(values) => values.iter().all(safe),
        Predicate::Between { low, high } => safe(low) && safe(high),
        Predicate::IsNull | Predicate::IsNotNull => true,
    }
}

/// Ask a durable scalar index for exact equality candidates without creating an accelerator. Providers decline unsupported stored comparison domains. SQL null tests retain their ordinary path because a row's null test examines its fields rather than comparing its storage key with `Value::Null`.
pub fn probe_durable_equality(
    backend: &dyn uqa_storage::PersistentStorageBackend,
    table: &str,
    field: &uqa_storage::ValueIndexKey,
    predicate: &Predicate,
) -> uqa_storage::StorageBackendResult<Option<PostingList>> {
    let Some(value) = durable_equality_value(predicate) else {
        return Ok(None);
    };
    let Some(ids) = backend.probe_btree_index_equal(table, field, value)? else {
        return Ok(None);
    };
    Ok(Some(posting_list_from_sorted_ids(ids.into_iter())))
}

fn durable_equality_value(predicate: &Predicate) -> Option<&Value> {
    match predicate {
        Predicate::Equals(
            value @ (Value::Bool(_)
            | Value::Int(_)
            | Value::Str(_)
            | Value::Bytes(_)
            | Value::Row(_)),
        ) => Some(value),
        Predicate::Equals(value @ Value::Float(number)) if !number.is_nan() => Some(value),
        _ => None,
    }
}

/// The callback retains only identities and must not reenter the provider. Preserve its typed SQL error separately from provider diagnostics.
pub fn visit_durable_equality(
    backend: &dyn uqa_storage::PersistentStorageBackend,
    table: &str,
    field: &uqa_storage::ValueIndexKey,
    predicate: &Predicate,
    visit: &mut dyn FnMut(DocId) -> Result<(), uqa_sql::SQLError>,
) -> Result<bool, uqa_sql::SQLError> {
    let Some(value) = durable_equality_value(predicate) else {
        return Ok(false);
    };
    let mut failure = None;
    let result = backend.visit_btree_index_equal(table, field, value, &mut |id| match visit(id) {
        Ok(()) => true,
        Err(error) => {
            failure = Some(error);
            false
        }
    });
    if let Some(error) = failure {
        return Err(error);
    }
    result.map_err(|error| crate::storage_errors::storage_error("visit stored value index", &error))
}

impl ColumnValueIndex {
    /// Visit exact equality candidates without copying their bucket or decorating identities with empty posting payloads. SQL-dependent comparison keeps its original ordered value evaluation.
    pub fn visit_equal_with_catalog(
        &self,
        value: &Value,
        catalog: Option<&dyn uqa_sql::expr::SQLValueCatalog>,
        visit: &mut dyn FnMut(DocId) -> Result<(), uqa_sql::SQLError>,
    ) -> Result<bool, uqa_sql::SQLError> {
        self.visit_key_candidates_with_catalog(&Predicate::Equals(value.clone()), catalog, visit)
    }

    /// Equality and scalar NULL candidates retain the same eligibility, comparison order and null semantics as their posting-producing probes.
    pub fn visit_key_candidates_with_catalog(
        &self,
        predicate: &Predicate,
        catalog: Option<&dyn uqa_sql::expr::SQLValueCatalog>,
        visit: &mut dyn FnMut(DocId) -> Result<(), uqa_sql::SQLError>,
    ) -> Result<bool, uqa_sql::SQLError> {
        if !matches!(predicate, Predicate::Equals(_) | Predicate::IsNull) {
            return Ok(false);
        }
        let Some(index) = &self.index else {
            return Ok(false);
        };
        if comparison::needs_sql_comparison(predicate, self.comparison.can_fail()) {
            for (&id, value) in &self.values {
                if comparison::matches(value, predicate, catalog)? {
                    visit(id)?;
                }
            }
            return Ok(true);
        }
        if !self.supports(predicate) {
            return Ok(false);
        }
        let ids = match predicate {
            Predicate::Equals(value) => index.equality_ids(value),
            Predicate::IsNull => self.nulls.as_slice(),
            _ => unreachable!("candidate predicate checked above"),
        };
        for &id in ids {
            visit(id)?;
        }
        Ok(true)
    }

    /// Borrow the key evaluated for the stored row, without reevaluating an index expression against a newer routine definition.
    pub fn stored_value(&self, doc_id: DocId) -> Option<&Value> {
        self.values.get(&doc_id)
    }

    /// Whether a row is indexed, which every row of the table is while the accelerator is current.
    pub fn contains(&self, doc_id: DocId) -> bool {
        self.values.contains_key(&doc_id)
    }

    /// Whether this accelerator only carries its column's values and answers no predicate.
    pub fn is_carried(&self) -> bool {
        self.index.is_none()
    }

    /// Build a search key.
    pub fn build(field: &str, values: impl Iterator<Item = (DocId, Value)>) -> Self {
        let mut built = Self {
            index: Some(BTreeIndex::new(field)),
            values: BTreeMap::new(),
            nulls: Vec::new(),
            has_temporal: false,
            comparison: comparison::StoredComparison::default(),
            has_row_values: false,
        };
        for (doc_id, value) in values {
            built.index_value(doc_id, &value);
            built.values.insert(doc_id, value);
        }
        built.nulls.sort_unstable();
        built.nulls.dedup();
        built
    }

    /// Build the values of a column that an index only carries.
    pub fn build_carried(values: impl Iterator<Item = (DocId, Value)>) -> Self {
        Self {
            index: None,
            values: values.collect(),
            nulls: Vec::new(),
            has_temporal: false,
            comparison: comparison::StoredComparison::default(),
            has_row_values: false,
        }
    }

    /// The same stored values, carried or as a search key of `field`, when the indexes of the table give the column the other use.
    #[must_use]
    pub fn with_use(self, field: &str, carried: bool) -> Self {
        match (carried, self.is_carried()) {
            (false, true) => Self::build(field, self.values.into_iter()),
            (true, false) => Self::build_carried(self.values.into_iter()),
            _ => self,
        }
    }

    /// Order one stored value for predicates. `nulls` is appended to and sorted by the caller.
    fn index_value(&mut self, doc_id: DocId, value: &Value) {
        let Some(index) = self.index.as_mut() else {
            return;
        };
        match value {
            Value::Null => self.nulls.push(doc_id),
            value => {
                self.has_temporal |= value_is_temporal(value);
                self.has_row_values |= value_is_row(value);
                self.comparison.include(value);
                index.insert(doc_id, value.clone());
            }
        }
    }

    pub fn insert(&mut self, doc_id: DocId, value: &Value) {
        self.values.insert(doc_id, value.clone());
        let Some(index) = self.index.as_mut() else {
            return;
        };
        match value {
            Value::Null => {
                if let Err(pos) = self.nulls.binary_search(&doc_id) {
                    self.nulls.insert(pos, doc_id);
                }
            }
            value => {
                self.has_temporal |= value_is_temporal(value);
                self.has_row_values |= value_is_row(value);
                self.comparison.include(value);
                index.insert(doc_id, value.clone());
            }
        }
    }

    pub fn remove(&mut self, doc_id: DocId, value: &Value) {
        let stored = self.values.remove(&doc_id);
        let Some(index) = self.index.as_mut() else {
            return;
        };
        let value = stored.as_ref().unwrap_or(value);
        match value {
            Value::Null => {
                if let Ok(pos) = self.nulls.binary_search(&doc_id) {
                    self.nulls.remove(pos);
                }
            }
            value => index.remove(doc_id, value),
        }
    }

    pub fn clear(&mut self) {
        if let Some(index) = self.index.as_mut() {
            index.clear();
        }
        self.values.clear();
        self.nulls.clear();
        self.has_temporal = false;
        self.comparison = comparison::StoredComparison::default();
        self.has_row_values = false;
    }

    /// Resolve `predicate` to a posting list, or `None` when this
    /// index cannot reproduce evaluated-scan semantics for it.
    pub fn scan(&self, predicate: &Predicate) -> Option<PostingList> {
        let index = self.index.as_ref()?;
        if !self.supports(predicate) {
            return None;
        }
        match predicate {
            Predicate::IsNull => Some(posting_list_from_sorted_ids(self.nulls.iter().copied())),
            Predicate::IsNotNull => Some(index.scan(&Predicate::IsNotNull)),
            // `NotEquals` needs "all non-null minus matches"; the
            // complement is rarely selective, so leave it to the scan.
            Predicate::NotEquals(_) => unreachable!("unsupported predicates return above"),
            predicate => Some(index.scan(predicate)),
        }
    }

    /// Exact field candidates without evaluating stored values. A declined probe
    /// lets the caller mask private identities before any fallible comparison.
    /// NULL candidates include absent fields, which the caller must recheck.
    pub fn field_candidates(&self, value: &Value) -> Option<PostingList> {
        if !field_is_index_safe(value) {
            return None;
        }
        let predicate = if matches!(value, Value::Null) {
            Predicate::IsNull
        } else {
            if self.comparison.field_needs_evaluation() {
                return None;
            }
            Predicate::Equals(value.clone())
        };
        self.scan(&predicate)
    }

    pub fn estimate_cardinality(&self, predicate: &Predicate) -> Option<usize> {
        let index = self.index.as_ref()?;
        if !self.supports(predicate) {
            return None;
        }
        Some(match predicate {
            Predicate::IsNull => self.nulls.len(),
            Predicate::IsNotNull => index.estimate_cardinality(predicate),
            Predicate::NotEquals(_) => unreachable!("unsupported predicates return above"),
            predicate => index.estimate_cardinality(predicate),
        })
    }

    /// The selected access path registers its logical predicate before reading even an empty posting list. Declined predicates do not register a read.
    pub fn scan_observing(
        &self,
        predicate: &Predicate,
        observe: impl FnOnce() -> Result<(), uqa_sql::SQLError>,
    ) -> Result<Option<PostingList>, uqa_sql::SQLError> {
        self.scan_observing_with_catalog(predicate, None, observe)
    }

    /// Capture predicate support without materializing posting payloads. SQL-dependent comparisons keep document order; plain B-tree candidates may arrive in key order.
    pub fn visit_observing_with_catalog(
        &self,
        predicate: &Predicate,
        catalog: Option<&dyn uqa_sql::expr::SQLValueCatalog>,
        observe: impl FnOnce() -> Result<(), uqa_sql::SQLError>,
        visit: &mut dyn FnMut(DocId) -> Result<(), uqa_sql::SQLError>,
    ) -> Result<bool, uqa_sql::SQLError> {
        let Some(index) = &self.index else {
            return Ok(false);
        };
        if comparison::needs_sql_comparison(predicate, self.comparison.can_fail()) {
            observe()?;
            for (&id, value) in &self.values {
                if comparison::matches(value, predicate, catalog)? {
                    visit(id)?;
                }
            }
            return Ok(true);
        }
        if !self.supports(predicate) {
            return Ok(false);
        }
        observe()?;
        if matches!(predicate, Predicate::IsNull) {
            for &id in &self.nulls {
                visit(id)?;
            }
        } else {
            let mut failure = None;
            index.visit_matching_ids(predicate, &mut |id| match visit(id) {
                Ok(()) => true,
                Err(error) => {
                    failure = Some(error);
                    false
                }
            });
            if let Some(error) = failure {
                return Err(error);
            }
        }
        Ok(true)
    }

    /// Evaluate catalog-dependent keys in the same catalog generation as the caller.
    pub fn scan_observing_with_catalog(
        &self,
        predicate: &Predicate,
        catalog: Option<&dyn uqa_sql::expr::SQLValueCatalog>,
        observe: impl FnOnce() -> Result<(), uqa_sql::SQLError>,
    ) -> Result<Option<PostingList>, uqa_sql::SQLError> {
        if self.is_carried() {
            return Ok(None);
        }
        if comparison::needs_sql_comparison(predicate, self.comparison.can_fail()) {
            observe()?;
            let mut ids = Vec::new();
            for (&id, value) in &self.values {
                if comparison::matches(value, predicate, catalog)? {
                    ids.push(id);
                }
            }
            return Ok(Some(posting_list_from_sorted_ids(ids.into_iter())));
        }
        if !self.supports(predicate) {
            return Ok(None);
        }
        observe()?;
        Ok(self.scan(predicate))
    }

    pub fn supports(&self, predicate: &Predicate) -> bool {
        !self.is_carried()
            && predicate_targets_are_index_safe(predicate)
            && !comparison::needs_sql_comparison(predicate, self.comparison.can_fail())
            && !matches!(predicate, Predicate::NotEquals(_))
            && if matches!(predicate, Predicate::IsNull | Predicate::IsNotNull) {
                !self.has_row_values
            } else {
                !self.has_temporal
            }
    }
}

fn posting_list_from_sorted_ids(ids: impl Iterator<Item = DocId>) -> PostingList {
    let entries: Vec<PostingEntry> = ids
        .map(|doc_id| PostingEntry::new(doc_id, Payload::default()))
        .collect();
    PostingList::from_sorted_unchecked(entries)
}

#[cfg(test)]
mod tests;