Skip to main content

micromegas_analytics/lakehouse/otel/
spans_view.rs

1//! Per-process JIT view of OTel spans.
2//!
3//! `otel_spans` mirrors the `AsyncEventsView` pattern (no batch path; JIT-only;
4//! materialized per-process) but the time-conversion plumbing is simpler: OTLP
5//! timestamps are absolute nanoseconds (`tsc_frequency = 1_000_000_000`), so we
6//! use the plain `find_process` flow instead of the latest-timing variant.
7//!
8//! Cross-process trace traversal (`WHERE trace_id = X` across services) is a
9//! documented v1 limitation — users supply the `process_id` to
10//! `view_instance('otel_spans', '<uuid>')` or UNION across multiple instances.
11
12use super::spans_block_processor::OtelSpansBlockProcessor;
13use super::spans_table::otel_spans_table_schema;
14use crate::lakehouse::{
15    batch_update::PartitionCreationStrategy,
16    block_partition_spec::{BlockProcessor, BlockProcessorMap},
17    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
18    jit_partitions::update_insert_time_jit_view,
19    lakehouse_context::LakehouseContext,
20    partition_cache::PartitionCache,
21    partitioned_execution_plan::ScanOrdering,
22    view::{PartitionSpec, View},
23    view_factory::ViewMaker,
24};
25use crate::{
26    metadata::find_process,
27    time::{TimeRange, datetime_to_scalar},
28};
29use anyhow::{Context, Result};
30use async_trait::async_trait;
31use chrono::{DateTime, TimeDelta, Utc};
32use datafusion::{
33    arrow::datatypes::Schema,
34    logical_expr::{BinaryExpr, Expr, Operator, col},
35};
36use micromegas_ingestion::web_ingestion_service::FORMAT_OTLP_TRACES;
37use micromegas_tracing::prelude::*;
38use std::collections::HashMap;
39use std::sync::Arc;
40use uuid::Uuid;
41
42const VIEW_SET_NAME: &str = "otel_spans";
43const SCHEMA_VERSION: u8 = 1;
44lazy_static::lazy_static! {
45    static ref TIME_COLUMN: Arc<String> = Arc::new(String::from("start_time"));
46    static ref END_TIME_COLUMN: Arc<String> = Arc::new(String::from("end_time"));
47}
48
49/// `ViewMaker` for `OtelSpansView`. Per-process only — `"global"` is rejected.
50#[derive(Debug)]
51pub struct OtelSpansViewMaker {}
52
53impl ViewMaker for OtelSpansViewMaker {
54    fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
55        Ok(Arc::new(OtelSpansView::new(view_instance_id)?))
56    }
57
58    fn get_schema_hash(&self) -> Vec<u8> {
59        vec![SCHEMA_VERSION]
60    }
61
62    fn get_schema(&self) -> Arc<Schema> {
63        Arc::new(otel_spans_table_schema())
64    }
65
66    fn get_scan_output_ordering(&self) -> ScanOrdering {
67        ScanOrdering::Unordered
68    }
69}
70
71#[derive(Clone, Debug)]
72pub struct OtelSpansView {
73    view_set_name: Arc<String>,
74    view_instance_id: Arc<String>,
75    process_id: sqlx::types::Uuid,
76}
77
78impl OtelSpansView {
79    pub fn new(view_instance_id: &str) -> Result<Self> {
80        if view_instance_id == "global" {
81            anyhow::bail!("OtelSpansView does not support global view access");
82        }
83        let process_id = Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?;
84        Ok(Self {
85            view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
86            view_instance_id: Arc::new(view_instance_id.into()),
87            process_id,
88        })
89    }
90}
91
92#[async_trait]
93impl View for OtelSpansView {
94    fn get_view_set_name(&self) -> Arc<String> {
95        self.view_set_name.clone()
96    }
97
98    fn get_view_instance_id(&self) -> Arc<String> {
99        self.view_instance_id.clone()
100    }
101
102    async fn make_batch_partition_spec(
103        &self,
104        _lakehouse: Arc<LakehouseContext>,
105        _existing_partitions: Arc<PartitionCache>,
106        _insert_range: TimeRange,
107    ) -> Result<Arc<dyn PartitionSpec>> {
108        anyhow::bail!("OtelSpansView does not support batch partition specs");
109    }
110
111    fn get_file_schema_hash(&self) -> Vec<u8> {
112        vec![SCHEMA_VERSION]
113    }
114
115    fn get_file_schema(&self) -> Arc<Schema> {
116        Arc::new(otel_spans_table_schema())
117    }
118
119    #[span_fn]
120    async fn jit_update(
121        &self,
122        lakehouse: Arc<LakehouseContext>,
123        query_range: Option<TimeRange>,
124    ) -> Result<()> {
125        let process = Arc::new(
126            find_process(
127                &lakehouse.lake().db_pool,
128                &self.process_id,
129                &lakehouse.default_audience(),
130            )
131            .await
132            .with_context(|| "find_process")?,
133        );
134        let query_range =
135            query_range.unwrap_or_else(|| TimeRange::new(process.start_time, chrono::Utc::now()));
136
137        let mut block_processors: BlockProcessorMap = HashMap::new();
138        block_processors.insert(
139            FORMAT_OTLP_TRACES,
140            Arc::new(OtelSpansBlockProcessor {}) as Arc<dyn BlockProcessor>,
141        );
142        let block_processors = Arc::new(block_processors);
143
144        update_insert_time_jit_view(
145            lakehouse,
146            Arc::new(self.clone()),
147            process,
148            query_range,
149            "trace",
150            block_processors,
151        )
152        .await
153    }
154
155    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
156        // Dual-bound (start_time <= end AND end_time >= begin) so spans whose
157        // duration crosses the query window — i.e. start before `begin` or end
158        // after `end` — are still included. A `start_time BETWEEN begin AND end`
159        // filter would silently drop long-running spans that overlap the window.
160        Ok(vec![
161            Expr::BinaryExpr(BinaryExpr::new(
162                col("start_time").into(),
163                Operator::LtEq,
164                Expr::Literal(datetime_to_scalar(end), None).into(),
165            )),
166            Expr::BinaryExpr(BinaryExpr::new(
167                col("end_time").into(),
168                Operator::GtEq,
169                Expr::Literal(datetime_to_scalar(begin), None).into(),
170            )),
171        ])
172    }
173
174    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
175        Arc::new(NamedColumnsTimeBounds::new(
176            TIME_COLUMN.clone(),
177            END_TIME_COLUMN.clone(),
178        ))
179    }
180
181    fn get_update_group(&self) -> Option<i32> {
182        None // process-specific JIT view; no scheduled updates
183    }
184
185    fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
186        TimeDelta::hours(1)
187    }
188}