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
//! Tool-call-native query surface.
//!
//! A [`Query`] is a conjunction of [`Condition`]s. Each condition resolves to a
//! set of row ids in the shared [`crate::rowid::RowId`] space (PK exact, bitmap
//! equality, ANN semantic, FM substring, or a column range). [`crate::Table`]
//! intersects the sets and materializes the survivors — letting an agent express
//! `semsearch ∩ fm_contains ∩ cat_in`, which no SQL FTS pipeline can.
/// One predicate over the row-id space.
#[derive(Debug, Clone)]
pub enum Condition {
/// Primary-key exact match (encoded key bytes).
Pk(Vec<u8>),
/// Low-cardinality equality via the roaring bitmap index.
BitmapEq { column_id: u16, value: Vec<u8> },
/// Multi-value equality via the roaring bitmap index (Phase 13.5). Resolves
/// to the **union** of `bitmap[col].get(v)` for each value — the index-
/// accelerated equivalent of `col IN (v1, v2, …)` or a semi-join's runtime
/// value set.
BitmapIn {
column_id: u16,
values: Vec<Vec<u8>>,
},
/// Prefix match on a Bytes column with a bitmap index: all row-ids whose
/// indexed value starts with `prefix`. Exact (no residual needed) — the
/// bitmap's distinct keys are enumerated and filtered by prefix. Tighter
/// than `FmContains` for anchored `LIKE 'prefix%'`. (§5.6)
BytesPrefix { column_id: u16, prefix: Vec<u8> },
/// Semantic search via the binary-quantized ANN index.
Ann {
column_id: u16,
query: Vec<f32>,
k: usize,
},
/// Arbitrary substring via the FM index (no tokenization).
FmContains { column_id: u16, pattern: Vec<u8> },
/// Multi-segment FM intersection for `LIKE '%seg1%seg2%...'` (Priority 12).
/// Resolves to the **intersection** of FM lookups for each segment — a much
/// tighter superset than the single longest segment. DataFusion still
/// re-applies the real wildcard semantics (`Inexact` pushdown).
FmContainsAll {
column_id: u16,
patterns: Vec<Vec<u8>>,
},
/// Inclusive integer range (served by scanning the int column, later by the
/// learned PGM index / page-index pruning). Exclusive bounds (`>`,`<`) are
/// expressed exactly via ±1 in the translator.
Range { column_id: u16, lo: i64, hi: i64 },
/// Floating-point range with per-bound inclusivity (exact for `>`/`<`/`>=`/
/// `<=`/`BETWEEN`), served the same way as [`Condition::Range`].
RangeF64 {
column_id: u16,
lo: f64,
lo_inclusive: bool,
hi: f64,
hi_inclusive: bool,
},
/// SPLADE-style sparse retrieval: top-k row ids by sparse dot product over
/// shared tokens. `query` is a sparse vector `(token id → weight)`.
SparseMatch {
column_id: u16,
query: Vec<(u32, f32)>,
k: usize,
},
/// MinHash/LSH set-similarity: candidate row ids whose set is similar to
/// `query` (a set of 64-bit token hashes), ranked by estimated Jaccard,
/// truncated to `k`. Approximate (LSH recall) — the caller re-verifies.
MinHashSimilar {
column_id: u16,
query: Vec<u64>,
k: usize,
},
/// Rows where `column_id` is NULL. Resolved by decoding the column and
/// collecting null positions — a column scan, but no row materialization.
/// Page-stat aware: pages with `null_count == 0` are skipped.
IsNull { column_id: u16 },
/// Rows where `column_id` is NOT NULL. The complement of [`Self::IsNull`].
/// Page-stat aware: pages with `null_count == row_count` are skipped.
IsNotNull { column_id: u16 },
}
/// A conjunctive query. Empty ⇒ all rows.
#[derive(Debug, Default, Clone)]
pub struct Query {
pub conditions: Vec<Condition>,
}
impl Query {
pub fn new() -> Self {
Self::default()
}
pub fn and(mut self, c: Condition) -> Self {
self.conditions.push(c);
self
}
pub fn pk(key: Vec<u8>) -> Self {
Self::new().and(Condition::Pk(key))
}
}
/// Canonical 64-bit cache key for a conjunctive native query + optional
/// projection at `epoch` (Phase 19.1 / 19.6). Conditions are commutative (they
/// are ANDed), so each condition is hashed into its own 64-bit digest, the
/// digests are sorted, then folded together — two queries with the same
/// semantics in a different order produce the same key. Within a condition,
/// `BitmapIn` values are deduped+sorted and the `SparseMatch` query is sorted
/// by token id. `epoch` is folded in so a `commit()` (which bumps it) orphans
/// every prior entry without an explicit sweep.
pub fn canonical_query_key(
conditions: &[Condition],
projection: Option<&[u16]>,
epoch: u64,
) -> u64 {
let fold = |seed: u64, b: u64| -> u64 { seed.wrapping_mul(0x9E3779B97F4A7C15).wrapping_add(b) };
let mut acc = fold(0xA5A5_A5A5_A5A5_A5A5, epoch);
// Order-independent: per-condition digests, sorted, then folded.
let mut digests: Vec<u64> = conditions.iter().map(hash_condition).collect();
digests.sort_unstable();
let n = digests.len() as u64;
acc = fold(acc, n);
for d in digests {
acc = fold(acc, d);
}
// Projection: sorted column ids (None ⇒ "all columns", distinct from any
// explicit projection incl. one listing every column, by intent).
match projection {
Some(p) => {
let mut p = p.to_vec();
p.sort_unstable();
p.dedup();
acc = fold(acc, 0x5E);
acc = fold(acc, p.len() as u64);
for id in p {
acc = fold(acc, id as u64);
}
}
None => {
acc = fold(acc, 0xA5);
}
}
acc
}
/// Hash a single condition into a 64-bit digest (order-independent w.r.t. its
/// siblings; see [`canonical_query_key`]). Floats are hashed via `to_bits` for
/// determinism.
fn hash_condition(c: &Condition) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
match c {
Condition::Pk(k) => {
0u8.hash(&mut h);
k.hash(&mut h);
}
Condition::BitmapEq { column_id, value } => {
1u8.hash(&mut h);
column_id.hash(&mut h);
value.hash(&mut h);
}
Condition::BitmapIn { column_id, values } => {
2u8.hash(&mut h);
column_id.hash(&mut h);
let mut v: Vec<&Vec<u8>> = values.iter().collect();
v.sort();
v.dedup();
v.len().hash(&mut h);
for b in v {
b.hash(&mut h);
}
}
Condition::Ann {
column_id,
query,
k,
} => {
3u8.hash(&mut h);
column_id.hash(&mut h);
k.hash(&mut h);
for f in query {
f.to_bits().hash(&mut h);
}
}
Condition::FmContains { column_id, pattern } => {
4u8.hash(&mut h);
column_id.hash(&mut h);
pattern.hash(&mut h);
}
Condition::FmContainsAll {
column_id,
patterns,
} => {
10u8.hash(&mut h);
column_id.hash(&mut h);
let mut sorted: Vec<&[u8]> = patterns.iter().map(|p| p.as_slice()).collect();
sorted.sort();
sorted.len().hash(&mut h);
for p in sorted {
p.hash(&mut h);
}
}
Condition::Range { column_id, lo, hi } => {
5u8.hash(&mut h);
column_id.hash(&mut h);
lo.hash(&mut h);
hi.hash(&mut h);
}
Condition::RangeF64 {
column_id,
lo,
lo_inclusive,
hi,
hi_inclusive,
} => {
6u8.hash(&mut h);
column_id.hash(&mut h);
lo.to_bits().hash(&mut h);
lo_inclusive.hash(&mut h);
hi.to_bits().hash(&mut h);
hi_inclusive.hash(&mut h);
}
Condition::SparseMatch {
column_id,
query,
k,
} => {
7u8.hash(&mut h);
column_id.hash(&mut h);
k.hash(&mut h);
let mut q: Vec<(u32, u32)> = query.iter().map(|(t, w)| (*t, w.to_bits())).collect();
q.sort_by_key(|(t, _)| *t);
for (t, wb) in q {
t.hash(&mut h);
wb.hash(&mut h);
}
}
Condition::MinHashSimilar {
column_id,
query,
k,
} => {
10u8.hash(&mut h);
column_id.hash(&mut h);
k.hash(&mut h);
let mut q = query.clone();
q.sort_unstable();
for t in q {
t.hash(&mut h);
}
}
Condition::IsNull { column_id } => {
8u8.hash(&mut h);
column_id.hash(&mut h);
}
Condition::IsNotNull { column_id } => {
9u8.hash(&mut h);
column_id.hash(&mut h);
}
Condition::BytesPrefix { column_id, prefix } => {
11u8.hash(&mut h);
column_id.hash(&mut h);
prefix.hash(&mut h);
}
}
h.finish()
}
/// Extract the column IDs referenced by a slice of conditions (Phase 19.1
/// hardening (c)). `Pk` references no user column (it's a row-id lookup) so it
/// contributes nothing. Used for conservative column-based cache invalidation:
/// a commit touching any of these columns may change the result.
pub fn condition_columns(conditions: &[Condition]) -> Vec<u16> {
let mut cols: Vec<u16> = conditions
.iter()
.filter_map(|c| match c {
Condition::Pk(_) => None,
Condition::BitmapEq { column_id, .. }
| Condition::BitmapIn { column_id, .. }
| Condition::BytesPrefix { column_id, .. }
| Condition::Ann { column_id, .. }
| Condition::FmContains { column_id, .. }
| Condition::FmContainsAll { column_id, .. }
| Condition::Range { column_id, .. }
| Condition::RangeF64 { column_id, .. }
| Condition::SparseMatch { column_id, .. }
| Condition::MinHashSimilar { column_id, .. }
| Condition::IsNull { column_id }
| Condition::IsNotNull { column_id } => Some(*column_id),
})
.collect();
cols.sort_unstable();
cols.dedup();
cols
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_chains() {
let q = Query::pk(b"k".to_vec()).and(Condition::Range {
column_id: 1,
lo: 0,
hi: 10,
});
assert_eq!(q.conditions.len(), 2);
}
/// Phase 19.6: order-independent canonicalization — the same conditions in a
/// different order, and a `BitmapIn` with shuffled/duplicate values, all
/// produce the same key.
#[test]
fn canonical_key_is_order_independent() {
let e = 7u64;
let a = Query::new()
.and(Condition::Range {
column_id: 1,
lo: 0,
hi: 10,
})
.and(Condition::BitmapEq {
column_id: 2,
value: b"x".to_vec(),
});
let b = Query::new()
.and(Condition::BitmapEq {
column_id: 2,
value: b"x".to_vec(),
})
.and(Condition::Range {
column_id: 1,
lo: 0,
hi: 10,
});
assert_eq!(
canonical_query_key(&a.conditions, None, e),
canonical_query_key(&b.conditions, None, e),
"condition order must not affect the key"
);
// BitmapIn dedup + sort.
let ordered = Condition::BitmapIn {
column_id: 3,
values: vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()],
};
let shuffled = Condition::BitmapIn {
column_id: 3,
values: vec![b"c".to_vec(), b"a".to_vec(), b"a".to_vec(), b"b".to_vec()],
};
assert_eq!(
canonical_query_key(std::slice::from_ref(&ordered), None, e),
canonical_query_key(&[shuffled], None, e),
"BitmapIn values must dedup+sort"
);
// Epoch changes the key (invalidation).
assert_ne!(
canonical_query_key(&a.conditions, None, e),
canonical_query_key(&a.conditions, None, e + 1),
"epoch must fold into the key"
);
// Projection None vs explicit differs (by intent).
let proj = vec![1u16, 2];
assert_ne!(
canonical_query_key(&a.conditions, None, e),
canonical_query_key(&a.conditions, Some(&proj), e),
"None projection must differ from an explicit projection"
);
// Projection order-independence.
let proj_rev = vec![2u16, 1];
assert_eq!(
canonical_query_key(&a.conditions, Some(&proj), e),
canonical_query_key(&a.conditions, Some(&proj_rev), e),
);
}
}