From a6e89863a04bcebed4621b95ba08d8f54fbb2493 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:24:44 -0600 Subject: [PATCH 1/3] perf(ingest): look up batch schema fields by name during validation fields_mismatch scanned the schema once per field of every row. A lookup table built once per batch replaces the scan; the first field of a name still wins. It runs for batches that leave the known-scalar fast path (arrays, nested values, new fields). Benchmark by the agent that wrote it (100 fields, 400 rows, release build): 67.5M -> 12.4M instructions per batch. A differential test compares the table with the previous scan, which is kept as a test-only oracle. Written by a GLM-5.3 agent; reviewed by Claude, not re-measured. Co-Authored-By: Claude Fable 5.2 --- src/event/format/json.rs | 193 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 184 insertions(+), 9 deletions(-) diff --git a/src/event/format/json.rs b/src/event/format/json.rs index 648e3ce7f..cec10ae1b 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -37,9 +37,7 @@ use tracing::{error, info_span}; use super::EventFormat; use super::{detect_schema_conflicts, rename_conflicting_fields_in_json}; -use crate::{ - handlers::TelemetryType, metadata::SchemaVersion, storage::StreamType, utils::arrow::get_field, -}; +use crate::{handlers::TelemetryType, metadata::SchemaVersion, storage::StreamType}; pub struct Event { pub json: Value, @@ -547,10 +545,18 @@ fn to_data_full( } }; - if let Some(mismatch) = value_arr - .iter() - .find_map(|value| fields_mismatch(&schema, value, schema_version, static_schema_flag)) - { + // One lookup table for the whole batch instead of a linear scan of the + // schema per field of every row. + let mut schema_by_name: HashMap<&str, &Field> = HashMap::with_capacity(schema.len()); + for field in &schema { + // The first field of a name wins, as in the scan this replaces + schema_by_name + .entry(field.name().as_str()) + .or_insert(field.as_ref()); + } + if let Some(mismatch) = value_arr.iter().find_map(|value| { + fields_mismatch(&schema_by_name, value, schema_version, static_schema_flag) + }) { return Err(anyhow!( "Could not process this event due to mismatch in datatype: {mismatch}" )); @@ -765,7 +771,7 @@ fn rename_json_keys(values: Vec) -> Result, anyhow::Error> { /// `reason` names the offending field and includes the expected vs. actual /// types so the caller can surface it in the error message. fn fields_mismatch( - schema: &[Arc], + schema: &HashMap<&str, &Field>, body: &Value, schema_version: SchemaVersion, static_schema_flag: bool, @@ -774,7 +780,7 @@ fn fields_mismatch( if val.is_null() { continue; } - let Some(field) = get_field(schema, name) else { + let Some(field) = schema.get(name.as_str()).copied() else { return Some(format!( "field '{name}' not present in stream schema (got {})", json_value_kind(val) @@ -791,6 +797,41 @@ fn fields_mismatch( None } +/// The schema scan `fields_mismatch` used before the per-batch lookup table, +/// kept as a differential oracle for tests and benchmarks. +#[cfg(test)] +pub(crate) mod fields_mismatch_legacy { + use super::*; + use crate::utils::arrow::get_field; + + pub fn fields_mismatch( + schema: &[Arc], + body: &Value, + schema_version: SchemaVersion, + static_schema_flag: bool, + ) -> Option { + for (name, val) in body.as_object().expect("body is of object variant") { + if val.is_null() { + continue; + } + let Some(field) = get_field(schema, name) else { + return Some(format!( + "field '{name}' not present in stream schema (got {})", + json_value_kind(val) + )); + }; + if !valid_type(field, val, schema_version, static_schema_flag) { + return Some(format!( + "field '{name}' expected {:?} but got {} value", + field.data_type(), + json_value_kind(val), + )); + } + } + None + } +} + fn json_value_kind(value: &Value) -> &'static str { match value { Value::Null => "null", @@ -2120,4 +2161,138 @@ mod partition_batching_tests { } } } + + // --- fields_mismatch lookup table (hunt-perf-glm) --- + + #[test] + fn fields_mismatch_lookup_table_matches_the_linear_scan() { + let schema: Vec> = [ + ("a", DataType::Utf8), + ("s", DataType::Utf8), + ("n", DataType::Int64), + ("u", DataType::UInt64), + ("f", DataType::Float64), + ("b", DataType::Boolean), + ( + "ts", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + ), + ("d", DataType::Date32), + ( + "lst", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + ), + ( + "st", + DataType::Struct(vec![Field::new("x", DataType::Utf8, true)].into()), + ), + ] + .into_iter() + .map(|(name, ty)| Arc::new(Field::new(name, ty, true))) + .collect(); + let by_name: HashMap<&str, &Field> = schema + .iter() + .map(|field| (field.name().as_str(), field.as_ref())) + .collect(); + + let rows = [ + json!({}), + json!({"a": "x", "n": 1, "b": true}), + json!({"missing": "x"}), + json!({"missing": null, "a": "x"}), + json!({"a": null}), + json!({"n": "x"}), + json!({"f": "not a number"}), + json!({"b": 1}), + json!({"ts": 1714557600000i64}), + json!({"ts": "2024-05-01T10:00:00Z"}), + json!({"d": "2024-05-01"}), + json!({"d": "nope"}), + json!({"lst": ["x", 1]}), + json!({"lst": ["x", null]}), + json!({"st": {"x": "y"}}), + json!({"st": {"x": 1}}), + json!({"st": {"missing": 1}}), + // the first mismatch stays the row's first offending field + json!({"n": "x", "a": 1, "b": 2}), + json!({"a": 1, "n": "x"}), + json!({"ünïcode": 1, "a": 1}), + ]; + for schema_version in [SchemaVersion::V0, SchemaVersion::V1] { + for static_schema_flag in [false, true] { + for row in &rows { + assert_eq!( + fields_mismatch(&by_name, row, schema_version, static_schema_flag), + fields_mismatch_legacy::fields_mismatch( + &schema, + row, + schema_version, + static_schema_flag + ), + "row {row} version {schema_version:?} static {static_schema_flag}" + ); + } + } + } + } + + /// The per-batch schema validation of `to_data_full`: a linear scan of + /// the schema per field of every row, against one lookup table per + /// batch, over a wide batch (100 fields, 400 rows). + #[ignore = "release-profile microbenchmark; select the section with HUNT_BENCH_SECTION"] + #[test] + fn bench_fields_mismatch() { + let iters: usize = std::env::var("HUNT_BENCH_ITERS") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(200); + let old = !matches!(std::env::var("HUNT_BENCH_SECTION").as_deref(), Ok("new")); + + let schema: Vec> = (0..100) + .map(|index| { + Arc::new(Field::new( + format!("field_{index:03}"), + DataType::Utf8, + true, + )) + }) + .collect(); + let rows: Vec = (0..400) + .map(|row| { + let mut object = serde_json::Map::new(); + for index in 0..100u32 { + object.insert( + format!("field_{index:03}"), + json!(format!("value {row}-{index}")), + ); + } + Value::Object(object) + }) + .collect(); + + let mut checksum = 0u64; + let start = std::time::Instant::now(); + for _ in 0..iters { + if old { + let mismatch = rows.iter().find_map(|row| { + fields_mismatch_legacy::fields_mismatch(&schema, row, SchemaVersion::V1, false) + }); + checksum = checksum.wrapping_add(u64::from(mismatch.is_some())); + } else { + let by_name: HashMap<&str, &Field> = schema + .iter() + .map(|field| (field.name().as_str(), field.as_ref())) + .collect(); + let mismatch = rows + .iter() + .find_map(|row| fields_mismatch(&by_name, row, SchemaVersion::V1, false)); + checksum = checksum.wrapping_add(u64::from(mismatch.is_some())); + } + } + let section = if old { "old" } else { "new" }; + println!( + "bench_fields_mismatch section={section} iters={iters} checksum={checksum} elapsed={:?}", + start.elapsed() + ); + } } From 2a1bd562488dde020244e65351d5c7912e989d33 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:24:44 -0600 Subject: [PATCH 2/3] perf(ingest): drop two per-request scans of stream metadata - ingest and post_event listed every internal stream of the tenant, locking each stream's metadata, to ask whether one named stream is internal. They now look up that stream. - The dataset field-count check built a sorted Schema to read its length. It now reads the length of the stored schema map. Benchmark by the agent that wrote the first change (64 streams, release build): 4,647 -> 539 instructions per request. The second is not measured on its own. First change written by a GLM-5.3 agent; reviewed by Claude, not re-measured. Co-Authored-By: Claude Fable 5.2 --- src/handlers/http/ingest.rs | 17 +- src/handlers/http/modal/utils/ingest_utils.rs | 171 +++++++++++++++++- src/parseable/streams.rs | 5 + 3 files changed, 186 insertions(+), 7 deletions(-) diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index ea8242371..a3468807e 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -75,8 +75,13 @@ pub async fn ingest( }; let stream_name = stream_name.to_owned(); let tenant_id = get_tenant_id_from_request(&req)?; - let internal_stream_names = PARSEABLE.streams.list_internal_streams(&tenant_id); - if internal_stream_names.contains(&stream_name) { + // One stream lookup answers the internal-stream question directly; building + // the tenant's list of internal stream names would lock every stream's + // metadata on every request. + if PARSEABLE + .get_stream(&stream_name, &tenant_id) + .is_ok_and(|stream| stream.get_stream_type() == StreamType::Internal) + { return Err(PostError::InternalStream(stream_name)); } @@ -386,8 +391,12 @@ pub async fn post_event( ) -> Result { let stream_name = logstream.into_inner(); let tenant_id = get_tenant_id_from_request(&req)?; - let internal_stream_names = PARSEABLE.streams.list_internal_streams(&tenant_id); - if internal_stream_names.contains(&stream_name) { + // One stream lookup instead of locking every stream of the tenant to list + // the internal stream names. + if PARSEABLE + .get_stream(&stream_name, &tenant_id) + .is_ok_and(|stream| stream.get_stream_type() == StreamType::Internal) + { return Err(PostError::InternalStream(stream_name)); } if !PARSEABLE.streams.contains(&stream_name, &tenant_id) { diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 1192f613c..33c8a7af4 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -628,9 +628,7 @@ fn verify_dataset_fields_count( ) -> Result<(), PostError> { let fields_count = PARSEABLE .get_stream(stream_name, tenant_id)? - .get_schema() - .fields() - .len(); + .get_schema_len(); let dataset_fields_warn_threshold = 0.8 * PARSEABLE.options.dataset_fields_allowed_limit as f64; // Check if the fields count exceeds the warn threshold if fields_count > dataset_fields_warn_threshold as usize { @@ -1044,4 +1042,171 @@ mod tests { assert_eq!(custom_fields.get(SOURCE_IP_KEY).unwrap(), "192.0.2.1"); } + + // Micro-benchmarks and equivalence proofs for the shared ingest path + // (hunt-perf-glm). The benches are `#[ignore]`d release-profile loops that + // construct the objects the handlers read, so they never touch `PARSEABLE` + // and are safe to run through a test-name filter. Each bench runs one of + // two sections per process, selected by `HUNT_BENCH_SECTION`: + // old - the per-request work before the change + // new - the per-request work after it + // Compare them under perf, e.g. + // HUNT_BENCH_SECTION=old sudo -n perf stat -e instructions:u \ + // bench_json_byte_size --exact --ignored --nocapture + mod request_overhead { + use std::sync::Arc; + use std::time::Instant; + + use crate::{ + cli::Options, + metadata::LogStreamMetadata, + parseable::{DEFAULT_TENANT, Stream, Streams}, + storage::StreamType, + }; + + fn bench_iters(default: usize) -> usize { + std::env::var("HUNT_BENCH_ITERS") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) + } + + fn bench_section_is_old() -> bool { + !matches!(std::env::var("HUNT_BENCH_SECTION").as_deref(), Ok("new")) + } + + fn bench_report(name: &str, old: bool, iters: usize, checksum: u64, start: Instant) { + let section = if old { "old" } else { "new" }; + println!( + "{name} section={section} iters={iters} checksum={checksum} elapsed={:?}", + start.elapsed() + ); + } + + // --- internal-stream check (ingest / post_event) --- + + /// The single-stream lookup `ingest` and `post_event` now perform, + /// mirroring `PARSEABLE.get_stream` minus the discarded error values. + fn single_stream_lookup(streams: &Streams, tenant: &Option, name: &str) -> bool { + let tenant = tenant.as_deref().unwrap_or(DEFAULT_TENANT); + streams + .read() + .expect("test map") + .get(tenant) + .and_then(|tenant_streams| tenant_streams.get(name)) + .cloned() + .is_some_and(|stream| stream.get_stream_type() == StreamType::Internal) + } + + #[test] + fn internal_stream_check_matches_the_internal_stream_list() { + let streams = Streams::default(); + let options = Arc::new(Options::default()); + let add = |tenant: &str, name: &str, stream_type: StreamType| { + let metadata = LogStreamMetadata { + stream_type, + ..Default::default() + }; + let stream = Stream::new( + options.clone(), + name, + metadata, + None, + &Some(tenant.to_owned()), + ); + streams + .write() + .expect("test map") + .entry(tenant.to_owned()) + .or_default() + .insert(name.to_owned(), stream); + }; + // Two tenants with internal and user-defined streams, one of them + // sharing a name across tenants, plus an unknown tenant. + for (tenant, name) in [ + ("tenant", "i1"), + ("tenant", "i2"), + ("tenant", "u1"), + ("tenant", "u2"), + ("other", "i1"), + ("other", "u1"), + ] { + let stream_type = if name.starts_with('i') { + StreamType::Internal + } else { + StreamType::UserDefined + }; + add(tenant, name, stream_type); + } + + for tenant in [ + None, + Some("tenant".to_owned()), + Some("other".to_owned()), + Some("missing".to_owned()), + ] { + for name in ["i1", "i2", "u1", "u2", "missing"] { + assert_eq!( + streams + .list_internal_streams(&tenant) + .contains(&name.to_owned()), + single_stream_lookup(&streams, &tenant, name), + "tenant {tenant:?} stream {name}" + ); + } + } + } + + /// Per-request internal-stream check of the plain JSON handlers: + /// listing every internal stream name of the tenant against looking up + /// only the named stream. + #[ignore = "release-profile microbenchmark; select the section with HUNT_BENCH_SECTION"] + #[test] + fn bench_internal_stream_check() { + let iters = bench_iters(200_000); + let old = bench_section_is_old(); + let streams = Streams::default(); + let options = Arc::new(Options::default()); + let tenant = Some("tenant".to_owned()); + for index in 0..64u32 { + let metadata = LogStreamMetadata { + stream_type: if index.is_multiple_of(16) { + StreamType::Internal + } else { + StreamType::UserDefined + }, + ..Default::default() + }; + let stream = Stream::new( + options.clone(), + format!("s{index}"), + metadata, + None, + &tenant, + ); + streams + .write() + .expect("test map") + .entry(tenant.clone().unwrap()) + .or_default() + .insert(format!("s{index}"), stream); + } + // The common case: an existing user-defined stream. + let needle = "s17".to_owned(); + + let mut checksum = 0u64; + let start = Instant::now(); + for _ in 0..iters { + if old { + checksum = checksum.wrapping_add(u64::from( + streams.list_internal_streams(&tenant).contains(&needle), + )); + } else { + checksum = checksum + .wrapping_add(u64::from(single_stream_lookup(&streams, &tenant, &needle))); + } + } + bench_report("bench_internal_stream_check", old, iters, checksum, start); + } + } } diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index d389a2131..d59376149 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -3338,6 +3338,11 @@ impl Stream { Arc::new(Schema::new(fields)) } + /// Field count of the stored schema, without sorting it into a `Schema` + pub fn get_schema_len(&self) -> usize { + self.metadata.read().expect(LOCK_EXPECT).schema.len() + } + pub fn get_schema_raw(&self) -> HashMap> { self.metadata.read().expect(LOCK_EXPECT).schema.clone() } From 9aec6397b789cdddeadada519b19fcaa276e9800 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:14:29 -0600 Subject: [PATCH 3/3] docs(ingest): drop a working-branch name from two test comments Co-Authored-By: Claude Fable 5.2 --- src/event/format/json.rs | 2 +- src/handlers/http/modal/utils/ingest_utils.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/event/format/json.rs b/src/event/format/json.rs index cec10ae1b..1aee7961b 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -2162,7 +2162,7 @@ mod partition_batching_tests { } } - // --- fields_mismatch lookup table (hunt-perf-glm) --- + // --- fields_mismatch lookup table --- #[test] fn fields_mismatch_lookup_table_matches_the_linear_scan() { diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 33c8a7af4..41d7e6aba 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -1043,8 +1043,8 @@ mod tests { assert_eq!(custom_fields.get(SOURCE_IP_KEY).unwrap(), "192.0.2.1"); } - // Micro-benchmarks and equivalence proofs for the shared ingest path - // (hunt-perf-glm). The benches are `#[ignore]`d release-profile loops that + // Micro-benchmarks and equivalence proofs for the shared ingest path. + // The benches are `#[ignore]`d release-profile loops that // construct the objects the handlers read, so they never touch `PARSEABLE` // and are safe to run through a test-name filter. Each bench runs one of // two sections per process, selected by `HUNT_BENCH_SECTION`: