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
28mod conventions;
29mod relationships;
30
31use std::sync::{Arc, LazyLock};
32
33use api::v1::column_data_type_extension::TypeExt;
34use api::v1::{
35    ColumnDataType, ColumnDataTypeExtension, ColumnDef, CreateTableExpr, JsonTypeExtension,
36    SemanticType,
37};
38use common_catalog::consts::{
39    CONFIDENCE_COLUMN, DEFAULT_CATALOG_NAME, DEFAULT_PRIVATE_SCHEMA_NAME, DST_ID_COLUMN,
40    DST_TYPE_COLUMN, DURATION_COUNT_COLUMN, DURATION_SUM_COLUMN, EDGE_ATTRIBUTES_COLUMN,
41    ENTITY_DESCRIPTIVE_COLUMN, ENTITY_ID_ATTRS_COLUMN, ENTITY_ID_COLUMN, ENTITY_SCOPE_COLUMN,
42    ENTITY_TYPE_COLUMN, ERROR_COUNT_COLUMN, FRESH_UNTIL_COLUMN, GENERATION_ID_COLUMN,
43    OBSERVED_AT_COLUMN, PROVENANCE_COLUMN, REL_TYPE_COLUMN, REQUEST_COUNT_COLUMN,
44    SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME, SOURCE_TABLES_COLUMN, SRC_ID_COLUMN,
45    SRC_TYPE_COLUMN, VALID_FROM_COLUMN, VALID_UNTIL_COLUMN, WINDOW_END_COLUMN, WINDOW_START_COLUMN,
46};
47use common_function::function::FunctionContext;
48use common_function::function_registry::FUNCTION_REGISTRY;
49pub use conventions::{
50    Conventions, ENTITY_TYPE_GEN_AI_AGENT, ENTITY_TYPE_GEN_AI_MODEL, ENTITY_TYPE_GEN_AI_TOOL,
51    ENTITY_TYPE_HOST, ENTITY_TYPE_K8S_CONTAINER, ENTITY_TYPE_K8S_NODE, ENTITY_TYPE_K8S_POD,
52    ENTITY_TYPE_K8S_WORKLOAD, ENTITY_TYPE_PROCESS, ENTITY_TYPE_SERVICE,
53    ENTITY_TYPE_SERVICE_INSTANCE, ImplicitEntity, PROVENANCE_AGENT, PROVENANCE_ATTRIBUTE,
54    PROVENANCE_DECLARED, PROVENANCE_TRACE, REL_TYPE_CALLS, REL_TYPE_CONTAINS, REL_TYPE_DEPENDS_ON,
55    REL_TYPE_INVOKES, REL_TYPE_OWNS, REL_TYPE_PART_OF, REL_TYPE_RUNS_ON, REL_TYPE_USES,
56    conventions,
57};
58use datafusion::arrow::datatypes::{DataType, TimeUnit};
59use datafusion::dataframe::DataFrame;
60use datafusion::functions::{core as core_fns, datetime as datetime_fns, string as string_fns};
61use datafusion::functions_nested::expr_fn::make_array;
62use datafusion_common::{Column, Result as DfResult, ScalarValue};
63use datafusion_expr::{Expr, LogicalPlan, ScalarUDF, cast, ident, lit};
64pub use relationships::{
65    CallsSource, CoDeclaredSource, DeclaredSource, RelationshipSources, build_relationships_plan,
66};
67use store_api::mito_engine_options::{APPEND_MODE_KEY, MERGE_MODE_KEY, TTL_KEY};
68
69/// Whether an existing declared-edge table still matches the canonical
70/// definition ([`build_declared_relationships_expr`]): columns, time index,
71/// primary key, engine, and merge behaviour — the union branch's revision and
72/// dedup semantics lean on all of these. A mismatch (upgrade skew) must be
73/// surfaced, not silently derived wrong; DROP resets the table.
74pub fn declared_relationships_schema_matches(table_info: &table::metadata::TableInfo) -> bool {
75    let meta = &table_info.meta;
76    if meta.engine != common_catalog::consts::MITO_ENGINE {
77        return false;
78    }
79    let schema = &meta.schema;
80    if schema
81        .timestamp_column()
82        .is_none_or(|column| column.name != OBSERVED_AT_COLUMN)
83    {
84        return false;
85    }
86    let primary_keys = meta
87        .primary_key_indices
88        .iter()
89        .filter_map(|idx| schema.column_schemas().get(*idx))
90        .map(|column| column.name.as_str());
91    if !primary_keys.eq(DECLARED_PRIMARY_KEY_COLUMNS) {
92        return false;
93    }
94    // LastRow merge is what makes a re-asserted edge a *revision*; append mode
95    // or another merge mode would change the read-side dedup semantics.
96    let options = &meta.options.extra_options;
97    if options.get(APPEND_MODE_KEY).map(String::as_str) == Some("true")
98        || options
99            .get(MERGE_MODE_KEY)
100            .is_some_and(|mode| mode != "last_row")
101    {
102        return false;
103    }
104
105    let canonical = build_declared_relationships_expr(DEFAULT_CATALOG_NAME);
106    if schema.column_schemas().len() != canonical.column_defs.len() {
107        return false;
108    }
109    canonical
110        .column_defs
111        .iter()
112        .zip(schema.column_schemas())
113        .all(|(def, column)| {
114            let Ok(wrapper) = api::helper::ColumnDataTypeWrapper::try_new(
115                def.data_type,
116                def.datatype_extension.clone(),
117            ) else {
118                return false;
119            };
120            def.name == column.name
121                && datatypes::prelude::ConcreteDataType::from(wrapper) == column.data_type
122        })
123}
124
125/// Bin width for the temporal window of derived rows: 60s buckets, matching the
126/// service-graph convention.
127const BIN_NANOS: i64 = 60 * 1_000_000_000;
128
129/// Default retention for the declared-edge table; expiry slides the topology window.
130const DEFAULT_DECLARED_RELATIONSHIPS_TTL: &str = "90d";
131/// Environment variable overriding the declared-edge table's TTL at creation
132/// time (e.g. `180d`, `forever`).
133// TODO(entity-graph): promote this to a real configuration option.
134const DECLARED_RELATIONSHIPS_TTL_ENV: &str = "GREPTIMEDB_DECLARED_RELATIONSHIPS_TTL";
135
136fn declared_relationships_ttl() -> String {
137    std::env::var(DECLARED_RELATIONSHIPS_TTL_ENV)
138        .ok()
139        .map(|ttl| ttl.trim().to_string())
140        .filter(|ttl| !ttl.is_empty())
141        .unwrap_or_else(|| DEFAULT_DECLARED_RELATIONSHIPS_TTL.to_string())
142}
143
144/// The primary-key (tag) columns, in key order. Starting with the source endpoint
145/// makes out-edge lookup (`WHERE src_type=? AND src_id=?`) a key-prefix scan;
146/// `provenance` and `generation_id` are in the key so a declared edge and a
147/// (future) derived edge for the same pair coexist without clobbering.
148pub const DECLARED_PRIMARY_KEY_COLUMNS: [&str; 8] = [
149    SRC_TYPE_COLUMN,
150    SRC_ID_COLUMN,
151    REL_TYPE_COLUMN,
152    DST_TYPE_COLUMN,
153    DST_ID_COLUMN,
154    PROVENANCE_COLUMN,
155    ENTITY_SCOPE_COLUMN,
156    GENERATION_ID_COLUMN,
157];
158
159/// The externally visible edge identity: the primary key minus `scope` and
160/// `generation_id`, which the computed table does not expose. Revision ranking
161/// uses this identity, or assertions differing only in those two columns would
162/// surface as indistinguishable duplicate rows.
163const DECLARED_EDGE_IDENTITY_COLUMNS: [&str; 6] = [
164    SRC_TYPE_COLUMN,
165    SRC_ID_COLUMN,
166    REL_TYPE_COLUMN,
167    DST_TYPE_COLUMN,
168    DST_ID_COLUMN,
169    PROVENANCE_COLUMN,
170];
171
172fn column(
173    name: &str,
174    data_type: ColumnDataType,
175    semantic_type: SemanticType,
176    nullable: bool,
177) -> ColumnDef {
178    ColumnDef {
179        name: name.to_string(),
180        data_type: data_type as i32,
181        is_nullable: nullable,
182        default_constraint: vec![],
183        semantic_type: semantic_type as i32,
184        comment: String::new(),
185        datatype_extension: None,
186        options: None,
187    }
188}
189
190fn tag(name: &str) -> ColumnDef {
191    column(name, ColumnDataType::String, SemanticType::Tag, false)
192}
193
194fn field(name: &str, data_type: ColumnDataType) -> ColumnDef {
195    column(name, data_type, SemanticType::Field, true)
196}
197
198fn json_field(name: &str) -> ColumnDef {
199    let mut def = field(name, ColumnDataType::Binary);
200    def.datatype_extension = Some(ColumnDataTypeExtension {
201        type_ext: Some(TypeExt::JsonType(JsonTypeExtension::JsonBinary.into())),
202    });
203    def
204}
205
206/// Builds the `CREATE TABLE` request for the declared-edge table. Columns mirror
207/// the computed `semantic_relationships` shape (temporal window + endpoints +
208/// provenance/confidence + RED metrics) plus the declared-only business validity
209/// window (`valid_from` / `valid_until`), which — unlike TTL (physical retention)
210/// — expresses whether a hand-declared edge is still in effect.
211///
212/// The default `LastRow` merge dedups on primary key **plus** `observed_at`
213/// (the time index is part of mito's dedup key): re-asserting an edge at a new
214/// `observed_at` stores a new revision, and the read-side union keeps only the
215/// latest revision per edge key.
216pub fn build_declared_relationships_expr(catalog: &str) -> CreateTableExpr {
217    let column_defs = vec![
218        // Temporal: when this revision of the edge was declared (time index,
219        // also the TTL clock).
220        column(
221            OBSERVED_AT_COLUMN,
222            ColumnDataType::TimestampMillisecond,
223            SemanticType::Timestamp,
224            false,
225        ),
226        field(WINDOW_START_COLUMN, ColumnDataType::TimestampMillisecond),
227        field(WINDOW_END_COLUMN, ColumnDataType::TimestampMillisecond),
228        field(FRESH_UNTIL_COLUMN, ColumnDataType::TimestampMillisecond),
229        // Declared-only business validity. NULL valid_from = valid since the
230        // declaration; NULL valid_until = valid for as long as the row exists
231        // (TTL expiry retires the edge with the row).
232        field(VALID_FROM_COLUMN, ColumnDataType::TimestampMillisecond),
233        field(VALID_UNTIL_COLUMN, ColumnDataType::TimestampMillisecond),
234        // Endpoints + edge identity (all tags, in primary-key order).
235        tag(SRC_TYPE_COLUMN),
236        tag(SRC_ID_COLUMN),
237        tag(REL_TYPE_COLUMN),
238        tag(DST_TYPE_COLUMN),
239        tag(DST_ID_COLUMN),
240        tag(PROVENANCE_COLUMN),
241        tag(ENTITY_SCOPE_COLUMN),
242        tag(GENERATION_ID_COLUMN),
243        // Confidence + RED metrics (populated for derived edges; usually NULL here).
244        field(CONFIDENCE_COLUMN, ColumnDataType::Float64),
245        field(REQUEST_COUNT_COLUMN, ColumnDataType::Int64),
246        field(ERROR_COUNT_COLUMN, ColumnDataType::Int64),
247        field(DURATION_SUM_COLUMN, ColumnDataType::Float64),
248        field(DURATION_COUNT_COLUMN, ColumnDataType::Int64),
249        // JSONB, so the union matches the computed table's json column
250        // without a per-scan parse.
251        json_field(EDGE_ATTRIBUTES_COLUMN),
252    ];
253
254    let table_options = [(TTL_KEY.to_string(), declared_relationships_ttl())]
255        .into_iter()
256        .collect();
257
258    CreateTableExpr {
259        catalog_name: catalog.to_string(),
260        schema_name: DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
261        table_name: SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME.to_string(),
262        desc: "Hand-declared edges of the entity-relationship graph".to_string(),
263        column_defs,
264        time_index: OBSERVED_AT_COLUMN.to_string(),
265        primary_keys: DECLARED_PRIMARY_KEY_COLUMNS
266            .iter()
267            .map(|c| c.to_string())
268            .collect(),
269        create_if_not_exists: true,
270        table_options,
271        table_id: None,
272        engine: common_catalog::consts::MITO_ENGINE.to_string(),
273    }
274}
275
276/// A single table's entity-identity declaration, projected from
277/// `information_schema.table_semantics` (`greptime.semantic.entity.<type>.*`).
278#[derive(Debug, Clone)]
279pub struct EntityDeclaration {
280    /// The declaring table's schema, for the qualified `source_tables` lineage.
281    pub schema: String,
282    /// The declaring table's name, recorded in `source_tables`.
283    pub table: String,
284    /// The table's time index column, used for the temporal window filter.
285    pub time_index: String,
286    pub entity_type: String,
287    /// Identifying columns (>= 1). One column → id verbatim; several → composite.
288    pub id_columns: Vec<String>,
289    /// Descriptive columns snapshotted into the `descriptive` JSON (may be empty).
290    pub descriptive_columns: Vec<String>,
291    /// Scope columns (namespace/environment). One column → scope verbatim;
292    /// several → sorted `k=v,k=v`, mirroring the composite id rendering.
293    pub scope_columns: Vec<String>,
294}
295
296/// The read-time query window, resolved from the scan's `observed_at` predicate
297/// (or the product default). Two half-open `[start, end)` millisecond ranges:
298///
299/// - *observed*: the queried `observed_at` range. The scan's filters are
300///   re-applied above the computed table (`FilterPushDownType::Inexact`), so
301///   every emitted row's `observed_at` must fall inside it. The declared-edge
302///   branch also runs its validity overlap against this range.
303/// - *source scan*: `observed` widened to whole 60s buckets. Derived rows are
304///   `date_bin('60s')` aggregates keyed by the bucket start, so a bucket the
305///   observed range selects must be scanned over its full extent — filtering
306///   the source rows to the observed range instead would silently truncate the
307///   RED numbers of the boundary buckets.
308///
309/// The bounds are plain millisecond values turned into timestamp literals on
310/// demand — wall-clock snapshot semantics like `now()`, but as constants they
311/// prune the source table scans without depending on constant-folding.
312#[derive(Debug, Clone)]
313pub struct GraphQueryWindow {
314    observed_start_ms: i64,
315    observed_end_ms: i64,
316    source_start_ms: i64,
317    source_end_ms: i64,
318}
319
320impl GraphQueryWindow {
321    /// Builds the window for the queried `observed_at` range `[start_ms, end_ms)`.
322    pub fn from_observed(start_ms: i64, end_ms: i64) -> Self {
323        const BIN_MS: i64 = BIN_NANOS / 1_000_000;
324        // Ceiling division that stays correct for pre-epoch (negative) values.
325        let ceil_to_bin = |ms: i64| {
326            ms.div_euclid(BIN_MS) * BIN_MS
327                + if ms.rem_euclid(BIN_MS) == 0 {
328                    0
329                } else {
330                    BIN_MS
331                }
332        };
333        // A bucket `b` (a 60s multiple, `date_bin`'s floor of its rows) is
334        // selected when `start <= b < end`: the first is ceil(start) and the
335        // last one's rows extend to ceil(end).
336        Self {
337            observed_start_ms: start_ms,
338            observed_end_ms: end_ms,
339            source_start_ms: ceil_to_bin(start_ms),
340            source_end_ms: ceil_to_bin(end_ms),
341        }
342    }
343
344    /// Conservative default when a query carries no explicit time predicate: the
345    /// last hour, so a bare `SELECT * FROM semantic_entities` never scans every
346    /// declaring table's full history. This is a product default, not a cap.
347    pub fn default_last_hour() -> Self {
348        let end_ms = common_time::util::current_time_millis();
349        Self::from_observed(end_ms - 60 * 60 * 1000, end_ms)
350    }
351
352    /// Start of the queried `observed_at` range (inclusive).
353    pub fn observed_start(&self) -> Expr {
354        ts_ms_lit(self.observed_start_ms)
355    }
356
357    /// End of the queried `observed_at` range (exclusive).
358    pub fn observed_end(&self) -> Expr {
359        ts_ms_lit(self.observed_end_ms)
360    }
361
362    /// Start of the source-table scan range (inclusive).
363    pub fn source_start(&self) -> Expr {
364        ts_ms_lit(self.source_start_ms)
365    }
366
367    /// End of the source-table scan range (exclusive).
368    pub fn source_end(&self) -> Expr {
369        ts_ms_lit(self.source_end_ms)
370    }
371}
372
373fn ts_ms_lit(ms: i64) -> Expr {
374    lit(ScalarValue::TimestampMillisecond(Some(ms), None))
375}
376
377/// An `INTERVAL` literal of `nanos` nanoseconds.
378fn interval(nanos: i64) -> Expr {
379    lit(ScalarValue::new_interval_mdn(0, 0, nanos))
380}
381
382fn bin_interval() -> Expr {
383    interval(BIN_NANOS)
384}
385
386/// `date_bin(60s, ts)` cast to millisecond precision, so the output schema is
387/// deterministic regardless of the source column's precision (trace tables are
388/// nanosecond, metric tables millisecond).
389fn bin_ms(ts: Expr) -> Expr {
390    cast(
391        datetime_fns::date_bin().call(vec![bin_interval(), ts]),
392        DataType::Timestamp(TimeUnit::Millisecond, None),
393    )
394}
395
396/// Folds union branches without requiring a non-empty input.
397fn union_all(acc: Option<DataFrame>, branch: DataFrame) -> DfResult<Option<DataFrame>> {
398    Ok(Some(match acc {
399        Some(acc) => acc.union(branch)?,
400        None => branch,
401    }))
402}
403
404/// A column reference qualified by a join-side alias, built without string
405/// parsing (so column names containing `.` or `"` stay verbatim).
406fn qcol(relation: &str, name: &str) -> Expr {
407    Expr::Column(Column::new(Some(relation), name))
408}
409
410fn concat_expr(parts: Vec<Expr>) -> Expr {
411    string_fns::concat().call(parts)
412}
413
414/// `coalesce(CAST(column AS STRING), '')`: renders a nullable column for string
415/// concatenation without collapsing the result to NULL.
416fn cast_string_or_empty(column: &str) -> Expr {
417    core_fns::coalesce().call(vec![cast(ident(column), DataType::Utf8), lit("")])
418}
419
420/// The canonical entity-id expression for `id_columns`: the value verbatim for
421/// a single column, the sorted `k=v,k=v` rendering for a composite. `col`
422/// constructs the column reference (unqualified for registry branches,
423/// join-side-qualified for the calls derivation).
424/// A row identifies an entity only when every identity component is present
425/// and non-empty: kube-state-metrics descriptors emit empty-string labels (an
426/// unscheduled pod's `node`, an owner-less pod's `owner_*`), and an empty
427/// string is never a meaningful entity id.
428pub(crate) fn identifies(column: &str) -> Expr {
429    ident(column)
430        .is_not_null()
431        .and(cast(ident(column), DataType::Utf8).not_eq(lit("")))
432}
433
434fn entity_id_expr(id_columns: &[String], col: &dyn Fn(&str) -> Expr) -> Expr {
435    if let [id] = id_columns {
436        cast(col(id), DataType::Utf8)
437    } else {
438        let mut cols = id_columns.to_vec();
439        cols.sort();
440        sorted_kv_expr_with(&cols, false, col)
441    }
442}
443
444/// The `parse_json` UDF, shared by all derivation plans. Resolved from the
445/// global registry once: the UDF is stateless (its `FunctionContext` is unused).
446static PARSE_JSON_UDF: LazyLock<Arc<ScalarUDF>> = LazyLock::new(|| {
447    Arc::new(
448        FUNCTION_REGISTRY
449            .get_function("parse_json")
450            .expect("parse_json must be registered")
451            .provide(FunctionContext::default()),
452    )
453});
454
455/// Parses a JSON text expression into a JSONB value, cast from the UDF's
456/// `BinaryView` output to `Binary` — the storage type the computed tables'
457/// declared `json` columns map to in Arrow.
458fn parse_json_expr(json_text: Expr) -> Expr {
459    cast(PARSE_JSON_UDF.call(vec![json_text]), DataType::Binary)
460}
461
462/// A NULL literal typed as JSONB storage (`Binary`), so branches without a JSON
463/// value union-align with branches that produce one.
464fn null_json() -> Expr {
465    lit(ScalarValue::Binary(None))
466}
467
468/// Renders a compile-time-known string as JSON text (quoted, fully escaped —
469/// including control characters, unlike the runtime value escaping).
470fn json_quote(value: &str) -> String {
471    serde_json::Value::from(value).to_string()
472}
473
474/// Wraps a column reference in `replace` calls so its runtime value is
475/// JSON-escaped (`\` then `"`); NULL becomes `''` so one NULL column does not
476/// invalidate the whole JSON text (descriptive columns are nullable).
477fn json_escaped_value_expr(column: &str) -> Expr {
478    let escaped_backslash =
479        string_fns::replace().call(vec![cast_string_or_empty(column), lit("\\"), lit("\\\\")]);
480    string_fns::replace().call(vec![escaped_backslash, lit("\""), lit("\\\"")])
481}
482
483/// Builds a JSONB object from `columns` by concatenating a JSON text and parsing
484/// it — GreptimeDB has no struct→json function. Keys are JSON-escaped in Rust;
485/// values are JSON-escaped at runtime via [`json_escaped_value_expr`].
486///
487/// TODO(entity-graph): replace the text round-trip with a UDF that assembles
488/// JSONB directly from the value columns (`jsonb::ObjectBuilder`, keys baked
489/// in), dropping the escaping helpers and the per-row parse cost.
490fn json_object_expr(columns: &[String]) -> Expr {
491    if columns.is_empty() {
492        return parse_json_expr(lit("{}"));
493    }
494    let mut parts = vec![lit("{")];
495    for (i, column) in columns.iter().enumerate() {
496        if i > 0 {
497            parts.push(lit(","));
498        }
499        parts.push(lit(format!("{}:\"", json_quote(column))));
500        parts.push(json_escaped_value_expr(column));
501        parts.push(lit("\""));
502    }
503    parts.push(lit("}"));
504    parse_json_expr(concat_expr(parts))
505}
506
507/// Renders pre-sorted columns as a `k=v,k=v` concatenation. `nullable`
508/// coalesces each value to `''` (id columns are tags and non-null; scope
509/// columns carry no such guarantee).
510fn sorted_kv_expr_with(sorted_cols: &[String], nullable: bool, col: &dyn Fn(&str) -> Expr) -> Expr {
511    let mut parts = Vec::with_capacity(sorted_cols.len() * 3);
512    for (i, column) in sorted_cols.iter().enumerate() {
513        if i > 0 {
514            parts.push(lit(","));
515        }
516        parts.push(lit(format!("{column}=")));
517        parts.push(if nullable {
518            core_fns::coalesce().call(vec![cast(col(column), DataType::Utf8), lit("")])
519        } else {
520            cast(col(column), DataType::Utf8)
521        });
522    }
523    concat_expr(parts)
524}
525
526const REGISTRY_COLUMNS: [&str; 10] = [
527    OBSERVED_AT_COLUMN,
528    WINDOW_START_COLUMN,
529    WINDOW_END_COLUMN,
530    FRESH_UNTIL_COLUMN,
531    ENTITY_TYPE_COLUMN,
532    ENTITY_ID_COLUMN,
533    ENTITY_ID_ATTRS_COLUMN,
534    ENTITY_SCOPE_COLUMN,
535    ENTITY_DESCRIPTIVE_COLUMN,
536    SOURCE_TABLES_COLUMN,
537];
538
539const REGISTRY_VALID_COLUMN: &str = "__entity_valid";
540
541/// Expands one source row into one output row per entry of `rows` with a
542/// single source scan: each output field is first built as an array whose
543/// entries correspond to the rows, then unnested. Every row is `[valid,
544/// values...]` aligned with `columns`; rows whose `valid` expression is false
545/// are dropped, and the distinct output columns are `columns`.
546fn unnest_rows(
547    df: DataFrame,
548    window_predicate: Expr,
549    valid_column: &'static str,
550    columns: &[&'static str],
551    rows: Vec<Vec<Expr>>,
552) -> DfResult<DataFrame> {
553    let mut arrays = vec![Vec::with_capacity(rows.len()); columns.len() + 1];
554    for row in rows {
555        debug_assert_eq!(row.len(), arrays.len());
556        for (array, value) in arrays.iter_mut().zip(row) {
557            array.push(value);
558        }
559    }
560    let array_names = std::iter::once(valid_column)
561        .chain(columns.iter().copied())
562        .collect::<Vec<_>>();
563    let array_projection = array_names
564        .iter()
565        .zip(arrays)
566        .map(|(name, values)| make_array(values).alias(*name))
567        .collect::<Vec<_>>();
568
569    df.filter(window_predicate)?
570        .select(array_projection)?
571        .unnest_columns(&array_names)?
572        .filter(ident(valid_column))?
573        .select(columns.iter().map(|c| ident(*c)).collect::<Vec<_>>())?
574        .distinct()
575}
576
577/// Projects all entity declarations of one source table with one source scan
578/// via [`unnest_rows`].
579fn registry_source(
580    first: &EntityDeclaration,
581    rest: &[EntityDeclaration],
582    df: DataFrame,
583    window: &GraphQueryWindow,
584) -> DfResult<DataFrame> {
585    let ts = ident(&first.time_index);
586    let bin = bin_ms(ts.clone());
587    let window_predicate = ts
588        .clone()
589        .gt_eq(window.source_start())
590        .and(ts.lt(window.source_end()));
591
592    let mut rows = Vec::with_capacity(1 + rest.len());
593    for decl in std::iter::once(first).chain(rest) {
594        // CAST even a single-column id: id columns need not be strings, and
595        // the computed table declares entity_id STRING. Composite ids
596        // additionally carry a JSON object of the id columns in
597        // entity_id_attrs.
598        let entity_id = entity_id_expr(&decl.id_columns, &|c| ident(c));
599        let entity_id_attrs = if decl.id_columns.len() == 1 {
600            null_json()
601        } else {
602            let mut cols = decl.id_columns.clone();
603            cols.sort();
604            json_object_expr(&cols)
605        };
606
607        let scope = match decl.scope_columns.as_slice() {
608            [] => lit(""),
609            // Scope columns are not required to be tags, so guard against NULL.
610            [single] => cast_string_or_empty(single),
611            _ => {
612                let mut cols = decl.scope_columns.clone();
613                cols.sort();
614                sorted_kv_expr_with(&cols, true, &|c| ident(c))
615            }
616        };
617
618        let descriptive = if decl.descriptive_columns.is_empty() {
619            null_json()
620        } else {
621            json_object_expr(&decl.descriptive_columns)
622        };
623
624        let source_tables = parse_json_expr(lit(format!(
625            "[{}]",
626            json_quote(&format!("{}.{}", decl.schema, decl.table))
627        )));
628
629        // Keep this predicate per declaration so an absent identity for one
630        // entity does not remove other entities on the row.
631        let valid = decl
632            .id_columns
633            .iter()
634            .fold(lit(true), |predicate, id| predicate.and(identifies(id)));
635
636        rows.push(vec![
637            valid,
638            bin.clone(),
639            bin.clone(),
640            bin.clone() + bin_interval(),
641            bin.clone() + bin_interval(),
642            lit(decl.entity_type.as_str()),
643            entity_id,
644            entity_id_attrs,
645            scope,
646            descriptive,
647            source_tables,
648        ]);
649    }
650
651    unnest_rows(
652        df,
653        window_predicate,
654        REGISTRY_VALID_COLUMN,
655        &REGISTRY_COLUMNS,
656        rows,
657    )
658}
659
660/// A declaring table's scan paired with the entity declarations it carries —
661/// the unit `build_registry_plan` derives registry rows from.
662pub struct RegistrySource {
663    pub declarations: Vec<EntityDeclaration>,
664    pub scan: DataFrame,
665}
666
667/// Builds the `semantic_entities` registry plan: one branch and source scan per
668/// declaring table, filtered to `window`, then `UNION ALL` across source tables.
669/// Returns `None` when nothing declared an entity, so the computed table streams
670/// empty.
671pub fn build_registry_plan(
672    sources: Vec<RegistrySource>,
673    window: &GraphQueryWindow,
674) -> DfResult<Option<LogicalPlan>> {
675    let mut union_df: Option<DataFrame> = None;
676    for source in sources {
677        let Some((first, rest)) = source.declarations.split_first() else {
678            continue;
679        };
680        union_df = union_all(union_df, registry_source(first, rest, source.scan, window)?)?;
681    }
682    Ok(union_df.map(DataFrame::into_unoptimized_plan))
683}
684
685/// RecordBatch readers shared by this module's tests and the `relationships`
686/// tests.
687#[cfg(test)]
688pub(crate) mod test_util {
689    use datafusion::arrow::array::{Array, BinaryArray, StringArray, TimestampMillisecondArray};
690    use datafusion::arrow::record_batch::RecordBatch;
691    use datafusion::prelude::SessionContext;
692    use datafusion_expr::LogicalPlan;
693
694    pub(crate) async fn collect(ctx: &SessionContext, plan: LogicalPlan) -> Vec<RecordBatch> {
695        ctx.execute_logical_plan(plan)
696            .await
697            .unwrap()
698            .collect()
699            .await
700            .unwrap()
701    }
702
703    pub(crate) fn json_texts(batch: &RecordBatch, column: usize) -> Vec<Option<String>> {
704        let array = batch
705            .column(column)
706            .as_any()
707            .downcast_ref::<BinaryArray>()
708            .unwrap();
709        (0..array.len())
710            .map(|i| {
711                array
712                    .is_valid(i)
713                    .then(|| jsonb::from_slice(array.value(i)).unwrap().to_string())
714            })
715            .collect()
716    }
717
718    pub(crate) fn strings(batch: &RecordBatch, column: usize) -> Vec<String> {
719        let array = batch
720            .column(column)
721            .as_any()
722            .downcast_ref::<StringArray>()
723            .unwrap();
724        (0..array.len())
725            .map(|i| array.value(i).to_string())
726            .collect()
727    }
728
729    pub(crate) fn ts_values(batch: &RecordBatch, column: usize) -> Vec<i64> {
730        let array = batch
731            .column(column)
732            .as_any()
733            .downcast_ref::<TimestampMillisecondArray>()
734            .unwrap();
735        (0..array.len()).map(|i| array.value(i)).collect()
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use std::sync::Arc;
742
743    use datafusion::arrow::array::{ArrayRef, Int64Array, StringArray, TimestampMillisecondArray};
744    use datafusion::arrow::datatypes::{Field, Schema};
745    use datafusion::arrow::record_batch::RecordBatch;
746    use datafusion::datasource::MemTable;
747    use datafusion::prelude::SessionContext;
748
749    use super::test_util::{collect, json_texts, strings};
750    use super::*;
751
752    fn test_window() -> GraphQueryWindow {
753        GraphQueryWindow::from_observed(0, 10 * 60 * 1000)
754    }
755
756    #[test]
757    fn window_source_scan_covers_whole_buckets() {
758        // Buckets selected by [10:30.5', 11:30') is exactly {11:00'}; its source
759        // rows span [11:00', 12:00').
760        let window = GraphQueryWindow::from_observed(630_000, 690_000);
761        assert_eq!(
762            (window.source_start_ms, window.source_end_ms),
763            (660_000, 720_000)
764        );
765
766        // Aligned bounds stay put.
767        let window = GraphQueryWindow::from_observed(600_000, 720_000);
768        assert_eq!(
769            (window.source_start_ms, window.source_end_ms),
770            (600_000, 720_000)
771        );
772
773        // A sub-bucket range that selects no bucket start scans nothing.
774        let window = GraphQueryWindow::from_observed(610_000, 650_000);
775        assert!(window.source_start_ms >= window.source_end_ms);
776
777        // Pre-epoch bounds round toward the correct buckets.
778        let window = GraphQueryWindow::from_observed(-90_000, -30_000);
779        assert_eq!((window.source_start_ms, window.source_end_ms), (-60_000, 0));
780    }
781
782    /// A metric-like table: ms timestamps, service/pid identity, nullable
783    /// descriptive column with JSON-hostile characters.
784    fn metric_table_ctx() -> SessionContext {
785        let schema = Arc::new(Schema::new(vec![
786            Field::new(
787                "ts",
788                DataType::Timestamp(TimeUnit::Millisecond, None),
789                false,
790            ),
791            Field::new("service_name", DataType::Utf8, false),
792            Field::new("pid", DataType::Int64, false),
793            Field::new("host", DataType::Utf8, true),
794        ]));
795        let batch = RecordBatch::try_new(
796            schema.clone(),
797            vec![
798                Arc::new(TimestampMillisecondArray::from(vec![1_000, 2_000, 61_000])) as ArrayRef,
799                Arc::new(StringArray::from(vec!["cart", "cart", "cart"])),
800                Arc::new(Int64Array::from(vec![42, 42, 42])),
801                Arc::new(StringArray::from(vec![
802                    Some(r#"we"ird\host"#),
803                    None,
804                    Some("h2"),
805                ])),
806            ],
807        )
808        .unwrap();
809        let ctx = SessionContext::new();
810        ctx.register_table(
811            "app_latency",
812            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
813        )
814        .unwrap();
815        ctx
816    }
817
818    fn decl(entity_type: &str, id_columns: &[&str]) -> EntityDeclaration {
819        EntityDeclaration {
820            schema: "public".to_string(),
821            table: "app_latency".to_string(),
822            time_index: "ts".to_string(),
823            entity_type: entity_type.to_string(),
824            id_columns: id_columns.iter().map(|s| s.to_string()).collect(),
825            descriptive_columns: vec![],
826            scope_columns: vec![],
827        }
828    }
829
830    #[tokio::test]
831    async fn registry_single_column_identity() {
832        let ctx = metric_table_ctx();
833        let df = ctx.table("app_latency").await.unwrap();
834        let plan = build_registry_plan(
835            vec![RegistrySource {
836                declarations: vec![decl("service", &["service_name"])],
837                scan: df,
838            }],
839            &test_window(),
840        )
841        .unwrap()
842        .unwrap();
843
844        let names = plan
845            .schema()
846            .fields()
847            .iter()
848            .map(|f| f.name().as_str())
849            .collect::<Vec<_>>();
850        assert_eq!(
851            names,
852            [
853                "observed_at",
854                "window_start",
855                "window_end",
856                "fresh_until",
857                "entity_type",
858                "entity_id",
859                "entity_id_attrs",
860                "scope",
861                "descriptive",
862                "source_tables",
863            ]
864        );
865
866        let batches = collect(&ctx, plan).await;
867        let total: usize = batches.iter().map(|b| b.num_rows()).sum();
868        // 3 rows in 2 distinct 60s bins, all the same entity -> 2 rows.
869        assert_eq!(total, 2);
870        let batch = &batches[0];
871        assert_eq!(strings(batch, 4), vec!["service"; batch.num_rows()]);
872        assert_eq!(strings(batch, 5), vec!["cart"; batch.num_rows()]);
873        // Single-column id -> entity_id_attrs and descriptive are typed-JSON NULLs.
874        assert!(json_texts(batch, 6).iter().all(Option::is_none));
875        assert!(json_texts(batch, 8).iter().all(Option::is_none));
876        assert_eq!(
877            json_texts(batch, 9),
878            vec![Some(r#"["public.app_latency"]"#.to_string()); batch.num_rows()]
879        );
880    }
881
882    #[tokio::test]
883    async fn registry_composite_identity_and_descriptive_escaping() {
884        let ctx = metric_table_ctx();
885        let df = ctx.table("app_latency").await.unwrap();
886        let mut declaration = decl("process", &["service_name", "pid"]);
887        declaration.descriptive_columns = vec!["host".to_string()];
888        let plan = build_registry_plan(
889            vec![RegistrySource {
890                declarations: vec![declaration],
891                scan: df,
892            }],
893            &test_window(),
894        )
895        .unwrap()
896        .unwrap();
897
898        let batches = collect(&ctx, plan).await;
899        let mut rows: Vec<(String, Option<String>, Option<String>)> = batches
900            .iter()
901            .flat_map(|batch| {
902                let ids = strings(batch, 5);
903                let id_attrs = json_texts(batch, 6);
904                let descriptives = json_texts(batch, 8);
905                ids.into_iter()
906                    .zip(id_attrs)
907                    .zip(descriptives)
908                    .map(|((id, attrs), descriptive)| (id, attrs, descriptive))
909                    .collect::<Vec<_>>()
910            })
911            .collect();
912        rows.sort();
913
914        // Composite id -> sorted `k=v,k=v` plus a JSON object of the id columns;
915        // descriptive JSON escapes `\` and `"` in runtime values, NULL -> "".
916        assert_eq!(
917            rows,
918            vec![
919                (
920                    "pid=42,service_name=cart".to_string(),
921                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
922                    Some(r#"{"host":""}"#.to_string()),
923                ),
924                (
925                    "pid=42,service_name=cart".to_string(),
926                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
927                    Some(r#"{"host":"h2"}"#.to_string()),
928                ),
929                (
930                    "pid=42,service_name=cart".to_string(),
931                    Some(r#"{"pid":"42","service_name":"cart"}"#.to_string()),
932                    Some(r#"{"host":"we\"ird\\host"}"#.to_string()),
933                ),
934            ]
935        );
936    }
937
938    #[tokio::test]
939    async fn registry_scope_variants() {
940        let ctx = metric_table_ctx();
941
942        // Single scope column: its (NULL-safe) value verbatim.
943        let mut single = decl("service", &["service_name"]);
944        single.scope_columns = vec!["host".to_string()];
945        let df = ctx.table("app_latency").await.unwrap();
946        let plan = build_registry_plan(
947            vec![RegistrySource {
948                declarations: vec![single],
949                scan: df,
950            }],
951            &test_window(),
952        )
953        .unwrap()
954        .unwrap();
955        let batches = collect(&ctx, plan).await;
956        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
957        scopes.sort();
958        assert_eq!(scopes, vec!["", "h2", r#"we"ird\host"#]);
959
960        // Multiple scope columns: sorted `k=v,k=v`.
961        let mut multi = decl("service", &["service_name"]);
962        multi.scope_columns = vec!["pid".to_string(), "host".to_string()];
963        let df = ctx.table("app_latency").await.unwrap();
964        let plan = build_registry_plan(
965            vec![RegistrySource {
966                declarations: vec![multi],
967                scan: df,
968            }],
969            &test_window(),
970        )
971        .unwrap()
972        .unwrap();
973        let batches = collect(&ctx, plan).await;
974        let mut scopes: Vec<String> = batches.iter().flat_map(|b| strings(b, 7)).collect();
975        scopes.sort();
976        assert_eq!(
977            scopes,
978            vec![
979                "host=,pid=42",
980                "host=h2,pid=42",
981                r#"host=we"ird\host,pid=42"#
982            ]
983        );
984    }
985
986    #[tokio::test]
987    async fn registry_skips_absent_identity_rows() {
988        // NULL identifies nothing, and so does a kube-state-metrics-style
989        // empty label (an unscheduled pod's `node` arrives as "").
990        let schema = Arc::new(Schema::new(vec![
991            Field::new(
992                "ts",
993                DataType::Timestamp(TimeUnit::Millisecond, None),
994                false,
995            ),
996            Field::new("host", DataType::Utf8, true),
997        ]));
998        let batch = RecordBatch::try_new(
999            schema.clone(),
1000            vec![
1001                Arc::new(TimestampMillisecondArray::from(vec![1_000, 2_000, 3_000])) as ArrayRef,
1002                Arc::new(StringArray::from(vec![Some("h2"), None, Some("")])),
1003            ],
1004        )
1005        .unwrap();
1006        let ctx = SessionContext::new();
1007        ctx.register_table(
1008            "app_latency",
1009            Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()),
1010        )
1011        .unwrap();
1012        let df = ctx.table("app_latency").await.unwrap();
1013        let plan = build_registry_plan(
1014            vec![RegistrySource {
1015                declarations: vec![decl("host", &["host"])],
1016                scan: df,
1017            }],
1018            &test_window(),
1019        )
1020        .unwrap()
1021        .unwrap();
1022        let batches = collect(&ctx, plan).await;
1023        let ids: Vec<String> = batches.iter().flat_map(|b| strings(b, 5)).collect();
1024        assert_eq!(ids, vec!["h2"]);
1025    }
1026
1027    #[tokio::test]
1028    async fn registry_expands_declarations_with_one_source_scan() {
1029        let ctx = metric_table_ctx();
1030        let df = ctx.table("app_latency").await.unwrap();
1031        let plan = build_registry_plan(
1032            vec![RegistrySource {
1033                declarations: vec![decl("service", &["service_name"]), decl("host", &["pid"])],
1034                scan: df,
1035            }],
1036            &test_window(),
1037        )
1038        .unwrap()
1039        .unwrap();
1040
1041        assert_eq!(
1042            plan.display_indent()
1043                .to_string()
1044                .matches("TableScan: app_latency")
1045                .count(),
1046            1
1047        );
1048        let batches = collect(&ctx, plan).await;
1049        let mut types: Vec<String> = batches.iter().flat_map(|b| strings(b, 4)).collect();
1050        types.sort();
1051        assert_eq!(types, vec!["host", "host", "service", "service"]);
1052
1053        // No declarations -> no plan.
1054        assert!(
1055            build_registry_plan(vec![], &test_window())
1056                .unwrap()
1057                .is_none()
1058        );
1059    }
1060
1061    /// A `TableInfo` derived from the canonical declared-edge definition, with
1062    /// injection points for each aspect the schema matcher must check.
1063    fn declared_table_info(
1064        mutate_columns: impl FnOnce(&mut Vec<datatypes::schema::ColumnSchema>),
1065        engine: &str,
1066        primary_key_indices: Vec<usize>,
1067        extra_options: &[(&str, &str)],
1068    ) -> table::metadata::TableInfo {
1069        let canonical = build_declared_relationships_expr("greptime");
1070        let mut columns: Vec<datatypes::schema::ColumnSchema> = canonical
1071            .column_defs
1072            .iter()
1073            .map(|def| {
1074                let wrapper = api::helper::ColumnDataTypeWrapper::try_new(
1075                    def.data_type,
1076                    def.datatype_extension.clone(),
1077                )
1078                .unwrap();
1079                datatypes::schema::ColumnSchema::new(
1080                    &def.name,
1081                    datatypes::prelude::ConcreteDataType::from(wrapper),
1082                    def.is_nullable,
1083                )
1084                .with_time_index(def.name == OBSERVED_AT_COLUMN)
1085            })
1086            .collect();
1087        mutate_columns(&mut columns);
1088        let schema = Arc::new(
1089            datatypes::schema::SchemaBuilder::try_from_columns(columns)
1090                .unwrap()
1091                .build()
1092                .unwrap(),
1093        );
1094        let options = table::requests::TableOptions {
1095            extra_options: extra_options
1096                .iter()
1097                .map(|(k, v)| (k.to_string(), v.to_string()))
1098                .collect(),
1099            ..Default::default()
1100        };
1101        let meta = table::metadata::TableMeta {
1102            schema,
1103            primary_key_indices,
1104            value_indices: vec![],
1105            engine: engine.to_string(),
1106            next_column_id: 1,
1107            options,
1108            created_on: Default::default(),
1109            updated_on: Default::default(),
1110            partition_key_indices: vec![],
1111            column_ids: vec![],
1112        };
1113        table::metadata::TableInfoBuilder::default()
1114            .table_id(1)
1115            .name(SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME)
1116            .catalog_name("greptime")
1117            .schema_name(DEFAULT_PRIVATE_SCHEMA_NAME)
1118            .table_version(0)
1119            .table_type(table::metadata::TableType::Base)
1120            .meta(meta)
1121            .build()
1122            .unwrap()
1123    }
1124
1125    #[test]
1126    fn declared_schema_match_checks_more_than_columns() {
1127        let mito = common_catalog::consts::MITO_ENGINE;
1128        let canonical_pk = || (6..14).collect::<Vec<_>>();
1129
1130        let ok = declared_table_info(|_| {}, mito, canonical_pk(), &[(TTL_KEY, "180d")]);
1131        assert!(declared_relationships_schema_matches(&ok));
1132        // The canonical expr must declare attributes as json, matching the
1133        // computed table's column.
1134        assert_eq!(
1135            ok.meta
1136                .schema
1137                .column_schema_by_name("attributes")
1138                .map(|c| c.data_type.clone()),
1139            Some(datatypes::prelude::ConcreteDataType::json_datatype())
1140        );
1141        let ok = declared_table_info(
1142            |_| {},
1143            mito,
1144            canonical_pk(),
1145            &[(MERGE_MODE_KEY, "last_row")],
1146        );
1147        assert!(declared_relationships_schema_matches(&ok));
1148
1149        let wrong_engine = declared_table_info(|_| {}, "metric", canonical_pk(), &[]);
1150        assert!(!declared_relationships_schema_matches(&wrong_engine));
1151
1152        let pk_missing_generation_id = declared_table_info(|_| {}, mito, (6..13).collect(), &[]);
1153        assert!(!declared_relationships_schema_matches(
1154            &pk_missing_generation_id
1155        ));
1156
1157        let wrong_time_index = declared_table_info(
1158            |columns| {
1159                columns[0] = columns[0].clone().with_time_index(false);
1160                columns[4] = datatypes::schema::ColumnSchema::new(
1161                    "valid_from",
1162                    datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype(),
1163                    false,
1164                )
1165                .with_time_index(true);
1166            },
1167            mito,
1168            canonical_pk(),
1169            &[],
1170        );
1171        assert!(!declared_relationships_schema_matches(&wrong_time_index));
1172
1173        let append_mode =
1174            declared_table_info(|_| {}, mito, canonical_pk(), &[(APPEND_MODE_KEY, "true")]);
1175        assert!(!declared_relationships_schema_matches(&append_mode));
1176
1177        let wrong_column_type = declared_table_info(
1178            |columns| {
1179                columns[14] = datatypes::schema::ColumnSchema::new(
1180                    "confidence",
1181                    datatypes::prelude::ConcreteDataType::int64_datatype(),
1182                    true,
1183                );
1184            },
1185            mito,
1186            canonical_pk(),
1187            &[],
1188        );
1189        assert!(!declared_relationships_schema_matches(&wrong_column_type));
1190    }
1191}