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 let Some(existing) = self
1626            .inner
1627            .index_store
1628            .list_indices(&query.table)
1629            .into_iter()
1630            .find(|index| index.name == query.name)
1631        {
1632            if query.if_not_exists {
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            if query.method == IndexMethod::Cron
1643                || existing.method == super::index_store::IndexMethodKind::Cron
1644            {
1645                return Err(RedDBError::Query(format!(
1646                    "index '{}' already exists",
1647                    query.name
1648                )));
1649            }
1650        }
1651
1652        let method_kind = match query.method {
1653            IndexMethod::Cron => {
1654                let count = self.build_cron_index(query, &manager)?;
1655                return self.finish_create_index(
1656                    raw_query,
1657                    query,
1658                    super::index_store::IndexMethodKind::Cron,
1659                    count,
1660                    count,
1661                );
1662            }
1663            IndexMethod::Hash => super::index_store::IndexMethodKind::Hash,
1664            IndexMethod::BTree => super::index_store::IndexMethodKind::BTree,
1665            IndexMethod::Bitmap => super::index_store::IndexMethodKind::Bitmap,
1666            // Generic spatial request → engine default spatial backend
1667            // (disk-resident H3 as of PRD #1574 slice 4, #1578).
1668            IndexMethod::Spatial => super::index_store::IndexMethodKind::default_spatial(),
1669            IndexMethod::H3 { resolution } => {
1670                super::index_store::IndexMethodKind::H3 { resolution }
1671            }
1672        };
1673
1674        // Extract fields from existing entities for indexing. Row
1675        // entities may arrive in either the "named" HashMap layout
1676        // (gRPC `BulkInsertBinary` path) OR the columnar layout
1677        // (HTTP `POST /collections/X/bulk/rows` fast path, which uses
1678        // `schema: Some(Arc<Vec<String>>)` + `columns: Vec<Value>` and
1679        // leaves `named == None`). Prior to this commit the columnar
1680        // branch returned an empty field list, so `CREATE INDEX` built
1681        // a zero-entity index over HTTP-inserted data even though the
1682        // data was queryable via `SELECT`.
1683        let index_fields = |e: &crate::storage::UnifiedEntity| -> Vec<(String, Value)> {
1684            match &e.data {
1685                crate::storage::EntityData::Row(row) => {
1686                    if let Some(ref named) = row.named {
1687                        named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
1688                    } else if let Some(ref schema) = row.schema {
1689                        // Columnar layout — pair each column
1690                        // with its positional name from the
1691                        // shared schema Arc.
1692                        schema
1693                            .iter()
1694                            .zip(row.columns.iter())
1695                            .map(|(k, v)| (k.clone(), v.clone()))
1696                            .collect()
1697                    } else {
1698                        Vec::new()
1699                    }
1700                }
1701                crate::storage::EntityData::Node(node) => node
1702                    .properties
1703                    .iter()
1704                    .map(|(k, v)| (k.clone(), v.clone()))
1705                    .collect(),
1706                crate::storage::EntityData::TimeSeries(ts) => ts
1707                    .fields
1708                    .iter()
1709                    .map(|(k, v)| (k.clone(), v.clone()))
1710                    .collect(),
1711                _ => Vec::new(),
1712            }
1713        };
1714        let entities = manager.query_all(|_| true);
1715        let mut entity_fields: Vec<(crate::storage::unified::EntityId, Vec<(String, Value)>)> =
1716            entities.iter().map(|e| (e.id, index_fields(e))).collect();
1717
1718        if query.unique
1719            && matches!(
1720                method_kind,
1721                super::index_store::IndexMethodKind::Hash
1722                    | super::index_store::IndexMethodKind::BTree
1723            )
1724        {
1725            // Only live rows reserve a key: the dead versions of an updated or
1726            // deleted row share its key but are not duplicates. This is DDL
1727            // only — reopening must still rebuild an index over data that an
1728            // older release let duplicate.
1729            let snapshots = self.snapshot_manager();
1730            let own_xids = self.own_transaction_xids();
1731            let mut live = entities.iter().map(|entity| {
1732                snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids)
1733            });
1734            entity_fields.retain(|_| live.next().unwrap_or(false));
1735            let duplicate = if manager.has_backing() {
1736                // `entities` holds the rows in memory; a row that was
1737                // checkpointed is on disk. A table whose duplicates had been
1738                // checkpointed got its unique index, over the duplicates.
1739                // One digest a row stays in memory for the scan.
1740                let mut seen = std::collections::HashMap::new();
1741                let mut duplicate = None;
1742                manager
1743                    .try_scan_for_each(None, usize::MAX, |entity| {
1744                        if !snapshots.row_reserves_unique_key(entity.xmin, entity.xmax, &own_xids) {
1745                            return true;
1746                        }
1747                        let Some(key) = super::index_store::unique_index_key(
1748                            &query.columns,
1749                            &index_fields(entity),
1750                        ) else {
1751                            return true;
1752                        };
1753                        match seen.insert(*blake3::hash(&key).as_bytes(), entity.id) {
1754                            Some(earlier) => {
1755                                duplicate = Some((earlier, entity.id));
1756                                false
1757                            }
1758                            None => true,
1759                        }
1760                    })
1761                    .map_err(|error| RedDBError::Internal(error.to_string()))?;
1762                duplicate
1763            } else {
1764                super::index_store::first_duplicate_unique_key(&query.columns, &entity_fields)
1765            };
1766            if let Some((earlier, later)) = duplicate {
1767                return Err(RedDBError::Query(format!(
1768                    "cannot create unique index '{}' on '{}': rows {} and {} share the same ({}) key",
1769                    query.name,
1770                    query.table,
1771                    earlier.raw(),
1772                    later.raw(),
1773                    query.columns.join(", ")
1774                )));
1775            }
1776        }
1777
1778        let index_growth_rows = entity_fields
1779            .iter()
1780            .map(|(_, fields)| fields.clone())
1781            .collect::<Vec<_>>();
1782        let _reservation = self.admit_non_evictable_growth(
1783            crate::storage::memory_pools::MemoryPool::IndexMemory,
1784            &format!("create index {}", query.name),
1785            crate::runtime::memory_admission::estimate_index_growth(
1786                &index_growth_rows,
1787                &query.columns,
1788            ),
1789        )?;
1790
1791        // Build the index
1792        let indexed_count = self
1793            .inner
1794            .index_store
1795            .create_index(
1796                &query.name,
1797                &query.table,
1798                &query.columns,
1799                method_kind,
1800                query.unique,
1801                &entity_fields,
1802            )
1803            .map_err(RedDBError::Internal)?;
1804
1805        let analyzed = crate::storage::query::planner::stats_catalog::analyze_entity_fields(
1806            &query.table,
1807            &entity_fields,
1808        );
1809        crate::storage::query::planner::stats_catalog::persist_table_stats(&store, &analyzed);
1810        self.finish_create_index(
1811            raw_query,
1812            query,
1813            method_kind,
1814            indexed_count,
1815            entity_fields.len(),
1816        )
1817    }
1818
1819    fn finish_create_index(
1820        &self,
1821        raw_query: &str,
1822        query: &CreateIndexQuery,
1823        method_kind: super::index_store::IndexMethodKind,
1824        indexed_count: usize,
1825        total_count: usize,
1826    ) -> RedDBResult<RuntimeQueryResult> {
1827        self.invalidate_plan_cache();
1828
1829        let descriptor = super::index_store::RegisteredIndex {
1830            name: query.name.clone(),
1831            collection: query.table.clone(),
1832            columns: query.columns.clone(),
1833            method: method_kind,
1834            unique: query.unique,
1835        };
1836        self.inner.index_store.register(descriptor.clone());
1837        if let Err(error) = self.persist_runtime_index_descriptor(descriptor) {
1838            if method_kind == super::index_store::IndexMethodKind::Cron {
1839                self.inner.index_store.drop_index(&query.name, &query.table);
1840            }
1841            return Err(error);
1842        }
1843        // Issue #120 — surface the index name + indexed columns in
1844        // the schema-vocabulary so AskPipeline (#121) can resolve
1845        // "the email index" back to its collection.
1846        self.schema_vocabulary_apply(crate::runtime::schema_vocabulary::DdlEvent::CreateIndex {
1847            collection: query.table.clone(),
1848            index: query.name.clone(),
1849            columns: query.columns.clone(),
1850        });
1851
1852        let method_str = format!("{}", query.method);
1853        let unique_str = if query.unique { "unique " } else { "" };
1854        let cols = query.columns.join(", ");
1855        let coverage_detail =
1856            if matches!(method_kind, super::index_store::IndexMethodKind::H3 { .. })
1857                && total_count > 0
1858                && indexed_count == 0
1859            {
1860                format!(
1861                    "{} of {} entities indexed — no indexable geo value in '{}'; expected {}",
1862                    indexed_count,
1863                    total_count,
1864                    cols,
1865                    crate::geo::RECOGNIZED_GEO_SHAPES
1866                )
1867            } else if matches!(method_kind, super::index_store::IndexMethodKind::H3 { .. }) {
1868                format!("{} of {} entities indexed", indexed_count, total_count)
1869            } else {
1870                format!("{} entities indexed", indexed_count)
1871            };
1872
1873        Ok(RuntimeQueryResult::ok_message(
1874            raw_query.to_string(),
1875            &format!(
1876                "{}index '{}' created on '{}' ({}) using {} ({})",
1877                unique_str, query.name, query.table, cols, method_str, coverage_detail
1878            ),
1879            "create",
1880        ))
1881    }
1882
1883    /// Execute DROP INDEX
1884    ///
1885    /// Removes an index from a collection.
1886    pub fn execute_drop_index(
1887        &self,
1888        raw_query: &str,
1889        query: &DropIndexQuery,
1890    ) -> RedDBResult<RuntimeQueryResult> {
1891        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1892        let topology_lock = self
1893            .inner
1894            .index_store
1895            .collection_topology_lock(&query.table);
1896        let _topology_guard = topology_lock.write();
1897        let store = self.inner.db.store();
1898
1899        // Verify the table exists
1900        if store.get_collection(&query.table).is_none() {
1901            if query.if_exists {
1902                return Ok(RuntimeQueryResult::ok_message(
1903                    raw_query.to_string(),
1904                    &format!("table '{}' does not exist", query.table),
1905                    "drop",
1906                ));
1907            }
1908            return Err(RedDBError::NotFound(format!(
1909                "table '{}' not found",
1910                query.table
1911            )));
1912        }
1913
1914        // Remove from IndexStore
1915        self.inner.index_store.drop_index(&query.name, &query.table);
1916        self.persist_runtime_index_drop(&query.table, &query.name)?;
1917        self.invalidate_plan_cache();
1918        // Issue #120 — keep the schema-vocabulary index entry in sync.
1919        self.schema_vocabulary_apply(crate::runtime::schema_vocabulary::DdlEvent::DropIndex {
1920            collection: query.table.clone(),
1921            index: query.name.clone(),
1922        });
1923
1924        Ok(RuntimeQueryResult::ok_message(
1925            raw_query.to_string(),
1926            &format!("index '{}' dropped from '{}'", query.name, query.table),
1927            "drop",
1928        ))
1929    }
1930
1931    fn execute_drop_typed_collection(
1932        &self,
1933        raw_query: &str,
1934        name: &str,
1935        if_exists: bool,
1936        expected_model: CollectionModel,
1937        label: &str,
1938    ) -> RedDBResult<RuntimeQueryResult> {
1939        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1940        if is_system_schema_name(name) {
1941            return Err(RedDBError::Query("system schema is read-only".to_string()));
1942        }
1943        let store = self.inner.db.store();
1944        let _publication = store.vault_publication_lock.lock();
1945        self.vcs_reject_destructive_ddl(name)?;
1946        if store.get_collection(name).is_none() {
1947            if if_exists {
1948                return Ok(RuntimeQueryResult::ok_message(
1949                    raw_query.to_string(),
1950                    &format!("{label} '{name}' does not exist"),
1951                    "drop",
1952                ));
1953            }
1954            return Err(RedDBError::NotFound(format!("{label} '{name}' not found")));
1955        }
1956
1957        let actual = self
1958            .inner
1959            .db
1960            .collection_contract(name)
1961            .map(|contract| contract.declared_model)
1962            .map(Ok)
1963            .unwrap_or_else(|| {
1964                polymorphic_resolver::resolve(name, &self.inner.db.catalog_model_snapshot())
1965            })?;
1966        polymorphic_resolver::ensure_model_match(expected_model, actual)?;
1967        self.drop_collection_storage(raw_query, name, label)
1968    }
1969
1970    pub fn execute_truncate(
1971        &self,
1972        raw_query: &str,
1973        query: &TruncateQuery,
1974    ) -> RedDBResult<RuntimeQueryResult> {
1975        self.check_write(crate::runtime::write_gate::WriteKind::Ddl)?;
1976        if is_system_schema_name(&query.name) {
1977            return Err(RedDBError::Query("system schema is read-only".to_string()));
1978        }
1979
1980        let label = query
1981            .model
1982            .map(polymorphic_resolver::model_name)
1983            .unwrap_or("collection");
1984        let store = self.inner.db.store();
1985        if store.get_collection(&query.name).is_none() {
1986            if query.if_exists {
1987                return Ok(RuntimeQueryResult::ok_message(
1988                    raw_query.to_string(),
1989                    &format!("{label} '{}' does not exist", query.name),
1990                    "truncate",
1991                ));
1992            }
1993            return Err(RedDBError::NotFound(format!(
1994                "{label} '{}' not found",
1995                query.name
1996            )));
1997        }
1998
1999        let actual =
2000            polymorphic_resolver::resolve(&query.name, &self.inner.db.catalog_model_snapshot())?;
2001        if let Some(expected) = query.model {
2002            polymorphic_resolver::ensure_model_match(expected, actual)?;
2003        }
2004
2005        if actual == CollectionModel::Queue {
2006            return self.execute_queue_command(
2007                raw_query,
2008                &QueueCommand::Purge {
2009                    queue: query.name.clone(),
2010                },
2011            );
2012        }
2013
2014        // Count before wiping so we can emit the aggregated truncate event.
2015        let affected = self.truncate_collection_entities(&query.name)?;
2016        // Emit 1 truncate event (not N delete events) for event-enabled collections.
2017        crate::runtime::mutation::emit_truncate_event_for_collection(self, &query.name, affected)?;
2018        self.inner.db.invalidate_vector_index(&query.name);
2019        self.clear_table_planner_stats(&query.name);
2020        self.invalidate_result_cache();
2021
2022        Ok(RuntimeQueryResult::ok_message(
2023            raw_query.to_string(),
2024            &format!(
2025                "{affected} entities truncated from {label} '{}'",
2026                query.name
2027            ),
2028            "truncate",
2029        ))
2030    }
2031
2032    fn truncate_collection_entities(&self, name: &str) -> RedDBResult<u64> {
2033        let store = self.inner.db.store();
2034        let _publication = store.vault_publication_lock.lock();
2035        self.vcs_reject_destructive_ddl(name)?;
2036        let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(name);
2037        let store = self.inner.db.store();
2038        let Some(manager) = store.get_collection(name) else {
2039            return Ok(0);
2040        };
2041        let entities = manager.query_all(|_| true);
2042        if entities.is_empty() {
2043            return Ok(0);
2044        }
2045
2046        for entity in &entities {
2047            let fields = entity_index_fields(&entity.data);
2048            self.inner
2049                .index_store
2050                .index_entity_delete(name, entity.id, &fields)
2051                .map_err(RedDBError::Internal)?;
2052        }
2053
2054        let ids = entities.iter().map(|entity| entity.id).collect::<Vec<_>>();
2055        let deleted_ids = store
2056            .delete_batch(name, &ids)
2057            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2058        for id in &deleted_ids {
2059            store.context_index().remove_entity(*id);
2060        }
2061        Ok(deleted_ids.len() as u64)
2062    }
2063
2064    fn drop_collection_storage(
2065        &self,
2066        raw_query: &str,
2067        name: &str,
2068        label: &str,
2069    ) -> RedDBResult<RuntimeQueryResult> {
2070        let store = self.inner.db.store();
2071        let _publication = store.vault_publication_lock.lock();
2072        self.vcs_reject_destructive_ddl(name)?;
2073
2074        // Emit 1 collection_dropped event before storage is wiped.
2075        // Queue is preserved; subscription is removed with the contract below.
2076        let final_count = store
2077            .get_collection(name)
2078            .map(|manager| manager.query_all(|_| true).len() as u64)
2079            .unwrap_or(0);
2080        crate::runtime::mutation::emit_collection_dropped_event_for_collection(
2081            self,
2082            name,
2083            final_count,
2084        )?;
2085
2086        let topology_lock = self.inner.index_store.collection_topology_lock(name);
2087        let _topology_guard = topology_lock.write();
2088        let orphaned_indices: Vec<String> = self
2089            .inner
2090            .index_store
2091            .list_indices(name)
2092            .into_iter()
2093            .map(|index| index.name)
2094            .collect();
2095        for index_name in &orphaned_indices {
2096            self.inner.index_store.drop_index(index_name, name);
2097        }
2098
2099        store
2100            .drop_collection(name)
2101            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2102        self.inner.db.invalidate_vector_index(name);
2103        self.inner.db.clear_collection_default_ttl_ms(name);
2104        self.inner
2105            .db
2106            .remove_collection_contract(name)
2107            .map_err(|err| RedDBError::Internal(err.to_string()))?;
2108        self.clear_table_planner_stats(name);
2109        self.invalidate_result_cache();
2110        if let Some(store) = self.inner.auth_store.read().clone() {
2111            store.invalidate_visible_collections_cache();
2112        }
2113        // The native registry and targeted contract metadata publication above
2114        // are the DROP commit boundary; do not turn this into a full database
2115        // fingerprint/checkpoint.
2116        self.schema_vocabulary_apply(
2117            crate::runtime::schema_vocabulary::DdlEvent::DropCollection {
2118                collection: name.to_string(),
2119            },
2120        );
2121
2122        Ok(RuntimeQueryResult::ok_message(
2123            raw_query.to_string(),
2124            &format!("{label} '{name}' dropped"),
2125            "drop",
2126        ))
2127    }
2128}
2129
2130pub(crate) fn is_system_schema_name(name: &str) -> bool {
2131    let name = reddb_engine::storage::system_collection_names::canonical_or_self(name);
2132    name == "red" || name.starts_with("red.") || name.starts_with("__red_schema_")
2133}
2134
2135fn entity_index_fields(data: &EntityData) -> Vec<(String, Value)> {
2136    match data {
2137        EntityData::Row(row) => {
2138            if let Some(ref named) = row.named {
2139                named
2140                    .iter()
2141                    .map(|(key, value)| (key.clone(), value.clone()))
2142                    .collect()
2143            } else if let Some(ref schema) = row.schema {
2144                schema
2145                    .iter()
2146                    .zip(row.columns.iter())
2147                    .map(|(key, value)| (key.clone(), value.clone()))
2148                    .collect()
2149            } else {
2150                Vec::new()
2151            }
2152        }
2153        EntityData::Node(node) => node
2154            .properties
2155            .iter()
2156            .map(|(key, value)| (key.clone(), value.clone()))
2157            .collect(),
2158        _ => Vec::new(),
2159    }
2160}
2161
2162/// DDL-time gate for a declared AI policy (issue #1271). Each declared
2163/// modality block is checked against the provider capability matrix
2164/// (#1269): a provider/model that cannot serve the requested modality is
2165/// rejected before the collection is created. Uses the built-in registry
2166/// (no per-deployment overrides at DDL time).
2167fn validate_ai_policy_modalities(policy: &crate::catalog::AiPolicy) -> RedDBResult<()> {
2168    use crate::runtime::ai::provider_capabilities::{Modality, Registry};
2169    let registry = Registry::new();
2170    let check = |provider: &str, model: &str, modality: Modality| -> RedDBResult<()> {
2171        registry
2172            .validate_policy_modality(provider, model, modality)
2173            .map_err(|err| RedDBError::Query(err.to_string()))
2174    };
2175    if let Some(embed) = &policy.embed {
2176        check(&embed.provider, &embed.model, Modality::Embed)?;
2177    }
2178    if let Some(moderate) = &policy.moderate {
2179        check(&moderate.provider, &moderate.model, Modality::Moderate)?;
2180    }
2181    if let Some(vision) = &policy.vision {
2182        check(&vision.provider, &vision.model, Modality::Vision)?;
2183    }
2184    Ok(())
2185}
2186
2187fn collection_contract_from_create_table(
2188    query: &CreateTableQuery,
2189) -> RedDBResult<crate::physical::CollectionContract> {
2190    reddb_engine::catalog::ddl::collection_contract_from_create_table(query, current_unix_ms())
2191        .map_err(RedDBError::Query)
2192}
2193
2194fn default_collection_contract_for_existing_table(
2195    name: &str,
2196) -> crate::physical::CollectionContract {
2197    let now = current_unix_ms();
2198    crate::physical::CollectionContract {
2199        graph_contract: None,
2200        name: name.to_string(),
2201        description: None,
2202        description_generated: false,
2203        declared_model: crate::catalog::CollectionModel::Table,
2204        schema_mode: crate::catalog::SchemaMode::SemiStructured,
2205        origin: crate::physical::ContractOrigin::Explicit,
2206        version: 0,
2207        created_at_unix_ms: now,
2208        updated_at_unix_ms: now,
2209        default_ttl_ms: None,
2210        vector_dimension: None,
2211        vector_metric: None,
2212        context_index_fields: Vec::new(),
2213        declared_columns: Vec::new(),
2214        table_def: Some(reddb_types::TableDef::new(name.to_string())),
2215        timestamps_enabled: false,
2216        context_index_enabled: false,
2217        metrics_raw_retention_ms: None,
2218        metrics_rollup_policies: Vec::new(),
2219        metrics_tenant_identity: None,
2220        metrics_namespace: None,
2221        append_only: false,
2222        subscriptions: Vec::new(),
2223        analytics_config: Vec::new(),
2224        session_key: None,
2225        session_gap_ms: None,
2226        retention_duration_ms: None,
2227        analytical_storage: None,
2228
2229        ai_policy: None,
2230    }
2231}
2232
2233fn keyed_collection_contract(
2234    name: &str,
2235    model: crate::catalog::CollectionModel,
2236    analytics_config: Vec<crate::catalog::AnalyticsViewDescriptor>,
2237) -> crate::physical::CollectionContract {
2238    let now = current_unix_ms();
2239    crate::physical::CollectionContract {
2240        graph_contract: None,
2241        name: name.to_string(),
2242        description: None,
2243        description_generated: false,
2244        declared_model: model,
2245        schema_mode: crate::catalog::SchemaMode::Dynamic,
2246        origin: crate::physical::ContractOrigin::Explicit,
2247        version: 1,
2248        created_at_unix_ms: now,
2249        updated_at_unix_ms: now,
2250        default_ttl_ms: None,
2251        vector_dimension: None,
2252        vector_metric: None,
2253        context_index_fields: Vec::new(),
2254        declared_columns: Vec::new(),
2255        table_def: None,
2256        timestamps_enabled: false,
2257        context_index_enabled: false,
2258        metrics_raw_retention_ms: None,
2259        metrics_rollup_policies: Vec::new(),
2260        metrics_tenant_identity: None,
2261        metrics_namespace: None,
2262        append_only: false,
2263        subscriptions: Vec::new(),
2264        analytics_config,
2265        session_key: None,
2266        session_gap_ms: None,
2267        retention_duration_ms: None,
2268        analytical_storage: None,
2269
2270        ai_policy: None,
2271    }
2272}
2273
2274fn metrics_collection_contract(query: &CreateTableQuery) -> crate::physical::CollectionContract {
2275    let now = current_unix_ms();
2276    crate::physical::CollectionContract {
2277        graph_contract: None,
2278        name: query.name.clone(),
2279        description: None,
2280        description_generated: false,
2281        declared_model: crate::catalog::CollectionModel::Metrics,
2282        schema_mode: crate::catalog::SchemaMode::SemiStructured,
2283        origin: crate::physical::ContractOrigin::Explicit,
2284        version: 1,
2285        created_at_unix_ms: now,
2286        updated_at_unix_ms: now,
2287        default_ttl_ms: query.default_ttl_ms,
2288        vector_dimension: None,
2289        vector_metric: None,
2290        context_index_fields: Vec::new(),
2291        declared_columns: Vec::new(),
2292        table_def: None,
2293        timestamps_enabled: false,
2294        context_index_enabled: false,
2295        metrics_raw_retention_ms: query.default_ttl_ms,
2296        metrics_rollup_policies: query.metrics_rollup_policies.clone(),
2297        metrics_tenant_identity: Some(
2298            query
2299                .tenant_by
2300                .clone()
2301                .unwrap_or_else(|| "current_tenant".to_string()),
2302        ),
2303        metrics_namespace: Some("default".to_string()),
2304        append_only: true,
2305        subscriptions: Vec::new(),
2306        analytics_config: Vec::new(),
2307        session_key: None,
2308        session_gap_ms: None,
2309        retention_duration_ms: None,
2310        analytical_storage: None,
2311
2312        ai_policy: None,
2313    }
2314}
2315
2316fn vector_collection_contract(query: &CreateVectorQuery) -> crate::physical::CollectionContract {
2317    let now = current_unix_ms();
2318    crate::physical::CollectionContract {
2319        graph_contract: None,
2320        name: query.name.clone(),
2321        description: None,
2322        description_generated: false,
2323        declared_model: crate::catalog::CollectionModel::Vector,
2324        schema_mode: crate::catalog::SchemaMode::Dynamic,
2325        origin: crate::physical::ContractOrigin::Explicit,
2326        version: 1,
2327        created_at_unix_ms: now,
2328        updated_at_unix_ms: now,
2329        default_ttl_ms: None,
2330        vector_dimension: Some(query.dimension),
2331        vector_metric: Some(query.metric),
2332        context_index_fields: Vec::new(),
2333        declared_columns: Vec::new(),
2334        table_def: None,
2335        timestamps_enabled: false,
2336        context_index_enabled: false,
2337        metrics_raw_retention_ms: None,
2338        metrics_rollup_policies: Vec::new(),
2339        metrics_tenant_identity: None,
2340        metrics_namespace: None,
2341        append_only: false,
2342        subscriptions: Vec::new(),
2343        analytics_config: Vec::new(),
2344        session_key: None,
2345        session_gap_ms: None,
2346        retention_duration_ms: None,
2347        analytical_storage: None,
2348
2349        ai_policy: None,
2350    }
2351}
2352
2353fn apply_alter_operations_to_contract(
2354    contract: &mut crate::physical::CollectionContract,
2355    operations: &[AlterOperation],
2356) {
2357    if contract.table_def.is_none() {
2358        contract.table_def = Some(reddb_types::TableDef::new(contract.name.clone()));
2359    }
2360    for operation in operations {
2361        match operation {
2362            AlterOperation::SetDescription {
2363                column,
2364                description,
2365            } => {
2366                if let Some(name) = column {
2367                    if let Some(declared) = contract
2368                        .declared_columns
2369                        .iter_mut()
2370                        .find(|declared| declared.name == *name)
2371                    {
2372                        declared.description = Some(description.clone());
2373                        declared.description_generated = false;
2374                    }
2375                } else {
2376                    contract.description = Some(description.clone());
2377                    contract.description_generated = false;
2378                }
2379            }
2380            AlterOperation::AddColumn(column) => {
2381                if !contract
2382                    .declared_columns
2383                    .iter()
2384                    .any(|existing| existing.name == column.name)
2385                {
2386                    contract
2387                        .declared_columns
2388                        .push(declared_column_contract_from_ddl(column));
2389                }
2390                if let Some(table_def) = contract.table_def.as_mut() {
2391                    if table_def.get_column(&column.name).is_none() {
2392                        if let Ok(column_def) = column_def_from_ddl(column) {
2393                            if column.primary_key {
2394                                table_def.primary_key.push(column.name.clone());
2395                                table_def.constraints.push(
2396                                    reddb_types::Constraint::new(
2397                                        format!("pk_{}", column.name),
2398                                        reddb_types::ConstraintType::PrimaryKey,
2399                                    )
2400                                    .on_columns(vec![column.name.clone()]),
2401                                );
2402                            }
2403                            if column.unique {
2404                                table_def.constraints.push(
2405                                    reddb_types::Constraint::new(
2406                                        format!("uniq_{}", column.name),
2407                                        reddb_types::ConstraintType::Unique,
2408                                    )
2409                                    .on_columns(vec![column.name.clone()]),
2410                                );
2411                            }
2412                            if column.not_null {
2413                                table_def.constraints.push(
2414                                    reddb_types::Constraint::new(
2415                                        format!("not_null_{}", column.name),
2416                                        reddb_types::ConstraintType::NotNull,
2417                                    )
2418                                    .on_columns(vec![column.name.clone()]),
2419                                );
2420                            }
2421                            table_def.columns.push(column_def);
2422                        }
2423                    }
2424                }
2425            }
2426            AlterOperation::DropColumn(name) => {
2427                contract
2428                    .declared_columns
2429                    .retain(|column| column.name != *name);
2430                if let Some(table_def) = contract.table_def.as_mut() {
2431                    if let Some(index) = table_def.column_index(name) {
2432                        table_def.columns.remove(index);
2433                    }
2434                    table_def.primary_key.retain(|column| column != name);
2435                    table_def.constraints.retain(|constraint| {
2436                        !constraint.columns.iter().any(|column| column == name)
2437                    });
2438                    table_def
2439                        .indexes
2440                        .retain(|index| !index.columns.iter().any(|column| column == name));
2441                }
2442            }
2443            AlterOperation::RenameColumn { from, to } => {
2444                if contract
2445                    .declared_columns
2446                    .iter()
2447                    .any(|column| column.name == *to)
2448                {
2449                    continue;
2450                }
2451                if let Some(column) = contract
2452                    .declared_columns
2453                    .iter_mut()
2454                    .find(|column| column.name == *from)
2455                {
2456                    column.name = to.clone();
2457                }
2458                if let Some(table_def) = contract.table_def.as_mut() {
2459                    if let Some(column) = table_def
2460                        .columns
2461                        .iter_mut()
2462                        .find(|column| column.name == *from)
2463                    {
2464                        column.name = to.clone();
2465                    }
2466                    for primary_key in &mut table_def.primary_key {
2467                        if *primary_key == *from {
2468                            *primary_key = to.clone();
2469                        }
2470                    }
2471                    for constraint in &mut table_def.constraints {
2472                        for column in &mut constraint.columns {
2473                            if *column == *from {
2474                                *column = to.clone();
2475                            }
2476                        }
2477                        if let Some(ref_columns) = constraint.ref_columns.as_mut() {
2478                            for column in ref_columns {
2479                                if *column == *from {
2480                                    *column = to.clone();
2481                                }
2482                            }
2483                        }
2484                    }
2485                    for index in &mut table_def.indexes {
2486                        for column in &mut index.columns {
2487                            if *column == *from {
2488                                *column = to.clone();
2489                            }
2490                        }
2491                    }
2492                }
2493            }
2494            // Partition ops don't touch the column contract — metadata is
2495            // persisted separately via `partition.*` inside `red.config`.
2496            AlterOperation::AttachPartition { .. } | AlterOperation::DetachPartition { .. } => {}
2497            // RLS toggles don't touch the column contract — flag is persisted
2498            // separately via `rls.enabled.{table}` inside `red.config` and enforced
2499            // through the in-memory `rls_enabled_tables` set.
2500            AlterOperation::EnableRowLevelSecurity | AlterOperation::DisableRowLevelSecurity => {}
2501            // Phase 2.5.4: tenancy toggles persist via `tenant_tables.*` in `red.config`
2502            // and are enforced through `tenant_tables` + RLS auto-policy.
2503            AlterOperation::EnableTenancy { .. } | AlterOperation::DisableTenancy => {}
2504            AlterOperation::SetAppendOnly(on) => {
2505                contract.append_only = *on;
2506            }
2507            // VCS opt-in is persisted to red.vcs.settings by the
2508            // executor, not the contract — nothing to do here.
2509            AlterOperation::SetVersioned(_) => {}
2510            AlterOperation::EnableEvents(subscription) => {
2511                let mut subscription = subscription.clone();
2512                subscription.source = contract.name.clone();
2513                subscription.enabled = true;
2514                if let Some(existing) = contract
2515                    .subscriptions
2516                    .iter_mut()
2517                    .find(|existing| existing.target_queue == subscription.target_queue)
2518                {
2519                    *existing = subscription;
2520                } else {
2521                    contract.subscriptions.push(subscription);
2522                }
2523            }
2524            AlterOperation::DisableEvents => {
2525                for subscription in &mut contract.subscriptions {
2526                    subscription.enabled = false;
2527                }
2528            }
2529            AlterOperation::AddSubscription { name, descriptor } => {
2530                let mut sub = descriptor.clone();
2531                sub.name = name.clone();
2532                sub.source = contract.name.clone();
2533                sub.enabled = true;
2534                if let Some(existing) = contract.subscriptions.iter_mut().find(|s| s.name == *name)
2535                {
2536                    *existing = sub;
2537                } else {
2538                    contract.subscriptions.push(sub);
2539                }
2540            }
2541            AlterOperation::DropSubscription { name } => {
2542                contract.subscriptions.retain(|s| s.name != *name);
2543            }
2544            // Signer registry mutations live in `red.config` outside the
2545            // contract surface — the executor applied them directly via
2546            // `signed_writes_kind::{add,revoke}_signer`. Nothing to fold
2547            // into the column-shaped contract.
2548            AlterOperation::AddSigner { .. } | AlterOperation::RevokeSigner { .. } => {}
2549            AlterOperation::SetRetention { duration_ms } => {
2550                contract.retention_duration_ms = Some(*duration_ms);
2551            }
2552            AlterOperation::UnsetRetention => {
2553                contract.retention_duration_ms = None;
2554            }
2555            // Issue #801 — fold analytics lifecycle into the WAL-backed
2556            // `analytics_config` so the change is durable and the
2557            // `<graph>.<output>` resolver picks it up on the next read.
2558            AlterOperation::AddAnalytics(views) => {
2559                for view in views {
2560                    // Idempotent: skip outputs already enabled so a repeated
2561                    // ADD never duplicates state. The first declaration wins —
2562                    // re-declaring options requires DROP then ADD.
2563                    if !contract
2564                        .analytics_config
2565                        .iter()
2566                        .any(|existing| existing.output == view.output)
2567                    {
2568                        contract.analytics_config.push(view.clone());
2569                    }
2570                }
2571            }
2572            AlterOperation::DropAnalytics(output) => {
2573                contract
2574                    .analytics_config
2575                    .retain(|view| view.output != *output);
2576            }
2577        }
2578    }
2579}
2580
2581/// Issue #580 — returns true if the contract carries at least one
2582/// column the retention filter can use as a timestamp anchor:
2583/// either `WITH timestamps = true` (auto `created_at` / `updated_at`)
2584/// or a user-declared column with a temporal data_type.
2585pub(crate) fn retention_timestamp_column_exists(
2586    contract: &crate::physical::CollectionContract,
2587) -> bool {
2588    if contract.timestamps_enabled {
2589        return true;
2590    }
2591    if matches!(
2592        contract.declared_model,
2593        crate::catalog::CollectionModel::TimeSeries | crate::catalog::CollectionModel::Metrics
2594    ) {
2595        // Time-series and metrics collections carry an intrinsic
2596        // timestamp axis on every row even without a declared column;
2597        // retention has a natural anchor.
2598        return true;
2599    }
2600    contract
2601        .declared_columns
2602        .iter()
2603        .any(|column| is_temporal_data_type(&column.data_type))
2604}
2605
2606fn is_temporal_data_type(data_type: &str) -> bool {
2607    let upper = data_type.to_ascii_uppercase();
2608    matches!(
2609        upper.as_str(),
2610        "TIMESTAMP" | "TIMESTAMPMS" | "TIMESTAMP_MS" | "DATETIME" | "DATE"
2611    )
2612}
2613
2614fn validate_event_subscriptions(
2615    runtime: &RedDBRuntime,
2616    source: &str,
2617    subscriptions: &[crate::catalog::SubscriptionDescriptor],
2618) -> RedDBResult<()> {
2619    for subscription in subscriptions
2620        .iter()
2621        .filter(|subscription| subscription.enabled)
2622    {
2623        if subscription.all_tenants && crate::runtime::impl_core::current_tenant().is_some() {
2624            return Err(RedDBError::Query(
2625                "cross-tenant subscription requires cluster-admin capability (events:cluster_subscribe)".to_string(),
2626            ));
2627        }
2628        validate_subscription_auth(runtime, source, subscription)?;
2629        if subscription.target_queue == source
2630            || subscription_would_create_cycle(
2631                &runtime.inner.db,
2632                source,
2633                &subscription.target_queue,
2634            )
2635        {
2636            return Err(RedDBError::Query(
2637                "subscription would create cycle".to_string(),
2638            ));
2639        }
2640        audit_subscription_redact_gap(runtime, source, subscription);
2641    }
2642    Ok(())
2643}
2644
2645fn validate_subscription_auth(
2646    runtime: &RedDBRuntime,
2647    source: &str,
2648    subscription: &crate::catalog::SubscriptionDescriptor,
2649) -> RedDBResult<()> {
2650    let auth_store = match runtime.inner.auth_store.read().clone() {
2651        Some(store) => store,
2652        None => return Ok(()),
2653    };
2654    let (username, role) = match crate::runtime::impl_core::current_auth_identity() {
2655        Some(identity) => identity,
2656        None => return Ok(()),
2657    };
2658    let tenant = crate::runtime::impl_core::current_tenant();
2659    let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
2660
2661    if auth_store.iam_authorization_enabled() {
2662        let ctx = crate::auth::policies::EvalContext {
2663            principal_tenant: tenant.clone(),
2664            current_tenant: tenant.clone(),
2665            peer_ip: None,
2666            mfa_present: false,
2667            now_ms: crate::auth::now_ms(),
2668            principal_is_admin_role: role == crate::auth::Role::Admin,
2669            principal_is_platform_scoped: principal.tenant.is_none(),
2670        };
2671        let mut source_resource = crate::auth::policies::ResourceRef::new("table", source);
2672        if let Some(t) = tenant.as_deref() {
2673            source_resource = source_resource.with_tenant(t.to_string());
2674        }
2675        if !auth_store.check_policy_authz_with_role(
2676            &principal,
2677            "select",
2678            &source_resource,
2679            &ctx,
2680            role,
2681        ) {
2682            return Err(RedDBError::Query(format!(
2683                "permission denied: principal=`{}` action=`select` resource=`{}:{}` denied by IAM policy",
2684                principal, source_resource.kind, source_resource.name
2685            )));
2686        }
2687
2688        let mut target_resource =
2689            crate::auth::policies::ResourceRef::new("queue", subscription.target_queue.clone());
2690        if let Some(t) = tenant.as_deref() {
2691            target_resource = target_resource.with_tenant(t.to_string());
2692        }
2693        if !auth_store.check_policy_authz_with_role(
2694            &principal,
2695            "write",
2696            &target_resource,
2697            &ctx,
2698            role,
2699        ) {
2700            return Err(RedDBError::Query(format!(
2701                "permission denied: principal=`{}` action=`write` resource=`{}:{}` denied by IAM policy",
2702                principal, target_resource.kind, target_resource.name
2703            )));
2704        }
2705        return Ok(());
2706    }
2707
2708    let ctx = crate::auth::privileges::AuthzContext {
2709        principal: &username,
2710        effective_role: role,
2711        tenant: tenant.as_deref(),
2712    };
2713    auth_store
2714        .check_grant(
2715            &ctx,
2716            crate::auth::privileges::Action::Select,
2717            &crate::auth::privileges::Resource::table_from_name(source),
2718        )
2719        .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))?;
2720    auth_store
2721        .check_grant(
2722            &ctx,
2723            crate::auth::privileges::Action::Insert,
2724            &crate::auth::privileges::Resource::table_from_name(&subscription.target_queue),
2725        )
2726        .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))?;
2727    Ok(())
2728}
2729
2730fn audit_subscription_redact_gap(
2731    runtime: &RedDBRuntime,
2732    source: &str,
2733    subscription: &crate::catalog::SubscriptionDescriptor,
2734) {
2735    let auth_store = match runtime.inner.auth_store.read().clone() {
2736        Some(store) if store.iam_authorization_enabled() => store,
2737        _ => return,
2738    };
2739    let (username, role) = match crate::runtime::impl_core::current_auth_identity() {
2740        Some(identity) => identity,
2741        None => return,
2742    };
2743    let tenant = crate::runtime::impl_core::current_tenant();
2744    let principal = crate::auth::UserId::from_parts(tenant.as_deref(), &username);
2745    let missing = subscription_redact_gap_columns(&auth_store, &principal, source, subscription);
2746    if missing.is_empty() {
2747        return;
2748    }
2749
2750    let columns = missing.into_iter().collect::<Vec<_>>().join(", ");
2751    tracing::warn!(
2752        target: "reddb::operator",
2753        "subscription_redact_gap: source={} target_queue={} columns=[{}]",
2754        source,
2755        subscription.target_queue,
2756        columns
2757    );
2758    let mut event = AuditEvent::builder("subscription_redact_gap")
2759        .principal(username)
2760        .source(AuditAuthSource::System)
2761        .resource(format!(
2762            "subscription:{}->{}",
2763            source, subscription.target_queue
2764        ))
2765        .outcome(Outcome::Success)
2766        .field(AuditFieldEscaper::field("source", source))
2767        .field(AuditFieldEscaper::field(
2768            "target_queue",
2769            subscription.target_queue.clone(),
2770        ))
2771        .field(AuditFieldEscaper::field(
2772            "subscription",
2773            subscription.name.clone(),
2774        ))
2775        .field(AuditFieldEscaper::field("columns", columns))
2776        .field(AuditFieldEscaper::field("role", role.as_str()));
2777    if let Some(t) = tenant {
2778        event = event.tenant(t);
2779    }
2780    runtime.inner.audit_log.record_event(event.build());
2781}
2782
2783fn subscription_redact_gap_columns(
2784    auth_store: &crate::auth::store::AuthStore,
2785    principal: &crate::auth::UserId,
2786    source: &str,
2787    subscription: &crate::catalog::SubscriptionDescriptor,
2788) -> BTreeSet<String> {
2789    let redacted: HashSet<String> = subscription
2790        .redact_fields
2791        .iter()
2792        .map(|field| field.to_ascii_lowercase())
2793        .collect();
2794    auth_store
2795        .effective_policies(principal)
2796        .iter()
2797        .flat_map(|policy| policy.statements.iter())
2798        .filter(|statement| statement.effect == crate::auth::policies::Effect::Deny)
2799        .filter(|statement| statement.actions.iter().any(action_pattern_matches_select))
2800        .flat_map(|statement| statement.resources.iter())
2801        .filter_map(|resource| denied_column_for_source(resource, source))
2802        .filter(|column| !redact_covers_column(&redacted, source, column))
2803        .collect()
2804}
2805
2806fn action_pattern_matches_select(pattern: &crate::auth::policies::ActionPattern) -> bool {
2807    match pattern {
2808        crate::auth::policies::ActionPattern::Wildcard => true,
2809        crate::auth::policies::ActionPattern::Exact(action) => action == "select",
2810        crate::auth::policies::ActionPattern::Prefix(prefix) => {
2811            "select".len() > prefix.len() + 1
2812                && "select".starts_with(prefix)
2813                && "select".as_bytes()[prefix.len()] == b':'
2814        }
2815    }
2816}
2817
2818fn denied_column_for_source(
2819    resource: &crate::auth::policies::ResourcePattern,
2820    source: &str,
2821) -> Option<String> {
2822    let crate::auth::policies::ResourcePattern::Exact { kind, name } = resource else {
2823        return None;
2824    };
2825    if kind != "column" {
2826        return None;
2827    }
2828    let column = crate::auth::ColumnRef::parse_resource_name(name).ok()?;
2829    (column.table_resource_name() == source).then_some(column.column)
2830}
2831
2832fn redact_covers_column(redacted: &HashSet<String>, source: &str, column: &str) -> bool {
2833    let column = column.to_ascii_lowercase();
2834    let qualified = format!("{}.{}", source.to_ascii_lowercase(), column);
2835    redacted.contains("*") || redacted.contains(&column) || redacted.contains(&qualified)
2836}
2837
2838fn subscription_would_create_cycle(
2839    db: &crate::storage::unified::devx::RedDB,
2840    source: &str,
2841    target: &str,
2842) -> bool {
2843    let mut graph: HashMap<String, Vec<String>> = HashMap::new();
2844    for contract in db.collection_contracts() {
2845        for subscription in contract
2846            .subscriptions
2847            .into_iter()
2848            .filter(|subscription| subscription.enabled)
2849        {
2850            graph
2851                .entry(subscription.source)
2852                .or_default()
2853                .push(subscription.target_queue);
2854        }
2855    }
2856    graph
2857        .entry(source.to_string())
2858        .or_default()
2859        .push(target.to_string());
2860
2861    let mut stack = vec![target.to_string()];
2862    let mut seen = HashSet::new();
2863    while let Some(node) = stack.pop() {
2864        if node == source {
2865            return true;
2866        }
2867        if !seen.insert(node.clone()) {
2868            continue;
2869        }
2870        if let Some(next) = graph.get(&node) {
2871            stack.extend(next.iter().cloned());
2872        }
2873    }
2874    false
2875}
2876
2877pub(crate) fn ensure_event_target_queue_pub(
2878    runtime: &RedDBRuntime,
2879    queue: &str,
2880) -> RedDBResult<()> {
2881    ensure_event_target_queue(runtime, queue)
2882}
2883
2884fn ensure_event_target_queue(runtime: &RedDBRuntime, queue: &str) -> RedDBResult<()> {
2885    let store = runtime.inner.db.store();
2886    if store.get_collection(queue).is_some() {
2887        return Ok(());
2888    }
2889    store
2890        .create_collection(queue)
2891        .map_err(|err| RedDBError::Internal(err.to_string()))?;
2892    crate::runtime::queue_storage_index::prepare_queue(runtime, queue)?;
2893    runtime
2894        .inner
2895        .db
2896        .save_collection_contract(event_queue_collection_contract(queue))
2897        .map_err(|err| RedDBError::Internal(err.to_string()))?;
2898    store.set_config_tree(
2899        &format!("queue.{queue}.mode"),
2900        &crate::serde_json::Value::String("fanout".to_string()),
2901    );
2902    Ok(())
2903}
2904
2905fn event_queue_collection_contract(queue: &str) -> crate::physical::CollectionContract {
2906    let now = current_unix_ms();
2907    crate::physical::CollectionContract {
2908        graph_contract: None,
2909        name: queue.to_string(),
2910        description: None,
2911        description_generated: false,
2912        declared_model: crate::catalog::CollectionModel::Queue,
2913        schema_mode: crate::catalog::SchemaMode::Dynamic,
2914        origin: crate::physical::ContractOrigin::Implicit,
2915        version: 1,
2916        created_at_unix_ms: now,
2917        updated_at_unix_ms: now,
2918        default_ttl_ms: None,
2919        vector_dimension: None,
2920        vector_metric: None,
2921        context_index_fields: Vec::new(),
2922        declared_columns: Vec::new(),
2923        table_def: None,
2924        timestamps_enabled: false,
2925        context_index_enabled: false,
2926        metrics_raw_retention_ms: None,
2927        metrics_rollup_policies: Vec::new(),
2928        metrics_tenant_identity: None,
2929        metrics_namespace: None,
2930        append_only: true,
2931        subscriptions: Vec::new(),
2932        analytics_config: Vec::new(),
2933        session_key: None,
2934        session_gap_ms: None,
2935        retention_duration_ms: None,
2936        analytical_storage: None,
2937
2938        ai_policy: None,
2939    }
2940}
2941
2942fn column_def_from_ddl(column: &CreateColumnDef) -> RedDBResult<reddb_types::ColumnDef> {
2943    reddb_engine::catalog::ddl::column_def_from_ddl(column).map_err(RedDBError::Query)
2944}
2945
2946fn current_unix_ms() -> u128 {
2947    std::time::SystemTime::now()
2948        .duration_since(std::time::UNIX_EPOCH)
2949        .unwrap_or_default()
2950        .as_millis()
2951}
2952
2953#[cfg(test)]
2954mod tests {
2955    use crate::auth::policies::{ActionPattern, Effect, Policy, ResourcePattern, Statement};
2956    use crate::auth::store::{AuthStore, PrincipalRef};
2957    use crate::auth::UserId;
2958    use crate::auth::{AuthConfig, Role};
2959    use crate::runtime::impl_core::{clear_current_auth_identity, set_current_auth_identity};
2960    use crate::{RedDBOptions, RedDBRuntime};
2961    use reddb_types::Value;
2962    use std::sync::Arc;
2963
2964    /// The duplicate check read the rows in memory. Checkpointed rows are on
2965    /// disk, and a table that held duplicates there got its unique index.
2966    #[test]
2967    fn a_unique_index_is_refused_over_duplicates_that_are_only_on_disk() {
2968        let directory = tempfile::tempdir().expect("fixture");
2969        let runtime = RedDBRuntime::with_options(
2970            RedDBOptions::persistent(directory.path().join("unique.rdb"))
2971                .with_memory_budget(32 * 1024 * 1024)
2972                .with_bounded_disk_residency(true),
2973        )
2974        .expect("runtime");
2975        for table in ["duplicated", "clean"] {
2976            runtime
2977                .execute_query(&format!("CREATE TABLE {table} (id TEXT, holder TEXT)"))
2978                .expect("table");
2979        }
2980        runtime
2981            .execute_query(
2982                "INSERT INTO duplicated (id, holder) VALUES ('a', 'one'), ('a', 'two'), ('b', 'three')",
2983            )
2984            .expect("seed duplicates");
2985        runtime
2986            .execute_query("INSERT INTO clean (id, holder) VALUES ('a', 'one'), ('b', 'two')")
2987            .expect("seed");
2988        let store = runtime.db().store();
2989        store.persist().expect("checkpoint");
2990        for table in ["duplicated", "clean"] {
2991            let manager = store.get_collection(table).expect("collection");
2992            assert!(manager.has_backing(), "{table} must be read from disk");
2993            assert!(
2994                manager.query_all(|_| true).is_empty(),
2995                "{table} must have no row in memory"
2996            );
2997        }
2998
2999        let error = runtime
3000            .execute_query("CREATE UNIQUE INDEX idx_duplicated_id ON duplicated (id)")
3001            .expect_err("the duplicates are on disk");
3002        assert!(
3003            error.to_string().contains("share the same (id) key"),
3004            "{error}"
3005        );
3006
3007        runtime
3008            .execute_query("CREATE UNIQUE INDEX idx_clean_id ON clean (id)")
3009            .expect("no duplicates");
3010        let error = runtime
3011            .execute_query("INSERT INTO clean (id, holder) VALUES ('a', 'again')")
3012            .expect_err("a duplicate of a row on disk");
3013        assert!(error.to_string().contains("idx_clean_id"), "{error}");
3014    }
3015
3016    fn make_allow_policy(id: &str, action: &str, collection: &str) -> Policy {
3017        Policy {
3018            id: id.to_string(),
3019            version: 1,
3020            tenant: None,
3021            created_at: 0,
3022            updated_at: 0,
3023            statements: vec![Statement {
3024                sid: None,
3025                effect: Effect::Allow,
3026                actions: vec![ActionPattern::Exact(action.to_string())],
3027                resources: vec![ResourcePattern::Exact {
3028                    kind: "collection".to_string(),
3029                    name: collection.to_string(),
3030                }],
3031                condition: None,
3032            }],
3033        }
3034    }
3035
3036    fn wire_auth_store(rt: &RedDBRuntime) -> Arc<AuthStore> {
3037        let store = Arc::new(AuthStore::new(AuthConfig::default()));
3038        *rt.inner.auth_store.write() = Some(store.clone());
3039        store
3040    }
3041
3042    #[test]
3043    fn drop_denied_without_iam_policy() {
3044        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3045        rt.execute_query("CREATE TABLE foo (id INT)").unwrap();
3046        let store = wire_auth_store(&rt);
3047        // Put a select-only policy so IAM mode activates, but give alice no drop policy.
3048        let select_only = Policy {
3049            id: "select-only".to_string(),
3050            version: 1,
3051            tenant: None,
3052            created_at: 0,
3053            updated_at: 0,
3054            statements: vec![Statement {
3055                sid: None,
3056                effect: Effect::Allow,
3057                actions: vec![ActionPattern::Exact("select".to_string())],
3058                resources: vec![ResourcePattern::Wildcard],
3059                condition: None,
3060            }],
3061        };
3062        store.put_policy_internal(select_only).unwrap();
3063        let alice = UserId::from_parts(None, "alice");
3064        store
3065            .attach_policy(PrincipalRef::User(alice), "select-only")
3066            .unwrap();
3067        set_current_auth_identity("alice".to_string(), Role::Write);
3068        let err = rt.execute_query("DROP TABLE foo").unwrap_err();
3069        clear_current_auth_identity();
3070        assert!(
3071            format!("{err}").contains("denied by IAM policy"),
3072            "got: {err}"
3073        );
3074    }
3075
3076    #[test]
3077    fn drop_allowed_with_explicit_iam_policy() {
3078        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3079        rt.execute_query("CREATE TABLE bar (id INT)").unwrap();
3080        let store = wire_auth_store(&rt);
3081        let policy = make_allow_policy("allow-drop-bar", "drop", "bar");
3082        store.put_policy_internal(policy).unwrap();
3083        let bob = UserId::from_parts(None, "bob");
3084        store
3085            .attach_policy(PrincipalRef::User(bob), "allow-drop-bar")
3086            .unwrap();
3087        set_current_auth_identity("bob".to_string(), Role::Write);
3088        rt.execute_query("DROP TABLE bar").unwrap();
3089        clear_current_auth_identity();
3090    }
3091
3092    #[test]
3093    fn drop_allowed_with_wildcard_iam_policy() {
3094        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3095        rt.execute_query("CREATE TABLE baz (id INT)").unwrap();
3096        let store = wire_auth_store(&rt);
3097        let policy = Policy {
3098            id: "allow-drop-all".to_string(),
3099            version: 1,
3100            tenant: None,
3101            created_at: 0,
3102            updated_at: 0,
3103            statements: vec![Statement {
3104                sid: None,
3105                effect: Effect::Allow,
3106                actions: vec![ActionPattern::Exact("drop".to_string())],
3107                resources: vec![ResourcePattern::Wildcard],
3108                condition: None,
3109            }],
3110        };
3111        store.put_policy_internal(policy).unwrap();
3112        let carl = UserId::from_parts(None, "carl");
3113        store
3114            .attach_policy(PrincipalRef::User(carl), "allow-drop-all")
3115            .unwrap();
3116        set_current_auth_identity("carl".to_string(), Role::Write);
3117        rt.execute_query("DROP TABLE baz").unwrap();
3118        clear_current_auth_identity();
3119    }
3120
3121    #[test]
3122    fn truncate_denied_without_iam_policy() {
3123        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3124        rt.execute_query("CREATE TABLE qux (id INT)").unwrap();
3125        let store = wire_auth_store(&rt);
3126        // Acceptance #2 (#712 / S5A): in `policy_only` mode a
3127        // principal with no matching policy is denied even if their
3128        // role would have permitted the action. The pre-#712 default
3129        // of "no policy → deny" only holds under `policy_only`, so
3130        // pin the mode explicitly here so the assertion holds
3131        // regardless of the construction-time default.
3132        store
3133            .set_enforcement_mode(crate::auth::enforcement_mode::PolicyEnforcementMode::PolicyOnly);
3134        // A policy exists (IAM active) but gives no truncate right.
3135        let select_only = Policy {
3136            id: "select-only-2".to_string(),
3137            version: 1,
3138            tenant: None,
3139            created_at: 0,
3140            updated_at: 0,
3141            statements: vec![Statement {
3142                sid: None,
3143                effect: Effect::Allow,
3144                actions: vec![ActionPattern::Exact("select".to_string())],
3145                resources: vec![ResourcePattern::Wildcard],
3146                condition: None,
3147            }],
3148        };
3149        store.put_policy_internal(select_only).unwrap();
3150        let dana = UserId::from_parts(None, "dana");
3151        store
3152            .attach_policy(PrincipalRef::User(dana), "select-only-2")
3153            .unwrap();
3154        set_current_auth_identity("dana".to_string(), Role::Write);
3155        let err = rt.execute_query("TRUNCATE TABLE qux").unwrap_err();
3156        clear_current_auth_identity();
3157        assert!(
3158            format!("{err}").contains("denied by IAM policy"),
3159            "got: {err}"
3160        );
3161    }
3162
3163    #[test]
3164    fn truncate_table_clears_rows_and_preserves_schema_and_indexes() {
3165        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3166        rt.execute_query("CREATE TABLE users (id INT, name TEXT)")
3167            .unwrap();
3168        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'ana'), (2, 'bob')")
3169            .unwrap();
3170        rt.execute_query("CREATE INDEX idx_users_id ON users (id) USING HASH")
3171            .unwrap();
3172
3173        let truncated = rt.execute_query("TRUNCATE TABLE users").unwrap();
3174        assert_eq!(truncated.statement_type, "truncate");
3175        assert_eq!(truncated.affected_rows, 0);
3176
3177        let empty = rt.execute_query("SELECT id FROM users").unwrap();
3178        assert!(empty.result.records.is_empty());
3179
3180        rt.execute_query("INSERT INTO users (id, name) VALUES (3, 'cy')")
3181            .unwrap();
3182        let selected = rt
3183            .execute_query("SELECT name FROM users WHERE id = 3")
3184            .unwrap();
3185        let name = selected.result.records[0].get("name").unwrap();
3186        assert_eq!(name, &Value::text("cy"));
3187        assert!(rt.db().collection_contract("users").is_some());
3188        assert!(rt
3189            .inner
3190            .index_store
3191            .list_indices("users")
3192            .iter()
3193            .any(|index| index.name == "idx_users_id"));
3194    }
3195
3196    #[test]
3197    fn truncate_collection_is_polymorphic_and_typed_mismatch_fails() {
3198        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3199        rt.execute_query("CREATE QUEUE tasks").unwrap();
3200        rt.execute_query("QUEUE PUSH tasks {'job':'a'}").unwrap();
3201
3202        let err = rt.execute_query("TRUNCATE TABLE tasks").unwrap_err();
3203        assert!(format!("{err}").contains("model mismatch: expected table, got queue"));
3204
3205        rt.execute_query("TRUNCATE COLLECTION tasks").unwrap();
3206        let len = rt.execute_query("QUEUE LEN tasks").unwrap();
3207        assert_eq!(
3208            len.result.records[0].get("len"),
3209            Some(&Value::UnsignedInteger(0))
3210        );
3211    }
3212
3213    #[test]
3214    fn truncate_system_schema_is_read_only() {
3215        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3216        let err = rt
3217            .execute_query("TRUNCATE COLLECTION red.collections")
3218            .unwrap_err();
3219        assert!(format!("{err}").contains("system schema is read-only"));
3220    }
3221
3222    // ── #302 / #310: TRUNCATE / DROP single-event semantics ────────────────
3223
3224    fn queue_payloads(rt: &RedDBRuntime, queue: &str) -> Vec<crate::json::Value> {
3225        let result = rt
3226            .execute_query(&format!("QUEUE PEEK {queue} 100"))
3227            .expect("peek queue");
3228        result
3229            .result
3230            .records
3231            .iter()
3232            .map(
3233                |record| match record.get("payload").expect("payload column") {
3234                    Value::Json(bytes) => crate::json::from_slice(bytes).expect("json payload"),
3235                    other => panic!("expected JSON queue payload, got {other:?}"),
3236                },
3237            )
3238            .collect()
3239    }
3240
3241    /// `TRUNCATE users` on an event-enabled collection emits exactly 1
3242    /// `truncate` event, not one delete event per row.
3243    #[test]
3244    fn truncate_event_enabled_table_emits_single_truncate_event() {
3245        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3246        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3247            .unwrap();
3248        rt.execute_query(
3249            "INSERT INTO users (id, name) VALUES (1, 'alice'), (2, 'bob'), (3, 'carol')",
3250        )
3251        .unwrap();
3252
3253        // Drain the 3 insert events so we start clean.
3254        rt.execute_query("QUEUE POP users_events COUNT 10").unwrap();
3255
3256        rt.execute_query("TRUNCATE TABLE users").unwrap();
3257
3258        let events = queue_payloads(&rt, "users_events");
3259        // Must be exactly 1 truncate event, not 3 delete events.
3260        assert_eq!(
3261            events.len(),
3262            1,
3263            "expected 1 truncate event, got {}",
3264            events.len()
3265        );
3266        let ev = events[0].as_object().expect("event is object");
3267        assert_eq!(
3268            ev.get("op").and_then(crate::json::Value::as_str),
3269            Some("truncate")
3270        );
3271        assert_eq!(
3272            ev.get("collection").and_then(crate::json::Value::as_str),
3273            Some("users")
3274        );
3275        assert_eq!(
3276            ev.get("entities_count")
3277                .and_then(crate::json::Value::as_u64),
3278            Some(3)
3279        );
3280        assert!(ev.get("ts").and_then(crate::json::Value::as_u64).is_some());
3281        assert!(ev.get("lsn").and_then(crate::json::Value::as_u64).is_some());
3282        assert!(ev
3283            .get("event_id")
3284            .and_then(crate::json::Value::as_str)
3285            .is_some_and(|s| !s.is_empty()));
3286    }
3287
3288    /// `TRUNCATE users` on a collection without event subscription emits no events.
3289    #[test]
3290    fn truncate_no_events_collection_emits_nothing() {
3291        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3292        rt.execute_query("CREATE TABLE plain (id INT, val TEXT)")
3293            .unwrap();
3294        rt.execute_query("INSERT INTO plain (id, val) VALUES (1, 'a'), (2, 'b')")
3295            .unwrap();
3296        // No EVENTS subscription — truncate must work without touching any queue.
3297        rt.execute_query("TRUNCATE TABLE plain").unwrap();
3298        // No crash, no queue to check. Just verify truncation happened.
3299        let rows = rt.execute_query("SELECT id FROM plain").unwrap();
3300        assert!(rows.result.records.is_empty());
3301    }
3302
3303    /// `DROP TABLE users` on an event-enabled collection emits exactly 1
3304    /// `collection_dropped` event. The subscription is removed from the
3305    /// source contract but the target queue is preserved for consumer drain.
3306    #[test]
3307    fn drop_event_enabled_table_emits_single_collection_dropped_event() {
3308        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3309        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3310            .unwrap();
3311        rt.execute_query("INSERT INTO users (id, name) VALUES (1, 'alice'), (2, 'bob')")
3312            .unwrap();
3313
3314        // Drain insert events so we start clean.
3315        rt.execute_query("QUEUE POP users_events COUNT 10").unwrap();
3316
3317        rt.execute_query("DROP TABLE users").unwrap();
3318
3319        // Queue must still exist with 1 collection_dropped event.
3320        let events = queue_payloads(&rt, "users_events");
3321        assert_eq!(
3322            events.len(),
3323            1,
3324            "expected 1 collection_dropped event, got {}",
3325            events.len()
3326        );
3327        let ev = events[0].as_object().expect("event is object");
3328        assert_eq!(
3329            ev.get("op").and_then(crate::json::Value::as_str),
3330            Some("collection_dropped")
3331        );
3332        assert_eq!(
3333            ev.get("collection").and_then(crate::json::Value::as_str),
3334            Some("users")
3335        );
3336        assert_eq!(
3337            ev.get("final_entities_count")
3338                .and_then(crate::json::Value::as_u64),
3339            Some(2)
3340        );
3341        assert!(ev.get("ts").and_then(crate::json::Value::as_u64).is_some());
3342        assert!(ev.get("lsn").and_then(crate::json::Value::as_u64).is_some());
3343        assert!(ev
3344            .get("event_id")
3345            .and_then(crate::json::Value::as_str)
3346            .is_some_and(|s| !s.is_empty()));
3347
3348        // Source collection is gone.
3349        let err = rt.execute_query("SELECT id FROM users").unwrap_err();
3350        assert!(
3351            format!("{err}").contains("users"),
3352            "expected not-found error"
3353        );
3354    }
3355
3356    /// `DROP TABLE users` on a collection without event subscription works
3357    /// normally with no event emitted.
3358    #[test]
3359    fn drop_no_events_collection_emits_nothing() {
3360        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3361        rt.execute_query("CREATE TABLE plain (id INT, val TEXT)")
3362            .unwrap();
3363        rt.execute_query("INSERT INTO plain (id, val) VALUES (1, 'a')")
3364            .unwrap();
3365        rt.execute_query("DROP TABLE plain").unwrap();
3366        // No crash and collection is gone.
3367        let err = rt.execute_query("SELECT id FROM plain").unwrap_err();
3368        assert!(format!("{err}").contains("plain"));
3369    }
3370
3371    // ── #297: ops_filter + WHERE filter ────────────────────────────────────
3372
3373    /// `WITH EVENTS (INSERT)` — UPDATE and DELETE events must NOT be emitted.
3374    #[test]
3375    fn ops_filter_insert_only_ignores_update_and_delete() {
3376        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3377        rt.execute_query(
3378            "CREATE TABLE items (id INT, val TEXT) WITH EVENTS (INSERT) TO items_events",
3379        )
3380        .unwrap();
3381        rt.execute_query("INSERT INTO items (id, val) VALUES (1, 'a')")
3382            .unwrap();
3383        rt.execute_query("UPDATE items SET val = 'b' WHERE id = 1")
3384            .unwrap();
3385        rt.execute_query("DELETE FROM items WHERE id = 1").unwrap();
3386
3387        let events = queue_payloads(&rt, "items_events");
3388        // Only the INSERT should have fired.
3389        assert_eq!(
3390            events.len(),
3391            1,
3392            "expected 1 insert event, got {}",
3393            events.len()
3394        );
3395        assert_eq!(
3396            events[0]
3397                .as_object()
3398                .unwrap()
3399                .get("op")
3400                .and_then(crate::json::Value::as_str),
3401            Some("insert")
3402        );
3403    }
3404
3405    /// `WITH EVENTS WHERE status = 'active'` — only rows matching the predicate generate events.
3406    #[test]
3407    fn where_filter_skips_rows_that_do_not_match() {
3408        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3409        rt.execute_query(
3410            "CREATE TABLE users (id INT, status TEXT) WITH EVENTS WHERE status = 'active' TO users_events",
3411        )
3412        .unwrap();
3413
3414        // This row should generate an event.
3415        rt.execute_query("INSERT INTO users (id, status) VALUES (1, 'active')")
3416            .unwrap();
3417        // This row should NOT generate an event.
3418        rt.execute_query("INSERT INTO users (id, status) VALUES (2, 'inactive')")
3419            .unwrap();
3420
3421        let events = queue_payloads(&rt, "users_events");
3422        assert_eq!(
3423            events.len(),
3424            1,
3425            "expected 1 event (only active), got {}",
3426            events.len()
3427        );
3428        let ev = events[0].as_object().unwrap();
3429        assert_eq!(
3430            ev.get("op").and_then(crate::json::Value::as_str),
3431            Some("insert")
3432        );
3433        let after = ev.get("after").unwrap().as_object().unwrap();
3434        assert_eq!(
3435            after.get("status").and_then(crate::json::Value::as_str),
3436            Some("active")
3437        );
3438    }
3439
3440    /// `WITH EVENTS (INSERT, UPDATE) WHERE status = 'active'` — combination functional.
3441    #[test]
3442    fn ops_filter_and_where_filter_combined() {
3443        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3444        rt.execute_query(
3445            "CREATE TABLE items (id INT, status TEXT) WITH EVENTS (INSERT, UPDATE) WHERE status = 'active' TO items_events",
3446        )
3447        .unwrap();
3448
3449        // INSERT active → event
3450        rt.execute_query("INSERT INTO items (id, status) VALUES (1, 'active')")
3451            .unwrap();
3452        // INSERT inactive → no event
3453        rt.execute_query("INSERT INTO items (id, status) VALUES (2, 'inactive')")
3454            .unwrap();
3455        // UPDATE row 1 to inactive → after = inactive, no event
3456        rt.execute_query("UPDATE items SET status = 'inactive' WHERE id = 1")
3457            .unwrap();
3458        // DELETE → ops_filter excludes it
3459        rt.execute_query("DELETE FROM items WHERE id = 2").unwrap();
3460
3461        let events = queue_payloads(&rt, "items_events");
3462        // Only the first INSERT (active) fires; UPDATE result is inactive so skipped; DELETE excluded by ops_filter.
3463        assert_eq!(
3464            events.len(),
3465            1,
3466            "expected 1 event, got {}: {events:?}",
3467            events.len()
3468        );
3469        assert_eq!(
3470            events[0]
3471                .as_object()
3472                .unwrap()
3473                .get("op")
3474                .and_then(crate::json::Value::as_str),
3475            Some("insert")
3476        );
3477    }
3478
3479    /// WHERE filter on DELETE events — the before-state (pre-image) is evaluated.
3480    #[test]
3481    fn where_filter_on_delete_checks_before_state() {
3482        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3483        rt.execute_query(
3484            "CREATE TABLE users (id INT, status TEXT) WITH EVENTS (DELETE) WHERE status = 'active' TO users_events",
3485        )
3486        .unwrap();
3487
3488        rt.execute_query("INSERT INTO users (id, status) VALUES (1, 'active'), (2, 'inactive')")
3489            .unwrap();
3490
3491        // Delete active row → event (before-state was active)
3492        rt.execute_query("DELETE FROM users WHERE id = 1").unwrap();
3493        // Delete inactive row → no event (before-state was inactive)
3494        rt.execute_query("DELETE FROM users WHERE id = 2").unwrap();
3495
3496        let events = queue_payloads(&rt, "users_events");
3497        assert_eq!(
3498            events.len(),
3499            1,
3500            "expected 1 delete event, got {}",
3501            events.len()
3502        );
3503        let ev = events[0].as_object().unwrap();
3504        assert_eq!(
3505            ev.get("op").and_then(crate::json::Value::as_str),
3506            Some("delete")
3507        );
3508    }
3509
3510    // ── #301: schema evolution OperatorEvent on ALTER ───────────────────────
3511
3512    /// ADD COLUMN on event-enabled table must succeed (OperatorEvent is best-effort).
3513    #[test]
3514    fn alter_add_column_on_event_enabled_table_succeeds() {
3515        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3516        rt.execute_query("CREATE TABLE users (id INT, name TEXT) WITH EVENTS TO users_events")
3517            .unwrap();
3518        // Must not error — OperatorEvent emission is best-effort (no global sink in tests).
3519        rt.execute_query("ALTER TABLE users ADD COLUMN phone TEXT")
3520            .unwrap();
3521        // The column is now in the contract.
3522        let contract = rt.db().collection_contract("users").unwrap();
3523        assert!(
3524            contract.declared_columns.iter().any(|c| c.name == "phone"),
3525            "phone column should be in contract"
3526        );
3527        // Subscription still enabled after the alter.
3528        assert!(
3529            contract.subscriptions.iter().any(|s| s.enabled),
3530            "subscription should remain enabled"
3531        );
3532    }
3533
3534    /// Rows inserted together after ADD COLUMN keep the new column's values,
3535    /// in memory and after a checkpoint and a reopen; a row inserted before
3536    /// it reads NULL there and joins the NULL group of a GROUP BY.
3537    #[test]
3538    fn rows_inserted_together_after_add_column_keep_its_values() {
3539        let directory = tempfile::tempdir().expect("directory");
3540        let path = directory.path().join("alter.rdb");
3541        let values = |rt: &RedDBRuntime| {
3542            let result = rt
3543                .execute_query("SELECT id, e FROM t ORDER BY id")
3544                .expect("select");
3545            result
3546                .result
3547                .records
3548                .iter()
3549                .map(|record| {
3550                    let text = |name: &str| match record.get(name) {
3551                        Some(Value::Text(text)) => Some(text.to_string()),
3552                        Some(Value::Null) | None => None,
3553                        other => panic!("{name}: {other:?}"),
3554                    };
3555                    (text("id").expect("id"), text("e"))
3556                })
3557                .collect::<Vec<_>>()
3558        };
3559        let groups = |rt: &RedDBRuntime, sql: &str| {
3560            let result = rt.execute_query(sql).expect(sql);
3561            let mut groups = result
3562                .result
3563                .records
3564                .iter()
3565                .map(|record| {
3566                    let e = match record.get("e") {
3567                        Some(Value::Text(text)) => Some(text.to_string()),
3568                        Some(Value::Null) | None => None,
3569                        other => panic!("e: {other:?}"),
3570                    };
3571                    let n = match record.get("n").or_else(|| record.get("COUNT(*)")) {
3572                        Some(Value::Integer(n)) => *n as u64,
3573                        Some(Value::UnsignedInteger(n)) => *n,
3574                        Some(Value::BigInt(n)) => *n as u64,
3575                        other => panic!("n: {other:?}"),
3576                    };
3577                    (e, n)
3578                })
3579                .collect::<Vec<_>>();
3580            groups.sort();
3581            groups
3582        };
3583        let expected = vec![
3584            ("1".to_string(), None),
3585            ("2".to_string(), Some("v2".to_string())),
3586            ("3".to_string(), None),
3587            ("4".to_string(), Some("v4".to_string())),
3588        ];
3589        let expected_groups = vec![
3590            (None, 2),
3591            (Some("v2".to_string()), 1),
3592            (Some("v4".to_string()), 1),
3593        ];
3594        {
3595            let rt = RedDBRuntime::with_options(RedDBOptions::persistent(&path)).unwrap();
3596            for sql in [
3597                "CREATE TABLE t (id TEXT PRIMARY KEY, g TEXT)",
3598                "INSERT INTO t (id, g) VALUES ('0', 'x'), ('1', 'x')",
3599                "DELETE FROM t WHERE id = '0'",
3600                "ALTER TABLE t ADD COLUMN e TEXT",
3601                "INSERT INTO t (id, g, e) VALUES ('2', 'x', 'v2'), ('3', 'x', NULL), \
3602                 ('4', 'x', 'v4')",
3603            ] {
3604                rt.execute_query(sql).expect(sql);
3605            }
3606            assert_eq!(values(&rt), expected, "in memory");
3607            assert_eq!(
3608                groups(&rt, "SELECT e, COUNT(*) AS n FROM t GROUP BY e"),
3609                expected_groups
3610            );
3611            assert_eq!(
3612                groups(&rt, "SELECT g, e, COUNT(*) AS n FROM t GROUP BY g, e"),
3613                expected_groups
3614            );
3615            rt.checkpoint().expect("checkpoint");
3616        }
3617        let rt = RedDBRuntime::with_options(RedDBOptions::persistent(&path)).unwrap();
3618        assert_eq!(values(&rt), expected, "after a reopen");
3619        assert_eq!(
3620            groups(&rt, "SELECT g, e, COUNT(*) AS n FROM t GROUP BY g, e"),
3621            expected_groups
3622        );
3623    }
3624
3625    /// DROP COLUMN on event-enabled table must succeed; non-column ALTERs
3626    /// (like ENABLE ROW LEVEL SECURITY) must also succeed without emitting.
3627    #[test]
3628    fn alter_drop_column_and_rls_on_event_enabled_table_succeeds() {
3629        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3630        rt.execute_query(
3631            "CREATE TABLE items (id INT, secret TEXT, status TEXT) WITH EVENTS TO items_events",
3632        )
3633        .unwrap();
3634        // DROP COLUMN — schema change event path exercises, must not error.
3635        rt.execute_query("ALTER TABLE items DROP COLUMN secret")
3636            .unwrap();
3637        let contract = rt.db().collection_contract("items").unwrap();
3638        assert!(
3639            !contract.declared_columns.iter().any(|c| c.name == "secret"),
3640            "secret column should be removed"
3641        );
3642        // ENABLE RLS — non-column op, no schema-change event (coverage).
3643        rt.execute_query("ALTER TABLE items ENABLE ROW LEVEL SECURITY")
3644            .unwrap();
3645        // Collection and subscription still intact.
3646        assert!(
3647            contract.subscriptions.iter().any(|s| s.enabled),
3648            "subscription should remain enabled"
3649        );
3650    }
3651
3652    /// Slice G (#675) — every newly-created `CollectionModel::Vector`
3653    /// collection is marked `vector.turbo` and gains a materialised
3654    /// `TurboCollectionState`. The marker is what the SEARCH/INSERT
3655    /// hot paths read to branch between TurboQuant and the legacy
3656    /// brute-force fallback.
3657    #[test]
3658    fn create_vector_marks_collection_as_turbo_baseline() {
3659        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3660        rt.execute_query("CREATE VECTOR embeddings DIM 4").unwrap();
3661        let store = rt.db().store();
3662        assert!(
3663            crate::runtime::vector_turbo_kind::is_turbo(&store, "embeddings"),
3664            "new vector collections must be turbo-marked baseline"
3665        );
3666        assert!(
3667            rt.db().turbo_state("embeddings").is_some(),
3668            "turbo_state must materialise after CREATE VECTOR"
3669        );
3670    }
3671
3672    /// Non-vector collections must NOT be turbo-marked. Guards against
3673    /// the always-baseline change accidentally leaking the marker onto
3674    /// CREATE TABLE / CREATE DOCUMENT / etc.
3675    #[test]
3676    fn create_table_does_not_mark_turbo() {
3677        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3678        rt.execute_query("CREATE TABLE plain (id INT)").unwrap();
3679        let store = rt.db().store();
3680        assert!(
3681            !crate::runtime::vector_turbo_kind::is_turbo(&store, "plain"),
3682            "non-vector collections must not gain the turbo marker"
3683        );
3684        assert!(rt.db().turbo_state("plain").is_none());
3685    }
3686
3687    /// `CREATE COLLECTION KIND vector.turbo` continues to mark the
3688    /// collection (idempotent with the new always-baseline path).
3689    #[test]
3690    fn create_collection_kind_vector_turbo_still_marked() {
3691        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3692        rt.execute_query("CREATE COLLECTION turbo_v KIND vector.turbo DIM 4")
3693            .unwrap();
3694        let store = rt.db().store();
3695        assert!(crate::runtime::vector_turbo_kind::is_turbo(
3696            &store, "turbo_v"
3697        ));
3698        assert!(rt.db().turbo_state("turbo_v").is_some());
3699    }
3700
3701    /// Issue #1271: a declared AI policy is persisted in the catalog and
3702    /// reads back identical via the collection contract (introspection).
3703    #[test]
3704    fn create_table_persists_and_introspects_ai_policy() {
3705        use crate::catalog::{ModerateDegradedMode, ModerateRejectAction};
3706        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3707        rt.execute_query(
3708            "CREATE TABLE posts (id INT, title TEXT, body TEXT, photo TEXT) WITH ( \
3709               EMBED (fields = ('title', 'body'), provider = 'openai', model = 'text-embedding-3-small'), \
3710               MODERATE (fields = ('body'), provider = 'openai', model = 'omni-moderation-latest', sync = true, degraded = closed, on_reject = flag), \
3711               VISION (image_field = 'photo', outputs = ('caption'), provider = 'openai', model = 'gpt-4o') \
3712             )",
3713        )
3714        .expect("create table with ai policy");
3715
3716        let contracts = rt.db().collection_contracts();
3717        let contract = contracts
3718            .iter()
3719            .find(|c| c.name == "posts")
3720            .expect("contract persisted");
3721        let policy = contract.ai_policy.as_ref().expect("ai policy persisted");
3722
3723        let embed = policy.embed.as_ref().expect("embed");
3724        assert_eq!(embed.fields, vec!["title".to_string(), "body".to_string()]);
3725        assert_eq!(embed.model, "text-embedding-3-small");
3726
3727        let moderate = policy.moderate.as_ref().expect("moderate");
3728        assert!(moderate.sync_gate);
3729        assert_eq!(moderate.degraded_mode, ModerateDegradedMode::Closed);
3730        assert_eq!(moderate.reject_action, ModerateRejectAction::Flag);
3731
3732        let vision = policy.vision.as_ref().expect("vision");
3733        assert_eq!(vision.image_field, "photo");
3734        assert_eq!(vision.model, "gpt-4o");
3735    }
3736
3737    /// Issue #1271 / #1269: a policy wiring a provider to a modality it
3738    /// cannot serve is rejected at DDL time, and the collection is not
3739    /// created. Anthropic has no embeddings product in the matrix.
3740    #[test]
3741    fn create_table_rejects_ai_policy_incapable_provider() {
3742        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
3743        let err = rt
3744            .execute_query(
3745                "CREATE TABLE bad (id INT, body TEXT) WITH ( \
3746                   EMBED (fields = ('body'), provider = 'anthropic', model = 'claude-3-5-sonnet') \
3747                 )",
3748            )
3749            .unwrap_err();
3750        assert!(
3751            err.to_string()
3752                .contains("cannot serve the 'embed' modality"),
3753            "{err}"
3754        );
3755        assert!(
3756            rt.db().store().get_collection("bad").is_none(),
3757            "rejected DDL must not create the collection"
3758        );
3759    }
3760
3761    #[test]
3762    fn descriptions_cover_collection_models_and_survive_reopen() {
3763        let directory = tempfile::tempdir().expect("temporary database");
3764        let path = directory.path().join("descriptions.rdb");
3765        let options = RedDBOptions::persistent(&path);
3766        {
3767            let rt = RedDBRuntime::with_options(options.clone()).expect("runtime");
3768            assert!(!rt.config_bool("ai.collection_descriptions.auto_enrich", false));
3769            rt.execute_query("CREATE TABLE contacts (email EMAIL DESCRIPTION 'Contact address', balance MONEY) WITH (DESCRIPTION = 'Contact records')").expect("table");
3770            rt.execute_query(
3771                "CREATE COLLECTION articles KIND document DESCRIPTION 'Published articles'",
3772            )
3773            .expect("document");
3774            rt.execute_query("ALTER COLLECTION articles SET DESCRIPTION 'Editorial articles'")
3775                .expect("alter document");
3776            rt.execute_query(
3777                "ALTER COLLECTION contacts ALTER COLUMN balance SET DESCRIPTION 'Account balance'",
3778            )
3779            .expect("alter column");
3780            let contract = rt
3781                .db()
3782                .collection_contract("contacts")
3783                .expect("table contract");
3784            assert_eq!(contract.description.as_deref(), Some("Contact records"));
3785            assert_eq!(
3786                contract.declared_columns[0].description.as_deref(),
3787                Some("Contact address")
3788            );
3789            assert_eq!(
3790                contract.declared_columns[1].description.as_deref(),
3791                Some("Account balance")
3792            );
3793            assert!(!contract.declared_columns[1].description_generated);
3794            let show_create = rt
3795                .execute_query("SHOW CREATE TABLE contacts")
3796                .expect("show create");
3797            let Some(Value::Text(ddl)) = show_create.result.records[0].get("ddl") else {
3798                panic!("DDL text")
3799            };
3800            assert!(ddl.contains("DESCRIPTION 'Account balance'"), "{ddl}");
3801            assert!(
3802                ddl.contains("WITH (DESCRIPTION = 'Contact records')"),
3803                "{ddl}"
3804            );
3805            let collections = rt
3806                .execute_query("SELECT description FROM red.collections WHERE name = 'contacts'")
3807                .expect("collections view");
3808            assert_eq!(
3809                collections.result.records[0].get("description"),
3810                Some(&Value::text("Contact records"))
3811            );
3812            let columns = rt.execute_query("SELECT description FROM red.columns WHERE collection = 'contacts' AND name = 'email'").expect("columns view");
3813            assert_eq!(
3814                columns.result.records[0].get("description"),
3815                Some(&Value::text("Contact address"))
3816            );
3817            assert!(rt
3818                .execute_query(
3819                    "ALTER COLLECTION contacts ALTER COLUMN missing SET DESCRIPTION 'Nope'"
3820                )
3821                .is_err());
3822            rt.checkpoint().expect("checkpoint");
3823        }
3824        let reopened = RedDBRuntime::with_options(options).expect("reopen");
3825        assert_eq!(
3826            reopened
3827                .db()
3828                .collection_contract("articles")
3829                .unwrap()
3830                .description
3831                .as_deref(),
3832            Some("Editorial articles")
3833        );
3834        let contract = reopened.db().collection_contract("contacts").unwrap();
3835        assert_eq!(
3836            contract.declared_columns[1].description.as_deref(),
3837            Some("Account balance")
3838        );
3839    }
3840
3841    #[test]
3842    fn generated_descriptions_preserve_manual_edits_and_reject_stale_versions() {
3843        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3844        rt.execute_query("CREATE TABLE readings (email EMAIL DESCRIPTION 'Manual', amount MONEY)")
3845            .expect("table");
3846        let contract = rt.db().collection_contract("readings").expect("contract");
3847        let suggestions = std::collections::HashMap::from([
3848            ("email".to_string(), "Generated email".to_string()),
3849            ("amount".to_string(), "Generated amount".to_string()),
3850        ]);
3851        assert!(rt
3852            .db()
3853            .save_generated_descriptions_if_version(
3854                "readings",
3855                contract.version,
3856                contract.created_at_unix_ms,
3857                Some("Generated collection".to_string()),
3858                &suggestions
3859            )
3860            .expect("save generated"));
3861        let generated = rt.db().collection_contract("readings").unwrap();
3862        assert_eq!(
3863            generated.declared_columns[0].description.as_deref(),
3864            Some("Manual")
3865        );
3866        assert!(!generated.declared_columns[0].description_generated);
3867        assert_eq!(
3868            generated.declared_columns[1].description.as_deref(),
3869            Some("Generated amount")
3870        );
3871        assert!(generated.declared_columns[1].description_generated);
3872        rt.execute_query(
3873            "ALTER COLLECTION readings ALTER COLUMN amount SET DESCRIPTION 'Manual amount'",
3874        )
3875        .expect("manual override");
3876        assert!(!rt
3877            .db()
3878            .save_generated_descriptions_if_version(
3879                "readings",
3880                generated.version,
3881                generated.created_at_unix_ms,
3882                Some("Stale".to_string()),
3883                &suggestions
3884            )
3885            .expect("stale rejected"));
3886        let updated = rt.db().collection_contract("readings").unwrap();
3887        assert_eq!(
3888            updated.declared_columns[1].description.as_deref(),
3889            Some("Manual amount")
3890        );
3891        assert!(!updated.declared_columns[1].description_generated);
3892    }
3893
3894    #[test]
3895    fn alter_collection_description_works_across_models() {
3896        let rt = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
3897        for (create, name) in [
3898            ("CREATE TABLE records (id INT)", "records"),
3899            ("CREATE DOCUMENT documents", "documents"),
3900            ("CREATE GRAPH network", "network"),
3901            ("CREATE VECTOR embeddings DIM 3", "embeddings"),
3902            (
3903                "CREATE TIMESERIES measurements RETENTION 90 d",
3904                "measurements",
3905            ),
3906            ("CREATE QUEUE jobs MAX_SIZE 100", "jobs"),
3907            ("CREATE KV settings", "settings"),
3908        ] {
3909            rt.execute_query(create).expect(create);
3910            rt.execute_query(&format!(
3911                "ALTER COLLECTION {name} SET DESCRIPTION 'User description'"
3912            ))
3913            .expect("alter collection");
3914            let contract = rt.db().collection_contract(name).expect("contract");
3915            assert_eq!(
3916                contract.description.as_deref(),
3917                Some("User description"),
3918                "{name}"
3919            );
3920            assert!(!contract.description_generated, "{name}");
3921        }
3922    }
3923}