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
//! Index handler: embed atoms and build/persist the Vamana ANN index.
use std::collections::BTreeMap;
use std::sync::Arc;
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, sql_err, DEFAULT_EMBED_BATCH};
use super::vamana;
use super::KnowledgeHandlers;
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" }),
);
}
// Every other registered engine gets the same batch, best-effort (issue
// #1115): a secondary-engine failure does not affect indexed/failed/
// skipped, which stay keyed on the default model as before this fix.
let secondary_model_names: Vec<String> = runtime
.registered_embedding_model_names()
.into_iter()
.filter(|m| m != default_model_name)
.collect();
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: Vec<Atom> = 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: "SELECT * FROM knowledge_atoms WHERE namespace = ?1 AND (id = ?2 OR slug = ?2) AND deleted_at IS NULL LIMIT 1".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);
}
}
}
out
} else {
let mut out = Vec::new();
let mut offset = 0i64;
loop {
let mut reader = sql
.reader()
.await
.map_err(|e| sql_err("index page reader", e))?;
let rows = reader
.query_all(SqlStatement {
sql: "SELECT * FROM knowledge_atoms WHERE namespace = ?1 AND deleted_at IS NULL ORDER BY created_at LIMIT ?2 OFFSET ?3".into(),
params: vec![
SqlValue::Text(ns.clone()),
SqlValue::Integer(batch_size as i64),
SqlValue::Integer(offset),
],
label: None,
})
.await
.map_err(|e| sql_err("index page", e))?;
let n = rows.len();
out.extend(rows.iter().filter_map(atom_from_row));
if n < batch_size {
break;
}
offset += n as i64;
}
out
};
let total = atoms.len();
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 chunk in atoms.chunks(batch_size) {
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() {
continue;
}
let texts: Vec<String> = staged.iter().map(|(_, text)| text.clone()).collect();
// Every configured engine embeds and writes its own batch independently
// (issue #1115): a secondary-engine failure does not affect `indexed`/
// `failed`, which stay keyed on the default model, as before this fix.
// Fan the models out concurrently — each is an independent embed call
// plus vector write, so serializing them only adds up their latencies.
let staged = Arc::new(staged);
let texts = Arc::new(texts);
let default_handle = tokio::spawn(embed_and_insert_model(
runtime.clone(),
token.clone(),
default_model_name.to_string(),
true,
Arc::clone(&staged),
Arc::clone(&texts),
));
let secondary_handles: Vec<_> = secondary_model_names
.iter()
.map(|model_name| {
tokio::spawn(embed_and_insert_model(
runtime.clone(),
token.clone(),
model_name.clone(),
false,
Arc::clone(&staged),
Arc::clone(&texts),
))
})
.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.
match default_handle.await {
Ok(outcome) => {
indexed += outcome.affected as usize;
failed += outcome.failed as usize;
truncation_by_model
.entry(outcome.model_name)
.or_default()
.merge(outcome.truncation);
}
Err(e) => {
tracing::warn!(error = %e, "knowledge index default-model task panicked");
failed += staged.len();
}
}
for handle in secondary_handles {
// Secondary-engine failures are best-effort (logged inside the
// task) and never affect `indexed`/`failed`; only a task panic
// needs handling here.
match handle.await {
Ok(outcome) => truncation_by_model
.entry(outcome.model_name)
.or_default()
.merge(outcome.truncation),
Err(e) => {
tracing::warn!(error = %e, "knowledge index secondary-model task panicked");
}
}
}
if let Some(cb) = on_progress {
cb(indexed 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,
}))
}
}
/// One embedding model's outcome from [`embed_and_insert_model`], counted in vectors.
struct ModelIndexOutcome {
model_name: String,
affected: u64,
failed: u64,
truncation: khive_runtime::retrieval::EmbeddingTruncationReport,
}
/// Embed one chunk's staged atoms with `model_name` and batch-insert the resulting
/// vectors. Split out of `index` so the default model and every secondary model
/// (issue #1115) can run as independent `tokio::spawn` tasks instead of embedding
/// and writing serially, one model at a time. `is_default` only selects tracing
/// wording — the default model's outcome is applied to the caller's `indexed`/
/// `failed` counters; secondary-model outcomes are best-effort and only logged.
async fn embed_and_insert_model(
runtime: KhiveRuntime,
token: NamespaceToken,
model_name: String,
is_default: bool,
staged: Arc<Vec<(uuid::Uuid, String)>>,
texts: Arc<Vec<String>>,
) -> ModelIndexOutcome {
let outcomes = match runtime
.embed_document_batch_with_model_outcomes(&model_name, &texts)
.await
{
Ok(e) => e,
Err(e) => {
if is_default {
tracing::warn!(
batch_size = staged.len(),
error = %e,
"embed_batch failed; atoms cannot be recalled until reindexed"
);
} else {
tracing::warn!(
model = %model_name,
batch_size = staged.len(),
error = %e,
"knowledge secondary-engine embed_batch failed; \
atoms miss a vector for this engine until backfill"
);
}
return ModelIndexOutcome {
model_name,
affected: 0,
failed: if is_default { staged.len() as u64 } else { 0 },
truncation: Default::default(),
};
}
};
if outcomes.len() != staged.len() {
if is_default {
tracing::warn!(
expected = staged.len(),
got = outcomes.len(),
"embed_batch returned wrong number of vectors; atoms cannot be recalled until reindexed"
);
} else {
tracing::warn!(
model = %model_name,
expected = staged.len(),
got = outcomes.len(),
"knowledge secondary-engine embed_batch returned wrong \
vector count; skipping this engine for the batch"
);
}
return ModelIndexOutcome {
model_name,
affected: 0,
failed: if is_default { staged.len() as u64 } else { 0 },
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) => {
if is_default {
tracing::warn!(error = %e, "knowledge vector store unavailable");
} else {
tracing::warn!(
model = %model_name,
error = %e,
"knowledge secondary-engine vector store unavailable"
);
}
return ModelIndexOutcome {
model_name,
affected: 0,
failed: if is_default { staged.len() as u64 } else { 0 },
truncation,
};
}
};
let ns_str = token.namespace().as_str().to_string();
let records: Vec<VectorRecord> = staged
.iter()
.zip(outcomes.iter())
.map(|((id, _), outcome)| VectorRecord {
subject_id: *id,
kind: SubstrateKind::Entity,
namespace: ns_str.clone(),
field: "knowledge.atom".to_string(),
embedding_model: Some(model_name.clone()),
vectors: vec![outcome.vector.clone()],
updated_at: chrono::Utc::now(),
})
.collect();
match vectors.insert_batch(records).await {
Ok(summary) => {
if summary.failed > 0 {
if is_default {
tracing::warn!(
failed = summary.failed,
error = %summary.first_error,
"knowledge vector batch insert had failures"
);
} else {
tracing::warn!(
model = %model_name,
failed = summary.failed,
error = %summary.first_error,
"knowledge secondary-engine vector batch insert had failures"
);
}
}
ModelIndexOutcome {
model_name,
affected: summary.affected,
failed: summary.failed,
truncation,
}
}
Err(e) => {
if is_default {
tracing::warn!(error = %e, "knowledge vector store unavailable");
} else {
tracing::warn!(
model = %model_name,
error = %e,
"knowledge secondary-engine vector store unavailable"
);
}
ModelIndexOutcome {
model_name,
affected: 0,
failed: if is_default { staged.len() as u64 } else { 0 },
truncation,
}
}
}
}