micromegas_analytics/lakehouse/view_registry.rs
1//! `ViewRegistry`: a shared `Arc<ViewFactory>` (the code-driven base plus every DDL-defined global
2//! view) rebuilt from `lakehouse_view_set_definitions` on a timer, so `telemetry-maintenance-srv`
3//! and `flight-sql-srv` both start reading/materializing a new or changed view set without a
4//! restart. Shaped after `QueryDenyList`: a Postgres-backed store, an immutable compiled snapshot
5//! behind a lock, a `refresh`/`reload` that logs and meters its own failures, and
6//! `spawn_refresh_task`.
7
8use super::{
9 session_configurator::SessionConfigurator,
10 sql_batch_view::SqlBatchView,
11 view_definition::{ViewDefinition, build_sql_batch_view, validate_view_definition},
12 view_definition_store::{ViewDefinitionRow, ViewDefinitionStore},
13 view_factory::ViewFactory,
14};
15use anyhow::Result;
16use datafusion::execution::runtime_env::RuntimeEnv;
17use micromegas_ingestion::data_lake_connection::DataLakeConnection;
18use micromegas_tracing::prelude::*;
19use std::collections::HashSet;
20use std::future::Future;
21use std::hash::{DefaultHasher, Hash, Hasher};
22use std::sync::{Arc, RwLock};
23use std::time::Duration;
24
25/// `{prefix}`-less env var: how often `spawn_refresh_task` calls `reload()`, and the bound on
26/// cross-replica propagation of a definition change made on a different node (the node that
27/// executed the DDL statement reloads inline instead, see `rust/public/src/servers/view_ddl.rs`).
28pub const MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS: &str =
29 "MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS";
30/// Default value of [`MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS`].
31pub const DEFAULT_REFRESH_SECONDS: u64 = 60;
32
33fn refresh_interval() -> Duration {
34 let secs = std::env::var(MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS)
35 .ok()
36 .and_then(|s| s.parse::<u64>().ok())
37 .unwrap_or(DEFAULT_REFRESH_SECONDS)
38 .max(1);
39 Duration::from_secs(secs)
40}
41
42/// Hashes the `(view_set_name, updated_at)` tuples of `rows`, in the order given (already
43/// `(update_group NULLS LAST, view_set_name)`-ordered by `ViewDefinitionStore::list`) -- what
44/// `reload()`
45/// compares against `loaded_digest` to short-circuit a steady-state tick to one `SELECT`.
46fn digest_of(rows: &[ViewDefinitionRow]) -> u64 {
47 let mut hasher = DefaultHasher::new();
48 for row in rows {
49 row.view_set_name.hash(&mut hasher);
50 row.updated_at
51 .timestamp_nanos_opt()
52 .unwrap_or(0)
53 .hash(&mut hasher);
54 }
55 hasher.finish()
56}
57
58/// What a [`build_factory`] call is for, which decides how a skipped definition is reported.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum BuildPurpose {
61 /// The snapshot `current()` will serve: a skipped definition is real degradation -- something
62 /// that used to work no longer does, or never did -- so it is `warn!`-logged and metered.
63 LiveSnapshot,
64 /// A speculative build the DDL executor runs inside its own transaction, on row sets that may
65 /// deliberately be missing a view another one reads. A skip here is the expected signal, not
66 /// degradation: it is returned in [`BuildFailure`] for the caller to act on -- either to
67 /// refuse the statement, naming the definition and reason, or to ignore a row that was already
68 /// broken before the mutation. Logging it would report a rejected statement, or a pre-existing
69 /// breakage the live build already reports every tick, as a fresh registry failure.
70 Probe,
71}
72
73/// A definition [`build_factory`] skipped, with the reason it was skipped, so a [`BuildPurpose::
74/// Probe`] caller can name both in the error it raises.
75#[derive(Clone, Debug)]
76pub struct BuildFailure {
77 pub view_set_name: String,
78 /// The `{:#}` rendering of the parse/build/validation error, alternate-formatted to keep the
79 /// anyhow context chain.
80 pub error: String,
81}
82
83impl std::fmt::Display for BuildFailure {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85 write!(f, "{} ({})", self.view_set_name, self.error)
86 }
87}
88
89fn skip(
90 purpose: BuildPurpose,
91 view_set_name: String,
92 stage: &str,
93 e: anyhow::Error,
94) -> BuildFailure {
95 let error = format!("{e:#}");
96 if purpose == BuildPurpose::LiveSnapshot {
97 warn!("view_registry: '{view_set_name}' failed {stage}, skipping: {error}");
98 imetric!(
99 "view_definition_load_failure",
100 "count",
101 view_set_name = view_set_name,
102 1_u64
103 );
104 }
105 BuildFailure {
106 view_set_name,
107 error,
108 }
109}
110
111/// Builds a factory from an explicit row set instead of `store.list()`, so a caller already
112/// holding rows inside an open transaction (the DDL executor's dependent-protection check) can
113/// validate against them without a second, pool-backed read that would not see its own
114/// uncommitted write. `reload()` calls this too, after its own `store.list()`. `async` because
115/// building each row's `SqlBatchView` is itself `async` and needs `runtime`/`lake`/
116/// `session_configurator` to plan the extract query.
117///
118/// Builds incrementally as a fixpoint: `let mut factory = (**base).clone();` then, per row in the
119/// order given (`(update_group NULLS LAST, view_set_name)`), build and validate its
120/// `SqlBatchView` against `Arc::new(factory.clone())` -- the built-ins plus every already-folded-in
121/// row -- and only then `factory.add_global_view(...)`. Daemon rows are sorted sources-first by
122/// their group, but an on-demand row has no group, so one may sort before an on-demand view it
123/// reads; the rows that failed are therefore retried for as long as the previous pass added at
124/// least one view. A row that fails to parse, or still fails to build or validate when a pass adds
125/// nothing, is **skipped, not fatal**: collected into the returned failed-set with its reason, so
126/// one broken definition cannot take out every other view set. Whether that skip is also logged
127/// and metered is `purpose`'s call.
128pub async fn build_factory(
129 base: &Arc<ViewFactory>,
130 rows: &[ViewDefinitionRow],
131 runtime: Arc<RuntimeEnv>,
132 lake: Arc<DataLakeConnection>,
133 session_configurator: Arc<dyn SessionConfigurator>,
134 purpose: BuildPurpose,
135) -> Result<(Arc<ViewFactory>, Vec<BuildFailure>)> {
136 let mut factory = (**base).clone();
137 let mut failed = Vec::new();
138 let mut pending = Vec::new();
139 for row in rows {
140 match row.clone().into_definition() {
141 Ok(def) => pending.push(def),
142 Err(e) => failed.push(skip(purpose, row.view_set_name.clone(), "to parse", e)),
143 }
144 }
145 loop {
146 let mut added_any = false;
147 let mut still_failing = Vec::new();
148 for def in pending {
149 let factory_so_far = Arc::new(factory.clone());
150 let attempt = fold_definition(
151 &def,
152 &factory_so_far,
153 runtime.clone(),
154 lake.clone(),
155 session_configurator.clone(),
156 )
157 .await;
158 match attempt {
159 Ok(view) => {
160 factory.add_global_view(Arc::new(view));
161 if let Some(description) = &def.options.description {
162 factory
163 .set_description(&def.view_set_name, Arc::from(description.as_str()));
164 }
165 added_any = true;
166 }
167 Err((stage, e)) => still_failing.push((def, stage, e)),
168 }
169 }
170 if !added_any || still_failing.is_empty() {
171 for (def, stage, e) in still_failing {
172 failed.push(skip(purpose, def.view_set_name, stage, e));
173 }
174 break;
175 }
176 pending = still_failing.into_iter().map(|(def, _, _)| def).collect();
177 }
178 Ok((Arc::new(factory), failed))
179}
180
181/// Builds and validates one definition against `factory_so_far`, attaching the on-demand views it
182/// reads. The error carries the stage that failed, for [`skip`].
183async fn fold_definition(
184 def: &ViewDefinition,
185 factory_so_far: &Arc<ViewFactory>,
186 runtime: Arc<RuntimeEnv>,
187 lake: Arc<DataLakeConnection>,
188 session_configurator: Arc<dyn SessionConfigurator>,
189) -> std::result::Result<SqlBatchView, (&'static str, anyhow::Error)> {
190 let view = build_sql_batch_view(
191 def,
192 runtime.clone(),
193 lake.clone(),
194 factory_so_far.clone(),
195 session_configurator.clone(),
196 )
197 .await
198 .map_err(|e| ("to build", e))?;
199 let (on_demand_sources, extract_sources) = validate_view_definition(
200 def,
201 &view,
202 factory_so_far,
203 runtime,
204 lake,
205 session_configurator,
206 )
207 .await
208 .map_err(|e| ("validation", e))?;
209 Ok(view.with_on_demand_sources(on_demand_sources, extract_sources))
210}
211
212/// A shared `Arc<ViewFactory>` (base + N DDL-defined `SqlBatchView`s) rebuilt from
213/// `lakehouse_view_set_definitions` on a timer. See the module doc comment.
214pub struct ViewRegistry {
215 base: Arc<ViewFactory>,
216 store: Arc<dyn ViewDefinitionStore>,
217 runtime: Arc<RuntimeEnv>,
218 lake: Arc<DataLakeConnection>,
219 session_configurator: Arc<dyn SessionConfigurator>,
220 current: RwLock<Arc<ViewFactory>>,
221 loaded_digest: RwLock<Option<u64>>,
222 failed_view_sets: RwLock<Vec<String>>,
223 /// Held across all of `reload()` -- list, build, and swap -- not just the swap. Without this,
224 /// a periodic reload that listed rows before a DDL-triggered reload could block behind the
225 /// DDL's own reload and then swap the pre-mutation factory back in over the DDL executor's
226 /// post-commit one, a lost update that would stay live for up to
227 /// `MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS`. Mirrors `QueryDenyList::write_lock`'s
228 /// rationale.
229 reload_mutex: tokio::sync::Mutex<()>,
230}
231
232impl std::fmt::Debug for ViewRegistry {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 f.debug_struct("ViewRegistry")
235 .field(
236 "loaded_views",
237 &self.current.read().expect("lock").get_global_views().len(),
238 )
239 .field(
240 "failed_view_sets",
241 &self.failed_view_sets.read().expect("lock").len(),
242 )
243 .finish()
244 }
245}
246
247impl ViewRegistry {
248 pub fn new(
249 base: Arc<ViewFactory>,
250 store: Arc<dyn ViewDefinitionStore>,
251 runtime: Arc<RuntimeEnv>,
252 lake: Arc<DataLakeConnection>,
253 session_configurator: Arc<dyn SessionConfigurator>,
254 ) -> Self {
255 Self {
256 current: RwLock::new(base.clone()),
257 base,
258 store,
259 runtime,
260 lake,
261 session_configurator,
262 loaded_digest: RwLock::new(None),
263 failed_view_sets: RwLock::new(Vec::new()),
264 reload_mutex: tokio::sync::Mutex::new(()),
265 }
266 }
267
268 /// The current snapshot: the base factory before the first successful `reload()`, or the base
269 /// plus every definition that built and validated on the last successful build afterward.
270 pub fn current(&self) -> Arc<ViewFactory> {
271 self.current.read().expect("lock").clone()
272 }
273
274 /// Names skipped by the last build, for introspection/tests.
275 pub fn failed_view_sets(&self) -> Vec<String> {
276 self.failed_view_sets.read().expect("lock").clone()
277 }
278
279 /// Thin wrapper over [`build_factory`] supplying this registry's `base`/`runtime`/`lake`/
280 /// `session_configurator`.
281 pub async fn build_from_rows(
282 &self,
283 rows: &[ViewDefinitionRow],
284 purpose: BuildPurpose,
285 ) -> Result<(Arc<ViewFactory>, Vec<BuildFailure>)> {
286 build_factory(
287 &self.base,
288 rows,
289 self.runtime.clone(),
290 self.lake.clone(),
291 self.session_configurator.clone(),
292 purpose,
293 )
294 .await
295 }
296
297 /// The dependent-protection refusal: builds a factory from `pre_rows` and one from
298 /// `post_rows`, then refuses with a named error if any definition present in `post_rows` --
299 /// including the row just written -- both fails to build against `post_rows` and was not
300 /// already in the pre-mutation failed set. Exact rather than textual: it uses the real
301 /// planner, so it catches a removed column as readily as a removed view set.
302 ///
303 /// Both builds are [`BuildPurpose::Probe`]s: a skip is what this check is looking for, so it
304 /// belongs in the refusal the caller returns -- with the planner's own reason, the only place
305 /// the admin can now read it -- not in the service log as a registry failure.
306 pub async fn check_dependents_survive(
307 &self,
308 pre_rows: &[ViewDefinitionRow],
309 post_rows: &[ViewDefinitionRow],
310 ) -> Result<()> {
311 let (_, pre_failed) = self.build_from_rows(pre_rows, BuildPurpose::Probe).await?;
312 let (_, post_failed) = self.build_from_rows(post_rows, BuildPurpose::Probe).await?;
313 let pre_failed_set: HashSet<&str> = pre_failed
314 .iter()
315 .map(|f| f.view_set_name.as_str())
316 .collect();
317 let newly_broken: Vec<String> = post_failed
318 .iter()
319 .filter(|f| !pre_failed_set.contains(f.view_set_name.as_str()))
320 .map(BuildFailure::to_string)
321 .collect();
322 if !newly_broken.is_empty() {
323 anyhow::bail!(
324 "this change would break the following view definition(s), which built \
325 successfully before it: {}",
326 newly_broken.join(", ")
327 );
328 }
329 Ok(())
330 }
331
332 /// Refreshes `current()` from `lakehouse_view_set_definitions`.
333 ///
334 /// 0. Acquires `reload_mutex` and holds it through every step below.
335 /// 1. `store.list()` -> rows ordered by `(update_group NULLS LAST, view_set_name)`.
336 /// 2. Hashes the `(view_set_name, updated_at)` tuples; if unchanged from `loaded_digest`
337 /// **and** the previous build's failed set was empty, returns -- one `SELECT`, no
338 /// planning. A digest match after a failed build does *not* short-circuit, so a row that
339 /// failed for a transient reason is retried every tick.
340 /// 3. `build_factory(...)`.
341 /// 4. A row that still fails to build or validate once the build settles is skipped, not fatal
342 /// (see [`build_factory`]).
343 /// 5. Swaps `current`, updates `loaded_digest` and `failed_view_sets`.
344 pub async fn reload(&self) -> Result<()> {
345 let _guard = self.reload_mutex.lock().await;
346 let rows = self.store.list().await?;
347 let digest = digest_of(&rows);
348 let previous_build_was_healthy = self.failed_view_sets.read().expect("lock").is_empty();
349 if previous_build_was_healthy && Some(digest) == *self.loaded_digest.read().expect("lock") {
350 return Ok(());
351 }
352 let (factory, failed) = self
353 .build_from_rows(&rows, BuildPurpose::LiveSnapshot)
354 .await?;
355 *self.current.write().expect("lock") = factory;
356 *self.loaded_digest.write().expect("lock") = Some(digest);
357 *self.failed_view_sets.write().expect("lock") = failed
358 .into_iter()
359 .map(|f| f.view_set_name)
360 .collect::<Vec<_>>();
361 Ok(())
362 }
363
364 /// Spawns the background task that calls [`Self::reload`] once immediately and then on every
365 /// [`MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS`] tick, until `shutdown` resolves. A failed
366 /// `reload()` is `warn!`-logged here and discarded -- the previous snapshot is kept (the same
367 /// fail-open treatment `QueryDenyList::spawn_refresh_task` gives a failed periodic refresh).
368 pub fn spawn_refresh_task(
369 self: Arc<Self>,
370 shutdown: impl Future<Output = ()> + Send + 'static,
371 ) {
372 tokio::spawn(async move {
373 let mut shutdown = Box::pin(shutdown);
374 loop {
375 if let Err(e) = self.reload().await {
376 warn!("view_registry: reload failed, keeping previous snapshot: {e:#}");
377 }
378 tokio::select! {
379 _ = &mut shutdown => break,
380 _ = tokio::time::sleep(refresh_interval()) => {}
381 }
382 }
383 });
384 }
385}