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
//! Database Helpers - Batch Index Building
//!
//! Extracted from database_legacy.rs
//! Contains batch index building methods called during LSM flush.
//! Rows are sent as raw bytes from the flush callback and decoded
//! lazily in the builder thread to minimize flush latency.
use crate::types::{Row, RowId, TableSchema, Value};
use crate::{Result, StorageError};
use super::core::MoteDB;
/// Get total size of all files in a directory
pub(crate) fn dir_size(dir: &std::path::Path) -> Result<u64> {
let mut total = 0;
if !dir.exists() {
return Ok(0);
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let metadata = entry.metadata()?;
if metadata.is_file() {
total += metadata.len();
}
}
Ok(total)
}
impl MoteDB {
/// Batch build all indexes for a specific table.
///
/// Receives raw bytes from the flush callback, decodes them using schema,
/// then dispatches to 4 parallel index builder threads sharing one Arc.
pub(crate) fn batch_build_table_indexes_raw(
&self,
table_name: &str,
raw_rows: &[(RowId, Vec<u8>)],
) -> Result<()> {
use std::sync::Arc;
use std::time::Instant;
let _start = Instant::now();
let schema = match self.table_registry.get_table(table_name) {
Ok(s) => s,
Err(e) => {
debug_log!(
"[BatchIndexBuilder] Table '{}' not found during index build: {}",
table_name,
e
);
return Ok(());
}
};
// Decode all rows using schema (fast, no brute-force)
let col_types = schema.col_types();
let mut rows: Vec<(RowId, Row)> = Vec::with_capacity(raw_rows.len());
let mut decode_failures = 0u32;
for (row_id, raw) in raw_rows {
match crate::storage::row_format::decode(raw, col_types) {
Ok(r) => rows.push((*row_id, r)),
Err(_) => {
if let Ok(r) = crate::storage::row_format::decode_any(raw) {
rows.push((*row_id, r));
} else {
decode_failures += 1;
}
}
}
}
if decode_failures > 0 {
debug_log!(
"[BatchIndexBuilder] Table '{}': {} rows failed to decode",
table_name,
decode_failures
);
}
if rows.is_empty() {
return Ok(());
}
debug_log!(
"[BatchIndexBuilder] 📊 Table '{}': {} rows",
table_name,
rows.len()
);
let rows = Arc::new(rows);
let mut handles = vec![];
// 1. Column indexes
{
let db = self.clone_for_callback();
let table_name = table_name.to_string();
let schema = schema.clone();
let rows = Arc::clone(&rows);
handles.push(
std::thread::Builder::new()
.spawn(move || db.batch_build_column_indexes(&table_name, &schema, &rows)),
);
}
// 2. Timestamp indexes
{
let db = self.clone_for_callback();
let schema = schema.clone();
let rows = Arc::clone(&rows);
handles.push(
std::thread::Builder::new()
.spawn(move || db.batch_build_timestamp_indexes(&schema, &rows)),
);
}
// 3. Vector indexes
{
let db = self.clone_for_callback();
let table_name = table_name.to_string();
let schema = schema.clone();
let rows = Arc::clone(&rows);
handles.push(
std::thread::Builder::new()
.spawn(move || db.batch_build_vector_indexes(&table_name, &schema, &rows)),
);
}
// 4. Text indexes
{
let db = self.clone_for_callback();
let table_name = table_name.to_string();
let schema = schema.clone();
let rows = Arc::clone(&rows);
handles.push(
std::thread::Builder::new()
.spawn(move || db.batch_build_text_indexes(&table_name, &schema, &rows)),
);
}
// Wait for all threads
for (idx, handle_result) in handles.into_iter().enumerate() {
let handle = match handle_result {
Ok(h) => h,
Err(e) => {
debug_log!(
"[BatchIndexBuilder] ⚠️ Index type {} thread spawn failed: {}",
idx,
e
);
continue;
}
};
match handle.join() {
Ok(Ok(())) => {}
Ok(Err(e)) => {
debug_log!(
"[BatchIndexBuilder] ⚠️ Index type {} build failed: {}",
idx,
e
);
return Err(e);
}
Err(_) => {
return Err(StorageError::Index(
"Thread panicked during index build".into(),
));
}
}
}
debug_log!(
"[BatchIndexBuilder] ✓ Table '{}' indexes built in {:?}",
table_name,
_start.elapsed()
);
Ok(())
}
/// Batch build column indexes
fn batch_build_column_indexes(
&self,
table_name: &str,
schema: &TableSchema,
rows: &[(RowId, Row)],
) -> Result<()> {
use std::time::Instant;
let start = Instant::now();
let indexes_with_data: Vec<_> = {
schema
.columns
.iter()
.filter_map(|col_def| {
let index_name = format!("{}.{}", table_name, col_def.name);
self.column_indexes.get(&index_name).and_then(|index_ref| {
let index = index_ref.value();
// Skip if index is already up-to-date from synchronous path
if !index.needs_rebuild() {
return None;
}
let mut batch: Vec<(RowId, Value)> = Vec::with_capacity(rows.len());
for (row_id, row) in rows {
if let Some(value) = row.get(col_def.position) {
batch.push((*row_id, value.clone()));
}
}
Some((index.clone(), col_def.name.clone(), batch))
})
})
.collect()
};
for (index, _col_name, batch) in indexes_with_data {
if !batch.is_empty() {
let batch_refs: Vec<(RowId, &Value)> = batch
.iter()
.map(|(row_id, value)| (*row_id, value))
.collect();
index.insert_batch(&batch_refs)?;
index.mark_rebuilt();
debug_log!(
"[ColumnIndex] ✓ Built {} entries for column '{}'",
batch.len(),
_col_name
);
}
}
let _duration = start.elapsed();
debug_log!("[ColumnIndex] Batch build complete in {:?}", _duration);
Ok(())
}
/// Batch build timestamp indexes
fn batch_build_timestamp_indexes(
&self,
schema: &TableSchema,
rows: &[(RowId, Row)],
) -> Result<()> {
use std::time::Instant;
let start = Instant::now();
let ts_col = match schema
.columns
.iter()
.find(|c| c.col_type == crate::types::ColumnType::Timestamp)
{
Some(col) => col,
None => return Ok(()),
};
let mut ts_index = self.timestamp_index.write();
let mut count = 0;
for (row_id, row) in rows {
if let Some(crate::types::Value::Timestamp(ts)) = row.get(ts_col.position) {
ts_index.insert(ts.as_micros_u64(), *row_id)?;
count += 1;
}
}
if count > 0 {
debug_log!(
"[TimestampIndex] Batch built {} entries in {:?}",
count,
start.elapsed()
);
}
Ok(())
}
/// Batch build vector indexes
fn batch_build_vector_indexes(
&self,
table_name: &str,
schema: &TableSchema,
rows: &[(RowId, Row)],
) -> Result<()> {
for col_def in &schema.columns {
if let crate::types::ColumnType::Tensor(_dim) = col_def.col_type {
// Look up actual index name from registry (supports custom names)
let index_name = match self.index_registry.find_by_column(
table_name,
&col_def.name,
crate::database::index_metadata::IndexType::Vector,
) {
Some(name) => name,
None => continue,
};
if let Some(index_ref) = self.vector_indexes.get(&index_name) {
let index = index_ref.value();
let mut vectors = Vec::new();
for (row_id, row) in rows {
if let Some(crate::types::Value::Vector(vec)) = row.get(col_def.position) {
vectors.push((*row_id, vec.to_vec()));
}
}
if !vectors.is_empty() {
index.write().batch_insert(&vectors)?;
}
}
}
}
Ok(())
}
/// Batch build text indexes
fn batch_build_text_indexes(
&self,
table_name: &str,
schema: &TableSchema,
rows: &[(RowId, Row)],
) -> Result<()> {
use crate::index::builder::IndexBuilder;
for col_def in &schema.columns {
if matches!(col_def.col_type, crate::types::ColumnType::Text) {
// Look up actual index name from registry (supports custom names)
let index_name = match self.index_registry.find_by_column(
table_name,
&col_def.name,
crate::database::index_metadata::IndexType::Text,
) {
Some(name) => name,
None => continue,
};
if let Some(index_ref) = self.text_indexes.get(&index_name) {
let index = index_ref.value();
let mut index_guard = index.write();
// Filter rows to only include the target column's text value
let col_pos = col_def.position;
let filtered: Vec<(RowId, Vec<Value>)> = rows
.iter()
.filter_map(|(row_id, row)| {
row.get(col_pos).and_then(|v| match v {
Value::Text(t) => Some((*row_id, vec![Value::text(t.to_string())])),
Value::TextDoc(t) => {
Some((*row_id, vec![Value::text(t.content().to_string())]))
}
_ => None,
})
})
.collect();
if !filtered.is_empty() {
index_guard.build_from_memtable(&filtered)?;
}
}
}
}
Ok(())
}
}