From dac81ee7cc5c94f51d2ecd8aa808b94ac7a4cefc Mon Sep 17 00:00:00 2001 From: shuiyisong <113876041+shuiyisong@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:26:57 +0000 Subject: [PATCH] fix: tolerate invalid UTF-8 in JSON log ingestion (#10245) * fix: tolerate invalid UTF-8 in JSON ingestion Signed-off-by: shuiyisong * fix: tolerate invalid UTF-8 in NDJSON ingestion Signed-off-by: shuiyisong * chore: upgrade simd json Signed-off-by: shuiyisong * feat: add server default for ignore_errors Signed-off-by: shuiyisong --------- Signed-off-by: shuiyisong --- Cargo.lock | 18 +- Cargo.toml | 2 +- config/config.md | 4 + config/frontend.example.toml | 9 + config/standalone.example.toml | 9 + src/frontend/src/frontend.rs | 14 + src/frontend/src/instance/builder.rs | 1 + src/frontend/src/instance/log_handler.rs | 6 +- src/pipeline/Cargo.toml | 2 +- src/pipeline/src/lib.rs | 2 + src/pipeline/src/manager/pipeline_operator.rs | 10 +- src/pipeline/src/options.rs | 26 ++ src/servers/src/http/event.rs | 295 ++++++++++++++++-- src/servers/src/query_handler.rs | 7 +- src/standalone/Cargo.toml | 4 + src/standalone/src/options.rs | 22 ++ tests-integration/Cargo.toml | 2 +- tests-integration/src/standalone.rs | 10 + tests-integration/tests/http.rs | 129 +++++++- 19 files changed, 525 insertions(+), 47 deletions(-) create mode 100644 src/pipeline/src/options.rs diff --git a/Cargo.lock b/Cargo.lock index 19b9aaabca4..f78fa9cfe79 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6029,11 +6029,11 @@ dependencies = [ [[package]] name = "halfbrown" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2c385c6df70fd180bbb673d93039dbd2cd34e41d782600bdf6e1ca7bce39aa" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" dependencies = [ - "hashbrown 0.15.4", + "hashbrown 0.16.1", "serde", ] @@ -13346,13 +13346,11 @@ checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" [[package]] name = "simd-json" -version = "0.15.1" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c962f626b54771990066e5435ec8331d1462576cd2d1e62f24076ae014f92112" +checksum = "e8f2e4d523646f7da6dde3983bd18ede0babc21c258ab708b3dd93ea0259719d" dependencies = [ - "getrandom 0.3.4", "halfbrown", - "ref-cast", "serde", "serde_json", "simdutf8", @@ -13925,6 +13923,7 @@ dependencies = [ "hostname 0.4.1", "log-store", "mito2", + "pipeline", "query", "serde", "servers", @@ -13932,6 +13931,7 @@ dependencies = [ "store-api", "table", "tokio", + "toml 0.8.23", "url", ] @@ -15756,9 +15756,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "value-trait" -version = "0.11.0" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" dependencies = [ "float-cmp", "halfbrown", diff --git a/Cargo.toml b/Cargo.toml index fd6a533ed11..bfec91a2d38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -229,7 +229,7 @@ sea-query = "0.32" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["float_roundtrip"] } serde_with = "3" -simd-json = "0.15" +simd-json = "0.19" similar-asserts = "1.6.0" smallvec = { version = "1", features = ["serde"] } snafu = "0.8" diff --git a/config/config.md b/config/config.md index 80f2f036bdf..3f221f7fe63 100644 --- a/config/config.md +++ b/config/config.md @@ -223,6 +223,8 @@ | `slow_query.sample_ratio` | Float | Unset | The sampling ratio of slow query log. The value should be in the range of (0, 1]. | | `tracing` | -- | -- | The tracing options. Only effect when compiled with `tokio-console` feature. | | `tracing.tokio_console_addr` | String | Unset | The tokio console address. | +| `pipeline` | -- | -- | The pipeline options. | +| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
Explicit request values override this setting. Malformed input may be discarded,
and invalid custom timestamps in identity ingestion fall back to server time.
Pipeline execution errors are controlled separately by `skip_error`.
Default is false. Requires a restart. | | `memory` | -- | -- | The memory options. | | `memory.enable_heap_profiling` | Bool | `true` | Whether to enable heap profiling activation during startup.
When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
is set to "prof:true,prof_active:false". The official image adds this env variable.
Default is true. | @@ -348,6 +350,8 @@ | `tracing.tokio_console_addr` | String | Unset | The tokio console address. | | `memory` | -- | -- | The memory options. | | `memory.enable_heap_profiling` | Bool | `true` | Whether to enable heap profiling activation during startup.
When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
is set to "prof:true,prof_active:false". The official image adds this env variable.
Default is true. | +| `pipeline` | -- | -- | The pipeline options. | +| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
Explicit request values override this setting. Malformed input may be discarded,
and invalid custom timestamps in identity ingestion fall back to server time.
Pipeline execution errors are controlled separately by `skip_error`.
Default is false. Requires a restart. | | `event_recorder` | -- | -- | Configuration options for the event recorder. | | `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. | diff --git a/config/frontend.example.toml b/config/frontend.example.toml index 766a21a9654..05e85c5b91f 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -362,6 +362,15 @@ ttl = "90d" ## Default is true. enable_heap_profiling = true +## The pipeline options. +[pipeline] +## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter. +## Explicit request values override this setting. Malformed input may be discarded, +## and invalid custom timestamps in identity ingestion fall back to server time. +## Pipeline execution errors are controlled separately by `skip_error`. +## Default is false. Requires a restart. +ignore_errors = false + ## Configuration options for the event recorder. [event_recorder] ## TTL for the events table that will be used to store the events. Default is `90d`. diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 587aa3c05eb..a23b8b46d67 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -869,6 +869,15 @@ default_ratio = 1.0 ## @toml2docs:none-default #+ tokio_console_addr = "127.0.0.1" +## The pipeline options. +[pipeline] +## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter. +## Explicit request values override this setting. Malformed input may be discarded, +## and invalid custom timestamps in identity ingestion fall back to server time. +## Pipeline execution errors are controlled separately by `skip_error`. +## Default is false. Requires a restart. +ignore_errors = false + ## The memory options. [memory] ## Whether to enable heap profiling activation during startup. diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs index 918185cb8f6..b2253812ac3 100644 --- a/src/frontend/src/frontend.rs +++ b/src/frontend/src/frontend.rs @@ -22,6 +22,7 @@ use common_options::datanode::DatanodeClientOptions; use common_options::memory::MemoryOptions; use common_telemetry::logging::{LoggingOptions, SlowQueryOptions, TracingOptions}; use meta_client::MetaClientOptions; +use pipeline::PipelineOptions; use query::options::QueryOptions; use serde::{Deserialize, Serialize}; use servers::grpc::GrpcOptions; @@ -75,6 +76,7 @@ pub struct FrontendOptions { pub query: QueryOptions, pub slow_query: SlowQueryOptions, pub memory: MemoryOptions, + pub pipeline: PipelineOptions, /// The event recorder options. pub event_recorder: EventRecorderOptions, /// Environment variable keys to read and report in heartbeat messages. @@ -108,6 +110,7 @@ impl Default for FrontendOptions { query: QueryOptions::default(), slow_query: SlowQueryOptions::default(), memory: MemoryOptions::default(), + pipeline: PipelineOptions::default(), event_recorder: EventRecorderOptions::default(), heartbeat_env_vars: vec![], } @@ -191,6 +194,17 @@ mod tests { use crate::instance::builder::FrontendBuilder; use crate::server::Services; + #[test] + fn test_pipeline_config() { + let defaults: FrontendOptions = toml::from_str("").unwrap(); + assert!(!defaults.pipeline.ignore_errors); + let options: FrontendOptions = toml::from_str("[pipeline]\nignore_errors = true").unwrap(); + assert!(options.pipeline.ignore_errors); + let serialized = toml::to_string(&options).unwrap(); + let restored: FrontendOptions = toml::from_str(&serialized).unwrap(); + assert_eq!(options.pipeline, restored.pipeline); + } + #[test] fn test_toml() { let opts = FrontendOptions::default(); diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs index 5126c625f5c..6faad305ef7 100644 --- a/src/frontend/src/instance/builder.rs +++ b/src/frontend/src/instance/builder.rs @@ -286,6 +286,7 @@ impl FrontendBuilder { statement_executor.clone(), self.catalog_manager.clone(), query_engine.clone(), + self.options.pipeline.clone(), )); plugins.insert::(statement_executor.clone()); diff --git a/src/frontend/src/instance/log_handler.rs b/src/frontend/src/instance/log_handler.rs index ed3654559fd..72ff1b425ec 100644 --- a/src/frontend/src/instance/log_handler.rs +++ b/src/frontend/src/instance/log_handler.rs @@ -21,7 +21,7 @@ use client::Output; use common_error::ext::BoxedError; use datatypes::timestamp::TimestampNanosecond; use pipeline::pipeline_operator::PipelineOperator; -use pipeline::{Pipeline, PipelineInfo, PipelineVersion}; +use pipeline::{Pipeline, PipelineInfo, PipelineOptions, PipelineVersion}; use servers::error::{ AuthSnafu, Error as ServerError, ExecuteGrpcRequestSnafu, PipelineSnafu, Result as ServerResult, }; @@ -100,6 +100,10 @@ impl PipelineHandler for Instance { .await } + fn pipeline_options(&self) -> &PipelineOptions { + self.pipeline_operator.options() + } + fn build_pipeline(&self, pipeline: &str) -> ServerResult { PipelineOperator::build_pipeline(pipeline).context(PipelineSnafu) } diff --git a/src/pipeline/Cargo.toml b/src/pipeline/Cargo.toml index d1a1f88ca8d..5907005cc03 100644 --- a/src/pipeline/Cargo.toml +++ b/src/pipeline/Cargo.toml @@ -53,6 +53,7 @@ paste.workspace = true prometheus.workspace = true query.workspace = true regex.workspace = true +serde.workspace = true serde_json.workspace = true session.workspace = true snafu.workspace = true @@ -67,7 +68,6 @@ yaml-rust = "0.4" catalog = { workspace = true, features = ["testing"] } criterion = { workspace = true, features = ["html_reports"] } rayon = "1.0" -serde = { version = "1.0", features = ["derive"] } session = { workspace = true, features = ["testing"] } [[bench]] diff --git a/src/pipeline/src/lib.rs b/src/pipeline/src/lib.rs index c657f61342c..330971d8cf8 100644 --- a/src/pipeline/src/lib.rs +++ b/src/pipeline/src/lib.rs @@ -19,6 +19,7 @@ pub mod error; mod etl; mod manager; mod metrics; +mod options; mod tablesuffix; pub use etl::ctx_req::{ContextOpt, ContextReq}; @@ -34,6 +35,7 @@ pub use manager::{ IdentityTimeIndex, PipelineContext, PipelineDefinition, PipelineInfo, PipelineRef, PipelineTableRef, PipelineVersion, PipelineWay, SelectInfo, pipeline_operator, table, util, }; +pub use options::PipelineOptions; #[macro_export] macro_rules! unwrap_or_continue_if_err { diff --git a/src/pipeline/src/manager/pipeline_operator.rs b/src/pipeline/src/manager/pipeline_operator.rs index 6c4256db69b..142980f9ee4 100644 --- a/src/pipeline/src/manager/pipeline_operator.rs +++ b/src/pipeline/src/manager/pipeline_operator.rs @@ -31,7 +31,6 @@ use snafu::{OptionExt, ResultExt}; use table::TableRef; use table::requests::TTL_KEY; -use crate::Pipeline; use crate::error::{CatalogSnafu, CreateTableSnafu, PipelineTableNotFoundSnafu, Result}; use crate::manager::{PipelineInfo, PipelineTableRef, PipelineVersion}; use crate::metrics::{ @@ -39,6 +38,7 @@ use crate::metrics::{ METRIC_PIPELINE_RETRIEVE_HISTOGRAM, }; use crate::table::{PIPELINE_TABLE_NAME, PipelineTable}; +use crate::{Pipeline, PipelineOptions}; /// PipelineOperator is responsible for managing pipelines. /// It provides the ability to: @@ -54,6 +54,7 @@ pub struct PipelineOperator { catalog_manager: CatalogManagerRef, query_engine: QueryEngineRef, tables: RwLock>, + options: PipelineOptions, } impl PipelineOperator { @@ -171,6 +172,7 @@ impl PipelineOperator { statement_executor: StatementExecutorRef, catalog_manager: CatalogManagerRef, query_engine: QueryEngineRef, + options: PipelineOptions, ) -> Self { Self { inserter, @@ -178,6 +180,7 @@ impl PipelineOperator { catalog_manager, tables: RwLock::new(HashMap::new()), query_engine, + options, } } @@ -274,6 +277,11 @@ impl PipelineOperator { .await } + /// Returns the server's pipeline options. + pub fn options(&self) -> &PipelineOptions { + &self.options + } + /// Compile a pipeline. pub fn build_pipeline(pipeline: &str) -> Result { PipelineTable::compile_pipeline(pipeline) diff --git a/src/pipeline/src/options.rs b/src/pipeline/src/options.rs new file mode 100644 index 00000000000..859559edf1a --- /dev/null +++ b/src/pipeline/src/options.rs @@ -0,0 +1,26 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct PipelineOptions { + /// Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter. + /// Explicit request values override this setting. Malformed input may be discarded, + /// and invalid custom timestamps in identity ingestion fall back to server time. + /// Pipeline execution errors are controlled separately by `skip_error`. + /// Defaults to false. Changes require a restart. + pub ignore_errors: bool, +} diff --git a/src/servers/src/http/event.rs b/src/servers/src/http/event.rs index f08c76bcdb9..60f9eaa848a 100644 --- a/src/servers/src/http/event.rs +++ b/src/servers/src/http/event.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt::Display; use std::io::BufRead; @@ -97,7 +98,8 @@ pub struct LogIngesterQueryParams { pub pipeline_name: Option, /// The version of the pipeline to be used for log ingestion. pub version: Option, - /// Whether to ignore errors during log ingestion. + /// Whether to ignore payload parsing and custom timestamp errors during log ingestion. + /// Defaults to the server's `pipeline.ignore_errors` setting when omitted. pub ignore_errors: Option, /// The source of the log data. pub source: Option, @@ -116,7 +118,7 @@ pub struct LogIngesterQueryParams { /// Whether to skip errors during log ingestion. /// If set to true, the ingestion will continue even if there are errors in the data. /// If set to false, the ingestion will stop at the first error. - /// This is different from `ignore_errors`, which is used to ignore errors during the pipeline execution. + /// This controls pipeline execution errors, separately from `ignore_errors`. /// The priority of query params is lower than that headers of x-greptime-pipeline-params. pub skip_error: Option, } @@ -584,9 +586,13 @@ fn add_step_info_for_pipeline_dryrun_error(step_msg: &str, e: Error) -> Response /// Parse the data with given content type /// If the content type is invalid, return error /// content type is one of application/json, text/plain, application/x-ndjson -fn parse_dryrun_data(data_type: String, data: String) -> Result> { +fn parse_dryrun_data( + data_type: String, + data: String, + ignore_errors: bool, +) -> Result> { if let Ok(content_type) = ContentType::from_str(&data_type) { - extract_pipeline_value_by_content_type(content_type, Bytes::from(data), false) + extract_pipeline_value_by_content_type(content_type, Bytes::from(data), ignore_errors) } else { InvalidParameterSnafu { reason: format!( @@ -612,11 +618,16 @@ pub async fn pipeline_dryrun( query_ctx.set_channel(Channel::Log); let query_ctx = Arc::new(query_ctx); + let ignore_errors = query_params + .ignore_errors + .unwrap_or(handler.pipeline_options().ignore_errors); + match check_pipeline_dryrun_params_valid(&payload) { Some(params) => { let data = parse_dryrun_data( params.data_type.unwrap_or("application/json".to_string()), params.data, + ignore_errors, )?; check_data_valid(data.len())?; @@ -667,8 +678,6 @@ pub async fn pipeline_dryrun( let version = to_pipeline_version(query_params.version.as_deref()).context(PipelineSnafu)?; - let ignore_errors = query_params.ignore_errors.unwrap_or(false); - let value = extract_pipeline_value_by_content_type(content_type, payload, ignore_errors)?; @@ -718,7 +727,9 @@ pub async fn log_ingester( reason: "table is required", })?; - let ignore_errors = query_params.ignore_errors.unwrap_or(false); + let ignore_errors = query_params + .ignore_errors + .unwrap_or(handler.pipeline_options().ignore_errors); let pipeline_name = query_params.pipeline_name.context(InvalidParameterSnafu { reason: "pipeline_name is required", @@ -833,36 +844,69 @@ impl<'a> TryFrom<&'a ContentType> for EventPayloadResolver<'a> { impl EventPayloadResolver<'_> { fn parse_payload(&self, payload: Bytes, ignore_errors: bool) -> Result> { match self.inner { - EventPayloadResolverInner::Json => transform_ndjson_array_factory( - Deserializer::from_slice(&payload).into_iter(), - ignore_errors, - ), + EventPayloadResolverInner::Json => { + // Detect parse failures even when ignore_errors would discard them. + let mut saw_parse_error = false; + let result = transform_ndjson_array_factory( + Deserializer::from_slice(&payload) + .into_iter() + .inspect(|item| saw_parse_error |= item.is_err()), + ignore_errors, + ); + if saw_parse_error && let Cow::Owned(text) = String::from_utf8_lossy(&payload) { + // Release partially parsed records before retrying the entire payload. + drop(result); + return transform_ndjson_array_factory( + Deserializer::from_str(&text).into_iter(), + ignore_errors, + ); + } + result + } EventPayloadResolverInner::Ndjson => { let mut result = Vec::with_capacity(1000); let mut buffer = Buffers::new(1000); - for (index, line) in payload.lines().enumerate() { - let mut line = match line { - Ok(line) if !line.is_empty() => line, - Ok(_) => continue, // Skip empty lines - Err(_) if ignore_errors => continue, - Err(e) => { - warn!(e; "invalid string at index: {}", index); - return InvalidParameterSnafu { - reason: format!("invalid line at index: {}", index), - } - .fail(); - } - }; + let mut remaining = payload.as_ref(); + let mut line_bytes = Vec::new(); + // read_until keeps the optimized newline search without validating UTF-8. + for index in 0usize.. { + let original = remaining; + line_bytes.clear(); + let read = remaining.read_until(b'\n', &mut line_bytes)?; + if read == 0 { + break; + } - // simd_json, according to description, only de-escapes string at character level, - // like any other json parser. So it should be safe here. - if let Ok(v) = simd_json::serde::from_slice_with_buffers( - unsafe { line.as_bytes_mut() }, - &mut buffer, - ) { + let line = &original[..read]; + let line = if let Some(line) = line.strip_suffix(b"\n") { + line.strip_suffix(b"\r").unwrap_or(line) + } else { + line + }; + if line.is_empty() { + continue; + } + + line_bytes.truncate(line.len()); + let mut parsed = + simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer); + // Retry from the original line because SIMD parsing can rewrite its input. + if parsed.is_err() + && let Cow::Owned(text) = String::from_utf8_lossy(line) + { + line_bytes = text.into_bytes(); + parsed = + simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer); + } + + if let Ok(v) = parsed { result.push(v); } else if !ignore_errors { - warn!("invalid JSON at index: {}, content: {:?}", index, line); + warn!( + "invalid JSON at index: {}, content: {:?}", + index, + String::from_utf8_lossy(line) + ); return InvalidParameterSnafu { reason: format!("invalid JSON at index: {}", index), } @@ -1046,6 +1090,195 @@ mod tests { assert_eq!(a, "[{\"a\":1},{\"b\":2}]"); } + #[test] + fn test_json_invalid_utf8_retry() { + let expected = vec![ + json!({"message": "before"}).into(), + json!({"message": "bad\u{fffd}\u{fffd}\u{fffd}\u{7f}\u{7f}"}).into(), + json!({"message": "after"}).into(), + ]; + + for payload in [ + b"[{\"message\":\"before\"},{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"},{\"message\":\"after\"}]".as_slice(), + b"{\"message\":\"before\"}\n{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"}\n{\"message\":\"after\"}".as_slice(), + ] { + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + ContentType::json(), + Bytes::from_static(payload), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, expected); + } + } + } + + #[test] + fn test_json_invalid_utf8_retry_preserves_parse_errors() { + let cases = [ + ( + br#"{"message":"before"}{"message":"\uD800"}{"message":"after"}"#.as_slice(), + vec![json!({"message": "before"}).into()], + ), + ( + b"{\"message\":\"before\"}{\"message\":\"bad\xff\"}{\"broken\":}".as_slice(), + vec![ + json!({"message": "before"}).into(), + json!({"message": "bad\u{fffd}"}).into(), + ], + ), + ]; + + for (payload, expected) in cases { + for ignore_errors in [false, true] { + let result = extract_pipeline_value_by_content_type( + ContentType::json(), + Bytes::from_static(payload), + ignore_errors, + ); + if ignore_errors { + assert_eq!(result.unwrap(), expected); + } else { + assert!(matches!(result, Err(Error::ParseJson { .. }))); + } + } + } + } + + #[test] + fn test_json_invalid_utf8_retry_preserves_ignored_items() { + let payload = Bytes::from_static(b"0{\"message\":\"bad\xff\"}false{\"message\":\"after\"}"); + let result = + extract_pipeline_value_by_content_type(ContentType::json(), payload.clone(), false); + assert!(matches!(result, Err(Error::InvalidParameter { .. }))); + + let actual = + extract_pipeline_value_by_content_type(ContentType::json(), payload.clone(), true) + .unwrap(); + assert_eq!( + actual, + vec![ + json!({"message": "bad\u{fffd}"}).into(), + json!({"message": "after"}).into(), + ], + ); + } + + #[test] + fn test_ndjson_invalid_utf8_retry() { + for invalid_bytes in [1, 8192] { + let mut payload = b"\n{\"message\":\"before\"}\r\n\r\n{\"escaped\":\"line\\nquote\\\"slash\\\\\",\"message\":\"bad".to_vec(); + payload.extend(std::iter::repeat_n(0xff, invalid_bytes)); + payload.extend_from_slice(b"\"}\r\n{\"message\":\"after\"}"); + let payload = Bytes::from(payload); + let expected = vec![ + json!({"message": "before"}).into(), + json!({ + "escaped": "line\nquote\"slash\\", + "message": format!("bad{}", "\u{fffd}".repeat(invalid_bytes)), + }) + .into(), + json!({"message": "after"}).into(), + ]; + + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, expected); + } + } + } + + #[test] + fn test_ndjson_invalid_utf8_retry_preserves_parse_errors() { + let too_deep = format!("{}0{}", "[".repeat(1025), "]".repeat(1025)); + for bad_line in [ + br#"{"escaped":"line\n","broken":}"#.as_slice(), + b"{\"escaped\":\"line\\n\",\"message\":\"bad\xff\",\"broken\":}".as_slice(), + br#"{"escaped":"line\n","message":"\uDC00"}"#.as_slice(), + br#"{"message":"\uD800"}"#.as_slice(), + br#"{"value":1e4294967296}"#.as_slice(), + b"{\"value\":123\0}".as_slice(), + b"{\"message\":\"bad\xe2\x82".as_slice(), + too_deep.as_bytes(), + ] { + let mut payload = b"{\"message\":\"before\"}\n".to_vec(); + payload.extend_from_slice(bad_line); + payload.extend_from_slice(b"\n{\"message\":\"after\"}\n"); + let payload = Bytes::from(payload); + + for ignore_errors in [false, true] { + let result = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ); + if ignore_errors { + assert_eq!( + result.unwrap(), + vec![ + json!({"message": "before"}).into(), + json!({"message": "after"}).into(), + ], + ); + } else { + assert!(matches!( + result, + Err(Error::InvalidParameter { reason, .. }) + if reason.ends_with("at index: 1") + )); + } + } + } + } + + #[test] + fn test_ndjson_large_exponents() { + let payload = Bytes::from_static(br#"{"zero":0e99999999999,"underflow":1e-4294967295}"#); + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, vec![json!({"zero": 0.0, "underflow": 0.0}).into()]); + } + } + + #[test] + fn test_ndjson_empty_and_whitespace_lines() { + for ignore_errors in [false, true] { + for payload in [b"".as_slice(), b"\n\r\n".as_slice()] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + Bytes::from_static(payload), + ignore_errors, + ) + .unwrap(); + assert!(actual.is_empty()); + } + + for payload in [b"\r".as_slice(), b" \n".as_slice(), b"\r\r\n".as_slice()] { + let result = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + Bytes::from_static(payload), + ignore_errors, + ); + if ignore_errors { + assert!(result.unwrap().is_empty()); + } else { + assert!(matches!(result, Err(Error::InvalidParameter { .. }))); + } + } + } + } + #[test] fn test_extract_by_content() { let payload = r#" diff --git a/src/servers/src/query_handler.rs b/src/servers/src/query_handler.rs index d4b272de128..c58d6b3925e 100644 --- a/src/servers/src/query_handler.rs +++ b/src/servers/src/query_handler.rs @@ -40,7 +40,9 @@ use log_query::LogQuery; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; -use pipeline::{GreptimePipelineParams, Pipeline, PipelineInfo, PipelineVersion, PipelineWay}; +use pipeline::{ + GreptimePipelineParams, Pipeline, PipelineInfo, PipelineOptions, PipelineVersion, PipelineWay, +}; use serde_json::Value; use session::context::{QueryContext, QueryContextRef}; @@ -183,6 +185,9 @@ pub trait PipelineHandler { query_ctx: &QueryContext, ) -> std::result::Result>, catalog::error::Error>; + /// Returns the server's pipeline options. + fn pipeline_options(&self) -> &PipelineOptions; + //// Build a pipeline from a string. fn build_pipeline(&self, pipeline: &str) -> Result; diff --git a/src/standalone/Cargo.toml b/src/standalone/Cargo.toml index ac7d412c82a..fd5d5d217cd 100644 --- a/src/standalone/Cargo.toml +++ b/src/standalone/Cargo.toml @@ -32,6 +32,7 @@ frontend.workspace = true hostname.workspace = true log-store.workspace = true mito2.workspace = true +pipeline.workspace = true query.workspace = true serde.workspace = true servers.workspace = true @@ -40,3 +41,6 @@ store-api.workspace = true table.workspace = true tokio.workspace = true url.workspace = true + +[dev-dependencies] +toml.workspace = true diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs index bf1000fd584..e09464535bd 100644 --- a/src/standalone/src/options.rs +++ b/src/standalone/src/options.rs @@ -27,6 +27,7 @@ use frontend::service_config::{ PromStoreOptions, }; use mito2::config::MitoConfig; +use pipeline::PipelineOptions; use query::options::QueryOptions; use serde::{Deserialize, Serialize}; use servers::grpc::GrpcOptions; @@ -71,6 +72,7 @@ pub struct StandaloneOptions { pub slow_query: SlowQueryOptions, pub query: QueryOptions, pub memory: MemoryOptions, + pub pipeline: PipelineOptions, /// Environment variable keys to read and report in heartbeat messages. pub heartbeat_env_vars: Vec, } @@ -109,6 +111,7 @@ impl Default for StandaloneOptions { slow_query: SlowQueryOptions::default(), query: QueryOptions::default(), memory: MemoryOptions::default(), + pipeline: PipelineOptions::default(), heartbeat_env_vars: vec![], } } @@ -150,6 +153,7 @@ impl StandaloneOptions { logging: cloned_opts.logging, user_provider: cloned_opts.user_provider, slow_query: cloned_opts.slow_query, + pipeline: cloned_opts.pipeline, heartbeat_env_vars: cloned_opts.heartbeat_env_vars.clone(), ..Default::default() } @@ -183,3 +187,21 @@ impl StandaloneOptions { } } } + +#[cfg(test)] +mod tests { + use crate::options::StandaloneOptions; + + #[test] + fn test_pipeline_config_forwarding() { + let defaults: StandaloneOptions = toml::from_str("").unwrap(); + assert!(!defaults.pipeline.ignore_errors); + assert!(!defaults.frontend_options().pipeline.ignore_errors); + let options: StandaloneOptions = + toml::from_str("[pipeline]\nignore_errors = true").unwrap(); + assert!(options.frontend_options().pipeline.ignore_errors); + let serialized = toml::to_string(&options).unwrap(); + let restored: StandaloneOptions = toml::from_str(&serialized).unwrap(); + assert_eq!(options.pipeline, restored.pipeline); + } +} diff --git a/tests-integration/Cargo.toml b/tests-integration/Cargo.toml index f51badc8d61..03a6e07fe78 100644 --- a/tests-integration/Cargo.toml +++ b/tests-integration/Cargo.toml @@ -66,6 +66,7 @@ meta-srv = { workspace = true, features = ["mock"] } mito2 = { workspace = true, features = ["test-shared-fs-region-migration"] } object-store.workspace = true operator = { workspace = true, features = ["testing"] } +pipeline.workspace = true plugins.workspace = true prost.workspace = true query.workspace = true @@ -111,7 +112,6 @@ opentelemetry-proto.workspace = true otel-arrow-rust.workspace = true partition.workspace = true paste.workspace = true -pipeline.workspace = true prost.workspace = true rand.workspace = true rstest.workspace = true diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs index 74a15012071..ceda5068ea8 100644 --- a/tests-integration/src/standalone.rs +++ b/tests-integration/src/standalone.rs @@ -50,6 +50,7 @@ use frontend::instance::builder::FrontendBuilder; use frontend::instance::{Instance, StandaloneDatanodeManager}; use frontend::server::Services; use meta_srv::metasrv::{FLOW_ID_SEQ, TABLE_ID_SEQ}; +use pipeline::PipelineOptions; use servers::grpc::GrpcOptions; use snafu::ResultExt; use standalone::StandaloneRepartitionProcedureFactory; @@ -81,6 +82,7 @@ pub struct GreptimeDbStandaloneBuilder { plugin: Option, slow_query_options: SlowQueryOptions, auto_create_table: bool, + pipeline_options: PipelineOptions, } impl GreptimeDbStandaloneBuilder { @@ -99,6 +101,7 @@ impl GreptimeDbStandaloneBuilder { ..Default::default() }, auto_create_table: true, + pipeline_options: PipelineOptions::default(), } } @@ -108,6 +111,12 @@ impl GreptimeDbStandaloneBuilder { self } + #[must_use] + pub fn with_pipeline_options(mut self, pipeline_options: PipelineOptions) -> Self { + self.pipeline_options = pipeline_options; + self + } + #[must_use] pub fn with_default_store_type(self, store_type: StorageType) -> Self { Self { @@ -356,6 +365,7 @@ impl GreptimeDbStandaloneBuilder { grpc: GrpcOptions::default().with_server_addr("127.0.0.1:4001"), slow_query: self.slow_query_options.clone(), auto_create_table: self.auto_create_table, + pipeline: self.pipeline_options.clone(), ..StandaloneOptions::default() }; diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index c4c61ddb3f6..613e4d531f6 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -51,7 +51,6 @@ use opentelemetry_proto::tonic::collector::trace::v1::{ use pipeline::GREPTIME_INTERNAL_TRACE_PIPELINE_V1_NAME; use prost::Message; use serde_json::{Value, json}; -use servers::http::GreptimeQueryOutput; use servers::http::handler::HealthResponse; use servers::http::header::constants::{ GREPTIME_LOG_EXTRACT_KEYS_HEADER_NAME, GREPTIME_LOG_TABLE_NAME_HEADER_NAME, @@ -64,6 +63,7 @@ use servers::http::result::error_result::ErrorResponse; use servers::http::result::greptime_result_v1::GreptimedbV1Response; use servers::http::result::influxdb_result_v1::{InfluxdbOutput, InfluxdbV1Response}; use servers::http::test_helpers::{TestClient, TestResponse}; +use servers::http::{GreptimeQueryOutput, HttpOptions, HttpServerBuilder}; use servers::prom_store::{self, mock_timeseries_new_label}; use servers::request_memory_limiter::ServerMemoryLimiter; use standalone::options::StandaloneOptions; @@ -138,6 +138,7 @@ macro_rules! http_tests { test_pipeline_suffix_template, test_pipeline_context, test_pipeline_with_vrl, + test_pipeline_ignore_errors_config, test_pipeline_with_hint_vrl, test_pipeline_one_to_many_vrl, test_pipeline_2, @@ -1692,6 +1693,9 @@ allow_query_fallback = false [memory] enable_heap_profiling = true + +[pipeline] +ignore_errors = false "#, ) .trim() @@ -3716,6 +3720,129 @@ table_suffix: _${type} guard.remove_all().await; } +pub async fn test_pipeline_ignore_errors_config(storage_type: StorageType) { + let pipeline = "transform:\n - field: value\n type: int32\n"; + let data = "{\"value\":1}\ninvalid JSON\n{\"value\":2}\n"; + + for ignore_errors in [false, true] { + let mut instance = tests_integration::standalone::GreptimeDbStandaloneBuilder::new( + "test_pipeline_ignore_errors_config", + ) + .with_default_store_type(storage_type) + .with_pipeline_options(pipeline::PipelineOptions { ignore_errors }) + .build() + .await; + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_log_ingest_handler(instance.fe_instance().clone(), None, None) + .build(); + let client = TestClient::new(server.build(server.make_app()).unwrap()).await; + let response = client + .post("/v1/pipelines/ignore_errors") + .header("Content-Type", "application/x-yaml") + .body(pipeline) + .send() + .await; + assert_eq!(response.status(), StatusCode::OK); + + for request_override in [None, Some(false), Some(true)] { + let effective = request_override.unwrap_or(ignore_errors); + let query = request_override + .map(|value| format!("&ignore_errors={value}")) + .unwrap_or_default(); + let expected_status = if effective { + StatusCode::OK + } else { + StatusCode::BAD_REQUEST + }; + + for path in ["/v1/ingest", "/v1/events/logs"] { + let response = client + .post(&format!( + "{path}?table=logs&pipeline_name=ignore_errors{query}" + )) + .header("Content-Type", "application/x-ndjson") + .body(data) + .send() + .await; + assert_eq!(response.status(), expected_status); + if effective { + let body: Value = response.json().await; + assert_eq!(body["output"][0]["affectedrows"], 2); + } + } + + for (content_type, body) in [ + ("application/x-ndjson", data.to_string()), + ( + "application/json", + json!({ + "pipeline_name": "ignore_errors", + "data_type": "application/x-ndjson", + "data": data, + }) + .to_string(), + ), + ( + "application/json", + json!({ + "pipeline": pipeline, + "data_type": "application/x-ndjson", + "data": data, + }) + .to_string(), + ), + ] { + let response = client + .post(&format!( + "/v1/pipelines/_dryrun?pipeline_name=ignore_errors{query}" + )) + .header("Content-Type", content_type) + .body(body) + .send() + .await; + assert_eq!(response.status(), expected_status); + if effective { + let body: Value = response.json().await; + assert_eq!(body[0]["rows"].as_array().unwrap().len(), 2); + } + } + + let response = client + .post(&format!( + "/v1/ingest?table=timestamps&pipeline_name=greptime_identity\ + &custom_time_index=ts;epoch;s{query}" + )) + .header("Content-Type", "application/json") + .body(r#"{"ts":"invalid","value":1}"#) + .send() + .await; + assert_eq!( + response.status(), + if effective { + StatusCode::OK + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + ); + if effective { + let body: Value = response.json().await; + assert_eq!(body["output"][0]["affectedrows"], 1); + } + } + + // Parsing tolerance does not enable skipping pipeline execution errors. + let response = client + .post("/v1/ingest?table=logs&pipeline_name=ignore_errors&ignore_errors=true") + .header("Content-Type", "application/json") + .body(r#"{"value":"not an integer"}"#) + .send() + .await; + assert!(!response.status().is_success()); + + instance.guard.remove_all().await; + } +} + pub async fn test_pipeline_with_vrl(storage_type: StorageType) { common_telemetry::init_default_ut_logging(); let (app, mut guard) =