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
use crate::document::hako_doc::HakoDoc;
use crate::index::manager::IndexManager;
use crate::document::value::Value;
use std::sync::Arc;
/// Unified indexing service for all index families.
/// Keeps update/backfill logic in one place for easier maintenance.
pub struct IndexingService;
impl IndexingService {
pub fn apply_put(
manager: &mut IndexManager,
collection: &str,
doc_id: &str,
doc: &HakoDoc,
) {
manager.index_document(collection, doc_id, doc);
}
pub fn apply_delete(
manager: &mut IndexManager,
collection: &str,
doc_id: &str,
doc: &HakoDoc,
) {
manager.remove_document(collection, doc_id, doc);
}
/// P2 inflate-on-index: resolve blob-resident values of `fields` so a
/// live write indexes exactly what backfill would (backfill resolves
/// before indexing). Returns None when nothing needs resolving
/// (caller indexes the original, zero extra alloc). Unresolvable
/// blobs become Null and are skipped downstream — same rule as the
/// read path, never a worker panic.
pub fn resolve_vector_blobs(
doc: &HakoDoc,
fields: &[String],
blob_mgr: Option<&crate::storage::blob::BlobManager>,
) -> Option<HakoDoc> {
let mgr = blob_mgr?;
if !fields
.iter()
.any(|f| matches!(doc.get(f), Some(Value::BlobLink { .. })))
{
return None;
}
let mut out = doc.clone();
for f in fields {
if let Some(Value::BlobLink { offset, len }) = out.get(f) {
let (offset, len) = (*offset, *len);
let v = crate::query::executor::worker::resolve_single_blob_in_worker(
mgr, offset, len,
);
out.insert(f.clone(), v);
}
}
Some(out)
}
pub fn backfill_secondary<'a, I>(manager: &mut IndexManager, collection: &str, docs: I)
where
I: IntoIterator<Item = (&'a str, &'a HakoDoc)>,
{
for (doc_id, doc) in docs {
if let Some(sec_map) = manager.secondary.get_mut(collection) {
for (field_name, index) in sec_map.iter_mut() {
// VIRTUAL FIELD MAPPING
let val_opt = match field_name.as_str() {
"id" => Some(Value::String(doc_id.to_string())),
"_time" => Some(Value::Int(doc._time)),
_ => doc.get(field_name).cloned(),
};
if let Some(val) = val_opt {
index.insert(
crate::index::index_key::encode_scalar(&val),
doc_id.to_string(),
);
}
}
}
}
}
pub fn backfill_fts<'a, I>(manager: &mut IndexManager, collection: &str, docs: I)
where
I: IntoIterator<Item = (&'a str, &'a HakoDoc)>,
{
for (doc_id, doc) in docs {
if let Some(fts_map) = manager.fts.get_mut(collection) {
for (field_name, index) in fts_map.iter_mut() {
if let Some(crate::document::value::Value::String(text)) = doc.get(field_name) {
index.insert(text, doc_id.to_string());
}
}
}
}
}
/// Borrowed secondary backfill over stored bytes: framing walk plus
/// direct key encoding, no HakoDoc materialization. Returns false
/// unless the collection holds ONLY secondary indexes — fts and
/// composite entries need the owned path (caller falls back, same
/// outcome). All-or-nothing per doc: a doc any of whose matched
/// fields fail is skipped whole, exactly like owned decode failing.
pub fn backfill_secondary_borrowed(
manager: &mut IndexManager,
collection: &str,
docs: &[(String, Vec<u8>)],
) -> bool {
if manager.fts.contains_key(collection) {
return false;
}
// Vector defs need the owned path too: embeddings decode through
// index_document's HNSW hook, which the byte-level path below
// never touches.
if manager.vector.contains_key(collection) {
return false;
}
// Traverse defs need the owned path too: backlinks decode through
// index_document's hook over full docs (refs live in any field,
// and any collection's docs may point at tracked targets — so any
// tracking anywhere forces the owned rescan everywhere).
if !manager.traverse.is_empty() {
return false;
}
if manager
.composite
.all_indexes()
.any(|idx| idx.definition.collection == collection)
{
return false;
}
let Some(sec_map) = manager.secondary.get_mut(collection) else {
// Nothing registered: trivially complete.
return true;
};
let fields: Vec<String> = sec_map.keys().cloned().collect();
// ponytail: virtual fields resolve without stored bytes (same as
// the owned path, which maps them from doc_id/_time, never from a
// literal same-named field).
let want_id = fields.iter().any(|f| f == "id");
let want_time = fields.iter().any(|f| f == "_time");
crate::index::index_key::ENC_SCRATCH.with(|scratch| {
let mut enc = scratch.borrow_mut();
for (doc_id, bytes) in docs {
let Some(view) = crate::document::hako_doc::HakoDocView::new(bytes)
else {
continue;
};
// Pass 1: match + exact framing walk (owned-decode
// strictness: short/truncated docs index nothing).
let mut it = view.iter();
let mut matched: Vec<(&str, u8, &[u8])> = Vec::new();
for (key, tag, vdata) in it.by_ref() {
// Virtuals handled below from doc_id/_time.
if key == "id" || key == "_time" {
continue;
}
if fields.iter().any(|f| f == key) {
matched.push((key, tag, vdata));
}
}
if it.remaining() != 0 || it.position() != bytes.len() {
continue;
}
// Pass 2: encode all keys first; a single bad field
// discards the doc (owned parity), then insert.
let id_shared: Arc<str> = Arc::from(doc_id.as_str());
let mut staged: Vec<(usize, Vec<u8>)> = Vec::with_capacity(matched.len());
let mut ok = true;
for (key, tag, vdata) in matched {
let Some(pos) = fields.iter().position(|f| f == key) else {
ok = false;
break;
};
enc.clear();
if !crate::index::index_key::encode_raw_scalar(tag, vdata, &mut enc) {
enc.clear();
match crate::document::hako_doc::decode_value(tag, vdata) {
Some(v) => crate::index::index_key::encode_scalar_into(&v, &mut enc),
None => {
ok = false;
break;
}
}
}
staged.push((pos, enc.clone()));
}
if !ok {
continue;
}
// Virtual entries (owned path maps these identically).
if want_id {
if let Some(pos) = fields.iter().position(|f| f == "id") {
enc.clear();
crate::index::index_key::encode_str_scalar_into(doc_id, &mut enc);
staged.push((pos, enc.clone()));
}
}
if want_time {
if let Some(pos) = fields.iter().position(|f| f == "_time") {
enc.clear();
crate::index::index_key::encode_scalar_into(
&crate::document::value::Value::Int(view._time),
&mut enc,
);
staged.push((pos, enc.clone()));
}
}
for (pos, key) in staged {
if let Some(sec) = sec_map.get_mut(fields[pos].as_str()) {
sec.insert_borrowed(&key, id_shared.clone());
}
}
}
});
true
}
pub fn backfill_composite<'a, I>(manager: &mut IndexManager, collection: &str, docs: I)
where
I: IntoIterator<Item = (&'a str, &'a HakoDoc)> + Clone,
{
manager.composite.index_batch(collection, docs);
}
}