Skip to main content

reddb_server/runtime/
impl_ddl.rs

1//! DDL execution: CREATE TABLE, DROP TABLE, ALTER TABLE via SQL AST
2//!
3//! Translates DDL statements into collection-level operations on the
4//! underlying `UnifiedStore`.  RedDB uses a flexible schema-on-read
5//! model, so column definitions are advisory metadata rather than
6//! rigid constraints.
7
8use super::*;
9use crate::catalog::CollectionModel;
10use crate::runtime::audit_log::{AuditAuthSource, AuditEvent, AuditFieldEscaper, Outcome};
11use crate::runtime::ddl::polymorphic_resolver;
12use reddb_engine::catalog::ddl::declared_column_contract_from_ddl;
13use reddb_rql::analyzer::analyze_create_table;
14use reddb_rql::ast::CreateColumnDef;
15use reddb_rql::ast::{
16    CreateVcsRefQuery, DropForkQuery, DropVcsRefQuery, ForkStoreQuery, VcsRefKind,
17};
18use std::collections::{BTreeSet, HashMap, HashSet};
19
20fn vault_master_key_ref(collection: &str) -> String {
21    format!("red.vault.{collection}.master_key")
22}
23
24impl RedDBRuntime {
25    /// Execute CREATE TABLE
26    ///
27    /// Creates a new collection in the store.  Column definitions are
28    /// recorded for introspection but do not enforce rigid schema
29    /// constraints.
30    pub fn execute_create_table(
31        &self,
32        raw_query: &str,
33        query: &CreateTableQuery,
34    ) -> RedDBResult<RuntimeQueryResult> {
35        if query.collection_model != CollectionModel::Table {
36            if query
37                .columns
38                .iter()
39                .any(|column| column.generated.is_some() || column.check.is_some())
40            {
41                return Err(RedDBError::Query(
42                    "schema expressions currently require TABLE collections".to_string(),
43                ));
44            }
45            return self.execute_create_keyed_collection(raw_query, query);
46        }
47        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
48        if is_system_schema_name(&query.name) {
49            return Err(RedDBError::Query("system schema is read-only".to_string()));
50        }
51        let store = self.inner.db.store();
52        analyze_create_table(query).map_err(|err| RedDBError::Query(err.to_string()))?;
53        // Reject an AI policy that wires a provider/model to a modality it
54        // cannot serve — fail at DDL time, before the collection exists,
55        // using the capability matrix from #1269.
56        if let Some(policy) = &query.ai_policy {
57            validate_ai_policy_modalities(policy)?;
58        }
59        crate::reserved_fields::ensure_no_reserved_public_item_fields(
60            query.columns.iter().map(|column| column.name.as_str()),
61            &format!("table '{}'", query.name),
62        )?;
63        // Check if the collection already exists.
64        let exists = store.get_collection(&query.name).is_some();
65        if exists {
66            if query.if_not_exists {
67                return Ok(RuntimeQueryResult::ok_message(
68                    raw_query.to_string(),
69                    &format!("table '{}' already exists", query.name),
70                    "create",
71                ));
72            }
73            return Err(RedDBError::Query(format!(
74                "table '{}' already exists",
75                query.name
76            )));
77        }
78
79        // Build and validate the contract before mutating storage so invalid
80        // SQL types / duplicate columns do not leave partial side effects.
81        let contract = collection_contract_from_create_table(query)?;
82        crate::application::collection_contract_enforcer::validate_contract_expressions(&contract)?;
83        validate_event_subscriptions(self, &query.name, &contract.subscriptions)?;
84        // Create the collection.
85        store
86            .create_collection(&query.name)
87            .map_err(|err| RedDBError::Internal(err.to_string()))?;
88        for subscription in &contract.subscriptions {
89            ensure_event_target_queue(self, &subscription.target_queue)?;
90        }
91        if let Some(default_ttl_ms) = query.default_ttl_ms {
92            self.inner
93                .db
94                .set_collection_default_ttl_ms(&query.name, default_ttl_ms);
95        }
96        self.inner
97            .db
98            .save_collection_contract(contract)
99            .map_err(|err| RedDBError::Internal(err.to_string()))?;
100        if let Some(tenant_id) = crate::runtime::impl_core::current_tenant() {
101            store.set_config_tree(
102                &format!("collection_tenants.{}", query.name),
103                &crate::serde_json::Value::String(tenant_id),
104            );
105        }
106        self.inner
107            .db
108            .persist_metadata()
109            .map_err(|err| RedDBError::Internal(err.to_string()))?;
110        self.refresh_table_planner_stats(&query.name);
111        self.invalidate_result_cache();
112        // Issue #120 — feed the create into the schema-vocabulary
113        // reverse index so AskPipeline (#121) sees this collection.
114        let columns: Vec<String> = query.columns.iter().map(|col| col.name.clone()).collect();
115        self.schema_vocabulary_apply(
116            crate::runtime::schema_vocabulary::DdlEvent::CreateCollection {
117                collection: query.name.clone(),
118                columns,
119                type_tags: Vec::new(),
120                description: query.description.clone(),
121            },
122        );
123        self.schema_vocabulary_sync_descriptions(&query.name);
124        // Partition metadata (Phase 2.2 PG parity).
125        //
126        // When the CREATE TABLE carries a `PARTITION BY RANGE|LIST|HASH (col)`
127        // clause, stamp the partition config into `red.config` under
128        // `partition.{table}.{by,column}`. Children are registered separately
129        // via `ALTER TABLE parent ATTACH PARTITION child ...`.
130        if let Some(spec) = &query.partition_by {
131            let kind_str = match spec.kind {
132                reddb_rql::ast::PartitionKind::Range => "range",
133                reddb_rql::ast::PartitionKind::List => "list",
134                reddb_rql::ast::PartitionKind::Hash => "hash",
135            };
136            store.set_config_tree(
137                &format!("partition.{}.by", query.name),
138                &crate::serde_json::Value::String(kind_str.to_string()),
139            );
140            store.set_config_tree(
141                &format!("partition.{}.column", query.name),
142                &crate::serde_json::Value::String(spec.column.clone()),
143            );
144        }
145
146        // Table-scoped multi-tenancy (Phase 2.5.4).
147        //
148        // `CREATE TABLE t (...) TENANT BY (col)` declaration:
149        //   1. Persists the `tenant_tables.{table}.column` marker so
150        //      INSERTs can auto-fill and future opens re-hydrate.
151        //   2. Registers the table in the in-memory `tenant_tables`
152        //      HashMap used by the DML auto-fill path.
153        //   3. Installs an implicit RLS policy equivalent to
154        //      `USING (col = CURRENT_TENANT())` across all actions.
155        //   4. Flips `rls_enabled_tables` on so the policy applies.
156        if let Some(col) = &query.tenant_by {
157            store.set_config_tree(
158                &format!("tenant_tables.{}.column", query.name),
159                &crate::serde_json::Value::String(col.clone()),
160            );
161            self.register_tenant_table(&query.name, col);
162        }
163
164        let ttl_suffix = query
165            .default_ttl_ms
166            .map(|ttl_ms| format!(" with default TTL {}ms", ttl_ms))
167            .unwrap_or_default();
168
169        let tenant_suffix = query
170            .tenant_by
171            .as_ref()
172            .map(|col| format!(" (tenant-scoped by {col})"))
173            .unwrap_or_default();
174
175        Ok(RuntimeQueryResult::ok_message(
176            raw_query.to_string(),
177            &format!(
178                "table '{}' created{}{}",
179                query.name, ttl_suffix, tenant_suffix
180            ),
181            "create",
182        ))
183    }
184
185    fn execute_create_keyed_collection(
186        &self,
187        raw_query: &str,
188        query: &CreateTableQuery,
189    ) -> RedDBResult<RuntimeQueryResult> {
190        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
191        if is_system_schema_name(&query.name) {
192            return Err(RedDBError::Query("system schema is read-only".to_string()));
193        }
194        let store = self.inner.db.store();
195        let label = polymorphic_resolver::model_name(query.collection_model);
196        if store.get_collection(&query.name).is_some() {
197            if query.if_not_exists {
198                return Ok(RuntimeQueryResult::ok_message(
199                    raw_query.to_string(),
200                    &format!("{label} '{}' already exists", query.name),
201                    "create",
202                ));
203            }
204            return Err(RedDBError::Query(format!(
205                "{label} '{}' already exists",
206                query.name
207            )));
208        }
209
210        if query.collection_model == CollectionModel::Vault {
211            self.reject_vault_transaction()?;
212            self.provision_vault_key_material(&query.name, query.vault_own_master_key)?;
213        }
214        store
215            .create_collection(&query.name)
216            .map_err(|err| RedDBError::Internal(err.to_string()))?;
217        if query.collection_model == CollectionModel::Vault {
218            let key_scope = if query.vault_own_master_key {
219                "own"
220            } else {
221                "cluster"
222            };
223            store.set_config_tree(
224                &format!("vault.{}.key_scope", query.name),
225                &crate::serde_json::Value::String(key_scope.to_string()),
226            );
227            store.set_config_tree(
228                &format!("vault.{}.status", query.name),
229                &crate::serde_json::Value::String("sealed".to_string()),
230            );
231        }
232        if query.collection_model == CollectionModel::Metrics {
233            for spec in &query.metrics_rollup_policies {
234                let policy = crate::storage::timeseries::retention::DownsamplePolicy::parse(spec)
235                    .ok_or_else(|| {
236                    RedDBError::Query(format!("invalid metrics rollup policy '{}'", spec))
237                })?;
238                if policy.source != "raw" {
239                    return Err(RedDBError::Query(format!(
240                        "invalid metrics rollup policy '{}': metrics v0 rollups must use raw as source",
241                        spec
242                    )));
243                }
244                if !matches!(
245                    policy.aggregation.as_str(),
246                    "avg" | "sum" | "min" | "max" | "count"
247                ) {
248                    return Err(RedDBError::Query(format!(
249                        "invalid metrics rollup policy '{}': supported aggregations are avg, sum, min, max, count",
250                        spec
251                    )));
252                }
253            }
254            if let Some(raw_retention_ms) = query.default_ttl_ms {
255                self.inner
256                    .db
257                    .set_collection_default_ttl_ms(&query.name, raw_retention_ms);
258                store.set_config_tree(
259                    &format!("metrics.{}.raw_retention_ms", query.name),
260                    &crate::serde_json::Value::Number(raw_retention_ms as f64),
261                );
262            }
263            let tenant_identity = query
264                .tenant_by
265                .clone()
266                .unwrap_or_else(|| "current_tenant".to_string());
267            store.set_config_tree(
268                &format!("metrics.{}.tenant_identity", query.name),
269                &crate::serde_json::Value::String(tenant_identity),
270            );
271            store.set_config_tree(
272                &format!("metrics.{}.namespace", query.name),
273                &crate::serde_json::Value::String("default".to_string()),
274            );
275            if !query.metrics_rollup_policies.is_empty() {
276                store.set_config_tree(
277                    &format!("metrics.{}.rollup_policies", query.name),
278                    &crate::serde_json::Value::Array(
279                        query
280                            .metrics_rollup_policies
281                            .iter()
282                            .cloned()
283                            .map(crate::serde_json::Value::String)
284                            .collect(),
285                    ),
286                );
287            }
288        }
289        let mut contract = if query.collection_model == CollectionModel::Metrics {
290            metrics_collection_contract(query)
291        } else {
292            keyed_collection_contract(
293                &query.name,
294                query.collection_model,
295                query.analytics_config.clone(),
296            )
297        };
298        contract.description = query.description.clone();
299        self.inner
300            .db
301            .save_collection_contract(contract)
302            .map_err(|err| RedDBError::Internal(err.to_string()))?;
303        if let Some(tenant_id) = crate::runtime::impl_core::current_tenant() {
304            store.set_config_tree(
305                &format!("collection_tenants.{}", query.name),
306                &crate::serde_json::Value::String(tenant_id),
307            );
308        }
309        self.inner
310            .db
311            .persist_metadata()
312            .map_err(|err| RedDBError::Internal(err.to_string()))?;
313        self.invalidate_result_cache();
314        self.schema_vocabulary_apply(
315            crate::runtime::schema_vocabulary::DdlEvent::CreateCollection {
316                collection: query.name.clone(),
317                columns: Vec::new(),
318                type_tags: Vec::new(),
319                description: query.description.clone(),
320            },
321        );
322        self.schema_vocabulary_sync_descriptions(&query.name);
323
324        Ok(RuntimeQueryResult::ok_message(
325            raw_query.to_string(),
326            &format!("{label} '{}' created", query.name),
327            "create",
328        ))
329    }
330
331    /// Bootstrap an internal graph collection declared `WITH ANALYTICS`
332    /// (issue #803). The SQL DDL path refuses `red.*` names via
333    /// [`is_system_schema_name`], so built-ins like `red.topology.cluster`
334    /// cannot be created through `CREATE GRAPH`; this method drives the same
335    /// contract-build / save / persist path directly, bypassing only that
336    /// guard. Idempotent: a no-op when the collection already exists (its
337    /// analytics contract is recovered from the WAL on restart), so it is safe
338    /// to call unconditionally on every boot.
339    pub fn ensure_system_graph_with_analytics(
340        &self,
341        name: &str,
342        outputs: &[crate::catalog::AnalyticsOutput],
343    ) -> RedDBResult<()> {
344        let store = self.inner.db.store();
345        if store.get_collection(name).is_some() {
346            return Ok(());
347        }
348        let analytics_config = outputs
349            .iter()
350            .map(|output| crate::catalog::AnalyticsViewDescriptor {
351                output: *output,
352                algorithm: None,
353                resolution: None,
354                max_iterations: None,
355                tolerance: None,
356            })
357            .collect();
358        store
359            .create_collection(name)
360            .map_err(|err| RedDBError::Internal(err.to_string()))?;
361        let contract = keyed_collection_contract(
362            name,
363            crate::catalog::CollectionModel::Graph,
364            analytics_config,
365        );
366        self.inner
367            .db
368            .save_collection_contract(contract)
369            .map_err(|err| RedDBError::Internal(err.to_string()))?;
370        self.inner
371            .db
372            .persist_metadata()
373            .map_err(|err| RedDBError::Internal(err.to_string()))?;
374        self.invalidate_result_cache_process_only();
375        Ok(())
376    }
377
378    pub fn execute_create_collection(
379        &self,
380        raw_query: &str,
381        query: &CreateCollectionQuery,
382    ) -> RedDBResult<RuntimeQueryResult> {
383        let model = match query.kind.as_str() {
384            "graph" => CollectionModel::Graph,
385            "document" => CollectionModel::Document,
386            "metrics" => CollectionModel::Metrics,
387            "vector.turbo" => {
388                let dimension = query.vector_dimension.ok_or_else(|| {
389                    RedDBError::Query(
390                        "CREATE COLLECTION KIND vector.turbo requires DIM".to_string(),
391                    )
392                })?;
393                let create = CreateVectorQuery {
394                    name: query.name.clone(),
395                    dimension,
396                    metric: query
397                        .vector_metric
398                        .unwrap_or(crate::storage::engine::distance::DistanceMetric::Cosine),
399                    if_not_exists: query.if_not_exists,
400                };
401                let result = self.execute_create_vector(raw_query, &create)?;
402                if let Some(description) = &query.description {
403                    if let Some(mut contract) = self.inner.db.collection_contract(&query.name) {
404                        contract.description = Some(description.clone());
405                        self.inner
406                            .db
407                            .save_collection_contract(contract)
408                            .map_err(|err| RedDBError::Internal(err.to_string()))?;
409                        self.schema_vocabulary_sync_descriptions(&query.name);
410                    }
411                }
412                // Issue #693 — durable kind marker that distinguishes
413                // this collection from the legacy `vector` path on
414                // every restart. Runtime state (TurboQuantIndex +
415                // TurboExtent) is lazily materialised by
416                // `RedDB::turbo_state` on first INSERT/SEARCH so the
417                // marker is the only thing that needs to survive.
418                let store = self.inner.db.store();
419                crate::runtime::vector_turbo_kind::mark_as_turbo(&store, &query.name);
420                self.inner
421                    .db
422                    .persist_metadata()
423                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
424                // Eagerly construct the state so the TurboExtent (if
425                // any) is reserved at creation time rather than on
426                // first INSERT. Errors are swallowed: the lazy path in
427                // `turbo_state` will retry on the next access.
428                let _ = self.inner.db.turbo_state(&query.name);
429                return Ok(result);
430            }
431            // KIND blockchain — issue #523 foundation: stored on top of a
432            // Table-shaped collection. The `chain` marker + reserved-column
433            // discipline make the difference. Schema validation, conflict
434            // retries, and `verify_chain` come in later iterations.
435            "blockchain" => CollectionModel::Table,
436            other => {
437                return Err(RedDBError::Query(format!(
438                    "NOT_YET_SUPPORTED: CREATE COLLECTION KIND {other} is not implemented"
439                )));
440            }
441        };
442        let create = CreateTableQuery {
443            collection_model: model,
444            name: query.name.clone(),
445            description: query.description.clone(),
446            columns: Vec::new(),
447            unique_constraints: Vec::new(),
448            if_not_exists: query.if_not_exists,
449            default_ttl_ms: None,
450            metrics_rollup_policies: Vec::new(),
451            context_index_fields: Vec::new(),
452            context_index_enabled: false,
453            timestamps: false,
454            partition_by: None,
455            tenant_by: None,
456            append_only: false,
457            subscriptions: Vec::new(),
458            analytics_config: Vec::new(),
459            vault_own_master_key: false,
460            ai_policy: None,
461        };
462        let result = self.execute_create_table(raw_query, &create)?;
463        if query.kind == "blockchain" {
464            self.install_blockchain_kind(&query.name)?;
465        }
466        // Issue #522 — wire `SIGNED_BY (...)` into the runtime. The parser
467        // already produces a validated 32-byte pubkey list; installing
468        // the registry stamps the per-collection signer set into
469        // `red.config` so the INSERT path can load it cheaply.
470        if !query.allowed_signers.is_empty() {
471            let actor = crate::runtime::impl_core::current_user_projected()
472                .unwrap_or_else(|| "@system/create-collection".to_string());
473            crate::runtime::signed_writes_kind::try_install(
474                &self.inner.db.store(),
475                &query.name,
476                &query.allowed_signers,
477                &actor,
478            )?;
479        }
480        Ok(result)
481    }
482
483    /// Stamp `collection.{name}.kind = "chain"` and append the genesis
484    /// row. Idempotent against `IF NOT EXISTS`: if the collection already
485    /// has a row at height 0 we leave it.
486    fn install_blockchain_kind(&self, name: &str) -> RedDBResult<()> {
487        use crate::runtime::blockchain_kind;
488        use crate::storage::unified::{EntityData, EntityId, EntityKind, RowData, UnifiedEntity};
489        use std::sync::Arc;
490
491        let store = self.inner.db.store();
492        blockchain_kind::try_mark_as_chain(&store, name)?;
493
494        let existing_tip = blockchain_kind::try_chain_tip(&store, name)?;
495        if existing_tip.height.is_some() {
496            return Ok(());
497        }
498
499        let fields = blockchain_kind::genesis_fields(blockchain_kind::now_ms());
500        let named: std::collections::HashMap<String, reddb_types::Value> =
501            fields.into_iter().collect();
502        let entity = UnifiedEntity::new(
503            EntityId::new(0),
504            EntityKind::TableRow {
505                table: Arc::from(name),
506                row_id: 0,
507            },
508            EntityData::Row(RowData {
509                columns: Vec::new(),
510                named: Some(named),
511                schema: None,
512            }),
513        );
514        store
515            .insert_auto(name, entity)
516            .map_err(|err| RedDBError::Internal(err.to_string()))?;
517        // #524: prime the in-memory tip cache so the chain-tip endpoint and
518        // subsequent INSERTs don't have to scan the collection to find genesis.
519        if let Some(tip) = blockchain_kind::try_chain_tip_full(&store, name)? {
520            self.inner
521                .chain_tip_cache
522                .lock()
523                .insert(name.to_string(), tip);
524        }
525        Ok(())
526    }
527
528    pub fn execute_create_vector(
529        &self,
530        raw_query: &str,
531        query: &CreateVectorQuery,
532    ) -> RedDBResult<RuntimeQueryResult> {
533        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
534        if is_system_schema_name(&query.name) {
535            return Err(RedDBError::Query("system schema is read-only".to_string()));
536        }
537        let store = self.inner.db.store();
538        if store.get_collection(&query.name).is_some() {
539            if query.if_not_exists {
540                return Ok(RuntimeQueryResult::ok_message(
541                    raw_query.to_string(),
542                    &format!("vector '{}' already exists", query.name),
543                    "create",
544                ));
545            }
546            return Err(RedDBError::Query(format!(
547                "vector '{}' already exists",
548                query.name
549            )));
550        }
551
552        store
553            .create_collection(&query.name)
554            .map_err(|err| RedDBError::Internal(err.to_string()))?;
555        self.inner
556            .db
557            .save_collection_contract(vector_collection_contract(query))
558            .map_err(|err| RedDBError::Internal(err.to_string()))?;
559        if let Some(tenant_id) = crate::runtime::impl_core::current_tenant() {
560            store.set_config_tree(
561                &format!("collection_tenants.{}", query.name),
562                &crate::serde_json::Value::String(tenant_id),
563            );
564        }
565        // Slice G (#675) — register `vector.turbo` as the built-in
566        // baseline for every newly-created vector collection. The
567        // marker is the durable signal `RedDB::turbo_state` reads to
568        // materialise the TurboQuantIndex + TurboExtent on first
569        // INSERT/SEARCH. Pre-existing vector collections were created
570        // without the marker and stay on the brute-force fallback path
571        // until they are explicitly migrated — there is no implicit
572        // backfill in this slice.
573        crate::runtime::vector_turbo_kind::mark_as_turbo(&store, &query.name);
574        self.inner
575            .db
576            .persist_metadata()
577            .map_err(|err| RedDBError::Internal(err.to_string()))?;
578        // Eagerly materialise the per-collection turbo state so the
579        // TurboExtent (when the store is paged) is reserved at CREATE
580        // time rather than on the first INSERT. Failures are swallowed
581        // — the lazy path in `turbo_state` retries on next access.
582        let _ = self.inner.db.turbo_state(&query.name);
583        self.invalidate_result_cache();
584        self.schema_vocabulary_apply(
585            crate::runtime::schema_vocabulary::DdlEvent::CreateCollection {
586                collection: query.name.clone(),
587                columns: Vec::new(),
588                type_tags: Vec::new(),
589                description: None,
590            },
591        );
592
593        Ok(RuntimeQueryResult::ok_message(
594            raw_query.to_string(),
595            &format!("vector '{}' created", query.name),
596            "create",
597        ))
598    }
599
600    fn provision_vault_key_material(
601        &self,
602        collection: &str,
603        own_master_key: bool,
604    ) -> RedDBResult<()> {
605        let auth_store = self.inner.auth_store.read().clone().ok_or_else(|| {
606            RedDBError::Query("CREATE VAULT requires an enabled, unsealed vault".to_string())
607        })?;
608        if !auth_store.is_vault_backed() {
609            return Err(RedDBError::Query(
610                "CREATE VAULT requires an enabled, unsealed vault".to_string(),
611            ));
612        }
613
614        auth_store
615            .ensure_vault_secret_key_result()
616            .map_err(|err| RedDBError::Query(err.to_string()))?;
617
618        if own_master_key
619            && auth_store
620                .vault_kv_get(&vault_master_key_ref(collection))
621                .is_none()
622        {
623            let key = crate::auth::store::random_bytes(32);
624            auth_store
625                .vault_kv_try_set(vault_master_key_ref(collection), hex::encode(key))
626                .map_err(|err| RedDBError::Query(err.to_string()))?;
627        }
628
629        Ok(())
630    }
631
632    /// Execute DROP TABLE
633    ///
634    /// Drops the collection and all its data from the store.
635    pub fn execute_drop_table(
636        &self,
637        raw_query: &str,
638        query: &DropTableQuery,
639    ) -> RedDBResult<RuntimeQueryResult> {
640        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
641        let store = self.inner.db.store();
642        let _publication = store.vault_publication_lock.lock();
643        self.vcs_reject_destructive_ddl(&query.name)?;
644
645        if is_system_schema_name(&query.name) {
646            return Err(RedDBError::Query("system schema is read-only".to_string()));
647        }
648
649        let exists = store.get_collection(&query.name).is_some();
650        if !exists {
651            if query.if_exists {
652                return Ok(RuntimeQueryResult::ok_message(
653                    raw_query.to_string(),
654                    &format!("table '{}' does not exist", query.name),
655                    "drop",
656                ));
657            }
658            return Err(RedDBError::NotFound(format!(
659                "table '{}' not found",
660                query.name
661            )));
662        }
663        let actual =
664            polymorphic_resolver::resolve(&query.name, &self.inner.db.catalog_model_snapshot())?;
665        polymorphic_resolver::ensure_model_match(CollectionModel::Table, actual)?;
666
667        // Emit 1 collection_dropped event before storage is wiped.
668        // Queue is preserved; subscription is removed with the contract below.
669        let final_count = store
670            .get_collection(&query.name)
671            .map(|manager| manager.query_all(|_| true).len() as u64)
672            .unwrap_or(0);
673        crate::runtime::mutation::emit_collection_dropped_event_for_collection(
674            self,
675            &query.name,
676            final_count,
677        )?;
678
679        let topology_lock = self.inner.index_store.collection_topology_lock(&query.name);
680        let _topology_guard = topology_lock.write();
681        let orphaned_indices: Vec<String> = self
682            .inner
683            .index_store
684            .list_indices(&query.name)
685            .into_iter()
686            .map(|index| index.name)
687            .collect();
688        for name in &orphaned_indices {
689            self.inner.index_store.drop_index(name, &query.name);
690        }
691
692        store
693            .drop_collection(&query.name)
694            .map_err(|err| RedDBError::Internal(err.to_string()))?;
695        self.inner.db.invalidate_vector_index(&query.name);
696        self.inner.db.clear_collection_default_ttl_ms(&query.name);
697        self.inner
698            .db
699            .remove_collection_contract(&query.name)
700            .map_err(|err| RedDBError::Internal(err.to_string()))?;
701        self.clear_table_planner_stats(&query.name);
702        self.invalidate_result_cache();
703        // Issue #119: a dropped collection vanishes from every
704        // (tenant, role)'s visible-collections set. Auth is optional in
705        // embedded mode so guard the call.
706        if let Some(store) = self.inner.auth_store.read().clone() {
707            store.invalidate_visible_collections_cache();
708        }
709        // The native registry and targeted contract metadata publication above
710        // are the DROP commit boundary; do not turn this into a full database
711        // fingerprint/checkpoint.
712        // Issue #120 — drop both the collection entries *and* every
713        // index entry that was scoped to this collection.  Dropping the
714        // collection wipes columns + collection-name + type-tags +
715        // index hits in one pass via `purge_collection_entries`, so
716        // the explicit `DropIndex` calls would be redundant.
717        self.schema_vocabulary_apply(
718            crate::runtime::schema_vocabulary::DdlEvent::DropCollection {
719                collection: query.name.clone(),
720            },
721        );
722
723        Ok(RuntimeQueryResult::ok_message(
724            raw_query.to_string(),
725            &format!("table '{}' dropped", query.name),
726            "drop",
727        ))
728    }
729
730    pub fn execute_drop_graph(
731        &self,
732        raw_query: &str,
733        query: &DropGraphQuery,
734    ) -> RedDBResult<RuntimeQueryResult> {
735        self.execute_drop_typed_collection(
736            raw_query,
737            &query.name,
738            query.if_exists,
739            CollectionModel::Graph,
740            "graph",
741        )
742    }
743
744    pub fn execute_drop_vector(
745        &self,
746        raw_query: &str,
747        query: &DropVectorQuery,
748    ) -> RedDBResult<RuntimeQueryResult> {
749        self.execute_drop_typed_collection(
750            raw_query,
751            &query.name,
752            query.if_exists,
753            CollectionModel::Vector,
754            "vector",
755        )
756    }
757
758    pub fn execute_drop_document(
759        &self,
760        raw_query: &str,
761        query: &DropDocumentQuery,
762    ) -> RedDBResult<RuntimeQueryResult> {
763        self.execute_drop_typed_collection(
764            raw_query,
765            &query.name,
766            query.if_exists,
767            CollectionModel::Document,
768            "document",
769        )
770    }
771
772    pub fn execute_drop_kv(
773        &self,
774        raw_query: &str,
775        query: &DropKvQuery,
776    ) -> RedDBResult<RuntimeQueryResult> {
777        let label = polymorphic_resolver::model_name(query.model);
778        self.execute_drop_typed_collection(
779            raw_query,
780            &query.name,
781            query.if_exists,
782            query.model,
783            label,
784        )
785    }
786
787    pub fn execute_drop_collection(
788        &self,
789        raw_query: &str,
790        query: &DropCollectionQuery,
791    ) -> RedDBResult<RuntimeQueryResult> {
792        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
793        if is_system_schema_name(&query.name) {
794            return Err(RedDBError::Query("system schema is read-only".to_string()));
795        }
796        let store = self.inner.db.store();
797        let _publication = store.vault_publication_lock.lock();
798        self.vcs_reject_destructive_ddl(&query.name)?;
799        if store.get_collection(&query.name).is_none() {
800            if query.if_exists {
801                return Ok(RuntimeQueryResult::ok_message(
802                    raw_query.to_string(),
803                    &format!("collection '{}' does not exist", query.name),
804                    "drop",
805                ));
806            }
807            return Err(RedDBError::NotFound(format!(
808                "collection '{}' not found",
809                query.name
810            )));
811        }
812
813        let actual =
814            polymorphic_resolver::resolve(&query.name, &self.inner.db.catalog_model_snapshot())?;
815        if let Some(expected) = query.model {
816            polymorphic_resolver::ensure_model_match(expected, actual)?;
817        }
818
819        match actual {
820            CollectionModel::Table => self.execute_drop_table(
821                raw_query,
822                &DropTableQuery {
823                    name: query.name.clone(),
824                    if_exists: query.if_exists,
825                },
826            ),
827            CollectionModel::TimeSeries => self.execute_drop_timeseries(
828                raw_query,
829                &DropTimeSeriesQuery {
830                    name: query.name.clone(),
831                    if_exists: query.if_exists,
832                },
833            ),
834            CollectionModel::Queue => self.execute_drop_queue(
835                raw_query,
836                &DropQueueQuery {
837                    name: query.name.clone(),
838                    if_exists: query.if_exists,
839                },
840            ),
841            CollectionModel::Graph => self.execute_drop_graph(
842                raw_query,
843                &DropGraphQuery {
844                    name: query.name.clone(),
845                    if_exists: query.if_exists,
846                },
847            ),
848            CollectionModel::Vector => self.execute_drop_vector(
849                raw_query,
850                &DropVectorQuery {
851                    name: query.name.clone(),
852                    if_exists: query.if_exists,
853                },
854            ),
855            CollectionModel::Document => self.execute_drop_document(
856                raw_query,
857                &DropDocumentQuery {
858                    name: query.name.clone(),
859                    if_exists: query.if_exists,
860                },
861            ),
862            CollectionModel::Kv => self.execute_drop_kv(
863                raw_query,
864                &DropKvQuery {
865                    name: query.name.clone(),
866                    if_exists: query.if_exists,
867                    model: CollectionModel::Kv,
868                },
869            ),
870            CollectionModel::Config => self.execute_drop_kv(
871                raw_query,
872                &DropKvQuery {
873                    name: query.name.clone(),
874                    if_exists: query.if_exists,
875                    model: CollectionModel::Config,
876                },
877            ),
878            CollectionModel::Vault => self.execute_drop_kv(
879                raw_query,
880                &DropKvQuery {
881                    name: query.name.clone(),
882                    if_exists: query.if_exists,
883                    model: CollectionModel::Vault,
884                },
885            ),
886            CollectionModel::Hll => self.execute_probabilistic_command(
887                raw_query,
888                &ProbabilisticCommand::DropHll {
889                    name: query.name.clone(),
890                    if_exists: query.if_exists,
891                },
892            ),
893            CollectionModel::Sketch => self.execute_probabilistic_command(
894                raw_query,
895                &ProbabilisticCommand::DropSketch {
896                    name: query.name.clone(),
897                    if_exists: query.if_exists,
898                },
899            ),
900            CollectionModel::Filter => self.execute_probabilistic_command(
901                raw_query,
902                &ProbabilisticCommand::DropFilter {
903                    name: query.name.clone(),
904                    if_exists: query.if_exists,
905                },
906            ),
907            CollectionModel::Metrics => self.execute_drop_typed_collection(
908                raw_query,
909                &query.name,
910                query.if_exists,
911                CollectionModel::Metrics,
912                "metrics",
913            ),
914            CollectionModel::Mixed => self.execute_drop_typed_collection(
915                raw_query,
916                &query.name,
917                query.if_exists,
918                CollectionModel::Mixed,
919                "collection",
920            ),
921        }
922    }
923
924    /// Issue #801 — guard `ALTER GRAPH ... ADD|DROP ANALYTICS` so analytics
925    /// lifecycle mutations only land on a collection declared as a graph. The
926    /// `<graph>.<output>` resolver only consults `analytics_config` on
927    /// graph-model contracts, so allowing the op on any other model would write
928    /// dead config the reader can never surface.
929    fn require_graph_for_analytics(&self, name: &str) -> RedDBResult<()> {
930        let is_graph = self
931            .inner
932            .db
933            .collection_contract(name)
934            .map(|c| c.declared_model == crate::catalog::CollectionModel::Graph)
935            .unwrap_or(false);
936        if !is_graph {
937            return Err(RedDBError::Query(format!(
938                "ALTER GRAPH ... ANALYTICS: '{name}' is not a graph collection"
939            )));
940        }
941        Ok(())
942    }
943
944    /// Execute ALTER TABLE
945    ///
946    /// In RedDB's schema-on-read model, ALTER TABLE operations are advisory.
947    /// ADD COLUMN records the schema intent, DROP COLUMN removes it, and
948    /// RENAME COLUMN is a metadata rename.  Existing data is not rewritten.
949    pub fn execute_alter_table(
950        &self,
951        raw_query: &str,
952        query: &AlterTableQuery,
953    ) -> RedDBResult<RuntimeQueryResult> {
954        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
955        let expression_contract =
956            self.db()
957                .collection_contract(&query.name)
958                .is_some_and(|contract| {
959                    crate::application::collection_contract_enforcer::has_contract_expressions(
960                        &contract,
961                    )
962                });
963        if query.operations.iter().any(|operation| match operation {
964            AlterOperation::AddColumn(column) => {
965                expression_contract || column.generated.is_some() || column.check.is_some()
966            }
967            AlterOperation::DropColumn(_) | AlterOperation::RenameColumn { .. } => {
968                expression_contract
969            }
970            _ => false,
971        }) {
972            return Err(RedDBError::Query("ALTER of expression schemas requires validated backfill; create a new collection and import explicitly".to_string()));
973        }
974
975        let store = self.inner.db.store();
976
977        // Verify the table exists.
978        if store.get_collection(&query.name).is_none() {
979            return Err(RedDBError::NotFound(format!(
980                "table '{}' not found",
981                query.name
982            )));
983        }
984
985        let mut messages = Vec::new();
986        let existing_contract = self.inner.db.collection_contract(&query.name);
987        for operation in &query.operations {
988            if let AlterOperation::SetDescription {
989                column: Some(name), ..
990            } = operation
991            {
992                if !existing_contract.as_ref().is_some_and(|contract| {
993                    contract
994                        .declared_columns
995                        .iter()
996                        .any(|declared| declared.name == *name)
997                }) {
998                    return Err(RedDBError::NotFound(format!(
999                        "column '{}' not found in collection '{}'",
1000                        name, query.name
1001                    )));
1002                }
1003            }
1004        }
1005
1006        // Collect column-level changes upfront for schema-change event emission below.
1007        let fields_added: Vec<String> = query
1008            .operations
1009            .iter()
1010            .filter_map(|op| {
1011                if let AlterOperation::AddColumn(col) = op {
1012                    Some(col.name.clone())
1013                } else {
1014                    None
1015                }
1016            })
1017            .collect();
1018        let fields_removed: Vec<String> = query
1019            .operations
1020            .iter()
1021            .filter_map(|op| {
1022                if let AlterOperation::DropColumn(name) = op {
1023                    Some(name.clone())
1024                } else {
1025                    None
1026                }
1027            })
1028            .collect();
1029
1030        for op in &query.operations {
1031            match op {
1032                AlterOperation::AddColumn(col) => {
1033                    // Schema-on-read: column will be available on next insert.
1034                    messages.push(format!("column '{}' added", col.name));
1035                }
1036                AlterOperation::DropColumn(name) => {
1037                    messages.push(format!("column '{}' dropped", name));
1038                }
1039                AlterOperation::RenameColumn { from, to } => {
1040                    messages.push(format!("column '{}' renamed to '{}'", from, to));
1041                }
1042                AlterOperation::SetDescription { column, .. } => {
1043                    messages.push(match column {
1044                        Some(name) => format!("column '{}' description set", name),
1045                        None => "collection description set".to_string(),
1046                    });
1047                }
1048                AlterOperation::AttachPartition { child, bound } => {
1049                    // Persist child → parent binding in red.config so the
1050                    // future planner-side pruner can enumerate children and
1051                    // evaluate their bounds.
1052                    store.set_config_tree(
1053                        &format!("partition.{}.children.{}", query.name, child),
1054                        &crate::serde_json::Value::String(bound.clone()),
1055                    );
1056                    messages.push(format!(
1057                        "partition '{child}' attached to '{}' ({bound})",
1058                        query.name
1059                    ));
1060                }
1061                AlterOperation::DetachPartition { child } => {
1062                    store.set_config_tree(
1063                        &format!("partition.{}.children.{}", query.name, child),
1064                        &crate::serde_json::Value::Null,
1065                    );
1066                    messages.push(format!(
1067                        "partition '{child}' detached from '{}'",
1068                        query.name
1069                    ));
1070                }
1071                AlterOperation::EnableRowLevelSecurity => {
1072                    self.inner
1073                        .rls_enabled_tables
1074                        .write()
1075                        .insert(query.name.clone());
1076                    // Persist flag so RLS survives restart via red.config.
1077                    store.set_config_tree(
1078                        &format!("rls.enabled.{}", query.name),
1079                        &crate::serde_json::Value::Bool(true),
1080                    );
1081                    self.invalidate_plan_cache();
1082                    messages.push(format!("row level security enabled on '{}'", query.name));
1083                    self.invalidate_result_cache();
1084                }
1085                AlterOperation::DisableRowLevelSecurity => {
1086                    self.inner.rls_enabled_tables.write().remove(&query.name);
1087                    store.set_config_tree(
1088                        &format!("rls.enabled.{}", query.name),
1089                        &crate::serde_json::Value::Null,
1090                    );
1091                    self.invalidate_plan_cache();
1092                    messages.push(format!("row level security disabled on '{}'", query.name));
1093                    self.invalidate_result_cache();
1094                }
1095                // Phase 2.5.4: retrofit tenancy onto an existing table.
1096                AlterOperation::EnableTenancy { column } => {
1097                    store.set_config_tree(
1098                        &format!("tenant_tables.{}.column", query.name),
1099                        &crate::serde_json::Value::String(column.clone()),
1100                    );
1101                    self.register_tenant_table(&query.name, column);
1102                    self.invalidate_plan_cache();
1103                    messages.push(format!(
1104                        "tenancy enabled on '{}' by column '{column}'",
1105                        query.name
1106                    ));
1107                }
1108                AlterOperation::DisableTenancy => {
1109                    store.set_config_tree(
1110                        &format!("tenant_tables.{}.column", query.name),
1111                        &crate::serde_json::Value::Null,
1112                    );
1113                    self.unregister_tenant_table(&query.name);
1114                    self.invalidate_plan_cache();
1115                    messages.push(format!("tenancy disabled on '{}'", query.name));
1116                }
1117                AlterOperation::SetAppendOnly(on) => {
1118                    // Contract is the single source of truth for the
1119                    // UPDATE/DELETE parse-time guard. The flag lands
1120                    // below via `apply_alter_operations_to_contract`;
1121                    // here we only publish the human-readable message.
1122                    messages.push(format!(
1123                        "append_only {} on '{}'",
1124                        if *on { "enabled" } else { "disabled" },
1125                        query.name
1126                    ));
1127                }
1128                AlterOperation::SetVersioned(on) => {
1129                    // Opt the collection into (or out of) Git-for-Data.
1130                    // Persists a row in red.vcs.settings; next AS OF /
1131                    // merge / diff against this table honours the
1132                    // flag. Retroactive: existing row versions whose
1133                    // xmins are still pinned by commits become
1134                    // reachable via AS OF COMMIT immediately.
1135                    self.vcs_set_versioned(&query.name, *on)?;
1136                    messages.push(format!(
1137                        "versioned {} on '{}'",
1138                        if *on { "enabled" } else { "disabled" },
1139                        query.name
1140                    ));
1141                }
1142                AlterOperation::EnableEvents(subscription) => {
1143                    let mut subscription = subscription.clone();
1144                    subscription.source = query.name.clone();
1145                    validate_event_subscriptions(
1146                        self,
1147                        &query.name,
1148                        std::slice::from_ref(&subscription),
1149                    )?;
1150                    ensure_event_target_queue(self, &subscription.target_queue)?;
1151                    messages.push(format!(
1152                        "events enabled on '{}' to '{}'",
1153                        query.name, subscription.target_queue
1154                    ));
1155                }
1156                AlterOperation::DisableEvents => {
1157                    messages.push(format!("events disabled on '{}'", query.name));
1158                }
1159                AlterOperation::AddSubscription { name, descriptor } => {
1160                    let mut sub = descriptor.clone();
1161                    sub.name = name.clone();
1162                    sub.source = query.name.clone();
1163                    validate_event_subscriptions(self, &query.name, std::slice::from_ref(&sub))?;
1164                    ensure_event_target_queue(self, &sub.target_queue)?;
1165                    messages.push(format!(
1166                        "subscription '{}' added on '{}' to '{}'",
1167                        name, query.name, sub.target_queue
1168                    ));
1169                }
1170                AlterOperation::DropSubscription { name } => {
1171                    messages.push(format!(
1172                        "subscription '{}' dropped on '{}'",
1173                        name, query.name
1174                    ));
1175                }
1176                AlterOperation::AddSigner { pubkey } => {
1177                    // Issue #522 — admin-gated registry mutation. The
1178                    // standard DDL `check_write` above gates by role; we
1179                    // additionally verify the collection actually has a
1180                    // signed-writes registry installed so this isn't a
1181                    // covert way to retrofit one (use `CREATE COLLECTION
1182                    // ... SIGNED_BY (...)` for that).
1183                    if !crate::runtime::signed_writes_kind::try_is_signed(&store, &query.name)? {
1184                        return Err(RedDBError::Query(format!(
1185                            "ALTER COLLECTION ADD SIGNER: '{}' has no signer registry; \
1186                             recreate it with CREATE COLLECTION ... SIGNED_BY (...)",
1187                            query.name
1188                        )));
1189                    }
1190                    let actor = crate::runtime::impl_core::current_user_projected()
1191                        .unwrap_or_else(|| "@system/alter".to_string());
1192                    let changed = crate::runtime::signed_writes_kind::try_add_signer(
1193                        &store,
1194                        &query.name,
1195                        *pubkey,
1196                        &actor,
1197                    )?;
1198                    messages.push(format!(
1199                        "signer {} on '{}'",
1200                        if changed { "added" } else { "already present" },
1201                        query.name
1202                    ));
1203                }
1204                AlterOperation::RevokeSigner { pubkey } => {
1205                    if !crate::runtime::signed_writes_kind::try_is_signed(&store, &query.name)? {
1206                        return Err(RedDBError::Query(format!(
1207                            "ALTER COLLECTION REVOKE SIGNER: '{}' has no signer registry",
1208                            query.name
1209                        )));
1210                    }
1211                    let actor = crate::runtime::impl_core::current_user_projected()
1212                        .unwrap_or_else(|| "@system/alter".to_string());
1213                    let changed = crate::runtime::signed_writes_kind::try_revoke_signer(
1214                        &store,
1215                        &query.name,
1216                        pubkey,
1217                        &actor,
1218                    )?;
1219                    messages.push(format!(
1220                        "signer {} on '{}'",
1221                        if changed {
1222                            "revoked"
1223                        } else {
1224                            "already revoked"
1225                        },
1226                        query.name
1227                    ));
1228                }
1229                AlterOperation::SetRetention { duration_ms } => {
1230                    // Issue #580 — validate that the collection has a
1231                    // timestamp column the lazy-on-scan filter can key
1232                    // off. Without one there is no anchor for "older
1233                    // than now - duration"; reject at ALTER time so the
1234                    // policy can never silently hide all rows.
1235                    let existing = self.inner.db.collection_contract(&query.name);
1236                    let has_ts_column = existing
1237                        .as_ref()
1238                        .map(retention_timestamp_column_exists)
1239                        .unwrap_or(false);
1240                    if !has_ts_column {
1241                        return Err(RedDBError::Query(format!(
1242                            "ALTER COLLECTION SET RETENTION: '{}' has no timestamp \
1243                             column — declare a TIMESTAMP/TIMESTAMPMS/DATETIME column \
1244                             or enable WITH timestamps = true before setting a \
1245                             retention policy",
1246                            query.name
1247                        )));
1248                    }
1249                    messages.push(format!(
1250                        "retention set to {duration_ms} ms on '{}'",
1251                        query.name
1252                    ));
1253                }
1254                AlterOperation::UnsetRetention => {
1255                    messages.push(format!("retention cleared on '{}'", query.name));
1256                }
1257                AlterOperation::AddAnalytics(views) => {
1258                    // Issue #801 — analytics lifecycle is graph-only. Reject the
1259                    // op on a non-graph collection so a misrouted ALTER fails
1260                    // loudly instead of silently writing analytics_config onto a
1261                    // model whose reader never resolves `<name>.<output>`.
1262                    self.require_graph_for_analytics(&query.name)?;
1263                    let existing = self.inner.db.collection_contract(&query.name);
1264                    let enabled: std::collections::BTreeSet<crate::catalog::AnalyticsOutput> =
1265                        existing
1266                            .as_ref()
1267                            .map(|c| c.analytics_config.iter().map(|v| v.output).collect())
1268                            .unwrap_or_default();
1269                    for view in views {
1270                        if enabled.contains(&view.output) {
1271                            // Idempotent: adding an already-enabled output is a
1272                            // no-op — no error, no duplicate state.
1273                            messages.push(format!(
1274                                "analytics '{}' already enabled on '{}'",
1275                                view.output.as_str(),
1276                                query.name
1277                            ));
1278                        } else {
1279                            messages.push(format!(
1280                                "analytics '{}' enabled on '{}'",
1281                                view.output.as_str(),
1282                                query.name
1283                            ));
1284                        }
1285                    }
1286                }
1287                AlterOperation::DropAnalytics(output) => {
1288                    self.require_graph_for_analytics(&query.name)?;
1289                    let enabled = self
1290                        .inner
1291                        .db
1292                        .collection_contract(&query.name)
1293                        .map(|c| c.analytics_config.iter().any(|v| v.output == *output))
1294                        .unwrap_or(false);
1295                    if !enabled {
1296                        // Dropping an output that was never enabled is a clean,
1297                        // explicit error (AC4) rather than a silent no-op.
1298                        return Err(RedDBError::Query(format!(
1299                            "ALTER GRAPH DROP ANALYTICS: analytics output '{}' is not enabled on graph '{}'",
1300                            output.as_str(),
1301                            query.name
1302                        )));
1303                    }
1304                    messages.push(format!(
1305                        "analytics '{}' disabled on '{}'",
1306                        output.as_str(),
1307                        query.name
1308                    ));
1309                }
1310            }
1311        }
1312
1313        let mut contract = self
1314            .inner
1315            .db
1316            .collection_contract(&query.name)
1317            .unwrap_or_else(|| default_collection_contract_for_existing_table(&query.name));
1318        apply_alter_operations_to_contract(&mut contract, &query.operations);
1319        contract.version = contract.version.saturating_add(1);
1320        contract.updated_at_unix_ms = current_unix_ms();
1321        self.inner
1322            .db
1323            .save_collection_contract(contract)
1324            .map_err(|err| RedDBError::Internal(err.to_string()))?;
1325        // Issue #301 — emit OperatorEvent when column schema changes on a
1326        // collection that has active event subscriptions, so operators know
1327        // downstream consumers may see a different payload shape.
1328        if !fields_added.is_empty() || !fields_removed.is_empty() {
1329            let sub_names: Vec<String> = self
1330                .inner
1331                .db
1332                .collection_contract(&query.name)
1333                .map(|c| {
1334                    c.subscriptions
1335                        .iter()
1336                        .filter(|s| s.enabled)
1337                        .map(|s| s.name.clone())
1338                        .collect()
1339                })
1340                .unwrap_or_default();
1341            if !sub_names.is_empty() {
1342                crate::telemetry::operator_event::OperatorEvent::SubscriptionSchemaChange {
1343                    collection: query.name.clone(),
1344                    subscription_names: sub_names.join(", "),
1345                    fields_added: fields_added.join(", "),
1346                    fields_removed: fields_removed.join(", "),
1347                    lsn: self.cdc_current_lsn(),
1348                }
1349                .emit_global();
1350            }
1351        }
1352
1353        self.clear_table_planner_stats(&query.name);
1354        self.invalidate_result_cache();
1355        // Issue #120 — refresh the schema-vocabulary entries from the
1356        // post-ALTER contract. Drop+recreate inside the index keeps
1357        // the invalidation guarantee complete (no stale columns from
1358        // before an ALTER ... DROP COLUMN).
1359        let post_alter_columns: Vec<String> = self
1360            .inner
1361            .db
1362            .collection_contract(&query.name)
1363            .map(|contract| {
1364                contract
1365                    .declared_columns
1366                    .iter()
1367                    .map(|col| col.name.clone())
1368                    .collect()
1369            })
1370            .unwrap_or_default();
1371        self.schema_vocabulary_apply(
1372            crate::runtime::schema_vocabulary::DdlEvent::AlterCollection {
1373                collection: query.name.clone(),
1374                columns: post_alter_columns,
1375                type_tags: Vec::new(),
1376                description: self
1377                    .inner
1378                    .db
1379                    .collection_contract(&query.name)
1380                    .and_then(|contract| contract.description),
1381            },
1382        );
1383        self.schema_vocabulary_sync_descriptions(&query.name);
1384
1385        let message = if messages.is_empty() {
1386            format!("table '{}' altered (no operations)", query.name)
1387        } else {
1388            format!("table '{}' altered: {}", query.name, messages.join(", "))
1389        };
1390
1391        Ok(RuntimeQueryResult::ok_message(
1392            raw_query.to_string(),
1393            &message,
1394            "alter",
1395        ))
1396    }
1397
1398    pub fn execute_create_vcs_ref(
1399        &self,
1400        raw_query: &str,
1401        query: &CreateVcsRefQuery,
1402    ) -> RedDBResult<RuntimeQueryResult> {
1403        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1404        let connection_id = crate::runtime::impl_core::current_connection_id();
1405        match query.kind {
1406            VcsRefKind::Branch => {
1407                self.vcs_branch_create(crate::application::vcs::CreateBranchInput {
1408                    name: query.name.clone(),
1409                    from: query.target.clone(),
1410                    connection_id,
1411                })?;
1412            }
1413            VcsRefKind::Tag => {
1414                let target = match &query.target {
1415                    Some(target) => target.clone(),
1416                    None => self
1417                        .vcs_status(crate::application::vcs::StatusInput { connection_id })?
1418                        .head_commit
1419                        .filter(|head| !head.is_empty())
1420                        .ok_or_else(|| {
1421                            RedDBError::InvalidConfig(
1422                                "cannot create tag: HEAD has no commits".to_string(),
1423                            )
1424                        })?,
1425                };
1426                self.vcs_tag_create(crate::application::vcs::CreateTagInput {
1427                    name: query.name.clone(),
1428                    target,
1429                    annotation: None,
1430                })?;
1431            }
1432        }
1433        let kind = match query.kind {
1434            VcsRefKind::Branch => "branch",
1435            VcsRefKind::Tag => "tag",
1436        };
1437        Ok(RuntimeQueryResult::ok_message(
1438            raw_query.to_string(),
1439            &format!("{kind} '{}' created", query.name),
1440            "create",
1441        ))
1442    }
1443
1444    pub fn execute_drop_vcs_ref(
1445        &self,
1446        raw_query: &str,
1447        query: &DropVcsRefQuery,
1448    ) -> RedDBResult<RuntimeQueryResult> {
1449        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1450        match query.kind {
1451            VcsRefKind::Branch => self.vcs_branch_delete(&query.name)?,
1452            VcsRefKind::Tag => self.vcs_tag_delete(&query.name)?,
1453        }
1454        let kind = match query.kind {
1455            VcsRefKind::Branch => "branch",
1456            VcsRefKind::Tag => "tag",
1457        };
1458        Ok(RuntimeQueryResult::ok_message(
1459            raw_query.to_string(),
1460            &format!("{kind} '{}' dropped", query.name),
1461            "drop",
1462        ))
1463    }
1464
1465    pub fn execute_fork_store(
1466        &self,
1467        raw_query: &str,
1468        query: &ForkStoreQuery,
1469    ) -> RedDBResult<RuntimeQueryResult> {
1470        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1471        let fork = self.fork_store_at_lsn(&query.name, query.at_lsn)?;
1472        let path = self
1473            .fork_store_path(&query.name)?
1474            .ok_or_else(|| RedDBError::Internal("created fork path is missing".into()))?;
1475        Ok(RuntimeQueryResult::ok_message(
1476            raw_query.to_string(),
1477            &format!(
1478                "store fork '{}' created at LSN {}; database {}",
1479                fork.name,
1480                fork.fork_lsn,
1481                path.display()
1482            ),
1483            "fork_store",
1484        ))
1485    }
1486
1487    pub fn execute_drop_fork(
1488        &self,
1489        raw_query: &str,
1490        query: &DropForkQuery,
1491    ) -> RedDBResult<RuntimeQueryResult> {
1492        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1493        if !self.drop_fork_store(&query.name)? && !query.if_exists {
1494            return Err(RedDBError::NotFound(format!("store fork '{}'", query.name)));
1495        }
1496        Ok(RuntimeQueryResult::ok_message(
1497            raw_query.to_string(),
1498            &format!("store fork '{}' dropped", query.name),
1499            "drop_fork",
1500        ))
1501    }
1502
1503    pub fn execute_promote_fork(
1504        &self,
1505        raw_query: &str,
1506        query: &PromoteForkQuery,
1507    ) -> RedDBResult<RuntimeQueryResult> {
1508        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1509        let path = self.promote_fork_store(&query.name)?;
1510        Ok(RuntimeQueryResult::ok_message(raw_query.to_string(),
1511            &format!("store fork '{}' promoted; reopen the server with database {}; the previous database is preserved", query.name, path.display()), "promote_fork"))
1512    }
1513
1514    /// Execute EXPLAIN ALTER FOR CREATE TABLE
1515    ///
1516    /// Pure read: computes the schema diff between the target table's
1517    /// current `CollectionContract` and the embedded `CREATE TABLE` body,
1518    /// and returns it as SQL `ALTER TABLE` text (default) or structured
1519    /// JSON. Never mutates storage.
1520    pub fn execute_explain_alter(
1521        &self,
1522        raw_query: &str,
1523        query: &ExplainAlterQuery,
1524    ) -> RedDBResult<RuntimeQueryResult> {
1525        // Validate the target CREATE TABLE body so syntactically valid
1526        // but semantically broken targets (bad SQL types, duplicate
1527        // columns) are caught here rather than inside the diff engine.
1528        let analyzed = analyze_create_table(&query.target)
1529            .map_err(|err| RedDBError::Query(err.to_string()))?;
1530
1531        let current_contract = self.inner.db.collection_contract(&query.target.name);
1532
1533        // The column-diff planner cannot emit ADD/DROP CONSTRAINT. Do not
1534        // silently report a complete migration when table-level UNIQUE changes.
1535        let current_unique = current_contract
1536            .as_ref()
1537            .map(|contract| {
1538                contract
1539                    .table_def
1540                    .iter()
1541                    .flat_map(|table| &table.constraints)
1542                    .filter(|constraint| {
1543                        constraint.constraint_type == reddb_types::ConstraintType::Unique
1544                            && !contract.declared_columns.iter().any(|column| {
1545                                column.unique
1546                                    && constraint.columns == [column.name.clone()]
1547                                    && constraint.name == format!("uniq_{}", column.name)
1548                            })
1549                    })
1550                    .map(|constraint| (constraint.name.clone(), constraint.columns.clone()))
1551                    .collect::<BTreeSet<_>>()
1552            })
1553            .unwrap_or_default();
1554        let target_unique = analyzed
1555            .unique_constraints
1556            .into_iter()
1557            .map(|constraint| (constraint.name, constraint.columns))
1558            .collect::<BTreeSet<_>>();
1559        if current_unique != target_unique {
1560            return Err(RedDBError::Query("NOT_YET_SUPPORTED: EXPLAIN ALTER cannot plan changes to table-level UNIQUE constraints".to_string()));
1561        }
1562
1563        let current_columns: Vec<crate::physical::DeclaredColumnContract> = current_contract
1564            .as_ref()
1565            .map(|c| c.declared_columns.clone())
1566            .unwrap_or_default();
1567
1568        let diff = super::schema_diff::compute_column_diff(
1569            &query.target.name,
1570            &current_columns,
1571            &query.target.columns,
1572        );
1573
1574        let rendered = match query.format {
1575            ExplainFormat::Sql => super::schema_diff::format_as_sql(&diff),
1576            ExplainFormat::Json => super::schema_diff::format_as_json(&diff),
1577        };
1578
1579        let format_label = match query.format {
1580            ExplainFormat::Sql => "sql",
1581            ExplainFormat::Json => "json",
1582        };
1583
1584        let columns = vec![
1585            "table".to_string(),
1586            "format".to_string(),
1587            "diff".to_string(),
1588        ];
1589        let row = vec![
1590            ("table".to_string(), Value::text(query.target.name.clone())),
1591            ("format".to_string(), Value::text(format_label.to_string())),
1592            ("diff".to_string(), Value::text(rendered)),
1593        ];
1594
1595        Ok(RuntimeQueryResult::ok_records(
1596            raw_query.to_string(),
1597            columns,
1598            vec![row],
1599            "explain",
1600        ))
1601    }
1602
1603    /// Execute CREATE INDEX
1604    ///
1605    /// Registers a new index on a collection, builds it from existing data,
1606    /// and makes it available to the query executor for O(1) lookups.
1607    pub fn execute_create_index(
1608        &self,
1609        raw_query: &str,
1610        query: &CreateIndexQuery,
1611    ) -> RedDBResult<RuntimeQueryResult> {
1612        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1613        let topology_lock = self
1614            .inner
1615            .index_store
1616            .collection_topology_lock(&query.table);
1617        let _topology_guard = topology_lock.write();
1618        let store = self.inner.db.store();
1619
1620        // Verify the table exists
1621        let manager = store
1622            .get_collection(&query.table)
1623            .ok_or_else(|| RedDBError::NotFound(format!("table '{}' not found", query.table)))?;
1624
1625        if query.if_not_exists
1626            && self
1627                .inner
1628                .index_store
1629                .list_indices(&query.table)
1630                .iter()
1631                .any(|index| index.name == query.name)
1632        {
1633            return Ok(RuntimeQueryResult::ok_message(
1634                raw_query.to_string(),
1635                &format!(
1636                    "index '{}' already exists on '{}'; skipped",
1637                    query.name, query.table
1638                ),
1639                "create",
1640            ));
1641        }
1642
1643        let method_kind = match query.method {
1644            IndexMethod::Hash => super::index_store::IndexMethodKind::Hash,
1645            IndexMethod::BTree => super::index_store::IndexMethodKind::BTree,
1646            IndexMethod::Bitmap => super::index_store::IndexMethodKind::Bitmap,
1647            // Generic spatial request → engine default spatial backend
1648            // (disk-resident H3 as of PRD #1574 slice 4, #1578).
1649            IndexMethod::Spatial => super::index_store::IndexMethodKind::default_spatial(),
1650            IndexMethod::H3 { resolution } => {
1651                super::index_store::IndexMethodKind::H3 { resolution }
1652            }
1653        };
1654
1655        // Extract fields from existing entities for indexing. Row
1656        // entities may arrive in either the "named" HashMap layout
1657        // (gRPC `BulkInsertBinary` path) OR the columnar layout
1658        // (HTTP `POST /collections/X/bulk/rows` fast path, which uses
1659        // `schema: Some(Arc<Vec<String>>)` + `columns: Vec<Value>` and
1660        // leaves `named == None`). Prior to this commit the columnar
1661        // branch returned an empty field list, so `CREATE INDEX` built
1662        // a zero-entity index over HTTP-inserted data even though the
1663        // data was queryable via `SELECT`.
1664        let index_fields = |e: &crate::storage::UnifiedEntity| -> Vec<(String, Value)> {
1665            match &e.data {
1666                crate::storage::EntityData::Row(row) => {
1667                    if let Some(ref named) = row.named {
1668                        named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
1669                    } else if let Some(ref schema) = row.schema {
1670                        // Columnar layout — pair each column
1671                        // with its positional name from the
1672                        // shared schema Arc.
1673                        schema
1674                            .iter()
1675                            .zip(row.columns.iter())
1676                            .map(|(k, v)| (k.clone(), v.clone()))
1677                            .collect()
1678                    } else {
1679                        Vec::new()
1680                    }
1681                }
1682                crate::storage::EntityData::Node(node) => node
1683                    .properties
1684                    .iter()
1685                    .map(|(k, v)| (k.clone(), v.clone()))
1686                    .collect(),
1687                crate::storage::EntityData::TimeSeries(ts) => ts
1688                    .fields
1689                    .iter()
1690                    .map(|(k, v)| (k.clone(), v.clone()))
1691                    .collect(),
1692                _ => Vec::new(),
1693            }
1694        };
1695        let entities = manager.query_all(|_| true);
1696        let mut entity_fields: Vec<(crate::storage::unified::EntityId, Vec<(String, Value)>)> =
1697            entities.iter().map(|e| (e.id, index_fields(e))).collect();
1698
1699        if query.unique
1700            && matches!(
1701                method_kind,
1702                super::index_store::IndexMethodKind::Hash
1703                    | super::index_store::IndexMethodKind::BTree
1704            )
1705        {
1706            // Only live rows reserve a key: the dead versions of an updated or
1707            // deleted row share its key but are not duplicates. This is DDL
1708            // only — reopening must still rebuild an index over data that an
1709            // older release let duplicate.
1710            let snapshots = self.snapshot_manager();
1711            let own_xids = self.own_transaction_xids();
1712            let mut live = entities.iter().map(|entity| {
1713                snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids)
1714            });
1715            entity_fields.retain(|_| live.next().unwrap_or(false));
1716            let duplicate = if manager.has_backing() {
1717                // `entities` holds the rows in memory; a row that was
1718                // checkpointed is on disk. A table whose duplicates had been
1719                // checkpointed got its unique index, over the duplicates.
1720                // One digest a row stays in memory for the scan.
1721                let mut seen = std::collections::HashMap::new();
1722                let mut duplicate = None;
1723                manager
1724                    .try_scan_for_each(None, usize::MAX, |entity| {
1725                        if !snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids) {
1726                            return true;
1727                        }
1728                        let Some(key) = super::index_store::unique_index_key(
1729                            &query.columns,
1730                            &index_fields(entity),
1731                        ) else {
1732                            return true;
1733                        };
1734                        match seen.insert(*blake3::hash(&key).as_bytes(), entity.id) {
1735                            Some(earlier) => {
1736                                duplicate = Some((earlier, entity.id));
1737                                false
1738                            }
1739                            None => true,
1740                        }
1741                    })
1742                    .map_err(|error| RedDBError::Internal(error.to_string()))?;
1743                duplicate
1744            } else {
1745                super::index_store::first_duplicate_unique_key(&query.columns, &entity_fields)
1746            };
1747            if let Some((earlier, later)) = duplicate {
1748                return Err(RedDBError::Query(format!(
1749                    "cannot create unique index '{}' on '{}': rows {} and {} share the same ({}) key",
1750                    query.name,
1751                    query.table,
1752                    earlier.raw(),
1753                    later.raw(),
1754                    query.columns.join(", ")
1755                )));
1756            }
1757        }
1758
1759        let index_growth_rows = entity_fields
1760            .iter()
1761            .map(|(_, fields)| fields.clone())
1762            .collect::<Vec<_>>();
1763        let _reservation = self.admit_non_evictable_growth(
1764            crate::storage::memory_pools::MemoryPool::IndexMemory,
1765            &format!("create index {}", query.name),
1766            crate::runtime::memory_admission::estimate_index_growth(
1767                &index_growth_rows,
1768                &query.columns,
1769            ),
1770        )?;
1771
1772        // Build the index
1773        let indexed_count = self
1774            .inner
1775            .index_store
1776            .create_index(
1777                &query.name,
1778                &query.table,
1779                &query.columns,
1780                method_kind,
1781                query.unique,
1782                &entity_fields,
1783            )
1784            .map_err(RedDBError::Internal)?;
1785
1786        let analyzed = crate::storage::query::planner::stats_catalog::analyze_entity_fields(
1787            &query.table,
1788            &entity_fields,
1789        );
1790        crate::storage::query::planner::stats_catalog::persist_table_stats(&store, &analyzed);
1791        self.invalidate_plan_cache();
1792
1793        // Register metadata
1794        self.inner
1795            .index_store
1796            .register(super::index_store::RegisteredIndex {
1797                name: query.name.clone(),
1798                collection: query.table.clone(),
1799                columns: query.columns.clone(),
1800                method: method_kind,
1801                unique: query.unique,
1802            });
1803        self.persist_runtime_index_descriptor(super::index_store::RegisteredIndex {
1804            name: query.name.clone(),
1805            collection: query.table.clone(),
1806            columns: query.columns.clone(),
1807            method: method_kind,
1808            unique: query.unique,
1809        })?;
1810        // Issue #120 — surface the index name + indexed columns in
1811        // the schema-vocabulary so AskPipeline (#121) can resolve
1812        // "the email index" back to its collection.
1813        self.schema_vocabulary_apply(crate::runtime::schema_vocabulary::DdlEvent::CreateIndex {
1814            collection: query.table.clone(),
1815            index: query.name.clone(),
1816            columns: query.columns.clone(),
1817        });
1818
1819        let method_str = format!("{}", query.method);
1820        let unique_str = if query.unique { "unique " } else { "" };
1821        let cols = query.columns.join(", ");
1822        let total_count = entity_fields.len();
1823        let coverage_detail =
1824            if matches!(method_kind, super::index_store::IndexMethodKind::H3 { .. })
1825                && total_count > 0
1826                && indexed_count == 0
1827            {
1828                format!(
1829                    "{} of {} entities indexed — no indexable geo value in '{}'; expected {}",
1830                    indexed_count,
1831                    total_count,
1832                    cols,
1833                    crate::geo::RECOGNIZED_GEO_SHAPES
1834                )
1835            } else if matches!(method_kind, super::index_store::IndexMethodKind::H3 { .. }) {
1836                format!("{} of {} entities indexed", indexed_count, total_count)
1837            } else {
1838                format!("{} entities indexed", indexed_count)
1839            };
1840
1841        Ok(RuntimeQueryResult::ok_message(
1842            raw_query.to_string(),
1843            &format!(
1844                "{}index '{}' created on '{}' ({}) using {} ({})",
1845                unique_str, query.name, query.table, cols, method_str, coverage_detail
1846            ),
1847            "create",
1848        ))
1849    }
1850
1851    /// Execute DROP INDEX
1852    ///
1853    /// Removes an index from a collection.
1854    pub fn execute_drop_index(
1855        &self,
1856        raw_query: &str,
1857        query: &DropIndexQuery,
1858    ) -> RedDBResult<RuntimeQueryResult> {
1859        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1860        let topology_lock = self
1861            .inner
1862            .index_store
1863            .collection_topology_lock(&query.table);
1864        let _topology_guard = topology_lock.write();
1865        let store = self.inner.db.store();
1866
1867        // Verify the table exists
1868        if store.get_collection(&query.table).is_none() {
1869            if query.if_exists {
1870                return Ok(RuntimeQueryResult::ok_message(
1871                    raw_query.to_string(),
1872                    &format!("table '{}' does not exist", query.table),
1873                    "drop",
1874                ));
1875            }
1876            return Err(RedDBError::NotFound(format!(
1877                "table '{}' not found",
1878                query.table
1879            )));
1880        }
1881
1882        // Remove from IndexStore
1883        self.inner.index_store.drop_index(&query.name, &query.table);
1884        self.persist_runtime_index_drop(&query.table, &query.name)?;
1885        self.invalidate_plan_cache();
1886        // Issue #120 — keep the schema-vocabulary index entry in sync.
1887        self.schema_vocabulary_apply(crate::runtime::schema_vocabulary::DdlEvent::DropIndex {
1888            collection: query.table.clone(),
1889            index: query.name.clone(),
1890        });
1891
1892        Ok(RuntimeQueryResult::ok_message(
1893            raw_query.to_string(),
1894            &format!("index '{}' dropped from '{}'", query.name, query.table),
1895            "drop",
1896        ))
1897    }
1898
1899    fn execute_drop_typed_collection(
1900        &self,
1901        raw_query: &str,
1902        name: &str,
1903        if_exists: bool,
1904        expected_model: CollectionModel,
1905        label: &str,
1906    ) -> RedDBResult<RuntimeQueryResult> {
1907        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1908        if is_system_schema_name(name) {
1909            return Err(RedDBError::Query("system schema is read-only".to_string()));
1910        }
1911        let store = self.inner.db.store();
1912        let _publication = store.vault_publication_lock.lock();
1913        self.vcs_reject_destructive_ddl(name)?;
1914        if store.get_collection(name).is_none() {
1915            if if_exists {
1916                return Ok(RuntimeQueryResult::ok_message(
1917                    raw_query.to_string(),
1918                    &format!("{label} '{name}' does not exist"),
1919                    "drop",
1920                ));
1921            }
1922            return Err(RedDBError::NotFound(format!("{label} '{name}' not found")));
1923        }
1924
1925        let actual = self
1926            .inner
1927            .db
1928            .collection_contract(name)
1929            .map(|contract| contract.declared_model)
1930            .map(Ok)
1931            .unwrap_or_else(|| {
1932                polymorphic_resolver::resolve(name, &self.inner.db.catalog_model_snapshot())
1933            })?;
1934        polymorphic_resolver::ensure_model_match(expected_model, actual)?;
1935        self.drop_collection_storage(raw_query, name, label)
1936    }
1937
1938    pub fn execute_truncate(
1939        &self,
1940        raw_query: &str,
1941        query: &TruncateQuery,
1942    ) -> RedDBResult<RuntimeQueryResult> {
1943        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1944        if is_system_schema_name(&query.name) {
1945            return Err(RedDBError::Query("system schema is read-only".to_string()));
1946        }
1947
1948        let label = query
1949            .model
1950            .map(polymorphic_resolver::model_name)
1951            .unwrap_or("collection");
1952        let store = self.inner.db.store();
1953        if store.get_collection(&query.name).is_none() {
1954            if query.if_exists {
1955                return Ok(RuntimeQueryResult::ok_message(
1956                    raw_query.to_string(),
1957                    &format!("{label} '{}' does not exist", query.name),
1958                    "truncate",
1959                ));
1960            }
1961            return Err(RedDBError::NotFound(format!(
1962                "{label} '{}' not found",
1963                query.name
1964            )));
1965        }
1966
1967        let actual =
1968            polymorphic_resolver::resolve(&query.name, &self.inner.db.catalog_model_snapshot())?;
1969        if let Some(expected) = query.model {
1970            polymorphic_resolver::ensure_model_match(expected, actual)?;
1971        }
1972
1973        if actual == CollectionModel::Queue {
1974            return self.execute_queue_command(
1975                raw_query,
1976                &QueueCommand::Purge {
1977                    queue: query.name.clone(),
1978                },
1979            );
1980        }
1981
1982        // Count before wiping so we can emit the aggregated truncate event.
1983        let affected = self.truncate_collection_entities(&query.name)?;
1984        // Emit 1 truncate event (not N delete events) for event-enabled collections.
1985        crate::runtime::mutation::emit_truncate_event_for_collection(self, &query.name, affected)?;
1986        self.inner.db.invalidate_vector_index(&query.name);
1987        self.clear_table_planner_stats(&query.name);
1988        self.invalidate_result_cache();
1989
1990        Ok(RuntimeQueryResult::ok_message(
1991            raw_query.to_string(),
1992            &format!(
1993                "{affected} entities truncated from {label} '{}'",
1994                query.name
1995            ),
1996            "truncate",
1997        ))
1998    }
1999
2000    fn truncate_collection_entities(&self, name: &str) -> RedDBResult<u64> {
2001        let store = self.inner.db.store();
2002        let _publication = store.vault_publication_lock.lock();
2003        self.vcs_reject_destructive_ddl(name)?;
2004        let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(name);
2005        let store = self.inner.db.store();
2006        let Some(manager) = store.get_collection(name) else {
2007            return Ok(0);
2008        };
2009        let entities = manager.query_all(|_| true);
2010        if entities.is_empty() {
2011            return Ok(0);
2012        }
2013
2014        for entity in &entities {
2015            let fields = entity_index_fields(&entity.data);
2016            self.inner
2017                .index_store
2018                .index_entity_delete(name, entity.id, &fields)
2019                .map_err(RedDBError::Internal)?;
2020        }
2021
2022        let ids = entities.iter().map(|entity| entity.id).collect::<Vec<_>>();
2023        let deleted_ids = store
2024            .delete_batch(name, &ids)
2025            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2026        for id in &deleted_ids {
2027            store.context_index().remove_entity(*id);
2028        }
2029        Ok(deleted_ids.len() as u64)
2030    }
2031
2032    fn drop_collection_storage(
2033        &self,
2034        raw_query: &str,
2035        name: &str,
2036        label: &str,
2037    ) -> RedDBResult<RuntimeQueryResult> {
2038        let store = self.inner.db.store();
2039        let _publication = store.vault_publication_lock.lock();
2040        self.vcs_reject_destructive_ddl(name)?;
2041
2042        // Emit 1 collection_dropped event before storage is wiped.
2043        // Queue is preserved; subscription is removed with the contract below.
2044        let final_count = store
2045            .get_collection(name)
2046            .map(|manager| manager.query_all(|_| true).len() as u64)
2047            .unwrap_or(0);
2048        crate::runtime::mutation::emit_collection_dropped_event_for_collection(
2049            self,
2050            name,
2051            final_count,
2052        )?;
2053
2054        let topology_lock = self.inner.index_store.collection_topology_lock(name);
2055        let _topology_guard = topology_lock.write();
2056        let orphaned_indices: Vec<String> = self
2057            .inner
2058            .index_store
2059            .list_indices(name)
2060            .into_iter()
2061            .map(|index| index.name)
2062            .collect();
2063        for index_name in &orphaned_indices {
2064            self.inner.index_store.drop_index(index_name, name);
2065        }
2066
2067        store
2068            .drop_collection(name)
2069            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2070        self.inner.db.invalidate_vector_index(name);
2071        self.inner.db.clear_collection_default_ttl_ms(name);
2072        self.inner
2073            .db
2074            .remove_collection_contract(name)
2075            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2076        self.clear_table_planner_stats(name);
2077        self.invalidate_result_cache();
2078        if let Some(store) = self.inner.auth_store.read().clone() {
2079            store.invalidate_visible_collections_cache();
2080        }
2081        // The native registry and targeted contract metadata publication above
2082        // are the DROP commit boundary; do not turn this into a full database
2083        // fingerprint/checkpoint.
2084        self.schema_vocabulary_apply(
2085            crate::runtime::schema_vocabulary::DdlEvent::DropCollection {
2086                collection: name.to_string(),
2087            },
2088        );
2089
2090        Ok(RuntimeQueryResult::ok_message(
2091            raw_query.to_string(),
2092            &format!("{label} '{name}' dropped"),
2093            "drop",
2094        ))
2095    }
2096}
2097
2098pub(crate) fn is_system_schema_name(name: &str) -> bool {
2099    let name = reddb_engine::storage::system_collection_names::canonical_or_self(name);
2100    name == "red" || name.starts_with("red.") || name.starts_with("__red_schema_")
2101}
2102
2103fn entity_index_fields(data: &EntityData) -> Vec<(String, Value)> {
2104    match data {
2105        EntityData::Row(row) => {
2106            if let Some(ref named) = row.named {
2107                named
2108                    .iter()
2109                    .map(|(key, value)| (key.clone(), value.clone()))
2110                    .collect()
2111            } else if let Some(ref schema) = row.schema {
2112                schema
2113                    .iter()
2114                    .zip(row.columns.iter())
2115                    .map(|(key, value)| (key.clone(), value.clone()))
2116                    .collect()
2117            } else {
2118                Vec::new()
2119            }
2120        }
2121        EntityData::Node(node) => node
2122            .properties
2123            .iter()
2124            .map(|(key, value)| (key.clone(), value.clone()))
2125            .collect(),
2126        _ => Vec::new(),
2127    }
2128}
2129
2130/// DDL-time gate for a declared AI policy (issue #1271). Each declared
2131/// modality block is checked against the provider capability matrix
2132/// (#1269): a provider/model that cannot serve the requested modality is
2133/// rejected before the collection is created. Uses the built-in registry
2134/// (no per-deployment overrides at DDL time).
2135fn validate_ai_policy_modalities(policy: &crate::catalog::AiPolicy) -> RedDBResult<()> {
2136    use crate::runtime::ai::provider_capabilities::{Modality, Registry};
2137    let registry = Registry::new();
2138    let check = |provider: &str, model: &str, modality: Modality| -> RedDBResult<()> {
2139        registry
2140            .validate_policy_modality(provider, model, modality)
2141            .map_err(|err| RedDBError::Query(err.to_string()))
2142    };
2143    if let Some(embed) = &policy.embed {
2144        check(&embed.provider, &embed.model, Modality::Embed)?;
2145    }
2146    if let Some(moderate) = &policy.moderate {
2147        check(&moderate.provider, &moderate.model, Modality::Moderate)?;
2148    }
2149    if let Some(vision) = &policy.vision {
2150        check(&vision.provider, &vision.model, Modality::Vision)?;
2151    }
2152    Ok(())
2153}
2154
2155fn collection_contract_from_create_table(
2156    query: &CreateTableQuery,
2157) -> RedDBResult<crate::physical::CollectionContract> {
2158    reddb_engine::catalog::ddl::collection_contract_from_create_table(query, current_unix_ms())
2159        .map_err(RedDBError::Query)
2160}
2161
2162fn default_collection_contract_for_existing_table(
2163    name: &str,
2164) -> crate::physical::CollectionContract {
2165    let now = current_unix_ms();
2166    crate::physical::CollectionContract {
2167        graph_contract: None,
2168        name: name.to_string(),
2169        description: None,
2170        description_generated: false,
2171        declared_model: crate::catalog::CollectionModel::Table,
2172        schema_mode: crate::catalog::SchemaMode::SemiStructured,
2173        origin: crate::physical::ContractOrigin::Explicit,
2174        version: 0,
2175        created_at_unix_ms: now,
2176        updated_at_unix_ms: now,
2177        default_ttl_ms: None,
2178        vector_dimension: None,
2179        vector_metric: None,
2180        context_index_fields: Vec::new(),
2181        declared_columns: Vec::new(),
2182        table_def: Some(reddb_types::TableDef::new(name.to_string())),
2183        timestamps_enabled: false,
2184        context_index_enabled: false,
2185        metrics_raw_retention_ms: None,
2186        metrics_rollup_policies: Vec::new(),
2187        metrics_tenant_identity: None,
2188        metrics_namespace: None,
2189        append_only: false,
2190        subscriptions: Vec::new(),
2191        analytics_config: Vec::new(),
2192        session_key: None,
2193        session_gap_ms: None,
2194        retention_duration_ms: None,
2195        analytical_storage: None,
2196
2197        ai_policy: None,
2198    }
2199}
2200
2201fn keyed_collection_contract(
2202    name: &str,
2203    model: crate::catalog::CollectionModel,
2204    analytics_config: Vec<crate::catalog::AnalyticsViewDescriptor>,
2205) -> crate::physical::CollectionContract {
2206    let now = current_unix_ms();
2207    crate::physical::CollectionContract {
2208        graph_contract: None,
2209        name: name.to_string(),
2210        description: None,
2211        description_generated: false,
2212        declared_model: model,
2213        schema_mode: crate::catalog::SchemaMode::Dynamic,
2214        origin: crate::physical::ContractOrigin::Explicit,
2215        version: 1,
2216        created_at_unix_ms: now,
2217        updated_at_unix_ms: now,
2218        default_ttl_ms: None,
2219        vector_dimension: None,
2220        vector_metric: None,
2221        context_index_fields: Vec::new(),
2222        declared_columns: Vec::new(),
2223        table_def: None,
2224        timestamps_enabled: false,
2225        context_index_enabled: false,
2226        metrics_raw_retention_ms: None,
2227        metrics_rollup_policies: Vec::new(),
2228        metrics_tenant_identity: None,
2229        metrics_namespace: None,
2230        append_only: false,
2231        subscriptions: Vec::new(),
2232        analytics_config,
2233        session_key: None,
2234        session_gap_ms: None,
2235        retention_duration_ms: None,
2236        analytical_storage: None,
2237
2238        ai_policy: None,
2239    }
2240}
2241
2242fn metrics_collection_contract(query: &CreateTableQuery) -> crate::physical::CollectionContract {
2243    let now = current_unix_ms();
2244    crate::physical::CollectionContract {
2245        graph_contract: None,
2246        name: query.name.clone(),
2247        description: None,
2248        description_generated: false,
2249        declared_model: crate::catalog::CollectionModel::Metrics,
2250        schema_mode: crate::catalog::SchemaMode::SemiStructured,
2251        origin: crate::physical::ContractOrigin::Explicit,
2252        version: 1,
2253        created_at_unix_ms: now,
2254        updated_at_unix_ms: now,
2255        default_ttl_ms: query.default_ttl_ms,
2256        vector_dimension: None,
2257        vector_metric: None,
2258        context_index_fields: Vec::new(),
2259        declared_columns: Vec::new(),
2260        table_def: None,
2261        timestamps_enabled: false,
2262        context_index_enabled: false,
2263        metrics_raw_retention_ms: query.default_ttl_ms,
2264        metrics_rollup_policies: query.metrics_rollup_policies.clone(),
2265        metrics_tenant_identity: Some(
2266            query
2267                .tenant_by
2268                .clone()
2269                .unwrap_or_else(|| "current_tenant".to_string()),
2270        ),
2271        metrics_namespace: Some("default".to_string()),
2272        append_only: true,
2273        subscriptions: Vec::new(),
2274        analytics_config: Vec::new(),
2275        session_key: None,
2276        session_gap_ms: None,
2277        retention_duration_ms: None,
2278        analytical_storage: None,
2279
2280        ai_policy: None,
2281    }
2282}
2283
2284fn vector_collection_contract(query: &CreateVectorQuery) -> crate::physical::CollectionContract {
2285    let now = current_unix_ms();
2286    crate::physical::CollectionContract {
2287        graph_contract: None,
2288        name: query.name.clone(),
2289        description: None,
2290        description_generated: false,
2291        declared_model: crate::catalog::CollectionModel::Vector,
2292        schema_mode: crate::catalog::SchemaMode::Dynamic,
2293        origin: crate::physical::ContractOrigin::Explicit,
2294        version: 1,
2295        created_at_unix_ms: now,
2296        updated_at_unix_ms: now,
2297        default_ttl_ms: None,
2298        vector_dimension: Some(query.dimension),
2299        vector_metric: Some(query.metric),
2300        context_index_fields: Vec::new(),
2301        declared_columns: Vec::new(),
2302        table_def: None,
2303        timestamps_enabled: false,
2304        context_index_enabled: false,
2305        metrics_raw_retention_ms: None,
2306        metrics_rollup_policies: Vec::new(),
2307        metrics_tenant_identity: None,
2308        metrics_namespace: None,
2309        append_only: false,
2310        subscriptions: Vec::new(),
2311        analytics_config: Vec::new(),
2312        session_key: None,
2313        session_gap_ms: None,
2314        retention_duration_ms: None,
2315        analytical_storage: None,
2316
2317        ai_policy: None,
2318    }
2319}
2320
2321fn apply_alter_operations_to_contract(
2322    contract: &mut crate::physical::CollectionContract,
2323    operations: &[AlterOperation],
2324) {
2325    if contract.table_def.is_none() {
2326        contract.table_def = Some(reddb_types::TableDef::new(contract.name.clone()));
2327    }
2328    for operation in operations {
2329        match operation {
2330            AlterOperation::SetDescription {
2331                column,
2332                description,
2333            } => {
2334                if let Some(name) = column {
2335                    if let Some(declared) = contract
2336                        .declared_columns
2337                        .iter_mut()
2338                        .find(|declared| declared.name == *name)
2339                    {
2340                        declared.description = Some(description.clone());
2341                        declared.description_generated = false;
2342                    }
2343                } else {
2344                    contract.description = Some(description.clone());
2345                    contract.description_generated = false;
2346                }
2347            }
2348            AlterOperation::AddColumn(column) => {
2349                if !contract
2350                    .declared_columns
2351                    .iter()
2352                    .any(|existing| existing.name == column.name)
2353                {
2354                    contract
2355                        .declared_columns
2356                        .push(declared_column_contract_from_ddl(column));
2357                }
2358                if let Some(table_def) = contract.table_def.as_mut() {
2359                    if table_def.get_column(&column.name).is_none() {
2360                        if let Ok(column_def) = column_def_from_ddl(column) {
2361                            if column.primary_key {
2362                                table_def.primary_key.push(column.name.clone());
2363                                table_def.constraints.push(
2364                                    reddb_types::Constraint::new(
2365                                        format!("pk_{}", column.name),
2366                                        reddb_types::ConstraintType::PrimaryKey,
2367                                    )
2368                                    .on_columns(vec![column.name.clone()]),
2369                                );
2370                            }
2371                            if column.unique {
2372                                table_def.constraints.push(
2373                                    reddb_types::Constraint::new(
2374                                        format!("uniq_{}", column.name),
2375                                        reddb_types::ConstraintType::Unique,
2376                                    )
2377                                    .on_columns(vec![column.name.clone()]),
2378                                );
2379                            }
2380                            if column.not_null {
2381                                table_def.constraints.push(
2382                                    reddb_types::Constraint::new(
2383                                        format!("not_null_{}", column.name),
2384                                        reddb_types::ConstraintType::NotNull,
2385                                    )
2386                                    .on_columns(vec![column.name.clone()]),
2387                                );
2388                            }
2389                            table_def.columns.push(column_def);
2390                        }
2391                    }
2392                }
2393            }
2394            AlterOperation::DropColumn(name) => {
2395                contract
2396                    .declared_columns
2397                    .retain(|column| column.name != *name);
2398                if let Some(table_def) = contract.table_def.as_mut() {
2399                    if let Some(index) = table_def.column_index(name) {
2400                        table_def.columns.remove(index);
2401                    }
2402                    table_def.primary_key.retain(|column| column != name);
2403                    table_def.constraints.retain(|constraint| {
2404                        !constraint.columns.iter().any(|column| column == name)
2405                    });
2406                    table_def
2407                        .indexes
2408                        .retain(|index| !index.columns.iter().any(|column| column == name));
2409                }
2410            }
2411            AlterOperation::RenameColumn { from, to } => {
2412                if contract
2413                    .declared_columns
2414                    .iter()
2415                    .any(|column| column.name == *to)
2416                {
2417                    continue;
2418                }
2419                if let Some(column) = contract
2420                    .declared_columns
2421                    .iter_mut()
2422                    .find(|column| column.name == *from)
2423                {
2424                    column.name = to.clone();
2425                }
2426                if let Some(table_def) = contract.table_def.as_mut() {
2427                    if let Some(column) = table_def
2428                        .columns
2429                        .iter_mut()
2430                        .find(|column| column.name == *from)
2431                    {
2432                        column.name = to.clone();
2433                    }
2434                    for primary_key in &mut table_def.primary_key {
2435                        if *primary_key == *from {
2436                            *primary_key = to.clone();
2437                        }
2438                    }
2439                    for constraint in &mut table_def.constraints {
2440                        for column in &mut constraint.columns {
2441                            if *column == *from {
2442                                *column = to.clone();
2443                            }
2444                        }
2445                        if let Some(ref_columns) = constraint.ref_columns.as_mut() {
2446                            for column in ref_columns {
2447                                if *column == *from {
2448                                    *column = to.clone();
2449                                }
2450                            }
2451                        }
2452                    }
2453                    for index in &mut table_def.indexes {
2454                        for column in &mut index.columns {
2455                            if *column == *from {
2456                                *column = to.clone();
2457                            }
2458                        }
2459                    }
2460                }
2461            }
2462            // Partition ops don't touch the column contract — metadata is
2463            // persisted separately via `partition.*` inside `red.config`.
2464            AlterOperation::AttachPartition { .. } | AlterOperation::DetachPartition { .. } => {}
2465            // RLS toggles don't touch the column contract — flag is persisted
2466            // separately via `rls.enabled.{table}` inside `red.config` and enforced
2467            // through the in-memory `rls_enabled_tables` set.
2468            AlterOperation::EnableRowLevelSecurity | AlterOperation::DisableRowLevelSecurity => {}
2469            // Phase 2.5.4: tenancy toggles persist via `tenant_tables.*` in `red.config`
2470            // and are enforced through `tenant_tables` + RLS auto-policy.
2471            AlterOperation::EnableTenancy { .. } | AlterOperation::DisableTenancy => {}
2472            AlterOperation::SetAppendOnly(on) => {
2473                contract.append_only = *on;
2474            }
2475            // VCS opt-in is persisted to red.vcs.settings by the
2476            // executor, not the contract — nothing to do here.
2477            AlterOperation::SetVersioned(_) => {}
2478            AlterOperation::EnableEvents(subscription) => {
2479                let mut subscription = subscription.clone();
2480                subscription.source = contract.name.clone();
2481                subscription.enabled = true;
2482                if let Some(existing) = contract
2483                    .subscriptions
2484                    .iter_mut()
2485                    .find(|existing| existing.target_queue == subscription.target_queue)
2486                {
2487                    *existing = subscription;
2488                } else {
2489                    contract.subscriptions.push(subscription);
2490                }
2491            }
2492            AlterOperation::DisableEvents => {
2493                for subscription in &mut contract.subscriptions {
2494                    subscription.enabled = false;
2495                }
2496            }
2497            AlterOperation::AddSubscription { name, descriptor } => {
2498                let mut sub = descriptor.clone();
2499                sub.name = name.clone();
2500                sub.source = contract.name.clone();
2501                sub.enabled = true;
2502                if let Some(existing) = contract.subscriptions.iter_mut().find(|s| s.name == *name)
2503                {
2504                    *existing = sub;
2505                } else {
2506                    contract.subscriptions.push(sub);
2507                }
2508            }
2509            AlterOperation::DropSubscription { name } => {
2510                contract.subscriptions.retain(|s| s.name != *name);
2511            }
2512            // Signer registry mutations live in `red.config` outside the
2513            // contract surface — the executor applied them directly via
2514            // `signed_writes_kind::{add,revoke}_signer`. Nothing to fold
2515            // into the column-shaped contract.
2516            AlterOperation::AddSigner { .. } | AlterOperation::RevokeSigner { .. } => {}
2517            AlterOperation::SetRetention { duration_ms } => {
2518                contract.retention_duration_ms = Some(*duration_ms);
2519            }
2520            AlterOperation::UnsetRetention => {
2521                contract.retention_duration_ms = None;
2522            }
2523            // Issue #801 — fold analytics lifecycle into the WAL-backed
2524            // `analytics_config` so the change is durable and the
2525            // `<graph>.<output>` resolver picks it up on the next read.
2526            AlterOperation::AddAnalytics(views) => {
2527                for view in views {
2528                    // Idempotent: skip outputs already enabled so a repeated
2529                    // ADD never duplicates state. The first declaration wins —
2530                    // re-declaring options requires DROP then ADD.
2531                    if !contract
2532                        .analytics_config
2533                        .iter()
2534                        .any(|existing| existing.output == view.output)
2535                    {
2536                        contract.analytics_config.push(view.clone());
2537                    }
2538                }
2539            }
2540            AlterOperation::DropAnalytics(output) => {
2541                contract
2542                    .analytics_config
2543                    .retain(|view| view.output != *output);
2544            }
2545        }
2546    }
2547}
2548
2549/// Issue #580 — returns true if the contract carries at least one
2550/// column the retention filter can use as a timestamp anchor:
2551/// either `WITH timestamps = true` (auto `created_at` / `updated_at`)
2552/// or a user-declared column with a temporal data_type.
2553pub(crate) fn retention_timestamp_column_exists(
2554    contract: &crate::physical::CollectionContract,
2555) -> bool {
2556    if contract.timestamps_enabled {
2557        return true;
2558    }
2559    if matches!(
2560        contract.declared_model,
2561        crate::catalog::CollectionModel::TimeSeries | crate::catalog::CollectionModel::Metrics
2562    ) {
2563        // Time-series and metrics collections carry an intrinsic
2564        // timestamp axis on every row even without a declared column;
2565        // retention has a natural anchor.
2566        return true;
2567    }
2568    contract
2569        .declared_columns
2570        .iter()
2571        .any(|column| is_temporal_data_type(&column.data_type))
2572}
2573
2574fn is_temporal_data_type(data_type: &str) -> bool {
2575    let upper = data_type.to_ascii_uppercase();
2576    matches!(
2577        upper.as_str(),
2578        "TIMESTAMP" | "TIMESTAMPMS" | "TIMESTAMP_MS" | "DATETIME" | "DATE"
2579    )
2580}
2581
2582fn validate_event_subscriptions(
2583    runtime: &RedDBRuntime,
2584    source: &str,
2585    subscriptions: &[crate::catalog::SubscriptionDescriptor],
2586) -> RedDBResult<()> {
2587    for subscription in subscriptions
2588        .iter()
2589        .filter(|subscription| subscription.enabled)
2590    {
2591        if subscription.all_tenants && crate::runtime::impl_core::current_tenant().is_some() {
2592            return Err(RedDBError::Query(
2593                "cross-tenant subscription requires cluster-admin capability (events:cluster_subscribe)".to_string(),
2594            ));
2595        }
2596        validate_subscription_auth(runtime, source, subscription)?;
2597        if subscription.target_queue == source
2598            || subscription_would_create_cycle(
2599                &runtime.inner.db,
2600                source,
2601                &subscription.target_queue,
2602            )
2603        {
2604            return Err(RedDBError::Query(
2605                "subscription would create cycle".to_string(),
2606            ));
2607        }
2608        audit_subscription_redact_gap(runtime, source, subscription);
2609    }
2610    Ok(())
2611}
2612
2613fn validate_subscription_auth(
2614    runtime: &RedDBRuntime,
2615    source: &str,
2616    subscription: &crate::catalog::SubscriptionDescriptor,
2617) -> RedDBResult<()> {
2618    let auth_store = match runtime.inner.auth_store.read().clone() {
2619        Some(store) => store,
2620        None => return Ok(()),
2621    };
2622    let (username, role) = match crate::runtime::impl_core::current_auth_identity() {
2623        Some(identity) => identity,
2624        None => return Ok(()),
2625    };
2626    let tenant = crate::runtime::impl_core::current_tenant();
2627    let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
2628
2629    if auth_store.iam_authorization_enabled() {
2630        let ctx = crate::auth::policies::EvalContext {
2631            principal_tenant: tenant.clone(),
2632            current_tenant: tenant.clone(),
2633            peer_ip: None,
2634            mfa_present: false,
2635            now_ms: crate::auth::now_ms(),
2636            principal_is_admin_role: role == crate::auth::Role::Admin,
2637            principal_is_platform_scoped: principal.tenant.is_none(),
2638        };
2639        let mut source_resource = crate::auth::policies::ResourceRef::new("table", source);
2640        if let Some(t) = tenant.as_deref() {
2641            source_resource = source_resource.with_tenant(t.to_string());
2642        }
2643        if !auth_store.check_policy_authz_with_role(
2644            &principal,
2645            "select",
2646            &source_resource,
2647            &ctx,
2648            role,
2649        ) {
2650            return Err(RedDBError::Query(format!(
2651                "permission denied: principal=`{}` action=`select` resource=`{}:{}` denied by IAM policy",
2652                principal, source_resource.kind, source_resource.name
2653            )));
2654        }
2655
2656        let mut target_resource =
2657            crate::auth::policies::ResourceRef::new("queue", subscription.target_queue.clone());
2658        if let Some(t) = tenant.as_deref() {
2659            target_resource = target_resource.with_tenant(t.to_string());
2660        }
2661        if !auth_store.check_policy_authz_with_role(
2662            &principal,
2663            "write",
2664            &target_resource,
2665            &ctx,
2666            role,
2667        ) {
2668            return Err(RedDBError::Query(format!(
2669                "permission denied: principal=`{}` action=`write` resource=`{}:{}` denied by IAM policy",
2670                principal, target_resource.kind, target_resource.name
2671            )));
2672        }
2673        return Ok(());
2674    }
2675
2676    let ctx = crate::auth::privileges::AuthzContext {
2677        principal: &username,
2678        effective_role: role,
2679        tenant: tenant.as_deref(),
2680    };
2681    auth_store
2682        .check_grant(
2683            &ctx,
2684            crate::auth::privileges::Action::Select,
2685            &crate::auth::privileges::Resource::table_from_name(source),
2686        )
2687        .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))?;
2688    auth_store
2689        .check_grant(
2690            &ctx,
2691            crate::auth::privileges::Action::Insert,
2692            &crate::auth::privileges::Resource::table_from_name(&subscription.target_queue),
2693        )
2694        .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))?;
2695    Ok(())
2696}
2697
2698fn audit_subscription_redact_gap(
2699    runtime: &RedDBRuntime,
2700    source: &str,
2701    subscription: &crate::catalog::SubscriptionDescriptor,
2702) {
2703    let auth_store = match runtime.inner.auth_store.read().clone() {
2704        Some(store) if store.iam_authorization_enabled() => store,
2705        _ => return,
2706    };
2707    let (username, role) = match crate::runtime::impl_core::current_auth_identity() {
2708        Some(identity) => identity,
2709        None => return,
2710    };
2711    let tenant = crate::runtime::impl_core::current_tenant();
2712    let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
2713    let missing = subscription_redact_gap_columns(&auth_store, &principal, source, subscription);
2714    if missing.is_empty() {
2715        return;
2716    }
2717
2718    let columns = missing.into_iter().collect::<Vec<_>>().join(", ");
2719    tracing::warn!(
2720        target: "reddb::operator",
2721        "subscription_redact_gap: source={} target_queue={} columns=[{}]",
2722        source,
2723        subscription.target_queue,
2724        columns
2725    );
2726    let mut event = AuditEvent::builder("subscription_redact_gap")
2727        .principal(username)
2728        .source(AuditAuthSource::System)
2729        .resource(format!(
2730            "subscription:{}->{}",
2731            source, subscription.target_queue
2732        ))
2733        .outcome(Outcome::Success)
2734        .field(AuditFieldEscaper::field("source", source))
2735        .field(AuditFieldEscaper::field(
2736            "target_queue",
2737            subscription.target_queue.clone(),
2738        ))
2739        .field(AuditFieldEscaper::field(
2740            "subscription",
2741            subscription.name.clone(),
2742        ))
2743        .field(AuditFieldEscaper::field("columns", columns))
2744        .field(AuditFieldEscaper::field("role", role.as_str()));
2745    if let Some(t) = tenant {
2746        event = event.tenant(t);
2747    }
2748    runtime.inner.audit_log.record_event(event.build());
2749}
2750
2751fn subscription_redact_gap_columns(
2752    auth_store: &crate::auth::store::AuthStore,
2753    principal: &crate::auth::UserId,
2754    source: &str,
2755    subscription: &crate::catalog::SubscriptionDescriptor,
2756) -> BTreeSet<String> {
2757    let redacted: HashSet<String> = subscription
2758        .redact_fields
2759        .iter()
2760        .map(|field| field.to_ascii_lowercase())
2761        .collect();
2762    auth_store
2763        .effective_policies(principal)
2764        .iter()
2765        .flat_map(|policy| policy.statements.iter())
2766        .filter(|statement| statement.effect == crate::auth::policies::Effect::Deny)
2767        .filter(|statement| statement.actions.iter().any(action_pattern_matches_select))
2768        .flat_map(|statement| statement.resources.iter())
2769        .filter_map(|resource| denied_column_for_source(resource, source))
2770        .filter(|column| !redact_covers_column(&redacted, source, column))
2771        .collect()
2772}
2773
2774fn action_pattern_matches_select(pattern: &crate::auth::policies::ActionPattern) -> bool {
2775    match pattern {
2776        crate::auth::policies::ActionPattern::Wildcard => true,
2777        crate::auth::policies::ActionPattern::Exact(action) => action == "select",
2778        crate::auth::policies::ActionPattern::Prefix(prefix) => {
2779            "select".len() > prefix.len() + 1
2780                && "select".starts_with(prefix)
2781                && "select".as_bytes()[prefix.len()] == b':'
2782        }
2783    }
2784}
2785
2786fn denied_column_for_source(
2787    resource: &crate::auth::policies::ResourcePattern,
2788    source: &str,
2789) -> Option<String> {
2790    let crate::auth::policies::ResourcePattern::Exact { kind, name } = resource else {
2791        return None;
2792    };
2793    if kind != "column" {
2794        return None;
2795    }
2796    let column = crate::auth::ColumnRef::parse_resource_name(name).ok()?;
2797    (column.table_resource_name() == source).then_some(column.column)
2798}
2799
2800fn redact_covers_column(redacted: &HashSet<String>, source: &str, column: &str) -> bool {
2801    let column = column.to_ascii_lowercase();
2802    let qualified = format!("{}.{}", source.to_ascii_lowercase(), column);
2803    redacted.contains("*") || redacted.contains(&column) || redacted.contains(&qualified)
2804}
2805
2806fn subscription_would_create_cycle(
2807    db: &crate::storage::unified::devx::RedDB,
2808    source: &str,
2809    target: &str,
2810) -> bool {
2811    let mut graph: HashMap<String, Vec<String>> = HashMap::new();
2812    for contract in db.collection_contracts() {
2813        for subscription in contract
2814            .subscriptions
2815            .into_iter()
2816            .filter(|subscription| subscription.enabled)
2817        {
2818            graph
2819                .entry(subscription.source)
2820                .or_default()
2821                .push(subscription.target_queue);
2822        }
2823    }
2824    graph
2825        .entry(source.to_string())
2826        .or_default()
2827        .push(target.to_string());
2828
2829    let mut stack = vec![target.to_string()];
2830    let mut seen = HashSet::new();
2831    while let Some(node) = stack.pop() {
2832        if node == source {
2833            return true;
2834        }
2835        if !seen.insert(node.clone()) {
2836            continue;
2837        }
2838        if let Some(next) = graph.get(&node) {
2839            stack.extend(next.iter().cloned());
2840        }
2841    }
2842    false
2843}
2844
2845pub(crate) fn ensure_event_target_queue_pub(
2846    runtime: &RedDBRuntime,
2847    queue: &str,
2848) -> RedDBResult<()> {
2849    ensure_event_target_queue(runtime, queue)
2850}
2851
2852fn ensure_event_target_queue(runtime: &RedDBRuntime, queue: &str) -> RedDBResult<()> {
2853    let store = runtime.inner.db.store();
2854    if store.get_collection(queue).is_some() {
2855        return Ok(());
2856    }
2857    store
2858        .create_collection(queue)
2859        .map_err(|err| RedDBError::Internal(err.to_string()))?;
2860    crate::runtime::queue_storage_index::prepare_queue(runtime, queue)?;
2861    runtime
2862        .inner
2863        .db
2864        .save_collection_contract(event_queue_collection_contract(queue))
2865        .map_err(|err| RedDBError::Internal(err.to_string()))?;
2866    store.set_config_tree(
2867        &format!("queue.{queue}.mode"),
2868        &crate::serde_json::Value::String("fanout".to_string()),
2869    );
2870    Ok(())
2871}
2872
2873fn event_queue_collection_contract(queue: &str) -> crate::physical::CollectionContract {
2874    let now = current_unix_ms();
2875    crate::physical::CollectionContract {
2876        graph_contract: None,
2877        name: queue.to_string(),
2878        description: None,
2879        description_generated: false,
2880        declared_model: crate::catalog::CollectionModel::Queue,
2881        schema_mode: crate::catalog::SchemaMode::Dynamic,
2882        origin: crate::physical::ContractOrigin::Implicit,
2883        version: 1,
2884        created_at_unix_ms: now,
2885        updated_at_unix_ms: now,
2886        default_ttl_ms: None,
2887        vector_dimension: None,
2888        vector_metric: None,
2889        context_index_fields: Vec::new(),
2890        declared_columns: Vec::new(),
2891        table_def: None,
2892        timestamps_enabled: false,
2893        context_index_enabled: false,
2894        metrics_raw_retention_ms: None,
2895        metrics_rollup_policies: Vec::new(),
2896        metrics_tenant_identity: None,
2897        metrics_namespace: None,
2898        append_only: true,
2899        subscriptions: Vec::new(),
2900        analytics_config: Vec::new(),
2901        session_key: None,
2902        session_gap_ms: None,
2903        retention_duration_ms: None,
2904        analytical_storage: None,
2905
2906        ai_policy: None,
2907    }
2908}
2909
2910fn column_def_from_ddl(column: &CreateColumnDef) -> RedDBResult<reddb_types::ColumnDef> {
2911    reddb_engine::catalog::ddl::column_def_from_ddl(column).map_err(RedDBError::Query)
2912}
2913
2914fn current_unix_ms() -> u128 {
2915    std::time::SystemTime::now()
2916        .duration_since(std::time::UNIX_EPOCH)
2917        .unwrap_or_default()
2918        .as_millis()
2919}
2920
2921#[cfg(test)]
2922mod tests {
2923    use crate::auth::policies::{ActionPattern, Effect, Policy, ResourcePattern, Statement};
2924    use crate::auth::store::{AuthStore, PrincipalRef};
2925    use crate::auth::UserId;
2926    use crate::auth::{AuthConfig, Role};
2927    use crate::runtime::impl_core::{clear_current_auth_identity, set_current_auth_identity};
2928    use crate::{RedDBOptions, RedDBRuntime};
2929    use reddb_types::Value;
2930    use std::sync::Arc;
2931
2932    /// The duplicate check read the rows in memory. Checkpointed rows are on
2933    /// disk, and a table that held duplicates there got its unique index.
2934    #[test]
2935    fn a_unique_index_is_refused_over_duplicates_that_are_only_on_disk() {
2936        let directory = tempfile::tempdir().expect("fixture");
2937        let runtime = RedDBRuntime::with_options(
2938            RedDBOptions::persistent(directory.path().join("unique.rdb"))
2939                .with_memory_budget(32 * 1024 * 1024)
2940                .with_bounded_disk_residency(true),
2941        )
2942        .expect("runtime");
2943        for table in ["duplicated", "clean"] {
2944            runtime
2945                .execute_query(&format!("CREATE TABLE {table} (id TEXT, holder TEXT)"))
2946                .expect("table");
2947        }
2948        runtime
2949            .execute_query(
2950                "INSERT INTO duplicated (id, holder) VALUES ('a', 'one'), ('a', 'two'), ('b', 'three')",
2951            )
2952            .expect("seed duplicates");
2953        runtime
2954            .execute_query("INSERT INTO clean (id, holder) VALUES ('a', 'one'), ('b', 'two')")
2955            .expect("seed");
2956        let store = runtime.db().store();
2957        store.persist().expect("checkpoint");
2958        for table in ["duplicated", "clean"] {
2959            let manager = store.get_collection(table).expect("collection");
2960            assert!(manager.has_backing(), "{table} must be read from disk");
2961            assert!(
2962                manager.query_all(|_| true).is_empty(),
2963                "{table} must have no row in memory"
2964            );
2965        }
2966
2967        let error = runtime
2968            .execute_query("CREATE UNIQUE INDEX idx_duplicated_id ON duplicated (id)")
2969            .expect_err("the duplicates are on disk");
2970        assert!(
2971            error.to_string().contains("share the same (id) key"),
2972            "{error}"
2973        );
2974
2975        runtime
2976            .execute_query("CREATE UNIQUE INDEX idx_clean_id ON clean (id)")
2977            .expect("no duplicates");
2978        let error = runtime
2979            .execute_query("INSERT INTO clean (id, holder) VALUES ('a', 'again')")
2980            .expect_err("a duplicate of a row on disk");
2981        assert!(error.to_string().contains("idx_clean_id"), "{error}");
2982    }
2983
2984    fn make_allow_policy(id: &str, action: &str, collection: &str) -> Policy {
2985        Policy {
2986            id: id.to_string(),
2987            version: 1,
2988            tenant: None,
2989            created_at: 0,
2990            updated_at: 0,
2991            statements: vec![Statement {
2992                sid: None,
2993                effect: Effect::Allow,
2994                actions: vec![ActionPattern::Exact(action.to_string())],
2995                resources: vec![ResourcePattern::Exact {
2996                    kind: "collection".to_string(),
2997                    name: collection.to_string(),
2998                }],
2999                condition: None,
3000            }],
3001        }
3002    }
3003
3004    fn wire_auth_store(rt: &RedDBRuntime) -> Arc<AuthStore> {
3005        let store = Arc::new(AuthStore::new(AuthConfig::default()));
3006        *rt.inner.auth_store.write() = Some(store.clone());
3007        store
3008    }
3009
3010    #[test]
3011    fn drop_denied_without_iam_policy() {
3012        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3013        rt.execute_query("CREATE TABLE foo (id INT)").unwrap();
3014        let store = wire_auth_store(&rt);
3015        // Put a select-only policy so IAM mode activates, but give alice no drop policy.
3016        let select_only = Policy {
3017            id: "select-only".to_string(),
3018            version: 1,
3019            tenant: None,
3020            created_at: 0,
3021            updated_at: 0,
3022            statements: vec![Statement {
3023                sid: None,
3024                effect: Effect::Allow,
3025                actions: vec![ActionPattern::Exact("select".to_string())],
3026                resources: vec![ResourcePattern::Wildcard],
3027                condition: None,
3028            }],
3029        };
3030        store.put_policy_internal(select_only).unwrap();
3031        let alice = UserId::from_parts(None, "alice");
3032        store
3033            .attach_policy(PrincipalRef::User(alice), "select-only")
3034            .unwrap();
3035        set_current_auth_identity("alice".to_string(), Role::Write);
3036        let err = rt.execute_query("DROP TABLE foo").unwrap_err();
3037        clear_current_auth_identity();
3038        assert!(
3039            format!("{err}").contains("denied by IAM policy"),
3040            "got: {err}"
3041        );
3042    }
3043
3044    #[test]
3045    fn drop_allowed_with_explicit_iam_policy() {
3046        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3047        rt.execute_query("CREATE TABLE bar (id INT)").unwrap();
3048        let store = wire_auth_store(&rt);
3049        let policy = make_allow_policy("allow-drop-bar", "drop", "bar");
3050        store.put_policy_internal(policy).unwrap();
3051        let bob = UserId::from_parts(None, "bob");
3052        store
3053            .attach_policy(PrincipalRef::User(bob), "allow-drop-bar")
3054            .unwrap();
3055        set_current_auth_identity("bob".to_string(), Role::Write);
3056        rt.execute_query("DROP TABLE bar").unwrap();
3057        clear_current_auth_identity();
3058    }
3059
3060    #[test]
3061    fn drop_allowed_with_wildcard_iam_policy() {
3062        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3063        rt.execute_query("CREATE TABLE baz (id INT)").unwrap();
3064        let store = wire_auth_store(&rt);
3065        let policy = Policy {
3066            id: "allow-drop-all".to_string(),
3067            version: 1,
3068            tenant: None,
3069            created_at: 0,
3070            updated_at: 0,
3071            statements: vec![Statement {
3072                sid: None,
3073                effect: Effect::Allow,
3074                actions: vec![ActionPattern::Exact("drop".to_string())],
3075                resources: vec![ResourcePattern::Wildcard],
3076                condition: None,
3077            }],
3078        };
3079        store.put_policy_internal(policy).unwrap();
3080        let carl = UserId::from_parts(None, "carl");
3081        store
3082            .attach_policy(PrincipalRef::User(carl), "allow-drop-all")
3083            .unwrap();
3084        set_current_auth_identity("carl".to_string(), Role::Write);
3085        rt.execute_query("DROP TABLE baz").unwrap();
3086        clear_current_auth_identity();
3087    }
3088
3089    #[test]
3090    fn truncate_denied_without_iam_policy() {
3091        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3092        rt.execute_query("CREATE TABLE qux (id INT)").unwrap();
3093        let store = wire_auth_store(&rt);
3094        // Acceptance #2 (#712 / S5A): in `policy_only` mode a
3095        // principal with no matching policy is denied even if their
3096        // role would have permitted the action. The pre-#712 default
3097        // of "no policy → deny" only holds under `policy_only`, so
3098        // pin the mode explicitly here so the assertion holds
3099        // regardless of the construction-time default.
3100        store
3101            .set_enforcement_mode(crate::auth::enforcement_mode::PolicyEnforcementMode::PolicyOnly);
3102        // A policy exists (IAM active) but gives no truncate right.
3103        let select_only = Policy {
3104            id: "select-only-2".to_string(),
3105            version: 1,
3106            tenant: None,
3107            created_at: 0,
3108            updated_at: 0,
3109            statements: vec![Statement {
3110                sid: None,
3111                effect: Effect::Allow,
3112                actions: vec![ActionPattern::Exact("select".to_string())],
3113                resources: vec![ResourcePattern::Wildcard],
3114                condition: None,
3115            }],
3116        };
3117        store.put_policy_internal(select_only).unwrap();
3118        let dana = UserId::from_parts(None, "dana");
3119        store
3120            .attach_policy(PrincipalRef::User(dana), "select-only-2")
3121            .unwrap();
3122        set_current_auth_identity("dana".to_string(), Role::Write);
3123        let err = rt.execute_query("TRUNCATE TABLE qux").unwrap_err();
3124        clear_current_auth_identity();
3125        assert!(
3126            format!("{err}").contains("denied by IAM policy"),
3127            "got: {err}"
3128        );
3129    }
3130
3131    #[test]
3132    fn truncate_table_clears_rows_and_preserves_schema_and_indexes() {
3133        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3134        rt.execute_query("CREATE TABLE users (id INT, name TEXT)")
3135            .unwrap();
3136        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'ana'), (2, 'bob')")
3137            .unwrap();
3138        rt.execute_query("CREATE INDEX idx_users_id ON users (id) USING HASH")
3139            .unwrap();
3140
3141        let truncated = rt.execute_query("TRUNCATE TABLE users").unwrap();
3142        assert_eq!(truncated.statement_type, "truncate");
3143        assert_eq!(truncated.affected_rows, 0);
3144
3145        let empty = rt.execute_query("SELECT id FROM users").unwrap();
3146        assert!(empty.result.records.is_empty());
3147
3148        rt.execute_query("INSERT INTO users (id, name) VALUES (3, 'cy')")
3149            .unwrap();
3150        let selected = rt
3151            .execute_query("SELECT name FROM users WHERE id = 3")
3152            .unwrap();
3153        let name = selected.result.records[0].get("name").unwrap();
3154        assert_eq!(name, &Value::text("cy"));
3155        assert!(rt.db().collection_contract("users").is_some());
3156        assert!(rt
3157            .inner
3158            .index_store
3159            .list_indices("users")
3160            .iter()
3161            .any(|index| index.name == "idx_users_id"));
3162    }
3163
3164    #[test]
3165    fn truncate_collection_is_polymorphic_and_typed_mismatch_fails() {
3166        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3167        rt.execute_query("CREATE QUEUE tasks").unwrap();
3168        rt.execute_query("QUEUE PUSH tasks {'job':'a'}").unwrap();
3169
3170        let err = rt.execute_query("TRUNCATE TABLE tasks").unwrap_err();
3171        assert!(format!("{err}").contains("model mismatch: expected table, got queue"));
3172
3173        rt.execute_query("TRUNCATE COLLECTION tasks").unwrap();
3174        let len = rt.execute_query("QUEUE LEN tasks").unwrap();
3175        assert_eq!(
3176            len.result.records[0].get("len"),
3177            Some(&Value::UnsignedInteger(0))
3178        );
3179    }
3180
3181    #[test]
3182    fn truncate_system_schema_is_read_only() {
3183        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3184        let err = rt
3185            .execute_query("TRUNCATE COLLECTION red.collections")
3186            .unwrap_err();
3187        assert!(format!("{err}").contains("system schema is read-only"));
3188    }
3189
3190    // ── #302 / #310: TRUNCATE / DROP single-event semantics ────────────────
3191
3192    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
3193        let result = rt
3194            .execute_query(&format!("QUEUE PEEK {queue} 100"))
3195            .expect("peek queue");
3196        result
3197            .result
3198            .records
3199            .iter()
3200            .map(
3201                |record| match record.get("payload").expect("payload column") {
3202                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
3203                    other => panic!("expected JSON queue payload, got {other:?}"),
3204                },
3205            )
3206            .collect()
3207    }
3208
3209    /// `TRUNCATE users` on an event-enabled collection emits exactly 1
3210    /// `truncate` event, not one delete event per row.
3211    #[test]
3212    fn truncate_event_enabled_table_emits_single_truncate_event() {
3213        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3214        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3215            .unwrap();
3216        rt.execute_query(
3217            "INSERT INTO users (id, name) VALUES (1, 'alice'), (2, 'bob'), (3, 'carol')",
3218        )
3219        .unwrap();
3220
3221        // Drain the 3 insert events so we start clean.
3222        rt.execute_query("QUEUE POP users_events COUNT 10").unwrap();
3223
3224        rt.execute_query("TRUNCATE TABLE users").unwrap();
3225
3226        let events = queue_payloads(&rt, "users_events");
3227        // Must be exactly 1 truncate event, not 3 delete events.
3228        assert_eq!(
3229            events.len(),
3230            1,
3231            "expected 1 truncate event, got {}",
3232            events.len()
3233        );
3234        let ev = events[0].as_object().expect("event is object");
3235        assert_eq!(
3236            ev.get("op").and_then(crate::json::Value::as_str),
3237            Some("truncate")
3238        );
3239        assert_eq!(
3240            ev.get("collection").and_then(crate::json::Value::as_str),
3241            Some("users")
3242        );
3243        assert_eq!(
3244            ev.get("entities_count")
3245                .and_then(crate::json::Value::as_u64),
3246            Some(3)
3247        );
3248        assert!(ev.get("ts").and_then(crate::json::Value::as_u64).is_some());
3249        assert!(ev.get("lsn").and_then(crate::json::Value::as_u64).is_some());
3250        assert!(ev
3251            .get("event_id")
3252            .and_then(crate::json::Value::as_str)
3253            .is_some_and(|s| !s.is_empty()));
3254    }
3255
3256    /// `TRUNCATE users` on a collection without event subscription emits no events.
3257    #[test]
3258    fn truncate_no_events_collection_emits_nothing() {
3259        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3260        rt.execute_query("CREATE TABLE plain (id INT, val TEXT)")
3261            .unwrap();
3262        rt.execute_query("INSERT INTO plain (id, val) VALUES (1, 'a'), (2, 'b')")
3263            .unwrap();
3264        // No EVENTS subscription — truncate must work without touching any queue.
3265        rt.execute_query("TRUNCATE TABLE plain").unwrap();
3266        // No crash, no queue to check. Just verify truncation happened.
3267        let rows = rt.execute_query("SELECT id FROM plain").unwrap();
3268        assert!(rows.result.records.is_empty());
3269    }
3270
3271    /// `DROP TABLE users` on an event-enabled collection emits exactly 1
3272    /// `collection_dropped` event. The subscription is removed from the
3273    /// source contract but the target queue is preserved for consumer drain.
3274    #[test]
3275    fn drop_event_enabled_table_emits_single_collection_dropped_event() {
3276        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3277        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3278            .unwrap();
3279        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'alice'), (2, 'bob')")
3280            .unwrap();
3281
3282        // Drain insert events so we start clean.
3283        rt.execute_query("QUEUE POP users_events COUNT 10").unwrap();
3284
3285        rt.execute_query("DROP TABLE users").unwrap();
3286
3287        // Queue must still exist with 1 collection_dropped event.
3288        let events = queue_payloads(&rt, "users_events");
3289        assert_eq!(
3290            events.len(),
3291            1,
3292            "expected 1 collection_dropped event, got {}",
3293            events.len()
3294        );
3295        let ev = events[0].as_object().expect("event is object");
3296        assert_eq!(
3297            ev.get("op").and_then(crate::json::Value::as_str),
3298            Some("collection_dropped")
3299        );
3300        assert_eq!(
3301            ev.get("collection").and_then(crate::json::Value::as_str),
3302            Some("users")
3303        );
3304        assert_eq!(
3305            ev.get("final_entities_count")
3306                .and_then(crate::json::Value::as_u64),
3307            Some(2)
3308        );
3309        assert!(ev.get("ts").and_then(crate::json::Value::as_u64).is_some());
3310        assert!(ev.get("lsn").and_then(crate::json::Value::as_u64).is_some());
3311        assert!(ev
3312            .get("event_id")
3313            .and_then(crate::json::Value::as_str)
3314            .is_some_and(|s| !s.is_empty()));
3315
3316        // Source collection is gone.
3317        let err = rt.execute_query("SELECT id FROM users").unwrap_err();
3318        assert!(
3319            format!("{err}").contains("users"),
3320            "expected not-found error"
3321        );
3322    }
3323
3324    /// `DROP TABLE users` on a collection without event subscription works
3325    /// normally with no event emitted.
3326    #[test]
3327    fn drop_no_events_collection_emits_nothing() {
3328        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3329        rt.execute_query("CREATE TABLE plain (id INT, val TEXT)")
3330            .unwrap();
3331        rt.execute_query("INSERT INTO plain (id, val) VALUES (1, 'a')")
3332            .unwrap();
3333        rt.execute_query("DROP TABLE plain").unwrap();
3334        // No crash and collection is gone.
3335        let err = rt.execute_query("SELECT id FROM plain").unwrap_err();
3336        assert!(format!("{err}").contains("plain"));
3337    }
3338
3339    // ── #297: ops_filter + WHERE filter ────────────────────────────────────
3340
3341    /// `WITH EVENTS (INSERT)` — UPDATE and DELETE events must NOT be emitted.
3342    #[test]
3343    fn ops_filter_insert_only_ignores_update_and_delete() {
3344        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3345        rt.execute_query(
3346            "CREATE TABLE items (id INT, val TEXT) WITH EVENTS (INSERT) TO items_events",
3347        )
3348        .unwrap();
3349        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 'a')")
3350            .unwrap();
3351        rt.execute_query("UPDATE items SET val = 'b' WHERE id = 1")
3352            .unwrap();
3353        rt.execute_query("DELETE FROM items WHERE id = 1").unwrap();
3354
3355        let events = queue_payloads(&rt, "items_events");
3356        // Only the INSERT should have fired.
3357        assert_eq!(
3358            events.len(),
3359            1,
3360            "expected 1 insert event, got {}",
3361            events.len()
3362        );
3363        assert_eq!(
3364            events[0]
3365                .as_object()
3366                .unwrap()
3367                .get("op")
3368                .and_then(crate::json::Value::as_str),
3369            Some("insert")
3370        );
3371    }
3372
3373    /// `WITH EVENTS WHERE status = 'active'` — only rows matching the predicate generate events.
3374    #[test]
3375    fn where_filter_skips_rows_that_do_not_match() {
3376        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3377        rt.execute_query(
3378            "CREATE TABLE users (id INT, status TEXT) WITH EVENTS WHERE status = 'active' TO users_events",
3379        )
3380        .unwrap();
3381
3382        // This row should generate an event.
3383        rt.execute_query("INSERT INTO users (id, status) VALUES (1, 'active')")
3384            .unwrap();
3385        // This row should NOT generate an event.
3386        rt.execute_query("INSERT INTO users (id, status) VALUES (2, 'inactive')")
3387            .unwrap();
3388
3389        let events = queue_payloads(&rt, "users_events");
3390        assert_eq!(
3391            events.len(),
3392            1,
3393            "expected 1 event (only active), got {}",
3394            events.len()
3395        );
3396        let ev = events[0].as_object().unwrap();
3397        assert_eq!(
3398            ev.get("op").and_then(crate::json::Value::as_str),
3399            Some("insert")
3400        );
3401        let after = ev.get("after").unwrap().as_object().unwrap();
3402        assert_eq!(
3403            after.get("status").and_then(crate::json::Value::as_str),
3404            Some("active")
3405        );
3406    }
3407
3408    /// `WITH EVENTS (INSERT, UPDATE) WHERE status = 'active'` — combination functional.
3409    #[test]
3410    fn ops_filter_and_where_filter_combined() {
3411        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3412        rt.execute_query(
3413            "CREATE TABLE items (id INT, status TEXT) WITH EVENTS (INSERT, UPDATE) WHERE status = 'active' TO items_events",
3414        )
3415        .unwrap();
3416
3417        // INSERT active → event
3418        rt.execute_query("INSERT INTO items (id, status) VALUES (1, 'active')")
3419            .unwrap();
3420        // INSERT inactive → no event
3421        rt.execute_query("INSERT INTO items (id, status) VALUES (2, 'inactive')")
3422            .unwrap();
3423        // UPDATE row 1 to inactive → after = inactive, no event
3424        rt.execute_query("UPDATE items SET status = 'inactive' WHERE id = 1")
3425            .unwrap();
3426        // DELETE → ops_filter excludes it
3427        rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
3428
3429        let events = queue_payloads(&rt, "items_events");
3430        // Only the first INSERT (active) fires; UPDATE result is inactive so skipped; DELETE excluded by ops_filter.
3431        assert_eq!(
3432            events.len(),
3433            1,
3434            "expected 1 event, got {}: {events:?}",
3435            events.len()
3436        );
3437        assert_eq!(
3438            events[0]
3439                .as_object()
3440                .unwrap()
3441                .get("op")
3442                .and_then(crate::json::Value::as_str),
3443            Some("insert")
3444        );
3445    }
3446
3447    /// WHERE filter on DELETE events — the before-state (pre-image) is evaluated.
3448    #[test]
3449    fn where_filter_on_delete_checks_before_state() {
3450        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3451        rt.execute_query(
3452            "CREATE TABLE users (id INT, status TEXT) WITH EVENTS (DELETE) WHERE status = 'active' TO users_events",
3453        )
3454        .unwrap();
3455
3456        rt.execute_query("INSERT INTO users (id, status) VALUES (1, 'active'), (2, 'inactive')")
3457            .unwrap();
3458
3459        // Delete active row → event (before-state was active)
3460        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
3461        // Delete inactive row → no event (before-state was inactive)
3462        rt.execute_query("DELETE FROM users WHERE id = 2").unwrap();
3463
3464        let events = queue_payloads(&rt, "users_events");
3465        assert_eq!(
3466            events.len(),
3467            1,
3468            "expected 1 delete event, got {}",
3469            events.len()
3470        );
3471        let ev = events[0].as_object().unwrap();
3472        assert_eq!(
3473            ev.get("op").and_then(crate::json::Value::as_str),
3474            Some("delete")
3475        );
3476    }
3477
3478    // ── #301: schema evolution OperatorEvent on ALTER ───────────────────────
3479
3480    /// ADD COLUMN on event-enabled table must succeed (OperatorEvent is best-effort).
3481    #[test]
3482    fn alter_add_column_on_event_enabled_table_succeeds() {
3483        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3484        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3485            .unwrap();
3486        // Must not error — OperatorEvent emission is best-effort (no global sink in tests).
3487        rt.execute_query("ALTER TABLE users ADD COLUMN phone TEXT")
3488            .unwrap();
3489        // The column is now in the contract.
3490        let contract = rt.db().collection_contract("users").unwrap();
3491        assert!(
3492            contract.declared_columns.iter().any(|c| c.name == "phone"),
3493            "phone column should be in contract"
3494        );
3495        // Subscription still enabled after the alter.
3496        assert!(
3497            contract.subscriptions.iter().any(|s| s.enabled),
3498            "subscription should remain enabled"
3499        );
3500    }
3501
3502    /// DROP COLUMN on event-enabled table must succeed; non-column ALTERs
3503    /// (like ENABLE ROW LEVEL SECURITY) must also succeed without emitting.
3504    #[test]
3505    fn alter_drop_column_and_rls_on_event_enabled_table_succeeds() {
3506        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3507        rt.execute_query(
3508            "CREATE TABLE items (id INT, secret TEXT, status TEXT) WITH EVENTS TO items_events",
3509        )
3510        .unwrap();
3511        // DROP COLUMN — schema change event path exercises, must not error.
3512        rt.execute_query("ALTER TABLE items DROP COLUMN secret")
3513            .unwrap();
3514        let contract = rt.db().collection_contract("items").unwrap();
3515        assert!(
3516            !contract.declared_columns.iter().any(|c| c.name == "secret"),
3517            "secret column should be removed"
3518        );
3519        // ENABLE RLS — non-column op, no schema-change event (coverage).
3520        rt.execute_query("ALTER TABLE items ENABLE ROW LEVEL SECURITY")
3521            .unwrap();
3522        // Collection and subscription still intact.
3523        assert!(
3524            contract.subscriptions.iter().any(|s| s.enabled),
3525            "subscription should remain enabled"
3526        );
3527    }
3528
3529    /// Slice G (#675) — every newly-created `CollectionModel::Vector`
3530    /// collection is marked `vector.turbo` and gains a materialised
3531    /// `TurboCollectionState`. The marker is what the SEARCH/INSERT
3532    /// hot paths read to branch between TurboQuant and the legacy
3533    /// brute-force fallback.
3534    #[test]
3535    fn create_vector_marks_collection_as_turbo_baseline() {
3536        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3537        rt.execute_query("CREATE VECTOR embeddings DIM 4").unwrap();
3538        let store = rt.db().store();
3539        assert!(
3540            crate::runtime::vector_turbo_kind::is_turbo(&store, "embeddings"),
3541            "new vector collections must be turbo-marked baseline"
3542        );
3543        assert!(
3544            rt.db().turbo_state("embeddings").is_some(),
3545            "turbo_state must materialise after CREATE VECTOR"
3546        );
3547    }
3548
3549    /// Non-vector collections must NOT be turbo-marked. Guards against
3550    /// the always-baseline change accidentally leaking the marker onto
3551    /// CREATE TABLE / CREATE DOCUMENT / etc.
3552    #[test]
3553    fn create_table_does_not_mark_turbo() {
3554        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3555        rt.execute_query("CREATE TABLE plain (id INT)").unwrap();
3556        let store = rt.db().store();
3557        assert!(
3558            !crate::runtime::vector_turbo_kind::is_turbo(&store, "plain"),
3559            "non-vector collections must not gain the turbo marker"
3560        );
3561        assert!(rt.db().turbo_state("plain").is_none());
3562    }
3563
3564    /// `CREATE COLLECTION KIND vector.turbo` continues to mark the
3565    /// collection (idempotent with the new always-baseline path).
3566    #[test]
3567    fn create_collection_kind_vector_turbo_still_marked() {
3568        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3569        rt.execute_query("CREATE COLLECTION turbo_v KIND vector.turbo DIM 4")
3570            .unwrap();
3571        let store = rt.db().store();
3572        assert!(crate::runtime::vector_turbo_kind::is_turbo(
3573            &store, "turbo_v"
3574        ));
3575        assert!(rt.db().turbo_state("turbo_v").is_some());
3576    }
3577
3578    /// Issue #1271: a declared AI policy is persisted in the catalog and
3579    /// reads back identical via the collection contract (introspection).
3580    #[test]
3581    fn create_table_persists_and_introspects_ai_policy() {
3582        use crate::catalog::{ModerateDegradedMode, ModerateRejectAction};
3583        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3584        rt.execute_query(
3585            "CREATE TABLE posts (id INT, title TEXT, body TEXT, photo TEXT) WITH ( \
3586               EMBED (fields = ('title', 'body'), provider = 'openai', model = 'text-embedding-3-small'), \
3587               MODERATE (fields = ('body'), provider = 'openai', model = 'omni-moderation-latest', sync = true, degraded = closed, on_reject = flag), \
3588               VISION (image_field = 'photo', outputs = ('caption'), provider = 'openai', model = 'gpt-4o') \
3589             )",
3590        )
3591        .expect("create table with ai policy");
3592
3593        let contracts = rt.db().collection_contracts();
3594        let contract = contracts
3595            .iter()
3596            .find(|c| c.name == "posts")
3597            .expect("contract persisted");
3598        let policy = contract.ai_policy.as_ref().expect("ai policy persisted");
3599
3600        let embed = policy.embed.as_ref().expect("embed");
3601        assert_eq!(embed.fields, vec!["title".to_string(), "body".to_string()]);
3602        assert_eq!(embed.model, "text-embedding-3-small");
3603
3604        let moderate = policy.moderate.as_ref().expect("moderate");
3605        assert!(moderate.sync_gate);
3606        assert_eq!(moderate.degraded_mode, ModerateDegradedMode::Closed);
3607        assert_eq!(moderate.reject_action, ModerateRejectAction::Flag);
3608
3609        let vision = policy.vision.as_ref().expect("vision");
3610        assert_eq!(vision.image_field, "photo");
3611        assert_eq!(vision.model, "gpt-4o");
3612    }
3613
3614    /// Issue #1271 / #1269: a policy wiring a provider to a modality it
3615    /// cannot serve is rejected at DDL time, and the collection is not
3616    /// created. Anthropic has no embeddings product in the matrix.
3617    #[test]
3618    fn create_table_rejects_ai_policy_incapable_provider() {
3619        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3620        let err = rt
3621            .execute_query(
3622                "CREATE TABLE bad (id INT, body TEXT) WITH ( \
3623                   EMBED (fields = ('body'), provider = 'anthropic', model = 'claude-3-5-sonnet') \
3624                 )",
3625            )
3626            .unwrap_err();
3627        assert!(
3628            err.to_string()
3629                .contains("cannot serve the 'embed' modality"),
3630            "{err}"
3631        );
3632        assert!(
3633            rt.db().store().get_collection("bad").is_none(),
3634            "rejected DDL must not create the collection"
3635        );
3636    }
3637
3638    #[test]
3639    fn descriptions_cover_collection_models_and_survive_reopen() {
3640        let directory = tempfile::tempdir().expect("temporary database");
3641        let path = directory.path().join("descriptions.rdb");
3642        let options = RedDBOptions::persistent(&path);
3643        {
3644            let rt = RedDBRuntime::with_options(options.clone()).expect("runtime");
3645            assert!(!rt.config_bool("ai.collection_descriptions.auto_enrich", false));
3646            rt.execute_query("CREATE TABLE contacts (email EMAIL DESCRIPTION 'Contact address', balance MONEY) WITH (DESCRIPTION = 'Contact records')").expect("table");
3647            rt.execute_query(
3648                "CREATE COLLECTION articles KIND document DESCRIPTION 'Published articles'",
3649            )
3650            .expect("document");
3651            rt.execute_query("ALTER COLLECTION articles SET DESCRIPTION 'Editorial articles'")
3652                .expect("alter document");
3653            rt.execute_query(
3654                "ALTER COLLECTION contacts ALTER COLUMN balance SET DESCRIPTION 'Account balance'",
3655            )
3656            .expect("alter column");
3657            let contract = rt
3658                .db()
3659                .collection_contract("contacts")
3660                .expect("table contract");
3661            assert_eq!(contract.description.as_deref(), Some("Contact records"));
3662            assert_eq!(
3663                contract.declared_columns[0].description.as_deref(),
3664                Some("Contact address")
3665            );
3666            assert_eq!(
3667                contract.declared_columns[1].description.as_deref(),
3668                Some("Account balance")
3669            );
3670            assert!(!contract.declared_columns[1].description_generated);
3671            let show_create = rt
3672                .execute_query("SHOW CREATE TABLE contacts")
3673                .expect("show create");
3674            let Some(Value::Text(ddl)) = show_create.result.records[0].get("ddl") else {
3675                panic!("DDL text")
3676            };
3677            assert!(ddl.contains("DESCRIPTION 'Account balance'"), "{ddl}");
3678            assert!(
3679                ddl.contains("WITH (DESCRIPTION = 'Contact records')"),
3680                "{ddl}"
3681            );
3682            let collections = rt
3683                .execute_query("SELECT description FROM red.collections WHERE name = 'contacts'")
3684                .expect("collections view");
3685            assert_eq!(
3686                collections.result.records[0].get("description"),
3687                Some(&Value::text("Contact records"))
3688            );
3689            let columns = rt.execute_query("SELECT description FROM red.columns WHERE collection = 'contacts' AND name = 'email'").expect("columns view");
3690            assert_eq!(
3691                columns.result.records[0].get("description"),
3692                Some(&Value::text("Contact address"))
3693            );
3694            assert!(rt
3695                .execute_query(
3696                    "ALTER COLLECTION contacts ALTER COLUMN missing SET DESCRIPTION 'Nope'"
3697                )
3698                .is_err());
3699            rt.checkpoint().expect("checkpoint");
3700        }
3701        let reopened = RedDBRuntime::with_options(options).expect("reopen");
3702        assert_eq!(
3703            reopened
3704                .db()
3705                .collection_contract("articles")
3706                .unwrap()
3707                .description
3708                .as_deref(),
3709            Some("Editorial articles")
3710        );
3711        let contract = reopened.db().collection_contract("contacts").unwrap();
3712        assert_eq!(
3713            contract.declared_columns[1].description.as_deref(),
3714            Some("Account balance")
3715        );
3716    }
3717
3718    #[test]
3719    fn generated_descriptions_preserve_manual_edits_and_reject_stale_versions() {
3720        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3721        rt.execute_query("CREATE TABLE readings (email EMAIL DESCRIPTION 'Manual', amount MONEY)")
3722            .expect("table");
3723        let contract = rt.db().collection_contract("readings").expect("contract");
3724        let suggestions = std::collections::HashMap::from([
3725            ("email".to_string(), "Generated email".to_string()),
3726            ("amount".to_string(), "Generated amount".to_string()),
3727        ]);
3728        assert!(rt
3729            .db()
3730            .save_generated_descriptions_if_version(
3731                "readings",
3732                contract.version,
3733                contract.created_at_unix_ms,
3734                Some("Generated collection".to_string()),
3735                &suggestions
3736            )
3737            .expect("save generated"));
3738        let generated = rt.db().collection_contract("readings").unwrap();
3739        assert_eq!(
3740            generated.declared_columns[0].description.as_deref(),
3741            Some("Manual")
3742        );
3743        assert!(!generated.declared_columns[0].description_generated);
3744        assert_eq!(
3745            generated.declared_columns[1].description.as_deref(),
3746            Some("Generated amount")
3747        );
3748        assert!(generated.declared_columns[1].description_generated);
3749        rt.execute_query(
3750            "ALTER COLLECTION readings ALTER COLUMN amount SET DESCRIPTION 'Manual amount'",
3751        )
3752        .expect("manual override");
3753        assert!(!rt
3754            .db()
3755            .save_generated_descriptions_if_version(
3756                "readings",
3757                generated.version,
3758                generated.created_at_unix_ms,
3759                Some("Stale".to_string()),
3760                &suggestions
3761            )
3762            .expect("stale rejected"));
3763        let updated = rt.db().collection_contract("readings").unwrap();
3764        assert_eq!(
3765            updated.declared_columns[1].description.as_deref(),
3766            Some("Manual amount")
3767        );
3768        assert!(!updated.declared_columns[1].description_generated);
3769    }
3770
3771    #[test]
3772    fn alter_collection_description_works_across_models() {
3773        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3774        for (create, name) in [
3775            ("CREATE TABLE records (id INT)", "records"),
3776            ("CREATE DOCUMENT documents", "documents"),
3777            ("CREATE GRAPH network", "network"),
3778            ("CREATE VECTOR embeddings DIM 3", "embeddings"),
3779            (
3780                "CREATE TIMESERIES measurements RETENTION 90 d",
3781                "measurements",
3782            ),
3783            ("CREATE QUEUE jobs MAX_SIZE 100", "jobs"),
3784            ("CREATE KV settings", "settings"),
3785        ] {
3786            rt.execute_query(create).expect(create);
3787            rt.execute_query(&format!(
3788                "ALTER COLLECTION {name} SET DESCRIPTION 'User description'"
3789            ))
3790            .expect("alter collection");
3791            let contract = rt.db().collection_contract(name).expect("contract");
3792            assert_eq!(
3793                contract.description.as_deref(),
3794                Some("User description"),
3795                "{name}"
3796            );
3797            assert!(!contract.description_generated, "{name}");
3798        }
3799    }
3800}