Skip to main content

micromegas_analytics/lakehouse/
perfetto_trace_execution_plan.rs

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    read_scope::CallerContext,
8    session_configurator::NoOpSessionConfigurator,
9    view_factory::ViewFactory,
10};
11use crate::dfext::{
12    string_column_accessor::string_column_by_name, typed_column::typed_column_by_name,
13};
14use crate::time::TimeRange;
15use async_stream::stream;
16use datafusion::{
17    arrow::{
18        array::{RecordBatch, TimestampNanosecondArray, UInt32Array},
19        datatypes::SchemaRef,
20    },
21    catalog::{Session, TableProvider},
22    common::Result as DFResult,
23    error::DataFusionError,
24    execution::{SendableRecordBatchStream, TaskContext},
25    logical_expr::{Expr, TableType},
26    physical_expr::EquivalenceProperties,
27    physical_plan::{
28        DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
29        execution_plan::{Boundedness, EmissionType},
30        limit::GlobalLimitExec,
31        stream::RecordBatchStreamAdapter,
32    },
33};
34use futures::{StreamExt, TryStreamExt, stream};
35use micromegas_perfetto::{chunk_sender::ChunkSender, streaming_writer::PerfettoWriter};
36use micromegas_tracing::prelude::*;
37use std::{
38    fmt::{self, Debug, Formatter},
39    sync::Arc,
40};
41use uuid::Uuid;
42
43pub use super::process_spans_table_function::SpanTypes;
44
45/// Marker error for a process that could not be found. This is a caller error (the
46/// requested process id doesn't exist), not a server-side failure, so it must stay
47/// classified as `DataFusionError::Execution` while every other failure inside
48/// `generate_streaming_perfetto_trace` (session context, object store, DB, parquet
49/// reads, ...) is a genuine internal failure.
50#[derive(Debug, thiserror::Error)]
51#[error("Process {0} not found")]
52struct ProcessNotFoundError(String);
53
54/// Execution plan that generates Perfetto trace chunks
55pub struct PerfettoTraceExecutionPlan {
56    schema: SchemaRef,
57    process_id: String,
58    process_uuid: Uuid,
59    span_types: SpanTypes,
60    time_range: TimeRange,
61    lakehouse: Arc<LakehouseContext>,
62    view_factory: Arc<ViewFactory>,
63    part_provider: Arc<dyn QueryPartitionProvider>,
64    guard: Arc<AudienceGuard>,
65    /// Set only by [`PerfettoTraceTableProvider::scan`], after `AudienceGuard::authorize`
66    /// succeeds -- see `process_spans_table_function.rs`'s identical field for the full
67    /// rationale (fail-closed by construction, not by convention).
68    authorized: Option<Authorized>,
69    properties: Arc<PlanProperties>,
70}
71
72impl PerfettoTraceExecutionPlan {
73    #[allow(clippy::too_many_arguments)]
74    pub(crate) fn new(
75        schema: SchemaRef,
76        process_id: String,
77        process_uuid: Uuid,
78        span_types: SpanTypes,
79        time_range: TimeRange,
80        lakehouse: Arc<LakehouseContext>,
81        view_factory: Arc<ViewFactory>,
82        part_provider: Arc<dyn QueryPartitionProvider>,
83        guard: Arc<AudienceGuard>,
84    ) -> Self {
85        let properties = PlanProperties::new(
86            EquivalenceProperties::new(schema.clone()),
87            Partitioning::UnknownPartitioning(1),
88            EmissionType::Final,
89            Boundedness::Bounded,
90        );
91
92        Self {
93            schema,
94            process_id,
95            process_uuid,
96            span_types,
97            time_range,
98            lakehouse,
99            view_factory,
100            part_provider,
101            guard,
102            authorized: None,
103            properties: Arc::new(properties),
104        }
105    }
106
107    /// See `ProcessSpansExecutionPlan::with_authorized`'s identical doc comment.
108    fn with_authorized(&self, authorized: Authorized) -> Self {
109        Self {
110            schema: self.schema.clone(),
111            process_id: self.process_id.clone(),
112            process_uuid: self.process_uuid,
113            span_types: self.span_types,
114            time_range: self.time_range,
115            lakehouse: self.lakehouse.clone(),
116            view_factory: self.view_factory.clone(),
117            part_provider: self.part_provider.clone(),
118            guard: self.guard.clone(),
119            authorized: Some(authorized),
120            properties: self.properties.clone(),
121        }
122    }
123}
124
125impl Debug for PerfettoTraceExecutionPlan {
126    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
127        f.debug_struct("PerfettoTraceExecutionPlan")
128            .field("process_id", &self.process_id)
129            .field("span_types", &self.span_types)
130            .field("time_range", &self.time_range)
131            .finish()
132    }
133}
134
135impl DisplayAs for PerfettoTraceExecutionPlan {
136    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
137        write!(
138            f,
139            "PerfettoTraceExecutionPlan: process_id={}, span_types={:?}, time_range={}..{}",
140            self.process_id, self.span_types, self.time_range.begin, self.time_range.end
141        )
142    }
143}
144
145impl ExecutionPlan for PerfettoTraceExecutionPlan {
146    fn name(&self) -> &str {
147        "PerfettoTraceExecutionPlan"
148    }
149
150    fn schema(&self) -> SchemaRef {
151        self.schema.clone()
152    }
153
154    fn properties(&self) -> &Arc<PlanProperties> {
155        &self.properties
156    }
157
158    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
159        vec![]
160    }
161
162    fn with_new_children(
163        self: Arc<Self>,
164        _children: Vec<Arc<dyn ExecutionPlan>>,
165    ) -> DFResult<Arc<dyn ExecutionPlan>> {
166        Ok(self)
167    }
168
169    #[span_fn]
170    fn execute(
171        &self,
172        _partition: usize,
173        _context: Arc<TaskContext>,
174    ) -> DFResult<SendableRecordBatchStream> {
175        let schema = self.schema.clone();
176        let process_id = self.process_id.clone();
177        let span_types = self.span_types;
178        let time_range = self.time_range;
179        let lakehouse = self.lakehouse.clone();
180        let view_factory = self.view_factory.clone();
181        let part_provider = self.part_provider.clone();
182        // No witness ⇒ this plan never went through `scan` -- fail-closed by construction.
183        let Some(authorized) = &self.authorized else {
184            return Err(DataFusionError::Internal(
185                "perfetto_trace_chunks: unauthorized plan (no witness from scan)".into(),
186            ));
187        };
188        let caller = authorized.internal_caller();
189
190        // Create the stream directly without channels
191        let stream = generate_perfetto_trace_stream(
192            process_id,
193            span_types,
194            time_range,
195            lakehouse,
196            view_factory,
197            part_provider,
198            caller,
199        );
200
201        Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
202    }
203
204    fn apply_expressions(
205        &self,
206        _f: &mut dyn FnMut(
207            &Arc<dyn datafusion::physical_plan::PhysicalExpr>,
208        ) -> DFResult<datafusion::common::tree_node::TreeNodeRecursion>,
209    ) -> DFResult<datafusion::common::tree_node::TreeNodeRecursion> {
210        Ok(datafusion::common::tree_node::TreeNodeRecursion::Continue)
211    }
212}
213
214/// Creates a stream of Perfetto trace chunks using streaming architecture
215#[span_fn]
216fn generate_perfetto_trace_stream(
217    process_id: String,
218    span_types: SpanTypes,
219    time_range: TimeRange,
220    lakehouse: Arc<LakehouseContext>,
221    view_factory: Arc<ViewFactory>,
222    part_provider: Arc<dyn QueryPartitionProvider>,
223    caller: CallerContext,
224) -> impl futures::Stream<Item = DFResult<RecordBatch>> {
225    stream! {
226        // Create channel for streaming chunks
227        const CHUNK_SIZE: usize = 8 * 1024; // 8KB chunks
228        let (chunk_sender, mut chunk_receiver) = tokio::sync::mpsc::channel(16);
229
230        // Create ChunkSender that will stream data through the channel
231        let chunk_sender_writer = ChunkSender::new(chunk_sender, CHUNK_SIZE);
232
233        // Spawn background task to generate trace
234        let generation_task = spawn_with_context(async move {
235            generate_streaming_perfetto_trace(
236                chunk_sender_writer,
237                process_id,
238                span_types,
239                time_range,
240                lakehouse,
241                view_factory,
242                part_provider,
243                caller,
244            ).await
245        });
246
247        // Stream chunks as they become available
248        while let Some(chunk_result) = chunk_receiver.recv().await {
249            match chunk_result {
250                Ok(batch) => yield Ok(batch),
251                Err(e) => {
252                    // ChunkSender only ever pushes `Ok(batch)` into this channel, so
253                    // reaching this branch means the channel itself misbehaved - an
254                    // internal failure, never a caller mistake.
255                    error!("Error in chunk generation: {:?}", e);
256                    yield Err(datafusion::error::DataFusionError::Internal(
257                        format!("Chunk generation failed: {}", e)
258                    ));
259                    return;
260                }
261            }
262        }
263
264        // Wait for generation task to complete and check for errors
265        match generation_task.await {
266            Ok(Ok(())) => {}, // Success
267            Ok(Err(e)) => {
268                if e.downcast_ref::<ProcessNotFoundError>().is_some() {
269                    // Caller asked for a process id that doesn't exist.
270                    warn!("Trace generation failed: {:?}", e);
271                    yield Err(datafusion::error::DataFusionError::Execution(
272                        format!("Trace generation failed: {}", e)
273                    ));
274                } else {
275                    // Everything else (session context, object store, DB, parquet
276                    // reads, ...) is a genuine server-side failure.
277                    error!("Trace generation failed: {:?}", e);
278                    yield Err(datafusion::error::DataFusionError::Internal(
279                        format!("Trace generation failed: {}", e)
280                    ));
281                }
282            }
283            Err(e) => {
284                error!("Task panicked: {:?}", e);
285                yield Err(datafusion::error::DataFusionError::Internal(
286                    format!("Task panicked: {}", e)
287                ));
288            }
289        }
290    }
291}
292
293/// Generate Perfetto trace using streaming architecture
294#[allow(clippy::too_many_arguments)]
295async fn generate_streaming_perfetto_trace(
296    chunk_sender: ChunkSender,
297    process_id: String,
298    span_types: SpanTypes,
299    time_range: TimeRange,
300    lakehouse: Arc<LakehouseContext>,
301    view_factory: Arc<ViewFactory>,
302    part_provider: Arc<dyn QueryPartitionProvider>,
303    caller: CallerContext,
304) -> anyhow::Result<()> {
305    info!(
306        "Generating streaming Perfetto trace for process {} with span types {:?} from {} to {}",
307        process_id, span_types, time_range.begin, time_range.end
308    );
309
310    // Runs under the witness's internal caller (`caller`, threaded in from `execute`), not the
311    // caller's own scope: every SQL statement below is server-constructed and confined to the
312    // process id the guard already authorized (`get_process_exe`, `get_process_thread_list`, the
313    // `view_instance` calls further down) -- if that process is readable, everything these
314    // statements can reach is readable too. A deliberate deviation from naive scope inheritance.
315    let ctx = super::query::make_session_context(
316        lakehouse,
317        part_provider,
318        SessionRange::Query(TimeRange {
319            begin: time_range.begin,
320            end: time_range.end,
321        }),
322        view_factory,
323        Arc::new(NoOpSessionConfigurator),
324        caller,
325    )
326    .await?;
327
328    // Use ChunkSender directly as the writer destination
329    let mut writer = PerfettoWriter::new(Box::new(chunk_sender), &process_id);
330
331    let process_exe = get_process_exe(&process_id, &ctx).await?;
332    writer.emit_process_descriptor(&process_exe).await?;
333    writer.flush().await?; // Forces chunk emission
334
335    let threads = get_process_thread_list(&process_id, &ctx).await?;
336    for (stream_id, thread_id, thread_name) in &threads {
337        writer
338            .emit_thread_descriptor(stream_id, *thread_id, thread_name)
339            .await?;
340    }
341    if !threads.is_empty() {
342        writer.flush().await?; // Forces chunk emission
343    }
344
345    if matches!(span_types, SpanTypes::Async | SpanTypes::Both) {
346        writer.emit_async_track_descriptor().await?;
347        writer.flush().await?; // Forces chunk emission
348    }
349
350    if matches!(span_types, SpanTypes::Thread | SpanTypes::Both) {
351        generate_thread_spans_with_writer(&mut writer, &ctx, &time_range, &threads).await?;
352    }
353
354    if matches!(span_types, SpanTypes::Async | SpanTypes::Both) {
355        generate_async_spans_with_writer(&mut writer, &process_id, &ctx, &time_range).await?;
356    }
357
358    writer.flush().await?; // Final chunk - this handles the chunk_sender.flush() internally
359    Ok(())
360}
361
362/// Get process executable name from the processes table
363async fn get_process_exe(
364    process_id: &str,
365    ctx: &datafusion::execution::context::SessionContext,
366) -> anyhow::Result<String> {
367    let sql = format!(
368        r#"
369        SELECT exe
370        FROM processes
371        WHERE process_id = '{}'
372        LIMIT 1
373        "#,
374        process_id
375    );
376
377    let df = ctx.sql(&sql).await?;
378    let batches = df.collect().await?;
379
380    if batches.is_empty() || batches[0].num_rows() == 0 {
381        return Err(ProcessNotFoundError(process_id.to_owned()).into());
382    }
383
384    let exes = string_column_by_name(&batches[0], "exe")?;
385    Ok(exes.value(0)?.to_owned())
386}
387
388/// Format the SQL query for thread spans
389fn format_thread_spans_query(stream_id: &str, time_range: &TimeRange) -> String {
390    format!(
391        r#"
392        SELECT "begin", "end", name, filename, target, line
393        FROM view_instance('thread_spans', '{}')
394        WHERE begin <= TIMESTAMP '{}'
395          AND end >= TIMESTAMP '{}'
396        ORDER BY begin
397        "#,
398        stream_id,
399        time_range.end.to_rfc3339(),
400        time_range.begin.to_rfc3339()
401    )
402}
403
404/// Generate thread spans with parallel JIT and sequential writing.
405///
406/// JIT partition locking is per-(view_set_name, view_instance_id), and each thread
407/// has a unique stream_id used as view_instance_id. This means different threads
408/// get different lock keys, making parallel JIT safe.
409///
410/// Strategy:
411/// - Spawn tasks with spawn_with_context() for true multi-threaded parallelism
412/// - Use buffered() to limit concurrent spawned tasks
413/// - Collect all streams preserving order
414/// - Consume streams sequentially to write each thread's spans together
415async fn generate_thread_spans_with_writer(
416    writer: &mut PerfettoWriter,
417    ctx: &datafusion::execution::context::SessionContext,
418    time_range: &TimeRange,
419    threads: &[(String, i32, String)],
420) -> anyhow::Result<()> {
421    let max_concurrent = std::thread::available_parallelism()
422        .map(|n| n.get())
423        .unwrap_or(4);
424
425    // Prepare query inputs upfront
426    let queries: Vec<(String, String)> = threads
427        .iter()
428        .map(|(stream_id, _, _)| {
429            (
430                stream_id.clone(),
431                format_thread_spans_query(stream_id, time_range),
432            )
433        })
434        .collect();
435
436    // Build streams in parallel using spawn for true multi-threading
437    let streams: Vec<(String, SendableRecordBatchStream)> = stream::iter(queries)
438        .map(|(stream_id, sql)| {
439            let ctx = ctx.clone();
440            async move {
441                spawn_with_context(async move {
442                    let df = ctx.sql(&sql).await?;
443                    let stream = df.execute_stream().await?;
444                    Ok::<_, anyhow::Error>((stream_id, stream))
445                })
446                .await?
447            }
448        })
449        .buffered(max_concurrent)
450        .try_collect()
451        .await?;
452
453    // Consume streams sequentially - each thread's spans written together
454    for (stream_id, data_stream) in streams {
455        write_thread_spans(writer, &stream_id, data_stream).await?;
456    }
457    Ok(())
458}
459
460/// Writes one thread's spans, in row order, from its query result stream to the Perfetto writer.
461///
462/// `begin` is only guaranteed sorted *within* a single thread's stream (different threads are
463/// independent timelines), so the monotonicity tracker below is local to this call. It is the
464/// runtime backstop for the ordering `ThreadSpansView::get_scan_output_ordering` declares to
465/// DataFusion: once the redundant `Sort` node is elided, DataFusion trusts that declared ordering
466/// and never re-validates it against the actual rows, so a violated invariant would otherwise
467/// silently mis-order the exported trace. Errors instead of writing a row whose `begin` regresses.
468pub async fn write_thread_spans(
469    writer: &mut PerfettoWriter,
470    stream_id: &str,
471    mut data_stream: SendableRecordBatchStream,
472) -> anyhow::Result<()> {
473    writer.set_current_thread(stream_id);
474
475    let mut previous_begin_ns: Option<i64> = None;
476    let mut span_count = 0;
477    while let Some(batch_result) = data_stream.next().await {
478        let batch = batch_result?;
479        let begin_times: &TimestampNanosecondArray = typed_column_by_name(&batch, "begin")?;
480        let end_times: &TimestampNanosecondArray = typed_column_by_name(&batch, "end")?;
481        let names = string_column_by_name(&batch, "name")?;
482        let filenames = string_column_by_name(&batch, "filename")?;
483        let targets = string_column_by_name(&batch, "target")?;
484        let lines: &UInt32Array = typed_column_by_name(&batch, "line")?;
485
486        for i in 0..batch.num_rows() {
487            let begin_time = begin_times.value(i);
488            if let Some(previous) = previous_begin_ns
489                && begin_time < previous
490            {
491                anyhow::bail!(
492                    "thread spans out of order for stream {stream_id}: begin {begin_time} follows {previous}"
493                );
494            }
495            previous_begin_ns = Some(begin_time);
496
497            let begin_ns = begin_time as u64;
498            let end_ns = end_times.value(i) as u64;
499            let name = names.value(i)?;
500            let filename = filenames.value(i)?;
501            let target = targets.value(i)?;
502            let line = lines.value(i);
503
504            writer
505                .emit_span(begin_ns, end_ns, name, target, filename, line)
506                .await?;
507
508            span_count += 1;
509            if span_count % 10 == 0 {
510                writer.flush().await?;
511            }
512        }
513    }
514    Ok(())
515}
516
517/// Generate async spans using the provided PerfettoWriter
518async fn generate_async_spans_with_writer(
519    writer: &mut PerfettoWriter,
520    process_id: &str,
521    ctx: &datafusion::execution::context::SessionContext,
522    time_range: &TimeRange,
523) -> anyhow::Result<()> {
524    let sql = format!(
525        r#"
526        WITH begin_events AS (
527            SELECT span_id, time as begin_time, name, filename, target, line
528            FROM view_instance('async_events', '{}')
529            WHERE time >= TIMESTAMP '{}'
530              AND time <= TIMESTAMP '{}'
531              AND event_type = 'begin'
532        ),
533        end_events AS (
534            SELECT span_id, time as end_time
535            FROM view_instance('async_events', '{}')
536            WHERE time >= TIMESTAMP '{}'
537              AND time <= TIMESTAMP '{}'
538              AND event_type = 'end'
539        )
540        SELECT 
541            b.span_id,
542            b.begin_time,
543            e.end_time,
544            b.name,
545            b.filename,
546            b.target,
547            b.line
548        FROM begin_events b
549        INNER JOIN end_events e ON b.span_id = e.span_id
550        ORDER BY b.begin_time
551        "#,
552        process_id,
553        time_range.begin.to_rfc3339(),
554        time_range.end.to_rfc3339(),
555        process_id,
556        time_range.begin.to_rfc3339(),
557        time_range.end.to_rfc3339(),
558    );
559
560    let df = ctx.sql(&sql).await?;
561    let mut stream = df.execute_stream().await?;
562
563    let mut span_count = 0;
564    while let Some(batch_result) = stream.next().await {
565        let batch = batch_result?;
566        let span_ids: &datafusion::arrow::array::Int64Array =
567            typed_column_by_name(&batch, "span_id")?;
568        let begin_times: &TimestampNanosecondArray = typed_column_by_name(&batch, "begin_time")?;
569        let end_times: &TimestampNanosecondArray = typed_column_by_name(&batch, "end_time")?;
570        let names = string_column_by_name(&batch, "name")?;
571        let filenames = string_column_by_name(&batch, "filename")?;
572        let targets = string_column_by_name(&batch, "target")?;
573        let lines: &UInt32Array = typed_column_by_name(&batch, "line")?;
574        for i in 0..batch.num_rows() {
575            let _span_id = span_ids.value(i);
576            let begin_ns = begin_times.value(i) as u64;
577            let end_ns = end_times.value(i) as u64;
578            let name = names.value(i)?;
579            let filename = filenames.value(i)?;
580            let target = targets.value(i)?;
581            let line = lines.value(i);
582
583            if begin_ns < end_ns {
584                // Emit async span begin and end events with single writer
585                writer
586                    .emit_async_span_begin(begin_ns, name, target, filename, line)
587                    .await?;
588                writer
589                    .emit_async_span_end(end_ns, name, target, filename, line)
590                    .await?;
591
592                span_count += 1;
593                // Flush every 10 async spans to create multiple chunks
594                if span_count % 10 == 0 {
595                    writer.flush().await?;
596                }
597            } else {
598                warn!("Skipping async span with invalid duration");
599            }
600        }
601    }
602
603    Ok(())
604}
605
606/// TableProvider wrapper for PerfettoTraceExecutionPlan
607#[derive(Debug)]
608pub struct PerfettoTraceTableProvider {
609    execution_plan: Arc<PerfettoTraceExecutionPlan>,
610}
611
612impl PerfettoTraceTableProvider {
613    /// `pub(crate)`, not `pub`: only ever called from `perfetto_trace_table_function.rs`, same
614    /// crate. So an external test crate can't build an un-authorized plan directly, matching
615    /// `process_spans`' existing module-private shape.
616    pub(crate) fn new(execution_plan: Arc<PerfettoTraceExecutionPlan>) -> Self {
617        Self { execution_plan }
618    }
619}
620
621#[async_trait::async_trait]
622impl TableProvider for PerfettoTraceTableProvider {
623    fn schema(&self) -> SchemaRef {
624        self.execution_plan.schema()
625    }
626
627    fn table_type(&self) -> TableType {
628        TableType::Base
629    }
630
631    async fn scan(
632        &self,
633        _state: &dyn Session,
634        _projection: Option<&Vec<usize>>,
635        _filters: &[Expr],
636        limit: Option<usize>,
637    ) -> DFResult<Arc<dyn ExecutionPlan>> {
638        let authorized = self
639            .execution_plan
640            .guard
641            .authorize(
642                self.execution_plan.process_uuid,
643                IdKind::Process,
644                "perfetto_trace_chunks",
645            )
646            .await?;
647        // Wrap the execution plan in a GlobalLimitExec if a limit is provided.
648        // DataFusion trusts us to apply the limit - if we ignore it, too many rows
649        // will be returned to the client.
650        let plan: Arc<dyn ExecutionPlan> =
651            Arc::new(self.execution_plan.with_authorized(authorized));
652        if let Some(fetch) = limit {
653            Ok(Arc::new(GlobalLimitExec::new(plan, 0, Some(fetch))))
654        } else {
655            Ok(plan)
656        }
657    }
658}