1use super::{
2 audience_guard::{AudienceGuard, Authorized, IdKind},
3 lakehouse_context::LakehouseContext,
4 partition_cache::QueryPartitionProvider,
5 process_streams::get_process_thread_list,
6 query::SessionRange,
7 session_configurator::NoOpSessionConfigurator,
8 view_factory::ViewFactory,
9};
10use crate::{dfext::expressions::exp_to_string, span_table::get_spans_schema};
11use async_stream::try_stream;
12use datafusion::{
13 arrow::{
14 array::{ArrayRef, RecordBatch, StringDictionaryBuilder},
15 datatypes::{DataType, Field, Int32Type, Schema, SchemaRef},
16 },
17 catalog::{Session, TableFunctionArgs, TableFunctionImpl, TableProvider},
18 common::{Result as DFResult, plan_err},
19 error::DataFusionError,
20 execution::{SendableRecordBatchStream, TaskContext},
21 logical_expr::{Expr, TableType},
22 physical_expr::EquivalenceProperties,
23 physical_plan::{
24 DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
25 execution_plan::{Boundedness, EmissionType},
26 limit::GlobalLimitExec,
27 projection::ProjectionExec,
28 stream::RecordBatchStreamAdapter,
29 },
30};
31use futures::{StreamExt, TryStreamExt};
32use micromegas_tracing::prelude::*;
33use std::{
34 fmt::{self, Debug, Formatter},
35 sync::Arc,
36};
37use uuid::Uuid;
38
39#[derive(Debug, Clone, Copy)]
41pub enum SpanTypes {
42 Thread,
43 Async,
44 Both,
45}
46
47fn output_schema() -> SchemaRef {
48 let mut fields = vec![
49 Field::new(
50 "stream_id",
51 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
52 false,
53 ),
54 Field::new(
55 "thread_name",
56 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
57 false,
58 ),
59 ];
60 fields.extend(get_spans_schema().fields.iter().map(|f| f.as_ref().clone()));
61 Arc::new(Schema::new(fields))
62}
63
64fn augment_batch(
65 batch: &RecordBatch,
66 schema: SchemaRef,
67 stream_id: &str,
68 thread_name: &str,
69) -> DFResult<RecordBatch> {
70 let n = batch.num_rows();
71 let mut stream_id_builder = StringDictionaryBuilder::<Int32Type>::new();
72 let mut thread_name_builder = StringDictionaryBuilder::<Int32Type>::new();
73 stream_id_builder.append_values(stream_id, n);
74 thread_name_builder.append_values(thread_name, n);
75 let mut columns: Vec<ArrayRef> = vec![
76 Arc::new(stream_id_builder.finish()),
77 Arc::new(thread_name_builder.finish()),
78 ];
79 columns.extend(batch.columns().iter().cloned());
80 RecordBatch::try_new(schema, columns).map_err(Into::into)
81}
82
83#[derive(Debug)]
86pub struct ProcessSpansTableFunction {
87 lakehouse: Arc<LakehouseContext>,
88 view_factory: Arc<ViewFactory>,
89 part_provider: Arc<dyn QueryPartitionProvider>,
90 query_range: SessionRange,
91 guard: Arc<AudienceGuard>,
92}
93
94impl ProcessSpansTableFunction {
95 pub fn new(
96 lakehouse: Arc<LakehouseContext>,
97 view_factory: Arc<ViewFactory>,
98 part_provider: Arc<dyn QueryPartitionProvider>,
99 query_range: SessionRange,
100 guard: Arc<AudienceGuard>,
101 ) -> Self {
102 Self {
103 lakehouse,
104 view_factory,
105 part_provider,
106 query_range,
107 guard,
108 }
109 }
110}
111
112impl TableFunctionImpl for ProcessSpansTableFunction {
113 #[span_fn]
114 fn call_with_args(
115 &self,
116 args: TableFunctionArgs,
117 ) -> datafusion::error::Result<Arc<dyn TableProvider>> {
118 let exprs = args.exprs();
119 let arg1 = exprs.first().map(exp_to_string);
120 let Some(Ok(process_id_arg)) = arg1 else {
121 return plan_err!(
122 "First argument to process_spans must be a string (the process ID), given {:?}",
123 arg1
124 );
125 };
126 let Ok(process_uuid) = Uuid::parse_str(&process_id_arg) else {
131 return plan_err!(
132 "First argument to process_spans must be a valid UUID (the process ID), given '{process_id_arg}'"
133 );
134 };
135 let process_id = process_uuid.hyphenated().to_string();
136
137 let arg2 = exprs.get(1).map(exp_to_string);
138 let Some(Ok(span_types_str)) = arg2 else {
139 return plan_err!(
140 "Second argument to process_spans must be a string ('thread', 'async', or 'both'), given {:?}",
141 arg2
142 );
143 };
144
145 let span_types = match span_types_str.as_str() {
146 "thread" => SpanTypes::Thread,
147 "async" => SpanTypes::Async,
148 "both" => SpanTypes::Both,
149 _ => {
150 return plan_err!(
151 "span_types must be 'thread', 'async', or 'both', given: {span_types_str}"
152 );
153 }
154 };
155
156 let schema = output_schema();
157 let execution_plan = Arc::new(ProcessSpansExecutionPlan::new(
158 schema,
159 process_id,
160 process_uuid,
161 span_types,
162 self.query_range,
163 self.lakehouse.clone(),
164 self.view_factory.clone(),
165 self.part_provider.clone(),
166 self.guard.clone(),
167 ));
168
169 Ok(Arc::new(ProcessSpansTableProvider { execution_plan }))
170 }
171}
172
173pub struct ProcessSpansExecutionPlan {
176 schema: SchemaRef,
177 process_id: String,
178 process_uuid: Uuid,
179 span_types: SpanTypes,
180 query_range: SessionRange,
181 lakehouse: Arc<LakehouseContext>,
182 view_factory: Arc<ViewFactory>,
183 part_provider: Arc<dyn QueryPartitionProvider>,
184 guard: Arc<AudienceGuard>,
185 authorized: Option<Authorized>,
190 properties: Arc<PlanProperties>,
191}
192
193impl ProcessSpansExecutionPlan {
194 #[allow(clippy::too_many_arguments)]
195 fn new(
196 schema: SchemaRef,
197 process_id: String,
198 process_uuid: Uuid,
199 span_types: SpanTypes,
200 query_range: SessionRange,
201 lakehouse: Arc<LakehouseContext>,
202 view_factory: Arc<ViewFactory>,
203 part_provider: Arc<dyn QueryPartitionProvider>,
204 guard: Arc<AudienceGuard>,
205 ) -> Self {
206 let properties = PlanProperties::new(
207 EquivalenceProperties::new(schema.clone()),
208 Partitioning::UnknownPartitioning(1),
209 EmissionType::Final,
210 Boundedness::Bounded,
211 );
212 Self {
213 schema,
214 process_id,
215 process_uuid,
216 span_types,
217 query_range,
218 lakehouse,
219 view_factory,
220 part_provider,
221 guard,
222 authorized: None,
223 properties: Arc::new(properties),
224 }
225 }
226
227 fn with_authorized(&self, authorized: Authorized) -> Self {
232 Self {
233 schema: self.schema.clone(),
234 process_id: self.process_id.clone(),
235 process_uuid: self.process_uuid,
236 span_types: self.span_types,
237 query_range: self.query_range,
238 lakehouse: self.lakehouse.clone(),
239 view_factory: self.view_factory.clone(),
240 part_provider: self.part_provider.clone(),
241 guard: self.guard.clone(),
242 authorized: Some(authorized),
243 properties: self.properties.clone(),
244 }
245 }
246}
247
248impl Debug for ProcessSpansExecutionPlan {
249 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
250 f.debug_struct("ProcessSpansExecutionPlan")
251 .field("process_id", &self.process_id)
252 .field("span_types", &self.span_types)
253 .finish()
254 }
255}
256
257impl DisplayAs for ProcessSpansExecutionPlan {
258 fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
259 write!(
260 f,
261 "ProcessSpansExecutionPlan: process_id={}, span_types={:?}",
262 self.process_id, self.span_types
263 )
264 }
265}
266
267impl ExecutionPlan for ProcessSpansExecutionPlan {
268 fn name(&self) -> &str {
269 "ProcessSpansExecutionPlan"
270 }
271
272 fn schema(&self) -> SchemaRef {
273 self.schema.clone()
274 }
275
276 fn properties(&self) -> &Arc<PlanProperties> {
277 &self.properties
278 }
279
280 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
281 vec![]
282 }
283
284 fn with_new_children(
285 self: Arc<Self>,
286 _children: Vec<Arc<dyn ExecutionPlan>>,
287 ) -> DFResult<Arc<dyn ExecutionPlan>> {
288 Ok(self)
289 }
290
291 #[span_fn]
292 fn execute(
293 &self,
294 _partition: usize,
295 _context: Arc<TaskContext>,
296 ) -> DFResult<SendableRecordBatchStream> {
297 let schema = self.schema.clone();
298 let stream_schema = schema.clone();
299 let process_id = self.process_id.clone();
300 let span_types = self.span_types;
301 let query_range = self.query_range;
302 let lakehouse = self.lakehouse.clone();
303 let view_factory = self.view_factory.clone();
304 let part_provider = self.part_provider.clone();
305 let Some(authorized) = &self.authorized else {
308 return Err(DataFusionError::Internal(
309 "process_spans: unauthorized plan (no witness from scan)".into(),
310 ));
311 };
312 let caller = authorized.internal_caller();
313
314 let record_batch_stream = try_stream! {
315 let schema = stream_schema;
316 let ctx = super::query::make_session_context(
322 lakehouse,
323 part_provider,
324 query_range,
325 view_factory,
326 Arc::new(NoOpSessionConfigurator),
327 caller,
328 )
329 .await
330 .map_err(|e| datafusion::error::DataFusionError::Internal(
331 format!("Failed to create session context: {e}"),
332 ))?;
333
334 if matches!(span_types, SpanTypes::Thread | SpanTypes::Both) {
336 let threads = get_process_thread_list(&process_id, &ctx)
337 .await
338 .map_err(|e| datafusion::error::DataFusionError::Internal(
339 format!("Failed to get thread list: {e}"),
340 ))?;
341
342 let max_concurrent = std::thread::available_parallelism()
343 .map(|n| n.get())
344 .unwrap_or(4);
345
346 let queries: Vec<(String, String, String)> = threads
347 .iter()
348 .map(|(stream_id, _thread_id, display_name)| {
349 let sql = format!(
350 "SELECT * FROM view_instance('thread_spans', '{stream_id}')"
351 );
352 (stream_id.clone(), display_name.clone(), sql)
353 })
354 .collect();
355
356 let stream_results: Vec<(String, String, SendableRecordBatchStream)> =
357 futures::stream::iter(queries)
358 .map(|(stream_id, thread_name, sql)| {
359 let ctx = ctx.clone();
360 async move {
361 spawn_with_context(async move {
362 let df = ctx.sql(&sql).await?;
363 let s = df.execute_stream().await?;
364 Ok::<_, anyhow::Error>((stream_id, thread_name, s))
365 })
366 .await?
367 }
368 })
369 .buffered(max_concurrent)
370 .try_collect()
371 .await
372 .map_err(|e| datafusion::error::DataFusionError::Internal(
373 format!("Failed to query thread spans: {e}"),
374 ))?;
375
376 for (stream_id, thread_name, mut data_stream) in stream_results {
377 while let Some(batch) = data_stream.try_next().await? {
378 let augmented = augment_batch(&batch, schema.clone(), &stream_id, &thread_name)?;
379 yield augmented;
380 }
381 }
382 }
383
384 if matches!(span_types, SpanTypes::Async | SpanTypes::Both) {
386 let async_sql = format!(
387 "SELECT \
388 b.span_id as id, \
389 b.parent_span_id as parent, \
390 b.depth, \
391 b.hash, \
392 b.time as \"begin\", \
393 e.time as \"end\", \
394 arrow_cast(e.time, 'Int64') - arrow_cast(b.time, 'Int64') as duration, \
395 b.name, \
396 b.target, \
397 b.filename, \
398 b.line, \
399 e.properties \
400 FROM (SELECT * FROM view_instance('async_events', '{process_id}') \
401 WHERE event_type = 'begin') b \
402 INNER JOIN (SELECT * FROM view_instance('async_events', '{process_id}') \
403 WHERE event_type = 'end') e \
404 ON b.span_id = e.span_id \
405 WHERE b.time < e.time \
406 ORDER BY b.time"
407 );
408
409 let df = ctx.sql(&async_sql).await
410 .map_err(|e| datafusion::error::DataFusionError::Internal(
411 format!("Failed to query async spans: {e}"),
412 ))?;
413 let mut async_stream = df.execute_stream().await
414 .map_err(|e| datafusion::error::DataFusionError::Internal(
415 format!("Failed to execute async spans stream: {e}"),
416 ))?;
417
418 while let Some(batch) = async_stream.try_next().await? {
419 let augmented = augment_batch(&batch, schema.clone(), "", "async")?;
420 yield augmented;
421 }
422 }
423 };
424
425 Ok(Box::pin(RecordBatchStreamAdapter::new(
426 schema,
427 record_batch_stream,
428 )))
429 }
430
431 fn apply_expressions(
432 &self,
433 _f: &mut dyn FnMut(
434 &Arc<dyn datafusion::physical_plan::PhysicalExpr>,
435 ) -> DFResult<datafusion::common::tree_node::TreeNodeRecursion>,
436 ) -> DFResult<datafusion::common::tree_node::TreeNodeRecursion> {
437 Ok(datafusion::common::tree_node::TreeNodeRecursion::Continue)
438 }
439}
440
441#[derive(Debug)]
444struct ProcessSpansTableProvider {
445 execution_plan: Arc<ProcessSpansExecutionPlan>,
446}
447
448#[async_trait::async_trait]
449impl TableProvider for ProcessSpansTableProvider {
450 fn schema(&self) -> SchemaRef {
451 self.execution_plan.schema()
452 }
453
454 fn table_type(&self) -> TableType {
455 TableType::Base
456 }
457
458 async fn scan(
459 &self,
460 _state: &dyn Session,
461 projection: Option<&Vec<usize>>,
462 _filters: &[Expr],
463 limit: Option<usize>,
464 ) -> DFResult<Arc<dyn ExecutionPlan>> {
465 let authorized = self
466 .execution_plan
467 .guard
468 .authorize(
469 self.execution_plan.process_uuid,
470 IdKind::Process,
471 "process_spans",
472 )
473 .await?;
474 let mut plan: Arc<dyn ExecutionPlan> =
475 Arc::new(self.execution_plan.with_authorized(authorized));
476 if let Some(projection) = projection {
477 let schema = plan.schema();
478 let projected_exprs: Vec<(Arc<dyn datafusion::physical_expr::PhysicalExpr>, String)> =
479 projection
480 .iter()
481 .map(|&i| {
482 let name = schema.field(i).name().clone();
483 let expr = Arc::new(datafusion::physical_expr::expressions::Column::new(
484 &name, i,
485 ))
486 as Arc<dyn datafusion::physical_expr::PhysicalExpr>;
487 (expr, name)
488 })
489 .collect();
490 plan = Arc::new(ProjectionExec::try_new(projected_exprs, plan)?);
491 }
492 if let Some(fetch) = limit {
493 plan = Arc::new(GlobalLimitExec::new(plan, 0, Some(fetch)));
494 }
495 Ok(plan)
496 }
497}