Skip to main content

frontend/instance/
entity_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//! Frontend implementation of the [`EntityGraphProvider`]: the live connector that
16//! makes the computed `greptime_private.semantic_entities` /
17//! `semantic_relationships` tables produce rows.
18//!
19//! It enumerates the entity-identity declarations by iterating the catalog's
20//! `TableInfo` options (`greptime.semantic.entity.*`), builds the read-time
21//! derivation plans as typed DataFusion `Expr`s over the declaring tables'
22//! DataFrames (`operator::statement::semantic_graph`), and executes them through
23//! the query engine. Injected into the catalog manager after the engine is built,
24//! breaking the `catalog -> query` cycle.
25
26use std::collections::HashMap;
27use std::sync::Weak;
28
29use async_trait::async_trait;
30use auth::{
31    PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
32    PermissionTableTargets, SEMANTIC_GRAPH_QUERY,
33};
34use catalog::CatalogManager;
35use catalog::system_schema::semantic_graph::EntityGraphProvider;
36use common_catalog::consts::{
37    DEFAULT_PRIVATE_SCHEMA_NAME, DEFAULT_SCHEMA_NAME, INFORMATION_SCHEMA_NAME, PG_CATALOG_NAME,
38    SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME, SERVICE_NAME_COLUMN,
39};
40use common_error::ext::{BoxedError, ErrorExt};
41use common_error::status_code::StatusCode;
42use common_query::OutputData;
43use common_recordbatch::SendableRecordBatchStream;
44use common_telemetry::{debug, warn};
45use common_time::timestamp::TimeUnit;
46use datafusion::dataframe::DataFrame;
47use datafusion_expr::LogicalPlan;
48use futures::TryStreamExt;
49use operator::statement::semantic_graph::{
50    CallsSource, DeclaredSource, EntityDeclaration, GraphQueryWindow, OBSERVED_AT_COLUMN,
51    RegistrySource, build_registry_plan, build_relationships_plan,
52    declared_relationships_schema_matches,
53};
54use query::QueryEngineRef;
55use session::context::{QueryContext, QueryContextBuilder, QueryContextRef};
56use snafu::ResultExt;
57use store_api::storage::ScanRequest;
58use table::TableRef;
59use table::metadata::TableInfo;
60use table::predicate::{TimeRangeExtraction, extract_time_range_strict};
61use table::requests::{
62    EntityRole, is_trace_v1_table, parse_entity_columns, parse_entity_option_key,
63};
64
65use crate::error;
66
67/// The live [`EntityGraphProvider`], backed by the query engine.
68pub struct EntityGraphProviderImpl {
69    query_engine: QueryEngineRef,
70    catalog_manager: Weak<dyn CatalogManager>,
71    permission_checker: Option<PermissionCheckerRef>,
72}
73
74struct EntitySource {
75    declarations: Vec<EntityDeclaration>,
76    table: TableRef,
77}
78
79impl EntityGraphProviderImpl {
80    pub fn new(
81        query_engine: QueryEngineRef,
82        catalog_manager: Weak<dyn CatalogManager>,
83        permission_checker: Option<PermissionCheckerRef>,
84    ) -> Self {
85        Self {
86            query_engine,
87            catalog_manager,
88            permission_checker,
89        }
90    }
91
92    /// Whether the caller may read the derivation sources named by `targets`.
93    /// `Ok(false)` = denied: the source is silently excluded, per the
94    /// derivation contract. Errors other than a denial abort the scan.
95    fn authorize_sources(
96        &self,
97        query_ctx: Option<&QueryContext>,
98        targets: PermissionTableTargets,
99    ) -> Result<bool, BoxedError> {
100        let Some(ctx) = query_ctx else {
101            return Ok(true);
102        };
103        match self
104            .permission_checker
105            .as_ref()
106            .check_permission_with_table_targets(
107                ctx.current_user(),
108                PermissionReq::Action(SEMANTIC_GRAPH_QUERY),
109                targets,
110            ) {
111            Ok(_) => Ok(true),
112            Err(err) if err.status_code() == StatusCode::PermissionDenied => Ok(false),
113            Err(err) => Err(BoxedError::new(err)),
114        }
115    }
116
117    /// Parses `greptime.semantic.entity.<type>.{id|descriptive|scope}` options of
118    /// one table into per-type declarations. A type with no `id` columns is skipped.
119    fn parse_declarations(table_info: &TableInfo) -> Vec<EntityDeclaration> {
120        let Some(time_index) = table_info
121            .meta
122            .schema
123            .timestamp_column()
124            .map(|c| c.name.clone())
125        else {
126            return vec![];
127        };
128
129        // entity_type -> (id_columns, descriptive_columns, scope_columns)
130        type RoleColumns = (Vec<String>, Vec<String>, Vec<String>);
131        let mut by_type: HashMap<String, RoleColumns> = HashMap::new();
132        for (key, value) in &table_info.meta.options.extra_options {
133            let Some((entity_type, role)) = parse_entity_option_key(key) else {
134                continue;
135            };
136            let cols = parse_entity_columns(value);
137            let entry = by_type.entry(entity_type.to_string()).or_default();
138            match role {
139                EntityRole::Id => entry.0 = cols,
140                EntityRole::Descriptive => entry.1 = cols,
141                EntityRole::Scope => entry.2 = cols,
142            }
143        }
144
145        by_type
146            .into_iter()
147            .filter(|(_, (id, _, _))| !id.is_empty())
148            .filter_map(
149                |(entity_type, (id_columns, descriptive_columns, scope_columns))| {
150                    // A stale declaration (e.g. its column was dropped later)
151                    // must not poison every graph scan; skip it.
152                    let schema = &table_info.meta.schema;
153                    if let Some(missing) = id_columns
154                        .iter()
155                        .chain(&descriptive_columns)
156                        .chain(&scope_columns)
157                        .find(|c| schema.column_schema_by_name(c).is_none())
158                    {
159                        warn!(
160                            "Skipping entity declaration `{}` of table `{}`: column `{}` not found",
161                            entity_type, table_info.name, missing
162                        );
163                        return None;
164                    }
165                    Some(EntityDeclaration {
166                        schema: table_info.schema_name.clone(),
167                        table: table_info.name.clone(),
168                        time_index: time_index.clone(),
169                        entity_type,
170                        id_columns,
171                        descriptive_columns,
172                        scope_columns,
173                    })
174                },
175            )
176            .collect()
177    }
178
179    /// All entity declarations of one table. Trace-v1 tables created before the
180    /// ingest-side auto-stamp carry no `entity.service.id` option; synthesize it
181    /// (their schema is fixed), so their `calls` edges have endpoint entities.
182    /// A table with an explicit service declaration never gets the synthesized
183    /// one — not even when the explicit declaration is invalid and skipped:
184    /// silently falling back would change entity identity behind the user's back.
185    fn declarations_for(table_info: &TableInfo) -> Vec<EntityDeclaration> {
186        let mut declarations = Self::parse_declarations(table_info);
187        let has_explicit_service = table_info.meta.options.extra_options.keys().any(|key| {
188            parse_entity_option_key(key)
189                .is_some_and(|(ty, role)| ty == "service" && role == EntityRole::Id)
190        });
191        if is_trace_v1_table(table_info)
192            && !has_explicit_service
193            && table_info
194                .meta
195                .schema
196                .column_schema_by_name(SERVICE_NAME_COLUMN)
197                .is_some()
198            && let Some(time_index) = table_info
199                .meta
200                .schema
201                .timestamp_column()
202                .map(|c| c.name.clone())
203        {
204            declarations.push(EntityDeclaration {
205                schema: table_info.schema_name.clone(),
206                table: table_info.name.clone(),
207                time_index,
208                entity_type: "service".to_string(),
209                id_columns: vec![SERVICE_NAME_COLUMN.to_string()],
210                descriptive_columns: vec![],
211                scope_columns: vec![],
212            });
213        }
214        declarations
215    }
216
217    /// Enumerates entity declarations and trace tables across a catalog. Trace
218    /// tables are keyed off the engine-native `table_data_model` option (same
219    /// check as the Jaeger query path) so pre-existing trace tables without the
220    /// newer `greptime.semantic.*` stamps are recognized too.
221    async fn enumerate(
222        &self,
223        catalog: &str,
224        query_ctx: Option<&QueryContext>,
225    ) -> Result<(Vec<EntitySource>, Vec<(EntityDeclaration, TableRef)>), BoxedError> {
226        let Some(catalog_manager) = self.catalog_manager.upgrade() else {
227            return Ok((vec![], vec![]));
228        };
229
230        // A target-blind checker (e.g. the default mode-based one) answers the
231        // same for every table: ask once up front instead of per table.
232        let per_table_auth = match self.permission_checker.as_ref() {
233            Some(checker) if query_ctx.is_some() => {
234                if checker.uses_table_targets() {
235                    true
236                } else if self
237                    .authorize_sources(query_ctx, PermissionTableTargets::resolved(vec![]))?
238                {
239                    false
240                } else {
241                    debug!(
242                        "Caller lacks the entity-graph read permission; deriving an empty graph \
243                         (catalog: {catalog})"
244                    );
245                    return Ok((vec![], vec![]));
246                }
247            }
248            _ => false,
249        };
250
251        let mut declarations = vec![];
252        let mut traces = vec![];
253        let schemas = catalog_manager
254            .schema_names(catalog, query_ctx)
255            .await
256            .map_err(BoxedError::new)?;
257        for schema in schemas {
258            // User telemetry never lives in the system schemas; skip them to avoid
259            // scanning information_schema (including the computed graph tables) etc.
260            if schema == INFORMATION_SCHEMA_NAME
261                || schema == PG_CATALOG_NAME
262                || schema == DEFAULT_PRIVATE_SCHEMA_NAME
263            {
264                continue;
265            }
266            let mut tables = catalog_manager.tables(catalog, &schema, query_ctx);
267            while let Some(table) = tables.try_next().await.map_err(BoxedError::new)? {
268                let table_info = table.table_info();
269                let table_declarations = Self::declarations_for(&table_info);
270                let is_trace = is_trace_v1_table(&table_info);
271                // Authorize only tables that would contribute rows.
272                if per_table_auth
273                    && (is_trace || !table_declarations.is_empty())
274                    && !self.authorize_sources(
275                        query_ctx,
276                        PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
277                            catalog,
278                            &schema,
279                            &table_info.name,
280                        )]),
281                    )?
282                {
283                    debug!(
284                        "Excluding `{schema}.{}` from the entity-graph derivation: caller lacks \
285                         read permission",
286                        table_info.name
287                    );
288                    continue;
289                }
290                if is_trace {
291                    // TODO(entity-graph): validate the complete fixed trace-v1
292                    // schema before adding the table to calls derivation, and
293                    // skip malformed/stale tables instead of letting one poison
294                    // the whole relationship scan.
295                    match table_declarations
296                        .iter()
297                        .find(|d| d.entity_type == "service")
298                    {
299                        Some(service) => traces.push((service.clone(), table.clone())),
300                        // No usable service identity: the table cannot
301                        // contribute calls edges (see declarations_for).
302                        None => warn!(
303                            "Trace table `{}` has no usable service declaration; skipping calls derivation",
304                            table_info.name
305                        ),
306                    }
307                }
308                if !table_declarations.is_empty() {
309                    declarations.push(EntitySource {
310                        declarations: table_declarations,
311                        table,
312                    });
313                }
314            }
315        }
316        Ok((declarations, traces))
317    }
318
319    /// The time window to derive over, taken from the scan's `observed_at`
320    /// predicate.
321    ///
322    /// The contract (RFC "The contract"): no `observed_at` predicate → the
323    /// product default (last hour); a missing upper bound means "up to now"; a
324    /// predicate without a lower bound or in a shape that cannot be safely
325    /// extracted is an error asking for an explicit range — never a silent
326    /// fallback into incomplete results.
327    /// `Ok(None)` = the window cannot match anything (e.g. a lower bound in
328    /// the future with the implicit "up to now" upper bound): the scan streams
329    /// empty instead of deriving.
330    fn query_window(request: &ScanRequest) -> Result<Option<GraphQueryWindow>, BoxedError> {
331        let invalid =
332            |err_msg: String| Err(BoxedError::new(error::InvalidSqlSnafu { err_msg }.build()));
333        match extract_time_range_strict(OBSERVED_AT_COLUMN, TimeUnit::Millisecond, &request.filters)
334        {
335            TimeRangeExtraction::Absent => Ok(Some(GraphQueryWindow::default_last_hour())),
336            TimeRangeExtraction::Extracted(range) => {
337                let Some(start) = range.start() else {
338                    return invalid(format!(
339                        "the {OBSERVED_AT_COLUMN} filter has no lower bound; the graph cannot \
340                         derive over unbounded history — add e.g. {OBSERVED_AT_COLUMN} >= \
341                         '2026-01-01 00:00:00'"
342                    ));
343                };
344                let end_ms = range
345                    .end()
346                    .map(|ts| ts.value())
347                    .unwrap_or_else(common_time::util::current_time_millis);
348                if start.value() >= end_ms {
349                    return Ok(None);
350                }
351                Ok(Some(GraphQueryWindow::from_observed(start.value(), end_ms)))
352            }
353            TimeRangeExtraction::Unsupported => invalid(format!(
354                "cannot derive the graph window from the {OBSERVED_AT_COLUMN} filter; use plain \
355                 range predicates (>=, <, BETWEEN) with literal bounds"
356            )),
357        }
358    }
359
360    fn read_table(&self, table: TableRef) -> Result<DataFrame, BoxedError> {
361        self.query_engine.read_table(table).map_err(BoxedError::new)
362    }
363
364    /// The declared-edge branch source, when the physical table exists, the
365    /// caller may read it, and it still matches the canonical definition. A
366    /// mismatch (upgrade skew) is an explicit error, not a silent skip:
367    /// dropping declared edges would misrepresent the graph.
368    async fn declared_source(
369        &self,
370        catalog: &str,
371        query_ctx: Option<&QueryContext>,
372    ) -> Result<Option<DeclaredSource>, BoxedError> {
373        let Some(catalog_manager) = self.catalog_manager.upgrade() else {
374            return Ok(None);
375        };
376        let Some(table) = catalog_manager
377            .table(
378                catalog,
379                DEFAULT_PRIVATE_SCHEMA_NAME,
380                SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
381                query_ctx,
382            )
383            .await
384            .map_err(BoxedError::new)?
385        else {
386            return Ok(None);
387        };
388        if !self.authorize_sources(
389            query_ctx,
390            PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
391                catalog,
392                DEFAULT_PRIVATE_SCHEMA_NAME,
393                SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
394            )]),
395        )? {
396            debug!(
397                "Excluding declared edges: caller lacks read permission on \
398                 `{DEFAULT_PRIVATE_SCHEMA_NAME}.{SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME}`"
399            );
400            return Ok(None);
401        }
402        let table_info = table.table_info();
403        if !declared_relationships_schema_matches(&table_info) {
404            return Err(BoxedError::new(
405                error::InvalidSqlSnafu {
406                    err_msg: format!(
407                        "{DEFAULT_PRIVATE_SCHEMA_NAME}.{SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME} \
408                         does not match its canonical schema; declared edges cannot be derived"
409                    ),
410                }
411                .build(),
412            ));
413        }
414        Ok(Some(DeclaredSource {
415            scan: self.read_table(table)?,
416        }))
417    }
418
419    /// Executes a derivation plan under the caller's context (inheriting its
420    /// permissions, cancellation and deadline); context-less internal scans
421    /// get a minimal default.
422    async fn execute_plan(
423        &self,
424        catalog: &str,
425        plan: LogicalPlan,
426        query_ctx: Option<QueryContextRef>,
427    ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
428        let query_ctx = query_ctx.unwrap_or_else(|| {
429            QueryContextBuilder::default()
430                .current_catalog(catalog.to_string())
431                .current_schema(DEFAULT_SCHEMA_NAME.to_string())
432                .build()
433                .into()
434        });
435        let output = self
436            .query_engine
437            .execute(plan, query_ctx)
438            .await
439            .map_err(BoxedError::new)?;
440        let stream = match output.data {
441            OutputData::Stream(stream) => stream,
442            OutputData::RecordBatches(batches) => batches.as_stream(),
443            OutputData::AffectedRows(_) => return Ok(None),
444        };
445        Ok(Some(stream))
446    }
447}
448
449#[async_trait]
450impl EntityGraphProvider for EntityGraphProviderImpl {
451    async fn scan_entities(
452        &self,
453        catalog: &str,
454        request: ScanRequest,
455        query_ctx: Option<QueryContextRef>,
456    ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
457        let (sources, _) = self.enumerate(catalog, query_ctx.as_deref()).await?;
458        let mut plans = Vec::with_capacity(sources.len());
459        for source in sources {
460            plans.push(RegistrySource {
461                declarations: source.declarations,
462                scan: self.read_table(source.table)?,
463            });
464        }
465        let Some(window) = Self::query_window(&request)? else {
466            return Ok(None);
467        };
468        let Some(plan) = build_registry_plan(plans, &window)
469            .context(error::DataFusionSnafu)
470            .map_err(BoxedError::new)?
471        else {
472            return Ok(None);
473        };
474        self.execute_plan(catalog, plan, query_ctx).await
475    }
476
477    async fn scan_relationships(
478        &self,
479        catalog: &str,
480        request: ScanRequest,
481        query_ctx: Option<QueryContextRef>,
482    ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
483        let (_, traces) = self.enumerate(catalog, query_ctx.as_deref()).await?;
484        let mut scans = Vec::with_capacity(traces.len());
485        for (service, trace) in traces {
486            scans.push(CallsSource {
487                service,
488                scan: self.read_table(trace)?,
489            });
490        }
491        let declared = self.declared_source(catalog, query_ctx.as_deref()).await?;
492        let Some(window) = Self::query_window(&request)? else {
493            return Ok(None);
494        };
495        let Some(plan) = build_relationships_plan(scans, declared, &window)
496            .context(error::DataFusionSnafu)
497            .map_err(BoxedError::new)?
498        else {
499            return Ok(None);
500        };
501        self.execute_plan(catalog, plan, query_ctx).await
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use std::collections::HashMap;
508    use std::sync::Arc;
509
510    use common_catalog::consts::{DEFAULT_CATALOG_NAME, MITO_ENGINE};
511    use datatypes::prelude::ConcreteDataType;
512    use datatypes::schema::{ColumnSchema, SchemaBuilder};
513    use table::metadata::{TableInfoBuilder, TableMeta, TableType};
514    use table::requests::{TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1, TableOptions};
515
516    use super::*;
517
518    fn table_info(columns: &[&str], extra: &[(&str, &str)]) -> TableInfo {
519        let mut column_schemas = vec![
520            ColumnSchema::new(
521                "ts",
522                ConcreteDataType::timestamp_millisecond_datatype(),
523                false,
524            )
525            .with_time_index(true),
526        ];
527        column_schemas.extend(
528            columns
529                .iter()
530                .map(|c| ColumnSchema::new(*c, ConcreteDataType::string_datatype(), true)),
531        );
532        let schema = Arc::new(
533            SchemaBuilder::try_from_columns(column_schemas)
534                .unwrap()
535                .build()
536                .unwrap(),
537        );
538        let options = TableOptions {
539            extra_options: extra
540                .iter()
541                .map(|(k, v)| (k.to_string(), v.to_string()))
542                .collect::<HashMap<_, _>>(),
543            ..Default::default()
544        };
545        let meta = TableMeta {
546            schema,
547            primary_key_indices: vec![],
548            value_indices: vec![],
549            engine: MITO_ENGINE.to_string(),
550            next_column_id: 1,
551            options,
552            created_on: Default::default(),
553            updated_on: Default::default(),
554            partition_key_indices: vec![],
555            column_ids: vec![],
556        };
557        TableInfoBuilder::default()
558            .table_id(1)
559            .name("t1")
560            .catalog_name(DEFAULT_CATALOG_NAME)
561            .schema_name(DEFAULT_SCHEMA_NAME)
562            .table_version(0)
563            .table_type(TableType::Base)
564            .meta(meta)
565            .build()
566            .unwrap()
567    }
568
569    #[test]
570    fn future_lower_only_window_matches_nothing() {
571        let future_ms = common_time::util::current_time_millis() + 86_400_000;
572        let request = ScanRequest {
573            filters: vec![
574                datafusion_expr::col(OBSERVED_AT_COLUMN).gt_eq(datafusion_expr::lit(
575                    datafusion::common::ScalarValue::TimestampMillisecond(Some(future_ms), None),
576                )),
577            ],
578            ..Default::default()
579        };
580        assert!(
581            EntityGraphProviderImpl::query_window(&request)
582                .unwrap()
583                .is_none()
584        );
585
586        assert!(
587            EntityGraphProviderImpl::query_window(&ScanRequest::default())
588                .unwrap()
589                .is_some()
590        );
591    }
592
593    #[test]
594    fn declaration_referencing_missing_column_is_skipped() {
595        let info = table_info(
596            &["service_name"],
597            &[
598                ("greptime.semantic.entity.service.id", "service_name"),
599                ("greptime.semantic.entity.host.id", "gone"),
600            ],
601        );
602        let declarations = EntityGraphProviderImpl::declarations_for(&info);
603        assert_eq!(declarations.len(), 1);
604        assert_eq!(declarations[0].entity_type, "service");
605
606        let info = table_info(
607            &["service_name"],
608            &[
609                ("greptime.semantic.entity.service.id", "service_name"),
610                ("greptime.semantic.entity.service.descriptive", "gone"),
611            ],
612        );
613        assert!(EntityGraphProviderImpl::declarations_for(&info).is_empty());
614    }
615
616    #[test]
617    fn trace_v1_table_gets_implicit_service_declaration() {
618        let info = table_info(
619            &["service_name"],
620            &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
621        );
622        let declarations = EntityGraphProviderImpl::declarations_for(&info);
623        assert_eq!(declarations.len(), 1);
624        let decl = &declarations[0];
625        assert_eq!(decl.entity_type, "service");
626        assert_eq!(decl.id_columns, vec![SERVICE_NAME_COLUMN.to_string()]);
627        assert_eq!(decl.time_index, "ts");
628
629        // An explicit service declaration wins; no duplicate is synthesized.
630        let info = table_info(
631            &["service_name"],
632            &[
633                (TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1),
634                ("greptime.semantic.entity.service.id", "service_name"),
635            ],
636        );
637        assert_eq!(EntityGraphProviderImpl::declarations_for(&info).len(), 1);
638
639        // A trace-model table without the fixed column synthesizes nothing.
640        let info = table_info(&[], &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)]);
641        assert!(EntityGraphProviderImpl::declarations_for(&info).is_empty());
642
643        // An explicit but invalid declaration must not silently fall back to
644        // the synthesized one: identity must not change behind the user's back.
645        let info = table_info(
646            &["service_name"],
647            &[
648                (TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1),
649                ("greptime.semantic.entity.service.id", "gone"),
650            ],
651        );
652        assert!(EntityGraphProviderImpl::declarations_for(&info).is_empty());
653    }
654}