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 }
167 }
168
169 /// Register a table as tenant-scoped (Phase 2.5.4). Installs the
170 /// in-memory column mapping, the implicit RLS policy, and enables
171 /// row-level security on the table. Idempotent — re-registering
172 /// the same `(table, column)` replaces the prior auto-policy.
173 pub fn register_tenant_table(&self, table: &str, column: &str) {
174 use reddb_rql::ast::{CompareOp, CreatePolicyQuery, Expr, FieldRef, Filter, Span};
175 self.inner
176 .tenant_tables
177 .write()
178 .insert(table.to_string(), column.to_string());
179
180 // Build the policy: col = CURRENT_TENANT()
181 // Uses CompareExpr so the comparison happens at runtime against
182 // the thread-local tenant value read by the CURRENT_TENANT
183 // scalar. Spans are synthetic — there's no source location for
184 // an auto-generated policy.
185 let lhs = Expr::Column {
186 field: FieldRef::TableColumn {
187 table: table.to_string(),
188 column: column.to_string(),
189 },
190 span: Span::synthetic(),
191 };
192 let rhs = Expr::FunctionCall {
193 name: "CURRENT_TENANT".to_string(),
194 args: Vec::new(),
195 span: Span::synthetic(),
196 };
197 let policy_filter = Filter::CompareExpr {
198 lhs,
199 op: CompareOp::Eq,
200 rhs,
201 };
202
203 let policy = CreatePolicyQuery {
204 name: "__tenant_iso".to_string(),
205 table: table.to_string(),
206 action: None, // None = ALL actions (SELECT/INSERT/UPDATE/DELETE)
207 role: None, // None = every role
208 using: Box::new(policy_filter),
209 // Auto-tenancy defaults to Table targets. Collections of
210 // other kinds (graph / vector / queue / timeseries) that
211 // opt in via `ALTER ... ENABLE TENANCY` should use the
212 // matching kind — but for now we keep the auto-policy
213 // kind-agnostic so the evaluator can apply it to any
214 // entity living in the collection.
215 target_kind: reddb_rql::ast::PolicyTargetKind::Table,
216 };
217
218 // Replace any prior auto-policy for this table (column rename).
219 self.inner.rls_policies.write().insert(
220 (table.to_string(), "__tenant_iso".to_string()),
221 Arc::new(policy),
222 );
223 self.inner
224 .rls_enabled_tables
225 .write()
226 .insert(table.to_string());
227
228 // Auto-build a hash index on the tenant column. Every read/write
229 // against a tenant-scoped table carries an implicit
230 // `col = CURRENT_TENANT()` predicate from the auto-policy, so an
231 // index on that column is on the hot path of every query. Without
232 // it, every SELECT/UPDATE/DELETE degrades to a full scan.
233 self.ensure_tenant_index(table, column);
234 }
235
236 /// Auto-create the hash index that backs the tenant-iso RLS predicate.
237 /// Skipped when:
238 /// * the column is dotted (nested path — flat secondary indices
239 /// don't cover those today; RLS still works via the policy)
240 /// * `__tenant_idx_{table}` already exists (idempotent on rehydrate)
241 /// * the user already registered an index whose first column matches
242 /// (avoids redundant duplicates of a user-defined composite)
243 fn ensure_tenant_index(&self, table: &str, column: &str) {
244 if column.contains('.') {
245 return;
246 }
247 let topology_lock = self.inner.index_store.collection_topology_lock(table);
248 let _topology_guard = topology_lock.write();
249 let index_name = format!("__tenant_idx_{table}");
250 let registry = self.inner.index_store.list_indices(table);
251 if registry.iter().any(|idx| idx.name == index_name) {
252 return;
253 }
254 if registry
255 .iter()
256 .any(|idx| idx.columns.first().map(|c| c.as_str()) == Some(column))
257 {
258 return;
259 }
260
261 let store = self.inner.db.store();
262 let Some(manager) = store.get_collection(table) else {
263 return;
264 };
265 let entities = manager.query_all(|_| true);
266 let entity_fields: Vec<(
267 crate::storage::unified::EntityId,
268 Vec<(String, reddb_types::Value)>,
269 )> = entities
270 .iter()
271 .map(|e| {
272 let fields = match &e.data {
273 crate::storage::EntityData::Row(row) => {
274 if let Some(ref named) = row.named {
275 named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
276 } else if let Some(ref schema) = row.schema {
277 schema
278 .iter()
279 .zip(row.columns.iter())
280 .map(|(k, v)| (k.clone(), v.clone()))
281 .collect()
282 } else {
283 Vec::new()
284 }
285 }
286 crate::storage::EntityData::Node(node) => node
287 .properties
288 .iter()
289 .map(|(k, v)| (k.clone(), v.clone()))
290 .collect(),
291 _ => Vec::new(),
292 };
293 (e.id, fields)
294 })
295 .collect();
296
297 let columns = vec![column.to_string()];
298 if self
299 .inner
300 .index_store
301 .create_index(
302 &index_name,
303 table,
304 &columns,
305 super::index_store::IndexMethodKind::Hash,
306 false,
307 &entity_fields,
308 )
309 .is_err()
310 {
311 return;
312 }
313 self.inner
314 .index_store
315 .register(super::index_store::RegisteredIndex {
316 name: index_name,
317 collection: table.to_string(),
318 columns,
319 method: super::index_store::IndexMethodKind::Hash,
320 unique: false,
321 });
322 self.invalidate_plan_cache();
323 }
324
325 /// Drop the auto-generated tenant index, if one exists. Called from
326 /// `unregister_tenant_table` so DISABLE TENANCY / DROP TABLE clean up.
327 fn drop_tenant_index(&self, table: &str) {
328 let topology_lock = self.inner.index_store.collection_topology_lock(table);
329 let _topology_guard = topology_lock.write();
330 let index_name = format!("__tenant_idx_{table}");
331 self.inner.index_store.drop_index(&index_name, table);
332 }
333
334 /// Retrieve the tenant column for a table, if any (Phase 2.5.4).
335 /// Used by the INSERT auto-fill path to know which column to
336 /// populate with `current_tenant()` when the user didn't name it.
337 pub fn tenant_column(&self, table: &str) -> Option<String> {
338 self.inner.tenant_tables.read().get(table).cloned()
339 }
340
341 /// Remove a table's tenant registration (Phase 2.5.4). Called by
342 /// DROP TABLE / ALTER TABLE DISABLE TENANCY. Removes the auto-policy
343 /// but leaves any user-installed explicit policies intact.
344 pub fn unregister_tenant_table(&self, table: &str) {
345 self.inner.tenant_tables.write().remove(table);
346 self.inner
347 .rls_policies
348 .write()
349 .remove(&(table.to_string(), "__tenant_iso".to_string()));
350 self.drop_tenant_index(table);
351 // Only clear RLS enablement if no other policies remain.
352 let has_other_policies = self
353 .inner
354 .rls_policies
355 .read()
356 .keys()
357 .any(|(t, _)| t == table);
358 if !has_other_policies {
359 self.inner.rls_enabled_tables.write().remove(table);
360 }
361 }
362
363 pub(crate) fn refresh_table_planner_stats(&self, table: &str) {
364 let store = self.inner.db.store();
365 if let Some(stats) =
366 crate::storage::query::planner::stats_catalog::analyze_collection(store.as_ref(), table)
367 {
368 crate::storage::query::planner::stats_catalog::persist_table_stats(
369 store.as_ref(),
370 &stats,
371 );
372 } else {
373 crate::storage::query::planner::stats_catalog::clear_table_stats(store.as_ref(), table);
374 }
375 self.invalidate_plan_cache();
376 }
377
378 pub(crate) fn note_table_write(&self, table: &str) {
379 // Skip the write lock when the table is already marked
380 // dirty. With single-row UPDATEs in a loop this used to
381 // grab the planner_dirty_tables write lock N times even
382 // though the first call already flipped the flag.
383 let already_dirty = self.inner.planner_dirty_tables.read().contains(table);
384 if !already_dirty {
385 self.inner
386 .planner_dirty_tables
387 .write()
388 .insert(table.to_string());
389 }
390 self.invalidate_result_cache_for_table(table);
391 }
392}