Skip to main content

operator/statement/
semantic_graph.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
15//! Typed DataFusion plan builders for the read-time derivation behind the
16//! computed `semantic_entities` / `semantic_relationships` tables.
17//!
18//! The derivation is built as typed [`Expr`]s over [`DataFrame`]s (never as SQL
19//! text), so user-controlled identifiers are plain values — no quoting or SQL
20//! injection surface — and the plans compose with DataFusion's optimizer,
21//! including filter pushdown into the source table scans. See
22//! `docs/rfcs/2026-06-25-entity-relationships-and-graph-query.md`.
23
24use std::sync::{Arc, LazyLock};
25
26use common_catalog::consts::{
27    DURATION_NANO_COLUMN, PARENT_SPAN_ID_COLUMN, SPAN_ID_COLUMN, SPAN_KIND_CLIENT,
28    SPAN_KIND_COLUMN, SPAN_KIND_SERVER, SPAN_STATUS_CODE_COLUMN, SPAN_STATUS_ERROR,
29    TRACE_ID_COLUMN, TRACE_TIMESTAMP_COLUMN,
30};
31use common_function::function::FunctionContext;
32use common_function::function_registry::FUNCTION_REGISTRY;
33use datafusion::arrow::datatypes::{DataType, TimeUnit};
34use datafusion::dataframe::DataFrame;
35use datafusion::functions::{core as core_fns, datetime as datetime_fns, string as string_fns};
36use datafusion::functions_aggregate::expr_fn::{count, sum};
37use datafusion::functions_nested::expr_fn::make_array;
38use datafusion_common::{Column, Result as DfResult, ScalarValue};
39use datafusion_expr::{Expr, ExprFunctionExt, JoinType, LogicalPlan, ScalarUDF, cast, ident, lit};
40
41/// Bin width for the temporal window of derived rows: 60s buckets, matching the
42/// service-graph convention.
43const BIN_NANOS: i64 = 60 * 1_000_000_000;
44
45/// A single table's entity-identity declaration, projected from
46/// `information_schema.table_semantics` (`greptime.semantic.entity.<type>.*`).
47#[derive(Debug, Clone)]
48pub struct EntityDeclaration {
49    /// The declaring table's schema, for the qualified `source_tables` lineage.
50    pub schema: String,
51    /// The declaring table's name, recorded in `source_tables`.
52    pub table: String,
53    /// The table's time index column, used for the temporal window filter.
54    pub time_index: String,
55    pub entity_type: String,
56    /// Identifying columns (>= 1). One column → id verbatim; several → composite.
57    pub id_columns: Vec<String>,
58    /// Descriptive columns snapshotted into the `descriptive` JSON (may be empty).
59    pub descriptive_columns: Vec<String>,
60    /// Scope columns (namespace/environment). One column → scope verbatim;
61    /// several → sorted `k=v,k=v`, mirroring the composite id rendering.
62    pub scope_columns: Vec<String>,
63}
64
65/// The read-time query window as scalar [`Expr`]s. Kept as expressions so the
66/// provider can fill them from a scan's time predicate or the product default.
67#[derive(Debug, Clone)]
68pub struct GraphWindow {
69    pub start: Expr,
70    pub end: Expr,
71}
72
73impl GraphWindow {
74    /// Conservative default when a query carries no explicit time predicate: the
75    /// last hour, so a bare `SELECT * FROM semantic_entities` never scans every
76    /// declaring table's full history. This is a product default, not a cap.
77    ///
78    /// The bounds are timestamp literals taken from the wall clock at plan-build
79    /// time — the same snapshot semantics `now()` would give, but as plain
80    /// constants they prune the source table scans without depending on
81    /// constant-folding.
82    pub fn default_last_hour() -> Self {
83        let end_ms = common_time::util::current_time_millis();
84        Self {
85            start: lit(ScalarValue::TimestampMillisecond(
86                Some(end_ms - 60 * 60 * 1000),
87                None,
88            )),
89            end: lit(ScalarValue::TimestampMillisecond(Some(end_ms), None)),
90        }
91    }
92}
93
94/// An `INTERVAL` literal of `nanos` nanoseconds.
95fn interval(nanos: i64) -> Expr {
96    lit(ScalarValue::new_interval_mdn(0, 0, nanos))
97}
98
99fn bin_interval() -> Expr {
100    interval(BIN_NANOS)
101}
102
103/// `date_bin(60s, ts)` cast to millisecond precision, so the output schema is
104/// deterministic regardless of the source column's precision (trace tables are
105/// nanosecond, metric tables millisecond).
106fn bin_ms(ts: Expr) -> Expr {
107    cast(
108        datetime_fns::date_bin().call(vec![bin_interval(), ts]),
109        DataType::Timestamp(TimeUnit::Millisecond, None),
110    )
111}
112
113/// Folds union branches without requiring a non-empty input.
114fn union_all(acc: Option<DataFrame>, branch: DataFrame) -> DfResult<Option<DataFrame>> {
115    Ok(Some(match acc {
116        Some(acc) => acc.union(branch)?,
117        None => branch,
118    }))
119}
120
121/// A column reference qualified by a join-side alias, built without string
122/// parsing (so column names containing `.` or `"` stay verbatim).
123fn qcol(relation: &str, name: &str) -> Expr {
124    Expr::Column(Column::new(Some(relation), name))
125}
126
127fn concat_expr(parts: Vec<Expr>) -> Expr {
128    string_fns::concat().call(parts)
129}
130
131/// `coalesce(CAST(column AS STRING), '')`: renders a nullable column for string
132/// concatenation without collapsing the result to NULL.
133fn cast_string_or_empty(column: &str) -> Expr {
134    core_fns::coalesce().call(vec![cast(ident(column), DataType::Utf8), lit("")])
135}
136
137/// The canonical entity-id expression for `id_columns`: the value verbatim for
138/// a single column, the sorted `k=v,k=v` rendering for a composite. `col`
139/// constructs the column reference (unqualified for registry branches,
140/// join-side-qualified for the calls derivation).
141fn entity_id_expr(id_columns: &[String], col: &dyn Fn(&str) -> Expr) -> Expr {
142    if let [id] = id_columns {
143        cast(col(id), DataType::Utf8)
144    } else {
145        let mut cols = id_columns.to_vec();
146        cols.sort();
147        sorted_kv_expr_with(&cols, false, col)
148    }
149}
150
151/// The `parse_json` UDF, shared by all derivation plans. Resolved from the
152/// global registry once: the UDF is stateless (its `FunctionContext` is unused).
153static PARSE_JSON_UDF: LazyLock<Arc<ScalarUDF>> = LazyLock::new(|| {
154    Arc::new(
155        FUNCTION_REGISTRY
156            .get_function("parse_json")
157            .expect("parse_json must be registered")
158            .provide(FunctionContext::default()),
159    )
160});
161
162/// Parses a JSON text expression into a JSONB value, cast from the UDF's
163/// `BinaryView` output to `Binary` — the storage type the computed tables'
164/// declared `json` columns map to in Arrow.
165fn parse_json_expr(json_text: Expr) -> Expr {
166    cast(PARSE_JSON_UDF.call(vec![json_text]), DataType::Binary)
167}
168
169/// A NULL literal typed as JSONB storage (`Binary`), so branches without a JSON
170/// value union-align with branches that produce one.
171fn null_json() -> Expr {
172    lit(ScalarValue::Binary(None))
173}
174
175/// Renders a compile-time-known string as JSON text (quoted, fully escaped —
176/// including control characters, unlike the runtime value escaping).
177fn json_quote(value: &str) -> String {
178    serde_json::Value::from(value).to_string()
179}
180
181/// Wraps a column reference in `replace` calls so its runtime value is
182/// JSON-escaped (`\` then `"`); NULL becomes `''` so one NULL column does not
183/// invalidate the whole JSON text (descriptive columns are nullable).
184fn json_escaped_value_expr(column: &str) -> Expr {
185    let escaped_backslash =
186        string_fns::replace().call(vec![cast_string_or_empty(column), lit("\\"), lit("\\\\")]);
187    string_fns::replace().call(vec![escaped_backslash, lit("\""), lit("\\\"")])
188}
189
190/// Builds a JSONB object from `columns` by concatenating a JSON text and parsing
191/// it — GreptimeDB has no struct→json function. Keys are JSON-escaped in Rust;
192/// values are JSON-escaped at runtime via [`json_escaped_value_expr`].
193///
194/// TODO(entity-graph): replace the text round-trip with a UDF that assembles
195/// JSONB directly from the value columns (`jsonb::ObjectBuilder`, keys baked
196/// in), dropping the escaping helpers and the per-row parse cost.
197fn json_object_expr(columns: &[String]) -> Expr {
198    if columns.is_empty() {
199        return parse_json_expr(lit("{}"));
200    }
201    let mut parts = vec![lit("{")];
202    for (i, column) in columns.iter().enumerate() {
203        if i > 0 {
204            parts.push(lit(","));
205        }
206        parts.push(lit(format!("{}:\"", json_quote(column))));
207        parts.push(json_escaped_value_expr(column));
208        parts.push(lit("\""));
209    }
210    parts.push(lit("}"));
211    parse_json_expr(concat_expr(parts))
212}
213
214/// Renders pre-sorted columns as a `k=v,k=v` concatenation. `nullable`
215/// coalesces each value to `''` (id columns are tags and non-null; scope
216/// columns carry no such guarantee).
217fn sorted_kv_expr_with(sorted_cols: &[String], nullable: bool, col: &dyn Fn(&str) -> Expr) -> Expr {
218    let mut parts = Vec::with_capacity(sorted_cols.len() * 3);
219    for (i, column) in sorted_cols.iter().enumerate() {
220        if i > 0 {
221            parts.push(lit(","));
222        }
223        parts.push(lit(format!("{column}=")));
224        parts.push(if nullable {
225            core_fns::coalesce().call(vec![cast(col(column), DataType::Utf8), lit("")])
226        } else {
227            cast(col(column), DataType::Utf8)
228        });
229    }
230    concat_expr(parts)
231}
232
233const REGISTRY_COLUMNS: [&str; 10] = [
234    "observed_at",
235    "window_start",
236    "window_end",
237    "fresh_until",
238    "entity_type",
239    "entity_id",
240    "entity_id_attrs",
241    "scope",
242    "descriptive",
243    "source_tables",
244];
245
246const REGISTRY_VALID_COLUMN: &str = "__entity_valid";
247
248/// Projects all entity declarations of one source table with one source scan.
249///
250/// Each output field is first built as an array whose entries correspond to the
251/// table's declarations. Unnesting the arrays expands one source row into one
252/// row per declared entity without cloning the table scan under `UNION ALL`.
253fn registry_source(
254    first: &EntityDeclaration,
255    rest: &[EntityDeclaration],
256    df: DataFrame,
257    window: &GraphWindow,
258) -> DfResult<DataFrame> {
259    let ts = ident(&first.time_index);
260    let bin = bin_ms(ts.clone());
261    let window_predicate = ts
262        .clone()
263        .gt_eq(window.start.clone())
264        .and(ts.lt(window.end.clone()));
265
266    let mut arrays = vec![Vec::new(); REGISTRY_COLUMNS.len() + 1];
267    for decl in std::iter::once(first).chain(rest) {
268        // CAST even a single-column id: id columns must be tags but not
269        // necessarily strings, and the computed table declares entity_id
270        // STRING. Composite ids additionally carry a JSON object of the id
271        // columns in entity_id_attrs.
272        let entity_id = entity_id_expr(&decl.id_columns, &|c| ident(c));
273        let entity_id_attrs = if decl.id_columns.len() == 1 {
274            null_json()
275        } else {
276            let mut cols = decl.id_columns.clone();
277            cols.sort();
278            json_object_expr(&cols)
279        };
280
281        let scope = match decl.scope_columns.as_slice() {
282            [] => lit(""),
283            // Scope columns are not required to be tags, so guard against NULL.
284            [single] => cast_string_or_empty(single),
285            _ => {
286                let mut cols = decl.scope_columns.clone();
287                cols.sort();
288                sorted_kv_expr_with(&cols, true, &|c| ident(c))
289            }
290        };
291
292        let descriptive = if decl.descriptive_columns.is_empty() {
293            null_json()
294        } else {
295            json_object_expr(&decl.descriptive_columns)
296        };
297
298        let source_tables = parse_json_expr(lit(format!(
299            "[{}]",
300            json_quote(&format!("{}.{}", decl.schema, decl.table))
301        )));
302
303        // Tag columns may still be nullable; a NULL identity component
304        // identifies nothing. Keep this predicate per declaration so a NULL
305        // identity for one entity does not remove other entities on the row.
306        let valid = decl.id_columns.iter().fold(lit(true), |predicate, id| {
307            predicate.and(ident(id).is_not_null())
308        });
309
310        let row = [
311            valid,
312            bin.clone(),
313            bin.clone(),
314            bin.clone() + bin_interval(),
315            bin.clone() + bin_interval(),
316            lit(decl.entity_type.as_str()),
317            entity_id,
318            entity_id_attrs,
319            scope,
320            descriptive,
321            source_tables,
322        ];
323        for (array, value) in arrays.iter_mut().zip(row) {
324            array.push(value);
325        }
326    }
327
328    let array_names = std::iter::once(REGISTRY_VALID_COLUMN)
329        .chain(REGISTRY_COLUMNS)
330        .collect::<Vec<_>>();
331    let array_projection = array_names
332        .iter()
333        .zip(arrays)
334        .map(|(name, values)| make_array(values).alias(*name))
335        .collect::<Vec<_>>();
336
337    df.filter(window_predicate)?
338        .select(array_projection)?
339        .unnest_columns(&array_names)?
340        .filter(ident(REGISTRY_VALID_COLUMN))?
341        .select(REGISTRY_COLUMNS.into_iter().map(ident).collect::<Vec<_>>())?
342        .distinct()
343}
344
345/// A declaring table's scan paired with the entity declarations it carries —
346/// the unit `build_registry_plan` derives registry rows from.
347pub struct RegistrySource {
348    pub declarations: Vec<EntityDeclaration>,
349    pub scan: DataFrame,
350}
351
352/// A trace table's scan paired with the `service` declaration it derives
353/// `calls` edges for — the unit `build_calls_plan` consumes.
354pub struct CallsSource {
355    pub service: EntityDeclaration,
356    pub scan: DataFrame,
357}
358
359/// Builds the `semantic_entities` registry plan: one branch and source scan per
360/// declaring table, filtered to `window`, then `UNION ALL` across source tables.
361/// Returns `None` when nothing declared an entity, so the computed table streams
362/// empty.
363pub fn build_registry_plan(
364    sources: Vec<RegistrySource>,
365    window: &GraphWindow,
366) -> DfResult<Option<LogicalPlan>> {
367    let mut union_df: Option<DataFrame> = None;
368    for source in sources {
369        let Some((first, rest)) = source.declarations.split_first() else {
370            continue;
371        };
372        union_df = union_all(union_df, registry_source(first, rest, source.scan, window)?)?;
373    }
374    Ok(union_df.map(DataFrame::into_unoptimized_plan))
375}
376
377/// The projected columns of `semantic_relationships`, in order. Every derived
378/// branch and the declared-edge scan must project exactly these so the top-level
379/// `UNION ALL` type-aligns. (The physical declared table additionally stores
380/// `valid_from`/`valid_until`, which are applied as a filter, not projected.)
381/// Test-only until the declared-edge union branch lands and enforces it in code.
382#[cfg(test)]
383const RELATIONSHIP_COLUMNS: [&str; 16] = [
384    "observed_at",
385    "window_start",
386    "window_end",
387    "fresh_until",
388    "src_type",
389    "src_id",
390    "dst_type",
391    "dst_id",
392    "rel_type",
393    "provenance",
394    "confidence",
395    "request_count",
396    "error_count",
397    "duration_sum",
398    "duration_count",
399    "attributes",
400];
401
402/// A child server span starts no earlier than 5 minutes before its client span
403/// (clock-skew allowance) and no later than 1 hour after it; the bounds keep the
404/// join windowed instead of pairing arbitrarily distant spans of a long-lived
405/// trace.
406const CHILD_SPAN_EARLY_NANOS: i64 = 5 * 60 * 1_000_000_000;
407const CHILD_SPAN_LATE_NANOS: i64 = 60 * 60 * 1_000_000_000;
408
409/// Builds the `calls` derivation (RFC §3a) over `traces`: pair each client span
410/// with its child server span on `trace_id` + `parent_span_id`, project to
411/// `service`, union the pairs of all trace tables, and aggregate to RED metrics
412/// per 60s window in one pass — so an edge observed across several trace tables
413/// yields one row, not per-table fragments. This is the plan form of the Tempo
414/// servicegraph connector. Virtual-node edges (uninstrumented peers) are a
415/// separate branch, added on top of this. Column names are the fixed
416/// `greptime_trace_v1` schema (the reason `table_data_model = greptime_trace_v1`
417/// is required); `span_status_code` is a string column (`STATUS_CODE_ERROR`),
418/// verified against the trace ingest path. Returns `None` when there is no
419/// trace table.
420pub fn build_calls_plan(
421    traces: Vec<CallsSource>,
422    window: &GraphWindow,
423) -> DfResult<Option<LogicalPlan>> {
424    let mut union_df: Option<DataFrame> = None;
425    for trace in traces {
426        union_df = union_all(union_df, calls_pairs(&trace.service, trace.scan, window)?)?;
427    }
428    let Some(pairs) = union_df else {
429        return Ok(None);
430    };
431
432    let plan = pairs
433        .aggregate(
434            vec![ident("observed_at"), ident("src_id"), ident("dst_id")],
435            vec![
436                count(lit(1)).alias("request_count"),
437                count(lit(1))
438                    .filter(ident("status_code").eq(lit(SPAN_STATUS_ERROR)))
439                    .build()?
440                    .alias("error_count"),
441                sum(ident("duration_nano")).alias("duration_nano_sum"),
442            ],
443        )?
444        .select(vec![
445            ident("observed_at"),
446            ident("observed_at").alias("window_start"),
447            (ident("observed_at") + bin_interval()).alias("window_end"),
448            (ident("observed_at") + bin_interval()).alias("fresh_until"),
449            lit("service").alias("src_type"),
450            ident("src_id"),
451            lit("service").alias("dst_type"),
452            ident("dst_id"),
453            lit("calls").alias("rel_type"),
454            lit("trace").alias("provenance"),
455            lit(1.0_f64).alias("confidence"),
456            ident("request_count"),
457            ident("error_count"),
458            // duration_nano sums in nanoseconds; the contract column is seconds.
459            (cast(ident("duration_nano_sum"), DataType::Float64) / lit(1e9_f64))
460                .alias("duration_sum"),
461            ident("request_count").alias("duration_count"),
462            null_json().alias("attributes"),
463        ])?
464        .into_unoptimized_plan();
465    Ok(Some(plan))
466}
467
468/// One trace table's client/server span pairs, projected to the aggregation
469/// inputs `(observed_at, src_id, dst_id, status_code, duration_nano)`.
470/// Endpoint ids are built from the table's `service` entity declaration, so
471/// edges land on exactly the entity ids the registry emits (a composite
472/// service identity renders the same sorted `k=v` form on both sides).
473fn calls_pairs(
474    service: &EntityDeclaration,
475    trace: DataFrame,
476    window: &GraphWindow,
477) -> DfResult<DataFrame> {
478    let mut client_pred = ident(SPAN_KIND_COLUMN)
479        .eq(lit(SPAN_KIND_CLIENT))
480        .and(ident(TRACE_TIMESTAMP_COLUMN).gt_eq(window.start.clone()))
481        .and(ident(TRACE_TIMESTAMP_COLUMN).lt(window.end.clone()));
482    let mut server_pred = ident(SPAN_KIND_COLUMN)
483        .eq(lit(SPAN_KIND_SERVER))
484        // Static bounds implied by the window and the join's time-proximity
485        // conditions below; the join bounds reference client.timestamp and
486        // cannot prune the server-side scan.
487        .and(
488            ident(TRACE_TIMESTAMP_COLUMN)
489                .gt_eq(window.start.clone() - interval(CHILD_SPAN_EARLY_NANOS)),
490        )
491        .and(
492            ident(TRACE_TIMESTAMP_COLUMN).lt(window.end.clone() + interval(CHILD_SPAN_LATE_NANOS)),
493        );
494    // A NULL identity component identifies nothing, on either endpoint.
495    for id in &service.id_columns {
496        client_pred = client_pred.and(ident(id).is_not_null());
497        server_pred = server_pred.and(ident(id).is_not_null());
498    }
499
500    let client = trace.clone().filter(client_pred)?.alias("client")?;
501    let server = trace.filter(server_pred)?.alias("server")?;
502
503    let join_conditions = vec![
504        qcol("client", TRACE_ID_COLUMN).eq(qcol("server", TRACE_ID_COLUMN)),
505        qcol("server", PARENT_SPAN_ID_COLUMN).eq(qcol("client", SPAN_ID_COLUMN)),
506        qcol("server", TRACE_TIMESTAMP_COLUMN)
507            .gt_eq(qcol("client", TRACE_TIMESTAMP_COLUMN) - interval(CHILD_SPAN_EARLY_NANOS)),
508        qcol("server", TRACE_TIMESTAMP_COLUMN)
509            .lt_eq(qcol("client", TRACE_TIMESTAMP_COLUMN) + interval(CHILD_SPAN_LATE_NANOS)),
510    ];
511
512    client
513        .join_on(server, JoinType::Inner, join_conditions)?
514        .select(vec![
515            bin_ms(qcol("client", TRACE_TIMESTAMP_COLUMN)).alias("observed_at"),
516            // The cast inside entity_id_expr also normalizes tag columns, which
517            // come out of the storage engine dictionary-encoded.
518            entity_id_expr(&service.id_columns, &|c| qcol("client", c)).alias("src_id"),
519            entity_id_expr(&service.id_columns, &|c| qcol("server", c)).alias("dst_id"),
520            qcol("server", SPAN_STATUS_CODE_COLUMN).alias("status_code"),
521            qcol("server", DURATION_NANO_COLUMN).alias("duration_nano"),
522        ])?
523        // Exclude self-calls on the composed identity: an edge needs two
524        // distinct service entities.
525        .filter(ident("src_id").not_eq(ident("dst_id")))
526}
527
528#[cfg(test)]
529mod tests {
530    use std::sync::Arc;
531
532    use common_catalog::consts::SERVICE_NAME_COLUMN;
533    use datafusion::arrow::array::{
534        Array, ArrayRef, BinaryArray, Float64Array, Int64Array, StringArray,
535        TimestampMillisecondArray, TimestampNanosecondArray, UInt64Array,
536    };
537    use datafusion::arrow::datatypes::{Field, Schema};
538    use datafusion::arrow::record_batch::RecordBatch;
539    use datafusion::datasource::MemTable;
540    use datafusion::prelude::SessionContext;
541
542    use super::*;
543
544    fn test_window() -> GraphWindow {
545        GraphWindow {
546            start: lit(ScalarValue::TimestampMillisecond(Some(0), None)),
547            end: lit(ScalarValue::TimestampMillisecond(
548                Some(10 * 60 * 1000),
549                None,
550            )),
551        }
552    }
553
554    async fn collect(ctx: &SessionContext, plan: LogicalPlan) -> Vec<RecordBatch> {
555        ctx.execute_logical_plan(plan)
556            .await
557            .unwrap()
558            .collect()
559            .await
560            .unwrap()
561    }
562
563    fn json_texts(batch: &RecordBatch, column: usize) -> Vec<Option<String>> {
564        let array = batch
565            .column(column)
566            .as_any()
567            .downcast_ref::<BinaryArray>()
568            .unwrap();
569        (0..array.len())
570            .map(|i| {
571                array
572                    .is_valid(i)
573                    .then(|| jsonb::from_slice(array.value(i)).unwrap().to_string())
574            })
575            .collect()
576    }
577
578    fn strings(batch: &RecordBatch, column: usize) -> Vec<String> {
579        let array = batch
580            .column(column)
581            .as_any()
582            .downcast_ref::<StringArray>()
583            .unwrap();
584        (0..array.len())
585            .map(|i| array.value(i).to_string())
586            .collect()
587    }
588
589    /// A metric-like table: ms timestamps, service/pid identity, nullable
590    /// descriptive column with JSON-hostile characters.
591    fn metric_table_ctx() -> SessionContext {
592        let schema = Arc::new(Schema::new(vec![
593            Field::new(
594                "ts",
595                DataType::Timestamp(TimeUnit::Millisecond, None),
596                false,
597            ),
598            Field::new("service_name", DataType::Utf8, false),
599            Field::new("pid", DataType::Int64, false),
600            Field::new("host", DataType::Utf8, true),
601        ]));
602        let batch = RecordBatch::try_new(
603            schema.clone(),
604            vec![
605                Arc::new(TimestampMillisecondArray::from(vec![1_000, 2_000, 61_000])) as ArrayRef,
606                Arc::new(StringArray::from(vec!["cart", "cart", "cart"])),
607                Arc::new(Int64Array::from(vec![42, 42, 42])),
608                Arc::new(StringArray::from(vec![
609                    Some(r#"we"ird\host"#),
610                    None,
611                    Some("h2"),
612                ])),
613            ],
614        )
615        .unwrap();
616        let ctx = SessionContext::new();
617        ctx.register_table(
618            "app_latency",
619            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
620        )
621        .unwrap();
622        ctx
623    }
624
625    fn decl(entity_type: &str, id_columns: &[&str]) -> EntityDeclaration {
626        EntityDeclaration {
627            schema: "public".to_string(),
628            table: "app_latency".to_string(),
629            time_index: "ts".to_string(),
630            entity_type: entity_type.to_string(),
631            id_columns: id_columns.iter().map(|s| s.to_string()).collect(),
632            descriptive_columns: vec![],
633            scope_columns: vec![],
634        }
635    }
636
637    #[tokio::test]
638    async fn registry_single_column_identity() {
639        let ctx = metric_table_ctx();
640        let df = ctx.table("app_latency").await.unwrap();
641        let plan = build_registry_plan(
642            vec![RegistrySource {
643                declarations: vec![decl("service", &["service_name"])],
644                scan: df,
645            }],
646            &test_window(),
647        )
648        .unwrap()
649        .unwrap();
650
651        let names = plan
652            .schema()
653            .fields()
654            .iter()
655            .map(|f| f.name().as_str())
656            .collect::<Vec<_>>();
657        assert_eq!(
658            names,
659            [
660                "observed_at",
661                "window_start",
662                "window_end",
663                "fresh_until",
664                "entity_type",
665                "entity_id",
666                "entity_id_attrs",
667                "scope",
668                "descriptive",
669                "source_tables",
670            ]
671        );
672
673        let batches = collect(&ctx, plan).await;
674        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
675        // 3 rows in 2 distinct 60s bins, all the same entity -> 2 rows.
676        assert_eq!(total, 2);
677        let batch = &batches[0];
678        assert_eq!(strings(batch, 4), vec!["service"; batch.num_rows()]);
679        assert_eq!(strings(batch, 5), vec!["cart"; batch.num_rows()]);
680        // Single-column id -> entity_id_attrs and descriptive are typed-JSON NULLs.
681        assert!(json_texts(batch, 6).iter().all(Option::is_none));
682        assert!(json_texts(batch, 8).iter().all(Option::is_none));
683        assert_eq!(
684            json_texts(batch, 9),
685            vec![Some(r#"["public.app_latency"]"#.to_string()); batch.num_rows()]
686        );
687    }
688
689    #[tokio::test]
690    async fn registry_composite_identity_and_descriptive_escaping() {
691        let ctx = metric_table_ctx();
692        let df = ctx.table("app_latency").await.unwrap();
693        let mut declaration = decl("process", &["service_name", "pid"]);
694        declaration.descriptive_columns = vec!["host".to_string()];
695        let plan = build_registry_plan(
696            vec![RegistrySource {
697                declarations: vec![declaration],
698                scan: df,
699            }],
700            &test_window(),
701        )
702        .unwrap()
703        .unwrap();
704
705        let batches = collect(&ctx, plan).await;
706        let mut rows: Vec<(String, Option<String>, Option<String>)> = batches
707            .iter()
708            .flat_map(|batch| {
709                let ids = strings(batch, 5);
710                let id_attrs = json_texts(batch, 6);
711                let descriptives = json_texts(batch, 8);
712                ids.into_iter()
713                    .zip(id_attrs)
714                    .zip(descriptives)
715                    .map(|((id, attrs), descriptive)| (id, attrs, descriptive))
716                    .collect::<Vec<_>>()
717            })
718            .collect();
719        rows.sort();
720
721        // Composite id -> sorted `k=v,k=v` plus a JSON object of the id columns;
722        // descriptive JSON escapes `\` and `"` in runtime values, NULL -> "".
723        assert_eq!(
724            rows,
725            vec![
726                (
727                    "pid=42,service_name=cart".to_string(),
728                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
729                    Some(r#"{"host":""}"#.to_string()),
730                ),
731                (
732                    "pid=42,service_name=cart".to_string(),
733                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
734                    Some(r#"{"host":"h2"}"#.to_string()),
735                ),
736                (
737                    "pid=42,service_name=cart".to_string(),
738                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
739                    Some(r#"{"host":"we\"ird\\host"}"#.to_string()),
740                ),
741            ]
742        );
743    }
744
745    #[tokio::test]
746    async fn registry_scope_variants() {
747        let ctx = metric_table_ctx();
748
749        // Single scope column: its (NULL-safe) value verbatim.
750        let mut single = decl("service", &["service_name"]);
751        single.scope_columns = vec!["host".to_string()];
752        let df = ctx.table("app_latency").await.unwrap();
753        let plan = build_registry_plan(
754            vec![RegistrySource {
755                declarations: vec![single],
756                scan: df,
757            }],
758            &test_window(),
759        )
760        .unwrap()
761        .unwrap();
762        let batches = collect(&ctx, plan).await;
763        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
764        scopes.sort();
765        assert_eq!(scopes, vec!["", "h2", r#"we"ird\host"#]);
766
767        // Multiple scope columns: sorted `k=v,k=v`.
768        let mut multi = decl("service", &["service_name"]);
769        multi.scope_columns = vec!["pid".to_string(), "host".to_string()];
770        let df = ctx.table("app_latency").await.unwrap();
771        let plan = build_registry_plan(
772            vec![RegistrySource {
773                declarations: vec![multi],
774                scan: df,
775            }],
776            &test_window(),
777        )
778        .unwrap()
779        .unwrap();
780        let batches = collect(&ctx, plan).await;
781        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
782        scopes.sort();
783        assert_eq!(
784            scopes,
785            vec![
786                "host=,pid=42",
787                "host=h2,pid=42",
788                r#"host=we"ird\host,pid=42"#
789            ]
790        );
791    }
792
793    #[tokio::test]
794    async fn registry_skips_null_identity_rows() {
795        let ctx = metric_table_ctx();
796        let df = ctx.table("app_latency").await.unwrap();
797        let plan = build_registry_plan(
798            vec![RegistrySource {
799                declarations: vec![decl("host", &["host"])],
800                scan: df,
801            }],
802            &test_window(),
803        )
804        .unwrap()
805        .unwrap();
806        let batches = collect(&ctx, plan).await;
807        let mut ids: Vec<String> = batches.iter().flat_map(|b| strings(b, 5)).collect();
808        ids.sort();
809        assert_eq!(ids, vec!["h2", r#"we"ird\host"#]);
810    }
811
812    #[tokio::test]
813    async fn registry_expands_declarations_with_one_source_scan() {
814        let ctx = metric_table_ctx();
815        let df = ctx.table("app_latency").await.unwrap();
816        let plan = build_registry_plan(
817            vec![RegistrySource {
818                declarations: vec![decl("service", &["service_name"]), decl("host", &["pid"])],
819                scan: df,
820            }],
821            &test_window(),
822        )
823        .unwrap()
824        .unwrap();
825
826        assert_eq!(
827            plan.display_indent()
828                .to_string()
829                .matches("TableScan: app_latency")
830                .count(),
831            1
832        );
833        let batches = collect(&ctx, plan).await;
834        let mut types: Vec<String> = batches.iter().flat_map(|b| strings(b, 4)).collect();
835        types.sort();
836        assert_eq!(types, vec!["host", "host", "service", "service"]);
837
838        // No declarations -> no plan.
839        assert!(
840            build_registry_plan(vec![], &test_window())
841                .unwrap()
842                .is_none()
843        );
844    }
845
846    /// A trace-like table in the fixed `greptime_trace_v1` shape (ns timestamps).
847    fn trace_table_ctx() -> SessionContext {
848        let schema = Arc::new(Schema::new(vec![
849            Field::new(
850                TRACE_TIMESTAMP_COLUMN,
851                DataType::Timestamp(TimeUnit::Nanosecond, None),
852                false,
853            ),
854            Field::new(TRACE_ID_COLUMN, DataType::Utf8, false),
855            Field::new(SPAN_ID_COLUMN, DataType::Utf8, false),
856            Field::new(PARENT_SPAN_ID_COLUMN, DataType::Utf8, true),
857            Field::new(SPAN_KIND_COLUMN, DataType::Utf8, false),
858            Field::new(SPAN_STATUS_CODE_COLUMN, DataType::Utf8, false),
859            Field::new(SERVICE_NAME_COLUMN, DataType::Utf8, false),
860            Field::new("service_namespace", DataType::Utf8, false),
861            Field::new(DURATION_NANO_COLUMN, DataType::UInt64, false),
862        ]));
863        const MS: i64 = 1_000_000;
864        // Two client->server pairs frontend->cart (one errored), one pair
865        // cart->cart (self-call, excluded), one unmatched client span.
866        let batch = RecordBatch::try_new(
867            schema.clone(),
868            vec![
869                Arc::new(TimestampNanosecondArray::from(vec![
870                    1_000 * MS, // client frontend->cart
871                    1_010 * MS, //   server cart
872                    2_000 * MS, // client frontend->cart (error)
873                    2_010 * MS, //   server cart (error)
874                    3_000 * MS, // client cart->cart (self-call)
875                    3_010 * MS, //   server cart
876                    4_000 * MS, // client with no matching server
877                ])) as ArrayRef,
878                Arc::new(StringArray::from(vec![
879                    "t1", "t1", "t2", "t2", "t3", "t3", "t4",
880                ])),
881                Arc::new(StringArray::from(vec![
882                    "c1", "s1", "c2", "s2", "c3", "s3", "c4",
883                ])),
884                Arc::new(StringArray::from(vec![
885                    None,
886                    Some("c1"),
887                    None,
888                    Some("c2"),
889                    None,
890                    Some("c3"),
891                    None,
892                ])),
893                Arc::new(StringArray::from(vec![
894                    "SPAN_KIND_CLIENT",
895                    "SPAN_KIND_SERVER",
896                    "SPAN_KIND_CLIENT",
897                    "SPAN_KIND_SERVER",
898                    "SPAN_KIND_CLIENT",
899                    "SPAN_KIND_SERVER",
900                    "SPAN_KIND_CLIENT",
901                ])),
902                Arc::new(StringArray::from(vec![
903                    "STATUS_CODE_UNSET",
904                    "STATUS_CODE_UNSET",
905                    "STATUS_CODE_UNSET",
906                    "STATUS_CODE_ERROR",
907                    "STATUS_CODE_UNSET",
908                    "STATUS_CODE_UNSET",
909                    "STATUS_CODE_UNSET",
910                ])),
911                Arc::new(StringArray::from(vec![
912                    "frontend", "cart", "frontend", "cart", "cart", "cart", "frontend",
913                ])),
914                Arc::new(StringArray::from(vec!["ns1"; 7])),
915                Arc::new(UInt64Array::from(vec![
916                    0,
917                    500_000_000, // 0.5s
918                    0,
919                    1_500_000_000, // 1.5s
920                    0,
921                    100,
922                    0,
923                ])),
924            ],
925        )
926        .unwrap();
927        let ctx = SessionContext::new();
928        ctx.register_table(
929            "opentelemetry_traces",
930            Arc::new(MemTable::try_new(schema.clone(), vec![vec![batch.clone()]]).unwrap()),
931        )
932        .unwrap();
933        ctx.register_table(
934            "opentelemetry_traces_2",
935            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
936        )
937        .unwrap();
938        ctx
939    }
940
941    fn trace_service_decl(id_columns: &[&str]) -> EntityDeclaration {
942        EntityDeclaration {
943            schema: "public".to_string(),
944            table: "opentelemetry_traces".to_string(),
945            time_index: TRACE_TIMESTAMP_COLUMN.to_string(),
946            entity_type: "service".to_string(),
947            id_columns: id_columns.iter().map(|s| s.to_string()).collect(),
948            descriptive_columns: vec![],
949            scope_columns: vec![],
950        }
951    }
952
953    #[tokio::test]
954    async fn calls_plan_aggregates_red_metrics() {
955        let ctx = trace_table_ctx();
956        let trace = ctx.table("opentelemetry_traces").await.unwrap();
957        let plan = build_calls_plan(
958            vec![CallsSource {
959                service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
960                scan: trace,
961            }],
962            &test_window(),
963        )
964        .unwrap()
965        .unwrap();
966
967        let names = plan
968            .schema()
969            .fields()
970            .iter()
971            .map(|f| f.name().as_str())
972            .collect::<Vec<_>>();
973        assert_eq!(names, RELATIONSHIP_COLUMNS);
974
975        let batches = collect(&ctx, plan).await;
976        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
977        // frontend->cart only: the self-call and the unmatched client drop out;
978        // both pairs land in the same 60s bin.
979        assert_eq!(total, 1);
980        let batch = &batches[0];
981        assert_eq!(strings(batch, 5), vec!["frontend"]);
982        assert_eq!(strings(batch, 7), vec!["cart"]);
983        assert_eq!(strings(batch, 8), vec!["calls"]);
984        assert_eq!(strings(batch, 9), vec!["trace"]);
985
986        let request_count = batch
987            .column(11)
988            .as_any()
989            .downcast_ref::<Int64Array>()
990            .unwrap();
991        assert_eq!(request_count.value(0), 2);
992        let error_count = batch
993            .column(12)
994            .as_any()
995            .downcast_ref::<Int64Array>()
996            .unwrap();
997        assert_eq!(error_count.value(0), 1);
998        let duration_sum = batch
999            .column(13)
1000            .as_any()
1001            .downcast_ref::<Float64Array>()
1002            .unwrap();
1003        assert!((duration_sum.value(0) - 2.0).abs() < 1e-9);
1004        let duration_count = batch
1005            .column(14)
1006            .as_any()
1007            .downcast_ref::<Int64Array>()
1008            .unwrap();
1009        assert_eq!(duration_count.value(0), 2);
1010        // Derived calls edges carry no attributes: a typed-JSON NULL.
1011        assert!(json_texts(batch, 15)[0].is_none());
1012    }
1013
1014    #[tokio::test]
1015    async fn calls_plan_merges_edges_across_trace_tables() {
1016        let ctx = trace_table_ctx();
1017        let t1 = ctx.table("opentelemetry_traces").await.unwrap();
1018        let t2 = ctx.table("opentelemetry_traces_2").await.unwrap();
1019        let plan = build_calls_plan(
1020            vec![
1021                CallsSource {
1022                    service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1023                    scan: t1,
1024                },
1025                CallsSource {
1026                    service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1027                    scan: t2,
1028                },
1029            ],
1030            &test_window(),
1031        )
1032        .unwrap()
1033        .unwrap();
1034
1035        let batches = collect(&ctx, plan).await;
1036        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1037        // The same frontend->cart edge from both tables folds into one row with
1038        // summed RED metrics.
1039        assert_eq!(total, 1);
1040        let batch = &batches[0];
1041        let request_count = batch
1042            .column(11)
1043            .as_any()
1044            .downcast_ref::<Int64Array>()
1045            .unwrap();
1046        assert_eq!(request_count.value(0), 4);
1047        let error_count = batch
1048            .column(12)
1049            .as_any()
1050            .downcast_ref::<Int64Array>()
1051            .unwrap();
1052        assert_eq!(error_count.value(0), 2);
1053        let duration_sum = batch
1054            .column(13)
1055            .as_any()
1056            .downcast_ref::<Float64Array>()
1057            .unwrap();
1058        assert!((duration_sum.value(0) - 4.0).abs() < 1e-9);
1059    }
1060
1061    #[tokio::test]
1062    async fn calls_endpoints_follow_service_declaration() {
1063        let ctx = trace_table_ctx();
1064        let trace = ctx.table("opentelemetry_traces").await.unwrap();
1065        let plan = build_calls_plan(
1066            vec![CallsSource {
1067                service: trace_service_decl(&[SERVICE_NAME_COLUMN, "service_namespace"]),
1068                scan: trace,
1069            }],
1070            &test_window(),
1071        )
1072        .unwrap()
1073        .unwrap();
1074
1075        let batches = collect(&ctx, plan).await;
1076        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1077        assert_eq!(total, 1);
1078        let batch = &batches[0];
1079        // Composite service identity renders the same sorted `k=v` form the
1080        // registry emits, so edges land on registry entity ids.
1081        assert_eq!(
1082            strings(batch, 5),
1083            vec!["service_name=frontend,service_namespace=ns1"]
1084        );
1085        assert_eq!(
1086            strings(batch, 7),
1087            vec!["service_name=cart,service_namespace=ns1"]
1088        );
1089    }
1090}