Skip to main content

frontend/instance/
jaeger.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use auth::{JAEGER_QUERY, PermissionReq, PermissionTableTarget, PermissionTableTargets};
20use catalog::CatalogManagerRef;
21use common_catalog::consts::{
22    TRACE_TABLE_NAME, trace_operations_table_name, trace_services_table_name,
23};
24use common_function::function::FunctionRef;
25use common_function::scalars::json::json_get::{
26    JsonGetBool, JsonGetFloat, JsonGetInt, JsonGetString, JsonGetWithType,
27};
28use common_function::scalars::udf::create_udf;
29use common_query::{Output, OutputData};
30use common_recordbatch::adapter::RecordBatchStreamAdapter;
31use common_recordbatch::util;
32use common_telemetry::warn;
33use datafusion::common::ScalarValue;
34use datafusion::dataframe::DataFrame;
35use datafusion::execution::SessionStateBuilder;
36use datafusion::execution::context::SessionContext;
37use datafusion::functions::core::expr_fn::coalesce;
38use datafusion::functions_aggregate::expr_fn::max;
39use datafusion::functions_window::expr_fn::row_number;
40use datafusion_expr::select_expr::SelectExpr;
41use datafusion_expr::{Expr, ExprFunctionExt, SortExpr, col, lit, lit_timestamp_nano, wildcard};
42use query::QueryEngineRef;
43use serde_json::Value as JsonValue;
44use servers::error::{
45    CollectRecordbatchSnafu, DataFusionSnafu, Result as ServerResult, TableNotFoundSnafu,
46};
47use servers::http::jaeger::{JAEGER_QUERY_TABLE_NAME_KEY, QueryTraceParams, TraceUserAgent};
48use servers::otlp::trace::{
49    DURATION_NANO_COLUMN, KEY_OTEL_STATUS_ERROR_KEY, RESOURCE_ATTRIBUTES_COLUMN,
50    SERVICE_NAME_COLUMN, SPAN_ATTRIBUTES_COLUMN, SPAN_KIND_COLUMN, SPAN_KIND_PREFIX,
51    SPAN_NAME_COLUMN, SPAN_STATUS_CODE, SPAN_STATUS_ERROR, TIMESTAMP_COLUMN, TRACE_ID_COLUMN,
52};
53use servers::query_handler::JaegerQueryHandler;
54use session::context::QueryContextRef;
55use snafu::{OptionExt, ResultExt};
56use table::TableRef;
57use table::table::adapter::DfTableProviderAdapter;
58
59use crate::instance::Instance;
60
61const DEFAULT_LIMIT: usize = 2000;
62const KEY_RN: &str = "greptime_rn";
63const KEY_LATEST_MATCH: &str = "greptime_latest_match";
64
65impl Instance {
66    async fn check_jaeger_query_permission(&self, ctx: &QueryContextRef) -> ServerResult<()> {
67        let table = ctx
68            .extension(JAEGER_QUERY_TABLE_NAME_KEY)
69            .unwrap_or(TRACE_TABLE_NAME);
70        let targets = PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
71            ctx.current_catalog(),
72            ctx.current_schema(),
73            table,
74        )]);
75        self.check_server_table_permission(ctx, PermissionReq::Action(JAEGER_QUERY), targets)
76            .await?;
77        Ok(())
78    }
79}
80
81#[async_trait]
82impl JaegerQueryHandler for Instance {
83    async fn get_services(&self, ctx: QueryContextRef) -> ServerResult<Output> {
84        self.check_jaeger_query_permission(&ctx).await?;
85
86        // It's equivalent to `SELECT DISTINCT(service_name) FROM {db}.{trace_table}`.
87        Ok(query_trace_table(
88            ctx,
89            self,
90            vec![SelectExpr::from(col(SERVICE_NAME_COLUMN))],
91            vec![],
92            vec![],
93            None,
94            None,
95            vec![col(SERVICE_NAME_COLUMN)],
96        )
97        .await?)
98    }
99
100    async fn get_operations(
101        &self,
102        ctx: QueryContextRef,
103        service_name: &str,
104        span_kind: Option<&str>,
105    ) -> ServerResult<Output> {
106        self.check_jaeger_query_permission(&ctx).await?;
107
108        let mut filters = vec![col(SERVICE_NAME_COLUMN).eq(lit(service_name))];
109
110        if let Some(span_kind) = span_kind {
111            filters.push(col(SPAN_KIND_COLUMN).eq(lit(format!(
112                "{}{}",
113                SPAN_KIND_PREFIX,
114                span_kind.to_uppercase()
115            ))));
116        }
117
118        // It's equivalent to the following SQL query:
119        //
120        // ```
121        // SELECT DISTINCT span_name, span_kind
122        // FROM
123        //   {db}.{trace_table}
124        // WHERE
125        //   service_name = '{service_name}' AND
126        //   span_kind = '{span_kind}'
127        // ORDER BY
128        //   span_name ASC
129        // ```.
130        Ok(query_trace_table(
131            ctx,
132            self,
133            vec![
134                SelectExpr::from(col(SPAN_NAME_COLUMN)),
135                SelectExpr::from(col(SPAN_KIND_COLUMN)),
136                SelectExpr::from(col(SERVICE_NAME_COLUMN)),
137                SelectExpr::from(col(TIMESTAMP_COLUMN)),
138            ],
139            filters,
140            vec![col(SPAN_NAME_COLUMN).sort(true, false)], // Sort by span_name in ascending order.
141            Some(DEFAULT_LIMIT),
142            None,
143            vec![col(SPAN_NAME_COLUMN), col(SPAN_KIND_COLUMN)],
144        )
145        .await?)
146    }
147
148    async fn get_trace(
149        &self,
150        ctx: QueryContextRef,
151        trace_id: &str,
152        start_time: Option<i64>,
153        end_time: Option<i64>,
154        limit: Option<usize>,
155    ) -> ServerResult<Output> {
156        self.check_jaeger_query_permission(&ctx).await?;
157
158        // It's equivalent to the following SQL query:
159        //
160        // ```
161        // SELECT
162        //   *
163        // FROM
164        //   {db}.{trace_table}
165        // WHERE
166        //   trace_id = '{trace_id}' AND
167        //   timestamp >= {start_time} AND
168        //   timestamp <= {end_time}
169        // ORDER BY
170        //   timestamp DESC
171        // ```.
172        let selects = vec![wildcard()];
173
174        let mut filters = vec![col(TRACE_ID_COLUMN).eq(lit(trace_id))];
175
176        if let Some(start_time) = start_time {
177            filters.push(col(TIMESTAMP_COLUMN).gt_eq(lit_timestamp_nano(start_time)));
178        }
179
180        if let Some(end_time) = end_time {
181            filters.push(col(TIMESTAMP_COLUMN).lt_eq(lit_timestamp_nano(end_time)));
182        }
183
184        Ok(query_trace_table(
185            ctx,
186            self,
187            selects,
188            filters,
189            vec![col(TIMESTAMP_COLUMN).sort(false, false)], // Sort by timestamp in descending order.
190            limit,
191            None,
192            vec![],
193        )
194        .await?)
195    }
196
197    async fn find_traces(
198        &self,
199        ctx: QueryContextRef,
200        query_params: QueryTraceParams,
201    ) -> ServerResult<Output> {
202        self.check_jaeger_query_permission(&ctx).await?;
203
204        let mut filters = vec![];
205
206        if let Some(service_name) = query_params.service_name {
207            filters.push(col(SERVICE_NAME_COLUMN).eq(lit(service_name)));
208        }
209
210        if let Some(operation_name) = query_params.operation_name {
211            filters.push(col(SPAN_NAME_COLUMN).eq(lit(operation_name)));
212        }
213
214        if let Some(start_time) = query_params.start_time {
215            filters.push(col(TIMESTAMP_COLUMN).gt_eq(lit_timestamp_nano(start_time)));
216        }
217
218        if let Some(end_time) = query_params.end_time {
219            filters.push(col(TIMESTAMP_COLUMN).lt_eq(lit_timestamp_nano(end_time)));
220        }
221
222        if let Some(min_duration) = query_params.min_duration {
223            filters.push(col(DURATION_NANO_COLUMN).gt_eq(lit(min_duration)));
224        }
225
226        if let Some(max_duration) = query_params.max_duration {
227            filters.push(col(DURATION_NANO_COLUMN).lt_eq(lit(max_duration)));
228        }
229
230        // Get the ids of the most recent traces that match the filters.
231        // It's equivalent to the following SQL query:
232        //
233        // ```
234        // SELECT trace_id
235        // FROM
236        //   {db}.{trace_table}
237        // WHERE
238        //   service_name = '{service_name}' AND
239        //   operation_name = '{operation_name}' AND
240        //   timestamp >= {start_time} AND
241        //   timestamp <= {end_time} AND
242        //   duration >= {min_duration} AND
243        //   duration <= {max_duration}
244        // GROUP BY trace_id
245        // ORDER BY max(timestamp) DESC, trace_id
246        // LIMIT {limit}
247        // ```.
248        let output = find_latest_trace_ids(
249            ctx.clone(),
250            self,
251            filters,
252            query_params.limit.unwrap_or(DEFAULT_LIMIT),
253            query_params.tags,
254        )
255        .await?;
256
257        // Get all traces that match the trace ids from the previous query.
258        // API v3 applies the time window only to the search, not to the returned spans.
259        // It's equivalent to the following SQL query:
260        //
261        // ```
262        // SELECT *
263        // FROM
264        //   {db}.{trace_table}
265        // WHERE
266        //   trace_id IN ({trace_ids}) AND
267        //   timestamp >= {start_time} AND
268        //   timestamp <= {end_time}
269        // ```
270        let mut filters = vec![
271            col(TRACE_ID_COLUMN).in_list(
272                trace_ids_from_output(output)
273                    .await?
274                    .iter()
275                    .map(lit)
276                    .collect::<Vec<Expr>>(),
277                false,
278            ),
279        ];
280
281        if !query_params.fetch_full_trace
282            && let Some(start_time) = query_params.start_time
283        {
284            filters.push(col(TIMESTAMP_COLUMN).gt_eq(lit_timestamp_nano(start_time)));
285        }
286
287        if !query_params.fetch_full_trace
288            && let Some(end_time) = query_params.end_time
289        {
290            filters.push(col(TIMESTAMP_COLUMN).lt_eq(lit_timestamp_nano(end_time)));
291        }
292
293        match query_params.user_agent {
294            TraceUserAgent::Grafana => {
295                // grafana only use trace id and timestamp
296                // clicking the trace id will invoke the query trace api
297                // so we only need to return 1 span for each trace
298                let table_name = ctx
299                    .extension(JAEGER_QUERY_TABLE_NAME_KEY)
300                    .unwrap_or(TRACE_TABLE_NAME);
301
302                let table = get_table(ctx.clone(), self.catalog_manager(), table_name).await?;
303
304                Ok(find_traces_rank_3(
305                    table,
306                    self.query_engine(),
307                    filters,
308                    vec![col(TIMESTAMP_COLUMN).sort(false, false)], // Sort by timestamp in descending order.
309                )
310                .await?)
311            }
312            _ => {
313                // query all spans
314                Ok(query_trace_table(
315                    ctx,
316                    self,
317                    vec![wildcard()],
318                    filters,
319                    vec![col(TIMESTAMP_COLUMN).sort(false, false)], // Sort by timestamp in descending order.
320                    None,
321                    None,
322                    vec![],
323                )
324                .await?)
325            }
326        }
327    }
328}
329
330#[allow(clippy::too_many_arguments)]
331async fn query_trace_table(
332    ctx: QueryContextRef,
333    instance: &Instance,
334    selects: Vec<SelectExpr>,
335    filters: Vec<Expr>,
336    sorts: Vec<SortExpr>,
337    limit: Option<usize>,
338    tags: Option<HashMap<String, JsonValue>>,
339    distincts: Vec<Expr>,
340) -> ServerResult<Output> {
341    let dataframe =
342        build_trace_dataframe(&ctx, instance, selects, filters, tags, &distincts).await?;
343
344    // Apply the distinct if needed.
345    let dataframe = if !distincts.is_empty() {
346        dataframe
347            .distinct_on(distincts.clone(), distincts, None)
348            .context(DataFusionSnafu)?
349    } else {
350        dataframe
351    };
352
353    // Apply the sorts if needed.
354    let dataframe = if !sorts.is_empty() {
355        dataframe.sort(sorts).context(DataFusionSnafu)?
356    } else {
357        dataframe
358    };
359
360    // Apply the limit if needed.
361    let dataframe = if let Some(limit) = limit {
362        dataframe.limit(0, Some(limit)).context(DataFusionSnafu)?
363    } else {
364        dataframe
365    };
366
367    execute_trace_dataframe(dataframe).await
368}
369
370/// Returns the ids of the `limit` traces whose latest span matching `filters`
371/// and `tags` is the most recent, newest first.
372///
373/// Ordering before the limit keeps a search that matches more traces than the
374/// limit deterministic.
375async fn find_latest_trace_ids(
376    ctx: QueryContextRef,
377    instance: &Instance,
378    filters: Vec<Expr>,
379    limit: usize,
380    tags: Option<HashMap<String, JsonValue>>,
381) -> ServerResult<Output> {
382    let dataframe =
383        build_trace_dataframe(&ctx, instance, vec![wildcard()], filters, tags, &[]).await?;
384    let dataframe = dataframe
385        .aggregate(
386            vec![col(TRACE_ID_COLUMN)],
387            vec![max(col(TIMESTAMP_COLUMN)).alias(KEY_LATEST_MATCH)],
388        )
389        .context(DataFusionSnafu)?
390        .sort(vec![
391            col(KEY_LATEST_MATCH).sort(false, false),
392            col(TRACE_ID_COLUMN).sort(true, false),
393        ])
394        .context(DataFusionSnafu)?
395        .limit(0, Some(limit))
396        .context(DataFusionSnafu)?
397        .select(vec![col(TRACE_ID_COLUMN)])
398        .context(DataFusionSnafu)?;
399
400    execute_trace_dataframe(dataframe).await
401}
402
403/// Reads the trace table, or the services or operations lookup table that
404/// answers `selects` and `distincts`, then projects `selects` and applies
405/// `filters` and the Jaeger tag filters.
406async fn build_trace_dataframe(
407    ctx: &QueryContextRef,
408    instance: &Instance,
409    selects: Vec<SelectExpr>,
410    filters: Vec<Expr>,
411    tags: Option<HashMap<String, JsonValue>>,
412    distincts: &[Expr],
413) -> ServerResult<DataFrame> {
414    let trace_table_name = ctx
415        .extension(JAEGER_QUERY_TABLE_NAME_KEY)
416        .unwrap_or(TRACE_TABLE_NAME);
417
418    // If only select services, use the trace services table.
419    // If querying operations (distinct by span_name and span_kind), use the trace operations table.
420    let table_name = {
421        if match selects.as_slice() {
422            [SelectExpr::Expression(x)] => x == &col(SERVICE_NAME_COLUMN),
423            _ => false,
424        } {
425            &trace_services_table_name(trace_table_name)
426        } else if !distincts.is_empty()
427            && distincts.contains(&col(SPAN_NAME_COLUMN))
428            && distincts.contains(&col(SPAN_KIND_COLUMN))
429        {
430            &trace_operations_table_name(trace_table_name)
431        } else {
432            trace_table_name
433        }
434    };
435
436    let table = instance
437        .catalog_manager()
438        .table(
439            ctx.current_catalog(),
440            &ctx.current_schema(),
441            table_name,
442            Some(ctx),
443        )
444        .await?
445        .with_context(|| TableNotFoundSnafu {
446            table: table_name,
447            catalog: ctx.current_catalog(),
448            schema: ctx.current_schema(),
449        })?;
450
451    let table_info = table.table_info();
452    let data_model = table_info.meta.options.data_model();
453
454    // collect to set
455    let col_names = table_info
456        .meta
457        .field_column_names()
458        .map(|s| format!("\"{}\"", s))
459        .collect::<HashSet<String>>();
460
461    let df_context = create_df_context(instance.query_engine())?;
462
463    let dataframe = df_context
464        .read_table(Arc::new(DfTableProviderAdapter::new(table)))
465        .context(DataFusionSnafu)?;
466
467    let dataframe = dataframe.select(selects).context(DataFusionSnafu)?;
468
469    // Apply all filters.
470    let dataframe = filters
471        .into_iter()
472        .chain(tags.map_or(Ok(vec![]), |t| {
473            tags_filters(&dataframe, t, data_model, &col_names)
474        })?)
475        .try_fold(dataframe, |df, expr| {
476            df.filter(expr).context(DataFusionSnafu)
477        })?;
478
479    Ok(dataframe)
480}
481
482/// Executes `dataframe` and wraps its stream into an [`Output`] with dictionary
483/// columns decoded to values.
484async fn execute_trace_dataframe(dataframe: DataFrame) -> ServerResult<Output> {
485    let stream = dataframe.execute_stream().await.context(DataFusionSnafu)?;
486
487    let output = Output::new_with_stream(Box::pin(
488        RecordBatchStreamAdapter::try_new(stream).context(CollectRecordbatchSnafu)?,
489    ));
490
491    output
492        .map_dictionary_to_values()
493        .context(CollectRecordbatchSnafu)
494}
495
496async fn get_table(
497    ctx: QueryContextRef,
498    catalog_manager: &CatalogManagerRef,
499    table_name: &str,
500) -> ServerResult<TableRef> {
501    catalog_manager
502        .table(
503            ctx.current_catalog(),
504            &ctx.current_schema(),
505            table_name,
506            Some(&ctx),
507        )
508        .await?
509        .with_context(|| TableNotFoundSnafu {
510            table: table_name,
511            catalog: ctx.current_catalog(),
512            schema: ctx.current_schema(),
513        })
514}
515
516async fn find_traces_rank_3(
517    table: TableRef,
518    query_engine: &QueryEngineRef,
519    filters: Vec<Expr>,
520    sorts: Vec<SortExpr>,
521) -> ServerResult<Output> {
522    let df_context = create_df_context(query_engine)?;
523
524    let dataframe = df_context
525        .read_table(Arc::new(DfTableProviderAdapter::new(table)))
526        .context(DataFusionSnafu)?;
527
528    let dataframe = dataframe
529        .select(vec![wildcard()])
530        .context(DataFusionSnafu)?;
531
532    // Apply all filters.
533    let dataframe = filters.into_iter().try_fold(dataframe, |df, expr| {
534        df.filter(expr).context(DataFusionSnafu)
535    })?;
536
537    // Apply the sorts if needed.
538    let dataframe = if !sorts.is_empty() {
539        dataframe.sort(sorts).context(DataFusionSnafu)?
540    } else {
541        dataframe
542    };
543
544    // create rank column, for each trace, get the earliest 3 spans
545    let trace_id_col = vec![col(TRACE_ID_COLUMN)];
546    let timestamp_asc = vec![col(TIMESTAMP_COLUMN).sort(true, false)];
547
548    let dataframe = dataframe
549        .with_column(
550            KEY_RN,
551            row_number()
552                .partition_by(trace_id_col)
553                .order_by(timestamp_asc)
554                .build()
555                .context(DataFusionSnafu)?,
556        )
557        .context(DataFusionSnafu)?;
558
559    let dataframe = dataframe
560        .filter(col(KEY_RN).lt_eq(lit(3)))
561        .context(DataFusionSnafu)?;
562
563    // Execute the query and collect the result.
564    let stream = dataframe.execute_stream().await.context(DataFusionSnafu)?;
565
566    let output = Output::new_with_stream(Box::pin(
567        RecordBatchStreamAdapter::try_new(stream).context(CollectRecordbatchSnafu)?,
568    ));
569
570    output
571        .map_dictionary_to_values()
572        .context(CollectRecordbatchSnafu)
573}
574
575// The current implementation registers UDFs during the planning stage, which makes it difficult
576// to utilize them through DataFrame APIs. To address this limitation, we create a new session
577// context and register the required UDFs, allowing them to be decoupled from the global context.
578// TODO(zyy17): Is it possible or necessary to reuse the existing session context?
579fn create_df_context(query_engine: &QueryEngineRef) -> ServerResult<SessionContext> {
580    let df_context = SessionContext::new_with_state(
581        SessionStateBuilder::new_from_existing(query_engine.engine_state().session_state()).build(),
582    );
583
584    // JSON UDFs used by the v0 and v2 tag filters.
585    let udfs: Vec<FunctionRef> = vec![
586        Arc::new(JsonGetWithType::default()),
587        Arc::new(JsonGetInt::default()),
588        Arc::new(JsonGetFloat::default()),
589        Arc::new(JsonGetBool::default()),
590        Arc::new(JsonGetString::default()),
591    ];
592
593    for udf in udfs {
594        df_context.register_udf(create_udf(udf));
595    }
596
597    Ok(df_context)
598}
599
600fn json_tag_filters(
601    dataframe: &DataFrame,
602    tags: HashMap<String, JsonValue>,
603) -> ServerResult<Vec<Expr>> {
604    let has_resource_attributes = dataframe
605        .schema()
606        .has_column_with_unqualified_name(RESOURCE_ATTRIBUTES_COLUMN);
607    let mut filters = vec![];
608
609    // NOTE: The key of the tags may contain `.`, for example: `http.status_code`, so we need to use `["http.status_code"]` in json path to access the value.
610    for (key, value) in tags.iter() {
611        let (udf, value) = match value {
612            JsonValue::String(value) => (JsonGetString::NAME, lit(value)),
613            JsonValue::Number(value) if value.is_i64() => {
614                (JsonGetInt::NAME, lit(value.as_i64().unwrap()))
615            }
616            JsonValue::Number(value) if value.is_f64() => {
617                (JsonGetFloat::NAME, lit(value.as_f64().unwrap()))
618            }
619            JsonValue::Bool(value) => (JsonGetBool::NAME, lit(*value)),
620            _ => continue,
621        };
622        let get = dataframe.registry().udf(udf).context(DataFusionSnafu)?;
623        let path = lit(format!("[\"{}\"]", key));
624        let span_value = get.call(vec![col(SPAN_ATTRIBUTES_COLUMN), path.clone()]);
625        // Same precedence as `json2_tag_filters`: a span attribute shadows a resource attribute.
626        let attribute = if has_resource_attributes {
627            coalesce(vec![
628                span_value,
629                get.call(vec![col(RESOURCE_ATTRIBUTES_COLUMN), path]),
630            ])
631        } else {
632            span_value
633        };
634        filters.push(attribute.eq(value));
635    }
636
637    Ok(filters)
638}
639
640/// Resolves each tag per row, falling back to Resource when the typed Span value is null.
641fn json2_tag_filters(
642    dataframe: &DataFrame,
643    tags: HashMap<String, JsonValue>,
644) -> ServerResult<Vec<Expr>> {
645    let get = dataframe
646        .registry()
647        .udf(JsonGetWithType::NAME)
648        .context(DataFusionSnafu)?;
649    tags.into_iter()
650        .map(|(key, value)| {
651            if key == KEY_OTEL_STATUS_ERROR_KEY && value == JsonValue::Bool(true) {
652                return Ok(col(SPAN_STATUS_CODE).eq(lit(SPAN_STATUS_ERROR)));
653            }
654            // JSON quoting preserves literal dots, quotes, and backslashes in attribute keys.
655            let path = lit(format!("$[{}]", JsonValue::String(key)));
656            let (value, value_type) = match value {
657                JsonValue::String(value) => (
658                    ScalarValue::Utf8View(Some(value)),
659                    ScalarValue::Utf8View(None),
660                ),
661                JsonValue::Bool(value) => (
662                    ScalarValue::Boolean(Some(value)),
663                    ScalarValue::Boolean(None),
664                ),
665                JsonValue::Number(value) => {
666                    if let Some(value) = value.as_i64() {
667                        (ScalarValue::Int64(Some(value)), ScalarValue::Int64(None))
668                    } else if let Some(value) = value.as_u64() {
669                        (ScalarValue::UInt64(Some(value)), ScalarValue::UInt64(None))
670                    } else if let Some(value) = value.as_f64() {
671                        (
672                            ScalarValue::Float64(Some(value)),
673                            ScalarValue::Float64(None),
674                        )
675                    } else {
676                        return Ok(lit(false));
677                    }
678                }
679                JsonValue::Null => (ScalarValue::Utf8View(None), ScalarValue::Utf8View(None)),
680                JsonValue::Array(_) | JsonValue::Object(_) => return Ok(lit(false)),
681            };
682            let attribute = coalesce(vec![
683                get.call(vec![
684                    col(SPAN_ATTRIBUTES_COLUMN),
685                    path.clone(),
686                    lit(value_type.clone()),
687                ]),
688                get.call(vec![col(RESOURCE_ATTRIBUTES_COLUMN), path, lit(value_type)]),
689            ]);
690            Ok(if value.is_null() {
691                attribute.is_null()
692            } else {
693                attribute.eq(lit(value))
694            })
695        })
696        .collect()
697}
698
699/// Helper function to check if span_key or resource_key exists in col_names and create an expression.
700/// If neither exists, logs a warning and returns None.
701#[inline]
702fn check_col_and_build_expr<F>(
703    span_key: String,
704    resource_key: String,
705    key: &str,
706    col_names: &HashSet<String>,
707    expr_builder: F,
708) -> Option<Expr>
709where
710    F: FnOnce(String) -> Expr,
711{
712    if col_names.contains(&span_key) {
713        return Some(expr_builder(span_key));
714    }
715    if col_names.contains(&resource_key) {
716        return Some(expr_builder(resource_key));
717    }
718    warn!("tag key {} not found in table columns", key);
719    None
720}
721
722fn flatten_tag_filters(
723    tags: HashMap<String, JsonValue>,
724    col_names: &HashSet<String>,
725) -> ServerResult<Vec<Expr>> {
726    let filters = tags
727        .into_iter()
728        .filter_map(|(key, value)| {
729            if key == KEY_OTEL_STATUS_ERROR_KEY && value == JsonValue::Bool(true) {
730                return Some(col(SPAN_STATUS_CODE).eq(lit(SPAN_STATUS_ERROR)));
731            }
732
733            // TODO(shuiyisong): add more precise mapping from key to col name
734            let span_key = format!("\"span_attributes.{}\"", key);
735            let resource_key = format!("\"resource_attributes.{}\"", key);
736            match value {
737                JsonValue::String(value) => {
738                    check_col_and_build_expr(span_key, resource_key, &key, col_names, |k| {
739                        col(k).eq(lit(value))
740                    })
741                }
742                JsonValue::Number(value) => {
743                    if value.is_f64() {
744                        // safe to unwrap as checked previously
745                        let value = value.as_f64().unwrap();
746                        check_col_and_build_expr(span_key, resource_key, &key, col_names, |k| {
747                            col(k).eq(lit(value))
748                        })
749                    } else {
750                        let value = value.as_i64().unwrap();
751                        check_col_and_build_expr(span_key, resource_key, &key, col_names, |k| {
752                            col(k).eq(lit(value))
753                        })
754                    }
755                }
756                JsonValue::Bool(value) => {
757                    check_col_and_build_expr(span_key, resource_key, &key, col_names, |k| {
758                        col(k).eq(lit(value))
759                    })
760                }
761                JsonValue::Null => {
762                    check_col_and_build_expr(span_key, resource_key, &key, col_names, |k| {
763                        col(k).is_null()
764                    })
765                }
766                // not supported at the moment
767                JsonValue::Array(_value) => None,
768                JsonValue::Object(_value) => None,
769            }
770        })
771        .collect();
772    Ok(filters)
773}
774
775fn tags_filters(
776    dataframe: &DataFrame,
777    tags: HashMap<String, JsonValue>,
778    data_model: Option<&str>,
779    col_names: &HashSet<String>,
780) -> ServerResult<Vec<Expr>> {
781    match data_model {
782        Some(table::requests::TABLE_DATA_MODEL_TRACE_V1) => flatten_tag_filters(tags, col_names),
783        Some(table::requests::TABLE_DATA_MODEL_TRACE_V2) => json2_tag_filters(dataframe, tags),
784        _ => json_tag_filters(dataframe, tags),
785    }
786}
787
788// Get trace ids from the output in recordbatches.
789async fn trace_ids_from_output(output: Output) -> ServerResult<Vec<String>> {
790    if let OutputData::Stream(stream) = output.data {
791        let schema = stream.schema().clone();
792        let recordbatches = util::collect(stream)
793            .await
794            .context(CollectRecordbatchSnafu)?;
795
796        // Only contains `trace_id` column in string type.
797        if !recordbatches.is_empty()
798            && schema.num_columns() == 1
799            && schema.contains_column(TRACE_ID_COLUMN)
800        {
801            let mut trace_ids = vec![];
802            for recordbatch in recordbatches {
803                recordbatch
804                    .iter_column_as_string(0)
805                    .flatten()
806                    .for_each(|x| trace_ids.push(x));
807            }
808
809            return Ok(trace_ids);
810        }
811    }
812
813    Ok(vec![])
814}