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