1use 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
67pub 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 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 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 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 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 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 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 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 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 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 match table_declarations
296 .iter()
297 .find(|d| d.entity_type == "service")
298 {
299 Some(service) => traces.push((service.clone(), table.clone())),
300 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 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 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 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 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 let info = table_info(&[], &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)]);
641 assert!(EntityGraphProviderImpl::declarations_for(&info).is_empty());
642
643 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}