table/requests/semantic.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//! Table semantic layer vocabulary.
16//!
17//! A thin layer of semantic metadata attached to a table via `table_options`, so
18//! machine consumers (LLM agents, alert/dashboard builders, MCP servers, ETL) can
19//! align a table with the observability concept it stands for without guessing
20//! from column names. See `docs/rfcs/2026-05-28-table-semantic-layer.md`.
21//!
22//! The vocabulary is intentionally small: a key earns its place only when it
23//! records something a consumer cannot cheaply and reliably recover from the
24//! schema/data itself. Keys whose value is already in the metric name by
25//! convention, is a constant, or duplicates an existing column are deliberately
26//! omitted rather than stamped for completeness.
27//!
28//! All public keys share the [`SEMANTIC_PREFIX`] namespace and are string-valued.
29//! [`is_semantic_option_key`] gates them through
30//! [`crate::requests::validate_table_option`], so they are accepted both on the
31//! ingestion auto-create path and on explicit `CREATE TABLE ... WITH (...)` DDL.
32
33use datatypes::prelude::ConcreteDataType;
34
35/// Reserved prefix for every public semantic table-option key.
36pub const SEMANTIC_PREFIX: &str = "greptime.semantic.";
37
38/// Internal `QueryContext` extension key carrying the per-table semantic index
39/// (a `{table_name -> {semantic_key: value}}` JSON blob) from the ingestion
40/// encode path to the auto-create site. Deliberately OUTSIDE [`SEMANTIC_PREFIX`]
41/// so it is not a valid table option and never leaks into a table's options.
42pub const SEMANTIC_PER_TABLE_INDEX_KEY: &str = "greptime.internal.semantic.per_table_index";
43
44// ---- Common keys (all signals) ----
45
46/// Signal kind: one of [`SIGNAL_TYPE_TRACE`] / [`SIGNAL_TYPE_LOG`] /
47/// [`SIGNAL_TYPE_METRIC`] / [`SIGNAL_TYPE_EVENT`].
48pub const SEMANTIC_SIGNAL_TYPE: &str = "greptime.semantic.signal_type";
49/// Ingestion ecosystem, e.g. [`SOURCE_OPENTELEMETRY`] / [`SOURCE_PROMETHEUS`].
50pub const SEMANTIC_SOURCE: &str = "greptime.semantic.source";
51/// Source protocol version, e.g. Prometheus remote write `1.0` / `2.0`.
52pub const SEMANTIC_SOURCE_VERSION: &str = "greptime.semantic.source_version";
53/// Internal ingestion pipeline / data model, e.g. `greptime_trace_v1`. The
54/// signal-agnostic successor to the engine-specific `table_data_model` option.
55pub const SEMANTIC_PIPELINE: &str = "greptime.semantic.pipeline";
56
57// ---- Trace keys ----
58
59/// Semantic-conventions version the rows conform to (e.g. the OTel schema URL),
60/// or [`SEMANTIC_VALUE_UNKNOWN`] / [`SEMANTIC_VALUE_MIXED`] when not single-valued.
61pub const SEMANTIC_TRACE_CONVENTIONS: &str = "greptime.semantic.trace.conventions";
62
63// ---- Metric keys ----
64
65/// Instrument kind: `counter` / `gauge` / `histogram` / `summary` /
66/// `updown_counter` / `gauge_histogram` / `info` / `stateset`.
67pub const SEMANTIC_METRIC_TYPE: &str = "greptime.semantic.metric.type";
68/// UCUM unit, e.g. `s`, `By`, `{request}`. Discarded by the row encoders, so it
69/// is unrecoverable once ingested.
70pub const SEMANTIC_METRIC_UNIT: &str = "greptime.semantic.metric.unit";
71/// `cumulative` / `delta` (OTel only). Invisible in the metric name, so it is
72/// unrecoverable from the table alone.
73pub const SEMANTIC_METRIC_TEMPORALITY: &str = "greptime.semantic.metric.temporality";
74/// [`METADATA_QUALITY_DECLARED`] when the protocol stated the type, or
75/// [`METADATA_QUALITY_INFERRED`] when guessed from a name suffix.
76pub const SEMANTIC_METRIC_METADATA_QUALITY: &str = "greptime.semantic.metric.metadata_quality";
77/// Pre-translation OTel name when the table name was Prometheus-ised; the key a
78/// consumer uses to look the metric up in the OTel semantic conventions.
79pub const SEMANTIC_METRIC_ORIGINAL_NAME: &str = "greptime.semantic.metric.original_name";
80
81// ---- Entity keys (open sub-namespace) ----
82
83/// Reserved prefix for the entity-identity sub-namespace:
84/// `greptime.semantic.entity.<type>.{id|descriptive|scope}`. Unlike the rest of
85/// the vocabulary (a closed whitelist), entity types are open-ended (`service`,
86/// `host`, `k8s.pod`, `process`, `agent`, custom, ...), so keys here are validated
87/// by prefix + shape rather than membership. See
88/// `docs/rfcs/2026-06-25-entity-relationships-and-graph-query.md`.
89pub const SEMANTIC_ENTITY_PREFIX: &str = "greptime.semantic.entity.";
90
91/// The well-known entity-identity key auto-stamped on OTLP trace tables; its value
92/// is the `service_name` tag column, declaring the logical `service` entity.
93pub const SEMANTIC_ENTITY_SERVICE_ID: &str = "greptime.semantic.entity.service.id";
94
95/// The role a set of columns plays for an entity: `id` (identifying
96/// attributes), `descriptive`, or `scope`. Columns may be tags or fields; DDL
97/// validation only requires that they exist and render as stable strings
98/// ([`has_stable_string_form`]).
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum EntityRole {
101 /// Identifying columns. Their **order is part of the identity**: the
102 /// entity id is their values joined in the declared order, so two tables
103 /// naming the same entity must list them the same way (broad to narrow)
104 /// or they name two entities.
105 Id,
106 Descriptive,
107 Scope,
108}
109
110impl EntityRole {
111 fn parse(role: &str) -> Option<Self> {
112 match role {
113 "id" => Some(EntityRole::Id),
114 "descriptive" => Some(EntityRole::Descriptive),
115 "scope" => Some(EntityRole::Scope),
116 _ => None,
117 }
118 }
119}
120
121// ---- Value constants ----
122
123pub const SIGNAL_TYPE_TRACE: &str = "trace";
124pub const SIGNAL_TYPE_LOG: &str = "log";
125pub const SIGNAL_TYPE_METRIC: &str = "metric";
126pub const SIGNAL_TYPE_EVENT: &str = "event";
127
128pub const SOURCE_OPENTELEMETRY: &str = "opentelemetry";
129pub const SOURCE_PROMETHEUS: &str = "prometheus";
130pub const SOURCE_INFLUXDB: &str = "influxdb";
131pub const SOURCE_OPENTSDB: &str = "opentsdb";
132pub const SOURCE_LOKI: &str = "loki";
133pub const SOURCE_ELASTICSEARCH: &str = "elasticsearch";
134
135pub const METADATA_QUALITY_DECLARED: &str = "declared";
136pub const METADATA_QUALITY_INFERRED: &str = "inferred";
137
138/// Sentinel for a key that cannot be determined at stamp time.
139pub const SEMANTIC_VALUE_UNKNOWN: &str = "unknown";
140/// Sentinel for a single-valued key that saw conflicting sources.
141pub const SEMANTIC_VALUE_MIXED: &str = "mixed";
142
143/// Every recognised public semantic table-option key. The set is a closed
144/// whitelist: keys under [`SEMANTIC_PREFIX`] that are not listed here are rejected,
145/// so an unknown key like `greptime.semantic.unknown_key` does not silently land
146/// in a table's options. Adding a key to the vocabulary means adding it here.
147pub const SEMANTIC_OPTION_KEYS: &[&str] = &[
148 SEMANTIC_SIGNAL_TYPE,
149 SEMANTIC_SOURCE,
150 SEMANTIC_SOURCE_VERSION,
151 SEMANTIC_PIPELINE,
152 SEMANTIC_TRACE_CONVENTIONS,
153 SEMANTIC_METRIC_TYPE,
154 SEMANTIC_METRIC_UNIT,
155 SEMANTIC_METRIC_TEMPORALITY,
156 SEMANTIC_METRIC_METADATA_QUALITY,
157 SEMANTIC_METRIC_ORIGINAL_NAME,
158];
159
160/// Returns true if `ty` is a syntactically valid entity type, e.g. `service`,
161/// `host`, `k8s.pod`, `service.instance`. An entity type is one or more
162/// dot-separated segments, each a non-empty `[a-z0-9_]+` token. The dotted form
163/// carries the two-entity-layer convention (`service` vs `service.instance`).
164fn is_valid_entity_type(ty: &str) -> bool {
165 !ty.is_empty()
166 && ty.split('.').all(|seg| {
167 !seg.is_empty()
168 && seg
169 .bytes()
170 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
171 })
172}
173
174/// Parses a well-formed entity-identity option key of the shape
175/// `greptime.semantic.entity.<type>.{id|descriptive|scope}` into
176/// `(entity_type, role)`. The `<type>` may itself contain dots; the role is the
177/// final dot-separated segment. This is the single parser of the key format —
178/// DDL validation and the read-time derivation both go through it.
179pub fn parse_entity_option_key(key: &str) -> Option<(&str, EntityRole)> {
180 let rest = key.strip_prefix(SEMANTIC_ENTITY_PREFIX)?;
181 let (ty, role) = rest.rsplit_once('.')?;
182 if !is_valid_entity_type(ty) {
183 return None;
184 }
185 Some((ty, EntityRole::parse(role)?))
186}
187
188/// Returns true if `key` is a well-formed entity-identity option key.
189pub fn is_entity_option_key(key: &str) -> bool {
190 parse_entity_option_key(key).is_some()
191}
192
193/// Returns true if a column of `data_type` renders as a stable string — the
194/// requirement for entity id/descriptive/scope columns. The read-time
195/// derivation casts them to strings, so a type without a stable string form
196/// would fail only when the graph is scanned; DDL validation rejects it up
197/// front instead.
198pub fn has_stable_string_form(data_type: &ConcreteDataType) -> bool {
199 !matches!(
200 data_type,
201 ConcreteDataType::Binary(_)
202 | ConcreteDataType::Json(_)
203 | ConcreteDataType::Vector(_)
204 | ConcreteDataType::List(_)
205 | ConcreteDataType::Struct(_)
206 | ConcreteDataType::Dictionary(_)
207 | ConcreteDataType::Null(_)
208 )
209}
210
211/// Tokenizes an entity option's comma-separated column list (trimmed, empty
212/// tokens dropped). [`validate_semantic_option`] rejects empty tokens at DDL
213/// time, so readers only ever drop what validation already refused.
214pub fn parse_entity_columns(value: &str) -> Vec<String> {
215 value
216 .split(',')
217 .map(|c| c.trim().to_string())
218 .filter(|c| !c.is_empty())
219 .collect()
220}
221
222/// Returns true if `key` is a recognised semantic table-option key.
223///
224/// Two acceptance rules: membership in the closed [`SEMANTIC_OPTION_KEYS`]
225/// whitelist, OR the open entity sub-namespace ([`is_entity_option_key`], validated
226/// by prefix + shape). Everything else under [`SEMANTIC_PREFIX`] is rejected, and
227/// the internal [`SEMANTIC_PER_TABLE_INDEX_KEY`] (outside the prefix) never matches.
228pub fn is_semantic_option_key(key: &str) -> bool {
229 SEMANTIC_OPTION_KEYS.contains(&key) || is_entity_option_key(key)
230}
231
232/// Validates a `greptime.semantic.*` option's `value` against its allowed domain.
233///
234/// Open-value keys (unit, original_name, pipeline, conventions) accept any
235/// non-empty string. Closed-domain keys accept a fixed set, plus the `unknown`
236/// sentinel, plus `mixed` for the keys where one long-lived table can
237/// legitimately see multiple values. Entity keys ([`is_entity_option_key`]) take a
238/// comma-separated column-name list (each token non-empty); column existence and
239/// the stable-string-form rule for entity columns are enforced later against
240/// the table schema at DDL time, not here. Keys that are neither whitelisted nor a well-formed entity key
241/// are rejected.
242pub fn validate_semantic_option(key: &str, value: &str) -> bool {
243 if is_entity_option_key(key) {
244 return !value.is_empty() && value.split(',').all(|col| !col.trim().is_empty());
245 }
246 match key {
247 SEMANTIC_PIPELINE
248 | SEMANTIC_SOURCE_VERSION
249 | SEMANTIC_METRIC_UNIT
250 | SEMANTIC_METRIC_ORIGINAL_NAME
251 | SEMANTIC_TRACE_CONVENTIONS => !value.is_empty(),
252
253 SEMANTIC_SIGNAL_TYPE => matches!(value, "trace" | "log" | "metric" | "event" | "unknown"),
254 SEMANTIC_SOURCE => matches!(
255 value,
256 "opentelemetry"
257 | "prometheus"
258 | "influxdb"
259 | "opentsdb"
260 | "elasticsearch"
261 | "loki"
262 | "custom"
263 | "mixed"
264 | "unknown"
265 ),
266 SEMANTIC_METRIC_TYPE => matches!(
267 value,
268 "counter"
269 | "gauge"
270 | "histogram"
271 | "summary"
272 | "updown_counter"
273 | "gauge_histogram"
274 | "info"
275 | "stateset"
276 | "mixed"
277 | "unknown"
278 ),
279 SEMANTIC_METRIC_TEMPORALITY => {
280 matches!(value, "cumulative" | "delta" | "mixed" | "unknown")
281 }
282 SEMANTIC_METRIC_METADATA_QUALITY => matches!(value, "declared" | "inferred" | "unknown"),
283
284 _ => false,
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 #[test]
293 fn test_is_semantic_option_key() {
294 assert!(is_semantic_option_key(SEMANTIC_SIGNAL_TYPE));
295 assert!(is_semantic_option_key(SEMANTIC_METRIC_TYPE));
296 assert!(is_semantic_option_key(SEMANTIC_PIPELINE));
297
298 // Unknown keys under the prefix are not whitelisted.
299 assert!(!is_semantic_option_key("greptime.semantic.future.key"));
300 assert!(!is_semantic_option_key("greptime.semantic.unknown_key"));
301 // Keys cut from the vocabulary are no longer accepted.
302 assert!(!is_semantic_option_key(
303 "greptime.semantic.metric.monotonic"
304 ));
305 assert!(!is_semantic_option_key(
306 "greptime.semantic.resource.attributes_dropped"
307 ));
308 // Near-misses must not match.
309 assert!(!is_semantic_option_key("greptime.semanticx"));
310 assert!(!is_semantic_option_key("semantic.signal_type"));
311 assert!(!is_semantic_option_key("table_data_model"));
312 // The internal transport key must never be treated as a table option.
313 assert!(!is_semantic_option_key(SEMANTIC_PER_TABLE_INDEX_KEY));
314 }
315
316 #[test]
317 fn test_validate_semantic_option() {
318 // Enum keys reject out-of-domain values.
319 assert!(validate_semantic_option(SEMANTIC_SIGNAL_TYPE, "metric"));
320 assert!(!validate_semantic_option(SEMANTIC_SIGNAL_TYPE, "spans"));
321 assert!(validate_semantic_option(SEMANTIC_METRIC_TYPE, "counter"));
322 assert!(validate_semantic_option(SEMANTIC_METRIC_TYPE, "mixed"));
323 assert!(!validate_semantic_option(SEMANTIC_METRIC_TYPE, "bogus"));
324
325 // Sentinels and open values.
326 assert!(validate_semantic_option(
327 SEMANTIC_METRIC_TEMPORALITY,
328 "unknown"
329 ));
330 assert!(validate_semantic_option(SEMANTIC_METRIC_UNIT, "By"));
331 assert!(!validate_semantic_option(SEMANTIC_METRIC_UNIT, ""));
332 assert!(validate_semantic_option(
333 SEMANTIC_PIPELINE,
334 "greptime_trace_v1"
335 ));
336
337 // A cut key validates to false regardless of value.
338 assert!(!validate_semantic_option(
339 "greptime.semantic.metric.monotonic",
340 "true"
341 ));
342 // Unknown key is rejected regardless of value.
343 assert!(!validate_semantic_option(
344 "greptime.semantic.future.key",
345 "x"
346 ));
347
348 // Drift guard: every value stamped by the ingestion path must validate.
349 assert!(validate_semantic_option(
350 SEMANTIC_SIGNAL_TYPE,
351 SIGNAL_TYPE_TRACE
352 ));
353 assert!(validate_semantic_option(
354 SEMANTIC_SIGNAL_TYPE,
355 SIGNAL_TYPE_METRIC
356 ));
357 assert!(validate_semantic_option(
358 SEMANTIC_SIGNAL_TYPE,
359 SIGNAL_TYPE_LOG
360 ));
361 assert!(validate_semantic_option(
362 SEMANTIC_SOURCE,
363 SOURCE_OPENTELEMETRY
364 ));
365 assert!(validate_semantic_option(SEMANTIC_SOURCE, SOURCE_PROMETHEUS));
366 assert!(validate_semantic_option(SEMANTIC_SOURCE_VERSION, "2.0"));
367 assert!(validate_semantic_option(
368 SEMANTIC_METRIC_METADATA_QUALITY,
369 METADATA_QUALITY_INFERRED
370 ));
371 assert!(validate_semantic_option(
372 SEMANTIC_METRIC_METADATA_QUALITY,
373 METADATA_QUALITY_DECLARED
374 ));
375 assert!(validate_semantic_option(
376 SEMANTIC_TRACE_CONVENTIONS,
377 SEMANTIC_VALUE_UNKNOWN
378 ));
379 // An empty value never validates, for any whitelisted key.
380 for key in SEMANTIC_OPTION_KEYS {
381 assert!(
382 !validate_semantic_option(key, ""),
383 "empty value should never validate for {key}"
384 );
385 }
386 }
387
388 #[test]
389 fn test_entity_option_key() {
390 // Well-formed entity keys are accepted by the open sub-namespace, and are
391 // therefore recognised as semantic option keys.
392 for key in [
393 "greptime.semantic.entity.service.id",
394 "greptime.semantic.entity.k8s.pod.id",
395 "greptime.semantic.entity.service.instance.descriptive",
396 "greptime.semantic.entity.host.scope",
397 "greptime.semantic.entity.agent.id",
398 ] {
399 assert!(is_entity_option_key(key), "should accept {key}");
400 assert!(is_semantic_option_key(key), "should recognise {key}");
401 }
402
403 // Malformed: empty type segment, bogus role, missing role, bare prefix,
404 // invalid (uppercase) charset in the type.
405 for key in [
406 "greptime.semantic.entity..id",
407 "greptime.semantic.entity.service.bogusrole",
408 "greptime.semantic.entity.service",
409 "greptime.semantic.entity.",
410 "greptime.semantic.entity.Service.id",
411 ] {
412 assert!(!is_entity_option_key(key), "should reject {key}");
413 assert!(!is_semantic_option_key(key), "should not recognise {key}");
414 }
415
416 // A non-entity semantic key is not an entity key.
417 assert!(!is_entity_option_key(SEMANTIC_SIGNAL_TYPE));
418
419 // Drift guard: the auto-stamped constant is a well-formed entity key.
420 assert!(is_entity_option_key(SEMANTIC_ENTITY_SERVICE_ID));
421 assert!(is_semantic_option_key(SEMANTIC_ENTITY_SERVICE_ID));
422 }
423
424 #[test]
425 fn test_validate_entity_option() {
426 // Single- and composite-id column lists validate.
427 assert!(validate_semantic_option(
428 "greptime.semantic.entity.service.id",
429 "service_name"
430 ));
431 assert!(validate_semantic_option(
432 "greptime.semantic.entity.process.id",
433 "pid,start_time"
434 ));
435 // Empty value and blank/empty tokens do not.
436 assert!(!validate_semantic_option(
437 "greptime.semantic.entity.service.id",
438 ""
439 ));
440 assert!(!validate_semantic_option(
441 "greptime.semantic.entity.process.id",
442 "pid,"
443 ));
444 // A malformed entity key validates to false regardless of value.
445 assert!(!validate_semantic_option(
446 "greptime.semantic.entity.service.bogusrole",
447 "service_name"
448 ));
449 }
450}