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