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        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
1989        // Issue #523 — blockchain collections are immutable. Reject before
1990        // RLS / RETURNING work so the operator sees a clean 409-mapped
1991        // error instead of a partially-applied mutation surface.
1992        if crate::runtime::blockchain_kind::try_is_chain(
1993            self.inner.db.store().as_ref(),
1994            &query.table,
1995        )? {
1996            return Err(RedDBError::InvalidOperation(format!(
1997                "BlockchainCollectionImmutable: UPDATE not allowed on '{}'",
1998                query.table
1999            )));
2000        }
2001        // Queue-shaped CLAIM (ADR 0020, #1609): a CLAIM on a queue collection
2002        // is a QueueLifecycle delivery acquisition, not a raw row UPDATE.
2003        // Route it through the lifecycle seam before the table-shaped
2004        // contract / RLS gates below (which would reject an UPDATE against a
2005        // queue's declared model) so QueueLifecycle stays the sole authority
2006        // for delivery state.
2007        if query.claim_limit.is_some() && self.is_queue_collection(&query.table) {
2008            return self.execute_queue_shaped_claim(raw_query, query);
2009        }
2010        // ADR 0067 (#1711): the DOCUMENTS / ROWS / KV UPDATE markers were
2011        // removed. Resolve the model of an unmarked UPDATE from the catalog so
2012        // a document collection routes to document semantics and a KV
2013        // collection keeps its key-immutability guard, and gate dotted SET
2014        // targets that only a document body can satisfy. Runs before the
2015        // contract / RLS gates so every downstream path — the inner scan,
2016        // RETURNING — observes the resolved target.
2017        let inferred_owned;
2018        let query = match self.resolve_unmarked_update_target(query)? {
2019            Some(rewritten) => {
2020                inferred_owned = rewritten;
2021                &inferred_owned
2022            }
2023            None => query,
2024        };
2025        // CollectionContract gate (#50): runs the APPEND ONLY guard
2026        // (and any future contract bits) before RLS / RETURNING work
2027        // so the operator's immutability declaration is honoured
2028        // uniformly and the error message points at the DDL rather
2029        // than at a downstream symptom.
2030        crate::runtime::collection_contract::CollectionContractGate::check(
2031            self,
2032            &query.table,
2033            crate::runtime::collection_contract::MutationKind::Update,
2034        )?;
2035        ensure_update_target_contract(self, &query.table, query.target)?;
2036        ensure_kv_key_update_target_allowed(query)?;
2037        ensure_graph_identity_update_target_allowed(query)?;
2038
2039        // Apply RLS augmentation first so every downstream path — plain
2040        // UPDATE, UPDATE...RETURNING, the inner scan — observes the
2041        // same policy-filtered target set. This prevents RETURNING
2042        // from ever exposing rows the UPDATE policy would have
2043        // denied.
2044        let rls_gated = crate::runtime::impl_core::rls_is_enabled(self, &query.table);
2045        let augmented_query: UpdateQuery;
2046        let effective_query: &UpdateQuery = if rls_gated {
2047            let update_filter = crate::runtime::impl_core::rls_policy_filter(
2048                self,
2049                &query.table,
2050                reddb_rql::ast::PolicyAction::Update,
2051            );
2052            let Some(mut policy) = update_filter else {
2053                // No admitting policy: zero rows affected, empty
2054                // RETURNING (never leak rows the caller can't touch).
2055                let mut response = RuntimeQueryResult::dml_result(
2056                    raw_query.to_string(),
2057                    0,
2058                    "update",
2059                    "runtime-dml-rls",
2060                );
2061                if let Some(items) = query.returning.clone() {
2062                    response.result = build_returning_result(&items, &[], None);
2063                }
2064                return Ok(response);
2065            };
2066            if query.claim_limit.is_some() {
2067                let read_filter = crate::runtime::impl_core::rls_policy_filter(
2068                    self,
2069                    &query.table,
2070                    reddb_rql::ast::PolicyAction::Select,
2071                );
2072                let Some(read_policy) = read_filter else {
2073                    let mut response = RuntimeQueryResult::dml_result(
2074                        raw_query.to_string(),
2075                        0,
2076                        "update",
2077                        "runtime-dml-rls",
2078                    );
2079                    if let Some(items) = query.returning.clone() {
2080                        response.result = build_returning_result(&items, &[], None);
2081                    }
2082                    return Ok(response);
2083                };
2084                policy = reddb_rql::ast::Filter::And(Box::new(read_policy), Box::new(policy));
2085            }
2086            let mut augmented = query.clone();
2087            augmented.filter = Some(match augmented.filter.take() {
2088                Some(existing) => reddb_rql::ast::Filter::And(Box::new(existing), Box::new(policy)),
2089                None => policy,
2090            });
2091            augmented_query = augmented;
2092            &augmented_query
2093        } else {
2094            query
2095        };
2096
2097        // RETURNING wraps the inner executor and uses the touched-id
2098        // list the inner reports so the post-image reflects exactly
2099        // the rows the UPDATE actually mutated (not whatever a
2100        // separate SELECT might have observed).
2101        if let Some(items) = effective_query.returning.clone() {
2102            let mut inner_query = effective_query.clone();
2103            inner_query.returning = None;
2104            let (mut response, touched_ids) =
2105                self.execute_update_inner_tracked(raw_query, &inner_query)?;
2106
2107            let mut snapshots = if matches!(
2108                effective_query.target,
2109                UpdateTarget::Nodes | UpdateTarget::Edges
2110            ) {
2111                graph_update_returning_snapshots(self, &effective_query.table, &touched_ids)
2112            } else {
2113                super::dml_target_scan::DmlTargetScan::new(self, &effective_query.table, None, None)
2114                    .row_snapshots(&touched_ids)?
2115            };
2116            if matches!(effective_query.target, UpdateTarget::Kv) {
2117                restore_kv_returning_keys(
2118                    self,
2119                    &effective_query.table,
2120                    &touched_ids,
2121                    &mut snapshots,
2122                );
2123            }
2124
2125            response.result = build_returning_result(&items, &snapshots, None);
2126            response.engine = "runtime-dml-returning";
2127            return Ok(response);
2128        }
2129
2130        self.execute_update_inner(raw_query, effective_query)
2131    }
2132
2133    /// Back-compat shim: the older entry point ignored touched ids.
2134    fn execute_update_inner(
2135        &self,
2136        raw_query: &str,
2137        query: &UpdateQuery,
2138    ) -> RedDBResult<RuntimeQueryResult> {
2139        self.execute_update_inner_tracked(raw_query, query)
2140            .map(|(res, _)| res)
2141    }
2142
2143    /// Enforce the concurrent-claim ORDER BY index-gate (ADR 0063, #1607).
2144    ///
2145    /// A `CLAIM LIMIT n` / `CLAIM EXACT n` on a logical-identity model (tables
2146    /// and documents) must order its candidates through a compatible index; the
2147    /// planner rejects an ordering no index on the collection can serve rather
2148    /// than falling back to a broad write-path sort. KV (key identity) and graph
2149    /// nodes/edges are exempt — their claim identity is intrinsic, not a user
2150    /// ORDER BY column that needs a secondary index.
2151    fn enforce_claim_order_by_index_gate(&self, query: &UpdateQuery) -> RedDBResult<()> {
2152        if query.claim_limit.is_none()
2153            || !matches!(query.target, UpdateTarget::Rows | UpdateTarget::Documents)
2154        {
2155            return Ok(());
2156        }
2157        let available_indexes: Vec<Vec<String>> = self
2158            .index_store_ref()
2159            .list_indices(&query.table)
2160            .into_iter()
2161            .map(|index| index.columns)
2162            .collect();
2163        reddb_rql::planner::check_claim_order_by_index_gate(query, &available_indexes)
2164            .map_err(RedDBError::InvalidOperation)
2165    }
2166
2167    fn execute_update_inner_tracked(
2168        &self,
2169        raw_query: &str,
2170        query: &UpdateQuery,
2171    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2172        self.enforce_claim_order_by_index_gate(query)?;
2173        let store = self.inner.db.store();
2174        let topology_lock = self
2175            .index_store_ref()
2176            .collection_topology_lock(&query.table);
2177        let effective_filter = effective_update_filter(query);
2178        let compiled_plan = self.compile_update_plan(query)?;
2179        // Autocommit table-row UPDATE replaces an MVCC version even when its
2180        // assignments are constants. Resolve the current pre-image under the
2181        // RMW lock. Explicit transactions keep their statement snapshot and
2182        // first-committer-wins conflict detection.
2183        let autocommit_table_update =
2184            matches!(query.target, UpdateTarget::Rows) && self.current_xid().is_none();
2185        let needs_rmw_lock = autocommit_table_update || update_needs_rmw_lock(query);
2186        let claim_model = update_model_name(update_target_model(query.target));
2187        if query.claim_limit.is_some() {
2188            self.inner
2189                .claim_telemetry
2190                .record_attempt(&query.table, claim_model);
2191        }
2192        let claim_lock = query.claim_limit.map(|_| {
2193            self.inner
2194                .rmw_locks
2195                .lock_for(&query.table, "__table_claim_update__")
2196        });
2197        let _claim_guard = if let Some(lock) = claim_lock.as_ref() {
2198            let Some(guard) = lock.try_lock() else {
2199                let skipped_locked = query.claim_limit.unwrap_or(1);
2200                self.inner.claim_telemetry.record_skipped_locked(
2201                    &query.table,
2202                    claim_model,
2203                    skipped_locked,
2204                );
2205                tracing::debug!(
2206                    target: "reddb::claim",
2207                    collection = %query.table,
2208                    model = claim_model,
2209                    skipped_locked,
2210                    "concurrent claim skipped locked candidates"
2211                );
2212                return Ok((
2213                    RuntimeQueryResult::dml_result(
2214                        raw_query.to_string(),
2215                        0,
2216                        "update",
2217                        "runtime-dml",
2218                    ),
2219                    Vec::new(),
2220                ));
2221            };
2222            Some(guard)
2223        } else {
2224            None
2225        };
2226        let table_rmw_lock = if needs_rmw_lock {
2227            Some(
2228                self.inner
2229                    .rmw_locks
2230                    .lock_for(&query.table, "__table_rmw_update__"),
2231            )
2232        } else {
2233            None
2234        };
2235        let _table_rmw_guard = table_rmw_lock.as_ref().map(|lock| lock.lock());
2236        let mut touched_ids: Vec<EntityId> = Vec::new();
2237        let claim_cap = query.claim_limit.map(|limit| limit as usize);
2238        let limit_cap = claim_cap.or_else(|| query.limit.map(|limit| limit as usize));
2239        let manager = store
2240            .get_collection(&query.table)
2241            .ok_or_else(|| RedDBError::NotFound(query.table.clone()))?;
2242        let scan_limit = if query.order_by.is_empty() {
2243            limit_cap
2244        } else {
2245            None
2246        };
2247        let mut target_scan = super::dml_target_scan::DmlTargetScan::with_update_target(
2248            self,
2249            &query.table,
2250            effective_filter.as_ref(),
2251            scan_limit,
2252            query.target,
2253        );
2254        if needs_rmw_lock && !autocommit_table_update {
2255            target_scan = target_scan.with_live_table_rows();
2256        }
2257        let ids_to_update = {
2258            let _topology_guard = topology_lock.read();
2259            // The statement snapshot predates the table lock. Refresh it
2260            // after acquiring that lock so earlier autocommits are visible,
2261            // but never select an uncommitted physical tip. Historical
2262            // versions can be absent from current indexes while a writer is
2263            // active, so retain the snapshot-aware index fallback then.
2264            let _fresh_snapshot = if autocommit_table_update {
2265                let mut ctx =
2266                    crate::runtime::impl_core::capture_current_snapshot().unwrap_or_else(|| {
2267                        let manager = self.snapshot_manager();
2268                        crate::runtime::impl_core::SnapshotContext {
2269                            branch: None,
2270                            snapshot: manager.fresh_read_snapshot(),
2271                            manager,
2272                            own_xids: std::collections::HashSet::new(),
2273                            requires_index_fallback: false,
2274                            hidden_writers_only: false,
2275                            serializable_reader: None,
2276                        }
2277                    });
2278                // A writer of this table still in flight would be hidden from
2279                // the fresh snapshot and force a scan for the targets. It takes
2280                // milliseconds; the scan takes far longer.
2281                ctx.manager
2282                    .await_real_writers_of(&query.table, std::time::Duration::from_millis(100));
2283                ctx.snapshot = ctx.manager.fresh_read_snapshot();
2284                ctx.branch = self.vcs_branch_read_view(&ctx.snapshot, None)?;
2285                if !ctx.requires_index_fallback
2286                    && ctx.manager.snapshot_hides_real_writers(&ctx.snapshot)
2287                {
2288                    ctx.requires_index_fallback = true;
2289                    ctx.hidden_writers_only = true;
2290                }
2291                Some(crate::runtime::impl_core::CurrentSnapshotGuard::install(
2292                    ctx,
2293                ))
2294            } else {
2295                None
2296            };
2297            target_scan.find_target_ids()?
2298        };
2299        let order_limit = if query.claim_limit.is_some() {
2300            None
2301        } else {
2302            limit_cap
2303        };
2304        let ids_to_update = if query.order_by.is_empty() {
2305            ids_to_update
2306        } else {
2307            ordered_update_target_ids(&manager, &ids_to_update, &query.order_by, order_limit)?
2308        };
2309        let mut ids_to_update = if query.claim_limit.is_some() || autocommit_table_update {
2310            self.filter_claim_locked_target_ids(&query.table, ids_to_update)?
2311        } else {
2312            ids_to_update
2313        };
2314        if let Some(claim_cap) = claim_cap {
2315            ids_to_update.truncate(claim_cap);
2316        }
2317        if query.claim_exact
2318            && claim_cap.is_some_and(|claim_count| ids_to_update.len() < claim_count)
2319        {
2320            self.inner
2321                .claim_telemetry
2322                .record_miss(&query.table, claim_model);
2323            return Ok((
2324                RuntimeQueryResult::dml_result(raw_query.to_string(), 0, "update", "runtime-dml"),
2325                Vec::new(),
2326            ));
2327        }
2328
2329        // Cover the interval from post-image preparation through storage and
2330        // secondary-index publication. Target selection above remains indexed.
2331        let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(&query.table);
2332        if needs_rmw_lock {
2333            let result = self.execute_update_inner_tracked_locked(
2334                raw_query,
2335                query,
2336                &compiled_plan,
2337                &ids_to_update,
2338                effective_filter.as_ref(),
2339            )?;
2340            if query.claim_limit.is_some() {
2341                self.record_pending_claim_locks_for_touched_ids(&query.table, &result.1);
2342            }
2343            record_claim_outcome(
2344                &self.inner.claim_telemetry,
2345                query.claim_limit,
2346                &query.table,
2347                claim_model,
2348                result.0.affected_rows,
2349            );
2350            return Ok(result);
2351        }
2352
2353        // Keep topology fixed while reserving every post-image. No chunk is
2354        // published until all targets fit; a later denial cannot leave earlier
2355        // autocommit chunks visible. Prepared payload is bounded by admission.
2356        let topology_guard = topology_lock.read();
2357        let mut prepared = Vec::new();
2358        let mut reservations = super::memory_admission::MutationMemoryReservations::new(self);
2359        for chunk in ids_to_update.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2360            for id in chunk {
2361                #[cfg(test)]
2362                self.index_store_ref().mutation_test_hook(
2363                    &query.table,
2364                    super::index_store::MutationTestPhase::DmlPostImageCandidate,
2365                );
2366                super::query_budget::charge(1)?;
2367                let Some(entity) = manager.try_get(*id, usize::MAX)? else {
2368                    continue;
2369                };
2370                let assignments =
2371                    self.materialize_update_assignments_for_entity(query, &entity, &compiled_plan)?;
2372                let applied = self.apply_materialized_update_for_entity(
2373                    query,
2374                    entity,
2375                    &compiled_plan,
2376                    assignments,
2377                )?;
2378                reservations.admit(&applied)?;
2379                touched_ids.push(applied.id);
2380                prepared.push(applied);
2381            }
2382        }
2383        self.validate_graph_changes(
2384            &query.table,
2385            &prepared.iter().map(|item| &item.entity).collect::<Vec<_>>(),
2386            &prepared
2387                .iter()
2388                .map(|item| {
2389                    item.replaced_entity
2390                        .as_ref()
2391                        .map_or(item.id, |entity| entity.id)
2392                })
2393                .collect::<Vec<_>>(),
2394        )?;
2395        let affected = prepared.len() as u64;
2396        let mut published = 0;
2397        let mut _durable_publication = None;
2398        let persistence = (|| -> RedDBResult<()> {
2399            super::query_budget::charge(0)?;
2400            // Standalone UNIQUE keys are admitted for the whole statement
2401            // before any chunk is published.
2402            self.enforce_unique_update_post_images(&query.table, &compiled_plan, &prepared)?;
2403            // This is the cancellation boundary. Once durable publication
2404            // starts, finish the prepared statement rather than exposing a
2405            // timeout with only a prefix of its chunks committed.
2406            _durable_publication = Some(super::query_budget::begin_durable_publication()?);
2407            for chunk in prepared.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2408                if compiled_plan.row_touches_unique_columns
2409                    || compiled_plan
2410                        .row_contract_plan
2411                        .as_ref()
2412                        .is_some_and(|plan| plan.has_expressions)
2413                {
2414                    let db = self.db();
2415                    let contract = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(self, &db, &query.table);
2416                    for item in chunk {
2417                        let fields =
2418                            crate::application::ports::entity_row_fields_snapshot(&item.entity);
2419                        let previous_id =
2420                            item.replaced_entity.as_ref().map_or(item.id, |old| old.id);
2421                        let previous = (!item.pre_mutation_fields.is_empty())
2422                            .then_some(item.pre_mutation_fields.as_slice());
2423                        contract.enforce_updated_row_uniqueness(
2424                            &fields,
2425                            previous,
2426                            Some(previous_id),
2427                        )?;
2428                    }
2429                }
2430                self.persist_update_chunk(chunk)?;
2431                published += chunk.len();
2432            }
2433            Ok(())
2434        })();
2435        // A later storage/constraint error must still finish index and CDC
2436        // maintenance for earlier published chunks, as the chunked path did.
2437        let published_mutations = &prepared[..published];
2438        let lsns = self.flush_update_chunk(published_mutations, topology_guard)?;
2439        if !query.suppress_events {
2440            self.emit_update_events_for_collection(&query.table, published_mutations, &lsns)?;
2441        }
2442        persistence?;
2443        drop(reservations);
2444
2445        if affected > 0 {
2446            self.note_table_write(&query.table);
2447        }
2448        if query.claim_limit.is_some() {
2449            self.record_pending_claim_locks_for_touched_ids(&query.table, &touched_ids);
2450        }
2451        record_claim_outcome(
2452            &self.inner.claim_telemetry,
2453            query.claim_limit,
2454            &query.table,
2455            claim_model,
2456            affected,
2457        );
2458
2459        Ok((
2460            RuntimeQueryResult::dml_result(
2461                raw_query.to_string(),
2462                affected,
2463                "update",
2464                "runtime-dml",
2465            ),
2466            touched_ids,
2467        ))
2468    }
2469
2470    fn filter_claim_locked_target_ids(
2471        &self,
2472        table: &str,
2473        ids: Vec<EntityId>,
2474    ) -> RedDBResult<Vec<EntityId>> {
2475        let conn_id = current_connection_id();
2476        let locks = self.inner.pending_claim_locks.read();
2477        if locks.is_empty() {
2478            return Ok(ids);
2479        }
2480        let mut admitted = Vec::with_capacity(ids.len());
2481        for id in ids {
2482            super::query_budget::charge(1)?;
2483            if let Some(entity) = self.inner.db.store().try_get(table, id, usize::MAX)? {
2484                let key = (table.to_string(), entity.logical_id());
2485                if locks.get(&key).is_none_or(|owner| *owner == conn_id) {
2486                    admitted.push(id);
2487                }
2488            }
2489        }
2490        Ok(admitted)
2491    }
2492
2493    fn record_pending_claim_locks_for_touched_ids(&self, table: &str, ids: &[EntityId]) {
2494        if self.current_xid().is_none() || ids.is_empty() {
2495            return;
2496        }
2497
2498        let conn_id = current_connection_id();
2499        let store = self.inner.db.store();
2500        let mut locks = self.inner.pending_claim_locks.write();
2501        for id in ids {
2502            let Some(entity) = store.get(table, *id) else {
2503                continue;
2504            };
2505            locks.insert((table.to_string(), entity.logical_id()), conn_id);
2506        }
2507    }
2508
2509    fn execute_update_inner_tracked_locked(
2510        &self,
2511        raw_query: &str,
2512        query: &UpdateQuery,
2513        compiled_plan: &CompiledUpdatePlan,
2514        ids_to_update: &[EntityId],
2515        effective_filter: Option<&Filter>,
2516    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2517        // Existing table/claim locks precede topology; per-row RMW locks
2518        // below follow it. Keep the same index set through persistence/flush.
2519        let topology_lock = self
2520            .index_store_ref()
2521            .collection_topology_lock(&query.table);
2522        let topology_guard = topology_lock.read();
2523        let store = self.inner.db.store();
2524        let mut touched_ids = Vec::new();
2525        let mut lock_entries = Vec::new();
2526
2527        for id in ids_to_update {
2528            super::query_budget::charge(1)?;
2529            let Some(candidate) = store.try_get(&query.table, *id, usize::MAX)? else {
2530                continue;
2531            };
2532            let logical_id = candidate.logical_id();
2533            let lock_key = super::RmwLockTable::row_key(logical_id);
2534            let rmw_lock = self.inner.rmw_locks.lock_for(&query.table, &lock_key);
2535            lock_entries.push((lock_key, logical_id, rmw_lock));
2536        }
2537
2538        lock_entries.sort_by(|left, right| left.0.cmp(&right.0));
2539        lock_entries.dedup_by(|left, right| left.0 == right.0);
2540        let _rmw_guards: Vec<_> = lock_entries.iter().map(|entry| entry.2.lock()).collect();
2541
2542        let mut applied_chunk = Vec::new();
2543        let mut reservations = super::memory_admission::MutationMemoryReservations::new(self);
2544        for (_, logical_id, _) in &lock_entries {
2545            #[cfg(test)]
2546            self.index_store_ref().mutation_test_hook(
2547                &query.table,
2548                super::index_store::MutationTestPhase::DmlPostImageCandidate,
2549            );
2550            super::query_budget::charge(1)?;
2551            let Some(entity) =
2552                try_resolve_update_entity_by_logical_id(self, &query.table, *logical_id)?
2553            else {
2554                continue;
2555            };
2556            if let Some(filter) = effective_filter {
2557                if !crate::runtime::query_exec::evaluate_entity_filter_result_with_db(
2558                    Some(self.inner.db.as_ref()),
2559                    &entity,
2560                    filter,
2561                    &query.table,
2562                    &query.table,
2563                )? {
2564                    continue;
2565                }
2566            }
2567
2568            let assignments =
2569                self.materialize_update_assignments_for_entity(query, &entity, compiled_plan)?;
2570            let applied = self.apply_materialized_update_for_entity(
2571                query,
2572                entity,
2573                compiled_plan,
2574                assignments,
2575            )?;
2576            reservations.admit(&applied)?;
2577            touched_ids.push(applied.id);
2578            applied_chunk.push(applied);
2579        }
2580
2581        self.validate_graph_changes(
2582            &query.table,
2583            &applied_chunk
2584                .iter()
2585                .map(|item| &item.entity)
2586                .collect::<Vec<_>>(),
2587            &applied_chunk
2588                .iter()
2589                .map(|item| {
2590                    item.replaced_entity
2591                        .as_ref()
2592                        .map_or(item.id, |entity| entity.id)
2593                })
2594                .collect::<Vec<_>>(),
2595        )?;
2596        let affected = applied_chunk.len() as u64;
2597        let mut published = 0;
2598        let mut _durable_publication = None;
2599        let persistence = (|| -> RedDBResult<()> {
2600            super::query_budget::charge(0)?;
2601            self.enforce_unique_update_post_images(&query.table, compiled_plan, &applied_chunk)?;
2602            // Final cooperative checkpoint before the first durable chunk.
2603            // Cancellation after this point cannot safely abort a prefix.
2604            _durable_publication = Some(super::query_budget::begin_durable_publication()?);
2605            for chunk in applied_chunk.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2606                if compiled_plan.row_touches_unique_columns
2607                    || compiled_plan
2608                        .row_contract_plan
2609                        .as_ref()
2610                        .is_some_and(|plan| plan.has_expressions)
2611                {
2612                    let db = self.db();
2613                    let contract = crate::application::collection_contract_enforcer::CollectionContractWriteEnforcer::new(self, &db, &query.table);
2614                    for item in chunk {
2615                        let fields =
2616                            crate::application::ports::entity_row_fields_snapshot(&item.entity);
2617                        let previous_id =
2618                            item.replaced_entity.as_ref().map_or(item.id, |old| old.id);
2619                        let previous = (!item.pre_mutation_fields.is_empty())
2620                            .then_some(item.pre_mutation_fields.as_slice());
2621                        contract.enforce_updated_row_uniqueness(
2622                            &fields,
2623                            previous,
2624                            Some(previous_id),
2625                        )?;
2626                    }
2627                }
2628                self.persist_update_chunk(chunk)?;
2629                published += chunk.len();
2630            }
2631            Ok(())
2632        })();
2633        // Earlier chunks may have been published when a later constraint
2634        // check fails. Finish their indexes and events before returning it.
2635        let published_mutations = &applied_chunk[..published];
2636        let lsns = self.flush_update_chunk(published_mutations, topology_guard)?;
2637        if !query.suppress_events {
2638            self.emit_update_events_for_collection(&query.table, published_mutations, &lsns)?;
2639        }
2640        persistence?;
2641
2642        if affected > 0 {
2643            self.note_table_write(&query.table);
2644        }
2645
2646        Ok((
2647            RuntimeQueryResult::dml_result(
2648                raw_query.to_string(),
2649                affected,
2650                "update",
2651                "runtime-dml",
2652            ),
2653            touched_ids,
2654        ))
2655    }
2656
2657    fn enforce_unique_update_post_images(
2658        &self,
2659        collection: &str,
2660        compiled_plan: &CompiledUpdatePlan,
2661        applied: &[AppliedEntityMutation],
2662    ) -> RedDBResult<()> {
2663        if !compiled_plan.touches_unique_index {
2664            return Ok(());
2665        }
2666        let post_images: Vec<_> = applied
2667            .iter()
2668            .map(|item| {
2669                (
2670                    item.replaced_entity.as_ref().map_or(item.id, |old| old.id),
2671                    crate::application::ports::entity_row_fields_snapshot(&item.entity),
2672                )
2673            })
2674            .collect();
2675        self.enforce_unique_updates(collection, &post_images)
2676    }
2677
2678    fn compile_update_plan(&self, query: &UpdateQuery) -> RedDBResult<CompiledUpdatePlan> {
2679        let mut static_field_assignments = Vec::new();
2680        let mut static_metadata_assignments = Vec::new();
2681        let mut dynamic_assignments = Vec::new();
2682        let row_contract_plan = build_row_update_contract_plan(&self.db(), &query.table)?;
2683        let mut row_modified_columns = Vec::new();
2684
2685        for (idx, (column, expr)) in query.assignment_exprs.iter().enumerate() {
2686            let compound_op = query.compound_assignment_ops.get(idx).copied().flatten();
2687            let metadata_key = resolve_sql_ttl_metadata_key(column);
2688            if compound_op.is_some() && metadata_key.is_some() {
2689                return Err(RedDBError::Query(format!(
2690                    "compound assignment is only supported for row fields: {column}"
2691                )));
2692            }
2693            if compound_op.is_none() {
2694                if let Ok(value) = fold_expr_to_value(expr.clone()) {
2695                    // Without a declared type, a text constant may overwrite an
2696                    // existing Secret. Resolve it per row to preserve encryption.
2697                    let unknown_text_target = metadata_key.is_none()
2698                        && matches!(value, Value::Text(_))
2699                        && row_contract_plan
2700                            .as_ref()
2701                            .and_then(|plan| plan.declared_rules.get(column))
2702                            .is_none();
2703                    if !unknown_text_target {
2704                        if let Some(metadata_key) = metadata_key {
2705                            let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2706                            let (canonical_key, canonical_value) =
2707                                canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2708                            static_metadata_assignments
2709                                .push((canonical_key.to_string(), canonical_value));
2710                        } else {
2711                            let is_secret_column = row_contract_plan
2712                                .as_ref()
2713                                .and_then(|plan| plan.declared_rules.get(column))
2714                                .is_some_and(|rule| {
2715                                    rule.data_type == reddb_types::DataType::Secret
2716                                });
2717                            let value =
2718                                self.resolve_secret_column_value(value, is_secret_column)?;
2719                            static_field_assignments.push((
2720                                column.clone(),
2721                                normalize_row_update_assignment_with_plan(
2722                                    &query.table,
2723                                    column,
2724                                    value,
2725                                    row_contract_plan.as_ref(),
2726                                )?,
2727                            ));
2728                            row_modified_columns.push(column.clone());
2729                        }
2730                        continue;
2731                    }
2732                }
2733            }
2734
2735            dynamic_assignments.push(CompiledUpdateAssignment {
2736                column: column.clone(),
2737                expr: expr.clone(),
2738                compound_op,
2739                metadata_key,
2740                row_rule: if metadata_key.is_none() {
2741                    if let Some(plan) = row_contract_plan.as_ref() {
2742                        if plan.timestamps_enabled
2743                            && (column == "created_at" || column == "updated_at")
2744                        {
2745                            return Err(RedDBError::Query(format!(
2746                                "collection '{}' manages '{}' automatically — do not set it in UPDATE",
2747                                query.table, column
2748                            )));
2749                        }
2750                        if let Some(rule) = plan.declared_rules.get(column) {
2751                            Some(rule.clone())
2752                        } else if plan.strict_schema {
2753                            return Err(RedDBError::Query(format!(
2754                                "collection '{}' is strict and does not allow undeclared fields: {}",
2755                                query.table, column
2756                            )));
2757                        } else {
2758                            None
2759                        }
2760                    } else {
2761                        None
2762                    }
2763                } else {
2764                    None
2765                },
2766            });
2767            if metadata_key.is_none() {
2768                row_modified_columns.push(column.clone());
2769            }
2770        }
2771
2772        let row_modified_columns = dedupe_update_columns(row_modified_columns);
2773        let row_touches_unique_columns = row_contract_plan.as_ref().is_some_and(|plan| {
2774            row_modified_columns.iter().any(|column| {
2775                plan.unique_columns
2776                    .keys()
2777                    .any(|unique| unique.eq_ignore_ascii_case(column))
2778            })
2779        });
2780
2781        let touches_unique_index = self
2782            .index_store_ref()
2783            .touches_unique_index(&query.table, &row_modified_columns);
2784
2785        if let Some(ttl_ms) = query.ttl_ms {
2786            static_metadata_assignments
2787                .push(("_ttl_ms".to_string(), metadata_u64_to_value(ttl_ms)));
2788        }
2789        if let Some(expires_at_ms) = query.expires_at_ms {
2790            static_metadata_assignments.push((
2791                "_expires_at".to_string(),
2792                metadata_u64_to_value(expires_at_ms),
2793            ));
2794        }
2795        for (key, val) in &query.with_metadata {
2796            static_metadata_assignments.push((key.clone(), storage_value_to_metadata_value(val)));
2797        }
2798
2799        Ok(CompiledUpdatePlan {
2800            static_field_assignments,
2801            static_metadata_assignments,
2802            dynamic_assignments,
2803            row_contract_plan,
2804            row_modified_columns,
2805            row_touches_unique_columns,
2806            touches_unique_index,
2807        })
2808    }
2809
2810    fn materialize_update_assignments_for_entity(
2811        &self,
2812        query: &UpdateQuery,
2813        entity: &UnifiedEntity,
2814        compiled_plan: &CompiledUpdatePlan,
2815    ) -> RedDBResult<MaterializedUpdateAssignments> {
2816        let mut assignments = MaterializedUpdateAssignments::default();
2817        let mut record: Option<UnifiedRecord> = None;
2818
2819        for assignment in &compiled_plan.dynamic_assignments {
2820            if assignment.compound_op.is_some()
2821                && !matches!(
2822                    entity.data,
2823                    EntityData::Row(_) | EntityData::Node(_) | EntityData::Edge(_)
2824                )
2825            {
2826                return Err(RedDBError::Query(format!(
2827                    "compound assignment is only supported for row or graph UPDATE column '{}'",
2828                    assignment.column
2829                )));
2830            }
2831            if record.is_none() {
2832                record = runtime_any_record_from_entity_ref(entity);
2833            }
2834            let Some(record) = record.as_ref() else {
2835                return Err(RedDBError::Query(format!(
2836                    "UPDATE could not materialize runtime record for entity {} in '{}'",
2837                    entity.id.raw(),
2838                    query.table
2839                )));
2840            };
2841            let rhs = super::expr_eval::try_evaluate_runtime_expr_with_db(
2842                Some(self.inner.db.as_ref()),
2843                &assignment.expr,
2844                record,
2845                Some(query.table.as_str()),
2846                Some(query.table.as_str()),
2847            )?
2848            .ok_or_else(|| {
2849                RedDBError::Query(format!(
2850                    "failed to evaluate UPDATE expression for column '{}'",
2851                    assignment.column
2852                ))
2853            })?;
2854            let value = if let Some(op) = assignment.compound_op {
2855                evaluate_compound_update_assignment(&assignment.column, record, op, rhs)?
2856            } else {
2857                rhs
2858            };
2859
2860            let sensitive = super::join_filter::expression_uses_secret(
2861                &assignment.expr,
2862                record,
2863                Some(&query.table),
2864                Some(&query.table),
2865            );
2866            let secret_target = assignment
2867                .row_rule
2868                .as_ref()
2869                .is_some_and(|rule| rule.data_type == reddb_types::DataType::Secret)
2870                || record
2871                    .get(&assignment.column)
2872                    .is_some_and(|value| matches!(value, Value::Secret(_)));
2873            if sensitive && !secret_target {
2874                return Err(RedDBError::Query(
2875                    "secret-derived UPDATE values require a SECRET target column".into(),
2876                ));
2877            }
2878            if let Some(metadata_key) = assignment.metadata_key {
2879                let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2880                let (canonical_key, canonical_value) =
2881                    canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2882                assignments
2883                    .dynamic_metadata_assignments
2884                    .push((canonical_key.to_string(), canonical_value));
2885            } else {
2886                assignments.dynamic_field_assignments.push((
2887                    assignment.column.clone(),
2888                    normalize_row_update_value_for_rule(
2889                        &query.table,
2890                        self.resolve_secret_column_value(
2891                            value,
2892                            assignment.row_rule.as_ref().is_some_and(|rule| {
2893                                rule.data_type == reddb_types::DataType::Secret
2894                            }) || record
2895                                .get(&assignment.column)
2896                                .is_some_and(|value| matches!(value, Value::Secret(_))),
2897                        )?,
2898                        assignment.row_rule.as_ref(),
2899                    )?,
2900                ));
2901            }
2902        }
2903
2904        Ok(assignments)
2905    }
2906
2907    fn apply_materialized_update_for_entity(
2908        &self,
2909        query: &UpdateQuery,
2910        entity: UnifiedEntity,
2911        compiled_plan: &CompiledUpdatePlan,
2912        mut assignments: MaterializedUpdateAssignments,
2913    ) -> RedDBResult<AppliedEntityMutation> {
2914        if matches!(query.target, UpdateTarget::Kv)
2915            && !compiled_plan
2916                .static_field_assignments
2917                .iter()
2918                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
2919            && !assignments
2920                .dynamic_field_assignments
2921                .iter()
2922                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
2923        {
2924            if let Some(key) = runtime_any_record_from_entity_ref(&entity)
2925                .and_then(|record| record.get("key").cloned())
2926            {
2927                assignments
2928                    .dynamic_field_assignments
2929                    .push(("key".to_string(), key));
2930            }
2931        }
2932        if matches!(entity.data, EntityData::Row(_)) {
2933            return self.apply_loaded_sql_update_row_core(
2934                query.table.clone(),
2935                entity,
2936                &compiled_plan.static_field_assignments,
2937                assignments.dynamic_field_assignments,
2938                &compiled_plan.static_metadata_assignments,
2939                assignments.dynamic_metadata_assignments,
2940                compiled_plan.row_contract_plan.as_ref(),
2941                &compiled_plan.row_modified_columns,
2942                compiled_plan.row_touches_unique_columns,
2943            );
2944        }
2945
2946        ensure_graph_identity_update_allowed(&entity, compiled_plan, &assignments)?;
2947
2948        let operations = build_patch_operations_from_materialized_assignments(
2949            &entity,
2950            compiled_plan,
2951            assignments,
2952        );
2953        self.apply_loaded_patch_entity_core(
2954            query.table.clone(),
2955            entity,
2956            crate::json::Value::Null,
2957            operations,
2958        )
2959    }
2960
2961    /// Execute DELETE FROM table WHERE filter
2962    pub fn execute_delete(
2963        &self,
2964        raw_query: &str,
2965        query: &DeleteQuery,
2966    ) -> RedDBResult<RuntimeQueryResult> {
2967        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2968        let branch_store = self.db().store();
2969        let _branch_publication = (self.vcs_is_versioned(&query.table)?
2970            || self.has_graph_contract(&query.table))
2971        .then(|| branch_store.vault_publication_lock.lock());
2972        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
2973            self,
2974            &query.table,
2975        );
2976        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2977        // Issue #523 — blockchain collections are immutable; see
2978        // execute_update for the same gate.
2979        if crate::runtime::blockchain_kind::try_is_chain(
2980            self.inner.db.store().as_ref(),
2981            &query.table,
2982        )? {
2983            return Err(RedDBError::InvalidOperation(format!(
2984                "BlockchainCollectionImmutable: DELETE not allowed on '{}'",
2985                query.table
2986            )));
2987        }
2988        // CollectionContract gate (#50) — see execute_update for
2989        // rationale. The gate handles APPEND ONLY rejection and is
2990        // the single point where future contract bits land.
2991        crate::runtime::collection_contract::CollectionContractGate::check(
2992            self,
2993            &query.table,
2994            crate::runtime::collection_contract::MutationKind::Delete,
2995        )?;
2996
2997        // RETURNING on DELETE: capture the pre-image via an internal
2998        // SELECT that reuses the same WHERE, then run the delete with
2999        // the RETURNING clause stripped, then project the captured
3000        // rows through the requested items. The extra SELECT is a
3001        // pragmatic MVP — a future pass can fuse the scan with the
3002        // delete to avoid the second pass over the heap.
3003        if let Some(items) = query.returning.clone() {
3004            let select_sql = delete_to_select_sql(raw_query).ok_or_else(|| {
3005                RedDBError::Query(
3006                    "DELETE ... RETURNING: cannot rewrite query for pre-image scan".to_string(),
3007                )
3008            })?;
3009            let captured = self.execute_query(&select_sql)?;
3010
3011            let mut inner_query = query.clone();
3012            inner_query.returning = None;
3013            let _ = self.execute_delete(raw_query, &inner_query)?;
3014
3015            let snapshots: Vec<Vec<(String, Value)>> = captured
3016                .result
3017                .records
3018                .iter()
3019                .map(|rec| {
3020                    rec.iter_fields()
3021                        .map(|(k, v)| (k.as_ref().to_string(), v.clone()))
3022                        .collect()
3023                })
3024                .collect();
3025            let affected = snapshots.len() as u64;
3026            let result = build_returning_result(&items, &snapshots, None);
3027
3028            let mut response = RuntimeQueryResult::dml_result(
3029                raw_query.to_string(),
3030                affected,
3031                "delete",
3032                "runtime-dml-returning",
3033            );
3034            response.result = result;
3035            return Ok(response);
3036        }
3037        // Row-Level Security enforcement (Phase 2.5.2 PG parity).
3038        //
3039        // When the table has RLS enabled, gate the DELETE by the
3040        // per-role policy set: mutations only touch rows that *every*
3041        // matching `FOR DELETE` policy would accept. No policies =>
3042        // zero rows affected (PG restrictive-default).
3043        if crate::runtime::impl_core::rls_is_enabled(self, &query.table) {
3044            let rls_filter = crate::runtime::impl_core::rls_policy_filter(
3045                self,
3046                &query.table,
3047                reddb_rql::ast::PolicyAction::Delete,
3048            );
3049            let Some(policy) = rls_filter else {
3050                return Ok(RuntimeQueryResult::dml_result(
3051                    raw_query.to_string(),
3052                    0,
3053                    "delete",
3054                    "runtime-dml-rls",
3055                ));
3056            };
3057            // Fold the policy predicate into the user's WHERE before
3058            // dispatching — the remainder of this function reads the
3059            // filter from `query` via `effective_delete_filter`, which
3060            // respects the updated value.
3061            let mut augmented = query.clone();
3062            augmented.filter = Some(match augmented.filter.take() {
3063                Some(existing) => reddb_rql::ast::Filter::And(Box::new(existing), Box::new(policy)),
3064                None => policy,
3065            });
3066            return self.execute_delete_inner(raw_query, &augmented);
3067        }
3068        self.execute_delete_inner(raw_query, query)
3069    }
3070
3071    fn execute_delete_inner(
3072        &self,
3073        raw_query: &str,
3074        query: &DeleteQuery,
3075    ) -> RedDBResult<RuntimeQueryResult> {
3076        let maintenance_limit = super::retention_sweeper::take_delete_limit();
3077        let topology_lock = self
3078            .index_store_ref()
3079            .collection_topology_lock(&query.table);
3080        let effective_filter = effective_delete_filter(query);
3081
3082        // Find the rows that match the WHERE clause. The "find target
3083        // rows" loop lives in DmlTargetScan so UPDATE (#52) can reuse
3084        // the same scan strategy.
3085        let scan = super::dml_target_scan::DmlTargetScan::new(
3086            self,
3087            &query.table,
3088            effective_filter.as_ref(),
3089            maintenance_limit,
3090        );
3091        let ids_to_delete = {
3092            let _topology_guard = topology_lock.read();
3093            let ids = scan.find_target_ids()?;
3094            if ids.len() > UPDATE_APPLY_CHUNK_SIZE
3095                && self.current_xid().is_none()
3096                && UnifiedStore::deferred_store_wal_capture_active()
3097            {
3098                super::delete_publication::order_target_ids(self, &query.table, ids)?
3099            } else {
3100                ids
3101            }
3102        };
3103
3104        let needs_delete_events =
3105            !query.suppress_events && self.collection_has_delete_subscriptions(&query.table);
3106        let mut affected: u64 = 0;
3107        // Final cooperative checkpoint before DELETE begins publishing its
3108        // prepared target set. A later timeout must not strand a partial
3109        // statement merely to stop sooner.
3110        let _durable_publication = super::query_budget::begin_durable_publication()?;
3111        self.validate_graph_changes(&query.table, &[], &ids_to_delete)?;
3112        for chunk in ids_to_delete.chunks(UPDATE_APPLY_CHUNK_SIZE) {
3113            let deleted = self.delete_entities_batch(
3114                &query.table,
3115                chunk,
3116                topology_lock.read(),
3117                effective_filter.as_ref(),
3118                needs_delete_events,
3119            )?;
3120            #[cfg(test)]
3121            self.index_store_ref().mutation_test_hook(
3122                &query.table,
3123                super::index_store::MutationTestPhase::BeforeEvents,
3124            );
3125            affected += deleted.affected;
3126            if needs_delete_events && !deleted.changes.is_empty() {
3127                let ids: Vec<_> = deleted.changes.iter().map(|(id, _)| *id).collect();
3128                let lsns: Vec<_> = deleted.changes.iter().map(|(_, lsn)| *lsn).collect();
3129                self.emit_delete_events_for_collection(
3130                    &query.table,
3131                    &ids,
3132                    &lsns,
3133                    &deleted.pre_images,
3134                )?;
3135            }
3136        }
3137
3138        if affected > 0 {
3139            self.note_table_write(&query.table);
3140        }
3141
3142        Ok(RuntimeQueryResult::dml_result(
3143            raw_query.to_string(),
3144            affected,
3145            "delete",
3146            "runtime-dml",
3147        ))
3148    }
3149}
3150
3151#[cfg(test)]
3152mod tests {
3153    use crate::storage::wal::{WalReader, WalRecord};
3154    use crate::storage::{DeployProfile, StoragePackaging, StorageProfileSelection};
3155    use crate::{RedDBOptions, RedDBRuntime};
3156    use reddb_types::Value;
3157    use std::path::Path;
3158
3159    #[test]
3160    fn captured_bulk_delete_keeps_global_row_lock_order_across_chunks() {
3161        use std::sync::{
3162            atomic::{AtomicUsize, Ordering},
3163            Arc,
3164        };
3165        let runtime = Arc::new(
3166            RedDBRuntime::with_options(
3167                RedDBOptions::in_memory().with_memory_budget(128 * 1024 * 1024),
3168            )
3169            .expect("bulk lock fixture"),
3170        );
3171        runtime
3172            .execute_query("CREATE TABLE bulk_lock_order (id INTEGER)")
3173            .expect("table");
3174        let count = super::UPDATE_APPLY_CHUNK_SIZE + 16;
3175        for batch in (0..count).collect::<Vec<_>>().chunks(512) {
3176            let values = batch
3177                .iter()
3178                .map(|id| format!("({id})"))
3179                .collect::<Vec<_>>()
3180                .join(",");
3181            runtime
3182                .execute_query(&format!("INSERT INTO bulk_lock_order (id) VALUES {values}"))
3183                .expect("seed chunk boundary");
3184        }
3185        let manager = runtime
3186            .db()
3187            .store()
3188            .get_collection("bulk_lock_order")
3189            .expect("rows");
3190        // Imported/versioned rows can have logical identities independent
3191        // of their physical positions. Cross decimal-width boundaries too;
3192        // fresh time-based physical IDs alone keep the same string order.
3193        let mut rows = manager.query_all(|_| true);
3194        rows.sort_unstable_by_key(|entity| entity.id);
3195        for (position, mut entity) in rows.into_iter().enumerate() {
3196            entity.set_logical_id(crate::storage::EntityId::new(
3197                u64::try_from(position + 1).expect("small identity"),
3198            ));
3199            manager
3200                .update(entity)
3201                .expect("independent logical identity");
3202        }
3203        let mut expected: Vec<_> = manager
3204            .query_all(|_| true)
3205            .iter()
3206            .map(|entity| format!("row:{}", entity.logical_id().raw()))
3207            .collect();
3208        expected.sort_unstable();
3209        let calls = Arc::new(AtomicUsize::new(0));
3210        let hook_calls = Arc::clone(&calls);
3211        let weak_runtime = Arc::downgrade(&runtime);
3212        *runtime.index_store_ref().mutation_hook.lock() =
3213            Some(Arc::new(move |collection, phase| {
3214                if collection == "bulk_lock_order"
3215                    && phase == super::super::index_store::MutationTestPhase::BeforeEvents
3216                {
3217                    let runtime = weak_runtime.upgrade().expect("writer still alive");
3218                    let held =
3219                        super::super::delete_publication::pending_lock_keys(&runtime, collection);
3220                    assert!(!held.is_empty());
3221                    assert!(held.len() <= expected.len());
3222                    let mismatch = held
3223                        .iter()
3224                        .zip(&expected)
3225                        .position(|(actual, expected)| actual != expected);
3226                    assert!(
3227                        mismatch.is_none(),
3228                        "captured DELETE violated global lock order at position {mismatch:?}"
3229                    );
3230                    hook_calls.fetch_add(1, Ordering::SeqCst);
3231                }
3232            }));
3233        let result = runtime
3234            .with_deferred_store_wal_for_dml(true, || {
3235                runtime.execute_query("DELETE FROM bulk_lock_order")
3236            })
3237            .expect("captured bulk delete");
3238        assert_eq!(
3239            result.affected_rows,
3240            u64::try_from(count).expect("small fixture")
3241        );
3242        assert!(
3243            calls.load(Ordering::SeqCst) >= 2,
3244            "fixture must cross an apply chunk"
3245        );
3246        assert!(runtime
3247            .execute_query("SELECT id FROM bulk_lock_order")
3248            .expect("deleted rows")
3249            .result
3250            .records
3251            .is_empty());
3252        assert_eq!(runtime.snapshot_manager().oldest_active_xid(), None);
3253    }
3254
3255    #[test]
3256    fn locked_update_recheck_read_failure_preserves_preimages_and_retry() {
3257        use crate::storage::engine::BTree;
3258        use reddb_engine::storage::collection_read::PagedCollection;
3259        use std::sync::Arc;
3260
3261        let directory = tempfile::tempdir().expect("locked update fixture");
3262        let options = RedDBOptions::persistent(directory.path().join("locked-update.rdb"))
3263            .with_memory_budget(128 * 1024 * 1024)
3264            .with_storage_profile(
3265                crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
3266            )
3267            .expect("locked update profile");
3268        let runtime = RedDBRuntime::with_options(options).expect("locked update runtime");
3269        for sql in [
3270            "CREATE TABLE recheck_probe (id INTEGER)",
3271            "INSERT INTO recheck_probe (id) VALUES (1), (2)",
3272            "SET CONFIG fixture.flag = 'ready'",
3273        ] {
3274            runtime.execute_query(sql).expect(sql);
3275        }
3276        let sql = "UPDATE recheck_probe SET id = id + 10 WHERE id = 1 OR CONFIG('fixture.flag') = 'ready'";
3277        let reddb_rql::ast::QueryExpr::Update(query) =
3278            reddb_rql::parse(sql).expect("parse update").query
3279        else {
3280            panic!("expected UPDATE");
3281        };
3282        let compiled = runtime.compile_update_plan(&query).expect("compile update");
3283        let filter = reddb_rql::sql_lowering::effective_update_filter(&query);
3284        let ids = super::super::dml_target_scan::DmlTargetScan::new(
3285            &runtime,
3286            "recheck_probe",
3287            filter.as_ref(),
3288            None,
3289        )
3290        .find_target_ids()
3291        .expect("discover targets before failure");
3292        assert_eq!(ids.len(), 2);
3293        let store = runtime.db().store();
3294        store.persist().expect("publish recheck configuration");
3295        let root = store
3296            .collection_root_page("red.config")
3297            .expect("configuration root");
3298        let manager = store
3299            .get_collection("red.config")
3300            .expect("configuration collection");
3301        let install = |limit| {
3302            let tree = BTree::with_root(Arc::clone(store.pager().expect("pager")), root);
3303            manager.install_backing(
3304                Arc::new(PagedCollection::new(Arc::new(tree))),
3305                root,
3306                store.format_version(),
3307                limit,
3308                manager.count() as u64,
3309            );
3310        };
3311        let assert_ids = |expected: [i64; 2]| {
3312            runtime.invalidate_result_cache();
3313            let rows = runtime
3314                .execute_query("SELECT id FROM recheck_probe ORDER BY id")
3315                .expect("read preimages");
3316            let actual: Vec<_> = rows
3317                .result
3318                .records
3319                .iter()
3320                .map(|row| row.get("id").cloned().expect("row value"))
3321                .collect();
3322            assert_eq!(actual, expected.map(Value::Integer));
3323        };
3324        // Candidate discovery has succeeded. Fail only the locked recheck,
3325        // after the first row's postimage can already have been prepared.
3326        install(1);
3327        let error = runtime
3328            .execute_update_inner_tracked_locked(sql, &query, &compiled, &ids, filter.as_ref())
3329            .err()
3330            .expect("locked recheck must propagate its read failure");
3331        assert!(error.to_string().contains("read memory limit"), "{error}");
3332        install(4096);
3333        assert_ids([1, 2]);
3334        let retried = runtime
3335            .execute_update_inner_tracked_locked(sql, &query, &compiled, &ids, filter.as_ref())
3336            .expect("retry locked recheck");
3337        assert_eq!(retried.0.affected_rows, 2);
3338        assert_ids([11, 12]);
3339    }
3340
3341    #[test]
3342    fn concurrent_constant_updates_leave_one_visible_row_per_logical_id() {
3343        use std::sync::{Arc, Barrier};
3344
3345        const WRITERS: usize = 3;
3346        const ROUNDS: usize = 8;
3347        let rt = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
3348        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3349            .unwrap();
3350        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3351            .unwrap();
3352        let barrier = Arc::new(Barrier::new(WRITERS));
3353        let handles: Vec<_> = (0..WRITERS)
3354            .map(|writer| {
3355                let rt = Arc::clone(&rt);
3356                let barrier = Arc::clone(&barrier);
3357                std::thread::spawn(move || {
3358                    for round in 0..ROUNDS {
3359                        barrier.wait();
3360                        rt.execute_query(&format!(
3361                            "UPDATE capabilities SET observed_at = '{writer}-{round}' WHERE id = 'A'"
3362                        ))
3363                        .unwrap();
3364                    }
3365                })
3366            })
3367            .collect();
3368        for handle in handles {
3369            handle.join().unwrap();
3370        }
3371        let selected = rt
3372            .execute_query("SELECT id, observed_at FROM capabilities WHERE id = 'A'")
3373            .unwrap();
3374        assert_eq!(
3375            selected.result.records.len(),
3376            1,
3377            "concurrent updates published multiple visible versions"
3378        );
3379    }
3380
3381    #[test]
3382    fn locked_constant_updates_preserve_unique_constraints() {
3383        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3384        rt.execute_query("CREATE TABLE accounts (id INT PRIMARY KEY, email TEXT UNIQUE)")
3385            .unwrap();
3386        rt.execute_query("INSERT INTO accounts (id, email) VALUES (1, 'a'), (2, 'b')")
3387            .unwrap();
3388        assert!(rt
3389            .execute_query("UPDATE accounts SET email = 'b' WHERE id = 1")
3390            .is_err());
3391        let selected = rt
3392            .execute_query("SELECT id FROM accounts WHERE email = 'a'")
3393            .unwrap();
3394        assert_eq!(selected.result.records.len(), 1);
3395    }
3396
3397    #[test]
3398    fn concurrent_transactions_do_not_both_commit_the_same_row_update() {
3399        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3400
3401        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3402        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3403            .unwrap();
3404        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3405            .unwrap();
3406        for connection in [41, 42] {
3407            set_current_connection_id(connection);
3408            rt.execute_query("BEGIN").unwrap();
3409        }
3410        set_current_connection_id(41);
3411        rt.execute_query("UPDATE capabilities SET observed_at = 'first' WHERE id = 'A'")
3412            .unwrap();
3413        set_current_connection_id(42);
3414        let competing =
3415            rt.execute_query("UPDATE capabilities SET observed_at = 'second' WHERE id = 'A'");
3416        set_current_connection_id(41);
3417        rt.execute_query("COMMIT").unwrap();
3418        set_current_connection_id(42);
3419        if competing.is_ok() {
3420            assert!(
3421                rt.execute_query("COMMIT").is_err(),
3422                "both writers committed"
3423            );
3424        } else {
3425            rt.execute_query("ROLLBACK").unwrap();
3426        }
3427        clear_current_connection_id();
3428        let selected = rt
3429            .execute_query("SELECT id FROM capabilities WHERE id = 'A'")
3430            .unwrap();
3431        assert_eq!(selected.result.records.len(), 1);
3432    }
3433
3434    #[test]
3435    fn transaction_and_autocommit_update_do_not_publish_two_live_versions() {
3436        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3437
3438        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3439        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3440            .unwrap();
3441        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'initial')")
3442            .unwrap();
3443        set_current_connection_id(41);
3444        rt.execute_query("BEGIN").unwrap();
3445        rt.execute_query("UPDATE capabilities SET observed_at = 'transaction' WHERE id = 'A'")
3446            .unwrap();
3447        clear_current_connection_id();
3448        let autocommit =
3449            rt.execute_query("UPDATE capabilities SET observed_at = 'auto' WHERE id = 'A'");
3450        set_current_connection_id(41);
3451        let commit = rt.execute_query("COMMIT");
3452        clear_current_connection_id();
3453        assert!(
3454            autocommit.is_err() || commit.is_err(),
3455            "conflicting writers both committed"
3456        );
3457        let selected = rt
3458            .execute_query("SELECT id FROM capabilities WHERE id = 'A'")
3459            .unwrap();
3460        assert_eq!(selected.result.records.len(), 1);
3461    }
3462
3463    #[test]
3464    fn transaction_update_does_not_target_rows_created_after_snapshot() {
3465        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3466
3467        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3468        rt.execute_query("CREATE TABLE capabilities (id TEXT, observed_at TEXT)")
3469            .unwrap();
3470        set_current_connection_id(41);
3471        rt.execute_query("BEGIN").unwrap();
3472        rt.execute_query("SELECT id FROM capabilities").unwrap();
3473        clear_current_connection_id();
3474        rt.execute_query("INSERT INTO capabilities (id, observed_at) VALUES ('A', 'after')")
3475            .unwrap();
3476        set_current_connection_id(41);
3477        let updated = rt
3478            .execute_query("UPDATE capabilities SET observed_at = 'changed' WHERE id = 'A'")
3479            .unwrap();
3480        assert_eq!(
3481            updated.affected_rows, 0,
3482            "updated a row outside the transaction snapshot"
3483        );
3484        rt.execute_query("COMMIT").unwrap();
3485        clear_current_connection_id();
3486        let selected = rt
3487            .execute_query("SELECT observed_at FROM capabilities WHERE id = 'A'")
3488            .unwrap();
3489        assert_eq!(selected.result.records.len(), 1);
3490        assert_eq!(
3491            selected.result.records[0].get("observed_at"),
3492            Some(&Value::text("after"))
3493        );
3494    }
3495
3496    #[test]
3497    fn autocommit_update_does_not_filter_on_uncommitted_row_image() {
3498        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3499
3500        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3501        rt.execute_query("CREATE TABLE capabilities (id TEXT, status TEXT, payload TEXT)")
3502            .unwrap();
3503        rt.execute_query(
3504            "INSERT INTO capabilities (id, status, payload) VALUES ('A', 'ready', 'old')",
3505        )
3506        .unwrap();
3507        set_current_connection_id(41);
3508        rt.execute_query("BEGIN").unwrap();
3509        rt.execute_query("UPDATE capabilities SET status = 'busy' WHERE id = 'A'")
3510            .unwrap();
3511        clear_current_connection_id();
3512        let autocommit =
3513            rt.execute_query("UPDATE capabilities SET payload = 'new' WHERE status = 'ready'");
3514        if let Ok(result) = &autocommit {
3515            assert_eq!(
3516                result.affected_rows, 1,
3517                "uncommitted status hid the committed target"
3518            );
3519        }
3520        set_current_connection_id(41);
3521        rt.execute_query("ROLLBACK").unwrap();
3522        clear_current_connection_id();
3523        let selected = rt
3524            .execute_query("SELECT status, payload FROM capabilities WHERE id = 'A'")
3525            .unwrap();
3526        assert_eq!(selected.result.records.len(), 1);
3527        assert_eq!(
3528            selected.result.records[0].get("status"),
3529            Some(&Value::text("ready"))
3530        );
3531        if autocommit.is_ok() {
3532            assert_eq!(
3533                selected.result.records[0].get("payload"),
3534                Some(&Value::text("new"))
3535            );
3536        }
3537    }
3538
3539    #[test]
3540    fn autocommit_update_skips_row_claimed_by_another_transaction() {
3541        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
3542
3543        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3544        rt.execute_query("CREATE TABLE capabilities (id INT, rank INT, status TEXT, note TEXT)")
3545            .unwrap();
3546        rt.execute_query("CREATE INDEX capabilities_rank ON capabilities (rank)")
3547            .unwrap();
3548        rt.execute_query(
3549            "INSERT INTO capabilities (id, rank, status, note) VALUES (1, 10, 'ready', 'old')",
3550        )
3551        .unwrap();
3552        set_current_connection_id(41);
3553        rt.execute_query("BEGIN").unwrap();
3554        let claim = rt.execute_query("UPDATE capabilities SET status = 'claimed' WHERE status = 'ready' CLAIM LIMIT 1 ORDER BY rank ASC").unwrap();
3555        assert_eq!(claim.affected_rows, 1);
3556        set_current_connection_id(42);
3557        let other = rt
3558            .execute_query("UPDATE capabilities SET note = 'new' WHERE id = 1")
3559            .unwrap();
3560        assert_eq!(other.affected_rows, 0);
3561        set_current_connection_id(41);
3562        rt.execute_query("ROLLBACK").unwrap();
3563        clear_current_connection_id();
3564        let rows = rt
3565            .execute_query("SELECT status, note FROM capabilities WHERE id = 1")
3566            .unwrap();
3567        assert_eq!(rows.result.records.len(), 1);
3568        assert_eq!(
3569            rows.result.records[0].get("status"),
3570            Some(&Value::text("ready"))
3571        );
3572        assert_eq!(
3573            rows.result.records[0].get("note"),
3574            Some(&Value::text("old"))
3575        );
3576    }
3577
3578    fn persistent_operational_options(path: &Path) -> RedDBOptions {
3579        RedDBOptions::persistent(path)
3580            .with_storage_profile(StorageProfileSelection {
3581                deploy_profile: DeployProfile::Embedded,
3582                packaging: StoragePackaging::OperationalDirectory,
3583                replica_count: 0,
3584                managed_backup: false,
3585                wal_retention: false,
3586            })
3587            .unwrap()
3588    }
3589
3590    fn store_commit_batches(wal_path: &Path) -> Vec<Vec<Vec<u8>>> {
3591        WalReader::open(wal_path)
3592            .expect("wal opens")
3593            .iter()
3594            .map(|record| record.expect("wal record decodes").1)
3595            .filter_map(|record| match record {
3596                WalRecord::TxCommitBatch { actions, .. } => Some(actions),
3597                _ => None,
3598            })
3599            .collect()
3600    }
3601
3602    fn action_contains_text(action: &[u8], needle: &str) -> bool {
3603        action
3604            .windows(needle.len())
3605            .any(|window| window == needle.as_bytes())
3606    }
3607
3608    fn claim_metric_count(
3609        snapshot: &crate::runtime::ClaimTelemetrySnapshot,
3610        metric: &str,
3611        collection: &str,
3612        model: &str,
3613    ) -> u64 {
3614        let rows = match metric {
3615            "attempts" => &snapshot.attempts,
3616            "successful" => &snapshot.successful,
3617            "misses" => &snapshot.misses,
3618            "skipped_locked" => &snapshot.skipped_locked,
3619            other => panic!("unknown claim metric {other}"),
3620        };
3621        rows.iter()
3622            .find(|((actual_collection, actual_model), _)| {
3623                actual_collection == collection && actual_model == model
3624            })
3625            .map(|(_, count)| *count)
3626            .unwrap_or(0)
3627    }
3628
3629    fn assert_statement_writes_collections_in_one_new_wal_batch(
3630        rt: &RedDBRuntime,
3631        wal_path: &Path,
3632        statement: &str,
3633        source: &str,
3634        event_queue: &str,
3635    ) {
3636        let before_batches = store_commit_batches(wal_path).len();
3637
3638        rt.execute_query(statement).unwrap();
3639
3640        let batches = store_commit_batches(wal_path);
3641        let statement_batches = &batches[before_batches..];
3642        let source_batch = statement_batches
3643            .iter()
3644            .position(|actions| {
3645                actions.iter().any(|action| {
3646                    action_contains_text(action, source)
3647                        && !action_contains_text(action, event_queue)
3648                })
3649            })
3650            .expect("source collection write batch is present");
3651        let event_batch = statement_batches
3652            .iter()
3653            .position(|actions| {
3654                actions
3655                    .iter()
3656                    .any(|action| action_contains_text(action, event_queue))
3657            })
3658            .expect("event queue write batch is present");
3659
3660        assert_eq!(
3661            source_batch, event_batch,
3662            "WITH EVENTS must persist the source write and queue event in the same WAL batch"
3663        );
3664    }
3665
3666    #[test]
3667    fn with_events_autocommit_persists_mutation_and_event_in_one_wal_batch() {
3668        let dir = tempfile::tempdir().unwrap();
3669        let db_path = dir.path().join("events_dual_write.rdb");
3670        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3671        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3672
3673        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
3674            .unwrap();
3675        assert_statement_writes_collections_in_one_new_wal_batch(
3676            &rt,
3677            &wal_path,
3678            "INSERT INTO users (id, email) VALUES (1, 'a@example.test')",
3679            "users",
3680            "users_events",
3681        );
3682    }
3683
3684    #[test]
3685    fn with_events_autocommit_update_persists_mutation_and_event_in_one_wal_batch() {
3686        let dir = tempfile::tempdir().unwrap();
3687        let db_path = dir.path().join("events_update_atomic.rdb");
3688        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3689        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3690
3691        rt.execute_query(
3692            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (UPDATE) TO user_updates",
3693        )
3694        .unwrap();
3695        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
3696            .unwrap();
3697
3698        assert_statement_writes_collections_in_one_new_wal_batch(
3699            &rt,
3700            &wal_path,
3701            "UPDATE users SET email = 'b@example.test' WHERE id = 1",
3702            "users",
3703            "user_updates",
3704        );
3705    }
3706
3707    #[test]
3708    fn with_events_autocommit_delete_persists_mutation_and_event_in_one_wal_batch() {
3709        let dir = tempfile::tempdir().unwrap();
3710        let db_path = dir.path().join("events_delete_atomic.rdb");
3711        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
3712        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
3713
3714        rt.execute_query(
3715            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (DELETE) TO user_deletes",
3716        )
3717        .unwrap();
3718        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
3719            .unwrap();
3720
3721        assert_statement_writes_collections_in_one_new_wal_batch(
3722            &rt,
3723            &wal_path,
3724            "DELETE FROM users WHERE id = 1",
3725            "users",
3726            "user_deletes",
3727        );
3728    }
3729
3730    #[test]
3731    fn update_where_id_in_with_hash_index_updates_expected_rows() {
3732        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3733        rt.execute_query("CREATE TABLE users (id INT, score INT)")
3734            .unwrap();
3735        for id in 0..5 {
3736            rt.execute_query(&format!("INSERT INTO users (id, score) VALUES ({id}, 0)"))
3737                .unwrap();
3738        }
3739        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
3740            .unwrap();
3741
3742        let updated = rt
3743            .execute_query("UPDATE users SET score = 42 WHERE id IN (1,3,4)")
3744            .unwrap();
3745        assert_eq!(updated.affected_rows, 3);
3746
3747        let selected = rt
3748            .execute_query("SELECT id, score FROM users ORDER BY id")
3749            .unwrap();
3750        let scores: Vec<(i64, i64)> = selected
3751            .result
3752            .records
3753            .iter()
3754            .map(|record| {
3755                let id = match record.get("id").unwrap() {
3756                    Value::Integer(value) => *value,
3757                    other => panic!("expected integer id, got {other:?}"),
3758                };
3759                let score = match record.get("score").unwrap() {
3760                    Value::Integer(value) => *value,
3761                    other => panic!("expected integer score, got {other:?}"),
3762                };
3763                (id, score)
3764            })
3765            .collect();
3766        assert_eq!(scores, vec![(0, 0), (1, 42), (2, 0), (3, 42), (4, 42)]);
3767    }
3768
3769    /// Drives UPDATE through the shared `DmlTargetScan` module — the
3770    /// same code path DELETE uses (#51, #52). Exercises the indexed
3771    /// equality fast-path (WHERE id = N with a HASH index), the
3772    /// unindexed range scan (WHERE score > N), and the no-WHERE
3773    /// full-scan branch to confirm the extracted "find target rows"
3774    /// loop preserves affected-row counts and the resulting row state.
3775    #[test]
3776    fn update_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
3777        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3778        rt.execute_query("CREATE TABLE items (id INT, score INT)")
3779            .unwrap();
3780        for id in 0..5 {
3781            rt.execute_query(&format!(
3782                "INSERT INTO items (id, score) VALUES ({id}, {})",
3783                id * 10
3784            ))
3785            .unwrap();
3786        }
3787        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
3788            .unwrap();
3789
3790        // Indexed equality UPDATE — hits the hash fast-path inside
3791        // DmlTargetScan::find_target_ids. id=2 has score=20, drop it
3792        // below the score>25 cutoff so the next assertion stays clean.
3793        let updated_one = rt
3794            .execute_query("UPDATE items SET score = 5 WHERE id = 2")
3795            .unwrap();
3796        assert_eq!(updated_one.affected_rows, 1);
3797
3798        // Unindexed scan UPDATE — bumps everyone with score > 25,
3799        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
3800        // zoned/full-scan branch.
3801        let updated_many = rt
3802            .execute_query("UPDATE items SET score = 7 WHERE score > 25")
3803            .unwrap();
3804        assert_eq!(updated_many.affected_rows, 2);
3805
3806        let snapshot = rt
3807            .execute_query("SELECT id, score FROM items ORDER BY id")
3808            .unwrap();
3809        let pairs: Vec<(i64, i64)> = snapshot
3810            .result
3811            .records
3812            .iter()
3813            .map(|record| {
3814                let id = match record.get("id").unwrap() {
3815                    Value::Integer(value) => *value,
3816                    other => panic!("expected integer id, got {other:?}"),
3817                };
3818                let score = match record.get("score").unwrap() {
3819                    Value::Integer(value) => *value,
3820                    other => panic!("expected integer score, got {other:?}"),
3821                };
3822                (id, score)
3823            })
3824            .collect();
3825        assert_eq!(pairs, vec![(0, 0), (1, 10), (2, 5), (3, 7), (4, 7)]);
3826
3827        // Full-scan UPDATE with no WHERE rewrites every remaining row.
3828        let updated_all = rt.execute_query("UPDATE items SET score = 1").unwrap();
3829        assert_eq!(updated_all.affected_rows, 5);
3830        let after = rt
3831            .execute_query("SELECT score FROM items ORDER BY id")
3832            .unwrap();
3833        let scores: Vec<i64> = after
3834            .result
3835            .records
3836            .iter()
3837            .map(|record| match record.get("score").unwrap() {
3838                Value::Integer(value) => *value,
3839                other => panic!("expected integer score, got {other:?}"),
3840            })
3841            .collect();
3842        assert_eq!(scores, vec![1, 1, 1, 1, 1]);
3843    }
3844
3845    /// Drives DELETE through the new `DmlTargetScan` module. Exercises
3846    /// both the index fast-path (WHERE id = N with a HASH index) and
3847    /// the unindexed scan path (WHERE score > N) to confirm the
3848    /// extracted "find target rows" loop preserves the affected-row
3849    /// count and which rows survive.
3850    #[test]
3851    fn delete_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
3852        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3853        rt.execute_query("CREATE TABLE items (id INT, score INT)")
3854            .unwrap();
3855        for id in 0..5 {
3856            rt.execute_query(&format!(
3857                "INSERT INTO items (id, score) VALUES ({id}, {})",
3858                id * 10
3859            ))
3860            .unwrap();
3861        }
3862        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
3863            .unwrap();
3864
3865        // Indexed equality DELETE — hits the hash fast-path inside
3866        // DmlTargetScan::find_target_ids.
3867        let deleted_one = rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
3868        assert_eq!(deleted_one.affected_rows, 1);
3869
3870        // Unindexed scan DELETE — drops everyone with score > 25,
3871        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
3872        // zoned/full-scan branch.
3873        let deleted_many = rt
3874            .execute_query("DELETE FROM items WHERE score > 25")
3875            .unwrap();
3876        assert_eq!(deleted_many.affected_rows, 2);
3877
3878        let surviving = rt
3879            .execute_query("SELECT id FROM items ORDER BY id")
3880            .unwrap();
3881        let ids: Vec<i64> = surviving
3882            .result
3883            .records
3884            .iter()
3885            .map(|record| match record.get("id").unwrap() {
3886                Value::Integer(value) => *value,
3887                other => panic!("expected integer id, got {other:?}"),
3888            })
3889            .collect();
3890        assert_eq!(ids, vec![0, 1]);
3891
3892        // Sanity: full-scan DELETE with no WHERE clears the rest.
3893        let deleted_rest = rt.execute_query("DELETE FROM items").unwrap();
3894        assert_eq!(deleted_rest.affected_rows, 2);
3895        let empty = rt.execute_query("SELECT id FROM items").unwrap();
3896        assert!(empty.result.records.is_empty());
3897    }
3898
3899    /// CollectionContract gate (#49 + #50): APPEND ONLY tables accept
3900    /// INSERT but reject UPDATE and DELETE with the documented
3901    /// operator-facing error strings. Drives all three DML verbs so
3902    /// the centralized gate is exercised end-to-end.
3903    #[test]
3904    fn collection_contract_gate_blocks_update_and_delete_on_append_only() {
3905        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3906        rt.execute_query("CREATE TABLE events (id INT, payload TEXT) APPEND ONLY")
3907            .unwrap();
3908
3909        // INSERT must succeed — APPEND ONLY exists precisely to allow
3910        // appends. The gate should be a no-op for INSERT.
3911        let inserted = rt
3912            .execute_query("INSERT INTO events (id, payload) VALUES (1, 'hello')")
3913            .unwrap();
3914        assert_eq!(inserted.affected_rows, 1);
3915
3916        // UPDATE is rejected with the gate's UPDATE-specific message.
3917        let update_err = rt
3918            .execute_query("UPDATE events SET payload = 'mut' WHERE id = 1")
3919            .unwrap_err();
3920        let msg = format!("{update_err}");
3921        assert!(
3922            msg.contains("APPEND ONLY") && msg.contains("UPDATE is rejected"),
3923            "expected UPDATE rejection message, got: {msg}"
3924        );
3925
3926        // DELETE is rejected with the gate's DELETE-specific message.
3927        let delete_err = rt
3928            .execute_query("DELETE FROM events WHERE id = 1")
3929            .unwrap_err();
3930        let msg = format!("{delete_err}");
3931        assert!(
3932            msg.contains("APPEND ONLY") && msg.contains("DELETE is rejected"),
3933            "expected DELETE rejection message, got: {msg}"
3934        );
3935
3936        // Row should still be present — neither rejected mutation
3937        // touched storage.
3938        let surviving = rt.execute_query("SELECT id FROM events").unwrap();
3939        assert_eq!(surviving.result.records.len(), 1);
3940    }
3941
3942    /// CollectionContract gate: tables without an APPEND ONLY contract
3943    /// permit INSERT, UPDATE, and DELETE — the gate's default branch
3944    /// is a true pass-through, not an accidental block.
3945    #[test]
3946    fn collection_contract_gate_allows_all_verbs_on_unrestricted_table() {
3947        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3948        rt.execute_query("CREATE TABLE notes (id INT, body TEXT)")
3949            .unwrap();
3950
3951        rt.execute_query("INSERT INTO notes (id, body) VALUES (1, 'a')")
3952            .unwrap();
3953        let updated = rt
3954            .execute_query("UPDATE notes SET body = 'b' WHERE id = 1")
3955            .unwrap();
3956        assert_eq!(updated.affected_rows, 1);
3957        let deleted = rt.execute_query("DELETE FROM notes WHERE id = 1").unwrap();
3958        assert_eq!(deleted.affected_rows, 1);
3959    }
3960
3961    #[test]
3962    fn insert_into_event_enabled_table_emits_event_to_configured_queue() {
3963        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3964        rt.execute_query(
3965            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (INSERT) TO audit_log",
3966        )
3967        .unwrap();
3968
3969        let inserted = rt
3970            .execute_query("INSERT INTO users (id, email) VALUES (7, 'a@example.com')")
3971            .unwrap();
3972        assert_eq!(inserted.affected_rows, 1);
3973
3974        let events = queue_payloads(&rt, "audit_log");
3975        assert_eq!(events.len(), 1);
3976        let event = events[0].as_object().expect("event payload object");
3977        assert!(event
3978            .get("event_id")
3979            .and_then(crate::json::Value::as_str)
3980            .is_some_and(|value| !value.is_empty()));
3981        assert_eq!(
3982            event.get("op").and_then(crate::json::Value::as_str),
3983            Some("insert")
3984        );
3985        assert_eq!(
3986            event.get("collection").and_then(crate::json::Value::as_str),
3987            Some("users")
3988        );
3989        assert_eq!(
3990            event.get("id").and_then(crate::json::Value::as_u64),
3991            Some(7)
3992        );
3993        assert!(event
3994            .get("ts")
3995            .and_then(crate::json::Value::as_u64)
3996            .is_some());
3997        assert!(event
3998            .get("lsn")
3999            .and_then(crate::json::Value::as_u64)
4000            .is_some());
4001        assert!(matches!(
4002            event.get("tenant"),
4003            Some(crate::json::Value::Null)
4004        ));
4005        assert!(matches!(
4006            event.get("before"),
4007            Some(crate::json::Value::Null)
4008        ));
4009        let after = event
4010            .get("after")
4011            .and_then(crate::json::Value::as_object)
4012            .expect("after object");
4013        assert_eq!(
4014            after.get("id").and_then(crate::json::Value::as_u64),
4015            Some(7)
4016        );
4017        assert_eq!(
4018            after.get("email").and_then(crate::json::Value::as_str),
4019            Some("a@example.com")
4020        );
4021    }
4022
4023    #[test]
4024    fn multi_row_insert_emits_one_insert_event_per_row_in_order() {
4025        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4026        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4027            .unwrap();
4028
4029        rt.execute_query(
4030            "INSERT INTO users (id, email) VALUES (1, 'a@example.com'), (2, 'b@example.com')",
4031        )
4032        .unwrap();
4033
4034        let events = queue_payloads(&rt, "users_events");
4035        assert_eq!(events.len(), 2);
4036        let mut previous_lsn = 0;
4037        for (event, expected_id) in events.iter().zip([1_u64, 2]) {
4038            let object = event.as_object().expect("event payload object");
4039            assert_eq!(
4040                object.get("op").and_then(crate::json::Value::as_str),
4041                Some("insert")
4042            );
4043            assert_eq!(
4044                object.get("id").and_then(crate::json::Value::as_u64),
4045                Some(expected_id)
4046            );
4047            let lsn = object
4048                .get("lsn")
4049                .and_then(crate::json::Value::as_u64)
4050                .expect("event lsn");
4051            assert!(
4052                lsn > previous_lsn,
4053                "event LSNs should increase in row order"
4054            );
4055            previous_lsn = lsn;
4056            let after = object
4057                .get("after")
4058                .and_then(crate::json::Value::as_object)
4059                .expect("after object");
4060            assert_eq!(
4061                after.get("id").and_then(crate::json::Value::as_u64),
4062                Some(expected_id)
4063            );
4064        }
4065    }
4066
4067    #[test]
4068    fn claim_metrics_increment_skipped_locked_without_counting_miss() {
4069        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
4070        rt.execute_query("CREATE TABLE claim_metric_locked (id INT, rank INT, status TEXT)")
4071            .expect("create table");
4072        // ADR 0063: index-backed claim ordering on `rank`.
4073        rt.execute_query("CREATE INDEX idx_claim_metric_locked_rank ON claim_metric_locked (rank)")
4074            .expect("create index");
4075        rt.execute_query(
4076            "INSERT INTO claim_metric_locked (id, rank, status) VALUES \
4077             (1, 10, 'ready'), (2, 20, 'ready')",
4078        )
4079        .expect("insert rows");
4080
4081        let claim_lock = rt
4082            .inner
4083            .rmw_locks
4084            .lock_for("claim_metric_locked", "__table_claim_update__");
4085        let _guard = claim_lock.lock();
4086        let updated = rt
4087            .execute_query(
4088                "UPDATE claim_metric_locked SET status = 'claimed' WHERE status = 'ready' \
4089                 CLAIM LIMIT 2 ORDER BY rank ASC",
4090            )
4091            .expect("claim skips locked candidates");
4092
4093        assert_eq!(updated.affected_rows, 0);
4094        let snapshot = rt.claim_telemetry_snapshot();
4095        assert_eq!(
4096            claim_metric_count(&snapshot, "attempts", "claim_metric_locked", "table"),
4097            1
4098        );
4099        assert_eq!(
4100            claim_metric_count(&snapshot, "skipped_locked", "claim_metric_locked", "table"),
4101            2
4102        );
4103        assert_eq!(
4104            claim_metric_count(&snapshot, "misses", "claim_metric_locked", "table"),
4105            0
4106        );
4107        assert_eq!(
4108            snapshot.skipped_locked.len(),
4109            1,
4110            "skipped-lock labels stay bounded to collection/model"
4111        );
4112    }
4113
4114    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
4115        let result = rt
4116            .execute_query(&format!("QUEUE PEEK {queue} 10"))
4117            .expect("peek queue");
4118        result
4119            .result
4120            .records
4121            .iter()
4122            .map(
4123                |record| match record.get("payload").expect("payload column") {
4124                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
4125                    other => panic!("expected JSON queue payload, got {other:?}"),
4126                },
4127            )
4128            .collect()
4129    }
4130
4131    // ── #112: auto-index user `id` on first insert ─────────────────────
4132
4133    /// First insert into a fresh collection that carries a column named
4134    /// `id` registers an implicit HASH index on `id`. Subsequent inserts
4135    /// populate it transparently, and `WHERE id = N` lookups exercise
4136    /// the hash-index fast path in `DmlTargetScan::find_target_ids`.
4137    ///
4138    /// This is the load-bearing acceptance test for #112 — without the
4139    /// hook, `find_index_for_column` returns `None` and DELETE/UPDATE
4140    /// fall through to a full segment scan (the 4× perf gap documented
4141    /// in `docs/perf/delete-sequential-2026-05-06.md`).
4142    #[test]
4143    fn auto_index_id_fires_on_first_insert() {
4144        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4145        rt.execute_query("CREATE TABLE bench_users (id INT, score INT)")
4146            .unwrap();
4147
4148        // Pre-condition: no index on `id` yet.
4149        assert!(
4150            rt.index_store_ref()
4151                .find_index_for_column("bench_users", "id")
4152                .is_none(),
4153            "freshly created collection should not have an `id` index"
4154        );
4155
4156        // Single-row INSERT — drives `MutationEngine::append_one`.
4157        rt.execute_query("INSERT INTO bench_users (id, score) VALUES (1, 10)")
4158            .unwrap();
4159
4160        // Post-condition: hash index registered on `id`.
4161        let registered = rt
4162            .index_store_ref()
4163            .find_index_for_column("bench_users", "id")
4164            .expect("auto-index hook should have registered idx_id on first insert");
4165        assert_eq!(registered.name, "idx_id");
4166        assert_eq!(registered.collection, "bench_users");
4167        assert_eq!(registered.columns, vec!["id".to_string()]);
4168        assert!(matches!(
4169            registered.method,
4170            super::super::index_store::IndexMethodKind::Hash
4171        ));
4172
4173        // Subsequent inserts populate the index; `WHERE id = N` should
4174        // resolve via the hash fast path and round-trip every row.
4175        for id in 2..=5 {
4176            rt.execute_query(&format!(
4177                "INSERT INTO bench_users (id, score) VALUES ({id}, {})",
4178                id * 10
4179            ))
4180            .unwrap();
4181        }
4182        for id in 1..=5 {
4183            let result = rt
4184                .execute_query(&format!("SELECT score FROM bench_users WHERE id = {id}"))
4185                .unwrap();
4186            assert_eq!(
4187                result.result.records.len(),
4188                1,
4189                "id={id} should match one row"
4190            );
4191        }
4192
4193        // Delete via the hash fast-path — exactly the bench scenario the
4194        // perf doc identified as the 4× regression. With the index
4195        // present, `find_target_ids` short-circuits before
4196        // `for_each_entity_zoned` runs.
4197        let deleted = rt
4198            .execute_query("DELETE FROM bench_users WHERE id = 3")
4199            .unwrap();
4200        assert_eq!(deleted.affected_rows, 1);
4201    }
4202
4203    /// Bulk INSERT (the multi-row VALUES path) drives
4204    /// `MutationEngine::append_batch`. The hook must fire there too —
4205    /// otherwise the batch entry points (gRPC binary bulk, HTTP bulk,
4206    /// wire bulk INSERT) skip auto-indexing entirely.
4207    #[test]
4208    fn auto_index_id_fires_on_first_bulk_insert() {
4209        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4210        rt.execute_query("CREATE TABLE bench_bulk (id INT, score INT)")
4211            .unwrap();
4212
4213        rt.execute_query("INSERT INTO bench_bulk (id, score) VALUES (1, 10), (2, 20), (3, 30)")
4214            .unwrap();
4215
4216        let registered = rt
4217            .index_store_ref()
4218            .find_index_for_column("bench_bulk", "id")
4219            .expect("auto-index hook should fire on first bulk insert");
4220        assert_eq!(registered.name, "idx_id");
4221
4222        // Every row populated via `index_entity_insert_batch`.
4223        for id in 1..=3 {
4224            let result = rt
4225                .execute_query(&format!("SELECT score FROM bench_bulk WHERE id = {id}"))
4226                .unwrap();
4227            assert_eq!(result.result.records.len(), 1);
4228        }
4229    }
4230
4231    /// Hook is a no-op when the row carries no `id` column. Conservative
4232    /// match (case-sensitive `id`) — `Id`, `ID`, and `rid`
4233    /// don't trigger it.
4234    #[test]
4235    fn auto_index_id_skips_when_no_id_column() {
4236        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4237        rt.execute_query("CREATE TABLE plain (uid INT, label TEXT)")
4238            .unwrap();
4239        rt.execute_query("INSERT INTO plain (uid, label) VALUES (1, 'a')")
4240            .unwrap();
4241
4242        assert!(rt
4243            .index_store_ref()
4244            .find_index_for_column("plain", "id")
4245            .is_none());
4246        assert!(rt
4247            .index_store_ref()
4248            .find_index_for_column("plain", "uid")
4249            .is_none());
4250    }
4251
4252    /// Hook only fires once per collection. If an explicit
4253    /// `CREATE INDEX ... USING BTREE` already covers `id`, the hook
4254    /// detects it via `find_index_for_column` and does NOT clobber it
4255    /// with a HASH index on the next insert.
4256    #[test]
4257    fn auto_index_id_skips_when_index_already_exists() {
4258        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4259        rt.execute_query("CREATE TABLE pre (id INT, score INT)")
4260            .unwrap();
4261        // User-declared BTREE index on `id` before any insert.
4262        rt.execute_query("CREATE INDEX user_idx ON pre (id) USING BTREE")
4263            .unwrap();
4264        rt.execute_query("INSERT INTO pre (id, score) VALUES (1, 10)")
4265            .unwrap();
4266
4267        let registered = rt
4268            .index_store_ref()
4269            .find_index_for_column("pre", "id")
4270            .expect("user index should still be there");
4271        assert_eq!(
4272            registered.name, "user_idx",
4273            "auto-index hook must not overwrite an existing index"
4274        );
4275    }
4276
4277    /// Implicit `idx_id` is reaped when the collection drops. The
4278    /// existing `execute_drop_table` walks `list_indices` and drops every
4279    /// entry — confirm the auto-created index participates.
4280    #[test]
4281    fn auto_index_id_dropped_with_collection() {
4282        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4283        rt.execute_query("CREATE TABLE ephemeral (id INT, score INT)")
4284            .unwrap();
4285        rt.execute_query("INSERT INTO ephemeral (id, score) VALUES (1, 10)")
4286            .unwrap();
4287        assert!(rt
4288            .index_store_ref()
4289            .find_index_for_column("ephemeral", "id")
4290            .is_some());
4291
4292        rt.execute_query("DROP TABLE ephemeral").unwrap();
4293
4294        assert!(
4295            rt.index_store_ref()
4296                .find_index_for_column("ephemeral", "id")
4297                .is_none(),
4298            "implicit `idx_id` must be reaped when its collection drops"
4299        );
4300    }
4301
4302    /// Opt-out via `RedDBOptions::with_auto_index_id(false)` (which
4303    /// forwards to `UnifiedStoreConfig::auto_index_id`). With the knob
4304    /// off, first insert leaves the collection without an `id` index —
4305    /// DELETE/UPDATE fall back to the scan path.
4306    #[test]
4307    fn auto_index_id_disabled_by_config() {
4308        let opts = RedDBOptions::in_memory().with_auto_index_id(false);
4309        let rt = RedDBRuntime::with_options(opts).unwrap();
4310
4311        rt.execute_query("CREATE TABLE off (id INT, score INT)")
4312            .unwrap();
4313        rt.execute_query("INSERT INTO off (id, score) VALUES (1, 10)")
4314            .unwrap();
4315
4316        assert!(
4317            rt.index_store_ref()
4318                .find_index_for_column("off", "id")
4319                .is_none(),
4320            "with auto_index_id=false, no implicit index should be created"
4321        );
4322    }
4323
4324    // ── #293: UPDATE / DELETE events ─────────────────────────────────────
4325
4326    #[test]
4327    fn update_single_row_emits_update_event() {
4328        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4329        rt.execute_query(
4330            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO audit_log",
4331        )
4332        .unwrap();
4333        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4334            .unwrap();
4335
4336        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
4337            .unwrap();
4338
4339        let events = queue_payloads(&rt, "audit_log");
4340        assert_eq!(events.len(), 1, "expected exactly 1 update event");
4341        let event = events[0].as_object().expect("event payload object");
4342        assert_eq!(
4343            event.get("op").and_then(crate::json::Value::as_str),
4344            Some("update")
4345        );
4346        assert_eq!(
4347            event.get("collection").and_then(crate::json::Value::as_str),
4348            Some("users")
4349        );
4350        assert!(event
4351            .get("event_id")
4352            .and_then(crate::json::Value::as_str)
4353            .is_some_and(|v| !v.is_empty()));
4354        let before = event
4355            .get("before")
4356            .and_then(crate::json::Value::as_object)
4357            .expect("before must be an object");
4358        let after = event
4359            .get("after")
4360            .and_then(crate::json::Value::as_object)
4361            .expect("after must be an object");
4362        assert_eq!(
4363            before.get("name").and_then(crate::json::Value::as_str),
4364            Some("Alice"),
4365            "before.name should be the old value"
4366        );
4367        assert_eq!(
4368            after.get("name").and_then(crate::json::Value::as_str),
4369            Some("Bob"),
4370            "after.name should be the new value"
4371        );
4372    }
4373
4374    #[test]
4375    fn update_event_only_includes_changed_fields() {
4376        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4377        rt.execute_query(
4378            "CREATE TABLE users (id INT, name TEXT, email TEXT) WITH EVENTS (UPDATE) TO evts",
4379        )
4380        .unwrap();
4381        rt.execute_query("INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'a@x.com')")
4382            .unwrap();
4383
4384        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
4385            .unwrap();
4386
4387        let events = queue_payloads(&rt, "evts");
4388        assert_eq!(events.len(), 1);
4389        let event = events[0].as_object().unwrap();
4390        let before = event
4391            .get("before")
4392            .and_then(crate::json::Value::as_object)
4393            .unwrap();
4394        let after = event
4395            .get("after")
4396            .and_then(crate::json::Value::as_object)
4397            .unwrap();
4398        // Only changed field included.
4399        assert!(
4400            before.contains_key("name"),
4401            "before must include changed field"
4402        );
4403        assert!(
4404            after.contains_key("name"),
4405            "after must include changed field"
4406        );
4407        // Unchanged fields must not appear.
4408        assert!(
4409            !before.contains_key("email"),
4410            "before must not include unchanged email"
4411        );
4412        assert!(
4413            !after.contains_key("email"),
4414            "after must not include unchanged email"
4415        );
4416    }
4417
4418    #[test]
4419    fn multi_row_update_emits_one_event_per_row() {
4420        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4421        rt.execute_query("CREATE TABLE items (id INT, status TEXT) WITH EVENTS (UPDATE) TO evts")
4422            .unwrap();
4423        rt.execute_query(
4424            "INSERT INTO items (id, status) VALUES (1, 'new'), (2, 'new'), (3, 'new')",
4425        )
4426        .unwrap();
4427
4428        rt.execute_query("UPDATE items SET status = 'done'")
4429            .unwrap();
4430
4431        let events = queue_payloads(&rt, "evts");
4432        assert_eq!(events.len(), 3, "expected one update event per row");
4433        for event in &events {
4434            let obj = event.as_object().unwrap();
4435            assert_eq!(
4436                obj.get("op").and_then(crate::json::Value::as_str),
4437                Some("update")
4438            );
4439        }
4440    }
4441
4442    #[test]
4443    fn delete_single_row_emits_delete_event() {
4444        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4445        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (DELETE) TO del_log")
4446            .unwrap();
4447        rt.execute_query("INSERT INTO users (id, name) VALUES (42, 'Alice')")
4448            .unwrap();
4449
4450        rt.execute_query("DELETE FROM users WHERE id = 42").unwrap();
4451
4452        let events = queue_payloads(&rt, "del_log");
4453        assert_eq!(events.len(), 1);
4454        let event = events[0].as_object().expect("event payload object");
4455        assert_eq!(
4456            event.get("op").and_then(crate::json::Value::as_str),
4457            Some("delete")
4458        );
4459        assert_eq!(
4460            event.get("collection").and_then(crate::json::Value::as_str),
4461            Some("users")
4462        );
4463        assert!(event
4464            .get("event_id")
4465            .and_then(crate::json::Value::as_str)
4466            .is_some_and(|v| !v.is_empty()));
4467        let before = event
4468            .get("before")
4469            .and_then(crate::json::Value::as_object)
4470            .expect("before must be an object for delete");
4471        assert_eq!(
4472            before.get("id").and_then(crate::json::Value::as_u64),
4473            Some(42)
4474        );
4475        assert_eq!(
4476            before.get("name").and_then(crate::json::Value::as_str),
4477            Some("Alice")
4478        );
4479        assert!(matches!(event.get("after"), Some(crate::json::Value::Null)));
4480    }
4481
4482    #[test]
4483    fn multi_row_delete_emits_one_event_per_row() {
4484        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4485        rt.execute_query("CREATE TABLE items (id INT, val INT) WITH EVENTS (DELETE) TO del_log")
4486            .unwrap();
4487        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 10), (2, 20), (3, 30)")
4488            .unwrap();
4489
4490        rt.execute_query("DELETE FROM items").unwrap();
4491
4492        let events = queue_payloads(&rt, "del_log");
4493        assert_eq!(events.len(), 3, "expected one delete event per deleted row");
4494        for event in &events {
4495            let obj = event.as_object().unwrap();
4496            assert_eq!(
4497                obj.get("op").and_then(crate::json::Value::as_str),
4498                Some("delete")
4499            );
4500            assert!(matches!(obj.get("after"), Some(crate::json::Value::Null)));
4501        }
4502    }
4503
4504    #[test]
4505    fn ops_filter_update_does_not_emit_on_insert_or_delete() {
4506        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4507        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO evts")
4508            .unwrap();
4509
4510        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4511            .unwrap();
4512        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
4513
4514        let events = queue_payloads(&rt, "evts");
4515        assert!(
4516            events.is_empty(),
4517            "UPDATE-only filter must not emit INSERT or DELETE events"
4518        );
4519    }
4520
4521    // ── SUPPRESS EVENTS ────────────────────────────────────────────────────
4522
4523    #[test]
4524    fn suppress_events_on_insert_emits_no_events() {
4525        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4526        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4527            .unwrap();
4528
4529        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4530            .unwrap();
4531
4532        let events = queue_payloads(&rt, "evts");
4533        assert!(
4534            events.is_empty(),
4535            "SUPPRESS EVENTS must prevent INSERT events"
4536        );
4537    }
4538
4539    #[test]
4540    fn suppress_events_on_update_emits_no_events() {
4541        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4542        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4543            .unwrap();
4544        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
4545            .unwrap();
4546        // drain the INSERT event
4547        let _ = queue_payloads(&rt, "evts");
4548        // Force pop to drain; simpler: just check new count after UPDATE
4549        rt.execute_query("QUEUE PURGE evts").unwrap();
4550
4551        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1 SUPPRESS EVENTS")
4552            .unwrap();
4553
4554        let events = queue_payloads(&rt, "evts");
4555        assert!(
4556            events.is_empty(),
4557            "SUPPRESS EVENTS must prevent UPDATE events"
4558        );
4559    }
4560
4561    #[test]
4562    fn suppress_events_on_delete_emits_no_events() {
4563        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4564        rt.execute_query(
4565            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (INSERT, DELETE) TO evts",
4566        )
4567        .unwrap();
4568        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4569            .unwrap();
4570
4571        rt.execute_query("DELETE FROM users WHERE id = 1 SUPPRESS EVENTS")
4572            .unwrap();
4573
4574        let events = queue_payloads(&rt, "evts");
4575        assert!(
4576            events.is_empty(),
4577            "SUPPRESS EVENTS must prevent DELETE events"
4578        );
4579    }
4580
4581    #[test]
4582    fn normal_insert_after_suppress_still_emits() {
4583        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4584        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
4585            .unwrap();
4586
4587        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
4588            .unwrap();
4589        rt.execute_query("INSERT INTO users (id, name) VALUES (2, 'Bob')")
4590            .unwrap();
4591
4592        let events = queue_payloads(&rt, "evts");
4593        assert_eq!(
4594            events.len(),
4595            1,
4596            "only the non-suppressed INSERT should emit"
4597        );
4598        assert_eq!(
4599            events[0].get("id").and_then(crate::json::Value::as_u64),
4600            Some(2)
4601        );
4602    }
4603}