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_kv_key_update_target_allowed(query)?;
1724        ensure_graph_identity_update_target_allowed(query)?;
1725
1726        // Apply RLS augmentation first so every downstream path — plain
1727        // UPDATE, UPDATE...RETURNING, the inner scan — observes the
1728        // same policy-filtered target set. This prevents RETURNING
1729        // from ever exposing rows the UPDATE policy would have
1730        // denied.
1731        let rls_gated = crate::runtime::impl_core::rls_is_enabled(self, &query.table);
1732        let augmented_query: UpdateQuery;
1733        let effective_query: &UpdateQuery = if rls_gated {
1734            let update_filter = crate::runtime::impl_core::rls_policy_filter(
1735                self,
1736                &query.table,
1737                crate::storage::query::ast::PolicyAction::Update,
1738            );
1739            let Some(mut policy) = update_filter else {
1740                // No admitting policy: zero rows affected, empty
1741                // RETURNING (never leak rows the caller can't touch).
1742                let mut response = RuntimeQueryResult::dml_result(
1743                    raw_query.to_string(),
1744                    0,
1745                    "update",
1746                    "runtime-dml-rls",
1747                );
1748                if let Some(items) = query.returning.clone() {
1749                    response.result = build_returning_result(&items, &[], None);
1750                }
1751                return Ok(response);
1752            };
1753            if query.claim_limit.is_some() {
1754                let read_filter = crate::runtime::impl_core::rls_policy_filter(
1755                    self,
1756                    &query.table,
1757                    crate::storage::query::ast::PolicyAction::Select,
1758                );
1759                let Some(read_policy) = read_filter else {
1760                    let mut response = RuntimeQueryResult::dml_result(
1761                        raw_query.to_string(),
1762                        0,
1763                        "update",
1764                        "runtime-dml-rls",
1765                    );
1766                    if let Some(items) = query.returning.clone() {
1767                        response.result = build_returning_result(&items, &[], None);
1768                    }
1769                    return Ok(response);
1770                };
1771                policy = crate::storage::query::ast::Filter::And(
1772                    Box::new(read_policy),
1773                    Box::new(policy),
1774                );
1775            }
1776            let mut augmented = query.clone();
1777            augmented.filter = Some(match augmented.filter.take() {
1778                Some(existing) => {
1779                    crate::storage::query::ast::Filter::And(Box::new(existing), Box::new(policy))
1780                }
1781                None => policy,
1782            });
1783            augmented_query = augmented;
1784            &augmented_query
1785        } else {
1786            query
1787        };
1788
1789        // RETURNING wraps the inner executor and uses the touched-id
1790        // list the inner reports so the post-image reflects exactly
1791        // the rows the UPDATE actually mutated (not whatever a
1792        // separate SELECT might have observed).
1793        if let Some(items) = effective_query.returning.clone() {
1794            let mut inner_query = effective_query.clone();
1795            inner_query.returning = None;
1796            let (mut response, touched_ids) =
1797                self.execute_update_inner_tracked(raw_query, &inner_query)?;
1798
1799            let mut snapshots = if matches!(
1800                effective_query.target,
1801                UpdateTarget::Nodes | UpdateTarget::Edges
1802            ) {
1803                graph_update_returning_snapshots(self, &effective_query.table, &touched_ids)
1804            } else {
1805                super::dml_target_scan::DmlTargetScan::new(self, &effective_query.table, None, None)
1806                    .row_snapshots(&touched_ids)
1807            };
1808            if matches!(effective_query.target, UpdateTarget::Kv) {
1809                restore_kv_returning_keys(
1810                    self,
1811                    &effective_query.table,
1812                    &touched_ids,
1813                    &mut snapshots,
1814                );
1815            }
1816
1817            response.result = build_returning_result(&items, &snapshots, None);
1818            response.engine = "runtime-dml-returning";
1819            return Ok(response);
1820        }
1821
1822        self.execute_update_inner(raw_query, effective_query)
1823    }
1824
1825    /// Back-compat shim: the older entry point ignored touched ids.
1826    fn execute_update_inner(
1827        &self,
1828        raw_query: &str,
1829        query: &UpdateQuery,
1830    ) -> RedDBResult<RuntimeQueryResult> {
1831        self.execute_update_inner_tracked(raw_query, query)
1832            .map(|(res, _)| res)
1833    }
1834
1835    fn execute_update_inner_tracked(
1836        &self,
1837        raw_query: &str,
1838        query: &UpdateQuery,
1839    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
1840        let store = self.inner.db.store();
1841        let effective_filter = effective_update_filter(query);
1842        let compiled_plan = self.compile_update_plan(query)?;
1843        let needs_rmw_lock = update_needs_rmw_lock(query);
1844        let claim_model = update_model_name(update_target_model(query.target));
1845        if query.claim_limit.is_some() {
1846            self.inner
1847                .claim_telemetry
1848                .record_attempt(&query.table, claim_model);
1849        }
1850        let claim_lock = query.claim_limit.map(|_| {
1851            self.inner
1852                .rmw_locks
1853                .lock_for(&query.table, "__table_claim_update__")
1854        });
1855        let _claim_guard = if let Some(lock) = claim_lock.as_ref() {
1856            let Some(guard) = lock.try_lock() else {
1857                let skipped_locked = query.claim_limit.unwrap_or(1);
1858                self.inner.claim_telemetry.record_skipped_locked(
1859                    &query.table,
1860                    claim_model,
1861                    skipped_locked,
1862                );
1863                tracing::debug!(
1864                    target: "reddb::claim",
1865                    collection = %query.table,
1866                    model = claim_model,
1867                    skipped_locked,
1868                    "concurrent claim skipped locked candidates"
1869                );
1870                return Ok((
1871                    RuntimeQueryResult::dml_result(
1872                        raw_query.to_string(),
1873                        0,
1874                        "update",
1875                        "runtime-dml",
1876                    ),
1877                    Vec::new(),
1878                ));
1879            };
1880            Some(guard)
1881        } else {
1882            None
1883        };
1884        let table_rmw_lock = if needs_rmw_lock {
1885            Some(
1886                self.inner
1887                    .rmw_locks
1888                    .lock_for(&query.table, "__table_rmw_update__"),
1889            )
1890        } else {
1891            None
1892        };
1893        let _table_rmw_guard = table_rmw_lock.as_ref().map(|lock| lock.lock());
1894        let mut touched_ids: Vec<EntityId> = Vec::new();
1895        let claim_cap = query.claim_limit.map(|limit| limit as usize);
1896        let limit_cap = claim_cap.or_else(|| query.limit.map(|limit| limit as usize));
1897        let manager = store
1898            .get_collection(&query.table)
1899            .ok_or_else(|| RedDBError::NotFound(query.table.clone()))?;
1900        let scan_limit = if query.order_by.is_empty() {
1901            limit_cap
1902        } else {
1903            None
1904        };
1905        let mut target_scan = super::dml_target_scan::DmlTargetScan::with_update_target(
1906            self,
1907            &query.table,
1908            effective_filter.as_ref(),
1909            scan_limit,
1910            query.target,
1911        );
1912        if needs_rmw_lock {
1913            target_scan = target_scan.with_live_table_rows();
1914        }
1915        let ids_to_update = target_scan.find_target_ids()?;
1916        let order_limit = if query.claim_limit.is_some() {
1917            None
1918        } else {
1919            limit_cap
1920        };
1921        let ids_to_update = if query.order_by.is_empty() {
1922            ids_to_update
1923        } else {
1924            ordered_update_target_ids(&manager, &ids_to_update, &query.order_by, order_limit)
1925        };
1926        let mut ids_to_update = if query.claim_limit.is_some() {
1927            self.filter_claim_locked_target_ids(&query.table, ids_to_update)
1928        } else {
1929            ids_to_update
1930        };
1931        if let Some(claim_cap) = claim_cap {
1932            ids_to_update.truncate(claim_cap);
1933        }
1934        if query.claim_exact
1935            && claim_cap.is_some_and(|claim_count| ids_to_update.len() < claim_count)
1936        {
1937            self.inner
1938                .claim_telemetry
1939                .record_miss(&query.table, claim_model);
1940            return Ok((
1941                RuntimeQueryResult::dml_result(raw_query.to_string(), 0, "update", "runtime-dml"),
1942                Vec::new(),
1943            ));
1944        }
1945
1946        if needs_rmw_lock {
1947            let result = self.execute_update_inner_tracked_locked(
1948                raw_query,
1949                query,
1950                &compiled_plan,
1951                &ids_to_update,
1952                effective_filter.as_ref(),
1953            )?;
1954            if query.claim_limit.is_some() {
1955                self.record_pending_claim_locks_for_touched_ids(&query.table, &result.1);
1956            }
1957            record_claim_outcome(
1958                &self.inner.claim_telemetry,
1959                query.claim_limit,
1960                &query.table,
1961                claim_model,
1962                result.0.affected_rows,
1963            );
1964            return Ok(result);
1965        }
1966
1967        let mut affected: u64 = 0;
1968        for chunk in ids_to_update.chunks(UPDATE_APPLY_CHUNK_SIZE) {
1969            let mut applied_chunk = Vec::with_capacity(chunk.len());
1970            for entity in manager.get_many(chunk).into_iter().flatten() {
1971                let assignments =
1972                    self.materialize_update_assignments_for_entity(query, &entity, &compiled_plan)?;
1973                let applied = self.apply_materialized_update_for_entity(
1974                    query,
1975                    entity,
1976                    &compiled_plan,
1977                    assignments,
1978                )?;
1979                touched_ids.push(applied.id);
1980                applied_chunk.push(applied);
1981            }
1982            self.persist_update_chunk(&applied_chunk)?;
1983            affected += applied_chunk.len() as u64;
1984            let lsns = self.flush_update_chunk(&applied_chunk)?;
1985            if !query.suppress_events {
1986                self.emit_update_events_for_collection(&query.table, &applied_chunk, &lsns)?;
1987            }
1988        }
1989
1990        if affected > 0 {
1991            self.note_table_write(&query.table);
1992        }
1993        if query.claim_limit.is_some() {
1994            self.record_pending_claim_locks_for_touched_ids(&query.table, &touched_ids);
1995        }
1996        record_claim_outcome(
1997            &self.inner.claim_telemetry,
1998            query.claim_limit,
1999            &query.table,
2000            claim_model,
2001            affected,
2002        );
2003
2004        Ok((
2005            RuntimeQueryResult::dml_result(
2006                raw_query.to_string(),
2007                affected,
2008                "update",
2009                "runtime-dml",
2010            ),
2011            touched_ids,
2012        ))
2013    }
2014
2015    fn filter_claim_locked_target_ids(&self, table: &str, ids: Vec<EntityId>) -> Vec<EntityId> {
2016        let conn_id = current_connection_id();
2017        let locks = self.inner.pending_claim_locks.read();
2018        ids.into_iter()
2019            .filter(|id| {
2020                let Some(entity) = self.inner.db.store().get(table, *id) else {
2021                    return false;
2022                };
2023                let key = (table.to_string(), entity.logical_id());
2024                locks
2025                    .get(&key)
2026                    .is_none_or(|owner_conn_id| *owner_conn_id == conn_id)
2027            })
2028            .collect()
2029    }
2030
2031    fn record_pending_claim_locks_for_touched_ids(&self, table: &str, ids: &[EntityId]) {
2032        if self.current_xid().is_none() || ids.is_empty() {
2033            return;
2034        }
2035
2036        let conn_id = current_connection_id();
2037        let store = self.inner.db.store();
2038        let mut locks = self.inner.pending_claim_locks.write();
2039        for id in ids {
2040            let Some(entity) = store.get(table, *id) else {
2041                continue;
2042            };
2043            locks.insert((table.to_string(), entity.logical_id()), conn_id);
2044        }
2045    }
2046
2047    fn execute_update_inner_tracked_locked(
2048        &self,
2049        raw_query: &str,
2050        query: &UpdateQuery,
2051        compiled_plan: &CompiledUpdatePlan,
2052        ids_to_update: &[EntityId],
2053        effective_filter: Option<&Filter>,
2054    ) -> RedDBResult<(RuntimeQueryResult, Vec<EntityId>)> {
2055        let store = self.inner.db.store();
2056        let mut touched_ids = Vec::new();
2057        let mut lock_entries = Vec::new();
2058
2059        for id in ids_to_update {
2060            let Some(candidate) = store.get(&query.table, *id) else {
2061                continue;
2062            };
2063            let logical_id = candidate.logical_id();
2064            let lock_key = format!("row:{}", logical_id.raw());
2065            let rmw_lock = self.inner.rmw_locks.lock_for(&query.table, &lock_key);
2066            lock_entries.push((lock_key, logical_id, rmw_lock));
2067        }
2068
2069        lock_entries.sort_by(|left, right| left.0.cmp(&right.0));
2070        lock_entries.dedup_by(|left, right| left.0 == right.0);
2071        let _rmw_guards: Vec<_> = lock_entries.iter().map(|entry| entry.2.lock()).collect();
2072
2073        let mut applied_chunk = Vec::new();
2074        for (_, logical_id, _) in &lock_entries {
2075            let Some(entity) = resolve_update_entity_by_logical_id(self, &query.table, *logical_id)
2076            else {
2077                continue;
2078            };
2079            if let Some(filter) = effective_filter {
2080                if !crate::runtime::query_exec::evaluate_entity_filter_with_db(
2081                    Some(self.inner.db.as_ref()),
2082                    &entity,
2083                    filter,
2084                    &query.table,
2085                    &query.table,
2086                ) {
2087                    continue;
2088                }
2089            }
2090
2091            let assignments =
2092                self.materialize_update_assignments_for_entity(query, &entity, compiled_plan)?;
2093            let applied = self.apply_materialized_update_for_entity(
2094                query,
2095                entity,
2096                compiled_plan,
2097                assignments,
2098            )?;
2099            touched_ids.push(applied.id);
2100            applied_chunk.push(applied);
2101        }
2102
2103        let affected = applied_chunk.len() as u64;
2104        if !applied_chunk.is_empty() {
2105            self.persist_update_chunk(&applied_chunk)?;
2106            let lsns = self.flush_update_chunk(&applied_chunk)?;
2107            if !query.suppress_events {
2108                self.emit_update_events_for_collection(&query.table, &applied_chunk, &lsns)?;
2109            }
2110        }
2111
2112        if affected > 0 {
2113            self.note_table_write(&query.table);
2114        }
2115
2116        Ok((
2117            RuntimeQueryResult::dml_result(
2118                raw_query.to_string(),
2119                affected,
2120                "update",
2121                "runtime-dml",
2122            ),
2123            touched_ids,
2124        ))
2125    }
2126
2127    fn compile_update_plan(&self, query: &UpdateQuery) -> RedDBResult<CompiledUpdatePlan> {
2128        let mut static_field_assignments = Vec::new();
2129        let mut static_metadata_assignments = Vec::new();
2130        let mut dynamic_assignments = Vec::new();
2131        let row_contract_plan = build_row_update_contract_plan(&self.db(), &query.table)?;
2132        let mut row_modified_columns = Vec::new();
2133
2134        for (idx, (column, expr)) in query.assignment_exprs.iter().enumerate() {
2135            let compound_op = query.compound_assignment_ops.get(idx).copied().flatten();
2136            let metadata_key = resolve_sql_ttl_metadata_key(column);
2137            if compound_op.is_some() && metadata_key.is_some() {
2138                return Err(RedDBError::Query(format!(
2139                    "compound assignment is only supported for row fields: {column}"
2140                )));
2141            }
2142            if compound_op.is_none() {
2143                if let Ok(value) = fold_expr_to_value(expr.clone()) {
2144                    if let Some(metadata_key) = metadata_key {
2145                        let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2146                        let (canonical_key, canonical_value) =
2147                            canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2148                        static_metadata_assignments
2149                            .push((canonical_key.to_string(), canonical_value));
2150                    } else {
2151                        let value = self.resolve_crypto_sentinel(value)?;
2152                        static_field_assignments.push((
2153                            column.clone(),
2154                            normalize_row_update_assignment_with_plan(
2155                                &query.table,
2156                                column,
2157                                value,
2158                                row_contract_plan.as_ref(),
2159                            )?,
2160                        ));
2161                        row_modified_columns.push(column.clone());
2162                    }
2163                    continue;
2164                }
2165            }
2166
2167            dynamic_assignments.push(CompiledUpdateAssignment {
2168                column: column.clone(),
2169                expr: expr.clone(),
2170                compound_op,
2171                metadata_key,
2172                row_rule: if metadata_key.is_none() {
2173                    if let Some(plan) = row_contract_plan.as_ref() {
2174                        if plan.timestamps_enabled
2175                            && (column == "created_at" || column == "updated_at")
2176                        {
2177                            return Err(RedDBError::Query(format!(
2178                                "collection '{}' manages '{}' automatically — do not set it in UPDATE",
2179                                query.table, column
2180                            )));
2181                        }
2182                        if let Some(rule) = plan.declared_rules.get(column) {
2183                            Some(rule.clone())
2184                        } else if plan.strict_schema {
2185                            return Err(RedDBError::Query(format!(
2186                                "collection '{}' is strict and does not allow undeclared fields: {}",
2187                                query.table, column
2188                            )));
2189                        } else {
2190                            None
2191                        }
2192                    } else {
2193                        None
2194                    }
2195                } else {
2196                    None
2197                },
2198            });
2199            if metadata_key.is_none() {
2200                row_modified_columns.push(column.clone());
2201            }
2202        }
2203
2204        let row_modified_columns = dedupe_update_columns(row_modified_columns);
2205        let row_touches_unique_columns = row_contract_plan.as_ref().is_some_and(|plan| {
2206            row_modified_columns.iter().any(|column| {
2207                plan.unique_columns
2208                    .keys()
2209                    .any(|unique| unique.eq_ignore_ascii_case(column))
2210            })
2211        });
2212
2213        if let Some(ttl_ms) = query.ttl_ms {
2214            static_metadata_assignments
2215                .push(("_ttl_ms".to_string(), metadata_u64_to_value(ttl_ms)));
2216        }
2217        if let Some(expires_at_ms) = query.expires_at_ms {
2218            static_metadata_assignments.push((
2219                "_expires_at".to_string(),
2220                metadata_u64_to_value(expires_at_ms),
2221            ));
2222        }
2223        for (key, val) in &query.with_metadata {
2224            static_metadata_assignments.push((key.clone(), storage_value_to_metadata_value(val)));
2225        }
2226
2227        Ok(CompiledUpdatePlan {
2228            static_field_assignments,
2229            static_metadata_assignments,
2230            dynamic_assignments,
2231            row_contract_plan,
2232            row_modified_columns,
2233            row_touches_unique_columns,
2234        })
2235    }
2236
2237    fn materialize_update_assignments_for_entity(
2238        &self,
2239        query: &UpdateQuery,
2240        entity: &UnifiedEntity,
2241        compiled_plan: &CompiledUpdatePlan,
2242    ) -> RedDBResult<MaterializedUpdateAssignments> {
2243        let mut assignments = MaterializedUpdateAssignments::default();
2244        let mut record: Option<UnifiedRecord> = None;
2245
2246        for assignment in &compiled_plan.dynamic_assignments {
2247            if assignment.compound_op.is_some()
2248                && !matches!(
2249                    entity.data,
2250                    EntityData::Row(_) | EntityData::Node(_) | EntityData::Edge(_)
2251                )
2252            {
2253                return Err(RedDBError::Query(format!(
2254                    "compound assignment is only supported for row or graph UPDATE column '{}'",
2255                    assignment.column
2256                )));
2257            }
2258            if record.is_none() {
2259                record = runtime_any_record_from_entity_ref(entity);
2260            }
2261            let Some(record) = record.as_ref() else {
2262                return Err(RedDBError::Query(format!(
2263                    "UPDATE could not materialize runtime record for entity {} in '{}'",
2264                    entity.id.raw(),
2265                    query.table
2266                )));
2267            };
2268            let rhs = super::expr_eval::evaluate_runtime_expr_with_db(
2269                Some(self.inner.db.as_ref()),
2270                &assignment.expr,
2271                record,
2272                Some(query.table.as_str()),
2273                Some(query.table.as_str()),
2274            )
2275            .ok_or_else(|| {
2276                RedDBError::Query(format!(
2277                    "failed to evaluate UPDATE expression for column '{}'",
2278                    assignment.column
2279                ))
2280            })?;
2281            let value = if let Some(op) = assignment.compound_op {
2282                evaluate_compound_update_assignment(&assignment.column, record, op, rhs)?
2283            } else {
2284                rhs
2285            };
2286
2287            if let Some(metadata_key) = assignment.metadata_key {
2288                let raw_value = sql_literal_to_metadata_value(metadata_key, &value)?;
2289                let (canonical_key, canonical_value) =
2290                    canonicalize_sql_ttl_metadata(metadata_key, raw_value);
2291                assignments
2292                    .dynamic_metadata_assignments
2293                    .push((canonical_key.to_string(), canonical_value));
2294            } else {
2295                assignments.dynamic_field_assignments.push((
2296                    assignment.column.clone(),
2297                    normalize_row_update_value_for_rule(
2298                        &query.table,
2299                        self.resolve_crypto_sentinel(value)?,
2300                        assignment.row_rule.as_ref(),
2301                    )?,
2302                ));
2303            }
2304        }
2305
2306        Ok(assignments)
2307    }
2308
2309    fn apply_materialized_update_for_entity(
2310        &self,
2311        query: &UpdateQuery,
2312        entity: UnifiedEntity,
2313        compiled_plan: &CompiledUpdatePlan,
2314        mut assignments: MaterializedUpdateAssignments,
2315    ) -> RedDBResult<AppliedEntityMutation> {
2316        if matches!(query.target, UpdateTarget::Kv)
2317            && !compiled_plan
2318                .static_field_assignments
2319                .iter()
2320                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
2321            && !assignments
2322                .dynamic_field_assignments
2323                .iter()
2324                .any(|(column, _)| column.eq_ignore_ascii_case("key"))
2325        {
2326            if let Some(key) = runtime_any_record_from_entity_ref(&entity)
2327                .and_then(|record| record.get("key").cloned())
2328            {
2329                assignments
2330                    .dynamic_field_assignments
2331                    .push(("key".to_string(), key));
2332            }
2333        }
2334        if matches!(entity.data, EntityData::Row(_)) {
2335            return self.apply_loaded_sql_update_row_core(
2336                query.table.clone(),
2337                entity,
2338                &compiled_plan.static_field_assignments,
2339                assignments.dynamic_field_assignments,
2340                &compiled_plan.static_metadata_assignments,
2341                assignments.dynamic_metadata_assignments,
2342                compiled_plan.row_contract_plan.as_ref(),
2343                &compiled_plan.row_modified_columns,
2344                compiled_plan.row_touches_unique_columns,
2345            );
2346        }
2347
2348        ensure_graph_identity_update_allowed(&entity, compiled_plan, &assignments)?;
2349
2350        let operations = build_patch_operations_from_materialized_assignments(
2351            &entity,
2352            compiled_plan,
2353            assignments,
2354        );
2355        self.apply_loaded_patch_entity_core(
2356            query.table.clone(),
2357            entity,
2358            crate::json::Value::Null,
2359            operations,
2360        )
2361    }
2362
2363    /// Execute DELETE FROM table WHERE filter
2364    pub fn execute_delete(
2365        &self,
2366        raw_query: &str,
2367        query: &DeleteQuery,
2368    ) -> RedDBResult<RuntimeQueryResult> {
2369        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2370        // Issue #523 — blockchain collections are immutable; see
2371        // execute_update for the same gate.
2372        if crate::runtime::blockchain_kind::is_chain(self.inner.db.store().as_ref(), &query.table) {
2373            return Err(RedDBError::InvalidOperation(format!(
2374                "BlockchainCollectionImmutable: DELETE not allowed on '{}'",
2375                query.table
2376            )));
2377        }
2378        // CollectionContract gate (#50) — see execute_update for
2379        // rationale. The gate handles APPEND ONLY rejection and is
2380        // the single point where future contract bits land.
2381        crate::runtime::collection_contract::CollectionContractGate::check(
2382            self,
2383            &query.table,
2384            crate::runtime::collection_contract::MutationKind::Delete,
2385        )?;
2386
2387        // RETURNING on DELETE: capture the pre-image via an internal
2388        // SELECT that reuses the same WHERE, then run the delete with
2389        // the RETURNING clause stripped, then project the captured
2390        // rows through the requested items. The extra SELECT is a
2391        // pragmatic MVP — a future pass can fuse the scan with the
2392        // delete to avoid the second pass over the heap.
2393        if let Some(items) = query.returning.clone() {
2394            let select_sql = delete_to_select_sql(raw_query).ok_or_else(|| {
2395                RedDBError::Query(
2396                    "DELETE ... RETURNING: cannot rewrite query for pre-image scan".to_string(),
2397                )
2398            })?;
2399            let captured = self.execute_query(&select_sql)?;
2400
2401            let mut inner_query = query.clone();
2402            inner_query.returning = None;
2403            let _ = self.execute_delete(raw_query, &inner_query)?;
2404
2405            let snapshots: Vec<Vec<(String, Value)>> = captured
2406                .result
2407                .records
2408                .iter()
2409                .map(|rec| {
2410                    rec.iter_fields()
2411                        .map(|(k, v)| (k.as_ref().to_string(), v.clone()))
2412                        .collect()
2413                })
2414                .collect();
2415            let affected = snapshots.len() as u64;
2416            let result = build_returning_result(&items, &snapshots, None);
2417
2418            let mut response = RuntimeQueryResult::dml_result(
2419                raw_query.to_string(),
2420                affected,
2421                "delete",
2422                "runtime-dml-returning",
2423            );
2424            response.result = result;
2425            return Ok(response);
2426        }
2427        // Row-Level Security enforcement (Phase 2.5.2 PG parity).
2428        //
2429        // When the table has RLS enabled, gate the DELETE by the
2430        // per-role policy set: mutations only touch rows that *every*
2431        // matching `FOR DELETE` policy would accept. No policies =>
2432        // zero rows affected (PG restrictive-default).
2433        if crate::runtime::impl_core::rls_is_enabled(self, &query.table) {
2434            let rls_filter = crate::runtime::impl_core::rls_policy_filter(
2435                self,
2436                &query.table,
2437                crate::storage::query::ast::PolicyAction::Delete,
2438            );
2439            let Some(policy) = rls_filter else {
2440                return Ok(RuntimeQueryResult::dml_result(
2441                    raw_query.to_string(),
2442                    0,
2443                    "delete",
2444                    "runtime-dml-rls",
2445                ));
2446            };
2447            // Fold the policy predicate into the user's WHERE before
2448            // dispatching — the remainder of this function reads the
2449            // filter from `query` via `effective_delete_filter`, which
2450            // respects the updated value.
2451            let mut augmented = query.clone();
2452            augmented.filter = Some(match augmented.filter.take() {
2453                Some(existing) => {
2454                    crate::storage::query::ast::Filter::And(Box::new(existing), Box::new(policy))
2455                }
2456                None => policy,
2457            });
2458            return self.execute_delete_inner(raw_query, &augmented);
2459        }
2460        self.execute_delete_inner(raw_query, query)
2461    }
2462
2463    fn execute_delete_inner(
2464        &self,
2465        raw_query: &str,
2466        query: &DeleteQuery,
2467    ) -> RedDBResult<RuntimeQueryResult> {
2468        let effective_filter = effective_delete_filter(query);
2469
2470        // Find the rows that match the WHERE clause. The "find target
2471        // rows" loop lives in DmlTargetScan so UPDATE (#52) can reuse
2472        // the same scan strategy.
2473        let scan = super::dml_target_scan::DmlTargetScan::new(
2474            self,
2475            &query.table,
2476            effective_filter.as_ref(),
2477            None,
2478        );
2479        let ids_to_delete = scan.find_target_ids()?;
2480
2481        // For event-enabled collections, snapshot the pre-delete state
2482        // before rows are physically removed.
2483        let needs_delete_events =
2484            !query.suppress_events && self.collection_has_delete_subscriptions(&query.table);
2485        let mut pre_images: HashMap<u64, crate::json::Value> = if needs_delete_events {
2486            scan.row_json_pre_images(&ids_to_delete)
2487        } else {
2488            HashMap::new()
2489        };
2490
2491        let mut affected: u64 = 0;
2492        for chunk in ids_to_delete.chunks(UPDATE_APPLY_CHUNK_SIZE) {
2493            let (count, lsns) = self.delete_entities_batch(&query.table, chunk)?;
2494            affected += count;
2495            if needs_delete_events && !lsns.is_empty() {
2496                // lsns.len() == actually-deleted entities; align with chunk ids.
2497                // `delete_batch` may skip missing entities, so we correlate by
2498                // the number returned (they're emitted in chunk order).
2499                let deleted_chunk = &chunk[..lsns.len().min(chunk.len())];
2500                self.emit_delete_events_for_collection(
2501                    &query.table,
2502                    deleted_chunk,
2503                    &lsns,
2504                    &pre_images,
2505                )?;
2506            }
2507        }
2508        pre_images.clear();
2509
2510        if affected > 0 {
2511            self.note_table_write(&query.table);
2512        }
2513
2514        Ok(RuntimeQueryResult::dml_result(
2515            raw_query.to_string(),
2516            affected,
2517            "delete",
2518            "runtime-dml",
2519        ))
2520    }
2521}
2522
2523/// Reject UPDATE … NODES/EDGES that assign to graph identity/topology
2524/// columns regardless of whether any row matches the WHERE clause. The
2525/// per-entity guard below covers only the matched-rows case, but ADR 0019
2526/// declares these columns immutable on the surface itself, so a zero-row
2527/// UPDATE should still surface the same error to operators and SDKs.
2528fn ensure_graph_identity_update_target_allowed(query: &UpdateQuery) -> RedDBResult<()> {
2529    if !matches!(query.target, UpdateTarget::Nodes | UpdateTarget::Edges) {
2530        return Ok(());
2531    }
2532    for (column, _) in &query.assignment_exprs {
2533        if is_immutable_graph_identity_field(column) {
2534            return Err(RedDBError::Query(format!(
2535                "immutable graph field '{column}' cannot be updated"
2536            )));
2537        }
2538    }
2539    Ok(())
2540}
2541
2542fn ensure_kv_key_update_target_allowed(query: &UpdateQuery) -> RedDBResult<()> {
2543    if !matches!(query.target, UpdateTarget::Kv) {
2544        return Ok(());
2545    }
2546    for (column, _) in &query.assignment_exprs {
2547        if column.eq_ignore_ascii_case("key") {
2548            return Err(RedDBError::Query(
2549                "KV key cannot be updated; delete and insert a new key instead".to_string(),
2550            ));
2551        }
2552    }
2553    Ok(())
2554}
2555
2556fn ensure_graph_identity_update_allowed(
2557    entity: &UnifiedEntity,
2558    compiled_plan: &CompiledUpdatePlan,
2559    assignments: &MaterializedUpdateAssignments,
2560) -> RedDBResult<()> {
2561    if !matches!(entity.data, EntityData::Node(_) | EntityData::Edge(_)) {
2562        return Ok(());
2563    }
2564
2565    for (column, _) in compiled_plan
2566        .static_field_assignments
2567        .iter()
2568        .chain(assignments.dynamic_field_assignments.iter())
2569    {
2570        if is_immutable_graph_identity_field(column) {
2571            return Err(RedDBError::Query(format!(
2572                "immutable graph field '{column}' cannot be updated"
2573            )));
2574        }
2575    }
2576
2577    Ok(())
2578}
2579
2580fn is_immutable_graph_identity_field(column: &str) -> bool {
2581    ["rid", "label", "from_rid", "to_rid", "from", "to"]
2582        .iter()
2583        .any(|reserved| column.eq_ignore_ascii_case(reserved))
2584}
2585
2586fn build_patch_operations_from_materialized_assignments(
2587    entity: &UnifiedEntity,
2588    compiled_plan: &CompiledUpdatePlan,
2589    assignments: MaterializedUpdateAssignments,
2590) -> Vec<PatchEntityOperation> {
2591    let mut operations = Vec::with_capacity(
2592        compiled_plan.static_field_assignments.len()
2593            + compiled_plan.static_metadata_assignments.len()
2594            + assignments.dynamic_field_assignments.len()
2595            + assignments.dynamic_metadata_assignments.len(),
2596    );
2597
2598    for (column, value) in &compiled_plan.static_field_assignments {
2599        operations.push(PatchEntityOperation {
2600            op: PatchEntityOperationType::Set,
2601            path: update_patch_path_for_entity(entity, column),
2602            value: Some(storage_value_to_json(value)),
2603        });
2604    }
2605
2606    for (column, value) in assignments.dynamic_field_assignments {
2607        operations.push(PatchEntityOperation {
2608            op: PatchEntityOperationType::Set,
2609            path: update_patch_path_for_entity(entity, &column),
2610            value: Some(storage_value_to_json(&value)),
2611        });
2612    }
2613
2614    for (key, value) in &compiled_plan.static_metadata_assignments {
2615        operations.push(PatchEntityOperation {
2616            op: PatchEntityOperationType::Set,
2617            path: vec!["metadata".to_string(), key.clone()],
2618            value: Some(metadata_value_to_json(value)),
2619        });
2620    }
2621
2622    for (key, value) in assignments.dynamic_metadata_assignments {
2623        operations.push(PatchEntityOperation {
2624            op: PatchEntityOperationType::Set,
2625            path: vec!["metadata".to_string(), key],
2626            value: Some(metadata_value_to_json(&value)),
2627        });
2628    }
2629
2630    operations
2631}
2632
2633fn update_patch_path_for_entity(entity: &UnifiedEntity, column: &str) -> Vec<String> {
2634    if matches!(
2635        (&entity.kind, &entity.data),
2636        (
2637            crate::storage::EntityKind::GraphNode(_),
2638            EntityData::Node(_)
2639        )
2640    ) && column.eq_ignore_ascii_case("node_type")
2641    {
2642        return vec!["node_type".to_string()];
2643    }
2644    if matches!(
2645        (&entity.kind, &entity.data),
2646        (
2647            crate::storage::EntityKind::GraphEdge(_),
2648            EntityData::Edge(_)
2649        )
2650    ) && column.eq_ignore_ascii_case("weight")
2651    {
2652        return vec!["weight".to_string()];
2653    }
2654    vec!["fields".to_string(), column.to_string()]
2655}
2656
2657/// Rewrite `DELETE FROM <table> [WHERE …] [RETURNING …]` as
2658/// `SELECT * FROM <table> [WHERE …]` so the delete executor can
2659/// capture the pre-image before actually removing the rows. Returns
2660/// `None` when the input does not start with `DELETE`.
2661///
2662/// Case-insensitive on the keywords. Preserves everything between
2663/// the table name and the RETURNING clause, so WHERE / ORDER BY /
2664/// LIMIT survive untouched. The RETURNING tail — if present — is
2665/// truncated at the first top-level `RETURNING` token.
2666fn delete_to_select_sql(sql: &str) -> Option<String> {
2667    let trimmed = sql.trim_start();
2668    let lowered = trimmed.to_ascii_lowercase();
2669    if !lowered.starts_with("delete ") && !lowered.starts_with("delete\t") {
2670        return None;
2671    }
2672    // Find `FROM` after DELETE.
2673    let from_idx = lowered.find(" from ")?;
2674    let after_from = &trimmed[from_idx + " from ".len()..];
2675    let after_from_lc = &lowered[from_idx + " from ".len()..];
2676
2677    // Cut off the RETURNING tail (a naive search — the RETURNING
2678    // clause only appears once per statement at top level in our
2679    // grammar). Matches whitespace-bounded tokens to avoid clipping
2680    // `RETURNING` inside a string literal.
2681    let mut body = after_from.to_string();
2682    if let Some(pos) = find_top_level_keyword(after_from_lc, "returning") {
2683        body.truncate(pos);
2684    }
2685    Some(format!("SELECT * FROM {}", body.trim_end()))
2686}
2687
2688/// Find the byte offset of a whitespace-bounded keyword in a
2689/// lowercased haystack, skipping matches inside single-quoted
2690/// string literals. Naive — no escape handling — but enough for
2691/// the shapes the DML parser emits.
2692fn find_top_level_keyword(haystack: &str, needle: &str) -> Option<usize> {
2693    let bytes = haystack.as_bytes();
2694    let nlen = needle.len();
2695    let mut i = 0usize;
2696    let mut in_string = false;
2697    while i < bytes.len() {
2698        let c = bytes[i];
2699        if c == b'\'' {
2700            in_string = !in_string;
2701            i += 1;
2702            continue;
2703        }
2704        if !in_string
2705            && i + nlen <= bytes.len()
2706            && &bytes[i..i + nlen] == needle.as_bytes()
2707            && (i == 0 || bytes[i - 1].is_ascii_whitespace())
2708            && (i + nlen == bytes.len() || bytes[i + nlen].is_ascii_whitespace())
2709        {
2710            return Some(i);
2711        }
2712        i += 1;
2713    }
2714    None
2715}
2716
2717/// Build a `UnifiedResult` from the rows affected by a DML statement plus
2718/// its `RETURNING` clause. Each snapshot is a list of (column, value) pairs
2719/// for one affected row; `outputs`, when provided, supplies the engine-
2720/// assigned entity id for the same row (INSERT path). Projection honours
2721/// the RETURNING items: `*` expands to every snapshot column plus
2722/// the public row envelope when available.
2723fn build_returning_result(
2724    items: &[ReturningItem],
2725    snapshots: &[Vec<(String, Value)>],
2726    outputs: Option<&[CreateEntityOutput]>,
2727) -> UnifiedResult {
2728    let project_all = items.iter().any(|it| matches!(it, ReturningItem::All));
2729    let public_item_outputs = outputs.is_some_and(|outs| {
2730        outs.first()
2731            .and_then(|out| out.entity.as_ref())
2732            .is_some_and(|entity| public_returning_item_kind(entity).is_some())
2733    });
2734
2735    let mut columns: Vec<String> = if project_all {
2736        let mut cols: Vec<String> = Vec::new();
2737        if public_item_outputs {
2738            cols.extend(
2739                [
2740                    "rid",
2741                    "collection",
2742                    "kind",
2743                    "tenant",
2744                    "created_at",
2745                    "updated_at",
2746                ]
2747                .into_iter()
2748                .map(str::to_string),
2749            );
2750        } else if outputs.is_some() {
2751            cols.push("rid".to_string());
2752        }
2753        if let Some(first) = snapshots.first() {
2754            for (name, _) in first {
2755                cols.push(name.clone());
2756            }
2757        }
2758        cols
2759    } else {
2760        items
2761            .iter()
2762            .filter_map(|it| match it {
2763                ReturningItem::Column(c) => Some(c.clone()),
2764                ReturningItem::All => None,
2765            })
2766            .collect()
2767    };
2768    // Guarantee unique order-preserving column list.
2769    {
2770        let mut seen = std::collections::HashSet::new();
2771        columns.retain(|c| seen.insert(c.clone()));
2772    }
2773
2774    let mut records: Vec<UnifiedRecord> = Vec::with_capacity(snapshots.len());
2775    for (idx, snap) in snapshots.iter().enumerate() {
2776        let mut values: HashMap<Arc<str>, Value> = HashMap::with_capacity(columns.len());
2777        if let Some(outs) = outputs {
2778            if let Some(out) = outs.get(idx) {
2779                if let Some(entity) = out.entity.as_ref() {
2780                    if let Some(kind) = public_returning_item_kind(entity) {
2781                        values.insert(
2782                            Arc::clone(&sys_key_rid()),
2783                            Value::UnsignedInteger(out.id.raw()),
2784                        );
2785                        values.insert(
2786                            Arc::clone(&sys_key_collection()),
2787                            Value::text(entity.kind.collection().to_string()),
2788                        );
2789                        values.insert(Arc::clone(&sys_key_kind()), Value::text(kind.to_string()));
2790                        values.insert(
2791                            Arc::clone(&sys_key_created_at()),
2792                            Value::UnsignedInteger(entity.created_at),
2793                        );
2794                        values.insert(
2795                            Arc::clone(&sys_key_updated_at()),
2796                            Value::UnsignedInteger(entity.updated_at),
2797                        );
2798                    } else {
2799                        values.insert(
2800                            Arc::clone(&sys_key_rid()),
2801                            Value::Integer(out.id.raw() as i64),
2802                        );
2803                    }
2804                } else {
2805                    values.insert(
2806                        Arc::clone(&sys_key_rid()),
2807                        Value::Integer(out.id.raw() as i64),
2808                    );
2809                }
2810            }
2811        }
2812        for (name, val) in snap {
2813            values.insert(Arc::from(name.as_str()), val.clone());
2814        }
2815        if !values.contains_key("tenant") {
2816            let tenant = values.get("tenant_id").cloned().unwrap_or(Value::Null);
2817            values.insert(Arc::clone(&sys_key_tenant()), tenant);
2818        }
2819        let mut rec = UnifiedRecord::default();
2820        // Only keep projected columns on the record.
2821        for col in &columns {
2822            if let Some(v) = values.get(col.as_str()) {
2823                rec.set_arc(Arc::from(col.as_str()), v.clone());
2824            }
2825        }
2826        records.push(rec);
2827    }
2828
2829    UnifiedResult {
2830        columns,
2831        records,
2832        stats: Default::default(),
2833        pre_serialized_json: None,
2834    }
2835}
2836
2837fn public_returning_item_kind(entity: &crate::storage::UnifiedEntity) -> Option<&'static str> {
2838    match (&entity.kind, &entity.data) {
2839        (crate::storage::EntityKind::GraphNode(_), crate::storage::EntityData::Node(_)) => {
2840            Some("node")
2841        }
2842        (crate::storage::EntityKind::GraphEdge(_), crate::storage::EntityData::Edge(_)) => {
2843            Some("edge")
2844        }
2845        (_, crate::storage::EntityData::Row(_)) => Some(public_returning_row_kind(entity)),
2846        // #1369 — every entity model must expose its `rid` in RETURNING *.
2847        // Vectors carry their payload in `EntityData::Vector`, not `Row`, so
2848        // they were falling through to a no-rid envelope
2849        // and `RETURNING *` never surfaced the entity-id.
2850        (_, crate::storage::EntityData::Vector(_)) => Some("vector"),
2851        _ => None,
2852    }
2853}
2854
2855fn public_returning_row_kind(entity: &crate::storage::UnifiedEntity) -> &'static str {
2856    let Some(row) = entity.data.as_row() else {
2857        return "row";
2858    };
2859
2860    let is_kv = row.named.as_ref().is_some_and(|named| {
2861        (named.len() == 2 && named.contains_key("key") && named.contains_key("value"))
2862            || (named.len() == 1 && (named.contains_key("key") || named.contains_key("value")))
2863    });
2864    if is_kv {
2865        return "kv";
2866    }
2867
2868    let is_document = row
2869        .named
2870        .as_ref()
2871        .is_some_and(|named| named.values().any(runtime_returning_documentish_value))
2872        || row.columns.iter().any(runtime_returning_documentish_value);
2873    if is_document {
2874        "document"
2875    } else {
2876        "row"
2877    }
2878}
2879
2880fn runtime_returning_documentish_value(value: &Value) -> bool {
2881    matches!(value, Value::Json(_) | Value::Blob(_))
2882}
2883
2884fn row_insert_returning_snapshots(
2885    outputs: &[CreateEntityOutput],
2886    fallback: Vec<Vec<(String, Value)>>,
2887) -> Vec<Vec<(String, Value)>> {
2888    outputs
2889        .iter()
2890        .enumerate()
2891        .map(|(idx, out)| {
2892            out.entity
2893                .as_ref()
2894                .map(entity_row_fields_snapshot)
2895                .filter(|snap| !snap.is_empty())
2896                .unwrap_or_else(|| fallback.get(idx).cloned().unwrap_or_default())
2897        })
2898        .collect()
2899}
2900
2901fn graph_insert_returning_snapshots(
2902    store: &crate::storage::unified::UnifiedStore,
2903    collection: &str,
2904    ids: &[EntityId],
2905) -> Vec<Vec<(String, Value)>> {
2906    let Some(manager) = store.get_collection(collection) else {
2907        return Vec::new();
2908    };
2909
2910    ids.iter()
2911        .filter_map(|id| manager.get(*id))
2912        .filter_map(|entity| {
2913            let mut record = runtime_any_record_from_entity_ref(&entity)?;
2914            record.set_arc(sys_key_collection(), Value::text(collection.to_string()));
2915            Some(record)
2916        })
2917        .map(|record| {
2918            record
2919                .iter_fields()
2920                .map(|(key, value)| (key.as_ref().to_string(), value.clone()))
2921                .collect()
2922        })
2923        .collect()
2924}
2925
2926fn graph_update_returning_snapshots(
2927    runtime: &RedDBRuntime,
2928    collection: &str,
2929    ids: &[EntityId],
2930) -> Vec<Vec<(String, Value)>> {
2931    let store = runtime.db().store();
2932    let Some(manager) = store.get_collection(collection) else {
2933        return Vec::new();
2934    };
2935
2936    manager
2937        .get_many(ids)
2938        .into_iter()
2939        .flatten()
2940        .filter_map(|entity| runtime_any_record_from_entity_ref(&entity))
2941        .map(|record| {
2942            record
2943                .iter_fields()
2944                .map(|(key, value)| (key.as_ref().to_string(), value.clone()))
2945                .collect()
2946        })
2947        .collect()
2948}
2949
2950fn restore_kv_returning_keys(
2951    runtime: &RedDBRuntime,
2952    collection: &str,
2953    ids: &[EntityId],
2954    snapshots: &mut [Vec<(String, Value)>],
2955) {
2956    if ids.is_empty() || snapshots.is_empty() {
2957        return;
2958    }
2959
2960    let store = runtime.db().store();
2961    for (idx, id) in ids.iter().enumerate() {
2962        let Some(snapshot) = snapshots.get_mut(idx) else {
2963            continue;
2964        };
2965        if snapshot.iter().any(|(name, _)| name == "key") {
2966            continue;
2967        }
2968        let Some(entity) = store.get(collection, *id) else {
2969            continue;
2970        };
2971        let logical_id = entity.logical_id();
2972        let key = store
2973            .table_row_versions_by_logical_id(collection, logical_id)
2974            .into_iter()
2975            .find_map(kv_key_value_from_entity)
2976            .or_else(|| kv_key_value_from_entity(entity));
2977        if let Some(key) = key {
2978            snapshot.push(("key".to_string(), key));
2979        }
2980    }
2981}
2982
2983fn kv_key_value_from_entity(entity: UnifiedEntity) -> Option<Value> {
2984    let row = entity.data.as_row()?;
2985    row.get_field("key")
2986        .cloned()
2987        .or_else(|| row.columns.first().cloned())
2988}
2989
2990fn ensure_update_target_contract(
2991    runtime: &RedDBRuntime,
2992    collection: &str,
2993    target: UpdateTarget,
2994) -> RedDBResult<()> {
2995    let Some(contract) = runtime.db().collection_contract(collection) else {
2996        return Ok(());
2997    };
2998    if update_target_contract_is_advisory(&contract)
2999        || update_target_allows_model(contract.declared_model, update_target_model(target))
3000    {
3001        return Ok(());
3002    }
3003    Err(RedDBError::InvalidOperation(format!(
3004        "collection '{}' is declared as '{}' and does not allow '{}' updates",
3005        collection,
3006        update_model_name(contract.declared_model),
3007        update_model_name(update_target_model(target))
3008    )))
3009}
3010
3011fn update_target_contract_is_advisory(contract: &crate::physical::CollectionContract) -> bool {
3012    matches!(
3013        (&contract.origin, &contract.schema_mode),
3014        (
3015            crate::physical::ContractOrigin::Implicit,
3016            crate::catalog::SchemaMode::Dynamic,
3017        )
3018    )
3019}
3020
3021fn update_target_model(target: UpdateTarget) -> crate::catalog::CollectionModel {
3022    match target {
3023        UpdateTarget::Rows => crate::catalog::CollectionModel::Table,
3024        UpdateTarget::Documents => crate::catalog::CollectionModel::Document,
3025        UpdateTarget::Kv => crate::catalog::CollectionModel::Kv,
3026        UpdateTarget::Nodes | UpdateTarget::Edges => crate::catalog::CollectionModel::Graph,
3027    }
3028}
3029
3030fn update_target_allows_model(
3031    declared_model: crate::catalog::CollectionModel,
3032    requested_model: crate::catalog::CollectionModel,
3033) -> bool {
3034    declared_model == requested_model || declared_model == crate::catalog::CollectionModel::Mixed
3035}
3036
3037fn update_model_name(model: crate::catalog::CollectionModel) -> &'static str {
3038    match model {
3039        crate::catalog::CollectionModel::Table => "table",
3040        crate::catalog::CollectionModel::Document => "document",
3041        crate::catalog::CollectionModel::Graph => "graph",
3042        crate::catalog::CollectionModel::Vector => "vector",
3043        crate::catalog::CollectionModel::Hll => "hll",
3044        crate::catalog::CollectionModel::Sketch => "sketch",
3045        crate::catalog::CollectionModel::Filter => "filter",
3046        crate::catalog::CollectionModel::Kv => "kv",
3047        crate::catalog::CollectionModel::Config => "config",
3048        crate::catalog::CollectionModel::Vault => "vault",
3049        crate::catalog::CollectionModel::Mixed => "mixed",
3050        crate::catalog::CollectionModel::TimeSeries => "timeseries",
3051        crate::catalog::CollectionModel::Queue => "queue",
3052        crate::catalog::CollectionModel::Metrics => "metrics",
3053    }
3054}
3055
3056fn ensure_graph_insert_contract(runtime: &RedDBRuntime, collection: &str) -> RedDBResult<()> {
3057    let db = runtime.db();
3058    if let Some(contract) = db.collection_contract(collection) {
3059        let advisory_implicit_dynamic = matches!(
3060            (&contract.origin, &contract.schema_mode),
3061            (
3062                crate::physical::ContractOrigin::Implicit,
3063                crate::catalog::SchemaMode::Dynamic,
3064            )
3065        );
3066        if advisory_implicit_dynamic
3067            || matches!(
3068                contract.declared_model,
3069                crate::catalog::CollectionModel::Graph | crate::catalog::CollectionModel::Mixed
3070            )
3071        {
3072            return Ok(());
3073        }
3074        return Err(RedDBError::InvalidOperation(format!(
3075            "collection '{}' is declared as '{:?}' and does not allow 'Graph' writes",
3076            collection, contract.declared_model
3077        )));
3078    }
3079
3080    let now = std::time::SystemTime::now()
3081        .duration_since(std::time::UNIX_EPOCH)
3082        .unwrap_or_default()
3083        .as_millis();
3084    db.save_collection_contract(crate::physical::CollectionContract {
3085        name: collection.to_string(),
3086        declared_model: crate::catalog::CollectionModel::Graph,
3087        schema_mode: crate::catalog::SchemaMode::Dynamic,
3088        origin: crate::physical::ContractOrigin::Implicit,
3089        version: 1,
3090        created_at_unix_ms: now,
3091        updated_at_unix_ms: now,
3092        default_ttl_ms: db.collection_default_ttl_ms(collection),
3093        vector_dimension: None,
3094        vector_metric: None,
3095        context_index_fields: Vec::new(),
3096        declared_columns: Vec::new(),
3097        table_def: None,
3098        timestamps_enabled: false,
3099        context_index_enabled: false,
3100        metrics_raw_retention_ms: None,
3101        metrics_rollup_policies: Vec::new(),
3102        metrics_tenant_identity: None,
3103        metrics_namespace: None,
3104        append_only: false,
3105        subscriptions: Vec::new(),
3106        analytics_config: Vec::new(),
3107        session_key: None,
3108        session_gap_ms: None,
3109        retention_duration_ms: None,
3110        analytical_storage: None,
3111
3112        ai_policy: None,
3113    })
3114    .map(|_| ())
3115    .map_err(|err| RedDBError::Internal(err.to_string()))
3116}
3117
3118fn update_needs_rmw_lock(query: &UpdateQuery) -> bool {
3119    query
3120        .assignment_exprs
3121        .iter()
3122        .enumerate()
3123        .any(|(idx, (column, expr))| {
3124            query
3125                .compound_assignment_ops
3126                .get(idx)
3127                .is_some_and(|op| op.is_some())
3128                || expr_references_update_column(expr, &query.table, column)
3129        })
3130}
3131
3132fn record_claim_outcome(
3133    telemetry: &crate::runtime::claim_telemetry::ClaimTelemetryCounters,
3134    claim_limit: Option<u64>,
3135    table: &str,
3136    model: &str,
3137    affected: u64,
3138) {
3139    if claim_limit.is_none() {
3140        return;
3141    }
3142    if affected == 0 {
3143        telemetry.record_miss(table, model);
3144        tracing::debug!(
3145            target: "reddb::claim",
3146            collection = table,
3147            model,
3148            "concurrent claim missed"
3149        );
3150    } else {
3151        telemetry.record_successful(table, model, affected);
3152        tracing::debug!(
3153            target: "reddb::claim",
3154            collection = table,
3155            model,
3156            successful = affected,
3157            "concurrent claim succeeded"
3158        );
3159    }
3160}
3161
3162fn evaluate_compound_update_assignment(
3163    column: &str,
3164    record: &UnifiedRecord,
3165    op: BinOp,
3166    rhs: Value,
3167) -> RedDBResult<Value> {
3168    let lhs = record.get(column).ok_or_else(|| {
3169        RedDBError::Query(format!(
3170            "compound assignment requires existing numeric field '{column}'"
3171        ))
3172    })?;
3173    if matches!(lhs, Value::Null) {
3174        return Err(RedDBError::Query(format!(
3175            "compound assignment requires non-null numeric field '{column}'"
3176        )));
3177    }
3178    apply_compound_numeric_op(column, op, lhs, &rhs)
3179}
3180
3181fn apply_compound_numeric_op(
3182    column: &str,
3183    op: BinOp,
3184    lhs: &Value,
3185    rhs: &Value,
3186) -> RedDBResult<Value> {
3187    let Some(lhs_number) = CompoundNumber::from_value(lhs) else {
3188        return Err(RedDBError::Query(format!(
3189            "compound assignment requires numeric field '{column}'"
3190        )));
3191    };
3192    let Some(rhs_number) = CompoundNumber::from_value(rhs) else {
3193        return Err(RedDBError::Query(format!(
3194            "compound assignment requires numeric right-hand value for field '{column}'"
3195        )));
3196    };
3197
3198    if lhs_number.is_float() || rhs_number.is_float() || matches!(op, BinOp::Div) {
3199        let a = lhs_number.as_f64();
3200        let b = rhs_number.as_f64();
3201        let out = match op {
3202            BinOp::Add => a + b,
3203            BinOp::Sub => a - b,
3204            BinOp::Mul => a * b,
3205            BinOp::Div => {
3206                if b == 0.0 {
3207                    return Err(RedDBError::Query(format!(
3208                        "division by zero in compound assignment for field '{column}'"
3209                    )));
3210                }
3211                a / b
3212            }
3213            BinOp::Mod => {
3214                if b == 0.0 {
3215                    return Err(RedDBError::Query(format!(
3216                        "modulo by zero in compound assignment for field '{column}'"
3217                    )));
3218                }
3219                a % b
3220            }
3221            _ => {
3222                return Err(RedDBError::Query(format!(
3223                    "unsupported compound assignment operator for field '{column}'"
3224                )));
3225            }
3226        };
3227        if !out.is_finite() {
3228            return Err(RedDBError::Query(format!(
3229                "numeric overflow in compound assignment for field '{column}'"
3230            )));
3231        }
3232        return Ok(Value::Float(out));
3233    }
3234
3235    let a = lhs_number.as_i128();
3236    let b = rhs_number.as_i128();
3237    let out = match op {
3238        BinOp::Add => a.checked_add(b),
3239        BinOp::Sub => a.checked_sub(b),
3240        BinOp::Mul => a.checked_mul(b),
3241        BinOp::Mod => {
3242            if b == 0 {
3243                return Err(RedDBError::Query(format!(
3244                    "modulo by zero in compound assignment for field '{column}'"
3245                )));
3246            }
3247            a.checked_rem(b)
3248        }
3249        BinOp::Div => unreachable!("integer division is handled by the float branch"),
3250        _ => None,
3251    }
3252    .ok_or_else(|| {
3253        RedDBError::Query(format!(
3254            "numeric overflow in compound assignment for field '{column}'"
3255        ))
3256    })?;
3257
3258    if matches!(lhs, Value::UnsignedInteger(_)) {
3259        let value = u64::try_from(out).map_err(|_| {
3260            RedDBError::Query(format!(
3261                "numeric overflow in compound assignment for field '{column}'"
3262            ))
3263        })?;
3264        Ok(Value::UnsignedInteger(value))
3265    } else {
3266        let value = i64::try_from(out).map_err(|_| {
3267            RedDBError::Query(format!(
3268                "numeric overflow in compound assignment for field '{column}'"
3269            ))
3270        })?;
3271        Ok(Value::Integer(value))
3272    }
3273}
3274
3275#[derive(Clone, Copy)]
3276enum CompoundNumber {
3277    Integer(i128),
3278    Float(f64),
3279}
3280
3281impl CompoundNumber {
3282    fn from_value(value: &Value) -> Option<Self> {
3283        match value {
3284            Value::Integer(value) | Value::BigInt(value) => Some(Self::Integer(*value as i128)),
3285            Value::UnsignedInteger(value) => Some(Self::Integer(*value as i128)),
3286            Value::Float(value) => value.is_finite().then_some(Self::Float(*value)),
3287            Value::Decimal(value) => Some(Self::Float(*value as f64 / 10_000.0)),
3288            _ => None,
3289        }
3290    }
3291
3292    fn is_float(self) -> bool {
3293        matches!(self, Self::Float(_))
3294    }
3295
3296    fn as_f64(self) -> f64 {
3297        match self {
3298            Self::Integer(value) => value as f64,
3299            Self::Float(value) => value,
3300        }
3301    }
3302
3303    fn as_i128(self) -> i128 {
3304        match self {
3305            Self::Integer(value) => value,
3306            Self::Float(_) => unreachable!("float compound number used as integer"),
3307        }
3308    }
3309}
3310
3311fn expr_references_update_column(expr: &Expr, table_name: &str, target_column: &str) -> bool {
3312    match expr {
3313        Expr::Literal { .. } | Expr::Parameter { .. } | Expr::Subquery { .. } => false,
3314        Expr::Column { field, .. } => {
3315            field_ref_matches_update_column(field, table_name, target_column)
3316        }
3317        Expr::BinaryOp { lhs, rhs, .. } => {
3318            expr_references_update_column(lhs, table_name, target_column)
3319                || expr_references_update_column(rhs, table_name, target_column)
3320        }
3321        Expr::UnaryOp { operand, .. } | Expr::Cast { inner: operand, .. } => {
3322            expr_references_update_column(operand, table_name, target_column)
3323        }
3324        Expr::FunctionCall { args, .. } => args
3325            .iter()
3326            .any(|arg| expr_references_update_column(arg, table_name, target_column)),
3327        Expr::Case {
3328            branches, else_, ..
3329        } => {
3330            branches.iter().any(|(cond, value)| {
3331                expr_references_update_column(cond, table_name, target_column)
3332                    || expr_references_update_column(value, table_name, target_column)
3333            }) || else_
3334                .as_deref()
3335                .is_some_and(|expr| expr_references_update_column(expr, table_name, target_column))
3336        }
3337        Expr::IsNull { operand, .. } => {
3338            expr_references_update_column(operand, table_name, target_column)
3339        }
3340        Expr::InList { target, values, .. } => {
3341            expr_references_update_column(target, table_name, target_column)
3342                || values
3343                    .iter()
3344                    .any(|value| expr_references_update_column(value, table_name, target_column))
3345        }
3346        Expr::Between {
3347            target, low, high, ..
3348        } => {
3349            expr_references_update_column(target, table_name, target_column)
3350                || expr_references_update_column(low, table_name, target_column)
3351                || expr_references_update_column(high, table_name, target_column)
3352        }
3353        Expr::WindowFunctionCall { args, window, .. } => {
3354            args.iter()
3355                .any(|arg| expr_references_update_column(arg, table_name, target_column))
3356                || window
3357                    .partition_by
3358                    .iter()
3359                    .any(|e| expr_references_update_column(e, table_name, target_column))
3360                || window
3361                    .order_by
3362                    .iter()
3363                    .any(|o| expr_references_update_column(&o.expr, table_name, target_column))
3364        }
3365    }
3366}
3367
3368fn field_ref_matches_update_column(
3369    field: &FieldRef,
3370    table_name: &str,
3371    target_column: &str,
3372) -> bool {
3373    match field {
3374        FieldRef::TableColumn { table, column } => {
3375            column.eq_ignore_ascii_case(target_column)
3376                && (table.is_empty() || table.eq_ignore_ascii_case(table_name))
3377        }
3378        FieldRef::NodeProperty { .. } | FieldRef::EdgeProperty { .. } | FieldRef::NodeId { .. } => {
3379            false
3380        }
3381    }
3382}
3383
3384fn resolve_update_entity_by_logical_id(
3385    runtime: &RedDBRuntime,
3386    table: &str,
3387    logical_id: EntityId,
3388) -> Option<UnifiedEntity> {
3389    let store = runtime.inner.db.store();
3390    if let Some(entity) = store.get_table_row_by_logical_id(table, logical_id) {
3391        return Some(entity);
3392    }
3393    // Fallback for non-table-row entities (graph nodes/edges, etc.) where
3394    // entity_id == logical_id and the MVCC table-row resolver doesn't apply.
3395    store.get(table, logical_id)
3396}
3397
3398fn update_cdc_item_kind(
3399    runtime: &RedDBRuntime,
3400    collection: &str,
3401    entity: &UnifiedEntity,
3402) -> &'static str {
3403    match &entity.data {
3404        EntityData::Node(_) => return "node",
3405        EntityData::Edge(_) => return "edge",
3406        _ => {}
3407    }
3408
3409    match runtime
3410        .db()
3411        .collection_contract(collection)
3412        .map(|contract| contract.declared_model)
3413    {
3414        Some(crate::catalog::CollectionModel::Document) => "document",
3415        Some(crate::catalog::CollectionModel::Kv)
3416        | Some(crate::catalog::CollectionModel::Vault) => "kv",
3417        _ => "row",
3418    }
3419}
3420
3421fn ordered_update_target_ids(
3422    manager: &Arc<crate::storage::SegmentManager>,
3423    entity_ids: &[EntityId],
3424    order_by: &[OrderByClause],
3425    limit: Option<usize>,
3426) -> Vec<EntityId> {
3427    let mut entities: Vec<UnifiedEntity> =
3428        manager.get_many(entity_ids).into_iter().flatten().collect();
3429    entities.sort_by(|left, right| compare_update_order(left, right, order_by));
3430    if let Some(limit) = limit {
3431        entities.truncate(limit);
3432    }
3433    entities.into_iter().map(|entity| entity.id).collect()
3434}
3435
3436fn compare_update_order(
3437    left: &UnifiedEntity,
3438    right: &UnifiedEntity,
3439    order_by: &[OrderByClause],
3440) -> Ordering {
3441    for clause in order_by {
3442        let left_value = update_order_value(left, &clause.field);
3443        let right_value = update_order_value(right, &clause.field);
3444        let ordering = compare_update_order_values(
3445            left_value.as_ref(),
3446            right_value.as_ref(),
3447            clause.nulls_first,
3448        );
3449        if ordering != Ordering::Equal {
3450            return if clause.ascending {
3451                ordering
3452            } else {
3453                ordering.reverse()
3454            };
3455        }
3456    }
3457    left.logical_id().raw().cmp(&right.logical_id().raw())
3458}
3459
3460fn compare_update_order_values(
3461    left: Option<&Value>,
3462    right: Option<&Value>,
3463    nulls_first: bool,
3464) -> Ordering {
3465    match (left, right) {
3466        (None, None) => Ordering::Equal,
3467        (None, Some(_)) => {
3468            if nulls_first {
3469                Ordering::Less
3470            } else {
3471                Ordering::Greater
3472            }
3473        }
3474        (Some(_), None) => {
3475            if nulls_first {
3476                Ordering::Greater
3477            } else {
3478                Ordering::Less
3479            }
3480        }
3481        (Some(left), Some(right)) => {
3482            crate::storage::query::value_compare::total_compare_values(left, right)
3483        }
3484    }
3485}
3486
3487fn update_order_value(entity: &UnifiedEntity, field: &FieldRef) -> Option<Value> {
3488    let FieldRef::TableColumn { table, column } = field else {
3489        return None;
3490    };
3491    if !table.is_empty() {
3492        return None;
3493    }
3494    if column.eq_ignore_ascii_case("rid") {
3495        return Some(Value::UnsignedInteger(entity.logical_id().raw()));
3496    }
3497    match &entity.data {
3498        // After the single-source binary-body cutover (ADR 0063) a DOCUMENT's
3499        // top-level fields live only inside the binary `body` container, not as
3500        // promoted row fields, so a direct `get_field` misses them and the
3501        // claim/UPDATE `ORDER BY <body-field>` would silently fall back to
3502        // insertion order. Mirror the filter read-seam: when the field isn't a
3503        // direct row field, offset-read it from the binary body.
3504        EntityData::Row(row) => {
3505            row.get_field(column)
3506                .cloned()
3507                .or_else(|| match row.get_field("body") {
3508                    Some(Value::Json(bytes)) => {
3509                        crate::document_body::read_body_field(bytes, column)
3510                    }
3511                    _ => None,
3512                })
3513        }
3514        EntityData::Node(_) | EntityData::Edge(_) => runtime_any_record_from_entity_ref(entity)
3515            .and_then(|record| record.get(column).cloned()),
3516        _ => None,
3517    }
3518}
3519
3520fn dedupe_update_columns(mut columns: Vec<String>) -> Vec<String> {
3521    if columns.is_empty() {
3522        return columns;
3523    }
3524
3525    let mut unique = Vec::with_capacity(columns.len());
3526    for column in columns.drain(..) {
3527        if !unique
3528            .iter()
3529            .any(|existing: &String| existing.eq_ignore_ascii_case(&column))
3530        {
3531            unique.push(column);
3532        }
3533    }
3534    unique
3535}
3536
3537// =============================================================================
3538// Helper functions for extracting typed values from column/value pairs
3539// =============================================================================
3540
3541const SQL_TTL_METADATA_COLUMNS: [&str; 3] = ["_ttl", "_ttl_ms", "_expires_at"];
3542
3543fn resolve_sql_ttl_metadata_key(column: &str) -> Option<&'static str> {
3544    if column.eq_ignore_ascii_case("_ttl") {
3545        Some(SQL_TTL_METADATA_COLUMNS[0])
3546    } else if column.eq_ignore_ascii_case("_ttl_ms") {
3547        Some(SQL_TTL_METADATA_COLUMNS[1])
3548    } else if column.eq_ignore_ascii_case("_expires_at") {
3549        Some(SQL_TTL_METADATA_COLUMNS[2])
3550    } else {
3551        None
3552    }
3553}
3554
3555/// Canonicalize a SQL TTL metadata `(key, value)` pair so the retention
3556/// sweeper sees a single key (`_ttl_ms`) regardless of which legacy form
3557/// the operator wrote. `_ttl` is scaled from seconds to milliseconds;
3558/// `_ttl_ms` and `_expires_at` are passed through.
3559fn canonicalize_sql_ttl_metadata(
3560    key: &'static str,
3561    value: MetadataValue,
3562) -> (&'static str, MetadataValue) {
3563    if key != "_ttl" {
3564        return (key, value);
3565    }
3566    let scaled = match value {
3567        MetadataValue::Int(s) => MetadataValue::Int(s.saturating_mul(1_000)),
3568        MetadataValue::Timestamp(ms_or_s) => {
3569            // Timestamp is already chosen for very large values; treat as
3570            // already-ms to avoid silent overflow.
3571            MetadataValue::Timestamp(ms_or_s)
3572        }
3573        MetadataValue::Float(f) => MetadataValue::Float(f * 1_000.0),
3574        other => other,
3575    };
3576    ("_ttl_ms", scaled)
3577}
3578
3579/// Sentinel prefix produced by the parser for `PASSWORD('...')` and
3580/// `SECRET('...')` literals. The runtime strips this marker and
3581/// applies the actual crypto transform during INSERT execution.
3582pub(crate) const PLAINTEXT_SENTINEL: &str = "@@plain@@";
3583
3584impl RedDBRuntime {
3585    /// Strip the plaintext sentinel from a `Value::Password` or
3586    /// `Value::Secret` produced by the parser and apply the real
3587    /// crypto transform. `Password` is always hashed with argon2id.
3588    /// `Secret` is encrypted with AES-256-GCM keyed by the vault
3589    /// when `red.config.secret.auto_encrypt = true` (default).
3590    pub(crate) fn resolve_crypto_sentinel(&self, value: Value) -> RedDBResult<Value> {
3591        match value {
3592            Value::Password(marked) => {
3593                if let Some(plain) = marked.strip_prefix(PLAINTEXT_SENTINEL) {
3594                    Ok(Value::Password(crate::auth::store::hash_password(plain)))
3595                } else {
3596                    Ok(Value::Password(marked))
3597                }
3598            }
3599            Value::Secret(bytes) => {
3600                if bytes.starts_with(PLAINTEXT_SENTINEL.as_bytes()) {
3601                    if !self.secret_auto_encrypt() {
3602                        return Err(RedDBError::Query(
3603                            "SECRET() literal rejected: red.config.secret.auto_encrypt \
3604                             is false. Insert pre-encrypted bytes directly instead."
3605                                .to_string(),
3606                        ));
3607                    }
3608                    let key = self.secret_aes_key().ok_or_else(|| {
3609                        RedDBError::Query(
3610                            "SECRET() column encryption requires a bootstrapped \
3611                             vault (red.secret.aes_key is missing). Start the server \
3612                             with --vault to enable."
3613                                .to_string(),
3614                        )
3615                    })?;
3616                    let plain = &bytes[PLAINTEXT_SENTINEL.len()..];
3617                    Ok(Value::Secret(encrypt_secret_payload(&key, plain)))
3618                } else {
3619                    Ok(Value::Secret(bytes))
3620                }
3621            }
3622            other => Ok(other),
3623        }
3624    }
3625}
3626
3627/// Encode an AES-256-GCM ciphertext as `[12-byte nonce][ciphertext||tag]`.
3628/// This is the on-disk representation of `Value::Secret`.
3629fn encrypt_secret_payload(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
3630    let nonce_bytes = crate::auth::store::random_bytes(12);
3631    let mut nonce = [0u8; 12];
3632    nonce.copy_from_slice(&nonce_bytes[..12]);
3633    let ct = crate::crypto::aes_gcm::aes256_gcm_encrypt(key, &nonce, b"reddb.secret", plaintext);
3634    let mut out = Vec::with_capacity(12 + ct.len());
3635    out.extend_from_slice(&nonce);
3636    out.extend_from_slice(&ct);
3637    out
3638}
3639
3640/// Decode a `Value::Secret` payload back to plaintext. Returns
3641/// `None` when the payload is too short or AES-GCM authentication
3642/// fails (tampered or wrong key).
3643pub(crate) fn decrypt_secret_payload(key: &[u8; 32], payload: &[u8]) -> Option<Vec<u8>> {
3644    if payload.len() < 12 {
3645        return None;
3646    }
3647    let mut nonce = [0u8; 12];
3648    nonce.copy_from_slice(&payload[..12]);
3649    crate::crypto::aes_gcm::aes256_gcm_decrypt(key, &nonce, b"reddb.secret", &payload[12..]).ok()
3650}
3651
3652fn split_insert_metadata(
3653    runtime: &RedDBRuntime,
3654    columns: &[String],
3655    values: &[Value],
3656) -> RedDBResult<(Vec<(String, Value)>, Vec<(String, MetadataValue)>)> {
3657    let mut fields = Vec::new();
3658    let mut metadata = Vec::new();
3659
3660    for (column, value) in columns.iter().zip(values.iter()) {
3661        // Still support legacy _ttl columns for backward compat
3662        if let Some(metadata_key) = resolve_sql_ttl_metadata_key(column) {
3663            let raw_value = sql_literal_to_metadata_value(metadata_key, value)?;
3664            let (canonical_key, canonical_value) =
3665                canonicalize_sql_ttl_metadata(metadata_key, raw_value);
3666            metadata.push((canonical_key.to_string(), canonical_value));
3667            continue;
3668        }
3669        fields.push((
3670            column.clone(),
3671            runtime.resolve_crypto_sentinel(value.clone())?,
3672        ));
3673    }
3674
3675    Ok((fields, metadata))
3676}
3677
3678/// Merge structured WITH TTL, WITH EXPIRES AT, and WITH METADATA clauses into metadata entries.
3679fn merge_with_clauses(
3680    metadata: &mut Vec<(String, MetadataValue)>,
3681    ttl_ms: Option<u64>,
3682    expires_at_ms: Option<u64>,
3683    with_metadata: &[(String, Value)],
3684) {
3685    if let Some(ms) = ttl_ms {
3686        metadata.push((
3687            "_ttl_ms".to_string(),
3688            if ms <= i64::MAX as u64 {
3689                MetadataValue::Int(ms as i64)
3690            } else {
3691                MetadataValue::Timestamp(ms)
3692            },
3693        ));
3694    }
3695    if let Some(ms) = expires_at_ms {
3696        metadata.push(("_expires_at".to_string(), MetadataValue::Timestamp(ms)));
3697    }
3698    for (key, value) in with_metadata {
3699        let meta_value = match value {
3700            Value::Text(s) => MetadataValue::String(s.to_string()),
3701            Value::Integer(n) => MetadataValue::Int(*n),
3702            Value::Float(n) => MetadataValue::Float(*n),
3703            Value::Boolean(b) => MetadataValue::Bool(*b),
3704            _ => MetadataValue::String(value.to_string()),
3705        };
3706        metadata.push((key.clone(), meta_value));
3707    }
3708}
3709
3710fn merge_vector_metadata_column(
3711    metadata: &mut Vec<(String, MetadataValue)>,
3712    columns: &[String],
3713    values: &[Value],
3714) -> RedDBResult<()> {
3715    let Some(value) = columns
3716        .iter()
3717        .position(|column| column.eq_ignore_ascii_case("metadata"))
3718        .map(|index| &values[index])
3719    else {
3720        return Ok(());
3721    };
3722    let json = match value {
3723        Value::Null => return Ok(()),
3724        Value::Json(bytes) => crate::json::from_slice(bytes).map_err(|err| {
3725            RedDBError::Query(format!("column 'metadata' invalid JSON object: {err}"))
3726        })?,
3727        Value::Text(text) => crate::json::from_str(text).map_err(|err| {
3728            RedDBError::Query(format!("column 'metadata' invalid JSON object: {err}"))
3729        })?,
3730        other => {
3731            return Err(RedDBError::Query(format!(
3732                "column 'metadata' expected JSON object, got {other:?}"
3733            )))
3734        }
3735    };
3736    let parsed = metadata_from_json(&json)?;
3737    for (key, value) in parsed.iter() {
3738        metadata.push((key.clone(), value.clone()));
3739    }
3740    Ok(())
3741}
3742
3743fn apply_collection_default_ttl_metadata(
3744    runtime: &RedDBRuntime,
3745    collection: &str,
3746    metadata: &mut Vec<(String, MetadataValue)>,
3747) {
3748    if has_internal_ttl_metadata(metadata) {
3749        return;
3750    }
3751
3752    let Some(default_ttl_ms) = runtime.db().collection_default_ttl_ms(collection) else {
3753        return;
3754    };
3755
3756    metadata.push((
3757        "_ttl_ms".to_string(),
3758        if default_ttl_ms <= i64::MAX as u64 {
3759            MetadataValue::Int(default_ttl_ms as i64)
3760        } else {
3761            MetadataValue::Timestamp(default_ttl_ms)
3762        },
3763    ));
3764}
3765
3766fn ensure_non_tree_reserved_metadata_entries(
3767    metadata: &[(String, MetadataValue)],
3768) -> RedDBResult<()> {
3769    for (key, _) in metadata {
3770        ensure_non_tree_reserved_metadata_key(key)?;
3771    }
3772    Ok(())
3773}
3774
3775fn ensure_non_tree_reserved_metadata_key(key: &str) -> RedDBResult<()> {
3776    if key.starts_with(TREE_METADATA_PREFIX) {
3777        return Err(RedDBError::Query(format!(
3778            "metadata key '{}' is reserved for managed trees",
3779            key
3780        )));
3781    }
3782    Ok(())
3783}
3784
3785fn ensure_non_tree_structural_edge_label(label: &str) -> RedDBResult<()> {
3786    if label.eq_ignore_ascii_case(TREE_CHILD_EDGE_LABEL) {
3787        return Err(RedDBError::Query(format!(
3788            "edge label '{}' is reserved for managed trees",
3789            TREE_CHILD_EDGE_LABEL
3790        )));
3791    }
3792    Ok(())
3793}
3794
3795fn pairwise_columns_values(pairs: &[(String, Value)]) -> (Vec<String>, Vec<Value>) {
3796    let mut columns = Vec::with_capacity(pairs.len());
3797    let mut values = Vec::with_capacity(pairs.len());
3798
3799    for (column, value) in pairs {
3800        columns.push(column.clone());
3801        values.push(value.clone());
3802    }
3803
3804    (columns, values)
3805}
3806
3807/// Find a required column value and return it as-is.
3808fn find_column_value(columns: &[String], values: &[Value], name: &str) -> RedDBResult<Value> {
3809    for (i, col) in columns.iter().enumerate() {
3810        if col.eq_ignore_ascii_case(name) {
3811            return Ok(values[i].clone());
3812        }
3813    }
3814    Err(RedDBError::Query(format!(
3815        "required column '{name}' not found in INSERT"
3816    )))
3817}
3818
3819/// Find a required column value and coerce to String.
3820fn find_column_value_string(
3821    columns: &[String],
3822    values: &[Value],
3823    name: &str,
3824) -> RedDBResult<String> {
3825    let val = find_column_value(columns, values, name)?;
3826    match val {
3827        Value::Text(s) => Ok(s.to_string()),
3828        Value::Integer(n) => Ok(n.to_string()),
3829        Value::Float(n) => Ok(n.to_string()),
3830        other => Err(RedDBError::Query(format!(
3831            "column '{name}' expected text, got {other:?}"
3832        ))),
3833    }
3834}
3835
3836fn find_document_body_json(
3837    columns: &[String],
3838    values: &[Value],
3839) -> RedDBResult<crate::json::Value> {
3840    let val = find_column_value(columns, values, "body")?;
3841    match val {
3842        Value::Json(bytes) | Value::Blob(bytes) => {
3843            if let Some(body) = crate::document_body::decode_container_to_json(&bytes) {
3844                Ok(body)
3845            } else {
3846                crate::json::from_slice(&bytes)
3847                    .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}")))
3848            }
3849        }
3850        Value::Text(text) => crate::json::from_str(text.as_ref())
3851            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3852        Value::Integer(value) => crate::json::from_str(&value.to_string())
3853            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3854        Value::UnsignedInteger(value) => crate::json::from_str(&value.to_string())
3855            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3856        Value::Float(value) => crate::json::from_str(&value.to_string())
3857            .map_err(|err| RedDBError::Query(format!("invalid JSON body: {err}"))),
3858        other => Err(RedDBError::Query(format!(
3859            "column 'body' expected JSON body, got {other:?}"
3860        ))),
3861    }
3862}
3863
3864fn find_column_value_f64(columns: &[String], values: &[Value], name: &str) -> RedDBResult<f64> {
3865    let val = find_column_value(columns, values, name)?;
3866    match val {
3867        Value::Float(n) => Ok(n),
3868        Value::Integer(n) => Ok(n as f64),
3869        Value::UnsignedInteger(n) => Ok(n as f64),
3870        Value::Text(s) => s
3871            .parse::<f64>()
3872            .map_err(|_| RedDBError::Query(format!("column '{name}' expected number, got '{s}'"))),
3873        other => Err(RedDBError::Query(format!(
3874            "column '{name}' expected number, got {other:?}"
3875        ))),
3876    }
3877}
3878
3879/// Find an optional column value as String.
3880fn find_column_value_opt_string(
3881    columns: &[String],
3882    values: &[Value],
3883    name: &str,
3884) -> Option<String> {
3885    for (i, col) in columns.iter().enumerate() {
3886        if col.eq_ignore_ascii_case(name) {
3887            return match &values[i] {
3888                Value::Null => None,
3889                Value::Text(s) => Some(s.to_string()),
3890                Value::Integer(n) => Some(n.to_string()),
3891                Value::Float(n) => Some(n.to_string()),
3892                _ => None,
3893            };
3894        }
3895    }
3896    None
3897}
3898
3899/// Resolve an EDGE endpoint (`from`/`to`) to a numeric entity id.
3900///
3901/// Accepts integer literals, decimal strings, and node labels resolved via
3902/// the per-collection graph label index (same source of truth that
3903/// `GRAPH NEIGHBORHOOD` / `GRAPH TRAVERSE` use at query time). Ambiguous
3904/// labels error so callers can fall back to the numeric id form.
3905fn resolve_edge_endpoint(
3906    store: &crate::storage::unified::UnifiedStore,
3907    collection: &str,
3908    columns: &[String],
3909    values: &[Value],
3910    name: &str,
3911) -> RedDBResult<u64> {
3912    let val = find_column_value(columns, values, name)?;
3913    match val {
3914        Value::Integer(n) => Ok(n as u64),
3915        Value::UnsignedInteger(n) => Ok(n),
3916        Value::Text(s) => {
3917            if let Ok(n) = s.parse::<u64>() {
3918                return Ok(n);
3919            }
3920            let matches = store.lookup_graph_nodes_by_label_in(collection, &s);
3921            match matches.len() {
3922                0 => Err(RedDBError::Query(format!(
3923                    "column '{name}': no graph node with label '{s}' in collection '{collection}'"
3924                ))),
3925                1 => Ok(matches[0].raw()),
3926                n => Err(RedDBError::Query(format!(
3927                    "column '{name}': ambiguous label '{s}' matches {n} nodes in collection '{collection}'; use the numeric id"
3928                ))),
3929            }
3930        }
3931        other => Err(RedDBError::Query(format!(
3932            "column '{name}' expected integer or node label, got {other:?}"
3933        ))),
3934    }
3935}
3936
3937fn resolve_edge_endpoint_any(
3938    store: &crate::storage::unified::UnifiedStore,
3939    collection: &str,
3940    columns: &[String],
3941    values: &[Value],
3942    names: &[&str],
3943) -> RedDBResult<u64> {
3944    for name in names {
3945        if columns
3946            .iter()
3947            .any(|column| column.eq_ignore_ascii_case(name))
3948        {
3949            return resolve_edge_endpoint(store, collection, columns, values, name);
3950        }
3951    }
3952
3953    Err(RedDBError::Query(format!(
3954        "required column '{}' not found in INSERT",
3955        names.first().copied().unwrap_or("from_rid")
3956    )))
3957}
3958
3959/// Find a required column value and coerce to u64.
3960fn find_column_value_u64(columns: &[String], values: &[Value], name: &str) -> RedDBResult<u64> {
3961    let val = find_column_value(columns, values, name)?;
3962    match val {
3963        Value::Integer(n) => Ok(n as u64),
3964        Value::UnsignedInteger(n) => Ok(n),
3965        Value::Text(s) => s
3966            .parse::<u64>()
3967            .map_err(|_| RedDBError::Query(format!("column '{name}' expected integer, got '{s}'"))),
3968        other => Err(RedDBError::Query(format!(
3969            "column '{name}' expected integer, got {other:?}"
3970        ))),
3971    }
3972}
3973
3974/// Find an optional column value as f32.
3975fn find_column_value_f32_opt(columns: &[String], values: &[Value], name: &str) -> Option<f32> {
3976    for (i, col) in columns.iter().enumerate() {
3977        if col.eq_ignore_ascii_case(name) {
3978            return match &values[i] {
3979                Value::Float(n) => Some(*n as f32),
3980                Value::Integer(n) => Some(*n as f32),
3981                Value::Null => None,
3982                _ => None,
3983            };
3984        }
3985    }
3986    None
3987}
3988
3989/// Find a required column value and coerce to Vec<f32> (from Value::Vector).
3990fn find_column_value_vec_f32(
3991    columns: &[String],
3992    values: &[Value],
3993    name: &str,
3994) -> RedDBResult<Vec<f32>> {
3995    let val = find_column_value(columns, values, name)?;
3996    match val {
3997        Value::Vector(v) => Ok(v),
3998        Value::Json(bytes) => {
3999            // Try to parse as JSON array of numbers
4000            let s = std::str::from_utf8(&bytes).map_err(|_| {
4001                RedDBError::Query(format!("column '{name}' contains invalid UTF-8"))
4002            })?;
4003            let arr: Vec<f32> = crate::json::from_str(s).map_err(|e| {
4004                RedDBError::Query(format!("column '{name}' invalid vector JSON: {e}"))
4005            })?;
4006            Ok(arr)
4007        }
4008        other => Err(RedDBError::Query(format!(
4009            "column '{name}' expected vector, got {other:?}"
4010        ))),
4011    }
4012}
4013
4014fn find_column_value_vec_f32_any(
4015    columns: &[String],
4016    values: &[Value],
4017    names: &[&str],
4018) -> RedDBResult<Vec<f32>> {
4019    for name in names {
4020        if columns
4021            .iter()
4022            .any(|column| column.eq_ignore_ascii_case(name))
4023        {
4024            return find_column_value_vec_f32(columns, values, name);
4025        }
4026    }
4027    Err(RedDBError::Query(format!(
4028        "required vector column '{}' not found in INSERT",
4029        names.join("' or '")
4030    )))
4031}
4032
4033/// Extract remaining properties (all columns not in the exclusion list).
4034fn extract_remaining_properties(
4035    columns: &[String],
4036    values: &[Value],
4037    exclude: &[&str],
4038) -> Vec<(String, Value)> {
4039    columns
4040        .iter()
4041        .zip(values.iter())
4042        .filter(|(col, _)| !exclude.iter().any(|e| col.eq_ignore_ascii_case(e)))
4043        .map(|(col, val)| (col.clone(), val.clone()))
4044        .collect()
4045}
4046
4047fn validate_timeseries_insert_columns(columns: &[String]) -> RedDBResult<()> {
4048    let mut invalid = Vec::new();
4049    for column in columns {
4050        if !is_timeseries_insert_column(column) && resolve_sql_ttl_metadata_key(column).is_none() {
4051            invalid.push(column.clone());
4052        }
4053    }
4054
4055    if invalid.is_empty() {
4056        Ok(())
4057    } else {
4058        Err(RedDBError::Query(format!(
4059            "timeseries INSERT only accepts metric, value, tags, timestamp, timestamp_ns, or time columns; got {}",
4060            invalid.join(", ")
4061        )))
4062    }
4063}
4064
4065fn is_timeseries_insert_column(column: &str) -> bool {
4066    matches!(
4067        column.to_ascii_lowercase().as_str(),
4068        "metric"
4069            | "value"
4070            | "tags"
4071            | "timestamp"
4072            | "timestamp_ns"
4073            | "time"
4074            // Analytics-event extension (#577): an analytics row carries
4075            // an `event_name` + JSON `payload`. The payload is validated
4076            // against the AnalyticsSchemaRegistry inside
4077            // `insert_timeseries_point` before the row lands.
4078            | "event_name"
4079            | "payload"
4080    )
4081}
4082
4083fn find_timeseries_timestamp_ns(columns: &[String], values: &[Value]) -> RedDBResult<Option<u64>> {
4084    let mut found = None;
4085
4086    for alias in ["timestamp_ns", "timestamp", "time"] {
4087        for (index, column) in columns.iter().enumerate() {
4088            if !column.eq_ignore_ascii_case(alias) {
4089                continue;
4090            }
4091
4092            if found.is_some() {
4093                return Err(RedDBError::Query(
4094                    "timeseries INSERT accepts only one timestamp column".to_string(),
4095                ));
4096            }
4097
4098            found = Some(coerce_value_to_non_negative_u64(&values[index], alias)?);
4099        }
4100    }
4101
4102    Ok(found)
4103}
4104
4105fn find_timeseries_tags(
4106    columns: &[String],
4107    values: &[Value],
4108) -> RedDBResult<std::collections::HashMap<String, String>> {
4109    for (index, column) in columns.iter().enumerate() {
4110        if column.eq_ignore_ascii_case("tags") {
4111            return parse_timeseries_tags(&values[index]);
4112        }
4113    }
4114    Ok(std::collections::HashMap::new())
4115}
4116
4117fn parse_timeseries_tags(value: &Value) -> RedDBResult<std::collections::HashMap<String, String>> {
4118    match value {
4119        Value::Null => Ok(std::collections::HashMap::new()),
4120        Value::Json(bytes) => parse_timeseries_tags_json(bytes),
4121        Value::Text(text) => parse_timeseries_tags_json(text.as_bytes()),
4122        other => Err(RedDBError::Query(format!(
4123            "timeseries tags must be a JSON object or JSON text, got {other:?}"
4124        ))),
4125    }
4126}
4127
4128fn parse_timeseries_tags_json(
4129    bytes: &[u8],
4130) -> RedDBResult<std::collections::HashMap<String, String>> {
4131    let json: crate::json::Value = crate::json::from_slice(bytes)
4132        .map_err(|err| RedDBError::Query(format!("timeseries tags must be valid JSON: {err}")))?;
4133
4134    let object = match json {
4135        crate::json::Value::Object(object) => object,
4136        other => {
4137            return Err(RedDBError::Query(format!(
4138                "timeseries tags must be a JSON object, got {other:?}"
4139            )))
4140        }
4141    };
4142
4143    let mut tags = std::collections::HashMap::with_capacity(object.len());
4144    for (key, value) in object {
4145        tags.insert(key, json_tag_value_to_string(&value));
4146    }
4147    Ok(tags)
4148}
4149
4150/// Encode a tag value for storage so the original JSON type can be
4151/// recovered on read (issue #543).
4152///
4153/// Time-series tags are stored as `HashMap<String, String>` on the
4154/// physical record (see [`crate::storage::TimeSeriesData`]) so that
4155/// the segment codec, WAL and gRPC mirrors don't need a new value
4156/// variant. To preserve the original JSON type across that
4157/// string-only channel we prepend the
4158/// [`crate::runtime::query_exec::TIMESERIES_TAG_JSON_PREFIX`] marker
4159/// and serialize the value as compact JSON text. The read paths
4160/// (`timeseries_tags_json_value` / `timeseries_tags_value`) detect
4161/// the marker, parse the suffix, and recover a real JSON value.
4162/// Tags written through other channels (Prometheus remote write,
4163/// metrics handlers, legacy on-disk data) lack the marker and are
4164/// returned as `JsonValue::String(raw)` exactly as before.
4165fn json_tag_value_to_string(value: &crate::json::Value) -> String {
4166    let mut buf = String::with_capacity(value.to_string_compact().len() + 1);
4167    buf.push(crate::runtime::query_exec::TIMESERIES_TAG_JSON_PREFIX);
4168    buf.push_str(&value.to_string_compact());
4169    buf
4170}
4171
4172fn coerce_value_to_non_negative_u64(value: &Value, column: &str) -> RedDBResult<u64> {
4173    match value {
4174        Value::UnsignedInteger(value) => Ok(*value),
4175        Value::Integer(value) if *value >= 0 => Ok(*value as u64),
4176        Value::Float(value) if *value >= 0.0 => Ok(*value as u64),
4177        Value::Text(value) => value.parse::<u64>().map_err(|_| {
4178            RedDBError::Query(format!(
4179                "column '{column}' expected a non-negative integer timestamp, got '{value}'"
4180            ))
4181        }),
4182        other => Err(RedDBError::Query(format!(
4183            "column '{column}' expected a non-negative integer timestamp, got {other:?}"
4184        ))),
4185    }
4186}
4187
4188fn current_unix_ns() -> u64 {
4189    std::time::SystemTime::now()
4190        .duration_since(std::time::UNIX_EPOCH)
4191        .unwrap_or_default()
4192        .as_nanos()
4193        .min(u128::from(u64::MAX)) as u64
4194}
4195
4196fn metadata_value_to_json(value: &MetadataValue) -> crate::json::Value {
4197    use crate::json::{Map, Value as JV};
4198    match value {
4199        MetadataValue::Null => JV::Null,
4200        MetadataValue::Bool(value) => JV::Bool(*value),
4201        MetadataValue::Int(value) => JV::Number(*value as f64),
4202        MetadataValue::Float(value) => JV::Number(*value),
4203        MetadataValue::String(value) => JV::String(value.clone()),
4204        MetadataValue::Bytes(value) => JV::Array(
4205            value
4206                .iter()
4207                .map(|value| JV::Number(*value as f64))
4208                .collect(),
4209        ),
4210        MetadataValue::Timestamp(value) => JV::Number(*value as f64),
4211        MetadataValue::Array(values) => {
4212            JV::Array(values.iter().map(metadata_value_to_json).collect())
4213        }
4214        MetadataValue::Object(object) => {
4215            let entries = object
4216                .iter()
4217                .map(|(key, value)| (key.clone(), metadata_value_to_json(value)))
4218                .collect();
4219            JV::Object(entries)
4220        }
4221        MetadataValue::Geo { lat, lon } => {
4222            let mut object = Map::new();
4223            object.insert("lat".to_string(), JV::Number(*lat));
4224            object.insert("lon".to_string(), JV::Number(*lon));
4225            JV::Object(object)
4226        }
4227        MetadataValue::Reference(target) => {
4228            let mut object = Map::new();
4229            object.insert(
4230                "collection".to_string(),
4231                JV::String(target.collection().to_string()),
4232            );
4233            object.insert(
4234                "entity_id".to_string(),
4235                JV::Number(target.entity_id().raw() as f64),
4236            );
4237            JV::Object(object)
4238        }
4239        MetadataValue::References(values) => {
4240            let refs = values
4241                .iter()
4242                .map(|target| {
4243                    let mut object = Map::new();
4244                    object.insert(
4245                        "collection".to_string(),
4246                        JV::String(target.collection().to_string()),
4247                    );
4248                    object.insert(
4249                        "entity_id".to_string(),
4250                        JV::Number(target.entity_id().raw() as f64),
4251                    );
4252                    JV::Object(object)
4253                })
4254                .collect();
4255            JV::Array(refs)
4256        }
4257    }
4258}
4259
4260fn storage_value_to_metadata_value(value: &Value) -> MetadataValue {
4261    match value {
4262        Value::Null => MetadataValue::Null,
4263        Value::Boolean(value) => MetadataValue::Bool(*value),
4264        Value::Integer(value) => MetadataValue::Int(*value),
4265        Value::UnsignedInteger(value) => metadata_u64_to_value(*value),
4266        Value::Float(value) => MetadataValue::Float(*value),
4267        Value::Text(value) => MetadataValue::String(value.to_string()),
4268        Value::Blob(value) => MetadataValue::Bytes(value.clone()),
4269        Value::Timestamp(value) => {
4270            if *value >= 0 {
4271                metadata_u64_to_value(*value as u64)
4272            } else {
4273                MetadataValue::Int(*value)
4274            }
4275        }
4276        Value::TimestampMs(value) => {
4277            if *value >= 0 {
4278                metadata_u64_to_value(*value as u64)
4279            } else {
4280                MetadataValue::Int(*value)
4281            }
4282        }
4283        Value::Json(value) => MetadataValue::String(String::from_utf8_lossy(value).into_owned()),
4284        Value::Uuid(value) => MetadataValue::String(format!("{value:?}")),
4285        Value::Date(value) => MetadataValue::String(value.to_string()),
4286        Value::Time(value) => MetadataValue::String(value.to_string()),
4287        Value::Decimal(value) => MetadataValue::String(value.to_string()),
4288        Value::Ipv4(value) => MetadataValue::String(format!(
4289            "{}.{}.{}.{}",
4290            (value >> 24) & 0xFF,
4291            (value >> 16) & 0xFF,
4292            (value >> 8) & 0xFF,
4293            value & 0xFF
4294        )),
4295        Value::Port(value) => MetadataValue::Int(i64::from(*value)),
4296        Value::Latitude(value) => MetadataValue::Float(*value as f64 / 1_000_000.0),
4297        Value::Longitude(value) => MetadataValue::Float(*value as f64 / 1_000_000.0),
4298        Value::GeoPoint(lat, lon) => MetadataValue::Geo {
4299            lat: *lat as f64 / 1_000_000.0,
4300            lon: *lon as f64 / 1_000_000.0,
4301        },
4302        Value::BigInt(value) => MetadataValue::String(value.to_string()),
4303        Value::TableRef(value) => MetadataValue::String(value.clone()),
4304        Value::PageRef(value) => MetadataValue::Int(*value as i64),
4305        Value::Password(value) => MetadataValue::String(value.clone()),
4306        Value::Array(values) => {
4307            MetadataValue::Array(values.iter().map(storage_value_to_metadata_value).collect())
4308        }
4309        _ => MetadataValue::String(value.to_string()),
4310    }
4311}
4312
4313fn sql_literal_to_metadata_value(field: &str, value: &Value) -> RedDBResult<MetadataValue> {
4314    match value {
4315        Value::Null => Ok(MetadataValue::Null),
4316        Value::Integer(value) if *value >= 0 => Ok(metadata_u64_to_value(*value as u64)),
4317        Value::Integer(_) => Err(RedDBError::Query(format!(
4318            "column '{field}' must be non-negative for TTL metadata"
4319        ))),
4320        Value::UnsignedInteger(value) => Ok(metadata_u64_to_value(*value)),
4321        Value::Float(value) if value.is_finite() => {
4322            if value.fract().abs() >= f64::EPSILON {
4323                return Err(RedDBError::Query(format!(
4324                    "column '{field}' must be an integer (TTL metadata must be an integer)"
4325                )));
4326            }
4327            if *value < 0.0 {
4328                return Err(RedDBError::Query(format!(
4329                    "column '{field}' must be non-negative for TTL metadata"
4330                )));
4331            }
4332            if *value > u64::MAX as f64 {
4333                return Err(RedDBError::Query(format!(
4334                    "column '{field}' value is too large"
4335                )));
4336            }
4337            Ok(metadata_u64_to_value(*value as u64))
4338        }
4339        Value::Float(_) => Err(RedDBError::Query(format!(
4340            "column '{field}' must be a finite number"
4341        ))),
4342        Value::Text(value) => {
4343            let value = value.trim();
4344            if let Ok(value) = value.parse::<u64>() {
4345                Ok(metadata_u64_to_value(value))
4346            } else if let Ok(value) = value.parse::<i64>() {
4347                if value < 0 {
4348                    return Err(RedDBError::Query(format!(
4349                        "column '{field}' must be non-negative for TTL metadata"
4350                    )));
4351                }
4352                Ok(metadata_u64_to_value(value as u64))
4353            } else if let Ok(value) = value.parse::<f64>() {
4354                if !value.is_finite() {
4355                    return Err(RedDBError::Query(format!(
4356                        "column '{field}' must be a finite number"
4357                    )));
4358                }
4359                if value.fract().abs() >= f64::EPSILON {
4360                    return Err(RedDBError::Query(format!(
4361                        "column '{field}' must be an integer (TTL metadata must be an integer)"
4362                    )));
4363                }
4364                if value < 0.0 {
4365                    return Err(RedDBError::Query(format!(
4366                        "column '{field}' must be non-negative for TTL metadata"
4367                    )));
4368                }
4369                if value > u64::MAX as f64 {
4370                    return Err(RedDBError::Query(format!(
4371                        "column '{field}' value is too large"
4372                    )));
4373                }
4374                Ok(metadata_u64_to_value(value as u64))
4375            } else {
4376                Err(RedDBError::Query(format!(
4377                    "column '{field}' expects a numeric value for TTL metadata"
4378                )))
4379            }
4380        }
4381        _ => Err(RedDBError::Query(format!(
4382            "column '{field}' expects a numeric value for TTL metadata"
4383        ))),
4384    }
4385}
4386
4387fn metadata_u64_to_value(value: u64) -> MetadataValue {
4388    if value <= i64::MAX as u64 {
4389        MetadataValue::Int(value as i64)
4390    } else {
4391        MetadataValue::Timestamp(value)
4392    }
4393}
4394
4395/// Phase 2 PG parity: inspect a column value and return `true` when
4396/// the dotted `tail` path is already present under it. Used by the
4397/// tenant auto-fill so rows that already carry an explicit value
4398/// (bulk import, admin insert on behalf of a tenant) are not
4399/// double-stamped with the session's current_tenant().
4400fn dotted_tail_already_set(value: &Value, tail: &str) -> bool {
4401    let json = match value {
4402        Value::Null => return false,
4403        Value::Json(bytes) | Value::Blob(bytes) => {
4404            match crate::json::from_slice::<crate::json::Value>(bytes) {
4405                Ok(v) => v,
4406                Err(_) => return false,
4407            }
4408        }
4409        Value::Text(s) => {
4410            let trimmed = s.trim_start();
4411            if !(trimmed.starts_with('{') || trimmed.starts_with('[')) {
4412                return false;
4413            }
4414            match crate::json::from_str::<crate::json::Value>(s) {
4415                Ok(v) => v,
4416                Err(_) => return false,
4417            }
4418        }
4419        _ => return false,
4420    };
4421    let mut cursor = &json;
4422    for seg in tail.split('.') {
4423        match cursor {
4424            crate::json::Value::Object(map) => match map.iter().find(|(k, _)| *k == seg) {
4425                Some((_, v)) => cursor = v,
4426                None => return false,
4427            },
4428            _ => return false,
4429        }
4430    }
4431    !matches!(cursor, crate::json::Value::Null)
4432}
4433
4434/// Phase 2 PG parity: take a column value (possibly Null / Text /
4435/// Json) and return a `Value::Json` with the dotted `tail` path set
4436/// to `tenant_id`. Preserves every pre-existing key.
4437///
4438/// Accepts:
4439/// * `Value::Null`  → fresh `{tail: tenant_id}` object
4440/// * `Value::Json(bytes)` → parse, navigate / create path, re-serialize
4441/// * `Value::text(s)` if `s` is valid JSON → same as Json
4442/// * anything else → error (user supplied a scalar where we need
4443///   a JSON container)
4444fn merge_dotted_tenant(current: Value, tail: &str, tenant_id: &str) -> RedDBResult<Value> {
4445    let mut root = match current {
4446        Value::Null => crate::json::Value::Object(Default::default()),
4447        Value::Json(bytes) | Value::Blob(bytes) => {
4448            crate::json::from_slice(&bytes).map_err(|err| {
4449                RedDBError::Query(format!(
4450                    "tenant auto-fill: root column is not valid JSON ({err})"
4451                ))
4452            })?
4453        }
4454        Value::Text(s) => {
4455            if s.trim().is_empty() {
4456                crate::json::Value::Object(Default::default())
4457            } else {
4458                crate::json::from_str::<crate::json::Value>(&s).map_err(|err| {
4459                    RedDBError::Query(format!(
4460                        "tenant auto-fill: text root is not valid JSON ({err})"
4461                    ))
4462                })?
4463            }
4464        }
4465        other => {
4466            return Err(RedDBError::Query(format!(
4467                "tenant auto-fill: root column must be JSON / NULL, got {other:?}"
4468            )));
4469        }
4470    };
4471
4472    // Navigate path segments, creating intermediate objects on demand.
4473    let segments: Vec<&str> = tail.split('.').collect();
4474    let mut cursor: &mut crate::json::Value = &mut root;
4475    for (i, seg) in segments.iter().enumerate() {
4476        let is_last = i + 1 == segments.len();
4477        let map = match cursor {
4478            crate::json::Value::Object(m) => m,
4479            _ => {
4480                return Err(RedDBError::Query(format!(
4481                    "tenant auto-fill: segment '{seg}' is not inside an object"
4482                )));
4483            }
4484        };
4485        if is_last {
4486            map.insert(
4487                seg.to_string(),
4488                crate::json::Value::String(tenant_id.to_string()),
4489            );
4490            break;
4491        }
4492        cursor = map
4493            .entry(seg.to_string())
4494            .or_insert_with(|| crate::json::Value::Object(Default::default()));
4495    }
4496
4497    let bytes = crate::json::to_vec(&root).map_err(|err| {
4498        RedDBError::Query(format!(
4499            "tenant auto-fill: failed to re-serialize JSON ({err})"
4500        ))
4501    })?;
4502    Ok(Value::Json(bytes))
4503}
4504
4505#[cfg(test)]
4506mod tests {
4507    use crate::storage::schema::Value;
4508    use crate::storage::wal::{WalReader, WalRecord};
4509    use crate::storage::{DeployProfile, StoragePackaging, StorageProfileSelection};
4510    use crate::{RedDBOptions, RedDBRuntime};
4511    use std::path::Path;
4512
4513    fn persistent_operational_options(path: &Path) -> RedDBOptions {
4514        RedDBOptions::persistent(path)
4515            .with_storage_profile(StorageProfileSelection {
4516                deploy_profile: DeployProfile::Embedded,
4517                packaging: StoragePackaging::OperationalDirectory,
4518                replica_count: 0,
4519                managed_backup: false,
4520                wal_retention: false,
4521            })
4522            .unwrap()
4523    }
4524
4525    fn store_commit_batches(wal_path: &Path) -> Vec<Vec<Vec<u8>>> {
4526        WalReader::open(wal_path)
4527            .expect("wal opens")
4528            .iter()
4529            .map(|record| record.expect("wal record decodes").1)
4530            .filter_map(|record| match record {
4531                WalRecord::TxCommitBatch { actions, .. } => Some(actions),
4532                _ => None,
4533            })
4534            .collect()
4535    }
4536
4537    fn action_contains_text(action: &[u8], needle: &str) -> bool {
4538        action
4539            .windows(needle.len())
4540            .any(|window| window == needle.as_bytes())
4541    }
4542
4543    fn claim_metric_count(
4544        snapshot: &crate::runtime::ClaimTelemetrySnapshot,
4545        metric: &str,
4546        collection: &str,
4547        model: &str,
4548    ) -> u64 {
4549        let rows = match metric {
4550            "attempts" => &snapshot.attempts,
4551            "successful" => &snapshot.successful,
4552            "misses" => &snapshot.misses,
4553            "skipped_locked" => &snapshot.skipped_locked,
4554            other => panic!("unknown claim metric {other}"),
4555        };
4556        rows.iter()
4557            .find(|((actual_collection, actual_model), _)| {
4558                actual_collection == collection && actual_model == model
4559            })
4560            .map(|(_, count)| *count)
4561            .unwrap_or(0)
4562    }
4563
4564    fn assert_statement_writes_collections_in_one_new_wal_batch(
4565        rt: &RedDBRuntime,
4566        wal_path: &Path,
4567        statement: &str,
4568        source: &str,
4569        event_queue: &str,
4570    ) {
4571        let before_batches = store_commit_batches(wal_path).len();
4572
4573        rt.execute_query(statement).unwrap();
4574
4575        let batches = store_commit_batches(wal_path);
4576        let statement_batches = &batches[before_batches..];
4577        let source_batch = statement_batches
4578            .iter()
4579            .position(|actions| {
4580                actions.iter().any(|action| {
4581                    action_contains_text(action, source)
4582                        && !action_contains_text(action, event_queue)
4583                })
4584            })
4585            .expect("source collection write batch is present");
4586        let event_batch = statement_batches
4587            .iter()
4588            .position(|actions| {
4589                actions
4590                    .iter()
4591                    .any(|action| action_contains_text(action, event_queue))
4592            })
4593            .expect("event queue write batch is present");
4594
4595        assert_eq!(
4596            source_batch, event_batch,
4597            "WITH EVENTS must persist the source write and queue event in the same WAL batch"
4598        );
4599    }
4600
4601    #[test]
4602    fn with_events_autocommit_persists_mutation_and_event_in_one_wal_batch() {
4603        let dir = tempfile::tempdir().unwrap();
4604        let db_path = dir.path().join("events_dual_write.rdb");
4605        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4606        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4607
4608        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4609            .unwrap();
4610        assert_statement_writes_collections_in_one_new_wal_batch(
4611            &rt,
4612            &wal_path,
4613            "INSERT INTO users (id, email) VALUES (1, 'a@example.test')",
4614            "users",
4615            "users_events",
4616        );
4617    }
4618
4619    #[test]
4620    fn with_events_autocommit_update_persists_mutation_and_event_in_one_wal_batch() {
4621        let dir = tempfile::tempdir().unwrap();
4622        let db_path = dir.path().join("events_update_atomic.rdb");
4623        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4624        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4625
4626        rt.execute_query(
4627            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (UPDATE) TO user_updates",
4628        )
4629        .unwrap();
4630        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
4631            .unwrap();
4632
4633        assert_statement_writes_collections_in_one_new_wal_batch(
4634            &rt,
4635            &wal_path,
4636            "UPDATE users SET email = 'b@example.test' WHERE id = 1",
4637            "users",
4638            "user_updates",
4639        );
4640    }
4641
4642    #[test]
4643    fn with_events_autocommit_delete_persists_mutation_and_event_in_one_wal_batch() {
4644        let dir = tempfile::tempdir().unwrap();
4645        let db_path = dir.path().join("events_delete_atomic.rdb");
4646        let wal_path = reddb_file::layout::unified_wal_path(&db_path);
4647        let rt = RedDBRuntime::with_options(persistent_operational_options(&db_path)).unwrap();
4648
4649        rt.execute_query(
4650            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (DELETE) TO user_deletes",
4651        )
4652        .unwrap();
4653        rt.execute_query("INSERT INTO users (id, email) VALUES (1, 'a@example.test')")
4654            .unwrap();
4655
4656        assert_statement_writes_collections_in_one_new_wal_batch(
4657            &rt,
4658            &wal_path,
4659            "DELETE FROM users WHERE id = 1",
4660            "users",
4661            "user_deletes",
4662        );
4663    }
4664
4665    #[test]
4666    fn update_where_id_in_with_hash_index_updates_expected_rows() {
4667        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4668        rt.execute_query("CREATE TABLE users (id INT, score INT)")
4669            .unwrap();
4670        for id in 0..5 {
4671            rt.execute_query(&format!("INSERT INTO users (id, score) VALUES ({id}, 0)"))
4672                .unwrap();
4673        }
4674        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
4675            .unwrap();
4676
4677        let updated = rt
4678            .execute_query("UPDATE users SET score = 42 WHERE id IN (1,3,4)")
4679            .unwrap();
4680        assert_eq!(updated.affected_rows, 3);
4681
4682        let selected = rt
4683            .execute_query("SELECT id, score FROM users ORDER BY id")
4684            .unwrap();
4685        let scores: Vec<(i64, i64)> = selected
4686            .result
4687            .records
4688            .iter()
4689            .map(|record| {
4690                let id = match record.get("id").unwrap() {
4691                    Value::Integer(value) => *value,
4692                    other => panic!("expected integer id, got {other:?}"),
4693                };
4694                let score = match record.get("score").unwrap() {
4695                    Value::Integer(value) => *value,
4696                    other => panic!("expected integer score, got {other:?}"),
4697                };
4698                (id, score)
4699            })
4700            .collect();
4701        assert_eq!(scores, vec![(0, 0), (1, 42), (2, 0), (3, 42), (4, 42)]);
4702    }
4703
4704    /// Drives UPDATE through the shared `DmlTargetScan` module — the
4705    /// same code path DELETE uses (#51, #52). Exercises the indexed
4706    /// equality fast-path (WHERE id = N with a HASH index), the
4707    /// unindexed range scan (WHERE score > N), and the no-WHERE
4708    /// full-scan branch to confirm the extracted "find target rows"
4709    /// loop preserves affected-row counts and the resulting row state.
4710    #[test]
4711    fn update_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
4712        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4713        rt.execute_query("CREATE TABLE items (id INT, score INT)")
4714            .unwrap();
4715        for id in 0..5 {
4716            rt.execute_query(&format!(
4717                "INSERT INTO items (id, score) VALUES ({id}, {})",
4718                id * 10
4719            ))
4720            .unwrap();
4721        }
4722        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
4723            .unwrap();
4724
4725        // Indexed equality UPDATE — hits the hash fast-path inside
4726        // DmlTargetScan::find_target_ids. id=2 has score=20, drop it
4727        // below the score>25 cutoff so the next assertion stays clean.
4728        let updated_one = rt
4729            .execute_query("UPDATE items SET score = 5 WHERE id = 2")
4730            .unwrap();
4731        assert_eq!(updated_one.affected_rows, 1);
4732
4733        // Unindexed scan UPDATE — bumps everyone with score > 25,
4734        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
4735        // zoned/full-scan branch.
4736        let updated_many = rt
4737            .execute_query("UPDATE items SET score = 7 WHERE score > 25")
4738            .unwrap();
4739        assert_eq!(updated_many.affected_rows, 2);
4740
4741        let snapshot = rt
4742            .execute_query("SELECT id, score FROM items ORDER BY id")
4743            .unwrap();
4744        let pairs: Vec<(i64, i64)> = snapshot
4745            .result
4746            .records
4747            .iter()
4748            .map(|record| {
4749                let id = match record.get("id").unwrap() {
4750                    Value::Integer(value) => *value,
4751                    other => panic!("expected integer id, got {other:?}"),
4752                };
4753                let score = match record.get("score").unwrap() {
4754                    Value::Integer(value) => *value,
4755                    other => panic!("expected integer score, got {other:?}"),
4756                };
4757                (id, score)
4758            })
4759            .collect();
4760        assert_eq!(pairs, vec![(0, 0), (1, 10), (2, 5), (3, 7), (4, 7)]);
4761
4762        // Full-scan UPDATE with no WHERE rewrites every remaining row.
4763        let updated_all = rt.execute_query("UPDATE items SET score = 1").unwrap();
4764        assert_eq!(updated_all.affected_rows, 5);
4765        let after = rt
4766            .execute_query("SELECT score FROM items ORDER BY id")
4767            .unwrap();
4768        let scores: Vec<i64> = after
4769            .result
4770            .records
4771            .iter()
4772            .map(|record| match record.get("score").unwrap() {
4773                Value::Integer(value) => *value,
4774                other => panic!("expected integer score, got {other:?}"),
4775            })
4776            .collect();
4777        assert_eq!(scores, vec![1, 1, 1, 1, 1]);
4778    }
4779
4780    /// Drives DELETE through the new `DmlTargetScan` module. Exercises
4781    /// both the index fast-path (WHERE id = N with a HASH index) and
4782    /// the unindexed scan path (WHERE score > N) to confirm the
4783    /// extracted "find target rows" loop preserves the affected-row
4784    /// count and which rows survive.
4785    #[test]
4786    fn delete_routes_through_dml_target_scan_for_indexed_and_scan_paths() {
4787        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4788        rt.execute_query("CREATE TABLE items (id INT, score INT)")
4789            .unwrap();
4790        for id in 0..5 {
4791            rt.execute_query(&format!(
4792                "INSERT INTO items (id, score) VALUES ({id}, {})",
4793                id * 10
4794            ))
4795            .unwrap();
4796        }
4797        rt.execute_query("CREATE INDEX idx_items_id ON items (id) USING HASH")
4798            .unwrap();
4799
4800        // Indexed equality DELETE — hits the hash fast-path inside
4801        // DmlTargetScan::find_target_ids.
4802        let deleted_one = rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
4803        assert_eq!(deleted_one.affected_rows, 1);
4804
4805        // Unindexed scan DELETE — drops everyone with score > 25,
4806        // i.e. ids 3 and 4 (scores 30, 40). Goes through the
4807        // zoned/full-scan branch.
4808        let deleted_many = rt
4809            .execute_query("DELETE FROM items WHERE score > 25")
4810            .unwrap();
4811        assert_eq!(deleted_many.affected_rows, 2);
4812
4813        let surviving = rt
4814            .execute_query("SELECT id FROM items ORDER BY id")
4815            .unwrap();
4816        let ids: Vec<i64> = surviving
4817            .result
4818            .records
4819            .iter()
4820            .map(|record| match record.get("id").unwrap() {
4821                Value::Integer(value) => *value,
4822                other => panic!("expected integer id, got {other:?}"),
4823            })
4824            .collect();
4825        assert_eq!(ids, vec![0, 1]);
4826
4827        // Sanity: full-scan DELETE with no WHERE clears the rest.
4828        let deleted_rest = rt.execute_query("DELETE FROM items").unwrap();
4829        assert_eq!(deleted_rest.affected_rows, 2);
4830        let empty = rt.execute_query("SELECT id FROM items").unwrap();
4831        assert!(empty.result.records.is_empty());
4832    }
4833
4834    /// CollectionContract gate (#49 + #50): APPEND ONLY tables accept
4835    /// INSERT but reject UPDATE and DELETE with the documented
4836    /// operator-facing error strings. Drives all three DML verbs so
4837    /// the centralized gate is exercised end-to-end.
4838    #[test]
4839    fn collection_contract_gate_blocks_update_and_delete_on_append_only() {
4840        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4841        rt.execute_query("CREATE TABLE events (id INT, payload TEXT) APPEND ONLY")
4842            .unwrap();
4843
4844        // INSERT must succeed — APPEND ONLY exists precisely to allow
4845        // appends. The gate should be a no-op for INSERT.
4846        let inserted = rt
4847            .execute_query("INSERT INTO events (id, payload) VALUES (1, 'hello')")
4848            .unwrap();
4849        assert_eq!(inserted.affected_rows, 1);
4850
4851        // UPDATE is rejected with the gate's UPDATE-specific message.
4852        let update_err = rt
4853            .execute_query("UPDATE events SET payload = 'mut' WHERE id = 1")
4854            .unwrap_err();
4855        let msg = format!("{update_err}");
4856        assert!(
4857            msg.contains("APPEND ONLY") && msg.contains("UPDATE is rejected"),
4858            "expected UPDATE rejection message, got: {msg}"
4859        );
4860
4861        // DELETE is rejected with the gate's DELETE-specific message.
4862        let delete_err = rt
4863            .execute_query("DELETE FROM events WHERE id = 1")
4864            .unwrap_err();
4865        let msg = format!("{delete_err}");
4866        assert!(
4867            msg.contains("APPEND ONLY") && msg.contains("DELETE is rejected"),
4868            "expected DELETE rejection message, got: {msg}"
4869        );
4870
4871        // Row should still be present — neither rejected mutation
4872        // touched storage.
4873        let surviving = rt.execute_query("SELECT id FROM events").unwrap();
4874        assert_eq!(surviving.result.records.len(), 1);
4875    }
4876
4877    /// CollectionContract gate: tables without an APPEND ONLY contract
4878    /// permit INSERT, UPDATE, and DELETE — the gate's default branch
4879    /// is a true pass-through, not an accidental block.
4880    #[test]
4881    fn collection_contract_gate_allows_all_verbs_on_unrestricted_table() {
4882        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4883        rt.execute_query("CREATE TABLE notes (id INT, body TEXT)")
4884            .unwrap();
4885
4886        rt.execute_query("INSERT INTO notes (id, body) VALUES (1, 'a')")
4887            .unwrap();
4888        let updated = rt
4889            .execute_query("UPDATE notes SET body = 'b' WHERE id = 1")
4890            .unwrap();
4891        assert_eq!(updated.affected_rows, 1);
4892        let deleted = rt.execute_query("DELETE FROM notes WHERE id = 1").unwrap();
4893        assert_eq!(deleted.affected_rows, 1);
4894    }
4895
4896    #[test]
4897    fn insert_into_event_enabled_table_emits_event_to_configured_queue() {
4898        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4899        rt.execute_query(
4900            "CREATE TABLE users (id INT, email TEXT) WITH EVENTS (INSERT) TO audit_log",
4901        )
4902        .unwrap();
4903
4904        let inserted = rt
4905            .execute_query("INSERT INTO users (id, email) VALUES (7, 'a@example.com')")
4906            .unwrap();
4907        assert_eq!(inserted.affected_rows, 1);
4908
4909        let events = queue_payloads(&rt, "audit_log");
4910        assert_eq!(events.len(), 1);
4911        let event = events[0].as_object().expect("event payload object");
4912        assert!(event
4913            .get("event_id")
4914            .and_then(crate::json::Value::as_str)
4915            .is_some_and(|value| !value.is_empty()));
4916        assert_eq!(
4917            event.get("op").and_then(crate::json::Value::as_str),
4918            Some("insert")
4919        );
4920        assert_eq!(
4921            event.get("collection").and_then(crate::json::Value::as_str),
4922            Some("users")
4923        );
4924        assert_eq!(
4925            event.get("id").and_then(crate::json::Value::as_u64),
4926            Some(7)
4927        );
4928        assert!(event
4929            .get("ts")
4930            .and_then(crate::json::Value::as_u64)
4931            .is_some());
4932        assert!(event
4933            .get("lsn")
4934            .and_then(crate::json::Value::as_u64)
4935            .is_some());
4936        assert!(matches!(
4937            event.get("tenant"),
4938            Some(crate::json::Value::Null)
4939        ));
4940        assert!(matches!(
4941            event.get("before"),
4942            Some(crate::json::Value::Null)
4943        ));
4944        let after = event
4945            .get("after")
4946            .and_then(crate::json::Value::as_object)
4947            .expect("after object");
4948        assert_eq!(
4949            after.get("id").and_then(crate::json::Value::as_u64),
4950            Some(7)
4951        );
4952        assert_eq!(
4953            after.get("email").and_then(crate::json::Value::as_str),
4954            Some("a@example.com")
4955        );
4956    }
4957
4958    #[test]
4959    fn multi_row_insert_emits_one_insert_event_per_row_in_order() {
4960        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
4961        rt.execute_query("CREATE TABLE users (id INT, email TEXT) WITH EVENTS")
4962            .unwrap();
4963
4964        rt.execute_query(
4965            "INSERT INTO users (id, email) VALUES (1, 'a@example.com'), (2, 'b@example.com')",
4966        )
4967        .unwrap();
4968
4969        let events = queue_payloads(&rt, "users_events");
4970        assert_eq!(events.len(), 2);
4971        let mut previous_lsn = 0;
4972        for (event, expected_id) in events.iter().zip([1_u64, 2]) {
4973            let object = event.as_object().expect("event payload object");
4974            assert_eq!(
4975                object.get("op").and_then(crate::json::Value::as_str),
4976                Some("insert")
4977            );
4978            assert_eq!(
4979                object.get("id").and_then(crate::json::Value::as_u64),
4980                Some(expected_id)
4981            );
4982            let lsn = object
4983                .get("lsn")
4984                .and_then(crate::json::Value::as_u64)
4985                .expect("event lsn");
4986            assert!(
4987                lsn > previous_lsn,
4988                "event LSNs should increase in row order"
4989            );
4990            previous_lsn = lsn;
4991            let after = object
4992                .get("after")
4993                .and_then(crate::json::Value::as_object)
4994                .expect("after object");
4995            assert_eq!(
4996                after.get("id").and_then(crate::json::Value::as_u64),
4997                Some(expected_id)
4998            );
4999        }
5000    }
5001
5002    #[test]
5003    fn claim_metrics_increment_skipped_locked_without_counting_miss() {
5004        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
5005        rt.execute_query("CREATE TABLE claim_metric_locked (id INT, rank INT, status TEXT)")
5006            .expect("create table");
5007        rt.execute_query(
5008            "INSERT INTO claim_metric_locked (id, rank, status) VALUES \
5009             (1, 10, 'ready'), (2, 20, 'ready')",
5010        )
5011        .expect("insert rows");
5012
5013        let claim_lock = rt
5014            .inner
5015            .rmw_locks
5016            .lock_for("claim_metric_locked", "__table_claim_update__");
5017        let _guard = claim_lock.lock();
5018        let updated = rt
5019            .execute_query(
5020                "UPDATE claim_metric_locked SET status = 'claimed' WHERE status = 'ready' \
5021                 CLAIM LIMIT 2 ORDER BY rank ASC",
5022            )
5023            .expect("claim skips locked candidates");
5024
5025        assert_eq!(updated.affected_rows, 0);
5026        let snapshot = rt.claim_telemetry_snapshot();
5027        assert_eq!(
5028            claim_metric_count(&snapshot, "attempts", "claim_metric_locked", "table"),
5029            1
5030        );
5031        assert_eq!(
5032            claim_metric_count(&snapshot, "skipped_locked", "claim_metric_locked", "table"),
5033            2
5034        );
5035        assert_eq!(
5036            claim_metric_count(&snapshot, "misses", "claim_metric_locked", "table"),
5037            0
5038        );
5039        assert_eq!(
5040            snapshot.skipped_locked.len(),
5041            1,
5042            "skipped-lock labels stay bounded to collection/model"
5043        );
5044    }
5045
5046    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
5047        let result = rt
5048            .execute_query(&format!("QUEUE PEEK {queue} 10"))
5049            .expect("peek queue");
5050        result
5051            .result
5052            .records
5053            .iter()
5054            .map(
5055                |record| match record.get("payload").expect("payload column") {
5056                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
5057                    other => panic!("expected JSON queue payload, got {other:?}"),
5058                },
5059            )
5060            .collect()
5061    }
5062
5063    // ── #112: auto-index user `id` on first insert ─────────────────────
5064
5065    /// First insert into a fresh collection that carries a column named
5066    /// `id` registers an implicit HASH index on `id`. Subsequent inserts
5067    /// populate it transparently, and `WHERE id = N` lookups exercise
5068    /// the hash-index fast path in `DmlTargetScan::find_target_ids`.
5069    ///
5070    /// This is the load-bearing acceptance test for #112 — without the
5071    /// hook, `find_index_for_column` returns `None` and DELETE/UPDATE
5072    /// fall through to a full segment scan (the 4× perf gap documented
5073    /// in `docs/perf/delete-sequential-2026-05-06.md`).
5074    #[test]
5075    fn auto_index_id_fires_on_first_insert() {
5076        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5077        rt.execute_query("CREATE TABLE bench_users (id INT, score INT)")
5078            .unwrap();
5079
5080        // Pre-condition: no index on `id` yet.
5081        assert!(
5082            rt.index_store_ref()
5083                .find_index_for_column("bench_users", "id")
5084                .is_none(),
5085            "freshly created collection should not have an `id` index"
5086        );
5087
5088        // Single-row INSERT — drives `MutationEngine::append_one`.
5089        rt.execute_query("INSERT INTO bench_users (id, score) VALUES (1, 10)")
5090            .unwrap();
5091
5092        // Post-condition: hash index registered on `id`.
5093        let registered = rt
5094            .index_store_ref()
5095            .find_index_for_column("bench_users", "id")
5096            .expect("auto-index hook should have registered idx_id on first insert");
5097        assert_eq!(registered.name, "idx_id");
5098        assert_eq!(registered.collection, "bench_users");
5099        assert_eq!(registered.columns, vec!["id".to_string()]);
5100        assert!(matches!(
5101            registered.method,
5102            super::super::index_store::IndexMethodKind::Hash
5103        ));
5104
5105        // Subsequent inserts populate the index; `WHERE id = N` should
5106        // resolve via the hash fast path and round-trip every row.
5107        for id in 2..=5 {
5108            rt.execute_query(&format!(
5109                "INSERT INTO bench_users (id, score) VALUES ({id}, {})",
5110                id * 10
5111            ))
5112            .unwrap();
5113        }
5114        for id in 1..=5 {
5115            let result = rt
5116                .execute_query(&format!("SELECT score FROM bench_users WHERE id = {id}"))
5117                .unwrap();
5118            assert_eq!(
5119                result.result.records.len(),
5120                1,
5121                "id={id} should match one row"
5122            );
5123        }
5124
5125        // Delete via the hash fast-path — exactly the bench scenario the
5126        // perf doc identified as the 4× regression. With the index
5127        // present, `find_target_ids` short-circuits before
5128        // `for_each_entity_zoned` runs.
5129        let deleted = rt
5130            .execute_query("DELETE FROM bench_users WHERE id = 3")
5131            .unwrap();
5132        assert_eq!(deleted.affected_rows, 1);
5133    }
5134
5135    /// Bulk INSERT (the multi-row VALUES path) drives
5136    /// `MutationEngine::append_batch`. The hook must fire there too —
5137    /// otherwise the batch entry points (gRPC binary bulk, HTTP bulk,
5138    /// wire bulk INSERT) skip auto-indexing entirely.
5139    #[test]
5140    fn auto_index_id_fires_on_first_bulk_insert() {
5141        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5142        rt.execute_query("CREATE TABLE bench_bulk (id INT, score INT)")
5143            .unwrap();
5144
5145        rt.execute_query("INSERT INTO bench_bulk (id, score) VALUES (1, 10), (2, 20), (3, 30)")
5146            .unwrap();
5147
5148        let registered = rt
5149            .index_store_ref()
5150            .find_index_for_column("bench_bulk", "id")
5151            .expect("auto-index hook should fire on first bulk insert");
5152        assert_eq!(registered.name, "idx_id");
5153
5154        // Every row populated via `index_entity_insert_batch`.
5155        for id in 1..=3 {
5156            let result = rt
5157                .execute_query(&format!("SELECT score FROM bench_bulk WHERE id = {id}"))
5158                .unwrap();
5159            assert_eq!(result.result.records.len(), 1);
5160        }
5161    }
5162
5163    /// Hook is a no-op when the row carries no `id` column. Conservative
5164    /// match (case-sensitive `id`) — `Id`, `ID`, and `rid`
5165    /// don't trigger it.
5166    #[test]
5167    fn auto_index_id_skips_when_no_id_column() {
5168        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5169        rt.execute_query("CREATE TABLE plain (uid INT, label TEXT)")
5170            .unwrap();
5171        rt.execute_query("INSERT INTO plain (uid, label) VALUES (1, 'a')")
5172            .unwrap();
5173
5174        assert!(rt
5175            .index_store_ref()
5176            .find_index_for_column("plain", "id")
5177            .is_none());
5178        assert!(rt
5179            .index_store_ref()
5180            .find_index_for_column("plain", "uid")
5181            .is_none());
5182    }
5183
5184    /// Hook only fires once per collection. If an explicit
5185    /// `CREATE INDEX ... USING BTREE` already covers `id`, the hook
5186    /// detects it via `find_index_for_column` and does NOT clobber it
5187    /// with a HASH index on the next insert.
5188    #[test]
5189    fn auto_index_id_skips_when_index_already_exists() {
5190        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5191        rt.execute_query("CREATE TABLE pre (id INT, score INT)")
5192            .unwrap();
5193        // User-declared BTREE index on `id` before any insert.
5194        rt.execute_query("CREATE INDEX user_idx ON pre (id) USING BTREE")
5195            .unwrap();
5196        rt.execute_query("INSERT INTO pre (id, score) VALUES (1, 10)")
5197            .unwrap();
5198
5199        let registered = rt
5200            .index_store_ref()
5201            .find_index_for_column("pre", "id")
5202            .expect("user index should still be there");
5203        assert_eq!(
5204            registered.name, "user_idx",
5205            "auto-index hook must not overwrite an existing index"
5206        );
5207    }
5208
5209    /// Implicit `idx_id` is reaped when the collection drops. The
5210    /// existing `execute_drop_table` walks `list_indices` and drops every
5211    /// entry — confirm the auto-created index participates.
5212    #[test]
5213    fn auto_index_id_dropped_with_collection() {
5214        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5215        rt.execute_query("CREATE TABLE ephemeral (id INT, score INT)")
5216            .unwrap();
5217        rt.execute_query("INSERT INTO ephemeral (id, score) VALUES (1, 10)")
5218            .unwrap();
5219        assert!(rt
5220            .index_store_ref()
5221            .find_index_for_column("ephemeral", "id")
5222            .is_some());
5223
5224        rt.execute_query("DROP TABLE ephemeral").unwrap();
5225
5226        assert!(
5227            rt.index_store_ref()
5228                .find_index_for_column("ephemeral", "id")
5229                .is_none(),
5230            "implicit `idx_id` must be reaped when its collection drops"
5231        );
5232    }
5233
5234    /// Opt-out via `RedDBOptions::with_auto_index_id(false)` (which
5235    /// forwards to `UnifiedStoreConfig::auto_index_id`). With the knob
5236    /// off, first insert leaves the collection without an `id` index —
5237    /// DELETE/UPDATE fall back to the scan path.
5238    #[test]
5239    fn auto_index_id_disabled_by_config() {
5240        let opts = RedDBOptions::in_memory().with_auto_index_id(false);
5241        let rt = RedDBRuntime::with_options(opts).unwrap();
5242
5243        rt.execute_query("CREATE TABLE off (id INT, score INT)")
5244            .unwrap();
5245        rt.execute_query("INSERT INTO off (id, score) VALUES (1, 10)")
5246            .unwrap();
5247
5248        assert!(
5249            rt.index_store_ref()
5250                .find_index_for_column("off", "id")
5251                .is_none(),
5252            "with auto_index_id=false, no implicit index should be created"
5253        );
5254    }
5255
5256    // ── #293: UPDATE / DELETE events ─────────────────────────────────────
5257
5258    #[test]
5259    fn update_single_row_emits_update_event() {
5260        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5261        rt.execute_query(
5262            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO audit_log",
5263        )
5264        .unwrap();
5265        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5266            .unwrap();
5267
5268        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
5269            .unwrap();
5270
5271        let events = queue_payloads(&rt, "audit_log");
5272        assert_eq!(events.len(), 1, "expected exactly 1 update event");
5273        let event = events[0].as_object().expect("event payload object");
5274        assert_eq!(
5275            event.get("op").and_then(crate::json::Value::as_str),
5276            Some("update")
5277        );
5278        assert_eq!(
5279            event.get("collection").and_then(crate::json::Value::as_str),
5280            Some("users")
5281        );
5282        assert!(event
5283            .get("event_id")
5284            .and_then(crate::json::Value::as_str)
5285            .is_some_and(|v| !v.is_empty()));
5286        let before = event
5287            .get("before")
5288            .and_then(crate::json::Value::as_object)
5289            .expect("before must be an object");
5290        let after = event
5291            .get("after")
5292            .and_then(crate::json::Value::as_object)
5293            .expect("after must be an object");
5294        assert_eq!(
5295            before.get("name").and_then(crate::json::Value::as_str),
5296            Some("Alice"),
5297            "before.name should be the old value"
5298        );
5299        assert_eq!(
5300            after.get("name").and_then(crate::json::Value::as_str),
5301            Some("Bob"),
5302            "after.name should be the new value"
5303        );
5304    }
5305
5306    #[test]
5307    fn update_event_only_includes_changed_fields() {
5308        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5309        rt.execute_query(
5310            "CREATE TABLE users (id INT, name TEXT, email TEXT) WITH EVENTS (UPDATE) TO evts",
5311        )
5312        .unwrap();
5313        rt.execute_query("INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'a@x.com')")
5314            .unwrap();
5315
5316        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1")
5317            .unwrap();
5318
5319        let events = queue_payloads(&rt, "evts");
5320        assert_eq!(events.len(), 1);
5321        let event = events[0].as_object().unwrap();
5322        let before = event
5323            .get("before")
5324            .and_then(crate::json::Value::as_object)
5325            .unwrap();
5326        let after = event
5327            .get("after")
5328            .and_then(crate::json::Value::as_object)
5329            .unwrap();
5330        // Only changed field included.
5331        assert!(
5332            before.contains_key("name"),
5333            "before must include changed field"
5334        );
5335        assert!(
5336            after.contains_key("name"),
5337            "after must include changed field"
5338        );
5339        // Unchanged fields must not appear.
5340        assert!(
5341            !before.contains_key("email"),
5342            "before must not include unchanged email"
5343        );
5344        assert!(
5345            !after.contains_key("email"),
5346            "after must not include unchanged email"
5347        );
5348    }
5349
5350    #[test]
5351    fn multi_row_update_emits_one_event_per_row() {
5352        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5353        rt.execute_query("CREATE TABLE items (id INT, status TEXT) WITH EVENTS (UPDATE) TO evts")
5354            .unwrap();
5355        rt.execute_query(
5356            "INSERT INTO items (id, status) VALUES (1, 'new'), (2, 'new'), (3, 'new')",
5357        )
5358        .unwrap();
5359
5360        rt.execute_query("UPDATE items SET status = 'done'")
5361            .unwrap();
5362
5363        let events = queue_payloads(&rt, "evts");
5364        assert_eq!(events.len(), 3, "expected one update event per row");
5365        for event in &events {
5366            let obj = event.as_object().unwrap();
5367            assert_eq!(
5368                obj.get("op").and_then(crate::json::Value::as_str),
5369                Some("update")
5370            );
5371        }
5372    }
5373
5374    #[test]
5375    fn delete_single_row_emits_delete_event() {
5376        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5377        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (DELETE) TO del_log")
5378            .unwrap();
5379        rt.execute_query("INSERT INTO users (id, name) VALUES (42, 'Alice')")
5380            .unwrap();
5381
5382        rt.execute_query("DELETE FROM users WHERE id = 42").unwrap();
5383
5384        let events = queue_payloads(&rt, "del_log");
5385        assert_eq!(events.len(), 1);
5386        let event = events[0].as_object().expect("event payload object");
5387        assert_eq!(
5388            event.get("op").and_then(crate::json::Value::as_str),
5389            Some("delete")
5390        );
5391        assert_eq!(
5392            event.get("collection").and_then(crate::json::Value::as_str),
5393            Some("users")
5394        );
5395        assert!(event
5396            .get("event_id")
5397            .and_then(crate::json::Value::as_str)
5398            .is_some_and(|v| !v.is_empty()));
5399        let before = event
5400            .get("before")
5401            .and_then(crate::json::Value::as_object)
5402            .expect("before must be an object for delete");
5403        assert_eq!(
5404            before.get("id").and_then(crate::json::Value::as_u64),
5405            Some(42)
5406        );
5407        assert_eq!(
5408            before.get("name").and_then(crate::json::Value::as_str),
5409            Some("Alice")
5410        );
5411        assert!(matches!(event.get("after"), Some(crate::json::Value::Null)));
5412    }
5413
5414    #[test]
5415    fn multi_row_delete_emits_one_event_per_row() {
5416        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5417        rt.execute_query("CREATE TABLE items (id INT, val INT) WITH EVENTS (DELETE) TO del_log")
5418            .unwrap();
5419        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 10), (2, 20), (3, 30)")
5420            .unwrap();
5421
5422        rt.execute_query("DELETE FROM items").unwrap();
5423
5424        let events = queue_payloads(&rt, "del_log");
5425        assert_eq!(events.len(), 3, "expected one delete event per deleted row");
5426        for event in &events {
5427            let obj = event.as_object().unwrap();
5428            assert_eq!(
5429                obj.get("op").and_then(crate::json::Value::as_str),
5430                Some("delete")
5431            );
5432            assert!(matches!(obj.get("after"), Some(crate::json::Value::Null)));
5433        }
5434    }
5435
5436    #[test]
5437    fn ops_filter_update_does_not_emit_on_insert_or_delete() {
5438        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5439        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS (UPDATE) TO evts")
5440            .unwrap();
5441
5442        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5443            .unwrap();
5444        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
5445
5446        let events = queue_payloads(&rt, "evts");
5447        assert!(
5448            events.is_empty(),
5449            "UPDATE-only filter must not emit INSERT or DELETE events"
5450        );
5451    }
5452
5453    // ── SUPPRESS EVENTS ────────────────────────────────────────────────────
5454
5455    #[test]
5456    fn suppress_events_on_insert_emits_no_events() {
5457        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5458        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5459            .unwrap();
5460
5461        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5462            .unwrap();
5463
5464        let events = queue_payloads(&rt, "evts");
5465        assert!(
5466            events.is_empty(),
5467            "SUPPRESS EVENTS must prevent INSERT events"
5468        );
5469    }
5470
5471    #[test]
5472    fn suppress_events_on_update_emits_no_events() {
5473        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5474        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5475            .unwrap();
5476        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice')")
5477            .unwrap();
5478        // drain the INSERT event
5479        let _ = queue_payloads(&rt, "evts");
5480        // Force pop to drain; simpler: just check new count after UPDATE
5481        rt.execute_query("QUEUE PURGE evts").unwrap();
5482
5483        rt.execute_query("UPDATE users SET name = 'Bob' WHERE id = 1 SUPPRESS EVENTS")
5484            .unwrap();
5485
5486        let events = queue_payloads(&rt, "evts");
5487        assert!(
5488            events.is_empty(),
5489            "SUPPRESS EVENTS must prevent UPDATE events"
5490        );
5491    }
5492
5493    #[test]
5494    fn suppress_events_on_delete_emits_no_events() {
5495        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5496        rt.execute_query(
5497            "CREATE TABLE users (id INT, name TEXT) WITH EVENTS (INSERT, DELETE) TO evts",
5498        )
5499        .unwrap();
5500        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5501            .unwrap();
5502
5503        rt.execute_query("DELETE FROM users WHERE id = 1 SUPPRESS EVENTS")
5504            .unwrap();
5505
5506        let events = queue_payloads(&rt, "evts");
5507        assert!(
5508            events.is_empty(),
5509            "SUPPRESS EVENTS must prevent DELETE events"
5510        );
5511    }
5512
5513    #[test]
5514    fn normal_insert_after_suppress_still_emits() {
5515        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
5516        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO evts")
5517            .unwrap();
5518
5519        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'Alice') SUPPRESS EVENTS")
5520            .unwrap();
5521        rt.execute_query("INSERT INTO users (id, name) VALUES (2, 'Bob')")
5522            .unwrap();
5523
5524        let events = queue_payloads(&rt, "evts");
5525        assert_eq!(
5526            events.len(),
5527            1,
5528            "only the non-suppressed INSERT should emit"
5529        );
5530        assert_eq!(
5531            events[0].get("id").and_then(crate::json::Value::as_u64),
5532            Some(2)
5533        );
5534    }
5535}