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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Index handler: embed atoms and build/persist the Vamana ANN index.
use std::collections::BTreeMap;
use serde_json::{json, Value};
use khive_runtime::{KhiveRuntime, NamespaceToken, RuntimeError};
use khive_storage::types::{SqlStatement, SqlValue, VectorRecord};
use khive_types::SubstrateKind;
use super::schema::{Atom, IndexParams};
use super::util::{
atom_embed_text, atom_from_row, deser, row_i64, row_str, sql_err, DEFAULT_EMBED_BATCH,
};
use super::vamana;
use super::KnowledgeHandlers;
enum IndexAtoms {
Explicit(Vec<Atom>),
CatalogueIds(Vec<String>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct IndexCursor {
pub(super) created_at: i64,
pub(super) id: String,
}
pub(super) struct CataloguePage {
pub(super) ids: Vec<String>,
pub(super) cursor: Option<IndexCursor>,
pub(super) raw_len: usize,
}
/// Read one short-lived page in the catalogue's `(created_at, id)` order.
/// Advance past the last raw row even when that row cannot decode as an atom.
/// Continuously live rows with unchanged ordering keys are visited once. Rows
/// created, deleted or restored during traversal may or may not be visited. A
/// namespace move counts as leaving or entering the namespace and has the same
/// may-or-may-not guarantee.
pub(super) async fn read_catalogue_page(
runtime: &KhiveRuntime,
namespace: &str,
batch_size: usize,
cursor: Option<&IndexCursor>,
) -> Result<CataloguePage, RuntimeError> {
let mut params = vec![
SqlValue::Text(namespace.to_owned()),
SqlValue::Integer(batch_size as i64),
];
let query = if let Some(cursor) = cursor {
params.push(SqlValue::Integer(cursor.created_at));
params.push(SqlValue::Text(cursor.id.clone()));
khive_runtime::sql!("knowledge_index_atom_after")
} else {
khive_runtime::sql!("knowledge_index_atom_page")
};
let sql = runtime.sql();
let mut reader = sql
.reader()
.await
.map_err(|e| sql_err("index page reader", e))?;
let rows = reader
.query_all(SqlStatement {
sql: query.into(),
params,
label: None,
})
.await
.map_err(|e| sql_err("index page", e))?;
drop(reader);
let cursor = rows
.last()
.map(|row| {
let created_at = row_i64(row, "created_at")
.ok_or_else(|| sql_err("index page cursor", "missing raw creation timestamp"))?;
let id = row_str(row, "id")
.ok_or_else(|| sql_err("index page cursor", "missing raw atom ID"))?;
Ok::<_, RuntimeError>(IndexCursor { created_at, id })
})
.transpose()?;
let ids = rows
.iter()
.filter_map(|row| {
atom_from_row(row)?;
row_str(row, "id")
})
.collect();
Ok(CataloguePage {
ids,
cursor,
raw_len: rows.len(),
})
}
impl KnowledgeHandlers {
pub(crate) async fn index(
runtime: &KhiveRuntime,
token: &NamespaceToken,
params: Value,
ann: &vamana::SharedAnn,
on_progress: Option<&(dyn Fn(u64, u64) + Send + Sync)>,
) -> Result<Value, RuntimeError> {
let p: IndexParams = deser(params)?;
let rebuild_ann = p.rebuild_ann.unwrap_or(false);
let ns = token.namespace().as_str().to_owned();
let default_model_name = runtime.default_embedder_name();
if default_model_name.is_empty() {
return Ok(json!({
"indexed": 0,
"skipped": 0,
"failed": 0,
"total": 0,
"reason": "no embedding model configured",
}));
}
let sql = runtime.sql();
let batch_size = p.batch_size.unwrap_or(DEFAULT_EMBED_BATCH).clamp(1, 1000);
// insert_only is accepted for API compatibility but no longer drives a
// pre-delete loop: SqliteVecStore::insert atomically replaces via its own
// transacted DELETE+INSERT regardless of this flag.
let _insert_only = p.insert_only.unwrap_or(false);
let atoms = if let Some(ref ids) = p.ids {
let mut out = Vec::with_capacity(ids.len());
let mut reader = sql.reader().await.map_err(|e| sql_err("index reader", e))?;
for id_or_slug in ids {
let row = reader
.query_row(SqlStatement {
sql: khive_runtime::sql!("knowledge_index_atom_target").into(),
params: vec![
SqlValue::Text(ns.clone()),
SqlValue::Text(id_or_slug.clone()),
],
label: None,
})
.await
.map_err(|e| sql_err("index atom lookup", e))?;
if let Some(r) = row {
if let Some(a) = atom_from_row(&r) {
out.push(a);
}
}
}
IndexAtoms::Explicit(out)
} else {
let mut out = Vec::new();
let mut cursor = None;
loop {
let page = read_catalogue_page(runtime, &ns, batch_size, cursor.as_ref()).await?;
// Only IDs survive this page; payloads are reloaded before embedding.
out.extend(page.ids);
if page.raw_len < batch_size {
break;
}
cursor = page.cursor;
}
IndexAtoms::CatalogueIds(out)
};
let total = match &atoms {
IndexAtoms::Explicit(atoms) => atoms.len(),
IndexAtoms::CatalogueIds(ids) => ids.len(),
};
#[cfg(test)]
if matches!(&atoms, IndexAtoms::CatalogueIds(_)) {
super::index_catalogue_tests::after_capture().await;
}
let mut indexed = 0usize;
let mut skipped = 0usize;
let mut failed = 0usize;
let mut truncation_by_model =
BTreeMap::<String, khive_runtime::retrieval::EmbeddingTruncationReport>::new();
if let Some(cb) = on_progress {
cb(0, total as u64);
}
for start in (0..total).step_by(batch_size) {
let end = (start + batch_size).min(total);
let reloaded;
let chunk: &[Atom] = match &atoms {
IndexAtoms::Explicit(atoms) => &atoms[start..end],
IndexAtoms::CatalogueIds(ids) => {
let rows = match async {
let mut reader = sql
.reader()
.await
.map_err(|e| sql_err("index page reader", e))?;
reader
.query_all(SqlStatement {
sql: khive_runtime::sql!("knowledge_index_atom_batch").into(),
params: vec![
SqlValue::Text(ns.clone()),
SqlValue::Text(json!(&ids[start..end]).to_string()),
],
label: None,
})
.await
.map_err(|e| sql_err("index page", e))
}
.await
{
Ok(rows) => rows,
Err(error) => {
if indexed > 0 {
vamana::invalidate_snapshot(runtime, &ns).await;
vamana::clear_namespace(ann, &ns).await;
}
return Err(error);
}
};
reloaded = rows.iter().filter_map(atom_from_row).collect::<Vec<_>>();
skipped += (end - start).saturating_sub(reloaded.len());
reloaded.as_slice()
}
};
let mut staged: Vec<(uuid::Uuid, String)> = Vec::with_capacity(chunk.len());
for atom in chunk {
let text = atom_embed_text(atom);
if text.trim().is_empty() {
skipped += 1;
continue;
}
staged.push((atom.id, text));
}
if staged.is_empty() {
if let Some(cb) = on_progress {
cb(end as u64, total as u64);
}
continue;
}
let texts: Vec<String> = staged.iter().map(|(_, text)| text.clone()).collect();
// Track which atoms in this chunk had their vector persisted, so a
// failed insert is reported as `failed` rather than silently counted
// as `indexed`. A failed vector write means recall cannot retrieve
// that atom — that is a failure, not a success.
//
// No pre-delete loop: SqliteVecStore::insert_batch wraps each record's
// own DELETE+INSERT in a savepoint, so a failed INSERT rolls back only
// that record's DELETE and the prior vector survives (no-worse-than-
// stale). A separate pre-delete committed before insert would
// re-introduce the stranding window.
// Knowledge retrieval embeds and probes only the default model. Keep
// atom indexing on that same model so every vector written has a read
// path; secondary-model fan-out belongs with model-aware retrieval.
// Await in the dispatch task so usage accounting observes the work.
let outcome =
embed_and_insert_default_model(runtime, token, default_model_name, &staged, &texts)
.await;
indexed += outcome.affected as usize;
failed += outcome.failed as usize;
truncation_by_model
.entry(default_model_name.to_string())
.or_default()
.merge(outcome.truncation);
if let Some(cb) = on_progress {
cb(end as u64, total as u64);
}
}
// Any vector write invalidates the existing snapshot — the corpus has changed.
if indexed > 0 {
vamana::invalidate_snapshot(runtime, &ns).await;
vamana::clear_namespace(ann, &ns).await;
}
let mut ann_count: Option<usize> = None;
let mut ann_failed = false;
let is_full_corpus = p.ids.is_none();
if rebuild_ann && is_full_corpus && indexed > 0 {
if let Some(cb) = on_progress {
cb(total as u64, total as u64);
}
let model_name = runtime.default_embedder_name();
// Capture the namespace's write-generation floor before scanning the
// corpus, mirroring `ensure_ann_for_model`'s `target_generation` capture
// (PR #815); `install_if_fresher` then fences this direct
// rebuild insertion with the same generation check the warm path uses,
// instead of the old presence-only `insert_ann_if_absent`.
let build_generation = vamana::current_generation(ann, &ns);
let key = vamana::AnnKey::new(&ns, model_name);
let scan_authority = match vamana::prepare_full_corpus_scan(runtime, ann, &key).await {
Ok(authority) => Some(authority),
Err(e) => {
tracing::error!(error = %e, "failed to establish Vamana full-scan authority");
ann_failed = true;
None
}
};
// Build from the shared corpus scan (ORDER BY subject_id) so the persisted
// v2 content_hash matches the warm-path live_content_hash. Building from
// atom-iteration order persists a hash the warm path always reads as stale.
if let Some(scan_authority) = scan_authority {
match vamana::load_and_build_from_vector_store(runtime, token, model_name).await {
Ok(Some(bridge)) => {
let n = bridge.num_vectors();
ann_count = Some(n);
let published = vamana::checkpoint_raise_compact_readopt(
runtime,
ann,
&key,
bridge,
build_generation,
scan_authority,
)
.await;
if published {
eprintln!(" Vamana ANN built ({n} vectors)");
} else {
tracing::warn!(
"Vamana ANN publication was fenced; retrying on the next rebuild"
);
ann_failed = true;
}
}
Ok(None) => {}
Err(e) => {
tracing::error!(error = %e, "failed to build Vamana ANN index");
eprintln!(" Vamana ANN build failed: {e}");
ann_failed = true;
}
}
}
}
Ok(json!({
"indexed": indexed,
"skipped": skipped,
"failed": failed,
"total": total,
"ann_vectors": ann_count,
"ann_failed": ann_failed,
"truncation_by_model": truncation_by_model,
}))
}
}
/// Rebuild both external-content FTS indexes and verify that each one matches
/// its content object. The writer batch is atomic: callers never receive a
/// successful repair acknowledgement after only one index was rebuilt.
///
/// Not reachable from the `knowledge.index` MCP verb: rebuilding both indexes
/// touches the whole database regardless of the caller's namespace, so the
/// only entry point is the `kkernel reindex` operator CLI, via
/// [`crate::rebuild_knowledge_fts_indexes`]. The returned value reports what the rebuild
/// actually did — index names, wall time, and the integrity-check outcome —
/// so that CLI path never has to promise a rebuild happened without evidence.
pub(crate) async fn rebuild_fts_indexes(runtime: &KhiveRuntime) -> Result<Value, RuntimeError> {
let start = std::time::Instant::now();
let mut writer = runtime
.sql()
.writer()
.await
.map_err(|e| sql_err("knowledge FTS rebuild writer", e))?;
writer
.execute_batch(vec![
SqlStatement {
sql: khive_runtime::sql!("knowledge_fts_rebuild").into(),
params: vec![],
label: Some("knowledge.index.fts_knowledge.rebuild".into()),
},
SqlStatement {
sql: khive_runtime::sql!("knowledge_sections_fts_rebuild").into(),
params: vec![],
label: Some("knowledge.index.fts_sections.rebuild".into()),
},
SqlStatement {
sql: khive_runtime::sql!("knowledge_fts_integrity_check").into(),
params: vec![],
label: Some("knowledge.index.fts_knowledge.integrity".into()),
},
SqlStatement {
sql: khive_runtime::sql!("knowledge_sections_fts_integrity_check").into(),
params: vec![],
label: Some("knowledge.index.fts_sections.integrity".into()),
},
])
.await
.map_err(|e| sql_err("knowledge FTS rebuild", e))?;
// The writer batch above is one atomic transaction (ADR-067 Component A):
// either both rebuild statements AND both rank-1 integrity checks
// succeeded, or the whole thing rolled back and the `?` above already
// returned. Reaching this line therefore means integrity passed for both.
Ok(json!({
"indexes": ["fts_knowledge", "fts_sections"],
"elapsed_ms": start.elapsed().as_millis() as u64,
"integrity_ok": true,
}))
}
/// One default-model indexing outcome, counted in vectors.
struct ModelIndexOutcome {
affected: u64,
failed: u64,
truncation: khive_runtime::retrieval::EmbeddingTruncationReport,
}
/// Embed one chunk's staged atoms with the default model and batch-insert the
/// resulting vectors. Knowledge search has no model selector or multi-model
/// fusion, so this helper deliberately cannot target a secondary model.
async fn embed_and_insert_default_model(
runtime: &KhiveRuntime,
token: &NamespaceToken,
model_name: &str,
staged: &[(uuid::Uuid, String)],
texts: &[String],
) -> ModelIndexOutcome {
let outcomes = match runtime
.embed_document_batch_with_model_outcomes(model_name, texts)
.await
{
Ok(e) => e,
Err(e) => {
tracing::warn!(
batch_size = staged.len(),
error = %e,
"embed_batch failed; atoms cannot be recalled until reindexed"
);
return ModelIndexOutcome {
affected: 0,
failed: staged.len() as u64,
truncation: Default::default(),
};
}
};
if outcomes.len() != staged.len() {
tracing::warn!(
expected = staged.len(),
got = outcomes.len(),
"embed_batch returned wrong number of vectors; atoms cannot be recalled until reindexed"
);
return ModelIndexOutcome {
affected: 0,
failed: staged.len() as u64,
truncation: Default::default(),
};
}
let mut truncation = khive_runtime::retrieval::EmbeddingTruncationReport::default();
for outcome in &outcomes {
truncation.observe(outcome);
}
let vectors = match runtime.vectors_for_model(token, model_name) {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, "knowledge vector store unavailable");
return ModelIndexOutcome {
affected: 0,
failed: staged.len() as u64,
truncation,
};
}
};
let ns_str = token.namespace().as_str().to_string();
let records: Vec<VectorRecord> = staged
.iter()
.zip(outcomes.iter())
.map(|((id, _text), outcome)| VectorRecord {
subject_id: *id,
kind: SubstrateKind::Entity,
namespace: ns_str.clone(),
field: "knowledge.atom".to_string(),
embedding_model: Some(model_name.to_string()),
vectors: vec![outcome.vector.clone()],
text_fingerprint: outcome.prepared_text_fingerprint.clone(),
updated_at: chrono::Utc::now(),
})
.collect();
match vectors.insert_batch(records).await {
Ok(summary) => {
if summary.failed > 0 {
tracing::warn!(
failed = summary.failed,
error = %summary.first_error,
"knowledge vector batch insert had failures"
);
}
ModelIndexOutcome {
affected: summary.affected,
failed: summary.failed,
truncation,
}
}
Err(e) => {
tracing::warn!(error = %e, "knowledge vector store unavailable");
ModelIndexOutcome {
affected: 0,
failed: staged.len() as u64,
truncation,
}
}
}
}