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::presentation::entity_json::storage_value_to_json;
22use crate::runtime::mvcc::current_connection_id;
23use crate::storage::query::ast::{BinOp, Expr, FieldRef, ReturningItem, UpdateTarget};
24use crate::storage::query::sql_lowering::{
25    effective_delete_filter, effective_insert_rows, effective_update_filter, fold_expr_to_value,
26};
27use crate::storage::query::unified::{
28    sys_key_collection, sys_key_created_at, sys_key_kind, sys_key_rid, sys_key_tenant,
29    sys_key_updated_at, UnifiedRecord, UnifiedResult,
30};
31use crate::storage::unified::MetadataValue;
32use crate::storage::Metadata;
33use std::collections::HashMap;
34use std::sync::Arc;
35
36use super::*;
37
38const UPDATE_APPLY_CHUNK_SIZE: usize = 2048;
39const TREE_CHILD_EDGE_LABEL: &str = "TREE_CHILD";
40const TREE_METADATA_PREFIX: &str = "red.tree.";
41
42#[derive(Clone)]
43struct CompiledUpdateAssignment {
44    column: String,
45    expr: Expr,
46    compound_op: Option<BinOp>,
47    metadata_key: Option<&'static str>,
48    row_rule: Option<RowUpdateColumnRule>,
49}
50
51struct CompiledUpdatePlan {
52    static_field_assignments: Vec<(String, Value)>,
53    static_metadata_assignments: Vec<(String, MetadataValue)>,
54    dynamic_assignments: Vec<CompiledUpdateAssignment>,
55    row_contract_plan: Option<RowUpdateContractPlan>,
56    row_modified_columns: Vec<String>,
57    row_touches_unique_columns: bool,
58}
59
60#[derive(Default)]
61struct MaterializedUpdateAssignments {
62    dynamic_field_assignments: Vec<(String, Value)>,
63    dynamic_metadata_assignments: Vec<(String, MetadataValue)>,
64}
65
66impl RedDBRuntime {
67    /// Issue #524 — public read of the in-memory chain tip. Returns `None`
68    /// when the collection is not a chain or has no rows (pre-genesis). On a
69    /// cold cache the first call falls back to a one-time scan so the HTTP
70    /// `GET /collections/:name/chain-tip` handler stays consistent with the
71    /// INSERT path after a restart.
72    pub fn chain_tip_for_collection(
73        &self,
74        collection: &str,
75    ) -> Option<crate::runtime::blockchain_kind::ChainTipFull> {
76        let store = self.inner.db.store();
77        if !crate::runtime::blockchain_kind::is_chain(&store, collection) {
78            return None;
79        }
80        let mut cache = self.inner.chain_tip_cache.lock();
81        if let Some(existing) = cache.get(collection) {
82            return Some(existing.clone());
83        }
84        let scanned = crate::runtime::blockchain_kind::chain_tip_full(&store, collection)?;
85        cache.insert(collection.to_string(), scanned.clone());
86        Some(scanned)
87    }
88
89    /// Issue #525 — walks the chain end-to-end, recomputes each block's hash
90    /// against the stored fields, and returns the verification outcome.  On
91    /// `ok == false` the integrity flag is persisted and the in-memory cache
92    /// is updated so subsequent INSERTs surface `ChainIntegrityBroken`.
93    ///
94    /// Returns `None` when the collection is absent or not a `KIND blockchain`.
95    pub fn verify_chain_for_collection(
96        &self,
97        collection: &str,
98    ) -> Option<crate::runtime::blockchain_kind::VerifyChainOutcome> {
99        let store = self.inner.db.store();
100        let outcome = crate::runtime::blockchain_kind::verify_chain_outcome(&store, collection)?;
101        if !outcome.ok {
102            crate::runtime::blockchain_kind::persist_integrity_flag(&store, collection, true);
103            self.inner
104                .chain_integrity_broken
105                .lock()
106                .insert(collection.to_string(), true);
107        }
108        Some(outcome)
109    }
110
111    /// Issue #525 — admin clears the `ChainIntegrityBroken` flag so the chain
112    /// accepts INSERTs again.  Returns `false` when the collection is not a
113    /// chain.
114    pub fn clear_chain_integrity_flag(&self, collection: &str) -> bool {
115        let store = self.inner.db.store();
116        if !crate::runtime::blockchain_kind::is_chain(&store, collection) {
117            return false;
118        }
119        crate::runtime::blockchain_kind::persist_integrity_flag(&store, collection, false);
120        self.inner
121            .chain_integrity_broken
122            .lock()
123            .insert(collection.to_string(), false);
124        true
125    }
126
127    /// Issue #525 — INSERT-time check.  Combines in-memory cache (fast path)
128    /// with a one-time scan of `red_config` on cold start so the flag survives
129    /// restart.
130    fn is_chain_integrity_broken(&self, collection: &str) -> bool {
131        {
132            let cache = self.inner.chain_integrity_broken.lock();
133            if let Some(v) = cache.get(collection) {
134                return *v;
135            }
136        }
137        let store = self.inner.db.store();
138        let persisted =
139            crate::runtime::blockchain_kind::is_integrity_broken_persisted(&store, collection)
140                .unwrap_or(false);
141        self.inner
142            .chain_integrity_broken
143            .lock()
144            .insert(collection.to_string(), persisted);
145        persisted
146    }
147
148    /// Issue #765 / S6 — lazily hydrate the integrity-tombstone cache from
149    /// `red_config` on first access. Returns `true` when at least one
150    /// tombstone range is present. Subsequent calls observe the cached state
151    /// flag (`1` empty / `2` present) and skip the store scan.
152    fn ensure_integrity_tombstones_loaded(&self) -> bool {
153        use std::sync::atomic::Ordering;
154        match self
155            .inner
156            .integrity_tombstones_state
157            .load(Ordering::Relaxed)
158        {
159            1 => return false,
160            2 => return true,
161            _ => {}
162        }
163        // Cold: load under the cache lock so a concurrent reader cannot
164        // observe a half-populated vector.
165        let mut guard = self.inner.integrity_tombstones.lock();
166        if self
167            .inner
168            .integrity_tombstones_state
169            .load(Ordering::Relaxed)
170            == 0
171        {
172            let ranges = crate::runtime::integrity_tombstone::load_ranges(&self.inner.db.store());
173            let present = !ranges.is_empty();
174            *guard = ranges;
175            self.inner
176                .integrity_tombstones_state
177                .store(if present { 2 } else { 1 }, Ordering::Relaxed);
178        }
179        self.inner
180            .integrity_tombstones_state
181            .load(Ordering::Relaxed)
182            == 2
183    }
184
185    /// Issue #765 / S6 — durably record an integrity tombstone over the
186    /// inclusive RID range `[lo, hi]` of `table` (the committed rows of an
187    /// input stream whose end-to-end SHA-256 digest did not match). The range
188    /// is persisted to `red_config` (survives restart) and folded into the
189    /// in-memory cache so the same process filters it immediately.
190    pub fn record_integrity_tombstone(&self, table: &str, lo: u64, hi: u64) {
191        use std::sync::atomic::Ordering;
192        self.ensure_integrity_tombstones_loaded();
193        let mut guard = self.inner.integrity_tombstones.lock();
194        guard.push(crate::runtime::integrity_tombstone::TombstoneRange::new(
195            table.to_string(),
196            lo,
197            hi,
198        ));
199        crate::runtime::integrity_tombstone::persist_ranges(&self.inner.db.store(), &guard);
200        self.inner
201            .integrity_tombstones_state
202            .store(2, Ordering::Relaxed);
203    }
204
205    /// Issue #765 / S6 — snapshot of the currently-cached tombstone ranges.
206    /// Intended for tests and forensic surfaces; the read path uses
207    /// [`Self::filter_integrity_tombstoned`] which avoids the clone.
208    pub fn integrity_tombstone_ranges(
209        &self,
210    ) -> Vec<crate::runtime::integrity_tombstone::TombstoneRange> {
211        self.ensure_integrity_tombstones_loaded();
212        self.inner.integrity_tombstones.lock().clone()
213    }
214
215    /// Issue #765 / S6 — drop tombstoned rows from a SELECT result in place.
216    /// Fast no-op (one relaxed atomic load) when no tombstone has ever been
217    /// recorded. Clears `pre_serialized_json` when any row is removed so the
218    /// fast-path JSON cannot leak a filtered row back onto the wire.
219    pub fn filter_integrity_tombstoned(&self, result: &mut UnifiedResult) {
220        if !self.ensure_integrity_tombstones_loaded() {
221            return;
222        }
223        let guard = self.inner.integrity_tombstones.lock();
224        if guard.is_empty() {
225            return;
226        }
227        let before = result.records.len();
228        result.records.retain(|record| {
229            !crate::runtime::integrity_tombstone::record_tombstoned(&guard, record)
230        });
231        if result.records.len() != before {
232            result.pre_serialized_json = None;
233        }
234    }
235
236    /// Phase 2.5.4: inject `CURRENT_TENANT()` into an INSERT when the
237    /// target table is tenant-scoped and the user's column list does
238    /// not already name the tenant column.
239    ///
240    /// Returns:
241    /// * `Ok(None)` — no injection needed (non-tenant table, or user
242    ///   supplied the column explicitly). Caller uses the original
243    ///   query unchanged.
244    /// * `Ok(Some(augmented))` — a cloned query with the tenant column
245    ///   + literal value appended to every row.
246    /// * `Err(..)` — table is tenant-scoped but no tenant is bound to
247    ///   the current session. Fails loudly so callers don't produce
248    ///   rows that RLS would then hide on read.
249    fn maybe_inject_tenant_column(&self, query: &InsertQuery) -> RedDBResult<Option<InsertQuery>> {
250        let Some(tenant_col) = self.tenant_column(&query.table) else {
251            return Ok(None);
252        };
253        // User already named the column (literal match) — trust them.
254        if query
255            .columns
256            .iter()
257            .any(|c| c.eq_ignore_ascii_case(&tenant_col))
258        {
259            return Ok(None);
260        }
261
262        // Phase 2 PG parity: dotted-path tenancy. When `tenant_col` is a
263        // nested key like `headers.tenant` we operate on the root
264        // column (`headers`) and set / add the nested path inside its
265        // JSON value. If the user named the root column we mutate in
266        // place; otherwise we create a fresh JSON column for every row.
267        if let Some(dot_pos) = tenant_col.find('.') {
268            let (root, tail) = tenant_col.split_at(dot_pos);
269            let tail = &tail[1..]; // drop leading '.'
270            return self.inject_dotted_tenant(query, root, tail);
271        }
272
273        let Some(tenant_id) = crate::runtime::impl_core::current_tenant() else {
274            return Err(RedDBError::Query(format!(
275                "INSERT into tenant-scoped table '{}' requires an active tenant — \
276                 run SET TENANT '<id>' first or name column '{}' explicitly",
277                query.table, tenant_col
278            )));
279        };
280
281        let mut augmented = query.clone();
282        augmented.columns.push(tenant_col);
283        let lit = Value::text(tenant_id.clone());
284        for row in augmented.values.iter_mut() {
285            row.push(lit.clone());
286        }
287        for row in augmented.value_exprs.iter_mut() {
288            row.push(crate::storage::query::ast::Expr::Literal {
289                value: lit.clone(),
290                span: crate::storage::query::ast::Span::synthetic(),
291            });
292        }
293        Ok(Some(augmented))
294    }
295
296    /// Dotted-path auto-fill — set `root.tail` to `CURRENT_TENANT()` on
297    /// every row. Mirrors `maybe_inject_tenant_column` but mutates
298    /// nested JSON instead of appending a flat column.
299    ///
300    /// Cases:
301    /// * Root column already in the INSERT list → mutate per-row JSON
302    ///   (parse, set path, re-serialize).
303    /// * Root column absent → create a fresh `{tail: tenant}` JSON
304    ///   object and append the root column to the INSERT.
305    fn inject_dotted_tenant(
306        &self,
307        query: &InsertQuery,
308        root: &str,
309        tail: &str,
310    ) -> RedDBResult<Option<InsertQuery>> {
311        let active_tenant = crate::runtime::impl_core::current_tenant();
312        let mut augmented = query.clone();
313        let root_idx = augmented
314            .columns
315            .iter()
316            .position(|c| c.eq_ignore_ascii_case(root));
317
318        if let Some(idx) = root_idx {
319            // User supplied the root column. Per-row: if the dotted
320            // tail is already present we trust the user (admin / bulk
321            // loader scenario); otherwise fill from the active
322            // tenant. An unbound tenant is only an error when some
323            // row actually needs filling.
324            for row in augmented.values.iter_mut() {
325                let Some(slot) = row.get_mut(idx) else {
326                    continue;
327                };
328                if dotted_tail_already_set(slot, tail) {
329                    continue;
330                }
331                let Some(tenant_id) = &active_tenant else {
332                    return Err(RedDBError::Query(format!(
333                        "INSERT into tenant-scoped table '{}' requires an active tenant — \
334                         run SET TENANT '<id>' first or set '{}.{}' explicitly in each row",
335                        query.table, root, tail
336                    )));
337                };
338                *slot = merge_dotted_tenant(slot.clone(), tail, tenant_id)?;
339            }
340            // Expression row is kept in sync by re-wrapping the
341            // mutated literal; the canonical path will re-evaluate
342            // against the same JSON shape.
343            for (row_idx, row) in augmented.value_exprs.iter_mut().enumerate() {
344                if let Some(slot) = row.get_mut(idx) {
345                    let new_value = augmented
346                        .values
347                        .get(row_idx)
348                        .and_then(|v| v.get(idx))
349                        .cloned()
350                        .unwrap_or(Value::Null);
351                    *slot = crate::storage::query::ast::Expr::Literal {
352                        value: new_value,
353                        span: crate::storage::query::ast::Span::synthetic(),
354                    };
355                }
356            }
357        } else {
358            // No root column in the INSERT list — auto-fill needs a
359            // bound tenant to synthesise one. Error loud so we never
360            // create a tenant-less row that RLS would then hide.
361            let Some(tenant_id) = &active_tenant else {
362                return Err(RedDBError::Query(format!(
363                    "INSERT into tenant-scoped table '{}' requires an active tenant — \
364                     run SET TENANT '<id>' first or name path '{}.{}' explicitly",
365                    query.table, root, tail
366                )));
367            };
368            // Create a fresh JSON column with only the tenant path set.
369            augmented.columns.push(root.to_string());
370            let fresh = merge_dotted_tenant(Value::Null, tail, tenant_id)?;
371            for row in augmented.values.iter_mut() {
372                row.push(fresh.clone());
373            }
374            for row in augmented.value_exprs.iter_mut() {
375                row.push(crate::storage::query::ast::Expr::Literal {
376                    value: fresh.clone(),
377                    span: crate::storage::query::ast::Span::synthetic(),
378                });
379            }
380        }
381
382        Ok(Some(augmented))
383    }
384
385    /// Returns `(affected_count, lsns)`. For the txn (xmax-stamp) path,
386    /// `lsns` is empty because events fire at commit time.
387    fn delete_entities_batch(
388        &self,
389        collection: &str,
390        ids: &[EntityId],
391    ) -> RedDBResult<(u64, Vec<u64>)> {
392        if ids.is_empty() {
393            return Ok((0, vec![]));
394        }
395
396        let store = self.db().store();
397        let Some(manager) = store.get_collection(collection) else {
398            return Ok((0, vec![]));
399        };
400
401        let active_xid = self.current_xid();
402        let conn_id = crate::runtime::impl_core::current_connection_id();
403        let mut autocommit_xid = None;
404        let mut tombstoned_ids = Vec::new();
405        let mut tombstoned_entities = Vec::new();
406        let mut physical_delete_ids = Vec::new();
407        let table_row_resolver =
408            crate::runtime::table_row_mvcc_resolver::TableRowMvccReadResolver::current_statement();
409        // Phase 3: versioned graph collections tombstone node/edge
410        // deletes (xmax stamp) instead of physically removing them, so
411        // `AS OF` time-travel can still resolve the pre-delete version.
412        // Non-versioned graph collections keep the legacy physical
413        // delete (no history). Row entities (Phase 1/2) always tombstone
414        // under universal MVCC and are unaffected by this flag.
415        //
416        // Vectors (Phase 3b): versioned vector deletes tombstone (xmax
417        // stamp) instead of physically dropping, so history is retained.
418        // The `VECTOR SEARCH` read path post-filters every candidate
419        // through the current-snapshot visibility gate (which hides
420        // `xmax != 0` even in autocommit), so a tombstoned versioned
421        // vector never reaches live search. Non-versioned vectors keep
422        // the legacy physical delete.
423        let versioned_collection = self.vcs_is_versioned(collection).unwrap_or(false);
424
425        for &id in ids {
426            let Some(mut entity) = manager.get(id) else {
427                continue;
428            };
429            let is_versioned_graph = versioned_collection
430                && matches!(entity.data, EntityData::Node(_) | EntityData::Edge(_));
431            let is_versioned_vector =
432                versioned_collection && matches!(entity.data, EntityData::Vector(_));
433            if matches!(entity.data, EntityData::Row(_))
434                || is_versioned_graph
435                || is_versioned_vector
436            {
437                let previous_xmax = entity.xmax;
438                if matches!(entity.kind, crate::storage::EntityKind::TableRow { .. }) {
439                    if table_row_resolver.resolve_candidate(&entity).is_none() {
440                        continue;
441                    }
442                } else if is_versioned_vector {
443                    // Versioned vectors gate the delete on the statement
444                    // snapshot (not a crude `xmax != 0`) so a concurrent
445                    // delete whose snapshot predates a still-uncommitted
446                    // tombstone still targets the row, records its own
447                    // pending tombstone, and conflicts at commit
448                    // (first-committer-wins).
449                    if table_row_resolver.resolve_read_candidate(&entity).is_none() {
450                        continue;
451                    }
452                } else if entity.xmax != 0 {
453                    continue;
454                }
455
456                let xid = match active_xid {
457                    Some(xid) => xid,
458                    None => match autocommit_xid {
459                        Some(xid) => xid,
460                        None => {
461                            let mgr = self.snapshot_manager();
462                            let xid = mgr.begin();
463                            autocommit_xid = Some(xid);
464                            xid
465                        }
466                    },
467                };
468                entity.set_xmax(xid);
469                if manager.update(entity.clone()).is_ok() {
470                    if active_xid.is_some() {
471                        self.record_pending_tombstone(conn_id, collection, id, xid, previous_xmax);
472                    }
473                    tombstoned_entities.push(entity);
474                    tombstoned_ids.push(id);
475                }
476            } else {
477                physical_delete_ids.push(id);
478            }
479        }
480
481        if let Some(xid) = autocommit_xid {
482            self.snapshot_manager().commit(xid);
483        }
484
485        let mut affected = tombstoned_ids.len() as u64;
486        let mut lsns = Vec::with_capacity(tombstoned_ids.len() + physical_delete_ids.len());
487        if active_xid.is_some() {
488            store
489                .persist_entities_to_pager(collection, &tombstoned_entities)
490                .map_err(|err| RedDBError::Internal(err.to_string()))?;
491        } else {
492            store
493                .persist_entities_to_pager(collection, &tombstoned_entities)
494                .map_err(|err| RedDBError::Internal(err.to_string()))?;
495            for id in &tombstoned_ids {
496                store.context_index().remove_entity(*id);
497                let lsn = self.cdc_emit(
498                    crate::replication::cdc::ChangeOperation::Delete,
499                    collection,
500                    id.raw(),
501                    "entity",
502                );
503                lsns.push(lsn);
504            }
505        }
506
507        let deleted_ids = store
508            .delete_batch(collection, &physical_delete_ids)
509            .map_err(|err| RedDBError::Internal(err.to_string()))?;
510        affected += deleted_ids.len() as u64;
511        for id in &deleted_ids {
512            store.context_index().remove_entity(*id);
513            let lsn = self.cdc_emit(
514                crate::replication::cdc::ChangeOperation::Delete,
515                collection,
516                id.raw(),
517                "entity",
518            );
519            lsns.push(lsn);
520        }
521
522        Ok((affected, lsns))
523    }
524
525    /// Flushes context-index updates and CDC for each applied mutation.
526    /// Returns one LSN per entity in the same order as `applied`.
527    fn flush_update_chunk(&self, applied: &[AppliedEntityMutation]) -> RedDBResult<Vec<u64>> {
528        if applied.is_empty() {
529            return Ok(Vec::new());
530        }
531
532        let store = self.db().store();
533        if applied.iter().any(|item| item.context_index_dirty) {
534            store.context_index().index_entities(
535                &applied[0].collection,
536                applied
537                    .iter()
538                    .filter(|item| item.context_index_dirty)
539                    .map(|item| &item.entity),
540            );
541        }
542
543        for item in applied {
544            self.refresh_update_secondary_indexes(item)?;
545        }
546
547        let mut lsns = Vec::with_capacity(applied.len());
548        for item in applied {
549            let lsn = self.cdc_emit_prebuilt(
550                crate::replication::cdc::ChangeOperation::Update,
551                &item.collection,
552                &item.entity,
553                update_cdc_item_kind(self, &item.collection, &item.entity),
554                item.metadata.as_ref(),
555                false,
556            );
557            lsns.push(lsn);
558        }
559        Ok(lsns)
560    }
561
562    fn persist_update_chunk(&self, applied: &[AppliedEntityMutation]) -> RedDBResult<()> {
563        self.persist_applied_entity_mutations(applied)
564    }
565
566    fn refresh_update_secondary_indexes(&self, applied: &AppliedEntityMutation) -> RedDBResult<()> {
567        if applied.pre_mutation_fields.is_empty() {
568            return Ok(());
569        }
570        let post = entity_row_fields_snapshot(&applied.entity);
571        if post.is_empty() {
572            return Ok(());
573        }
574
575        // Use the parent-expanded set so that dot-path indexes (e.g.
576        // "body.service.tier") are triggered when the root field ("body")
577        // is modified.
578        let indexed_cols = self
579            .index_store_ref()
580            .indexed_columns_set_with_parents(&applied.collection);
581        if indexed_cols.is_empty() {
582            return Ok(());
583        }
584
585        // Single-source documents keep promoted index columns (`score`) in the
586        // body, not as stored fields. Resolve each indexed column from the body
587        // and fold it into the field snapshots so the diff below sees the value
588        // move — for an ordinary stored column this adds nothing.
589        let pre = self
590            .index_store_ref()
591            .augment_body_derived_index_fields(&applied.pre_mutation_fields, &indexed_cols);
592        let post = self
593            .index_store_ref()
594            .augment_body_derived_index_fields(&post, &indexed_cols);
595
596        if let Some(old_version) = applied.replaced_entity.as_ref() {
597            let old_index_fields: Vec<(String, crate::storage::schema::Value)> = pre
598                .iter()
599                .filter(|(col, _)| indexed_cols.contains(col))
600                .cloned()
601                .collect();
602            let new_index_fields: Vec<(String, crate::storage::schema::Value)> = post
603                .iter()
604                .filter(|(col, _)| indexed_cols.contains(col))
605                .cloned()
606                .collect();
607            if !old_index_fields.is_empty() {
608                self.index_store_ref()
609                    .index_entity_delete(&applied.collection, old_version.id, &old_index_fields)
610                    .map_err(crate::RedDBError::Internal)?;
611            }
612            if !new_index_fields.is_empty() {
613                self.index_store_ref()
614                    .index_entity_insert(&applied.collection, applied.entity.id, &new_index_fields)
615                    .map_err(crate::RedDBError::Internal)?;
616            }
617            return Ok(());
618        }
619
620        let damage = crate::application::entity::row_damage_vector(&pre, &post);
621        if damage
622            .touched_columns()
623            .into_iter()
624            .any(|col| indexed_cols.contains(col))
625        {
626            self.index_store_ref()
627                .index_entity_update(&applied.collection, applied.id, &pre, &post)
628                .map_err(crate::RedDBError::Internal)?;
629        }
630        Ok(())
631    }
632
633    /// Execute INSERT INTO table [entity_type] (cols) VALUES (vals), ...
634    ///
635    /// Each row in `query.values` is zipped with `query.columns` to produce a
636    /// set of named fields, which is then dispatched based on entity_type.
637    pub fn execute_insert(
638        &self,
639        raw_query: &str,
640        query: &InsertQuery,
641    ) -> RedDBResult<RuntimeQueryResult> {
642        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
643        // CollectionContract gate (#49): single entry point for the
644        // operator's collection-level write rules. Today this is a
645        // no-op for INSERT (APPEND ONLY permits insert); routing
646        // through the gate now means future contract bits — versioned,
647        // vault-only writes — plug in once instead of per verb.
648        crate::runtime::collection_contract::CollectionContractGate::check(
649            self,
650            &query.table,
651            crate::runtime::collection_contract::MutationKind::Insert,
652        )?;
653        // Phase 2.5.4 table-scoped tenancy: if the target table is
654        // tenant-scoped and the user didn't name the tenant column,
655        // auto-inject it with the thread-local `CURRENT_TENANT()`
656        // value. When the column is named explicitly we trust the
657        // caller (useful for admin tooling that writes on behalf of
658        // specific tenants). An unbound tenant on an implicit-fill
659        // path errors up front rather than producing a row the RLS
660        // policy would silently hide.
661        let augmented_owned;
662        let query = match self.maybe_inject_tenant_column(query)? {
663            Some(new_q) => {
664                augmented_owned = new_q;
665                &augmented_owned
666            }
667            None => query,
668        };
669        self.check_insert_column_policy(query)?;
670        if let Some(ref embed_config) = query.auto_embed {
671            let provider = crate::ai::parse_provider(&embed_config.provider)?;
672            // S3 / #711: planner-level provider gate. Runs before the
673            // local-model preflight and the API-key resolver so neither
674            // side-effect fires when policy denies.
675            crate::runtime::ai::provider_gate::enforce(self, &provider)?;
676            if matches!(provider, crate::ai::AiProvider::Local) {
677                crate::runtime::ai::local_embedding::ensure_local_embedding_available()?;
678                // Issue #682 — pre-flight the local model registry before
679                // any row write. Missing model, uninstalled artifacts,
680                // wrong task, and disabled-feature failures surface as
681                // deterministic errors that leave the target collection
682                // untouched, satisfying the "no partial writes on
683                // embedding failure" criterion for the failure modes
684                // owned by the local provider.
685                let model_name = embed_config.model.as_deref().map(str::trim).unwrap_or("");
686                if model_name.is_empty() {
687                    return Err(RedDBError::Query(
688                        "AUTO EMBED with provider=local requires MODEL '<registered-model-name>'; \
689                         the local provider does not have an implicit default model"
690                            .to_string(),
691                    ));
692                }
693                crate::runtime::ai::local_embedding::preflight_local_embedding(
694                    &self.inner.db,
695                    model_name,
696                )?;
697            }
698        }
699
700        let mut inserted_count: u64 = 0;
701        let effective_rows =
702            effective_insert_rows(query).map_err(|msg| RedDBError::Query(msg.to_string()))?;
703
704        // Ensure the collection exists (auto-create on first insert).
705        let store = self.inner.db.store();
706        let _ = store.get_or_create_collection(&query.table);
707        let declared_model = self
708            .db()
709            .collection_contract_arc(&query.table)
710            .map(|contract| contract.declared_model);
711
712        let mut returning_snapshots: Option<Vec<Vec<(String, Value)>>> =
713            if query.returning.is_some() {
714                Some(Vec::with_capacity(effective_rows.len()))
715            } else {
716                None
717            };
718        let mut returning_result: Option<UnifiedResult> = None;
719
720        if matches!(query.entity_type, InsertEntityType::Row)
721            && !matches!(
722                declared_model,
723                Some(crate::catalog::CollectionModel::TimeSeries)
724            )
725        {
726            // Issue #523 + #524: blockchain collections seal each row into the
727            // chain. When the caller omits the reserved columns, the engine
728            // auto-fills (#523). When the caller supplies any reserved column,
729            // the values are validated against the current tip and a mismatch
730            // surfaces a `BlockchainConflict:` error mapped to HTTP 409 (#524).
731            //
732            // The whole batch runs under a per-collection chain lock so two
733            // concurrent submitters can't both bind to the same prev_hash —
734            // the loser observes the advanced tip and gets 409 with the new
735            // tip so it can retry.
736            let chain_mode = crate::runtime::blockchain_kind::is_chain(&store, &query.table);
737            let _chain_lock_arc: Option<Arc<parking_lot::Mutex<()>>> = if chain_mode {
738                Some(self.inner.rmw_locks.lock_for(&query.table, "__chain__"))
739            } else {
740                None
741            };
742            let _chain_guard = _chain_lock_arc.as_ref().map(|m| m.lock());
743
744            // Issue #525 — refuse new blocks if the chain has been marked
745            // `integrity = broken` until an admin clears the flag.
746            if chain_mode && self.is_chain_integrity_broken(&query.table) {
747                return Err(RedDBError::InvalidOperation(format!(
748                    "ChainIntegrityBroken: collection '{}' is locked until \
749                     POST /collections/{}/clear-integrity-flag is called by an admin",
750                    query.table, query.table
751                )));
752            }
753
754            // Pull the tip from the in-memory cache; fall back to a one-time
755            // scan if the cache hasn't seen this collection yet (cold start
756            // after restart). Cache is updated below as rows are sealed.
757            let mut chain_tip_full: Option<crate::runtime::blockchain_kind::ChainTipFull> =
758                if chain_mode {
759                    let mut cache = self.inner.chain_tip_cache.lock();
760                    if let Some(existing) = cache.get(&query.table) {
761                        Some(existing.clone())
762                    } else if let Some(scanned) =
763                        crate::runtime::blockchain_kind::chain_tip_full(&store, &query.table)
764                    {
765                        cache.insert(query.table.clone(), scanned.clone());
766                        Some(scanned)
767                    } else {
768                        None
769                    }
770                } else {
771                    None
772                };
773
774            let mut rows = Vec::with_capacity(effective_rows.len());
775            for row_values in &effective_rows {
776                if row_values.len() != query.columns.len() {
777                    return Err(RedDBError::Query(format!(
778                        "INSERT column count ({}) does not match value count ({})",
779                        query.columns.len(),
780                        row_values.len()
781                    )));
782                }
783                let (mut fields, mut metadata) =
784                    split_insert_metadata(self, &query.columns, row_values)?;
785                if chain_mode {
786                    use crate::runtime::blockchain_kind::{
787                        chain_conflict_error, COL_BLOCK_HEIGHT, COL_HASH, COL_PREV_HASH,
788                        COL_TIMESTAMP, RESERVED_COLUMNS,
789                    };
790                    let supplied_height = fields
791                        .iter()
792                        .find(|(k, _)| k == COL_BLOCK_HEIGHT)
793                        .map(|(_, v)| v.clone());
794                    let supplied_prev = fields
795                        .iter()
796                        .find(|(k, _)| k == COL_PREV_HASH)
797                        .map(|(_, v)| v.clone());
798                    let supplied_ts = fields
799                        .iter()
800                        .find(|(k, _)| k == COL_TIMESTAMP)
801                        .map(|(_, v)| v.clone());
802                    let supplied_hash = fields.iter().any(|(k, _)| k == COL_HASH);
803                    let user_supplied_any = supplied_height.is_some()
804                        || supplied_prev.is_some()
805                        || supplied_ts.is_some()
806                        || supplied_hash;
807
808                    fields.retain(|(k, _)| !RESERVED_COLUMNS.contains(&k.as_str()));
809                    let payload = crate::runtime::blockchain_kind::canonical_payload(&fields);
810
811                    let (tip_prev_hash, tip_next_height) = match &chain_tip_full {
812                        Some(t) => (t.hash, t.height + 1),
813                        None => (crate::storage::blockchain::GENESIS_PREV_HASH, 0u64),
814                    };
815                    let server_now = crate::runtime::blockchain_kind::now_ms();
816
817                    let (use_prev, use_height, use_ts) = if user_supplied_any {
818                        // Caller is participating in the chain protocol —
819                        // every field must be supplied AND match the tip.
820                        if supplied_hash {
821                            return Err(chain_conflict_error(
822                                tip_next_height.saturating_sub(1),
823                                tip_prev_hash,
824                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
825                                server_now,
826                                "hash column is engine-computed and cannot be supplied",
827                            ));
828                        }
829                        let caller_prev = match &supplied_prev {
830                            Some(Value::Blob(b)) if b.len() == 32 => {
831                                let mut a = [0u8; 32];
832                                a.copy_from_slice(b);
833                                a
834                            }
835                            Some(Value::Text(s)) if s.len() == 64 => {
836                                // Accept hex-encoded prev_hash so JSON / SQL
837                                // callers without literal-blob syntax can
838                                // still participate in the chain protocol.
839                                let mut a = [0u8; 32];
840                                let mut ok = true;
841                                for (i, slot) in a.iter_mut().enumerate() {
842                                    let pair = &s.as_ref()[i * 2..i * 2 + 2];
843                                    match u8::from_str_radix(pair, 16) {
844                                        Ok(byte) => *slot = byte,
845                                        Err(_) => {
846                                            ok = false;
847                                            break;
848                                        }
849                                    }
850                                }
851                                if !ok {
852                                    return Err(chain_conflict_error(
853                                        tip_next_height.saturating_sub(1),
854                                        tip_prev_hash,
855                                        chain_tip_full
856                                            .as_ref()
857                                            .map(|t| t.timestamp_ms)
858                                            .unwrap_or(0),
859                                        server_now,
860                                        "prev_hash is not valid hex",
861                                    ));
862                                }
863                                a
864                            }
865                            _ => {
866                                return Err(chain_conflict_error(
867                                    tip_next_height.saturating_sub(1),
868                                    tip_prev_hash,
869                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
870                                    server_now,
871                                    "prev_hash missing or not a 32-byte Blob",
872                                ));
873                            }
874                        };
875                        if caller_prev != tip_prev_hash {
876                            return Err(chain_conflict_error(
877                                tip_next_height.saturating_sub(1),
878                                tip_prev_hash,
879                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
880                                server_now,
881                                "prev_hash does not match current tip",
882                            ));
883                        }
884                        let caller_height = match &supplied_height {
885                            Some(Value::UnsignedInteger(v)) => *v,
886                            Some(Value::Integer(v)) if *v >= 0 => *v as u64,
887                            _ => {
888                                return Err(chain_conflict_error(
889                                    tip_next_height.saturating_sub(1),
890                                    tip_prev_hash,
891                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
892                                    server_now,
893                                    "block_height missing or not an unsigned integer",
894                                ));
895                            }
896                        };
897                        if caller_height != tip_next_height {
898                            return Err(chain_conflict_error(
899                                tip_next_height.saturating_sub(1),
900                                tip_prev_hash,
901                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
902                                server_now,
903                                "block_height does not match tip+1",
904                            ));
905                        }
906                        let caller_ts = match &supplied_ts {
907                            Some(Value::UnsignedInteger(v)) => *v,
908                            Some(Value::Integer(v)) if *v >= 0 => *v as u64,
909                            _ => {
910                                return Err(chain_conflict_error(
911                                    tip_next_height.saturating_sub(1),
912                                    tip_prev_hash,
913                                    chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
914                                    server_now,
915                                    "timestamp missing or not an unsigned integer",
916                                ));
917                            }
918                        };
919                        let drift = (caller_ts as i128) - (server_now as i128);
920                        if drift.abs() > 60_000 {
921                            return Err(chain_conflict_error(
922                                tip_next_height.saturating_sub(1),
923                                tip_prev_hash,
924                                chain_tip_full.as_ref().map(|t| t.timestamp_ms).unwrap_or(0),
925                                server_now,
926                                "timestamp outside ±60s of server_time",
927                            ));
928                        }
929                        (caller_prev, caller_height, caller_ts)
930                    } else {
931                        (tip_prev_hash, tip_next_height, server_now)
932                    };
933
934                    let (reserved, new_hash) =
935                        crate::runtime::blockchain_kind::make_block_reserved_fields(
936                            use_prev, use_height, use_ts, &payload,
937                        );
938                    fields.extend(reserved);
939                    chain_tip_full = Some(crate::runtime::blockchain_kind::ChainTipFull {
940                        height: use_height,
941                        hash: new_hash,
942                        timestamp_ms: use_ts,
943                    });
944                }
945                // Issue #522 — signed-writes verification. On collections
946                // created with `SIGNED_BY (...)` the row must carry valid
947                // `signer_pubkey` + `signature` reserved columns. Runs
948                // after chain_mode so canonical payload covers user-supplied
949                // fields only (blockchain reserved columns are filtered by
950                // `canonical_payload`; the two signed-writes reserved
951                // columns are split out before payload computation, then
952                // re-attached for storage). The blockchain + SIGNED_BY
953                // composition is owned by issue #526; we keep #522 to the
954                // non-chain path and let chain_mode collections punt to that
955                // slice rather than half-wire it here.
956                if crate::runtime::signed_writes_kind::is_signed(&store, &query.table) {
957                    let (pk_col, sig_col, residual) =
958                        crate::runtime::signed_writes_kind::split_signature_fields(fields);
959                    let payload = crate::runtime::blockchain_kind::canonical_payload(&residual);
960                    let reg = crate::runtime::signed_writes_kind::registry(&store, &query.table);
961                    crate::runtime::signed_writes_kind::verify_row(
962                        &reg,
963                        pk_col.as_ref().map(|c| c.bytes.as_slice()),
964                        sig_col.as_ref().map(|c| c.bytes.as_slice()),
965                        &payload,
966                    )
967                    .map_err(crate::runtime::signed_writes_kind::map_error)?;
968                    fields = residual;
969                    // Round-trip the reserved columns with the value
970                    // type the caller supplied (Text/hex on the SQL path,
971                    // Blob on the binary path). Keeps SELECT and WHERE
972                    // predicates symmetric with the INSERT shape.
973                    if let Some(col) = pk_col {
974                        fields.push((
975                            crate::storage::signed_writes::RESERVED_SIGNER_PUBKEY_COL.to_string(),
976                            col.raw_value,
977                        ));
978                    }
979                    if let Some(col) = sig_col {
980                        fields.push((
981                            crate::storage::signed_writes::RESERVED_SIGNATURE_COL.to_string(),
982                            col.raw_value,
983                        ));
984                    }
985                }
986                merge_with_clauses(
987                    &mut metadata,
988                    query.ttl_ms,
989                    query.expires_at_ms,
990                    &query.with_metadata,
991                );
992                if let Some(snaps) = returning_snapshots.as_mut() {
993                    snaps.push(fields.clone());
994                }
995                rows.push(CreateRowInput {
996                    collection: query.table.clone(),
997                    fields,
998                    metadata,
999                    node_links: Vec::new(),
1000                    vector_links: Vec::new(),
1001                });
1002            }
1003            let outputs = self.create_rows_batch(CreateRowsBatchInput {
1004                collection: query.table.clone(),
1005                rows,
1006                suppress_events: query.suppress_events,
1007            })?;
1008            inserted_count = outputs.len() as u64;
1009
1010            // Chain mode: commit the new tip to the in-memory cache only after
1011            // the batch persisted successfully. If the batch threw mid-way the
1012            // cache stays on the previous tip and the chain lock releases.
1013            if chain_mode {
1014                if let Some(new_tip) = chain_tip_full.as_ref() {
1015                    self.inner
1016                        .chain_tip_cache
1017                        .lock()
1018                        .insert(query.table.clone(), new_tip.clone());
1019                }
1020            }
1021
1022            // Hypertable chunk routing: if this table was declared via
1023            // CREATE HYPERTABLE, register each row's time-column value
1024            // with the registry so chunk metadata (bounds, row counts,
1025            // TTL eligibility) stays current. This is what lets
1026            // HYPERTABLE_PRUNE_CHUNKS answer real questions + lets the
1027            // retention daemon sweep expired chunks without scanning
1028            // every row.
1029            if let Some(spec) = self.inner.db.hypertables().get(&query.table) {
1030                let time_col = &spec.time_column;
1031                // Find the column's index in the INSERT column list.
1032                if let Some(idx) = query.columns.iter().position(|c| c == time_col) {
1033                    for row in &effective_rows {
1034                        if let Some(Value::Integer(n) | Value::BigInt(n)) = row.get(idx) {
1035                            if *n >= 0 {
1036                                let _ = self.inner.db.hypertables().route(&query.table, *n as u64);
1037                            }
1038                        } else if let Some(Value::UnsignedInteger(n)) = row.get(idx) {
1039                            let _ = self.inner.db.hypertables().route(&query.table, *n);
1040                        }
1041                    }
1042                }
1043            }
1044
1045            if let (Some(items), Some(snaps)) =
1046                (query.returning.as_ref(), returning_snapshots.take())
1047            {
1048                let snaps = row_insert_returning_snapshots(&outputs, snaps);
1049                returning_result = Some(build_returning_result(items, &snaps, Some(&outputs)));
1050            }
1051        } else {
1052            // Issue #419: surface the inserted entity id on every INSERT path.
1053            // For Node/Edge/Vector/Document/Kv we now keep each CreateEntityOutput
1054            // so a RETURNING clause (and the unconditional inserted_ids list,
1055            // below) can expose the engine-assigned id. TimeSeries (the row
1056            // branch in this else) still returns the not-supported error
1057            // because create_timeseries_point isn't plumbed through this fn.
1058            let mut entity_outputs: Vec<crate::application::entity::CreateEntityOutput> =
1059                Vec::with_capacity(effective_rows.len());
1060            let mut returning_field_snaps: Vec<Vec<(String, Value)>> = if query.returning.is_some()
1061            {
1062                Vec::with_capacity(effective_rows.len())
1063            } else {
1064                Vec::new()
1065            };
1066            if matches!(
1067                query.entity_type,
1068                InsertEntityType::Node | InsertEntityType::Edge
1069            ) {
1070                enum PreparedGraphInsert {
1071                    Node {
1072                        fields: Vec<(String, Value)>,
1073                        input: CreateNodeInput,
1074                    },
1075                    Edge {
1076                        fields: Vec<(String, Value)>,
1077                        input: CreateEdgeInput,
1078                    },
1079                }
1080
1081                let mut prepared = Vec::with_capacity(effective_rows.len());
1082                for row_values in &effective_rows {
1083                    if row_values.len() != query.columns.len() {
1084                        return Err(RedDBError::Query(format!(
1085                            "INSERT column count ({}) does not match value count ({})",
1086                            query.columns.len(),
1087                            row_values.len()
1088                        )));
1089                    }
1090
1091                    match query.entity_type {
1092                        InsertEntityType::Node => {
1093                            let (node_values, mut metadata) =
1094                                split_insert_metadata(self, &query.columns, row_values)?;
1095                            merge_with_clauses(
1096                                &mut metadata,
1097                                query.ttl_ms,
1098                                query.expires_at_ms,
1099                                &query.with_metadata,
1100                            );
1101                            ensure_non_tree_reserved_metadata_entries(&metadata)?;
1102                            apply_collection_default_ttl_metadata(
1103                                self,
1104                                &query.table,
1105                                &mut metadata,
1106                            );
1107                            let (columns, values) = pairwise_columns_values(&node_values);
1108                            let label = find_column_value_string(&columns, &values, "label")?;
1109                            let node_type =
1110                                find_column_value_opt_string(&columns, &values, "node_type");
1111                            let properties = extract_remaining_properties(
1112                                &columns,
1113                                &values,
1114                                &["label", "node_type"],
1115                            );
1116                            crate::reserved_fields::ensure_no_reserved_public_item_fields(
1117                                properties.iter().map(|(key, _)| key.as_str()),
1118                                &format!("node '{}'", query.table),
1119                            )?;
1120                            prepared.push(PreparedGraphInsert::Node {
1121                                fields: node_values,
1122                                input: CreateNodeInput {
1123                                    collection: query.table.clone(),
1124                                    label,
1125                                    node_type,
1126                                    properties,
1127                                    metadata,
1128                                    embeddings: Vec::new(),
1129                                    table_links: Vec::new(),
1130                                    node_links: Vec::new(),
1131                                },
1132                            });
1133                        }
1134                        InsertEntityType::Edge => {
1135                            let (edge_values, mut metadata) =
1136                                split_insert_metadata(self, &query.columns, row_values)?;
1137                            merge_with_clauses(
1138                                &mut metadata,
1139                                query.ttl_ms,
1140                                query.expires_at_ms,
1141                                &query.with_metadata,
1142                            );
1143                            ensure_non_tree_reserved_metadata_entries(&metadata)?;
1144                            apply_collection_default_ttl_metadata(
1145                                self,
1146                                &query.table,
1147                                &mut metadata,
1148                            );
1149                            let (columns, values) = pairwise_columns_values(&edge_values);
1150                            let label = find_column_value_string(&columns, &values, "label")?;
1151                            ensure_non_tree_structural_edge_label(&label)?;
1152                            let from_id = resolve_edge_endpoint_any(
1153                                self.inner.db.store().as_ref(),
1154                                &query.table,
1155                                &columns,
1156                                &values,
1157                                &["from_rid", "from"],
1158                            )?;
1159                            let to_id = resolve_edge_endpoint_any(
1160                                self.inner.db.store().as_ref(),
1161                                &query.table,
1162                                &columns,
1163                                &values,
1164                                &["to_rid", "to"],
1165                            )?;
1166                            let weight = find_column_value_f32_opt(&columns, &values, "weight");
1167                            let properties = extract_remaining_properties(
1168                                &columns,
1169                                &values,
1170                                &["label", "from_rid", "to_rid", "from", "to", "weight"],
1171                            );
1172                            crate::reserved_fields::ensure_no_reserved_public_item_fields(
1173                                properties.iter().map(|(key, _)| key.as_str()),
1174                                &format!("edge '{}'", query.table),
1175                            )?;
1176                            prepared.push(PreparedGraphInsert::Edge {
1177                                fields: edge_values,
1178                                input: CreateEdgeInput {
1179                                    collection: query.table.clone(),
1180                                    label,
1181                                    from: EntityId::new(from_id),
1182                                    to: EntityId::new(to_id),
1183                                    weight,
1184                                    properties,
1185                                    metadata,
1186                                },
1187                            });
1188                        }
1189                        _ => unreachable!("prepared graph insert only handles NODE and EDGE"),
1190                    }
1191                }
1192
1193                ensure_graph_insert_contract(self, &query.table)?;
1194                let mut batch = self.inner.db.batch();
1195                for item in prepared {
1196                    match item {
1197                        PreparedGraphInsert::Node { fields, input } => {
1198                            if query.returning.is_some() {
1199                                returning_field_snaps.push(fields);
1200                            }
1201                            let node_type = input.node_type.unwrap_or_else(|| input.label.clone());
1202                            batch = batch.add_node_with_type(
1203                                input.collection,
1204                                input.label,
1205                                node_type,
1206                                input.properties.into_iter().collect(),
1207                                input.metadata.into_iter().collect(),
1208                            );
1209                        }
1210                        PreparedGraphInsert::Edge { fields, input } => {
1211                            if query.returning.is_some() {
1212                                returning_field_snaps.push(fields);
1213                            }
1214                            batch = batch.add_edge(
1215                                input.collection,
1216                                input.label,
1217                                input.from,
1218                                input.to,
1219                                input.weight.unwrap_or(1.0),
1220                                input.properties.into_iter().collect(),
1221                                input.metadata.into_iter().collect(),
1222                            );
1223                        }
1224                    }
1225                }
1226                let batch_result = batch
1227                    .execute()
1228                    .map_err(|err| RedDBError::Internal(format!("{err:?}")))?;
1229                let (ids, entity_kind) = match query.entity_type {
1230                    InsertEntityType::Node => (batch_result.nodes, "graph_node"),
1231                    InsertEntityType::Edge => (batch_result.edges, "graph_edge"),
1232                    _ => unreachable!("prepared graph insert only handles NODE and EDGE"),
1233                };
1234                for id in &ids {
1235                    self.stamp_xmin_if_in_txn(&query.table, *id);
1236                }
1237                if query.returning.is_some() {
1238                    returning_field_snaps = graph_insert_returning_snapshots(
1239                        self.inner.db.store().as_ref(),
1240                        &query.table,
1241                        &ids,
1242                    );
1243                }
1244                self.cdc_emit_insert_batch_no_cache_invalidate(&query.table, &ids, entity_kind);
1245                let store = self.inner.db.store();
1246                entity_outputs.extend(ids.iter().map(|id| {
1247                    crate::application::entity::CreateEntityOutput {
1248                        id: *id,
1249                        entity: store.get(&query.table, *id),
1250                    }
1251                }));
1252                inserted_count = ids.len() as u64;
1253            } else {
1254                for row_values in &effective_rows {
1255                    if row_values.len() != query.columns.len() {
1256                        return Err(RedDBError::Query(format!(
1257                            "INSERT column count ({}) does not match value count ({})",
1258                            query.columns.len(),
1259                            row_values.len()
1260                        )));
1261                    }
1262
1263                    match query.entity_type {
1264                        InsertEntityType::Row => {
1265                            if query.returning.is_some() {
1266                                return Err(RedDBError::Query(
1267                                "RETURNING is not yet supported for this INSERT path (TimeSeries)"
1268                                    .to_string(),
1269                            ));
1270                            }
1271                            let (fields, mut metadata) =
1272                                split_insert_metadata(self, &query.columns, row_values)?;
1273                            merge_with_clauses(
1274                                &mut metadata,
1275                                query.ttl_ms,
1276                                query.expires_at_ms,
1277                                &query.with_metadata,
1278                            );
1279                            self.insert_timeseries_point(&query.table, fields, metadata)?;
1280                        }
1281                        InsertEntityType::Node | InsertEntityType::Edge => {
1282                            unreachable!("NODE and EDGE are handled by the prepared graph path")
1283                        }
1284                        InsertEntityType::Vector => {
1285                            let (vector_values, mut metadata) =
1286                                split_insert_metadata(self, &query.columns, row_values)?;
1287                            merge_with_clauses(
1288                                &mut metadata,
1289                                query.ttl_ms,
1290                                query.expires_at_ms,
1291                                &query.with_metadata,
1292                            );
1293                            let (columns, values) = pairwise_columns_values(&vector_values);
1294                            let dense = find_column_value_vec_f32_any(
1295                                &columns,
1296                                &values,
1297                                &["dense", "embedding"],
1298                            )?;
1299                            merge_vector_metadata_column(&mut metadata, &columns, &values)?;
1300                            let content =
1301                                find_column_value_opt_string(&columns, &values, "content");
1302                            if query.returning.is_some() {
1303                                returning_field_snaps.push(vector_values.clone());
1304                            }
1305                            let input = CreateVectorInput {
1306                                collection: query.table.clone(),
1307                                dense,
1308                                content,
1309                                metadata,
1310                                link_row: None,
1311                                link_node: None,
1312                            };
1313                            entity_outputs.push(self.create_vector(input)?);
1314                        }
1315                        InsertEntityType::Document => {
1316                            let (document_values, mut metadata) =
1317                                split_insert_metadata(self, &query.columns, row_values)?;
1318                            merge_with_clauses(
1319                                &mut metadata,
1320                                query.ttl_ms,
1321                                query.expires_at_ms,
1322                                &query.with_metadata,
1323                            );
1324                            let (columns, values) = pairwise_columns_values(&document_values);
1325                            let body = find_document_body_json(&columns, &values)?;
1326                            let input = CreateDocumentInput {
1327                                collection: query.table.clone(),
1328                                body,
1329                                metadata,
1330                                node_links: Vec::new(),
1331                                vector_links: Vec::new(),
1332                            };
1333                            let output = self.create_document(input)?;
1334                            if query.returning.is_some() {
1335                                let fields = output
1336                                    .entity
1337                                    .as_ref()
1338                                    .map(entity_row_fields_snapshot)
1339                                    .filter(|fields| !fields.is_empty())
1340                                    .unwrap_or(document_values);
1341                                returning_field_snaps.push(fields);
1342                            }
1343                            entity_outputs.push(output);
1344                        }
1345                        InsertEntityType::Kv => {
1346                            let (kv_values, mut metadata) =
1347                                split_insert_metadata(self, &query.columns, row_values)?;
1348                            merge_with_clauses(
1349                                &mut metadata,
1350                                query.ttl_ms,
1351                                query.expires_at_ms,
1352                                &query.with_metadata,
1353                            );
1354                            let (columns, values) = pairwise_columns_values(&kv_values);
1355                            let key = find_column_value_string(&columns, &values, "key")?;
1356                            let value = find_column_value(&columns, &values, "value")?;
1357                            if query.returning.is_some() {
1358                                returning_field_snaps.push(kv_values.clone());
1359                            }
1360                            let input = CreateKvInput {
1361                                collection: query.table.clone(),
1362                                key,
1363                                value,
1364                                metadata,
1365                            };
1366                            entity_outputs.push(self.create_kv(input)?);
1367                        }
1368                    }
1369
1370                    inserted_count += 1;
1371                }
1372            }
1373
1374            if let Some(items) = query.returning.as_ref() {
1375                if !entity_outputs.is_empty() {
1376                    returning_result = Some(build_returning_result(
1377                        items,
1378                        &returning_field_snaps,
1379                        Some(&entity_outputs),
1380                    ));
1381                }
1382            }
1383        }
1384
1385        // Auto-embed pipeline: batch-embed fields across all inserted rows via AiBatchClient.
1386        if let Some(ref embed_config) = query.auto_embed {
1387            let store = self.inner.db.store();
1388            let provider = crate::ai::parse_provider(&embed_config.provider)?;
1389            let is_local_provider = matches!(provider, crate::ai::AiProvider::Local);
1390            // Local provider runs in-process — no API key path applies.
1391            // The pre-flight above already required `MODEL '<name>'`
1392            // for the local case, so the unwrap_or default below only
1393            // ever fires for OpenAI-compatible providers.
1394            let api_key = if is_local_provider {
1395                String::new()
1396            } else {
1397                crate::ai::resolve_api_key_from_runtime(&provider, None, self)?
1398            };
1399            let model = embed_config.model.clone().unwrap_or_else(|| {
1400                std::env::var("REDDB_OPENAI_EMBEDDING_MODEL")
1401                    .ok()
1402                    .unwrap_or_else(|| crate::ai::DEFAULT_OPENAI_EMBEDDING_MODEL.to_string())
1403            });
1404
1405            // Collect the just-inserted rows (most-recently appended, reversed back to insert order).
1406            let manager = store
1407                .get_collection(&query.table)
1408                .ok_or_else(|| RedDBError::NotFound(query.table.clone()))?;
1409            let entities = manager.query_all(|_| true);
1410            let recent: Vec<_> = entities
1411                .into_iter()
1412                .rev()
1413                .take(effective_rows.len())
1414                .collect();
1415
1416            // Collector phase: (entity_index, combined_text) for rows that have non-empty fields.
1417            let entity_combos: Vec<(usize, String)> = recent
1418                .iter()
1419                .enumerate()
1420                .filter_map(|(i, entity)| {
1421                    if let EntityData::Row(ref row) = entity.data {
1422                        if let Some(ref named) = row.named {
1423                            let texts: Vec<String> = embed_config
1424                                .fields
1425                                .iter()
1426                                .filter_map(|field| match named.get(field) {
1427                                    Some(Value::Text(t)) if !t.is_empty() => Some(t.to_string()),
1428                                    _ => None,
1429                                })
1430                                .collect();
1431                            if !texts.is_empty() {
1432                                return Some((i, texts.join(" ")));
1433                            }
1434                        }
1435                    }
1436                    None
1437                })
1438                .collect();
1439
1440            if !entity_combos.is_empty() {
1441                // Batch phase: single provider round-trip for all rows.
1442                let batch_texts: Vec<String> =
1443                    entity_combos.iter().map(|(_, t)| t.clone()).collect();
1444
1445                // Issue #682 — when the provider is `local`, bypass
1446                // AiBatchClient (which is HTTP-only) and dispatch
1447                // directly through the in-process local embedding
1448                // backend. All texts go in one call, mirroring the
1449                // single-round-trip shape of the remote path. The
1450                // local backend does not perform intra-batch dedup —
1451                // each input position gets its own row in the output
1452                // — which keeps the per-row "create_vector" loop
1453                // below correct without additional fan-out logic.
1454                let embeddings = if is_local_provider {
1455                    let response = crate::runtime::ai::local_embedding::embed_local_with_db(
1456                        &self.inner.db,
1457                        &model,
1458                        batch_texts,
1459                    )?;
1460                    response.embeddings
1461                } else {
1462                    let batch_client =
1463                        crate::runtime::ai::batch_client::AiBatchClient::from_runtime(self);
1464
1465                    match tokio::runtime::Handle::try_current() {
1466                        Ok(handle) => tokio::task::block_in_place(|| {
1467                            handle.block_on(batch_client.embed_batch(
1468                                &provider,
1469                                &model,
1470                                &api_key,
1471                                batch_texts,
1472                            ))
1473                        }),
1474                        Err(_) => {
1475                            return Err(RedDBError::Query(
1476                                "AUTO EMBED requires a Tokio runtime context".to_string(),
1477                            ));
1478                        }
1479                    }
1480                    .map_err(|e| RedDBError::Query(e.to_string()))?
1481                };
1482
1483                // Distribute phase: persist one vector per non-empty embedding.
1484                for ((_, combined), dense) in entity_combos.iter().zip(embeddings) {
1485                    if dense.is_empty() {
1486                        continue;
1487                    }
1488                    self.create_vector(CreateVectorInput {
1489                        collection: query.table.clone(),
1490                        dense,
1491                        content: Some(combined.clone()),
1492                        metadata: Vec::new(),
1493                        link_row: None,
1494                        link_node: None,
1495                    })?;
1496                }
1497            }
1498        }
1499
1500        if inserted_count > 0 {
1501            self.note_table_write(&query.table);
1502        }
1503
1504        let mut result = RuntimeQueryResult::dml_result(
1505            raw_query.to_string(),
1506            inserted_count,
1507            "insert",
1508            "runtime-dml",
1509        );
1510        if let Some(returning) = returning_result {
1511            result.result = returning;
1512        }
1513        Ok(result)
1514    }
1515
1516    fn check_insert_column_policy(&self, query: &InsertQuery) -> RedDBResult<()> {
1517        let Some(auth_store) = self.inner.auth_store.read().clone() else {
1518            return Ok(());
1519        };
1520        if !auth_store.iam_authorization_enabled() {
1521            return Ok(());
1522        }
1523        let Some((username, role)) = crate::runtime::impl_core::current_auth_identity() else {
1524            return Ok(());
1525        };
1526
1527        let tenant = crate::runtime::impl_core::current_tenant();
1528        let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
1529        let request = crate::auth::ColumnAccessRequest {
1530            action: "insert".to_string(),
1531            schema: None,
1532            table: query.table.clone(),
1533            columns: query.columns.clone(),
1534        };
1535        let ctx = crate::auth::policies::EvalContext {
1536            principal_tenant: tenant.clone(),
1537            current_tenant: tenant,
1538            peer_ip: None,
1539            mfa_present: false,
1540            now_ms: crate::auth::now_ms(),
1541            principal_is_admin_role: role == crate::auth::Role::Admin,
1542            principal_is_platform_scoped: principal.tenant.is_none(),
1543        };
1544
1545        let outcome = auth_store.check_column_projection_authz(&principal, &request, &ctx);
1546        let table_allowed = matches!(
1547            outcome.table_decision,
1548            crate::auth::policies::Decision::Allow { .. }
1549                | crate::auth::policies::Decision::AdminBypass
1550        );
1551        if !table_allowed {
1552            return Err(RedDBError::Query(format!(
1553                "principal=`{username}` action=`insert` resource=`{}:{}` denied by IAM policy",
1554                outcome.table_resource.kind, outcome.table_resource.name
1555            )));
1556        }
1557        if let Some(denied) = outcome.first_denied_column() {
1558            return Err(RedDBError::Query(format!(
1559                "principal=`{username}` action=`insert` resource=`{}:{}` denied by IAM policy",
1560                denied.resource.kind, denied.resource.name
1561            )));
1562        }
1563
1564        Ok(())
1565    }
1566
1567    pub(crate) fn insert_timeseries_point(
1568        &self,
1569        collection: &str,
1570        fields: Vec<(String, Value)>,
1571        mut metadata: Vec<(String, MetadataValue)>,
1572    ) -> RedDBResult<EntityId> {
1573        apply_collection_default_ttl_metadata(self, collection, &mut metadata);
1574
1575        let (columns, values) = pairwise_columns_values(&fields);
1576        validate_timeseries_insert_columns(&columns)?;
1577
1578        // Issue #577 — AnalyticsSchemaRegistry hook. If the row carries
1579        // an `event_name` whose schema is registered, validate the
1580        // `payload` JSON against it BEFORE any write side-effect. On
1581        // failure we return a typed error and the row is not
1582        // persisted. When no schema is registered for the event name
1583        // (or no `event_name` column is supplied at all) we fall
1584        // through to the normal write path for back-compat with
1585        // existing timeseries rows.
1586        let event_name_opt = find_column_value_opt_string(&columns, &values, "event_name");
1587        let payload_opt = find_column_value_opt_string(&columns, &values, "payload");
1588        if let Some(event_name) = event_name_opt.as_deref() {
1589            let store_for_schema = self.inner.db.store();
1590            if super::analytics_schema_registry::latest(store_for_schema.as_ref(), event_name)
1591                .is_some()
1592            {
1593                let payload_json = payload_opt.as_deref().unwrap_or("{}");
1594                super::analytics_schema_registry::validate(
1595                    store_for_schema.as_ref(),
1596                    event_name,
1597                    payload_json,
1598                )
1599                .map_err(super::analytics_schema_registry::validation_error_to_reddb)?;
1600            }
1601        }
1602
1603        // `metric` is required by the existing timeseries write path;
1604        // when an analytics-style row supplies `event_name` but not
1605        // `metric`, fall back to the event name so the storage path
1606        // still has a non-empty metric tag.
1607        let metric = match find_column_value_opt_string(&columns, &values, "metric") {
1608            Some(m) => m,
1609            None => event_name_opt.clone().ok_or_else(|| {
1610                RedDBError::Query(
1611                    "timeseries INSERT requires either `metric` or `event_name`".to_string(),
1612                )
1613            })?,
1614        };
1615        // `value` is optional for analytics-event rows (which are
1616        // semantically counts of 1); default to 1.0 when missing so
1617        // analytics inserts don't have to fabricate a metric value.
1618        let value = match find_column_value_opt_string(&columns, &values, "value") {
1619            Some(s) => s.parse::<f64>().unwrap_or(1.0),
1620            None => columns
1621                .iter()
1622                .position(|c| c.eq_ignore_ascii_case("value"))
1623                .and_then(|i| match &values[i] {
1624                    Value::Float(f) => Some(*f),
1625                    Value::Integer(n) | Value::BigInt(n) => Some(*n as f64),
1626                    Value::UnsignedInteger(n) => Some(*n as f64),
1627                    _ => None,
1628                })
1629                .unwrap_or(1.0),
1630        };
1631        let timestamp_ns =
1632            find_timeseries_timestamp_ns(&columns, &values)?.unwrap_or_else(current_unix_ns);
1633        let mut tags = find_timeseries_tags(&columns, &values)?;
1634        if let Some(ref name) = event_name_opt {
1635            tags.entry("event_name".to_string())
1636                .or_insert_with(|| name.clone());
1637        }
1638        if let Some(ref payload) = payload_opt {
1639            tags.entry("payload".to_string())
1640                .or_insert_with(|| payload.clone());
1641        }
1642
1643        let mut entity = UnifiedEntity::new(
1644            EntityId::new(0),
1645            EntityKind::TimeSeriesPoint(Box::new(crate::storage::TimeSeriesPointKind {
1646                series: collection.to_string(),
1647                metric: metric.clone(),
1648            })),
1649            EntityData::TimeSeries(crate::storage::TimeSeriesData {
1650                metric,
1651                timestamp_ns,
1652                value,
1653                tags,
1654            }),
1655        );
1656        // MVCC #30: stamp xmin with the active tx xid (inside a tx)
1657        // or an autocommit xid (allocated and committed up-front so
1658        // future snapshots see the row as soon as it lands).
1659        let writer_xid = match self.current_xid() {
1660            Some(xid) => xid,
1661            None => {
1662                let mgr = self.snapshot_manager();
1663                let xid = mgr.begin();
1664                mgr.commit(xid);
1665                xid
1666            }
1667        };
1668        entity.set_xmin(writer_xid);
1669
1670        let store = self.inner.db.store();
1671        let id = store
1672            .insert_auto(collection, entity)
1673            .map_err(|err| RedDBError::Internal(err.to_string()))?;
1674
1675        if !metadata.is_empty() {
1676            let _ = store.set_metadata(
1677                collection,
1678                id,
1679                Metadata::with_fields(metadata.into_iter().collect()),
1680            );
1681        }
1682
1683        self.cdc_emit(
1684            crate::replication::cdc::ChangeOperation::Insert,
1685            collection,
1686            id.raw(),
1687            "timeseries",
1688        );
1689
1690        Ok(id)
1691    }
1692
1693    /// Execute UPDATE table SET col=val, ... WHERE filter
1694    ///
1695    /// Scans the target collection, evaluates the WHERE filter against each
1696    /// record, and patches every matching entity.
1697    pub fn execute_update(
1698        &self,
1699        raw_query: &str,
1700        query: &UpdateQuery,
1701    ) -> RedDBResult<RuntimeQueryResult> {
1702        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
1703        // Issue #523 — blockchain collections are immutable. Reject before
1704        // RLS / RETURNING work so the operator sees a clean 409-mapped
1705        // error instead of a partially-applied mutation surface.
1706        if crate::runtime::blockchain_kind::is_chain(self.inner.db.store().as_ref(), &query.table) {
1707            return Err(RedDBError::InvalidOperation(format!(
1708                "BlockchainCollectionImmutable: UPDATE not allowed on '{}'",
1709                query.table
1710            )));
1711        }
1712        // CollectionContract gate (#50): runs the APPEND ONLY guard
1713        // (and any future contract bits) before RLS / RETURNING work
1714        // so the operator's immutability declaration is honoured
1715        // uniformly and the error message points at the DDL rather
1716        // than at a downstream symptom.
1717        crate::runtime::collection_contract::CollectionContractGate::check(
1718            self,
1719            &query.table,
1720            crate::runtime::collection_contract::MutationKind::Update,
1721        )?;
1722        ensure_update_target_contract(self, &query.table, query.target)?;
1723        ensure_graph_identity_update_target_allowed(query)?;
1724
1725        // Apply RLS augmentation first so every downstream path — plain
1726        // UPDATE, UPDATE...RETURNING, the inner scan — observes the
1727        // same policy-filtered target set. This prevents RETURNING
1728        // from ever exposing rows the UPDATE policy would have
1729        // denied.
1730        let rls_gated = crate::runtime::impl_core::rls_is_enabled(self, &query.table);
1731        let augmented_query: UpdateQuery;
1732        let effective_query: &UpdateQuery = if rls_gated {
1733            let update_filter = crate::runtime::impl_core::rls_policy_filter(
1734                self,
1735                &query.table,
1736                crate::storage::query::ast::PolicyAction::Update,
1737            );
1738            let Some(mut policy) = update_filter else {
1739                // No admitting policy: zero rows affected, empty
1740                // RETURNING (never leak rows the caller can't touch).
1741                let mut response = RuntimeQueryResult::dml_result(
1742                    raw_query.to_string(),
1743                    0,
1744                    "update",
1745                    "runtime-dml-rls",
1746                );
1747                if let Some(items) = query.returning.clone() {
1748                    response.result = build_returning_result(&items, &[], None);
1749                }
1750                return Ok(response);
1751            };
1752            if query.claim_limit.is_some() {
1753                let read_filter = crate::runtime::impl_core::rls_policy_filter(
1754                    self,
1755                    &query.table,
1756                    crate::storage::query::ast::PolicyAction::Select,
1757                );
1758                let Some(read_policy) = read_filter else {
1759                    let mut response = RuntimeQueryResult::dml_result(
1760                        raw_query.to_string(),
1761                        0,
1762                        "update",
1763                        "runtime-dml-rls",
1764                    );
1765                    if let Some(items) = query.returning.clone() {
1766                        response.result = build_returning_result(&items, &[], None);
1767                    }
1768                    return Ok(response);
1769                };
1770                policy = crate::storage::query::ast::Filter::And(
1771                    Box::new(read_policy),
1772                    Box::new(policy),
1773                );
1774            }
1775            let mut augmented = query.clone();
1776            augmented.filter = Some(match augmented.filter.take() {
1777                Some(existing) => {
1778                    crate::storage::query::ast::Filter::And(Box::new(existing), Box::new(policy))
1779                }
1780                None => policy,
1781            });
1782            augmented_query = augmented;
1783            &augmented_query
1784        } else {
1785            query
1786        };
1787
1788        // RETURNING wraps the inner executor and uses the touched-id
1789        // list the inner reports so the post-image reflects exactly
1790        // the rows the UPDATE actually mutated (not whatever a
1791        // separate SELECT might have observed).
1792        if let Some(items) = effective_query.returning.clone() {
1793            let mut inner_query = effective_query.clone();
1794            inner_query.returning = None;
1795            let (mut response, touched_ids) =
1796                self.execute_update_inner_tracked(raw_query, &inner_query)?;
1797
1798            let snapshots = if matches!(
1799                effective_query.target,
1800                UpdateTarget::Nodes | UpdateTarget::Edges
1801            ) {
1802                graph_update_returning_snapshots(self, &effective_query.table, &touched_ids)
1803            } else {
1804                super::dml_target_scan::DmlTargetScan::new(self, &effective_query.table, None, None)
1805                    .row_snapshots(&touched_ids)
1806            };
1807
1808            response.result = build_returning_result(&items, &snapshots, None);
1809            response.engine = "runtime-dml-returning";
1810            return Ok(response);
1811        }
1812
1813        self.execute_update_inner(raw_query, effective_query)
1814    }
1815
1816    /// Back-compat shim: the older entry point ignored touched ids.
1817    fn execute_update_inner(
1818        &self,
1819        raw_query: &str,
1820        query: &UpdateQuery,
1821    ) -> RedDBResult<RuntimeQueryResult> {
1822        self.execute_update_inner_tracked(raw_query, query)
1823            .map(|(res, _)| res)
1824    }
1825
1826    fn execute_update_inner_tracked(
1827        &self,
1828        raw_query: &str,
1829        query: &UpdateQuery,
1830    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
1831        let store = self.inner.db.store();
1832        let effective_filter = effective_update_filter(query);
1833        let compiled_plan = self.compile_update_plan(query)?;
1834        let needs_rmw_lock = update_needs_rmw_lock(query);
1835        let claim_model = update_model_name(update_target_model(query.target));
1836        if query.claim_limit.is_some() {
1837            self.inner
1838                .claim_telemetry
1839                .record_attempt(&query.table, claim_model);
1840        }
1841        let claim_lock = query.claim_limit.map(|_| {
1842            self.inner
1843                .rmw_locks
1844                .lock_for(&query.table, "__table_claim_update__")
1845        });
1846        let _claim_guard = if let Some(lock) = claim_lock.as_ref() {
1847            let Some(guard) = lock.try_lock() else {
1848                let skipped_locked = query.claim_limit.unwrap_or(1);
1849                self.inner.claim_telemetry.record_skipped_locked(
1850                    &query.table,
1851                    claim_model,
1852                    skipped_locked,
1853                );
1854                tracing::debug!(
1855                    target: "reddb::claim",
1856                    collection = %query.table,
1857                    model = claim_model,
1858                    skipped_locked,
1859                    "concurrent claim skipped locked candidates"
1860                );
1861                return Ok((
1862                    RuntimeQueryResult::dml_result(
1863                        raw_query.to_string(),
1864                        0,
1865                        "update",
1866                        "runtime-dml",
1867                    ),
1868                    Vec::new(),
1869                ));
1870            };
1871            Some(guard)
1872        } else {
1873            None
1874        };
1875        let table_rmw_lock = if needs_rmw_lock {
1876            Some(
1877                self.inner
1878                    .rmw_locks
1879                    .lock_for(&query.table, "__table_rmw_update__"),
1880            )
1881        } else {
1882            None
1883        };
1884        let _table_rmw_guard = table_rmw_lock.as_ref().map(|lock| lock.lock());
1885        let mut touched_ids: Vec<EntityId> = Vec::new();
1886        let claim_cap = query.claim_limit.map(|limit| limit as usize);
1887        let limit_cap = claim_cap.or_else(|| query.limit.map(|limit| limit as usize));
1888        let manager = store
1889            .get_collection(&query.table)
1890            .ok_or_else(|| RedDBError::NotFound(query.table.clone()))?;
1891        let scan_limit = if query.order_by.is_empty() {
1892            limit_cap
1893        } else {
1894            None
1895        };
1896        let mut target_scan = super::dml_target_scan::DmlTargetScan::with_update_target(
1897            self,
1898            &query.table,
1899            effective_filter.as_ref(),
1900            scan_limit,
1901            query.target,
1902        );
1903        if needs_rmw_lock {
1904            target_scan = target_scan.with_live_table_rows();
1905        }
1906        let ids_to_update = target_scan.find_target_ids()?;
1907        let order_limit = if query.claim_limit.is_some() {
1908            None
1909        } else {
1910            limit_cap
1911        };
1912        let ids_to_update = if query.order_by.is_empty() {
1913            ids_to_update
1914        } else {
1915            ordered_update_target_ids(&manager, &ids_to_update, &query.order_by, order_limit)
1916        };
1917        let mut ids_to_update = if query.claim_limit.is_some() {
1918            self.filter_claim_locked_target_ids(&query.table, ids_to_update)
1919        } else {
1920            ids_to_update
1921        };
1922        if let Some(claim_cap) = claim_cap {
1923            ids_to_update.truncate(claim_cap);
1924        }
1925        if query.claim_exact
1926            && claim_cap.is_some_and(|claim_count| ids_to_update.len() < claim_count)
1927        {
1928            self.inner
1929                .claim_telemetry
1930                .record_miss(&query.table, claim_model);
1931            return Ok((
1932                RuntimeQueryResult::dml_result(raw_query.to_string(), 0, "update", "runtime-dml"),
1933                Vec::new(),
1934            ));
1935        }
1936
1937        if needs_rmw_lock {
1938            let result = self.execute_update_inner_tracked_locked(
1939                raw_query,
1940                query,
1941                &compiled_plan,
1942                &ids_to_update,
1943                effective_filter.as_ref(),
1944            )?;
1945            if query.claim_limit.is_some() {
1946                self.record_pending_claim_locks_for_touched_ids(&query.table, &result.1);
1947            }
1948            record_claim_outcome(
1949                &self.inner.claim_telemetry,
1950                query.claim_limit,
1951                &query.table,
1952                claim_model,
1953                result.0.affected_rows,
1954            );
1955            return Ok(result);
1956        }
1957
1958        let mut affected: u64 = 0;
1959        for chunk in ids_to_update.chunks(UPDATE_APPLY_CHUNK_SIZE) {
1960            let mut applied_chunk = Vec::with_capacity(chunk.len());
1961            for entity in manager.get_many(chunk).into_iter().flatten() {
1962                let assignments =
1963                    self.materialize_update_assignments_for_entity(query, &entity, &compiled_plan)?;
1964                let applied = self.apply_materialized_update_for_entity(
1965                    query.table.clone(),
1966                    entity,
1967                    &compiled_plan,
1968                    assignments,
1969                )?;
1970                touched_ids.push(applied.id);
1971                applied_chunk.push(applied);
1972            }
1973            self.persist_update_chunk(&applied_chunk)?;
1974            affected += applied_chunk.len() as u64;
1975            let lsns = self.flush_update_chunk(&applied_chunk)?;
1976            if !query.suppress_events {
1977                self.emit_update_events_for_collection(&query.table, &applied_chunk, &lsns)?;
1978            }
1979        }
1980
1981        if affected > 0 {
1982            self.note_table_write(&query.table);
1983        }
1984        if query.claim_limit.is_some() {
1985            self.record_pending_claim_locks_for_touched_ids(&query.table, &touched_ids);
1986        }
1987        record_claim_outcome(
1988            &self.inner.claim_telemetry,
1989            query.claim_limit,
1990            &query.table,
1991            claim_model,
1992            affected,
1993        );
1994
1995        Ok((
1996            RuntimeQueryResult::dml_result(
1997                raw_query.to_string(),
1998                affected,
1999                "update",
2000                "runtime-dml",
2001            ),
2002            touched_ids,
2003        ))
2004    }
2005
2006    fn filter_claim_locked_target_ids(&self, table: &str, ids: Vec<EntityId>) -> Vec<EntityId> {
2007        let conn_id = current_connection_id();
2008        let locks = self.inner.pending_claim_locks.read();
2009        ids.into_iter()
2010            .filter(|id| {
2011                let Some(entity) = self.inner.db.store().get(table, *id) else {
2012                    return false;
2013                };
2014                let key = (table.to_string(), entity.logical_id());
2015                locks
2016                    .get(&key)
2017                    .is_none_or(|owner_conn_id| *owner_conn_id == conn_id)
2018            })
2019            .collect()
2020    }
2021
2022    fn record_pending_claim_locks_for_touched_ids(&self, table: &str, ids: &[EntityId]) {
2023        if self.current_xid().is_none() || ids.is_empty() {
2024            return;
2025        }
2026
2027        let conn_id = current_connection_id();
2028        let store = self.inner.db.store();
2029        let mut locks = self.inner.pending_claim_locks.write();
2030        for id in ids {
2031            let Some(entity) = store.get(table, *id) else {
2032                continue;
2033            };
2034            locks.insert((table.to_string(), entity.logical_id()), conn_id);
2035        }
2036    }
2037
2038    fn execute_update_inner_tracked_locked(
2039        &self,
2040        raw_query: &str,
2041        query: &UpdateQuery,
2042        compiled_plan: &CompiledUpdatePlan,
2043        ids_to_update: &[EntityId],
2044        effective_filter: Option<&Filter>,
2045    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2046        let store = self.inner.db.store();
2047        let mut touched_ids = Vec::new();
2048        let mut lock_entries = Vec::new();
2049
2050        for id in ids_to_update {
2051            let Some(candidate) = store.get(&query.table, *id) else {
2052                continue;
2053            };
2054            let logical_id = candidate.logical_id();
2055            let lock_key = format!("row:{}", logical_id.raw());
2056            let rmw_lock = self.inner.rmw_locks.lock_for(&query.table, &lock_key);
2057            lock_entries.push((lock_key, logical_id, rmw_lock));
2058        }
2059
2060        lock_entries.sort_by(|left, right| left.0.cmp(&right.0));
2061        lock_entries.dedup_by(|left, right| left.0 == right.0);
2062        let _rmw_guards: Vec<_> = lock_entries.iter().map(|entry| entry.2.lock()).collect();
2063
2064        let mut applied_chunk = Vec::new();
2065        for (_, logical_id, _) in &lock_entries {
2066            let Some(entity) = resolve_update_entity_by_logical_id(self, &query.table, *logical_id)
2067            else {
2068                continue;
2069            };
2070            if let Some(filter) = effective_filter {
2071                if !crate::runtime::query_exec::evaluate_entity_filter_with_db(
2072                    Some(self.inner.db.as_ref()),
2073                    &entity,
2074                    filter,
2075                    &query.table,
2076                    &query.table,
2077                ) {
2078                    continue;
2079                }
2080            }
2081
2082            let assignments =
2083                self.materialize_update_assignments_for_entity(query, &entity, compiled_plan)?;
2084            let applied = self.apply_materialized_update_for_entity(
2085                query.table.clone(),
2086                entity,
2087                compiled_plan,
2088                assignments,
2089            )?;
2090            touched_ids.push(applied.id);
2091            applied_chunk.push(applied);
2092        }
2093
2094        let affected = applied_chunk.len() as u64;
2095        if !applied_chunk.is_empty() {
2096            self.persist_update_chunk(&applied_chunk)?;
2097            let lsns = self.flush_update_chunk(&applied_chunk)?;
2098            if !query.suppress_events {
2099                self.emit_update_events_for_collection(&query.table, &applied_chunk, &lsns)?;
2100            }
2101        }
2102
2103        if affected > 0 {
2104            self.note_table_write(&query.table);
2105        }
2106
2107        Ok((
2108            RuntimeQueryResult::dml_result(
2109                raw_query.to_string(),
2110                affected,
2111                "update",
2112                "runtime-dml",
2113            ),
2114            touched_ids,
2115        ))
2116    }
2117
2118    fn compile_update_plan(&self, query: &UpdateQuery) -> RedDBResult<CompiledUpdatePlan> {
2119        let mut static_field_assignments = Vec::new();
2120        let mut static_metadata_assignments = Vec::new();
2121        let mut dynamic_assignments = Vec::new();
2122        let row_contract_plan = build_row_update_contract_plan(&self.db(), &query.table)?;
2123        let mut row_modified_columns = Vec::new();
2124
2125        for (idx, (column, expr)) in query.assignment_exprs.iter().enumerate() {
2126            let compound_op = query.compound_assignment_ops.get(idx).copied().flatten();
2127            let metadata_key = resolve_sql_ttl_metadata_key(column);
2128            if compound_op.is_some() && metadata_key.is_some() {
2129                return Err(RedDBError::Query(format!(
2130                    "compound assignment is only supported for row fields: {column}"
2131                )));
2132            }
2133            if compound_op.is_none() {
2134                if let Ok(value) = fold_expr_to_value(expr.clone()) {
2135                    if let Some(metadata_key) = metadata_key {
2136                        let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2137                        let (canonical_key, canonical_value) =
2138                            canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2139                        static_metadata_assignments
2140                            .push((canonical_key.to_string(), canonical_value));
2141                    } else {
2142                        let value = self.resolve_crypto_sentinel(value)?;
2143                        static_field_assignments.push((
2144                            column.clone(),
2145                            normalize_row_update_assignment_with_plan(
2146                                &query.table,
2147                                column,
2148                                value,
2149                                row_contract_plan.as_ref(),
2150                            )?,
2151                        ));
2152                        row_modified_columns.push(column.clone());
2153                    }
2154                    continue;
2155                }
2156            }
2157
2158            dynamic_assignments.push(CompiledUpdateAssignment {
2159                column: column.clone(),
2160                expr: expr.clone(),
2161                compound_op,
2162                metadata_key,
2163                row_rule: if metadata_key.is_none() {
2164                    if let Some(plan) = row_contract_plan.as_ref() {
2165                        if plan.timestamps_enabled
2166                            && (column == "created_at" || column == "updated_at")
2167                        {
2168                            return Err(RedDBError::Query(format!(
2169                                "collection '{}' manages '{}' automatically — do not set it in UPDATE",
2170                                query.table, column
2171                            )));
2172                        }
2173                        if let Some(rule) = plan.declared_rules.get(column) {
2174                            Some(rule.clone())
2175                        } else if plan.strict_schema {
2176                            return Err(RedDBError::Query(format!(
2177                                "collection '{}' is strict and does not allow undeclared fields: {}",
2178                                query.table, column
2179                            )));
2180                        } else {
2181                            None
2182                        }
2183                    } else {
2184                        None
2185                    }
2186                } else {
2187                    None
2188                },
2189            });
2190            if metadata_key.is_none() {
2191                row_modified_columns.push(column.clone());
2192            }
2193        }
2194
2195        let row_modified_columns = dedupe_update_columns(row_modified_columns);
2196        let row_touches_unique_columns = row_contract_plan.as_ref().is_some_and(|plan| {
2197            row_modified_columns.iter().any(|column| {
2198                plan.unique_columns
2199                    .keys()
2200                    .any(|unique| unique.eq_ignore_ascii_case(column))
2201            })
2202        });
2203
2204        if let Some(ttl_ms) = query.ttl_ms {
2205            static_metadata_assignments
2206                .push(("_ttl_ms".to_string(), metadata_u64_to_value(ttl_ms)));
2207        }
2208        if let Some(expires_at_ms) = query.expires_at_ms {
2209            static_metadata_assignments.push((
2210                "_expires_at".to_string(),
2211                metadata_u64_to_value(expires_at_ms),
2212            ));
2213        }
2214        for (key, val) in &query.with_metadata {
2215            static_metadata_assignments.push((key.clone(), storage_value_to_metadata_value(val)));
2216        }
2217
2218        Ok(CompiledUpdatePlan {
2219            static_field_assignments,
2220            static_metadata_assignments,
2221            dynamic_assignments,
2222            row_contract_plan,
2223            row_modified_columns,
2224            row_touches_unique_columns,
2225        })
2226    }
2227
2228    fn materialize_update_assignments_for_entity(
2229        &self,
2230        query: &UpdateQuery,
2231        entity: &UnifiedEntity,
2232        compiled_plan: &CompiledUpdatePlan,
2233    ) -> RedDBResult<MaterializedUpdateAssignments> {
2234        let mut assignments = MaterializedUpdateAssignments::default();
2235        let mut record: Option<UnifiedRecord> = None;
2236
2237        for assignment in &compiled_plan.dynamic_assignments {
2238            if assignment.compound_op.is_some()
2239                && !matches!(
2240                    entity.data,
2241                    EntityData::Row(_) | EntityData::Node(_) | EntityData::Edge(_)
2242                )
2243            {
2244                return Err(RedDBError::Query(format!(
2245                    "compound assignment is only supported for row or graph UPDATE column '{}'",
2246                    assignment.column
2247                )));
2248            }
2249            if record.is_none() {
2250                record = runtime_any_record_from_entity_ref(entity);
2251            }
2252            let Some(record) = record.as_ref() else {
2253                return Err(RedDBError::Query(format!(
2254                    "UPDATE could not materialize runtime record for entity {} in '{}'",
2255                    entity.id.raw(),
2256                    query.table
2257                )));
2258            };
2259            let rhs = super::expr_eval::evaluate_runtime_expr_with_db(
2260                Some(self.inner.db.as_ref()),
2261                &assignment.expr,
2262                record,
2263                Some(query.table.as_str()),
2264                Some(query.table.as_str()),
2265            )
2266            .ok_or_else(|| {
2267                RedDBError::Query(format!(
2268                    "failed to evaluate UPDATE expression for column '{}'",
2269                    assignment.column
2270                ))
2271            })?;
2272            let value = if let Some(op) = assignment.compound_op {
2273                evaluate_compound_update_assignment(&assignment.column, record, op, rhs)?
2274            } else {
2275                rhs
2276            };
2277
2278            if let Some(metadata_key) = assignment.metadata_key {
2279                let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2280                let (canonical_key, canonical_value) =
2281                    canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2282                assignments
2283                    .dynamic_metadata_assignments
2284                    .push((canonical_key.to_string(), canonical_value));
2285            } else {
2286                assignments.dynamic_field_assignments.push((
2287                    assignment.column.clone(),
2288                    normalize_row_update_value_for_rule(
2289                        &query.table,
2290                        self.resolve_crypto_sentinel(value)?,
2291                        assignment.row_rule.as_ref(),
2292                    )?,
2293                ));
2294            }
2295        }
2296
2297        Ok(assignments)
2298    }
2299
2300    fn apply_materialized_update_for_entity(
2301        &self,
2302        collection: String,
2303        entity: UnifiedEntity,
2304        compiled_plan: &CompiledUpdatePlan,
2305        assignments: MaterializedUpdateAssignments,
2306    ) -> RedDBResult<AppliedEntityMutation> {
2307        if matches!(entity.data, EntityData::Row(_)) {
2308            return self.apply_loaded_sql_update_row_core(
2309                collection,
2310                entity,
2311                &compiled_plan.static_field_assignments,
2312                assignments.dynamic_field_assignments,
2313                &compiled_plan.static_metadata_assignments,
2314                assignments.dynamic_metadata_assignments,
2315                compiled_plan.row_contract_plan.as_ref(),
2316                &compiled_plan.row_modified_columns,
2317                compiled_plan.row_touches_unique_columns,
2318            );
2319        }
2320
2321        ensure_graph_identity_update_allowed(&entity, compiled_plan, &assignments)?;
2322
2323        let operations = build_patch_operations_from_materialized_assignments(
2324            &entity,
2325            compiled_plan,
2326            assignments,
2327        );
2328        self.apply_loaded_patch_entity_core(
2329            collection,
2330            entity,
2331            crate::json::Value::Null,
2332            operations,
2333        )
2334    }
2335
2336    /// Execute DELETE FROM table WHERE filter
2337    pub fn execute_delete(
2338        &self,
2339        raw_query: &str,
2340        query: &DeleteQuery,
2341    ) -> RedDBResult<RuntimeQueryResult> {
2342        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2343        // Issue #523 — blockchain collections are immutable; see
2344        // execute_update for the same gate.
2345        if crate::runtime::blockchain_kind::is_chain(self.inner.db.store().as_ref(), &query.table) {
2346            return Err(RedDBError::InvalidOperation(format!(
2347                "BlockchainCollectionImmutable: DELETE not allowed on '{}'",
2348                query.table
2349            )));
2350        }
2351        // CollectionContract gate (#50) — see execute_update for
2352        // rationale. The gate handles APPEND ONLY rejection and is
2353        // the single point where future contract bits land.
2354        crate::runtime::collection_contract::CollectionContractGate::check(
2355            self,
2356            &query.table,
2357            crate::runtime::collection_contract::MutationKind::Delete,
2358        )?;
2359
2360        // RETURNING on DELETE: capture the pre-image via an internal
2361        // SELECT that reuses the same WHERE, then run the delete with
2362        // the RETURNING clause stripped, then project the captured
2363        // rows through the requested items. The extra SELECT is a
2364        // pragmatic MVP — a future pass can fuse the scan with the
2365        // delete to avoid the second pass over the heap.
2366        if let Some(items) = query.returning.clone() {
2367            let select_sql = delete_to_select_sql(raw_query).ok_or_else(|| {
2368                RedDBError::Query(
2369                    "DELETE ... RETURNING: cannot rewrite query for pre-image scan".to_string(),
2370                )
2371            })?;
2372            let captured = self.execute_query(&select_sql)?;
2373
2374            let mut inner_query = query.clone();
2375            inner_query.returning = None;
2376            let _ = self.execute_delete(raw_query, &inner_query)?;
2377
2378            let snapshots: Vec<Vec<(String, Value)>> = captured
2379                .result
2380                .records
2381                .iter()
2382                .map(|rec| {
2383                    rec.iter_fields()
2384                        .map(|(k, v)| (k.as_ref().to_string(), v.clone()))
2385                        .collect()
2386                })
2387                .collect();
2388            let affected = snapshots.len() as u64;
2389            let result = build_returning_result(&items, &snapshots, None);
2390
2391            let mut response = RuntimeQueryResult::dml_result(
2392                raw_query.to_string(),
2393                affected,
2394                "delete",
2395                "runtime-dml-returning",
2396            );
2397            response.result = result;
2398            return Ok(response);
2399        }
2400        // Row-Level Security enforcement (Phase 2.5.2 PG parity).
2401        //
2402        // When the table has RLS enabled, gate the DELETE by the
2403        // per-role policy set: mutations only touch rows that *every*
2404        // matching `FOR DELETE` policy would accept. No policies =>
2405        // zero rows affected (PG restrictive-default).
2406        if crate::runtime::impl_core::rls_is_enabled(self, &query.table) {
2407            let rls_filter = crate::runtime::impl_core::rls_policy_filter(
2408                self,
2409                &query.table,
2410                crate::storage::query::ast::PolicyAction::Delete,
2411            );
2412            let Some(policy) = rls_filter else {
2413                return Ok(RuntimeQueryResult::dml_result(
2414                    raw_query.to_string(),
2415                    0,
2416                    "delete",
2417                    "runtime-dml-rls",
2418                ));
2419            };
2420            // Fold the policy predicate into the user's WHERE before
2421            // dispatching — the remainder of this function reads the
2422            // filter from `query` via `effective_delete_filter`, which
2423            // respects the updated value.
2424            let mut augmented = query.clone();
2425            augmented.filter = Some(match augmented.filter.take() {
2426                Some(existing) => {
2427                    crate::storage::query::ast::Filter::And(Box::new(existing), Box::new(policy))
2428                }
2429                None => policy,
2430            });
2431            return self.execute_delete_inner(raw_query, &augmented);
2432        }
2433        self.execute_delete_inner(raw_query, query)
2434    }
2435
2436    fn execute_delete_inner(
2437        &self,
2438        raw_query: &str,
2439        query: &DeleteQuery,
2440    ) -> RedDBResult<RuntimeQueryResult> {
2441        let effective_filter = effective_delete_filter(query);
2442
2443        // Find the rows that match the WHERE clause. The "find target
2444        // rows" loop lives in DmlTargetScan so UPDATE (#52) can reuse
2445        // the same scan strategy.
2446        let scan = super::dml_target_scan::DmlTargetScan::new(
2447            self,
2448            &query.table,
2449            effective_filter.as_ref(),
2450            None,
2451        );
2452        let ids_to_delete = scan.find_target_ids()?;
2453
2454        // For event-enabled collections, snapshot the pre-delete state
2455        // before rows are physically removed.
2456        let needs_delete_events =
2457            !query.suppress_events && self.collection_has_delete_subscriptions(&query.table);
2458        let mut pre_images: HashMap<u64, crate::json::Value> = if needs_delete_events {
2459            scan.row_json_pre_images(&ids_to_delete)
2460        } else {
2461            HashMap::new()
2462        };
2463
2464        let mut affected: u64 = 0;
2465        for chunk in ids_to_delete.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2466            let (count, lsns) = self.delete_entities_batch(&query.table, chunk)?;
2467            affected += count;
2468            if needs_delete_events && !lsns.is_empty() {
2469                // lsns.len() == actually-deleted entities; align with chunk ids.
2470                // `delete_batch` may skip missing entities, so we correlate by
2471                // the number returned (they're emitted in chunk order).
2472                let deleted_chunk = &chunk[..lsns.len().min(chunk.len())];
2473                self.emit_delete_events_for_collection(
2474                    &query.table,
2475                    deleted_chunk,
2476                    &lsns,
2477                    &pre_images,
2478                )?;
2479            }
2480        }
2481        pre_images.clear();
2482
2483        if affected > 0 {
2484            self.note_table_write(&query.table);
2485        }
2486
2487        Ok(RuntimeQueryResult::dml_result(
2488            raw_query.to_string(),
2489            affected,
2490            "delete",
2491            "runtime-dml",
2492        ))
2493    }
2494}
2495
2496/// Reject UPDATE … NODES/EDGES that assign to graph identity/topology
2497/// columns regardless of whether any row matches the WHERE clause. The
2498/// per-entity guard below covers only the matched-rows case, but ADR 0019
2499/// declares these columns immutable on the surface itself, so a zero-row
2500/// UPDATE should still surface the same error to operators and SDKs.
2501fn ensure_graph_identity_update_target_allowed(query: &UpdateQuery) -> RedDBResult<()> {
2502    if !matches!(query.target, UpdateTarget::Nodes | UpdateTarget::Edges) {
2503        return Ok(());
2504    }
2505    for (column, _) in &query.assignment_exprs {
2506        if is_immutable_graph_identity_field(column) {
2507            return Err(RedDBError::Query(format!(
2508                "immutable graph field '{column}' cannot be updated"
2509            )));
2510        }
2511    }
2512    Ok(())
2513}
2514
2515fn ensure_graph_identity_update_allowed(
2516    entity: &UnifiedEntity,
2517    compiled_plan: &CompiledUpdatePlan,
2518    assignments: &MaterializedUpdateAssignments,
2519) -> RedDBResult<()> {
2520    if !matches!(entity.data, EntityData::Node(_) | EntityData::Edge(_)) {
2521        return Ok(());
2522    }
2523
2524    for (column, _) in compiled_plan
2525        .static_field_assignments
2526        .iter()
2527        .chain(assignments.dynamic_field_assignments.iter())
2528    {
2529        if is_immutable_graph_identity_field(column) {
2530            return Err(RedDBError::Query(format!(
2531                "immutable graph field '{column}' cannot be updated"
2532            )));
2533        }
2534    }
2535
2536    Ok(())
2537}
2538
2539fn is_immutable_graph_identity_field(column: &str) -> bool {
2540    ["rid", "label", "from_rid", "to_rid", "from", "to"]
2541        .iter()
2542        .any(|reserved| column.eq_ignore_ascii_case(reserved))
2543}
2544
2545fn build_patch_operations_from_materialized_assignments(
2546    entity: &UnifiedEntity,
2547    compiled_plan: &CompiledUpdatePlan,
2548    assignments: MaterializedUpdateAssignments,
2549) -> Vec<PatchEntityOperation> {
2550    let mut operations = Vec::with_capacity(
2551        compiled_plan.static_field_assignments.len()
2552            + compiled_plan.static_metadata_assignments.len()
2553            + assignments.dynamic_field_assignments.len()
2554            + assignments.dynamic_metadata_assignments.len(),
2555    );
2556
2557    for (column, value) in &compiled_plan.static_field_assignments {
2558        operations.push(PatchEntityOperation {
2559            op: PatchEntityOperationType::Set,
2560            path: update_patch_path_for_entity(entity, column),
2561            value: Some(storage_value_to_json(value)),
2562        });
2563    }
2564
2565    for (column, value) in assignments.dynamic_field_assignments {
2566        operations.push(PatchEntityOperation {
2567            op: PatchEntityOperationType::Set,
2568            path: update_patch_path_for_entity(entity, &column),
2569            value: Some(storage_value_to_json(&value)),
2570        });
2571    }
2572
2573    for (key, value) in &compiled_plan.static_metadata_assignments {
2574        operations.push(PatchEntityOperation {
2575            op: PatchEntityOperationType::Set,
2576            path: vec!["metadata".to_string(), key.clone()],
2577            value: Some(metadata_value_to_json(value)),
2578        });
2579    }
2580
2581    for (key, value) in assignments.dynamic_metadata_assignments {
2582        operations.push(PatchEntityOperation {
2583            op: PatchEntityOperationType::Set,
2584            path: vec!["metadata".to_string(), key],
2585            value: Some(metadata_value_to_json(&value)),
2586        });
2587    }
2588
2589    operations
2590}
2591
2592fn update_patch_path_for_entity(entity: &UnifiedEntity, column: &str) -> Vec<String> {
2593    if matches!(
2594        (&entity.kind, &entity.data),
2595        (
2596            crate::storage::EntityKind::GraphNode(_),
2597            EntityData::Node(_)
2598        )
2599    ) && column.eq_ignore_ascii_case("node_type")
2600    {
2601        return vec!["node_type".to_string()];
2602    }
2603    if matches!(
2604        (&entity.kind, &entity.data),
2605        (
2606            crate::storage::EntityKind::GraphEdge(_),
2607            EntityData::Edge(_)
2608        )
2609    ) && column.eq_ignore_ascii_case("weight")
2610    {
2611        return vec!["weight".to_string()];
2612    }
2613    vec!["fields".to_string(), column.to_string()]
2614}
2615
2616/// Rewrite `DELETE FROM <table> [WHERE …] [RETURNING …]` as
2617/// `SELECT * FROM <table> [WHERE …]` so the delete executor can
2618/// capture the pre-image before actually removing the rows. Returns
2619/// `None` when the input does not start with `DELETE`.
2620///
2621/// Case-insensitive on the keywords. Preserves everything between
2622/// the table name and the RETURNING clause, so WHERE / ORDER BY /
2623/// LIMIT survive untouched. The RETURNING tail — if present — is
2624/// truncated at the first top-level `RETURNING` token.
2625fn delete_to_select_sql(sql: &str) -> Option<String> {
2626    let trimmed = sql.trim_start();
2627    let lowered = trimmed.to_ascii_lowercase();
2628    if !lowered.starts_with("delete ") && !lowered.starts_with("delete\t") {
2629        return None;
2630    }
2631    // Find `FROM` after DELETE.
2632    let from_idx = lowered.find(" from ")?;
2633    let after_from = &trimmed[from_idx + " from ".len()..];
2634    let after_from_lc = &lowered[from_idx + " from ".len()..];
2635
2636    // Cut off the RETURNING tail (a naive search — the RETURNING
2637    // clause only appears once per statement at top level in our
2638    // grammar). Matches whitespace-bounded tokens to avoid clipping
2639    // `RETURNING` inside a string literal.
2640    let mut body = after_from.to_string();
2641    if let Some(pos) = find_top_level_keyword(after_from_lc, "returning") {
2642        body.truncate(pos);
2643    }
2644    Some(format!("SELECT * FROM {}", body.trim_end()))
2645}
2646
2647/// Find the byte offset of a whitespace-bounded keyword in a
2648/// lowercased haystack, skipping matches inside single-quoted
2649/// string literals. Naive — no escape handling — but enough for
2650/// the shapes the DML parser emits.
2651fn find_top_level_keyword(haystack: &str, needle: &str) -> Option<usize> {
2652    let bytes = haystack.as_bytes();
2653    let nlen = needle.len();
2654    let mut i = 0usize;
2655    let mut in_string = false;
2656    while i < bytes.len() {
2657        let c = bytes[i];
2658        if c == b'\'' {
2659            in_string = !in_string;
2660            i += 1;
2661            continue;
2662        }
2663        if !in_string
2664            && i + nlen <= bytes.len()
2665            && &bytes[i..i + nlen] == needle.as_bytes()
2666            && (i == 0 || bytes[i - 1].is_ascii_whitespace())
2667            && (i + nlen == bytes.len() || bytes[i + nlen].is_ascii_whitespace())
2668        {
2669            return Some(i);
2670        }
2671        i += 1;
2672    }
2673    None
2674}
2675
2676/// Build a `UnifiedResult` from the rows affected by a DML statement plus
2677/// its `RETURNING` clause. Each snapshot is a list of (column, value) pairs
2678/// for one affected row; `outputs`, when provided, supplies the engine-
2679/// assigned entity id for the same row (INSERT path). Projection honours
2680/// the RETURNING items: `*` expands to every snapshot column plus
2681/// the public row envelope when available.
2682fn build_returning_result(
2683    items: &[ReturningItem],
2684    snapshots: &[Vec<(String, Value)>],
2685    outputs: Option<&[CreateEntityOutput]>,
2686) -> UnifiedResult {
2687    let project_all = items.iter().any(|it| matches!(it, ReturningItem::All));
2688    let public_item_outputs = outputs.is_some_and(|outs| {
2689        outs.first()
2690            .and_then(|out| out.entity.as_ref())
2691            .is_some_and(|entity| public_returning_item_kind(entity).is_some())
2692    });
2693
2694    let mut columns: Vec<String> = if project_all {
2695        let mut cols: Vec<String> = Vec::new();
2696        if public_item_outputs {
2697            cols.extend(
2698                [
2699                    "rid",
2700                    "collection",
2701                    "kind",
2702                    "tenant",
2703                    "created_at",
2704                    "updated_at",
2705                ]
2706                .into_iter()
2707                .map(str::to_string),
2708            );
2709        } else if outputs.is_some() {
2710            cols.push("rid".to_string());
2711        }
2712        if let Some(first) = snapshots.first() {
2713            for (name, _) in first {
2714                cols.push(name.clone());
2715            }
2716        }
2717        cols
2718    } else {
2719        items
2720            .iter()
2721            .filter_map(|it| match it {
2722                ReturningItem::Column(c) => Some(c.clone()),
2723                ReturningItem::All => None,
2724            })
2725            .collect()
2726    };
2727    // Guarantee unique order-preserving column list.
2728    {
2729        let mut seen = std::collections::HashSet::new();
2730        columns.retain(|c| seen.insert(c.clone()));
2731    }
2732
2733    let mut records: Vec<UnifiedRecord> = Vec::with_capacity(snapshots.len());
2734    for (idx, snap) in snapshots.iter().enumerate() {
2735        let mut values: HashMap<Arc<str>, Value> = HashMap::with_capacity(columns.len());
2736        if let Some(outs) = outputs {
2737            if let Some(out) = outs.get(idx) {
2738                if let Some(entity) = out.entity.as_ref() {
2739                    if let Some(kind) = public_returning_item_kind(entity) {
2740                        values.insert(
2741                            Arc::clone(&sys_key_rid()),
2742                            Value::UnsignedInteger(out.id.raw()),
2743                        );
2744                        values.insert(
2745                            Arc::clone(&sys_key_collection()),
2746                            Value::text(entity.kind.collection().to_string()),
2747                        );
2748                        values.insert(Arc::clone(&sys_key_kind()), Value::text(kind.to_string()));
2749                        values.insert(
2750                            Arc::clone(&sys_key_created_at()),
2751                            Value::UnsignedInteger(entity.created_at),
2752                        );
2753                        values.insert(
2754                            Arc::clone(&sys_key_updated_at()),
2755                            Value::UnsignedInteger(entity.updated_at),
2756                        );
2757                    } else {
2758                        values.insert(
2759                            Arc::clone(&sys_key_rid()),
2760                            Value::Integer(out.id.raw() as i64),
2761                        );
2762                    }
2763                } else {
2764                    values.insert(
2765                        Arc::clone(&sys_key_rid()),
2766                        Value::Integer(out.id.raw() as i64),
2767                    );
2768                }
2769            }
2770        }
2771        for (name, val) in snap {
2772            values.insert(Arc::from(name.as_str()), val.clone());
2773        }
2774        if !values.contains_key("tenant") {
2775            let tenant = values.get("tenant_id").cloned().unwrap_or(Value::Null);
2776            values.insert(Arc::clone(&sys_key_tenant()), tenant);
2777        }
2778        let mut rec = UnifiedRecord::default();
2779        // Only keep projected columns on the record.
2780        for col in &columns {
2781            if let Some(v) = values.get(col.as_str()) {
2782                rec.set_arc(Arc::from(col.as_str()), v.clone());
2783            }
2784        }
2785        records.push(rec);
2786    }
2787
2788    UnifiedResult {
2789        columns,
2790        records,
2791        stats: Default::default(),
2792        pre_serialized_json: None,
2793    }
2794}
2795
2796fn public_returning_item_kind(entity: &crate::storage::UnifiedEntity) -> Option<&'static str> {
2797    match (&entity.kind, &entity.data) {
2798        (crate::storage::EntityKind::GraphNode(_), crate::storage::EntityData::Node(_)) => {
2799            Some("node")
2800        }
2801        (crate::storage::EntityKind::GraphEdge(_), crate::storage::EntityData::Edge(_)) => {
2802            Some("edge")
2803        }
2804        (_, crate::storage::EntityData::Row(_)) => Some(public_returning_row_kind(entity)),
2805        // #1369 — every entity model must expose its `rid` in RETURNING *.
2806        // Vectors carry their payload in `EntityData::Vector`, not `Row`, so
2807        // they were falling through to a no-rid envelope
2808        // and `RETURNING *` never surfaced the entity-id.
2809        (_, crate::storage::EntityData::Vector(_)) => Some("vector"),
2810        _ => None,
2811    }
2812}
2813
2814fn public_returning_row_kind(entity: &crate::storage::UnifiedEntity) -> &'static str {
2815    let Some(row) = entity.data.as_row() else {
2816        return "row";
2817    };
2818
2819    let is_kv = row.named.as_ref().is_some_and(|named| {
2820        (named.len() == 2 && named.contains_key("key") && named.contains_key("value"))
2821            || (named.len() == 1 && (named.contains_key("key") || named.contains_key("value")))
2822    });
2823    if is_kv {
2824        return "kv";
2825    }
2826
2827    let is_document = row
2828        .named
2829        .as_ref()
2830        .is_some_and(|named| named.values().any(runtime_returning_documentish_value))
2831        || row.columns.iter().any(runtime_returning_documentish_value);
2832    if is_document {
2833        "document"
2834    } else {
2835        "row"
2836    }
2837}
2838
2839fn runtime_returning_documentish_value(value: &Value) -> bool {
2840    matches!(value, Value::Json(_) | Value::Blob(_))
2841}
2842
2843fn row_insert_returning_snapshots(
2844    outputs: &[CreateEntityOutput],
2845    fallback: Vec<Vec<(String, Value)>>,
2846) -> Vec<Vec<(String, Value)>> {
2847    outputs
2848        .iter()
2849        .enumerate()
2850        .map(|(idx, out)| {
2851            out.entity
2852                .as_ref()
2853                .map(entity_row_fields_snapshot)
2854                .filter(|snap| !snap.is_empty())
2855                .unwrap_or_else(|| fallback.get(idx).cloned().unwrap_or_default())
2856        })
2857        .collect()
2858}
2859
2860fn graph_insert_returning_snapshots(
2861    store: &crate::storage::unified::UnifiedStore,
2862    collection: &str,
2863    ids: &[EntityId],
2864) -> Vec<Vec<(String, Value)>> {
2865    let Some(manager) = store.get_collection(collection) else {
2866        return Vec::new();
2867    };
2868
2869    ids.iter()
2870        .filter_map(|id| manager.get(*id))
2871        .filter_map(|entity| {
2872            let mut record = runtime_any_record_from_entity_ref(&entity)?;
2873            record.set_arc(sys_key_collection(), Value::text(collection.to_string()));
2874            Some(record)
2875        })
2876        .map(|record| {
2877            record
2878                .iter_fields()
2879                .map(|(key, value)| (key.as_ref().to_string(), value.clone()))
2880                .collect()
2881        })
2882        .collect()
2883}
2884
2885fn graph_update_returning_snapshots(
2886    runtime: &RedDBRuntime,
2887    collection: &str,
2888    ids: &[EntityId],
2889) -> Vec<Vec<(String, Value)>> {
2890    let store = runtime.db().store();
2891    let Some(manager) = store.get_collection(collection) else {
2892        return Vec::new();
2893    };
2894
2895    manager
2896        .get_many(ids)
2897        .into_iter()
2898        .flatten()
2899        .filter_map(|entity| runtime_any_record_from_entity_ref(&entity))
2900        .map(|record| {
2901            record
2902                .iter_fields()
2903                .map(|(key, value)| (key.as_ref().to_string(), value.clone()))
2904                .collect()
2905        })
2906        .collect()
2907}
2908
2909fn ensure_update_target_contract(
2910    runtime: &RedDBRuntime,
2911    collection: &str,
2912    target: UpdateTarget,
2913) -> RedDBResult<()> {
2914    let Some(contract) = runtime.db().collection_contract(collection) else {
2915        return Ok(());
2916    };
2917    if update_target_contract_is_advisory(&contract)
2918        || update_target_allows_model(contract.declared_model, update_target_model(target))
2919    {
2920        return Ok(());
2921    }
2922    Err(RedDBError::InvalidOperation(format!(
2923        "collection '{}' is declared as '{}' and does not allow '{}' updates",
2924        collection,
2925        update_model_name(contract.declared_model),
2926        update_model_name(update_target_model(target))
2927    )))
2928}
2929
2930fn update_target_contract_is_advisory(contract: &crate::physical::CollectionContract) -> bool {
2931    matches!(
2932        (&contract.origin, &contract.schema_mode),
2933        (
2934            crate::physical::ContractOrigin::Implicit,
2935            crate::catalog::SchemaMode::Dynamic,
2936        )
2937    )
2938}
2939
2940fn update_target_model(target: UpdateTarget) -> crate::catalog::CollectionModel {
2941    match target {
2942        UpdateTarget::Rows => crate::catalog::CollectionModel::Table,
2943        UpdateTarget::Documents => crate::catalog::CollectionModel::Document,
2944        UpdateTarget::Kv => crate::catalog::CollectionModel::Kv,
2945        UpdateTarget::Nodes | UpdateTarget::Edges => crate::catalog::CollectionModel::Graph,
2946    }
2947}
2948
2949fn update_target_allows_model(
2950    declared_model: crate::catalog::CollectionModel,
2951    requested_model: crate::catalog::CollectionModel,
2952) -> bool {
2953    declared_model == requested_model || declared_model == crate::catalog::CollectionModel::Mixed
2954}
2955
2956fn update_model_name(model: crate::catalog::CollectionModel) -> &'static str {
2957    match model {
2958        crate::catalog::CollectionModel::Table => "table",
2959        crate::catalog::CollectionModel::Document => "document",
2960        crate::catalog::CollectionModel::Graph => "graph",
2961        crate::catalog::CollectionModel::Vector => "vector",
2962        crate::catalog::CollectionModel::Hll => "hll",
2963        crate::catalog::CollectionModel::Sketch => "sketch",
2964        crate::catalog::CollectionModel::Filter => "filter",
2965        crate::catalog::CollectionModel::Kv => "kv",
2966        crate::catalog::CollectionModel::Config => "config",
2967        crate::catalog::CollectionModel::Vault => "vault",
2968        crate::catalog::CollectionModel::Mixed => "mixed",
2969        crate::catalog::CollectionModel::TimeSeries => "timeseries",
2970        crate::catalog::CollectionModel::Queue => "queue",
2971        crate::catalog::CollectionModel::Metrics => "metrics",
2972    }
2973}
2974
2975fn ensure_graph_insert_contract(runtime: &RedDBRuntime, collection: &str) -> RedDBResult<()> {
2976    let db = runtime.db();
2977    if let Some(contract) = db.collection_contract(collection) {
2978        let advisory_implicit_dynamic = matches!(
2979            (&contract.origin, &contract.schema_mode),
2980            (
2981                crate::physical::ContractOrigin::Implicit,
2982                crate::catalog::SchemaMode::Dynamic,
2983            )
2984        );
2985        if advisory_implicit_dynamic
2986            || matches!(
2987                contract.declared_model,
2988                crate::catalog::CollectionModel::Graph | crate::catalog::CollectionModel::Mixed
2989            )
2990        {
2991            return Ok(());
2992        }
2993        return Err(RedDBError::InvalidOperation(format!(
2994            "collection '{}' is declared as '{:?}' and does not allow 'Graph' writes",
2995            collection, contract.declared_model
2996        )));
2997    }
2998
2999    let now = std::time::SystemTime::now()
3000        .duration_since(std::time::UNIX_EPOCH)
3001        .unwrap_or_default()
3002        .as_millis();
3003    db.save_collection_contract(crate::physical::CollectionContract {
3004        name: collection.to_string(),
3005        declared_model: crate::catalog::CollectionModel::Graph,
3006        schema_mode: crate::catalog::SchemaMode::Dynamic,
3007        origin: crate::physical::ContractOrigin::Implicit,
3008        version: 1,
3009        created_at_unix_ms: now,
3010        updated_at_unix_ms: now,
3011        default_ttl_ms: db.collection_default_ttl_ms(collection),
3012        vector_dimension: None,
3013        vector_metric: None,
3014        context_index_fields: Vec::new(),
3015        declared_columns: Vec::new(),
3016        table_def: None,
3017        timestamps_enabled: false,
3018        context_index_enabled: false,
3019        metrics_raw_retention_ms: None,
3020        metrics_rollup_policies: Vec::new(),
3021        metrics_tenant_identity: None,
3022        metrics_namespace: None,
3023        append_only: false,
3024        subscriptions: Vec::new(),
3025        analytics_config: Vec::new(),
3026        session_key: None,
3027        session_gap_ms: None,
3028        retention_duration_ms: None,
3029        analytical_storage: None,
3030
3031        ai_policy: None,
3032    })
3033    .map(|_| ())
3034    .map_err(|err| RedDBError::Internal(err.to_string()))
3035}
3036
3037fn update_needs_rmw_lock(query: &UpdateQuery) -> bool {
3038    query
3039        .assignment_exprs
3040        .iter()
3041        .enumerate()
3042        .any(|(idx, (column, expr))| {
3043            query
3044                .compound_assignment_ops
3045                .get(idx)
3046                .is_some_and(|op| op.is_some())
3047                || expr_references_update_column(expr, &query.table, column)
3048        })
3049}
3050
3051fn record_claim_outcome(
3052    telemetry: &crate::runtime::claim_telemetry::ClaimTelemetryCounters,
3053    claim_limit: Option<u64>,
3054    table: &str,
3055    model: &str,
3056    affected: u64,
3057) {
3058    if claim_limit.is_none() {
3059        return;
3060    }
3061    if affected == 0 {
3062        telemetry.record_miss(table, model);
3063        tracing::debug!(
3064            target: "reddb::claim",
3065            collection = table,
3066            model,
3067            "concurrent claim missed"
3068        );
3069    } else {
3070        telemetry.record_successful(table, model, affected);
3071        tracing::debug!(
3072            target: "reddb::claim",
3073            collection = table,
3074            model,
3075            successful = affected,
3076            "concurrent claim succeeded"
3077        );
3078    }
3079}
3080
3081fn evaluate_compound_update_assignment(
3082    column: &str,
3083    record: &UnifiedRecord,
3084    op: BinOp,
3085    rhs: Value,
3086) -> RedDBResult<Value> {
3087    let lhs = record.get(column).ok_or_else(|| {
3088        RedDBError::Query(format!(
3089            "compound assignment requires existing numeric field '{column}'"
3090        ))
3091    })?;
3092    if matches!(lhs, Value::Null) {
3093        return Err(RedDBError::Query(format!(
3094            "compound assignment requires non-null numeric field '{column}'"
3095        )));
3096    }
3097    apply_compound_numeric_op(column, op, lhs, &rhs)
3098}
3099
3100fn apply_compound_numeric_op(
3101    column: &str,
3102    op: BinOp,
3103    lhs: &Value,
3104    rhs: &Value,
3105) -> RedDBResult<Value> {
3106    let Some(lhs_number) = CompoundNumber::from_value(lhs) else {
3107        return Err(RedDBError::Query(format!(
3108            "compound assignment requires numeric field '{column}'"
3109        )));
3110    };
3111    let Some(rhs_number) = CompoundNumber::from_value(rhs) else {
3112        return Err(RedDBError::Query(format!(
3113            "compound assignment requires numeric right-hand value for field '{column}'"
3114        )));
3115    };
3116
3117    if lhs_number.is_float() || rhs_number.is_float() || matches!(op, BinOp::Div) {
3118        let a = lhs_number.as_f64();
3119        let b = rhs_number.as_f64();
3120        let out = match op {
3121            BinOp::Add => a + b,
3122            BinOp::Sub => a - b,
3123            BinOp::Mul => a * b,
3124            BinOp::Div => {
3125                if b == 0.0 {
3126                    return Err(RedDBError::Query(format!(
3127                        "division by zero in compound assignment for field '{column}'"
3128                    )));
3129                }
3130                a / b
3131            }
3132            BinOp::Mod => {
3133                if b == 0.0 {
3134                    return Err(RedDBError::Query(format!(
3135                        "modulo by zero in compound assignment for field '{column}'"
3136                    )));
3137                }
3138                a % b
3139            }
3140            _ => {
3141                return Err(RedDBError::Query(format!(
3142                    "unsupported compound assignment operator for field '{column}'"
3143                )));
3144            }
3145        };
3146        if !out.is_finite() {
3147            return Err(RedDBError::Query(format!(
3148                "numeric overflow in compound assignment for field '{column}'"
3149            )));
3150        }
3151        return Ok(Value::Float(out));
3152    }
3153
3154    let a = lhs_number.as_i128();
3155    let b = rhs_number.as_i128();
3156    let out = match op {
3157        BinOp::Add => a.checked_add(b),
3158        BinOp::Sub => a.checked_sub(b),
3159        BinOp::Mul => a.checked_mul(b),
3160        BinOp::Mod => {
3161            if b == 0 {
3162                return Err(RedDBError::Query(format!(
3163                    "modulo by zero in compound assignment for field '{column}'"
3164                )));
3165            }
3166            a.checked_rem(b)
3167        }
3168        BinOp::Div => unreachable!("integer division is handled by the float branch"),
3169        _ => None,
3170    }
3171    .ok_or_else(|| {
3172        RedDBError::Query(format!(
3173            "numeric overflow in compound assignment for field '{column}'"
3174        ))
3175    })?;
3176
3177    if matches!(lhs, Value::UnsignedInteger(_)) {
3178        let value = u64::try_from(out).map_err(|_| {
3179            RedDBError::Query(format!(
3180                "numeric overflow in compound assignment for field '{column}'"
3181            ))
3182        })?;
3183        Ok(Value::UnsignedInteger(value))
3184    } else {
3185        let value = i64::try_from(out).map_err(|_| {
3186            RedDBError::Query(format!(
3187                "numeric overflow in compound assignment for field '{column}'"
3188            ))
3189        })?;
3190        Ok(Value::Integer(value))
3191    }
3192}
3193
3194#[derive(Clone, Copy)]
3195enum CompoundNumber {
3196    Integer(i128),
3197    Float(f64),
3198}
3199
3200impl CompoundNumber {
3201    fn from_value(value: &Value) -> Option<Self> {
3202        match value {
3203            Value::Integer(value) | Value::BigInt(value) => Some(Self::Integer(*value as i128)),
3204            Value::UnsignedInteger(value) => Some(Self::Integer(*value as i128)),
3205            Value::Float(value) => value.is_finite().then_some(Self::Float(*value)),
3206            Value::Decimal(value) => Some(Self::Float(*value as f64 / 10_000.0)),
3207            _ => None,
3208        }
3209    }
3210
3211    fn is_float(self) -> bool {
3212        matches!(self, Self::Float(_))
3213    }
3214
3215    fn as_f64(self) -> f64 {
3216        match self {
3217            Self::Integer(value) => value as f64,
3218            Self::Float(value) => value,
3219        }
3220    }
3221
3222    fn as_i128(self) -> i128 {
3223        match self {
3224            Self::Integer(value) => value,
3225            Self::Float(_) => unreachable!("float compound number used as integer"),
3226        }
3227    }
3228}
3229
3230fn expr_references_update_column(expr: &Expr, table_name: &str, target_column: &str) -> bool {
3231    match expr {
3232        Expr::Literal { .. } | Expr::Parameter { .. } | Expr::Subquery { .. } => false,
3233        Expr::Column { field, .. } => {
3234            field_ref_matches_update_column(field, table_name, target_column)
3235        }
3236        Expr::BinaryOp { lhs, rhs, .. } => {
3237            expr_references_update_column(lhs, table_name, target_column)
3238                || expr_references_update_column(rhs, table_name, target_column)
3239        }
3240        Expr::UnaryOp { operand, .. } | Expr::Cast { inner: operand, .. } => {
3241            expr_references_update_column(operand, table_name, target_column)
3242        }
3243        Expr::FunctionCall { args, .. } => args
3244            .iter()
3245            .any(|arg| expr_references_update_column(arg, table_name, target_column)),
3246        Expr::Case {
3247            branches, else_, ..
3248        } => {
3249            branches.iter().any(|(cond, value)| {
3250                expr_references_update_column(cond, table_name, target_column)
3251                    || expr_references_update_column(value, table_name, target_column)
3252            }) || else_
3253                .as_deref()
3254                .is_some_and(|expr| expr_references_update_column(expr, table_name, target_column))
3255        }
3256        Expr::IsNull { operand, .. } => {
3257            expr_references_update_column(operand, table_name, target_column)
3258        }
3259        Expr::InList { target, values, .. } => {
3260            expr_references_update_column(target, table_name, target_column)
3261                || values
3262                    .iter()
3263                    .any(|value| expr_references_update_column(value, table_name, target_column))
3264        }
3265        Expr::Between {
3266            target, low, high, ..
3267        } => {
3268            expr_references_update_column(target, table_name, target_column)
3269                || expr_references_update_column(low, table_name, target_column)
3270                || expr_references_update_column(high, table_name, target_column)
3271        }
3272        Expr::WindowFunctionCall { args, window, .. } => {
3273            args.iter()
3274                .any(|arg| expr_references_update_column(arg, table_name, target_column))
3275                || window
3276                    .partition_by
3277                    .iter()
3278                    .any(|e| expr_references_update_column(e, table_name, target_column))
3279                || window
3280                    .order_by
3281                    .iter()
3282                    .any(|o| expr_references_update_column(&o.expr, table_name, target_column))
3283        }
3284    }
3285}
3286
3287fn field_ref_matches_update_column(
3288    field: &FieldRef,
3289    table_name: &str,
3290    target_column: &str,
3291) -> bool {
3292    match field {
3293        FieldRef::TableColumn { table, column } => {
3294            column.eq_ignore_ascii_case(target_column)
3295                && (table.is_empty() || table.eq_ignore_ascii_case(table_name))
3296        }
3297        FieldRef::NodeProperty { .. } | FieldRef::EdgeProperty { .. } | FieldRef::NodeId { .. } => {
3298            false
3299        }
3300    }
3301}
3302
3303fn resolve_update_entity_by_logical_id(
3304    runtime: &RedDBRuntime,
3305    table: &str,
3306    logical_id: EntityId,
3307) -> Option<UnifiedEntity> {
3308    let store = runtime.inner.db.store();
3309    if let Some(entity) = store.get_table_row_by_logical_id(table, logical_id) {
3310        return Some(entity);
3311    }
3312    // Fallback for non-table-row entities (graph nodes/edges, etc.) where
3313    // entity_id == logical_id and the MVCC table-row resolver doesn't apply.
3314    store.get(table, logical_id)
3315}
3316
3317fn update_cdc_item_kind(
3318    runtime: &RedDBRuntime,
3319    collection: &str,
3320    entity: &UnifiedEntity,
3321) -> &'static str {
3322    match &entity.data {
3323        EntityData::Node(_) => return "node",
3324        EntityData::Edge(_) => return "edge",
3325        _ => {}
3326    }
3327
3328    match runtime
3329        .db()
3330        .collection_contract(collection)
3331        .map(|contract| contract.declared_model)
3332    {
3333        Some(crate::catalog::CollectionModel::Document) => "document",
3334        Some(crate::catalog::CollectionModel::Kv)
3335        | Some(crate::catalog::CollectionModel::Vault) => "kv",
3336        _ => "row",
3337    }
3338}
3339
3340fn ordered_update_target_ids(
3341    manager: &Arc<crate::storage::SegmentManager>,
3342    entity_ids: &[EntityId],
3343    order_by: &[OrderByClause],
3344    limit: Option<usize>,
3345) -> Vec<EntityId> {
3346    let mut entities: Vec<UnifiedEntity> =
3347        manager.get_many(entity_ids).into_iter().flatten().collect();
3348    entities.sort_by(|left, right| compare_update_order(left, right, order_by));
3349    if let Some(limit) = limit {
3350        entities.truncate(limit);
3351    }
3352    entities.into_iter().map(|entity| entity.id).collect()
3353}
3354
3355fn compare_update_order(
3356    left: &UnifiedEntity,
3357    right: &UnifiedEntity,
3358    order_by: &[OrderByClause],
3359) -> Ordering {
3360    for clause in order_by {
3361        let left_value = update_order_value(left, &clause.field);
3362        let right_value = update_order_value(right, &clause.field);
3363        let ordering = compare_update_order_values(
3364            left_value.as_ref(),
3365            right_value.as_ref(),
3366            clause.nulls_first,
3367        );
3368        if ordering != Ordering::Equal {
3369            return if clause.ascending {
3370                ordering
3371            } else {
3372                ordering.reverse()
3373            };
3374        }
3375    }
3376    left.logical_id().raw().cmp(&right.logical_id().raw())
3377}
3378
3379fn compare_update_order_values(
3380    left: Option<&Value>,
3381    right: Option<&Value>,
3382    nulls_first: bool,
3383) -> Ordering {
3384    match (left, right) {
3385        (None, None) => Ordering::Equal,
3386        (None, Some(_)) => {
3387            if nulls_first {
3388                Ordering::Less
3389            } else {
3390                Ordering::Greater
3391            }
3392        }
3393        (Some(_), None) => {
3394            if nulls_first {
3395                Ordering::Greater
3396            } else {
3397                Ordering::Less
3398            }
3399        }
3400        (Some(left), Some(right)) => {
3401            crate::storage::query::value_compare::total_compare_values(left, right)
3402        }
3403    }
3404}
3405
3406fn update_order_value(entity: &UnifiedEntity, field: &FieldRef) -> Option<Value> {
3407    let FieldRef::TableColumn { table, column } = field else {
3408        return None;
3409    };
3410    if !table.is_empty() {
3411        return None;
3412    }
3413    if column.eq_ignore_ascii_case("rid") {
3414        return Some(Value::UnsignedInteger(entity.logical_id().raw()));
3415    }
3416    match &entity.data {
3417        EntityData::Row(row) => row.get_field(column).cloned(),
3418        EntityData::Node(_) | EntityData::Edge(_) => runtime_any_record_from_entity_ref(entity)
3419            .and_then(|record| record.get(column).cloned()),
3420        _ => None,
3421    }
3422}
3423
3424fn dedupe_update_columns(mut columns: Vec<String>) -> Vec<String> {
3425    if columns.is_empty() {
3426        return columns;
3427    }
3428
3429    let mut unique = Vec::with_capacity(columns.len());
3430    for column in columns.drain(..) {
3431        if !unique
3432            .iter()
3433            .any(|existing: &String| existing.eq_ignore_ascii_case(&column))
3434        {
3435            unique.push(column);
3436        }
3437    }
3438    unique
3439}
3440
3441// =============================================================================
3442// Helper functions for extracting typed values from column/value pairs
3443// =============================================================================
3444
3445const SQL_TTL_METADATA_COLUMNS: [&str; 3] = ["_ttl", "_ttl_ms", "_expires_at"];
3446
3447fn resolve_sql_ttl_metadata_key(column: &str) -> Option<&'static str> {
3448    if column.eq_ignore_ascii_case("_ttl") {
3449        Some(SQL_TTL_METADATA_COLUMNS[0])
3450    } else if column.eq_ignore_ascii_case("_ttl_ms") {
3451        Some(SQL_TTL_METADATA_COLUMNS[1])
3452    } else if column.eq_ignore_ascii_case("_expires_at") {
3453        Some(SQL_TTL_METADATA_COLUMNS[2])
3454    } else {
3455        None
3456    }
3457}
3458
3459/// Canonicalize a SQL TTL metadata `(key, value)` pair so the retention
3460/// sweeper sees a single key (`_ttl_ms`) regardless of which legacy form
3461/// the operator wrote. `_ttl` is scaled from seconds to milliseconds;
3462/// `_ttl_ms` and `_expires_at` are passed through.
3463fn canonicalize_sql_ttl_metadata(
3464    key: &'static str,
3465    value: MetadataValue,
3466) -> (&'static str, MetadataValue) {
3467    if key != "_ttl" {
3468        return (key, value);
3469    }
3470    let scaled = match value {
3471        MetadataValue::Int(s) => MetadataValue::Int(s.saturating_mul(1_000)),
3472        MetadataValue::Timestamp(ms_or_s) => {
3473            // Timestamp is already chosen for very large values; treat as
3474            // already-ms to avoid silent overflow.
3475            MetadataValue::Timestamp(ms_or_s)
3476        }
3477        MetadataValue::Float(f) => MetadataValue::Float(f * 1_000.0),
3478        other => other,
3479    };
3480    ("_ttl_ms", scaled)
3481}
3482
3483/// Sentinel prefix produced by the parser for `PASSWORD('...')` and
3484/// `SECRET('...')` literals. The runtime strips this marker and
3485/// applies the actual crypto transform during INSERT execution.
3486pub(crate) const PLAINTEXT_SENTINEL: &str = "@@plain@@";
3487
3488impl RedDBRuntime {
3489    /// Strip the plaintext sentinel from a `Value::Password` or
3490    /// `Value::Secret` produced by the parser and apply the real
3491    /// crypto transform. `Password` is always hashed with argon2id.
3492    /// `Secret` is encrypted with AES-256-GCM keyed by the vault
3493    /// when `red.config.secret.auto_encrypt = true` (default).
3494    pub(crate) fn resolve_crypto_sentinel(&self, value: Value) -> RedDBResult<Value> {
3495        match value {
3496            Value::Password(marked) => {
3497                if let Some(plain) = marked.strip_prefix(PLAINTEXT_SENTINEL) {
3498                    Ok(Value::Password(crate::auth::store::hash_password(plain)))
3499                } else {
3500                    Ok(Value::Password(marked))
3501                }
3502            }
3503            Value::Secret(bytes) => {
3504                if bytes.starts_with(PLAINTEXT_SENTINEL.as_bytes()) {
3505                    if !self.secret_auto_encrypt() {
3506                        return Err(RedDBError::Query(
3507                            "SECRET() literal rejected: red.config.secret.auto_encrypt \
3508                             is false. Insert pre-encrypted bytes directly instead."
3509                                .to_string(),
3510                        ));
3511                    }
3512                    let key = self.secret_aes_key().ok_or_else(|| {
3513                        RedDBError::Query(
3514                            "SECRET() column encryption requires a bootstrapped \
3515                             vault (red.secret.aes_key is missing). Start the server \
3516                             with --vault to enable."
3517                                .to_string(),
3518                        )
3519                    })?;
3520                    let plain = &bytes[PLAINTEXT_SENTINEL.len()..];
3521                    Ok(Value::Secret(encrypt_secret_payload(&key, plain)))
3522                } else {
3523                    Ok(Value::Secret(bytes))
3524                }
3525            }
3526            other => Ok(other),
3527        }
3528    }
3529}
3530
3531/// Encode an AES-256-GCM ciphertext as `[12-byte nonce][ciphertext||tag]`.
3532/// This is the on-disk representation of `Value::Secret`.
3533fn encrypt_secret_payload(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
3534    let nonce_bytes = crate::auth::store::random_bytes(12);
3535    let mut nonce = [0u8; 12];
3536    nonce.copy_from_slice(&nonce_bytes[..12]);
3537    let ct = crate::crypto::aes_gcm::aes256_gcm_encrypt(key, &nonce, b"reddb.secret", plaintext);
3538    let mut out = Vec::with_capacity(12 + ct.len());
3539    out.extend_from_slice(&nonce);
3540    out.extend_from_slice(&ct);
3541    out
3542}
3543
3544/// Decode a `Value::Secret` payload back to plaintext. Returns
3545/// `None` when the payload is too short or AES-GCM authentication
3546/// fails (tampered or wrong key).
3547pub(crate) fn decrypt_secret_payload(key: &[u8; 32], payload: &[u8]) -> Option<Vec<u8>> {
3548    if payload.len() < 12 {
3549        return None;
3550    }
3551    let mut nonce = [0u8; 12];
3552    nonce.copy_from_slice(&payload[..12]);
3553    crate::crypto::aes_gcm::aes256_gcm_decrypt(key, &nonce, b"reddb.secret", &payload[12..]).ok()
3554}
3555
3556fn split_insert_metadata(
3557    runtime: &RedDBRuntime,
3558    columns: &[String],
3559    values: &[Value],
3560) -> RedDBResult<(Vec<(String, Value)>, Vec<(String, MetadataValue)>)> {
3561    let mut fields = Vec::new();
3562    let mut metadata = Vec::new();
3563
3564    for (column, value) in columns.iter().zip(values.iter()) {
3565        // Still support legacy _ttl columns for backward compat
3566        if let Some(metadata_key) = resolve_sql_ttl_metadata_key(column) {
3567            let raw_value = sql_literal_to_metadata_value(metadata_key, value)?;
3568            let (canonical_key, canonical_value) =
3569                canonicalize_sql_ttl_metadata(metadata_key, raw_value);
3570            metadata.push((canonical_key.to_string(), canonical_value));
3571            continue;
3572        }
3573        fields.push((
3574            column.clone(),
3575            runtime.resolve_crypto_sentinel(value.clone())?,
3576        ));
3577    }
3578
3579    Ok((fields, metadata))
3580}
3581
3582/// Merge structured WITH TTL, WITH EXPIRES AT, and WITH METADATA clauses into metadata entries.
3583fn merge_with_clauses(
3584    metadata: &mut Vec<(String, MetadataValue)>,
3585    ttl_ms: Option<u64>,
3586    expires_at_ms: Option<u64>,
3587    with_metadata: &[(String, Value)],
3588) {
3589    if let Some(ms) = ttl_ms {
3590        metadata.push((
3591            "_ttl_ms".to_string(),
3592            if ms <= i64::MAX as u64 {
3593                MetadataValue::Int(ms as i64)
3594            } else {
3595                MetadataValue::Timestamp(ms)
3596            },
3597        ));
3598    }
3599    if let Some(ms) = expires_at_ms {
3600        metadata.push(("_expires_at".to_string(), MetadataValue::Timestamp(ms)));
3601    }
3602    for (key, value) in with_metadata {
3603        let meta_value = match value {
3604            Value::Text(s) => MetadataValue::String(s.to_string()),
3605            Value::Integer(n) => MetadataValue::Int(*n),
3606            Value::Float(n) => MetadataValue::Float(*n),
3607            Value::Boolean(b) => MetadataValue::Bool(*b),
3608            _ => MetadataValue::String(value.to_string()),
3609        };
3610        metadata.push((key.clone(), meta_value));
3611    }
3612}
3613
3614fn merge_vector_metadata_column(
3615    metadata: &mut Vec<(String, MetadataValue)>,
3616    columns: &[String],
3617    values: &[Value],
3618) -> RedDBResult<()> {
3619    let Some(value) = columns
3620        .iter()
3621        .position(|column| column.eq_ignore_ascii_case("metadata"))
3622        .map(|index| &values[index])
3623    else {
3624        return Ok(());
3625    };
3626    let json = match value {
3627        Value::Null => return Ok(()),
3628        Value::Json(bytes) => crate::json::from_slice(bytes).map_err(|err| {
3629            RedDBError::Query(format!("column 'metadata' invalid JSON object: {err}"))
3630        })?,
3631        Value::Text(text) => crate::json::from_str(text).map_err(|err| {
3632            RedDBError::Query(format!("column 'metadata' invalid JSON object: {err}"))
3633        })?,
3634        other => {
3635            return Err(RedDBError::Query(format!(
3636                "column 'metadata' expected JSON object, got {other:?}"
3637            )))
3638        }
3639    };
3640    let parsed = metadata_from_json(&json)?;
3641    for (key, value) in parsed.iter() {
3642        metadata.push((key.clone(), value.clone()));
3643    }
3644    Ok(())
3645}
3646
3647fn apply_collection_default_ttl_metadata(
3648    runtime: &RedDBRuntime,
3649    collection: &str,
3650    metadata: &mut Vec<(String, MetadataValue)>,
3651) {
3652    if has_internal_ttl_metadata(metadata) {
3653        return;
3654    }
3655
3656    let Some(default_ttl_ms) = runtime.db().collection_default_ttl_ms(collection) else {
3657        return;
3658    };
3659
3660    metadata.push((
3661        "_ttl_ms".to_string(),
3662        if default_ttl_ms <= i64::MAX as u64 {
3663            MetadataValue::Int(default_ttl_ms as i64)
3664        } else {
3665            MetadataValue::Timestamp(default_ttl_ms)
3666        },
3667    ));
3668}
3669
3670fn ensure_non_tree_reserved_metadata_entries(
3671    metadata: &[(String, MetadataValue)],
3672) -> RedDBResult<()> {
3673    for (key, _) in metadata {
3674        ensure_non_tree_reserved_metadata_key(key)?;
3675    }
3676    Ok(())
3677}
3678
3679fn ensure_non_tree_reserved_metadata_key(key: &str) -> RedDBResult<()> {
3680    if key.starts_with(TREE_METADATA_PREFIX) {
3681        return Err(RedDBError::Query(format!(
3682            "metadata key '{}' is reserved for managed trees",
3683            key
3684        )));
3685    }
3686    Ok(())
3687}
3688
3689fn ensure_non_tree_structural_edge_label(label: &str) -> RedDBResult<()> {
3690    if label.eq_ignore_ascii_case(TREE_CHILD_EDGE_LABEL) {
3691        return Err(RedDBError::Query(format!(
3692            "edge label '{}' is reserved for managed trees",
3693            TREE_CHILD_EDGE_LABEL
3694        )));
3695    }
3696    Ok(())
3697}
3698
3699fn pairwise_columns_values(pairs: &[(String, Value)]) -> (Vec<String>, Vec<Value>) {
3700    let mut columns = Vec::with_capacity(pairs.len());
3701    let mut values = Vec::with_capacity(pairs.len());
3702
3703    for (column, value) in pairs {
3704        columns.push(column.clone());
3705        values.push(value.clone());
3706    }
3707
3708    (columns, values)
3709}
3710
3711/// Find a required column value and return it as-is.
3712fn find_column_value(columns: &[String], values: &[Value], name: &str) -> RedDBResult<Value> {
3713    for (i, col) in columns.iter().enumerate() {
3714        if col.eq_ignore_ascii_case(name) {
3715            return Ok(values[i].clone());
3716        }
3717    }
3718    Err(RedDBError::Query(format!(
3719        "required column '{name}' not found in INSERT"
3720    )))
3721}
3722
3723/// Find a required column value and coerce to String.
3724fn find_column_value_string(
3725    columns: &[String],
3726    values: &[Value],
3727    name: &str,
3728) -> RedDBResult<String> {
3729    let val = find_column_value(columns, values, name)?;
3730    match val {
3731        Value::Text(s) => Ok(s.to_string()),
3732        Value::Integer(n) => Ok(n.to_string()),
3733        Value::Float(n) => Ok(n.to_string()),
3734        other => Err(RedDBError::Query(format!(
3735            "column '{name}' expected text, got {other:?}"
3736        ))),
3737    }
3738}
3739
3740fn find_document_body_json(
3741    columns: &[String],
3742    values: &[Value],
3743) -> RedDBResult<crate::json::Value> {
3744    let val = find_column_value(columns, values, "body")?;
3745    match val {
3746        Value::Json(bytes) | Value::Blob(bytes) => crate::json::from_slice(&bytes)
3747            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3748        Value::Text(text) => crate::json::from_str(text.as_ref())
3749            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3750        Value::Integer(value) => crate::json::from_str(&value.to_string())
3751            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3752        Value::UnsignedInteger(value) => crate::json::from_str(&value.to_string())
3753            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3754        Value::Float(value) => crate::json::from_str(&value.to_string())
3755            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3756        other => Err(RedDBError::Query(format!(
3757            "column 'body' expected JSON body, got {other:?}"
3758        ))),
3759    }
3760}
3761
3762fn find_column_value_f64(columns: &[String], values: &[Value], name: &str) -> RedDBResult<f64> {
3763    let val = find_column_value(columns, values, name)?;
3764    match val {
3765        Value::Float(n) => Ok(n),
3766        Value::Integer(n) => Ok(n as f64),
3767        Value::UnsignedInteger(n) => Ok(n as f64),
3768        Value::Text(s) => s
3769            .parse::<f64>()
3770            .map_err(|_| RedDBError::Query(format!("column '{name}' expected number, got '{s}'"))),
3771        other => Err(RedDBError::Query(format!(
3772            "column '{name}' expected number, got {other:?}"
3773        ))),
3774    }
3775}
3776
3777/// Find an optional column value as String.
3778fn find_column_value_opt_string(
3779    columns: &[String],
3780    values: &[Value],
3781    name: &str,
3782) -> Option<String> {
3783    for (i, col) in columns.iter().enumerate() {
3784        if col.eq_ignore_ascii_case(name) {
3785            return match &values[i] {
3786                Value::Null => None,
3787                Value::Text(s) => Some(s.to_string()),
3788                Value::Integer(n) => Some(n.to_string()),
3789                Value::Float(n) => Some(n.to_string()),
3790                _ => None,
3791            };
3792        }
3793    }
3794    None
3795}
3796
3797/// Resolve an EDGE endpoint (`from`/`to`) to a numeric entity id.
3798///
3799/// Accepts integer literals, decimal strings, and node labels resolved via
3800/// the per-collection graph label index (same source of truth that
3801/// `GRAPH NEIGHBORHOOD` / `GRAPH TRAVERSE` use at query time). Ambiguous
3802/// labels error so callers can fall back to the numeric id form.
3803fn resolve_edge_endpoint(
3804    store: &crate::storage::unified::UnifiedStore,
3805    collection: &str,
3806    columns: &[String],
3807    values: &[Value],
3808    name: &str,
3809) -> RedDBResult<u64> {
3810    let val = find_column_value(columns, values, name)?;
3811    match val {
3812        Value::Integer(n) => Ok(n as u64),
3813        Value::UnsignedInteger(n) => Ok(n),
3814        Value::Text(s) => {
3815            if let Ok(n) = s.parse::<u64>() {
3816                return Ok(n);
3817            }
3818            let matches = store.lookup_graph_nodes_by_label_in(collection, &s);
3819            match matches.len() {
3820                0 => Err(RedDBError::Query(format!(
3821                    "column '{name}': no graph node with label '{s}' in collection '{collection}'"
3822                ))),
3823                1 => Ok(matches[0].raw()),
3824                n => Err(RedDBError::Query(format!(
3825                    "column '{name}': ambiguous label '{s}' matches {n} nodes in collection '{collection}'; use the numeric id"
3826                ))),
3827            }
3828        }
3829        other => Err(RedDBError::Query(format!(
3830            "column '{name}' expected integer or node label, got {other:?}"
3831        ))),
3832    }
3833}
3834
3835fn resolve_edge_endpoint_any(
3836    store: &crate::storage::unified::UnifiedStore,
3837    collection: &str,
3838    columns: &[String],
3839    values: &[Value],
3840    names: &[&str],
3841) -> RedDBResult<u64> {
3842    for name in names {
3843        if columns
3844            .iter()
3845            .any(|column| column.eq_ignore_ascii_case(name))
3846        {
3847            return resolve_edge_endpoint(store, collection, columns, values, name);
3848        }
3849    }
3850
3851    Err(RedDBError::Query(format!(
3852        "required column '{}' not found in INSERT",
3853        names.first().copied().unwrap_or("from_rid")
3854    )))
3855}
3856
3857/// Find a required column value and coerce to u64.
3858fn find_column_value_u64(columns: &[String], values: &[Value], name: &str) -> RedDBResult<u64> {
3859    let val = find_column_value(columns, values, name)?;
3860    match val {
3861        Value::Integer(n) => Ok(n as u64),
3862        Value::UnsignedInteger(n) => Ok(n),
3863        Value::Text(s) => s
3864            .parse::<u64>()
3865            .map_err(|_| RedDBError::Query(format!("column '{name}' expected integer, got '{s}'"))),
3866        other => Err(RedDBError::Query(format!(
3867            "column '{name}' expected integer, got {other:?}"
3868        ))),
3869    }
3870}
3871
3872/// Find an optional column value as f32.
3873fn find_column_value_f32_opt(columns: &[String], values: &[Value], name: &str) -> Option<f32> {
3874    for (i, col) in columns.iter().enumerate() {
3875        if col.eq_ignore_ascii_case(name) {
3876            return match &values[i] {
3877                Value::Float(n) => Some(*n as f32),
3878                Value::Integer(n) => Some(*n as f32),
3879                Value::Null => None,
3880                _ => None,
3881            };
3882        }
3883    }
3884    None
3885}
3886
3887/// Find a required column value and coerce to Vec<f32> (from Value::Vector).
3888fn find_column_value_vec_f32(
3889    columns: &[String],
3890    values: &[Value],
3891    name: &str,
3892) -> RedDBResult<Vec<f32>> {
3893    let val = find_column_value(columns, values, name)?;
3894    match val {
3895        Value::Vector(v) => Ok(v),
3896        Value::Json(bytes) => {
3897            // Try to parse as JSON array of numbers
3898            let s = std::str::from_utf8(&bytes).map_err(|_| {
3899                RedDBError::Query(format!("column '{name}' contains invalid UTF-8"))
3900            })?;
3901            let arr: Vec<f32> = crate::json::from_str(s).map_err(|e| {
3902                RedDBError::Query(format!("column '{name}' invalid vector JSON: {e}"))
3903            })?;
3904            Ok(arr)
3905        }
3906        other => Err(RedDBError::Query(format!(
3907            "column '{name}' expected vector, got {other:?}"
3908        ))),
3909    }
3910}
3911
3912fn find_column_value_vec_f32_any(
3913    columns: &[String],
3914    values: &[Value],
3915    names: &[&str],
3916) -> RedDBResult<Vec<f32>> {
3917    for name in names {
3918        if columns
3919            .iter()
3920            .any(|column| column.eq_ignore_ascii_case(name))
3921        {
3922            return find_column_value_vec_f32(columns, values, name);
3923        }
3924    }
3925    Err(RedDBError::Query(format!(
3926        "required vector column '{}' not found in INSERT",
3927        names.join("' or '")
3928    )))
3929}
3930
3931/// Extract remaining properties (all columns not in the exclusion list).
3932fn extract_remaining_properties(
3933    columns: &[String],
3934    values: &[Value],
3935    exclude: &[&str],
3936) -> Vec<(String, Value)> {
3937    columns
3938        .iter()
3939        .zip(values.iter())
3940        .filter(|(col, _)| !exclude.iter().any(|e| col.eq_ignore_ascii_case(e)))
3941        .map(|(col, val)| (col.clone(), val.clone()))
3942        .collect()
3943}
3944
3945fn validate_timeseries_insert_columns(columns: &[String]) -> RedDBResult<()> {
3946    let mut invalid = Vec::new();
3947    for column in columns {
3948        if !is_timeseries_insert_column(column) && resolve_sql_ttl_metadata_key(column).is_none() {
3949            invalid.push(column.clone());
3950        }
3951    }
3952
3953    if invalid.is_empty() {
3954        Ok(())
3955    } else {
3956        Err(RedDBError::Query(format!(
3957            "timeseries INSERT only accepts metric, value, tags, timestamp, timestamp_ns, or time columns; got {}",
3958            invalid.join(", ")
3959        )))
3960    }
3961}
3962
3963fn is_timeseries_insert_column(column: &str) -> bool {
3964    matches!(
3965        column.to_ascii_lowercase().as_str(),
3966        "metric"
3967            | "value"
3968            | "tags"
3969            | "timestamp"
3970            | "timestamp_ns"
3971            | "time"
3972            // Analytics-event extension (#577): an analytics row carries
3973            // an `event_name` + JSON `payload`. The payload is validated
3974            // against the AnalyticsSchemaRegistry inside
3975            // `insert_timeseries_point` before the row lands.
3976            | "event_name"
3977            | "payload"
3978    )
3979}
3980
3981fn find_timeseries_timestamp_ns(columns: &[String], values: &[Value]) -> RedDBResult<Option<u64>> {
3982    let mut found = None;
3983
3984    for alias in ["timestamp_ns", "timestamp", "time"] {
3985        for (index, column) in columns.iter().enumerate() {
3986            if !column.eq_ignore_ascii_case(alias) {
3987                continue;
3988            }
3989
3990            if found.is_some() {
3991                return Err(RedDBError::Query(
3992                    "timeseries INSERT accepts only one timestamp column".to_string(),
3993                ));
3994            }
3995
3996            found = Some(coerce_value_to_non_negative_u64(&values[index], alias)?);
3997        }
3998    }
3999
4000    Ok(found)
4001}
4002
4003fn find_timeseries_tags(
4004    columns: &[String],
4005    values: &[Value],
4006) -> RedDBResult<std::collections::HashMap<String, String>> {
4007    for (index, column) in columns.iter().enumerate() {
4008        if column.eq_ignore_ascii_case("tags") {
4009            return parse_timeseries_tags(&values[index]);
4010        }
4011    }
4012    Ok(std::collections::HashMap::new())
4013}
4014
4015fn parse_timeseries_tags(value: &Value) -> RedDBResult<std::collections::HashMap<String, String>> {
4016    match value {
4017        Value::Null => Ok(std::collections::HashMap::new()),
4018        Value::Json(bytes) => parse_timeseries_tags_json(bytes),
4019        Value::Text(text) => parse_timeseries_tags_json(text.as_bytes()),
4020        other => Err(RedDBError::Query(format!(
4021            "timeseries tags must be a JSON object or JSON text, got {other:?}"
4022        ))),
4023    }
4024}
4025
4026fn parse_timeseries_tags_json(
4027    bytes: &[u8],
4028) -> RedDBResult<std::collections::HashMap<String, String>> {
4029    let json: crate::json::Value = crate::json::from_slice(bytes)
4030        .map_err(|err| RedDBError::Query(format!("timeseries tags must be valid JSON: {err}")))?;
4031
4032    let object = match json {
4033        crate::json::Value::Object(object) => object,
4034        other => {
4035            return Err(RedDBError::Query(format!(
4036                "timeseries tags must be a JSON object, got {other:?}"
4037            )))
4038        }
4039    };
4040
4041    let mut tags = std::collections::HashMap::with_capacity(object.len());
4042    for (key, value) in object {
4043        tags.insert(key, json_tag_value_to_string(&value));
4044    }
4045    Ok(tags)
4046}
4047
4048/// Encode a tag value for storage so the original JSON type can be
4049/// recovered on read (issue #543).
4050///
4051/// Time-series tags are stored as `HashMap<String, String>` on the
4052/// physical record (see [`crate::storage::TimeSeriesData`]) so that
4053/// the segment codec, WAL and gRPC mirrors don't need a new value
4054/// variant. To preserve the original JSON type across that
4055/// string-only channel we prepend the
4056/// [`crate::runtime::query_exec::TIMESERIES_TAG_JSON_PREFIX`] marker
4057/// and serialize the value as compact JSON text. The read paths
4058/// (`timeseries_tags_json_value` / `timeseries_tags_value`) detect
4059/// the marker, parse the suffix, and recover a real JSON value.
4060/// Tags written through other channels (Prometheus remote write,
4061/// metrics handlers, legacy on-disk data) lack the marker and are
4062/// returned as `JsonValue::String(raw)` exactly as before.
4063fn json_tag_value_to_string(value: &crate::json::Value) -> String {
4064    let mut buf = String::with_capacity(value.to_string_compact().len() + 1);
4065    buf.push(crate::runtime::query_exec::TIMESERIES_TAG_JSON_PREFIX);
4066    buf.push_str(&value.to_string_compact());
4067    buf
4068}
4069
4070fn coerce_value_to_non_negative_u64(value: &Value, column: &str) -> RedDBResult<u64> {
4071    match value {
4072        Value::UnsignedInteger(value) => Ok(*value),
4073        Value::Integer(value) if *value >= 0 => Ok(*value as u64),
4074        Value::Float(value) if *value >= 0.0 => Ok(*value as u64),
4075        Value::Text(value) => value.parse::<u64>().map_err(|_| {
4076            RedDBError::Query(format!(
4077                "column '{column}' expected a non-negative integer timestamp, got '{value}'"
4078            ))
4079        }),
4080        other => Err(RedDBError::Query(format!(
4081            "column '{column}' expected a non-negative integer timestamp, got {other:?}"
4082        ))),
4083    }
4084}
4085
4086fn current_unix_ns() -> u64 {
4087    std::time::SystemTime::now()
4088        .duration_since(std::time::UNIX_EPOCH)
4089        .unwrap_or_default()
4090        .as_nanos()
4091        .min(u128::from(u64::MAX)) as u64
4092}
4093
4094fn metadata_value_to_json(value: &MetadataValue) -> crate::json::Value {
4095    use crate::json::{Map, Value as JV};
4096    match value {
4097        MetadataValue::Null => JV::Null,
4098        MetadataValue::Bool(value) => JV::Bool(*value),
4099        MetadataValue::Int(value) => JV::Number(*value as f64),
4100        MetadataValue::Float(value) => JV::Number(*value),
4101        MetadataValue::String(value) => JV::String(value.clone()),
4102        MetadataValue::Bytes(value) => JV::Array(
4103            value
4104                .iter()
4105                .map(|value| JV::Number(*value as f64))
4106                .collect(),
4107        ),
4108        MetadataValue::Timestamp(value) => JV::Number(*value as f64),
4109        MetadataValue::Array(values) => {
4110            JV::Array(values.iter().map(metadata_value_to_json).collect())
4111        }
4112        MetadataValue::Object(object) => {
4113            let entries = object
4114                .iter()
4115                .map(|(key, value)| (key.clone(), metadata_value_to_json(value)))
4116                .collect();
4117            JV::Object(entries)
4118        }
4119        MetadataValue::Geo { lat, lon } => {
4120            let mut object = Map::new();
4121            object.insert("lat".to_string(), JV::Number(*lat));
4122            object.insert("lon".to_string(), JV::Number(*lon));
4123            JV::Object(object)
4124        }
4125        MetadataValue::Reference(target) => {
4126            let mut object = Map::new();
4127            object.insert(
4128                "collection".to_string(),
4129                JV::String(target.collection().to_string()),
4130            );
4131            object.insert(
4132                "entity_id".to_string(),
4133                JV::Number(target.entity_id().raw() as f64),
4134            );
4135            JV::Object(object)
4136        }
4137        MetadataValue::References(values) => {
4138            let refs = values
4139                .iter()
4140                .map(|target| {
4141                    let mut object = Map::new();
4142                    object.insert(
4143                        "collection".to_string(),
4144                        JV::String(target.collection().to_string()),
4145                    );
4146                    object.insert(
4147                        "entity_id".to_string(),
4148                        JV::Number(target.entity_id().raw() as f64),
4149                    );
4150                    JV::Object(object)
4151                })
4152                .collect();
4153            JV::Array(refs)
4154        }
4155    }
4156}
4157
4158fn storage_value_to_metadata_value(value: &Value) -> MetadataValue {
4159    match value {
4160        Value::Null => MetadataValue::Null,
4161        Value::Boolean(value) => MetadataValue::Bool(*value),
4162        Value::Integer(value) => MetadataValue::Int(*value),
4163        Value::UnsignedInteger(value) => metadata_u64_to_value(*value),
4164        Value::Float(value) => MetadataValue::Float(*value),
4165        Value::Text(value) => MetadataValue::String(value.to_string()),
4166        Value::Blob(value) => MetadataValue::Bytes(value.clone()),
4167        Value::Timestamp(value) => {
4168            if *value >= 0 {
4169                metadata_u64_to_value(*value as u64)
4170            } else {
4171                MetadataValue::Int(*value)
4172            }
4173        }
4174        Value::TimestampMs(value) => {
4175            if *value >= 0 {
4176                metadata_u64_to_value(*value as u64)
4177            } else {
4178                MetadataValue::Int(*value)
4179            }
4180        }
4181        Value::Json(value) => MetadataValue::String(String::from_utf8_lossy(value).into_owned()),
4182        Value::Uuid(value) => MetadataValue::String(format!("{value:?}")),
4183        Value::Date(value) => MetadataValue::String(value.to_string()),
4184        Value::Time(value) => MetadataValue::String(value.to_string()),
4185        Value::Decimal(value) => MetadataValue::String(value.to_string()),
4186        Value::Ipv4(value) => MetadataValue::String(format!(
4187            "{}.{}.{}.{}",
4188            (value >> 24) & 0xFF,
4189            (value >> 16) & 0xFF,
4190            (value >> 8) & 0xFF,
4191            value & 0xFF
4192        )),
4193        Value::Port(value) => MetadataValue::Int(i64::from(*value)),
4194        Value::Latitude(value) => MetadataValue::Float(*value as f64 / 1_000_000.0),
4195        Value::Longitude(value) => MetadataValue::Float(*value as f64 / 1_000_000.0),
4196        Value::GeoPoint(lat, lon) => MetadataValue::Geo {
4197            lat: *lat as f64 / 1_000_000.0,
4198            lon: *lon as f64 / 1_000_000.0,
4199        },
4200        Value::BigInt(value) => MetadataValue::String(value.to_string()),
4201        Value::TableRef(value) => MetadataValue::String(value.clone()),
4202        Value::PageRef(value) => MetadataValue::Int(*value as i64),
4203        Value::Password(value) => MetadataValue::String(value.clone()),
4204        Value::Array(values) => {
4205            MetadataValue::Array(values.iter().map(storage_value_to_metadata_value).collect())
4206        }
4207        _ => MetadataValue::String(value.to_string()),
4208    }
4209}
4210
4211fn sql_literal_to_metadata_value(field: &str, value: &Value) -> RedDBResult<MetadataValue> {
4212    match value {
4213        Value::Null => Ok(MetadataValue::Null),
4214        Value::Integer(value) if *value >= 0 => Ok(metadata_u64_to_value(*value as u64)),
4215        Value::Integer(_) => Err(RedDBError::Query(format!(
4216            "column '{field}' must be non-negative for TTL metadata"
4217        ))),
4218        Value::UnsignedInteger(value) => Ok(metadata_u64_to_value(*value)),
4219        Value::Float(value) if value.is_finite() => {
4220            if value.fract().abs() >= f64::EPSILON {
4221                return Err(RedDBError::Query(format!(
4222                    "column '{field}' must be an integer (TTL metadata must be an integer)"
4223                )));
4224            }
4225            if *value < 0.0 {
4226                return Err(RedDBError::Query(format!(
4227                    "column '{field}' must be non-negative for TTL metadata"
4228                )));
4229            }
4230            if *value > u64::MAX as f64 {
4231                return Err(RedDBError::Query(format!(
4232                    "column '{field}' value is too large"
4233                )));
4234            }
4235            Ok(metadata_u64_to_value(*value as u64))
4236        }
4237        Value::Float(_) => Err(RedDBError::Query(format!(
4238            "column '{field}' must be a finite number"
4239        ))),
4240        Value::Text(value) => {
4241            let value = value.trim();
4242            if let Ok(value) = value.parse::<u64>() {
4243                Ok(metadata_u64_to_value(value))
4244            } else if let Ok(value) = value.parse::<i64>() {
4245                if value < 0 {
4246                    return Err(RedDBError::Query(format!(
4247                        "column '{field}' must be non-negative for TTL metadata"
4248                    )));
4249                }
4250                Ok(metadata_u64_to_value(value as u64))
4251            } else if let Ok(value) = value.parse::<f64>() {
4252                if !value.is_finite() {
4253                    return Err(RedDBError::Query(format!(
4254                        "column '{field}' must be a finite number"
4255                    )));
4256                }
4257                if value.fract().abs() >= f64::EPSILON {
4258                    return Err(RedDBError::Query(format!(
4259                        "column '{field}' must be an integer (TTL metadata must be an integer)"
4260                    )));
4261                }
4262                if value < 0.0 {
4263                    return Err(RedDBError::Query(format!(
4264                        "column '{field}' must be non-negative for TTL metadata"
4265                    )));
4266                }
4267                if value > u64::MAX as f64 {
4268                    return Err(RedDBError::Query(format!(
4269                        "column '{field}' value is too large"
4270                    )));
4271                }
4272                Ok(metadata_u64_to_value(value as u64))
4273            } else {
4274                Err(RedDBError::Query(format!(
4275                    "column '{field}' expects a numeric value for TTL metadata"
4276                )))
4277            }
4278        }
4279        _ => Err(RedDBError::Query(format!(
4280            "column '{field}' expects a numeric value for TTL metadata"
4281        ))),
4282    }
4283}
4284
4285fn metadata_u64_to_value(value: u64) -> MetadataValue {
4286    if value <= i64::MAX as u64 {
4287        MetadataValue::Int(value as i64)
4288    } else {
4289        MetadataValue::Timestamp(value)
4290    }
4291}
4292
4293/// Phase 2 PG parity: inspect a column value and return `true` when
4294/// the dotted `tail` path is already present under it. Used by the
4295/// tenant auto-fill so rows that already carry an explicit value
4296/// (bulk import, admin insert on behalf of a tenant) are not
4297/// double-stamped with the session's current_tenant().
4298fn dotted_tail_already_set(value: &Value, tail: &str) -> bool {
4299    let json = match value {
4300        Value::Null => return false,
4301        Value::Json(bytes) | Value::Blob(bytes) => {
4302            match crate::json::from_slice::<crate::json::Value>(bytes) {
4303                Ok(v) => v,
4304                Err(_) => return false,
4305            }
4306        }
4307        Value::Text(s) => {
4308            let trimmed = s.trim_start();
4309            if !(trimmed.starts_with('{') || trimmed.starts_with('[')) {
4310                return false;
4311            }
4312            match crate::json::from_str::<crate::json::Value>(s) {
4313                Ok(v) => v,
4314                Err(_) => return false,
4315            }
4316        }
4317        _ => return false,
4318    };
4319    let mut cursor = &json;
4320    for seg in tail.split('.') {
4321        match cursor {
4322            crate::json::Value::Object(map) => match map.iter().find(|(k, _)| *k == seg) {
4323                Some((_, v)) => cursor = v,
4324                None => return false,
4325            },
4326            _ => return false,
4327        }
4328    }
4329    !matches!(cursor, crate::json::Value::Null)
4330}
4331
4332/// Phase 2 PG parity: take a column value (possibly Null / Text /
4333/// Json) and return a `Value::Json` with the dotted `tail` path set
4334/// to `tenant_id`. Preserves every pre-existing key.
4335///
4336/// Accepts:
4337/// * `Value::Null`  → fresh `{tail: tenant_id}` object
4338/// * `Value::Json(bytes)` → parse, navigate / create path, re-serialize
4339/// * `Value::text(s)` if `s` is valid JSON → same as Json
4340/// * anything else → error (user supplied a scalar where we need
4341///   a JSON container)
4342fn merge_dotted_tenant(current: Value, tail: &str, tenant_id: &str) -> RedDBResult<Value> {
4343    let mut root = match current {
4344        Value::Null => crate::json::Value::Object(Default::default()),
4345        Value::Json(bytes) | Value::Blob(bytes) => {
4346            crate::json::from_slice(&bytes).map_err(|err| {
4347                RedDBError::Query(format!(
4348                    "tenant auto-fill: root column is not valid JSON ({err})"
4349                ))
4350            })?
4351        }
4352        Value::Text(s) => {
4353            if s.trim().is_empty() {
4354                crate::json::Value::Object(Default::default())
4355            } else {
4356                crate::json::from_str::<crate::json::Value>(&s).map_err(|err| {
4357                    RedDBError::Query(format!(
4358                        "tenant auto-fill: text root is not valid JSON ({err})"
4359                    ))
4360                })?
4361            }
4362        }
4363        other => {
4364            return Err(RedDBError::Query(format!(
4365                "tenant auto-fill: root column must be JSON / NULL, got {other:?}"
4366            )));
4367        }
4368    };
4369
4370    // Navigate path segments, creating intermediate objects on demand.
4371    let segments: Vec<&str> = tail.split('.').collect();
4372    let mut cursor: &mut crate::json::Value = &mut root;
4373    for (i, seg) in segments.iter().enumerate() {
4374        let is_last = i + 1 == segments.len();
4375        let map = match cursor {
4376            crate::json::Value::Object(m) => m,
4377            _ => {
4378                return Err(RedDBError::Query(format!(
4379                    "tenant auto-fill: segment '{seg}' is not inside an object"
4380                )));
4381            }
4382        };
4383        if is_last {
4384            map.insert(
4385                seg.to_string(),
4386                crate::json::Value::String(tenant_id.to_string()),
4387            );
4388            break;
4389        }
4390        cursor = map
4391            .entry(seg.to_string())
4392            .or_insert_with(|| crate::json::Value::Object(Default::default()));
4393    }
4394
4395    let bytes = crate::json::to_vec(&root).map_err(|err| {
4396        RedDBError::Query(format!(
4397            "tenant auto-fill: failed to re-serialize JSON ({err})"
4398        ))
4399    })?;
4400    Ok(Value::Json(bytes))
4401}
4402
4403#[cfg(test)]
4404mod tests {
4405    use crate::storage::schema::Value;
4406    use crate::storage::wal::{WalReader, WalRecord};
4407    use crate::storage::{DeployProfile, StoragePackaging, StorageProfileSelection};
4408    use crate::{RedDBOptions, RedDBRuntime};
4409    use std::path::Path;
4410
4411    fn persistent_operational_options(path: &Path) -> RedDBOptions {
4412        RedDBOptions::persistent(path)
4413            .with_storage_profile(StorageProfileSelection {
4414                deploy_profile: DeployProfile::Embedded,
4415                packaging: StoragePackaging::OperationalDirectory,
4416                replica_count: 0,
4417                managed_backup: false,
4418                wal_retention: false,
4419            })
4420            .unwrap()
4421    }
4422
4423    fn store_commit_batches(wal_path: &Path) -> Vec<Vec<Vec<u8>>> {
4424        WalReader::open(wal_path)
4425            .expect("wal opens")
4426            .iter()
4427            .map(|record| record.expect("wal record decodes").1)
4428            .filter_map(|record| match record {
4429                WalRecord::TxCommitBatch { actions, .. } => Some(actions),
4430                _ => None,
4431            })
4432            .collect()
4433    }
4434
4435    fn action_contains_text(action: &[u8], needle: &str) -> bool {
4436        action
4437            .windows(needle.len())
4438            .any(|window| window == needle.as_bytes())
4439    }
4440
4441    fn claim_metric_count(
4442        snapshot: &crate::runtime::ClaimTelemetrySnapshot,
4443        metric: &str,
4444        collection: &str,
4445        model: &str,
4446    ) -> u64 {
4447        let rows = match metric {
4448            "attempts" => &snapshot.attempts,
4449            "successful" => &snapshot.successful,
4450            "misses" => &snapshot.misses,
4451            "skipped_locked" => &snapshot.skipped_locked,
4452            other => panic!("unknown claim metric {other}"),
4453        };
4454        rows.iter()
4455            .find(|((actual_collection, actual_model), _)| {
4456                actual_collection == collection && actual_model == model
4457            })
4458            .map(|(_, count)| *count)
4459            .unwrap_or(0)
4460    }
4461
4462    fn assert_statement_writes_collections_in_one_new_wal_batch(
4463        rt: &RedDBRuntime,
4464        wal_path: &Path,
4465        statement: &str,
4466        source: &str,
4467        event_queue: &str,
4468    ) {
4469        let before_batches = store_commit_batches(wal_path).len();
4470
4471        rt.execute_query(statement).unwrap();
4472
4473        let batches = store_commit_batches(wal_path);
4474        let statement_batches = &batches[before_batches..];
4475        let source_batch = statement_batches
4476            .iter()
4477            .position(|actions| {
4478                actions.iter().any(|action| {
4479                    action_contains_text(action, source)
4480                        && !action_contains_text(action, event_queue)
4481                })
4482            })
4483            .expect("source collection write batch is present");
4484        let event_batch = statement_batches
4485            .iter()
4486            .position(|actions| {
4487                actions
4488                    .iter()
4489                    .any(|action| action_contains_text(action, event_queue))
4490            })
4491            .expect("event queue write batch is present");
4492
4493        assert_eq!(
4494            source_batch, event_batch,
4495            "WITH EVENTS must persist the source write and queue event in the same WAL batch"
4496        );
4497    }
4498
4499    #[test]
4500    fn with_events_autocommit_persists_mutation_and_event_in_one_wal_batch() {
4501        let dir = tempfile::tempdir().unwrap();
4502        let db_path = dir.path().join("events_dual_write.rdb");
4503        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4504        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4505
4506        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4507            .unwrap();
4508        assert_statement_writes_collections_in_one_new_wal_batch(
4509            &rt,
4510            &wal_path,
4511            "INSERT INTO users (id, email) VALUES (1, 'a@example.test')",
4512            "users",
4513            "users_events",
4514        );
4515    }
4516
4517    #[test]
4518    fn with_events_autocommit_update_persists_mutation_and_event_in_one_wal_batch() {
4519        let dir = tempfile::tempdir().unwrap();
4520        let db_path = dir.path().join("events_update_atomic.rdb");
4521        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4522        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4523
4524        rt.execute_query(
4525            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (UPDATE) TO user_updates",
4526        )
4527        .unwrap();
4528        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
4529            .unwrap();
4530
4531        assert_statement_writes_collections_in_one_new_wal_batch(
4532            &rt,
4533            &wal_path,
4534            "UPDATE users SET email = 'b@example.test' WHERE id = 1",
4535            "users",
4536            "user_updates",
4537        );
4538    }
4539
4540    #[test]
4541    fn with_events_autocommit_delete_persists_mutation_and_event_in_one_wal_batch() {
4542        let dir = tempfile::tempdir().unwrap();
4543        let db_path = dir.path().join("events_delete_atomic.rdb");
4544        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4545        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4546
4547        rt.execute_query(
4548            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (DELETE) TO user_deletes",
4549        )
4550        .unwrap();
4551        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
4552            .unwrap();
4553
4554        assert_statement_writes_collections_in_one_new_wal_batch(
4555            &rt,
4556            &wal_path,
4557            "DELETE FROM users WHERE id = 1",
4558            "users",
4559            "user_deletes",
4560        );
4561    }
4562
4563    #[test]
4564    fn update_where_id_in_with_hash_index_updates_expected_rows() {
4565        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4566        rt.execute_query("CREATE TABLE users (id INT, score INT)")
4567            .unwrap();
4568        for id in 0..5 {
4569            rt.execute_query(&format!("INSERT INTO users (id, score) VALUES ({id}, 0)"))
4570                .unwrap();
4571        }
4572        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
4573            .unwrap();
4574
4575        let updated = rt
4576            .execute_query("UPDATE users SET score = 42 WHERE id IN (1,3,4)")
4577            .unwrap();
4578        assert_eq!(updated.affected_rows, 3);
4579
4580        let selected = rt
4581            .execute_query("SELECT id, score FROM users ORDER BY id")
4582            .unwrap();
4583        let scores: Vec<(i64, i64)> = selected
4584            .result
4585            .records
4586            .iter()
4587            .map(|record| {
4588                let id = match record.get("id").unwrap() {
4589                    Value::Integer(value) => *value,
4590                    other => panic!("expected integer id, got {other:?}"),
4591                };
4592                let score = match record.get("score").unwrap() {
4593                    Value::Integer(value) => *value,
4594                    other => panic!("expected integer score, got {other:?}"),
4595                };
4596                (id, score)
4597            })
4598            .collect();
4599        assert_eq!(scores, vec![(0, 0), (1, 42), (2, 0), (3, 42), (4, 42)]);
4600    }
4601
4602    /// Drives UPDATE through the shared `DmlTargetScan` module — the
4603    /// same code path DELETE uses (#51, #52). Exercises the indexed
4604    /// equality fast-path (WHERE id = N with a HASH index), the
4605    /// unindexed range scan (WHERE score > N), and the no-WHERE
4606    /// full-scan branch to confirm the extracted "find target rows"
4607    /// loop preserves affected-row counts and the resulting row state.
4608    #[test]
4609    fn update_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
4610        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4611        rt.execute_query("CREATE TABLE items (id INT, score INT)")
4612            .unwrap();
4613        for id in 0..5 {
4614            rt.execute_query(&format!(
4615                "INSERT INTO items (id, score) VALUES ({id}, {})",
4616                id * 10
4617            ))
4618            .unwrap();
4619        }
4620        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
4621            .unwrap();
4622
4623        // Indexed equality UPDATE — hits the hash fast-path inside
4624        // DmlTargetScan::find_target_ids. id=2 has score=20, drop it
4625        // below the score>25 cutoff so the next assertion stays clean.
4626        let updated_one = rt
4627            .execute_query("UPDATE items SET score = 5 WHERE id = 2")
4628            .unwrap();
4629        assert_eq!(updated_one.affected_rows, 1);
4630
4631        // Unindexed scan UPDATE — bumps everyone with score > 25,
4632        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
4633        // zoned/full-scan branch.
4634        let updated_many = rt
4635            .execute_query("UPDATE items SET score = 7 WHERE score > 25")
4636            .unwrap();
4637        assert_eq!(updated_many.affected_rows, 2);
4638
4639        let snapshot = rt
4640            .execute_query("SELECT id, score FROM items ORDER BY id")
4641            .unwrap();
4642        let pairs: Vec<(i64, i64)> = snapshot
4643            .result
4644            .records
4645            .iter()
4646            .map(|record| {
4647                let id = match record.get("id").unwrap() {
4648                    Value::Integer(value) => *value,
4649                    other => panic!("expected integer id, got {other:?}"),
4650                };
4651                let score = match record.get("score").unwrap() {
4652                    Value::Integer(value) => *value,
4653                    other => panic!("expected integer score, got {other:?}"),
4654                };
4655                (id, score)
4656            })
4657            .collect();
4658        assert_eq!(pairs, vec![(0, 0), (1, 10), (2, 5), (3, 7), (4, 7)]);
4659
4660        // Full-scan UPDATE with no WHERE rewrites every remaining row.
4661        let updated_all = rt.execute_query("UPDATE items SET score = 1").unwrap();
4662        assert_eq!(updated_all.affected_rows, 5);
4663        let after = rt
4664            .execute_query("SELECT score FROM items ORDER BY id")
4665            .unwrap();
4666        let scores: Vec<i64> = after
4667            .result
4668            .records
4669            .iter()
4670            .map(|record| match record.get("score").unwrap() {
4671                Value::Integer(value) => *value,
4672                other => panic!("expected integer score, got {other:?}"),
4673            })
4674            .collect();
4675        assert_eq!(scores, vec![1, 1, 1, 1, 1]);
4676    }
4677
4678    /// Drives DELETE through the new `DmlTargetScan` module. Exercises
4679    /// both the index fast-path (WHERE id = N with a HASH index) and
4680    /// the unindexed scan path (WHERE score > N) to confirm the
4681    /// extracted "find target rows" loop preserves the affected-row
4682    /// count and which rows survive.
4683    #[test]
4684    fn delete_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
4685        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4686        rt.execute_query("CREATE TABLE items (id INT, score INT)")
4687            .unwrap();
4688        for id in 0..5 {
4689            rt.execute_query(&format!(
4690                "INSERT INTO items (id, score) VALUES ({id}, {})",
4691                id * 10
4692            ))
4693            .unwrap();
4694        }
4695        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
4696            .unwrap();
4697
4698        // Indexed equality DELETE — hits the hash fast-path inside
4699        // DmlTargetScan::find_target_ids.
4700        let deleted_one = rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
4701        assert_eq!(deleted_one.affected_rows, 1);
4702
4703        // Unindexed scan DELETE — drops everyone with score > 25,
4704        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
4705        // zoned/full-scan branch.
4706        let deleted_many = rt
4707            .execute_query("DELETE FROM items WHERE score > 25")
4708            .unwrap();
4709        assert_eq!(deleted_many.affected_rows, 2);
4710
4711        let surviving = rt
4712            .execute_query("SELECT id FROM items ORDER BY id")
4713            .unwrap();
4714        let ids: Vec<i64> = surviving
4715            .result
4716            .records
4717            .iter()
4718            .map(|record| match record.get("id").unwrap() {
4719                Value::Integer(value) => *value,
4720                other => panic!("expected integer id, got {other:?}"),
4721            })
4722            .collect();
4723        assert_eq!(ids, vec![0, 1]);
4724
4725        // Sanity: full-scan DELETE with no WHERE clears the rest.
4726        let deleted_rest = rt.execute_query("DELETE FROM items").unwrap();
4727        assert_eq!(deleted_rest.affected_rows, 2);
4728        let empty = rt.execute_query("SELECT id FROM items").unwrap();
4729        assert!(empty.result.records.is_empty());
4730    }
4731
4732    /// CollectionContract gate (#49 + #50): APPEND ONLY tables accept
4733    /// INSERT but reject UPDATE and DELETE with the documented
4734    /// operator-facing error strings. Drives all three DML verbs so
4735    /// the centralized gate is exercised end-to-end.
4736    #[test]
4737    fn collection_contract_gate_blocks_update_and_delete_on_append_only() {
4738        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4739        rt.execute_query("CREATE TABLE events (id INT, payload TEXT) APPEND ONLY")
4740            .unwrap();
4741
4742        // INSERT must succeed — APPEND ONLY exists precisely to allow
4743        // appends. The gate should be a no-op for INSERT.
4744        let inserted = rt
4745            .execute_query("INSERT INTO events (id, payload) VALUES (1, 'hello')")
4746            .unwrap();
4747        assert_eq!(inserted.affected_rows, 1);
4748
4749        // UPDATE is rejected with the gate's UPDATE-specific message.
4750        let update_err = rt
4751            .execute_query("UPDATE events SET payload = 'mut' WHERE id = 1")
4752            .unwrap_err();
4753        let msg = format!("{update_err}");
4754        assert!(
4755            msg.contains("APPEND ONLY") && msg.contains("UPDATE is rejected"),
4756            "expected UPDATE rejection message, got: {msg}"
4757        );
4758
4759        // DELETE is rejected with the gate's DELETE-specific message.
4760        let delete_err = rt
4761            .execute_query("DELETE FROM events WHERE id = 1")
4762            .unwrap_err();
4763        let msg = format!("{delete_err}");
4764        assert!(
4765            msg.contains("APPEND ONLY") && msg.contains("DELETE is rejected"),
4766            "expected DELETE rejection message, got: {msg}"
4767        );
4768
4769        // Row should still be present — neither rejected mutation
4770        // touched storage.
4771        let surviving = rt.execute_query("SELECT id FROM events").unwrap();
4772        assert_eq!(surviving.result.records.len(), 1);
4773    }
4774
4775    /// CollectionContract gate: tables without an APPEND ONLY contract
4776    /// permit INSERT, UPDATE, and DELETE — the gate's default branch
4777    /// is a true pass-through, not an accidental block.
4778    #[test]
4779    fn collection_contract_gate_allows_all_verbs_on_unrestricted_table() {
4780        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4781        rt.execute_query("CREATE TABLE notes (id INT, body TEXT)")
4782            .unwrap();
4783
4784        rt.execute_query("INSERT INTO notes (id, body) VALUES (1, 'a')")
4785            .unwrap();
4786        let updated = rt
4787            .execute_query("UPDATE notes SET body = 'b' WHERE id = 1")
4788            .unwrap();
4789        assert_eq!(updated.affected_rows, 1);
4790        let deleted = rt.execute_query("DELETE FROM notes WHERE id = 1").unwrap();
4791        assert_eq!(deleted.affected_rows, 1);
4792    }
4793
4794    #[test]
4795    fn insert_into_event_enabled_table_emits_event_to_configured_queue() {
4796        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4797        rt.execute_query(
4798            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (INSERT) TO audit_log",
4799        )
4800        .unwrap();
4801
4802        let inserted = rt
4803            .execute_query("INSERT INTO users (id, email) VALUES (7, 'a@example.com')")
4804            .unwrap();
4805        assert_eq!(inserted.affected_rows, 1);
4806
4807        let events = queue_payloads(&rt, "audit_log");
4808        assert_eq!(events.len(), 1);
4809        let event = events[0].as_object().expect("event payload object");
4810        assert!(event
4811            .get("event_id")
4812            .and_then(crate::json::Value::as_str)
4813            .is_some_and(|value| !value.is_empty()));
4814        assert_eq!(
4815            event.get("op").and_then(crate::json::Value::as_str),
4816            Some("insert")
4817        );
4818        assert_eq!(
4819            event.get("collection").and_then(crate::json::Value::as_str),
4820            Some("users")
4821        );
4822        assert_eq!(
4823            event.get("id").and_then(crate::json::Value::as_u64),
4824            Some(7)
4825        );
4826        assert!(event
4827            .get("ts")
4828            .and_then(crate::json::Value::as_u64)
4829            .is_some());
4830        assert!(event
4831            .get("lsn")
4832            .and_then(crate::json::Value::as_u64)
4833            .is_some());
4834        assert!(matches!(
4835            event.get("tenant"),
4836            Some(crate::json::Value::Null)
4837        ));
4838        assert!(matches!(
4839            event.get("before"),
4840            Some(crate::json::Value::Null)
4841        ));
4842        let after = event
4843            .get("after")
4844            .and_then(crate::json::Value::as_object)
4845            .expect("after object");
4846        assert_eq!(
4847            after.get("id").and_then(crate::json::Value::as_u64),
4848            Some(7)
4849        );
4850        assert_eq!(
4851            after.get("email").and_then(crate::json::Value::as_str),
4852            Some("a@example.com")
4853        );
4854    }
4855
4856    #[test]
4857    fn multi_row_insert_emits_one_insert_event_per_row_in_order() {
4858        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4859        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4860            .unwrap();
4861
4862        rt.execute_query(
4863            "INSERT INTO users (id, email) VALUES (1, 'a@example.com'), (2, 'b@example.com')",
4864        )
4865        .unwrap();
4866
4867        let events = queue_payloads(&rt, "users_events");
4868        assert_eq!(events.len(), 2);
4869        let mut previous_lsn = 0;
4870        for (event, expected_id) in events.iter().zip([1_u64, 2]) {
4871            let object = event.as_object().expect("event payload object");
4872            assert_eq!(
4873                object.get("op").and_then(crate::json::Value::as_str),
4874                Some("insert")
4875            );
4876            assert_eq!(
4877                object.get("id").and_then(crate::json::Value::as_u64),
4878                Some(expected_id)
4879            );
4880            let lsn = object
4881                .get("lsn")
4882                .and_then(crate::json::Value::as_u64)
4883                .expect("event lsn");
4884            assert!(
4885                lsn > previous_lsn,
4886                "event LSNs should increase in row order"
4887            );
4888            previous_lsn = lsn;
4889            let after = object
4890                .get("after")
4891                .and_then(crate::json::Value::as_object)
4892                .expect("after object");
4893            assert_eq!(
4894                after.get("id").and_then(crate::json::Value::as_u64),
4895                Some(expected_id)
4896            );
4897        }
4898    }
4899
4900    #[test]
4901    fn claim_metrics_increment_skipped_locked_without_counting_miss() {
4902        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
4903        rt.execute_query("CREATE TABLE claim_metric_locked (id INT, rank INT, status TEXT)")
4904            .expect("create table");
4905        rt.execute_query(
4906            "INSERT INTO claim_metric_locked (id, rank, status) VALUES \
4907             (1, 10, 'ready'), (2, 20, 'ready')",
4908        )
4909        .expect("insert rows");
4910
4911        let claim_lock = rt
4912            .inner
4913            .rmw_locks
4914            .lock_for("claim_metric_locked", "__table_claim_update__");
4915        let _guard = claim_lock.lock();
4916        let updated = rt
4917            .execute_query(
4918                "UPDATE claim_metric_locked SET status = 'claimed' WHERE status = 'ready' \
4919                 CLAIM LIMIT 2 ORDER BY rank ASC",
4920            )
4921            .expect("claim skips locked candidates");
4922
4923        assert_eq!(updated.affected_rows, 0);
4924        let snapshot = rt.claim_telemetry_snapshot();
4925        assert_eq!(
4926            claim_metric_count(&snapshot, "attempts", "claim_metric_locked", "table"),
4927            1
4928        );
4929        assert_eq!(
4930            claim_metric_count(&snapshot, "skipped_locked", "claim_metric_locked", "table"),
4931            2
4932        );
4933        assert_eq!(
4934            claim_metric_count(&snapshot, "misses", "claim_metric_locked", "table"),
4935            0
4936        );
4937        assert_eq!(
4938            snapshot.skipped_locked.len(),
4939            1,
4940            "skipped-lock labels stay bounded to collection/model"
4941        );
4942    }
4943
4944    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
4945        let result = rt
4946            .execute_query(&format!("QUEUE PEEK {queue} 10"))
4947            .expect("peek queue");
4948        result
4949            .result
4950            .records
4951            .iter()
4952            .map(
4953                |record| match record.get("payload").expect("payload column") {
4954                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
4955                    other => panic!("expected JSON queue payload, got {other:?}"),
4956                },
4957            )
4958            .collect()
4959    }
4960
4961    // ── #112: auto-index user `id` on first insert ─────────────────────
4962
4963    /// First insert into a fresh collection that carries a column named
4964    /// `id` registers an implicit HASH index on `id`. Subsequent inserts
4965    /// populate it transparently, and `WHERE id = N` lookups exercise
4966    /// the hash-index fast path in `DmlTargetScan::find_target_ids`.
4967    ///
4968    /// This is the load-bearing acceptance test for #112 — without the
4969    /// hook, `find_index_for_column` returns `None` and DELETE/UPDATE
4970    /// fall through to a full segment scan (the 4× perf gap documented
4971    /// in `docs/perf/delete-sequential-2026-05-06.md`).
4972    #[test]
4973    fn auto_index_id_fires_on_first_insert() {
4974        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4975        rt.execute_query("CREATE TABLE bench_users (id INT, score INT)")
4976            .unwrap();
4977
4978        // Pre-condition: no index on `id` yet.
4979        assert!(
4980            rt.index_store_ref()
4981                .find_index_for_column("bench_users", "id")
4982                .is_none(),
4983            "freshly created collection should not have an `id` index"
4984        );
4985
4986        // Single-row INSERT — drives `MutationEngine::append_one`.
4987        rt.execute_query("INSERT INTO bench_users (id, score) VALUES (1, 10)")
4988            .unwrap();
4989
4990        // Post-condition: hash index registered on `id`.
4991        let registered = rt
4992            .index_store_ref()
4993            .find_index_for_column("bench_users", "id")
4994            .expect("auto-index hook should have registered idx_id on first insert");
4995        assert_eq!(registered.name, "idx_id");
4996        assert_eq!(registered.collection, "bench_users");
4997        assert_eq!(registered.columns, vec!["id".to_string()]);
4998        assert!(matches!(
4999            registered.method,
5000            super::super::index_store::IndexMethodKind::Hash
5001        ));
5002
5003        // Subsequent inserts populate the index; `WHERE id = N` should
5004        // resolve via the hash fast path and round-trip every row.
5005        for id in 2..=5 {
5006            rt.execute_query(&format!(
5007                "INSERT INTO bench_users (id, score) VALUES ({id}, {})",
5008                id * 10
5009            ))
5010            .unwrap();
5011        }
5012        for id in 1..=5 {
5013            let result = rt
5014                .execute_query(&format!("SELECT score FROM bench_users WHERE id = {id}"))
5015                .unwrap();
5016            assert_eq!(
5017                result.result.records.len(),
5018                1,
5019                "id={id} should match one row"
5020            );
5021        }
5022
5023        // Delete via the hash fast-path — exactly the bench scenario the
5024        // perf doc identified as the 4× regression. With the index
5025        // present, `find_target_ids` short-circuits before
5026        // `for_each_entity_zoned` runs.
5027        let deleted = rt
5028            .execute_query("DELETE FROM bench_users WHERE id = 3")
5029            .unwrap();
5030        assert_eq!(deleted.affected_rows, 1);
5031    }
5032
5033    /// Bulk INSERT (the multi-row VALUES path) drives
5034    /// `MutationEngine::append_batch`. The hook must fire there too —
5035    /// otherwise the batch entry points (gRPC binary bulk, HTTP bulk,
5036    /// wire bulk INSERT) skip auto-indexing entirely.
5037    #[test]
5038    fn auto_index_id_fires_on_first_bulk_insert() {
5039        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5040        rt.execute_query("CREATE TABLE bench_bulk (id INT, score INT)")
5041            .unwrap();
5042
5043        rt.execute_query("INSERT INTO bench_bulk (id, score) VALUES (1, 10), (2, 20), (3, 30)")
5044            .unwrap();
5045
5046        let registered = rt
5047            .index_store_ref()
5048            .find_index_for_column("bench_bulk", "id")
5049            .expect("auto-index hook should fire on first bulk insert");
5050        assert_eq!(registered.name, "idx_id");
5051
5052        // Every row populated via `index_entity_insert_batch`.
5053        for id in 1..=3 {
5054            let result = rt
5055                .execute_query(&format!("SELECT score FROM bench_bulk WHERE id = {id}"))
5056                .unwrap();
5057            assert_eq!(result.result.records.len(), 1);
5058        }
5059    }
5060
5061    /// Hook is a no-op when the row carries no `id` column. Conservative
5062    /// match (case-sensitive `id`) — `Id`, `ID`, and `rid`
5063    /// don't trigger it.
5064    #[test]
5065    fn auto_index_id_skips_when_no_id_column() {
5066        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5067        rt.execute_query("CREATE TABLE plain (uid INT, label TEXT)")
5068            .unwrap();
5069        rt.execute_query("INSERT INTO plain (uid, label) VALUES (1, 'a')")
5070            .unwrap();
5071
5072        assert!(rt
5073            .index_store_ref()
5074            .find_index_for_column("plain", "id")
5075            .is_none());
5076        assert!(rt
5077            .index_store_ref()
5078            .find_index_for_column("plain", "uid")
5079            .is_none());
5080    }
5081
5082    /// Hook only fires once per collection. If an explicit
5083    /// `CREATE INDEX ... USING BTREE` already covers `id`, the hook
5084    /// detects it via `find_index_for_column` and does NOT clobber it
5085    /// with a HASH index on the next insert.
5086    #[test]
5087    fn auto_index_id_skips_when_index_already_exists() {
5088        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5089        rt.execute_query("CREATE TABLE pre (id INT, score INT)")
5090            .unwrap();
5091        // User-declared BTREE index on `id` before any insert.
5092        rt.execute_query("CREATE INDEX user_idx ON pre (id) USING BTREE")
5093            .unwrap();
5094        rt.execute_query("INSERT INTO pre (id, score) VALUES (1, 10)")
5095            .unwrap();
5096
5097        let registered = rt
5098            .index_store_ref()
5099            .find_index_for_column("pre", "id")
5100            .expect("user index should still be there");
5101        assert_eq!(
5102            registered.name, "user_idx",
5103            "auto-index hook must not overwrite an existing index"
5104        );
5105    }
5106
5107    /// Implicit `idx_id` is reaped when the collection drops. The
5108    /// existing `execute_drop_table` walks `list_indices` and drops every
5109    /// entry — confirm the auto-created index participates.
5110    #[test]
5111    fn auto_index_id_dropped_with_collection() {
5112        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5113        rt.execute_query("CREATE TABLE ephemeral (id INT, score INT)")
5114            .unwrap();
5115        rt.execute_query("INSERT INTO ephemeral (id, score) VALUES (1, 10)")
5116            .unwrap();
5117        assert!(rt
5118            .index_store_ref()
5119            .find_index_for_column("ephemeral", "id")
5120            .is_some());
5121
5122        rt.execute_query("DROP TABLE ephemeral").unwrap();
5123
5124        assert!(
5125            rt.index_store_ref()
5126                .find_index_for_column("ephemeral", "id")
5127                .is_none(),
5128            "implicit `idx_id` must be reaped when its collection drops"
5129        );
5130    }
5131
5132    /// Opt-out via `RedDBOptions::with_auto_index_id(false)` (which
5133    /// forwards to `UnifiedStoreConfig::auto_index_id`). With the knob
5134    /// off, first insert leaves the collection without an `id` index —
5135    /// DELETE/UPDATE fall back to the scan path.
5136    #[test]
5137    fn auto_index_id_disabled_by_config() {
5138        let opts = RedDBOptions::in_memory().with_auto_index_id(false);
5139        let rt = RedDBRuntime::with_options(opts).unwrap();
5140
5141        rt.execute_query("CREATE TABLE off (id INT, score INT)")
5142            .unwrap();
5143        rt.execute_query("INSERT INTO off (id, score) VALUES (1, 10)")
5144            .unwrap();
5145
5146        assert!(
5147            rt.index_store_ref()
5148                .find_index_for_column("off", "id")
5149                .is_none(),
5150            "with auto_index_id=false, no implicit index should be created"
5151        );
5152    }
5153
5154    // ── #293: UPDATE / DELETE events ─────────────────────────────────────
5155
5156    #[test]
5157    fn update_single_row_emits_update_event() {
5158        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5159        rt.execute_query(
5160            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO audit_log",
5161        )
5162        .unwrap();
5163        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5164            .unwrap();
5165
5166        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
5167            .unwrap();
5168
5169        let events = queue_payloads(&rt, "audit_log");
5170        assert_eq!(events.len(), 1, "expected exactly 1 update event");
5171        let event = events[0].as_object().expect("event payload object");
5172        assert_eq!(
5173            event.get("op").and_then(crate::json::Value::as_str),
5174            Some("update")
5175        );
5176        assert_eq!(
5177            event.get("collection").and_then(crate::json::Value::as_str),
5178            Some("users")
5179        );
5180        assert!(event
5181            .get("event_id")
5182            .and_then(crate::json::Value::as_str)
5183            .is_some_and(|v| !v.is_empty()));
5184        let before = event
5185            .get("before")
5186            .and_then(crate::json::Value::as_object)
5187            .expect("before must be an object");
5188        let after = event
5189            .get("after")
5190            .and_then(crate::json::Value::as_object)
5191            .expect("after must be an object");
5192        assert_eq!(
5193            before.get("name").and_then(crate::json::Value::as_str),
5194            Some("Alice"),
5195            "before.name should be the old value"
5196        );
5197        assert_eq!(
5198            after.get("name").and_then(crate::json::Value::as_str),
5199            Some("Bob"),
5200            "after.name should be the new value"
5201        );
5202    }
5203
5204    #[test]
5205    fn update_event_only_includes_changed_fields() {
5206        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5207        rt.execute_query(
5208            "CREATE TABLE users (id INT, name TEXT, email TEXT) WITH EVENTS (UPDATE) TO evts",
5209        )
5210        .unwrap();
5211        rt.execute_query("INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'a@x.com')")
5212            .unwrap();
5213
5214        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
5215            .unwrap();
5216
5217        let events = queue_payloads(&rt, "evts");
5218        assert_eq!(events.len(), 1);
5219        let event = events[0].as_object().unwrap();
5220        let before = event
5221            .get("before")
5222            .and_then(crate::json::Value::as_object)
5223            .unwrap();
5224        let after = event
5225            .get("after")
5226            .and_then(crate::json::Value::as_object)
5227            .unwrap();
5228        // Only changed field included.
5229        assert!(
5230            before.contains_key("name"),
5231            "before must include changed field"
5232        );
5233        assert!(
5234            after.contains_key("name"),
5235            "after must include changed field"
5236        );
5237        // Unchanged fields must not appear.
5238        assert!(
5239            !before.contains_key("email"),
5240            "before must not include unchanged email"
5241        );
5242        assert!(
5243            !after.contains_key("email"),
5244            "after must not include unchanged email"
5245        );
5246    }
5247
5248    #[test]
5249    fn multi_row_update_emits_one_event_per_row() {
5250        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5251        rt.execute_query("CREATE TABLE items (id INT, status TEXT) WITH EVENTS (UPDATE) TO evts")
5252            .unwrap();
5253        rt.execute_query(
5254            "INSERT INTO items (id, status) VALUES (1, 'new'), (2, 'new'), (3, 'new')",
5255        )
5256        .unwrap();
5257
5258        rt.execute_query("UPDATE items SET status = 'done'")
5259            .unwrap();
5260
5261        let events = queue_payloads(&rt, "evts");
5262        assert_eq!(events.len(), 3, "expected one update event per row");
5263        for event in &events {
5264            let obj = event.as_object().unwrap();
5265            assert_eq!(
5266                obj.get("op").and_then(crate::json::Value::as_str),
5267                Some("update")
5268            );
5269        }
5270    }
5271
5272    #[test]
5273    fn delete_single_row_emits_delete_event() {
5274        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5275        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (DELETE) TO del_log")
5276            .unwrap();
5277        rt.execute_query("INSERT INTO users (id, name) VALUES (42, 'Alice')")
5278            .unwrap();
5279
5280        rt.execute_query("DELETE FROM users WHERE id = 42").unwrap();
5281
5282        let events = queue_payloads(&rt, "del_log");
5283        assert_eq!(events.len(), 1);
5284        let event = events[0].as_object().expect("event payload object");
5285        assert_eq!(
5286            event.get("op").and_then(crate::json::Value::as_str),
5287            Some("delete")
5288        );
5289        assert_eq!(
5290            event.get("collection").and_then(crate::json::Value::as_str),
5291            Some("users")
5292        );
5293        assert!(event
5294            .get("event_id")
5295            .and_then(crate::json::Value::as_str)
5296            .is_some_and(|v| !v.is_empty()));
5297        let before = event
5298            .get("before")
5299            .and_then(crate::json::Value::as_object)
5300            .expect("before must be an object for delete");
5301        assert_eq!(
5302            before.get("id").and_then(crate::json::Value::as_u64),
5303            Some(42)
5304        );
5305        assert_eq!(
5306            before.get("name").and_then(crate::json::Value::as_str),
5307            Some("Alice")
5308        );
5309        assert!(matches!(event.get("after"), Some(crate::json::Value::Null)));
5310    }
5311
5312    #[test]
5313    fn multi_row_delete_emits_one_event_per_row() {
5314        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5315        rt.execute_query("CREATE TABLE items (id INT, val INT) WITH EVENTS (DELETE) TO del_log")
5316            .unwrap();
5317        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 10), (2, 20), (3, 30)")
5318            .unwrap();
5319
5320        rt.execute_query("DELETE FROM items").unwrap();
5321
5322        let events = queue_payloads(&rt, "del_log");
5323        assert_eq!(events.len(), 3, "expected one delete event per deleted row");
5324        for event in &events {
5325            let obj = event.as_object().unwrap();
5326            assert_eq!(
5327                obj.get("op").and_then(crate::json::Value::as_str),
5328                Some("delete")
5329            );
5330            assert!(matches!(obj.get("after"), Some(crate::json::Value::Null)));
5331        }
5332    }
5333
5334    #[test]
5335    fn ops_filter_update_does_not_emit_on_insert_or_delete() {
5336        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5337        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO evts")
5338            .unwrap();
5339
5340        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5341            .unwrap();
5342        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
5343
5344        let events = queue_payloads(&rt, "evts");
5345        assert!(
5346            events.is_empty(),
5347            "UPDATE-only filter must not emit INSERT or DELETE events"
5348        );
5349    }
5350
5351    // ── SUPPRESS EVENTS ────────────────────────────────────────────────────
5352
5353    #[test]
5354    fn suppress_events_on_insert_emits_no_events() {
5355        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5356        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5357            .unwrap();
5358
5359        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5360            .unwrap();
5361
5362        let events = queue_payloads(&rt, "evts");
5363        assert!(
5364            events.is_empty(),
5365            "SUPPRESS EVENTS must prevent INSERT events"
5366        );
5367    }
5368
5369    #[test]
5370    fn suppress_events_on_update_emits_no_events() {
5371        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5372        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5373            .unwrap();
5374        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5375            .unwrap();
5376        // drain the INSERT event
5377        let _ = queue_payloads(&rt, "evts");
5378        // Force pop to drain; simpler: just check new count after UPDATE
5379        rt.execute_query("QUEUE PURGE evts").unwrap();
5380
5381        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1 SUPPRESS EVENTS")
5382            .unwrap();
5383
5384        let events = queue_payloads(&rt, "evts");
5385        assert!(
5386            events.is_empty(),
5387            "SUPPRESS EVENTS must prevent UPDATE events"
5388        );
5389    }
5390
5391    #[test]
5392    fn suppress_events_on_delete_emits_no_events() {
5393        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5394        rt.execute_query(
5395            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (INSERT, DELETE) TO evts",
5396        )
5397        .unwrap();
5398        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5399            .unwrap();
5400
5401        rt.execute_query("DELETE FROM users WHERE id = 1 SUPPRESS EVENTS")
5402            .unwrap();
5403
5404        let events = queue_payloads(&rt, "evts");
5405        assert!(
5406            events.is_empty(),
5407            "SUPPRESS EVENTS must prevent DELETE events"
5408        );
5409    }
5410
5411    #[test]
5412    fn normal_insert_after_suppress_still_emits() {
5413        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5414        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5415            .unwrap();
5416
5417        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5418            .unwrap();
5419        rt.execute_query("INSERT INTO users (id, name) VALUES (2, 'Bob')")
5420            .unwrap();
5421
5422        let events = queue_payloads(&rt, "evts");
5423        assert_eq!(
5424            events.len(),
5425            1,
5426            "only the non-suppressed INSERT should emit"
5427        );
5428        assert_eq!(
5429            events[0].get("id").and_then(crate::json::Value::as_u64),
5430            Some(2)
5431        );
5432    }
5433}