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_stream_jit_partitions, group_contiguous_block_chains, is_jit_partition_up_to_date,
7 },
8 lakehouse_context::LakehouseContext,
9 partition_cache::PartitionCache,
10 partition_source_data::{SourceDataBlocksInMemory, hash_to_object_count},
11 partitioned_execution_plan::{OrderingBounds, ScanOrdering},
12 view::{PartitionSpec, ScanSortColumn, View, ViewMetadata},
13 view_factory::{ViewFactory, ViewMaker},
14};
15use crate::{
16 call_tree::make_call_tree,
17 dfext::typed_column::typed_column_by_name,
18 lakehouse::write_partition::{PartitionRowSet, RetireMatch, write_partition_from_rows},
19 metadata::{find_process_with_latest_timing, find_stream_from_view},
20 response_writer::ResponseWriter,
21 span_table::{SpanRecordBuilder, get_spans_schema},
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::arrow::array::TimestampNanosecondArray;
28use datafusion::arrow::record_batch::RecordBatch;
29use datafusion::logical_expr::{BinaryExpr, Expr, Operator};
30use datafusion::{arrow::datatypes::Schema, logical_expr::expr_fn::col};
31use micromegas_ingestion::data_lake_connection::DataLakeConnection;
32use micromegas_telemetry::{blob_storage::BlobStorage, types::block::BlockMetadata};
33use micromegas_tracing::prelude::*;
34use std::sync::Arc;
35use uuid::Uuid;
36
37const VIEW_SET_NAME: &str = "thread_spans";
38const SCHEMA_VERSION: u8 = 4;
39lazy_static::lazy_static! {
40 static ref MIN_TIME_COLUMN: Arc<String> = Arc::new( String::from("begin"));
41 static ref MAX_TIME_COLUMN: Arc<String> = Arc::new( String::from("end"));
42}
43
44#[derive(Debug)]
46pub struct ThreadSpansViewMaker {
47 view_factory: Arc<ViewFactory>,
48}
49
50impl ThreadSpansViewMaker {
51 pub fn new(view_factory: Arc<ViewFactory>) -> Self {
52 Self { view_factory }
53 }
54}
55
56fn thread_spans_scan_ordering() -> ScanOrdering {
58 ScanOrdering::Concatenated {
59 columns: vec![ScanSortColumn {
60 column: MIN_TIME_COLUMN.clone(),
61 descending: false,
62 }],
63 bounds: OrderingBounds::EventTime,
64 }
65}
66
67impl ViewMaker for ThreadSpansViewMaker {
68 fn make_view(&self, stream_id: &str) -> Result<Arc<dyn View>> {
69 Ok(Arc::new(ThreadSpansView::new(
70 stream_id,
71 self.view_factory.clone(),
72 )?))
73 }
74
75 fn get_schema_hash(&self) -> Vec<u8> {
76 vec![SCHEMA_VERSION]
77 }
78
79 fn get_schema(&self) -> Arc<Schema> {
80 Arc::new(get_spans_schema())
81 }
82
83 fn get_scan_output_ordering(&self) -> ScanOrdering {
84 thread_spans_scan_ordering()
85 }
86}
87
88#[derive(Debug)]
90pub struct ThreadSpansView {
91 view_set_name: Arc<String>,
92 view_instance_id: Arc<String>,
93 stream_id: sqlx::types::Uuid,
94 view_factory: Arc<ViewFactory>,
95}
96
97impl ThreadSpansView {
98 pub fn new(view_instance_id: &str, view_factory: Arc<ViewFactory>) -> Result<Self> {
99 if view_instance_id == "global" {
100 anyhow::bail!("the global view is not implemented for thread spans");
101 }
102
103 Ok(Self {
104 view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
105 view_instance_id: Arc::new(String::from(view_instance_id)),
106 stream_id: Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?,
107 view_factory,
108 })
109 }
110}
111
112#[span_fn]
113async fn append_call_tree(
114 record_builder: &mut SpanRecordBuilder,
115 convert_ticks: &ConvertTicks,
116 blocks: &[BlockMetadata],
117 blob_storage: Arc<BlobStorage>,
118 stream: &crate::metadata::StreamMetadata,
119) -> Result<()> {
120 let call_tree = make_call_tree(
121 blocks,
122 convert_ticks.delta_ticks_to_ns(blocks[0].begin_ticks),
123 convert_ticks.delta_ticks_to_ns(blocks[blocks.len() - 1].end_ticks),
124 None,
125 blob_storage,
126 convert_ticks.clone(),
127 stream,
128 )
129 .await
130 .with_context(|| "make_call_tree")?;
131 record_builder
132 .append_call_tree(&call_tree)
133 .with_context(|| "adding call tree to span record builder")?;
134 Ok(())
135}
136
137pub fn ensure_begin_non_decreasing(stream_id: &str, batch: &RecordBatch) -> Result<()> {
147 let begins: &TimestampNanosecondArray = typed_column_by_name(batch, "begin")?;
148 let mut previous: Option<i64> = None;
149 for i in 0..begins.len() {
150 let begin = begins.value(i);
151 if let Some(prev) = previous
152 && begin < prev
153 {
154 let msg = format!(
155 "thread_spans stream {stream_id}: begin regressed at row {i}: {begin} < {prev}"
156 );
157 error!("{msg}");
158 anyhow::bail!(msg);
159 }
160 previous = Some(begin);
161 }
162 Ok(())
163}
164
165#[span_fn]
167async fn write_partition(
168 lake: Arc<DataLakeConnection>,
169 view_meta: ViewMetadata,
170 schema: Arc<Schema>,
171 convert_ticks: &ConvertTicks,
172 spec: &SourceDataBlocksInMemory,
173 same_run_ranges: &[TimeRange],
174) -> Result<()> {
175 let nb_events = hash_to_object_count(&spec.block_ids_hash)? as usize;
176 info!("nb_events: {nb_events}");
177 if spec.blocks.is_empty() {
178 anyhow::bail!("empty partition spec");
179 }
180 let stream_id = spec.blocks[0].stream.stream_id.to_string();
184 let insert_range =
185 blocks_insert_time_range(&spec.blocks).with_context(|| "blocks_insert_time_range")?;
186
187 let (tx, rx) = tokio::sync::mpsc::channel(1);
188 let null_response_writer = Arc::new(ResponseWriter::new(None));
189 let join_handle = spawn_with_context(write_partition_from_rows(
190 lake.clone(),
191 view_meta,
192 schema,
193 insert_range,
194 spec.block_ids_hash.clone(),
195 None,
196 RetireMatch::Overlap,
197 same_run_ranges.to_vec(),
198 rx,
199 null_response_writer,
200 ));
201
202 let build_result: Result<PartitionRowSet> = async {
203 let mut record_builder = SpanRecordBuilder::with_capacity(nb_events / 2);
204 for chain in group_contiguous_block_chains(&spec.blocks) {
207 append_call_tree(
208 &mut record_builder,
209 convert_ticks,
210 &chain,
211 lake.blob_storage.clone(),
212 &spec.blocks[0].stream,
213 )
214 .await?;
215 }
216 let min_ticks = spec
217 .blocks
218 .iter()
219 .map(|b| b.block.begin_ticks)
220 .min()
221 .with_context(|| "empty partition spec")?;
222 let max_ticks = spec
223 .blocks
224 .iter()
225 .map(|b| b.block.end_ticks)
226 .max()
227 .with_context(|| "empty partition spec")?;
228 let min_time_row = convert_ticks.delta_ticks_to_time(min_ticks);
229 let max_time_row = convert_ticks.delta_ticks_to_time(max_ticks);
230 let rows = record_builder
231 .finish()
232 .with_context(|| "record_builder.finish()")?;
233 ensure_begin_non_decreasing(&stream_id, &rows)
234 .with_context(|| "ensure_begin_non_decreasing")?;
235 info!("writing {} rows", rows.num_rows());
236 let max_sort_key_time = if rows.num_rows() == 0 {
243 None
244 } else {
245 let begins: &TimestampNanosecondArray = typed_column_by_name(&rows, "begin")?;
246 Some(DateTime::from_timestamp_nanos(
247 begins.value(begins.len() - 1),
248 ))
249 };
250 Ok(PartitionRowSet {
251 rows_time_range: TimeRange::new(min_time_row, max_time_row),
252 rows,
253 max_sort_key_time,
254 })
255 }
256 .await;
257
258 match build_result {
259 Ok(row_set) => {
260 tx.send(Ok(row_set)).await?;
261 drop(tx);
262 join_handle.await??;
263 Ok(())
264 }
265 Err(e) => {
266 warn!(
267 "aborting thread-spans partition write for block {:?}: {e:?}",
268 spec.block_ids_hash
269 );
270 let _ = tx
271 .send(Err(anyhow::anyhow!("thread-spans build aborted")))
272 .await;
273 drop(tx);
274 match join_handle.await {
275 Ok(Ok(())) => {}
276 Ok(Err(writer_err)) => {
277 debug!("thread-spans writer task error during abort: {writer_err:?}");
278 }
279 Err(join_err) => {
280 warn!("thread-spans writer task panicked during abort: {join_err:?}");
281 }
282 }
283 Err(e)
284 }
285 }
286}
287#[span_fn]
300pub async fn update_partition(
301 lake: Arc<DataLakeConnection>,
302 view_meta: ViewMetadata,
303 schema: Arc<Schema>,
304 convert_ticks: &ConvertTicks,
305 spec: &SourceDataBlocksInMemory,
306 same_run_ranges: &mut Vec<TimeRange>,
307) -> Result<()> {
308 let insert_range =
309 blocks_insert_time_range(&spec.blocks).with_context(|| "blocks_insert_time_range")?;
310 if is_jit_partition_up_to_date(&lake.db_pool, view_meta.clone(), spec).await? {
311 same_run_ranges.push(insert_range);
312 return Ok(());
313 }
314 write_partition(
315 lake,
316 view_meta,
317 schema,
318 convert_ticks,
319 spec,
320 same_run_ranges.as_slice(),
321 )
322 .await
323 .with_context(|| "write_partition")?;
324 same_run_ranges.push(insert_range);
325
326 Ok(())
327}
328
329#[async_trait]
330impl View for ThreadSpansView {
331 fn get_view_set_name(&self) -> Arc<String> {
332 self.view_set_name.clone()
333 }
334
335 fn get_view_instance_id(&self) -> Arc<String> {
336 self.view_instance_id.clone()
337 }
338
339 async fn make_batch_partition_spec(
340 &self,
341 _lakehouse: Arc<LakehouseContext>,
342 _existing_partitions: Arc<PartitionCache>,
343 _insert_range: TimeRange,
344 ) -> Result<Arc<dyn PartitionSpec>> {
345 anyhow::bail!("not implemented")
346 }
347
348 fn get_file_schema_hash(&self) -> Vec<u8> {
349 vec![SCHEMA_VERSION]
350 }
351
352 fn get_file_schema(&self) -> Arc<Schema> {
353 Arc::new(get_spans_schema())
354 }
355
356 #[span_fn]
357 async fn jit_update(
358 &self,
359 lakehouse: Arc<LakehouseContext>,
360 query_range: Option<TimeRange>,
361 ) -> Result<()> {
362 let Some(query_range) = query_range else {
363 anyhow::bail!("query range mandatory for thread spans view");
364 };
365 let stream = Arc::new(
366 find_stream_from_view(
367 lakehouse.clone(),
368 self.view_factory.clone(),
369 &self.stream_id,
370 None,
371 )
372 .await
373 .with_context(|| "find_stream_from_view")?,
374 );
375 let (process, last_block_end_ticks, last_block_end_time) = find_process_with_latest_timing(
376 lakehouse.clone(),
377 self.view_factory.clone(),
378 &stream.process_id,
379 None,
380 )
381 .await
382 .with_context(|| "find_process_with_latest_timing")?;
383 let process = Arc::new(process);
384 let convert_ticks = make_time_converter_from_latest_timing(
385 &process,
386 last_block_end_ticks,
387 last_block_end_time,
388 )
389 .with_context(|| "make_time_converter_from_latest_timing")?;
390 let blocks_view = BlocksView::new(lakehouse.default_audience())?;
391 let config = JitPartitionConfig {
395 block_order: BlockOrder::EventTime,
396 bucket_sizing: BucketSizing::Fixed(TimeDelta::hours(1)),
397 ..Default::default()
398 };
399 let partitions = generate_stream_jit_partitions(
400 &config,
401 lakehouse.clone(),
402 &blocks_view,
403 &query_range,
404 stream.clone(),
405 process.clone(),
406 )
407 .await
408 .with_context(|| "generate_stream_jit_partitions")?;
409 let mut same_run_ranges: Vec<TimeRange> = Vec::new();
413 for part in &partitions {
414 update_partition(
415 lakehouse.lake().clone(),
416 ViewMetadata {
417 view_set_name: self.get_view_set_name(),
418 view_instance_id: self.get_view_instance_id(),
419 file_schema_hash: self.get_file_schema_hash(),
420 },
421 self.get_file_schema(),
422 &convert_ticks,
423 part,
424 &mut same_run_ranges,
425 )
426 .await
427 .with_context(|| "update_partition")?;
428 }
429 Ok(())
430 }
431
432 fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
433 Ok(vec![
434 Expr::BinaryExpr(BinaryExpr::new(
435 col("begin").into(),
436 Operator::LtEq,
437 Expr::Literal(datetime_to_scalar(end), None).into(),
438 )),
439 Expr::BinaryExpr(BinaryExpr::new(
440 col("end").into(),
441 Operator::GtEq,
442 Expr::Literal(datetime_to_scalar(begin), None).into(),
443 )),
444 ])
445 }
446
447 fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
448 Arc::new(NamedColumnsTimeBounds::new(
449 MIN_TIME_COLUMN.clone(),
450 MAX_TIME_COLUMN.clone(),
451 ))
452 }
453
454 fn get_update_group(&self) -> Option<i32> {
455 None
456 }
457
458 fn get_scan_output_ordering(&self) -> ScanOrdering {
459 thread_spans_scan_ordering()
460 }
461}