Skip to main content

mongreldb_core/
index_ddl.rs

1//! Online secondary-index create / drop / replace (MONGRELDB_TODO §4).
2//!
3//! Create and replace are driven as real [`JobKind::IndexBuild`] jobs through
4//! [`run_build_publish`]. Publication is a short barrier under the commit lock:
5//! the job constructs only the target hidden artifact from a pinned read
6//! generation, refreshes from authoritative rows when the table generation
7//! changes, then atomically publishes the staged schema + [`IndexGeneration`]
8//! through the catalog/WAL path. Drop is a synchronous schema-only catalog
9//! command with no table rewrite.
10//!
11//! Cluster replica roots reject this local user-DDL path (fail closed via the
12//! shared `require` / `read_only` gates).
13
14use super::*;
15use crate::catalog_cmds::CatalogCommand;
16use crate::jobs::{run_build_publish, BuildPublishJob, JobContext, JobError, JobKind, JobTarget};
17use crate::retention::{PinGuard, PinSource};
18use crate::schema::IndexDef;
19use crate::wal::DdlOp;
20
21/// Kind of online index-build job being driven.
22#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
23enum IndexBuildKind {
24    Create {
25        definition: IndexDef,
26    },
27    Replace {
28        expected_old_name: String,
29        new_definition: IndexDef,
30    },
31}
32
33impl IndexBuildKind {
34    fn definition(&self) -> &IndexDef {
35        match self {
36            Self::Create { definition } => definition,
37            Self::Replace { new_definition, .. } => new_definition,
38        }
39    }
40}
41
42const INDEX_BUILD_SPEC_VERSION: u16 = 1;
43
44/// Complete durable definition for reconstructing an index build after a
45/// process restart. Phase watermarks stay in the bounded job checkpoint.
46#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
47#[serde(deny_unknown_fields)]
48struct IndexBuildSpec {
49    version: u16,
50    table: String,
51    expected_schema_sequence: u64,
52    kind: IndexBuildKind,
53}
54
55impl IndexBuildSpec {
56    fn encode(&self) -> Result<Vec<u8>> {
57        serde_json::to_vec(self)
58            .map_err(|error| MongrelError::Other(format!("serialize index-build spec: {error}")))
59    }
60
61    fn decode(bytes: &[u8]) -> Result<Self> {
62        let spec: Self = serde_json::from_slice(bytes)
63            .map_err(|error| MongrelError::Other(format!("decode index-build spec: {error}")))?;
64        if spec.version != INDEX_BUILD_SPEC_VERSION {
65            return Err(MongrelError::Other(format!(
66                "unsupported index-build spec version {}",
67                spec.version
68            )));
69        }
70        Ok(spec)
71    }
72}
73
74/// In-memory driver state for one [`JobKind::IndexBuild`] drive.
75struct IndexBuildJob<'a> {
76    db: &'a Database,
77    table: String,
78    kind: IndexBuildKind,
79    expected_schema_sequence: u64,
80    /// Snapshot epoch pinned for the build (set in pin_snapshot).
81    snapshot_epoch: Option<Epoch>,
82    /// Live pin holding versions for the build (released on success/rollback).
83    pin: Option<PinGuard>,
84    /// Rows observed at the pinned snapshot (progress / validation only).
85    snapshot_row_count: u64,
86    /// Authoritative visible rows replayed through `built_through`.
87    snapshot_rows: std::collections::BTreeMap<RowId, crate::memtable::Row>,
88    /// Hidden target index built from `snapshot_rows`.
89    artifact: Option<crate::engine::SecondaryIndexArtifact>,
90    /// Governor charge covering the hidden rows, index, and build scratch.
91    memory_reservation: Option<crate::memory::Reservation>,
92    /// Exact table epoch covered by `artifact`.
93    built_through: Option<Epoch>,
94    /// Table-local content generation covered by `artifact`.
95    built_data_generation: Option<u64>,
96    /// Set once the durable catalog/generation publish completed.
97    published: bool,
98}
99
100impl IndexBuildJob<'_> {
101    fn catalog_command(&self) -> CatalogCommand {
102        match &self.kind {
103            IndexBuildKind::Create { definition } => CatalogCommand::AddIndex {
104                table: self.table.clone(),
105                index: definition.clone(),
106            },
107            IndexBuildKind::Replace {
108                expected_old_name,
109                new_definition,
110            } => CatalogCommand::ReplaceIndex {
111                table: self.table.clone(),
112                expected_schema_sequence: self.expected_schema_sequence,
113                expected_old_name: expected_old_name.clone(),
114                new_definition: new_definition.clone(),
115            },
116        }
117    }
118
119    fn release_pin(&mut self) {
120        self.pin = None;
121    }
122
123    fn reserve_hidden_memory(
124        &mut self,
125        schema: &Schema,
126        rows: &[crate::memtable::Row],
127    ) -> std::result::Result<(), JobError> {
128        let row_bytes = rows.iter().fold(0u64, |total, row| {
129            total.saturating_add(row.estimated_bytes().saturating_add(64))
130        });
131        let mut estimate = row_bytes.saturating_mul(2);
132        if self.definition().kind == crate::schema::IndexKind::Ann {
133            let dim = schema
134                .columns
135                .iter()
136                .find(|column| column.id == self.definition().column_id)
137                .and_then(|column| match column.ty {
138                    crate::schema::TypeId::Embedding { dim } => Some(dim as u64),
139                    _ => None,
140                })
141                .ok_or_else(|| {
142                    JobError::Phase(format!(
143                        "ANN index {} has no embedding column",
144                        self.definition().name
145                    ))
146                })?;
147            let options = self.definition().options.ann.clone().unwrap_or_default();
148            // Per-representation stored-vector bytes.
149            let vector_bytes = match options.quantization {
150                crate::schema::AnnQuantization::BinarySign => dim.div_ceil(8),
151                crate::schema::AnnQuantization::Dense => dim.saturating_mul(4),
152                // PQ codes are one byte per subvector; the active delta also
153                // buffers the Dense source for training, so account Dense.
154                crate::schema::AnnQuantization::Product { num_subvectors, .. } => {
155                    dim.saturating_mul(4).max(num_subvectors as u64)
156                }
157            };
158            // Algorithm-specific per-node graph/structure cost.
159            let (per_node_struct, transient) = match options.algorithm {
160                crate::schema::AnnAlgorithm::Hnsw => {
161                    let levels = (crate::index::hnsw::MAX_HNSW_LEVEL as u64).saturating_add(1);
162                    let adjacency_slots = (options.m as u64).saturating_mul(2).saturating_add(
163                        (options.m as u64).saturating_mul(levels.saturating_sub(1)),
164                    );
165                    let per_node = vector_bytes
166                        .saturating_add(std::mem::size_of::<RowId>() as u64)
167                        .saturating_add(
168                            levels.saturating_mul(std::mem::size_of::<Vec<usize>>() as u64),
169                        )
170                        .saturating_add(
171                            adjacency_slots.saturating_mul(std::mem::size_of::<usize>() as u64),
172                        );
173                    let transient = (options.ef_construction as u64)
174                        .saturating_mul(dim.saturating_add(32))
175                        .saturating_mul(8);
176                    (per_node, transient)
177                }
178                crate::schema::AnnAlgorithm::DiskAnn => {
179                    // Single-layer graph: degree R neighbors per node.
180                    let r = options.diskann.as_ref().map(|d| d.r as u64).unwrap_or(64);
181                    let per_node = vector_bytes
182                        .saturating_add(std::mem::size_of::<RowId>() as u64)
183                        .saturating_add(r.saturating_mul(std::mem::size_of::<usize>() as u64));
184                    let transient = options
185                        .diskann
186                        .as_ref()
187                        .map(|d| {
188                            (d.l as u64)
189                                .saturating_mul(dim.saturating_add(32))
190                                .saturating_mul(8)
191                        })
192                        .unwrap_or(0);
193                    (per_node, transient)
194                }
195                crate::schema::AnnAlgorithm::Ivf => {
196                    // Vectors stored per-node in inverted lists; centroids are
197                    // a fixed nlist * dim overhead.
198                    let nlist = options.ivf.as_ref().map(|o| o.nlist as u64).unwrap_or(256);
199                    let per_node = vector_bytes.saturating_add(std::mem::size_of::<RowId>() as u64);
200                    let transient = nlist.saturating_mul(dim.saturating_mul(4));
201                    (per_node, transient)
202                }
203            };
204            // Persistent structure plus transient construction clones/heaps/sets.
205            estimate = estimate.saturating_add(
206                per_node_struct
207                    .saturating_mul(rows.len() as u64)
208                    .saturating_mul(2),
209            );
210            estimate = estimate.saturating_add(transient);
211        }
212
213        let requested = usize::try_from(estimate).unwrap_or(usize::MAX);
214        let governor = self.db.memory_governor();
215        let result = match self.memory_reservation.as_mut() {
216            Some(reservation) => reservation.resize(estimate),
217            None => governor
218                .try_reserve(estimate, crate::memory::MemoryClass::Compaction)
219                .map(|reservation| self.memory_reservation = Some(reservation)),
220        };
221        result.map_err(|error| {
222            let limit = match error {
223                crate::memory::MemoryError::Exhausted { available, .. } => {
224                    usize::try_from(available).unwrap_or(usize::MAX)
225                }
226                crate::memory::MemoryError::LowPriorityRejected { .. } => 0,
227                crate::memory::MemoryError::InvalidConfig(_) => {
228                    usize::try_from(governor.class_budget(crate::memory::MemoryClass::Compaction))
229                        .unwrap_or(usize::MAX)
230                }
231            };
232            JobError::ResourceLimitExceeded {
233                resource: "index build memory",
234                requested,
235                limit,
236            }
237        })
238    }
239
240    fn definition(&self) -> &IndexDef {
241        self.kind.definition()
242    }
243
244    fn publication_already_applied(&self, schema: &Schema) -> bool {
245        schema.schema_id == self.expected_schema_sequence.saturating_add(1)
246            && schema
247                .indexes
248                .iter()
249                .any(|index| index == self.definition())
250            && match &self.kind {
251                IndexBuildKind::Create { .. } => true,
252                IndexBuildKind::Replace {
253                    expected_old_name,
254                    new_definition,
255                } => {
256                    expected_old_name == &new_definition.name
257                        || !schema
258                            .indexes
259                            .iter()
260                            .any(|index| index.name == *expected_old_name)
261                }
262            }
263    }
264
265    /// Refresh the hidden target from an authoritative pinned read generation.
266    /// The row-map diff is the delta replay: missing row ids delete, present
267    /// row ids insert or replace. Graph families are then rebuilt outside the
268    /// final barrier because HNSW has no safe in-place delete.
269    fn refresh_hidden(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
270        context.check_cancelled()?;
271        let handle = self.db.table(&self.table).map_err(job_phase_err)?;
272        let (generation, snapshot) = handle
273            .read_generation_with_context(None)
274            .map_err(job_phase_err)?;
275        if self.pin.is_none() {
276            self.pin = Some(
277                Arc::clone(generation.pin_registry())
278                    .pin(PinSource::OnlineIndexBuild, snapshot.epoch),
279            );
280            self.snapshot_epoch.get_or_insert(snapshot.epoch);
281        }
282
283        let rows = generation.visible_rows(snapshot).map_err(job_phase_err)?;
284        self.reserve_hidden_memory(generation.schema(), &rows)?;
285        let next: std::collections::BTreeMap<_, _> =
286            rows.into_iter().map(|row| (row.row_id, row)).collect();
287        self.snapshot_rows
288            .retain(|row_id, _| next.contains_key(row_id));
289        for (row_id, row) in next {
290            self.snapshot_rows.insert(row_id, row);
291        }
292
293        let rows: Vec<_> = self.snapshot_rows.values().cloned().collect();
294        let total = rows.len();
295        let definition = self.definition().clone();
296        let mut last_reported = None;
297        let artifact = generation
298            .build_secondary_index_artifact(&definition, &rows, |done, total| {
299                context.check_cancelled().map_err(MongrelError::from)?;
300                if total > 0
301                    && last_reported != Some(done)
302                    && (done.is_multiple_of(256) || done == total)
303                {
304                    context
305                        .report_progress(done as u64, total as u64)
306                        .map_err(MongrelError::from)?;
307                    last_reported = Some(done);
308                }
309                Ok(())
310            })
311            .map_err(job_phase_err)?;
312        self.snapshot_row_count = total as u64;
313        self.built_through = Some(snapshot.epoch);
314        self.built_data_generation = Some(generation.data_generation());
315        self.artifact = Some(artifact);
316        Ok(())
317    }
318}
319
320impl BuildPublishJob for IndexBuildJob<'_> {
321    fn checkpoint_state(&self) -> Vec<u8> {
322        // Bounded, small state only — never an unbounded delta stream.
323        let epoch = self.snapshot_epoch.map(|e| e.0).unwrap_or(0);
324        let built_through = self.built_through.map(|epoch| epoch.0).unwrap_or(0);
325        let built_data_generation = self.built_data_generation.unwrap_or(0);
326        let published = u8::from(self.published);
327        let mut out = Vec::with_capacity(33);
328        out.extend_from_slice(&epoch.to_le_bytes());
329        out.extend_from_slice(&self.snapshot_row_count.to_le_bytes());
330        out.extend_from_slice(&built_through.to_le_bytes());
331        out.extend_from_slice(&built_data_generation.to_le_bytes());
332        out.push(published);
333        out
334    }
335
336    fn restore_checkpoint(&mut self, state: &[u8]) -> std::result::Result<(), JobError> {
337        if state.len() < 17 {
338            return Err(JobError::Phase(
339                "index-build checkpoint is truncated".into(),
340            ));
341        }
342        let mut epoch_bytes = [0u8; 8];
343        epoch_bytes.copy_from_slice(&state[0..8]);
344        let epoch = u64::from_le_bytes(epoch_bytes);
345        if epoch != 0 {
346            self.snapshot_epoch = Some(Epoch(epoch));
347        }
348        let mut count_bytes = [0u8; 8];
349        count_bytes.copy_from_slice(&state[8..16]);
350        self.snapshot_row_count = u64::from_le_bytes(count_bytes);
351        if state.len() >= 33 {
352            let mut built_bytes = [0u8; 8];
353            built_bytes.copy_from_slice(&state[16..24]);
354            let built = u64::from_le_bytes(built_bytes);
355            if built != 0 {
356                self.built_through = Some(Epoch(built));
357            }
358            let mut generation_bytes = [0u8; 8];
359            generation_bytes.copy_from_slice(&state[24..32]);
360            self.built_data_generation = Some(u64::from_le_bytes(generation_bytes));
361            self.published = state[32] != 0;
362        } else if state.len() >= 25 {
363            let mut built_bytes = [0u8; 8];
364            built_bytes.copy_from_slice(&state[16..24]);
365            let built = u64::from_le_bytes(built_bytes);
366            if built != 0 {
367                self.built_through = Some(Epoch(built));
368            }
369            self.published = state[24] != 0;
370        } else {
371            self.published = state[16] != 0;
372        }
373        Ok(())
374    }
375
376    fn record_pending(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
377        context.check_cancelled()?;
378        // Job is already durable in the JOBS registry (submit). Validate the
379        // definition still resolves against the live schema image.
380        let catalog = self.db.catalog.read();
381        let entry = catalog
382            .live(&self.table)
383            .ok_or_else(|| JobError::Phase(format!("table {:?} not found", self.table)))?;
384        if entry.schema.schema_id != self.expected_schema_sequence {
385            return Err(JobError::Phase(format!(
386                "schema sequence changed before index build started on {:?}",
387                self.table
388            )));
389        }
390        let command = self.catalog_command();
391        crate::catalog_cmds::apply(&catalog, &command).map_err(job_phase_err)?;
392        Ok(())
393    }
394
395    fn pin_snapshot(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
396        context.check_cancelled()?;
397        if self.pin.is_some() {
398            return Ok(());
399        }
400        let handle = self.db.table(&self.table).map_err(job_phase_err)?;
401        let table = handle.lock();
402        let epoch = table.current_epoch();
403        let pin = Arc::clone(table.pin_registry()).pin(PinSource::OnlineIndexBuild, epoch);
404        self.snapshot_epoch = Some(epoch);
405        self.pin = Some(pin);
406        Ok(())
407    }
408
409    fn build_hidden(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
410        self.refresh_hidden(context)
411    }
412
413    fn catch_up(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
414        self.refresh_hidden(context)
415    }
416
417    fn validate(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
418        context.check_cancelled()?;
419        let catalog = self.db.catalog.read();
420        let entry = catalog
421            .live(&self.table)
422            .ok_or_else(|| JobError::Phase(format!("table {:?} not found", self.table)))?;
423        if entry.schema.schema_id != self.expected_schema_sequence {
424            return Err(JobError::Phase(format!(
425                "schema sequence conflict during index build on {:?}: expected {}, found {}",
426                self.table, self.expected_schema_sequence, entry.schema.schema_id
427            )));
428        }
429        crate::catalog_cmds::apply(&catalog, &self.catalog_command()).map_err(job_phase_err)?;
430        Ok(())
431    }
432
433    fn publish(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
434        context.check_cancelled()?;
435        if self.published {
436            return Ok(());
437        }
438        match self.db.publish_index_build(self, context) {
439            Ok(()) => {
440                self.published = true;
441                Ok(())
442            }
443            Err(error @ MongrelError::DurableCommit { .. }) => {
444                let applied = self
445                    .db
446                    .catalog
447                    .read()
448                    .live(&self.table)
449                    .is_some_and(|entry| self.publication_already_applied(&entry.schema));
450                if applied {
451                    self.published = true;
452                    Ok(())
453                } else {
454                    Err(job_phase_err(error))
455                }
456            }
457            Err(error) => Err(job_phase_err(error)),
458        }
459    }
460
461    fn release_old(&mut self, context: &JobContext) -> std::result::Result<(), JobError> {
462        context.check_cancelled()?;
463        // Drop the build pin so version GC can advance. Old index generations
464        // remain alive only while reader pins hold them (Arc).
465        self.release_pin();
466        self.artifact = None;
467        self.memory_reservation = None;
468        self.snapshot_rows.clear();
469        Ok(())
470    }
471
472    fn rollback(&mut self) -> std::result::Result<(), JobError> {
473        // Pre-publication cancel/failure: drop the pin and leave the old
474        // schema + generation active. No hidden on-disk generation exists.
475        self.release_pin();
476        self.artifact = None;
477        self.memory_reservation = None;
478        self.snapshot_rows.clear();
479        Ok(())
480    }
481}
482
483fn job_phase_err(error: MongrelError) -> JobError {
484    match error {
485        MongrelError::Cancelled => JobError::Cancelled,
486        MongrelError::Conflict(message) => JobError::Phase(message),
487        other => JobError::Phase(other.to_string()),
488    }
489}
490
491impl Database {
492    /// Returns the immutable target definition recorded for one durable
493    /// index-build job.
494    ///
495    /// Consumers use this to distinguish a resumable job for the requested
496    /// representation from an obsolete job that must be cancelled before a
497    /// replacement in the opposite direction is submitted.
498    pub fn index_build_target_definition(&self, job_id: u64) -> Result<IndexDef> {
499        let record = self
500            .job_registry
501            .get(job_id)
502            .ok_or_else(|| MongrelError::NotFound(format!("job {job_id} not found")))?;
503        if record.kind != JobKind::IndexBuild {
504            return Err(MongrelError::InvalidArgument(format!(
505                "job {job_id} is not an index build"
506            )));
507        }
508        let definition = record.definition.as_deref().ok_or_else(|| {
509            MongrelError::Other(format!(
510                "index-build job {job_id} has no durable definition"
511            ))
512        })?;
513        Ok(IndexBuildSpec::decode(definition)?
514            .kind
515            .definition()
516            .clone())
517    }
518
519    /// Create a secondary index online, waiting for terminal success.
520    ///
521    /// SQL and local typed callers share this path. Cluster replica roots
522    /// reject the mutation (fail closed).
523    pub fn create_index(&self, table: &str, definition: IndexDef) -> Result<u64> {
524        self.run_index_build(
525            table,
526            IndexBuildKind::Create {
527                definition: definition.clone(),
528            },
529            Some(definition),
530            None,
531        )
532    }
533
534    /// Persist a create-index job without starting its worker.
535    ///
536    /// This is the queueing primitive for callers that own an executor. The
537    /// returned id always names a durable `Pending` record containing the full
538    /// versioned index definition.
539    pub fn submit_create_index(&self, table: &str, definition: IndexDef) -> Result<u64> {
540        let (job_id, _) = self.submit_index_build(
541            table,
542            IndexBuildKind::Create {
543                definition: definition.clone(),
544            },
545            Some(definition),
546            None,
547        )?;
548        Ok(job_id)
549    }
550
551    /// Persist and asynchronously drive a create-index job.
552    pub fn start_create_index(self: &Arc<Self>, table: &str, definition: IndexDef) -> Result<u64> {
553        let (job_id, spec) = self.submit_index_build(
554            table,
555            IndexBuildKind::Create {
556                definition: definition.clone(),
557            },
558            Some(definition),
559            None,
560        )?;
561        self.spawn_index_build(job_id, spec)?;
562        Ok(job_id)
563    }
564
565    /// Atomically replace one secondary index with a new definition (e.g.
566    /// BinarySign ↔ Dense ANN). Returns the durable job id after success.
567    ///
568    /// Publication is compare-and-swap on the table's `schema_id` captured at
569    /// job start; concurrent DDL fails closed with [`MongrelError::Conflict`].
570    pub fn replace_index(
571        &self,
572        table: &str,
573        expected_old_name: &str,
574        new_definition: IndexDef,
575    ) -> Result<u64> {
576        self.run_index_build(
577            table,
578            IndexBuildKind::Replace {
579                expected_old_name: expected_old_name.to_string(),
580                new_definition: new_definition.clone(),
581            },
582            Some(new_definition),
583            Some(expected_old_name),
584        )
585    }
586
587    /// Persist a replace-index job without starting its worker.
588    pub fn submit_replace_index(
589        &self,
590        table: &str,
591        expected_old_name: &str,
592        new_definition: IndexDef,
593    ) -> Result<u64> {
594        let (job_id, _) = self.submit_index_build(
595            table,
596            IndexBuildKind::Replace {
597                expected_old_name: expected_old_name.to_string(),
598                new_definition: new_definition.clone(),
599            },
600            Some(new_definition),
601            Some(expected_old_name),
602        )?;
603        Ok(job_id)
604    }
605
606    /// Persist and asynchronously drive a replace-index job.
607    pub fn start_replace_index(
608        self: &Arc<Self>,
609        table: &str,
610        expected_old_name: &str,
611        new_definition: IndexDef,
612    ) -> Result<u64> {
613        let (job_id, spec) = self.submit_index_build(
614            table,
615            IndexBuildKind::Replace {
616                expected_old_name: expected_old_name.to_string(),
617                new_definition: new_definition.clone(),
618            },
619            Some(new_definition),
620            Some(expected_old_name),
621        )?;
622        self.spawn_index_build(job_id, spec)?;
623        Ok(job_id)
624    }
625
626    /// Requeue and asynchronously redrive a persisted index-build job after
627    /// crash recovery or an operator pause.
628    pub fn resume_index_build(self: &Arc<Self>, job_id: u64) -> Result<()> {
629        let record = self
630            .job_registry
631            .get(job_id)
632            .ok_or_else(|| MongrelError::NotFound(format!("job {job_id}")))?;
633        if record.kind != JobKind::IndexBuild {
634            return Err(MongrelError::InvalidArgument(format!(
635                "job {job_id} is not an index build"
636            )));
637        }
638        let definition = record.definition.as_deref().ok_or_else(|| {
639            MongrelError::Other(format!(
640                "index build job {job_id} has no reconstructible definition"
641            ))
642        })?;
643        let spec = IndexBuildSpec::decode(definition)?;
644        match record.state {
645            crate::jobs::JobState::Paused => self
646                .job_registry
647                .resume(job_id)
648                .map_err(MongrelError::from)?,
649            crate::jobs::JobState::Pending => {}
650            state => {
651                return Err(MongrelError::Conflict(format!(
652                    "index build job {job_id} cannot resume from {state:?}"
653                )));
654            }
655        }
656        self.spawn_index_build(job_id, spec)
657    }
658
659    /// Drop a secondary index by name. Schema + published generation advance
660    /// atomically through the catalog commit path; table rows are not rewritten.
661    pub fn drop_index(&self, table: &str, name: &str) -> Result<()> {
662        use std::sync::atomic::Ordering;
663
664        self.require(&crate::auth::Permission::Ddl)?;
665        if self.poisoned.load(Ordering::Relaxed) {
666            return Err(MongrelError::Other(
667                "database poisoned by fsync error".into(),
668            ));
669        }
670        let _operation = self.admit_operation()?;
671        let _schema_barrier = self.acquire_schema_barrier_exclusive()?;
672        let _ddl = self.ddl_lock.lock();
673        let _security_write = self.security_write()?;
674        self.require(&crate::auth::Permission::Ddl)?;
675
676        let table_id = {
677            let catalog = self.catalog.read();
678            catalog
679                .live(table)
680                .ok_or_else(|| MongrelError::NotFound(format!("table {table:?} not found")))?
681                .table_id
682        };
683        let handle = self
684            .tables
685            .read()
686            .get(&table_id)
687            .cloned()
688            .ok_or_else(|| MongrelError::NotFound(format!("table {table:?} not mounted")))?;
689
690        let command = CatalogCommand::RemoveIndex {
691            table: table.to_string(),
692            name: name.to_string(),
693        };
694        // Pure pre-check before an epoch is consumed.
695        let prepared_schema = match crate::catalog_cmds::apply(&self.catalog.read(), &command)? {
696            crate::catalog_cmds::CatalogDelta::SchemaReplaced { schema, .. } => schema,
697            crate::catalog_cmds::CatalogDelta::NoOp => return Ok(()),
698            other => {
699                return Err(MongrelError::Other(format!(
700                    "unexpected catalog delta for drop_index: {other:?}"
701                )));
702            }
703        };
704
705        crate::catalog::inject_hook("index.publish.before")?;
706
707        let durable_epoch = std::cell::Cell::new(None);
708        let result: Result<()> = (|| {
709            let mut table_guard = handle.lock();
710            let commit_lock = Arc::clone(&self.commit_lock);
711            let _commit = commit_lock.lock();
712            let epoch = self.epoch.bump_assigned();
713            let mut epoch_guard = EpochGuard::new(self.epoch.as_ref(), epoch);
714            let txn_id = self.alloc_txn_id()?;
715            let mut next_catalog = self.catalog.read().clone();
716            let catalog_entry_index = next_catalog
717                .tables
718                .iter()
719                .position(|entry| entry.table_id == table_id)
720                .ok_or_else(|| MongrelError::NotFound(format!("table {table:?} not found")))?;
721            self.apply_catalog_command_to(&mut next_catalog, command)?;
722            next_catalog.tables[catalog_entry_index].schema = prepared_schema.clone();
723            next_catalog.db_epoch = next_catalog.db_epoch.max(epoch.0);
724
725            let commit_seq = {
726                let mut wal = self.shared_wal.lock();
727                let append: Result<u64> = (|| {
728                    append_catalog_snapshot(&mut wal, txn_id, &next_catalog)?;
729                    wal.append_commit(txn_id, epoch, &[])
730                })();
731                append.map_err(|error| self.commit_outcome_unknown(epoch, error))?
732            };
733            let receipt = self.await_durable_commit(txn_id, commit_seq, epoch)?;
734            durable_epoch.set(Some(epoch));
735
736            table_guard.publish_index_drop(prepared_schema)?;
737            let schema = table_guard.schema().clone();
738            drop(table_guard);
739            next_catalog.tables[catalog_entry_index].schema = schema;
740            let catalog_result =
741                catalog::write_atomic(&self.root, &next_catalog, self.meta_dek.as_ref());
742            *self.catalog.write() = next_catalog;
743            self.publish_committed(&receipt, epoch)?;
744            epoch_guard.disarm();
745            if let Err(error) = catalog_result {
746                self.poisoned.store(true, Ordering::Relaxed);
747                self.lifecycle.poison();
748                return Err(MongrelError::DurableCommit {
749                    epoch: epoch.0,
750                    message: error.to_string(),
751                });
752            }
753            crate::catalog::inject_hook("index.publish.after")?;
754            Ok(())
755        })();
756        result.map_err(|error| match (durable_epoch.get(), error) {
757            (_, error @ MongrelError::DurableCommit { .. }) => error,
758            (Some(epoch), error) => MongrelError::DurableCommit {
759                epoch: epoch.0,
760                message: error.to_string(),
761            },
762            (None, error) => error,
763        })
764    }
765
766    fn run_index_build(
767        &self,
768        table: &str,
769        kind: IndexBuildKind,
770        definition: Option<IndexDef>,
771        expected_old_name: Option<&str>,
772    ) -> Result<u64> {
773        let (job_id, spec) = self.submit_index_build(table, kind, definition, expected_old_name)?;
774        self.drive_index_build(job_id, spec)
775    }
776
777    fn submit_index_build(
778        &self,
779        table: &str,
780        kind: IndexBuildKind,
781        definition: Option<IndexDef>,
782        expected_old_name: Option<&str>,
783    ) -> Result<(u64, IndexBuildSpec)> {
784        self.require(&crate::auth::Permission::Ddl)?;
785        if self.poisoned.load(Ordering::Relaxed) {
786            return Err(MongrelError::Other(
787                "database poisoned by fsync error".into(),
788            ));
789        }
790        if table.is_empty() {
791            return Err(MongrelError::InvalidArgument(
792                "index DDL requires a non-empty table name".into(),
793            ));
794        }
795
796        // Validate against the live schema before allocating a job id.
797        let (expected_schema_sequence, index_name) = {
798            let catalog = self.catalog.read();
799            let entry = catalog
800                .live(table)
801                .ok_or_else(|| MongrelError::NotFound(format!("table {table:?} not found")))?;
802            if let Some(old) = expected_old_name {
803                if !entry.schema.indexes.iter().any(|index| index.name == old) {
804                    return Err(MongrelError::NotFound(format!(
805                        "index {old} does not exist on {table}"
806                    )));
807                }
808            }
809            if let Some(def) = &definition {
810                def.validate_options()?;
811            }
812            // Pure apply against a clone of the schema image (via catalog
813            // command) catches name/column/AI conflicts fail closed.
814            let command = match &kind {
815                IndexBuildKind::Create { definition } => CatalogCommand::AddIndex {
816                    table: table.to_string(),
817                    index: definition.clone(),
818                },
819                IndexBuildKind::Replace {
820                    expected_old_name,
821                    new_definition,
822                } => CatalogCommand::ReplaceIndex {
823                    table: table.to_string(),
824                    expected_schema_sequence: entry.schema.schema_id,
825                    expected_old_name: expected_old_name.clone(),
826                    new_definition: new_definition.clone(),
827                },
828            };
829            crate::catalog_cmds::apply(&catalog, &command)?;
830            let name = match &kind {
831                IndexBuildKind::Create { definition } => definition.name.clone(),
832                IndexBuildKind::Replace { new_definition, .. } => new_definition.name.clone(),
833            };
834            (entry.schema.schema_id, name)
835        };
836
837        // Ensure the table is mounted.
838        let _ = self.table(table)?;
839
840        let spec = IndexBuildSpec {
841            version: INDEX_BUILD_SPEC_VERSION,
842            table: table.to_string(),
843            expected_schema_sequence,
844            kind,
845        };
846        let job_id = self.job_registry.submit_with_definition(
847            JobKind::IndexBuild,
848            JobTarget {
849                table: table.to_string(),
850                index: Some(index_name),
851            },
852            Some(spec.encode()?),
853        )?;
854        Ok((job_id, spec))
855    }
856
857    fn spawn_index_build(self: &Arc<Self>, job_id: u64, spec: IndexBuildSpec) -> Result<()> {
858        let db = Arc::clone(self);
859        std::thread::Builder::new()
860            .name(format!("mongreldb-index-{job_id}"))
861            .spawn(move || {
862                // Terminal state and error detail are persisted by the driver.
863                let _ = db.drive_index_build(job_id, spec);
864            })
865            .map_err(|error| {
866                MongrelError::Io(std::io::Error::new(
867                    error.kind(),
868                    format!("spawn index build job {job_id}: {error}"),
869                ))
870            })?;
871        Ok(())
872    }
873
874    fn drive_index_build(&self, job_id: u64, spec: IndexBuildSpec) -> Result<u64> {
875        let mut job = IndexBuildJob {
876            db: self,
877            table: spec.table,
878            kind: spec.kind,
879            expected_schema_sequence: spec.expected_schema_sequence,
880            snapshot_epoch: None,
881            pin: None,
882            snapshot_row_count: 0,
883            snapshot_rows: std::collections::BTreeMap::new(),
884            artifact: None,
885            memory_reservation: None,
886            built_through: None,
887            built_data_generation: None,
888            published: false,
889        };
890
891        match run_build_publish(self.job_registry.as_ref(), job_id, &mut job) {
892            Ok(()) => {
893                let record = self.job_registry.get(job_id);
894                match record.map(|r| r.state) {
895                    Some(crate::jobs::JobState::Succeeded) => Ok(job_id),
896                    Some(crate::jobs::JobState::Paused) => Err(MongrelError::Other(format!(
897                        "index build job {job_id} parked mid-run; resume and redrive"
898                    ))),
899                    Some(state) => Err(MongrelError::Other(format!(
900                        "index build job {job_id} ended in unexpected state {state:?}"
901                    ))),
902                    None => Err(MongrelError::NotFound(format!("job {job_id}"))),
903                }
904            }
905            Err(JobError::Cancelled) => {
906                // Cancellation after durable publication is reported as success
907                // of the committed result (phase publish sets published=true
908                // before release; cancel then cannot roll it back).
909                if job.published
910                    || self
911                        .job_registry
912                        .get(job_id)
913                        .is_some_and(|r| r.state == crate::jobs::JobState::Succeeded)
914                {
915                    Ok(job_id)
916                } else {
917                    Err(MongrelError::Cancelled)
918                }
919            }
920            Err(error) => {
921                if job.published {
922                    // Committed: surface success of the durable outcome.
923                    Ok(job_id)
924                } else {
925                    Err(error.into())
926                }
927            }
928        }
929    }
930
931    /// Short publication barrier for an index-build job. If the table changed
932    /// after catch-up, release every barrier, refresh the hidden artifact, and
933    /// retry. The barrier itself performs only CAS, WAL/catalog publication,
934    /// and an O(number of indexed columns) generation swap.
935    fn publish_index_build(&self, job: &mut IndexBuildJob<'_>, context: &JobContext) -> Result<()> {
936        use std::sync::atomic::Ordering;
937
938        if self.poisoned.load(Ordering::Relaxed) {
939            return Err(MongrelError::Other(
940                "database poisoned by fsync error".into(),
941            ));
942        }
943        // Re-check DDL auth at publication (revocation must stay effective).
944        self.require(&crate::auth::Permission::Ddl)?;
945
946        let table_name = job.table.clone();
947        let table_id = {
948            let catalog = self.catalog.read();
949            let entry = catalog
950                .live(&table_name)
951                .ok_or_else(|| MongrelError::NotFound(format!("table {table_name:?} not found")))?;
952            if entry.schema.schema_id != job.expected_schema_sequence {
953                if job.publication_already_applied(&entry.schema) {
954                    job.published = true;
955                    return Ok(());
956                }
957                return Err(MongrelError::Conflict(format!(
958                    "index publish on {table_name}: expected schema sequence {}, found {}",
959                    job.expected_schema_sequence, entry.schema.schema_id
960                )));
961            }
962            entry.table_id
963        };
964        let handle =
965            self.tables.read().get(&table_id).cloned().ok_or_else(|| {
966                MongrelError::NotFound(format!("table {table_name:?} not mounted"))
967            })?;
968
969        loop {
970            context.check_cancelled().map_err(MongrelError::from)?;
971            if job.artifact.is_none() || job.built_data_generation.is_none() {
972                job.refresh_hidden(context).map_err(MongrelError::from)?;
973            }
974            let built_data_generation = job.built_data_generation.ok_or_else(|| {
975                MongrelError::Other("index build has no content watermark".into())
976            })?;
977            let command = job.catalog_command();
978            let prepared_schema = match crate::catalog_cmds::apply(&self.catalog.read(), &command)?
979            {
980                crate::catalog_cmds::CatalogDelta::SchemaReplaced { schema, .. } => schema,
981                other => {
982                    return Err(MongrelError::Other(format!(
983                        "unexpected catalog delta for index publish: {other:?}"
984                    )));
985                }
986            };
987            let durable_epoch = std::cell::Cell::new(None);
988
989            // Jobs run without the schema barrier during scan/build. Take it
990            // only for the exact-CAS and publication window.
991            let _schema_barrier = self.acquire_schema_barrier_exclusive()?;
992            let _ddl = self.ddl_lock.lock();
993            let _security_write = self.security_write()?;
994            self.require(&crate::auth::Permission::Ddl)?;
995
996            // Re-check CAS under the barrier.
997            {
998                let catalog = self.catalog.read();
999                let entry = catalog.live(&table_name).ok_or_else(|| {
1000                    MongrelError::NotFound(format!("table {table_name:?} not found"))
1001                })?;
1002                if entry.schema.schema_id != job.expected_schema_sequence {
1003                    if job.publication_already_applied(&entry.schema) {
1004                        job.published = true;
1005                        return Ok(());
1006                    }
1007                    return Err(MongrelError::Conflict(format!(
1008                        "index publish on {table_name}: expected schema sequence {}, found {}",
1009                        job.expected_schema_sequence, entry.schema.schema_id
1010                    )));
1011                }
1012            }
1013
1014            // Global lock order is commit lock -> table lock.
1015            let commit_lock = Arc::clone(&self.commit_lock);
1016            let _commit = commit_lock.lock();
1017            let mut table_guard = handle.lock();
1018            if table_guard.data_generation() != built_data_generation {
1019                drop(table_guard);
1020                drop(_commit);
1021                drop(_security_write);
1022                drop(_ddl);
1023                drop(_schema_barrier);
1024                job.refresh_hidden(context).map_err(MongrelError::from)?;
1025                continue;
1026            }
1027
1028            let result: Result<()> = (|| {
1029                // Fail closed immediately before the durable catalog/generation
1030                // boundary. Tests arm barriers here, never sleeps.
1031                crate::catalog::inject_hook("index.publish.before")?;
1032
1033                let epoch = self.epoch.bump_assigned();
1034                let mut epoch_guard = EpochGuard::new(self.epoch.as_ref(), epoch);
1035                let txn_id = self.alloc_txn_id()?;
1036                let mut next_catalog = self.catalog.read().clone();
1037                let catalog_entry_index = next_catalog
1038                    .tables
1039                    .iter()
1040                    .position(|entry| entry.table_id == table_id)
1041                    .ok_or_else(|| {
1042                        MongrelError::NotFound(format!("table {table_name:?} not found"))
1043                    })?;
1044                self.apply_catalog_command_to(&mut next_catalog, command)?;
1045                next_catalog.tables[catalog_entry_index].schema = prepared_schema.clone();
1046                next_catalog.db_epoch = next_catalog.db_epoch.max(epoch.0);
1047
1048                let commit_seq = {
1049                    let mut wal = self.shared_wal.lock();
1050                    let append: Result<u64> = (|| {
1051                        // Catalog snapshot is the durable record of the index DDL.
1052                        let _ = DdlOp::encode_schema(&prepared_schema)?;
1053                        append_catalog_snapshot(&mut wal, txn_id, &next_catalog)?;
1054                        wal.append_commit(txn_id, epoch, &[])
1055                    })();
1056                    append.map_err(|error| self.commit_outcome_unknown(epoch, error))?
1057                };
1058                let receipt = self.await_durable_commit(txn_id, commit_seq, epoch)?;
1059                durable_epoch.set(Some(epoch));
1060
1061                let artifact = job.artifact.take().ok_or_else(|| {
1062                    MongrelError::Other("index build lost its hidden artifact".into())
1063                })?;
1064                table_guard.publish_index_schema_change(prepared_schema, artifact)?;
1065                let schema = table_guard.schema().clone();
1066                drop(table_guard);
1067
1068                next_catalog.tables[catalog_entry_index].schema = schema;
1069                let catalog_result =
1070                    catalog::write_atomic(&self.root, &next_catalog, self.meta_dek.as_ref());
1071                *self.catalog.write() = next_catalog;
1072                self.publish_committed(&receipt, epoch)?;
1073                epoch_guard.disarm();
1074                if let Err(error) = catalog_result {
1075                    self.poisoned.store(true, Ordering::Relaxed);
1076                    self.lifecycle.poison();
1077                    return Err(MongrelError::DurableCommit {
1078                        epoch: epoch.0,
1079                        message: error.to_string(),
1080                    });
1081                }
1082                crate::catalog::inject_hook("index.publish.after")?;
1083                Ok(())
1084            })();
1085            return result.map_err(|error| match (durable_epoch.get(), error) {
1086                (_, error @ MongrelError::DurableCommit { .. }) => error,
1087                (Some(epoch), error) => MongrelError::DurableCommit {
1088                    epoch: epoch.0,
1089                    message: error.to_string(),
1090                },
1091                (None, error) => error,
1092            });
1093        }
1094    }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099    use super::*;
1100    use crate::query::{Retriever, RetrieverScore};
1101    use crate::schema::{AnnOptions, AnnQuantization, IndexKind, IndexOptions, TypeId};
1102    use std::sync::Mutex;
1103
1104    /// Serializes unit tests that touch the process-global fault registry or
1105    /// share online-index publication hooks with concurrent cases.
1106    static INDEX_DDL_TEST_LOCK: Mutex<()> = Mutex::new(());
1107
1108    fn lock_tests() -> std::sync::MutexGuard<'static, ()> {
1109        INDEX_DDL_TEST_LOCK
1110            .lock()
1111            .unwrap_or_else(|poisoned| poisoned.into_inner())
1112    }
1113
1114    fn embedding_schema(quantization: AnnQuantization) -> Schema {
1115        Schema {
1116            columns: vec![
1117                ColumnDef {
1118                    id: 1,
1119                    name: "id".into(),
1120                    ty: TypeId::Int64,
1121                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
1122                    default_value: None,
1123                    embedding_source: None,
1124                },
1125                ColumnDef {
1126                    id: 2,
1127                    name: "embedding".into(),
1128                    ty: TypeId::Embedding { dim: 4 },
1129                    flags: ColumnFlags::empty(),
1130                    default_value: None,
1131                    embedding_source: None,
1132                },
1133            ],
1134            indexes: vec![IndexDef {
1135                name: "idx_embed_ann".into(),
1136                column_id: 2,
1137                kind: IndexKind::Ann,
1138                predicate: None,
1139                options: IndexOptions {
1140                    ann: Some(AnnOptions {
1141                        m: 8,
1142                        ef_construction: 32,
1143                        ef_search: 16,
1144                        quantization,
1145                        ..AnnOptions::default()
1146                    }),
1147                    ..IndexOptions::default()
1148                },
1149            }],
1150            ..Schema::default()
1151        }
1152    }
1153
1154    fn plain_embedding_schema() -> Schema {
1155        Schema {
1156            columns: vec![
1157                ColumnDef {
1158                    id: 1,
1159                    name: "id".into(),
1160                    ty: TypeId::Int64,
1161                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
1162                    default_value: None,
1163                    embedding_source: None,
1164                },
1165                ColumnDef {
1166                    id: 2,
1167                    name: "embedding".into(),
1168                    ty: TypeId::Embedding { dim: 4 },
1169                    flags: ColumnFlags::empty(),
1170                    default_value: None,
1171                    embedding_source: None,
1172                },
1173            ],
1174            ..Schema::default()
1175        }
1176    }
1177
1178    fn put_row(db: &Database, table: &str, id: i64, embedding: Vec<f32>) {
1179        let mut txn = db.begin();
1180        txn.put(
1181            table,
1182            vec![(1, Value::Int64(id)), (2, Value::Embedding(embedding))],
1183        )
1184        .unwrap();
1185        txn.commit().unwrap();
1186    }
1187
1188    fn row_id_for_pk(db: &Database, table: &str, id: i64) -> RowId {
1189        let handle = db.table(table).unwrap();
1190        let table = handle.lock();
1191        table
1192            .visible_rows(Snapshot::at(table.current_epoch()))
1193            .unwrap()
1194            .into_iter()
1195            .find(|row| row.columns.get(&1) == Some(&Value::Int64(id)))
1196            .map(|row| row.row_id)
1197            .unwrap()
1198    }
1199
1200    fn dense_definition() -> IndexDef {
1201        IndexDef {
1202            name: "idx_embed_ann".into(),
1203            column_id: 2,
1204            kind: IndexKind::Ann,
1205            predicate: None,
1206            options: IndexOptions {
1207                ann: Some(AnnOptions {
1208                    quantization: AnnQuantization::Dense,
1209                    ..AnnOptions::default()
1210                }),
1211                ..IndexOptions::default()
1212            },
1213        }
1214    }
1215
1216    #[test]
1217    fn create_index_indexes_snapshot_rows() {
1218        let _lock = lock_tests();
1219        let dir = tempfile::tempdir().unwrap();
1220        let db = Database::create(dir.path()).unwrap();
1221        db.create_table("docs", plain_embedding_schema()).unwrap();
1222        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1223        put_row(&db, "docs", 2, vec![0.0, 1.0, 0.0, 0.0]);
1224
1225        let definition = IndexDef {
1226            name: "idx_embed_ann".into(),
1227            column_id: 2,
1228            kind: IndexKind::Ann,
1229            predicate: None,
1230            options: IndexOptions {
1231                ann: Some(AnnOptions {
1232                    m: 8,
1233                    ef_construction: 32,
1234                    ef_search: 16,
1235                    quantization: AnnQuantization::Dense,
1236                    ..AnnOptions::default()
1237                }),
1238                ..IndexOptions::default()
1239            },
1240        };
1241        let job_id = db.create_index("docs", definition).unwrap();
1242        let record = db.job_registry().get(job_id).unwrap();
1243        assert_eq!(record.state, crate::jobs::JobState::Succeeded);
1244
1245        let handle = db.table("docs").unwrap();
1246        let mut table = handle.lock();
1247        let hits = table
1248            .retrieve(&Retriever::Ann {
1249                column_id: 2,
1250                query: vec![1.0, 0.0, 0.0, 0.0],
1251                k: 2,
1252            })
1253            .unwrap();
1254        assert_eq!(hits.len(), 2);
1255        assert!(matches!(
1256            hits[0].score,
1257            RetrieverScore::AnnCosineDistance(d) if d.abs() < 1e-5
1258        ));
1259        // Schema sequence advanced once for the create (initial schema_id is
1260        // the allocated table_id, then AddIndex bumps by one).
1261        assert_eq!(table.schema().schema_id, table.table_id().saturating_add(1));
1262    }
1263
1264    #[test]
1265    fn replace_binary_sign_with_dense_search_works() {
1266        let _lock = lock_tests();
1267        let dir = tempfile::tempdir().unwrap();
1268        let db = Database::create(dir.path()).unwrap();
1269        db.create_table("docs", embedding_schema(AnnQuantization::BinarySign))
1270            .unwrap();
1271        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1272        put_row(&db, "docs", 2, vec![0.0, 1.0, 0.0, 0.0]);
1273
1274        let new_def = IndexDef {
1275            name: "idx_embed_ann".into(),
1276            column_id: 2,
1277            kind: IndexKind::Ann,
1278            predicate: None,
1279            options: IndexOptions {
1280                ann: Some(AnnOptions {
1281                    m: 8,
1282                    ef_construction: 32,
1283                    ef_search: 16,
1284                    quantization: AnnQuantization::Dense,
1285                    ..AnnOptions::default()
1286                }),
1287                ..IndexOptions::default()
1288            },
1289        };
1290        db.replace_index("docs", "idx_embed_ann", new_def).unwrap();
1291
1292        let handle = db.table("docs").unwrap();
1293        let mut table = handle.lock();
1294        let hits = table
1295            .retrieve(&Retriever::Ann {
1296                column_id: 2,
1297                query: vec![1.0, 0.0, 0.0, 0.0],
1298                k: 1,
1299            })
1300            .unwrap();
1301        assert_eq!(hits.len(), 1);
1302        assert!(matches!(
1303            hits[0].score,
1304            RetrieverScore::AnnCosineDistance(_)
1305        ));
1306        assert!(!hits
1307            .iter()
1308            .any(|hit| matches!(hit.score, RetrieverScore::AnnHammingDistance(_))));
1309    }
1310
1311    #[test]
1312    fn drop_index_removes_schema_entry_without_rewrite() {
1313        let _lock = lock_tests();
1314        let dir = tempfile::tempdir().unwrap();
1315        let db = Database::create(dir.path()).unwrap();
1316        db.create_table("docs", embedding_schema(AnnQuantization::Dense))
1317            .unwrap();
1318        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1319        db.drop_index("docs", "idx_embed_ann").unwrap();
1320        let handle = db.table("docs").unwrap();
1321        let table = handle.lock();
1322        assert!(table.schema().indexes.is_empty());
1323        // Rows remain.
1324        let rows = table
1325            .visible_rows(Snapshot::at(table.current_epoch()))
1326            .unwrap();
1327        assert_eq!(rows.len(), 1);
1328    }
1329
1330    #[test]
1331    fn concurrent_writes_progress_during_create() {
1332        use std::sync::Barrier;
1333        let _lock = lock_tests();
1334        let dir = tempfile::tempdir().unwrap();
1335        let db = Arc::new(Database::create(dir.path()).unwrap());
1336        db.create_table("docs", plain_embedding_schema()).unwrap();
1337        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1338
1339        let start = Arc::new(Barrier::new(2));
1340        let writer = {
1341            let db = Arc::clone(&db);
1342            let start = Arc::clone(&start);
1343            std::thread::spawn(move || {
1344                start.wait();
1345                for id in 100..120 {
1346                    put_row(&db, "docs", id, vec![0.0, 1.0, 0.0, 0.0]);
1347                }
1348            })
1349        };
1350        start.wait();
1351        let definition = IndexDef {
1352            name: "idx_embed_ann".into(),
1353            column_id: 2,
1354            kind: IndexKind::Ann,
1355            predicate: None,
1356            options: IndexOptions {
1357                ann: Some(AnnOptions {
1358                    quantization: AnnQuantization::Dense,
1359                    ..AnnOptions::default()
1360                }),
1361                ..IndexOptions::default()
1362            },
1363        };
1364        db.create_index("docs", definition).unwrap();
1365        writer.join().unwrap();
1366        // Writers completed; index is published.
1367        let handle = db.table("docs").unwrap();
1368        let table = handle.lock();
1369        assert!(table
1370            .schema()
1371            .indexes
1372            .iter()
1373            .any(|index| index.name == "idx_embed_ann"));
1374    }
1375
1376    #[test]
1377    fn asynchronous_build_is_observable_and_replays_all_row_deltas() {
1378        use std::sync::Barrier;
1379        use std::time::Duration;
1380
1381        let _lock = lock_tests();
1382        let dir = tempfile::tempdir().unwrap();
1383        let db = Arc::new(Database::create(dir.path()).unwrap());
1384        db.create_table("docs", plain_embedding_schema()).unwrap();
1385        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1386        put_row(&db, "docs", 3, vec![0.0, 0.0, 1.0, 0.0]);
1387        let deleted_row = row_id_for_pk(&db, "docs", 3);
1388        let baseline = db
1389            .memory_governor()
1390            .usage(crate::memory::MemoryClass::Compaction);
1391
1392        let entered = Arc::new(Barrier::new(2));
1393        let release = Arc::new(Barrier::new(2));
1394        let callback_entered = Arc::clone(&entered);
1395        let callback_release = Arc::clone(&release);
1396        let _guard = mongreldb_fault::ScopedGuard::new(
1397            "job.build_hidden.after",
1398            mongreldb_fault::Action::Callback(Arc::new(move |_| {
1399                callback_entered.wait();
1400                callback_release.wait();
1401            })),
1402        );
1403
1404        let job_id = db.start_create_index("docs", dense_definition()).unwrap();
1405        entered.wait();
1406
1407        let running = db.job_registry().get(job_id).unwrap();
1408        assert_eq!(running.state, crate::jobs::JobState::Running);
1409        let persisted = IndexBuildSpec::decode(running.definition.as_deref().unwrap()).unwrap();
1410        assert_eq!(persisted.table, "docs");
1411        assert_eq!(persisted.kind.definition(), &dense_definition());
1412        assert_eq!(
1413            db.index_build_target_definition(job_id).unwrap(),
1414            dense_definition()
1415        );
1416        assert!(
1417            db.memory_governor()
1418                .usage(crate::memory::MemoryClass::Compaction)
1419                > baseline,
1420            "hidden generation must hold a governor reservation"
1421        );
1422
1423        // These commits land after the initial hidden graph was built and
1424        // before catch-up: one update, one insert, and one delete.
1425        put_row(&db, "docs", 1, vec![0.0, 1.0, 0.0, 0.0]);
1426        put_row(&db, "docs", 2, vec![0.0, 1.0, 0.0, 0.0]);
1427        db.transaction(|txn| txn.delete("docs", deleted_row))
1428            .unwrap();
1429
1430        release.wait();
1431        let terminal = db
1432            .job_registry()
1433            .wait_terminal(job_id, Duration::from_secs(30))
1434            .unwrap();
1435        assert_eq!(terminal.state, crate::jobs::JobState::Succeeded);
1436        assert_eq!(
1437            db.memory_governor()
1438                .usage(crate::memory::MemoryClass::Compaction),
1439            baseline,
1440            "successful build must release its reservation"
1441        );
1442
1443        let expected: std::collections::HashSet<_> = [1, 2]
1444            .into_iter()
1445            .map(|id| row_id_for_pk(&db, "docs", id))
1446            .collect();
1447        let handle = db.table("docs").unwrap();
1448        let mut table = handle.lock();
1449        let actual: std::collections::HashSet<_> = table
1450            .retrieve(&Retriever::Ann {
1451                column_id: 2,
1452                query: vec![0.0, 1.0, 0.0, 0.0],
1453                k: 10,
1454            })
1455            .unwrap()
1456            .into_iter()
1457            .map(|hit| hit.row_id)
1458            .collect();
1459        assert_eq!(actual, expected);
1460    }
1461
1462    #[test]
1463    fn cancelling_real_hidden_build_rolls_back_pin_memory_and_schema() {
1464        use std::sync::Barrier;
1465        use std::time::Duration;
1466
1467        let _lock = lock_tests();
1468        let dir = tempfile::tempdir().unwrap();
1469        let db = Arc::new(Database::create(dir.path()).unwrap());
1470        db.create_table("docs", plain_embedding_schema()).unwrap();
1471        for id in 0..32 {
1472            put_row(&db, "docs", id, vec![1.0, id as f32, 0.0, 0.0]);
1473        }
1474        let baseline = db
1475            .memory_governor()
1476            .usage(crate::memory::MemoryClass::Compaction);
1477
1478        let entered = Arc::new(Barrier::new(2));
1479        let release = Arc::new(Barrier::new(2));
1480        let callback_entered = Arc::clone(&entered);
1481        let callback_release = Arc::clone(&release);
1482        let _guard = mongreldb_fault::ScopedGuard::new(
1483            "job.build_hidden.after",
1484            mongreldb_fault::Action::Callback(Arc::new(move |_| {
1485                callback_entered.wait();
1486                callback_release.wait();
1487            })),
1488        );
1489
1490        let job_id = db.start_create_index("docs", dense_definition()).unwrap();
1491        entered.wait();
1492        db.job_registry().cancel(job_id).unwrap();
1493        release.wait();
1494        let terminal = db
1495            .job_registry()
1496            .wait_terminal(job_id, Duration::from_secs(30))
1497            .unwrap();
1498        assert_eq!(terminal.state, crate::jobs::JobState::Failed);
1499        assert!(terminal
1500            .error
1501            .as_deref()
1502            .is_some_and(|error| error.contains("cancel")));
1503        assert_eq!(
1504            db.memory_governor()
1505                .usage(crate::memory::MemoryClass::Compaction),
1506            baseline
1507        );
1508        assert!(
1509            db.table("docs").unwrap().lock().schema().indexes.is_empty(),
1510            "pre-publication cancellation must keep the old schema"
1511        );
1512    }
1513
1514    #[test]
1515    fn pending_index_job_reconstructs_and_resumes_after_reopen() {
1516        use std::time::Duration;
1517
1518        let _lock = lock_tests();
1519        let dir = tempfile::tempdir().unwrap();
1520        let path = dir.path().to_path_buf();
1521        let job_id = {
1522            let db = Database::create(&path).unwrap();
1523            db.create_table("docs", plain_embedding_schema()).unwrap();
1524            put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1525            let job_id = db.submit_create_index("docs", dense_definition()).unwrap();
1526            let pending = db.job_registry().get(job_id).unwrap();
1527            assert_eq!(pending.state, crate::jobs::JobState::Pending);
1528            assert!(pending.definition.is_some());
1529            job_id
1530        };
1531
1532        let db = Arc::new(Database::open(&path).unwrap());
1533        db.resume_index_build(job_id).unwrap();
1534        let terminal = db
1535            .job_registry()
1536            .wait_terminal(job_id, Duration::from_secs(30))
1537            .unwrap();
1538        assert_eq!(terminal.state, crate::jobs::JobState::Succeeded);
1539        assert_eq!(
1540            db.table("docs")
1541                .unwrap()
1542                .lock()
1543                .schema()
1544                .indexes
1545                .iter()
1546                .find(|index| index.name == "idx_embed_ann")
1547                .and_then(|index| index.options.ann.as_ref())
1548                .map(|options| options.quantization),
1549            Some(AnnQuantization::Dense)
1550        );
1551    }
1552
1553    #[test]
1554    fn dense_build_is_rejected_by_memory_admission_before_graph_allocation() {
1555        let _lock = lock_tests();
1556        let dir = tempfile::tempdir().unwrap();
1557        let path = dir.path().to_path_buf();
1558        let dim = 4_096u32;
1559        {
1560            let db = Database::create(&path).unwrap();
1561            let mut schema = plain_embedding_schema();
1562            schema.columns[1].ty = TypeId::Embedding { dim };
1563            db.create_table("docs", schema).unwrap();
1564            for id in 0..64 {
1565                let mut vector = vec![0.0; dim as usize];
1566                vector[id as usize] = 1.0;
1567                put_row(&db, "docs", id, vector);
1568            }
1569        }
1570
1571        let db = Database::open_with_options(
1572            &path,
1573            crate::database::OpenOptions::default().with_memory_budget_bytes(2 * 1024 * 1024),
1574        )
1575        .unwrap();
1576        let baseline = db
1577            .memory_governor()
1578            .usage(crate::memory::MemoryClass::Compaction);
1579        let error = db
1580            .create_index("docs", dense_definition())
1581            .expect_err("oversized Dense graph must be denied");
1582        assert!(
1583            matches!(
1584                error,
1585                MongrelError::ResourceLimitExceeded {
1586                    resource: "index build memory",
1587                    ..
1588                }
1589            ),
1590            "unexpected admission error: {error:?}"
1591        );
1592        assert_eq!(
1593            db.memory_governor()
1594                .usage(crate::memory::MemoryClass::Compaction),
1595            baseline,
1596            "rejected build must not leak a reservation"
1597        );
1598        assert!(db.table("docs").unwrap().lock().schema().indexes.is_empty());
1599    }
1600
1601    #[test]
1602    fn ddl_auth_fail_closed() {
1603        let _lock = lock_tests();
1604        let dir = tempfile::tempdir().unwrap();
1605        let path = dir.path().to_path_buf();
1606        {
1607            let db = Database::create_with_credentials(&path, "admin", "admin-pw").unwrap();
1608            db.create_table("docs", plain_embedding_schema()).unwrap();
1609            db.create_user("alice", "alice-pw").unwrap();
1610            db.create_role("reader").unwrap();
1611            db.grant_permission(
1612                "reader",
1613                crate::auth::Permission::Select {
1614                    table: "docs".into(),
1615                },
1616            )
1617            .unwrap();
1618            db.grant_role("alice", "reader").unwrap();
1619        }
1620        let db = Database::open_with_credentials(&path, "alice", "alice-pw").unwrap();
1621        let definition = IndexDef {
1622            name: "idx".into(),
1623            column_id: 2,
1624            kind: IndexKind::Ann,
1625            predicate: None,
1626            options: IndexOptions {
1627                ann: Some(AnnOptions {
1628                    quantization: AnnQuantization::Dense,
1629                    ..AnnOptions::default()
1630                }),
1631                ..IndexOptions::default()
1632            },
1633        };
1634        let err = db.create_index("docs", definition).unwrap_err();
1635        assert!(
1636            matches!(err, MongrelError::PermissionDenied { .. }),
1637            "unexpected error: {err:?}"
1638        );
1639    }
1640
1641    #[test]
1642    fn cluster_replica_rejects_local_index_ddl() {
1643        let _lock = lock_tests();
1644        use mongreldb_types::ids::{ClusterId, DatabaseId, NodeId};
1645        let dir = tempfile::tempdir().unwrap();
1646        let cluster_id = ClusterId::from_bytes([1; 16]);
1647        let node_id = NodeId::from_bytes([2; 16]);
1648        let database_id = DatabaseId::from_bytes([3; 16]);
1649        let db =
1650            Database::create_cluster_replica(dir.path(), cluster_id, node_id, database_id).unwrap();
1651        assert!(db.is_read_only_replica());
1652        let definition = IndexDef {
1653            name: "idx".into(),
1654            column_id: 2,
1655            kind: IndexKind::Ann,
1656            predicate: None,
1657            options: Default::default(),
1658        };
1659        let err = db.create_index("docs", definition).unwrap_err();
1660        assert!(
1661            matches!(err, MongrelError::ReadOnlyReplica),
1662            "cluster replica must reject local index DDL: {err:?}"
1663        );
1664    }
1665
1666    #[test]
1667    fn fault_before_publish_leaves_old_schema() {
1668        let _lock = lock_tests();
1669        // ScopedGuard clears the registry on drop so other serial tests never
1670        // observe a leftover armed hook.
1671        let _guard = mongreldb_fault::ScopedGuard::new(
1672            "index.publish.before",
1673            mongreldb_fault::Action::Fail,
1674        );
1675        let dir = tempfile::tempdir().unwrap();
1676        let db = Database::create(dir.path()).unwrap();
1677        db.create_table("docs", plain_embedding_schema()).unwrap();
1678        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1679
1680        let definition = IndexDef {
1681            name: "idx_embed_ann".into(),
1682            column_id: 2,
1683            kind: IndexKind::Ann,
1684            predicate: None,
1685            options: IndexOptions {
1686                ann: Some(AnnOptions {
1687                    quantization: AnnQuantization::Dense,
1688                    ..AnnOptions::default()
1689                }),
1690                ..IndexOptions::default()
1691            },
1692        };
1693        let err = db.create_index("docs", definition).unwrap_err();
1694        assert!(
1695            !matches!(err, MongrelError::NotFound(_)),
1696            "should fail at publish, not earlier: {err:?}"
1697        );
1698        let handle = db.table("docs").unwrap();
1699        let table = handle.lock();
1700        assert!(
1701            table.schema().indexes.is_empty(),
1702            "pre-publication fault must leave the old schema active"
1703        );
1704    }
1705
1706    #[test]
1707    fn cancel_pre_publish_leaves_old_index() {
1708        let _lock = lock_tests();
1709        // Drive a job and cancel while Pending so publication never runs.
1710        let dir = tempfile::tempdir().unwrap();
1711        let db = Database::create(dir.path()).unwrap();
1712        db.create_table("docs", embedding_schema(AnnQuantization::BinarySign))
1713            .unwrap();
1714        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1715
1716        // Submit without driving, then cancel.
1717        let job_id = db
1718            .job_registry()
1719            .submit(
1720                JobKind::IndexBuild,
1721                JobTarget {
1722                    table: "docs".into(),
1723                    index: Some("idx_embed_ann".into()),
1724                },
1725            )
1726            .unwrap();
1727        db.job_registry().cancel(job_id).unwrap();
1728        let record = db.job_registry().get(job_id).unwrap();
1729        assert_eq!(record.state, crate::jobs::JobState::Failed);
1730
1731        // Schema still has the original BinarySign index.
1732        let handle = db.table("docs").unwrap();
1733        let table = handle.lock();
1734        let index = table
1735            .schema()
1736            .indexes
1737            .iter()
1738            .find(|index| index.name == "idx_embed_ann")
1739            .unwrap();
1740        assert_eq!(
1741            index
1742                .options
1743                .ann
1744                .as_ref()
1745                .map(|options| options.quantization),
1746            Some(AnnQuantization::BinarySign)
1747        );
1748    }
1749
1750    #[test]
1751    fn replace_dense_with_binary_sign_search_works() {
1752        let _lock = lock_tests();
1753        let dir = tempfile::tempdir().unwrap();
1754        let db = Database::create(dir.path()).unwrap();
1755        db.create_table("docs", embedding_schema(AnnQuantization::Dense))
1756            .unwrap();
1757        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1758        put_row(&db, "docs", 2, vec![0.0, 1.0, 0.0, 0.0]);
1759
1760        let new_def = IndexDef {
1761            name: "idx_embed_ann".into(),
1762            column_id: 2,
1763            kind: IndexKind::Ann,
1764            predicate: None,
1765            options: IndexOptions {
1766                ann: Some(AnnOptions {
1767                    m: 8,
1768                    ef_construction: 32,
1769                    ef_search: 16,
1770                    quantization: AnnQuantization::BinarySign,
1771                    ..AnnOptions::default()
1772                }),
1773                ..IndexOptions::default()
1774            },
1775        };
1776        db.replace_index("docs", "idx_embed_ann", new_def).unwrap();
1777
1778        let handle = db.table("docs").unwrap();
1779        let mut table = handle.lock();
1780        let hits = table
1781            .retrieve(&Retriever::Ann {
1782                column_id: 2,
1783                query: vec![1.0, 0.0, 0.0, 0.0],
1784                k: 1,
1785            })
1786            .unwrap();
1787        assert_eq!(hits.len(), 1);
1788        assert!(matches!(
1789            hits[0].score,
1790            RetrieverScore::AnnHammingDistance(_)
1791        ));
1792        assert!(!hits
1793            .iter()
1794            .any(|hit| matches!(hit.score, RetrieverScore::AnnCosineDistance(_))));
1795    }
1796
1797    #[test]
1798    fn fault_after_publish_keeps_new_index() {
1799        let _lock = lock_tests();
1800        // `index.publish.after` fires only after the durable boundary; Fail
1801        // must not roll back the new schema (spec §4.7 / FND-006 after semantics).
1802        let _guard =
1803            mongreldb_fault::ScopedGuard::new("index.publish.after", mongreldb_fault::Action::Fail);
1804        let dir = tempfile::tempdir().unwrap();
1805        let db = Database::create(dir.path()).unwrap();
1806        db.create_table("docs", plain_embedding_schema()).unwrap();
1807        put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1808
1809        let definition = IndexDef {
1810            name: "idx_embed_ann".into(),
1811            column_id: 2,
1812            kind: IndexKind::Ann,
1813            predicate: None,
1814            options: IndexOptions {
1815                ann: Some(AnnOptions {
1816                    quantization: AnnQuantization::Dense,
1817                    ..AnnOptions::default()
1818                }),
1819                ..IndexOptions::default()
1820            },
1821        };
1822        // Publication may surface a post-fence error; the schema must still
1823        // carry the new Dense index.
1824        let _ = db.create_index("docs", definition);
1825        let handle = db.table("docs").unwrap();
1826        let table = handle.lock();
1827        let index = table
1828            .schema()
1829            .indexes
1830            .iter()
1831            .find(|index| index.name == "idx_embed_ann");
1832        assert!(
1833            index.is_some(),
1834            "post-publish fault must keep the new index active"
1835        );
1836        assert_eq!(
1837            index
1838                .unwrap()
1839                .options
1840                .ann
1841                .as_ref()
1842                .map(|options| options.quantization),
1843            Some(AnnQuantization::Dense)
1844        );
1845    }
1846
1847    #[test]
1848    fn dense_plaintext_close_reopen_preserves_search() {
1849        let _lock = lock_tests();
1850        let dir = tempfile::tempdir().unwrap();
1851        let path = dir.path().to_path_buf();
1852        {
1853            let db = Database::create(&path).unwrap();
1854            db.create_table("docs", embedding_schema(AnnQuantization::Dense))
1855                .unwrap();
1856            put_row(&db, "docs", 1, vec![1.0, 0.0, 0.0, 0.0]);
1857            put_row(&db, "docs", 2, vec![0.0, 1.0, 0.0, 0.0]);
1858            // Force checkpoint materialization.
1859            let handle = db.table("docs").unwrap();
1860            let mut table = handle.lock();
1861            table.flush().unwrap();
1862            let _ = table.publish_read_generation().unwrap();
1863        }
1864        let db = Database::open(&path).unwrap();
1865        let handle = db.table("docs").unwrap();
1866        let mut table = handle.lock();
1867        let hits = table
1868            .retrieve(&Retriever::Ann {
1869                column_id: 2,
1870                query: vec![1.0, 0.0, 0.0, 0.0],
1871                k: 1,
1872            })
1873            .unwrap();
1874        assert_eq!(hits.len(), 1);
1875        assert!(matches!(
1876            hits[0].score,
1877            RetrieverScore::AnnCosineDistance(d) if d.abs() < 1e-4
1878        ));
1879    }
1880}