Skip to main content

reddb_server/runtime/
impl_tenant_registry.rs

1//! Tenant-table registry and rehydration.
2//!
3//! Extracted verbatim from `impl_core.rs` (impl_core slice 9/10, issue #1630).
4//! Houses tenant-table rehydration (`rehydrate_tenant_tables`,
5//! `rehydrate_materialized_view_descriptors`, `rehydrate_declared_column_schemas`),
6//! registration (`register_tenant_table`, `ensure_tenant_index`, `drop_tenant_index`,
7//! `tenant_column`, `unregister_tenant_table`), and planner-stat maintenance
8//! (`refresh_table_planner_stats`, `note_table_write`).
9use super::*;
10
11impl RedDBRuntime {
12    /// Replay `tenant_tables.*.column` keys from red_config at boot so
13    /// `CREATE TABLE ... TENANT BY (col)` declarations persist across
14    /// restarts (Phase 2.5.4). Reads every row of the `red_config`
15    /// collection, picks the keys matching the tenant-marker shape,
16    /// and calls `register_tenant_table` for each.
17    ///
18    /// Safe no-op when `red_config` doesn't exist (first boot on a
19    /// fresh datadir).
20    pub(crate) fn rehydrate_tenant_tables(&self) {
21        let store = self.inner.db.store();
22        let Some(manager) = store.get_collection("red_config") else {
23            return;
24        };
25        // Replay in insertion order (SegmentManager iteration). Multiple
26        // toggles on the same table leave several rows behind — the
27        // last one processed wins because each register/unregister
28        // call overwrites the in-memory state.
29        for entity in manager.query_all(|_| true) {
30            let crate::storage::unified::entity::EntityData::Row(row) = &entity.data else {
31                continue;
32            };
33            let Some(named) = &row.named else { continue };
34            let Some(reddb_types::Value::Text(key)) = named.get("key") else {
35                continue;
36            };
37            // Shape: tenant_tables.{table}.column
38            let Some(rest) = key.strip_prefix("tenant_tables.") else {
39                continue;
40            };
41            let Some((table, suffix)) = rest.rsplit_once('.') else {
42                // Issue #205 — a `tenant_tables.*` row that doesn't
43                // split cleanly is a schema-shape regression: the
44                // metadata writer must always emit the `.column`
45                // suffix, so reaching this branch means an upgrade
46                // with incompatible state or external tampering.
47                crate::telemetry::operator_event::OperatorEvent::SchemaCorruption {
48                    collection: "red_config".to_string(),
49                    detail: format!("malformed tenant_tables key: {key}"),
50                }
51                .emit_global();
52                continue;
53            };
54            if suffix != "column" {
55                crate::telemetry::operator_event::OperatorEvent::SchemaCorruption {
56                    collection: "red_config".to_string(),
57                    detail: format!("unexpected tenant_tables suffix: {key}"),
58                }
59                .emit_global();
60                continue;
61            }
62            match named.get("value") {
63                Some(reddb_types::Value::Text(column)) => {
64                    self.register_tenant_table(table, column);
65                }
66                // Null / missing value = DISABLE TENANCY marker.
67                Some(reddb_types::Value::Null) | None => {
68                    self.unregister_tenant_table(table);
69                }
70                _ => {}
71            }
72        }
73    }
74
75    /// Replay every persisted `MaterializedViewDescriptor` from the
76    /// `red_materialized_view_defs` system collection (issue #593
77    /// slice 9a). For each descriptor, re-parse the original SQL,
78    /// extract the `QueryExpr::CreateView` it produced, and populate
79    /// the in-memory registries (`inner.views` and
80    /// `inner.materialized_views`) directly — no write paths run, so
81    /// rehydrate does not re-persist what it just read.
82    ///
83    /// Malformed rows (missing `name`/`source_sql`, parse errors) are
84    /// skipped with a `SchemaCorruption` operator event so a single
85    /// bad entry does not block startup.
86    pub(crate) fn rehydrate_materialized_view_descriptors(&self) {
87        let store = self.inner.db.store();
88        let descriptors = crate::runtime::continuous_materialized_view::load_all(store.as_ref());
89        for descriptor in descriptors {
90            let parsed = match reddb_rql::parser::parse(&descriptor.source_sql) {
91                Ok(qc) => qc,
92                Err(err) => {
93                    crate::telemetry::operator_event::OperatorEvent::SchemaCorruption {
94                        collection:
95                            crate::runtime::continuous_materialized_view::CATALOG_COLLECTION
96                                .to_string(),
97                        detail: format!(
98                            "failed to re-parse materialized-view source for {}: {err}",
99                            descriptor.name
100                        ),
101                    }
102                    .emit_global();
103                    continue;
104                }
105            };
106            let reddb_rql::ast::QueryExpr::CreateView(create) = parsed.query else {
107                crate::telemetry::operator_event::OperatorEvent::SchemaCorruption {
108                    collection: crate::runtime::continuous_materialized_view::CATALOG_COLLECTION
109                        .to_string(),
110                    detail: format!(
111                        "materialized-view source for {} did not re-parse as CREATE VIEW",
112                        descriptor.name
113                    ),
114                }
115                .emit_global();
116                continue;
117            };
118            // Populate in-memory view registry.
119            let view_name = create.name.clone();
120            self.inner
121                .views
122                .write()
123                .insert(view_name.clone(), Arc::new(create));
124            // Materialized cache slot (data empty until next REFRESH).
125            use crate::storage::cache::result::{MaterializedViewDef, RefreshPolicy};
126            let refresh = match descriptor.refresh_every_ms {
127                Some(ms) => RefreshPolicy::Periodic(std::time::Duration::from_millis(ms)),
128                None => RefreshPolicy::Manual,
129            };
130            let def = MaterializedViewDef {
131                name: view_name.clone(),
132                query: format!("<parsed view {}>", view_name),
133                dependencies: descriptor.source_collections.clone(),
134                refresh,
135                retention_duration_ms: descriptor.retention_duration_ms,
136            };
137            self.inner.materialized_views.write().register(def);
138            if let Err(err) = self.ensure_materialized_view_backing(&view_name) {
139                crate::telemetry::operator_event::OperatorEvent::SchemaCorruption {
140                    collection: crate::runtime::continuous_materialized_view::CATALOG_COLLECTION
141                        .to_string(),
142                    detail: format!(
143                        "failed to rehydrate backing collection for materialized view {view_name}: {err}"
144                    ),
145                }
146                .emit_global();
147            }
148        }
149        // A rehydrated view shape may differ from any plans the cache
150        // bootstrapped before this method ran — flush to be safe.
151        self.invalidate_plan_cache();
152    }
153
154    pub(crate) fn rehydrate_declared_column_schemas(&self) {
155        let store = self.inner.db.store();
156        for contract in self.inner.db.collection_contracts() {
157            let columns: Vec<String> = contract
158                .declared_columns
159                .iter()
160                .map(|column| column.name.clone())
161                .collect();
162            let Some(manager) = store.get_collection(&contract.name) else {
163                continue;
164            };
165            manager.set_column_schema_if_empty(columns);
166            manager.compact_recovered_rows();
167        }
168    }
169
170    /// Register a table as tenant-scoped (Phase 2.5.4). Installs the
171    /// in-memory column mapping, the implicit RLS policy, and enables
172    /// row-level security on the table. Idempotent — re-registering
173    /// the same `(table, column)` replaces the prior auto-policy.
174    pub fn register_tenant_table(&self, table: &str, column: &str) {
175        use reddb_rql::ast::{CompareOp, CreatePolicyQuery, Expr, FieldRef, Filter, Span};
176        self.inner
177            .tenant_tables
178            .write()
179            .insert(table.to_string(), column.to_string());
180
181        // Build the policy: col = CURRENT_TENANT()
182        // Uses CompareExpr so the comparison happens at runtime against
183        // the thread-local tenant value read by the CURRENT_TENANT
184        // scalar. Spans are synthetic — there's no source location for
185        // an auto-generated policy.
186        let lhs = Expr::Column {
187            field: FieldRef::TableColumn {
188                table: table.to_string(),
189                column: column.to_string(),
190            },
191            span: Span::synthetic(),
192        };
193        let rhs = Expr::FunctionCall {
194            name: "CURRENT_TENANT".to_string(),
195            args: Vec::new(),
196            span: Span::synthetic(),
197        };
198        let policy_filter = Filter::CompareExpr {
199            lhs,
200            op: CompareOp::Eq,
201            rhs,
202        };
203
204        let policy = CreatePolicyQuery {
205            name: "__tenant_iso".to_string(),
206            table: table.to_string(),
207            action: None, // None = ALL actions (SELECT/INSERT/UPDATE/DELETE)
208            role: None,   // None = every role
209            using: Box::new(policy_filter),
210            // Auto-tenancy defaults to Table targets. Collections of
211            // other kinds (graph / vector / queue / timeseries) that
212            // opt in via `ALTER ... ENABLE TENANCY` should use the
213            // matching kind — but for now we keep the auto-policy
214            // kind-agnostic so the evaluator can apply it to any
215            // entity living in the collection.
216            target_kind: reddb_rql::ast::PolicyTargetKind::Table,
217        };
218
219        // Replace any prior auto-policy for this table (column rename).
220        self.inner.rls_policies.write().insert(
221            (table.to_string(), "__tenant_iso".to_string()),
222            Arc::new(policy),
223        );
224        self.inner
225            .rls_enabled_tables
226            .write()
227            .insert(table.to_string());
228
229        // Auto-build a hash index on the tenant column. Every read/write
230        // against a tenant-scoped table carries an implicit
231        // `col = CURRENT_TENANT()` predicate from the auto-policy, so an
232        // index on that column is on the hot path of every query. Without
233        // it, every SELECT/UPDATE/DELETE degrades to a full scan.
234        self.ensure_tenant_index(table, column);
235    }
236
237    /// Auto-create the hash index that backs the tenant-iso RLS predicate.
238    /// Skipped when:
239    ///   * the column is dotted (nested path — flat secondary indices
240    ///     don't cover those today; RLS still works via the policy)
241    ///   * `__tenant_idx_{table}` already exists (idempotent on rehydrate)
242    ///   * the user already registered an index whose first column matches
243    ///     (avoids redundant duplicates of a user-defined composite)
244    fn ensure_tenant_index(&self, table: &str, column: &str) {
245        if column.contains('.') {
246            return;
247        }
248        let topology_lock = self.inner.index_store.collection_topology_lock(table);
249        let _topology_guard = topology_lock.write();
250        let index_name = format!("__tenant_idx_{table}");
251        let registry = self.inner.index_store.list_indices(table);
252        if registry.iter().any(|idx| idx.name == index_name) {
253            return;
254        }
255        if registry
256            .iter()
257            .any(|idx| idx.columns.first().map(|c| c.as_str()) == Some(column))
258        {
259            return;
260        }
261
262        let store = self.inner.db.store();
263        let Some(manager) = store.get_collection(table) else {
264            return;
265        };
266        let entities = manager.query_all(|_| true);
267        let entity_fields: Vec<(
268            crate::storage::unified::EntityId,
269            Vec<(String, reddb_types::Value)>,
270        )> = entities
271            .iter()
272            .map(|e| {
273                let fields = match &e.data {
274                    crate::storage::EntityData::Row(row) => {
275                        if let Some(ref named) = row.named {
276                            named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
277                        } else if let Some(ref schema) = row.schema {
278                            schema
279                                .iter()
280                                .zip(row.columns.iter())
281                                .map(|(k, v)| (k.clone(), v.clone()))
282                                .collect()
283                        } else {
284                            Vec::new()
285                        }
286                    }
287                    crate::storage::EntityData::Node(node) => node
288                        .properties
289                        .iter()
290                        .map(|(k, v)| (k.clone(), v.clone()))
291                        .collect(),
292                    _ => Vec::new(),
293                };
294                (e.id, fields)
295            })
296            .collect();
297
298        let columns = vec![column.to_string()];
299        if self
300            .inner
301            .index_store
302            .create_index(
303                &index_name,
304                table,
305                &columns,
306                super::index_store::IndexMethodKind::Hash,
307                false,
308                &entity_fields,
309            )
310            .is_err()
311        {
312            return;
313        }
314        self.inner
315            .index_store
316            .register(super::index_store::RegisteredIndex {
317                name: index_name,
318                collection: table.to_string(),
319                columns,
320                method: super::index_store::IndexMethodKind::Hash,
321                unique: false,
322            });
323        self.invalidate_plan_cache();
324    }
325
326    /// Drop the auto-generated tenant index, if one exists. Called from
327    /// `unregister_tenant_table` so DISABLE TENANCY / DROP TABLE clean up.
328    fn drop_tenant_index(&self, table: &str) {
329        let topology_lock = self.inner.index_store.collection_topology_lock(table);
330        let _topology_guard = topology_lock.write();
331        let index_name = format!("__tenant_idx_{table}");
332        self.inner.index_store.drop_index(&index_name, table);
333    }
334
335    /// Retrieve the tenant column for a table, if any (Phase 2.5.4).
336    /// Used by the INSERT auto-fill path to know which column to
337    /// populate with `current_tenant()` when the user didn't name it.
338    pub fn tenant_column(&self, table: &str) -> Option<String> {
339        self.inner.tenant_tables.read().get(table).cloned()
340    }
341
342    /// Remove a table's tenant registration (Phase 2.5.4). Called by
343    /// DROP TABLE / ALTER TABLE DISABLE TENANCY. Removes the auto-policy
344    /// but leaves any user-installed explicit policies intact.
345    pub fn unregister_tenant_table(&self, table: &str) {
346        self.inner.tenant_tables.write().remove(table);
347        self.inner
348            .rls_policies
349            .write()
350            .remove(&(table.to_string(), "__tenant_iso".to_string()));
351        self.drop_tenant_index(table);
352        // Only clear RLS enablement if no other policies remain.
353        let has_other_policies = self
354            .inner
355            .rls_policies
356            .read()
357            .keys()
358            .any(|(t, _)| t == table);
359        if !has_other_policies {
360            self.inner.rls_enabled_tables.write().remove(table);
361        }
362    }
363
364    pub(crate) fn refresh_table_planner_stats(&self, table: &str) {
365        let store = self.inner.db.store();
366        if let Some(stats) =
367            crate::storage::query::planner::stats_catalog::analyze_collection(store.as_ref(), table)
368        {
369            crate::storage::query::planner::stats_catalog::persist_table_stats(
370                store.as_ref(),
371                &stats,
372            );
373        } else {
374            crate::storage::query::planner::stats_catalog::clear_table_stats(store.as_ref(), table);
375        }
376        self.invalidate_plan_cache();
377    }
378
379    pub(crate) fn note_table_write(&self, table: &str) {
380        // Skip the write lock when the table is already marked
381        // dirty. With single-row UPDATEs in a loop this used to
382        // grab the planner_dirty_tables write lock N times even
383        // though the first call already flipped the flag.
384        let already_dirty = self.inner.planner_dirty_tables.read().contains(table);
385        if !already_dirty {
386            self.inner
387                .planner_dirty_tables
388                .write()
389                .insert(table.to_string());
390        }
391        self.invalidate_result_cache_for_table(table);
392    }
393}