Skip to main content

reddb_server/runtime/
impl_dml.rs

1//! DML execution: INSERT, UPDATE, DELETE via SQL AST
2//!
3//! Implements `execute_insert`, `execute_update`, and `execute_delete` on
4//! `RedDBRuntime`.  Each method translates the parsed AST into entity-level
5//! operations through the existing `RuntimeEntityPort` trait so that all
6//! cross-cutting concerns (WAL, indexing, replication) are automatically
7//! applied.
8
9use crate::application::entity::{
10    metadata_from_json, AppliedEntityMutation, CreateDocumentInput, CreateEdgeInput,
11    CreateEntityOutput, CreateKvInput, CreateNodeInput, CreateRowInput, CreateRowsBatchInput,
12    CreateVectorInput, DeleteEntityInput, PatchEntityOperation, PatchEntityOperationType,
13    RowUpdateColumnRule, RowUpdateContractPlan,
14};
15use crate::application::ports::{
16    build_row_update_contract_plan, entity_row_fields_snapshot,
17    normalize_row_update_assignment_with_plan, normalize_row_update_value_for_rule,
18    RuntimeEntityPort,
19};
20use crate::application::ttl_payload::has_internal_ttl_metadata;
21use crate::runtime::mvcc::current_connection_id;
22use crate::storage::query::unified::{
23    sys_key_collection, sys_key_created_at, sys_key_kind, sys_key_rid, sys_key_tenant,
24    sys_key_updated_at, UnifiedRecord, UnifiedResult,
25};
26use crate::storage::unified::MetadataValue;
27use crate::storage::Metadata;
28use reddb_rql::ast::{
29    BinOp, CompareOp, Expr, FieldRef, Filter, OnConflictAction, ReturningItem, UpdateQuery,
30    UpdateTarget,
31};
32use reddb_rql::sql_lowering::{
33    effective_delete_filter, effective_insert_rows, effective_update_filter, fold_expr_to_value,
34};
35use std::collections::HashMap;
36use std::sync::Arc;
37
38use super::*;
39// Insert-support and value-conversion helpers were extracted to
40// `impl_dml_support` (issue #1632); import them so existing call sites keep
41// using their bare names unchanged.
42use super::impl_dml_support::*;
43// RETURNING / update-analysis / update-target / claim helpers were extracted
44// to sibling modules (issue #1633); import them so existing call sites keep
45// using their bare names unchanged.
46use super::impl_dml_claim::*;
47use super::impl_dml_returning::*;
48use super::impl_dml_update_analysis::*;
49use super::impl_dml_update_target::*;
50// Chain-integrity / tenant-injection / batch-flush / crypto method families
51// were extracted to sibling modules (issue #1634). Their methods dispatch
52// through `self`, so no glob import is needed here. The SQL TTL free functions
53// are re-exported so both the execution paths below and
54// `impl_dml_support`'s `use super::impl_dml::{...}` keep resolving unchanged.
55pub(super) use super::impl_dml_ttl::{canonicalize_sql_ttl_metadata, resolve_sql_ttl_metadata_key};
56
57pub(super) const UPDATE_APPLY_CHUNK_SIZE: usize = 2048;
58pub(super) const TREE_CHILD_EDGE_LABEL: &str = "TREE_CHILD";
59pub(super) const TREE_METADATA_PREFIX: &str = "red.tree.";
60
61#[derive(Clone)]
62pub(super) struct CompiledUpdateAssignment {
63    column: String,
64    expr: Expr,
65    compound_op: Option<BinOp>,
66    metadata_key: Option<&'static str>,
67    row_rule: Option<RowUpdateColumnRule>,
68}
69
70pub(super) struct CompiledUpdatePlan {
71    pub(super) static_field_assignments: Vec<(String, Value)>,
72    pub(super) static_metadata_assignments: Vec<(String, MetadataValue)>,
73    dynamic_assignments: Vec<CompiledUpdateAssignment>,
74    row_contract_plan: Option<RowUpdateContractPlan>,
75    row_modified_columns: Vec<String>,
76    row_touches_unique_columns: bool,
77    /// The SET list names a column of a standalone UNIQUE index.
78    touches_unique_index: bool,
79}
80
81#[derive(Default)]
82pub(super) struct MaterializedUpdateAssignments {
83    pub(super) dynamic_field_assignments: Vec<(String, Value)>,
84    pub(super) dynamic_metadata_assignments: Vec<(String, MetadataValue)>,
85}
86
87fn resolve_excluded_assignment(
88    expr: &Expr,
89    excluded_fields: &[(String, Value)],
90) -> RedDBResult<Expr> {
91    match expr {
92        Expr::Column {
93            field: FieldRef::TableColumn { table, column },
94            span,
95        } if table.eq_ignore_ascii_case("excluded") => {
96            let value = excluded_fields
97                .iter()
98                .find(|(name, _)| name.eq_ignore_ascii_case(column))
99                .map(|(_, value)| value.clone())
100                .ok_or_else(|| {
101                    RedDBError::Query(format!(
102                        "ON CONFLICT EXCLUDED references unknown insert column '{column}'"
103                    ))
104                })?;
105            Ok(Expr::Literal { value, span: *span })
106        }
107        Expr::BinaryOp { op, lhs, rhs, span } => Ok(Expr::BinaryOp {
108            op: *op,
109            lhs: Box::new(resolve_excluded_assignment(lhs, excluded_fields)?),
110            rhs: Box::new(resolve_excluded_assignment(rhs, excluded_fields)?),
111            span: *span,
112        }),
113        _ => Ok(expr.clone()),
114    }
115}
116
117fn conflict_columns_match(index_columns: &[String], target_columns: &[String]) -> bool {
118    index_columns.len() == target_columns.len()
119        && index_columns.iter().all(|index_column| {
120            target_columns
121                .iter()
122                .any(|target_column| target_column.eq_ignore_ascii_case(index_column))
123        })
124}
125
126fn conflict_index_key(fields: &[(String, Value)], columns: &[String]) -> Option<Vec<Value>> {
127    columns
128        .iter()
129        .map(|column| {
130            super::index_store::index_field_value(fields, column)
131                .filter(|value| !matches!(value.as_ref(), Value::Null))
132                .map(|value| value.into_owned())
133        })
134        .collect()
135}
136
137fn document_on_conflict_fields(
138    stored_fields: &[(String, Value)],
139    body: &crate::json::Value,
140) -> RedDBResult<Vec<(String, Value)>> {
141    let mut fields = stored_fields.to_vec();
142    if let crate::json::Value::Object(object) = body {
143        for (name, value) in object {
144            fields.push((
145                name.clone(),
146                crate::application::entity::json_to_storage_value(value)?,
147            ));
148        }
149    }
150    Ok(fields)
151}
152
153impl RedDBRuntime {
154    fn conflict_unique_indexes(
155        &self,
156        collection: &str,
157        target: Option<&[String]>,
158    ) -> RedDBResult<Vec<super::index_store::RegisteredIndex>> {
159        let mut indexes = self
160            .index_store_ref()
161            .list_indices(collection)
162            .into_iter()
163            .filter(|index| index.unique)
164            .collect::<Vec<_>>();
165        if let Some(target) = target {
166            indexes.retain(|index| conflict_columns_match(&index.columns, target));
167            if indexes.is_empty() {
168                return Err(RedDBError::Query(format!(
169                    "no unique index on collection '{}' matches ON CONFLICT ({})",
170                    collection,
171                    target.join(", ")
172                )));
173            }
174        }
175        Ok(indexes)
176    }
177
178    fn unique_index_conflict_id(
179        &self,
180        collection: &str,
181        fields: &[(String, Value)],
182        target: Option<&[String]>,
183    ) -> RedDBResult<Option<EntityId>> {
184        let indexes = self.conflict_unique_indexes(collection, target)?;
185        let Some(manager) = self.inner.db.store().get_collection(collection) else {
186            return Ok(None);
187        };
188        for index in indexes {
189            let Some(proposed_key) = conflict_index_key(fields, &index.columns) else {
190                continue;
191            };
192            for entity in manager.query_all(|_| true) {
193                let Some(record) = runtime_any_record_from_entity_ref(&entity) else {
194                    continue;
195                };
196                let existing_fields = record
197                    .iter_fields()
198                    .map(|(name, value)| (name.as_ref().to_string(), value.clone()))
199                    .collect::<Vec<_>>();
200                if self.snapshot_manager().is_aborted(entity.xmin) {
201                    self.index_store_ref()
202                        .index_entity_delete(collection, entity.id, &existing_fields)
203                        .map_err(RedDBError::Internal)?;
204                    continue;
205                }
206                if conflict_index_key(&existing_fields, &index.columns)
207                    .is_some_and(|existing_key| existing_key == proposed_key)
208                {
209                    let conflicting_xid = entity.xmin;
210                    if self.snapshot_manager().is_active(conflicting_xid)
211                        && !self.own_transaction_xids().contains(&conflicting_xid)
212                    {
213                        return Err(RedDBError::Query(format!(
214                            "serialization conflict: ON CONFLICT key in '{collection}' is owned by active transaction {conflicting_xid}; retry the statement after that transaction resolves"
215                        )));
216                    }
217                    return Ok(Some(entity.id));
218                }
219            }
220        }
221        Ok(None)
222    }
223
224    fn on_conflict_unique_index_conflict_id(
225        &self,
226        collection: &str,
227        fields: &[(String, Value)],
228        target: Option<&[String]>,
229    ) -> RedDBResult<Option<EntityId>> {
230        let selected = self.unique_index_conflict_id(collection, fields, target)?;
231        if selected.is_some() || target.is_none() {
232            return Ok(selected);
233        }
234        if self
235            .unique_index_conflict_id(collection, fields, None)?
236            .is_some()
237        {
238            return Err(RedDBError::Query(format!(
239                "unique index conflict on collection '{collection}' is not covered by ON CONFLICT ({})",
240                target.unwrap_or_default().join(", ")
241            )));
242        }
243        Ok(None)
244    }
245
246    fn has_unique_index_conflict_with_fields(
247        &self,
248        collection: &str,
249        fields: &[(String, Value)],
250        existing_fields: &[Vec<(String, Value)>],
251        target: Option<&[String]>,
252    ) -> RedDBResult<bool> {
253        for index in self.conflict_unique_indexes(collection, target)? {
254            let Some(proposed_key) = conflict_index_key(fields, &index.columns) else {
255                continue;
256            };
257            if existing_fields.iter().any(|existing| {
258                conflict_index_key(existing, &index.columns)
259                    .is_some_and(|existing_key| existing_key == proposed_key)
260            }) {
261                return Ok(true);
262            }
263        }
264        Ok(false)
265    }
266
267    fn has_on_conflict_unique_index_conflict_with_fields(
268        &self,
269        collection: &str,
270        fields: &[(String, Value)],
271        existing_fields: &[Vec<(String, Value)>],
272        target: Option<&[String]>,
273    ) -> RedDBResult<bool> {
274        let selected = self.has_unique_index_conflict_with_fields(
275            collection,
276            fields,
277            existing_fields,
278            target,
279        )?;
280        if selected || target.is_none() {
281            return Ok(selected);
282        }
283        if self.has_unique_index_conflict_with_fields(collection, fields, existing_fields, None)? {
284            return Err(RedDBError::Query(format!(
285                "unique index conflict on collection '{collection}' is not covered by ON CONFLICT ({})",
286                target.unwrap_or_default().join(", ")
287            )));
288        }
289        Ok(false)
290    }
291
292    fn execute_unique_index_conflict_update(
293        &self,
294        raw_query: &str,
295        insert: &InsertQuery,
296        conflict_id: EntityId,
297        target: UpdateTarget,
298        excluded_fields: &[(String, Value)],
299        assignments: &[(String, Expr)],
300    ) -> RedDBResult<RuntimeQueryResult> {
301        let assignment_exprs = assignments
302            .iter()
303            .map(|(column, expr)| {
304                Ok((
305                    column.clone(),
306                    resolve_excluded_assignment(expr, excluded_fields)?,
307                ))
308            })
309            .collect::<RedDBResult<Vec<_>>>()?;
310        let literal_assignments = assignment_exprs
311            .iter()
312            .filter_map(|(column, expr)| {
313                fold_expr_to_value(expr.clone())
314                    .ok()
315                    .map(|value| (column.clone(), value))
316            })
317            .collect();
318        let update = UpdateQuery {
319            table: insert.table.clone(),
320            target,
321            compound_assignment_ops: vec![None; assignment_exprs.len()],
322            assignment_exprs,
323            assignments: literal_assignments,
324            where_expr: None,
325            filter: Some(Filter::Compare {
326                field: FieldRef::column("", "rid"),
327                op: CompareOp::Eq,
328                value: Value::UnsignedInteger(conflict_id.raw()),
329            }),
330            ttl_ms: None,
331            expires_at_ms: None,
332            with_metadata: Vec::new(),
333            returning: insert.returning.clone(),
334            claim_limit: None,
335            claim_exact: false,
336            order_by: Vec::new(),
337            limit: None,
338            suppress_events: insert.suppress_events,
339        };
340        self.execute_update(raw_query, &update)
341    }
342
343    /// ADR 0067 (#1710): resolve the model of an unmarked bare-VALUES
344    /// INSERT from the catalog, making the marker rule real — *a model
345    /// marker exists only where it disambiguates what the catalog cannot
346    /// know.*
347    ///
348    /// `INSERT INTO c VALUES ({…})` has no column list and no model marker,
349    /// so the parser leaves `entity_type = Row` with an empty column list.
350    /// Only that exact shape is a candidate for inference — every other
351    /// INSERT (an explicit column list, or an explicit `DOCUMENT` / `NODE`
352    /// / `VECTOR` / … marker) is returned untouched.
353    ///
354    /// * existing **document** collection → rewritten to a `DOCUMENT`
355    ///   insert so the body routes through document creation, exactly the
356    ///   path the explicit marker takes;
357    /// * existing **non-document** collection → the bare form does not
358    ///   apply; reported with a model-oriented error;
359    /// * unknown collection → didactic error naming both recourses (the
360    ///   `DOCUMENT` assertion form or `CREATE DOCUMENT` first).
361    fn infer_unmarked_document_insert(
362        &self,
363        query: &InsertQuery,
364    ) -> RedDBResult<Option<InsertQuery>> {
365        if !matches!(query.entity_type, InsertEntityType::Row) || !query.columns.is_empty() {
366            return Ok(None);
367        }
368        match self
369            .db()
370            .collection_contract_arc(&query.table)
371            .map(|contract| contract.declared_model)
372        {
373            Some(crate::catalog::CollectionModel::Document) => {
374                let mut rewritten = query.clone();
375                rewritten.entity_type = InsertEntityType::Document;
376                rewritten.columns = vec!["body".to_string()];
377                Ok(Some(rewritten))
378            }
379            Some(other) => Err(RedDBError::InvalidOperation(format!(
380                "collection '{table}' is declared as '{model}'; the bare \
381                 `INSERT INTO {table} VALUES (…)` form is the document body shorthand — \
382                 write an explicit column list (`INSERT INTO {table} (col, …) VALUES (…)`) \
383                 to insert into a {model} collection",
384                table = query.table,
385                model = crate::runtime::ddl::polymorphic_resolver::model_name(other),
386            ))),
387            None => Err(RedDBError::InvalidOperation(format!(
388                "collection '{table}' does not exist and the INSERT carries no model marker; \
389                 write `INSERT INTO {table} DOCUMENT VALUES ({{…}})` to create it as a document \
390                 (idempotent), or run `CREATE DOCUMENT {table}` first",
391                table = query.table,
392            ))),
393        }
394    }
395
396    /// Resolve the model of an unmarked UPDATE from the catalog (ADR 0067,
397    /// #1711). The `DOCUMENTS` / `ROWS` / `KV` UPDATE markers were removed, so
398    /// an unmarked UPDATE parses to the `Rows` target; the catalog is the
399    /// single source of truth for the collection's model. An existing document
400    /// collection is rewritten to the `Documents` target (the runtime routes
401    /// body / patch semantics off the target the explicit marker used to set);
402    /// a KV collection to `Kv` so the key-immutability guard still fires. Table
403    /// and unknown collections keep the `Rows` default.
404    ///
405    /// Dotted assignment targets (`SET a.b.c = …`) parse for every target — the
406    /// model is not a parse-time fact — but they are legal only on a document
407    /// collection and rejected here with a clear model-oriented error off it.
408    fn resolve_unmarked_update_target(
409        &self,
410        query: &UpdateQuery,
411    ) -> RedDBResult<Option<UpdateQuery>> {
412        // NODES / EDGES are explicit, user-declared graph targets — never
413        // inferred. Dotted paths off a graph target are still off-model.
414        if matches!(query.target, UpdateTarget::Nodes | UpdateTarget::Edges) {
415            ensure_update_dotted_targets_allowed(query, false)?;
416            return Ok(None);
417        }
418        let declared_model = self
419            .db()
420            .collection_contract_arc(&query.table)
421            .map(|contract| contract.declared_model);
422        let is_document = matches!(
423            declared_model,
424            Some(crate::catalog::CollectionModel::Document)
425        );
426        ensure_update_dotted_targets_allowed(query, is_document)?;
427        let inferred = match declared_model {
428            Some(crate::catalog::CollectionModel::Document) => UpdateTarget::Documents,
429            Some(crate::catalog::CollectionModel::Kv) => UpdateTarget::Kv,
430            _ => return Ok(None),
431        };
432        let mut rewritten = query.clone();
433        rewritten.target = inferred;
434        Ok(Some(rewritten))
435    }
436
437    /// Execute INSERT INTO table [entity_type] (cols) VALUES (vals), ...
438    ///
439    /// Each row in `query.values` is zipped with `query.columns` to produce a
440    /// set of named fields, which is then dispatched based on entity_type.
441    pub fn execute_insert(
442        &self,
443        raw_query: &str,
444        query: &InsertQuery,
445    ) -> RedDBResult<RuntimeQueryResult> {
446        self.with_graph_insert_for_dml(query, || self.execute_insert_inner(raw_query, query))
447    }
448
449    fn execute_insert_inner(
450        &self,
451        raw_query: &str,
452        query: &InsertQuery,
453    ) -> RedDBResult<RuntimeQueryResult> {
454        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
455        // A plain INSERT adds rows and index entries and removes none, so it
456        // leaves no index behind a concurrent reader. An upsert can update.
457        let _indexed_mutation = query
458            .on_conflict
459            .is_some()
460            .then(|| self.index_store_ref().begin_indexed_mutation(&query.table));
461        let branch_store = self.db().store();
462        let _branch_publication = (self.vcs_is_versioned(&query.table)?
463            || self.has_graph_contract(&query.table))
464        .then(|| branch_store.vault_publication_lock.lock());
465        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
466            self,
467            &query.table,
468        );
469        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
470        // CollectionContract gate (#49): single entry point for the
471        // operator's collection-level write rules. Today this is a
472        // no-op for INSERT (APPEND ONLY permits insert); routing
473        // through the gate now means future contract bits — versioned,
474        // vault-only writes — plug in once instead of per verb.
475        crate::runtime::collection_contract::CollectionContractGate::check(
476            self,
477            &query.table,
478            crate::runtime::collection_contract::MutationKind::Insert,
479        )?;
480        // ADR 0067 (#1710): catalog model inference for the unmarked
481        // bare-VALUES INSERT. `INSERT INTO c VALUES ({…})` carries no
482        // column list and no model marker (parsed as a Row insert with an
483        // empty column list); resolve the model from the catalog so an
484        // existing document collection routes to document creation and an
485        // unknown collection surfaces a didactic error. Runs before tenant
486        // injection so a rewritten document insert is tenant-scoped like
487        // the explicit `DOCUMENT` marker path.
488        let inferred_owned;
489        let query = match self.infer_unmarked_document_insert(query)? {
490            Some(rewritten) => {
491                inferred_owned = rewritten;
492                &inferred_owned
493            }
494            None => query,
495        };
496        // Phase 2.5.4 table-scoped tenancy: if the target table is
497        // tenant-scoped and the user didn't name the tenant column,
498        // auto-inject it with the thread-local `CURRENT_TENANT()`
499        // value. Explicit values must match the active transport/session
500        // tenant; an unbound platform caller may still write on behalf of a
501        // tenant. An unbound tenant on an implicit-fill path errors up front
502        // rather than producing a row the RLS policy would silently hide.
503        let augmented_owned;
504        let query = match self.maybe_inject_tenant_column(query)? {
505            Some(new_q) => {
506                augmented_owned = new_q;
507                &augmented_owned
508            }
509            None => query,
510        };
511        if query.on_conflict.is_some()
512            && !matches!(
513                query.entity_type,
514                InsertEntityType::Row
515                    | InsertEntityType::Document
516                    | InsertEntityType::Node
517                    | InsertEntityType::Edge
518            )
519        {
520            return Err(RedDBError::InvalidOperation(
521                "ON CONFLICT is supported for table rows, documents, graph nodes, and graph edges"
522                    .to_string(),
523            ));
524        }
525        self.check_insert_column_policy(query)?;
526        let resolved_auto_embed = if let Some(ref embed_config) = query.auto_embed {
527            // Empty provider → resolve via the embeddings task pointer
528            // (ADR-0068 §5); an explicit `USING` overrides it. A modality-
529            // incapable provider fails didactically here.
530            let provider =
531                crate::ai::resolve_embeddings_provider_from_runtime(self, &embed_config.provider)?;
532            // S3 / #711: planner-level provider gate. Runs before the
533            // local-model preflight and the API-key resolver so neither
534            // side-effect fires when policy denies.
535            crate::runtime::ai::provider_gate::enforce(self, &provider)?;
536            if matches!(provider, crate::ai::AiProvider::Local) {
537                crate::runtime::ai::local_embedding::ensure_local_embedding_available()?;
538                // Issue #682 — pre-flight the local model registry before
539                // any row write. Missing model, uninstalled artifacts,
540                // wrong task, and disabled-feature failures surface as
541                // deterministic errors that leave the target collection
542                // untouched, satisfying the "no partial writes on
543                // embedding failure" criterion for the failure modes
544                // owned by the local provider.
545                let model_name = embed_config.model.as_deref().map(str::trim).unwrap_or("");
546                if model_name.is_empty() {
547                    return Err(RedDBError::Query(
548                        "AUTO EMBED with provider=local requires MODEL '<registered-model-name>'; \
549                         the local provider does not have an implicit default model"
550                            .to_string(),
551                    ));
552                }
553                crate::runtime::ai::local_embedding::preflight_local_embedding(
554                    &self.inner.db,
555                    model_name,
556                )?;
557            }
558            let connection = if matches!(provider, crate::ai::AiProvider::Local) {
559                None
560            } else {
561                Some(crate::ai::resolve_connection_from_runtime(
562                    &provider, None, self,
563                )?)
564            };
565            let model = crate::ai::resolve_embeddings_model_from_runtime(
566                self,
567                &provider,
568                embed_config.model.as_deref(),
569            );
570            Some((provider, model, connection, &embed_config.fields))
571        } else {
572            None
573        };
574
575        let mut inserted_count: u64 = 0;
576        let effective_rows =
577            effective_insert_rows(query).map_err(|msg| RedDBError::Query(msg.to_string()))?;
578        if effective_rows.len() > 1
579            && matches!(
580                query.on_conflict.as_ref().map(|clause| &clause.action),
581                Some(OnConflictAction::DoUpdate { .. })
582            )
583        {
584            return Err(RedDBError::InvalidOperation(
585                "multi-row ON CONFLICT DO UPDATE is not supported atomically; execute one proposed row per statement"
586                    .to_string(),
587            ));
588        }
589
590        // Ensure the collection exists (auto-create on first insert).
591        let store = self.inner.db.store();
592        let _ = store.get_or_create_collection(&query.table);
593        let contract = self.db().collection_contract_arc(&query.table);
594        let declared_model = contract.as_ref().map(|contract| contract.declared_model);
595        let secret_columns: Vec<bool> = query
596            .columns
597            .iter()
598            .map(|column| {
599                contract.as_ref().is_some_and(|contract| {
600                    contract.declared_columns.iter().any(|declared| {
601                        declared.name == *column
602                            && declared.data_type.eq_ignore_ascii_case("secret")
603                    })
604                })
605            })
606            .collect();
607        if query.on_conflict.is_some()
608            && matches!(
609                declared_model,
610                Some(crate::catalog::CollectionModel::TimeSeries)
611            )
612        {
613            return Err(RedDBError::InvalidOperation(
614                "ON CONFLICT is not supported for time-series collections".to_string(),
615            ));
616        }
617
618        // One collection-scoped acquisition per upsert statement. Conflict
619        // discovery currently scans the collection, so the lock is not the
620        // dominant cost; it closes the check-then-insert race for every model
621        // until unique indexes become the atomic arbiter themselves.
622        let conflict_rmw_lock = query.on_conflict.as_ref().map(|_| {
623            self.inner
624                .rmw_locks
625                .lock_for(&query.table, "__collection_on_conflict_insert__")
626        });
627        let _conflict_rmw_guard = conflict_rmw_lock.as_ref().map(|lock| lock.lock());
628
629        let mut returning_snapshots: Option<Vec<Vec<(String, Value)>>> =
630            if query.returning.is_some() {
631                Some(Vec::with_capacity(effective_rows.len()))
632            } else {
633                None
634            };
635        let mut returning_result: Option<UnifiedResult> = None;
636        let mut conflict_returning_records: Vec<UnifiedRecord> = Vec::new();
637        let mut auto_embed_ids = Vec::new();
638
639        if matches!(query.entity_type, InsertEntityType::Row)
640            && !matches!(
641                declared_model,
642                Some(crate::catalog::CollectionModel::TimeSeries)
643            )
644        {
645            // Issue #523 + #524: blockchain collections seal each row into the
646            // chain. When the caller omits the reserved columns, the engine
647            // auto-fills (#523). When the caller supplies any reserved column,
648            // the values are validated against the current tip and a mismatch
649            // surfaces a `BlockchainConflict:` error mapped to HTTP 409 (#524).
650            //
651            // The whole batch runs under a per-collection chain lock so two
652            // concurrent submitters can't both bind to the same prev_hash —
653            // the loser observes the advanced tip and gets 409 with the new
654            // tip so it can retry.
655            let chain_mode = crate::runtime::blockchain_kind::try_is_chain(&store, &query.table)?;
656            let _chain_lock_arc: Option<Arc<super::RmwRowLock>> = if chain_mode {
657                Some(self.inner.rmw_locks.lock_for(&query.table, "__chain__"))
658            } else {
659                None
660            };
661            let _chain_guard = _chain_lock_arc.as_ref().map(|m| m.lock());
662
663            // Issue #525 — refuse new blocks if the chain has been marked
664            // `integrity = broken` until an admin clears the flag.
665            if chain_mode && self.is_chain_integrity_broken(&query.table)? {
666                return Err(RedDBError::InvalidOperation(format!(
667                    "ChainIntegrityBroken: collection '{}' is locked until \
668                     POST /collections/{}/clear-integrity-flag is called by an admin",
669                    query.table, query.table
670                )));
671            }
672
673            // Pull the tip from the in-memory cache; fall back to a one-time
674            // scan if the cache hasn't seen this collection yet (cold start
675            // after restart). Cache is updated below as rows are sealed.
676            let mut chain_tip_full: Option<crate::runtime::blockchain_kind::ChainTipFull> =
677                if chain_mode {
678                    let mut cache = self.inner.chain_tip_cache.lock();
679                    if let Some(existing) = cache.get(&query.table) {
680                        Some(existing.clone())
681                    } else if let Some(scanned) =
682                        crate::runtime::blockchain_kind::try_chain_tip_full(&store, &query.table)?
683                    {
684                        cache.insert(query.table.clone(), scanned.clone());
685                        Some(scanned)
686                    } else {
687                        None
688                    }
689                } else {
690                    None
691                };
692
693            let mut rows = Vec::with_capacity(effective_rows.len());
694            let mut accepted_row_fields: Vec<Vec<(String, Value)>> = Vec::new();
695            for row_values in &effective_rows {
696                if row_values.len() != query.columns.len() {
697                    return Err(RedDBError::Query(format!(
698                        "INSERT column count ({}) does not match value count ({})",
699                        query.columns.len(),
700                        row_values.len()
701                    )));
702                }
703                let (mut fields, mut metadata) =
704                    split_insert_metadata(self, &secret_columns, &query.columns, row_values)?;
705                if query
706                    .on_conflict
707                    .as_ref()
708                    .is_some_and(|clause| clause.target.is_none())
709                {
710                    fields = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(
711                        self,
712                        &self.db(),
713                        &query.table,
714                    )
715                    .normalize_insert_fields(fields)?;
716                }
717                if let Some(clause) = &query.on_conflict {
718                    let conflict_id = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(
719                        self,
720                        &self.db(),
721                        &query.table,
722                    )
723                    .row_uniqueness_conflict_id(&fields, clause.target.as_deref())?
724                    .filter(|conflict_id| {
725                        store.get(&query.table, *conflict_id).is_some_and(|entity| {
726                            !self.snapshot_manager().is_aborted(entity.xmin)
727                        })
728                    });
729                    if let Some(conflict_id) = conflict_id {
730                        if let Some(conflicting) = store.get(&query.table, conflict_id) {
731                            let conflicting_xid = conflicting.xmin;
732                            if self.snapshot_manager().is_active(conflicting_xid)
733                                && !self.own_transaction_xids().contains(&conflicting_xid)
734                            {
735                                return Err(RedDBError::Query(format!(
736                                    "serialization conflict: ON CONFLICT key in '{}' is owned by active transaction {conflicting_xid}; retry the statement after that transaction resolves",
737                                    query.table
738                                )));
739                            }
740                        }
741                        match &clause.action {
742                            OnConflictAction::DoNothing => continue,
743                            OnConflictAction::DoUpdate { assignments } => {
744                                let assignment_exprs = assignments
745                                    .iter()
746                                    .map(|(column, expr)| {
747                                        Ok((
748                                            column.clone(),
749                                            resolve_excluded_assignment(expr, &fields)?,
750                                        ))
751                                    })
752                                    .collect::<RedDBResult<Vec<_>>>()?;
753                                let literal_assignments = assignment_exprs
754                                    .iter()
755                                    .filter_map(|(column, expr)| {
756                                        fold_expr_to_value(expr.clone())
757                                            .ok()
758                                            .map(|value| (column.clone(), value))
759                                    })
760                                    .collect();
761                                let update = UpdateQuery {
762                                    table: query.table.clone(),
763                                    target: UpdateTarget::Rows,
764                                    compound_assignment_ops: vec![None; assignment_exprs.len()],
765                                    assignment_exprs,
766                                    assignments: literal_assignments,
767                                    where_expr: None,
768                                    filter: Some(Filter::Compare {
769                                        field: FieldRef::column("", "rid"),
770                                        op: CompareOp::Eq,
771                                        // Uniqueness locates a physical version; RQL rid is
772                                        // the stable logical identity across updates.
773                                        value: Value::UnsignedInteger(
774                                            store
775                                                .get(&query.table, conflict_id)
776                                                .map(|entity| entity.logical_id().raw())
777                                                .unwrap_or(conflict_id.raw()),
778                                        ),
779                                    }),
780                                    ttl_ms: None,
781                                    expires_at_ms: None,
782                                    with_metadata: Vec::new(),
783                                    returning: query.returning.clone(),
784                                    claim_limit: None,
785                                    claim_exact: false,
786                                    order_by: Vec::new(),
787                                    limit: None,
788                                    suppress_events: query.suppress_events,
789                                };
790                                let updated = self.execute_update(raw_query, &update)?;
791                                inserted_count += updated.affected_rows;
792                                conflict_returning_records.extend(updated.result.records);
793                                continue;
794                            }
795                        }
796                    }
797                    if matches!(&clause.action, OnConflictAction::DoNothing)
798                        && crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(
799                            self,
800                            &self.db(),
801                            &query.table,
802                        )
803                        .has_row_uniqueness_conflict_with_rows(
804                            &fields,
805                            &accepted_row_fields,
806                            clause.target.as_deref(),
807                        )?
808                    {
809                        continue;
810                    }
811                }
812                if chain_mode {
813                    use crate::runtime::blockchain_kind::{
814                        chain_conflict_error, COL_BLOCK_HEIGHT, COL_HASH, COL_PREV_HASH,
815                        COL_TIMESTAMP, RESERVED_COLUMNS,
816                    };
817                    let supplied_height = fields
818                        .iter()
819                        .find(|(k, _)| k == COL_BLOCK_HEIGHT)
820                        .map(|(_, v)| v.clone());
821                    let supplied_prev = fields
822                        .iter()
823                        .find(|(k, _)| k == COL_PREV_HASH)
824                        .map(|(_, v)| v.clone());
825                    let supplied_ts = fields
826                        .iter()
827                        .find(|(k, _)| k == COL_TIMESTAMP)
828                        .map(|(_, v)| v.clone());
829                    let supplied_hash = fields.iter().any(|(k, _)| k == COL_HASH);
830                    let user_supplied_any = supplied_height.is_some()
831                        || supplied_prev.is_some()
832                        || supplied_ts.is_some()
833                        || supplied_hash;
834
835                    fields.retain(|(k, _)| !RESERVED_COLUMNS.contains(&k.as_str()));
836                    let payload = crate::runtime::blockchain_kind::canonical_payload(&fields);
837
838                    let (tip_prev_hash, tip_next_height) = match &chain_tip_full {
839                        Some(t) => (t.hash, t.height + 1),
840                        None => (crate::storage::blockchain::GENESIS_PREV_HASH, 0u64),
841                    };
842                    let server_now = crate::runtime::blockchain_kind::now_ms();
843
844                    let (use_prev, use_height, use_ts) = if user_supplied_any {
845                        // Caller is participating in the chain protocol —
846                        // every field must be supplied AND match the tip.
847                        if supplied_hash {
848                            return Err(chain_conflict_error(
849                                tip_next_height.saturating_sub(1),
850                                tip_prev_hash,
851                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
852                                server_now,
853                                "hash column is engine-computed and cannot be supplied",
854                            ));
855                        }
856                        let caller_prev = match &supplied_prev {
857                            Some(Value::Blob(b)) if b.len() == 32 => {
858                                let mut a = [0u8; 32];
859                                a.copy_from_slice(b);
860                                a
861                            }
862                            Some(Value::Text(s)) if s.len() == 64 => {
863                                // Accept hex-encoded prev_hash so JSON / SQL
864                                // callers without literal-blob syntax can
865                                // still participate in the chain protocol.
866                                let mut a = [0u8; 32];
867                                let mut ok = true;
868                                for (i, slot) in a.iter_mut().enumerate() {
869                                    let pair = &s.as_ref()[i * 2..i * 2 + 2];
870                                    match u8::from_str_radix(pair, 16) {
871                                        Ok(byte) => *slot = byte,
872                                        Err(_) => {
873                                            ok = false;
874                                            break;
875                                        }
876                                    }
877                                }
878                                if !ok {
879                                    return Err(chain_conflict_error(
880                                        tip_next_height.saturating_sub(1),
881                                        tip_prev_hash,
882                                        chain_tip_full
883                                            .as_ref()
884                                            .map(|t| t.timestamp_ms)
885                                            .unwrap_or(0),
886                                        server_now,
887                                        "prev_hash is not valid hex",
888                                    ));
889                                }
890                                a
891                            }
892                            _ => {
893                                return Err(chain_conflict_error(
894                                    tip_next_height.saturating_sub(1),
895                                    tip_prev_hash,
896                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
897                                    server_now,
898                                    "prev_hash missing or not a 32-byte Blob",
899                                ));
900                            }
901                        };
902                        if caller_prev != tip_prev_hash {
903                            return Err(chain_conflict_error(
904                                tip_next_height.saturating_sub(1),
905                                tip_prev_hash,
906                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
907                                server_now,
908                                "prev_hash does not match current tip",
909                            ));
910                        }
911                        let caller_height = match &supplied_height {
912                            Some(Value::UnsignedInteger(v)) => *v,
913                            Some(Value::Integer(v)) if *v >= 0 => *v as u64,
914                            _ => {
915                                return Err(chain_conflict_error(
916                                    tip_next_height.saturating_sub(1),
917                                    tip_prev_hash,
918                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
919                                    server_now,
920                                    "block_height missing or not an unsigned integer",
921                                ));
922                            }
923                        };
924                        if caller_height != tip_next_height {
925                            return Err(chain_conflict_error(
926                                tip_next_height.saturating_sub(1),
927                                tip_prev_hash,
928                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
929                                server_now,
930                                "block_height does not match tip+1",
931                            ));
932                        }
933                        let caller_ts = match &supplied_ts {
934                            Some(Value::UnsignedInteger(v)) => *v,
935                            Some(Value::Integer(v)) if *v >= 0 => *v as u64,
936                            _ => {
937                                return Err(chain_conflict_error(
938                                    tip_next_height.saturating_sub(1),
939                                    tip_prev_hash,
940                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
941                                    server_now,
942                                    "timestamp missing or not an unsigned integer",
943                                ));
944                            }
945                        };
946                        let drift = (caller_ts as i128) - (server_now as i128);
947                        if drift.abs() > 60_000 {
948                            return Err(chain_conflict_error(
949                                tip_next_height.saturating_sub(1),
950                                tip_prev_hash,
951                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
952                                server_now,
953                                "timestamp outside ±60s of server_time",
954                            ));
955                        }
956                        (caller_prev, caller_height, caller_ts)
957                    } else {
958                        (tip_prev_hash, tip_next_height, server_now)
959                    };
960
961                    let (reserved, new_hash) =
962                        crate::runtime::blockchain_kind::make_block_reserved_fields(
963                            use_prev, use_height, use_ts, &payload,
964                        );
965                    fields.extend(reserved);
966                    chain_tip_full = Some(crate::runtime::blockchain_kind::ChainTipFull {
967                        height: use_height,
968                        hash: new_hash,
969                        timestamp_ms: use_ts,
970                    });
971                }
972                // Issue #522 — signed-writes verification. On collections
973                // created with `SIGNED_BY (...)` the row must carry valid
974                // `signer_pubkey` + `signature` reserved columns. Runs
975                // after chain_mode so canonical payload covers user-supplied
976                // fields only (blockchain reserved columns are filtered by
977                // `canonical_payload`; the two signed-writes reserved
978                // columns are split out before payload computation, then
979                // re-attached for storage). The blockchain + SIGNED_BY
980                // composition is owned by issue #526; we keep #522 to the
981                // non-chain path and let chain_mode collections punt to that
982                // slice rather than half-wire it here.
983                if crate::runtime::signed_writes_kind::try_is_signed(&store, &query.table)? {
984                    let (pk_col, sig_col, residual) =
985                        crate::runtime::signed_writes_kind::split_signature_fields(fields);
986                    let payload = crate::runtime::blockchain_kind::canonical_payload(&residual);
987                    let reg =
988                        crate::runtime::signed_writes_kind::try_registry(&store, &query.table)?;
989                    crate::runtime::signed_writes_kind::verify_row(
990                        &reg,
991                        pk_col.as_ref().map(|c| c.bytes.as_slice()),
992                        sig_col.as_ref().map(|c| c.bytes.as_slice()),
993                        &payload,
994                    )
995                    .map_err(crate::runtime::signed_writes_kind::map_error)?;
996                    fields = residual;
997                    // Round-trip the reserved columns with the value
998                    // type the caller supplied (Text/hex on the SQL path,
999                    // Blob on the binary path). Keeps SELECT and WHERE
1000                    // predicates symmetric with the INSERT shape.
1001                    if let Some(col) = pk_col {
1002                        fields.push((
1003                            crate::storage::signed_writes::RESERVED_SIGNER_PUBKEY_COL.to_string(),
1004                            col.raw_value,
1005                        ));
1006                    }
1007                    if let Some(col) = sig_col {
1008                        fields.push((
1009                            crate::storage::signed_writes::RESERVED_SIGNATURE_COL.to_string(),
1010                            col.raw_value,
1011                        ));
1012                    }
1013                }
1014                merge_with_clauses(
1015                    &mut metadata,
1016                    query.ttl_ms,
1017                    query.expires_at_ms,
1018                    &query.with_metadata,
1019                );
1020                if let Some(snaps) = returning_snapshots.as_mut() {
1021                    snaps.push(fields.clone());
1022                }
1023                accepted_row_fields.push(fields.clone());
1024                rows.push(CreateRowInput {
1025                    collection: query.table.clone(),
1026                    fields,
1027                    metadata,
1028                    node_links: Vec::new(),
1029                    vector_links: Vec::new(),
1030                });
1031            }
1032            let batch = CreateRowsBatchInput {
1033                collection: query.table.clone(),
1034                rows,
1035                suppress_events: query.suppress_events,
1036            };
1037            let outputs = if query
1038                .on_conflict
1039                .as_ref()
1040                .is_some_and(|clause| clause.target.is_none())
1041            {
1042                self.create_rows_batch_prevalidated_with_outputs(batch)?
1043            } else {
1044                self.create_rows_batch(batch)?
1045            };
1046            inserted_count += outputs.len() as u64;
1047            if query.auto_embed.is_some() {
1048                auto_embed_ids.extend(outputs.iter().map(|output| output.id));
1049            }
1050
1051            // Chain mode: commit the new tip to the in-memory cache only after
1052            // the batch persisted successfully. If the batch threw mid-way the
1053            // cache stays on the previous tip and the chain lock releases.
1054            if chain_mode {
1055                if let Some(new_tip) = chain_tip_full.as_ref() {
1056                    self.inner
1057                        .chain_tip_cache
1058                        .lock()
1059                        .insert(query.table.clone(), new_tip.clone());
1060                }
1061            }
1062
1063            // Hypertable chunk routing: if this table was declared via
1064            // CREATE HYPERTABLE, register each row's time-column value
1065            // with the registry so chunk metadata (bounds, row counts,
1066            // TTL eligibility) stays current. This is what lets
1067            // HYPERTABLE_PRUNE_CHUNKS answer real questions + lets the
1068            // retention daemon sweep expired chunks without scanning
1069            // every row.
1070            if let Some(spec) = self.inner.db.hypertables().get(&query.table) {
1071                let time_col = &spec.time_column;
1072                // Find the column's index in the INSERT column list.
1073                if let Some(idx) = query.columns.iter().position(|c| c == time_col) {
1074                    for row in &effective_rows {
1075                        if let Some(Value::Integer(n) | Value::BigInt(n)) = row.get(idx) {
1076                            if *n >= 0 {
1077                                let _ = self.inner.db.hypertables().route(&query.table, *n as u64);
1078                            }
1079                        } else if let Some(Value::UnsignedInteger(n)) = row.get(idx) {
1080                            let _ = self.inner.db.hypertables().route(&query.table, *n);
1081                        }
1082                    }
1083                }
1084            }
1085
1086            if let (Some(items), Some(snaps)) =
1087                (query.returning.as_ref(), returning_snapshots.take())
1088            {
1089                let snaps = row_insert_returning_snapshots(&outputs, snaps);
1090                let mut result = build_returning_result(items, &snaps, Some(&outputs));
1091                result
1092                    .records
1093                    .splice(0..0, conflict_returning_records.drain(..));
1094                returning_result = Some(result);
1095            }
1096        } else {
1097            // Issue #419: surface the inserted entity id on every INSERT path.
1098            // For Node/Edge/Vector/Document/Kv we now keep each CreateEntityOutput
1099            // so a RETURNING clause (and the unconditional inserted_ids list,
1100            // below) can expose the engine-assigned id. TimeSeries (the row
1101            // branch in this else) still returns the not-supported error
1102            // because create_timeseries_point isn't plumbed through this fn.
1103            let mut entity_outputs: Vec<crate::application::entity::CreateEntityOutput> =
1104                Vec::with_capacity(effective_rows.len());
1105            let mut returning_field_snaps: Vec<Vec<(String, Value)>> = if query.returning.is_some()
1106            {
1107                Vec::with_capacity(effective_rows.len())
1108            } else {
1109                Vec::new()
1110            };
1111            if matches!(
1112                query.entity_type,
1113                InsertEntityType::Node | InsertEntityType::Edge
1114            ) {
1115                enum PreparedGraphInsert {
1116                    Node {
1117                        fields: Vec<(String, Value)>,
1118                        input: CreateNodeInput,
1119                    },
1120                    Edge {
1121                        fields: Vec<(String, Value)>,
1122                        input: CreateEdgeInput,
1123                    },
1124                }
1125
1126                let mut prepared = Vec::with_capacity(effective_rows.len());
1127                let mut accepted_graph_fields: Vec<Vec<(String, Value)>> = Vec::new();
1128                for row_values in &effective_rows {
1129                    if row_values.len() != query.columns.len() {
1130                        return Err(RedDBError::Query(format!(
1131                            "INSERT column count ({}) does not match value count ({})",
1132                            query.columns.len(),
1133                            row_values.len()
1134                        )));
1135                    }
1136
1137                    match query.entity_type {
1138                        InsertEntityType::Node => {
1139                            let (node_values, mut metadata) = split_insert_metadata(
1140                                self,
1141                                &secret_columns,
1142                                &query.columns,
1143                                row_values,
1144                            )?;
1145                            if let Some(clause) = &query.on_conflict {
1146                                if let Some(conflict_id) = self
1147                                    .on_conflict_unique_index_conflict_id(
1148                                        &query.table,
1149                                        &node_values,
1150                                        clause.target.as_deref(),
1151                                    )?
1152                                {
1153                                    match &clause.action {
1154                                        OnConflictAction::DoNothing => continue,
1155                                        OnConflictAction::DoUpdate { assignments } => {
1156                                            let updated = self
1157                                                .execute_unique_index_conflict_update(
1158                                                    raw_query,
1159                                                    query,
1160                                                    conflict_id,
1161                                                    UpdateTarget::Nodes,
1162                                                    &node_values,
1163                                                    assignments,
1164                                                )?;
1165                                            inserted_count += updated.affected_rows;
1166                                            conflict_returning_records
1167                                                .extend(updated.result.records);
1168                                            continue;
1169                                        }
1170                                    }
1171                                }
1172                                if matches!(&clause.action, OnConflictAction::DoNothing)
1173                                    && self.has_on_conflict_unique_index_conflict_with_fields(
1174                                        &query.table,
1175                                        &node_values,
1176                                        &accepted_graph_fields,
1177                                        clause.target.as_deref(),
1178                                    )?
1179                                {
1180                                    continue;
1181                                }
1182                            }
1183                            merge_with_clauses(
1184                                &mut metadata,
1185                                query.ttl_ms,
1186                                query.expires_at_ms,
1187                                &query.with_metadata,
1188                            );
1189                            ensure_non_tree_reserved_metadata_entries(&metadata)?;
1190                            apply_collection_default_ttl_metadata(
1191                                self,
1192                                &query.table,
1193                                &mut metadata,
1194                            );
1195                            let (columns, values) = pairwise_columns_values(&node_values);
1196                            let label = find_column_value_string(&columns, &values, "label")?;
1197                            let node_type = columns
1198                                .iter()
1199                                .position(|name| name.eq_ignore_ascii_case("node_type"))
1200                                .map(|index| match &values[index] {
1201                                    Value::Text(value) => Ok(value.to_string()),
1202                                    _ => Err(RedDBError::Query(
1203                                        "node_type must be one text value".into(),
1204                                    )),
1205                                })
1206                                .transpose()?;
1207                            let properties = extract_remaining_properties(
1208                                &columns,
1209                                &values,
1210                                &["label", "node_type"],
1211                            );
1212                            crate::reserved_fields::ensure_no_reserved_public_item_fields(
1213                                properties.iter().map(|(key, _)| key.as_str()),
1214                                &format!("node '{}'", query.table),
1215                            )?;
1216                            accepted_graph_fields.push(node_values.clone());
1217                            prepared.push(PreparedGraphInsert::Node {
1218                                fields: node_values,
1219                                input: CreateNodeInput {
1220                                    collection: query.table.clone(),
1221                                    label,
1222                                    node_type,
1223                                    properties,
1224                                    metadata,
1225                                    embeddings: Vec::new(),
1226                                    table_links: Vec::new(),
1227                                    node_links: Vec::new(),
1228                                },
1229                            });
1230                        }
1231                        InsertEntityType::Edge => {
1232                            let (edge_values, mut metadata) = split_insert_metadata(
1233                                self,
1234                                &secret_columns,
1235                                &query.columns,
1236                                row_values,
1237                            )?;
1238                            if let Some(clause) = &query.on_conflict {
1239                                if let Some(conflict_id) = self
1240                                    .on_conflict_unique_index_conflict_id(
1241                                        &query.table,
1242                                        &edge_values,
1243                                        clause.target.as_deref(),
1244                                    )?
1245                                {
1246                                    match &clause.action {
1247                                        OnConflictAction::DoNothing => continue,
1248                                        OnConflictAction::DoUpdate { assignments } => {
1249                                            let updated = self
1250                                                .execute_unique_index_conflict_update(
1251                                                    raw_query,
1252                                                    query,
1253                                                    conflict_id,
1254                                                    UpdateTarget::Edges,
1255                                                    &edge_values,
1256                                                    assignments,
1257                                                )?;
1258                                            inserted_count += updated.affected_rows;
1259                                            conflict_returning_records
1260                                                .extend(updated.result.records);
1261                                            continue;
1262                                        }
1263                                    }
1264                                }
1265                                if matches!(&clause.action, OnConflictAction::DoNothing)
1266                                    && self.has_on_conflict_unique_index_conflict_with_fields(
1267                                        &query.table,
1268                                        &edge_values,
1269                                        &accepted_graph_fields,
1270                                        clause.target.as_deref(),
1271                                    )?
1272                                {
1273                                    continue;
1274                                }
1275                            }
1276                            merge_with_clauses(
1277                                &mut metadata,
1278                                query.ttl_ms,
1279                                query.expires_at_ms,
1280                                &query.with_metadata,
1281                            );
1282                            ensure_non_tree_reserved_metadata_entries(&metadata)?;
1283                            apply_collection_default_ttl_metadata(
1284                                self,
1285                                &query.table,
1286                                &mut metadata,
1287                            );
1288                            let (columns, values) = pairwise_columns_values(&edge_values);
1289                            let label = find_column_value_string(&columns, &values, "label")?;
1290                            ensure_non_tree_structural_edge_label(&label)?;
1291                            let from_id = resolve_edge_endpoint_any(
1292                                self.inner.db.store().as_ref(),
1293                                &query.table,
1294                                &columns,
1295                                &values,
1296                                &["from_rid", "from"],
1297                            )?;
1298                            let to_id = resolve_edge_endpoint_any(
1299                                self.inner.db.store().as_ref(),
1300                                &query.table,
1301                                &columns,
1302                                &values,
1303                                &["to_rid", "to"],
1304                            )?;
1305                            let weight = find_column_value_f32_opt(&columns, &values, "weight");
1306                            let properties = extract_remaining_properties(
1307                                &columns,
1308                                &values,
1309                                &["label", "from_rid", "to_rid", "from", "to", "weight"],
1310                            );
1311                            crate::reserved_fields::ensure_no_reserved_public_item_fields(
1312                                properties.iter().map(|(key, _)| key.as_str()),
1313                                &format!("edge '{}'", query.table),
1314                            )?;
1315                            accepted_graph_fields.push(edge_values.clone());
1316                            prepared.push(PreparedGraphInsert::Edge {
1317                                fields: edge_values,
1318                                input: CreateEdgeInput {
1319                                    collection: query.table.clone(),
1320                                    label,
1321                                    from: EntityId::new(from_id),
1322                                    to: EntityId::new(to_id),
1323                                    weight,
1324                                    properties,
1325                                    metadata,
1326                                },
1327                            });
1328                        }
1329                        _ => unreachable!("prepared graph insert only handles NODE and EDGE"),
1330                    }
1331                }
1332
1333                ensure_graph_insert_contract(self, &query.table)?;
1334                let mut batch = self.inner.db.batch();
1335                let mut graph_index_fields: Vec<Vec<(String, Value)>> =
1336                    Vec::with_capacity(prepared.len());
1337                for item in prepared {
1338                    match item {
1339                        PreparedGraphInsert::Node { fields, input } => {
1340                            if query.returning.is_some() {
1341                                returning_field_snaps.push(fields.clone());
1342                            }
1343                            graph_index_fields.push(fields);
1344                            let node_type = input.node_type.unwrap_or_else(|| input.label.clone());
1345                            batch = batch.add_node_with_type(
1346                                input.collection,
1347                                input.label,
1348                                node_type,
1349                                input.properties.into_iter().collect(),
1350                                input.metadata.into_iter().collect(),
1351                            );
1352                        }
1353                        PreparedGraphInsert::Edge { fields, input } => {
1354                            if query.returning.is_some() {
1355                                returning_field_snaps.push(fields.clone());
1356                            }
1357                            graph_index_fields.push(fields);
1358                            batch = batch.add_edge(
1359                                input.collection,
1360                                input.label,
1361                                input.from,
1362                                input.to,
1363                                input.weight.unwrap_or(1.0),
1364                                input.properties.into_iter().collect(),
1365                                input.metadata.into_iter().collect(),
1366                            );
1367                        }
1368                    }
1369                }
1370                let batch_result = batch
1371                    .with_graph_xmin(self.current_xid().or_else(|| self.graph_insert_xid()))
1372                    .with_graph_branch(self.vcs_writer_epoch(&query.table)?)
1373                    .execute()
1374                    .map_err(|err| RedDBError::Internal(format!("{err:?}")))?;
1375                let (ids, entity_kind) = match query.entity_type {
1376                    InsertEntityType::Node => (batch_result.nodes, "graph_node"),
1377                    InsertEntityType::Edge => (batch_result.edges, "graph_edge"),
1378                    _ => unreachable!("prepared graph insert only handles NODE and EDGE"),
1379                };
1380                #[cfg(test)]
1381                self.index_store_ref().mutation_test_hook(
1382                    &query.table,
1383                    super::index_store::MutationTestPhase::StoragePublished,
1384                );
1385                if !graph_index_fields.is_empty() {
1386                    let index_rows: Vec<_> = ids
1387                        .iter()
1388                        .zip(graph_index_fields)
1389                        .map(|(id, fields)| (*id, fields))
1390                        .collect();
1391                    self.inner
1392                        .index_store
1393                        .index_entity_insert_batch(&query.table, &index_rows)
1394                        .map_err(RedDBError::Internal)?;
1395                }
1396                if query.returning.is_some() {
1397                    returning_field_snaps = graph_insert_returning_snapshots(
1398                        self.inner.db.store().as_ref(),
1399                        &query.table,
1400                        &ids,
1401                    );
1402                }
1403                self.cdc_emit_insert_batch_no_cache_invalidate(&query.table, &ids, entity_kind)?;
1404                let store = self.inner.db.store();
1405                entity_outputs.extend(ids.iter().map(|id| {
1406                    crate::application::entity::CreateEntityOutput {
1407                        id: *id,
1408                        entity: store.get(&query.table, *id),
1409                    }
1410                }));
1411                inserted_count += ids.len() as u64;
1412            } else {
1413                for row_values in &effective_rows {
1414                    if row_values.len() != query.columns.len() {
1415                        return Err(RedDBError::Query(format!(
1416                            "INSERT column count ({}) does not match value count ({})",
1417                            query.columns.len(),
1418                            row_values.len()
1419                        )));
1420                    }
1421
1422                    match query.entity_type {
1423                        InsertEntityType::Row => {
1424                            if query.returning.is_some() {
1425                                return Err(RedDBError::Query(
1426                                "RETURNING is not yet supported for this INSERT path (TimeSeries)"
1427                                    .to_string(),
1428                            ));
1429                            }
1430                            let (fields, mut metadata) = split_insert_metadata(
1431                                self,
1432                                &secret_columns,
1433                                &query.columns,
1434                                row_values,
1435                            )?;
1436                            merge_with_clauses(
1437                                &mut metadata,
1438                                query.ttl_ms,
1439                                query.expires_at_ms,
1440                                &query.with_metadata,
1441                            );
1442                            self.insert_timeseries_point(&query.table, fields, metadata)?;
1443                        }
1444                        InsertEntityType::Node | InsertEntityType::Edge => {
1445                            unreachable!("NODE and EDGE are handled by the prepared graph path")
1446                        }
1447                        InsertEntityType::Vector => {
1448                            let (vector_values, mut metadata) = split_insert_metadata(
1449                                self,
1450                                &secret_columns,
1451                                &query.columns,
1452                                row_values,
1453                            )?;
1454                            merge_with_clauses(
1455                                &mut metadata,
1456                                query.ttl_ms,
1457                                query.expires_at_ms,
1458                                &query.with_metadata,
1459                            );
1460                            let (columns, values) = pairwise_columns_values(&vector_values);
1461                            let dense = find_column_value_vec_f32_any(
1462                                &columns,
1463                                &values,
1464                                &["dense", "embedding"],
1465                            )?;
1466                            merge_vector_metadata_column(&mut metadata, &columns, &values)?;
1467                            let content =
1468                                find_column_value_opt_string(&columns, &values, "content");
1469                            if query.returning.is_some() {
1470                                returning_field_snaps.push(vector_values.clone());
1471                            }
1472                            let input = CreateVectorInput {
1473                                collection: query.table.clone(),
1474                                dense,
1475                                content,
1476                                metadata,
1477                                link_row: None,
1478                                link_node: None,
1479                            };
1480                            entity_outputs.push(self.create_vector(input)?);
1481                        }
1482                        InsertEntityType::Document => {
1483                            let (document_values, mut metadata) = split_insert_metadata(
1484                                self,
1485                                &secret_columns,
1486                                &query.columns,
1487                                row_values,
1488                            )?;
1489                            let (columns, values) = pairwise_columns_values(&document_values);
1490                            let body = find_document_body_json(&columns, &values)?;
1491                            let conflict_fields =
1492                                document_on_conflict_fields(&document_values, &body)?;
1493                            if let Some(clause) = &query.on_conflict {
1494                                if let Some(conflict_id) = self
1495                                    .on_conflict_unique_index_conflict_id(
1496                                        &query.table,
1497                                        &conflict_fields,
1498                                        clause.target.as_deref(),
1499                                    )?
1500                                {
1501                                    match &clause.action {
1502                                        OnConflictAction::DoNothing => continue,
1503                                        OnConflictAction::DoUpdate { assignments } => {
1504                                            let updated = self
1505                                                .execute_unique_index_conflict_update(
1506                                                    raw_query,
1507                                                    query,
1508                                                    conflict_id,
1509                                                    UpdateTarget::Documents,
1510                                                    &conflict_fields,
1511                                                    assignments,
1512                                                )?;
1513                                            inserted_count += updated.affected_rows;
1514                                            conflict_returning_records
1515                                                .extend(updated.result.records);
1516                                            continue;
1517                                        }
1518                                    }
1519                                }
1520                            }
1521                            merge_with_clauses(
1522                                &mut metadata,
1523                                query.ttl_ms,
1524                                query.expires_at_ms,
1525                                &query.with_metadata,
1526                            );
1527                            let input = CreateDocumentInput {
1528                                collection: query.table.clone(),
1529                                body,
1530                                metadata,
1531                                node_links: Vec::new(),
1532                                vector_links: Vec::new(),
1533                            };
1534                            let output = self.create_document(input)?;
1535                            if query.returning.is_some() {
1536                                let fields = output
1537                                    .entity
1538                                    .as_ref()
1539                                    .map(entity_row_fields_snapshot)
1540                                    .filter(|fields| !fields.is_empty())
1541                                    .unwrap_or(document_values);
1542                                returning_field_snaps.push(fields);
1543                            }
1544                            entity_outputs.push(output);
1545                        }
1546                        InsertEntityType::Kv => {
1547                            let (kv_values, mut metadata) = split_insert_metadata(
1548                                self,
1549                                &secret_columns,
1550                                &query.columns,
1551                                row_values,
1552                            )?;
1553                            merge_with_clauses(
1554                                &mut metadata,
1555                                query.ttl_ms,
1556                                query.expires_at_ms,
1557                                &query.with_metadata,
1558                            );
1559                            let (columns, values) = pairwise_columns_values(&kv_values);
1560                            let key = find_column_value_string(&columns, &values, "key")?;
1561                            let value = find_column_value(&columns, &values, "value")?;
1562                            if query.returning.is_some() {
1563                                returning_field_snaps.push(kv_values.clone());
1564                            }
1565                            let input = CreateKvInput {
1566                                collection: query.table.clone(),
1567                                key,
1568                                value,
1569                                metadata,
1570                            };
1571                            entity_outputs.push(self.create_kv(input)?);
1572                        }
1573                    }
1574
1575                    inserted_count += 1;
1576                }
1577            }
1578
1579            if query.auto_embed.is_some() {
1580                auto_embed_ids.extend(entity_outputs.iter().map(|output| output.id));
1581            }
1582
1583            if let Some(items) = query.returning.as_ref() {
1584                let mut result =
1585                    build_returning_result(items, &returning_field_snaps, Some(&entity_outputs));
1586                result
1587                    .records
1588                    .splice(0..0, conflict_returning_records.drain(..));
1589                returning_result = Some(result);
1590            }
1591        }
1592
1593        // Auto-embed pipeline: batch-embed fields across all inserted rows via AiBatchClient.
1594        if let Some((provider, model, connection, fields)) = resolved_auto_embed.as_ref() {
1595            let store = self.inner.db.store();
1596            let is_local_provider = matches!(provider, crate::ai::AiProvider::Local);
1597            let (api_key, api_base) = connection
1598                .as_ref()
1599                .map(|connection| (connection.api_key.as_str(), connection.api_base.as_str()))
1600                .unwrap_or(("", ""));
1601
1602            // Read only this INSERT's returned IDs. A pre-write statement
1603            // snapshot correctly excludes newly committed rows; a fresh/global
1604            // scan could instead pick another writer's rows or conflict skips.
1605            let recent: Vec<_> = auto_embed_ids
1606                .iter()
1607                .filter_map(|id| store.get(&query.table, *id))
1608                .collect();
1609
1610            // Collector phase: (entity_index, combined_text) for rows that have non-empty fields.
1611            let entity_combos: Vec<(usize, String)> = recent
1612                .iter()
1613                .enumerate()
1614                .filter_map(|(i, entity)| {
1615                    if let EntityData::Row(ref row) = entity.data {
1616                        let texts: Vec<String> = fields
1617                            .iter()
1618                            .filter_map(|field| match row.get_field(field) {
1619                                Some(Value::Text(t)) if !t.is_empty() => Some(t.to_string()),
1620                                _ => None,
1621                            })
1622                            .collect();
1623                        if !texts.is_empty() {
1624                            return Some((i, texts.join(" ")));
1625                        }
1626                    }
1627                    None
1628                })
1629                .collect();
1630
1631            if !entity_combos.is_empty() {
1632                // Batch phase: single provider round-trip for all rows.
1633                let batch_texts: Vec<String> =
1634                    entity_combos.iter().map(|(_, t)| t.clone()).collect();
1635
1636                // Issue #682 — when the provider is `local`, bypass
1637                // AiBatchClient (which is HTTP-only) and dispatch
1638                // directly through the in-process local embedding
1639                // backend. All texts go in one call, mirroring the
1640                // single-round-trip shape of the remote path. The
1641                // local backend does not perform intra-batch dedup —
1642                // each input position gets its own row in the output
1643                // — which keeps the per-row "create_vector" loop
1644                // below correct without additional fan-out logic.
1645                let embeddings = if is_local_provider {
1646                    let response = crate::runtime::ai::local_embedding::embed_local_with_db(
1647                        &self.inner.db,
1648                        model,
1649                        batch_texts,
1650                    )?;
1651                    response.embeddings
1652                } else {
1653                    let batch_client =
1654                        crate::runtime::ai::batch_client::AiBatchClient::from_runtime(self);
1655
1656                    match tokio::runtime::Handle::try_current() {
1657                        Ok(handle) => tokio::task::block_in_place(|| {
1658                            handle.block_on(batch_client.embed_batch_at(
1659                                provider,
1660                                model,
1661                                api_key,
1662                                api_base,
1663                                batch_texts,
1664                            ))
1665                        }),
1666                        Err(_) => {
1667                            return Err(RedDBError::Query(
1668                                "AUTO EMBED requires a Tokio runtime context".to_string(),
1669                            ));
1670                        }
1671                    }
1672                    .map_err(|e| RedDBError::Query(e.to_string()))?
1673                };
1674
1675                // Distribute phase: persist one vector per non-empty embedding.
1676                for ((_, combined), dense) in entity_combos.iter().zip(embeddings) {
1677                    if dense.is_empty() {
1678                        continue;
1679                    }
1680                    self.create_vector(CreateVectorInput {
1681                        collection: query.table.clone(),
1682                        dense,
1683                        content: Some(combined.clone()),
1684                        metadata: Vec::new(),
1685                        link_row: None,
1686                        link_node: None,
1687                    })?;
1688                }
1689            }
1690        }
1691
1692        if inserted_count > 0 {
1693            self.note_table_write(&query.table);
1694        }
1695
1696        let mut result = RuntimeQueryResult::dml_result(
1697            raw_query.to_string(),
1698            inserted_count,
1699            "insert",
1700            "runtime-dml",
1701        );
1702        if let Some(returning) = returning_result {
1703            result.result = returning;
1704        }
1705        Ok(result)
1706    }
1707
1708    fn check_insert_column_policy(&self, query: &InsertQuery) -> RedDBResult<()> {
1709        let Some(auth_store) = self.inner.auth_store.read().clone() else {
1710            return Ok(());
1711        };
1712        if !auth_store.iam_authorization_enabled() {
1713            return Ok(());
1714        }
1715        let Some((username, role)) = crate::runtime::impl_core::current_auth_identity() else {
1716            return Ok(());
1717        };
1718
1719        let tenant = crate::runtime::impl_core::current_tenant();
1720        let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
1721        let request = crate::auth::ColumnAccessRequest {
1722            action: "insert".to_string(),
1723            schema: None,
1724            table: query.table.clone(),
1725            columns: query.columns.clone(),
1726        };
1727        let ctx = crate::auth::policies::EvalContext {
1728            principal_tenant: tenant.clone(),
1729            current_tenant: tenant,
1730            peer_ip: None,
1731            mfa_present: false,
1732            now_ms: crate::auth::now_ms(),
1733            principal_is_admin_role: role == crate::auth::Role::Admin,
1734            principal_is_platform_scoped: principal.tenant.is_none(),
1735        };
1736
1737        let outcome = auth_store.check_column_projection_authz(&principal, &request, &ctx);
1738        let table_allowed = matches!(
1739            outcome.table_decision,
1740            crate::auth::policies::Decision::Allow { .. }
1741                | crate::auth::policies::Decision::AdminBypass
1742        );
1743        if !table_allowed {
1744            return Err(RedDBError::Query(format!(
1745                "principal=`{username}` action=`insert` resource=`{}:{}` denied by IAM policy",
1746                outcome.table_resource.kind, outcome.table_resource.name
1747            )));
1748        }
1749        if let Some(denied) = outcome.first_denied_column() {
1750            return Err(RedDBError::Query(format!(
1751                "principal=`{username}` action=`insert` resource=`{}:{}` denied by IAM policy",
1752                denied.resource.kind, denied.resource.name
1753            )));
1754        }
1755
1756        Ok(())
1757    }
1758
1759    pub(crate) fn insert_timeseries_point(
1760        &self,
1761        collection: &str,
1762        fields: Vec<(String, Value)>,
1763        metadata: Vec<(String, MetadataValue)>,
1764    ) -> RedDBResult<EntityId> {
1765        if self.vcs_is_versioned(collection)? {
1766            let store = self.db().store();
1767            let _publication = store.vault_publication_lock.lock();
1768            self.with_versioned_graph_insert(|| {
1769                self.insert_timeseries_point_inner(collection, fields, metadata)
1770            })
1771        } else {
1772            self.insert_timeseries_point_inner(collection, fields, metadata)
1773        }
1774    }
1775
1776    fn insert_timeseries_point_inner(
1777        &self,
1778        collection: &str,
1779        mut fields: Vec<(String, Value)>,
1780        mut metadata: Vec<(String, MetadataValue)>,
1781    ) -> RedDBResult<EntityId> {
1782        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, collection)?;
1783        crate::runtime::mutation::enforce_tenant_fields(self, collection, &mut fields)?;
1784        apply_collection_default_ttl_metadata(self, collection, &mut metadata);
1785
1786        let (columns, values) = pairwise_columns_values(&fields);
1787        validate_timeseries_insert_columns(&columns)?;
1788
1789        // Issue #577 — AnalyticsSchemaRegistry hook. If the row carries
1790        // an `event_name` whose schema is registered, validate the
1791        // `payload` JSON against it BEFORE any write side-effect. On
1792        // failure we return a typed error and the row is not
1793        // persisted. When no schema is registered for the event name
1794        // (or no `event_name` column is supplied at all) we fall
1795        // through to the normal write path for back-compat with
1796        // existing timeseries rows.
1797        let event_name_opt = find_column_value_opt_string(&columns, &values, "event_name");
1798        let payload_opt = find_column_value_opt_string(&columns, &values, "payload");
1799        if let Some(event_name) = event_name_opt.as_deref() {
1800            let store_for_schema = self.inner.db.store();
1801            if super::analytics_schema_registry::latest(store_for_schema.as_ref(), event_name)
1802                .is_some()
1803            {
1804                let payload_json = payload_opt.as_deref().unwrap_or("{}");
1805                super::analytics_schema_registry::validate(
1806                    store_for_schema.as_ref(),
1807                    event_name,
1808                    payload_json,
1809                )
1810                .map_err(super::analytics_schema_registry::validation_error_to_reddb)?;
1811            }
1812        }
1813
1814        // `metric` is required by the existing timeseries write path;
1815        // when an analytics-style row supplies `event_name` but not
1816        // `metric`, fall back to the event name so the storage path
1817        // still has a non-empty metric tag.
1818        let metric = match find_column_value_opt_string(&columns, &values, "metric") {
1819            Some(m) => m,
1820            None => event_name_opt.clone().ok_or_else(|| {
1821                RedDBError::Query(
1822                    "timeseries INSERT requires either `metric` or `event_name`".to_string(),
1823                )
1824            })?,
1825        };
1826        // `value` is optional for analytics-event rows (which are
1827        // semantically counts of 1); default to 1.0 when missing so
1828        // analytics inserts don't have to fabricate a metric value.
1829        let value = match find_column_value_opt_string(&columns, &values, "value") {
1830            Some(s) => s.parse::<f64>().unwrap_or(1.0),
1831            None => columns
1832                .iter()
1833                .position(|c| c.eq_ignore_ascii_case("value"))
1834                .and_then(|i| match &values[i] {
1835                    Value::Float(f) => Some(*f),
1836                    Value::Integer(n) | Value::BigInt(n) => Some(*n as f64),
1837                    Value::UnsignedInteger(n) => Some(*n as f64),
1838                    _ => None,
1839                })
1840                .unwrap_or(1.0),
1841        };
1842        let timestamp_ns =
1843            find_timeseries_timestamp_ns(&columns, &values)?.unwrap_or_else(current_unix_ns);
1844        let mut tags = find_timeseries_tags(&columns, &values)?;
1845        if let Some(ref name) = event_name_opt {
1846            tags.entry("event_name".to_string())
1847                .or_insert_with(|| name.clone());
1848        }
1849        if let Some(ref payload) = payload_opt {
1850            tags.entry("payload".to_string())
1851                .or_insert_with(|| payload.clone());
1852        }
1853        let fields = extract_remaining_properties(
1854            &columns,
1855            &values,
1856            &[
1857                "metric",
1858                "value",
1859                "tags",
1860                "timestamp",
1861                "timestamp_ns",
1862                "time",
1863                "event_name",
1864                "payload",
1865            ],
1866        );
1867        let index_fields = fields.clone();
1868        let _segment_reservation = self.admit_non_evictable_growth(
1869            crate::storage::memory_pools::MemoryPool::SegmentArena,
1870            &format!("insert into {collection}"),
1871            crate::runtime::memory_admission::estimate_timeseries_point_growth(
1872                &metric, &tags, &fields,
1873            ),
1874        )?;
1875        let indexed_columns = self
1876            .inner
1877            .index_store
1878            .list_indices(collection)
1879            .into_iter()
1880            .flat_map(|index| index.columns)
1881            .collect::<Vec<_>>();
1882        let _index_reservation = if indexed_columns.is_empty() {
1883            None
1884        } else {
1885            Some(self.admit_non_evictable_growth(
1886                crate::storage::memory_pools::MemoryPool::IndexMemory,
1887                &format!("index insert into {collection}"),
1888                crate::runtime::memory_admission::estimate_index_growth(
1889                    std::slice::from_ref(&index_fields),
1890                    &indexed_columns,
1891                ),
1892            )?)
1893        };
1894        let series_id = super::impl_timeseries::intern_timeseries_series(
1895            self.inner.db.store().as_ref(),
1896            collection,
1897            &metric,
1898            &tags,
1899        )?;
1900
1901        let mut entity = UnifiedEntity::new(
1902            EntityId::new(0),
1903            EntityKind::TimeSeriesPoint(Box::new(crate::storage::TimeSeriesPointKind {
1904                series: collection.to_string(),
1905                metric: metric.clone(),
1906            })),
1907            EntityData::TimeSeries(crate::storage::TimeSeriesData {
1908                metric,
1909                series_id: Some(series_id),
1910                timestamp_ns,
1911                value,
1912                tags: HashMap::new(),
1913                fields: fields.into_iter().collect(),
1914            }),
1915        );
1916        if !crate::runtime::rls_injection::entity_passes_rls_action(
1917            self,
1918            collection,
1919            reddb_rql::ast::PolicyAction::Insert,
1920            &entity,
1921        ) {
1922            return Err(RedDBError::Query(format!(
1923                "insert into collection '{collection}' denied by row-level security"
1924            )));
1925        }
1926        // MVCC #30: stamp xmin with the active tx xid (inside a tx)
1927        // or an autocommit xid (allocated and committed up-front so
1928        // future snapshots see the row as soon as it lands).
1929        let writer_xid = match self.current_xid().or_else(|| self.graph_insert_xid()) {
1930            Some(xid) => xid,
1931            None => {
1932                let mgr = self.snapshot_manager();
1933                let xid = mgr.begin();
1934                mgr.commit(xid);
1935                xid
1936            }
1937        };
1938        entity.set_xmin(writer_xid);
1939        self.stamp_vcs_creation(collection, &mut entity)?;
1940
1941        let store = self.inner.db.store();
1942        let id = store
1943            .insert_auto(collection, entity)
1944            .map_err(|err| RedDBError::Internal(err.to_string()))?;
1945        self.inner
1946            .index_store
1947            .index_entity_insert(collection, id, &index_fields)
1948            .map_err(RedDBError::Internal)?;
1949
1950        if !metadata.is_empty() {
1951            store.set_metadata(
1952                collection,
1953                id,
1954                Metadata::with_fields(metadata.into_iter().collect()),
1955            )?;
1956        }
1957
1958        let _ = self.inner.db.hypertables().route(collection, timestamp_ns);
1959
1960        self.cdc_emit(
1961            crate::replication::cdc::ChangeOperation::Insert,
1962            collection,
1963            id.raw(),
1964            "timeseries",
1965        )?;
1966
1967        Ok(id)
1968    }
1969
1970    /// Execute UPDATE table SET col=val, ... WHERE filter
1971    ///
1972    /// Scans the target collection, evaluates the WHERE filter against each
1973    /// record, and patches every matching entity.
1974    pub fn execute_update(
1975        &self,
1976        raw_query: &str,
1977        query: &UpdateQuery,
1978    ) -> RedDBResult<RuntimeQueryResult> {
1979        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
1980        let branch_store = self.db().store();
1981        let _branch_publication = (self.vcs_is_versioned(&query.table)?
1982            || self.has_graph_contract(&query.table))
1983        .then(|| branch_store.vault_publication_lock.lock());
1984        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
1985            self,
1986            &query.table,
1987        );
1988        // Issue #523 — blockchain collections are immutable. Reject before
1989        // RLS / RETURNING work so the operator sees a clean 409-mapped
1990        // error instead of a partially-applied mutation surface.
1991        if crate::runtime::blockchain_kind::try_is_chain(
1992            self.inner.db.store().as_ref(),
1993            &query.table,
1994        )? {
1995            return Err(RedDBError::InvalidOperation(format!(
1996                "BlockchainCollectionImmutable: UPDATE not allowed on '{}'",
1997                query.table
1998            )));
1999        }
2000        // Queue-shaped CLAIM (ADR 0020, #1609): a CLAIM on a queue collection
2001        // is a QueueLifecycle delivery acquisition, not a raw row UPDATE.
2002        // Route it through the lifecycle seam before the table-shaped
2003        // contract / RLS gates below (which would reject an UPDATE against a
2004        // queue's declared model) so QueueLifecycle stays the sole authority
2005        // for delivery state.
2006        if query.claim_limit.is_some() && self.is_queue_collection(&query.table) {
2007            return self.execute_queue_shaped_claim(raw_query, query);
2008        }
2009        // ADR 0067 (#1711): the DOCUMENTS / ROWS / KV UPDATE markers were
2010        // removed. Resolve the model of an unmarked UPDATE from the catalog so
2011        // a document collection routes to document semantics and a KV
2012        // collection keeps its key-immutability guard, and gate dotted SET
2013        // targets that only a document body can satisfy. Runs before the
2014        // contract / RLS gates so every downstream path — the inner scan,
2015        // RETURNING — observes the resolved target.
2016        let inferred_owned;
2017        let query = match self.resolve_unmarked_update_target(query)? {
2018            Some(rewritten) => {
2019                inferred_owned = rewritten;
2020                &inferred_owned
2021            }
2022            None => query,
2023        };
2024        // CollectionContract gate (#50): runs the APPEND ONLY guard
2025        // (and any future contract bits) before RLS / RETURNING work
2026        // so the operator's immutability declaration is honoured
2027        // uniformly and the error message points at the DDL rather
2028        // than at a downstream symptom.
2029        crate::runtime::collection_contract::CollectionContractGate::check(
2030            self,
2031            &query.table,
2032            crate::runtime::collection_contract::MutationKind::Update,
2033        )?;
2034        ensure_update_target_contract(self, &query.table, query.target)?;
2035        ensure_kv_key_update_target_allowed(query)?;
2036        ensure_graph_identity_update_target_allowed(query)?;
2037
2038        // Apply RLS augmentation first so every downstream path — plain
2039        // UPDATE, UPDATE...RETURNING, the inner scan — observes the
2040        // same policy-filtered target set. This prevents RETURNING
2041        // from ever exposing rows the UPDATE policy would have
2042        // denied.
2043        let rls_gated = crate::runtime::impl_core::rls_is_enabled(self, &query.table);
2044        let augmented_query: UpdateQuery;
2045        let effective_query: &UpdateQuery = if rls_gated {
2046            let update_filter = crate::runtime::impl_core::rls_policy_filter(
2047                self,
2048                &query.table,
2049                reddb_rql::ast::PolicyAction::Update,
2050            );
2051            let Some(mut policy) = update_filter else {
2052                // No admitting policy: zero rows affected, empty
2053                // RETURNING (never leak rows the caller can't touch).
2054                let mut response = RuntimeQueryResult::dml_result(
2055                    raw_query.to_string(),
2056                    0,
2057                    "update",
2058                    "runtime-dml-rls",
2059                );
2060                if let Some(items) = query.returning.clone() {
2061                    response.result = build_returning_result(&items, &[], None);
2062                }
2063                return Ok(response);
2064            };
2065            if query.claim_limit.is_some() {
2066                let read_filter = crate::runtime::impl_core::rls_policy_filter(
2067                    self,
2068                    &query.table,
2069                    reddb_rql::ast::PolicyAction::Select,
2070                );
2071                let Some(read_policy) = read_filter else {
2072                    let mut response = RuntimeQueryResult::dml_result(
2073                        raw_query.to_string(),
2074                        0,
2075                        "update",
2076                        "runtime-dml-rls",
2077                    );
2078                    if let Some(items) = query.returning.clone() {
2079                        response.result = build_returning_result(&items, &[], None);
2080                    }
2081                    return Ok(response);
2082                };
2083                policy = reddb_rql::ast::Filter::And(Box::new(read_policy), Box::new(policy));
2084            }
2085            let mut augmented = query.clone();
2086            augmented.filter = Some(match augmented.filter.take() {
2087                Some(existing) => reddb_rql::ast::Filter::And(Box::new(existing), Box::new(policy)),
2088                None => policy,
2089            });
2090            augmented_query = augmented;
2091            &augmented_query
2092        } else {
2093            query
2094        };
2095
2096        if !rls_gated && _branch_publication.is_none() {
2097            if let Some(lock) = &constraint_lock {
2098                if let Some(result) =
2099                    self.try_execute_point_update(raw_query, effective_query, lock)?
2100                {
2101                    return Ok(result);
2102                }
2103            }
2104        }
2105        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2106
2107        // RETURNING wraps the inner executor and uses the touched-id
2108        // list the inner reports so the post-image reflects exactly
2109        // the rows the UPDATE actually mutated (not whatever a
2110        // separate SELECT might have observed).
2111        if let Some(items) = effective_query.returning.clone() {
2112            let mut inner_query = effective_query.clone();
2113            inner_query.returning = None;
2114            let (mut response, touched_ids) =
2115                self.execute_update_inner_tracked(raw_query, &inner_query)?;
2116
2117            let mut snapshots = if matches!(
2118                effective_query.target,
2119                UpdateTarget::Nodes | UpdateTarget::Edges
2120            ) {
2121                graph_update_returning_snapshots(self, &effective_query.table, &touched_ids)
2122            } else {
2123                super::dml_target_scan::DmlTargetScan::new(self, &effective_query.table, None, None)
2124                    .row_snapshots(&touched_ids)?
2125            };
2126            if matches!(effective_query.target, UpdateTarget::Kv) {
2127                restore_kv_returning_keys(
2128                    self,
2129                    &effective_query.table,
2130                    &touched_ids,
2131                    &mut snapshots,
2132                );
2133            }
2134
2135            response.result = build_returning_result(&items, &snapshots, None);
2136            response.engine = "runtime-dml-returning";
2137            return Ok(response);
2138        }
2139
2140        self.execute_update_inner(raw_query, effective_query)
2141    }
2142
2143    fn try_execute_point_update(
2144        &self,
2145        raw_query: &str,
2146        query: &UpdateQuery,
2147        constraint_lock: &crate::application::collection_contract_enforcer::RowConstraintLock,
2148    ) -> RedDBResult<Option<RuntimeQueryResult>> {
2149        if query.target != UpdateTarget::Rows
2150            || query.returning.is_some()
2151            || query.claim_limit.is_some()
2152            || query.limit.is_some()
2153            || !query.order_by.is_empty()
2154            || self.current_xid().is_some()
2155            || self.update_may_emit_events(query)
2156            || super::function_budget::stored_function_active()
2157            || !self.db().store().can_group_same_table_updates()
2158            || !query
2159                .assignment_exprs
2160                .iter()
2161                .all(|(_, expr)| point_update_expr(expr))
2162        {
2163            return Ok(None);
2164        }
2165        let Some(filter) = effective_update_filter(query) else {
2166            return Ok(None);
2167        };
2168        let Filter::Compare {
2169            field,
2170            op: CompareOp::Eq,
2171            value: Value::Integer(_) | Value::UnsignedInteger(_),
2172        } = &filter
2173        else {
2174            return Ok(None);
2175        };
2176        let Some(_point_guard) = constraint_lock.lock_for_point_update() else {
2177            return Ok(None);
2178        };
2179        let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(&query.table);
2180        let topology_lock = self
2181            .index_store_ref()
2182            .collection_topology_lock(&query.table);
2183        let topology_guard = topology_lock.read();
2184        if !self
2185            .db()
2186            .store()
2187            .get_collection(&query.table)
2188            .is_some_and(|manager| constraint_lock.protects(&manager.row_update_gate()))
2189        {
2190            return Ok(None);
2191        }
2192        let Some(contract) = self.db().collection_contract_arc(&query.table) else {
2193            return Ok(None);
2194        };
2195        if contract.declared_model != crate::catalog::CollectionModel::Table
2196            || !contract.table_def.as_ref().is_some_and(|table| {
2197                let [key] = table.primary_key.as_slice() else {
2198                    return false;
2199                };
2200                field_ref_matches_update_column(field, &query.table, key)
2201                    && table.columns.iter().any(|column| {
2202                        column.name == *key
2203                            && matches!(
2204                                column.data_type,
2205                                reddb_types::DataType::Integer
2206                                    | reddb_types::DataType::UnsignedInteger
2207                            )
2208                    })
2209            })
2210            || self.vcs_is_versioned(&query.table)?
2211        {
2212            return Ok(None);
2213        }
2214        let plan = self.compile_update_plan(query)?;
2215        if plan.row_touches_unique_columns
2216            || plan.touches_unique_index
2217            || plan
2218                .row_contract_plan
2219                .as_ref()
2220                .is_some_and(|plan| plan.has_expressions || plan.timestamps_enabled)
2221        {
2222            return Ok(None);
2223        }
2224        let manager = self.snapshot_manager();
2225        let _snapshot =
2226            super::impl_core::CurrentSnapshotGuard::install(super::impl_core::SnapshotContext {
2227                snapshot: manager.fresh_read_snapshot(),
2228                manager,
2229                branch: None,
2230                own_xids: Default::default(),
2231                requires_index_fallback: false,
2232                hidden_writers_only: false,
2233                serializable_reader: None,
2234            });
2235        let target = super::dml_target_scan::DmlTargetScan::with_update_target(
2236            self,
2237            &query.table,
2238            Some(&filter),
2239            None,
2240            UpdateTarget::Rows,
2241        );
2242        let Some(id) = target.indexed_point_update_target()? else {
2243            return Ok(None);
2244        };
2245        let ids = self.filter_claim_locked_target_ids(&query.table, vec![id])?;
2246        let (result, _) = self.execute_update_inner_tracked_locked(
2247            raw_query,
2248            query,
2249            &plan,
2250            &ids,
2251            Some(&filter),
2252            topology_guard,
2253        )?;
2254        Ok(Some(result))
2255    }
2256
2257    /// Back-compat shim: the older entry point ignored touched ids.
2258    fn execute_update_inner(
2259        &self,
2260        raw_query: &str,
2261        query: &UpdateQuery,
2262    ) -> RedDBResult<RuntimeQueryResult> {
2263        self.execute_update_inner_tracked(raw_query, query)
2264            .map(|(res, _)| res)
2265    }
2266
2267    /// Enforce the concurrent-claim ORDER BY index-gate (ADR 0063, #1607).
2268    ///
2269    /// A `CLAIM LIMIT n` / `CLAIM EXACT n` on a logical-identity model (tables
2270    /// and documents) must order its candidates through a compatible index; the
2271    /// planner rejects an ordering no index on the collection can serve rather
2272    /// than falling back to a broad write-path sort. KV (key identity) and graph
2273    /// nodes/edges are exempt — their claim identity is intrinsic, not a user
2274    /// ORDER BY column that needs a secondary index.
2275    fn enforce_claim_order_by_index_gate(&self, query: &UpdateQuery) -> RedDBResult<()> {
2276        if query.claim_limit.is_none()
2277            || !matches!(query.target, UpdateTarget::Rows | UpdateTarget::Documents)
2278        {
2279            return Ok(());
2280        }
2281        let available_indexes: Vec<Vec<String>> = self
2282            .index_store_ref()
2283            .list_indices(&query.table)
2284            .into_iter()
2285            .map(|index| index.columns)
2286            .collect();
2287        reddb_rql::planner::check_claim_order_by_index_gate(query, &available_indexes)
2288            .map_err(RedDBError::InvalidOperation)
2289    }
2290
2291    fn execute_update_inner_tracked(
2292        &self,
2293        raw_query: &str,
2294        query: &UpdateQuery,
2295    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2296        self.enforce_claim_order_by_index_gate(query)?;
2297        let store = self.inner.db.store();
2298        let topology_lock = self
2299            .index_store_ref()
2300            .collection_topology_lock(&query.table);
2301        let effective_filter = effective_update_filter(query);
2302        let compiled_plan = self.compile_update_plan(query)?;
2303        // Autocommit table-row UPDATE replaces an MVCC version even when its
2304        // assignments are constants. Resolve the current pre-image under the
2305        // RMW lock. Explicit transactions keep their statement snapshot and
2306        // first-committer-wins conflict detection.
2307        let autocommit_table_update =
2308            matches!(query.target, UpdateTarget::Rows) && self.current_xid().is_none();
2309        let needs_rmw_lock = autocommit_table_update || update_needs_rmw_lock(query);
2310        let claim_model = update_model_name(update_target_model(query.target));
2311        if query.claim_limit.is_some() {
2312            self.inner
2313                .claim_telemetry
2314                .record_attempt(&query.table, claim_model);
2315        }
2316        let claim_lock = query.claim_limit.map(|_| {
2317            self.inner
2318                .rmw_locks
2319                .lock_for(&query.table, "__table_claim_update__")
2320        });
2321        let _claim_guard = if let Some(lock) = claim_lock.as_ref() {
2322            let Some(guard) = lock.try_lock() else {
2323                let skipped_locked = query.claim_limit.unwrap_or(1);
2324                self.inner.claim_telemetry.record_skipped_locked(
2325                    &query.table,
2326                    claim_model,
2327                    skipped_locked,
2328                );
2329                tracing::debug!(
2330                    target: "reddb::claim",
2331                    collection = %query.table,
2332                    model = claim_model,
2333                    skipped_locked,
2334                    "concurrent claim skipped locked candidates"
2335                );
2336                return Ok((
2337                    RuntimeQueryResult::dml_result(
2338                        raw_query.to_string(),
2339                        0,
2340                        "update",
2341                        "runtime-dml",
2342                    ),
2343                    Vec::new(),
2344                ));
2345            };
2346            Some(guard)
2347        } else {
2348            None
2349        };
2350        let table_rmw_lock = if needs_rmw_lock {
2351            Some(
2352                self.inner
2353                    .rmw_locks
2354                    .lock_for(&query.table, "__table_rmw_update__"),
2355            )
2356        } else {
2357            None
2358        };
2359        let _table_rmw_guard = table_rmw_lock.as_ref().map(|lock| lock.lock());
2360        let mut touched_ids: Vec<EntityId> = Vec::new();
2361        let claim_cap = query.claim_limit.map(|limit| limit as usize);
2362        let limit_cap = claim_cap.or_else(|| query.limit.map(|limit| limit as usize));
2363        let manager = store
2364            .get_collection(&query.table)
2365            .ok_or_else(|| RedDBError::NotFound(query.table.clone()))?;
2366        let scan_limit = if query.order_by.is_empty() {
2367            limit_cap
2368        } else {
2369            None
2370        };
2371        let mut target_scan = super::dml_target_scan::DmlTargetScan::with_update_target(
2372            self,
2373            &query.table,
2374            effective_filter.as_ref(),
2375            scan_limit,
2376            query.target,
2377        );
2378        if needs_rmw_lock && !autocommit_table_update {
2379            target_scan = target_scan.with_live_table_rows();
2380        }
2381        let ids_to_update = {
2382            let _topology_guard = topology_lock.read();
2383            // The statement snapshot predates the table lock. Refresh it
2384            // after acquiring that lock so earlier autocommits are visible,
2385            // but never select an uncommitted physical tip. Historical
2386            // versions can be absent from current indexes while a writer is
2387            // active, so retain the snapshot-aware index fallback then.
2388            let _fresh_snapshot = if autocommit_table_update {
2389                let mut ctx =
2390                    crate::runtime::impl_core::capture_current_snapshot().unwrap_or_else(|| {
2391                        let manager = self.snapshot_manager();
2392                        crate::runtime::impl_core::SnapshotContext {
2393                            branch: None,
2394                            snapshot: manager.fresh_read_snapshot(),
2395                            manager,
2396                            own_xids: std::collections::HashSet::new(),
2397                            requires_index_fallback: false,
2398                            hidden_writers_only: false,
2399                            serializable_reader: None,
2400                        }
2401                    });
2402                // A writer of this table still in flight would be hidden from
2403                // the fresh snapshot and force a scan for the targets. It takes
2404                // milliseconds; the scan takes far longer.
2405                ctx.manager
2406                    .await_real_writers_of(&query.table, std::time::Duration::from_millis(100));
2407                ctx.snapshot = ctx.manager.fresh_read_snapshot();
2408                ctx.branch = self.vcs_branch_read_view(&ctx.snapshot, None)?;
2409                if !ctx.requires_index_fallback
2410                    && ctx.manager.snapshot_hides_real_writers(&ctx.snapshot)
2411                {
2412                    ctx.requires_index_fallback = true;
2413                    ctx.hidden_writers_only = true;
2414                }
2415                Some(crate::runtime::impl_core::CurrentSnapshotGuard::install(
2416                    ctx,
2417                ))
2418            } else {
2419                None
2420            };
2421            target_scan.find_target_ids()?
2422        };
2423        let order_limit = if query.claim_limit.is_some() {
2424            None
2425        } else {
2426            limit_cap
2427        };
2428        let ids_to_update = if query.order_by.is_empty() {
2429            ids_to_update
2430        } else {
2431            ordered_update_target_ids(&manager, &ids_to_update, &query.order_by, order_limit)?
2432        };
2433        let mut ids_to_update = if query.claim_limit.is_some() || autocommit_table_update {
2434            self.filter_claim_locked_target_ids(&query.table, ids_to_update)?
2435        } else {
2436            ids_to_update
2437        };
2438        if let Some(claim_cap) = claim_cap {
2439            ids_to_update.truncate(claim_cap);
2440        }
2441        if query.claim_exact
2442            && claim_cap.is_some_and(|claim_count| ids_to_update.len() < claim_count)
2443        {
2444            self.inner
2445                .claim_telemetry
2446                .record_miss(&query.table, claim_model);
2447            return Ok((
2448                RuntimeQueryResult::dml_result(raw_query.to_string(), 0, "update", "runtime-dml"),
2449                Vec::new(),
2450            ));
2451        }
2452
2453        // Cover the interval from post-image preparation through storage and
2454        // secondary-index publication. Target selection above remains indexed.
2455        let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(&query.table);
2456        if needs_rmw_lock {
2457            let result = self.execute_update_inner_tracked_locked(
2458                raw_query,
2459                query,
2460                &compiled_plan,
2461                &ids_to_update,
2462                effective_filter.as_ref(),
2463                topology_lock.read(),
2464            )?;
2465            if query.claim_limit.is_some() {
2466                self.record_pending_claim_locks_for_touched_ids(&query.table, &result.1);
2467            }
2468            record_claim_outcome(
2469                &self.inner.claim_telemetry,
2470                query.claim_limit,
2471                &query.table,
2472                claim_model,
2473                result.0.affected_rows,
2474            );
2475            return Ok(result);
2476        }
2477
2478        // Keep topology fixed while reserving every post-image. No chunk is
2479        // published until all targets fit; a later denial cannot leave earlier
2480        // autocommit chunks visible. Prepared payload is bounded by admission.
2481        let topology_guard = topology_lock.read();
2482        let mut prepared = Vec::new();
2483        let mut reservations = super::memory_admission::MutationMemoryReservations::new(self);
2484        for chunk in ids_to_update.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2485            for id in chunk {
2486                #[cfg(test)]
2487                self.index_store_ref().mutation_test_hook(
2488                    &query.table,
2489                    super::index_store::MutationTestPhase::DmlPostImageCandidate,
2490                );
2491                super::query_budget::charge(1)?;
2492                let Some(entity) = manager.try_get(*id, usize::MAX)? else {
2493                    continue;
2494                };
2495                let assignments =
2496                    self.materialize_update_assignments_for_entity(query, &entity, &compiled_plan)?;
2497                let applied = self.apply_materialized_update_for_entity(
2498                    query,
2499                    entity,
2500                    &compiled_plan,
2501                    assignments,
2502                )?;
2503                reservations.admit(&applied)?;
2504                touched_ids.push(applied.id);
2505                prepared.push(applied);
2506            }
2507        }
2508        self.validate_graph_changes(
2509            &query.table,
2510            &prepared.iter().map(|item| &item.entity).collect::<Vec<_>>(),
2511            &prepared
2512                .iter()
2513                .map(|item| {
2514                    item.replaced_entity
2515                        .as_ref()
2516                        .map_or(item.id, |entity| entity.id)
2517                })
2518                .collect::<Vec<_>>(),
2519        )?;
2520        let affected = prepared.len() as u64;
2521        let mut published = 0;
2522        let mut _durable_publication = None;
2523        let persistence = (|| -> RedDBResult<()> {
2524            super::query_budget::charge(0)?;
2525            // Standalone UNIQUE keys are admitted for the whole statement
2526            // before any chunk is published.
2527            self.enforce_unique_update_post_images(&query.table, &compiled_plan, &prepared)?;
2528            // This is the cancellation boundary. Once durable publication
2529            // starts, finish the prepared statement rather than exposing a
2530            // timeout with only a prefix of its chunks committed.
2531            _durable_publication = Some(super::query_budget::begin_durable_publication()?);
2532            let _chunk_checkpoints = self.chunk_checkpoints_for(&query.table, prepared.len());
2533            for chunk in prepared.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2534                if compiled_plan.row_touches_unique_columns
2535                    || compiled_plan
2536                        .row_contract_plan
2537                        .as_ref()
2538                        .is_some_and(|plan| plan.has_expressions)
2539                {
2540                    let db = self.db();
2541                    let contract = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(self, &db, &query.table);
2542                    for item in chunk {
2543                        let fields =
2544                            crate::application::ports::entity_row_fields_snapshot(&item.entity);
2545                        let previous_id =
2546                            item.replaced_entity.as_ref().map_or(item.id, |old| old.id);
2547                        let previous = (!item.pre_mutation_fields.is_empty())
2548                            .then_some(item.pre_mutation_fields.as_slice());
2549                        contract.enforce_updated_row_uniqueness(
2550                            &fields,
2551                            previous,
2552                            Some(previous_id),
2553                        )?;
2554                    }
2555                }
2556                self.persist_update_chunk(chunk)?;
2557                published += chunk.len();
2558            }
2559            Ok(())
2560        })();
2561        // A later storage/constraint error must still finish index and CDC
2562        // maintenance for earlier published chunks, as the chunked path did.
2563        let published_mutations = &prepared[..published];
2564        let lsns = self.flush_update_chunk(published_mutations, topology_guard)?;
2565        if !query.suppress_events {
2566            self.emit_update_events_for_collection(&query.table, published_mutations, &lsns)?;
2567        }
2568        persistence?;
2569        drop(reservations);
2570
2571        if affected > 0 {
2572            self.note_table_write(&query.table);
2573        }
2574        if query.claim_limit.is_some() {
2575            self.record_pending_claim_locks_for_touched_ids(&query.table, &touched_ids);
2576        }
2577        record_claim_outcome(
2578            &self.inner.claim_telemetry,
2579            query.claim_limit,
2580            &query.table,
2581            claim_model,
2582            affected,
2583        );
2584
2585        Ok((
2586            RuntimeQueryResult::dml_result(
2587                raw_query.to_string(),
2588                affected,
2589                "update",
2590                "runtime-dml",
2591            ),
2592            touched_ids,
2593        ))
2594    }
2595
2596    fn filter_claim_locked_target_ids(
2597        &self,
2598        table: &str,
2599        ids: Vec<EntityId>,
2600    ) -> RedDBResult<Vec<EntityId>> {
2601        let conn_id = current_connection_id();
2602        let locks = self.inner.pending_claim_locks.read();
2603        if locks.is_empty() {
2604            return Ok(ids);
2605        }
2606        let mut admitted = Vec::with_capacity(ids.len());
2607        for id in ids {
2608            super::query_budget::charge(1)?;
2609            if let Some(entity) = self.inner.db.store().try_get(table, id, usize::MAX)? {
2610                let key = (table.to_string(), entity.logical_id());
2611                if locks.get(&key).is_none_or(|owner| *owner == conn_id) {
2612                    admitted.push(id);
2613                }
2614            }
2615        }
2616        Ok(admitted)
2617    }
2618
2619    fn record_pending_claim_locks_for_touched_ids(&self, table: &str, ids: &[EntityId]) {
2620        if self.current_xid().is_none() || ids.is_empty() {
2621            return;
2622        }
2623
2624        let conn_id = current_connection_id();
2625        let store = self.inner.db.store();
2626        let mut locks = self.inner.pending_claim_locks.write();
2627        for id in ids {
2628            let Some(entity) = store.get(table, *id) else {
2629                continue;
2630            };
2631            locks.insert((table.to_string(), entity.logical_id()), conn_id);
2632        }
2633    }
2634
2635    fn execute_update_inner_tracked_locked(
2636        &self,
2637        raw_query: &str,
2638        query: &UpdateQuery,
2639        compiled_plan: &CompiledUpdatePlan,
2640        ids_to_update: &[EntityId],
2641        effective_filter: Option<&Filter>,
2642        topology_guard: parking_lot::RwLockReadGuard<'_, ()>,
2643    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2644        // Existing table/claim locks precede topology; per-row RMW locks
2645        // below follow it. Keep the same index set through persistence/flush.
2646        let store = self.inner.db.store();
2647        let mut touched_ids = Vec::new();
2648        let mut lock_entries = Vec::new();
2649
2650        for id in ids_to_update {
2651            super::query_budget::charge(1)?;
2652            let Some(candidate) = store.try_get(&query.table, *id, usize::MAX)? else {
2653                continue;
2654            };
2655            let logical_id = candidate.logical_id();
2656            let lock_key = super::RmwLockTable::row_key(logical_id);
2657            let rmw_lock = self.inner.rmw_locks.lock_for(&query.table, &lock_key);
2658            lock_entries.push((lock_key, logical_id, rmw_lock));
2659        }
2660
2661        lock_entries.sort_by(|left, right| left.0.cmp(&right.0));
2662        lock_entries.dedup_by(|left, right| left.0 == right.0);
2663        let _rmw_guards: Vec<_> = lock_entries.iter().map(|entry| entry.2.lock()).collect();
2664
2665        let mut applied_chunk = Vec::new();
2666        let mut reservations = super::memory_admission::MutationMemoryReservations::new(self);
2667        for (_, logical_id, _) in &lock_entries {
2668            #[cfg(test)]
2669            self.index_store_ref().mutation_test_hook(
2670                &query.table,
2671                super::index_store::MutationTestPhase::DmlPostImageCandidate,
2672            );
2673            super::query_budget::charge(1)?;
2674            let Some(entity) =
2675                try_resolve_update_entity_by_logical_id(self, &query.table, *logical_id)?
2676            else {
2677                continue;
2678            };
2679            if let Some(filter) = effective_filter {
2680                if !crate::runtime::query_exec::evaluate_entity_filter_result_with_db(
2681                    Some(self.inner.db.as_ref()),
2682                    &entity,
2683                    filter,
2684                    &query.table,
2685                    &query.table,
2686                )? {
2687                    continue;
2688                }
2689            }
2690
2691            let assignments =
2692                self.materialize_update_assignments_for_entity(query, &entity, compiled_plan)?;
2693            let applied = self.apply_materialized_update_for_entity(
2694                query,
2695                entity,
2696                compiled_plan,
2697                assignments,
2698            )?;
2699            reservations.admit(&applied)?;
2700            touched_ids.push(applied.id);
2701            applied_chunk.push(applied);
2702        }
2703
2704        self.validate_graph_changes(
2705            &query.table,
2706            &applied_chunk
2707                .iter()
2708                .map(|item| &item.entity)
2709                .collect::<Vec<_>>(),
2710            &applied_chunk
2711                .iter()
2712                .map(|item| {
2713                    item.replaced_entity
2714                        .as_ref()
2715                        .map_or(item.id, |entity| entity.id)
2716                })
2717                .collect::<Vec<_>>(),
2718        )?;
2719        let affected = applied_chunk.len() as u64;
2720        let mut published = 0;
2721        let mut _durable_publication = None;
2722        let persistence = (|| -> RedDBResult<()> {
2723            super::query_budget::charge(0)?;
2724            self.enforce_unique_update_post_images(&query.table, compiled_plan, &applied_chunk)?;
2725            // Final cooperative checkpoint before the first durable chunk.
2726            // Cancellation after this point cannot safely abort a prefix.
2727            _durable_publication = Some(super::query_budget::begin_durable_publication()?);
2728            let _chunk_checkpoints = self.chunk_checkpoints_for(&query.table, applied_chunk.len());
2729            for chunk in applied_chunk.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2730                if compiled_plan.row_touches_unique_columns
2731                    || compiled_plan
2732                        .row_contract_plan
2733                        .as_ref()
2734                        .is_some_and(|plan| plan.has_expressions)
2735                {
2736                    let db = self.db();
2737                    let contract = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(self, &db, &query.table);
2738                    for item in chunk {
2739                        let fields =
2740                            crate::application::ports::entity_row_fields_snapshot(&item.entity);
2741                        let previous_id =
2742                            item.replaced_entity.as_ref().map_or(item.id, |old| old.id);
2743                        let previous = (!item.pre_mutation_fields.is_empty())
2744                            .then_some(item.pre_mutation_fields.as_slice());
2745                        contract.enforce_updated_row_uniqueness(
2746                            &fields,
2747                            previous,
2748                            Some(previous_id),
2749                        )?;
2750                    }
2751                }
2752                self.persist_update_chunk(chunk)?;
2753                published += chunk.len();
2754            }
2755            Ok(())
2756        })();
2757        // Earlier chunks may have been published when a later constraint
2758        // check fails. Finish their indexes and events before returning it.
2759        let published_mutations = &applied_chunk[..published];
2760        let lsns = self.flush_update_chunk(published_mutations, topology_guard)?;
2761        if !query.suppress_events {
2762            self.emit_update_events_for_collection(&query.table, published_mutations, &lsns)?;
2763        }
2764        persistence?;
2765
2766        if affected > 0 {
2767            self.note_table_write(&query.table);
2768        }
2769
2770        Ok((
2771            RuntimeQueryResult::dml_result(
2772                raw_query.to_string(),
2773                affected,
2774                "update",
2775                "runtime-dml",
2776            ),
2777            touched_ids,
2778        ))
2779    }
2780
2781    fn enforce_unique_update_post_images(
2782        &self,
2783        collection: &str,
2784        compiled_plan: &CompiledUpdatePlan,
2785        applied: &[AppliedEntityMutation],
2786    ) -> RedDBResult<()> {
2787        if !compiled_plan.touches_unique_index {
2788            return Ok(());
2789        }
2790        let post_images: Vec<_> = applied
2791            .iter()
2792            .map(|item| {
2793                (
2794                    item.replaced_entity.as_ref().map_or(item.id, |old| old.id),
2795                    crate::application::ports::entity_row_fields_snapshot(&item.entity),
2796                )
2797            })
2798            .collect();
2799        self.enforce_unique_updates(collection, &post_images)
2800    }
2801
2802    fn compile_update_plan(&self, query: &UpdateQuery) -> RedDBResult<CompiledUpdatePlan> {
2803        let mut static_field_assignments = Vec::new();
2804        let mut static_metadata_assignments = Vec::new();
2805        let mut dynamic_assignments = Vec::new();
2806        let row_contract_plan = build_row_update_contract_plan(&self.db(), &query.table)?;
2807        let mut row_modified_columns = Vec::new();
2808
2809        for (idx, (column, expr)) in query.assignment_exprs.iter().enumerate() {
2810            let compound_op = query.compound_assignment_ops.get(idx).copied().flatten();
2811            let metadata_key = resolve_sql_ttl_metadata_key(column);
2812            if compound_op.is_some() && metadata_key.is_some() {
2813                return Err(RedDBError::Query(format!(
2814                    "compound assignment is only supported for row fields: {column}"
2815                )));
2816            }
2817            if compound_op.is_none() {
2818                if let Ok(value) = fold_expr_to_value(expr.clone()) {
2819                    // Without a declared type, a text constant may overwrite an
2820                    // existing Secret. Resolve it per row to preserve encryption.
2821                    let unknown_text_target = metadata_key.is_none()
2822                        && matches!(value, Value::Text(_))
2823                        && row_contract_plan
2824                            .as_ref()
2825                            .and_then(|plan| plan.declared_rules.get(column))
2826                            .is_none();
2827                    if !unknown_text_target {
2828                        if let Some(metadata_key) = metadata_key {
2829                            let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2830                            let (canonical_key, canonical_value) =
2831                                canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2832                            static_metadata_assignments
2833                                .push((canonical_key.to_string(), canonical_value));
2834                        } else {
2835                            let is_secret_column = row_contract_plan
2836                                .as_ref()
2837                                .and_then(|plan| plan.declared_rules.get(column))
2838                                .is_some_and(|rule| {
2839                                    rule.data_type == reddb_types::DataType::Secret
2840                                });
2841                            let value =
2842                                self.resolve_secret_column_value(value, is_secret_column)?;
2843                            static_field_assignments.push((
2844                                column.clone(),
2845                                normalize_row_update_assignment_with_plan(
2846                                    &query.table,
2847                                    column,
2848                                    value,
2849                                    row_contract_plan.as_ref(),
2850                                )?,
2851                            ));
2852                            row_modified_columns.push(column.clone());
2853                        }
2854                        continue;
2855                    }
2856                }
2857            }
2858
2859            dynamic_assignments.push(CompiledUpdateAssignment {
2860                column: column.clone(),
2861                expr: expr.clone(),
2862                compound_op,
2863                metadata_key,
2864                row_rule: if metadata_key.is_none() {
2865                    if let Some(plan) = row_contract_plan.as_ref() {
2866                        if plan.timestamps_enabled
2867                            && (column == "created_at" || column == "updated_at")
2868                        {
2869                            return Err(RedDBError::Query(format!(
2870                                "collection '{}' manages '{}' automatically — do not set it in UPDATE",
2871                                query.table, column
2872                            )));
2873                        }
2874                        if let Some(rule) = plan.declared_rules.get(column) {
2875                            Some(rule.clone())
2876                        } else if plan.strict_schema {
2877                            return Err(RedDBError::Query(format!(
2878                                "collection '{}' is strict and does not allow undeclared fields: {}",
2879                                query.table, column
2880                            )));
2881                        } else {
2882                            None
2883                        }
2884                    } else {
2885                        None
2886                    }
2887                } else {
2888                    None
2889                },
2890            });
2891            if metadata_key.is_none() {
2892                row_modified_columns.push(column.clone());
2893            }
2894        }
2895
2896        let row_modified_columns = dedupe_update_columns(row_modified_columns);
2897        let row_touches_unique_columns = row_contract_plan.as_ref().is_some_and(|plan| {
2898            row_modified_columns.iter().any(|column| {
2899                plan.unique_columns
2900                    .keys()
2901                    .any(|unique| unique.eq_ignore_ascii_case(column))
2902            })
2903        });
2904
2905        let touches_unique_index = self
2906            .index_store_ref()
2907            .touches_unique_index(&query.table, &row_modified_columns);
2908
2909        if let Some(ttl_ms) = query.ttl_ms {
2910            static_metadata_assignments
2911                .push(("_ttl_ms".to_string(), metadata_u64_to_value(ttl_ms)));
2912        }
2913        if let Some(expires_at_ms) = query.expires_at_ms {
2914            static_metadata_assignments.push((
2915                "_expires_at".to_string(),
2916                metadata_u64_to_value(expires_at_ms),
2917            ));
2918        }
2919        for (key, val) in &query.with_metadata {
2920            static_metadata_assignments.push((key.clone(), storage_value_to_metadata_value(val)));
2921        }
2922
2923        Ok(CompiledUpdatePlan {
2924            static_field_assignments,
2925            static_metadata_assignments,
2926            dynamic_assignments,
2927            row_contract_plan,
2928            row_modified_columns,
2929            row_touches_unique_columns,
2930            touches_unique_index,
2931        })
2932    }
2933
2934    fn materialize_update_assignments_for_entity(
2935        &self,
2936        query: &UpdateQuery,
2937        entity: &UnifiedEntity,
2938        compiled_plan: &CompiledUpdatePlan,
2939    ) -> RedDBResult<MaterializedUpdateAssignments> {
2940        let mut assignments = MaterializedUpdateAssignments::default();
2941        let mut record: Option<UnifiedRecord> = None;
2942
2943        for assignment in &compiled_plan.dynamic_assignments {
2944            if assignment.compound_op.is_some()
2945                && !matches!(
2946                    entity.data,
2947                    EntityData::Row(_) | EntityData::Node(_) | EntityData::Edge(_)
2948                )
2949            {
2950                return Err(RedDBError::Query(format!(
2951                    "compound assignment is only supported for row or graph UPDATE column '{}'",
2952                    assignment.column
2953                )));
2954            }
2955            if record.is_none() {
2956                record = runtime_any_record_from_entity_ref(entity);
2957            }
2958            let Some(record) = record.as_ref() else {
2959                return Err(RedDBError::Query(format!(
2960                    "UPDATE could not materialize runtime record for entity {} in '{}'",
2961                    entity.id.raw(),
2962                    query.table
2963                )));
2964            };
2965            let rhs = super::expr_eval::try_evaluate_runtime_expr_with_db(
2966                Some(self.inner.db.as_ref()),
2967                &assignment.expr,
2968                record,
2969                Some(query.table.as_str()),
2970                Some(query.table.as_str()),
2971            )?
2972            .ok_or_else(|| {
2973                RedDBError::Query(format!(
2974                    "failed to evaluate UPDATE expression for column '{}'",
2975                    assignment.column
2976                ))
2977            })?;
2978            let value = if let Some(op) = assignment.compound_op {
2979                evaluate_compound_update_assignment(&assignment.column, record, op, rhs)?
2980            } else {
2981                rhs
2982            };
2983
2984            let sensitive = super::join_filter::expression_uses_secret(
2985                &assignment.expr,
2986                record,
2987                Some(&query.table),
2988                Some(&query.table),
2989            );
2990            let secret_target = assignment
2991                .row_rule
2992                .as_ref()
2993                .is_some_and(|rule| rule.data_type == reddb_types::DataType::Secret)
2994                || record
2995                    .get(&assignment.column)
2996                    .is_some_and(|value| matches!(value, Value::Secret(_)));
2997            if sensitive && !secret_target {
2998                return Err(RedDBError::Query(
2999                    "secret-derived UPDATE values require a SECRET target column".into(),
3000                ));
3001            }
3002            if let Some(metadata_key) = assignment.metadata_key {
3003                let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
3004                let (canonical_key, canonical_value) =
3005                    canonicalize_sql_ttl_metadata(metadata_key, raw_value);
3006                assignments
3007                    .dynamic_metadata_assignments
3008                    .push((canonical_key.to_string(), canonical_value));
3009            } else {
3010                assignments.dynamic_field_assignments.push((
3011                    assignment.column.clone(),
3012                    normalize_row_update_value_for_rule(
3013                        &query.table,
3014                        self.resolve_secret_column_value(
3015                            value,
3016                            assignment.row_rule.as_ref().is_some_and(|rule| {
3017                                rule.data_type == reddb_types::DataType::Secret
3018                            }) || record
3019                                .get(&assignment.column)
3020                                .is_some_and(|value| matches!(value, Value::Secret(_))),
3021                        )?,
3022                        assignment.row_rule.as_ref(),
3023                    )?,
3024                ));
3025            }
3026        }
3027
3028        Ok(assignments)
3029    }
3030
3031    fn apply_materialized_update_for_entity(
3032        &self,
3033        query: &UpdateQuery,
3034        entity: UnifiedEntity,
3035        compiled_plan: &CompiledUpdatePlan,
3036        mut assignments: MaterializedUpdateAssignments,
3037    ) -> RedDBResult<AppliedEntityMutation> {
3038        if matches!(query.target, UpdateTarget::Kv)
3039            && !compiled_plan
3040                .static_field_assignments
3041                .iter()
3042                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
3043            && !assignments
3044                .dynamic_field_assignments
3045                .iter()
3046                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
3047        {
3048            if let Some(key) = runtime_any_record_from_entity_ref(&entity)
3049                .and_then(|record| record.get("key").cloned())
3050            {
3051                assignments
3052                    .dynamic_field_assignments
3053                    .push(("key".to_string(), key));
3054            }
3055        }
3056        if matches!(entity.data, EntityData::Row(_)) {
3057            return self.apply_loaded_sql_update_row_core(
3058                query.table.clone(),
3059                entity,
3060                &compiled_plan.static_field_assignments,
3061                assignments.dynamic_field_assignments,
3062                &compiled_plan.static_metadata_assignments,
3063                assignments.dynamic_metadata_assignments,
3064                compiled_plan.row_contract_plan.as_ref(),
3065                &compiled_plan.row_modified_columns,
3066                compiled_plan.row_touches_unique_columns,
3067            );
3068        }
3069
3070        ensure_graph_identity_update_allowed(&entity, compiled_plan, &assignments)?;
3071
3072        let operations = build_patch_operations_from_materialized_assignments(
3073            &entity,
3074            compiled_plan,
3075            assignments,
3076        );
3077        self.apply_loaded_patch_entity_core(
3078            query.table.clone(),
3079            entity,
3080            crate::json::Value::Null,
3081            operations,
3082        )
3083    }
3084
3085    /// Execute DELETE FROM table WHERE filter
3086    pub fn execute_delete(
3087        &self,
3088        raw_query: &str,
3089        query: &DeleteQuery,
3090    ) -> RedDBResult<RuntimeQueryResult> {
3091        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3092        let branch_store = self.db().store();
3093        let _branch_publication = (self.vcs_is_versioned(&query.table)?
3094            || self.has_graph_contract(&query.table))
3095        .then(|| branch_store.vault_publication_lock.lock());
3096        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
3097            self,
3098            &query.table,
3099        );
3100        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
3101        // Issue #523 — blockchain collections are immutable; see
3102        // execute_update for the same gate.
3103        if crate::runtime::blockchain_kind::try_is_chain(
3104            self.inner.db.store().as_ref(),
3105            &query.table,
3106        )? {
3107            return Err(RedDBError::InvalidOperation(format!(
3108                "BlockchainCollectionImmutable: DELETE not allowed on '{}'",
3109                query.table
3110            )));
3111        }
3112        // CollectionContract gate (#50) — see execute_update for
3113        // rationale. The gate handles APPEND ONLY rejection and is
3114        // the single point where future contract bits land.
3115        crate::runtime::collection_contract::CollectionContractGate::check(
3116            self,
3117            &query.table,
3118            crate::runtime::collection_contract::MutationKind::Delete,
3119        )?;
3120
3121        // RETURNING on DELETE: capture the pre-image via an internal
3122        // SELECT that reuses the same WHERE, then run the delete with
3123        // the RETURNING clause stripped, then project the captured
3124        // rows through the requested items. The extra SELECT is a
3125        // pragmatic MVP — a future pass can fuse the scan with the
3126        // delete to avoid the second pass over the heap.
3127        if let Some(items) = query.returning.clone() {
3128            let select_sql = delete_to_select_sql(raw_query).ok_or_else(|| {
3129                RedDBError::Query(
3130                    "DELETE ... RETURNING: cannot rewrite query for pre-image scan".to_string(),
3131                )
3132            })?;
3133            let captured = self.execute_query(&select_sql)?;
3134
3135            let mut inner_query = query.clone();
3136            inner_query.returning = None;
3137            let _ = self.execute_delete(raw_query, &inner_query)?;
3138
3139            let snapshots: Vec<Vec<(String, Value)>> = captured
3140                .result
3141                .records
3142                .iter()
3143                .map(|rec| {
3144                    rec.iter_fields()
3145                        .map(|(k, v)| (k.as_ref().to_string(), v.clone()))
3146                        .collect()
3147                })
3148                .collect();
3149            let affected = snapshots.len() as u64;
3150            let result = build_returning_result(&items, &snapshots, None);
3151
3152            let mut response = RuntimeQueryResult::dml_result(
3153                raw_query.to_string(),
3154                affected,
3155                "delete",
3156                "runtime-dml-returning",
3157            );
3158            response.result = result;
3159            return Ok(response);
3160        }
3161        // Row-Level Security enforcement (Phase 2.5.2 PG parity).
3162        //
3163        // When the table has RLS enabled, gate the DELETE by the
3164        // per-role policy set: mutations only touch rows that *every*
3165        // matching `FOR DELETE` policy would accept. No policies =>
3166        // zero rows affected (PG restrictive-default).
3167        if crate::runtime::impl_core::rls_is_enabled(self, &query.table) {
3168            let rls_filter = crate::runtime::impl_core::rls_policy_filter(
3169                self,
3170                &query.table,
3171                reddb_rql::ast::PolicyAction::Delete,
3172            );
3173            let Some(policy) = rls_filter else {
3174                return Ok(RuntimeQueryResult::dml_result(
3175                    raw_query.to_string(),
3176                    0,
3177                    "delete",
3178                    "runtime-dml-rls",
3179                ));
3180            };
3181            // Fold the policy predicate into the user's WHERE before
3182            // dispatching — the remainder of this function reads the
3183            // filter from `query` via `effective_delete_filter`, which
3184            // respects the updated value.
3185            let mut augmented = query.clone();
3186            augmented.filter = Some(match augmented.filter.take() {
3187                Some(existing) => reddb_rql::ast::Filter::And(Box::new(existing), Box::new(policy)),
3188                None => policy,
3189            });
3190            return self.execute_delete_inner(raw_query, &augmented);
3191        }
3192        self.execute_delete_inner(raw_query, query)
3193    }
3194
3195    fn execute_delete_inner(
3196        &self,
3197        raw_query: &str,
3198        query: &DeleteQuery,
3199    ) -> RedDBResult<RuntimeQueryResult> {
3200        let maintenance_limit = super::retention_sweeper::take_delete_limit();
3201        let topology_lock = self
3202            .index_store_ref()
3203            .collection_topology_lock(&query.table);
3204        let effective_filter = effective_delete_filter(query);
3205
3206        // Find the rows that match the WHERE clause. The "find target
3207        // rows" loop lives in DmlTargetScan so UPDATE (#52) can reuse
3208        // the same scan strategy.
3209        let scan = super::dml_target_scan::DmlTargetScan::new(
3210            self,
3211            &query.table,
3212            effective_filter.as_ref(),
3213            maintenance_limit,
3214        );
3215        let ids_to_delete = {
3216            let _topology_guard = topology_lock.read();
3217            let ids = scan.find_target_ids()?;
3218            if ids.len() > UPDATE_APPLY_CHUNK_SIZE
3219                && self.current_xid().is_none()
3220                && UnifiedStore::deferred_store_wal_capture_active()
3221            {
3222                super::delete_publication::order_target_ids(self, &query.table, ids)?
3223            } else {
3224                ids
3225            }
3226        };
3227
3228        let needs_delete_events =
3229            !query.suppress_events && self.collection_has_delete_subscriptions(&query.table);
3230        let mut affected: u64 = 0;
3231        // Final cooperative checkpoint before DELETE begins publishing its
3232        // prepared target set. A later timeout must not strand a partial
3233        // statement merely to stop sooner.
3234        let _durable_publication = super::query_budget::begin_durable_publication()?;
3235        self.validate_graph_changes(&query.table, &[], &ids_to_delete)?;
3236        for chunk in ids_to_delete.chunks(UPDATE_APPLY_CHUNK_SIZE) {
3237            let deleted = self.delete_entities_batch(
3238                &query.table,
3239                chunk,
3240                topology_lock.read(),
3241                effective_filter.as_ref(),
3242                needs_delete_events,
3243            )?;
3244            #[cfg(test)]
3245            self.index_store_ref().mutation_test_hook(
3246                &query.table,
3247                super::index_store::MutationTestPhase::BeforeEvents,
3248            );
3249            affected += deleted.affected;
3250            if needs_delete_events && !deleted.changes.is_empty() {
3251                let ids: Vec<_> = deleted.changes.iter().map(|(id, _)| *id).collect();
3252                let lsns: Vec<_> = deleted.changes.iter().map(|(_, lsn)| *lsn).collect();
3253                self.emit_delete_events_for_collection(
3254                    &query.table,
3255                    &ids,
3256                    &lsns,
3257                    &deleted.pre_images,
3258                )?;
3259            }
3260        }
3261
3262        if affected > 0 {
3263            self.note_table_write(&query.table);
3264        }
3265
3266        Ok(RuntimeQueryResult::dml_result(
3267            raw_query.to_string(),
3268            affected,
3269            "delete",
3270            "runtime-dml",
3271        ))
3272    }
3273}
3274
3275// Shared admission cannot run expressions that enter another DML statement.
3276fn point_update_expr(expr: &Expr) -> bool {
3277    match expr {
3278        Expr::Literal { .. } | Expr::Column { .. } => true,
3279        Expr::BinaryOp { lhs, rhs, .. } => point_update_expr(lhs) && point_update_expr(rhs),
3280        Expr::UnaryOp { operand, .. } => point_update_expr(operand),
3281        _ => false,
3282    }
3283}
3284
3285#[cfg(test)]
3286mod tests {
3287    use crate::storage::wal::{WalReader, WalRecord};
3288    use crate::storage::{DeployProfile, StoragePackaging, StorageProfileSelection};
3289    use crate::{RedDBOptions, RedDBRuntime};
3290    use reddb_types::Value;
3291    use std::path::Path;
3292
3293    #[test]
3294    fn captured_bulk_delete_keeps_global_row_lock_order_across_chunks() {
3295        use std::sync::{
3296            atomic::{AtomicUsize, Ordering},
3297            Arc,
3298        };
3299        let runtime = Arc::new(
3300            RedDBRuntime::with_options(
3301                RedDBOptions::in_memory().with_memory_budget(128 * 1024 * 1024),
3302            )
3303            .expect("bulk lock fixture"),
3304        );
3305        runtime
3306            .execute_query("CREATE TABLE bulk_lock_order (id INTEGER)")
3307            .expect("table");
3308        let count = super::UPDATE_APPLY_CHUNK_SIZE + 16;
3309        for batch in (0..count).collect::<Vec<_>>().chunks(512) {
3310            let values = batch
3311                .iter()
3312                .map(|id| format!("({id})"))
3313                .collect::<Vec<_>>()
3314                .join(",");
3315            runtime
3316                .execute_query(&format!("INSERT INTO bulk_lock_order (id) VALUES {values}"))
3317                .expect("seed chunk boundary");
3318        }
3319        let manager = runtime
3320            .db()
3321            .store()
3322            .get_collection("bulk_lock_order")
3323            .expect("rows");
3324        // Imported/versioned rows can have logical identities independent
3325        // of their physical positions. Cross decimal-width boundaries too;
3326        // fresh time-based physical IDs alone keep the same string order.
3327        let mut rows = manager.query_all(|_| true);
3328        rows.sort_unstable_by_key(|entity| entity.id);
3329        for (position, mut entity) in rows.into_iter().enumerate() {
3330            entity.set_logical_id(crate::storage::EntityId::new(
3331                u64::try_from(position + 1).expect("small identity"),
3332            ));
3333            manager
3334                .update(entity)
3335                .expect("independent logical identity");
3336        }
3337        let mut expected: Vec<_> = manager
3338            .query_all(|_| true)
3339            .iter()
3340            .map(|entity| format!("row:{}", entity.logical_id().raw()))
3341            .collect();
3342        expected.sort_unstable();
3343        let calls = Arc::new(AtomicUsize::new(0));
3344        let hook_calls = Arc::clone(&calls);
3345        let weak_runtime = Arc::downgrade(&runtime);
3346        *runtime.index_store_ref().mutation_hook.lock() =
3347            Some(Arc::new(move |collection, phase| {
3348                if collection == "bulk_lock_order"
3349                    && phase == super::super::index_store::MutationTestPhase::BeforeEvents
3350                {
3351                    let runtime = weak_runtime.upgrade().expect("writer still alive");
3352                    let held =
3353                        super::super::delete_publication::pending_lock_keys(&runtime, collection);
3354                    assert!(!held.is_empty());
3355                    assert!(held.len() <= expected.len());
3356                    let mismatch = held
3357                        .iter()
3358                        .zip(&expected)
3359                        .position(|(actual, expected)| actual != expected);
3360                    assert!(
3361                        mismatch.is_none(),
3362                        "captured DELETE violated global lock order at position {mismatch:?}"
3363                    );
3364                    hook_calls.fetch_add(1, Ordering::SeqCst);
3365                }
3366            }));
3367        let result = runtime
3368            .with_deferred_store_wal_for_dml(true, || {
3369                runtime.execute_query("DELETE FROM bulk_lock_order")
3370            })
3371            .expect("captured bulk delete");
3372        assert_eq!(
3373            result.affected_rows,
3374            u64::try_from(count).expect("small fixture")
3375        );
3376        assert!(
3377            calls.load(Ordering::SeqCst) >= 2,
3378            "fixture must cross an apply chunk"
3379        );
3380        assert!(runtime
3381            .execute_query("SELECT id FROM bulk_lock_order")
3382            .expect("deleted rows")
3383            .result
3384            .records
3385            .is_empty());
3386        assert_eq!(runtime.snapshot_manager().oldest_active_xid(), None);
3387    }
3388
3389    #[test]
3390    fn locked_update_recheck_read_failure_preserves_preimages_and_retry() {
3391        use crate::storage::engine::BTree;
3392        use reddb_engine::storage::collection_read::PagedCollection;
3393        use std::sync::Arc;
3394
3395        let directory = tempfile::tempdir().expect("locked update fixture");
3396        let options = RedDBOptions::persistent(directory.path().join("locked-update.rdb"))
3397            .with_memory_budget(128 * 1024 * 1024)
3398            .with_storage_profile(
3399                crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
3400            )
3401            .expect("locked update profile");
3402        let runtime = RedDBRuntime::with_options(options).expect("locked update runtime");
3403        for sql in [
3404            "CREATE TABLE recheck_probe (id INTEGER)",
3405            "INSERT INTO recheck_probe (id) VALUES (1), (2)",
3406            "SET CONFIG fixture.flag = 'ready'",
3407        ] {
3408            runtime.execute_query(sql).expect(sql);
3409        }
3410        let sql = "UPDATE recheck_probe SET id = id + 10 WHERE id = 1 OR CONFIG('fixture.flag') = 'ready'";
3411        let reddb_rql::ast::QueryExpr::Update(query) =
3412            reddb_rql::parse(sql).expect("parse update").query
3413        else {
3414            panic!("expected UPDATE");
3415        };
3416        let compiled = runtime.compile_update_plan(&query).expect("compile update");
3417        let filter = reddb_rql::sql_lowering::effective_update_filter(&query);
3418        let ids = super::super::dml_target_scan::DmlTargetScan::new(
3419            &runtime,
3420            "recheck_probe",
3421            filter.as_ref(),
3422            None,
3423        )
3424        .find_target_ids()
3425        .expect("discover targets before failure");
3426        assert_eq!(ids.len(), 2);
3427        let store = runtime.db().store();
3428        store.persist().expect("publish recheck configuration");
3429        let root = store
3430            .collection_root_page("red.config")
3431            .expect("configuration root");
3432        let manager = store
3433            .get_collection("red.config")
3434            .expect("configuration collection");
3435        let install = |limit| {
3436            let tree = BTree::with_root(Arc::clone(store.pager().expect("pager")), root);
3437            manager.install_backing(
3438                Arc::new(PagedCollection::new(Arc::new(tree))),
3439                root,
3440                store.format_version(),
3441                limit,
3442                manager.count() as u64,
3443            );
3444        };
3445        let assert_ids = |expected: [i64; 2]| {
3446            runtime.invalidate_result_cache();
3447            let rows = runtime
3448                .execute_query("SELECT id FROM recheck_probe ORDER BY id")
3449                .expect("read preimages");
3450            let actual: Vec<_> = rows
3451                .result
3452                .records
3453                .iter()
3454                .map(|row| row.get("id").cloned().expect("row value"))
3455                .collect();
3456            assert_eq!(actual, expected.map(Value::Integer));
3457        };
3458        // Candidate discovery has succeeded. Fail only the locked recheck,
3459        // after the first row's postimage can already have been prepared.
3460        let topology = runtime
3461            .index_store_ref()
3462            .collection_topology_lock(&query.table);
3463        install(1);
3464        let error = runtime
3465            .execute_update_inner_tracked_locked(
3466                sql,
3467                &query,
3468                &compiled,
3469                &ids,
3470                filter.as_ref(),
3471                topology.read(),
3472            )
3473            .err()
3474            .expect("locked recheck must propagate its read failure");
3475        assert!(error.to_string().contains("read memory limit"), "{error}");
3476        install(4096);
3477        assert_ids([1, 2]);
3478        let retried = runtime
3479            .execute_update_inner_tracked_locked(
3480                sql,
3481                &query,
3482                &compiled,
3483                &ids,
3484                filter.as_ref(),
3485                topology.read(),
3486            )
3487            .expect("retry locked recheck");
3488        assert_eq!(retried.0.affected_rows, 2);
3489        assert_ids([11, 12]);
3490    }
3491
3492    #[test]
3493    fn concurrent_constant_updates_leave_one_visible_row_per_logical_id() {
3494        use std::sync::{Arc, Barrier};
3495
3496        const WRITERS: usize = 3;
3497        const ROUNDS: usize = 8;
3498        let rt = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
3499        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3500            .unwrap();
3501        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3502            .unwrap();
3503        let barrier = Arc::new(Barrier::new(WRITERS));
3504        let handles: Vec<_> = (0..WRITERS)
3505            .map(|writer| {
3506                let rt = Arc::clone(&rt);
3507                let barrier = Arc::clone(&barrier);
3508                std::thread::spawn(move || {
3509                    for round in 0..ROUNDS {
3510                        barrier.wait();
3511                        rt.execute_query(&format!(
3512                            "UPDATE capabilities SET observed_at = '{writer}-{round}' WHERE id = 'A'"
3513                        ))
3514                        .unwrap();
3515                    }
3516                })
3517            })
3518            .collect();
3519        for handle in handles {
3520            handle.join().unwrap();
3521        }
3522        let selected = rt
3523            .execute_query("SELECT id, observed_at FROM capabilities WHERE id = 'A'")
3524            .unwrap();
3525        assert_eq!(
3526            selected.result.records.len(),
3527            1,
3528            "concurrent updates published multiple visible versions"
3529        );
3530    }
3531
3532    #[test]
3533    fn locked_constant_updates_preserve_unique_constraints() {
3534        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3535        rt.execute_query("CREATE TABLE accounts (id INT PRIMARY KEY, email TEXT UNIQUE)")
3536            .unwrap();
3537        rt.execute_query("INSERT INTO accounts (id, email) VALUES (1, 'a'), (2, 'b')")
3538            .unwrap();
3539        assert!(rt
3540            .execute_query("UPDATE accounts SET email = 'b' WHERE id = 1")
3541            .is_err());
3542        let selected = rt
3543            .execute_query("SELECT id FROM accounts WHERE email = 'a'")
3544            .unwrap();
3545        assert_eq!(selected.result.records.len(), 1);
3546    }
3547
3548    #[test]
3549    fn concurrent_transactions_do_not_both_commit_the_same_row_update() {
3550        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3551
3552        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3553        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3554            .unwrap();
3555        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3556            .unwrap();
3557        for connection in [41, 42] {
3558            set_current_connection_id(connection);
3559            rt.execute_query("BEGIN").unwrap();
3560        }
3561        set_current_connection_id(41);
3562        rt.execute_query("UPDATE capabilities SET observed_at = 'first' WHERE id = 'A'")
3563            .unwrap();
3564        set_current_connection_id(42);
3565        let competing =
3566            rt.execute_query("UPDATE capabilities SET observed_at = 'second' WHERE id = 'A'");
3567        set_current_connection_id(41);
3568        rt.execute_query("COMMIT").unwrap();
3569        set_current_connection_id(42);
3570        if competing.is_ok() {
3571            assert!(
3572                rt.execute_query("COMMIT").is_err(),
3573                "both writers committed"
3574            );
3575        } else {
3576            rt.execute_query("ROLLBACK").unwrap();
3577        }
3578        clear_current_connection_id();
3579        let selected = rt
3580            .execute_query("SELECT id FROM capabilities WHERE id = 'A'")
3581            .unwrap();
3582        assert_eq!(selected.result.records.len(), 1);
3583    }
3584
3585    #[test]
3586    fn transaction_and_autocommit_update_do_not_publish_two_live_versions() {
3587        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3588
3589        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3590        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3591            .unwrap();
3592        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3593            .unwrap();
3594        set_current_connection_id(41);
3595        rt.execute_query("BEGIN").unwrap();
3596        rt.execute_query("UPDATE capabilities SET observed_at = 'transaction' WHERE id = 'A'")
3597            .unwrap();
3598        clear_current_connection_id();
3599        let autocommit =
3600            rt.execute_query("UPDATE capabilities SET observed_at = 'auto' WHERE id = 'A'");
3601        set_current_connection_id(41);
3602        let commit = rt.execute_query("COMMIT");
3603        clear_current_connection_id();
3604        assert!(
3605            autocommit.is_err() || commit.is_err(),
3606            "conflicting writers both committed"
3607        );
3608        let selected = rt
3609            .execute_query("SELECT id FROM capabilities WHERE id = 'A'")
3610            .unwrap();
3611        assert_eq!(selected.result.records.len(), 1);
3612    }
3613
3614    #[test]
3615    fn transaction_update_does_not_target_rows_created_after_snapshot() {
3616        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3617
3618        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3619        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3620            .unwrap();
3621        set_current_connection_id(41);
3622        rt.execute_query("BEGIN").unwrap();
3623        rt.execute_query("SELECT id FROM capabilities").unwrap();
3624        clear_current_connection_id();
3625        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'after')")
3626            .unwrap();
3627        set_current_connection_id(41);
3628        let updated = rt
3629            .execute_query("UPDATE capabilities SET observed_at = 'changed' WHERE id = 'A'")
3630            .unwrap();
3631        assert_eq!(
3632            updated.affected_rows, 0,
3633            "updated a row outside the transaction snapshot"
3634        );
3635        rt.execute_query("COMMIT").unwrap();
3636        clear_current_connection_id();
3637        let selected = rt
3638            .execute_query("SELECT observed_at FROM capabilities WHERE id = 'A'")
3639            .unwrap();
3640        assert_eq!(selected.result.records.len(), 1);
3641        assert_eq!(
3642            selected.result.records[0].get("observed_at"),
3643            Some(&Value::text("after"))
3644        );
3645    }
3646
3647    #[test]
3648    fn autocommit_update_does_not_filter_on_uncommitted_row_image() {
3649        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3650
3651        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3652        rt.execute_query("CREATE TABLE capabilities (id TEXT, status TEXT, payload TEXT)")
3653            .unwrap();
3654        rt.execute_query(
3655            "INSERT INTO capabilities (id, status, payload) VALUES ('A', 'ready', 'old')",
3656        )
3657        .unwrap();
3658        set_current_connection_id(41);
3659        rt.execute_query("BEGIN").unwrap();
3660        rt.execute_query("UPDATE capabilities SET status = 'busy' WHERE id = 'A'")
3661            .unwrap();
3662        clear_current_connection_id();
3663        let autocommit =
3664            rt.execute_query("UPDATE capabilities SET payload = 'new' WHERE status = 'ready'");
3665        if let Ok(result) = &autocommit {
3666            assert_eq!(
3667                result.affected_rows, 1,
3668                "uncommitted status hid the committed target"
3669            );
3670        }
3671        set_current_connection_id(41);
3672        rt.execute_query("ROLLBACK").unwrap();
3673        clear_current_connection_id();
3674        let selected = rt
3675            .execute_query("SELECT status, payload FROM capabilities WHERE id = 'A'")
3676            .unwrap();
3677        assert_eq!(selected.result.records.len(), 1);
3678        assert_eq!(
3679            selected.result.records[0].get("status"),
3680            Some(&Value::text("ready"))
3681        );
3682        if autocommit.is_ok() {
3683            assert_eq!(
3684                selected.result.records[0].get("payload"),
3685                Some(&Value::text("new"))
3686            );
3687        }
3688    }
3689
3690    #[test]
3691    fn autocommit_update_skips_row_claimed_by_another_transaction() {
3692        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3693
3694        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3695        rt.execute_query("CREATE TABLE capabilities (id INT, rank INT, status TEXT, note TEXT)")
3696            .unwrap();
3697        rt.execute_query("CREATE INDEX capabilities_rank ON capabilities (rank)")
3698            .unwrap();
3699        rt.execute_query(
3700            "INSERT INTO capabilities (id, rank, status, note) VALUES (1, 10, 'ready', 'old')",
3701        )
3702        .unwrap();
3703        set_current_connection_id(41);
3704        rt.execute_query("BEGIN").unwrap();
3705        let claim = rt.execute_query("UPDATE capabilities SET status = 'claimed' WHERE status = 'ready' CLAIM LIMIT 1 ORDER BY rank ASC").unwrap();
3706        assert_eq!(claim.affected_rows, 1);
3707        set_current_connection_id(42);
3708        let other = rt
3709            .execute_query("UPDATE capabilities SET note = 'new' WHERE id = 1")
3710            .unwrap();
3711        assert_eq!(other.affected_rows, 0);
3712        set_current_connection_id(41);
3713        rt.execute_query("ROLLBACK").unwrap();
3714        clear_current_connection_id();
3715        let rows = rt
3716            .execute_query("SELECT status, note FROM capabilities WHERE id = 1")
3717            .unwrap();
3718        assert_eq!(rows.result.records.len(), 1);
3719        assert_eq!(
3720            rows.result.records[0].get("status"),
3721            Some(&Value::text("ready"))
3722        );
3723        assert_eq!(
3724            rows.result.records[0].get("note"),
3725            Some(&Value::text("old"))
3726        );
3727    }
3728
3729    fn persistent_operational_options(path: &Path) -> RedDBOptions {
3730        RedDBOptions::persistent(path)
3731            .with_storage_profile(StorageProfileSelection {
3732                deploy_profile: DeployProfile::Embedded,
3733                packaging: StoragePackaging::OperationalDirectory,
3734                replica_count: 0,
3735                managed_backup: false,
3736                wal_retention: false,
3737            })
3738            .unwrap()
3739    }
3740
3741    fn store_commit_batches(wal_path: &Path) -> Vec<Vec<Vec<u8>>> {
3742        WalReader::open(wal_path)
3743            .expect("wal opens")
3744            .iter()
3745            .map(|record| record.expect("wal record decodes").1)
3746            .filter_map(|record| match record {
3747                WalRecord::TxCommitBatch { actions, .. } => Some(actions),
3748                _ => None,
3749            })
3750            .collect()
3751    }
3752
3753    fn action_contains_text(action: &[u8], needle: &str) -> bool {
3754        action
3755            .windows(needle.len())
3756            .any(|window| window == needle.as_bytes())
3757    }
3758
3759    fn claim_metric_count(
3760        snapshot: &crate::runtime::ClaimTelemetrySnapshot,
3761        metric: &str,
3762        collection: &str,
3763        model: &str,
3764    ) -> u64 {
3765        let rows = match metric {
3766            "attempts" => &snapshot.attempts,
3767            "successful" => &snapshot.successful,
3768            "misses" => &snapshot.misses,
3769            "skipped_locked" => &snapshot.skipped_locked,
3770            other => panic!("unknown claim metric {other}"),
3771        };
3772        rows.iter()
3773            .find(|((actual_collection, actual_model), _)| {
3774                actual_collection == collection && actual_model == model
3775            })
3776            .map(|(_, count)| *count)
3777            .unwrap_or(0)
3778    }
3779
3780    fn assert_statement_writes_collections_in_one_new_wal_batch(
3781        rt: &RedDBRuntime,
3782        wal_path: &Path,
3783        statement: &str,
3784        source: &str,
3785        event_queue: &str,
3786    ) {
3787        let before_batches = store_commit_batches(wal_path).len();
3788
3789        rt.execute_query(statement).unwrap();
3790
3791        let batches = store_commit_batches(wal_path);
3792        let statement_batches = &batches[before_batches..];
3793        let source_batch = statement_batches
3794            .iter()
3795            .position(|actions| {
3796                actions.iter().any(|action| {
3797                    action_contains_text(action, source)
3798                        && !action_contains_text(action, event_queue)
3799                })
3800            })
3801            .expect("source collection write batch is present");
3802        let event_batch = statement_batches
3803            .iter()
3804            .position(|actions| {
3805                actions
3806                    .iter()
3807                    .any(|action| action_contains_text(action, event_queue))
3808            })
3809            .expect("event queue write batch is present");
3810
3811        assert_eq!(
3812            source_batch, event_batch,
3813            "WITH EVENTS must persist the source write and queue event in the same WAL batch"
3814        );
3815    }
3816
3817    #[test]
3818    fn with_events_autocommit_persists_mutation_and_event_in_one_wal_batch() {
3819        let dir = tempfile::tempdir().unwrap();
3820        let db_path = dir.path().join("events_dual_write.rdb");
3821        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3822        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3823
3824        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
3825            .unwrap();
3826        assert_statement_writes_collections_in_one_new_wal_batch(
3827            &rt,
3828            &wal_path,
3829            "INSERT INTO users (id, email) VALUES (1, 'a@example.test')",
3830            "users",
3831            "users_events",
3832        );
3833    }
3834
3835    #[test]
3836    fn with_events_autocommit_update_persists_mutation_and_event_in_one_wal_batch() {
3837        let dir = tempfile::tempdir().unwrap();
3838        let db_path = dir.path().join("events_update_atomic.rdb");
3839        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3840        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3841
3842        rt.execute_query(
3843            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (UPDATE) TO user_updates",
3844        )
3845        .unwrap();
3846        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
3847            .unwrap();
3848
3849        assert_statement_writes_collections_in_one_new_wal_batch(
3850            &rt,
3851            &wal_path,
3852            "UPDATE users SET email = 'b@example.test' WHERE id = 1",
3853            "users",
3854            "user_updates",
3855        );
3856    }
3857
3858    #[test]
3859    fn with_events_autocommit_delete_persists_mutation_and_event_in_one_wal_batch() {
3860        let dir = tempfile::tempdir().unwrap();
3861        let db_path = dir.path().join("events_delete_atomic.rdb");
3862        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3863        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3864
3865        rt.execute_query(
3866            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (DELETE) TO user_deletes",
3867        )
3868        .unwrap();
3869        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
3870            .unwrap();
3871
3872        assert_statement_writes_collections_in_one_new_wal_batch(
3873            &rt,
3874            &wal_path,
3875            "DELETE FROM users WHERE id = 1",
3876            "users",
3877            "user_deletes",
3878        );
3879    }
3880
3881    #[test]
3882    fn update_where_id_in_with_hash_index_updates_expected_rows() {
3883        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3884        rt.execute_query("CREATE TABLE users (id INT, score INT)")
3885            .unwrap();
3886        for id in 0..5 {
3887            rt.execute_query(&format!("INSERT INTO users (id, score) VALUES ({id}, 0)"))
3888                .unwrap();
3889        }
3890        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
3891            .unwrap();
3892
3893        let updated = rt
3894            .execute_query("UPDATE users SET score = 42 WHERE id IN (1,3,4)")
3895            .unwrap();
3896        assert_eq!(updated.affected_rows, 3);
3897
3898        let selected = rt
3899            .execute_query("SELECT id, score FROM users ORDER BY id")
3900            .unwrap();
3901        let scores: Vec<(i64, i64)> = selected
3902            .result
3903            .records
3904            .iter()
3905            .map(|record| {
3906                let id = match record.get("id").unwrap() {
3907                    Value::Integer(value) => *value,
3908                    other => panic!("expected integer id, got {other:?}"),
3909                };
3910                let score = match record.get("score").unwrap() {
3911                    Value::Integer(value) => *value,
3912                    other => panic!("expected integer score, got {other:?}"),
3913                };
3914                (id, score)
3915            })
3916            .collect();
3917        assert_eq!(scores, vec![(0, 0), (1, 42), (2, 0), (3, 42), (4, 42)]);
3918    }
3919
3920    /// Drives UPDATE through the shared `DmlTargetScan` module — the
3921    /// same code path DELETE uses (#51, #52). Exercises the indexed
3922    /// equality fast-path (WHERE id = N with a HASH index), the
3923    /// unindexed range scan (WHERE score > N), and the no-WHERE
3924    /// full-scan branch to confirm the extracted "find target rows"
3925    /// loop preserves affected-row counts and the resulting row state.
3926    #[test]
3927    fn update_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
3928        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3929        rt.execute_query("CREATE TABLE items (id INT, score INT)")
3930            .unwrap();
3931        for id in 0..5 {
3932            rt.execute_query(&format!(
3933                "INSERT INTO items (id, score) VALUES ({id}, {})",
3934                id * 10
3935            ))
3936            .unwrap();
3937        }
3938        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
3939            .unwrap();
3940
3941        // Indexed equality UPDATE — hits the hash fast-path inside
3942        // DmlTargetScan::find_target_ids. id=2 has score=20, drop it
3943        // below the score>25 cutoff so the next assertion stays clean.
3944        let updated_one = rt
3945            .execute_query("UPDATE items SET score = 5 WHERE id = 2")
3946            .unwrap();
3947        assert_eq!(updated_one.affected_rows, 1);
3948
3949        // Unindexed scan UPDATE — bumps everyone with score > 25,
3950        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
3951        // zoned/full-scan branch.
3952        let updated_many = rt
3953            .execute_query("UPDATE items SET score = 7 WHERE score > 25")
3954            .unwrap();
3955        assert_eq!(updated_many.affected_rows, 2);
3956
3957        let snapshot = rt
3958            .execute_query("SELECT id, score FROM items ORDER BY id")
3959            .unwrap();
3960        let pairs: Vec<(i64, i64)> = snapshot
3961            .result
3962            .records
3963            .iter()
3964            .map(|record| {
3965                let id = match record.get("id").unwrap() {
3966                    Value::Integer(value) => *value,
3967                    other => panic!("expected integer id, got {other:?}"),
3968                };
3969                let score = match record.get("score").unwrap() {
3970                    Value::Integer(value) => *value,
3971                    other => panic!("expected integer score, got {other:?}"),
3972                };
3973                (id, score)
3974            })
3975            .collect();
3976        assert_eq!(pairs, vec![(0, 0), (1, 10), (2, 5), (3, 7), (4, 7)]);
3977
3978        // Full-scan UPDATE with no WHERE rewrites every remaining row.
3979        let updated_all = rt.execute_query("UPDATE items SET score = 1").unwrap();
3980        assert_eq!(updated_all.affected_rows, 5);
3981        let after = rt
3982            .execute_query("SELECT score FROM items ORDER BY id")
3983            .unwrap();
3984        let scores: Vec<i64> = after
3985            .result
3986            .records
3987            .iter()
3988            .map(|record| match record.get("score").unwrap() {
3989                Value::Integer(value) => *value,
3990                other => panic!("expected integer score, got {other:?}"),
3991            })
3992            .collect();
3993        assert_eq!(scores, vec![1, 1, 1, 1, 1]);
3994    }
3995
3996    /// Drives DELETE through the new `DmlTargetScan` module. Exercises
3997    /// both the index fast-path (WHERE id = N with a HASH index) and
3998    /// the unindexed scan path (WHERE score > N) to confirm the
3999    /// extracted "find target rows" loop preserves the affected-row
4000    /// count and which rows survive.
4001    #[test]
4002    fn delete_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
4003        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4004        rt.execute_query("CREATE TABLE items (id INT, score INT)")
4005            .unwrap();
4006        for id in 0..5 {
4007            rt.execute_query(&format!(
4008                "INSERT INTO items (id, score) VALUES ({id}, {})",
4009                id * 10
4010            ))
4011            .unwrap();
4012        }
4013        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
4014            .unwrap();
4015
4016        // Indexed equality DELETE — hits the hash fast-path inside
4017        // DmlTargetScan::find_target_ids.
4018        let deleted_one = rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
4019        assert_eq!(deleted_one.affected_rows, 1);
4020
4021        // Unindexed scan DELETE — drops everyone with score > 25,
4022        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
4023        // zoned/full-scan branch.
4024        let deleted_many = rt
4025            .execute_query("DELETE FROM items WHERE score > 25")
4026            .unwrap();
4027        assert_eq!(deleted_many.affected_rows, 2);
4028
4029        let surviving = rt
4030            .execute_query("SELECT id FROM items ORDER BY id")
4031            .unwrap();
4032        let ids: Vec<i64> = surviving
4033            .result
4034            .records
4035            .iter()
4036            .map(|record| match record.get("id").unwrap() {
4037                Value::Integer(value) => *value,
4038                other => panic!("expected integer id, got {other:?}"),
4039            })
4040            .collect();
4041        assert_eq!(ids, vec![0, 1]);
4042
4043        // Sanity: full-scan DELETE with no WHERE clears the rest.
4044        let deleted_rest = rt.execute_query("DELETE FROM items").unwrap();
4045        assert_eq!(deleted_rest.affected_rows, 2);
4046        let empty = rt.execute_query("SELECT id FROM items").unwrap();
4047        assert!(empty.result.records.is_empty());
4048    }
4049
4050    /// CollectionContract gate (#49 + #50): APPEND ONLY tables accept
4051    /// INSERT but reject UPDATE and DELETE with the documented
4052    /// operator-facing error strings. Drives all three DML verbs so
4053    /// the centralized gate is exercised end-to-end.
4054    #[test]
4055    fn collection_contract_gate_blocks_update_and_delete_on_append_only() {
4056        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4057        rt.execute_query("CREATE TABLE events (id INT, payload TEXT) APPEND ONLY")
4058            .unwrap();
4059
4060        // INSERT must succeed — APPEND ONLY exists precisely to allow
4061        // appends. The gate should be a no-op for INSERT.
4062        let inserted = rt
4063            .execute_query("INSERT INTO events (id, payload) VALUES (1, 'hello')")
4064            .unwrap();
4065        assert_eq!(inserted.affected_rows, 1);
4066
4067        // UPDATE is rejected with the gate's UPDATE-specific message.
4068        let update_err = rt
4069            .execute_query("UPDATE events SET payload = 'mut' WHERE id = 1")
4070            .unwrap_err();
4071        let msg = format!("{update_err}");
4072        assert!(
4073            msg.contains("APPEND ONLY") && msg.contains("UPDATE is rejected"),
4074            "expected UPDATE rejection message, got: {msg}"
4075        );
4076
4077        // DELETE is rejected with the gate's DELETE-specific message.
4078        let delete_err = rt
4079            .execute_query("DELETE FROM events WHERE id = 1")
4080            .unwrap_err();
4081        let msg = format!("{delete_err}");
4082        assert!(
4083            msg.contains("APPEND ONLY") && msg.contains("DELETE is rejected"),
4084            "expected DELETE rejection message, got: {msg}"
4085        );
4086
4087        // Row should still be present — neither rejected mutation
4088        // touched storage.
4089        let surviving = rt.execute_query("SELECT id FROM events").unwrap();
4090        assert_eq!(surviving.result.records.len(), 1);
4091    }
4092
4093    /// CollectionContract gate: tables without an APPEND ONLY contract
4094    /// permit INSERT, UPDATE, and DELETE — the gate's default branch
4095    /// is a true pass-through, not an accidental block.
4096    #[test]
4097    fn collection_contract_gate_allows_all_verbs_on_unrestricted_table() {
4098        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4099        rt.execute_query("CREATE TABLE notes (id INT, body TEXT)")
4100            .unwrap();
4101
4102        rt.execute_query("INSERT INTO notes (id, body) VALUES (1, 'a')")
4103            .unwrap();
4104        let updated = rt
4105            .execute_query("UPDATE notes SET body = 'b' WHERE id = 1")
4106            .unwrap();
4107        assert_eq!(updated.affected_rows, 1);
4108        let deleted = rt.execute_query("DELETE FROM notes WHERE id = 1").unwrap();
4109        assert_eq!(deleted.affected_rows, 1);
4110    }
4111
4112    #[test]
4113    fn insert_into_event_enabled_table_emits_event_to_configured_queue() {
4114        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4115        rt.execute_query(
4116            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (INSERT) TO audit_log",
4117        )
4118        .unwrap();
4119
4120        let inserted = rt
4121            .execute_query("INSERT INTO users (id, email) VALUES (7, 'a@example.com')")
4122            .unwrap();
4123        assert_eq!(inserted.affected_rows, 1);
4124
4125        let events = queue_payloads(&rt, "audit_log");
4126        assert_eq!(events.len(), 1);
4127        let event = events[0].as_object().expect("event payload object");
4128        assert!(event
4129            .get("event_id")
4130            .and_then(crate::json::Value::as_str)
4131            .is_some_and(|value| !value.is_empty()));
4132        assert_eq!(
4133            event.get("op").and_then(crate::json::Value::as_str),
4134            Some("insert")
4135        );
4136        assert_eq!(
4137            event.get("collection").and_then(crate::json::Value::as_str),
4138            Some("users")
4139        );
4140        assert_eq!(
4141            event.get("id").and_then(crate::json::Value::as_u64),
4142            Some(7)
4143        );
4144        assert!(event
4145            .get("ts")
4146            .and_then(crate::json::Value::as_u64)
4147            .is_some());
4148        assert!(event
4149            .get("lsn")
4150            .and_then(crate::json::Value::as_u64)
4151            .is_some());
4152        assert!(matches!(
4153            event.get("tenant"),
4154            Some(crate::json::Value::Null)
4155        ));
4156        assert!(matches!(
4157            event.get("before"),
4158            Some(crate::json::Value::Null)
4159        ));
4160        let after = event
4161            .get("after")
4162            .and_then(crate::json::Value::as_object)
4163            .expect("after object");
4164        assert_eq!(
4165            after.get("id").and_then(crate::json::Value::as_u64),
4166            Some(7)
4167        );
4168        assert_eq!(
4169            after.get("email").and_then(crate::json::Value::as_str),
4170            Some("a@example.com")
4171        );
4172    }
4173
4174    #[test]
4175    fn multi_row_insert_emits_one_insert_event_per_row_in_order() {
4176        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4177        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4178            .unwrap();
4179
4180        rt.execute_query(
4181            "INSERT INTO users (id, email) VALUES (1, 'a@example.com'), (2, 'b@example.com')",
4182        )
4183        .unwrap();
4184
4185        let events = queue_payloads(&rt, "users_events");
4186        assert_eq!(events.len(), 2);
4187        let mut previous_lsn = 0;
4188        for (event, expected_id) in events.iter().zip([1_u64, 2]) {
4189            let object = event.as_object().expect("event payload object");
4190            assert_eq!(
4191                object.get("op").and_then(crate::json::Value::as_str),
4192                Some("insert")
4193            );
4194            assert_eq!(
4195                object.get("id").and_then(crate::json::Value::as_u64),
4196                Some(expected_id)
4197            );
4198            let lsn = object
4199                .get("lsn")
4200                .and_then(crate::json::Value::as_u64)
4201                .expect("event lsn");
4202            assert!(
4203                lsn > previous_lsn,
4204                "event LSNs should increase in row order"
4205            );
4206            previous_lsn = lsn;
4207            let after = object
4208                .get("after")
4209                .and_then(crate::json::Value::as_object)
4210                .expect("after object");
4211            assert_eq!(
4212                after.get("id").and_then(crate::json::Value::as_u64),
4213                Some(expected_id)
4214            );
4215        }
4216    }
4217
4218    #[test]
4219    fn claim_metrics_increment_skipped_locked_without_counting_miss() {
4220        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
4221        rt.execute_query("CREATE TABLE claim_metric_locked (id INT, rank INT, status TEXT)")
4222            .expect("create table");
4223        // ADR 0063: index-backed claim ordering on `rank`.
4224        rt.execute_query("CREATE INDEX idx_claim_metric_locked_rank ON claim_metric_locked (rank)")
4225            .expect("create index");
4226        rt.execute_query(
4227            "INSERT INTO claim_metric_locked (id, rank, status) VALUES \
4228             (1, 10, 'ready'), (2, 20, 'ready')",
4229        )
4230        .expect("insert rows");
4231
4232        let claim_lock = rt
4233            .inner
4234            .rmw_locks
4235            .lock_for("claim_metric_locked", "__table_claim_update__");
4236        let _guard = claim_lock.lock();
4237        let updated = rt
4238            .execute_query(
4239                "UPDATE claim_metric_locked SET status = 'claimed' WHERE status = 'ready' \
4240                 CLAIM LIMIT 2 ORDER BY rank ASC",
4241            )
4242            .expect("claim skips locked candidates");
4243
4244        assert_eq!(updated.affected_rows, 0);
4245        let snapshot = rt.claim_telemetry_snapshot();
4246        assert_eq!(
4247            claim_metric_count(&snapshot, "attempts", "claim_metric_locked", "table"),
4248            1
4249        );
4250        assert_eq!(
4251            claim_metric_count(&snapshot, "skipped_locked", "claim_metric_locked", "table"),
4252            2
4253        );
4254        assert_eq!(
4255            claim_metric_count(&snapshot, "misses", "claim_metric_locked", "table"),
4256            0
4257        );
4258        assert_eq!(
4259            snapshot.skipped_locked.len(),
4260            1,
4261            "skipped-lock labels stay bounded to collection/model"
4262        );
4263    }
4264
4265    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
4266        let result = rt
4267            .execute_query(&format!("QUEUE PEEK {queue} 10"))
4268            .expect("peek queue");
4269        result
4270            .result
4271            .records
4272            .iter()
4273            .map(
4274                |record| match record.get("payload").expect("payload column") {
4275                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
4276                    other => panic!("expected JSON queue payload, got {other:?}"),
4277                },
4278            )
4279            .collect()
4280    }
4281
4282    // ── #112: auto-index user `id` on first insert ─────────────────────
4283
4284    /// First insert into a fresh collection that carries a column named
4285    /// `id` registers an implicit HASH index on `id`. Subsequent inserts
4286    /// populate it transparently, and `WHERE id = N` lookups exercise
4287    /// the hash-index fast path in `DmlTargetScan::find_target_ids`.
4288    ///
4289    /// This is the load-bearing acceptance test for #112 — without the
4290    /// hook, `find_index_for_column` returns `None` and DELETE/UPDATE
4291    /// fall through to a full segment scan (the 4× perf gap documented
4292    /// in `docs/perf/delete-sequential-2026-05-06.md`).
4293    #[test]
4294    fn auto_index_id_fires_on_first_insert() {
4295        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4296        rt.execute_query("CREATE TABLE bench_users (id INT, score INT)")
4297            .unwrap();
4298
4299        // Pre-condition: no index on `id` yet.
4300        assert!(
4301            rt.index_store_ref()
4302                .find_index_for_column("bench_users", "id")
4303                .is_none(),
4304            "freshly created collection should not have an `id` index"
4305        );
4306
4307        // Single-row INSERT — drives `MutationEngine::append_one`.
4308        rt.execute_query("INSERT INTO bench_users (id, score) VALUES (1, 10)")
4309            .unwrap();
4310
4311        // Post-condition: hash index registered on `id`.
4312        let registered = rt
4313            .index_store_ref()
4314            .find_index_for_column("bench_users", "id")
4315            .expect("auto-index hook should have registered idx_id on first insert");
4316        assert_eq!(registered.name, "idx_id");
4317        assert_eq!(registered.collection, "bench_users");
4318        assert_eq!(registered.columns, vec!["id".to_string()]);
4319        assert!(matches!(
4320            registered.method,
4321            super::super::index_store::IndexMethodKind::Hash
4322        ));
4323
4324        // Subsequent inserts populate the index; `WHERE id = N` should
4325        // resolve via the hash fast path and round-trip every row.
4326        for id in 2..=5 {
4327            rt.execute_query(&format!(
4328                "INSERT INTO bench_users (id, score) VALUES ({id}, {})",
4329                id * 10
4330            ))
4331            .unwrap();
4332        }
4333        for id in 1..=5 {
4334            let result = rt
4335                .execute_query(&format!("SELECT score FROM bench_users WHERE id = {id}"))
4336                .unwrap();
4337            assert_eq!(
4338                result.result.records.len(),
4339                1,
4340                "id={id} should match one row"
4341            );
4342        }
4343
4344        // Delete via the hash fast-path — exactly the bench scenario the
4345        // perf doc identified as the 4× regression. With the index
4346        // present, `find_target_ids` short-circuits before
4347        // `for_each_entity_zoned` runs.
4348        let deleted = rt
4349            .execute_query("DELETE FROM bench_users WHERE id = 3")
4350            .unwrap();
4351        assert_eq!(deleted.affected_rows, 1);
4352    }
4353
4354    /// Bulk INSERT (the multi-row VALUES path) drives
4355    /// `MutationEngine::append_batch`. The hook must fire there too —
4356    /// otherwise the batch entry points (gRPC binary bulk, HTTP bulk,
4357    /// wire bulk INSERT) skip auto-indexing entirely.
4358    #[test]
4359    fn auto_index_id_fires_on_first_bulk_insert() {
4360        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4361        rt.execute_query("CREATE TABLE bench_bulk (id INT, score INT)")
4362            .unwrap();
4363
4364        rt.execute_query("INSERT INTO bench_bulk (id, score) VALUES (1, 10), (2, 20), (3, 30)")
4365            .unwrap();
4366
4367        let registered = rt
4368            .index_store_ref()
4369            .find_index_for_column("bench_bulk", "id")
4370            .expect("auto-index hook should fire on first bulk insert");
4371        assert_eq!(registered.name, "idx_id");
4372
4373        // Every row populated via `index_entity_insert_batch`.
4374        for id in 1..=3 {
4375            let result = rt
4376                .execute_query(&format!("SELECT score FROM bench_bulk WHERE id = {id}"))
4377                .unwrap();
4378            assert_eq!(result.result.records.len(), 1);
4379        }
4380    }
4381
4382    /// Hook is a no-op when the row carries no `id` column. Conservative
4383    /// match (case-sensitive `id`) — `Id`, `ID`, and `rid`
4384    /// don't trigger it.
4385    #[test]
4386    fn auto_index_id_skips_when_no_id_column() {
4387        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4388        rt.execute_query("CREATE TABLE plain (uid INT, label TEXT)")
4389            .unwrap();
4390        rt.execute_query("INSERT INTO plain (uid, label) VALUES (1, 'a')")
4391            .unwrap();
4392
4393        assert!(rt
4394            .index_store_ref()
4395            .find_index_for_column("plain", "id")
4396            .is_none());
4397        assert!(rt
4398            .index_store_ref()
4399            .find_index_for_column("plain", "uid")
4400            .is_none());
4401    }
4402
4403    /// Hook only fires once per collection. If an explicit
4404    /// `CREATE INDEX ... USING BTREE` already covers `id`, the hook
4405    /// detects it via `find_index_for_column` and does NOT clobber it
4406    /// with a HASH index on the next insert.
4407    #[test]
4408    fn auto_index_id_skips_when_index_already_exists() {
4409        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4410        rt.execute_query("CREATE TABLE pre (id INT, score INT)")
4411            .unwrap();
4412        // User-declared BTREE index on `id` before any insert.
4413        rt.execute_query("CREATE INDEX user_idx ON pre (id) USING BTREE")
4414            .unwrap();
4415        rt.execute_query("INSERT INTO pre (id, score) VALUES (1, 10)")
4416            .unwrap();
4417
4418        let registered = rt
4419            .index_store_ref()
4420            .find_index_for_column("pre", "id")
4421            .expect("user index should still be there");
4422        assert_eq!(
4423            registered.name, "user_idx",
4424            "auto-index hook must not overwrite an existing index"
4425        );
4426    }
4427
4428    /// Implicit `idx_id` is reaped when the collection drops. The
4429    /// existing `execute_drop_table` walks `list_indices` and drops every
4430    /// entry — confirm the auto-created index participates.
4431    #[test]
4432    fn auto_index_id_dropped_with_collection() {
4433        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4434        rt.execute_query("CREATE TABLE ephemeral (id INT, score INT)")
4435            .unwrap();
4436        rt.execute_query("INSERT INTO ephemeral (id, score) VALUES (1, 10)")
4437            .unwrap();
4438        assert!(rt
4439            .index_store_ref()
4440            .find_index_for_column("ephemeral", "id")
4441            .is_some());
4442
4443        rt.execute_query("DROP TABLE ephemeral").unwrap();
4444
4445        assert!(
4446            rt.index_store_ref()
4447                .find_index_for_column("ephemeral", "id")
4448                .is_none(),
4449            "implicit `idx_id` must be reaped when its collection drops"
4450        );
4451    }
4452
4453    /// Opt-out via `RedDBOptions::with_auto_index_id(false)` (which
4454    /// forwards to `UnifiedStoreConfig::auto_index_id`). With the knob
4455    /// off, first insert leaves the collection without an `id` index —
4456    /// DELETE/UPDATE fall back to the scan path.
4457    #[test]
4458    fn auto_index_id_disabled_by_config() {
4459        let opts = RedDBOptions::in_memory().with_auto_index_id(false);
4460        let rt = RedDBRuntime::with_options(opts).unwrap();
4461
4462        rt.execute_query("CREATE TABLE off (id INT, score INT)")
4463            .unwrap();
4464        rt.execute_query("INSERT INTO off (id, score) VALUES (1, 10)")
4465            .unwrap();
4466
4467        assert!(
4468            rt.index_store_ref()
4469                .find_index_for_column("off", "id")
4470                .is_none(),
4471            "with auto_index_id=false, no implicit index should be created"
4472        );
4473    }
4474
4475    // ── #293: UPDATE / DELETE events ─────────────────────────────────────
4476
4477    #[test]
4478    fn update_single_row_emits_update_event() {
4479        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4480        rt.execute_query(
4481            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO audit_log",
4482        )
4483        .unwrap();
4484        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4485            .unwrap();
4486
4487        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
4488            .unwrap();
4489
4490        let events = queue_payloads(&rt, "audit_log");
4491        assert_eq!(events.len(), 1, "expected exactly 1 update event");
4492        let event = events[0].as_object().expect("event payload object");
4493        assert_eq!(
4494            event.get("op").and_then(crate::json::Value::as_str),
4495            Some("update")
4496        );
4497        assert_eq!(
4498            event.get("collection").and_then(crate::json::Value::as_str),
4499            Some("users")
4500        );
4501        assert!(event
4502            .get("event_id")
4503            .and_then(crate::json::Value::as_str)
4504            .is_some_and(|v| !v.is_empty()));
4505        let before = event
4506            .get("before")
4507            .and_then(crate::json::Value::as_object)
4508            .expect("before must be an object");
4509        let after = event
4510            .get("after")
4511            .and_then(crate::json::Value::as_object)
4512            .expect("after must be an object");
4513        assert_eq!(
4514            before.get("name").and_then(crate::json::Value::as_str),
4515            Some("Alice"),
4516            "before.name should be the old value"
4517        );
4518        assert_eq!(
4519            after.get("name").and_then(crate::json::Value::as_str),
4520            Some("Bob"),
4521            "after.name should be the new value"
4522        );
4523    }
4524
4525    #[test]
4526    fn update_event_only_includes_changed_fields() {
4527        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4528        rt.execute_query(
4529            "CREATE TABLE users (id INT, name TEXT, email TEXT) WITH EVENTS (UPDATE) TO evts",
4530        )
4531        .unwrap();
4532        rt.execute_query("INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'a@x.com')")
4533            .unwrap();
4534
4535        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
4536            .unwrap();
4537
4538        let events = queue_payloads(&rt, "evts");
4539        assert_eq!(events.len(), 1);
4540        let event = events[0].as_object().unwrap();
4541        let before = event
4542            .get("before")
4543            .and_then(crate::json::Value::as_object)
4544            .unwrap();
4545        let after = event
4546            .get("after")
4547            .and_then(crate::json::Value::as_object)
4548            .unwrap();
4549        // Only changed field included.
4550        assert!(
4551            before.contains_key("name"),
4552            "before must include changed field"
4553        );
4554        assert!(
4555            after.contains_key("name"),
4556            "after must include changed field"
4557        );
4558        // Unchanged fields must not appear.
4559        assert!(
4560            !before.contains_key("email"),
4561            "before must not include unchanged email"
4562        );
4563        assert!(
4564            !after.contains_key("email"),
4565            "after must not include unchanged email"
4566        );
4567    }
4568
4569    #[test]
4570    fn multi_row_update_emits_one_event_per_row() {
4571        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4572        rt.execute_query("CREATE TABLE items (id INT, status TEXT) WITH EVENTS (UPDATE) TO evts")
4573            .unwrap();
4574        rt.execute_query(
4575            "INSERT INTO items (id, status) VALUES (1, 'new'), (2, 'new'), (3, 'new')",
4576        )
4577        .unwrap();
4578
4579        rt.execute_query("UPDATE items SET status = 'done'")
4580            .unwrap();
4581
4582        let events = queue_payloads(&rt, "evts");
4583        assert_eq!(events.len(), 3, "expected one update event per row");
4584        for event in &events {
4585            let obj = event.as_object().unwrap();
4586            assert_eq!(
4587                obj.get("op").and_then(crate::json::Value::as_str),
4588                Some("update")
4589            );
4590        }
4591    }
4592
4593    #[test]
4594    fn delete_single_row_emits_delete_event() {
4595        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4596        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (DELETE) TO del_log")
4597            .unwrap();
4598        rt.execute_query("INSERT INTO users (id, name) VALUES (42, 'Alice')")
4599            .unwrap();
4600
4601        rt.execute_query("DELETE FROM users WHERE id = 42").unwrap();
4602
4603        let events = queue_payloads(&rt, "del_log");
4604        assert_eq!(events.len(), 1);
4605        let event = events[0].as_object().expect("event payload object");
4606        assert_eq!(
4607            event.get("op").and_then(crate::json::Value::as_str),
4608            Some("delete")
4609        );
4610        assert_eq!(
4611            event.get("collection").and_then(crate::json::Value::as_str),
4612            Some("users")
4613        );
4614        assert!(event
4615            .get("event_id")
4616            .and_then(crate::json::Value::as_str)
4617            .is_some_and(|v| !v.is_empty()));
4618        let before = event
4619            .get("before")
4620            .and_then(crate::json::Value::as_object)
4621            .expect("before must be an object for delete");
4622        assert_eq!(
4623            before.get("id").and_then(crate::json::Value::as_u64),
4624            Some(42)
4625        );
4626        assert_eq!(
4627            before.get("name").and_then(crate::json::Value::as_str),
4628            Some("Alice")
4629        );
4630        assert!(matches!(event.get("after"), Some(crate::json::Value::Null)));
4631    }
4632
4633    #[test]
4634    fn multi_row_delete_emits_one_event_per_row() {
4635        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4636        rt.execute_query("CREATE TABLE items (id INT, val INT) WITH EVENTS (DELETE) TO del_log")
4637            .unwrap();
4638        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 10), (2, 20), (3, 30)")
4639            .unwrap();
4640
4641        rt.execute_query("DELETE FROM items").unwrap();
4642
4643        let events = queue_payloads(&rt, "del_log");
4644        assert_eq!(events.len(), 3, "expected one delete event per deleted row");
4645        for event in &events {
4646            let obj = event.as_object().unwrap();
4647            assert_eq!(
4648                obj.get("op").and_then(crate::json::Value::as_str),
4649                Some("delete")
4650            );
4651            assert!(matches!(obj.get("after"), Some(crate::json::Value::Null)));
4652        }
4653    }
4654
4655    #[test]
4656    fn ops_filter_update_does_not_emit_on_insert_or_delete() {
4657        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4658        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO evts")
4659            .unwrap();
4660
4661        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4662            .unwrap();
4663        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
4664
4665        let events = queue_payloads(&rt, "evts");
4666        assert!(
4667            events.is_empty(),
4668            "UPDATE-only filter must not emit INSERT or DELETE events"
4669        );
4670    }
4671
4672    // ── SUPPRESS EVENTS ────────────────────────────────────────────────────
4673
4674    #[test]
4675    fn suppress_events_on_insert_emits_no_events() {
4676        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4677        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4678            .unwrap();
4679
4680        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4681            .unwrap();
4682
4683        let events = queue_payloads(&rt, "evts");
4684        assert!(
4685            events.is_empty(),
4686            "SUPPRESS EVENTS must prevent INSERT events"
4687        );
4688    }
4689
4690    #[test]
4691    fn suppress_events_on_update_emits_no_events() {
4692        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4693        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4694            .unwrap();
4695        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4696            .unwrap();
4697        // drain the INSERT event
4698        let _ = queue_payloads(&rt, "evts");
4699        // Force pop to drain; simpler: just check new count after UPDATE
4700        rt.execute_query("QUEUE PURGE evts").unwrap();
4701
4702        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1 SUPPRESS EVENTS")
4703            .unwrap();
4704
4705        let events = queue_payloads(&rt, "evts");
4706        assert!(
4707            events.is_empty(),
4708            "SUPPRESS EVENTS must prevent UPDATE events"
4709        );
4710    }
4711
4712    #[test]
4713    fn suppress_events_on_delete_emits_no_events() {
4714        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4715        rt.execute_query(
4716            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (INSERT, DELETE) TO evts",
4717        )
4718        .unwrap();
4719        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4720            .unwrap();
4721
4722        rt.execute_query("DELETE FROM users WHERE id = 1 SUPPRESS EVENTS")
4723            .unwrap();
4724
4725        let events = queue_payloads(&rt, "evts");
4726        assert!(
4727            events.is_empty(),
4728            "SUPPRESS EVENTS must prevent DELETE events"
4729        );
4730    }
4731
4732    #[test]
4733    fn normal_insert_after_suppress_still_emits() {
4734        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4735        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4736            .unwrap();
4737
4738        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4739            .unwrap();
4740        rt.execute_query("INSERT INTO users (id, name) VALUES (2, 'Bob')")
4741            .unwrap();
4742
4743        let events = queue_payloads(&rt, "evts");
4744        assert_eq!(
4745            events.len(),
4746            1,
4747            "only the non-suppressed INSERT should emit"
4748        );
4749        assert_eq!(
4750            events[0].get("id").and_then(crate::json::Value::as_u64),
4751            Some(2)
4752        );
4753    }
4754}