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//! The entity-relationship graph: the physical declared-edge table DDL and the
16//! typed DataFusion plan builders for the read-time derivation behind the
17//! computed `semantic_entities` / `semantic_relationships` tables.
18//!
19//! In OSS the graph is derived at read time, so the *only* stored part is the
20//! declared-edge table: edges a user asserts by hand (`provenance = 'declared'`).
21//!
22//! The derivation is built as typed [`Expr`]s over [`DataFrame`]s (never as SQL
23//! text), so user-controlled identifiers are plain values — no quoting or SQL
24//! injection surface — and the plans compose with DataFusion's optimizer,
25//! including filter pushdown into the source table scans. See
26//! `docs/rfcs/2026-06-25-entity-relationships-and-graph-query.md`.
27
28use std::sync::{Arc, LazyLock};
29
30use api::v1::column_data_type_extension::TypeExt;
31use api::v1::{
32    ColumnDataType, ColumnDataTypeExtension, ColumnDef, CreateTableExpr, JsonTypeExtension,
33    SemanticType,
34};
35use common_catalog::consts::{
36    DEFAULT_PRIVATE_SCHEMA_NAME, DURATION_NANO_COLUMN, PARENT_SPAN_ID_COLUMN,
37    SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME, SPAN_ID_COLUMN, SPAN_KIND_CLIENT, SPAN_KIND_COLUMN,
38    SPAN_KIND_SERVER, SPAN_STATUS_CODE_COLUMN, SPAN_STATUS_ERROR, TRACE_ID_COLUMN,
39    TRACE_TIMESTAMP_COLUMN,
40};
41use common_function::function::FunctionContext;
42use common_function::function_registry::FUNCTION_REGISTRY;
43use datafusion::arrow::datatypes::{DataType, TimeUnit};
44use datafusion::dataframe::DataFrame;
45use datafusion::functions::{core as core_fns, datetime as datetime_fns, string as string_fns};
46use datafusion::functions_aggregate::expr_fn::{count, sum};
47use datafusion::functions_nested::expr_fn::make_array;
48use datafusion::functions_window::expr_fn::row_number;
49use datafusion_common::{Column, Result as DfResult, ScalarValue};
50use datafusion_expr::{Expr, ExprFunctionExt, JoinType, LogicalPlan, ScalarUDF, cast, ident, lit};
51use store_api::mito_engine_options::{APPEND_MODE_KEY, MERGE_MODE_KEY, TTL_KEY};
52
53/// Whether an existing declared-edge table still matches the canonical
54/// definition ([`build_declared_relationships_expr`]): columns, time index,
55/// primary key, engine, and merge behaviour — the union branch's revision and
56/// dedup semantics lean on all of these. A mismatch (upgrade skew) must be
57/// surfaced, not silently derived wrong; DROP resets the table.
58pub fn declared_relationships_schema_matches(table_info: &table::metadata::TableInfo) -> bool {
59    let meta = &table_info.meta;
60    if meta.engine != common_catalog::consts::MITO_ENGINE {
61        return false;
62    }
63    let schema = &meta.schema;
64    if schema
65        .timestamp_column()
66        .is_none_or(|column| column.name != OBSERVED_AT_COLUMN)
67    {
68        return false;
69    }
70    let primary_keys = meta
71        .primary_key_indices
72        .iter()
73        .filter_map(|idx| schema.column_schemas().get(*idx))
74        .map(|column| column.name.as_str());
75    if !primary_keys.eq(DECLARED_PRIMARY_KEY_COLUMNS) {
76        return false;
77    }
78    // LastRow merge is what makes a re-asserted edge a *revision*; append mode
79    // or another merge mode would change the read-side dedup semantics.
80    let options = &meta.options.extra_options;
81    if options.get(APPEND_MODE_KEY).map(String::as_str) == Some("true")
82        || options
83            .get(MERGE_MODE_KEY)
84            .is_some_and(|mode| mode != "last_row")
85    {
86        return false;
87    }
88
89    let canonical = build_declared_relationships_expr("greptime");
90    if schema.column_schemas().len() != canonical.column_defs.len() {
91        return false;
92    }
93    canonical
94        .column_defs
95        .iter()
96        .zip(schema.column_schemas())
97        .all(|(def, column)| {
98            let Ok(wrapper) = api::helper::ColumnDataTypeWrapper::try_new(
99                def.data_type,
100                def.datatype_extension.clone(),
101            ) else {
102                return false;
103            };
104            def.name == column.name
105                && datatypes::prelude::ConcreteDataType::from(wrapper) == column.data_type
106        })
107}
108
109/// Bin width for the temporal window of derived rows: 60s buckets, matching the
110/// service-graph convention.
111const BIN_NANOS: i64 = 60 * 1_000_000_000;
112
113/// Time index of the graph tables: when an observation was recorded.
114pub const OBSERVED_AT_COLUMN: &str = "observed_at";
115
116/// Default retention for the declared-edge table; expiry slides the topology window.
117const DEFAULT_DECLARED_RELATIONSHIPS_TTL: &str = "90d";
118/// Environment variable overriding the declared-edge table's TTL at creation
119/// time (e.g. `180d`, `forever`).
120// TODO(entity-graph): promote this to a real configuration option.
121const DECLARED_RELATIONSHIPS_TTL_ENV: &str = "GREPTIMEDB_DECLARED_RELATIONSHIPS_TTL";
122
123fn declared_relationships_ttl() -> String {
124    std::env::var(DECLARED_RELATIONSHIPS_TTL_ENV)
125        .ok()
126        .map(|ttl| ttl.trim().to_string())
127        .filter(|ttl| !ttl.is_empty())
128        .unwrap_or_else(|| DEFAULT_DECLARED_RELATIONSHIPS_TTL.to_string())
129}
130
131/// The primary-key (tag) columns, in key order. Starting with the source endpoint
132/// makes out-edge lookup (`WHERE src_type=? AND src_id=?`) a key-prefix scan;
133/// `provenance` and `generation_id` are in the key so a declared edge and a
134/// (future) derived edge for the same pair coexist without clobbering.
135pub const DECLARED_PRIMARY_KEY_COLUMNS: [&str; 8] = [
136    "src_type",
137    "src_id",
138    "rel_type",
139    "dst_type",
140    "dst_id",
141    "provenance",
142    "scope",
143    "generation_id",
144];
145
146/// The externally visible edge identity: the primary key minus `scope` and
147/// `generation_id`, which the computed table does not expose. Revision ranking
148/// uses this identity, or assertions differing only in those two columns would
149/// surface as indistinguishable duplicate rows.
150const DECLARED_EDGE_IDENTITY_COLUMNS: [&str; 6] = [
151    "src_type",
152    "src_id",
153    "rel_type",
154    "dst_type",
155    "dst_id",
156    "provenance",
157];
158
159fn column(
160    name: &str,
161    data_type: ColumnDataType,
162    semantic_type: SemanticType,
163    nullable: bool,
164) -> ColumnDef {
165    ColumnDef {
166        name: name.to_string(),
167        data_type: data_type as i32,
168        is_nullable: nullable,
169        default_constraint: vec![],
170        semantic_type: semantic_type as i32,
171        comment: String::new(),
172        datatype_extension: None,
173        options: None,
174    }
175}
176
177fn tag(name: &str) -> ColumnDef {
178    column(name, ColumnDataType::String, SemanticType::Tag, false)
179}
180
181fn field(name: &str, data_type: ColumnDataType) -> ColumnDef {
182    column(name, data_type, SemanticType::Field, true)
183}
184
185fn json_field(name: &str) -> ColumnDef {
186    let mut def = field(name, ColumnDataType::Binary);
187    def.datatype_extension = Some(ColumnDataTypeExtension {
188        type_ext: Some(TypeExt::JsonType(JsonTypeExtension::JsonBinary.into())),
189    });
190    def
191}
192
193/// Builds the `CREATE TABLE` request for the declared-edge table. Columns mirror
194/// the computed `semantic_relationships` shape (temporal window + endpoints +
195/// provenance/confidence + RED metrics) plus the declared-only business validity
196/// window (`valid_from` / `valid_until`), which — unlike TTL (physical retention)
197/// — expresses whether a hand-declared edge is still in effect.
198///
199/// The default `LastRow` merge dedups on primary key **plus** `observed_at`
200/// (the time index is part of mito's dedup key): re-asserting an edge at a new
201/// `observed_at` stores a new revision, and the read-side union keeps only the
202/// latest revision per edge key.
203pub fn build_declared_relationships_expr(catalog: &str) -> CreateTableExpr {
204    let column_defs = vec![
205        // Temporal: when this revision of the edge was declared (time index,
206        // also the TTL clock).
207        column(
208            OBSERVED_AT_COLUMN,
209            ColumnDataType::TimestampMillisecond,
210            SemanticType::Timestamp,
211            false,
212        ),
213        field("window_start", ColumnDataType::TimestampMillisecond),
214        field("window_end", ColumnDataType::TimestampMillisecond),
215        field("fresh_until", ColumnDataType::TimestampMillisecond),
216        // Declared-only business validity. NULL valid_from = valid since the
217        // declaration; NULL valid_until = valid for as long as the row exists
218        // (TTL expiry retires the edge with the row).
219        field("valid_from", ColumnDataType::TimestampMillisecond),
220        field("valid_until", ColumnDataType::TimestampMillisecond),
221        // Endpoints + edge identity (all tags, in primary-key order).
222        tag("src_type"),
223        tag("src_id"),
224        tag("rel_type"),
225        tag("dst_type"),
226        tag("dst_id"),
227        tag("provenance"),
228        tag("scope"),
229        tag("generation_id"),
230        // Confidence + RED metrics (populated for derived edges; usually NULL here).
231        field("confidence", ColumnDataType::Float64),
232        field("request_count", ColumnDataType::Int64),
233        field("error_count", ColumnDataType::Int64),
234        field("duration_sum", ColumnDataType::Float64),
235        field("duration_count", ColumnDataType::Int64),
236        // JSONB, so the union matches the computed table's json column
237        // without a per-scan parse.
238        json_field("attributes"),
239    ];
240
241    let table_options = [(TTL_KEY.to_string(), declared_relationships_ttl())]
242        .into_iter()
243        .collect();
244
245    CreateTableExpr {
246        catalog_name: catalog.to_string(),
247        schema_name: DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
248        table_name: SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME.to_string(),
249        desc: "Hand-declared edges of the entity-relationship graph".to_string(),
250        column_defs,
251        time_index: OBSERVED_AT_COLUMN.to_string(),
252        primary_keys: DECLARED_PRIMARY_KEY_COLUMNS
253            .iter()
254            .map(|c| c.to_string())
255            .collect(),
256        create_if_not_exists: true,
257        table_options,
258        table_id: None,
259        engine: common_catalog::consts::MITO_ENGINE.to_string(),
260    }
261}
262
263/// A single table's entity-identity declaration, projected from
264/// `information_schema.table_semantics` (`greptime.semantic.entity.<type>.*`).
265#[derive(Debug, Clone)]
266pub struct EntityDeclaration {
267    /// The declaring table's schema, for the qualified `source_tables` lineage.
268    pub schema: String,
269    /// The declaring table's name, recorded in `source_tables`.
270    pub table: String,
271    /// The table's time index column, used for the temporal window filter.
272    pub time_index: String,
273    pub entity_type: String,
274    /// Identifying columns (>= 1). One column → id verbatim; several → composite.
275    pub id_columns: Vec<String>,
276    /// Descriptive columns snapshotted into the `descriptive` JSON (may be empty).
277    pub descriptive_columns: Vec<String>,
278    /// Scope columns (namespace/environment). One column → scope verbatim;
279    /// several → sorted `k=v,k=v`, mirroring the composite id rendering.
280    pub scope_columns: Vec<String>,
281}
282
283/// The read-time query window, resolved from the scan's `observed_at` predicate
284/// (or the product default). Two half-open `[start, end)` millisecond ranges:
285///
286/// - *observed*: the queried `observed_at` range. The scan's filters are
287///   re-applied above the computed table (`FilterPushDownType::Inexact`), so
288///   every emitted row's `observed_at` must fall inside it. The declared-edge
289///   branch also runs its validity overlap against this range.
290/// - *source scan*: `observed` widened to whole 60s buckets. Derived rows are
291///   `date_bin('60s')` aggregates keyed by the bucket start, so a bucket the
292///   observed range selects must be scanned over its full extent — filtering
293///   the source rows to the observed range instead would silently truncate the
294///   RED numbers of the boundary buckets.
295///
296/// The bounds are plain millisecond values turned into timestamp literals on
297/// demand — wall-clock snapshot semantics like `now()`, but as constants they
298/// prune the source table scans without depending on constant-folding.
299#[derive(Debug, Clone)]
300pub struct GraphQueryWindow {
301    observed_start_ms: i64,
302    observed_end_ms: i64,
303    source_start_ms: i64,
304    source_end_ms: i64,
305}
306
307impl GraphQueryWindow {
308    /// Builds the window for the queried `observed_at` range `[start_ms, end_ms)`.
309    pub fn from_observed(start_ms: i64, end_ms: i64) -> Self {
310        const BIN_MS: i64 = BIN_NANOS / 1_000_000;
311        // Ceiling division that stays correct for pre-epoch (negative) values.
312        let ceil_to_bin = |ms: i64| {
313            ms.div_euclid(BIN_MS) * BIN_MS
314                + if ms.rem_euclid(BIN_MS) == 0 {
315                    0
316                } else {
317                    BIN_MS
318                }
319        };
320        // A bucket `b` (a 60s multiple, `date_bin`'s floor of its rows) is
321        // selected when `start <= b < end`: the first is ceil(start) and the
322        // last one's rows extend to ceil(end).
323        Self {
324            observed_start_ms: start_ms,
325            observed_end_ms: end_ms,
326            source_start_ms: ceil_to_bin(start_ms),
327            source_end_ms: ceil_to_bin(end_ms),
328        }
329    }
330
331    /// Conservative default when a query carries no explicit time predicate: the
332    /// last hour, so a bare `SELECT * FROM semantic_entities` never scans every
333    /// declaring table's full history. This is a product default, not a cap.
334    pub fn default_last_hour() -> Self {
335        let end_ms = common_time::util::current_time_millis();
336        Self::from_observed(end_ms - 60 * 60 * 1000, end_ms)
337    }
338
339    /// Start of the queried `observed_at` range (inclusive).
340    pub fn observed_start(&self) -> Expr {
341        ts_ms_lit(self.observed_start_ms)
342    }
343
344    /// End of the queried `observed_at` range (exclusive).
345    pub fn observed_end(&self) -> Expr {
346        ts_ms_lit(self.observed_end_ms)
347    }
348
349    /// Start of the source-table scan range (inclusive).
350    pub fn source_start(&self) -> Expr {
351        ts_ms_lit(self.source_start_ms)
352    }
353
354    /// End of the source-table scan range (exclusive).
355    pub fn source_end(&self) -> Expr {
356        ts_ms_lit(self.source_end_ms)
357    }
358}
359
360fn ts_ms_lit(ms: i64) -> Expr {
361    lit(ScalarValue::TimestampMillisecond(Some(ms), None))
362}
363
364/// An `INTERVAL` literal of `nanos` nanoseconds.
365fn interval(nanos: i64) -> Expr {
366    lit(ScalarValue::new_interval_mdn(0, 0, nanos))
367}
368
369fn bin_interval() -> Expr {
370    interval(BIN_NANOS)
371}
372
373/// `date_bin(60s, ts)` cast to millisecond precision, so the output schema is
374/// deterministic regardless of the source column's precision (trace tables are
375/// nanosecond, metric tables millisecond).
376fn bin_ms(ts: Expr) -> Expr {
377    cast(
378        datetime_fns::date_bin().call(vec![bin_interval(), ts]),
379        DataType::Timestamp(TimeUnit::Millisecond, None),
380    )
381}
382
383/// Folds union branches without requiring a non-empty input.
384fn union_all(acc: Option<DataFrame>, branch: DataFrame) -> DfResult<Option<DataFrame>> {
385    Ok(Some(match acc {
386        Some(acc) => acc.union(branch)?,
387        None => branch,
388    }))
389}
390
391/// A column reference qualified by a join-side alias, built without string
392/// parsing (so column names containing `.` or `"` stay verbatim).
393fn qcol(relation: &str, name: &str) -> Expr {
394    Expr::Column(Column::new(Some(relation), name))
395}
396
397fn concat_expr(parts: Vec<Expr>) -> Expr {
398    string_fns::concat().call(parts)
399}
400
401/// `coalesce(CAST(column AS STRING), '')`: renders a nullable column for string
402/// concatenation without collapsing the result to NULL.
403fn cast_string_or_empty(column: &str) -> Expr {
404    core_fns::coalesce().call(vec![cast(ident(column), DataType::Utf8), lit("")])
405}
406
407/// The canonical entity-id expression for `id_columns`: the value verbatim for
408/// a single column, the sorted `k=v,k=v` rendering for a composite. `col`
409/// constructs the column reference (unqualified for registry branches,
410/// join-side-qualified for the calls derivation).
411fn entity_id_expr(id_columns: &[String], col: &dyn Fn(&str) -> Expr) -> Expr {
412    if let [id] = id_columns {
413        cast(col(id), DataType::Utf8)
414    } else {
415        let mut cols = id_columns.to_vec();
416        cols.sort();
417        sorted_kv_expr_with(&cols, false, col)
418    }
419}
420
421/// The `parse_json` UDF, shared by all derivation plans. Resolved from the
422/// global registry once: the UDF is stateless (its `FunctionContext` is unused).
423static PARSE_JSON_UDF: LazyLock<Arc<ScalarUDF>> = LazyLock::new(|| {
424    Arc::new(
425        FUNCTION_REGISTRY
426            .get_function("parse_json")
427            .expect("parse_json must be registered")
428            .provide(FunctionContext::default()),
429    )
430});
431
432/// Parses a JSON text expression into a JSONB value, cast from the UDF's
433/// `BinaryView` output to `Binary` — the storage type the computed tables'
434/// declared `json` columns map to in Arrow.
435fn parse_json_expr(json_text: Expr) -> Expr {
436    cast(PARSE_JSON_UDF.call(vec![json_text]), DataType::Binary)
437}
438
439/// A NULL literal typed as JSONB storage (`Binary`), so branches without a JSON
440/// value union-align with branches that produce one.
441fn null_json() -> Expr {
442    lit(ScalarValue::Binary(None))
443}
444
445/// Renders a compile-time-known string as JSON text (quoted, fully escaped —
446/// including control characters, unlike the runtime value escaping).
447fn json_quote(value: &str) -> String {
448    serde_json::Value::from(value).to_string()
449}
450
451/// Wraps a column reference in `replace` calls so its runtime value is
452/// JSON-escaped (`\` then `"`); NULL becomes `''` so one NULL column does not
453/// invalidate the whole JSON text (descriptive columns are nullable).
454fn json_escaped_value_expr(column: &str) -> Expr {
455    let escaped_backslash =
456        string_fns::replace().call(vec![cast_string_or_empty(column), lit("\\"), lit("\\\\")]);
457    string_fns::replace().call(vec![escaped_backslash, lit("\""), lit("\\\"")])
458}
459
460/// Builds a JSONB object from `columns` by concatenating a JSON text and parsing
461/// it — GreptimeDB has no struct→json function. Keys are JSON-escaped in Rust;
462/// values are JSON-escaped at runtime via [`json_escaped_value_expr`].
463///
464/// TODO(entity-graph): replace the text round-trip with a UDF that assembles
465/// JSONB directly from the value columns (`jsonb::ObjectBuilder`, keys baked
466/// in), dropping the escaping helpers and the per-row parse cost.
467fn json_object_expr(columns: &[String]) -> Expr {
468    if columns.is_empty() {
469        return parse_json_expr(lit("{}"));
470    }
471    let mut parts = vec![lit("{")];
472    for (i, column) in columns.iter().enumerate() {
473        if i > 0 {
474            parts.push(lit(","));
475        }
476        parts.push(lit(format!("{}:\"", json_quote(column))));
477        parts.push(json_escaped_value_expr(column));
478        parts.push(lit("\""));
479    }
480    parts.push(lit("}"));
481    parse_json_expr(concat_expr(parts))
482}
483
484/// Renders pre-sorted columns as a `k=v,k=v` concatenation. `nullable`
485/// coalesces each value to `''` (id columns are tags and non-null; scope
486/// columns carry no such guarantee).
487fn sorted_kv_expr_with(sorted_cols: &[String], nullable: bool, col: &dyn Fn(&str) -> Expr) -> Expr {
488    let mut parts = Vec::with_capacity(sorted_cols.len() * 3);
489    for (i, column) in sorted_cols.iter().enumerate() {
490        if i > 0 {
491            parts.push(lit(","));
492        }
493        parts.push(lit(format!("{column}=")));
494        parts.push(if nullable {
495            core_fns::coalesce().call(vec![cast(col(column), DataType::Utf8), lit("")])
496        } else {
497            cast(col(column), DataType::Utf8)
498        });
499    }
500    concat_expr(parts)
501}
502
503const REGISTRY_COLUMNS: [&str; 10] = [
504    "observed_at",
505    "window_start",
506    "window_end",
507    "fresh_until",
508    "entity_type",
509    "entity_id",
510    "entity_id_attrs",
511    "scope",
512    "descriptive",
513    "source_tables",
514];
515
516const REGISTRY_VALID_COLUMN: &str = "__entity_valid";
517
518/// Projects all entity declarations of one source table with one source scan.
519///
520/// Each output field is first built as an array whose entries correspond to the
521/// table's declarations. Unnesting the arrays expands one source row into one
522/// row per declared entity without cloning the table scan under `UNION ALL`.
523fn registry_source(
524    first: &EntityDeclaration,
525    rest: &[EntityDeclaration],
526    df: DataFrame,
527    window: &GraphQueryWindow,
528) -> DfResult<DataFrame> {
529    let ts = ident(&first.time_index);
530    let bin = bin_ms(ts.clone());
531    let window_predicate = ts
532        .clone()
533        .gt_eq(window.source_start())
534        .and(ts.lt(window.source_end()));
535
536    let mut arrays = vec![Vec::new(); REGISTRY_COLUMNS.len() + 1];
537    for decl in std::iter::once(first).chain(rest) {
538        // CAST even a single-column id: id columns must be tags but not
539        // necessarily strings, and the computed table declares entity_id
540        // STRING. Composite ids additionally carry a JSON object of the id
541        // columns in entity_id_attrs.
542        let entity_id = entity_id_expr(&decl.id_columns, &|c| ident(c));
543        let entity_id_attrs = if decl.id_columns.len() == 1 {
544            null_json()
545        } else {
546            let mut cols = decl.id_columns.clone();
547            cols.sort();
548            json_object_expr(&cols)
549        };
550
551        let scope = match decl.scope_columns.as_slice() {
552            [] => lit(""),
553            // Scope columns are not required to be tags, so guard against NULL.
554            [single] => cast_string_or_empty(single),
555            _ => {
556                let mut cols = decl.scope_columns.clone();
557                cols.sort();
558                sorted_kv_expr_with(&cols, true, &|c| ident(c))
559            }
560        };
561
562        let descriptive = if decl.descriptive_columns.is_empty() {
563            null_json()
564        } else {
565            json_object_expr(&decl.descriptive_columns)
566        };
567
568        let source_tables = parse_json_expr(lit(format!(
569            "[{}]",
570            json_quote(&format!("{}.{}", decl.schema, decl.table))
571        )));
572
573        // Tag columns may still be nullable; a NULL identity component
574        // identifies nothing. Keep this predicate per declaration so a NULL
575        // identity for one entity does not remove other entities on the row.
576        let valid = decl.id_columns.iter().fold(lit(true), |predicate, id| {
577            predicate.and(ident(id).is_not_null())
578        });
579
580        let row = [
581            valid,
582            bin.clone(),
583            bin.clone(),
584            bin.clone() + bin_interval(),
585            bin.clone() + bin_interval(),
586            lit(decl.entity_type.as_str()),
587            entity_id,
588            entity_id_attrs,
589            scope,
590            descriptive,
591            source_tables,
592        ];
593        for (array, value) in arrays.iter_mut().zip(row) {
594            array.push(value);
595        }
596    }
597
598    let array_names = std::iter::once(REGISTRY_VALID_COLUMN)
599        .chain(REGISTRY_COLUMNS)
600        .collect::<Vec<_>>();
601    let array_projection = array_names
602        .iter()
603        .zip(arrays)
604        .map(|(name, values)| make_array(values).alias(*name))
605        .collect::<Vec<_>>();
606
607    df.filter(window_predicate)?
608        .select(array_projection)?
609        .unnest_columns(&array_names)?
610        .filter(ident(REGISTRY_VALID_COLUMN))?
611        .select(REGISTRY_COLUMNS.into_iter().map(ident).collect::<Vec<_>>())?
612        .distinct()
613}
614
615/// A declaring table's scan paired with the entity declarations it carries —
616/// the unit `build_registry_plan` derives registry rows from.
617pub struct RegistrySource {
618    pub declarations: Vec<EntityDeclaration>,
619    pub scan: DataFrame,
620}
621
622/// A trace table's scan paired with the `service` declaration it derives
623/// `calls` edges for — a unit of `build_relationships_plan`.
624pub struct CallsSource {
625    pub service: EntityDeclaration,
626    pub scan: DataFrame,
627}
628
629/// The declared-edge table's scan (`semantic_relationships_declared`), whose
630/// rows `build_relationships_plan` unions into the edge set.
631pub struct DeclaredSource {
632    pub scan: DataFrame,
633}
634
635/// Builds the `semantic_entities` registry plan: one branch and source scan per
636/// declaring table, filtered to `window`, then `UNION ALL` across source tables.
637/// Returns `None` when nothing declared an entity, so the computed table streams
638/// empty.
639pub fn build_registry_plan(
640    sources: Vec<RegistrySource>,
641    window: &GraphQueryWindow,
642) -> DfResult<Option<LogicalPlan>> {
643    let mut union_df: Option<DataFrame> = None;
644    for source in sources {
645        let Some((first, rest)) = source.declarations.split_first() else {
646            continue;
647        };
648        union_df = union_all(union_df, registry_source(first, rest, source.scan, window)?)?;
649    }
650    Ok(union_df.map(DataFrame::into_unoptimized_plan))
651}
652
653/// The projected columns of `semantic_relationships`, in order. Every derived
654/// branch and the declared-edge branch must project exactly these so the
655/// top-level `UNION ALL` type-aligns; `build_relationships_plan` re-selects
656/// them over the union to enforce the contract. (The physical declared table
657/// additionally stores `valid_from`/`valid_until`, which feed the validity
658/// filter and the projected window columns.)
659const RELATIONSHIP_COLUMNS: [&str; 16] = [
660    "observed_at",
661    "window_start",
662    "window_end",
663    "fresh_until",
664    "src_type",
665    "src_id",
666    "dst_type",
667    "dst_id",
668    "rel_type",
669    "provenance",
670    "confidence",
671    "request_count",
672    "error_count",
673    "duration_sum",
674    "duration_count",
675    "attributes",
676];
677
678/// A child server span starts no earlier than 5 minutes before its client span
679/// (clock-skew allowance) and no later than 1 hour after it; the bounds keep the
680/// join windowed instead of pairing arbitrarily distant spans of a long-lived
681/// trace.
682const CHILD_SPAN_EARLY_NANOS: i64 = 5 * 60 * 1_000_000_000;
683const CHILD_SPAN_LATE_NANOS: i64 = 60 * 60 * 1_000_000_000;
684
685/// Builds the `semantic_relationships` plan: the trace-derived `calls` branch
686/// unioned with the declared-edge branch, re-projected to the 16-column
687/// contract. Returns `None` when there is neither a trace table nor a
688/// declared-edge table, so the computed table streams empty.
689pub fn build_relationships_plan(
690    traces: Vec<CallsSource>,
691    declared: Option<DeclaredSource>,
692    window: &GraphQueryWindow,
693) -> DfResult<Option<LogicalPlan>> {
694    let mut union_df = calls_branch(traces, window)?;
695    if let Some(declared) = declared {
696        union_df = union_all(union_df, declared_edges(declared.scan, window)?)?;
697    }
698    union_df
699        .map(|df| {
700            Ok(df
701                .select_columns(&RELATIONSHIP_COLUMNS)?
702                .into_unoptimized_plan())
703        })
704        .transpose()
705}
706
707/// Ranking column used to pick the latest declared-edge revision per edge key.
708const DECLARED_REVISION_COLUMN: &str = "__declared_revision";
709
710/// The declared-edge branch: the latest revision per edge key *as of the
711/// queried window* (mito dedups on primary key + `observed_at`, so re-asserting
712/// an edge stores a new revision), filtered by business-validity overlap.
713///
714/// `valid_from` defaults to the declaration time; a NULL `valid_until` means
715/// the edge holds while its row exists (TTL retires it), so `window_end` /
716/// `fresh_until` take the window's upper bound. The output `observed_at` is
717/// synthesized inside the queried range: the scan's filters are re-applied
718/// above the computed table, and the physical revision time would fail them.
719fn declared_edges(scan: DataFrame, window: &GraphQueryWindow) -> DfResult<DataFrame> {
720    let eff_valid_from =
721        core_fns::coalesce().call(vec![ident("valid_from"), ident(OBSERVED_AT_COLUMN)]);
722    let eff_valid_until =
723        core_fns::coalesce().call(vec![ident("valid_until"), window.observed_end()]);
724
725    // As-of the queried window: a revision recorded after its end, or whose
726    // validity starts after it, was not the edge's state inside the window and
727    // must not outrank (and thereby hide) the revision that was.
728    let as_of = ident(OBSERVED_AT_COLUMN)
729        .lt(window.observed_end())
730        .and(eff_valid_from.clone().lt(window.observed_end()));
731
732    let revision = row_number()
733        .partition_by(
734            DECLARED_EDGE_IDENTITY_COLUMNS
735                .iter()
736                .map(|c| ident(*c))
737                .collect(),
738        )
739        // generation_id/scope break observed_at ties deterministically (rows
740        // differing only in them are not merged by the storage dedup).
741        .order_by(vec![
742            ident(OBSERVED_AT_COLUMN).sort(false, false),
743            ident("generation_id").sort(false, false),
744            ident("scope").sort(false, false),
745        ])
746        .build()?
747        .alias(DECLARED_REVISION_COLUMN);
748
749    // The as-of filter already bounds eff_valid_from below the window's end;
750    // only the retirement side of the overlap remains to check.
751    let still_valid = ident("valid_until")
752        .is_null()
753        .or(ident("valid_until").gt(window.observed_start()));
754    // Tags come out of the storage engine dictionary-encoded; cast to plain
755    // strings so the union with the derived branches type-aligns.
756    let tag_utf8 = |name: &str| cast(ident(name), DataType::Utf8).alias(name);
757
758    scan.filter(as_of)?
759        .window(vec![revision])?
760        .filter(ident(DECLARED_REVISION_COLUMN).eq(lit(1_u64)))?
761        .filter(still_valid)?
762        .select(vec![
763            core_fns::greatest()
764                .call(vec![eff_valid_from.clone(), window.observed_start()])
765                .alias(OBSERVED_AT_COLUMN),
766            eff_valid_from.alias("window_start"),
767            eff_valid_until.clone().alias("window_end"),
768            eff_valid_until.alias("fresh_until"),
769            tag_utf8("src_type"),
770            tag_utf8("src_id"),
771            tag_utf8("dst_type"),
772            tag_utf8("dst_id"),
773            tag_utf8("rel_type"),
774            tag_utf8("provenance"),
775            ident("confidence"),
776            ident("request_count"),
777            ident("error_count"),
778            ident("duration_sum"),
779            ident("duration_count"),
780            ident("attributes"),
781        ])
782}
783
784/// The `calls` derivation: pair each client span with its child server span on
785/// `trace_id` + `parent_span_id`, project to `service`, union the pairs of all
786/// trace tables, and aggregate RED metrics per 60s window in one pass — an edge
787/// observed across several trace tables yields one row, not per-table
788/// fragments (the plan form of the Tempo servicegraph connector). Column names
789/// are the fixed `greptime_trace_v1` schema, the reason
790/// `table_data_model = greptime_trace_v1` is required. Returns `None` when
791/// there is no trace table.
792fn calls_branch(
793    traces: Vec<CallsSource>,
794    window: &GraphQueryWindow,
795) -> DfResult<Option<DataFrame>> {
796    let mut union_df: Option<DataFrame> = None;
797    for trace in traces {
798        union_df = union_all(union_df, calls_pairs(&trace.service, trace.scan, window)?)?;
799    }
800    let Some(pairs) = union_df else {
801        return Ok(None);
802    };
803
804    let df = pairs
805        .aggregate(
806            vec![ident("observed_at"), ident("src_id"), ident("dst_id")],
807            vec![
808                count(lit(1)).alias("request_count"),
809                count(lit(1))
810                    .filter(ident("status_code").eq(lit(SPAN_STATUS_ERROR)))
811                    .build()?
812                    .alias("error_count"),
813                sum(ident("duration_nano")).alias("duration_nano_sum"),
814            ],
815        )?
816        .select(vec![
817            ident("observed_at"),
818            ident("observed_at").alias("window_start"),
819            (ident("observed_at") + bin_interval()).alias("window_end"),
820            (ident("observed_at") + bin_interval()).alias("fresh_until"),
821            lit("service").alias("src_type"),
822            ident("src_id"),
823            lit("service").alias("dst_type"),
824            ident("dst_id"),
825            lit("calls").alias("rel_type"),
826            lit("trace").alias("provenance"),
827            lit(1.0_f64).alias("confidence"),
828            ident("request_count"),
829            ident("error_count"),
830            // duration_nano sums in nanoseconds; the contract column is seconds.
831            (cast(ident("duration_nano_sum"), DataType::Float64) / lit(1e9_f64))
832                .alias("duration_sum"),
833            ident("request_count").alias("duration_count"),
834            null_json().alias("attributes"),
835        ])?;
836    Ok(Some(df))
837}
838
839/// One trace table's client/server span pairs, projected to the aggregation
840/// inputs `(observed_at, src_id, dst_id, status_code, duration_nano)`.
841/// Endpoint ids are built from the table's `service` entity declaration, so
842/// edges land on exactly the entity ids the registry emits (a composite
843/// service identity renders the same sorted `k=v` form on both sides).
844fn calls_pairs(
845    service: &EntityDeclaration,
846    trace: DataFrame,
847    window: &GraphQueryWindow,
848) -> DfResult<DataFrame> {
849    let mut client_pred = ident(SPAN_KIND_COLUMN)
850        .eq(lit(SPAN_KIND_CLIENT))
851        .and(ident(TRACE_TIMESTAMP_COLUMN).gt_eq(window.source_start()))
852        .and(ident(TRACE_TIMESTAMP_COLUMN).lt(window.source_end()));
853    let mut server_pred = ident(SPAN_KIND_COLUMN)
854        .eq(lit(SPAN_KIND_SERVER))
855        // Static bounds implied by the window and the join's time-proximity
856        // conditions below; the join bounds reference client.timestamp and
857        // cannot prune the server-side scan.
858        .and(
859            ident(TRACE_TIMESTAMP_COLUMN)
860                .gt_eq(window.source_start() - interval(CHILD_SPAN_EARLY_NANOS)),
861        )
862        .and(
863            ident(TRACE_TIMESTAMP_COLUMN).lt(window.source_end() + interval(CHILD_SPAN_LATE_NANOS)),
864        );
865    // A NULL identity component identifies nothing, on either endpoint.
866    for id in &service.id_columns {
867        client_pred = client_pred.and(ident(id).is_not_null());
868        server_pred = server_pred.and(ident(id).is_not_null());
869    }
870
871    let client = trace.clone().filter(client_pred)?.alias("client")?;
872    let server = trace.filter(server_pred)?.alias("server")?;
873
874    let join_conditions = vec![
875        qcol("client", TRACE_ID_COLUMN).eq(qcol("server", TRACE_ID_COLUMN)),
876        qcol("server", PARENT_SPAN_ID_COLUMN).eq(qcol("client", SPAN_ID_COLUMN)),
877        qcol("server", TRACE_TIMESTAMP_COLUMN)
878            .gt_eq(qcol("client", TRACE_TIMESTAMP_COLUMN) - interval(CHILD_SPAN_EARLY_NANOS)),
879        qcol("server", TRACE_TIMESTAMP_COLUMN)
880            .lt_eq(qcol("client", TRACE_TIMESTAMP_COLUMN) + interval(CHILD_SPAN_LATE_NANOS)),
881    ];
882
883    client
884        .join_on(server, JoinType::Inner, join_conditions)?
885        .select(vec![
886            bin_ms(qcol("client", TRACE_TIMESTAMP_COLUMN)).alias("observed_at"),
887            // The cast inside entity_id_expr also normalizes tag columns, which
888            // come out of the storage engine dictionary-encoded.
889            entity_id_expr(&service.id_columns, &|c| qcol("client", c)).alias("src_id"),
890            entity_id_expr(&service.id_columns, &|c| qcol("server", c)).alias("dst_id"),
891            qcol("server", SPAN_STATUS_CODE_COLUMN).alias("status_code"),
892            qcol("server", DURATION_NANO_COLUMN).alias("duration_nano"),
893        ])?
894        // Exclude self-calls on the composed identity: an edge needs two
895        // distinct service entities.
896        .filter(ident("src_id").not_eq(ident("dst_id")))
897}
898
899#[cfg(test)]
900mod tests {
901    use std::sync::Arc;
902
903    use common_catalog::consts::SERVICE_NAME_COLUMN;
904    use datafusion::arrow::array::{
905        Array, ArrayRef, BinaryArray, Float64Array, Int64Array, StringArray,
906        TimestampMillisecondArray, TimestampNanosecondArray, UInt64Array,
907    };
908    use datafusion::arrow::datatypes::{Field, Schema};
909    use datafusion::arrow::record_batch::RecordBatch;
910    use datafusion::datasource::MemTable;
911    use datafusion::prelude::SessionContext;
912
913    use super::*;
914
915    fn test_window() -> GraphQueryWindow {
916        GraphQueryWindow::from_observed(0, 10 * 60 * 1000)
917    }
918
919    #[test]
920    fn window_source_scan_covers_whole_buckets() {
921        // Buckets selected by [10:30.5', 11:30') is exactly {11:00'}; its source
922        // rows span [11:00', 12:00').
923        let window = GraphQueryWindow::from_observed(630_000, 690_000);
924        assert_eq!(
925            (window.source_start_ms, window.source_end_ms),
926            (660_000, 720_000)
927        );
928
929        // Aligned bounds stay put.
930        let window = GraphQueryWindow::from_observed(600_000, 720_000);
931        assert_eq!(
932            (window.source_start_ms, window.source_end_ms),
933            (600_000, 720_000)
934        );
935
936        // A sub-bucket range that selects no bucket start scans nothing.
937        let window = GraphQueryWindow::from_observed(610_000, 650_000);
938        assert!(window.source_start_ms >= window.source_end_ms);
939
940        // Pre-epoch bounds round toward the correct buckets.
941        let window = GraphQueryWindow::from_observed(-90_000, -30_000);
942        assert_eq!((window.source_start_ms, window.source_end_ms), (-60_000, 0));
943    }
944
945    async fn collect(ctx: &SessionContext, plan: LogicalPlan) -> Vec<RecordBatch> {
946        ctx.execute_logical_plan(plan)
947            .await
948            .unwrap()
949            .collect()
950            .await
951            .unwrap()
952    }
953
954    fn json_texts(batch: &RecordBatch, column: usize) -> Vec<Option<String>> {
955        let array = batch
956            .column(column)
957            .as_any()
958            .downcast_ref::<BinaryArray>()
959            .unwrap();
960        (0..array.len())
961            .map(|i| {
962                array
963                    .is_valid(i)
964                    .then(|| jsonb::from_slice(array.value(i)).unwrap().to_string())
965            })
966            .collect()
967    }
968
969    fn strings(batch: &RecordBatch, column: usize) -> Vec<String> {
970        let array = batch
971            .column(column)
972            .as_any()
973            .downcast_ref::<StringArray>()
974            .unwrap();
975        (0..array.len())
976            .map(|i| array.value(i).to_string())
977            .collect()
978    }
979
980    /// A metric-like table: ms timestamps, service/pid identity, nullable
981    /// descriptive column with JSON-hostile characters.
982    fn metric_table_ctx() -> SessionContext {
983        let schema = Arc::new(Schema::new(vec![
984            Field::new(
985                "ts",
986                DataType::Timestamp(TimeUnit::Millisecond, None),
987                false,
988            ),
989            Field::new("service_name", DataType::Utf8, false),
990            Field::new("pid", DataType::Int64, false),
991            Field::new("host", DataType::Utf8, true),
992        ]));
993        let batch = RecordBatch::try_new(
994            schema.clone(),
995            vec![
996                Arc::new(TimestampMillisecondArray::from(vec![1_000, 2_000, 61_000])) as ArrayRef,
997                Arc::new(StringArray::from(vec!["cart", "cart", "cart"])),
998                Arc::new(Int64Array::from(vec![42, 42, 42])),
999                Arc::new(StringArray::from(vec![
1000                    Some(r#"we"ird\host"#),
1001                    None,
1002                    Some("h2"),
1003                ])),
1004            ],
1005        )
1006        .unwrap();
1007        let ctx = SessionContext::new();
1008        ctx.register_table(
1009            "app_latency",
1010            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
1011        )
1012        .unwrap();
1013        ctx
1014    }
1015
1016    fn decl(entity_type: &str, id_columns: &[&str]) -> EntityDeclaration {
1017        EntityDeclaration {
1018            schema: "public".to_string(),
1019            table: "app_latency".to_string(),
1020            time_index: "ts".to_string(),
1021            entity_type: entity_type.to_string(),
1022            id_columns: id_columns.iter().map(|s| s.to_string()).collect(),
1023            descriptive_columns: vec![],
1024            scope_columns: vec![],
1025        }
1026    }
1027
1028    #[tokio::test]
1029    async fn registry_single_column_identity() {
1030        let ctx = metric_table_ctx();
1031        let df = ctx.table("app_latency").await.unwrap();
1032        let plan = build_registry_plan(
1033            vec![RegistrySource {
1034                declarations: vec![decl("service", &["service_name"])],
1035                scan: df,
1036            }],
1037            &test_window(),
1038        )
1039        .unwrap()
1040        .unwrap();
1041
1042        let names = plan
1043            .schema()
1044            .fields()
1045            .iter()
1046            .map(|f| f.name().as_str())
1047            .collect::<Vec<_>>();
1048        assert_eq!(
1049            names,
1050            [
1051                "observed_at",
1052                "window_start",
1053                "window_end",
1054                "fresh_until",
1055                "entity_type",
1056                "entity_id",
1057                "entity_id_attrs",
1058                "scope",
1059                "descriptive",
1060                "source_tables",
1061            ]
1062        );
1063
1064        let batches = collect(&ctx, plan).await;
1065        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1066        // 3 rows in 2 distinct 60s bins, all the same entity -> 2 rows.
1067        assert_eq!(total, 2);
1068        let batch = &batches[0];
1069        assert_eq!(strings(batch, 4), vec!["service"; batch.num_rows()]);
1070        assert_eq!(strings(batch, 5), vec!["cart"; batch.num_rows()]);
1071        // Single-column id -> entity_id_attrs and descriptive are typed-JSON NULLs.
1072        assert!(json_texts(batch, 6).iter().all(Option::is_none));
1073        assert!(json_texts(batch, 8).iter().all(Option::is_none));
1074        assert_eq!(
1075            json_texts(batch, 9),
1076            vec![Some(r#"["public.app_latency"]"#.to_string()); batch.num_rows()]
1077        );
1078    }
1079
1080    #[tokio::test]
1081    async fn registry_composite_identity_and_descriptive_escaping() {
1082        let ctx = metric_table_ctx();
1083        let df = ctx.table("app_latency").await.unwrap();
1084        let mut declaration = decl("process", &["service_name", "pid"]);
1085        declaration.descriptive_columns = vec!["host".to_string()];
1086        let plan = build_registry_plan(
1087            vec![RegistrySource {
1088                declarations: vec![declaration],
1089                scan: df,
1090            }],
1091            &test_window(),
1092        )
1093        .unwrap()
1094        .unwrap();
1095
1096        let batches = collect(&ctx, plan).await;
1097        let mut rows: Vec<(String, Option<String>, Option<String>)> = batches
1098            .iter()
1099            .flat_map(|batch| {
1100                let ids = strings(batch, 5);
1101                let id_attrs = json_texts(batch, 6);
1102                let descriptives = json_texts(batch, 8);
1103                ids.into_iter()
1104                    .zip(id_attrs)
1105                    .zip(descriptives)
1106                    .map(|((id, attrs), descriptive)| (id, attrs, descriptive))
1107                    .collect::<Vec<_>>()
1108            })
1109            .collect();
1110        rows.sort();
1111
1112        // Composite id -> sorted `k=v,k=v` plus a JSON object of the id columns;
1113        // descriptive JSON escapes `\` and `"` in runtime values, NULL -> "".
1114        assert_eq!(
1115            rows,
1116            vec![
1117                (
1118                    "pid=42,service_name=cart".to_string(),
1119                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
1120                    Some(r#"{"host":""}"#.to_string()),
1121                ),
1122                (
1123                    "pid=42,service_name=cart".to_string(),
1124                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
1125                    Some(r#"{"host":"h2"}"#.to_string()),
1126                ),
1127                (
1128                    "pid=42,service_name=cart".to_string(),
1129                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
1130                    Some(r#"{"host":"we\"ird\\host"}"#.to_string()),
1131                ),
1132            ]
1133        );
1134    }
1135
1136    #[tokio::test]
1137    async fn registry_scope_variants() {
1138        let ctx = metric_table_ctx();
1139
1140        // Single scope column: its (NULL-safe) value verbatim.
1141        let mut single = decl("service", &["service_name"]);
1142        single.scope_columns = vec!["host".to_string()];
1143        let df = ctx.table("app_latency").await.unwrap();
1144        let plan = build_registry_plan(
1145            vec![RegistrySource {
1146                declarations: vec![single],
1147                scan: df,
1148            }],
1149            &test_window(),
1150        )
1151        .unwrap()
1152        .unwrap();
1153        let batches = collect(&ctx, plan).await;
1154        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
1155        scopes.sort();
1156        assert_eq!(scopes, vec!["", "h2", r#"we"ird\host"#]);
1157
1158        // Multiple scope columns: sorted `k=v,k=v`.
1159        let mut multi = decl("service", &["service_name"]);
1160        multi.scope_columns = vec!["pid".to_string(), "host".to_string()];
1161        let df = ctx.table("app_latency").await.unwrap();
1162        let plan = build_registry_plan(
1163            vec![RegistrySource {
1164                declarations: vec![multi],
1165                scan: df,
1166            }],
1167            &test_window(),
1168        )
1169        .unwrap()
1170        .unwrap();
1171        let batches = collect(&ctx, plan).await;
1172        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
1173        scopes.sort();
1174        assert_eq!(
1175            scopes,
1176            vec![
1177                "host=,pid=42",
1178                "host=h2,pid=42",
1179                r#"host=we"ird\host,pid=42"#
1180            ]
1181        );
1182    }
1183
1184    #[tokio::test]
1185    async fn registry_skips_null_identity_rows() {
1186        let ctx = metric_table_ctx();
1187        let df = ctx.table("app_latency").await.unwrap();
1188        let plan = build_registry_plan(
1189            vec![RegistrySource {
1190                declarations: vec![decl("host", &["host"])],
1191                scan: df,
1192            }],
1193            &test_window(),
1194        )
1195        .unwrap()
1196        .unwrap();
1197        let batches = collect(&ctx, plan).await;
1198        let mut ids: Vec<String> = batches.iter().flat_map(|b| strings(b, 5)).collect();
1199        ids.sort();
1200        assert_eq!(ids, vec!["h2", r#"we"ird\host"#]);
1201    }
1202
1203    #[tokio::test]
1204    async fn registry_expands_declarations_with_one_source_scan() {
1205        let ctx = metric_table_ctx();
1206        let df = ctx.table("app_latency").await.unwrap();
1207        let plan = build_registry_plan(
1208            vec![RegistrySource {
1209                declarations: vec![decl("service", &["service_name"]), decl("host", &["pid"])],
1210                scan: df,
1211            }],
1212            &test_window(),
1213        )
1214        .unwrap()
1215        .unwrap();
1216
1217        assert_eq!(
1218            plan.display_indent()
1219                .to_string()
1220                .matches("TableScan: app_latency")
1221                .count(),
1222            1
1223        );
1224        let batches = collect(&ctx, plan).await;
1225        let mut types: Vec<String> = batches.iter().flat_map(|b| strings(b, 4)).collect();
1226        types.sort();
1227        assert_eq!(types, vec!["host", "host", "service", "service"]);
1228
1229        // No declarations -> no plan.
1230        assert!(
1231            build_registry_plan(vec![], &test_window())
1232                .unwrap()
1233                .is_none()
1234        );
1235    }
1236
1237    /// A trace-like table in the fixed `greptime_trace_v1` shape (ns timestamps).
1238    fn trace_table_ctx() -> SessionContext {
1239        let schema = Arc::new(Schema::new(vec![
1240            Field::new(
1241                TRACE_TIMESTAMP_COLUMN,
1242                DataType::Timestamp(TimeUnit::Nanosecond, None),
1243                false,
1244            ),
1245            Field::new(TRACE_ID_COLUMN, DataType::Utf8, false),
1246            Field::new(SPAN_ID_COLUMN, DataType::Utf8, false),
1247            Field::new(PARENT_SPAN_ID_COLUMN, DataType::Utf8, true),
1248            Field::new(SPAN_KIND_COLUMN, DataType::Utf8, false),
1249            Field::new(SPAN_STATUS_CODE_COLUMN, DataType::Utf8, false),
1250            Field::new(SERVICE_NAME_COLUMN, DataType::Utf8, false),
1251            Field::new("service_namespace", DataType::Utf8, false),
1252            Field::new(DURATION_NANO_COLUMN, DataType::UInt64, false),
1253        ]));
1254        const MS: i64 = 1_000_000;
1255        // Two client->server pairs frontend->cart (one errored), one pair
1256        // cart->cart (self-call, excluded), one unmatched client span.
1257        let batch = RecordBatch::try_new(
1258            schema.clone(),
1259            vec![
1260                Arc::new(TimestampNanosecondArray::from(vec![
1261                    1_000 * MS, // client frontend->cart
1262                    1_010 * MS, //   server cart
1263                    2_000 * MS, // client frontend->cart (error)
1264                    2_010 * MS, //   server cart (error)
1265                    3_000 * MS, // client cart->cart (self-call)
1266                    3_010 * MS, //   server cart
1267                    4_000 * MS, // client with no matching server
1268                ])) as ArrayRef,
1269                Arc::new(StringArray::from(vec![
1270                    "t1", "t1", "t2", "t2", "t3", "t3", "t4",
1271                ])),
1272                Arc::new(StringArray::from(vec![
1273                    "c1", "s1", "c2", "s2", "c3", "s3", "c4",
1274                ])),
1275                Arc::new(StringArray::from(vec![
1276                    None,
1277                    Some("c1"),
1278                    None,
1279                    Some("c2"),
1280                    None,
1281                    Some("c3"),
1282                    None,
1283                ])),
1284                Arc::new(StringArray::from(vec![
1285                    "SPAN_KIND_CLIENT",
1286                    "SPAN_KIND_SERVER",
1287                    "SPAN_KIND_CLIENT",
1288                    "SPAN_KIND_SERVER",
1289                    "SPAN_KIND_CLIENT",
1290                    "SPAN_KIND_SERVER",
1291                    "SPAN_KIND_CLIENT",
1292                ])),
1293                Arc::new(StringArray::from(vec![
1294                    "STATUS_CODE_UNSET",
1295                    "STATUS_CODE_UNSET",
1296                    "STATUS_CODE_UNSET",
1297                    "STATUS_CODE_ERROR",
1298                    "STATUS_CODE_UNSET",
1299                    "STATUS_CODE_UNSET",
1300                    "STATUS_CODE_UNSET",
1301                ])),
1302                Arc::new(StringArray::from(vec![
1303                    "frontend", "cart", "frontend", "cart", "cart", "cart", "frontend",
1304                ])),
1305                Arc::new(StringArray::from(vec!["ns1"; 7])),
1306                Arc::new(UInt64Array::from(vec![
1307                    0,
1308                    500_000_000, // 0.5s
1309                    0,
1310                    1_500_000_000, // 1.5s
1311                    0,
1312                    100,
1313                    0,
1314                ])),
1315            ],
1316        )
1317        .unwrap();
1318        let ctx = SessionContext::new();
1319        ctx.register_table(
1320            "opentelemetry_traces",
1321            Arc::new(MemTable::try_new(schema.clone(), vec![vec![batch.clone()]]).unwrap()),
1322        )
1323        .unwrap();
1324        ctx.register_table(
1325            "opentelemetry_traces_2",
1326            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
1327        )
1328        .unwrap();
1329        ctx
1330    }
1331
1332    fn trace_service_decl(id_columns: &[&str]) -> EntityDeclaration {
1333        EntityDeclaration {
1334            schema: "public".to_string(),
1335            table: "opentelemetry_traces".to_string(),
1336            time_index: TRACE_TIMESTAMP_COLUMN.to_string(),
1337            entity_type: "service".to_string(),
1338            id_columns: id_columns.iter().map(|s| s.to_string()).collect(),
1339            descriptive_columns: vec![],
1340            scope_columns: vec![],
1341        }
1342    }
1343
1344    #[tokio::test]
1345    async fn calls_plan_aggregates_red_metrics() {
1346        let ctx = trace_table_ctx();
1347        let trace = ctx.table("opentelemetry_traces").await.unwrap();
1348        let plan = build_relationships_plan_for_test(
1349            vec![CallsSource {
1350                service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1351                scan: trace,
1352            }],
1353            &test_window(),
1354        )
1355        .unwrap()
1356        .unwrap();
1357
1358        let names = plan
1359            .schema()
1360            .fields()
1361            .iter()
1362            .map(|f| f.name().as_str())
1363            .collect::<Vec<_>>();
1364        assert_eq!(names, RELATIONSHIP_COLUMNS);
1365
1366        let batches = collect(&ctx, plan).await;
1367        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1368        // frontend->cart only: the self-call and the unmatched client drop out;
1369        // both pairs land in the same 60s bin.
1370        assert_eq!(total, 1);
1371        let batch = &batches[0];
1372        assert_eq!(strings(batch, 5), vec!["frontend"]);
1373        assert_eq!(strings(batch, 7), vec!["cart"]);
1374        assert_eq!(strings(batch, 8), vec!["calls"]);
1375        assert_eq!(strings(batch, 9), vec!["trace"]);
1376
1377        let request_count = batch
1378            .column(11)
1379            .as_any()
1380            .downcast_ref::<Int64Array>()
1381            .unwrap();
1382        assert_eq!(request_count.value(0), 2);
1383        let error_count = batch
1384            .column(12)
1385            .as_any()
1386            .downcast_ref::<Int64Array>()
1387            .unwrap();
1388        assert_eq!(error_count.value(0), 1);
1389        let duration_sum = batch
1390            .column(13)
1391            .as_any()
1392            .downcast_ref::<Float64Array>()
1393            .unwrap();
1394        assert!((duration_sum.value(0) - 2.0).abs() < 1e-9);
1395        let duration_count = batch
1396            .column(14)
1397            .as_any()
1398            .downcast_ref::<Int64Array>()
1399            .unwrap();
1400        assert_eq!(duration_count.value(0), 2);
1401        // Derived calls edges carry no attributes: a typed-JSON NULL.
1402        assert!(json_texts(batch, 15)[0].is_none());
1403    }
1404
1405    #[tokio::test]
1406    async fn calls_plan_merges_edges_across_trace_tables() {
1407        let ctx = trace_table_ctx();
1408        let t1 = ctx.table("opentelemetry_traces").await.unwrap();
1409        let t2 = ctx.table("opentelemetry_traces_2").await.unwrap();
1410        let plan = build_relationships_plan_for_test(
1411            vec![
1412                CallsSource {
1413                    service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1414                    scan: t1,
1415                },
1416                CallsSource {
1417                    service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1418                    scan: t2,
1419                },
1420            ],
1421            &test_window(),
1422        )
1423        .unwrap()
1424        .unwrap();
1425
1426        let batches = collect(&ctx, plan).await;
1427        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1428        // The same frontend->cart edge from both tables folds into one row with
1429        // summed RED metrics.
1430        assert_eq!(total, 1);
1431        let batch = &batches[0];
1432        let request_count = batch
1433            .column(11)
1434            .as_any()
1435            .downcast_ref::<Int64Array>()
1436            .unwrap();
1437        assert_eq!(request_count.value(0), 4);
1438        let error_count = batch
1439            .column(12)
1440            .as_any()
1441            .downcast_ref::<Int64Array>()
1442            .unwrap();
1443        assert_eq!(error_count.value(0), 2);
1444        let duration_sum = batch
1445            .column(13)
1446            .as_any()
1447            .downcast_ref::<Float64Array>()
1448            .unwrap();
1449        assert!((duration_sum.value(0) - 4.0).abs() < 1e-9);
1450    }
1451
1452    #[tokio::test]
1453    async fn calls_endpoints_follow_service_declaration() {
1454        let ctx = trace_table_ctx();
1455        let trace = ctx.table("opentelemetry_traces").await.unwrap();
1456        let plan = build_relationships_plan_for_test(
1457            vec![CallsSource {
1458                service: trace_service_decl(&[SERVICE_NAME_COLUMN, "service_namespace"]),
1459                scan: trace,
1460            }],
1461            &test_window(),
1462        )
1463        .unwrap()
1464        .unwrap();
1465
1466        let batches = collect(&ctx, plan).await;
1467        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
1468        assert_eq!(total, 1);
1469        let batch = &batches[0];
1470        // Composite service identity renders the same sorted `k=v` form the
1471        // registry emits, so edges land on registry entity ids.
1472        assert_eq!(
1473            strings(batch, 5),
1474            vec!["service_name=frontend,service_namespace=ns1"]
1475        );
1476        assert_eq!(
1477            strings(batch, 7),
1478            vec!["service_name=cart,service_namespace=ns1"]
1479        );
1480    }
1481
1482    fn build_relationships_plan_for_test(
1483        traces: Vec<CallsSource>,
1484        window: &GraphQueryWindow,
1485    ) -> DfResult<Option<LogicalPlan>> {
1486        build_relationships_plan(traces, None, window)
1487    }
1488
1489    /// A `TableInfo` derived from the canonical declared-edge definition, with
1490    /// injection points for each aspect the schema matcher must check.
1491    fn declared_table_info(
1492        mutate_columns: impl FnOnce(&mut Vec<datatypes::schema::ColumnSchema>),
1493        engine: &str,
1494        primary_key_indices: Vec<usize>,
1495        extra_options: &[(&str, &str)],
1496    ) -> table::metadata::TableInfo {
1497        let canonical = build_declared_relationships_expr("greptime");
1498        let mut columns: Vec<datatypes::schema::ColumnSchema> = canonical
1499            .column_defs
1500            .iter()
1501            .map(|def| {
1502                let wrapper = api::helper::ColumnDataTypeWrapper::try_new(
1503                    def.data_type,
1504                    def.datatype_extension.clone(),
1505                )
1506                .unwrap();
1507                datatypes::schema::ColumnSchema::new(
1508                    &def.name,
1509                    datatypes::prelude::ConcreteDataType::from(wrapper),
1510                    def.is_nullable,
1511                )
1512                .with_time_index(def.name == OBSERVED_AT_COLUMN)
1513            })
1514            .collect();
1515        mutate_columns(&mut columns);
1516        let schema = Arc::new(
1517            datatypes::schema::SchemaBuilder::try_from_columns(columns)
1518                .unwrap()
1519                .build()
1520                .unwrap(),
1521        );
1522        let options = table::requests::TableOptions {
1523            extra_options: extra_options
1524                .iter()
1525                .map(|(k, v)| (k.to_string(), v.to_string()))
1526                .collect(),
1527            ..Default::default()
1528        };
1529        let meta = table::metadata::TableMeta {
1530            schema,
1531            primary_key_indices,
1532            value_indices: vec![],
1533            engine: engine.to_string(),
1534            next_column_id: 1,
1535            options,
1536            created_on: Default::default(),
1537            updated_on: Default::default(),
1538            partition_key_indices: vec![],
1539            column_ids: vec![],
1540        };
1541        table::metadata::TableInfoBuilder::default()
1542            .table_id(1)
1543            .name(SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME)
1544            .catalog_name("greptime")
1545            .schema_name(DEFAULT_PRIVATE_SCHEMA_NAME)
1546            .table_version(0)
1547            .table_type(table::metadata::TableType::Base)
1548            .meta(meta)
1549            .build()
1550            .unwrap()
1551    }
1552
1553    #[test]
1554    fn declared_schema_match_checks_more_than_columns() {
1555        let mito = common_catalog::consts::MITO_ENGINE;
1556        let canonical_pk = || (6..14).collect::<Vec<_>>();
1557
1558        let ok = declared_table_info(|_| {}, mito, canonical_pk(), &[(TTL_KEY, "180d")]);
1559        assert!(declared_relationships_schema_matches(&ok));
1560        // The canonical expr must declare attributes as json, matching the
1561        // computed table's column.
1562        assert_eq!(
1563            ok.meta
1564                .schema
1565                .column_schema_by_name("attributes")
1566                .map(|c| c.data_type.clone()),
1567            Some(datatypes::prelude::ConcreteDataType::json_datatype())
1568        );
1569        let ok = declared_table_info(
1570            |_| {},
1571            mito,
1572            canonical_pk(),
1573            &[(MERGE_MODE_KEY, "last_row")],
1574        );
1575        assert!(declared_relationships_schema_matches(&ok));
1576
1577        let wrong_engine = declared_table_info(|_| {}, "metric", canonical_pk(), &[]);
1578        assert!(!declared_relationships_schema_matches(&wrong_engine));
1579
1580        let pk_missing_generation_id = declared_table_info(|_| {}, mito, (6..13).collect(), &[]);
1581        assert!(!declared_relationships_schema_matches(
1582            &pk_missing_generation_id
1583        ));
1584
1585        let wrong_time_index = declared_table_info(
1586            |columns| {
1587                columns[0] = columns[0].clone().with_time_index(false);
1588                columns[4] = datatypes::schema::ColumnSchema::new(
1589                    "valid_from",
1590                    datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype(),
1591                    false,
1592                )
1593                .with_time_index(true);
1594            },
1595            mito,
1596            canonical_pk(),
1597            &[],
1598        );
1599        assert!(!declared_relationships_schema_matches(&wrong_time_index));
1600
1601        let append_mode =
1602            declared_table_info(|_| {}, mito, canonical_pk(), &[(APPEND_MODE_KEY, "true")]);
1603        assert!(!declared_relationships_schema_matches(&append_mode));
1604
1605        let wrong_column_type = declared_table_info(
1606            |columns| {
1607                columns[14] = datatypes::schema::ColumnSchema::new(
1608                    "confidence",
1609                    datatypes::prelude::ConcreteDataType::int64_datatype(),
1610                    true,
1611                );
1612            },
1613            mito,
1614            canonical_pk(),
1615            &[],
1616        );
1617        assert!(!declared_relationships_schema_matches(&wrong_column_type));
1618    }
1619
1620    fn ts_values(batch: &RecordBatch, column: usize) -> Vec<i64> {
1621        let array = batch
1622            .column(column)
1623            .as_any()
1624            .downcast_ref::<TimestampMillisecondArray>()
1625            .unwrap();
1626        (0..array.len()).map(|i| array.value(i)).collect()
1627    }
1628
1629    /// Registers a declared-edge table holding:
1630    /// - frontend->db: two revisions (0.5 then 1.0), the newer retiring the edge at 300s;
1631    /// - api->cache: expired at 100s;
1632    /// - agent-1->search: open-ended `provenance = 'agent'` with JSON attributes;
1633    /// - webapp->auth: two revisions, the newer declared at 900s;
1634    /// - batch->queue: declared at 100s but only valid from 700s;
1635    /// - gateway->redis: asserted twice at the same instant as generations g1/g2.
1636    fn declared_table(ctx: &SessionContext) {
1637        let ts_field = |name: &str| {
1638            Field::new(
1639                name,
1640                DataType::Timestamp(TimeUnit::Millisecond, None),
1641                name != OBSERVED_AT_COLUMN,
1642            )
1643        };
1644        let schema = Arc::new(Schema::new(vec![
1645            ts_field(OBSERVED_AT_COLUMN),
1646            ts_field("window_start"),
1647            ts_field("window_end"),
1648            ts_field("fresh_until"),
1649            ts_field("valid_from"),
1650            ts_field("valid_until"),
1651            Field::new("src_type", DataType::Utf8, false),
1652            Field::new("src_id", DataType::Utf8, false),
1653            Field::new("rel_type", DataType::Utf8, false),
1654            Field::new("dst_type", DataType::Utf8, false),
1655            Field::new("dst_id", DataType::Utf8, false),
1656            Field::new("provenance", DataType::Utf8, false),
1657            Field::new("scope", DataType::Utf8, false),
1658            Field::new("generation_id", DataType::Utf8, false),
1659            Field::new("confidence", DataType::Float64, true),
1660            Field::new("request_count", DataType::Int64, true),
1661            Field::new("error_count", DataType::Int64, true),
1662            Field::new("duration_sum", DataType::Float64, true),
1663            Field::new("duration_count", DataType::Int64, true),
1664            Field::new("attributes", DataType::Binary, true),
1665        ]));
1666        let attrs = jsonb::parse_value(br#"{"connection_type":"virtual_node"}"#)
1667            .unwrap()
1668            .to_vec();
1669        let no_ts = || Arc::new(TimestampMillisecondArray::from(vec![None::<i64>; 9])) as ArrayRef;
1670        let batch = RecordBatch::try_new(
1671            schema.clone(),
1672            vec![
1673                Arc::new(TimestampMillisecondArray::from(vec![
1674                    100_000, 200_000, 50_000, 90_000, 100_000, 900_000, 100_000, 100_000, 100_000,
1675                ])) as ArrayRef,
1676                no_ts(), // window_start
1677                no_ts(), // window_end
1678                no_ts(), // fresh_until
1679                Arc::new(TimestampMillisecondArray::from(vec![
1680                    None,
1681                    None,
1682                    None,
1683                    None,
1684                    None,
1685                    None,
1686                    Some(700_000),
1687                    None,
1688                    None,
1689                ])),
1690                Arc::new(TimestampMillisecondArray::from(vec![
1691                    None,
1692                    Some(300_000),
1693                    Some(100_000),
1694                    None,
1695                    None,
1696                    None,
1697                    None,
1698                    None,
1699                    None,
1700                ])),
1701                Arc::new(StringArray::from(vec![
1702                    "service", "service", "service", "agent", "service", "service", "service",
1703                    "service", "service",
1704                ])),
1705                Arc::new(StringArray::from(vec![
1706                    "frontend", "frontend", "api", "agent-1", "webapp", "webapp", "batch",
1707                    "gateway", "gateway",
1708                ])),
1709                Arc::new(StringArray::from(vec![
1710                    "depends_on",
1711                    "depends_on",
1712                    "depends_on",
1713                    "uses",
1714                    "depends_on",
1715                    "depends_on",
1716                    "depends_on",
1717                    "depends_on",
1718                    "depends_on",
1719                ])),
1720                Arc::new(StringArray::from(vec![
1721                    "service", "service", "service", "tool", "service", "service", "service",
1722                    "service", "service",
1723                ])),
1724                Arc::new(StringArray::from(vec![
1725                    "db", "db", "cache", "search", "auth", "auth", "queue", "redis", "redis",
1726                ])),
1727                Arc::new(StringArray::from(vec![
1728                    "declared", "declared", "declared", "agent", "declared", "declared",
1729                    "declared", "declared", "declared",
1730                ])),
1731                Arc::new(StringArray::from(vec![""; 9])),
1732                Arc::new(StringArray::from(vec![
1733                    "", "", "", "", "", "", "", "g1", "g2",
1734                ])),
1735                Arc::new(Float64Array::from(vec![
1736                    Some(0.5),
1737                    Some(1.0),
1738                    Some(1.0),
1739                    Some(0.8),
1740                    Some(0.5),
1741                    Some(1.0),
1742                    Some(1.0),
1743                    Some(0.5),
1744                    Some(1.0),
1745                ])),
1746                Arc::new(Int64Array::from(vec![None::<i64>; 9])),
1747                Arc::new(Int64Array::from(vec![None::<i64>; 9])),
1748                Arc::new(Float64Array::from(vec![None::<f64>; 9])),
1749                Arc::new(Int64Array::from(vec![None::<i64>; 9])),
1750                Arc::new(BinaryArray::from(vec![
1751                    None,
1752                    None,
1753                    None,
1754                    Some(attrs.as_slice()),
1755                    None,
1756                    None,
1757                    None,
1758                    None,
1759                    None,
1760                ])),
1761            ],
1762        )
1763        .unwrap();
1764        ctx.register_table(
1765            SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
1766            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
1767        )
1768        .unwrap();
1769    }
1770
1771    #[tokio::test]
1772    async fn declared_edges_latest_revision_validity_and_synthetic_time() {
1773        let ctx = SessionContext::new();
1774        declared_table(&ctx);
1775        let scan = ctx
1776            .table(SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME)
1777            .await
1778            .unwrap();
1779
1780        // Queried window [120s, 600s).
1781        let window = GraphQueryWindow::from_observed(120_000, 600_000);
1782        let plan = build_relationships_plan(vec![], Some(DeclaredSource { scan }), &window)
1783            .unwrap()
1784            .unwrap();
1785        let names = plan
1786            .schema()
1787            .fields()
1788            .iter()
1789            .map(|f| f.name().as_str())
1790            .collect::<Vec<_>>();
1791        assert_eq!(names, RELATIONSHIP_COLUMNS);
1792
1793        // (src_id, observed_at, window_start, window_end, fresh_until,
1794        //  provenance, attributes)
1795        type DeclaredRow = (String, i64, i64, i64, i64, String, Option<String>);
1796
1797        let batches = collect(&ctx, plan).await;
1798        let mut rows: Vec<DeclaredRow> = vec![];
1799        for batch in &batches {
1800            let observed = ts_values(batch, 0);
1801            let window_start = ts_values(batch, 1);
1802            let window_end = ts_values(batch, 2);
1803            let fresh_until = ts_values(batch, 3);
1804            let src = strings(batch, 5);
1805            let provenance = strings(batch, 9);
1806            let attributes = json_texts(batch, 15);
1807            for i in 0..batch.num_rows() {
1808                rows.push((
1809                    src[i].clone(),
1810                    observed[i],
1811                    window_start[i],
1812                    window_end[i],
1813                    fresh_until[i],
1814                    provenance[i].clone(),
1815                    attributes[i].clone(),
1816                ));
1817            }
1818        }
1819        rows.sort();
1820
1821        // api->cache expired before the window; batch->queue is not yet valid;
1822        // frontend->db keeps only the latest revision; webapp->auth keeps the
1823        // first revision (the second postdates the window); gateway->redis
1824        // collapses to one row across generations.
1825        assert_eq!(rows.len(), 4);
1826
1827        // agent->tool: open-ended validity declared at 90s. The synthesized
1828        // observed_at is clamped into the queried window; window_end and
1829        // fresh_until take the window's upper bound.
1830        assert_eq!(
1831            rows[0],
1832            (
1833                "agent-1".to_string(),
1834                120_000,
1835                90_000,
1836                600_000,
1837                600_000,
1838                "agent".to_string(),
1839                Some(r#"{"connection_type":"virtual_node"}"#.to_string()),
1840            )
1841        );
1842
1843        // frontend->db: the latest revision (declared at 200s, retired at 300s)
1844        // supersedes the open-ended first revision.
1845        assert_eq!(
1846            rows[1],
1847            (
1848                "frontend".to_string(),
1849                200_000,
1850                200_000,
1851                300_000,
1852                300_000,
1853                "declared".to_string(),
1854                None,
1855            )
1856        );
1857
1858        assert_eq!(
1859            rows[2],
1860            (
1861                "gateway".to_string(),
1862                120_000,
1863                100_000,
1864                600_000,
1865                600_000,
1866                "declared".to_string(),
1867                None,
1868            )
1869        );
1870
1871        assert_eq!(
1872            rows[3],
1873            (
1874                "webapp".to_string(),
1875                120_000,
1876                100_000,
1877                600_000,
1878                600_000,
1879                "declared".to_string(),
1880                None,
1881            )
1882        );
1883    }
1884
1885    #[tokio::test]
1886    async fn declared_edges_pick_the_revision_as_of_the_window() {
1887        let ctx = SessionContext::new();
1888        declared_table(&ctx);
1889        let scan = ctx
1890            .table(SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME)
1891            .await
1892            .unwrap();
1893
1894        // A historical window that predates frontend->db's second revision:
1895        // the first revision was the edge's state then and must not be hidden
1896        // by the newer one.
1897        let window = GraphQueryWindow::from_observed(0, 150_000);
1898        let plan = build_relationships_plan(vec![], Some(DeclaredSource { scan }), &window)
1899            .unwrap()
1900            .unwrap();
1901
1902        let batches = collect(&ctx, plan).await;
1903        let mut rows: Vec<(String, f64)> = vec![];
1904        for batch in &batches {
1905            let src = strings(batch, 5);
1906            let confidence = batch
1907                .column(10)
1908                .as_any()
1909                .downcast_ref::<Float64Array>()
1910                .unwrap();
1911            for (i, src) in src.into_iter().enumerate() {
1912                rows.push((src, confidence.value(i)));
1913            }
1914        }
1915        rows.sort_by(|a, b| a.0.cmp(&b.0));
1916
1917        // api->cache is valid inside this window; batch->queue is not yet.
1918        assert_eq!(
1919            rows,
1920            vec![
1921                ("agent-1".to_string(), 0.8),
1922                ("api".to_string(), 1.0),
1923                ("frontend".to_string(), 0.5),
1924                ("gateway".to_string(), 1.0),
1925                ("webapp".to_string(), 0.5),
1926            ]
1927        );
1928    }
1929
1930    #[tokio::test]
1931    async fn declared_edges_union_calls_branch() {
1932        let ctx = trace_table_ctx();
1933        declared_table(&ctx);
1934        let trace = ctx.table("opentelemetry_traces").await.unwrap();
1935        let declared = ctx
1936            .table(SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME)
1937            .await
1938            .unwrap();
1939
1940        let plan = build_relationships_plan(
1941            vec![CallsSource {
1942                service: trace_service_decl(&[SERVICE_NAME_COLUMN]),
1943                scan: trace,
1944            }],
1945            Some(DeclaredSource { scan: declared }),
1946            &test_window(),
1947        )
1948        .unwrap()
1949        .unwrap();
1950
1951        let batches = collect(&ctx, plan).await;
1952        let mut provenance: Vec<String> = batches.iter().flat_map(|b| strings(b, 9)).collect();
1953        provenance.sort();
1954        // One trace-derived calls edge plus the declared edges valid somewhere
1955        // inside [0s, 600s): frontend, api, webapp, gateway, and the
1956        // agent-asserted one.
1957        assert_eq!(
1958            provenance,
1959            vec![
1960                "agent", "declared", "declared", "declared", "declared", "trace"
1961            ]
1962        );
1963    }
1964}