1use std::collections::{BTreeMap, BTreeSet, HashMap};
27use std::sync::{Arc, 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::{
36 DeclarationOrigin, EntityGraphProvider, TableEntityDeclaration,
37};
38use common_catalog::consts::{
39 DEFAULT_PRIVATE_SCHEMA_NAME, DEFAULT_SCHEMA_NAME, INFORMATION_SCHEMA_NAME, OBSERVED_AT_COLUMN,
40 PG_CATALOG_NAME, SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
41};
42use common_error::ext::{BoxedError, ErrorExt};
43use common_error::status_code::StatusCode;
44use common_function::scalars::json::json_get::JsonGetWithType;
45use common_function::scalars::udf::create_udf;
46use common_query::OutputData;
47use common_query::prelude::OTLP_AGGREGATION_TEMPORALITY_LABEL;
48use common_recordbatch::SendableRecordBatchStream;
49use common_telemetry::{debug, warn};
50use common_time::timestamp::TimeUnit;
51use datafusion::common::{Column, ScalarValue};
52use datafusion::dataframe::DataFrame;
53use datafusion_expr::{Expr, LogicalPlan, lit};
54use futures::TryStreamExt;
55use operator::statement::semantic_graph::{
56 CallsSource, CoDeclaredSource, Conventions, DeclaredSource, ENTITY_TYPE_GEN_AI_AGENT,
57 ENTITY_TYPE_SERVICE, EntityDeclaration, GraphQueryWindow, ImplicitEntity, RegistrySource,
58 RelationshipSources, build_registry_plan, build_relationships_plan, conventions,
59 declared_relationships_schema_matches,
60};
61use query::QueryEngineRef;
62use session::context::{QueryContext, QueryContextBuilder, QueryContextRef};
63use snafu::ResultExt;
64use store_api::storage::ScanRequest;
65use table::TableRef;
66use table::metadata::TableInfo;
67use table::predicate::{TimeRangeExtraction, extract_time_range_strict};
68use table::requests::{
69 EntityRole, SEMANTIC_METRIC_TYPE, SEMANTIC_SIGNAL_TYPE, SEMANTIC_SOURCE, SIGNAL_TYPE_METRIC,
70 SOURCE_OPENTELEMETRY, SOURCE_PROMETHEUS, TABLE_DATA_MODEL_TRACE_V2, is_trace_table,
71 parse_entity_columns, parse_entity_option_key, trace_v2_attribute,
72};
73
74use crate::error;
75
76pub struct EntityGraphProviderImpl {
78 query_engine: QueryEngineRef,
79 catalog_manager: Weak<dyn CatalogManager>,
80 permission_checker: Option<PermissionCheckerRef>,
81}
82
83struct EntitySource {
84 declarations: Vec<EntityDeclaration>,
85 is_trace: bool,
86 table: TableRef,
87}
88
89struct TraceSource {
90 service: Option<EntityDeclaration>,
91 agent: Option<EntityDeclaration>,
92 table: TableRef,
93}
94
95impl EntityGraphProviderImpl {
96 pub fn new(
97 query_engine: QueryEngineRef,
98 catalog_manager: Weak<dyn CatalogManager>,
99 permission_checker: Option<PermissionCheckerRef>,
100 ) -> Self {
101 Self {
102 query_engine,
103 catalog_manager,
104 permission_checker,
105 }
106 }
107
108 fn authorize_sources(
112 &self,
113 query_ctx: Option<&QueryContext>,
114 targets: PermissionTableTargets,
115 ) -> Result<bool, BoxedError> {
116 let Some(ctx) = query_ctx else {
117 return Ok(true);
118 };
119 match self
120 .permission_checker
121 .as_ref()
122 .check_permission_with_table_targets(
123 ctx.current_user(),
124 PermissionReq::Action(SEMANTIC_GRAPH_QUERY),
125 targets,
126 Some(&ctx.current_schema()),
127 ) {
128 Ok(_) => Ok(true),
129 Err(err) if err.status_code() == StatusCode::PermissionDenied => Ok(false),
130 Err(err) => Err(BoxedError::new(err)),
131 }
132 }
133
134 fn parse_declarations(table_info: &TableInfo) -> Vec<EntityDeclaration> {
137 type RoleColumns = (Vec<String>, Vec<String>, Vec<String>);
139 let mut by_type: HashMap<String, RoleColumns> = HashMap::new();
140 for (key, value) in &table_info.meta.options.extra_options {
141 let Some((entity_type, role)) = parse_entity_option_key(key) else {
142 continue;
143 };
144 let cols = parse_entity_columns(value);
145 let entry = by_type.entry(entity_type.to_string()).or_default();
146 match role {
147 EntityRole::Id => entry.0 = cols,
148 EntityRole::Descriptive => entry.1 = cols,
149 EntityRole::Scope => entry.2 = cols,
150 }
151 }
152 if by_type.is_empty() {
153 return vec![];
154 }
155 let Some(time_index) = table_info
156 .meta
157 .schema
158 .timestamp_column()
159 .map(|c| c.name.clone())
160 else {
161 return vec![];
162 };
163
164 by_type
165 .into_iter()
166 .filter(|(_, (id, _, _))| !id.is_empty())
167 .filter_map(
168 |(entity_type, (id_columns, descriptive_columns, scope_columns))| {
169 if let Some(missing) = id_columns
172 .iter()
173 .chain(&descriptive_columns)
174 .chain(&scope_columns)
175 .find(|c| !Self::can_resolve_entity_column(table_info, c))
176 {
177 warn!(
178 "Skipping entity declaration `{}` of table `{}`: column `{}` not found",
179 entity_type, table_info.name, missing
180 );
181 return None;
182 }
183 Some(EntityDeclaration {
184 schema: table_info.schema_name.clone(),
185 table: table_info.name.clone(),
186 time_index: time_index.clone(),
187 entity_type,
188 id_columns,
189 id_qualifier: None,
190 superseded_by_columns: vec![],
191 descriptive_columns,
192 scope_columns,
193 })
194 },
195 )
196 .collect()
197 }
198
199 fn declarations_for(
208 table_info: &TableInfo,
209 conventions: &Conventions,
210 ) -> Vec<EntityDeclaration> {
211 let mut declarations = Self::parse_declarations(table_info);
212 let mut supersessions = Vec::new();
213 if is_trace_table(table_info) {
214 Self::extend_with_implicit_entities(
215 table_info,
216 &conventions.otlp_trace_entities,
217 &mut declarations,
218 &mut supersessions,
219 );
220 }
221 Self::extend_with_info_metric_conventions(
222 table_info,
223 &conventions.prometheus_info_metrics,
224 SOURCE_PROMETHEUS,
225 None,
226 &mut declarations,
227 &mut supersessions,
228 );
229 Self::extend_with_info_metric_conventions(
230 table_info,
231 &conventions.otel_info_metrics,
232 SOURCE_OPENTELEMETRY,
233 Some(servers::semantic::METRIC_TYPE_INFO),
234 &mut declarations,
235 &mut supersessions,
236 );
237 Self::resolve_supersessions(&mut declarations, supersessions);
238 declarations
239 }
240
241 fn resolve_supersessions(
246 declarations: &mut [EntityDeclaration],
247 supersessions: Vec<(usize, String)>,
248 ) {
249 for (index, entity_type) in supersessions {
250 let identity = declarations
251 .iter()
252 .find(|declaration| declaration.entity_type == entity_type)
253 .map(|declaration| declaration.id_columns.clone())
254 .unwrap_or_default();
255 declarations[index].superseded_by_columns = identity;
256 }
257 }
258
259 fn explicitly_declares(table_info: &TableInfo, entity_type: &str) -> bool {
261 table_info.meta.options.extra_options.keys().any(|key| {
262 parse_entity_option_key(key)
263 .is_some_and(|(ty, role)| ty == entity_type && role == EntityRole::Id)
264 })
265 }
266
267 fn extend_with_info_metric_conventions(
275 table_info: &TableInfo,
276 whitelist: &BTreeMap<String, Vec<ImplicitEntity>>,
277 expected_source: &str,
278 expected_metric_type: Option<&str>,
279 declarations: &mut Vec<EntityDeclaration>,
280 supersessions: &mut Vec<(usize, String)>,
281 ) {
282 let Some(implicit_entities) = whitelist.get(&table_info.name) else {
283 return;
284 };
285 let options = &table_info.meta.options.extra_options;
286 if options.get(SEMANTIC_SIGNAL_TYPE).map(String::as_str) != Some(SIGNAL_TYPE_METRIC)
287 || options.get(SEMANTIC_SOURCE).map(String::as_str) != Some(expected_source)
288 || expected_metric_type.is_some_and(|expected| {
289 options.get(SEMANTIC_METRIC_TYPE).map(String::as_str) != Some(expected)
290 })
291 || table_info.is_physical_table()
292 {
293 debug!(
294 "Table `{}` matches the info-metric whitelist but is not an eligible \
295 `{expected_source}` info-metric source; skipping its implicit declarations",
296 table_info.name
297 );
298 return;
299 }
300 Self::extend_with_implicit_entities(
301 table_info,
302 implicit_entities,
303 declarations,
304 supersessions,
305 );
306 }
307
308 fn extend_with_implicit_entities(
312 table_info: &TableInfo,
313 entities: &[ImplicitEntity],
314 declarations: &mut Vec<EntityDeclaration>,
315 supersessions: &mut Vec<(usize, String)>,
316 ) {
317 let schema = &table_info.meta.schema;
318 let Some(time_index) = schema.timestamp_column().map(|c| c.name.clone()) else {
319 debug!(
320 "Table `{}` has no time index; skipping its implicit declarations",
321 table_info.name
322 );
323 return;
324 };
325 for implicit in entities {
326 if Self::explicitly_declares(table_info, &implicit.entity) {
327 debug!(
328 "Table `{}` explicitly declares `{}`; the implicit declaration is suppressed",
329 table_info.name, implicit.entity
330 );
331 continue;
332 }
333 if let Some(missing) = implicit
334 .id
335 .iter()
336 .find(|c| !Self::can_resolve_entity_column(table_info, c))
337 {
338 debug!(
339 "Table `{}` lacks the id column `{}`; skipping the implicit `{}` declaration",
340 table_info.name, missing, implicit.entity
341 );
342 continue;
343 }
344 let descriptive_columns = if implicit.descriptive_rest {
345 table_info
346 .meta
347 .row_key_column_names()
348 .filter(|c| !implicit.id.contains(c))
349 .filter(|c| c.as_str() != OTLP_AGGREGATION_TEMPORALITY_LABEL)
350 .cloned()
351 .collect()
352 } else {
353 implicit
354 .descriptive
355 .iter()
356 .filter(|c| Self::can_resolve_entity_column(table_info, c))
357 .cloned()
358 .collect()
359 };
360 let id_qualifier = implicit
363 .qualified_by
364 .clone()
365 .filter(|c| Self::can_resolve_entity_column(table_info, c));
366 if let Some(entity_type) = &implicit.superseded_by {
367 supersessions.push((declarations.len(), entity_type.clone()));
368 }
369 declarations.push(EntityDeclaration {
370 schema: table_info.schema_name.clone(),
371 table: table_info.name.clone(),
372 time_index: time_index.clone(),
373 entity_type: implicit.entity.clone(),
374 id_columns: implicit.id.clone(),
375 id_qualifier,
376 superseded_by_columns: vec![],
377 descriptive_columns,
378 scope_columns: vec![],
379 });
380 }
381 }
382
383 async fn enumerate(
388 &self,
389 catalog: &str,
390 query_ctx: Option<&QueryContext>,
391 ) -> Result<(Vec<EntitySource>, Vec<TraceSource>), BoxedError> {
392 let Some(catalog_manager) = self.catalog_manager.upgrade() else {
393 return Ok((vec![], vec![]));
394 };
395 let conventions = conventions()
396 .map_err(datafusion::error::DataFusionError::Internal)
397 .context(error::DataFusionSnafu)
398 .map_err(BoxedError::new)?;
399
400 let per_table_auth = match self.permission_checker.as_ref() {
403 Some(checker) if query_ctx.is_some() => {
404 if checker.uses_table_targets() {
405 true
406 } else if self
407 .authorize_sources(query_ctx, PermissionTableTargets::resolved(vec![]))?
408 {
409 false
410 } else {
411 debug!(
412 "Caller lacks the entity-graph read permission; deriving an empty graph \
413 (catalog: {catalog})"
414 );
415 return Ok((vec![], vec![]));
416 }
417 }
418 _ => false,
419 };
420
421 let mut declarations = vec![];
422 let mut traces = vec![];
423 let schemas = catalog_manager
424 .schema_names(catalog, query_ctx)
425 .await
426 .map_err(BoxedError::new)?;
427 for schema in schemas {
428 if schema == INFORMATION_SCHEMA_NAME
431 || schema == PG_CATALOG_NAME
432 || schema == DEFAULT_PRIVATE_SCHEMA_NAME
433 {
434 continue;
435 }
436 let mut tables = catalog_manager.tables(catalog, &schema, query_ctx);
437 while let Some(table) = tables.try_next().await.map_err(BoxedError::new)? {
438 let table_info = table.table_info();
439 let table_declarations = Self::declarations_for(&table_info, conventions);
440 let is_trace = is_trace_table(&table_info);
441 if per_table_auth
443 && (is_trace || !table_declarations.is_empty())
444 && !self.authorize_sources(
445 query_ctx,
446 PermissionTableTargets::resolved(vec![
447 PermissionTableTarget::new(catalog, &schema, &table_info.name)
448 .with_physical_metric_table(table_info.is_physical_table()),
449 ]),
450 )?
451 {
452 debug!(
453 "Excluding `{schema}.{}` from the entity-graph derivation: caller lacks \
454 read permission",
455 table_info.name
456 );
457 continue;
458 }
459 if is_trace {
460 let find = |entity_type: &str| {
461 table_declarations
462 .iter()
463 .find(|d| d.entity_type == entity_type)
464 .cloned()
465 };
466 let service = find(ENTITY_TYPE_SERVICE);
467 let agent = find(ENTITY_TYPE_GEN_AI_AGENT);
468 if service.is_none() {
469 warn!(
472 "Trace table `{}` has no usable service declaration; skipping calls derivation",
473 table_info.name
474 );
475 }
476 if service.is_some() || agent.is_some() {
477 traces.push(TraceSource {
478 service,
479 agent,
480 table: table.clone(),
481 });
482 }
483 }
484 if !table_declarations.is_empty() {
485 declarations.push(EntitySource {
486 declarations: table_declarations,
487 is_trace,
488 table,
489 });
490 }
491 }
492 }
493 Ok((declarations, traces))
494 }
495
496 fn query_window(request: &ScanRequest) -> Result<Option<GraphQueryWindow>, BoxedError> {
508 let invalid =
509 |err_msg: String| Err(BoxedError::new(error::InvalidSqlSnafu { err_msg }.build()));
510 match extract_time_range_strict(OBSERVED_AT_COLUMN, TimeUnit::Millisecond, &request.filters)
511 {
512 TimeRangeExtraction::Absent => Ok(Some(GraphQueryWindow::default_last_hour())),
513 TimeRangeExtraction::Extracted(range) => {
514 let Some(start) = range.start() else {
515 return invalid(format!(
516 "the {OBSERVED_AT_COLUMN} filter has no lower bound; the graph cannot \
517 derive over unbounded history — add e.g. {OBSERVED_AT_COLUMN} >= \
518 '2026-01-01 00:00:00'"
519 ));
520 };
521 let end_ms = range
522 .end()
523 .map(|ts| ts.value())
524 .unwrap_or_else(common_time::util::current_time_millis);
525 if start.value() >= end_ms {
526 return Ok(None);
527 }
528 Ok(Some(GraphQueryWindow::from_observed(start.value(), end_ms)))
529 }
530 TimeRangeExtraction::Unsupported => invalid(format!(
531 "cannot derive the graph window from the {OBSERVED_AT_COLUMN} filter; use plain \
532 range predicates (>=, <, BETWEEN) with literal bounds"
533 )),
534 }
535 }
536
537 fn can_resolve_entity_column(table_info: &TableInfo, column: &str) -> bool {
538 let table_schema = &table_info.meta.schema;
539 if table_schema.column_schema_by_name(column).is_some() {
540 return true;
541 }
542 let data_model = table_info.meta.options.data_model();
543 trace_v2_attribute(table_schema, data_model, column).is_some()
544 }
545
546 fn read_table(
549 &self,
550 table: TableRef,
551 declarations: &[EntityDeclaration],
552 ) -> Result<DataFrame, BoxedError> {
553 let info = table.table_info();
554 let mut scan = self
555 .query_engine
556 .read_table(table)
557 .map_err(BoxedError::new)?;
558 let data_model = info.meta.options.data_model();
559 if data_model != Some(TABLE_DATA_MODEL_TRACE_V2) {
560 return Ok(scan);
561 }
562
563 let mut columns = BTreeSet::new();
565 for declaration in declarations {
566 columns.extend(declaration.id_columns.iter());
567 columns.extend(declaration.descriptive_columns.iter());
568 columns.extend(declaration.scope_columns.iter());
569 columns.extend(declaration.id_qualifier.iter());
570 columns.extend(declaration.superseded_by_columns.iter());
571 }
572 let conventions = conventions()
573 .map_err(datafusion::error::DataFusionError::Internal)
574 .context(error::DataFusionSnafu)
575 .map_err(BoxedError::new)?;
576 let virtual_candidates = &conventions.virtual_dst_candidates;
577 columns.extend(virtual_candidates.iter().map(|candidate| &candidate.column));
578 let get = create_udf(Arc::new(JsonGetWithType::default()));
579 for column in columns {
580 if let Some((root, key)) = trace_v2_attribute(&info.meta.schema, data_model, column) {
581 let path = format!("$.{}", serde_json::Value::String(key.to_string()));
582 let value = get.call(vec![
583 Expr::Column(Column::from_name(root)),
584 lit(path),
585 lit(ScalarValue::Utf8View(None)),
586 ]);
587 scan = scan
588 .with_column(column, value)
589 .context(error::DataFusionSnafu)
590 .map_err(BoxedError::new)?;
591 }
592 }
593 Ok(scan)
594 }
595
596 async fn declared_source(
601 &self,
602 catalog: &str,
603 query_ctx: Option<&QueryContext>,
604 ) -> Result<Option<DeclaredSource>, BoxedError> {
605 let Some(catalog_manager) = self.catalog_manager.upgrade() else {
606 return Ok(None);
607 };
608 let Some(table) = catalog_manager
609 .table(
610 catalog,
611 DEFAULT_PRIVATE_SCHEMA_NAME,
612 SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
613 query_ctx,
614 )
615 .await
616 .map_err(BoxedError::new)?
617 else {
618 return Ok(None);
619 };
620 let table_info = table.table_info();
621 if !self.authorize_sources(
622 query_ctx,
623 PermissionTableTargets::resolved(vec![
624 PermissionTableTarget::new(
625 catalog,
626 DEFAULT_PRIVATE_SCHEMA_NAME,
627 SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME,
628 )
629 .with_physical_metric_table(table_info.is_physical_table()),
630 ]),
631 )? {
632 debug!(
633 "Excluding declared edges: caller lacks read permission on \
634 `{DEFAULT_PRIVATE_SCHEMA_NAME}.{SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME}`"
635 );
636 return Ok(None);
637 }
638 if !declared_relationships_schema_matches(&table_info) {
639 return Err(BoxedError::new(
640 error::InvalidSqlSnafu {
641 err_msg: format!(
642 "{DEFAULT_PRIVATE_SCHEMA_NAME}.{SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME} \
643 does not match its canonical schema; declared edges cannot be derived"
644 ),
645 }
646 .build(),
647 ));
648 }
649 Ok(Some(DeclaredSource {
650 scan: self.read_table(table, &[])?,
651 }))
652 }
653
654 async fn execute_plan(
658 &self,
659 catalog: &str,
660 plan: LogicalPlan,
661 query_ctx: Option<QueryContextRef>,
662 ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
663 let query_ctx = query_ctx.unwrap_or_else(|| {
664 QueryContextBuilder::default()
665 .current_catalog(catalog.to_string())
666 .current_schema(DEFAULT_SCHEMA_NAME.to_string())
667 .build()
668 .into()
669 });
670 let output = self
671 .query_engine
672 .execute(plan, query_ctx)
673 .await
674 .map_err(BoxedError::new)?;
675 let stream = match output.data {
676 OutputData::Stream(stream) => stream,
677 OutputData::RecordBatches(batches) => batches.as_stream(),
678 OutputData::AffectedRows(_) => return Ok(None),
679 };
680 Ok(Some(stream))
681 }
682}
683
684#[async_trait]
685impl EntityGraphProvider for EntityGraphProviderImpl {
686 async fn scan_entities(
687 &self,
688 catalog: &str,
689 request: ScanRequest,
690 query_ctx: Option<QueryContextRef>,
691 ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
692 let (sources, _) = self.enumerate(catalog, query_ctx.as_deref()).await?;
693 let mut plans = Vec::with_capacity(sources.len());
694 for source in sources {
695 plans.push(RegistrySource {
696 scan: self.read_table(source.table, &source.declarations)?,
697 declarations: source.declarations,
698 });
699 }
700 let Some(window) = Self::query_window(&request)? else {
701 return Ok(None);
702 };
703 let Some(plan) = build_registry_plan(plans, &window)
704 .context(error::DataFusionSnafu)
705 .map_err(BoxedError::new)?
706 else {
707 return Ok(None);
708 };
709 self.execute_plan(catalog, plan, query_ctx).await
710 }
711
712 async fn scan_relationships(
713 &self,
714 catalog: &str,
715 request: ScanRequest,
716 query_ctx: Option<QueryContextRef>,
717 ) -> Result<Option<SendableRecordBatchStream>, BoxedError> {
718 let (sources, traces) = self.enumerate(catalog, query_ctx.as_deref()).await?;
719 let mut calls = Vec::with_capacity(traces.len());
720 for trace in traces {
721 let declarations = trace
722 .service
723 .iter()
724 .chain(trace.agent.iter())
725 .cloned()
726 .collect::<Vec<_>>();
727 calls.push(CallsSource {
728 scan: self.read_table(trace.table, &declarations)?,
729 service: trace.service,
730 agent: trace.agent,
731 });
732 }
733 let mut co_declared = Vec::with_capacity(sources.len());
734 for source in sources {
735 co_declared.push(CoDeclaredSource {
736 scan: self.read_table(source.table, &source.declarations)?,
737 declarations: source.declarations,
738 is_trace: source.is_trace,
739 });
740 }
741 let declared = self.declared_source(catalog, query_ctx.as_deref()).await?;
742 let Some(window) = Self::query_window(&request)? else {
743 return Ok(None);
744 };
745 let Some(plan) = build_relationships_plan(
746 RelationshipSources {
747 traces: calls,
748 co_declared,
749 declared,
750 },
751 &window,
752 )
753 .context(error::DataFusionSnafu)
754 .map_err(BoxedError::new)?
755 else {
756 return Ok(None);
757 };
758 self.execute_plan(catalog, plan, query_ctx).await
759 }
760
761 fn table_declarations(&self, table_info: &TableInfo) -> Vec<TableEntityDeclaration> {
762 let derived = match conventions() {
765 Ok(conventions) => Self::declarations_for(table_info, conventions),
766 Err(_) => Self::parse_declarations(table_info),
767 };
768 let mut declarations = derived
769 .into_iter()
770 .map(|declaration| TableEntityDeclaration {
771 origin: if Self::explicitly_declares(table_info, &declaration.entity_type) {
772 DeclarationOrigin::Declared
773 } else {
774 DeclarationOrigin::Convention
775 },
776 entity_type: declaration.entity_type,
777 id_columns: declaration.id_columns,
778 id_qualifier: declaration.id_qualifier,
779 superseded_by_columns: declaration.superseded_by_columns,
780 descriptive_columns: declaration.descriptive_columns,
781 scope_columns: declaration.scope_columns,
782 })
783 .collect::<Vec<_>>();
784 declarations.sort_by(|a, b| a.entity_type.cmp(&b.entity_type));
785 declarations
786 }
787}
788
789#[cfg(test)]
790mod tests {
791 use std::collections::HashMap;
792 use std::sync::Arc;
793
794 use common_catalog::consts::{DEFAULT_CATALOG_NAME, MITO_ENGINE};
795 use datatypes::prelude::ConcreteDataType;
796 use datatypes::schema::{ColumnSchema, SchemaBuilder};
797 use store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY;
798 use table::metadata::{TableInfoBuilder, TableMeta, TableType};
799 use table::requests::{TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1, TableOptions};
800
801 use super::*;
802
803 struct DenyPhysicalTables;
804
805 impl PermissionChecker for DenyPhysicalTables {
806 fn check_permission(
807 &self,
808 _: auth::UserInfoRef,
809 _: PermissionReq,
810 ) -> auth::error::Result<auth::PermissionResp> {
811 Ok(auth::PermissionResp::Allow)
812 }
813
814 fn check_permission_with_table_targets(
815 &self,
816 _: auth::UserInfoRef,
817 _: PermissionReq,
818 targets: PermissionTableTargets,
819 _: Option<&str>,
820 ) -> auth::error::Result<auth::PermissionResp> {
821 let PermissionTableTargets::Resolved(targets) = targets else {
822 panic!("entity graph must resolve its sources");
823 };
824 Ok(
825 if targets.iter().any(|target| target.is_physical_metric_table) {
826 auth::PermissionResp::Reject
827 } else {
828 auth::PermissionResp::Allow
829 },
830 )
831 }
832 }
833
834 #[tokio::test]
835 async fn test_enumerate_authorizes_physical_tables() {
836 for physical in [false, true] {
837 let mut options = vec![("greptime.semantic.entity.service.id", "service_name")];
838 if physical {
839 options.push((PHYSICAL_TABLE_METADATA_KEY, ""));
840 }
841 let info = table_info(&["service_name"], &options);
842 let batch = common_recordbatch::RecordBatch::new_empty(info.meta.schema.clone());
843 let source = table::test_util::MemTable::table("t1", batch);
844 let table = Arc::new(table::Table::new(
845 Arc::new(info),
846 table::metadata::FilterPushDownType::Unsupported,
847 source.data_source(),
848 ));
849 let catalog: Arc<dyn CatalogManager> =
850 catalog::memory::MemoryCatalogManager::new_with_table(table);
851 let engine = query::QueryEngineFactory::new(
852 catalog.clone(),
853 None,
854 None,
855 None,
856 None,
857 false,
858 query::options::QueryOptions::default(),
859 )
860 .query_engine();
861 let provider = EntityGraphProviderImpl::new(
862 engine,
863 Arc::downgrade(&catalog),
864 Some(Arc::new(DenyPhysicalTables)),
865 );
866 let ctx = QueryContext::arc();
867 let (sources, _) = provider
868 .enumerate(DEFAULT_CATALOG_NAME, Some(&ctx))
869 .await
870 .unwrap();
871 assert_eq!(sources.len(), usize::from(!physical));
872 }
873 }
874
875 fn table_info(columns: &[&str], extra: &[(&str, &str)]) -> TableInfo {
876 let mut column_schemas = vec![
877 ColumnSchema::new(
878 "ts",
879 ConcreteDataType::timestamp_millisecond_datatype(),
880 false,
881 )
882 .with_time_index(true),
883 ];
884 column_schemas.extend(
885 columns
886 .iter()
887 .map(|c| ColumnSchema::new(*c, ConcreteDataType::string_datatype(), true)),
888 );
889 assemble_table_info(column_schemas, extra)
890 }
891
892 fn assemble_table_info(column_schemas: Vec<ColumnSchema>, extra: &[(&str, &str)]) -> TableInfo {
893 named_table_info("t1", column_schemas, vec![], extra)
894 }
895
896 fn named_table_info(
897 name: &str,
898 column_schemas: Vec<ColumnSchema>,
899 primary_key_indices: Vec<usize>,
900 extra: &[(&str, &str)],
901 ) -> TableInfo {
902 let schema = Arc::new(
903 SchemaBuilder::try_from_columns(column_schemas)
904 .unwrap()
905 .build()
906 .unwrap(),
907 );
908 let options = TableOptions {
909 extra_options: extra
910 .iter()
911 .map(|(k, v)| (k.to_string(), v.to_string()))
912 .collect::<HashMap<_, _>>(),
913 ..Default::default()
914 };
915 let meta = TableMeta {
916 schema,
917 primary_key_indices,
918 value_indices: vec![],
919 engine: MITO_ENGINE.to_string(),
920 next_column_id: 1,
921 options,
922 created_on: Default::default(),
923 updated_on: Default::default(),
924 partition_key_indices: vec![],
925 column_ids: vec![],
926 };
927 TableInfoBuilder::default()
928 .table_id(1)
929 .name(name)
930 .catalog_name(DEFAULT_CATALOG_NAME)
931 .schema_name(DEFAULT_SCHEMA_NAME)
932 .table_version(0)
933 .table_type(TableType::Base)
934 .meta(meta)
935 .build()
936 .unwrap()
937 }
938
939 fn prom_table_info(name: &str, tags: &[&str], extra: &[(&str, &str)]) -> TableInfo {
941 let mut column_schemas = vec![
942 ColumnSchema::new(
943 "greptime_timestamp",
944 ConcreteDataType::timestamp_millisecond_datatype(),
945 false,
946 )
947 .with_time_index(true),
948 ];
949 column_schemas.extend(
950 tags.iter()
951 .map(|c| ColumnSchema::new(*c, ConcreteDataType::string_datatype(), true)),
952 );
953 let primary_key_indices = (1..=tags.len()).collect();
954 named_table_info(name, column_schemas, primary_key_indices, extra)
955 }
956
957 #[test]
958 fn future_lower_only_window_matches_nothing() {
959 let future_ms = common_time::util::current_time_millis() + 86_400_000;
960 let request = ScanRequest {
961 filters: vec![
962 datafusion_expr::col(OBSERVED_AT_COLUMN).gt_eq(datafusion_expr::lit(
963 datafusion::common::ScalarValue::TimestampMillisecond(Some(future_ms), None),
964 )),
965 ],
966 ..Default::default()
967 };
968 assert!(
969 EntityGraphProviderImpl::query_window(&request)
970 .unwrap()
971 .is_none()
972 );
973
974 assert!(
975 EntityGraphProviderImpl::query_window(&ScanRequest::default())
976 .unwrap()
977 .is_some()
978 );
979 }
980
981 #[test]
982 fn declaration_referencing_missing_column_is_skipped() {
983 let info = table_info(
984 &["service_name"],
985 &[
986 ("greptime.semantic.entity.service.id", "service_name"),
987 ("greptime.semantic.entity.host.id", "gone"),
988 ],
989 );
990 let declarations = EntityGraphProviderImpl::declarations_for(&info, conventions().unwrap());
991 assert_eq!(declarations.len(), 1);
992 assert_eq!(declarations[0].entity_type, "service");
993
994 let info = table_info(
995 &["service_name"],
996 &[
997 ("greptime.semantic.entity.service.id", "service_name"),
998 ("greptime.semantic.entity.service.descriptive", "gone"),
999 ],
1000 );
1001 assert!(
1002 EntityGraphProviderImpl::declarations_for(&info, conventions().unwrap()).is_empty()
1003 );
1004 }
1005
1006 const PROM_STAMPS: &[(&str, &str)] = &[
1007 (SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC),
1008 (SEMANTIC_SOURCE, SOURCE_PROMETHEUS),
1009 ];
1010
1011 fn sorted_declarations(info: &TableInfo) -> Vec<EntityDeclaration> {
1012 let mut declarations =
1013 EntityGraphProviderImpl::declarations_for(info, conventions().unwrap());
1014 declarations.sort_by(|a, b| a.entity_type.cmp(&b.entity_type));
1015 declarations
1016 }
1017
1018 #[test]
1019 fn prometheus_info_metric_gets_implicit_declarations() {
1020 let info = prom_table_info(
1021 "kube_pod_info",
1022 &["namespace", "pod", "uid", "node", "job", "instance"],
1023 PROM_STAMPS,
1024 );
1025 let declarations = sorted_declarations(&info);
1026 assert_eq!(declarations.len(), 2);
1027 assert_eq!(declarations[0].entity_type, "k8s.node");
1028 assert_eq!(declarations[0].id_columns, vec!["node"]);
1029 assert_eq!(declarations[1].entity_type, "k8s.pod");
1030 assert_eq!(declarations[1].id_columns, vec!["uid"]);
1031 assert_eq!(
1034 declarations[1].descriptive_columns,
1035 vec!["namespace", "pod", "node"]
1036 );
1037 assert_eq!(declarations[1].time_index, "greptime_timestamp");
1038 }
1039
1040 #[test]
1041 fn trace_table_gets_implicit_resource_entities() {
1042 let full = table_info(
1043 &[
1044 "service_name",
1045 "resource_attributes.service.instance.id",
1046 "resource_attributes.k8s.pod.uid",
1047 "resource_attributes.k8s.pod.name",
1048 "resource_attributes.k8s.node.name",
1049 ],
1050 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1051 );
1052 let declarations = sorted_declarations(&full);
1053 let types: Vec<&str> = declarations
1054 .iter()
1055 .map(|d| d.entity_type.as_str())
1056 .collect();
1057 assert_eq!(
1058 types,
1059 vec!["k8s.node", "k8s.pod", "service", "service.instance"]
1060 );
1061 assert_eq!(
1062 declarations[0].id_columns,
1063 vec!["resource_attributes.k8s.node.name"]
1064 );
1065 assert_eq!(
1066 declarations[1].id_columns,
1067 vec!["resource_attributes.k8s.pod.uid"]
1068 );
1069 assert_eq!(
1070 declarations[1].descriptive_columns,
1071 vec!["resource_attributes.k8s.pod.name"]
1072 );
1073 assert_eq!(
1074 declarations[3].id_columns,
1075 vec!["service_name", "resource_attributes.service.instance.id"]
1076 );
1077 assert_eq!(declarations[2].id_qualifier, None);
1078
1079 let namespaced = table_info(
1080 &[
1081 "service_name",
1082 "resource_attributes.service.namespace",
1083 "resource_attributes.service.instance.id",
1084 ],
1085 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1086 );
1087 for declaration in sorted_declarations(&namespaced) {
1088 assert_eq!(
1089 declaration.id_qualifier.as_deref(),
1090 Some("resource_attributes.service.namespace"),
1091 "{} must qualify its identity like the metric side's job",
1092 declaration.entity_type
1093 );
1094 }
1095
1096 let no_uid = table_info(
1098 &["service_name", "resource_attributes.k8s.pod.name"],
1099 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1100 );
1101 let types: Vec<String> = sorted_declarations(&no_uid)
1102 .into_iter()
1103 .map(|d| d.entity_type)
1104 .collect();
1105 assert_eq!(types, vec!["service"]);
1106
1107 let invalid_explicit = table_info(
1110 &["service_name"],
1111 &[
1112 (TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1),
1113 ("greptime.semantic.entity.service.id", "gone"),
1114 ],
1115 );
1116 assert!(sorted_declarations(&invalid_explicit).is_empty());
1117 }
1118
1119 #[test]
1120 fn trace_table_host_and_container_require_stable_ids() {
1121 let with_ids = table_info(
1122 &[
1123 "service_name",
1124 "resource_attributes.host.id",
1125 "resource_attributes.host.name",
1126 "resource_attributes.container.id",
1127 ],
1128 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1129 );
1130 let declarations = sorted_declarations(&with_ids);
1131 let types: Vec<&str> = declarations
1132 .iter()
1133 .map(|d| d.entity_type.as_str())
1134 .collect();
1135 assert_eq!(types, vec!["container", "host", "service"]);
1136 assert_eq!(
1137 declarations[1].id_columns,
1138 vec!["resource_attributes.host.id"]
1139 );
1140 assert_eq!(
1141 declarations[1].descriptive_columns,
1142 vec!["resource_attributes.host.name"]
1143 );
1144
1145 let pod_container = table_info(
1149 &[
1150 "service_name",
1151 "resource_attributes.container.id",
1152 "resource_attributes.container.name",
1153 "resource_attributes.k8s.pod.uid",
1154 "resource_attributes.k8s.container.name",
1155 ],
1156 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1157 );
1158 let declarations = sorted_declarations(&pod_container);
1159 let types: Vec<&str> = declarations
1160 .iter()
1161 .map(|d| d.entity_type.as_str())
1162 .collect();
1163 assert_eq!(
1164 types,
1165 vec!["container", "k8s.container", "k8s.pod", "service"]
1166 );
1167 assert_eq!(
1168 declarations[0].superseded_by_columns,
1169 vec![
1170 "resource_attributes.k8s.pod.uid",
1171 "resource_attributes.k8s.container.name"
1172 ]
1173 );
1174 assert_eq!(
1175 declarations[1].descriptive_columns,
1176 vec![
1177 "resource_attributes.container.id",
1178 "resource_attributes.container.name"
1179 ]
1180 );
1181
1182 let names_only = table_info(
1183 &[
1184 "service_name",
1185 "resource_attributes.host.name",
1186 "resource_attributes.container.name",
1187 ],
1188 &[(TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1)],
1189 );
1190 let types: Vec<String> = sorted_declarations(&names_only)
1191 .into_iter()
1192 .map(|d| d.entity_type)
1193 .collect();
1194 assert_eq!(types, vec!["service"]);
1195 }
1196
1197 #[test]
1198 fn prometheus_implicit_declarations_are_gated() {
1199 let labels: &[&str] = &["namespace", "pod", "node"];
1200 assert!(
1202 sorted_declarations(&prom_table_info(
1203 "kube_pod_info",
1204 labels,
1205 &[
1206 (SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC),
1207 (SEMANTIC_SOURCE, "opentelemetry"),
1208 ],
1209 ))
1210 .is_empty()
1211 );
1212 assert!(
1214 sorted_declarations(&prom_table_info("http_requests_total", labels, PROM_STAMPS))
1215 .is_empty()
1216 );
1217 let mut stamps = PROM_STAMPS.to_vec();
1218 stamps.push((PHYSICAL_TABLE_METADATA_KEY, "true"));
1219 assert!(sorted_declarations(&prom_table_info("kube_pod_info", labels, &stamps)).is_empty());
1220
1221 let info = prom_table_info("kube_pod_info", &["namespace", "pod", "node"], PROM_STAMPS);
1223 let declarations = sorted_declarations(&info);
1224 assert_eq!(declarations.len(), 1);
1225 assert_eq!(declarations[0].entity_type, "k8s.node");
1226 }
1227
1228 #[test]
1229 fn explicit_declaration_suppresses_the_implicit_one() {
1230 let mut stamps = PROM_STAMPS.to_vec();
1231 stamps.push(("greptime.semantic.entity.k8s.pod.id", "pod"));
1232 let info = prom_table_info("kube_pod_info", &["namespace", "pod", "node"], &stamps);
1233 let declarations = sorted_declarations(&info);
1234 assert_eq!(declarations.len(), 2);
1235 assert_eq!(declarations[0].entity_type, "k8s.node");
1236 assert_eq!(declarations[1].entity_type, "k8s.pod");
1237 assert_eq!(declarations[1].id_columns, vec!["pod"]);
1239 }
1240
1241 const OTEL_STAMPS: &[(&str, &str)] = &[
1242 (SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC),
1243 (SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY),
1244 (SEMANTIC_METRIC_TYPE, servers::semantic::METRIC_TYPE_INFO),
1245 ];
1246
1247 #[test]
1248 fn greptime_otel_resource_info_gets_implicit_declarations() {
1249 let info = prom_table_info(
1250 "greptime_otel_resource_info",
1251 &[
1252 "job",
1253 "instance",
1254 "service.name",
1255 "service.namespace",
1256 "host.id",
1257 "host.name",
1258 "container.id",
1259 "container.name",
1260 "k8s.pod.uid",
1261 "k8s.pod.name",
1262 "k8s.container.name",
1263 "k8s.namespace.name",
1264 "k8s.node.name",
1265 ],
1266 OTEL_STAMPS,
1267 );
1268 let declarations = sorted_declarations(&info);
1269 let types: Vec<&str> = declarations
1270 .iter()
1271 .map(|d| d.entity_type.as_str())
1272 .collect();
1273 assert_eq!(
1274 types,
1275 vec![
1276 "container",
1277 "host",
1278 "k8s.container",
1279 "k8s.node",
1280 "k8s.pod",
1281 "service",
1282 "service.instance"
1283 ]
1284 );
1285 assert_eq!(
1288 declarations[2].id_columns,
1289 vec!["k8s.pod.uid", "k8s.container.name"]
1290 );
1291 assert_eq!(
1292 declarations[0].superseded_by_columns,
1293 vec!["k8s.pod.uid", "k8s.container.name"],
1294 "the generic container must yield to the k8s.container identity itself"
1295 );
1296 assert_eq!(declarations[1].id_columns, vec!["host.id"]);
1297 assert_eq!(declarations[1].descriptive_columns, vec!["host.name"]);
1298 assert_eq!(declarations[3].id_columns, vec!["k8s.node.name"]);
1299 assert_eq!(declarations[5].id_columns, vec!["job"]);
1300 assert_eq!(
1301 declarations[5].descriptive_columns,
1302 vec!["service.name", "service.namespace"]
1303 );
1304 assert_eq!(declarations[6].id_columns, vec!["job", "instance"]);
1305 assert!(declarations[6].descriptive_columns.is_empty());
1306
1307 let no_k8s = prom_table_info(
1310 "greptime_otel_resource_info",
1311 &["job", "container.id", "k8s.pod.uid"],
1312 OTEL_STAMPS,
1313 );
1314 let declarations = sorted_declarations(&no_k8s);
1315 assert_eq!(declarations[0].entity_type, "container");
1316 assert!(declarations[0].superseded_by_columns.is_empty());
1317
1318 let mut stamps = OTEL_STAMPS.to_vec();
1321 stamps.push(("greptime.semantic.entity.k8s.container.id", "gone"));
1322 let broken_explicit = prom_table_info(
1323 "greptime_otel_resource_info",
1324 &["job", "container.id", "k8s.pod.uid", "k8s.container.name"],
1325 &stamps,
1326 );
1327 let declarations = sorted_declarations(&broken_explicit);
1328 let types: Vec<&str> = declarations
1329 .iter()
1330 .map(|d| d.entity_type.as_str())
1331 .collect();
1332 assert_eq!(types, vec!["container", "k8s.pod", "service"]);
1333 assert!(declarations[0].superseded_by_columns.is_empty());
1334
1335 let partial = prom_table_info(
1336 "greptime_otel_resource_info",
1337 &["job", "service.name", "host.id"],
1338 OTEL_STAMPS,
1339 );
1340 let types: Vec<String> = sorted_declarations(&partial)
1341 .into_iter()
1342 .map(|d| d.entity_type)
1343 .collect();
1344 assert_eq!(types, vec!["host", "service"]);
1345 }
1346
1347 #[test]
1348 fn otel_implicit_declarations_are_gated() {
1349 let labels: &[&str] = &["job", "instance", "host.id"];
1350 assert!(
1351 sorted_declarations(&prom_table_info(
1352 "greptime_otel_resource_info",
1353 labels,
1354 PROM_STAMPS
1355 ))
1356 .is_empty()
1357 );
1358 let mut stamps = OTEL_STAMPS.to_vec();
1359 stamps.push((PHYSICAL_TABLE_METADATA_KEY, "true"));
1360 assert!(
1361 sorted_declarations(&prom_table_info(
1362 "greptime_otel_resource_info",
1363 labels,
1364 &stamps
1365 ))
1366 .is_empty()
1367 );
1368 assert!(
1369 conventions()
1370 .unwrap()
1371 .otel_info_metrics
1372 .contains_key(servers::otlp::metrics::OTEL_RESOURCE_INFO_TABLE_NAME)
1373 );
1374
1375 let wrong_type = [
1376 (SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC),
1377 (SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY),
1378 (SEMANTIC_METRIC_TYPE, servers::semantic::METRIC_TYPE_GAUGE),
1379 ];
1380 assert!(
1381 sorted_declarations(&prom_table_info(
1382 "greptime_otel_resource_info",
1383 labels,
1384 &wrong_type
1385 ))
1386 .is_empty()
1387 );
1388 }
1389
1390 #[test]
1391 fn target_info_descriptive_rest_covers_remaining_tags() {
1392 let marker = OTLP_AGGREGATION_TEMPORALITY_LABEL;
1393 let info = prom_table_info(
1394 "target_info",
1395 &[
1396 "job",
1397 "instance",
1398 "k8s_cluster_name",
1399 "service_version",
1400 marker,
1401 ],
1402 PROM_STAMPS,
1403 );
1404 let declarations = sorted_declarations(&info);
1405 assert_eq!(declarations.len(), 2);
1406 assert_eq!(declarations[0].entity_type, "service");
1407 assert_eq!(declarations[0].id_columns, vec!["job"]);
1408 assert!(declarations[0].descriptive_columns.is_empty());
1409 assert_eq!(declarations[1].entity_type, "service.instance");
1412 assert_eq!(declarations[1].id_columns, vec!["job", "instance"]);
1413 assert_eq!(
1414 declarations[1].descriptive_columns,
1415 vec!["k8s_cluster_name", "service_version"]
1416 );
1417 }
1418}