Skip to main content

servers/otlp/
logs.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
15use std::collections::BTreeMap;
16
17use ahash::{HashMap, HashMapExt};
18use api::helper::{ColumnDataTypeWrapper, timestamp_unit};
19use api::v1::column_data_type_extension::TypeExt;
20use api::v1::column_def::{options_from_column_schema, options_from_skipping};
21use api::v1::value::ValueData;
22use api::v1::{
23    ColumnDataType, ColumnDataTypeExtension, ColumnOptions, ColumnSchema, JsonTypeExtension, Row,
24    RowInsertRequest, Rows, SemanticType, Value as GreptimeValue,
25};
26use bytes::Bytes;
27use common_catalog::consts::SERVICE_NAME_COLUMN;
28use common_telemetry::warn;
29use common_time::Timestamp;
30use common_time::timestamp::TimeUnit;
31use datatypes::schema::SkippingIndexOptions;
32use jsonb::{Number as JsonbNumber, Value as JsonbValue};
33use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
34use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value};
35use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
36use pipeline::{
37    ContextReq, GreptimePipelineParams, PipelineContext, PipelineWay, SchemaInfo, SelectInfo,
38};
39use session::context::QueryContextRef;
40use snafu::ensure;
41use table::requests::TABLE_DATA_MODEL_LOG_V1;
42use vrl::prelude::NotNan;
43use vrl::value::{KeyString, Value as VrlValue};
44
45use crate::error::{
46    Error, IncompatibleSchemaSnafu, InvalidParameterSnafu, NotSupportedSnafu, Result,
47    UnsupportedJsonDataTypeForTagSnafu,
48};
49use crate::http::event::PipelineIngestRequest;
50use crate::otlp::coerce::{coerce_value_data, is_supported_signed_to_unsigned_coercion};
51use crate::otlp::trace::attributes::OtlpAnyValue;
52use crate::otlp::utils::{bytes_to_hex_string, key_value_to_jsonb, resource_service_name};
53use crate::pipeline::run_pipeline;
54use crate::query_handler::PipelineHandlerRef;
55
56pub const LOG_TABLE_NAME: &str = "opentelemetry_logs";
57const EVENT_NAME_COLUMN: &str = "event_name";
58const OBSERVED_TIMESTAMP_COLUMN: &str = "observed_timestamp";
59
60/// Convert OpenTelemetry logs to GreptimeDB insert requests
61///
62/// See
63/// <https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/logs/v1/logs.proto>
64/// for data structure of OTLP logs.
65///
66/// Returns `InsertRequests` and total number of rows to ingest
67pub async fn to_grpc_insert_requests(
68    request: ExportLogsServiceRequest,
69    pipeline: PipelineWay,
70    pipeline_params: GreptimePipelineParams,
71    table_name: String,
72    query_ctx: &QueryContextRef,
73    pipeline_handler: PipelineHandlerRef,
74) -> Result<ContextReq> {
75    match pipeline {
76        PipelineWay::OtlpLogDirect(select_info) => {
77            let table = pipeline_handler
78                .get_table(&table_name, query_ctx)
79                .await
80                .map_err(Error::from)?;
81            // New tables get the v1 schema. Existing tables without the v1 marker keep
82            // the legacy schema, so upgrading never alters their columns or keys.
83            let v1_schema = table.as_deref().is_none_or(|table| {
84                table.table_info().meta.options.data_model() == Some(TABLE_DATA_MODEL_LOG_V1)
85            });
86            let existing_schema = table
87                .as_deref()
88                .map(ExistingLogSchema::try_from_table)
89                .transpose()?;
90            let rows = parse_export_logs_service_request_to_rows(
91                request,
92                select_info,
93                v1_schema,
94                existing_schema.as_ref(),
95                &table_name,
96            )?;
97            let insert_request = RowInsertRequest {
98                rows: Some(rows),
99                table_name,
100            };
101
102            Ok(ContextReq::default_opt_with_reqs(vec![insert_request]))
103        }
104        PipelineWay::Pipeline(pipeline_def) => {
105            let array = parse_export_logs_service_request(request);
106
107            let pipeline_ctx =
108                PipelineContext::new(&pipeline_def, &pipeline_params, query_ctx.channel());
109            run_pipeline(
110                &pipeline_handler,
111                &pipeline_ctx,
112                PipelineIngestRequest {
113                    table: table_name,
114                    values: array,
115                },
116                query_ctx,
117                true,
118            )
119            .await
120        }
121        _ => NotSupportedSnafu {
122            feat: "Unsupported pipeline for logs",
123        }
124        .fail(),
125    }
126}
127
128fn scope_to_pipeline_value(scope: Option<InstrumentationScope>) -> (VrlValue, VrlValue, VrlValue) {
129    scope
130        .map(|x| {
131            (
132                VrlValue::Object(key_value_to_map(x.attributes)),
133                VrlValue::Bytes(x.version.into()),
134                VrlValue::Bytes(x.name.into()),
135            )
136        })
137        .unwrap_or((VrlValue::Null, VrlValue::Null, VrlValue::Null))
138}
139
140fn scope_to_jsonb(
141    scope: Option<InstrumentationScope>,
142) -> (JsonbValue<'static>, Option<String>, Option<String>) {
143    scope
144        .map(|x| {
145            (
146                key_value_to_jsonb(x.attributes),
147                Some(x.version),
148                Some(x.name),
149            )
150        })
151        .unwrap_or((JsonbValue::Null, None, None))
152}
153
154fn log_to_pipeline_value(
155    log: LogRecord,
156    resource_schema_url: VrlValue,
157    resource_attr: VrlValue,
158    scope_schema_url: VrlValue,
159    scope_name: VrlValue,
160    scope_version: VrlValue,
161    scope_attrs: VrlValue,
162) -> VrlValue {
163    let log_attrs = VrlValue::Object(key_value_to_map(log.attributes));
164    let mut map = BTreeMap::new();
165    map.insert(
166        "Timestamp".into(),
167        VrlValue::Integer(log.time_unix_nano as i64),
168    );
169    map.insert(
170        "ObservedTimestamp".into(),
171        VrlValue::Integer(log.observed_time_unix_nano as i64),
172    );
173
174    // need to be convert to string
175    map.insert(
176        "TraceId".into(),
177        VrlValue::Bytes(bytes_to_hex_string(&log.trace_id).into()),
178    );
179    map.insert(
180        "SpanId".into(),
181        VrlValue::Bytes(bytes_to_hex_string(&log.span_id).into()),
182    );
183    map.insert("TraceFlags".into(), VrlValue::Integer(log.flags as i64));
184    map.insert(
185        "SeverityText".into(),
186        VrlValue::Bytes(log.severity_text.into()),
187    );
188    map.insert(
189        "SeverityNumber".into(),
190        VrlValue::Integer(log.severity_number as i64),
191    );
192    // need to be convert to string
193    map.insert(
194        "Body".into(),
195        log.body
196            .as_ref()
197            .map(|x| VrlValue::Bytes(log_body_to_string(x).into()))
198            .unwrap_or(VrlValue::Null),
199    );
200    map.insert("ResourceSchemaUrl".into(), resource_schema_url);
201
202    map.insert("ResourceAttributes".into(), resource_attr);
203    map.insert("ScopeSchemaUrl".into(), scope_schema_url);
204    map.insert("ScopeName".into(), scope_name);
205    map.insert("ScopeVersion".into(), scope_version);
206    map.insert("ScopeAttributes".into(), scope_attrs);
207    map.insert("LogAttributes".into(), log_attrs);
208    VrlValue::Object(map)
209}
210
211/// Built-in columns of a direct OTLP log row, in row order.
212///
213/// The v1 schema puts `service_name` before `scope_name` because auto-create
214/// orders the primary key by column order.
215fn build_otlp_logs_identity_schema(v1_schema: bool) -> Result<Vec<ColumnSchema>> {
216    let trace_id_options = if v1_schema {
217        options_from_skipping(&SkippingIndexOptions::default())?
218    } else {
219        None
220    };
221    let mut columns = vec![
222        (
223            "timestamp",
224            ColumnDataType::TimestampNanosecond,
225            SemanticType::Timestamp,
226            None,
227            None,
228        ),
229        (
230            "trace_id",
231            ColumnDataType::String,
232            SemanticType::Field,
233            None,
234            trace_id_options,
235        ),
236        (
237            "span_id",
238            ColumnDataType::String,
239            SemanticType::Field,
240            None,
241            None,
242        ),
243        (
244            "severity_text",
245            ColumnDataType::String,
246            SemanticType::Field,
247            None,
248            None,
249        ),
250        (
251            "severity_number",
252            ColumnDataType::Int32,
253            SemanticType::Field,
254            None,
255            None,
256        ),
257        (
258            "body",
259            ColumnDataType::String,
260            SemanticType::Field,
261            None,
262            Some(ColumnOptions {
263                options: std::collections::HashMap::from([(
264                    "fulltext".to_string(),
265                    r#"{"enable":true}"#.to_string(),
266                )]),
267            }),
268        ),
269        (
270            "log_attributes",
271            ColumnDataType::Binary,
272            SemanticType::Field,
273            Some(ColumnDataTypeExtension {
274                type_ext: Some(TypeExt::JsonType(JsonTypeExtension::JsonBinary.into())),
275            }),
276            None,
277        ),
278        (
279            "trace_flags",
280            ColumnDataType::Int32,
281            SemanticType::Field,
282            None,
283            None,
284        ),
285    ];
286    if v1_schema {
287        columns.push((
288            SERVICE_NAME_COLUMN,
289            ColumnDataType::String,
290            SemanticType::Tag,
291            None,
292            None,
293        ));
294    }
295    columns.extend([
296        (
297            "scope_name",
298            ColumnDataType::String,
299            SemanticType::Tag,
300            None,
301            None,
302        ),
303        (
304            "scope_version",
305            ColumnDataType::String,
306            SemanticType::Field,
307            None,
308            None,
309        ),
310        (
311            "scope_attributes",
312            ColumnDataType::Binary,
313            SemanticType::Field,
314            Some(ColumnDataTypeExtension {
315                type_ext: Some(TypeExt::JsonType(JsonTypeExtension::JsonBinary.into())),
316            }),
317            None,
318        ),
319        (
320            "scope_schema_url",
321            ColumnDataType::String,
322            SemanticType::Field,
323            None,
324            None,
325        ),
326        (
327            "resource_attributes",
328            ColumnDataType::Binary,
329            SemanticType::Field,
330            Some(ColumnDataTypeExtension {
331                type_ext: Some(TypeExt::JsonType(JsonTypeExtension::JsonBinary.into())),
332            }),
333            None,
334        ),
335        (
336            "resource_schema_url",
337            ColumnDataType::String,
338            SemanticType::Field,
339            None,
340            None,
341        ),
342    ]);
343    if v1_schema {
344        columns.extend([
345            (
346                EVENT_NAME_COLUMN,
347                ColumnDataType::String,
348                SemanticType::Field,
349                None,
350                None,
351            ),
352            (
353                OBSERVED_TIMESTAMP_COLUMN,
354                ColumnDataType::TimestampNanosecond,
355                SemanticType::Field,
356                None,
357                None,
358            ),
359        ]);
360    }
361
362    Ok(columns
363        .into_iter()
364        .map(
365            |(field_name, column_type, semantic_type, datatype_extension, options)| ColumnSchema {
366                column_name: field_name.to_string(),
367                datatype: column_type as i32,
368                semantic_type: semantic_type as i32,
369                datatype_extension,
370                options,
371            },
372        )
373        .collect())
374}
375
376#[derive(Clone)]
377struct ExistingLogColumn {
378    schema: ColumnSchema,
379    datatype: ColumnDataType,
380}
381
382impl ExistingLogColumn {
383    fn schema_for_request_type(&self, request_type: ColumnDataType) -> ColumnSchema {
384        let mut schema = self.schema.clone();
385        if request_type == ColumnDataType::Binary && self.is_json_binary() {
386            schema.datatype = ColumnDataType::Binary as i32;
387        }
388        schema
389    }
390
391    fn is_json_binary(&self) -> bool {
392        self.datatype == ColumnDataType::Json
393            && matches!(
394                self.schema
395                    .datatype_extension
396                    .as_ref()
397                    .and_then(|datatype_extension| datatype_extension.type_ext.as_ref()),
398                Some(TypeExt::JsonType(json_type))
399                     if *json_type == JsonTypeExtension::JsonBinary as i32
400            )
401    }
402}
403
404#[derive(Default)]
405struct ExistingLogSchema {
406    columns: HashMap<String, ExistingLogColumn>,
407}
408
409impl ExistingLogSchema {
410    fn try_from_table(table: &table::Table) -> Result<Self> {
411        let table_info = table.table_info();
412        Self::try_from_schema_parts(
413            table.schema_ref().column_schemas(),
414            &table_info.meta.primary_key_indices,
415        )
416    }
417
418    fn try_from_schema_parts(
419        column_schemas: &[datatypes::schema::ColumnSchema],
420        primary_key_indices: &[usize],
421    ) -> Result<Self> {
422        let mut columns = HashMap::with_capacity(column_schemas.len());
423
424        for (index, column_schema) in column_schemas.iter().enumerate() {
425            let (datatype, datatype_extension) =
426                ColumnDataTypeWrapper::try_from(column_schema.data_type.clone())
427                    .map(|wrapper| wrapper.into_parts())
428                    .map_err(Error::from)?;
429            let semantic_type = if column_schema.is_time_index() {
430                SemanticType::Timestamp
431            } else if primary_key_indices.contains(&index) {
432                SemanticType::Tag
433            } else {
434                SemanticType::Field
435            };
436            let schema = ColumnSchema {
437                column_name: column_schema.name.clone(),
438                datatype: datatype as i32,
439                semantic_type: semantic_type as i32,
440                datatype_extension,
441                options: options_from_column_schema(column_schema),
442            };
443            columns.insert(
444                schema.column_name.clone(),
445                ExistingLogColumn { schema, datatype },
446            );
447        }
448
449        Ok(Self { columns })
450    }
451
452    fn get(&self, column_name: &str) -> Option<&ExistingLogColumn> {
453        self.columns.get(column_name)
454    }
455}
456
457fn build_otlp_build_in_row(
458    log: LogRecord,
459    log_attr: &JsonbValue,
460    service_name: Option<String>,
461    parse_ctx: &ParseContext,
462) -> Row {
463    let ts = if log.time_unix_nano != 0 {
464        log.time_unix_nano
465    } else {
466        log.observed_time_unix_nano
467    };
468
469    let mut row = vec![
470        GreptimeValue {
471            value_data: Some(ValueData::TimestampNanosecondValue(ts as i64)),
472        },
473        GreptimeValue {
474            value_data: Some(ValueData::StringValue(bytes_to_hex_string(&log.trace_id))),
475        },
476        GreptimeValue {
477            value_data: Some(ValueData::StringValue(bytes_to_hex_string(&log.span_id))),
478        },
479        GreptimeValue {
480            value_data: Some(ValueData::StringValue(log.severity_text)),
481        },
482        GreptimeValue {
483            value_data: Some(ValueData::I32Value(log.severity_number)),
484        },
485        GreptimeValue {
486            value_data: log
487                .body
488                .as_ref()
489                .map(|x| ValueData::StringValue(log_body_to_string(x))),
490        },
491        GreptimeValue {
492            value_data: Some(ValueData::BinaryValue(log_attr.to_vec())),
493        },
494        GreptimeValue {
495            value_data: Some(ValueData::I32Value(log.flags as i32)),
496        },
497    ];
498    if parse_ctx.v1_schema {
499        row.push(GreptimeValue {
500            value_data: service_name.map(ValueData::StringValue),
501        });
502    }
503    row.extend([
504        GreptimeValue {
505            value_data: parse_ctx.scope_name.clone().map(ValueData::StringValue),
506        },
507        GreptimeValue {
508            value_data: parse_ctx.scope_version.clone().map(ValueData::StringValue),
509        },
510        GreptimeValue {
511            value_data: Some(ValueData::BinaryValue(parse_ctx.scope_attrs.to_vec())),
512        },
513        GreptimeValue {
514            value_data: Some(ValueData::StringValue(parse_ctx.scope_url.clone())),
515        },
516        GreptimeValue {
517            value_data: Some(ValueData::BinaryValue(parse_ctx.resource_attr.to_vec())),
518        },
519        GreptimeValue {
520            value_data: Some(ValueData::StringValue(parse_ctx.resource_url.clone())),
521        },
522    ]);
523    if parse_ctx.v1_schema {
524        row.extend([
525            GreptimeValue {
526                value_data: (!log.event_name.is_empty())
527                    .then_some(ValueData::StringValue(log.event_name)),
528            },
529            GreptimeValue {
530                value_data: (log.observed_time_unix_nano != 0).then_some(
531                    ValueData::TimestampNanosecondValue(log.observed_time_unix_nano as i64),
532                ),
533            },
534        ]);
535    }
536    Row { values: row }
537}
538
539/// Reads a `service_name` value the request asked to extract from `attrs`, with
540/// the same key matching and type rules as other extract keys.
541fn extracted_service_name(attrs: &JsonbValue) -> Result<Option<String>> {
542    attrs
543        .get_by_name_ignore_case(SERVICE_NAME_COLUMN)
544        .cloned()
545        .map(|value| scalar_attr_to_string(SERVICE_NAME_COLUMN, value))
546        .transpose()
547        .map(Option::flatten)
548}
549
550fn scalar_attr_to_string(name: &str, value: JsonbValue) -> Result<Option<String>> {
551    Ok(jsonb_value_to_log_value_data(name, value, true)?
552        .and_then(|(value_data, _)| stringify_scalar_value(value_data))
553        .and_then(|value_data| match value_data {
554            ValueData::StringValue(value) => Some(value),
555            _ => None,
556        }))
557}
558
559fn extract_field_from_attr_and_combine_schema(
560    select_info: &SelectInfo,
561    select_schema: &mut SchemaInfo,
562    attrs: &jsonb::Value,
563    existing_schema: Option<&ExistingLogSchema>,
564    table_name: &str,
565) -> Result<Vec<GreptimeValue>> {
566    // note we use schema.len instead of select_keys.len
567    // because the len of the row value should always matches the len of the schema
568    let mut extracted_values = vec![GreptimeValue::default(); select_schema.schema.len()];
569
570    for key in select_info.keys.iter() {
571        let Some(value) = attrs.get_by_name_ignore_case(key).cloned() else {
572            continue;
573        };
574        let Some((schema, value)) =
575            decide_column_schema_and_convert_value(key, value, existing_schema, table_name)?
576        else {
577            continue;
578        };
579
580        if let Some(index) = select_schema.index.get(key) {
581            let column_schema = &select_schema.schema[*index];
582            let column_schema: ColumnSchema = column_schema.clone().try_into()?;
583            // datatype of the same column name should be the same
584            ensure!(
585                column_schema.datatype == schema.datatype,
586                IncompatibleSchemaSnafu {
587                    column_name: key,
588                    datatype: column_schema.datatype().as_str_name(),
589                    expected: column_schema.datatype,
590                    actual: schema.datatype,
591                }
592            );
593            extracted_values[*index] = value;
594        } else {
595            select_schema.schema.push(schema.into());
596            select_schema
597                .index
598                .insert(key.clone(), select_schema.schema.len() - 1);
599            extracted_values.push(value);
600        }
601    }
602
603    Ok(extracted_values)
604}
605
606fn decide_column_schema_and_convert_value(
607    column_name: &str,
608    value: JsonbValue,
609    existing_schema: Option<&ExistingLogSchema>,
610    table_name: &str,
611) -> Result<Option<(ColumnSchema, GreptimeValue)>> {
612    if let Some(existing_column) = existing_schema.and_then(|schema| schema.get(column_name)) {
613        return decide_existing_column_schema_and_convert_value(
614            column_name,
615            value,
616            existing_column,
617            table_name,
618        );
619    }
620
621    let Some((value_data, column_type)) = jsonb_value_to_log_value_data(column_name, value, false)?
622    else {
623        return Ok(None);
624    };
625    Ok(Some((
626        ColumnSchema {
627            column_name: column_name.to_string(),
628            datatype: column_type as i32,
629            semantic_type: SemanticType::Tag as i32,
630            datatype_extension: None,
631            options: None,
632        },
633        GreptimeValue {
634            value_data: Some(value_data),
635        },
636    )))
637}
638
639fn decide_existing_column_schema_and_convert_value(
640    column_name: &str,
641    value: JsonbValue,
642    existing_column: &ExistingLogColumn,
643    table_name: &str,
644) -> Result<Option<(ColumnSchema, GreptimeValue)>> {
645    let Some((value_data, request_type)) = jsonb_value_to_log_value_data(column_name, value, true)?
646    else {
647        return Ok(None);
648    };
649    let value_data = coerce_log_value_data(
650        Some(value_data),
651        existing_column.datatype,
652        request_type,
653        existing_column.is_json_binary(),
654        column_name,
655        table_name,
656    )?;
657
658    Ok(Some((
659        existing_column.schema.clone(),
660        GreptimeValue { value_data },
661    )))
662}
663
664/// Converts a JSON `UInt64` number into the signed value used by built-in
665/// log columns. `JsonbNumber::UInt64` only arises for values that do not fit
666/// in `i64` (see `decide_column_schema_and_convert_value`), so the conversion
667/// is fallible: wrapping to a negative number would silently corrupt the
668/// value (a counter reading back as negative), so out-of-range values are
669/// rejected instead.
670fn jsonb_uint64_to_log_value(u: u64, column_name: &str) -> Result<i64> {
671    i64::try_from(u).map_err(|_| InvalidParameterSnafu {
672        reason: format!(
673            "uint64 value {u} in column '{column_name}' exceeds the i64 range supported by built-in log columns"
674        ),
675    }
676    .build())
677}
678
679fn jsonb_value_to_log_value_data(
680    column_name: &str,
681    value: JsonbValue,
682    allow_float: bool,
683) -> Result<Option<(ValueData, ColumnDataType)>> {
684    match value {
685        JsonbValue::String(s) => Ok(Some((
686            ValueData::StringValue(s.into()),
687            ColumnDataType::String,
688        ))),
689        JsonbValue::Number(n) => match n {
690            JsonbNumber::Int64(i) => Ok(Some((ValueData::I64Value(i), ColumnDataType::Int64))),
691            JsonbNumber::Float64(f) if allow_float => {
692                Ok(Some((ValueData::F64Value(f), ColumnDataType::Float64)))
693            }
694            JsonbNumber::Float64(_) => UnsupportedJsonDataTypeForTagSnafu {
695                ty: "FLOAT".to_string(),
696                key: column_name,
697            }
698            .fail(),
699            JsonbNumber::Decimal64(_) | JsonbNumber::Decimal128(_) | JsonbNumber::Decimal256(_) => {
700                UnsupportedJsonDataTypeForTagSnafu {
701                    ty: "DECIMAL".to_string(),
702                    key: column_name,
703                }
704                .fail()
705            }
706            JsonbNumber::UInt64(u) => Ok(Some((
707                ValueData::I64Value(jsonb_uint64_to_log_value(u, column_name)?),
708                ColumnDataType::Int64,
709            ))),
710        },
711        JsonbValue::Bool(b) => Ok(Some((ValueData::BoolValue(b), ColumnDataType::Boolean))),
712        JsonbValue::Array(_) | JsonbValue::Object(_) => UnsupportedJsonDataTypeForTagSnafu {
713            ty: "Json".to_string(),
714            key: column_name,
715        }
716        .fail(),
717        JsonbValue::Binary(_) => UnsupportedJsonDataTypeForTagSnafu {
718            ty: "Binary".to_string(),
719            key: column_name,
720        }
721        .fail(),
722        JsonbValue::Date(_) => UnsupportedJsonDataTypeForTagSnafu {
723            ty: "Date".to_string(),
724            key: column_name,
725        }
726        .fail(),
727        JsonbValue::Timestamp(_) => UnsupportedJsonDataTypeForTagSnafu {
728            ty: "Timestamp".to_string(),
729            key: column_name,
730        }
731        .fail(),
732        JsonbValue::TimestampTz(_) => UnsupportedJsonDataTypeForTagSnafu {
733            ty: "TimestampTz".to_string(),
734            key: column_name,
735        }
736        .fail(),
737        JsonbValue::Interval(_) => UnsupportedJsonDataTypeForTagSnafu {
738            ty: "Interval".to_string(),
739            key: column_name,
740        }
741        .fail(),
742        JsonbValue::Null => Ok(None),
743    }
744}
745
746fn align_rows_with_existing_schema(
747    schemas: &mut [ColumnSchema],
748    rows: &mut [Row],
749    existing_schema: Option<&ExistingLogSchema>,
750    table_name: &str,
751) -> Result<()> {
752    let Some(existing_schema) = existing_schema else {
753        return Ok(());
754    };
755
756    for (column_idx, schema) in schemas.iter_mut().enumerate() {
757        let request_type = schema.datatype();
758        let Some(existing_column) = existing_schema.get(&schema.column_name) else {
759            // Existing tables own their primary key definition; request-only
760            // columns must not expand it.
761            if schema.semantic_type() == SemanticType::Tag {
762                schema.semantic_type = SemanticType::Field as i32;
763            }
764            continue;
765        };
766
767        let target_type = existing_column.datatype;
768        let target_is_json_binary = existing_column.is_json_binary();
769        for row in rows.iter_mut() {
770            let Some(value) = row.values.get_mut(column_idx) else {
771                continue;
772            };
773            value.value_data = coerce_log_value_data(
774                value.value_data.take(),
775                target_type,
776                request_type,
777                target_is_json_binary,
778                &schema.column_name,
779                table_name,
780            )?;
781        }
782        *schema = existing_column.schema_for_request_type(request_type);
783    }
784
785    Ok(())
786}
787
788fn coerce_log_value_data(
789    value_data: Option<ValueData>,
790    target_type: ColumnDataType,
791    request_type: ColumnDataType,
792    target_is_json_binary: bool,
793    column_name: &str,
794    table_name: &str,
795) -> Result<Option<ValueData>> {
796    let Some(value_data) = value_data else {
797        return Ok(None);
798    };
799
800    if request_type == target_type {
801        return Ok(Some(value_data));
802    }
803
804    if request_type == ColumnDataType::Binary && target_is_json_binary {
805        return Ok(Some(value_data));
806    }
807
808    if is_timestamp_type(request_type)
809        && let Some(target_unit) = timestamp_unit(target_type)
810    {
811        return align_timestamp_value(value_data, target_unit, column_name, table_name).map(Some);
812    }
813
814    // Only the signed -> unsigned pairs shared with traces apply to non-String
815    // targets; String -> numeric stays rejected on the log path.
816    if target_type == ColumnDataType::String {
817        if let Ok(value_data) =
818            coerce_value_data(&Some(value_data.clone()), target_type, request_type)
819        {
820            return Ok(value_data);
821        }
822        if let Some(value_data) = stringify_scalar_value(value_data) {
823            return Ok(Some(value_data));
824        }
825    } else if is_supported_signed_to_unsigned_coercion(request_type, target_type)
826        && let Ok(Some(value_data)) =
827            coerce_value_data(&Some(value_data), target_type, request_type)
828    {
829        return Ok(Some(value_data));
830    }
831
832    InvalidParameterSnafu {
833        reason: format!(
834            "failed to align log column '{}' in table '{}' from {:?} to {:?}",
835            column_name, table_name, request_type, target_type
836        ),
837    }
838    .fail()
839}
840
841fn stringify_scalar_value(value_data: ValueData) -> Option<ValueData> {
842    let value = match value_data {
843        ValueData::StringValue(value) => value,
844        ValueData::BoolValue(value) => value.to_string(),
845        ValueData::I8Value(value) => value.to_string(),
846        ValueData::I16Value(value) => value.to_string(),
847        ValueData::I32Value(value) => value.to_string(),
848        ValueData::I64Value(value) => value.to_string(),
849        ValueData::U8Value(value) => value.to_string(),
850        ValueData::U16Value(value) => value.to_string(),
851        ValueData::U32Value(value) => value.to_string(),
852        ValueData::U64Value(value) => value.to_string(),
853        ValueData::F32Value(value) => value.to_string(),
854        ValueData::F64Value(value) => value.to_string(),
855        _ => return None,
856    };
857    Some(ValueData::StringValue(value))
858}
859
860fn align_timestamp_value(
861    value_data: ValueData,
862    target_unit: TimeUnit,
863    column_name: &str,
864    table_name: &str,
865) -> Result<ValueData> {
866    let timestamp = match value_data {
867        ValueData::TimestampSecondValue(value) => Timestamp::new_second(value),
868        ValueData::TimestampMillisecondValue(value) => Timestamp::new_millisecond(value),
869        ValueData::TimestampMicrosecondValue(value) => Timestamp::new_microsecond(value),
870        ValueData::TimestampNanosecondValue(value) => Timestamp::new_nanosecond(value),
871        value_data => {
872            return InvalidParameterSnafu {
873                reason: format!(
874                    "failed to align log column '{}' in table '{}' from non-timestamp value {:?}",
875                    column_name, table_name, value_data
876                ),
877            }
878            .fail();
879        }
880    };
881    let timestamp = timestamp.convert_to(target_unit).ok_or_else(|| {
882        InvalidParameterSnafu {
883            reason: format!(
884                "failed to align log column '{}' in table '{}' to timestamp unit {}",
885                column_name, table_name, target_unit
886            ),
887        }
888        .build()
889    })?;
890
891    Ok(match target_unit {
892        TimeUnit::Second => ValueData::TimestampSecondValue(timestamp.value()),
893        TimeUnit::Millisecond => ValueData::TimestampMillisecondValue(timestamp.value()),
894        TimeUnit::Microsecond => ValueData::TimestampMicrosecondValue(timestamp.value()),
895        TimeUnit::Nanosecond => ValueData::TimestampNanosecondValue(timestamp.value()),
896    })
897}
898
899fn is_timestamp_type(datatype: ColumnDataType) -> bool {
900    timestamp_unit(datatype).is_some()
901}
902
903fn parse_export_logs_service_request_to_rows(
904    request: ExportLogsServiceRequest,
905    mut select_info: Box<SelectInfo>,
906    v1_schema: bool,
907    existing_schema: Option<&ExistingLogSchema>,
908    table_name: &str,
909) -> Result<Rows> {
910    let mut schemas = build_otlp_logs_identity_schema(v1_schema)?;
911
912    // Extract keys named after v1 built-in columns would add duplicate columns. A
913    // `service_name` key fills the built-in column; `event_name` and
914    // `observed_timestamp` keep the LogRecord values, and the attribute stays in
915    // `log_attributes`.
916    let extract_service_name = v1_schema
917        && select_info
918            .keys
919            .iter()
920            .any(|key| key == SERVICE_NAME_COLUMN);
921    if v1_schema {
922        select_info.keys.retain(|key| {
923            !matches!(
924                key.as_str(),
925                SERVICE_NAME_COLUMN | EVENT_NAME_COLUMN | OBSERVED_TIMESTAMP_COLUMN
926            )
927        });
928    }
929    let mut parse_ctx = ParseContext::new(
930        select_info,
931        v1_schema,
932        extract_service_name,
933        existing_schema,
934        table_name,
935    );
936    let mut rows = parse_resource(&mut parse_ctx, request.resource_logs)?;
937
938    schemas.extend(parse_ctx.select_schema.column_schemas()?);
939    align_rows_with_existing_schema(&mut schemas, &mut rows, existing_schema, table_name)?;
940
941    rows.iter_mut().for_each(|row| {
942        row.values.resize(schemas.len(), GreptimeValue::default());
943    });
944
945    Ok(Rows {
946        schema: schemas,
947        rows,
948    })
949}
950
951fn parse_resource(
952    parse_ctx: &mut ParseContext,
953    resource_logs_vec: Vec<ResourceLogs>,
954) -> Result<Vec<Row>> {
955    let total_len = resource_logs_vec
956        .iter()
957        .flat_map(|r| r.scope_logs.iter())
958        .map(|s| s.log_records.len())
959        .sum();
960
961    let mut results = Vec::with_capacity(total_len);
962
963    for r in resource_logs_vec {
964        let mut resource_service = None;
965        parse_ctx.resource_attr = match r.resource {
966            Some(resource) => {
967                if parse_ctx.v1_schema {
968                    resource_service = resource_service_name(&resource.attributes);
969                }
970                key_value_to_jsonb(resource.attributes)
971            }
972            None => JsonbValue::Null,
973        };
974
975        parse_ctx.resource_url = r.schema_url;
976        if parse_ctx.v1_schema {
977            let extracted = if parse_ctx.extract_service_name {
978                extracted_service_name(&parse_ctx.resource_attr)?
979            } else {
980                None
981            };
982            parse_ctx.resource_service_name = extracted.or(resource_service);
983        }
984
985        parse_ctx.resource_uplift_values = extract_field_from_attr_and_combine_schema(
986            &parse_ctx.select_info,
987            &mut parse_ctx.select_schema,
988            &parse_ctx.resource_attr,
989            parse_ctx.existing_schema,
990            parse_ctx.table_name,
991        )?;
992
993        let rows = parse_scope(r.scope_logs, parse_ctx)?;
994        results.extend(rows);
995    }
996    Ok(results)
997}
998
999struct ParseContext<'a> {
1000    // input selected keys
1001    select_info: Box<SelectInfo>,
1002    v1_schema: bool,
1003    extract_service_name: bool,
1004    existing_schema: Option<&'a ExistingLogSchema>,
1005    table_name: &'a str,
1006    // schema infos for selected keys from resource/scope/log for current request
1007    // since the value override from bottom to top, the max capacity is the length of the keys
1008    select_schema: SchemaInfo,
1009
1010    // extracted and uplifted values using select keys
1011    resource_uplift_values: Vec<GreptimeValue>,
1012    scope_uplift_values: Vec<GreptimeValue>,
1013
1014    // passdown values
1015    resource_url: String,
1016    resource_attr: JsonbValue<'a>,
1017    scope_name: Option<String>,
1018    scope_version: Option<String>,
1019    scope_url: String,
1020    scope_attrs: JsonbValue<'a>,
1021    // `service_name` values resolved at the resource and scope levels; a log
1022    // record falls back to them when its own attributes don't carry one
1023    resource_service_name: Option<String>,
1024    scope_service_name: Option<String>,
1025}
1026
1027impl<'a> ParseContext<'a> {
1028    pub fn new(
1029        select_info: Box<SelectInfo>,
1030        v1_schema: bool,
1031        extract_service_name: bool,
1032        existing_schema: Option<&'a ExistingLogSchema>,
1033        table_name: &'a str,
1034    ) -> ParseContext<'a> {
1035        let len = select_info.keys.len();
1036        ParseContext {
1037            select_info,
1038            v1_schema,
1039            extract_service_name,
1040            existing_schema,
1041            table_name,
1042            select_schema: SchemaInfo::with_capacity(len),
1043            resource_uplift_values: vec![],
1044            scope_uplift_values: vec![],
1045            resource_url: String::new(),
1046            resource_attr: JsonbValue::Null,
1047            scope_name: None,
1048            scope_version: None,
1049            scope_url: String::new(),
1050            scope_attrs: JsonbValue::Null,
1051            resource_service_name: None,
1052            scope_service_name: None,
1053        }
1054    }
1055}
1056
1057fn parse_scope(scopes_log_vec: Vec<ScopeLogs>, parse_ctx: &mut ParseContext) -> Result<Vec<Row>> {
1058    let len = scopes_log_vec.iter().map(|l| l.log_records.len()).sum();
1059    let mut results = Vec::with_capacity(len);
1060
1061    for scope_logs in scopes_log_vec {
1062        let (scope_attrs, scope_version, scope_name) = scope_to_jsonb(scope_logs.scope);
1063        parse_ctx.scope_name = scope_name;
1064        parse_ctx.scope_version = scope_version;
1065        parse_ctx.scope_url = scope_logs.schema_url;
1066        parse_ctx.scope_attrs = scope_attrs;
1067        parse_ctx.scope_service_name = if parse_ctx.extract_service_name {
1068            extracted_service_name(&parse_ctx.scope_attrs)?
1069        } else {
1070            None
1071        };
1072
1073        parse_ctx.scope_uplift_values = extract_field_from_attr_and_combine_schema(
1074            &parse_ctx.select_info,
1075            &mut parse_ctx.select_schema,
1076            &parse_ctx.scope_attrs,
1077            parse_ctx.existing_schema,
1078            parse_ctx.table_name,
1079        )?;
1080
1081        let rows = parse_log(scope_logs.log_records, parse_ctx)?;
1082        results.extend(rows);
1083    }
1084    Ok(results)
1085}
1086
1087fn parse_log(log_records: Vec<LogRecord>, parse_ctx: &mut ParseContext) -> Result<Vec<Row>> {
1088    let mut result = Vec::with_capacity(log_records.len());
1089
1090    for mut log in log_records {
1091        let log_attr = key_value_to_jsonb(std::mem::take(&mut log.attributes));
1092        let service_name = if parse_ctx.v1_schema {
1093            let extracted = if parse_ctx.extract_service_name {
1094                extracted_service_name(&log_attr)?
1095            } else {
1096                None
1097            };
1098            extracted
1099                .or_else(|| parse_ctx.scope_service_name.clone())
1100                .or_else(|| parse_ctx.resource_service_name.clone())
1101        } else {
1102            None
1103        };
1104        let mut row = build_otlp_build_in_row(log, &log_attr, service_name, parse_ctx);
1105
1106        let log_values = extract_field_from_attr_and_combine_schema(
1107            &parse_ctx.select_info,
1108            &mut parse_ctx.select_schema,
1109            &log_attr,
1110            parse_ctx.existing_schema,
1111            parse_ctx.table_name,
1112        )?;
1113
1114        let extracted_values = merge_values(
1115            log_values,
1116            &parse_ctx.scope_uplift_values,
1117            &parse_ctx.resource_uplift_values,
1118        );
1119
1120        row.values.extend(extracted_values);
1121
1122        result.push(row);
1123    }
1124    Ok(result)
1125}
1126
1127fn merge_values(
1128    log: Vec<GreptimeValue>,
1129    scope: &[GreptimeValue],
1130    resource: &[GreptimeValue],
1131) -> Vec<GreptimeValue> {
1132    log.into_iter()
1133        .enumerate()
1134        .map(|(i, value)| GreptimeValue {
1135            value_data: value
1136                .value_data
1137                .or_else(|| scope.get(i).and_then(|x| x.value_data.clone()))
1138                .or_else(|| resource.get(i).and_then(|x| x.value_data.clone())),
1139        })
1140        .collect()
1141}
1142
1143/// transform otlp logs request to pipeline value
1144/// https://opentelemetry.io/docs/concepts/signals/logs/
1145fn parse_export_logs_service_request(request: ExportLogsServiceRequest) -> Vec<VrlValue> {
1146    let mut result = Vec::new();
1147    for r in request.resource_logs {
1148        let resource_attr = r
1149            .resource
1150            .map(|x| VrlValue::Object(key_value_to_map(x.attributes)))
1151            .unwrap_or(VrlValue::Null);
1152        let resource_schema_url = VrlValue::Bytes(r.schema_url.into());
1153        for scope_logs in r.scope_logs {
1154            let (scope_attrs, scope_version, scope_name) =
1155                scope_to_pipeline_value(scope_logs.scope);
1156            let scope_schema_url = VrlValue::Bytes(scope_logs.schema_url.into());
1157            for log in scope_logs.log_records {
1158                let value = log_to_pipeline_value(
1159                    log,
1160                    resource_schema_url.clone(),
1161                    resource_attr.clone(),
1162                    scope_schema_url.clone(),
1163                    scope_name.clone(),
1164                    scope_version.clone(),
1165                    scope_attrs.clone(),
1166                );
1167                result.push(value);
1168            }
1169        }
1170    }
1171    result
1172}
1173
1174// convert AnyValue to pipeline value
1175fn any_value_to_vrl_value(value: any_value::Value) -> VrlValue {
1176    match value {
1177        any_value::Value::StringValue(s) => VrlValue::Bytes(s.into()),
1178        any_value::Value::IntValue(i) => VrlValue::Integer(i),
1179        // VRL has no NaN float; like other unrepresentable values, NaN becomes null.
1180        any_value::Value::DoubleValue(d) => NotNan::new(d).map_or(VrlValue::Null, VrlValue::Float),
1181        any_value::Value::BoolValue(b) => VrlValue::Boolean(b),
1182        any_value::Value::ArrayValue(array_value) => {
1183            let values = array_value
1184                .values
1185                .into_iter()
1186                .filter_map(|v| v.value.map(any_value_to_vrl_value))
1187                .collect();
1188            VrlValue::Array(values)
1189        }
1190        any_value::Value::KvlistValue(key_value_list) => {
1191            VrlValue::Object(key_value_to_map(key_value_list.values))
1192        }
1193        any_value::Value::BytesValue(items) => VrlValue::Bytes(Bytes::from(items)),
1194        // `StringValueStrindex` references the Profiling signal's
1195        // `ProfilesDictionary.string_table`, which is unavailable to logs/traces.
1196        // Per the OTLP spec, non-Profiling receivers must treat it as a non-fatal
1197        // issue and process the value as if it were absent.
1198        any_value::Value::StringValueStrindex(_) => {
1199            warn!(
1200                "encountered a profiling-only `StringValueStrindex` value in a non-profiling signal; ignoring"
1201            );
1202            VrlValue::Null
1203        }
1204    }
1205}
1206
1207// convert otlp keyValue vec to map
1208fn key_value_to_map(key_values: Vec<KeyValue>) -> BTreeMap<KeyString, VrlValue> {
1209    let mut map = BTreeMap::new();
1210    for kv in key_values {
1211        let value = match kv.value {
1212            Some(value) => match value.value {
1213                Some(value) => any_value_to_vrl_value(value),
1214                None => VrlValue::Null,
1215            },
1216            None => VrlValue::Null,
1217        };
1218        map.insert(kv.key.into(), value);
1219    }
1220    map
1221}
1222
1223fn log_body_to_string(body: &AnyValue) -> String {
1224    let otlp_value = OtlpAnyValue::from(body);
1225    otlp_value.to_string()
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use datatypes::prelude::ConcreteDataType;
1231    use datatypes::schema::ColumnSchema as DatatypesColumnSchema;
1232    use opentelemetry_proto::tonic::common::v1::any_value::Value as OtlpValue;
1233
1234    use super::*;
1235    use crate::otlp::trace::KEY_SERVICE_NAME;
1236
1237    fn time_column(datatype: ConcreteDataType) -> DatatypesColumnSchema {
1238        DatatypesColumnSchema::new("timestamp", datatype, false).with_time_index(true)
1239    }
1240
1241    fn column(name: &str, datatype: ConcreteDataType) -> DatatypesColumnSchema {
1242        DatatypesColumnSchema::new(name, datatype, true)
1243    }
1244
1245    fn existing_schema(
1246        columns: Vec<DatatypesColumnSchema>,
1247        primary_key_indices: &[usize],
1248    ) -> ExistingLogSchema {
1249        ExistingLogSchema::try_from_schema_parts(&columns, primary_key_indices).unwrap()
1250    }
1251
1252    fn existing_uint32_trace_flags_schema() -> ExistingLogSchema {
1253        existing_schema(
1254            vec![
1255                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1256                column("trace_flags", ConcreteDataType::uint32_datatype()),
1257            ],
1258            &[],
1259        )
1260    }
1261
1262    fn kv(key: &str, value: OtlpValue) -> KeyValue {
1263        KeyValue {
1264            key: key.to_string(),
1265            value: Some(AnyValue { value: Some(value) }),
1266            ..Default::default()
1267        }
1268    }
1269
1270    fn request_with_log_attrs(attrs: Vec<KeyValue>) -> ExportLogsServiceRequest {
1271        request_with_log_attrs_and_flags(attrs, 0)
1272    }
1273
1274    fn request_with_log_attrs_and_flags(
1275        attrs: Vec<KeyValue>,
1276        flags: u32,
1277    ) -> ExportLogsServiceRequest {
1278        ExportLogsServiceRequest {
1279            resource_logs: vec![ResourceLogs {
1280                scope_logs: vec![ScopeLogs {
1281                    log_records: vec![LogRecord {
1282                        time_unix_nano: 1_234_000_000,
1283                        trace_id: vec![1; 16],
1284                        flags,
1285                        attributes: attrs,
1286                        ..Default::default()
1287                    }],
1288                    ..Default::default()
1289                }],
1290                ..Default::default()
1291            }],
1292        }
1293    }
1294
1295    fn parse_with_select(
1296        request: ExportLogsServiceRequest,
1297        select: &str,
1298        existing_schema: Option<&ExistingLogSchema>,
1299    ) -> Result<Rows> {
1300        // Mirrors production: only new tables get the v1 schema, and the existing
1301        // schemas built here carry no v1 marker.
1302        parse_export_logs_service_request_to_rows(
1303            request,
1304            Box::new(SelectInfo::from(select.to_string())),
1305            existing_schema.is_none(),
1306            existing_schema,
1307            "test_logs",
1308        )
1309    }
1310
1311    fn column_index(rows: &Rows, name: &str) -> usize {
1312        rows.schema
1313            .iter()
1314            .position(|schema| schema.column_name == name)
1315            .unwrap()
1316    }
1317
1318    #[test]
1319    fn test_no_existing_table_preserves_direct_schema() {
1320        let rows = parse_with_select(request_with_log_attrs(vec![]), "", None).unwrap();
1321
1322        assert_eq!(rows.schema[0].column_name, "timestamp");
1323        assert_eq!(
1324            rows.schema[0].datatype,
1325            ColumnDataType::TimestampNanosecond as i32
1326        );
1327        assert_eq!(rows.schema[0].semantic_type, SemanticType::Timestamp as i32);
1328        let scope_name_idx = column_index(&rows, "scope_name");
1329        assert_eq!(
1330            rows.schema[scope_name_idx].semantic_type,
1331            SemanticType::Tag as i32
1332        );
1333    }
1334
1335    fn request_with_resource_and_logs(
1336        resource_attrs: Vec<KeyValue>,
1337        log_records: Vec<LogRecord>,
1338    ) -> ExportLogsServiceRequest {
1339        ExportLogsServiceRequest {
1340            resource_logs: vec![ResourceLogs {
1341                resource: Some(opentelemetry_proto::tonic::resource::v1::Resource {
1342                    attributes: resource_attrs,
1343                    ..Default::default()
1344                }),
1345                scope_logs: vec![ScopeLogs {
1346                    scope: Some(InstrumentationScope {
1347                        name: "com.example.Checkout".to_string(),
1348                        ..Default::default()
1349                    }),
1350                    log_records,
1351                    ..Default::default()
1352                }],
1353                ..Default::default()
1354            }],
1355        }
1356    }
1357
1358    fn value_at(rows: &Rows, row: usize, column: &str) -> Option<ValueData> {
1359        rows.rows[row].values[column_index(rows, column)]
1360            .value_data
1361            .clone()
1362    }
1363
1364    #[test]
1365    fn test_new_table_uses_v1_schema() {
1366        let request = request_with_resource_and_logs(
1367            vec![kv(
1368                KEY_SERVICE_NAME,
1369                OtlpValue::StringValue("checkout".to_string()),
1370            )],
1371            vec![
1372                LogRecord {
1373                    time_unix_nano: 1_000,
1374                    observed_time_unix_nano: 2_000,
1375                    event_name: "gen_ai.choice".to_string(),
1376                    ..Default::default()
1377                },
1378                LogRecord {
1379                    time_unix_nano: 3_000,
1380                    ..Default::default()
1381                },
1382            ],
1383        );
1384        let rows = parse_with_select(request, "", None).unwrap();
1385
1386        // Auto-create orders the primary key by column order.
1387        let tags: Vec<_> = rows
1388            .schema
1389            .iter()
1390            .filter(|schema| schema.semantic_type == SemanticType::Tag as i32)
1391            .map(|schema| schema.column_name.as_str())
1392            .collect();
1393        assert_eq!(tags, [SERVICE_NAME_COLUMN, "scope_name"]);
1394        let trace_id = &rows.schema[column_index(&rows, "trace_id")];
1395        assert!(
1396            trace_id
1397                .options
1398                .as_ref()
1399                .is_some_and(|options| options.options.contains_key("skipping_index"))
1400        );
1401
1402        assert_eq!(
1403            value_at(&rows, 0, SERVICE_NAME_COLUMN),
1404            Some(ValueData::StringValue("checkout".to_string()))
1405        );
1406        assert_eq!(
1407            value_at(&rows, 0, EVENT_NAME_COLUMN),
1408            Some(ValueData::StringValue("gen_ai.choice".to_string()))
1409        );
1410        assert_eq!(
1411            value_at(&rows, 0, OBSERVED_TIMESTAMP_COLUMN),
1412            Some(ValueData::TimestampNanosecondValue(2_000))
1413        );
1414        // Empty event name and zero observed time mean "absent" in OTLP.
1415        assert_eq!(value_at(&rows, 1, EVENT_NAME_COLUMN), None);
1416        assert_eq!(value_at(&rows, 1, OBSERVED_TIMESTAMP_COLUMN), None);
1417    }
1418
1419    #[test]
1420    fn test_extracted_service_name_overrides_resource_service_name() {
1421        let mut request = request_with_resource_and_logs(
1422            vec![kv(
1423                KEY_SERVICE_NAME,
1424                OtlpValue::StringValue("from-resource".to_string()),
1425            )],
1426            vec![
1427                LogRecord {
1428                    attributes: vec![
1429                        kv(
1430                            SERVICE_NAME_COLUMN,
1431                            OtlpValue::StringValue("from-log".to_string()),
1432                        ),
1433                        kv(
1434                            EVENT_NAME_COLUMN,
1435                            OtlpValue::StringValue("from-attr".to_string()),
1436                        ),
1437                    ],
1438                    event_name: "from-record".to_string(),
1439                    ..Default::default()
1440                },
1441                LogRecord::default(),
1442            ],
1443        );
1444        let mut scope_logs = request.resource_logs[0].scope_logs[0].clone();
1445        scope_logs.scope.as_mut().unwrap().attributes = vec![kv(
1446            SERVICE_NAME_COLUMN,
1447            OtlpValue::StringValue("from-scope".to_string()),
1448        )];
1449        scope_logs.log_records = vec![LogRecord::default()];
1450        request.resource_logs[0].scope_logs.push(scope_logs);
1451        let rows = parse_with_select(request, "service_name,event_name,host", None).unwrap();
1452
1453        for column in [SERVICE_NAME_COLUMN, EVENT_NAME_COLUMN] {
1454            assert_eq!(
1455                rows.schema
1456                    .iter()
1457                    .filter(|schema| schema.column_name == column)
1458                    .count(),
1459                1
1460            );
1461        }
1462        assert_eq!(
1463            value_at(&rows, 0, SERVICE_NAME_COLUMN),
1464            Some(ValueData::StringValue("from-log".to_string()))
1465        );
1466        assert_eq!(
1467            value_at(&rows, 0, EVENT_NAME_COLUMN),
1468            Some(ValueData::StringValue("from-record".to_string()))
1469        );
1470        assert_eq!(
1471            value_at(&rows, 1, SERVICE_NAME_COLUMN),
1472            Some(ValueData::StringValue("from-resource".to_string()))
1473        );
1474        assert_eq!(
1475            value_at(&rows, 2, SERVICE_NAME_COLUMN),
1476            Some(ValueData::StringValue("from-scope".to_string()))
1477        );
1478    }
1479
1480    #[test]
1481    fn test_non_scalar_resource_service_name_is_not_an_error() {
1482        let request = request_with_resource_and_logs(
1483            vec![kv(
1484                KEY_SERVICE_NAME,
1485                OtlpValue::ArrayValue(Default::default()),
1486            )],
1487            vec![LogRecord::default()],
1488        );
1489        let rows = parse_with_select(request, "", None).unwrap();
1490
1491        assert_eq!(value_at(&rows, 0, SERVICE_NAME_COLUMN), None);
1492    }
1493
1494    #[test]
1495    fn test_fresh_table_trace_flags_is_int32() {
1496        // Phase 1 of the unsigned -> signed transition: a fresh log table now
1497        // creates `trace_flags` as Int32. Existing tables keep UInt32 (covered
1498        // by the coercion test above); new tables start signed.
1499        let rows = parse_with_select(request_with_log_attrs(vec![]), "", None).unwrap();
1500        let idx = column_index(&rows, "trace_flags");
1501
1502        assert_eq!(rows.schema[idx].datatype, ColumnDataType::Int32 as i32);
1503        assert_eq!(
1504            rows.rows[0].values[idx].value_data,
1505            Some(ValueData::I32Value(0))
1506        );
1507    }
1508
1509    #[test]
1510    fn test_existing_uint32_trace_flags_keeps_type_and_coerces_int32_request() {
1511        // An existing UInt32 `trace_flags` column keeps its type when new
1512        // signed (Int32) ingest arrives, without an `ALTER`.
1513        let existing = existing_uint32_trace_flags_schema();
1514
1515        let rows = parse_with_select(request_with_log_attrs(vec![]), "", Some(&existing)).unwrap();
1516        let idx = column_index(&rows, "trace_flags");
1517
1518        assert_eq!(rows.schema[idx].datatype, ColumnDataType::Uint32 as i32);
1519        assert_eq!(
1520            rows.rows[0].values[idx].value_data,
1521            Some(ValueData::U32Value(0))
1522        );
1523    }
1524
1525    #[test]
1526    fn test_existing_uint32_trace_flags_preserves_flag_bits() {
1527        // `trace_flags` is a bit field: the Int32 -> UInt32 coercion must keep
1528        // the exact bit pattern, including the sign bit.
1529        let existing = existing_uint32_trace_flags_schema();
1530        for flags in [256, 0x8000_0000] {
1531            let rows = parse_with_select(
1532                request_with_log_attrs_and_flags(vec![], flags),
1533                "",
1534                Some(&existing),
1535            )
1536            .unwrap();
1537            let idx = column_index(&rows, "trace_flags");
1538
1539            assert_eq!(rows.schema[idx].datatype, ColumnDataType::Uint32 as i32);
1540            assert_eq!(
1541                rows.rows[0].values[idx].value_data,
1542                Some(ValueData::U32Value(flags))
1543            );
1544        }
1545    }
1546
1547    #[test]
1548    fn test_existing_primary_key_updates_builtin_column_semantic_type() {
1549        let existing = existing_schema(
1550            vec![
1551                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1552                column("trace_id", ConcreteDataType::string_datatype()),
1553            ],
1554            &[1],
1555        );
1556
1557        let rows = parse_with_select(request_with_log_attrs(vec![]), "", Some(&existing)).unwrap();
1558        let trace_id_idx = column_index(&rows, "trace_id");
1559
1560        assert_eq!(
1561            rows.schema[trace_id_idx].semantic_type,
1562            SemanticType::Tag as i32
1563        );
1564    }
1565
1566    #[test]
1567    fn test_existing_string_primary_key_stringifies_selected_scalar_values() {
1568        let existing = existing_schema(
1569            vec![
1570                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1571                column("host", ConcreteDataType::string_datatype()),
1572            ],
1573            &[1],
1574        );
1575        let rows = parse_with_select(
1576            request_with_log_attrs(vec![kv("host", OtlpValue::IntValue(42))]),
1577            "host",
1578            Some(&existing),
1579        )
1580        .unwrap();
1581        let host_idx = column_index(&rows, "host");
1582
1583        assert_eq!(
1584            rows.schema[host_idx].datatype,
1585            ColumnDataType::String as i32
1586        );
1587        assert_eq!(
1588            rows.schema[host_idx].semantic_type,
1589            SemanticType::Tag as i32
1590        );
1591        assert_eq!(
1592            rows.rows[0].values[host_idx].value_data,
1593            Some(ValueData::StringValue("42".to_string()))
1594        );
1595    }
1596
1597    #[test]
1598    fn test_existing_string_field_stringifies_selected_scalar_values() {
1599        let existing = existing_schema(
1600            vec![
1601                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1602                column("host", ConcreteDataType::string_datatype()),
1603            ],
1604            &[],
1605        );
1606        let rows = parse_with_select(
1607            request_with_log_attrs(vec![kv("host", OtlpValue::IntValue(42))]),
1608            "host",
1609            Some(&existing),
1610        )
1611        .unwrap();
1612        let host_idx = column_index(&rows, "host");
1613
1614        assert_eq!(
1615            rows.schema[host_idx].datatype,
1616            ColumnDataType::String as i32
1617        );
1618        assert_eq!(
1619            rows.schema[host_idx].semantic_type,
1620            SemanticType::Field as i32
1621        );
1622        assert_eq!(
1623            rows.rows[0].values[host_idx].value_data,
1624            Some(ValueData::StringValue("42".to_string()))
1625        );
1626    }
1627
1628    #[test]
1629    fn test_existing_non_string_primary_key_rejects_incompatible_selected_value() {
1630        let existing = existing_schema(
1631            vec![
1632                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1633                column("host", ConcreteDataType::int64_datatype()),
1634            ],
1635            &[1],
1636        );
1637        let err = parse_with_select(
1638            request_with_log_attrs(vec![kv(
1639                "host",
1640                OtlpValue::StringValue("node-a".to_string()),
1641            )]),
1642            "host",
1643            Some(&existing),
1644        )
1645        .unwrap_err();
1646
1647        assert!(
1648            err.to_string()
1649                .contains("failed to align log column 'host'")
1650        );
1651    }
1652
1653    #[test]
1654    fn test_existing_timestamp_unit_is_respected() {
1655        let existing = existing_schema(
1656            vec![time_column(
1657                ConcreteDataType::timestamp_millisecond_datatype(),
1658            )],
1659            &[],
1660        );
1661        let rows = parse_with_select(request_with_log_attrs(vec![]), "", Some(&existing)).unwrap();
1662
1663        assert_eq!(
1664            rows.schema[0].datatype,
1665            ColumnDataType::TimestampMillisecond as i32
1666        );
1667        assert_eq!(
1668            rows.rows[0].values[0].value_data,
1669            Some(ValueData::TimestampMillisecondValue(1234))
1670        );
1671    }
1672
1673    #[test]
1674    fn test_missing_existing_primary_key_is_not_generated() {
1675        let existing = existing_schema(
1676            vec![
1677                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1678                column("host", ConcreteDataType::string_datatype()),
1679            ],
1680            &[1],
1681        );
1682        let rows = parse_with_select(request_with_log_attrs(vec![]), "", Some(&existing)).unwrap();
1683
1684        assert!(
1685            !rows
1686                .schema
1687                .iter()
1688                .any(|schema| schema.column_name == "host")
1689        );
1690    }
1691
1692    #[test]
1693    fn test_existing_table_keeps_new_generated_columns_as_fields() {
1694        let existing = existing_schema(
1695            vec![
1696                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1697                column("trace_id", ConcreteDataType::string_datatype()),
1698            ],
1699            &[1],
1700        );
1701        let rows = parse_with_select(
1702            request_with_log_attrs(vec![kv(
1703                "host",
1704                OtlpValue::StringValue("node-a".to_string()),
1705            )]),
1706            "host",
1707            Some(&existing),
1708        )
1709        .unwrap();
1710        let host_idx = column_index(&rows, "host");
1711        let scope_name_idx = column_index(&rows, "scope_name");
1712
1713        assert_eq!(
1714            rows.schema[host_idx].semantic_type,
1715            SemanticType::Field as i32
1716        );
1717        assert_eq!(
1718            rows.schema[scope_name_idx].semantic_type,
1719            SemanticType::Field as i32
1720        );
1721        // Unmarked existing tables keep the legacy columns.
1722        for column in [
1723            SERVICE_NAME_COLUMN,
1724            EVENT_NAME_COLUMN,
1725            OBSERVED_TIMESTAMP_COLUMN,
1726        ] {
1727            assert!(
1728                rows.schema
1729                    .iter()
1730                    .all(|schema| schema.column_name != column)
1731            );
1732        }
1733    }
1734
1735    #[test]
1736    fn test_existing_uint64_column_keeps_type_and_coerces_int64_request() {
1737        // An existing UInt64 column keeps its type when new signed (Int64)
1738        // ingest arrives, without an `ALTER`. The built-in models move to
1739        // signed while existing unsigned tables stay byte-for-byte unchanged.
1740        let existing = existing_schema(
1741            vec![
1742                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1743                column("counter", ConcreteDataType::uint64_datatype()),
1744            ],
1745            &[],
1746        );
1747
1748        let rows = parse_with_select(
1749            request_with_log_attrs(vec![kv("counter", OtlpValue::IntValue(42))]),
1750            "counter",
1751            Some(&existing),
1752        )
1753        .unwrap();
1754        let idx = column_index(&rows, "counter");
1755
1756        assert_eq!(rows.schema[idx].datatype, ColumnDataType::Uint64 as i32);
1757        assert_eq!(
1758            rows.rows[0].values[idx].value_data,
1759            Some(ValueData::U64Value(42))
1760        );
1761    }
1762
1763    #[test]
1764    fn test_jsonb_extended_log_values_rejected() {
1765        for (value, expected_type) in [
1766            (
1767                JsonbValue::Number(JsonbNumber::Decimal64(jsonb::Decimal64 {
1768                    value: 123,
1769                    scale: 2,
1770                })),
1771                "DECIMAL",
1772            ),
1773            (JsonbValue::Binary(&[1, 2, 3]), "Binary"),
1774            (JsonbValue::Date(jsonb::Date { value: 0 }), "Date"),
1775            (
1776                JsonbValue::Timestamp(jsonb::Timestamp { value: 0 }),
1777                "Timestamp",
1778            ),
1779            (
1780                JsonbValue::TimestampTz(jsonb::TimestampTz {
1781                    value: 0,
1782                    offset: 0,
1783                }),
1784                "TimestampTz",
1785            ),
1786            (
1787                JsonbValue::Interval(jsonb::Interval {
1788                    months: 0,
1789                    days: 0,
1790                    micros: 0,
1791                }),
1792                "Interval",
1793            ),
1794        ] {
1795            let error = decide_column_schema_and_convert_value("attr", value, None, "logs")
1796                .expect_err("extended JSONB type must be rejected");
1797            assert!(matches!(error,
1798                Error::UnsupportedJsonDataTypeForTag { key, ty, .. }
1799                    if key == "attr" && ty == expected_type
1800            ));
1801        }
1802    }
1803
1804    #[test]
1805    fn test_nan_double_becomes_null_vrl_value() {
1806        assert_eq!(
1807            any_value_to_vrl_value(OtlpValue::DoubleValue(f64::NAN)),
1808            VrlValue::Null
1809        );
1810        assert_eq!(
1811            any_value_to_vrl_value(OtlpValue::DoubleValue(1.5)),
1812            VrlValue::Float(NotNan::new(1.5).unwrap())
1813        );
1814    }
1815
1816    #[test]
1817    fn test_jsonb_uint64_exceeding_i64_range_rejected() {
1818        // A JSON number that only fits in u64 must be rejected, not wrapped:
1819        // storing it as a negative i64 would silently corrupt the value. The
1820        // unsigned -> signed transition is only lossless for values that fit
1821        // the signed range.
1822        let err = jsonb_value_to_log_value_data(
1823            "counter",
1824            JsonbValue::Number(JsonbNumber::UInt64(u64::MAX)),
1825            false,
1826        )
1827        .unwrap_err();
1828
1829        assert!(
1830            err.to_string()
1831                .contains("exceeds the i64 range supported by built-in log columns")
1832        );
1833    }
1834
1835    #[test]
1836    fn test_existing_int64_column_rejects_numeric_string_value() {
1837        // Regression guard for the signed -> unsigned transition scope: even a
1838        // parseable numeric string must keep its pre-existing rejection when
1839        // targeting a non-String column. Only the signed -> unsigned integer
1840        // pairs gained coercion on this path, not the generic String ->
1841        // numeric ones.
1842        let existing = existing_schema(
1843            vec![
1844                time_column(ConcreteDataType::timestamp_nanosecond_datatype()),
1845                column("counter", ConcreteDataType::int64_datatype()),
1846            ],
1847            &[],
1848        );
1849
1850        let err = parse_with_select(
1851            request_with_log_attrs(vec![kv(
1852                "counter",
1853                OtlpValue::StringValue("42".to_string()),
1854            )]),
1855            "counter",
1856            Some(&existing),
1857        )
1858        .unwrap_err();
1859
1860        assert!(
1861            err.to_string()
1862                .contains("failed to align log column 'counter'")
1863        );
1864    }
1865}