micromegas_analytics/lakehouse/view_factory.rs
1//! [`default_view_factory`] makes the default [`ViewFactory`], giving users access to view instances, grouped in sets.
2//!
3//! # View sets
4//!
5//! A ViewFactory defines the available view sets and can instanciate view instances.
6//! All view instances in a set have the same schema.
7//! Some view instances are global (their view_instance_id is 'global').
8//! Global view instances are implicitly accessible to SQL queries.
9//! Non-global view instances are accessible using the table function `view_instance`. See [ViewInstanceTableFunction](super::view_instance_table_function::ViewInstanceTableFunction).
10//!
11//! ## log_entries
12//!
13//! | field | type | description |
14//! |------------- |-----------------------------|-----------------------------------------------------------|
15//! |process_id |Utf8 | unique id of the process, references the processes table |
16//! |exe |Utf8 | filename of the process |
17//! |username |Utf8 | username of the process |
18//! |computer |Utf8 | computer name of the process |
19//! |time |UTC Timestamp (nanoseconds) | time of the log entry event |
20//! |target |Utf8 | category or module name of the log entry |
21//! |level |int32 | verbosity level (Fatal=1, Error=2, Warning=3, Info=4, Debug=5, Trace=6)| |
22//! |msg |Utf8 | message |
23//! |audience |Dictionary(Int32, Utf8) | the audience of the block this log entry came from (the block's own stamp), never `NULL` |
24//!
25//! ### log_entries view instances
26//!
27//! The implicit use of the `log_entries` table corresponds to the 'global' instance, which contains the log entries of all the processes.
28//!
29//! Except the 'global' instance, the instance_id refers to any process_id. `view_instance('log_entries', process_id)` contains that process's log. Process-specific views are materialized just-in-time and can provide much better query performance compared to the 'global' instance.
30//!
31//! ## measures
32//!
33//! | field | type | description |
34//! |------------- |-----------------------------|-----------------------------------------------------------|
35//! |process_id |Utf8 | unique id of the process, references the processes table |
36//! |exe |Utf8 | filename of the process |
37//! |username |Utf8 | username of the process |
38//! |computer |Utf8 | computer name of the process |
39//! |time |UTC Timestamp (nanoseconds) | time of the measure event |
40//! |target |Utf8 | category or module name of the measure |
41//! |name |Utf8 | name of the measure |
42//! |unit |Utf8 | unit of measure |
43//! |value |Float64 | value measured |
44//! |audience |Dictionary(Int32, Utf8) | the audience of the block this measure came from (the block's own stamp), never `NULL` |
45//!
46//!
47//! ### measures view instances
48//!
49//! The implicit use of the `measures` table corresponds to the 'global' instance, which contains the metrics of all the processes.
50//!
51//! Except the 'global' instance, the instance_id refers to any process_id. `view_instance('measures', process_id)` contains that process's metrics. Process-specific views are materialized just-in-time and can provide much better query performance compared to the 'global' instance.
52//!
53//! ## log_stats
54//!
55//! Materialized aggregate of `log_entries` by process, minute, level, and target -- one global
56//! instance, implicitly available (no `view_instance(...)` form). `log_stats` is
57//! a seeded row in `lakehouse_view_set_definitions`, not one `default_view_factory` builds -- it
58//! is droppable and replaceable by an operator like any other DDL-defined view, and the schema
59//! below is its shipped default, not a guarantee.
60//!
61//! | field | type | description |
62//! |------------- |-----------------------------|------------------------------------------------------------|
63//! |time_bin |UTC Timestamp (nanoseconds) | 1-minute time bucket for aggregation |
64//! |process_id |Dictionary(Int32, Utf8) | process unique id |
65//! |level |Int32 | log level (see `log_entries` above) |
66//! |target |Dictionary(Int32, Utf8) | category or module name of the aggregated logs |
67//! |count |Int64 | number of log entries in this aggregation |
68//! |audience |Dictionary(Int32, Utf8) | the audience of the blocks aggregated into this row (the blocks' own stamp), never `NULL` |
69//!
70//! ## thread_spans
71//!
72//! | field | type | description |
73//! |------------- |-----------------------------|------------------------------------------------------------|
74//! |id |Int64 | span id, unique within this thread |
75//! |parent |Int64 | span id of the calling span |
76//! |depth |UInt32 | call stack depth |
77//! |hash |UInt32 | identifies a call site (name, filename, line) |
78//! |begin |UTC Timestamp (nanoseconds) | when the span started its execution |
79//! |end |UTC Timestamp (nanoseconds) | when the span finished its execution |
80//! |duration |Int64 (nanoseconds) | end-begin |
81//! |name |Utf8 | name of the span, usually a function name |
82//! |target |Utf8 | category or module name |
83//! |filename |Utf8 | name or path of the source file where the span is coded |
84//! |line |UInt32 | line number in the file where the span can be found |
85//! |properties |Dictionary(Int32, Binary) | properties recorded on the span's end event (JSONB), empty when none |
86//!
87//! ### thread_spans view instances
88//!
89//! There is no 'global' instance in the 'thread_spans' view set, there is therefore no implicit thread_spans table availble.
90//! Users can call the table function `view_instance('thread_spans', stream_id)` to query the spans in the thread associated with the specified stream_id.
91//!
92//! ## async_events
93//!
94//! | field | type | description |
95//! |------------- |-----------------------------|-----------------------------------------------------------|
96//! |stream_id |Dictionary(Int32, Utf8) | identifier of the thread stream that emitted the event |
97//! |block_id |Dictionary(Int32, Utf8) | unique identifier of the event block |
98//! |time |UTC Timestamp (nanoseconds) | time when the async event occurred |
99//! |event_type |Dictionary(Int32, Utf8) | type of event: "begin" or "end" |
100//! |span_id |Int64 | unique async span identifier |
101//! |parent_span_id|Int64 | span id of the parent async span |
102//! |name |Dictionary(Int32, Utf8) | name of the async span, usually a function name |
103//! |filename |Dictionary(Int32, Utf8) | name or path of the source file where the span is coded |
104//! |target |Dictionary(Int32, Utf8) | category or module name |
105//! |line |UInt32 | line number in the file where the span can be found |
106//! |properties |Dictionary(Int32, Binary) | properties recorded on the span's end event (JSONB), empty on begin rows and when none |
107//!
108//! ### async_events view instances
109//!
110//! There is no 'global' instance in the 'async_events' view set, there is therefore no implicit async_events table available.
111//! Users can call the table function `view_instance('async_events', process_id)` to query the async events in all thread streams associated with the specified process_id.
112//! Process-specific views are materialized just-in-time and can provide good query performance.
113//!
114//! The schema is optimized for high-frequency data. Process information (exe, username, computer, etc.) can be joined when needed:
115//! ```sql
116//! SELECT ae.*, p.exe, p.username, p.computer
117//! FROM view_instance('async_events', process_id) ae
118//! JOIN streams s ON ae.stream_id = s.stream_id
119//! JOIN processes p ON s.process_id = p.process_id
120//! ```
121//!
122//! ## net_spans
123//!
124//! | field | type | description |
125//! |------------------|-----------------------------|-------------------------------------------------------------------------|
126//! |process_id |Dictionary(Int32, Utf8) | process unique id |
127//! |stream_id |Dictionary(Int32, Utf8) | net stream unique id |
128//! |span_id |Int64 | unique span id within the stream |
129//! |parent_span_id |Int64 | span id of the enclosing span (-1 sentinel at Connection roots) |
130//! |depth |UInt32 | tree depth (0 = Connection) |
131//! |kind |Dictionary(Int32, Utf8) | one of `connection` / `object` / `property` / `rpc` |
132//! |name |Dictionary(Int32, Utf8) | span name (connection / object / property / function name) |
133//! |connection_name |Dictionary(Int32, Utf8) | enclosing connection name (denormalized onto every row) |
134//! |is_outgoing |Boolean | direction inherited from the enclosing connection |
135//! |begin_bits |Int64 | cumulative bit offset within the parent span (0 at the Connection root) |
136//! |end_bits |Int64 | `begin_bits + bit_size` |
137//! |bit_size |Int64 | inclusive number of bits attributed to this span |
138//! |begin_time |UTC Timestamp (nanoseconds) | timestamp of the span's Begin event |
139//! |end_time |UTC Timestamp (nanoseconds) | timestamp of the span's End event (equals `begin_time` for properties) |
140//!
141//! ### net_spans view instances
142//!
143//! There is no 'global' instance in the 'net_spans' view set. Users call
144//! `view_instance('net_spans', process_id)` to query the network bandwidth spans emitted by a
145//! given process's net stream. Partitions are materialized just-in-time.
146//!
147//! ## processes
148//!
149//! | field | type | description |
150//! |------------- |-----------------------------|------------------------------------------------------------|
151//! |process_id |Utf8 | process unique id |
152//! |exe |Utf8 | filename of the process |
153//! |username |Utf8 | username of the process |
154//! |realname |Utf8 | real name of the user launching the process |
155//! |computer |Utf8 | name of the computer or vm |
156//! |distro |Utf8 | name of operating system |
157//! |cpu_brand |Utf8 | identifies the cpu |
158//! |tsc frequency |Int64 | number of ticks per second |
159//! |start_time |UTC Timestamp (nanoseconds) | when the process started (as reported by the instrumented process) |
160//! |start_ticks |Int64 | tick count associated with start_time |
161//! |insert_time |UTC Timestamp (nanoseconds) | server-side timestamp when the process metedata was received |
162//! |parent_process_id |Utf8 | unique id of the parent process |
163//! |properties | Array of {key: utf8, value: utf8} | self-reported metadata by the process |
164//! |last_update_time |UTC Timestamp (nanoseconds) | when this process's data was last updated |
165//! |last_block_end_ticks |Int64 | tick count when the last block ended |
166//! |last_block_end_time |UTC Timestamp (nanoseconds) | timestamp when the last block ended |
167//! |audience |Dictionary(Int32, Utf8) | this process's write audience, resolved from its blocks' own stamps via `max(audience)`; never `NULL` |
168//!
169//! There is only one instance in this view set and it is implicitly available.
170//!
171//! ## streams
172//!
173//! | field | type | description |
174//! |------------- |-----------------------------|------------------------------------------------------------|
175//! |stream_id |Utf8 | stream unique id |
176//! |process_id |Utf8 | process unique id |
177//! |dependencies_metadata|Binary | memory layout of the event dependencies |
178//! |objects_metadata|Binary | memory layout of the events |
179//! |tags | Array of utf8 | Purpose of the stream, can contain "log", "metrics" or "cpu" |
180//! |properties | Array of {key: utf8, value: utf8} | self-reported stream metadata by the process |
181//! |insert_time |UTC Timestamp (nanoseconds) | server-side timestamp when the stream metedata was received |
182//! |format |Utf8 | stream payload format (e.g. for OTLP support) |
183//! |last_update_time |UTC Timestamp (nanoseconds) | when this stream's data was last updated |
184//! |audience |Dictionary(Int32, Utf8) | this stream's write audience, resolved from its blocks' own stamps via `max(audience)`; never `NULL` |
185//!
186//! There is only one instance in this view set and it is implicitly available.
187//!
188//! ## blocks
189//!
190//! | field | type | description |
191//! |------------- |-----------------------------|------------------------------------------------------------|
192//! |block_id |Utf8 | block unique id |
193//! |stream_id |Utf8 | stream unique id |
194//! |process_id |Utf8 | process unique id |
195//! |begin_time |UTC Timestamp (nanoseconds) | system time marking the beginning of this event batch |
196//! |begin_ticks |Int64 | tick count associated with begin_time |
197//! |end_time |UTC Timestamp (nanoseconds) | system time marking the ending of this event batch |
198//! |end_ticks |Int64 | tick count associated with end_time |
199//! |nb_objects |Int32 | number of events in this batch |
200//! |object_offset |Int64 | number of events preceding this batch |
201//! |payload_size |Int64 | number of bytes of the binary payload |
202//! |insert_time |UTC Timestamp (nanoseconds) | server-side timestamp when the block was received |
203//! |streams.dependencies_metadata|Binary | memory layout of the event dependencies |
204//! |streams.objects_metadata|Binary | memory layout of the events |
205//! |streams.tags | Array of utf8 | Purpose of the stream, can contain "log", "metrics" or "cpu" |
206//! |streams.properties | Array of {key: utf8, value: utf8} | self-reported stream metadata by the process |
207//! |streams.insert_time |UTC Timestamp (nanoseconds) | server-side timestamp when the stream metedata was received |
208//! |streams.format |Utf8 | stream payload format (e.g. for OTLP support) |
209//! |processes.start_time |UTC Timestamp (nanoseconds) | when the process started (as reported by the instrumented process) |
210//! |processes.start_ticks |Int64 | tick count associated with start_time |
211//! |processes.tsc frequency |Int64 | number of ticks per second |
212//! |processes.exe |Utf8 | filename of the process |
213//! |processes.username |Utf8 | username of the process |
214//! |processes.realname |Utf8 | real name of the user launching the process |
215//! |processes.computer |Utf8 | name of the computer or vm |
216//! |processes.distro |Utf8 | name of operating system |
217//! |processes.cpu_brand |Utf8 | identifies the cpu |
218//! |processes.insert_time |UTC Timestamp (nanoseconds) | server-side timestamp when the process metedata was received |
219//! |processes.parent_process_id |Utf8 | unique id of the parent process (nullable in practice) |
220//! |processes.properties | Array of {key: utf8, value: utf8} | self-reported metadata by the process |
221//! |audience |Dictionary(Int32, Utf8) | this block's own write audience, never derived from its process_id/stream_id -- server-written, never `NULL` |
222//!
223//! There is only one instance in this view set and it is implicitly available.
224//!
225//!
226//!
227use super::blocks_view::BlocksView;
228use super::partitioned_execution_plan::ScanOrdering;
229use super::processes_view::make_processes_view;
230use super::streams_view::make_streams_view;
231use super::{
232 async_events_view::AsyncEventsViewMaker, images_view::ImagesViewMaker, log_view::LogViewMaker,
233 metrics_view::MetricsViewMaker, net_spans_view::NetSpansViewMaker,
234 otel::histograms_view::OtelHistogramsViewMaker, otel::spans_view::OtelSpansViewMaker,
235 thread_spans_view::ThreadSpansViewMaker, view::View,
236};
237use anyhow::Result;
238use datafusion::arrow::datatypes::Schema;
239use datafusion::execution::runtime_env::RuntimeEnv;
240use micromegas_ingestion::data_lake_connection::DataLakeConnection;
241use std::fmt::Debug;
242use std::{collections::HashMap, sync::Arc};
243
244/// A trait for creating views.
245pub trait ViewMaker: Send + Sync + Debug {
246 /// Creates a new view with the given instance ID.
247 fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>>;
248
249 /// Returns the schema hash for views created by this maker.
250 fn get_schema_hash(&self) -> Vec<u8>;
251
252 /// Returns the schema for views created by this maker.
253 fn get_schema(&self) -> Arc<Schema>;
254
255 /// Ordering every instance this maker builds declares; see `View::get_scan_output_ordering`.
256 fn get_scan_output_ordering(&self) -> ScanOrdering;
257}
258
259/// A factory for creating and managing views.
260#[derive(Debug, Clone)]
261pub struct ViewFactory {
262 view_sets: HashMap<String, Arc<dyn ViewMaker>>,
263 global_views: Vec<Arc<dyn View>>,
264 descriptions: HashMap<String, Arc<str>>,
265}
266
267impl ViewFactory {
268 pub fn new(global_views: Vec<Arc<dyn View>>) -> Self {
269 Self {
270 view_sets: HashMap::new(),
271 global_views,
272 descriptions: HashMap::new(),
273 }
274 }
275
276 pub fn set_description(&mut self, view_set_name: &str, text: Arc<str>) {
277 self.descriptions.insert(view_set_name.to_string(), text);
278 }
279
280 pub fn get_description(&self, view_set_name: &str) -> Option<Arc<str>> {
281 self.descriptions.get(view_set_name).cloned()
282 }
283
284 pub fn get_global_views(&self) -> &[Arc<dyn View>] {
285 &self.global_views
286 }
287
288 pub fn get_global_view(&self, view_name: &str) -> Option<Arc<dyn View>> {
289 self.global_views
290 .iter()
291 .find(|v| *(v.get_view_set_name()) == view_name)
292 .cloned()
293 }
294
295 pub fn add_global_view(&mut self, view: Arc<dyn View>) {
296 self.global_views.push(view);
297 }
298
299 pub fn add_view_set(&mut self, view_set_name: String, maker: Arc<dyn ViewMaker>) {
300 self.view_sets.insert(view_set_name, maker);
301 }
302
303 pub fn get_view_sets(&self) -> &HashMap<String, Arc<dyn ViewMaker>> {
304 &self.view_sets
305 }
306
307 pub fn make_view(&self, view_set_name: &str, view_instance_id: &str) -> Result<Arc<dyn View>> {
308 if let Some(maker) = self.view_sets.get(view_set_name) {
309 maker.make_view(view_instance_id)
310 } else {
311 anyhow::bail!("view set {view_set_name} not found");
312 }
313 }
314}
315
316/// Creates the default `ViewFactory` with all built-in views.
317///
318/// `default_audience` is the deployment's `MICROMEGAS_DEFAULT_AUDIENCE`, which the
319/// `blocks` view binds when it materializes. Callers source it from
320/// `LakehouseContext::default_audience` so every role that builds a factory bakes the same value
321/// into partitions -- notably the maintenance role, which is the one that actually materializes
322/// the five global views. `log_stats` is no longer one of them: it is a seeded row in
323/// `lakehouse_view_set_definitions`, folded in by `ViewRegistry` rather than by this function.
324pub async fn default_view_factory(
325 runtime: Arc<RuntimeEnv>,
326 lake: Arc<DataLakeConnection>,
327 default_audience: Arc<str>,
328) -> Result<ViewFactory> {
329 let blocks_view = Arc::new(BlocksView::new(default_audience)?);
330 let processes_view = Arc::new(
331 make_processes_view(
332 runtime.clone(),
333 lake.clone(),
334 Arc::new(ViewFactory::new(vec![blocks_view.clone()])),
335 )
336 .await?,
337 );
338 let streams_view = Arc::new(
339 make_streams_view(
340 runtime.clone(),
341 lake.clone(),
342 Arc::new(ViewFactory::new(vec![blocks_view.clone()])),
343 )
344 .await?,
345 );
346 let images_view_maker = Arc::new(ImagesViewMaker {});
347 let log_view_maker = Arc::new(LogViewMaker {});
348 let metrics_view_maker = Arc::new(MetricsViewMaker {});
349 let otel_histograms_view_maker = Arc::new(OtelHistogramsViewMaker {});
350
351 // Create base views first
352 let global_views = vec![
353 log_view_maker.make_view("global")?,
354 metrics_view_maker.make_view("global")?,
355 otel_histograms_view_maker.make_view("global")?,
356 processes_view,
357 streams_view,
358 blocks_view,
359 ];
360 let mut factory = ViewFactory::new(global_views);
361 factory.add_view_set(String::from("images"), images_view_maker);
362 factory.add_view_set(String::from("log_entries"), log_view_maker.clone());
363 factory.add_view_set(String::from("measures"), metrics_view_maker);
364 factory.add_view_set(String::from("otel_histograms"), otel_histograms_view_maker);
365
366 // `log_stats` no longer joins it here -- it is seeded into `lakehouse_view_set_definitions`
367 // and folded in by `ViewRegistry` instead (see the module doc comment).
368 let mut updated_factory = factory;
369
370 // Add async_events view maker
371 updated_factory.add_view_set(
372 String::from("async_events"),
373 Arc::new(AsyncEventsViewMaker::new(Arc::new(updated_factory.clone()))),
374 );
375
376 // Add net_spans view maker
377 updated_factory.add_view_set(
378 String::from("net_spans"),
379 Arc::new(NetSpansViewMaker::new(Arc::new(updated_factory.clone()))),
380 );
381
382 // Add thread_spans view maker
383 updated_factory.add_view_set(
384 String::from("thread_spans"),
385 Arc::new(ThreadSpansViewMaker::new(Arc::new(updated_factory.clone()))),
386 );
387
388 // Add otel_spans view maker (per-process JIT only — no global instance)
389 updated_factory.add_view_set(String::from("otel_spans"), Arc::new(OtelSpansViewMaker {}));
390
391 for (name, text) in [
392 ("processes", include_str!("view_descriptions/processes.md")),
393 ("streams", include_str!("view_descriptions/streams.md")),
394 ("blocks", include_str!("view_descriptions/blocks.md")),
395 (
396 "log_entries",
397 include_str!("view_descriptions/log_entries.md"),
398 ),
399 ("measures", include_str!("view_descriptions/measures.md")),
400 (
401 "otel_histograms",
402 include_str!("view_descriptions/otel_histograms.md"),
403 ),
404 ("images", include_str!("view_descriptions/images.md")),
405 (
406 "thread_spans",
407 include_str!("view_descriptions/thread_spans.md"),
408 ),
409 (
410 "async_events",
411 include_str!("view_descriptions/async_events.md"),
412 ),
413 ("net_spans", include_str!("view_descriptions/net_spans.md")),
414 (
415 "otel_spans",
416 include_str!("view_descriptions/otel_spans.md"),
417 ),
418 ] {
419 updated_factory.set_description(name, Arc::from(text));
420 }
421
422 Ok(updated_factory)
423}