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
// SPDX-License-Identifier: BUSL-1.1
//! Sparse-vector inverted-index side-effects for `apply_point_put`: maintain
//! declared strict-schema `SparseVector` columns and drop a document's prior
//! sparse entries on delete/update. Mirrors `apply_put/vector.rs`, but sparse
//! vectors are strict-schema-only (there is no schemaless `sparse_params`
//! analog), carry no cross-engine surrogate (the string `doc_id` keys the
//! index directly), and the index `insert` is itself an upsert — so this file
//! has neither the schemaless arm nor the per-field remove-before-insert dance
//! the dense-vector path needs.
use crate::data::executor::core_loop::CoreLoop;
impl CoreLoop {
/// Strict-schema `SparseVector` column names declared on `collection`, or
/// empty when the collection has no strict schema / no sparse columns.
/// Shared by `apply_point_put_sparse_indexes` (which extracts + parses each
/// field's literal) and `remove_document_sparse_indexes` (which drops each
/// field's prior posting entries). Sparse vectors are dimensionless, so —
/// unlike `strict_vector_fields` — only the field NAME is returned.
pub(in crate::data::executor) fn strict_sparse_fields(
&self,
database_id: u64,
tid: u64,
collection: &str,
) -> Vec<String> {
let config_key = (
crate::types::DatabaseId::new(database_id),
crate::types::TenantId::new(tid),
collection.to_string(),
);
self.doc_configs
.get(&config_key)
.and_then(|config| {
if let nodedb_physical::physical_plan::StorageMode::Strict { ref schema } =
config.storage_mode
{
let fields: Vec<String> = schema
.columns
.iter()
.filter(|col| {
matches!(
col.column_type,
nodedb_types::columnar::ColumnType::SparseVector
)
})
.map(|col| col.name.clone())
.collect();
if fields.is_empty() {
None
} else {
Some(fields)
}
} else {
None
}
})
.unwrap_or_default()
}
/// Whether `collection` declares any strict-schema `SparseVector` column —
/// the single gate callers check before paying for any sparse-index
/// maintenance. Callers looping over many rows must call this ONCE before
/// the loop and thread the resulting bool through, mirroring the
/// `collection_has_vectors` contract.
pub(in crate::data::executor) fn collection_has_sparse(
&self,
database_id: u64,
tid: u64,
collection: &str,
) -> bool {
!self
.strict_sparse_fields(database_id, tid, collection)
.is_empty()
}
/// Sparse inverted-index side-effect: for every declared `SparseVector`
/// column, extract its string literal from the document body, parse it, and
/// upsert it into the corresponding `SparseInvertedIndex` keyed by
/// `document_id`.
///
/// `document_id` is the hex-surrogate storage `row_key` — the SAME id the
/// delete path (`remove_document_sparse_indexes`) and the engine handler
/// (`execute_sparse_insert` / `execute_sparse_search`) key on, so a search
/// reads back exactly what this write wrote. The index `insert` is an
/// upsert (it removes the doc's prior entries first), so a second put for
/// the same `document_id` replaces rather than duplicates. A missing field,
/// a non-string value, or an unparseable literal is skipped — mirroring the
/// dense-vector path's silent skip of malformed fields.
///
/// No-op (byte-identical to a collection without sparse columns) when
/// `strict_sparse_fields` is empty.
pub(in crate::data::executor) fn apply_point_put_sparse_indexes(
&mut self,
database_id: u64,
tid: u64,
collection: &str,
document_id: &str,
value: &[u8],
) {
let sparse_fields = self.strict_sparse_fields(database_id, tid, collection);
if sparse_fields.is_empty() {
return;
}
// Decode from MessagePack (internal format) — not JSON. Matches the
// `value` `apply_point_put` feeds the dense-vector indexer.
let Ok(nodedb_types::Value::Object(obj)) = nodedb_types::value_from_msgpack(value) else {
return;
};
for field in &sparse_fields {
let Some(nodedb_types::Value::String(literal)) = obj.get(field) else {
continue;
};
let Ok(sv) = nodedb_types::SparseVector::parse_literal(literal) else {
continue;
};
self.get_or_create_sparse_index(database_id, tid, collection, field)
.insert(document_id, &sv);
// Sparse indexes are in-memory with no redb store behind them; the
// checkpoint that persists them fires only on a dirty mark, exactly
// as the standalone `execute_sparse_insert` handler flags it.
self.checkpoint_coordinator.mark_dirty("vector", 1);
}
}
/// Drop every sparse-index posting entry a document produced, keyed by its
/// hex-surrogate storage `row_key`. Shared by the PointDelete cascade
/// (which orphans a removed row's sparse entries) and the PointUpdate
/// re-index (which clears the old literal before inserting the new one).
/// Mirrors `remove_document_vector_indexes`. No-op when the collection
/// declares no sparse columns.
pub(in crate::data::executor) fn remove_document_sparse_indexes(
&mut self,
database_id: u64,
tid: u64,
collection: &str,
row_key: &str,
) {
let sparse_fields = self.strict_sparse_fields(database_id, tid, collection);
for field in &sparse_fields {
if self
.get_or_create_sparse_index(database_id, tid, collection, field)
.delete(row_key)
{
self.checkpoint_coordinator.mark_dirty("vector", 1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bridge::dispatch::{BridgeRequest, BridgeResponse};
use crate::engine::document::store::{CollectionConfig, surrogate_to_doc_id};
use nodedb_bridge::buffer::{Consumer, Producer, RingBuffer};
use nodedb_physical::physical_plan::StorageMode;
use nodedb_types::columnar::{ColumnDef, ColumnType, StrictSchema};
use nodedb_types::{Surrogate, Value};
/// Holds the bridge endpoints + tempdir alive for the core's lifetime. The
/// tests drive `apply_point_put_sparse_indexes` directly and never tick the
/// event loop, so the far ends are unused — they just must not be dropped.
struct CoreHarness {
core: CoreLoop,
_req_tx: Producer<BridgeRequest>,
_resp_rx: Consumer<BridgeResponse>,
_dir: tempfile::TempDir,
}
fn make_core() -> CoreHarness {
let dir = tempfile::tempdir().expect("tempdir");
let (req_tx, req_rx) = RingBuffer::channel::<BridgeRequest>(64);
let (resp_tx, resp_rx) = RingBuffer::channel::<BridgeResponse>(64);
let core = CoreLoop::open(
0,
req_rx,
resp_tx,
dir.path(),
std::sync::Arc::new(nodedb_types::OrdinalClock::new()),
)
.expect("open core");
CoreHarness {
core,
_req_tx: req_tx,
_resp_rx: resp_rx,
_dir: dir,
}
}
/// Seed a strict collection whose schema declares a `SparseVector` column
/// named `field`, so `strict_sparse_fields` reports it.
fn register_strict_sparse(core: &mut CoreLoop, tid: u64, collection: &str, field: &str) {
let schema = StrictSchema::new(vec![
ColumnDef::required("_rowid", ColumnType::Int64),
ColumnDef::nullable(field, ColumnType::SparseVector),
])
.expect("schema");
let config =
CollectionConfig::new(collection).with_storage_mode(StorageMode::Strict { schema });
core.doc_configs.insert(
(
crate::types::DatabaseId::DEFAULT,
crate::types::TenantId::new(tid),
collection.to_string(),
),
config,
);
}
/// A document body carrying a sparse-vector string literal for `field`.
fn doc_with_sparse(field: &str, literal: &str) -> Vec<u8> {
let mut obj = std::collections::HashMap::new();
obj.insert(field.to_string(), Value::String(literal.into()));
nodedb_types::value_to_msgpack(&Value::Object(obj)).expect("encode doc")
}
fn doc_count(core: &CoreLoop, db: u64, tid: u64, collection: &str, field: &str) -> usize {
let key = CoreLoop::sparse_index_key(db, tid, collection, field);
core.sparse_vector_indexes
.get(&key)
.map(|idx| idx.doc_count())
.unwrap_or(0)
}
/// A put of a strict document carrying a `SparseVector` field must upsert
/// exactly one document into that field's sparse inverted index, under the
/// hex-surrogate row key.
#[test]
fn put_indexes_sparse_field_once() {
let mut harness = make_core();
let core = &mut harness.core;
let db = 0u64;
let tid = 1u64;
let collection = "docs";
let field = "terms";
let row_key = surrogate_to_doc_id(Surrogate::new(1));
register_strict_sparse(core, tid, collection, field);
let doc = doc_with_sparse(field, "{3:0.5, 7:1.5}");
core.apply_point_put_sparse_indexes(db, tid, collection, &row_key, &doc);
assert_eq!(
doc_count(core, db, tid, collection, field),
1,
"the put must index exactly one document in the sparse field's index"
);
}
/// A second put for the same row key must replace (upsert), not duplicate —
/// the sparse index stays at one document.
#[test]
fn second_put_for_same_row_key_replaces_not_duplicates() {
let mut harness = make_core();
let core = &mut harness.core;
let db = 0u64;
let tid = 1u64;
let collection = "docs";
let field = "terms";
let row_key = surrogate_to_doc_id(Surrogate::new(1));
register_strict_sparse(core, tid, collection, field);
core.apply_point_put_sparse_indexes(
db,
tid,
collection,
&row_key,
&doc_with_sparse(field, "{3:0.5, 7:1.5}"),
);
core.apply_point_put_sparse_indexes(
db,
tid,
collection,
&row_key,
&doc_with_sparse(field, "{1:0.9}"),
);
assert_eq!(
doc_count(core, db, tid, collection, field),
1,
"a second put for the same row key must replace the prior entry, not append a duplicate"
);
}
/// `remove_document_sparse_indexes` must drop the document's entry, taking
/// the field's index back to zero documents.
#[test]
fn remove_drops_sparse_entry() {
let mut harness = make_core();
let core = &mut harness.core;
let db = 0u64;
let tid = 1u64;
let collection = "docs";
let field = "terms";
let row_key = surrogate_to_doc_id(Surrogate::new(1));
register_strict_sparse(core, tid, collection, field);
core.apply_point_put_sparse_indexes(
db,
tid,
collection,
&row_key,
&doc_with_sparse(field, "{3:0.5, 7:1.5}"),
);
assert_eq!(doc_count(core, db, tid, collection, field), 1);
core.remove_document_sparse_indexes(db, tid, collection, &row_key);
assert_eq!(
doc_count(core, db, tid, collection, field),
0,
"remove must drop the document from the sparse field's index"
);
}
/// A collection with no `SparseVector` column is untouched: no index is
/// created and the maintenance call is a pure no-op.
#[test]
fn non_sparse_collection_is_unaffected() {
let mut harness = make_core();
let core = &mut harness.core;
let db = 0u64;
let tid = 1u64;
let collection = "plain";
let row_key = surrogate_to_doc_id(Surrogate::new(1));
// No strict sparse schema registered.
assert!(!core.collection_has_sparse(
crate::types::DatabaseId::DEFAULT.as_u64(),
tid,
collection,
));
core.apply_point_put_sparse_indexes(
db,
tid,
collection,
&row_key,
&doc_with_sparse("terms", "{3:0.5}"),
);
assert!(
core.sparse_vector_indexes.is_empty(),
"a collection without a SparseVector column must create no sparse index"
);
}
}