Skip to main content

reddb_server/application/
ports_impls_entity.rs

1use std::collections::HashMap;
2
3use crate::application::collection_contract_enforcer::{
4    normalize_row_update_assignment_with_plan, CollectionContractWriteEnforcer,
5};
6use crate::application::entity::{
7    AppliedEntityMutation, CreateDocumentInput, CreateKvInput, CreateTimeSeriesPointInput,
8    RowUpdateColumnRule, RowUpdateContractPlan,
9};
10use crate::application::ttl_payload::{
11    normalize_ttl_patch_operations, parse_top_level_ttl_metadata_entries,
12};
13use crate::json::{to_vec as json_to_vec, Value as JsonValue};
14use crate::storage::unified::MetadataValue;
15use reddb_types::Value;
16
17use super::*;
18
19const TREE_METADATA_PREFIX: &str = "red.tree.";
20const TREE_CHILD_EDGE_LABEL: &str = "TREE_CHILD";
21
22fn refresh_context_index(
23    db: &crate::storage::unified::devx::RedDB,
24    collection: &str,
25    id: crate::storage::EntityId,
26) -> RedDBResult<()> {
27    let store = db.store();
28    let Some(entity) = store.get(collection, id) else {
29        return Ok(());
30    };
31
32    store.context_index().index_entity(collection, &entity);
33    Ok(())
34}
35
36fn ensure_insert_entity_rls(
37    runtime: &RedDBRuntime,
38    collection: &str,
39    entity: &crate::storage::UnifiedEntity,
40) -> RedDBResult<()> {
41    if crate::runtime::rls_injection::entity_passes_rls_action(
42        runtime,
43        collection,
44        reddb_rql::ast::PolicyAction::Insert,
45        entity,
46    ) {
47        Ok(())
48    } else {
49        Err(crate::RedDBError::Query(format!(
50            "insert into collection '{collection}' denied by row-level security"
51        )))
52    }
53}
54
55/// Pull `(name, value)` pairs for every indexable field on an entity.
56/// Returns empty if field names are not recoverable here, so secondary-index
57/// maintenance has nothing to act on. Used by the delete + update paths.
58pub(crate) fn entity_row_fields_snapshot(
59    entity: &crate::storage::UnifiedEntity,
60) -> Vec<(String, Value)> {
61    let mut fields = match &entity.data {
62        crate::storage::EntityData::Row(row) => {
63            if let Some(named) = &row.named {
64                named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
65            } else if let Some(schema) = &row.schema {
66                schema
67                    .iter()
68                    .zip(row.columns.iter())
69                    .map(|(name, value)| (name.clone(), value.clone()))
70                    .collect()
71            } else {
72                Vec::new()
73            }
74        }
75        crate::storage::EntityData::Node(node) => node
76            .properties
77            .iter()
78            .map(|(k, v)| (k.clone(), v.clone()))
79            .collect(),
80        crate::storage::EntityData::Edge(edge) => edge
81            .properties
82            .iter()
83            .map(|(k, v)| (k.clone(), v.clone()))
84            .collect(),
85        _ => Vec::new(),
86    };
87    expand_binary_document_body_snapshot(&mut fields);
88    fields
89}
90
91fn expand_binary_document_body_snapshot(fields: &mut Vec<(String, Value)>) {
92    let Some(body_idx) = fields.iter().position(|(name, _)| name == "body") else {
93        return;
94    };
95    let Value::Json(bytes) = &fields[body_idx].1 else {
96        return;
97    };
98    let body_fields = crate::document_body::body_fields(bytes);
99    if let Some(body_json) = crate::document_body::decode_container_to_json(bytes) {
100        if let Ok(json_bytes) = crate::json::to_vec(&body_json) {
101            fields[body_idx].1 = Value::Json(json_bytes);
102        }
103    }
104    let Some(body_fields) = body_fields else {
105        return;
106    };
107    for (name, value) in body_fields {
108        if fields.iter().all(|(existing, _)| existing != &name) {
109            fields.push((name, value));
110        }
111    }
112}
113
114fn set_row_field(row: &mut crate::storage::unified::entity::RowData, name: &str, value: Value) {
115    if let Some(named) = row.named.as_mut() {
116        named.insert(name.to_string(), value);
117        return;
118    }
119
120    if let Some(schema) = row.schema.as_ref() {
121        if let Some(index) = schema.iter().position(|column| column == name) {
122            if let Some(slot) = row.columns.get_mut(index) {
123                *slot = value;
124                return;
125            }
126        }
127
128        let mut named = HashMap::with_capacity(schema.len().saturating_add(1));
129        for (column, current) in schema.iter().zip(row.columns.iter()) {
130            named.insert(column.clone(), current.clone());
131        }
132        named.insert(name.to_string(), value);
133        row.named = Some(named);
134        return;
135    }
136
137    let mut named = HashMap::with_capacity(1);
138    named.insert(name.to_string(), value);
139    row.named = Some(named);
140}
141
142fn collect_row_fields(row: &crate::storage::unified::entity::RowData) -> Vec<(String, Value)> {
143    if let Some(named) = row.named.as_ref() {
144        named
145            .iter()
146            .map(|(key, value)| (key.clone(), value.clone()))
147            .collect()
148    } else if let Some(schema) = row.schema.as_ref() {
149        schema
150            .iter()
151            .cloned()
152            .zip(row.columns.iter().cloned())
153            .collect()
154    } else {
155        Vec::new()
156    }
157}
158
159fn apply_row_field_assignments_raw<I>(
160    row: &mut crate::storage::unified::entity::RowData,
161    field_assignments: I,
162) where
163    I: IntoIterator<Item = (String, Value)>,
164{
165    for (column, value) in field_assignments {
166        set_row_field(row, &column, value);
167    }
168}
169
170fn apply_row_field_assignments_incremental<I>(
171    collection: &str,
172    row: &mut crate::storage::unified::entity::RowData,
173    field_assignments: I,
174    row_contract_plan: Option<&RowUpdateContractPlan>,
175) -> RedDBResult<()>
176where
177    I: IntoIterator<Item = (String, Value)>,
178{
179    for (column, value) in field_assignments {
180        let value = normalize_row_update_assignment_with_plan(
181            collection,
182            &column,
183            value,
184            row_contract_plan,
185        )?;
186
187        set_row_field(row, &column, value);
188    }
189
190    Ok(())
191}
192
193fn dedupe_modified_columns(mut modified_columns: Vec<String>) -> Vec<String> {
194    if modified_columns.is_empty() {
195        return modified_columns;
196    }
197
198    let mut unique = Vec::with_capacity(modified_columns.len());
199    for column in modified_columns.drain(..) {
200        if !unique
201            .iter()
202            .any(|existing: &String| existing.eq_ignore_ascii_case(&column))
203        {
204            unique.push(column);
205        }
206    }
207    unique
208}
209
210fn reject_document_array_position_path(path: &[String]) -> RedDBResult<()> {
211    if path.iter().any(|segment| segment.parse::<usize>().is_ok()) {
212        return Err(crate::RedDBError::Query(
213            "array positional document patch paths are unsupported; replace the array or full document body instead"
214                .to_string(),
215        ));
216    }
217    Ok(())
218}
219
220/// Reject a document body `set` whose path would traverse *through* an existing
221/// non-object value (e.g. `SET a.b = …` where `a` is already a scalar). This
222/// mirrors the HTTP JSON-patch contract: intermediate objects are created only
223/// where a slot is absent, never by silently clobbering a scalar. `body` is the
224/// pre-merge document body.
225fn reject_document_patch_path_through_scalar(body: &JsonValue, path: &[String]) -> RedDBResult<()> {
226    if path.len() < 2 {
227        return Ok(());
228    }
229    let scalar_error = |prefix: &str| {
230        crate::RedDBError::Query(format!(
231            "cannot set nested path '{}': '{}' is not an object; setting a path through a non-object value is unsupported — replace that value or the full document body instead",
232            path.join("."),
233            prefix
234        ))
235    };
236    let mut current = body;
237    // Walk the parent path (every segment but the leaf). Each container we index
238    // into must be an object; an absent slot is fine (the merge creates it).
239    for (idx, segment) in path[..path.len() - 1].iter().enumerate() {
240        let JsonValue::Object(map) = current else {
241            return Err(scalar_error(&path[..idx].join(".")));
242        };
243        match map.get(segment) {
244            Some(next) => current = next,
245            None => return Ok(()),
246        }
247    }
248    // `current` is now the leaf's parent container; it must be an object.
249    if !matches!(current, JsonValue::Object(_)) {
250        return Err(scalar_error(&path[..path.len() - 1].join(".")));
251    }
252    Ok(())
253}
254
255/// Apply document body `set`/`unset` operations, enforcing the shared document
256/// patch contract first: array-positional paths and paths that traverse through
257/// a scalar are rejected with clear errors before any mutation touches `body`.
258/// Used by both the SQL nested-`SET` executor and the HTTP JSON-patch operation
259/// path so the two surfaces stay consistent (ADR 0067).
260fn apply_document_body_patch_operations(
261    body: &mut JsonValue,
262    operations: &[PatchEntityOperation],
263) -> RedDBResult<()> {
264    for op in operations {
265        reject_document_array_position_path(&op.path)?;
266        if matches!(op.op, PatchEntityOperationType::Set) {
267            reject_document_patch_path_through_scalar(body, &op.path)?;
268        }
269    }
270    apply_patch_operations_to_json(body, operations).map_err(crate::RedDBError::Query)
271}
272
273fn document_body_from_row(
274    row: &crate::storage::unified::entity::RowData,
275) -> RedDBResult<JsonValue> {
276    match row.get_field("body") {
277        Some(Value::Json(bytes)) => {
278            // The stored body may be the native binary container (PRD-1398) or
279            // plain JSON; decode either form back to JSON.
280            if let Some(body) = crate::document_body::decode_container_to_json(bytes) {
281                Ok(body)
282            } else {
283                crate::json::from_slice(bytes).map_err(|err| {
284                    crate::RedDBError::Query(format!("failed to decode document body: {err}"))
285                })
286            }
287        }
288        Some(_) => Err(crate::RedDBError::Query(
289            "document body field must contain JSON".to_string(),
290        )),
291        None => Ok(JsonValue::Object(Default::default())),
292    }
293}
294
295fn document_body_from_assignment(value: &Value) -> RedDBResult<JsonValue> {
296    match value {
297        Value::Json(bytes) | Value::Blob(bytes) => crate::json::from_slice(bytes)
298            .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
299        Value::Text(text) => crate::json::from_str(text.as_ref())
300            .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
301        Value::Integer(value) => crate::json::from_str(&value.to_string())
302            .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
303        Value::UnsignedInteger(value) => crate::json::from_str(&value.to_string())
304            .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
305        Value::Float(value) => crate::json::from_str(&value.to_string())
306            .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
307        other => Err(crate::RedDBError::Query(format!(
308            "column 'body' expected JSON body, got {other:?}"
309        ))),
310    }
311}
312
313fn document_body_set_operation(column: &str, value: Value) -> PatchEntityOperation {
314    PatchEntityOperation {
315        op: PatchEntityOperationType::Set,
316        path: column.split('.').map(str::to_string).collect(),
317        value: Some(value.to_json()),
318    }
319}
320
321fn replace_document_fields_body(
322    fields: &mut HashMap<String, Value>,
323    body: JsonValue,
324    binary: bool,
325    modified_columns: &mut Vec<String>,
326) -> RedDBResult<()> {
327    modified_columns.push("body".to_string());
328
329    let old_keys: Vec<String> = fields
330        .keys()
331        .filter(|key| key.as_str() != "body")
332        .cloned()
333        .collect();
334    for key in old_keys {
335        fields.remove(&key);
336        modified_columns.push(key);
337    }
338
339    let body_bytes = crate::document_body::serialize_document_body(&body, binary)?;
340    fields.insert("body".to_string(), Value::Json(body_bytes));
341
342    Ok(())
343}
344
345fn ensure_no_reserved_document_body_fields(body: &JsonValue, collection: &str) -> RedDBResult<()> {
346    if let JsonValue::Object(map) = body {
347        crate::reserved_fields::ensure_no_reserved_public_item_fields(
348            map.keys().map(String::as_str),
349            &format!("document '{collection}'"),
350        )?;
351    }
352    Ok(())
353}
354
355fn replace_document_row_body(
356    row: &mut crate::storage::unified::entity::RowData,
357    body: JsonValue,
358    collection: &str,
359    binary: bool,
360    modified_columns: &mut Vec<String>,
361) -> RedDBResult<()> {
362    ensure_no_reserved_document_body_fields(&body, collection)?;
363    let fields = row.named.get_or_insert_with(Default::default);
364    replace_document_fields_body(fields, body, binary, modified_columns)?;
365
366    // Full body replacement rebuilds the document from the canonical `body`.
367    // Stale positional/schema values would otherwise leak back through JSON
368    // presentation even after the named map was pruned.
369    row.columns.clear();
370    row.schema = None;
371    Ok(())
372}
373
374fn document_merge_patch_payload(payload: &JsonValue) -> &JsonValue {
375    if let JsonValue::Object(object) = payload {
376        if object.len() == 1 {
377            if let Some(body) = object.get("body") {
378                return body;
379            }
380        }
381    }
382    payload
383}
384
385fn apply_document_json_merge_patch(body: &mut JsonValue, patch: &JsonValue) -> RedDBResult<()> {
386    if !matches!(patch, JsonValue::Object(_)) {
387        *body = patch.clone();
388        return Ok(());
389    }
390
391    if matches!(patch, JsonValue::Object(object) if object.is_empty()) {
392        if !matches!(body, JsonValue::Object(_)) {
393            *body = JsonValue::Object(Default::default());
394        }
395        return Ok(());
396    }
397
398    let mut operations = Vec::new();
399    collect_document_json_merge_patch_operations(body, Vec::new(), patch, &mut operations);
400    apply_patch_operations_to_json(body, &operations).map_err(crate::RedDBError::Query)
401}
402
403fn collect_document_json_merge_patch_operations(
404    target: &JsonValue,
405    path: Vec<String>,
406    patch: &JsonValue,
407    operations: &mut Vec<PatchEntityOperation>,
408) {
409    let JsonValue::Object(patch_object) = patch else {
410        operations.push(PatchEntityOperation {
411            op: PatchEntityOperationType::Set,
412            path,
413            value: Some(patch.clone()),
414        });
415        return;
416    };
417
418    for (key, value) in patch_object {
419        let mut child_path = path.clone();
420        child_path.push(key.clone());
421        match value {
422            JsonValue::Null => operations.push(PatchEntityOperation {
423                op: PatchEntityOperationType::Unset,
424                path: child_path,
425                value: None,
426            }),
427            JsonValue::Object(object) if object.is_empty() => {
428                let child_target = match target {
429                    JsonValue::Object(target_object) => target_object.get(key),
430                    _ => None,
431                };
432                if !matches!(child_target, Some(JsonValue::Object(_))) {
433                    operations.push(PatchEntityOperation {
434                        op: PatchEntityOperationType::Set,
435                        path: child_path,
436                        value: Some(JsonValue::Object(Default::default())),
437                    });
438                }
439            }
440            JsonValue::Object(_) => {
441                let child_target = match target {
442                    JsonValue::Object(target_object) => target_object.get(key),
443                    _ => None,
444                }
445                .unwrap_or(&JsonValue::Null);
446                collect_document_json_merge_patch_operations(
447                    child_target,
448                    child_path,
449                    value,
450                    operations,
451                );
452            }
453            _ => operations.push(PatchEntityOperation {
454                op: PatchEntityOperationType::Set,
455                path: child_path,
456                value: Some(value.clone()),
457            }),
458        }
459    }
460}
461
462impl RedDBRuntime {
463    pub(crate) fn apply_loaded_patch_entity_core(
464        &self,
465        collection: String,
466        mut entity: crate::storage::UnifiedEntity,
467        payload: JsonValue,
468        operations: Vec<PatchEntityOperation>,
469    ) -> RedDBResult<AppliedEntityMutation> {
470        let id = entity.id;
471        let epoch = self.vcs_writer_epoch(&collection)?;
472        let previous_xmax = epoch.map_or(entity.xmax, |epoch| entity.branch_xmax(epoch));
473        let operations = normalize_ttl_patch_operations(operations)?;
474        // Snapshot pre-patch row fields for the secondary-index hook —
475        // empty for non-row entities, which is the desired no-op.
476        let pre_mutation_fields = entity_row_fields_snapshot(&entity);
477
478        // Retain MVCC history for VCS and transactional graph contracts.
479        let patch_versions = epoch.is_some() || self.has_graph_contract(&collection);
480        let mut replaced_entity = patch_versions.then(|| entity.clone());
481
482        let db = self.db();
483        let store = db.store();
484        if store.get_collection(&collection).is_none() {
485            return Err(crate::RedDBError::NotFound(format!(
486                "collection not found: {collection}"
487            )));
488        }
489
490        let mut patch_metadata: Option<crate::storage::unified::Metadata> = None;
491        let mut metadata_changed = false;
492        let mut modified_columns: Vec<String> = Vec::new();
493        let mut context_index_dirty = false;
494        let mut graph_node_type: Option<String> = None;
495        let mut graph_edge_weight: Option<f32> = None;
496
497        let row_contract_timestamps = db
498            .collection_contract(&collection)
499            .map(|c| c.timestamps_enabled)
500            .unwrap_or(false);
501
502        match &mut entity.data {
503            crate::storage::EntityData::Row(row) => {
504                // PATCH mutates a named map. A recovered row may instead own
505                // its values under a shared schema; move those values into
506                // the map before applying only the requested field changes.
507                if row.named.is_none() {
508                    if let Some(schema) = row.schema.as_ref() {
509                        let fields = if schema.len() == row.columns.len() {
510                            schema
511                                .iter()
512                                .cloned()
513                                .zip(std::mem::take(&mut row.columns))
514                                .collect()
515                        } else {
516                            collect_row_fields(row).into_iter().collect()
517                        };
518                        row.named = Some(fields);
519                    }
520                }
521                let is_document_collection = db
522                    .collection_contract(&collection)
523                    .map(|contract| {
524                        contract.declared_model == crate::catalog::CollectionModel::Document
525                    })
526                    .unwrap_or(false);
527                let binary_body = self.binary_document_body_enabled();
528                let mut field_ops = Vec::new();
529                let mut metadata_ops = Vec::new();
530                let mut document_body_ops = Vec::new();
531                let mut document_body_replace: Option<JsonValue> = None;
532                let has_patch_operations = !operations.is_empty();
533
534                for mut op in operations {
535                    let Some(root) = op.path.first().map(String::as_str) else {
536                        return Err(crate::RedDBError::Query(
537                            "patch path cannot be empty".to_string(),
538                        ));
539                    };
540
541                    match root {
542                        "body" if is_document_collection => {
543                            if op.path.len() == 1 {
544                                match op.op {
545                                    PatchEntityOperationType::Set
546                                    | PatchEntityOperationType::Replace => {
547                                        let Some(value) = op.value.take() else {
548                                            return Err(crate::RedDBError::Query(
549                                                "document body replacement requires a value"
550                                                    .to_string(),
551                                            ));
552                                        };
553                                        document_body_replace = Some(value);
554                                    }
555                                    PatchEntityOperationType::Unset => {
556                                        return Err(crate::RedDBError::Query(
557                                            "document body cannot be unset; replace it instead"
558                                                .to_string(),
559                                        ));
560                                    }
561                                }
562                                continue;
563                            }
564                            if op.path.len() < 2 {
565                                return Err(crate::RedDBError::Query(
566                                    "document body patch paths require a nested key; use payload.body for full replacement"
567                                        .to_string(),
568                                ));
569                            }
570                            op.path.remove(0);
571                            reject_document_array_position_path(&op.path)?;
572                            document_body_ops.push(op);
573                        }
574                        "fields" | "named" => {
575                            if op.path.len() < 2 {
576                                return Err(crate::RedDBError::Query(
577                                    "patch path 'fields' requires a nested key".to_string(),
578                                ));
579                            }
580                            if row_contract_timestamps {
581                                let leaf = op.path.get(1).map(String::as_str);
582                                if matches!(leaf, Some("created_at") | Some("updated_at")) {
583                                    return Err(crate::RedDBError::Query(format!(
584                                        "collection '{}' manages '{}' automatically — do not set it in UPDATE",
585                                        collection,
586                                        leaf.unwrap_or("")
587                                    )));
588                                }
589                            }
590                            op.path.remove(0);
591                            field_ops.push(op);
592                        }
593                        "metadata" => {
594                            if op.path.len() < 2 {
595                                return Err(crate::RedDBError::Query(
596                                    "patch path 'metadata' requires a nested key".to_string(),
597                                ));
598                            }
599                            op.path.remove(0);
600                            metadata_ops.push(op);
601                        }
602                        _ => {
603                            return Err(crate::RedDBError::Query(format!(
604                                "unsupported patch target '{root}' for table rows. Use fields/*, metadata/*, or weight"
605                            )));
606                        }
607                    }
608                }
609
610                if document_body_replace.is_some() || !document_body_ops.is_empty() {
611                    context_index_dirty = true;
612                    let mut body = match document_body_replace {
613                        Some(body) => body,
614                        None => document_body_from_row(row)?,
615                    };
616                    apply_document_body_patch_operations(&mut body, &document_body_ops)?;
617                    replace_document_row_body(
618                        row,
619                        body,
620                        &collection,
621                        binary_body,
622                        &mut modified_columns,
623                    )?;
624                }
625
626                if is_document_collection && !has_patch_operations {
627                    let mut body = document_body_from_row(row)?;
628                    let previous_body = body.clone();
629                    apply_document_json_merge_patch(
630                        &mut body,
631                        document_merge_patch_payload(&payload),
632                    )?;
633                    if body != previous_body {
634                        context_index_dirty = true;
635                        replace_document_row_body(
636                            row,
637                            body,
638                            &collection,
639                            binary_body,
640                            &mut modified_columns,
641                        )?;
642                    }
643                }
644
645                if !field_ops.is_empty() {
646                    context_index_dirty = true;
647                    if is_document_collection {
648                        // Document fields are projections of the canonical
649                        // `body` JSON. Apply the assignment to the body so the
650                        // stored document remains single-source.
651                        let mut body = document_body_from_row(row)?;
652                        apply_patch_operations_to_json(&mut body, &field_ops)
653                            .map_err(crate::RedDBError::Query)?;
654                        replace_document_row_body(
655                            row,
656                            body,
657                            &collection,
658                            binary_body,
659                            &mut modified_columns,
660                        )?;
661                    } else {
662                        let named = row.named.get_or_insert_with(Default::default);
663                        for op in &field_ops {
664                            if let Some(col) = op.path.first() {
665                                modified_columns.push(col.clone());
666                            }
667                        }
668                        apply_patch_operations_to_storage_map(named, &field_ops)?;
669                    }
670                }
671
672                if let Some(fields) = payload
673                    .get("fields")
674                    .and_then(crate::json::Value::as_object)
675                {
676                    if row_contract_timestamps {
677                        for key in fields.keys() {
678                            if key == "created_at" || key == "updated_at" {
679                                return Err(crate::RedDBError::Query(format!(
680                                    "collection '{}' manages '{}' automatically — do not set it in UPDATE",
681                                    collection, key
682                                )));
683                            }
684                        }
685                    }
686                    context_index_dirty = true;
687                    if is_document_collection {
688                        // Mirror the `field_ops` path above: keep the canonical
689                        // `body` JSON as the single stored representation.
690                        let mut body = document_body_from_row(row)?;
691                        if let JsonValue::Object(map) = &mut body {
692                            for (key, value) in fields {
693                                map.insert(key.clone(), value.clone());
694                            }
695                        }
696                        replace_document_row_body(
697                            row,
698                            body,
699                            &collection,
700                            binary_body,
701                            &mut modified_columns,
702                        )?;
703                    } else {
704                        let named = row.named.get_or_insert_with(Default::default);
705                        for (key, value) in fields {
706                            modified_columns.push(key.clone());
707                            named.insert(key.clone(), json_to_storage_value(value)?);
708                        }
709                    }
710                }
711
712                if !metadata_ops.is_empty() {
713                    ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
714                    let metadata = patch_metadata.get_or_insert_with(|| {
715                        store.get_metadata(&collection, id).unwrap_or_default()
716                    });
717                    let mut metadata_json = metadata_to_json(metadata);
718                    apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
719                        .map_err(crate::RedDBError::Query)?;
720                    *metadata = metadata_from_json(&metadata_json)?;
721                    metadata_changed = true;
722                }
723
724                if !modified_columns.is_empty() || row_contract_timestamps {
725                    let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
726                    let current_fields = if let Some(named) = row.named.take() {
727                        named.into_iter().collect::<Vec<_>>()
728                    } else if let Some(schema) = row.schema.as_ref() {
729                        schema
730                            .iter()
731                            .cloned()
732                            .zip(row.columns.iter().cloned())
733                            .collect::<Vec<_>>()
734                    } else {
735                        Vec::new()
736                    };
737                    let normalized_fields = contract.normalize_update_fields(current_fields)?;
738                    if let Some(schema) = db.collection_contract_arc(&collection) {
739                        for column in schema
740                            .declared_columns
741                            .iter()
742                            .filter(|column| column.generated.is_some())
743                        {
744                            modified_columns.push(column.name.clone());
745                            context_index_dirty = true;
746                        }
747                    }
748                    if row_contract_timestamps {
749                        modified_columns.push("updated_at".to_string());
750                        context_index_dirty = true;
751                    }
752                    if contract.requires_uniqueness_check(&modified_columns) {
753                        contract.enforce_updated_row_uniqueness(
754                            &normalized_fields,
755                            (!pre_mutation_fields.is_empty())
756                                .then_some(pre_mutation_fields.as_slice()),
757                            Some(id),
758                        )?;
759                    }
760                    if self
761                        .index_store_ref()
762                        .touches_unique_index(&collection, &modified_columns)
763                    {
764                        self.enforce_unique_updates(
765                            &collection,
766                            &[(id, normalized_fields.clone())],
767                        )?;
768                    }
769                    row.named = Some(normalized_fields.into_iter().collect());
770                }
771            }
772            crate::storage::EntityData::Node(node) => {
773                let mut field_ops = Vec::new();
774                let mut metadata_ops = Vec::new();
775                let mut node_type_ops = Vec::new();
776
777                for mut op in operations {
778                    let Some(root) = op.path.first().map(String::as_str) else {
779                        return Err(crate::RedDBError::Query(
780                            "patch path cannot be empty".to_string(),
781                        ));
782                    };
783
784                    match root {
785                        "fields" | "properties" => {
786                            if op.path.len() < 2 {
787                                return Err(crate::RedDBError::Query(
788                                    "patch path 'fields' requires a nested key".to_string(),
789                                ));
790                            }
791                            op.path.remove(0);
792                            field_ops.push(op);
793                        }
794                        "metadata" => {
795                            if op.path.len() < 2 {
796                                return Err(crate::RedDBError::Query(
797                                    "patch path 'metadata' requires a nested key".to_string(),
798                                ));
799                            }
800                            op.path.remove(0);
801                            metadata_ops.push(op);
802                        }
803                        "node_type" => {
804                            if op.path.len() != 1 {
805                                return Err(crate::RedDBError::Query(
806                                    "patch path 'node_type' does not allow nested keys".to_string(),
807                                ));
808                            }
809                            op.path.clear();
810                            node_type_ops.push(op);
811                        }
812                        _ => {
813                            return Err(crate::RedDBError::Query(format!(
814                                "unsupported patch target '{root}' for graph nodes. Use fields/*, properties/*, node_type, or metadata/*"
815                            )));
816                        }
817                    }
818                }
819
820                for op in node_type_ops {
821                    context_index_dirty = true;
822                    let value = op.value.ok_or_else(|| {
823                        crate::RedDBError::Query("node_type operations require a value".to_string())
824                    })?;
825
826                    match op.op {
827                        PatchEntityOperationType::Unset => {
828                            return Err(crate::RedDBError::Query(
829                                "node_type cannot be unset through patch operations".to_string(),
830                            ));
831                        }
832                        PatchEntityOperationType::Set | PatchEntityOperationType::Replace => {
833                            let Some(node_type) = value.as_str() else {
834                                return Err(crate::RedDBError::Query(
835                                    "node_type operation requires a text value".to_string(),
836                                ));
837                            };
838                            graph_node_type = Some(node_type.to_string());
839                            modified_columns.push("node_type".to_string());
840                        }
841                    }
842                }
843
844                if !field_ops.is_empty() {
845                    context_index_dirty = true;
846                    apply_patch_operations_to_storage_map(&mut node.properties, &field_ops)?;
847                }
848
849                if let Some(fields) = payload
850                    .get("fields")
851                    .and_then(crate::json::Value::as_object)
852                {
853                    context_index_dirty = true;
854                    for (key, value) in fields {
855                        node.properties
856                            .insert(key.clone(), json_to_storage_value(value)?);
857                    }
858                }
859
860                if !metadata_ops.is_empty() {
861                    ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
862                    let metadata = patch_metadata.get_or_insert_with(|| {
863                        store.get_metadata(&collection, id).unwrap_or_default()
864                    });
865                    let mut metadata_json = metadata_to_json(metadata);
866                    apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
867                        .map_err(crate::RedDBError::Query)?;
868                    *metadata = metadata_from_json(&metadata_json)?;
869                    metadata_changed = true;
870                }
871            }
872            crate::storage::EntityData::Edge(edge) => {
873                let mut field_ops = Vec::new();
874                let mut metadata_ops = Vec::new();
875                let mut weight_ops = Vec::new();
876
877                for mut op in operations {
878                    let Some(root) = op.path.first().map(String::as_str) else {
879                        return Err(crate::RedDBError::Query(
880                            "patch path cannot be empty".to_string(),
881                        ));
882                    };
883
884                    match root {
885                        "fields" | "properties" => {
886                            if op.path.len() < 2 {
887                                return Err(crate::RedDBError::Query(
888                                    "patch path 'fields' requires a nested key".to_string(),
889                                ));
890                            }
891                            op.path.remove(0);
892                            field_ops.push(op);
893                        }
894                        "weight" => {
895                            if op.path.len() != 1 {
896                                return Err(crate::RedDBError::Query(
897                                    "patch path 'weight' does not allow nested keys".to_string(),
898                                ));
899                            }
900                            op.path.clear();
901                            weight_ops.push(op);
902                        }
903                        "metadata" => {
904                            if op.path.len() < 2 {
905                                return Err(crate::RedDBError::Query(
906                                    "patch path 'metadata' requires a nested key".to_string(),
907                                ));
908                            }
909                            op.path.remove(0);
910                            metadata_ops.push(op);
911                        }
912                        _ => {
913                            return Err(crate::RedDBError::Query(format!(
914                                "unsupported patch target '{root}' for graph edges. Use fields/*, weight, metadata/*"
915                            )));
916                        }
917                    }
918                }
919
920                if !field_ops.is_empty() {
921                    context_index_dirty = true;
922                    apply_patch_operations_to_storage_map(&mut edge.properties, &field_ops)?;
923                }
924
925                for op in weight_ops {
926                    context_index_dirty = true;
927                    let value = op.value.ok_or_else(|| {
928                        crate::RedDBError::Query("weight operations require a value".to_string())
929                    })?;
930
931                    match op.op {
932                        PatchEntityOperationType::Unset => {
933                            return Err(crate::RedDBError::Query(
934                                "weight cannot be unset through patch operations".to_string(),
935                            ));
936                        }
937                        PatchEntityOperationType::Set | PatchEntityOperationType::Replace => {
938                            let Some(weight) = value.as_f64() else {
939                                return Err(crate::RedDBError::Query(
940                                    "weight operation requires a numeric value".to_string(),
941                                ));
942                            };
943                            graph_edge_weight = Some(weight as f32);
944                            edge.weight = weight as f32;
945                            modified_columns.push("weight".to_string());
946                        }
947                    }
948                }
949
950                if let Some(fields) = payload
951                    .get("fields")
952                    .and_then(crate::json::Value::as_object)
953                {
954                    context_index_dirty = true;
955                    for (key, value) in fields {
956                        edge.properties
957                            .insert(key.clone(), json_to_storage_value(value)?);
958                    }
959                }
960
961                if !metadata_ops.is_empty() {
962                    ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
963                    let metadata = patch_metadata.get_or_insert_with(|| {
964                        store.get_metadata(&collection, id).unwrap_or_default()
965                    });
966                    let mut metadata_json = metadata_to_json(metadata);
967                    apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
968                        .map_err(crate::RedDBError::Query)?;
969                    *metadata = metadata_from_json(&metadata_json)?;
970                    metadata_changed = true;
971                }
972            }
973            crate::storage::EntityData::Vector(vector) => {
974                let mut field_ops = Vec::new();
975                let mut metadata_ops = Vec::new();
976
977                for mut op in operations {
978                    let Some(root) = op.path.first().map(String::as_str) else {
979                        return Err(crate::RedDBError::Query(
980                            "patch path cannot be empty".to_string(),
981                        ));
982                    };
983
984                    match root {
985                        "fields" => {
986                            if op.path.len() < 2 {
987                                return Err(crate::RedDBError::Query(
988                                    "patch path 'fields' requires a nested key".to_string(),
989                                ));
990                            }
991                            op.path.remove(0);
992                            let Some(target) = op.path.first().map(String::as_str) else {
993                                return Err(crate::RedDBError::Query(
994                                    "patch path requires a target under fields".to_string(),
995                                ));
996                            };
997                            if !matches!(target, "dense" | "content" | "sparse") {
998                                return Err(crate::RedDBError::Query(format!(
999                                    "unsupported vector patch target '{target}'"
1000                                )));
1001                            }
1002                            field_ops.push(op);
1003                        }
1004                        "metadata" => {
1005                            if op.path.len() < 2 {
1006                                return Err(crate::RedDBError::Query(
1007                                    "patch path 'metadata' requires a nested key".to_string(),
1008                                ));
1009                            }
1010                            op.path.remove(0);
1011                            metadata_ops.push(op);
1012                        }
1013                        _ => {
1014                            return Err(crate::RedDBError::Query(format!(
1015                                "unsupported patch target '{root}' for vectors. Use fields/* or metadata/*"
1016                            )));
1017                        }
1018                    }
1019                }
1020
1021                if !field_ops.is_empty() {
1022                    context_index_dirty = true;
1023                    apply_patch_operations_to_vector_fields(vector, &field_ops)?;
1024                }
1025
1026                if let Some(fields) = payload
1027                    .get("fields")
1028                    .and_then(crate::json::Value::as_object)
1029                {
1030                    context_index_dirty = true;
1031                    if let Some(content) =
1032                        fields.get("content").and_then(crate::json::Value::as_str)
1033                    {
1034                        vector.content = Some(content.to_string());
1035                    }
1036                    if let Some(dense) = fields.get("dense") {
1037                        vector.dense = dense
1038                            .as_array()
1039                            .ok_or_else(|| {
1040                                crate::RedDBError::Query(
1041                                    "field 'dense' must be an array".to_string(),
1042                                )
1043                            })?
1044                            .iter()
1045                            .map(|value| {
1046                                value.as_f64().map(|value| value as f32).ok_or_else(|| {
1047                                    crate::RedDBError::Query(
1048                                        "field 'dense' must contain only numbers".to_string(),
1049                                    )
1050                                })
1051                            })
1052                            .collect::<Result<Vec<_>, _>>()?;
1053                    }
1054                }
1055
1056                if !metadata_ops.is_empty() {
1057                    ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
1058                    let metadata = patch_metadata.get_or_insert_with(|| {
1059                        store.get_metadata(&collection, id).unwrap_or_default()
1060                    });
1061                    let mut metadata_json = metadata_to_json(metadata);
1062                    apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
1063                        .map_err(crate::RedDBError::Query)?;
1064                    *metadata = metadata_from_json(&metadata_json)?;
1065                    metadata_changed = true;
1066                }
1067            }
1068            crate::storage::EntityData::TimeSeries(_)
1069            | crate::storage::EntityData::QueueMessage(_) => {
1070                return Err(crate::RedDBError::Query(
1071                    "patch operations are not supported for TimeSeries or QueueMessage entities"
1072                        .to_string(),
1073                ));
1074            }
1075        }
1076
1077        if let Some(node_type) = graph_node_type {
1078            if let crate::storage::EntityKind::GraphNode(node) = &mut entity.kind {
1079                node.node_type = node_type;
1080            }
1081        }
1082        if let Some(weight) = graph_edge_weight {
1083            if let crate::storage::EntityKind::GraphEdge(edge) = &mut entity.kind {
1084                edge.weight = (weight * 1000.0) as u32;
1085            }
1086        }
1087
1088        if let Some(metadata) = payload
1089            .get("metadata")
1090            .and_then(crate::json::Value::as_object)
1091        {
1092            let patch_metadata = patch_metadata
1093                .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default());
1094            for (key, value) in metadata {
1095                ensure_non_tree_reserved_metadata_key(key)?;
1096                patch_metadata.set(key.clone(), json_to_metadata_value(value)?);
1097            }
1098            metadata_changed = true;
1099        }
1100
1101        for (key, value) in parse_top_level_ttl_metadata_entries(&payload)? {
1102            let patch_metadata = patch_metadata
1103                .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default());
1104            if matches!(value, crate::storage::unified::MetadataValue::Null) {
1105                patch_metadata.remove(&key);
1106            } else {
1107                patch_metadata.set(key, value);
1108            }
1109            metadata_changed = true;
1110        }
1111
1112        entity.field_bloom =
1113            crate::storage::unified::entity::compute_entity_field_bloom(&entity.data);
1114        entity.updated_at = std::time::SystemTime::now()
1115            .duration_since(std::time::UNIX_EPOCH)
1116            .unwrap_or_default()
1117            .as_secs();
1118
1119        // Versioned PATCH: re-stamp the merged post-image as a fresh
1120        // physical version keyed on the same logical_id, and close the
1121        // prior version's xmax at the same xid. `install_versioned_*`
1122        // in persist installs the new row and tombstones the old one;
1123        // `record_pending_versioned_update` arms first-committer-wins.
1124        let current_xid = self.current_xid();
1125        let autocommit_update = (patch_versions && current_xid.is_none()).then(|| {
1126            crate::application::entity::AutocommitUpdate::new(self.snapshot_manager(), &collection)
1127        });
1128        let versioned_update_xid = if patch_versions {
1129            current_xid.or_else(|| autocommit_update.as_ref().map(|update| update.xid))
1130        } else {
1131            None
1132        };
1133        if let Some(xid) = versioned_update_xid {
1134            let logical_id = entity.logical_id();
1135            entity.id = store.next_entity_id();
1136            entity.set_logical_id(logical_id);
1137            entity.set_xmin(xid);
1138            entity.set_xmax(0);
1139            self.stamp_vcs_creation(&collection, &mut entity)?;
1140            if let Some(old) = replaced_entity.as_mut() {
1141                old.set_xmax(xid);
1142            }
1143        }
1144
1145        modified_columns = dedupe_modified_columns(modified_columns);
1146
1147        Ok(AppliedEntityMutation {
1148            autocommit_update,
1149            id: entity.id,
1150            collection,
1151            entity,
1152            metadata: patch_metadata,
1153            modified_columns,
1154            persist_metadata: metadata_changed,
1155            context_index_dirty,
1156            replaced_entity,
1157            replaced_entity_previous_xmax: previous_xmax,
1158            pre_mutation_fields,
1159        })
1160    }
1161
1162    pub(crate) fn apply_loaded_sql_update_row_core(
1163        &self,
1164        collection: String,
1165        mut entity: crate::storage::UnifiedEntity,
1166        static_field_assignments: &[(String, Value)],
1167        dynamic_field_assignments: Vec<(String, Value)>,
1168        static_metadata_assignments: &[(String, MetadataValue)],
1169        dynamic_metadata_assignments: Vec<(String, MetadataValue)>,
1170        row_contract_plan: Option<&RowUpdateContractPlan>,
1171        row_modified_columns_template: &[String],
1172        row_touches_unique_columns: bool,
1173    ) -> RedDBResult<AppliedEntityMutation> {
1174        let id = entity.id;
1175        let epoch = self.vcs_writer_epoch(&collection)?;
1176        let previous_xmax = epoch.map_or(entity.xmax, |epoch| entity.branch_xmax(epoch));
1177        let db = self.db();
1178        let store = db.store();
1179        let Some(_) = store.get_collection(&collection) else {
1180            return Err(crate::RedDBError::NotFound(format!(
1181                "collection not found: {collection}"
1182            )));
1183        };
1184
1185        let mut replaced_entity = Some(entity.clone());
1186
1187        let mut patch_metadata: Option<crate::storage::unified::Metadata> = None;
1188        let row_contract_timestamps = row_contract_plan
1189            .map(|plan| plan.timestamps_enabled)
1190            .unwrap_or(false);
1191        let mut metadata_changed = false;
1192        let mut modified_columns = row_modified_columns_template.to_vec();
1193        let mut context_index_dirty = !modified_columns.is_empty();
1194
1195        // Snapshot OLD field values BEFORE applying the assignments —
1196        // the secondary-index maintenance hook needs both before/after to
1197        // delete-then-insert under changed indexed columns.
1198        let pre_mutation_fields = entity_row_fields_snapshot(&entity);
1199
1200        let crate::storage::EntityData::Row(row) = &mut entity.data else {
1201            return Err(crate::RedDBError::Query(
1202                "SQL row update fast path requires a row entity".to_string(),
1203            ));
1204        };
1205
1206        let _ = row_contract_plan;
1207
1208        // Documents store the full JSON under the `body` column. Legacy rows
1209        // also promote top-level keys for filtering, while binary body mode
1210        // keeps `body` as the single source of truth. Reflect non-body SET
1211        // assignments into `body` as patch operations so dotted paths update
1212        // nested JSON instead of becoming literal top-level keys.
1213        let is_document_collection = db
1214            .collection_contract(&collection)
1215            .map(|contract| contract.declared_model == crate::catalog::CollectionModel::Document)
1216            .unwrap_or(false);
1217        let kv_key = if row.get_field("value").is_some() || row.columns.len() >= 2 {
1218            row.get_field("key")
1219                .cloned()
1220                .or_else(|| row.columns.first().cloned())
1221        } else {
1222            None
1223        };
1224        if is_document_collection {
1225            // #1366: when a SET assigns to `body`, treat it as a FULL REPLACE of
1226            // the stored document — drop other column assignments, the new body
1227            // is the single source of truth.
1228            let body_assignment = static_field_assignments
1229                .iter()
1230                .chain(dynamic_field_assignments.iter())
1231                .rev()
1232                .find(|(column, _)| column == "body")
1233                .cloned();
1234
1235            match body_assignment {
1236                Some((_, value)) => {
1237                    let body = document_body_from_assignment(&value)?;
1238                    replace_document_row_body(
1239                        row,
1240                        body,
1241                        &collection,
1242                        self.binary_document_body_enabled(),
1243                        &mut modified_columns,
1244                    )?;
1245                    context_index_dirty = true;
1246                }
1247                None => {
1248                    // #1365: no `body` assignment — fall back to nested-path
1249                    // partial update via document_body_set_operation.
1250                    let mut static_row_assignments = Vec::new();
1251                    let mut dynamic_row_assignments = Vec::new();
1252                    let mut document_body_ops = Vec::new();
1253                    for (column, value) in static_field_assignments.iter().cloned() {
1254                        if column == "body" {
1255                            static_row_assignments.push((column, value));
1256                        } else {
1257                            document_body_ops.push(document_body_set_operation(&column, value));
1258                        }
1259                    }
1260                    for (column, value) in dynamic_field_assignments {
1261                        if column == "body" {
1262                            dynamic_row_assignments.push((column, value));
1263                        } else {
1264                            document_body_ops.push(document_body_set_operation(&column, value));
1265                        }
1266                    }
1267                    apply_row_field_assignments_raw(row, static_row_assignments);
1268                    apply_row_field_assignments_raw(row, dynamic_row_assignments);
1269                    if !document_body_ops.is_empty() {
1270                        let mut body = document_body_from_row(row)?;
1271                        apply_document_body_patch_operations(&mut body, &document_body_ops)?;
1272                        replace_document_row_body(
1273                            row,
1274                            body,
1275                            &collection,
1276                            self.binary_document_body_enabled(),
1277                            &mut modified_columns,
1278                        )?;
1279                        context_index_dirty = true;
1280                    }
1281                }
1282            }
1283        } else {
1284            // Non-document collection: every assignment is a regular row column.
1285            let mut all_assignments: Vec<(String, Value)> = static_field_assignments.to_vec();
1286            all_assignments.extend(dynamic_field_assignments);
1287            apply_row_field_assignments_raw(row, all_assignments);
1288            if let Some(key) = kv_key {
1289                set_row_field(row, "key", key);
1290            }
1291        }
1292
1293        for (key, value) in static_metadata_assignments
1294            .iter()
1295            .cloned()
1296            .chain(dynamic_metadata_assignments)
1297        {
1298            ensure_non_tree_reserved_metadata_key(&key)?;
1299            patch_metadata
1300                .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default())
1301                .set(key, value);
1302            metadata_changed = true;
1303        }
1304
1305        if !modified_columns.is_empty() || row_contract_timestamps {
1306            let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
1307            if row_contract_timestamps {
1308                context_index_dirty = true;
1309                set_row_field(row, "updated_at", contract.managed_timestamp_value());
1310                modified_columns.push("updated_at".to_string());
1311            }
1312            let expression_contract = if row_contract_plan.is_some_and(|plan| plan.has_expressions)
1313            {
1314                db.collection_contract_arc(&collection)
1315            } else {
1316                None
1317            };
1318            if let Some(schema) = &expression_contract {
1319                let normalized = contract.normalize_update_fields(collect_row_fields(row))?;
1320                for column in schema
1321                    .declared_columns
1322                    .iter()
1323                    .filter(|column| column.generated.is_some())
1324                {
1325                    modified_columns.push(column.name.clone());
1326                }
1327                for (name, value) in normalized {
1328                    set_row_field(row, &name, value);
1329                }
1330                context_index_dirty = true;
1331            }
1332            if row_touches_unique_columns || expression_contract.is_some() {
1333                let current_fields = collect_row_fields(row);
1334                contract.enforce_updated_row_uniqueness(
1335                    &current_fields,
1336                    (!pre_mutation_fields.is_empty()).then_some(pre_mutation_fields.as_slice()),
1337                    Some(id),
1338                )?;
1339            }
1340        }
1341
1342        entity.field_bloom =
1343            crate::storage::unified::entity::compute_entity_field_bloom(&entity.data);
1344        entity.updated_at = std::time::SystemTime::now()
1345            .duration_since(std::time::UNIX_EPOCH)
1346            .unwrap_or_default()
1347            .as_secs();
1348
1349        let current_xid = self.current_xid();
1350        let autocommit_update = current_xid.is_none().then(|| {
1351            crate::application::entity::AutocommitUpdate::new(self.snapshot_manager(), &collection)
1352        });
1353        let versioned_update_xid =
1354            current_xid.or_else(|| autocommit_update.as_ref().map(|update| update.xid));
1355        if let Some(xid) = versioned_update_xid {
1356            let logical_id = entity.logical_id();
1357            entity.id = store.next_entity_id();
1358            entity.set_logical_id(logical_id);
1359            entity.set_xmin(xid);
1360            entity.set_xmax(0);
1361            self.stamp_vcs_creation(&collection, &mut entity)?;
1362            if let Some(old) = replaced_entity.as_mut() {
1363                old.set_xmax(xid);
1364            }
1365        }
1366
1367        modified_columns = dedupe_modified_columns(modified_columns);
1368
1369        Ok(AppliedEntityMutation {
1370            autocommit_update,
1371            id: entity.id,
1372            collection,
1373            entity,
1374            metadata: patch_metadata,
1375            modified_columns,
1376            persist_metadata: metadata_changed,
1377            context_index_dirty,
1378            replaced_entity,
1379            replaced_entity_previous_xmax: previous_xmax,
1380            pre_mutation_fields,
1381        })
1382    }
1383
1384    pub(crate) fn persist_applied_entity_mutations(
1385        &self,
1386        applied: &[AppliedEntityMutation],
1387    ) -> RedDBResult<()> {
1388        if applied.is_empty() {
1389            return Ok(());
1390        }
1391
1392        let store = self.db().store();
1393        // Fence the in-memory change and its WAL append together. Otherwise a
1394        // checkpoint can copy a new transaction's rows or truncate a concurrent
1395        // autocommit's WAL before those rows belong to its frozen generation.
1396        let _publication = store.vault_publication_lock.lock();
1397        let collection = &applied[0].collection;
1398        let Some(manager) = store.get_collection(collection) else {
1399            return Err(crate::RedDBError::NotFound(format!(
1400                "collection not found: {collection}"
1401            )));
1402        };
1403
1404        let epoch = self.vcs_writer_epoch(collection)?;
1405        if epoch.is_some_and(|epoch| {
1406            applied.iter().any(|item| {
1407                item.entity
1408                    .branch_version()
1409                    .is_none_or(|version| version.origin != epoch)
1410            })
1411        }) {
1412            return Err(crate::RedDBError::InvalidOperation(
1413                "branch changed during update; retry the statement".into(),
1414            ));
1415        }
1416        let mut ordinary = Vec::with_capacity(applied.len());
1417        for item in applied {
1418            if let Some(old_version) = item.replaced_entity.as_ref() {
1419                let old_version = if let Some(epoch) = epoch {
1420                    let mut current = manager
1421                        .try_get(old_version.id, usize::MAX)?
1422                        .ok_or_else(|| crate::RedDBError::NotFound(old_version.id.to_string()))?;
1423                    current.set_branch_xmax(epoch, item.entity.xmin);
1424                    current
1425                } else {
1426                    old_version.clone()
1427                };
1428                if item.autocommit_update.is_some()
1429                    && crate::storage::UnifiedStore::deferred_store_wal_capture_active()
1430                    && !crate::runtime::mvcc_lifecycle::autocommit_update_capture_available()
1431                {
1432                    return Err(crate::RedDBError::Internal(
1433                        "missing autocommit update WAL scope".into(),
1434                    ));
1435                }
1436                if let Err(error) = store.install_versioned_table_row_update(
1437                    collection,
1438                    old_version.clone(),
1439                    item.entity.clone(),
1440                    if item.persist_metadata {
1441                        item.metadata.as_ref()
1442                    } else {
1443                        None
1444                    },
1445                ) {
1446                    if let Some(update) = &item.autocommit_update {
1447                        let changed = manager.get_with(old_version.id, |old| {
1448                            epoch.map_or(old.xmax, |epoch| old.branch_xmax(epoch)) == update.xid
1449                        }) == Some(true);
1450                        if changed {
1451                            let topology =
1452                                self.index_store_ref().collection_topology_lock(collection);
1453                            if let Err(undo) = self.revive_versioned_update(
1454                                collection,
1455                                old_version.id,
1456                                item.entity.id,
1457                                update.xid,
1458                                item.replaced_entity_previous_xmax,
1459                                topology.read_recursive(),
1460                            ) {
1461                                tracing::error!(%undo, "failed to undo incomplete autocommit update");
1462                            }
1463                        }
1464                    }
1465                    return Err(crate::RedDBError::Internal(error.to_string()));
1466                }
1467                if let Some(update) = &item.autocommit_update {
1468                    crate::runtime::mvcc_lifecycle::publish_autocommit_update(self, item, update);
1469                }
1470                if self.current_xid().is_some() {
1471                    self.record_pending_versioned_update(
1472                        crate::runtime::impl_core::current_connection_id(),
1473                        collection,
1474                        old_version.id,
1475                        item.entity.id,
1476                        item.entity.xmin,
1477                        item.replaced_entity_previous_xmax,
1478                    );
1479                }
1480            } else {
1481                ordinary.push(item);
1482            }
1483        }
1484        if ordinary.is_empty() {
1485            return Ok(());
1486        }
1487
1488        manager
1489            .update_hot_batch_with_metadata(ordinary.iter().map(|item| {
1490                (
1491                    &item.entity,
1492                    item.modified_columns.as_slice(),
1493                    if item.persist_metadata {
1494                        item.metadata.as_ref()
1495                    } else {
1496                        None
1497                    },
1498                )
1499            }))
1500            .map_err(|err| crate::RedDBError::Query(err.to_string()))?;
1501
1502        // PG-HOT-like fast path: segment in-place is done; when no
1503        // mutation touches a secondary-indexed column AND no metadata
1504        // payload needs to be folded into a B-tree record, skip the
1505        // in-line B-tree upsert. The WAL still records the update
1506        // (durability preserved; recovery replay rebuilds the B-tree),
1507        // and `manager.get()` prefers the live segment over the
1508        // B-tree for reads — so the short-circuit is invisible to
1509        // callers. See `persist_entities_to_pager_wal_only`.
1510        let indexed_cols = self
1511            .index_store_ref()
1512            .indexed_columns_set(collection.as_str());
1513        let all_hot = !indexed_cols.is_empty()
1514            && ordinary.iter().all(|item| {
1515                !item.persist_metadata
1516                    && !item
1517                        .modified_columns
1518                        .iter()
1519                        .any(|c| indexed_cols.contains(c))
1520            })
1521            || indexed_cols.is_empty() && ordinary.iter().all(|item| !item.persist_metadata);
1522
1523        // Pass `&[&UnifiedEntity]` — no per-entity clone. The SQL UPDATE
1524        // inner loop hands us `applied` which already owns the post-image
1525        // entity; all we need for the persist path is a read borrow.
1526        let entity_refs: Vec<&crate::storage::UnifiedEntity> =
1527            ordinary.iter().map(|item| &item.entity).collect();
1528        let persist_fn = if all_hot {
1529            crate::storage::unified::UnifiedStore::persist_entity_refs_to_pager_wal_only
1530        } else {
1531            crate::storage::unified::UnifiedStore::persist_entity_refs_to_pager
1532        };
1533        persist_fn(store.as_ref(), collection, &entity_refs)
1534            .map_err(|err| crate::RedDBError::Internal(err.to_string()))
1535    }
1536
1537    pub(crate) fn flush_applied_entity_mutation(
1538        &self,
1539        applied: &AppliedEntityMutation,
1540        topology_guard: parking_lot::RwLockReadGuard<'_, ()>,
1541    ) -> RedDBResult<()> {
1542        let store = self.db().store();
1543        if applied.context_index_dirty {
1544            store
1545                .context_index()
1546                .index_entity(&applied.collection, &applied.entity);
1547        }
1548        // Secondary-index maintenance for SQL UPDATE / JSON-Patch flows.
1549        // Skip when pre_mutation_fields is empty (entity wasn't a row, or
1550        // didn't carry recoverable column names) — there's nothing to
1551        // delete-then-insert in that case.
1552        //
1553        // Also build the CDC damage vector here so downstream consumers
1554        // see which columns changed without re-diffing.
1555        let mut changed_columns: Option<Vec<String>> = None;
1556        if !applied.pre_mutation_fields.is_empty() {
1557            let post = entity_row_fields_snapshot(&applied.entity);
1558            if !post.is_empty() {
1559                let damage = crate::application::entity::row_damage_vector(
1560                    &applied.pre_mutation_fields,
1561                    &post,
1562                );
1563                if !damage.is_empty() {
1564                    changed_columns = Some(
1565                        damage
1566                            .touched_columns()
1567                            .into_iter()
1568                            .map(str::to_string)
1569                            .collect(),
1570                    );
1571                }
1572
1573                // HOT-like fast path (P3.T2/T3): when no modified
1574                // column is covered by a secondary index, skip the
1575                // `index_entity_update` call entirely. The function
1576                // would short-circuit internally, but the call still
1577                // reads the registry lock + walks the damage vector
1578                // — avoiding it saves a few microseconds per UPDATE.
1579                // Page-local replace + t_ctid chain support (true
1580                // HOT) lives in a follow-up storage spec.
1581                // Use the parent-expanded set so that dot-path indexes
1582                // (e.g. "body.service.tier") are triggered when the root
1583                // field ("body") appears in modified_columns.
1584                let indexed_cols: std::collections::HashSet<String> = self
1585                    .index_store_ref()
1586                    .indexed_columns_set_with_parents(applied.collection.as_str());
1587                // Single-source documents keep promoted index columns in the
1588                // body — surface them so the index sees the value move (a no-op
1589                // for ordinary stored columns).
1590                let pre_index_fields = self
1591                    .index_store_ref()
1592                    .augment_body_derived_index_fields(&applied.pre_mutation_fields, &indexed_cols);
1593                let post_index_fields = self
1594                    .index_store_ref()
1595                    .augment_body_derived_index_fields(&post, &indexed_cols);
1596                let modified_cols: std::collections::HashSet<String> =
1597                    crate::application::entity::row_damage_vector(
1598                        &pre_index_fields,
1599                        &post_index_fields,
1600                    )
1601                    .touched_columns()
1602                    .into_iter()
1603                    .map(str::to_string)
1604                    .collect();
1605                if let Some(old_version) = applied.replaced_entity.as_ref() {
1606                    let old_index_fields: Vec<(String, Value)> = pre_index_fields
1607                        .iter()
1608                        .filter(|(col, _)| indexed_cols.contains(col))
1609                        .cloned()
1610                        .collect();
1611                    let new_index_fields: Vec<(String, Value)> = post_index_fields
1612                        .iter()
1613                        .filter(|(col, _)| indexed_cols.contains(col))
1614                        .cloned()
1615                        .collect();
1616                    if !old_index_fields.is_empty() {
1617                        self.index_store_ref()
1618                            .index_entity_delete(
1619                                &applied.collection,
1620                                old_version.id,
1621                                &old_index_fields,
1622                            )
1623                            .map_err(crate::RedDBError::Internal)?;
1624                    }
1625                    if !new_index_fields.is_empty() {
1626                        self.index_store_ref()
1627                            .index_entity_insert(
1628                                &applied.collection,
1629                                applied.entity.id,
1630                                &new_index_fields,
1631                            )
1632                            .map_err(crate::RedDBError::Internal)?;
1633                    }
1634                } else {
1635                    let decision = crate::storage::engine::hot_update::decide(
1636                        &crate::storage::engine::hot_update::HotUpdateInputs {
1637                            collection: applied.collection.as_str(),
1638                            indexed_columns: &indexed_cols,
1639                            modified_columns: &modified_cols,
1640                            // The storage layer currently handles fit via
1641                            // the segment abstraction; we bypass the
1642                            // page-size check here.
1643                            new_tuple_size: 0,
1644                            page_free_space: usize::MAX,
1645                        },
1646                    );
1647                    if !decision.can_hot {
1648                        self.index_store_ref()
1649                            .index_entity_update(
1650                                &applied.collection,
1651                                applied.id,
1652                                &pre_index_fields,
1653                                &post_index_fields,
1654                            )
1655                            .map_err(crate::RedDBError::Internal)?;
1656                    } else {
1657                        // F-04: `applied.collection` is tenant-supplied;
1658                        // strip CR/LF/control bytes via the LogField
1659                        // escaper (ADR 0010).
1660                        tracing::debug!(
1661                            collection = %reddb_wire::audit_safe_log_field(&applied.collection),
1662                            "hot_update fast-path: skipped index_entity_update"
1663                        );
1664                    }
1665                }
1666            }
1667        }
1668        drop(topology_guard);
1669        #[cfg(test)]
1670        self.index_store_ref().mutation_test_hook(
1671            &applied.collection,
1672            crate::runtime::MutationTestPhase::BeforeEvents,
1673        );
1674        self.cdc_emit_prebuilt_with_columns(
1675            crate::replication::cdc::ChangeOperation::Update,
1676            &applied.collection,
1677            &applied.entity,
1678            "entity",
1679            applied.metadata.as_ref(),
1680            true,
1681            changed_columns,
1682        )?;
1683        Ok(())
1684    }
1685
1686    pub(crate) fn apply_loaded_patch_entity(
1687        &self,
1688        collection: String,
1689        entity: crate::storage::UnifiedEntity,
1690        payload: JsonValue,
1691        operations: Vec<PatchEntityOperation>,
1692        topology_guard: parking_lot::RwLockReadGuard<'_, ()>,
1693    ) -> RedDBResult<CreateEntityOutput> {
1694        let applied =
1695            self.apply_loaded_patch_entity_core(collection, entity, payload, operations)?;
1696        if !crate::runtime::rls_injection::entity_passes_rls_action(
1697            self,
1698            &applied.collection,
1699            reddb_rql::ast::PolicyAction::Update,
1700            &applied.entity,
1701        ) {
1702            return Err(crate::RedDBError::NotFound("entity not found".to_string()));
1703        }
1704        self.validate_graph_changes(
1705            &applied.collection,
1706            &[&applied.entity],
1707            &[applied
1708                .replaced_entity
1709                .as_ref()
1710                .map_or(applied.id, |entity| entity.id)],
1711        )?;
1712        let _reservation = self.admit_entity_mutation(&applied)?;
1713        self.persist_applied_entity_mutations(std::slice::from_ref(&applied))?;
1714        #[cfg(test)]
1715        self.index_store_ref().mutation_test_hook(
1716            &applied.collection,
1717            crate::runtime::MutationTestPhase::StoragePublished,
1718        );
1719        self.flush_applied_entity_mutation(&applied, topology_guard)?;
1720        Ok(CreateEntityOutput {
1721            id: applied.entity.logical_id(),
1722            entity: Some(public_document_entity(applied.entity)),
1723        })
1724    }
1725}
1726
1727/// Shape the canonical binary-body document into the public response entity.
1728/// The stored `body` is the single source of truth (RDOC binary container),
1729/// but callers read the returned entity two ways, so the response satisfies
1730/// both: top-level body fields are surfaced into `named` (mirroring the GET
1731/// presentation derive in `named_fields_json`), and `body` itself is decoded
1732/// back to plain JSON. Derivation runs against the binary container first,
1733/// then `body` is replaced with its JSON form. This only reshapes the
1734/// returned copy — persistence already happened against the binary body.
1735fn public_document_entity(
1736    mut entity: crate::storage::UnifiedEntity,
1737) -> crate::storage::UnifiedEntity {
1738    let crate::storage::EntityData::Row(row) = &mut entity.data else {
1739        return entity;
1740    };
1741    let Some(named) = row.named.as_mut() else {
1742        return entity;
1743    };
1744    let Some(Value::Json(bytes)) = named.get("body") else {
1745        return entity;
1746    };
1747    let bytes = bytes.clone();
1748    if let Some(fields) = crate::document_body::body_fields(&bytes) {
1749        for (name, value) in fields {
1750            named.entry(name).or_insert(value);
1751        }
1752    }
1753    if let Some(body_json) = crate::document_body::decode_container_to_json(&bytes) {
1754        if let Ok(json_bytes) = crate::json::to_vec(&body_json) {
1755            named.insert("body".to_string(), Value::Json(json_bytes));
1756        }
1757    }
1758    entity
1759}
1760
1761fn ensure_non_tree_reserved_metadata_patch_paths(
1762    operations: &[PatchEntityOperation],
1763) -> RedDBResult<()> {
1764    for operation in operations {
1765        let Some(key) = operation.path.first().map(String::as_str) else {
1766            continue;
1767        };
1768        ensure_non_tree_reserved_metadata_key(key)?;
1769    }
1770    Ok(())
1771}
1772
1773fn ensure_non_tree_reserved_metadata_key(key: &str) -> RedDBResult<()> {
1774    if key.starts_with(TREE_METADATA_PREFIX) {
1775        return Err(crate::RedDBError::Query(format!(
1776            "metadata key '{}' is reserved for managed trees",
1777            key
1778        )));
1779    }
1780    Ok(())
1781}
1782
1783fn ensure_non_tree_reserved_metadata_entries(
1784    metadata: &[(String, MetadataValue)],
1785) -> RedDBResult<()> {
1786    for (key, _) in metadata {
1787        ensure_non_tree_reserved_metadata_key(key)?;
1788    }
1789    Ok(())
1790}
1791
1792fn ensure_non_tree_structural_edge_label(label: &str) -> RedDBResult<()> {
1793    if label.eq_ignore_ascii_case(TREE_CHILD_EDGE_LABEL) {
1794        return Err(crate::RedDBError::Query(format!(
1795            "edge label '{}' is reserved for managed trees",
1796            TREE_CHILD_EDGE_LABEL
1797        )));
1798    }
1799    Ok(())
1800}
1801
1802impl RedDBRuntime {
1803    pub(crate) fn create_node_unchecked(
1804        &self,
1805        input: CreateNodeInput,
1806    ) -> RedDBResult<CreateEntityOutput> {
1807        if self.vcs_is_versioned(&input.collection)? || self.has_graph_contract(&input.collection) {
1808            self.with_versioned_graph_insert(|| self.create_node_unchecked_inner(input))
1809        } else {
1810            self.create_node_unchecked_inner(input)
1811        }
1812    }
1813
1814    fn create_node_unchecked_inner(
1815        &self,
1816        mut input: CreateNodeInput,
1817    ) -> RedDBResult<CreateEntityOutput> {
1818        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, &input.collection)?;
1819        crate::runtime::mutation::enforce_tenant_fields(
1820            self,
1821            &input.collection,
1822            &mut input.properties,
1823        )?;
1824        let node_type = input
1825            .node_type
1826            .clone()
1827            .unwrap_or_else(|| input.label.clone());
1828        let candidate = crate::storage::UnifiedEntity::new(
1829            crate::storage::EntityId::new(0),
1830            crate::storage::EntityKind::GraphNode(Box::new(
1831                crate::storage::unified::GraphNodeKind {
1832                    label: input.label.clone(),
1833                    node_type,
1834                },
1835            )),
1836            crate::storage::EntityData::Node(crate::storage::NodeData::with_properties(
1837                input.properties.iter().cloned().collect(),
1838            )),
1839        );
1840        ensure_insert_entity_rls(self, &input.collection, &candidate)?;
1841        let db = self.db();
1842        let contract = CollectionContractWriteEnforcer::new(self, &db, &input.collection);
1843        contract.ensure_model(crate::catalog::CollectionModel::Graph)?;
1844        let mut metadata = input.metadata;
1845        contract.apply_default_ttl(&mut metadata);
1846        let mut builder = db.node(&input.collection, &input.label);
1847
1848        if let Some(node_type) = input.node_type {
1849            builder = builder.node_type(node_type);
1850        }
1851
1852        for (key, value) in input.properties {
1853            builder = builder.property(key, value);
1854        }
1855
1856        for (key, value) in metadata {
1857            builder = builder.metadata(key, value);
1858        }
1859
1860        for embedding in input.embeddings {
1861            if let Some(model) = embedding.model {
1862                builder = builder.embedding_with_model(embedding.name, embedding.vector, model);
1863            } else {
1864                builder = builder.embedding(embedding.name, embedding.vector);
1865            }
1866        }
1867
1868        for link in input.table_links {
1869            builder = builder.link_to_table(link.key, link.table);
1870        }
1871
1872        for link in input.node_links {
1873            builder = builder.link_to_weighted(link.target, link.edge_label, link.weight);
1874        }
1875
1876        let id = builder.save_with_mvcc(
1877            self.current_xid().or_else(|| self.graph_insert_xid()),
1878            self.vcs_writer_epoch(&input.collection)?,
1879        )?;
1880        refresh_context_index(&db, &input.collection, id)?;
1881        self.cdc_emit(
1882            crate::replication::cdc::ChangeOperation::Insert,
1883            &input.collection,
1884            id.raw(),
1885            "graph_node",
1886        )?;
1887        Ok(CreateEntityOutput {
1888            id,
1889            entity: db.store().get(&input.collection, id),
1890        })
1891    }
1892
1893    pub(crate) fn create_edge_unchecked(
1894        &self,
1895        input: CreateEdgeInput,
1896    ) -> RedDBResult<CreateEntityOutput> {
1897        if self.vcs_is_versioned(&input.collection)? || self.has_graph_contract(&input.collection) {
1898            self.with_versioned_graph_insert(|| self.create_edge_unchecked_inner(input))
1899        } else {
1900            self.create_edge_unchecked_inner(input)
1901        }
1902    }
1903
1904    fn create_edge_unchecked_inner(
1905        &self,
1906        mut input: CreateEdgeInput,
1907    ) -> RedDBResult<CreateEntityOutput> {
1908        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, &input.collection)?;
1909        crate::runtime::mutation::enforce_tenant_fields(
1910            self,
1911            &input.collection,
1912            &mut input.properties,
1913        )?;
1914        let weight = input.weight.unwrap_or(1.0);
1915        let candidate = crate::storage::UnifiedEntity::new(
1916            crate::storage::EntityId::new(0),
1917            crate::storage::EntityKind::GraphEdge(Box::new(
1918                crate::storage::unified::GraphEdgeKind {
1919                    label: input.label.clone(),
1920                    from_node: input.from.raw().to_string(),
1921                    to_node: input.to.raw().to_string(),
1922                    weight: (weight * 1000.0) as u32,
1923                },
1924            )),
1925            crate::storage::EntityData::Edge(crate::storage::EdgeData::with_properties(
1926                weight,
1927                input.properties.iter().cloned().collect(),
1928            )),
1929        );
1930        ensure_insert_entity_rls(self, &input.collection, &candidate)?;
1931        let db = self.db();
1932        let contract = CollectionContractWriteEnforcer::new(self, &db, &input.collection);
1933        contract.ensure_model(crate::catalog::CollectionModel::Graph)?;
1934        let mut metadata = input.metadata;
1935        contract.apply_default_ttl(&mut metadata);
1936        let mut builder = db
1937            .edge(&input.collection, &input.label)
1938            .from(input.from)
1939            .to(input.to);
1940
1941        if let Some(weight) = input.weight {
1942            builder = builder.weight(weight);
1943        }
1944
1945        for (key, value) in input.properties {
1946            builder = builder.property(key, value);
1947        }
1948
1949        for (key, value) in metadata {
1950            builder = builder.metadata(key, value);
1951        }
1952
1953        let id = builder.save_with_mvcc(
1954            self.current_xid().or_else(|| self.graph_insert_xid()),
1955            self.vcs_writer_epoch(&input.collection)?,
1956        )?;
1957        refresh_context_index(&db, &input.collection, id)?;
1958        self.cdc_emit(
1959            crate::replication::cdc::ChangeOperation::Insert,
1960            &input.collection,
1961            id.raw(),
1962            "graph_edge",
1963        )?;
1964        Ok(CreateEntityOutput {
1965            id,
1966            entity: db.store().get(&input.collection, id),
1967        })
1968    }
1969}
1970
1971fn create_rows_batch_prevalidated_columnar_with_outputs(
1972    runtime: &RedDBRuntime,
1973    collection: String,
1974    column_names: std::sync::Arc<Vec<String>>,
1975    rows: Vec<Vec<reddb_types::Value>>,
1976) -> RedDBResult<Vec<CreateEntityOutput>> {
1977    use crate::storage::{
1978        unified::{EntityData, EntityKind, RowData},
1979        EntityId, UnifiedEntity,
1980    };
1981    use std::sync::Arc;
1982
1983    if rows.is_empty() {
1984        return Ok(Vec::new());
1985    }
1986    if crate::runtime::execution_context::current_auth_identity().is_some() {
1987        let inputs = rows
1988            .into_iter()
1989            .map(|values| CreateRowInput {
1990                collection: collection.clone(),
1991                fields: column_names.iter().cloned().zip(values).collect(),
1992                metadata: Vec::new(),
1993                node_links: Vec::new(),
1994                vector_links: Vec::new(),
1995            })
1996            .collect();
1997        return runtime.create_rows_batch_prevalidated_with_outputs(CreateRowsBatchInput {
1998            collection,
1999            rows: inputs,
2000            suppress_events: false,
2001        });
2002    }
2003    // Schema prevalidation does not admit standalone index keys. Route these
2004    // collections through the guarded row kernel before installing any row.
2005    if runtime.index_store_ref().has_unique_index(&collection) {
2006        return runtime.create_rows_batch_columnar_with_outputs(collection, column_names, rows);
2007    }
2008    runtime.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2009    runtime.check_batch_size(rows.len())?;
2010    runtime.check_db_size()?;
2011    let _insert_publication = runtime
2012        .index_store_ref()
2013        .begin_insert_publication(&collection, 0);
2014
2015    let db = runtime.db();
2016    let contract = CollectionContractWriteEnforcer::new(runtime, &db, &collection);
2017    contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2018
2019    let store = db.store();
2020    let table_arc: Arc<str> = Arc::from(collection.as_str());
2021
2022    let indexed_cols = runtime
2023        .index_store_ref()
2024        .indexed_columns_set(collection.as_str());
2025    let has_secondary_indexes = !indexed_cols.is_empty();
2026    let mut field_snapshots: Vec<Vec<(String, reddb_types::Value)>> = if has_secondary_indexes {
2027        Vec::with_capacity(rows.len())
2028    } else {
2029        Vec::new()
2030    };
2031
2032    let entities: Vec<UnifiedEntity> = rows
2033        .into_iter()
2034        .map(|values| {
2035            if has_secondary_indexes {
2036                let mut snap: Vec<(String, reddb_types::Value)> =
2037                    Vec::with_capacity(indexed_cols.len());
2038                for (name, val) in column_names.iter().zip(values.iter()) {
2039                    if indexed_cols.contains(name) {
2040                        snap.push((name.clone(), val.clone()));
2041                    }
2042                }
2043                field_snapshots.push(snap);
2044            }
2045            let mut row = RowData::new(values);
2046            row.schema = Some(Arc::clone(&column_names));
2047            UnifiedEntity::new(
2048                EntityId::new(0),
2049                EntityKind::TableRow {
2050                    table: Arc::clone(&table_arc),
2051                    row_id: 0,
2052                },
2053                EntityData::Row(row),
2054            )
2055        })
2056        .collect();
2057
2058    let ids = store
2059        .bulk_insert(&collection, entities)
2060        .map_err(|e| crate::RedDBError::Internal(format!("{e:?}")))?;
2061
2062    if has_secondary_indexes {
2063        let index_rows: Vec<(EntityId, Vec<(String, reddb_types::Value)>)> = ids
2064            .iter()
2065            .zip(field_snapshots)
2066            .map(|(id, fields)| (*id, fields))
2067            .collect();
2068        runtime
2069            .index_store_ref()
2070            .index_entity_insert_batch(&collection, &index_rows)
2071            .map_err(crate::RedDBError::Internal)?;
2072    }
2073
2074    runtime.invalidate_result_cache();
2075    runtime.cdc_emit_insert_batch_no_cache_invalidate(&collection, &ids, "table")?;
2076
2077    Ok(ids
2078        .into_iter()
2079        .map(|id| CreateEntityOutput { id, entity: None })
2080        .collect())
2081}
2082
2083impl RuntimeEntityPort for RedDBRuntime {
2084    fn create_row(&self, input: CreateRowInput) -> RedDBResult<CreateEntityOutput> {
2085        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2086        let branch_store = self.db().store();
2087        let _branch_publication = (self.vcs_is_versioned(&input.collection)?
2088            || self.has_graph_contract(&input.collection))
2089        .then(|| branch_store.vault_publication_lock.lock());
2090        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
2091            self,
2092            &input.collection,
2093        );
2094        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2095        let db = self.db();
2096        let CreateRowInput {
2097            collection,
2098            fields,
2099            metadata: input_metadata,
2100            node_links,
2101            vector_links,
2102        } = input;
2103        let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
2104        contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2105        let mut metadata = input_metadata;
2106        contract.apply_default_ttl(&mut metadata);
2107        let fields = contract.normalize_insert_fields(fields)?;
2108        contract.enforce_row_uniqueness(&fields, None)?;
2109        // Route through MutationEngine for unified hot path.
2110        let engine = self.mutation_engine();
2111        let result = engine.apply(
2112            collection.clone(),
2113            vec![crate::runtime::mutation::MutationRow {
2114                fields,
2115                metadata,
2116                node_links,
2117                vector_links,
2118            }],
2119        )?;
2120        let id = result.ids[0];
2121        // Perf: `db.get(id)` does a *cross-collection* scan (get_any)
2122        // that also takes a write lock on the entity cache. We know
2123        // the collection — hit the manager directly. Cuts
2124        // create_row() p50 roughly in half on the hot path.
2125        Ok(CreateEntityOutput {
2126            id,
2127            entity: db.store().get(&collection, id),
2128        })
2129    }
2130
2131    fn create_rows_batch(
2132        &self,
2133        input: CreateRowsBatchInput,
2134    ) -> RedDBResult<Vec<CreateEntityOutput>> {
2135        let branch_store = self.db().store();
2136        let _branch_publication = (self.vcs_is_versioned(&input.collection)?
2137            || self.has_graph_contract(&input.collection))
2138        .then(|| branch_store.vault_publication_lock.lock());
2139        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
2140            self,
2141            &input.collection,
2142        );
2143        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2144        if input.rows.is_empty() {
2145            return Ok(Vec::new());
2146        }
2147        self.check_batch_size(input.rows.len())?;
2148        self.check_db_size()?;
2149
2150        let db = self.db();
2151        let collection = input.collection;
2152        let suppress_events = input.suppress_events;
2153        let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
2154        contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2155
2156        let mut prepared_rows = Vec::with_capacity(input.rows.len());
2157        let mut uniqueness_rows = Vec::with_capacity(input.rows.len());
2158        for row in input.rows {
2159            if row.collection != collection {
2160                return Err(crate::RedDBError::Query(format!(
2161                    "batch row collection mismatch: expected '{}', got '{}'",
2162                    collection, row.collection
2163                )));
2164            }
2165
2166            let mut metadata = row.metadata;
2167            contract.apply_default_ttl(&mut metadata);
2168            let fields = contract.normalize_insert_fields(row.fields)?;
2169            contract.enforce_row_uniqueness(&fields, None)?;
2170            uniqueness_rows.push(fields.clone());
2171            prepared_rows.push((fields, metadata, row.node_links, row.vector_links));
2172        }
2173
2174        contract.enforce_batch_uniqueness(&uniqueness_rows)?;
2175
2176        // Route through MutationEngine: single bulk_insert + one CDC batch
2177        // instead of N separate cdc_emit() calls (each acquires a write lock).
2178        let engine = {
2179            let e = self.mutation_engine();
2180            if suppress_events {
2181                e.with_suppress_events()
2182            } else {
2183                e
2184            }
2185        };
2186        let mutation_rows: Vec<crate::runtime::mutation::MutationRow> = prepared_rows
2187            .into_iter()
2188            .map(|(fields, metadata, node_links, vector_links)| {
2189                crate::runtime::mutation::MutationRow {
2190                    fields,
2191                    metadata,
2192                    node_links,
2193                    vector_links,
2194                }
2195            })
2196            .collect();
2197
2198        let result = engine.apply(collection.clone(), mutation_rows)?;
2199
2200        let store = db.store();
2201        Ok(result
2202            .ids
2203            .into_iter()
2204            .map(|id| CreateEntityOutput {
2205                id,
2206                entity: store.get(&collection, id),
2207            })
2208            .collect())
2209    }
2210
2211    fn create_rows_batch_prevalidated_columnar(
2212        &self,
2213        collection: String,
2214        column_names: std::sync::Arc<Vec<String>>,
2215        rows: Vec<Vec<reddb_types::Value>>,
2216    ) -> RedDBResult<usize> {
2217        create_rows_batch_prevalidated_columnar_with_outputs(self, collection, column_names, rows)
2218            .map(|outputs| outputs.len())
2219    }
2220
2221    fn create_rows_batch_columnar(
2222        &self,
2223        collection: String,
2224        column_names: std::sync::Arc<Vec<String>>,
2225        rows: Vec<Vec<reddb_types::Value>>,
2226    ) -> RedDBResult<usize> {
2227        self.create_rows_batch_columnar_with_outputs(collection, column_names, rows)
2228            .map(|outputs| outputs.len())
2229    }
2230
2231    fn create_rows_batch_columnar_with_outputs(
2232        &self,
2233        collection: String,
2234        column_names: std::sync::Arc<Vec<String>>,
2235        rows: Vec<Vec<reddb_types::Value>>,
2236    ) -> RedDBResult<Vec<CreateEntityOutput>> {
2237        if rows.is_empty() {
2238            return Ok(Vec::new());
2239        }
2240        self.check_batch_size(rows.len())?;
2241        self.check_db_size()?;
2242
2243        let db = self.db();
2244        let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
2245        contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2246
2247        // Fast path: when the collection carries no contract (or the
2248        // contract has no declared columns) `normalize_insert_fields`
2249        // is a no-op and `enforce_row_uniqueness` finds no unique
2250        // columns to check. Skip the per-row `(String, Value)` tuple
2251        // materialisation entirely and route through the prevalidated
2252        // columnar kernel — same write, CDC, and index path, just
2253        // without the wasted (String, Value) clones. This is the
2254        // bench `bench_users` shape (no contract declared by the
2255        // adapter's `setup_schema`).
2256        let needs_normalisation = self.index_store_ref().has_unique_index(&collection)
2257            || match db.collection_contract(&collection) {
2258                Some(c) => {
2259                    c.declared_model == crate::catalog::CollectionModel::Table
2260                        && (!c.declared_columns.is_empty()
2261                            || c.table_def
2262                                .as_ref()
2263                                .map(|t| !t.columns.is_empty())
2264                                .unwrap_or(false))
2265                }
2266                None => false,
2267            };
2268        if !needs_normalisation {
2269            return create_rows_batch_prevalidated_columnar_with_outputs(
2270                self,
2271                collection,
2272                column_names,
2273                rows,
2274            );
2275        }
2276
2277        // Slow path: contract requires per-row normalisation /
2278        // uniqueness checks. Materialise `Vec<(String, Value)>` from
2279        // the columnar layout (this still pays N×ncols `String::clone`
2280        // — but it's deferred out of the wire decoder hot loop and
2281        // happens behind a runtime API, not the per-row decode loop)
2282        // and fall through to the existing `create_rows_batch` path.
2283        let ncols = column_names.len();
2284        let tuple_rows: Vec<CreateRowInput> = rows
2285            .into_iter()
2286            .map(|values| {
2287                let mut fields: Vec<(String, reddb_types::Value)> = Vec::with_capacity(ncols);
2288                for (name, value) in column_names.iter().zip(values) {
2289                    fields.push((name.clone(), value));
2290                }
2291                CreateRowInput {
2292                    collection: collection.clone(),
2293                    fields,
2294                    metadata: Vec::new(),
2295                    node_links: Vec::new(),
2296                    vector_links: Vec::new(),
2297                }
2298            })
2299            .collect();
2300        self.create_rows_batch(CreateRowsBatchInput {
2301            collection,
2302            rows: tuple_rows,
2303            suppress_events: false,
2304        })
2305    }
2306
2307    fn create_rows_batch_prevalidated(&self, input: CreateRowsBatchInput) -> RedDBResult<usize> {
2308        self.create_rows_batch_prevalidated_with_outputs(input)
2309            .map(|outputs| outputs.len())
2310    }
2311
2312    fn create_rows_batch_prevalidated_with_outputs(
2313        &self,
2314        input: CreateRowsBatchInput,
2315    ) -> RedDBResult<Vec<CreateEntityOutput>> {
2316        if input.rows.is_empty() {
2317            return Ok(Vec::new());
2318        }
2319        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2320        self.check_batch_size(input.rows.len())?;
2321        self.check_db_size()?;
2322
2323        let db = self.db();
2324        let collection = input.collection;
2325        let suppress_events = input.suppress_events;
2326        // Still verify the collection's declared model before we blast
2327        // rows at it — this one-off check is O(1), independent of
2328        // ncols, and catches schema-kind mismatches that the client
2329        // can't always see.
2330        let contract = CollectionContractWriteEnforcer::new(self, &db, &collection);
2331        contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2332
2333        // Hoist the per-collection default TTL lookup out of the
2334        // per-row loop — it only depends on the collection, not on
2335        // individual rows, and the old path did one HashMap read per
2336        // row (25k reads for a 25k typed_insert bulk). Fetch it once,
2337        // apply to any row whose metadata doesn't already carry a TTL.
2338        let default_ttl_plan = contract.default_ttl_plan();
2339
2340        let mutation_rows: Vec<crate::runtime::mutation::MutationRow> =
2341            Vec::with_capacity(input.rows.len());
2342        let mut mutation_rows = mutation_rows;
2343        for row in input.rows {
2344            if row.collection != collection {
2345                return Err(crate::RedDBError::Query(format!(
2346                    "batch row collection mismatch: expected '{}', got '{}'",
2347                    collection, row.collection
2348                )));
2349            }
2350            let mut metadata = row.metadata;
2351            default_ttl_plan.apply(&mut metadata);
2352            mutation_rows.push(crate::runtime::mutation::MutationRow {
2353                fields: row.fields,
2354                metadata,
2355                node_links: row.node_links,
2356                vector_links: row.vector_links,
2357            });
2358        }
2359
2360        let engine = {
2361            let engine = self.mutation_engine();
2362            if suppress_events {
2363                engine.with_suppress_events()
2364            } else {
2365                engine
2366            }
2367        };
2368        let result = engine.apply(collection.clone(), mutation_rows)?;
2369        let store = db.store();
2370        Ok(result
2371            .ids
2372            .into_iter()
2373            .map(|id| CreateEntityOutput {
2374                id,
2375                entity: store.get(&collection, id),
2376            })
2377            .collect())
2378    }
2379
2380    fn create_node(&self, input: CreateNodeInput) -> RedDBResult<CreateEntityOutput> {
2381        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2382        crate::reserved_fields::ensure_no_reserved_public_item_fields(
2383            input.properties.iter().map(|(key, _)| key.as_str()),
2384            &format!("node '{}'", input.collection),
2385        )?;
2386        ensure_non_tree_reserved_metadata_entries(&input.metadata)?;
2387        self.create_node_unchecked(input)
2388    }
2389
2390    fn create_edge(&self, input: CreateEdgeInput) -> RedDBResult<CreateEntityOutput> {
2391        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2392        crate::reserved_fields::ensure_no_reserved_public_item_fields(
2393            input.properties.iter().map(|(key, _)| key.as_str()),
2394            &format!("edge '{}'", input.collection),
2395        )?;
2396        ensure_non_tree_structural_edge_label(&input.label)?;
2397        ensure_non_tree_reserved_metadata_entries(&input.metadata)?;
2398        self.create_edge_unchecked(input)
2399    }
2400
2401    fn create_vector(&self, input: CreateVectorInput) -> RedDBResult<CreateEntityOutput> {
2402        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2403        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, &input.collection)?;
2404        let versioned = self.vcs_is_versioned(&input.collection)?;
2405        let create = || {
2406            let mut vector_data = crate::storage::VectorData::new(input.dense.clone());
2407            vector_data.content = input.content.clone();
2408            let candidate = crate::storage::UnifiedEntity::new(
2409                crate::storage::EntityId::new(0),
2410                crate::storage::EntityKind::Vector {
2411                    collection: input.collection.clone(),
2412                },
2413                crate::storage::EntityData::Vector(vector_data),
2414            );
2415            ensure_insert_entity_rls(self, &input.collection, &candidate)?;
2416            let db = self.db();
2417            let contract = CollectionContractWriteEnforcer::new(self, &db, &input.collection);
2418            contract.ensure_model(crate::catalog::CollectionModel::Vector)?;
2419            contract.ensure_vector_dimension(input.dense.len())?;
2420            let mut metadata = input.metadata;
2421            contract.apply_default_ttl(&mut metadata);
2422            let mut builder = db.vector(&input.collection).dense(input.dense);
2423
2424            if let Some(content) = input.content {
2425                builder = builder.content(content);
2426            }
2427
2428            for (key, value) in metadata {
2429                builder = builder.metadata(key, value);
2430            }
2431
2432            if let Some(link_row) = input.link_row {
2433                builder = builder.link_to_table(link_row);
2434            }
2435
2436            if let Some(link_node) = input.link_node {
2437                builder = builder.link_to_node(link_node);
2438            }
2439
2440            // The transaction stamp must be present on the first published version.
2441            // Stamping after save exposed an xmin=0 vector to concurrent snapshots.
2442            let id = builder.save_with_mvcc(
2443                self.current_xid().or_else(|| self.graph_insert_xid()),
2444                self.vcs_writer_epoch(&input.collection)?,
2445            )?;
2446            let dense_for_turbo = match db.store().get(&input.collection, id).map(|e| e.data) {
2447                Some(crate::storage::unified::EntityData::Vector(data)) => Some(data.dense.clone()),
2448                _ => None,
2449            };
2450            refresh_context_index(&db, &input.collection, id)?;
2451            // Issue #693 — vector.turbo write path. Order matters and
2452            // matches the write sequence the next slice (#673) will
2453            // attach kill-points to: WAL append → in-memory index update
2454            // → TurboExtent append. The legacy `vector` path is the
2455            // `None` branch and is untouched.
2456            if let (Some(state), Some(dense)) = (db.turbo_state(&input.collection), dense_for_turbo)
2457            {
2458                // Lazy populate so an INSERT after restart sees the
2459                // pre-restart vectors in the index before appending its
2460                // own.
2461                state.ensure_populated(&db.store(), &input.collection)?;
2462                // Issue #694 — named crash boundaries for #673.
2463                use crate::runtime::turbo_crash_inject::{fire, injected_io_error, InjectionPoint};
2464                fire(InjectionPoint::BeforeWalFsync);
2465                let wal_result = injected_io_error(InjectionPoint::BeforeWalFsync).map_or_else(
2466                    || {
2467                        db.store()
2468                            .append_vector_insert_record(&input.collection, id.raw(), &dense)
2469                    },
2470                    Err,
2471                );
2472                fire(InjectionPoint::BeforeIndexCommit);
2473                let mut index = state.index.lock();
2474                index.insert(id, dense.clone());
2475                if let Err(error) = wal_result {
2476                    return Err(error.into());
2477                }
2478                // Mirror the encoded codes into the per-collection
2479                // TurboExtent when one is available. The bytes are the
2480                // 4-bit-packed code groups (`n_byte_groups`) plus the
2481                // little-endian L2 norm — same shape `BlockedCodeStorage`
2482                // appends in-memory. The extent is derived state: on an
2483                // uncertain append, discard it and recover from the entity.
2484                fire(InjectionPoint::BeforeExtentFsync);
2485                let mut extent_guard = state.extent.lock();
2486                if let Some(extent) = extent_guard.as_mut() {
2487                    let packed = index.encode_for_extent(&dense);
2488                    let extent_result = injected_io_error(InjectionPoint::BeforeExtentFsync)
2489                        .map_or_else(|| extent.append(&packed), |error| Err(error.into()));
2490                    if let Err(error) = extent_result {
2491                        *extent_guard = None;
2492                        return Err(match error {
2493                            crate::storage::engine::pager::PagerError::Io(error) => error.into(),
2494                            error => crate::RedDBError::Internal(format!(
2495                                "vector.turbo extent append failed: {error}"
2496                            )),
2497                        });
2498                    }
2499                }
2500            }
2501            self.cdc_emit(
2502                crate::replication::cdc::ChangeOperation::Insert,
2503                &input.collection,
2504                id.raw(),
2505                "vector",
2506            )?;
2507            Ok(CreateEntityOutput {
2508                id,
2509                entity: db.store().get(&input.collection, id),
2510            })
2511        };
2512        if versioned {
2513            self.with_versioned_graph_insert(create)
2514        } else {
2515            create()
2516        }
2517    }
2518
2519    fn create_document(&self, input: CreateDocumentInput) -> RedDBResult<CreateEntityOutput> {
2520        let _indexed_mutation = self
2521            .index_store_ref()
2522            .begin_indexed_mutation(&input.collection);
2523        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2524        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, &input.collection)?;
2525        let db = self.db();
2526        let contract = CollectionContractWriteEnforcer::new(self, &db, &input.collection);
2527        contract.ensure_model(crate::catalog::CollectionModel::Document)?;
2528
2529        if let JsonValue::Object(ref map) = input.body {
2530            crate::reserved_fields::ensure_no_reserved_public_item_fields(
2531                map.keys().map(String::as_str),
2532                &format!("document '{}'", input.collection),
2533            )?;
2534        }
2535
2536        // Serialize the full body for the "body" field. Behind the
2537        // `storage.binary_document_body` flag (PRD-1398) this is the native binary
2538        // container; otherwise plain JSON. Reads decode either form to JSON.
2539        let mut fields: Vec<(String, reddb_types::Value)> = vec![(
2540            "body".to_string(),
2541            reddb_types::Value::Json(
2542                crate::json::to_vec(&input.body)
2543                    .map_err(|err| crate::RedDBError::Query(err.to_string()))?,
2544            ),
2545        )];
2546        crate::runtime::mutation::enforce_tenant_fields(self, &input.collection, &mut fields)?;
2547        let (field_names, field_values) =
2548            crate::runtime::impl_dml_support::pairwise_columns_values(&fields);
2549        let scoped_body =
2550            crate::runtime::impl_dml_support::find_document_body_json(&field_names, &field_values)?;
2551        let body_bytes = crate::document_body::serialize_document_body(
2552            &scoped_body,
2553            self.binary_document_body_enabled(),
2554        )?;
2555        if let Some((_, body)) = fields.iter_mut().find(|(name, _)| name == "body") {
2556            *body = reddb_types::Value::Json(body_bytes);
2557        }
2558        let mut row = crate::storage::RowData::new(Vec::new());
2559        row.named = Some(fields.iter().cloned().collect());
2560        let candidate = crate::storage::UnifiedEntity::new(
2561            crate::storage::EntityId::new(0),
2562            crate::storage::EntityKind::TableRow {
2563                table: std::sync::Arc::from(input.collection.as_str()),
2564                row_id: 0,
2565            },
2566            crate::storage::EntityData::Row(row),
2567        );
2568        ensure_insert_entity_rls(self, &input.collection, &candidate)?;
2569
2570        let mut metadata = input.metadata;
2571        contract.apply_default_ttl(&mut metadata);
2572        let columns: Vec<(&str, reddb_types::Value)> = fields
2573            .iter()
2574            .map(|(key, value)| (key.as_str(), value.clone()))
2575            .collect();
2576        let mut builder = db.row(&input.collection, columns);
2577
2578        for (key, value) in metadata {
2579            builder = builder.metadata(key, value);
2580        }
2581
2582        for node in input.node_links {
2583            builder = builder.link_to_node(node);
2584        }
2585
2586        for vector in input.vector_links {
2587            builder = builder.link_to_vector(vector);
2588        }
2589
2590        let create = || -> RedDBResult<crate::storage::EntityId> {
2591            Ok(builder.save_with_mvcc(
2592                self.current_xid().or_else(|| self.graph_insert_xid()),
2593                self.vcs_writer_epoch(&input.collection)?,
2594            )?)
2595        };
2596        let id = if self.vcs_is_versioned(&input.collection)?
2597            || self.has_graph_contract(&input.collection)
2598        {
2599            self.with_versioned_graph_insert(create)?
2600        } else {
2601            create()?
2602        };
2603        self.index_store_ref()
2604            .index_entity_insert(&input.collection, id, &fields)
2605            .map_err(crate::RedDBError::Internal)?;
2606        refresh_context_index(&db, &input.collection, id)?;
2607        self.cdc_emit(
2608            crate::replication::cdc::ChangeOperation::Insert,
2609            &input.collection,
2610            id.raw(),
2611            "document",
2612        )?;
2613        Ok(CreateEntityOutput {
2614            id,
2615            entity: db.store().get(&input.collection, id),
2616        })
2617    }
2618
2619    fn create_kv(&self, input: CreateKvInput) -> RedDBResult<CreateEntityOutput> {
2620        crate::runtime::kv_write::create(self, input, None)
2621    }
2622
2623    fn create_timeseries_point(
2624        &self,
2625        input: CreateTimeSeriesPointInput,
2626    ) -> RedDBResult<CreateEntityOutput> {
2627        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2628        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Insert, &input.collection)?;
2629        let db = self.db();
2630        let contract = CollectionContractWriteEnforcer::new(self, &db, &input.collection);
2631        contract.ensure_model(crate::catalog::CollectionModel::TimeSeries)?;
2632
2633        let mut fields = vec![
2634            ("metric".to_string(), reddb_types::Value::text(input.metric)),
2635            ("value".to_string(), reddb_types::Value::Float(input.value)),
2636        ];
2637
2638        if let Some(timestamp_ns) = input.timestamp_ns {
2639            fields.push((
2640                "timestamp".to_string(),
2641                reddb_types::Value::UnsignedInteger(timestamp_ns),
2642            ));
2643        }
2644
2645        if !input.tags.is_empty() {
2646            let tags_json = JsonValue::Object(
2647                input
2648                    .tags
2649                    .into_iter()
2650                    .map(|(key, value)| (key, JsonValue::String(value)))
2651                    .collect(),
2652            );
2653            let tags_bytes = json_to_vec(&tags_json).map_err(|err| {
2654                crate::RedDBError::Query(format!("failed to serialize timeseries tags: {err}"))
2655            })?;
2656            fields.push(("tags".to_string(), reddb_types::Value::Json(tags_bytes)));
2657        }
2658
2659        let collection = input.collection;
2660        let id = self.insert_timeseries_point(&collection, fields, input.metadata)?;
2661        // Phase 1.1 MVCC universal: stamp xmin on the point so
2662        // concurrent range scans hide it until COMMIT.
2663        self.stamp_xmin_if_in_txn(&collection, id);
2664        refresh_context_index(&db, &collection, id)?;
2665
2666        Ok(CreateEntityOutput {
2667            id,
2668            entity: db.store().get(&collection, id),
2669        })
2670    }
2671
2672    fn get_kv(
2673        &self,
2674        collection: &str,
2675        key: &str,
2676    ) -> RedDBResult<Option<(reddb_types::Value, crate::storage::EntityId)>> {
2677        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Select, collection)?;
2678        let resolver = crate::runtime::kv_read::KvReadResolver::for_rest_kv(self, collection)?;
2679        let Some(record) = resolver.record(key)? else {
2680            return Ok(None);
2681        };
2682        let visible = self
2683            .db()
2684            .store()
2685            .get(collection, record.id)
2686            .is_some_and(|entity| {
2687                crate::runtime::rls_injection::entity_passes_rls_action(
2688                    self,
2689                    collection,
2690                    reddb_rql::ast::PolicyAction::Select,
2691                    &entity,
2692                )
2693            });
2694        Ok(visible.then_some((record.value.unwrap_or(Value::Null), record.id)))
2695    }
2696
2697    fn delete_kv(&self, collection: &str, key: &str) -> RedDBResult<bool> {
2698        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2699        crate::runtime::impl_kv::KvAtomicOps::new(self).delete(
2700            crate::catalog::CollectionModel::Kv,
2701            collection,
2702            key,
2703        )
2704    }
2705
2706    fn patch_entity(&self, input: PatchEntityInput) -> RedDBResult<CreateEntityOutput> {
2707        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2708        let _indexed_mutation = self
2709            .index_store_ref()
2710            .begin_indexed_mutation(&input.collection);
2711        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Update, &input.collection)?;
2712        let branch_store = self.db().store();
2713        let _branch_publication = (self.vcs_is_versioned(&input.collection)?
2714            || self.has_graph_contract(&input.collection))
2715        .then(|| branch_store.vault_publication_lock.lock());
2716        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
2717            self,
2718            &input.collection,
2719        );
2720        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2721        let topology_lock = self
2722            .index_store_ref()
2723            .collection_topology_lock(&input.collection);
2724        let topology_guard = topology_lock.read();
2725        let PatchEntityInput {
2726            collection,
2727            id,
2728            payload,
2729            operations,
2730        } = input;
2731        let db = self.db();
2732        let store = db.store();
2733        let Some(_) = store.get_collection(&collection) else {
2734            return Err(crate::RedDBError::NotFound(format!(
2735                "collection not found: {collection}"
2736            )));
2737        };
2738        let (snapshot, _retention) = self.native_read_snapshot()?;
2739        let _snapshot = crate::runtime::impl_core::CurrentSnapshotGuard::install(snapshot);
2740        let Some(entity) = self.get_collection_entity_for_action(
2741            &collection,
2742            id,
2743            reddb_rql::ast::PolicyAction::Update,
2744        )?
2745        else {
2746            return Err(crate::RedDBError::NotFound(format!(
2747                "entity not found: {}",
2748                id.raw()
2749            )));
2750        };
2751        if !crate::runtime::rls_injection::entity_passes_rls_action(
2752            self,
2753            &collection,
2754            reddb_rql::ast::PolicyAction::Update,
2755            &entity,
2756        ) {
2757            return Err(crate::RedDBError::NotFound(format!(
2758                "entity not found: {}",
2759                id.raw()
2760            )));
2761        }
2762        self.apply_loaded_patch_entity(collection, entity, payload, operations, topology_guard)
2763    }
2764
2765    fn delete_entity(&self, input: DeleteEntityInput) -> RedDBResult<DeleteEntityOutput> {
2766        self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2767        let _indexed_mutation = self
2768            .index_store_ref()
2769            .begin_indexed_mutation(&input.collection);
2770        self.check_collection_privilege(reddb_rql::ast::PolicyAction::Delete, &input.collection)?;
2771        let branch_store = self.db().store();
2772        let _branch_publication = (self.vcs_is_versioned(&input.collection)?
2773            || self.has_graph_contract(&input.collection))
2774        .then(|| branch_store.vault_publication_lock.lock());
2775        let constraint_lock = crate::application::collection_contract_enforcer::row_constraint_lock(
2776            self,
2777            &input.collection,
2778        );
2779        let _constraint_guard = constraint_lock.as_ref().map(|lock| lock.lock());
2780        let topology_lock = self
2781            .index_store_ref()
2782            .collection_topology_lock(&input.collection);
2783        let topology_guard = topology_lock.read();
2784        let store = self.db().store();
2785        // Snapshot row fields before delete so we can mirror the removal
2786        // into every secondary index. The fetch is best-effort: if the
2787        // entity is already gone, the delete below is a no-op anyway.
2788        let (snapshot, _retention) = self.native_read_snapshot()?;
2789        let _snapshot = crate::runtime::impl_core::CurrentSnapshotGuard::install(snapshot);
2790        let Some(entity) = self.get_collection_entity_for_action(
2791            &input.collection,
2792            input.id,
2793            reddb_rql::ast::PolicyAction::Delete,
2794        )?
2795        else {
2796            return Ok(DeleteEntityOutput {
2797                deleted: false,
2798                id: input.id,
2799            });
2800        };
2801        if !crate::runtime::rls_injection::entity_passes_rls_action(
2802            self,
2803            &input.collection,
2804            reddb_rql::ast::PolicyAction::Delete,
2805            &entity,
2806        ) {
2807            return Ok(DeleteEntityOutput {
2808                deleted: false,
2809                id: input.id,
2810            });
2811        }
2812        if self.vcs_is_versioned(&input.collection)? || self.has_graph_contract(&input.collection) {
2813            if self
2814                .db()
2815                .collection_contract_arc(&input.collection)
2816                .is_some_and(|contract| contract.append_only)
2817            {
2818                return Err(crate::RedDBError::InvalidOperation(
2819                    "append-only collections require their native retirement operation".into(),
2820                ));
2821            }
2822            self.validate_graph_changes(&input.collection, &[], &[entity.id])?;
2823            let deleted = self.delete_entities_batch(
2824                &input.collection,
2825                &[entity.id],
2826                topology_guard,
2827                None,
2828                false,
2829            )?;
2830            if deleted.affected > 0 {
2831                self.invalidate_result_cache();
2832            }
2833            return Ok(DeleteEntityOutput {
2834                deleted: deleted.affected > 0,
2835                id: input.id,
2836            });
2837        }
2838        let pre_delete_fields = entity_row_fields_snapshot(&entity);
2839        // Store delete first (source of truth). Crash between here and index removal
2840        // leaves the entity invisible to most queries but recoverable; the reverse
2841        // (remove index first, then crash) leaves the entity permanently orphaned.
2842        let deleted = store
2843            .delete(&input.collection, input.id)
2844            .map_err(|err| crate::RedDBError::Internal(err.to_string()))?;
2845        if deleted {
2846            #[cfg(test)]
2847            self.index_store_ref().mutation_test_hook(
2848                &input.collection,
2849                crate::runtime::MutationTestPhase::StoragePublished,
2850            );
2851            store.context_index().remove_entity(input.id);
2852            // Secondary index maintenance — surface only registry-shape
2853            // errors; missing-index removals are tolerated inside the call.
2854            if !pre_delete_fields.is_empty() {
2855                self.index_store_ref()
2856                    .index_entity_delete(&input.collection, input.id, &pre_delete_fields)
2857                    .map_err(crate::RedDBError::Internal)?;
2858            }
2859            drop(topology_guard);
2860            #[cfg(test)]
2861            self.index_store_ref().mutation_test_hook(
2862                &input.collection,
2863                crate::runtime::MutationTestPhase::BeforeEvents,
2864            );
2865            self.cdc_emit(
2866                crate::replication::cdc::ChangeOperation::Delete,
2867                &input.collection,
2868                input.id.raw(),
2869                "entity",
2870            )?;
2871        }
2872        Ok(DeleteEntityOutput {
2873            deleted,
2874            id: input.id,
2875        })
2876    }
2877}