Skip to main content

micromegas_analytics/lakehouse/
net_spans_view.rs

1use super::{
2    blocks_view::BlocksView,
3    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
4    jit_partitions::{
5        BlockOrder, BucketSizing, JitPartitionConfig, blocks_insert_time_range,
6        generate_process_jit_partitions, group_contiguous_block_chains,
7        is_jit_partition_up_to_date,
8    },
9    lakehouse_context::LakehouseContext,
10    partition_cache::PartitionCache,
11    partition_source_data::{SourceDataBlocksInMemory, hash_to_object_count},
12    partitioned_execution_plan::ScanOrdering,
13    view::{PartitionSpec, View, ViewMetadata},
14    view_factory::{ViewFactory, ViewMaker},
15};
16use crate::{
17    lakehouse::write_partition::{PartitionRowSet, RetireMatch, write_partition_from_rows},
18    metadata::{StreamMetadata, find_process_with_latest_timing},
19    net_span_tree::make_net_span_tree,
20    net_spans_table::{NetSpanRecordBuilder, net_spans_table_schema},
21    response_writer::ResponseWriter,
22    time::{ConvertTicks, TimeRange, datetime_to_scalar, make_time_converter_from_latest_timing},
23};
24use anyhow::{Context, Result};
25use async_trait::async_trait;
26use chrono::{DateTime, TimeDelta, Utc};
27use datafusion::logical_expr::{BinaryExpr, Expr, Operator};
28use datafusion::{arrow::datatypes::Schema, logical_expr::expr_fn::col};
29use micromegas_ingestion::data_lake_connection::DataLakeConnection;
30use micromegas_telemetry::{blob_storage::BlobStorage, types::block::BlockMetadata};
31use micromegas_tracing::prelude::*;
32use std::sync::Arc;
33use uuid::Uuid;
34
35const VIEW_SET_NAME: &str = "net_spans";
36const SCHEMA_VERSION: u8 = 2;
37const NET_STREAM_TAG: &str = "net";
38
39lazy_static::lazy_static! {
40    static ref BEGIN_TIME_COLUMN: Arc<String> = Arc::new(String::from("begin_time"));
41    static ref END_TIME_COLUMN: Arc<String> = Arc::new(String::from("end_time"));
42}
43
44/// A `ViewMaker` for creating `NetSpansView` instances.
45#[derive(Debug)]
46pub struct NetSpansViewMaker {
47    view_factory: Arc<ViewFactory>,
48}
49
50impl NetSpansViewMaker {
51    pub fn new(view_factory: Arc<ViewFactory>) -> Self {
52        Self { view_factory }
53    }
54}
55
56impl ViewMaker for NetSpansViewMaker {
57    fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
58        Ok(Arc::new(NetSpansView::new(
59            view_instance_id,
60            self.view_factory.clone(),
61        )?))
62    }
63
64    fn get_schema_hash(&self) -> Vec<u8> {
65        vec![SCHEMA_VERSION]
66    }
67
68    fn get_schema(&self) -> Arc<Schema> {
69        Arc::new(net_spans_table_schema())
70    }
71
72    fn get_scan_output_ordering(&self) -> ScanOrdering {
73        ScanOrdering::Unordered
74    }
75}
76
77/// A view of network bandwidth spans (Connection / Object / Property / RPC).
78#[derive(Debug)]
79pub struct NetSpansView {
80    view_set_name: Arc<String>,
81    view_instance_id: Arc<String>,
82    process_id: sqlx::types::Uuid,
83    view_factory: Arc<ViewFactory>,
84}
85
86impl NetSpansView {
87    pub fn new(view_instance_id: &str, view_factory: Arc<ViewFactory>) -> Result<Self> {
88        if view_instance_id == "global" {
89            anyhow::bail!("NetSpansView does not support global view access");
90        }
91        let process_id = Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?;
92        Ok(Self {
93            view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
94            view_instance_id: Arc::new(view_instance_id.into()),
95            process_id,
96            view_factory,
97        })
98    }
99}
100
101#[span_fn]
102async fn append_net_span_tree(
103    record_builder: &mut NetSpanRecordBuilder,
104    convert_ticks: &ConvertTicks,
105    blocks: &[BlockMetadata],
106    blob_storage: Arc<BlobStorage>,
107    stream: &StreamMetadata,
108    process_id: Arc<String>,
109) -> Result<()> {
110    make_net_span_tree(
111        blocks,
112        record_builder,
113        blob_storage,
114        stream,
115        process_id,
116        convert_ticks.clone(),
117    )
118    .await
119    .with_context(|| "make_net_span_tree")
120}
121
122/// Writes a partition from a set of blocks.
123#[span_fn]
124async fn write_partition(
125    lake: Arc<DataLakeConnection>,
126    view_meta: ViewMetadata,
127    schema: Arc<Schema>,
128    convert_ticks: &ConvertTicks,
129    spec: &SourceDataBlocksInMemory,
130    process_id: Arc<String>,
131    same_run_ranges: &[TimeRange],
132) -> Result<()> {
133    let nb_events = hash_to_object_count(&spec.block_ids_hash)? as usize;
134    info!("nb_events: {nb_events}");
135    if spec.blocks.is_empty() {
136        anyhow::bail!("empty partition spec");
137    }
138    // NetSpansView is grouped under BlockOrder::EventTime (see jit_update below), so spec.blocks
139    // is event-time ordered, not insert-time ordered -- blocks_insert_time_range computes the real
140    // min/max rather than reading list endpoints.
141    let insert_range =
142        blocks_insert_time_range(&spec.blocks).with_context(|| "blocks_insert_time_range")?;
143
144    let (tx, rx) = tokio::sync::mpsc::channel(1);
145    let null_response_writer = Arc::new(ResponseWriter::new(None));
146    let join_handle = spawn_with_context(write_partition_from_rows(
147        lake.clone(),
148        view_meta,
149        schema,
150        insert_range,
151        spec.block_ids_hash.clone(),
152        None,
153        RetireMatch::Overlap,
154        same_run_ranges.to_vec(),
155        rx,
156        null_response_writer,
157    ));
158
159    let build_result: Result<Option<PartitionRowSet>> = async {
160        let mut record_builder = NetSpanRecordBuilder::with_capacity(nb_events / 2);
161        let stream = spec.blocks[0].stream.clone();
162        for b in &spec.blocks {
163            anyhow::ensure!(
164                b.stream.stream_id == stream.stream_id,
165                "net_spans partition contains multiple streams ({} and {}); expected one per process",
166                stream.stream_id,
167                b.stream.stream_id,
168            );
169        }
170        // One net span tree per unbroken chain of blocks; see `group_contiguous_block_chains`.
171        for chain in group_contiguous_block_chains(&spec.blocks) {
172            append_net_span_tree(
173                &mut record_builder,
174                convert_ticks,
175                &chain,
176                lake.blob_storage.clone(),
177                &stream,
178                process_id.clone(),
179            )
180            .await?;
181        }
182        // Real min/max over the blocks, not list endpoints: fallback only, since
183        // record_builder.get_time_range() normally supplies the actual row bounds below.
184        // `spec.blocks` is non-empty (checked above), so min/max are always `Some` -- surface a
185        // violation of that as an error rather than silently substituting tick 0, matching
186        // thread_spans_view's equivalent computation.
187        let rows_time_range = match record_builder.get_time_range() {
188            Some(range) => range,
189            None => {
190                let min_ticks = spec
191                    .blocks
192                    .iter()
193                    .map(|b| b.block.begin_ticks)
194                    .min()
195                    .with_context(|| "empty partition spec")?;
196                let max_ticks = spec
197                    .blocks
198                    .iter()
199                    .map(|b| b.block.end_ticks)
200                    .max()
201                    .with_context(|| "empty partition spec")?;
202                TimeRange::new(
203                    convert_ticks.delta_ticks_to_time(min_ticks),
204                    convert_ticks.delta_ticks_to_time(max_ticks),
205                )
206            }
207        };
208        let nb_rows = record_builder.len();
209        let rows = record_builder
210            .finish()
211            .with_context(|| "record_builder.finish()")?;
212        info!("writing {nb_rows} rows");
213        if nb_rows > 0 {
214            Ok(Some(PartitionRowSet {
215                rows_time_range,
216                rows,
217                max_sort_key_time: None,
218            }))
219        } else {
220            Ok(None)
221        }
222    }
223    .await;
224
225    match build_result {
226        Ok(Some(row_set)) => {
227            tx.send(Ok(row_set)).await?;
228            drop(tx);
229            join_handle.await??;
230            Ok(())
231        }
232        Ok(None) => {
233            drop(tx);
234            join_handle.await??;
235            Ok(())
236        }
237        Err(e) => {
238            warn!(
239                "aborting net-spans partition write for block {:?}: {e:?}",
240                spec.block_ids_hash
241            );
242            let _ = tx
243                .send(Err(anyhow::anyhow!("net-spans build aborted")))
244                .await;
245            drop(tx);
246            match join_handle.await {
247                Ok(Ok(())) => {}
248                Ok(Err(writer_err)) => {
249                    debug!("net-spans writer task error during abort: {writer_err:?}");
250                }
251                Err(join_err) => {
252                    warn!("net-spans writer task panicked during abort: {join_err:?}");
253                }
254            }
255            Err(e)
256        }
257    }
258}
259
260/// Rebuilds the partition if it's missing or out of date.
261///
262/// `same_run_ranges` accumulates the insert ranges this `jit_update` run has already handled --
263/// written, or found already up to date -- earlier in its loop; see `ThreadSpansView`'s
264/// `update_partition` and `RetireMatch::Overlap`'s docs for why.
265#[span_fn]
266async fn update_partition(
267    lake: Arc<DataLakeConnection>,
268    view_meta: ViewMetadata,
269    schema: Arc<Schema>,
270    convert_ticks: &ConvertTicks,
271    spec: &SourceDataBlocksInMemory,
272    process_id: Arc<String>,
273    same_run_ranges: &mut Vec<TimeRange>,
274) -> Result<()> {
275    let insert_range =
276        blocks_insert_time_range(&spec.blocks).with_context(|| "blocks_insert_time_range")?;
277    if is_jit_partition_up_to_date(&lake.db_pool, view_meta.clone(), spec).await? {
278        same_run_ranges.push(insert_range);
279        return Ok(());
280    }
281    write_partition(
282        lake,
283        view_meta,
284        schema,
285        convert_ticks,
286        spec,
287        process_id,
288        same_run_ranges.as_slice(),
289    )
290    .await
291    .with_context(|| "write_partition")?;
292    same_run_ranges.push(insert_range);
293    Ok(())
294}
295
296#[async_trait]
297impl View for NetSpansView {
298    fn get_view_set_name(&self) -> Arc<String> {
299        self.view_set_name.clone()
300    }
301
302    fn get_view_instance_id(&self) -> Arc<String> {
303        self.view_instance_id.clone()
304    }
305
306    async fn make_batch_partition_spec(
307        &self,
308        _lakehouse: Arc<LakehouseContext>,
309        _existing_partitions: Arc<PartitionCache>,
310        _insert_range: TimeRange,
311    ) -> Result<Arc<dyn PartitionSpec>> {
312        anyhow::bail!("NetSpansView does not support batch partition specs")
313    }
314
315    fn get_file_schema_hash(&self) -> Vec<u8> {
316        vec![SCHEMA_VERSION]
317    }
318
319    fn get_file_schema(&self) -> Arc<Schema> {
320        Arc::new(net_spans_table_schema())
321    }
322
323    #[span_fn]
324    async fn jit_update(
325        &self,
326        lakehouse: Arc<LakehouseContext>,
327        query_range: Option<TimeRange>,
328    ) -> Result<()> {
329        let (process, last_block_end_ticks, last_block_end_time) = find_process_with_latest_timing(
330            lakehouse.clone(),
331            self.view_factory.clone(),
332            &self.process_id,
333            query_range,
334        )
335        .await
336        .with_context(|| "find_process_with_latest_timing")?;
337
338        let process = Arc::new(process);
339        let query_range =
340            query_range.unwrap_or_else(|| TimeRange::new(process.start_time, last_block_end_time));
341
342        let convert_ticks = make_time_converter_from_latest_timing(
343            &process,
344            last_block_end_ticks,
345            last_block_end_time,
346        )
347        .with_context(|| "make_time_converter_from_latest_timing")?;
348
349        let blocks_view = BlocksView::new(lakehouse.default_audience())?;
350        // NetSpansView builds cross-block net span trees, so its JIT partitions must be
351        // event-time ordered, not insert-time ordered -- see BlockOrder::EventTime's docs. (Unlike
352        // ThreadSpansView, NetSpansView declares no ScanOrdering::Concatenated today, so it does
353        // not also need a monotonicity check -- see thread_spans_view.rs's
354        // ensure_begin_non_decreasing -- and its PartitionRowSet always carries
355        // max_sort_key_time: None. If it ever does declare that ordering, it must first add an
356        // ensure_begin_non_decreasing equivalent and populate max_sort_key_time, per
357        // tasks/completed/thread_spans_segment_boundary_overlap_plan.md.)
358        let config = JitPartitionConfig {
359            block_order: BlockOrder::EventTime,
360            bucket_sizing: BucketSizing::Fixed(TimeDelta::hours(1)),
361            ..Default::default()
362        };
363        let all_partitions = generate_process_jit_partitions(
364            &config,
365            lakehouse.clone(),
366            &blocks_view,
367            &query_range,
368            process.clone(),
369            NET_STREAM_TAG,
370        )
371        .await
372        .with_context(|| "generate_process_jit_partitions")?
373        .into_iter()
374        .flat_map(|bucket| bucket.specs)
375        .collect::<Vec<_>>();
376
377        let process_id_str = Arc::new(self.process_id.to_string());
378        // Accumulates this run's own already-handled insert ranges across the loop, so a later
379        // partition's retire step never retires an earlier one from this same run -- see
380        // `update_partition`'s and `RetireMatch::Overlap`'s docs.
381        let mut same_run_ranges: Vec<TimeRange> = Vec::new();
382        for part in &all_partitions {
383            update_partition(
384                lakehouse.lake().clone(),
385                ViewMetadata {
386                    view_set_name: self.get_view_set_name(),
387                    view_instance_id: self.get_view_instance_id(),
388                    file_schema_hash: self.get_file_schema_hash(),
389                },
390                self.get_file_schema(),
391                &convert_ticks,
392                part,
393                process_id_str.clone(),
394                &mut same_run_ranges,
395            )
396            .await
397            .with_context(|| "update_partition")?;
398        }
399        Ok(())
400    }
401
402    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
403        Ok(vec![
404            Expr::BinaryExpr(BinaryExpr::new(
405                col("begin_time").into(),
406                Operator::LtEq,
407                Expr::Literal(datetime_to_scalar(end), None).into(),
408            )),
409            Expr::BinaryExpr(BinaryExpr::new(
410                col("end_time").into(),
411                Operator::GtEq,
412                Expr::Literal(datetime_to_scalar(begin), None).into(),
413            )),
414        ])
415    }
416
417    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
418        Arc::new(NamedColumnsTimeBounds::new(
419            BEGIN_TIME_COLUMN.clone(),
420            END_TIME_COLUMN.clone(),
421        ))
422    }
423
424    fn get_update_group(&self) -> Option<i32> {
425        None
426    }
427}