Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(native): prepare JS events and encode batches through NAPI (#17938)

Valery Meleshkindbf3a4c3726d
diff --git a/packages/native/AGENTS.md b/packages/native/AGENTS.md
index 869869cd8c..71b8878994 100644
--- a/packages/native/AGENTS.md
+++ b/packages/native/AGENTS.md
@@ -3,8 +3,8 @@
## Purpose
- Rust native addon (napi-rs) loaded in-process by the worker as
- `@langfuse/native`. Currently a hello-world scaffold; see `README.md` for
- layout, commands, and how the addon ships in the worker image.
+ `@langfuse/native`. Exports telemetry, the startup probe, and the prepared-event
+ Native codec; see `README.md` for build and deployment layout.
## Maintenance Contract
@@ -23,6 +23,9 @@
mirrors dd-trace and the winston logger (`DD_*`, `LANGFUSE_LOG_*`).
- The worker calls `initTelemetry()` once in `worker/src/initialize.ts` and
imports functions from `@langfuse/native` directly; keep call sites few.
+- `PreparedEvent` snapshots finalized JS rows into owned Rust fields;
+ `encodeClickhouseEvents()` asynchronously encodes batches of those handles.
+ Keep column definitions in `src/native_schema.rs` and JS handles off worker threads.
## Verification
diff --git a/packages/native/Cargo.lock b/packages/native/Cargo.lock
index fe9600dfac..4fb532472b 100644
--- a/packages/native/Cargo.lock
+++ b/packages/native/Cargo.lock
@@ -603,8 +603,6 @@ dependencies = [
"napi-derive",
"proptest",
"rust_decimal",
- "serde",
- "serde_json",
"tracing",
"tracing-subscriber",
]
@@ -1130,7 +1128,6 @@ version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
- "indexmap",
"itoa",
"memchr",
"serde",
diff --git a/packages/native/Cargo.toml b/packages/native/Cargo.toml
index 5ca234f133..6c646c7bb7 100644
--- a/packages/native/Cargo.toml
+++ b/packages/native/Cargo.toml
@@ -10,10 +10,6 @@ publish = false
[lib]
crate-type = ["cdylib"]
-[[example]]
-name = "native_codec_test_driver"
-test = false
-
[dependencies]
bytes = "1"
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
@@ -24,8 +20,6 @@ metrics-exporter-dogstatsd = "0.9"
napi = { version = "3", default-features = false, features = ["napi9"] }
napi-derive = "3"
rust_decimal = { version = "1.37.2", default-features = false, features = ["std"] }
-serde = "1"
-serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
diff --git a/packages/native/examples/native_codec_test_driver.rs b/packages/native/examples/native_codec_test_driver.rs
deleted file mode 100644
index 6606257043..0000000000
--- a/packages/native/examples/native_codec_test_driver.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-//! Test driver used by the worker's TypeScript parity suite; not an addon export.
-
-#[allow(dead_code)]
-#[path = "../src/native_codec.rs"]
-mod native_codec;
-#[allow(dead_code)]
-#[path = "../src/native_schema.rs"]
-mod native_schema;
-
-use native_codec::encode_v4_native_blocks;
-use native_schema::PreparedEvent;
-use serde::Deserialize;
-use serde_json::{json, Value};
-use std::{env, fs, path::Path};
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct NativeCodecTestInput {
- rows: Vec<Value>,
- max_rows_per_block: usize,
-}
-
-fn main() {
- let input_path = env::var("LANGFUSE_NATIVE_TEST_INPUT")
- .expect("LANGFUSE_NATIVE_TEST_INPUT must point to the JSON input");
- let output_dir = env::var("LANGFUSE_NATIVE_TEST_OUTPUT")
- .expect("LANGFUSE_NATIVE_TEST_OUTPUT must point to an existing directory");
- let input: NativeCodecTestInput =
- serde_json::from_slice(&fs::read(&input_path).expect("read LANGFUSE_NATIVE_TEST_INPUT"))
- .expect("parse native codec test input");
- let prepared = input
- .rows
- .iter()
- .map(PreparedEvent::from_json)
- .collect::<Result<Vec<_>, _>>()
- .expect("prepare native codec test rows");
- let event_bytes = prepared
- .iter()
- .map(|row| row.event_bytes)
- .collect::<Vec<_>>();
- let blocks = encode_v4_native_blocks(&prepared, input.max_rows_per_block)
- .expect("encode native codec test rows");
- let mut native_payload = Vec::new();
- for block in blocks {
- native_payload.extend_from_slice(&block.bytes);
- }
-
- let output_dir = Path::new(&output_dir);
- fs::write(output_dir.join("native.bin"), native_payload).expect("write native.bin");
- let manifest = json!({
- "eventBytes": event_bytes,
- });
- fs::write(
- output_dir.join("manifest.json"),
- serde_json::to_vec(&manifest).expect("serialize manifest"),
- )
- .expect("write manifest.json");
-}
diff --git a/packages/native/index.d.ts b/packages/native/index.d.ts
index 2a0295473d..b05ebd253f 100644
--- a/packages/native/index.d.ts
+++ b/packages/native/index.d.ts
@@ -1,5 +1,25 @@
/* auto-generated by NAPI-RS */
/* eslint-disable */
+/** A snapshot of one finalized event row, retained until its JS handle and any encoder tasks drop it. */
+export declare class PreparedEvent {
+ /**
+ * Read a storage-ready row into owned Rust fields. JSON-valued String columns such as
+ * `model_parameters` must already be serialized by TypeScript; `event_bytes` must be supplied
+ * after overflow handling and accounting. This constructor never serializes the JS row.
+ */
+ constructor(row: object)
+ get ids(): PreparedEventIds
+ static columns(): Array<PreparedEventColumn>
+}
+
+/**
+ * Encode prepared event handles as Native blocks.
+ *
+ * The array is the batch merge point. Each handle already owns an immutable typed row, so the
+ * async task only clones its Arc and never reads or copies row fields.
+ */
+export declare function encodeClickhouseEvents(rows: PreparedEvent[], maxRowsPerBlock: number): Promise<NativeEventBlock[]>
+
/**
* Hello-world entry point. It proves that the worker can load and call the
* addon and that native code reports through the same telemetry as the rest
@@ -15,6 +35,31 @@ export declare function hello(source: string): void
*/
export declare function initTelemetry(options?: TelemetryOptions | undefined | null): void
+/**
+ * A complete ClickHouse Native request body and its row count.
+ *
+ * The buffer is created only after the async Rust encoder has finished. The JS transport can
+ * retain it for retries without retaining the input rows or any NAPI handles.
+ */
+export interface NativeEventBlock {
+ bytes: Buffer
+ rowCount: number
+}
+
+/** ClickHouse column metadata generated from the prepared-row schema. */
+export interface PreparedEventColumn {
+ name: string
+ columnType: string
+ usesDefault: boolean
+}
+
+/** Identifiers used by ingestion retry and drop logging. */
+export interface PreparedEventIds {
+ project_id: string
+ trace_id: string
+ id: string
+}
+
/**
* Overrides for [`init_telemetry`]. Everything left unset comes from the
* environment: `DD_DOGSTATSD_HOST` / `DD_AGENT_HOST` and `DD_DOGSTATSD_PORT`
diff --git a/packages/native/index.js b/packages/native/index.js
index 9ed5508d47..54be3a704c 100644
--- a/packages/native/index.js
+++ b/packages/native/index.js
@@ -700,5 +700,7 @@ if (!nativeBinding) {
}
module.exports = nativeBinding
+module.exports.PreparedEvent = nativeBinding.PreparedEvent
+module.exports.encodeClickhouseEvents = nativeBinding.encodeClickhouseEvents
module.exports.hello = nativeBinding.hello
module.exports.initTelemetry = nativeBinding.initTelemetry
diff --git a/packages/native/src/lib.rs b/packages/native/src/lib.rs
index 5231287d2d..77deac2783 100644
--- a/packages/native/src/lib.rs
+++ b/packages/native/src/lib.rs
@@ -6,18 +6,166 @@
//! values back for Node to record.
/// Rust-only encoder for prepared v4 `events_full` rows.
-// These modules are exercised by Rust tests until the ingestion transport calls them.
-#[allow(dead_code)]
pub mod native_codec;
-#[allow(dead_code)]
+mod native_js;
pub(crate) mod native_schema;
mod telemetry;
+use std::sync::Arc;
use std::time::Duration;
use napi::bindgen_prelude::*;
use napi_derive::napi;
+/// A complete ClickHouse Native request body and its row count.
+///
+/// The buffer is created only after the async Rust encoder has finished. The JS transport can
+/// retain it for retries without retaining the input rows or any NAPI handles.
+#[napi(object)]
+pub struct NativeEventBlock {
+ pub bytes: Buffer,
+ pub row_count: u32,
+}
+
+/// Identifiers used by ingestion retry and drop logging.
+#[napi(object)]
+pub struct PreparedEventIds {
+ #[napi(js_name = "project_id")]
+ pub project_id: String,
+ #[napi(js_name = "trace_id")]
+ pub trace_id: String,
+ pub id: String,
+}
+
+/// A snapshot of one finalized event row, retained until its JS handle and any encoder tasks drop it.
+#[napi]
+pub struct PreparedEvent {
+ row: Arc<native_schema::PreparedEventRow>,
+}
+
+#[napi]
+impl PreparedEvent {
+ /// Read a storage-ready row into owned Rust fields. JSON-valued String columns such as
+ /// `model_parameters` must already be serialized by TypeScript; `event_bytes` must be supplied
+ /// after overflow handling and accounting. This constructor never serializes the JS row.
+ #[napi(constructor, ts_args_type = "row: object")]
+ pub fn new(row: Unknown<'_>) -> Result<Self> {
+ let row = native_schema::PreparedEventRow::from_js(row)
+ .map_err(|error| Error::from_reason(format!("prepared event: {error}")))?;
+ Ok(Self { row: Arc::new(row) })
+ }
+
+ #[napi(getter)]
+ pub fn ids(&self) -> PreparedEventIds {
+ PreparedEventIds {
+ project_id: self.row.project_id.clone(),
+ trace_id: self.row.trace_id.clone(),
+ id: self.row.span_id.clone(),
+ }
+ }
+
+ #[napi]
+ pub fn columns() -> Vec<PreparedEventColumn> {
+ native_schema::PreparedEventRow::columns()
+ .into_iter()
+ .map(|(name, column_type, uses_default)| PreparedEventColumn {
+ name,
+ column_type,
+ uses_default,
+ })
+ .collect()
+ }
+}
+
+/// ClickHouse column metadata generated from the prepared-row schema.
+#[napi(object)]
+pub struct PreparedEventColumn {
+ pub name: String,
+ pub column_type: String,
+ pub uses_default: bool,
+}
+
+pub struct EncodeClickhouseEventsTask {
+ rows: Vec<Arc<native_schema::PreparedEventRow>>,
+ max_rows_per_block: usize,
+}
+
+impl Task for EncodeClickhouseEventsTask {
+ type Output = Vec<native_codec::EncodedBlock>;
+ type JsValue = Vec<NativeEventBlock>;
+
+ fn compute(&mut self) -> Result<Self::Output> {
+ native_codec::encode_v4_native_blocks(&self.rows, self.max_rows_per_block)
+ .map_err(Error::from_reason)
+ }
+
+ fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
+ output
+ .into_iter()
+ .map(|block| {
+ let row_count = u32::try_from(block.row_count)
+ .map_err(|_| Error::from_reason("Native block row count exceeds UInt32"))?;
+ // The encoder returns a fresh, uniquely owned allocation. Vec takes it over,
+ // then napi wraps the same memory in a JS Buffer whose GC finalizer frees it.
+ // This handoff does not copy the payload. If the runtime forbids external
+ // buffers, napi-rs copies it into Node-owned memory instead. Shared or sliced
+ // Bytes would not have the same no-copy guarantee when converted to Vec.
+ Ok(NativeEventBlock {
+ bytes: Buffer::from(Vec::from(block.bytes)),
+ row_count,
+ })
+ })
+ .collect()
+ }
+}
+
+fn checked_max_rows_per_block(value: f64) -> Result<usize> {
+ const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
+ if !value.is_finite() || value <= 0.0 || value.fract() != 0.0 {
+ return Err(Error::from_reason(
+ "maxRowsPerBlock must be a positive safe integer",
+ ));
+ }
+ if value > MAX_SAFE_INTEGER {
+ return Err(Error::from_reason(
+ "maxRowsPerBlock must be no greater than Number.MAX_SAFE_INTEGER",
+ ));
+ }
+ usize::try_from(value as u64)
+ .map_err(|_| Error::from_reason("maxRowsPerBlock does not fit in a native usize"))
+}
+
+/// Encode prepared event handles as Native blocks.
+///
+/// The array is the batch merge point. Each handle already owns an immutable typed row, so the
+/// async task only clones its Arc and never reads or copies row fields.
+#[napi(
+ ts_args_type = "rows: PreparedEvent[], maxRowsPerBlock: number",
+ ts_return_type = "Promise<NativeEventBlock[]>"
+)]
+pub fn encode_clickhouse_events(
+ rows: Array<'_>,
+ max_rows_per_block: f64,
+) -> Result<AsyncTask<EncodeClickhouseEventsTask>> {
+ let max_rows_per_block = checked_max_rows_per_block(max_rows_per_block)?;
+ let mut prepared_rows = Vec::with_capacity(rows.len() as usize);
+ // napi's Array is a JS handle with indexed access, not a Rust slice with an iterator.
+ // Retain each immutable Rust row for the background task before leaving the JS thread:
+ // Arc::clone increments a reference count without copying fields, and keeps the row alive
+ // even if Node collects its PreparedEvent wrapper. No JS handles enter the task.
+ for index in 0..rows.len() {
+ let event = rows
+ .get::<ClassInstance<'_, PreparedEvent>>(index)?
+ .ok_or_else(|| Error::from_reason(format!("missing row at index {index}")))?;
+ prepared_rows.push(Arc::clone(&event.row));
+ }
+
+ Ok(AsyncTask::new(EncodeClickhouseEventsTask {
+ rows: prepared_rows,
+ max_rows_per_block,
+ }))
+}
+
/// Overrides for [`init_telemetry`]. Everything left unset comes from the
/// environment: `DD_DOGSTATSD_HOST` / `DD_AGENT_HOST` and `DD_DOGSTATSD_PORT`
/// for the agent, `DD_ENV`, `DD_SERVICE`, `DD_VERSION`, `DD_TAGS` for global
diff --git a/packages/native/src/native_codec.rs b/packages/native/src/native_codec.rs
index ce5908a943..c7a214604c 100644
--- a/packages/native/src/native_codec.rs
+++ b/packages/native/src/native_codec.rs
@@ -1,13 +1,9 @@
//! Rust-only encoding for prepared v4 `events_full` rows.
//!
-//! `PreparedEvent::from_json` accepts the prepared `EventRecordInsertType` shape after
-//! observation-field overflow handling and before the writer's numeric Decimal clamp. Nested
-//! input/output payloads have already been serialized as strings. Native encoding then receives
-//! only typed, owned fields; the adapters below define the JSON conversion policy.
+//! Encoding receives typed, owned fields from the direct JS adapter in `native_js`.
-use std::borrow::Cow;
-use std::collections::BTreeMap;
use std::error::Error as StdError;
+use std::sync::Arc;
use bytes::Bytes;
use chrono::{DateTime, NaiveDateTime, Utc};
@@ -16,10 +12,8 @@ use clickhouse::native::encode::{Encode, ValueWriter};
use clickhouse::native::DataTypeNode;
use clickhouse_types::data_types::{DateTimePrecision, DecimalType};
use rust_decimal::{Decimal, RoundingStrategy};
-use serde::ser::{SerializeMap, Serializer}; // codespell:ignore ser
-use serde_json::Value;
-use crate::native_schema::{ColumnKind, DefaultPolicy, PreparedEvent};
+use crate::native_schema::PreparedEventRow;
const DECIMAL_SCALE: u32 = 12;
const DECIMAL_LIMIT: i128 = 1_000_000_000_000_000_000;
@@ -77,12 +71,10 @@ pub struct EncodedBlock {
/// Prepared rows already contain the defaults that production-prepared rows rely on when every
/// insertable column is listed in a Native block. Decimal values use the existing
/// Decimal(18,12) overflow policy and truncate toward zero at twelve fractional digits.
-/// `event_bytes` is the UTF-8 size of the compact Rust JSON serialization of the prepared row
-/// without the accounting field; it is intentionally a logical size metric and need not be
-/// byte-identical to JavaScript's JSON.stringify output. Preparation stores this value before
-/// applying typed decimal conversion or DEFAULT-backed field filling.
+/// Encoding preserves the prepared row's `event_bytes`. The NAPI adapter receives that value
+/// from TypeScript after overflow handling; it does not recompute accounting in Rust.
pub(crate) fn encode_v4_native_blocks(
- rows: &[PreparedEvent],
+ rows: &[Arc<PreparedEventRow>],
max_rows_per_block: usize,
) -> Result<Vec<EncodedBlock>, String> {
if max_rows_per_block == 0 {
@@ -100,47 +92,9 @@ pub(crate) fn encode_v4_native_blocks(
.collect()
}
-/// Compute the UTF-8 size of a prepared event's JSONEachRow representation without `event_bytes`.
-pub fn event_bytes(value: &Value) -> Result<u64, String> {
- let object = value
- .as_object()
- .ok_or_else(|| "event row must be a JSON object".to_owned())?;
- // Borrow the fields and discard serialized bytes immediately: accounting needs the length,
- // not a cloned row or a second payload buffer.
- let mut counter = ByteCounter(0);
- let mut serializer = serde_json::Serializer::new(&mut counter);
- let result = (|| -> Result<(), serde_json::Error> {
- let mut map = serializer.serialize_map(None)?;
- for (key, value) in object {
- if key != "event_bytes" {
- map.serialize_entry(key, value)?;
- }
- }
- map.end()
- })();
- result.map_err(|error| format!("failed to serialize event row: {error}"))?;
- Ok(counter.0)
-}
-
-struct ByteCounter(u64);
-
-impl std::io::Write for ByteCounter {
- fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
- self.0 = self
- .0
- .checked_add(bytes.len() as u64)
- .ok_or_else(|| std::io::Error::other("serialized event is too large"))?;
- Ok(bytes.len())
- }
-
- fn flush(&mut self) -> std::io::Result<()> {
- Ok(())
- }
-}
-
-fn encode_block(rows: &[PreparedEvent]) -> Result<Bytes, String> {
+fn encode_block(rows: &[Arc<PreparedEventRow>]) -> Result<Bytes, String> {
let mut builder = BlockBuilder::new();
- PreparedEvent::encode_into(&mut builder, rows)?;
+ PreparedEventRow::encode_arcs(&mut builder, rows)?;
builder
.build()
@@ -149,226 +103,24 @@ fn encode_block(rows: &[PreparedEvent]) -> Result<Bytes, String> {
.map_err(|error| error.to_string())
}
-/// Resolve values whose ClickHouse defaults would otherwise be bypassed by listing the column in
-/// the Native block. Ordinary columns stay borrowed from the input row; only synthesized defaults
-/// allocate a JSON value. This runs once at the JSON-to-typed preparation boundary.
-fn value_for<'a>(row: &'a Value, key: &str, default_policy: DefaultPolicy) -> Cow<'a, Value> {
- let explicit = row.get(key);
- if default_policy == DefaultPolicy::None {
- return explicit
- .map(Cow::Borrowed)
- .unwrap_or(Cow::Owned(Value::Null));
- }
- if let Some(value) = explicit.filter(|value| !value.is_null()) {
- return Cow::Borrowed(value);
- }
- // For example, omitted environment gets DEFAULT 'default' in JSONEachRow. Sending an empty
- // string in a Native column would instead persist that empty string and bypass the default.
- Cow::Owned(match default_policy {
- DefaultPolicy::Literal(value) => Value::String(value.to_owned()),
- DefaultPolicy::Metadata(key) => Value::String(metadata_value(row, key).unwrap_or_default()),
- DefaultPolicy::MetadataFallback(key, fallback) => Value::String(
- metadata_value(row, key)
- .filter(|value| !value.is_empty())
- .or_else(|| metadata_value(row, fallback))
- .unwrap_or_default(),
- ),
- DefaultPolicy::MetadataEquals(key, expected) => {
- Value::Bool(metadata_value(row, key).as_deref() == Some(expected))
- }
- DefaultPolicy::None => Value::Null,
- })
-}
-
-pub(crate) fn from_json_field<T: FromJson>(
- row: &Value,
- key: &str,
- default_policy: DefaultPolicy,
-) -> Result<T, String> {
- T::from_json(value_for(row, key, default_policy).as_ref())
- .map_err(|error| format!("{key}: {error}"))
-}
-
-fn metadata_value(row: &Value, name: &str) -> Option<String> {
- // Ingestion stores metadata as parallel arrays; default expressions look up the same pair.
- let names = row.get("metadata_names")?.as_array()?;
- let values = row.get("metadata_values")?.as_array()?;
- names.iter().zip(values).find_map(|(metadata_name, value)| {
- (metadata_name.as_str() == Some(name)).then(|| string_value(value))
- })
-}
-
-// Conversion is separate from wire encoding: upstream Encode implementations own nullable, array,
-// map, and primitive layouts, while these implementations define the prepared-row input policy.
-pub(crate) trait FromJson: Encode + Sized {
- const COLUMN_KIND: ColumnKind;
-
- fn from_json(value: &Value) -> Result<Self, String>;
-}
-
-impl FromJson for String {
- const COLUMN_KIND: ColumnKind = ColumnKind::String;
-
- fn from_json(value: &Value) -> Result<Self, String> {
- Ok(string_value(value))
- }
-}
-
-impl FromJson for bool {
- const COLUMN_KIND: ColumnKind = ColumnKind::Bool;
-
- fn from_json(value: &Value) -> Result<Self, String> {
- match value {
- Value::Null => Ok(false),
- Value::Bool(value) => Ok(*value),
- Value::Number(value) => value
- .as_f64()
- .filter(|value| value.is_finite())
- .map(|value| value != 0.0)
- .ok_or_else(|| "expected a finite boolean number".to_owned()),
- _ => Err(format!("expected boolean, got {value}")),
- }
- }
-}
-
-macro_rules! unsigned {
- ($(($type:ty, $kind:expr)),+ $(,)?) => {$(
- impl FromJson for $type {
- const COLUMN_KIND: ColumnKind = $kind;
-
- fn from_json(value: &Value) -> Result<Self, String> {
- <$type>::try_from(json_u64(Some(value), stringify!($type))?)
- .map_err(|_| format!("expected a {}", stringify!($type)))
- }
- }
- )+};
-}
-unsigned!(
- (u8, ColumnKind::UInt8),
- (u16, ColumnKind::UInt16),
- (u64, ColumnKind::UInt64),
-);
-
-impl FromJson for DateTime64Micros {
- const COLUMN_KIND: ColumnKind = ColumnKind::DateTime64;
-
- fn from_json(value: &Value) -> Result<Self, String> {
- parse_datetime_value(value, "datetime").map(Self)
- }
-}
-
-impl FromJson for Decimal64 {
- const COLUMN_KIND: ColumnKind = ColumnKind::Decimal;
-
- fn from_json(value: &Value) -> Result<Self, String> {
- parse_decimal_value(value, "decimal").map(Self)
- }
-}
-
-impl<T: FromJson> FromJson for Option<T> {
- const COLUMN_KIND: ColumnKind = match T::COLUMN_KIND {
- ColumnKind::String => ColumnKind::NullableString,
- ColumnKind::DateTime64 => ColumnKind::NullableDateTime64,
- ColumnKind::UInt16 => ColumnKind::NullableUInt16,
- _ => panic!("unsupported nullable events_full column type"),
- };
-
- fn from_json(value: &Value) -> Result<Self, String> {
- if value.is_null() {
- Ok(None)
- } else {
- T::from_json(value).map(Some)
- }
- }
-}
-
-impl<T: FromJson> FromJson for Vec<T> {
- const COLUMN_KIND: ColumnKind = match T::COLUMN_KIND {
- ColumnKind::String => ColumnKind::ArrayString,
- _ => panic!("unsupported array events_full column type"),
- };
-
- fn from_json(value: &Value) -> Result<Self, String> {
- match value {
- Value::Null => Ok(Vec::new()),
- Value::Array(values) => values.iter().map(T::from_json).collect(),
- _ => Err(format!("expected an array, got {value}")),
- }
- }
-}
-
-impl<T: FromJson> FromJson for BTreeMap<String, T> {
- const COLUMN_KIND: ColumnKind = match T::COLUMN_KIND {
- ColumnKind::String => ColumnKind::MapStringString,
- ColumnKind::UInt64 => ColumnKind::MapStringUInt64,
- ColumnKind::Decimal => ColumnKind::MapStringDecimal,
- _ => panic!("unsupported map events_full column type"),
- };
-
- fn from_json(value: &Value) -> Result<Self, String> {
- match value {
- Value::Null => Ok(BTreeMap::new()),
- Value::Object(values) => values
- .iter()
- .map(|(key, value)| Ok((key.clone(), T::from_json(value)?)))
- .collect(),
- _ => Err(format!("expected a map, got {value}")),
- }
- }
-}
-
-fn json_u64(value: Option<&Value>, type_name: &str) -> Result<u64, String> {
- // JSONEachRow inputs can represent whole numbers as either JSON integers or integral floats;
- // accept both forms while rejecting signs, fractions, and non-finite values for UInt columns.
- match value {
- None | Some(Value::Null) => Ok(0),
- Some(Value::Number(value)) => value
- .as_u64()
- .or_else(|| {
- value
- .as_f64()
- .filter(|number| number.is_finite() && *number >= 0.0 && number.fract() == 0.0)
- .and_then(|number| u64::try_from(number as u128).ok())
- })
- .ok_or_else(|| format!("expected a {type_name}")),
- Some(value) => Err(format!("expected a {type_name}, got {value}")),
- }
-}
-
/// Parse the UTC-only datetime values produced by the ingestion pipeline. A ClickHouse datetime
/// string without an offset is a UTC calendar value; an RFC3339 offset is normalized to that same
/// UTC instant. The project never interprets these values in the host's local timezone.
-fn parse_datetime_value(value: &Value, key: &str) -> Result<i64, String> {
- match value {
- Value::String(value) => {
- let normalized = if value.contains(' ') && !value.contains('T') {
- value.replacen(' ', "T", 1)
- } else {
- value.clone()
- };
- if let Ok(parsed) = DateTime::parse_from_rfc3339(&normalized) {
- return Ok(parsed.timestamp_micros());
- }
- let naive = NaiveDateTime::parse_from_str(&normalized, "%Y-%m-%dT%H:%M:%S%.f")
- .map_err(|error| {
- format!("{key} has invalid DateTime64 value {value:?}: {error}")
- })?;
- Ok(DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc).timestamp_micros())
- }
- _ => Err(format!("{key} must be a UTC timestamp string")),
- }
-}
-
-fn parse_decimal_value(value: &Value, key: &str) -> Result<i64, String> {
- let text = match value {
- Value::String(value) => value.as_str(),
- Value::Number(value) => return parse_decimal(&value.to_string(), key),
- _ => return Err(format!("{key} must be a decimal number or string")),
+pub(crate) fn parse_datetime_text(value: &str, key: &str) -> Result<i64, String> {
+ let normalized = if value.contains(' ') && !value.contains('T') {
+ value.replacen(' ', "T", 1)
+ } else {
+ value.to_owned()
};
- parse_decimal(text, key)
+ if let Ok(parsed) = DateTime::parse_from_rfc3339(&normalized) {
+ return Ok(parsed.timestamp_micros());
+ }
+ let naive = NaiveDateTime::parse_from_str(&normalized, "%Y-%m-%dT%H:%M:%S%.f")
+ .map_err(|error| format!("{key} has invalid DateTime64 value {value:?}: {error}"))?;
+ Ok(DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc).timestamp_micros())
}
-fn parse_decimal(value: &str, key: &str) -> Result<i64, String> {
+pub(crate) fn parse_decimal(value: &str, key: &str) -> Result<i64, String> {
let value = value.trim();
if value.is_empty() {
return Ok(0);
@@ -421,14 +173,6 @@ fn parse_decimal(value: &str, key: &str) -> Result<i64, String> {
i64::try_from(coefficient).map_err(|_| format!("{key} decimal is out of range"))
}
-fn string_value(value: &Value) -> String {
- match value {
- Value::String(value) => value.clone(),
- Value::Null => String::new(),
- value => serde_json::to_string(value).unwrap_or_default(),
- }
-}
-
#[cfg(test)]
#[path = "native_codec_tests.rs"]
mod tests;
diff --git a/packages/native/src/native_codec_tests.rs b/packages/native/src/native_codec_tests.rs
index 49bc32ad17..d680d87eca 100644
--- a/packages/native/src/native_codec_tests.rs
+++ b/packages/native/src/native_codec_tests.rs
@@ -1,80 +1,11 @@
use super::*;
-use crate::native_schema::{
- find_column, ColumnKind, DefaultPolicy, PreparedEvent, EVENTS_FULL_INSERT_COLUMNS,
-};
use proptest::prelude::*;
-use proptest::test_runner::{Config as ProptestConfig, TestRunner};
-use serde_json::json;
-use std::collections::BTreeSet;
-use std::io::Write;
-use std::process::{Command, Stdio};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-fn encode_json_rows(rows: &[Value], max_rows: usize) -> Result<Vec<EncodedBlock>, String> {
- let prepared = rows
- .iter()
- .map(PreparedEvent::from_json)
- .collect::<Result<Vec<_>, _>>()?;
- encode_v4_native_blocks(&prepared, max_rows)
-}
-
-fn row(input: &str, output: &str, event_bytes: Value) -> Value {
- json!({
- "project_id": "project",
- "trace_id": "trace",
- "span_id": "span",
- "start_time": "2026-07-22 00:00:00.000",
- "created_at": "2026-07-22 00:00:00.000",
- "updated_at": "2026-07-22 00:00:00.000",
- "event_ts": "2026-07-22 00:00:00.000",
- "input": input,
- "output": output,
- "metadata_names": ["source"],
- "metadata_values": ["API"],
- "provided_usage_details": {"input": 1},
- "usage_details": {"output": 2},
- "provided_cost_details": {"input": "0.000000000001"},
- "cost_details": {"output": 1.25},
- "event_bytes": event_bytes,
- })
-}
-
-#[test]
-fn event_bytes_excludes_the_accounting_field_and_counts_utf8() {
- let value = json!({"input": "🔥", "event_bytes": 123});
- assert_eq!(
- event_bytes(&value).expect("event bytes"),
- "{\"input\":\"🔥\"}".len() as u64
- );
- for payload in [
- json!({}),
- json!({"event_bytes": 99}),
- json!({"nested": [null, true, {"event_bytes": 7, "text": "\"\n\\🔥"}], "cost": 1e-13}),
- ] {
- let mut expected = payload.clone();
- expected.as_object_mut().unwrap().remove("event_bytes");
- assert_eq!(
- event_bytes(&payload).unwrap(),
- serde_json::to_vec(&expected).unwrap().len() as u64
- );
- }
-}
-
-#[test]
-fn zero_max_rows_per_block_is_rejected() {
- let error = match encode_json_rows(&[], 0) {
- Ok(_) => panic!("zero block size must fail"),
- Err(error) => error,
- };
- assert_eq!(error, "max_rows_per_block must be greater than zero");
-}
#[test]
fn decimal_parser_matches_clickhouse_scale_and_overflow_policy() {
assert_eq!(parse_decimal("1.25", "cost").unwrap(), 1_250_000_000_000);
- let precise_json_number: Value = serde_json::from_str("510407.65505697404").unwrap();
assert_eq!(
- parse_decimal_value(&precise_json_number, "cost").unwrap(),
+ parse_decimal("510407.65505697404", "cost").unwrap(),
510_407_655_056_974_040
);
assert_eq!(parse_decimal("0.0000000000001", "cost").unwrap(), 0);
@@ -93,267 +24,19 @@ fn decimal_parser_matches_clickhouse_scale_and_overflow_policy() {
assert_eq!(parse_decimal("1e2147483647", "cost").unwrap(), 0);
assert_eq!(parse_decimal("1e-2147483648", "cost").unwrap(), 0);
assert_eq!(parse_decimal("", "cost").unwrap(), 0);
- assert_eq!(u16::from_json(&json!(42.0)), Ok(42));
- assert!(u16::from_json(&json!(-1.0)).is_err());
+ assert!(parse_decimal("not-a-number", "cost").is_err());
}
#[test]
fn datetime_strings_are_explicitly_utc() {
- let naive = parse_datetime_value(&json!("2026-07-22 00:00:00.000"), "timestamp").unwrap();
- let utc = parse_datetime_value(&json!("2026-07-22T00:00:00.000Z"), "timestamp").unwrap();
- let offset =
- parse_datetime_value(&json!("2026-07-22T02:00:00.000+02:00"), "timestamp").unwrap();
+ let naive = parse_datetime_text("2026-07-22 00:00:00.000", "timestamp").unwrap();
+ let utc = parse_datetime_text("2026-07-22T00:00:00.000Z", "timestamp").unwrap();
+ let offset = parse_datetime_text("2026-07-22T02:00:00.000+02:00", "timestamp").unwrap();
assert_eq!(naive, utc);
assert_eq!(offset, utc);
}
-#[test]
-fn invalid_decimal_prevents_a_prepared_event_from_being_returned() {
- let mut value = row("input", "output", Value::Null);
- value["cost_details"] = json!({"output": "definitely-not-a-number"});
-
- let error = PreparedEvent::from_json(&value).expect_err("invalid decimal");
- assert!(error.contains("cost_details"));
- assert!(error.contains("invalid decimal"));
-}
-
-#[derive(Debug)]
-struct LiveColumn {
- name: String,
- column_type: String,
- default_kind: String,
-}
-
-fn live_events_full_schema() -> Option<Vec<LiveColumn>> {
- let output = match run_clickhouse_client(
- "SELECT name, type, default_kind FROM system.columns WHERE database = currentDatabase() AND table = 'events_full' ORDER BY position FORMAT JSONEachRow",
- &[],
- ) {
- Ok(output) => output,
- Err(error) => {
- if clickhouse_is_required() {
- panic!("ClickHouse schema introspection failed: {error}");
- }
- eprintln!("ClickHouse schema unavailable; skipping generated-row test: {error}");
- return None;
- }
- };
-
- output
- .split(|byte| *byte == b'\n')
- .filter(|line| !line.is_empty())
- .map(|line| {
- serde_json::from_slice::<Value>(line)
- .map_err(|error| format!("parse ClickHouse schema row: {error}"))
- .and_then(|value| {
- Ok(LiveColumn {
- name: value["name"]
- .as_str()
- .ok_or_else(|| "schema row has no column name".to_owned())?
- .to_owned(),
- column_type: value["type"]
- .as_str()
- .ok_or_else(|| "schema row has no column type".to_owned())?
- .to_owned(),
- default_kind: value["default_kind"]
- .as_str()
- .unwrap_or_default()
- .to_owned(),
- })
- })
- })
- .collect::<Result<Vec<_>, _>>()
- .map(Some)
- .unwrap_or_else(|error| panic!("invalid ClickHouse schema response: {error}"))
-}
-
-fn assert_live_schema_matches_codec(schema: &[LiveColumn]) {
- let actual_names = schema
- .iter()
- .filter(|column| !is_server_owned(column))
- .map(|column| column.name.clone())
- .collect::<BTreeSet<_>>();
- let expected_names = EVENTS_FULL_INSERT_COLUMNS
- .iter()
- .map(|column| column.name.to_owned())
- .collect::<BTreeSet<_>>();
- assert_eq!(
- actual_names, expected_names,
- "events_full insertable columns differ from the Native codec contract"
- );
-
- for column in schema.iter().filter(|column| !is_server_owned(column)) {
- let kind = ColumnKind::from_clickhouse_type(&column.column_type)
- .unwrap_or_else(|error| panic!("{}: {error}", column.name));
- let spec = find_column(&column.name).expect("column set checked above");
- assert_eq!(
- spec.kind, kind,
- "{} changed from {:?} to {}",
- column.name, spec.kind, column.column_type
- );
- if spec.default_policy != DefaultPolicy::None {
- assert_eq!(
- column.default_kind, "DEFAULT",
- "{} no longer has the DEFAULT expression required by the Native adapter",
- column.name
- );
- }
- }
-}
-
-fn is_server_owned(column: &LiveColumn) -> bool {
- matches!(column.default_kind.as_str(), "MATERIALIZED" | "ALIAS")
-}
-
-fn clickhouse_is_required() -> bool {
- std::env::var("LANGFUSE_NATIVE_FAIL_IF_CLICKHOUSE_UNAVAILABLE")
- .ok()
- .as_deref()
- == Some("1")
-}
-
-#[derive(Debug)]
-struct ClickhouseComparison {
- json_count: u64,
- native_count: u64,
- json_only: u64,
- native_only: u64,
- json_event_bytes: u64,
- native_event_bytes: u64,
-}
-
-fn clickhouse_server_round_trip(
- json_payload: &[u8],
- native_payload: &[u8],
-) -> Option<ClickhouseComparison> {
- let required = clickhouse_is_required();
- let suffix = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .expect("system clock")
- .as_nanos();
- let json_table = format!("native_codec_json_{}_{}", std::process::id(), suffix);
- let native_table = format!("native_codec_native_{}_{}", std::process::id(), suffix);
-
- let create_result = run_clickhouse_client(
- &format!(
- "CREATE TABLE {json_table} AS events_full ENGINE = Memory; CREATE TABLE {native_table} AS events_full ENGINE = Memory;"
- ),
- &[],
- );
- if let Err(error) = create_result {
- let _ = run_clickhouse_client(
- &format!("DROP TABLE IF EXISTS {json_table}; DROP TABLE IF EXISTS {native_table};"),
- &[],
- );
- if required {
- panic!("ClickHouse server parity test failed to create tables: {error}");
- }
- eprintln!("ClickHouse server unavailable; skipping parity test: {error}");
- return None;
- }
-
- let result: Result<ClickhouseComparison, String> = (|| {
- run_clickhouse_client(
- &format!("INSERT INTO {json_table} FORMAT JSONEachRow"),
- json_payload,
- )?;
- run_clickhouse_client(
- &format!("INSERT INTO {native_table} FORMAT Native"),
- native_payload,
- )?;
-
- let output = run_clickhouse_client(
- &format!(
- "SELECT (SELECT count() FROM {json_table}) AS json_count, (SELECT count() FROM {native_table}) AS native_count, (SELECT count() FROM (SELECT * EXCEPT (event_bytes, provided_usage_details, usage_details, provided_cost_details, cost_details), mapSort((k, v) -> k, provided_usage_details) AS provided_usage_details, mapSort((k, v) -> k, usage_details) AS usage_details, mapSort((k, v) -> k, provided_cost_details) AS provided_cost_details, mapSort((k, v) -> k, cost_details) AS cost_details FROM {json_table} EXCEPT ALL SELECT * EXCEPT (event_bytes, provided_usage_details, usage_details, provided_cost_details, cost_details), mapSort((k, v) -> k, provided_usage_details) AS provided_usage_details, mapSort((k, v) -> k, usage_details) AS usage_details, mapSort((k, v) -> k, provided_cost_details) AS provided_cost_details, mapSort((k, v) -> k, cost_details) AS cost_details FROM {native_table})) AS json_only, (SELECT count() FROM (SELECT * EXCEPT (event_bytes, provided_usage_details, usage_details, provided_cost_details, cost_details), mapSort((k, v) -> k, provided_usage_details) AS provided_usage_details, mapSort((k, v) -> k, usage_details) AS usage_details, mapSort((k, v) -> k, provided_cost_details) AS provided_cost_details, mapSort((k, v) -> k, cost_details) AS cost_details FROM {native_table} EXCEPT ALL SELECT * EXCEPT (event_bytes, provided_usage_details, usage_details, provided_cost_details, cost_details), mapSort((k, v) -> k, provided_usage_details) AS provided_usage_details, mapSort((k, v) -> k, usage_details) AS usage_details, mapSort((k, v) -> k, provided_cost_details) AS provided_cost_details, mapSort((k, v) -> k, cost_details) AS cost_details FROM {json_table})) AS native_only, (SELECT sum(event_bytes) FROM {json_table}) AS json_event_bytes, (SELECT sum(event_bytes) FROM {native_table}) AS native_event_bytes SETTINGS asterisk_include_materialized_columns=1, asterisk_include_alias_columns=1 FORMAT JSONEachRow"
- ),
- &[],
- )?;
- let line = output
- .split(|byte| *byte == b'\n')
- .find(|line| !line.is_empty())
- .ok_or_else(|| "ClickHouse comparison returned no rows".to_owned())?;
- let value: Value = serde_json::from_slice(line)
- .map_err(|error| format!("parse ClickHouse comparison: {error}"))?;
- let comparison = ClickhouseComparison {
- json_count: output_u64(&value["json_count"]),
- native_count: output_u64(&value["native_count"]),
- json_only: output_u64(&value["json_only"]),
- native_only: output_u64(&value["native_only"]),
- json_event_bytes: output_u64(&value["json_event_bytes"]),
- native_event_bytes: output_u64(&value["native_event_bytes"]),
- };
- Ok(comparison)
- })();
-
- let _ = run_clickhouse_client(
- &format!("DROP TABLE IF EXISTS {json_table}; DROP TABLE IF EXISTS {native_table};"),
- &[],
- );
-
- match result {
- Ok(comparison) => Some(comparison),
- Err(error) => panic!("ClickHouse server parity test failed: {error}"),
- }
-}
-
-fn run_clickhouse_client(query: &str, input: &[u8]) -> Result<Vec<u8>, String> {
- let binary =
- std::env::var("LANGFUSE_NATIVE_CLICKHOUSE_BIN").unwrap_or_else(|_| "clickhouse".to_owned());
- let host = std::env::var("LANGFUSE_NATIVE_CLICKHOUSE_HOST")
- .or_else(|_| std::env::var("CLICKHOUSE_HOST"))
- .unwrap_or_else(|_| "127.0.0.1".to_owned());
- let port = std::env::var("LANGFUSE_NATIVE_CLICKHOUSE_PORT")
- .or_else(|_| std::env::var("CLICKHOUSE_PORT"))
- .unwrap_or_else(|_| "9000".to_owned());
- let user = std::env::var("CLICKHOUSE_USER").unwrap_or_else(|_| "clickhouse".to_owned());
- let password = std::env::var("CLICKHOUSE_PASSWORD").unwrap_or_else(|_| "clickhouse".to_owned());
- let database = std::env::var("CLICKHOUSE_DB").unwrap_or_else(|_| "default".to_owned());
-
- let mut child = Command::new(&binary)
- .args([
- "client",
- "--host",
- &host,
- "--port",
- &port,
- "--user",
- &user,
- "--password",
- &password,
- "--database",
- &database,
- "--multiquery",
- "--query",
- query,
- ])
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .map_err(|error| format!("start {binary} client: {error}"))?;
- child
- .stdin
- .take()
- .expect("ClickHouse client stdin")
- .write_all(input)
- .map_err(|error| format!("write ClickHouse client input: {error}"))?;
- let output = child
- .wait_with_output()
- .map_err(|error| format!("wait for ClickHouse client: {error}"))?;
- if !output.status.success() {
- return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
- }
- Ok(output.stdout)
-}
-
-fn output_u64(value: &Value) -> u64 {
- value
- .as_u64()
- .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
- .expect("ClickHouse UInt64 output")
-}
-
proptest! {
#[test]
fn decimal_inputs_with_extreme_exponents_are_handled(
@@ -376,164 +59,3 @@ proptest! {
prop_assert_eq!(parse_decimal(&value, "cost").unwrap(), expected);
}
}
-
-// Derive wire-format properties from the live table, independently of the native field list.
-// The captured-traffic test in TypeScript separately exercises the production preparation path.
-fn generated_row_strategy(schema: &[LiveColumn]) -> BoxedStrategy<Value> {
- let fields = schema
- .iter()
- .filter(|column| !is_server_owned(column))
- .map(|column| {
- let name = column.name.clone();
- let kind = ColumnKind::from_clickhouse_type(&column.column_type).unwrap();
- let value = match name.as_str() {
- "type" => {
- prop::sample::select(vec![json!("SPAN"), json!("GENERATION"), json!("EVENT")])
- .boxed()
- }
- "level" => {
- prop::sample::select(vec![json!("DEFAULT"), json!("ERROR"), json!("WARNING")])
- .boxed()
- }
- "source" => Just(json!("API")).boxed(),
- _ => generated_value_strategy(kind),
- };
- (value, any::<bool>()).prop_map(move |(value, omit)| {
- let defaulted = find_column(&name).unwrap().default_policy != DefaultPolicy::None;
- (
- name.clone(),
- if omit && defaulted { None } else { Some(value) },
- )
- })
- })
- .collect::<Vec<_>>();
- fields
- .prop_map(|fields| {
- let mut object = fields
- .into_iter()
- .filter_map(|(name, value)| value.map(|v| (name, v)))
- .collect::<serde_json::Map<_, _>>();
- for prefix in [
- "metadata",
- "experiment_metadata",
- "experiment_item_metadata",
- ] {
- let values = object[&format!("{prefix}_values")].as_array().unwrap();
- let names = [
- "evaluator_id",
- "evaluation_rule_id",
- "job_configuration_id",
- "evaluator_test",
- ];
- object.insert(format!("{prefix}_names"), json!(&names[..values.len()]));
- }
- Value::Object(object)
- })
- .boxed()
-}
-
-fn generated_value_strategy(kind: ColumnKind) -> BoxedStrategy<Value> {
- let text = prop_oneof![
- prop::collection::vec(any::<char>(), 0..24)
- .prop_map(|chars| chars.into_iter().collect::<String>()),
- Just("true".to_owned()),
- Just(String::new()),
- ]
- .boxed();
- let datetime = (0i64..2_000_000_000, 0u32..1_000_000)
- .prop_map(|(seconds, micros)| {
- json!(DateTime::<Utc>::from_timestamp(seconds, micros * 1000)
- .unwrap()
- .format("%Y-%m-%d %H:%M:%S%.6f")
- .to_string())
- })
- .boxed();
- match kind {
- ColumnKind::String => text.prop_map(Value::String).boxed(),
- ColumnKind::NullableString => prop::option::of(text).prop_map(|v| json!(v)).boxed(),
- ColumnKind::DateTime64 => datetime,
- ColumnKind::NullableDateTime64 => prop_oneof![Just(Value::Null), datetime].boxed(),
- ColumnKind::NullableUInt16 => prop::option::of(any::<u16>())
- .prop_map(|v| json!(v))
- .boxed(),
- ColumnKind::Bool => any::<bool>().prop_map(|v| json!(v)).boxed(),
- ColumnKind::UInt8 => (0u8..=1).prop_map(|v| json!(v)).boxed(),
- ColumnKind::UInt16 => any::<u16>().prop_map(|v| json!(v)).boxed(),
- ColumnKind::UInt64 => (0u64..=9_007_199_254_740_991)
- .prop_map(|v| json!(v))
- .boxed(),
- ColumnKind::Decimal => (-999_999.0f64..999_999.0).prop_map(|v| json!(v)).boxed(),
- ColumnKind::ArrayString => prop::collection::vec(text, 0..=4)
- .prop_map(|v| json!(v))
- .boxed(),
- ColumnKind::MapStringString => prop::collection::btree_map(text.clone(), text, 0..=4)
- .prop_map(|v| json!(v))
- .boxed(),
- ColumnKind::MapStringUInt64 => {
- prop::collection::btree_map(text, 0u64..=9_007_199_254_740_991, 0..=4)
- .prop_map(|v| json!(v))
- .boxed()
- }
- ColumnKind::MapStringDecimal => {
- prop::collection::btree_map(text, -999_999.0f64..999_999.0, 0..=4)
- .prop_map(|v| json!(v))
- .boxed()
- }
- }
-}
-
-#[test]
-fn generated_prepared_rows_match_json_each_row_and_native() {
- let Some(schema) = live_events_full_schema() else {
- return;
- };
- assert_live_schema_matches_codec(&schema);
- let mut runner = TestRunner::new(ProptestConfig {
- cases: 32,
- ..ProptestConfig::default()
- });
- runner
- .run(
- &(
- prop::collection::vec(generated_row_strategy(&schema), 1..=8),
- 1usize..=8,
- ),
- |(rows, max_rows)| {
- let blocks = encode_json_rows(&rows, max_rows).map_err(TestCaseError::fail)?;
- prop_assert_eq!(blocks.len(), rows.len().div_ceil(max_rows));
- for (block, expected_rows) in blocks.iter().zip(rows.chunks(max_rows)) {
- prop_assert_eq!(block.row_count, expected_rows.len());
- }
- let native_payload = blocks
- .into_iter()
- .flat_map(|block| block.bytes)
- .collect::<Vec<_>>();
- let json_payload = rows
- .iter()
- .flat_map(|row| {
- let mut bytes = serde_json::to_vec(row).unwrap();
- bytes.push(b'\n');
- bytes
- })
- .collect::<Vec<_>>();
- let comparison = clickhouse_server_round_trip(&json_payload, &native_payload)
- .expect("schema introspection succeeded, so parity server is available");
- prop_assert_eq!(comparison.json_count, rows.len() as u64);
- prop_assert_eq!(comparison.native_count, rows.len() as u64);
- prop_assert_eq!(comparison.json_only, 0);
- prop_assert_eq!(comparison.native_only, 0);
- prop_assert_eq!(
- comparison.json_event_bytes,
- rows.iter()
- .map(|r| output_u64(&r["event_bytes"]))
- .sum::<u64>()
- );
- prop_assert_eq!(
- comparison.native_event_bytes,
- rows.iter().map(|r| event_bytes(r).unwrap()).sum::<u64>()
- );
- Ok(())
- },
- )
- .expect("generated prepared rows match JSONEachRow and Native");
-}
diff --git a/packages/native/src/native_js.rs b/packages/native/src/native_js.rs
new file mode 100644
index 0000000000..f9f41011ca
--- /dev/null
+++ b/packages/native/src/native_js.rs
@@ -0,0 +1,375 @@
+//! Direct reads of finalized JavaScript rows into Rust-owned schema fields.
+//! JS handles stay on the calling thread; only owned fields reach the async encoder.
+
+use crate::native_codec::{parse_datetime_text, parse_decimal, DateTime64Micros, Decimal64};
+use crate::native_schema::DefaultPolicy;
+use napi::bindgen_prelude::{Array, JsObjectValue, Object, Unknown};
+use napi::{JsNumber, JsValue};
+use std::collections::BTreeMap;
+
+/// Convert one schema field by reading its property directly from the JS object.
+///
+/// This is intentionally a small typed adapter rather than a generic serde bridge. It never
+/// enumerates unrelated row properties, so fields such as `toJSON` cannot affect the input, and
+/// it can reject unsafe JavaScript numbers before they are truncated into a Rust integer.
+pub(crate) fn from_js_field<T: FromJsValue>(
+ object: Object<'_>,
+ key: &str,
+ default_policy: DefaultPolicy,
+ metadata: &MetadataValues,
+) -> Result<T, String> {
+ let value = get_js_property(&object, key)?;
+ if is_missing(&value)? {
+ T::missing(default_policy, metadata).map_err(|error| format!("{key}: {error}"))
+ } else {
+ T::from_js(value).map_err(|error| format!("{key}: {error}"))
+ }
+}
+
+pub(crate) fn required_js_field<T: FromJsValue>(
+ object: Object<'_>,
+ key: &str,
+) -> Result<T, String> {
+ let value = get_js_property(&object, key)?;
+ if is_missing(&value)? {
+ return Err(format!(
+ "{key} must be supplied by the finalized TypeScript row"
+ ));
+ }
+ T::from_js(value).map_err(|error| format!("{key}: {error}"))
+}
+
+pub(crate) trait FromJsValue: Sized {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String>;
+
+ fn missing(policy: DefaultPolicy, metadata: &MetadataValues) -> Result<Self, String>;
+}
+
+fn get_js_property<'env>(object: &Object<'env>, key: &str) -> Result<Unknown<'env>, String> {
+ object
+ .get_named_property_unchecked(key)
+ .map_err(|error| format!("cannot read property {key}: {error}"))
+}
+
+/// Owned metadata arrays shared by metadata-backed defaults and the output columns.
+/// The optional vectors are taken into the prepared row after all defaulted columns are read.
+#[derive(Debug)]
+pub(crate) struct MetadataValues {
+ names: Vec<Option<String>>,
+ values: Vec<Option<String>>,
+}
+
+impl MetadataValues {
+ pub(crate) fn from_js(object: &Object<'_>) -> Result<Self, String> {
+ Ok(Self {
+ names: read_metadata_array(object, "metadata_names")?,
+ values: read_metadata_array(object, "metadata_values")?,
+ })
+ }
+
+ pub(crate) fn take_names(&mut self) -> Vec<String> {
+ std::mem::take(&mut self.names)
+ .into_iter()
+ .map(Option::unwrap_or_default)
+ .collect()
+ }
+
+ pub(crate) fn take_values(&mut self) -> Vec<String> {
+ std::mem::take(&mut self.values)
+ .into_iter()
+ .map(Option::unwrap_or_default)
+ .collect()
+ }
+
+ fn value(&self, name: &str) -> Result<Option<&str>, String> {
+ // Defaults use the first matching name and ignore unmatched trailing values.
+ for (metadata_name, metadata_value) in self.names.iter().zip(&self.values) {
+ let metadata_name = metadata_name
+ .as_deref()
+ .ok_or_else(|| "expected a string, got null or undefined".to_owned())?;
+ if metadata_name == name {
+ return metadata_value
+ .as_deref()
+ .map(Some)
+ .ok_or_else(|| "expected a string, got null or undefined".to_owned());
+ }
+ }
+ Ok(None)
+ }
+}
+
+fn read_metadata_array(object: &Object<'_>, key: &str) -> Result<Vec<Option<String>>, String> {
+ let value = get_js_property(object, key)?;
+ if is_missing(&value)? {
+ return Ok(Vec::new());
+ }
+ let array = js_array(value).map_err(|error| format!("{key}: {error}"))?;
+ (0..array.len())
+ .map(|index| {
+ let value = array
+ .get::<Unknown>(index)
+ .map_err(|error| error.to_string())?
+ .ok_or_else(|| format!("missing array element {index}"))?;
+ let value_type = value.get_type().map_err(|error| error.to_string())?;
+ let value = match value_type {
+ napi::ValueType::String => {
+ Some(unsafe { value.cast::<String>() }.map_err(|error| error.to_string())?)
+ }
+ napi::ValueType::Null | napi::ValueType::Undefined => None,
+ value_type => {
+ return Err(format!("expected a string, got {value_type:?}"));
+ }
+ };
+ Ok(value)
+ })
+ .collect::<Result<_, String>>()
+ .map_err(|error| format!("{key}: {error}"))
+}
+
+fn is_missing(value: &Unknown<'_>) -> Result<bool, String> {
+ Ok(matches!(
+ value.get_type().map_err(|error| error.to_string())?,
+ napi::ValueType::Null | napi::ValueType::Undefined
+ ))
+}
+
+impl FromJsValue for String {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ match value.get_type().map_err(|error| error.to_string())? {
+ napi::ValueType::String => {
+ unsafe { value.cast::<String>() }.map_err(|error| error.to_string())
+ }
+ napi::ValueType::Null | napi::ValueType::Undefined => Ok(String::new()),
+ value_type => Err(format!("expected a string, got {value_type:?}")),
+ }
+ }
+
+ fn missing(policy: DefaultPolicy, metadata: &MetadataValues) -> Result<Self, String> {
+ Ok(match policy {
+ DefaultPolicy::Literal(value) => value.to_owned(),
+ DefaultPolicy::Metadata(key) => metadata.value(key)?.unwrap_or_default().to_owned(),
+ DefaultPolicy::MetadataFallback(key, fallback) => {
+ let primary = metadata
+ .value(key)?
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned);
+ match primary {
+ Some(value) => value,
+ None => metadata
+ .value(fallback)?
+ .filter(|value| !value.is_empty())
+ .unwrap_or_default()
+ .to_owned(),
+ }
+ }
+ DefaultPolicy::MetadataEquals(_, _) | DefaultPolicy::None => String::new(),
+ })
+ }
+}
+
+impl FromJsValue for bool {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ match value.get_type().map_err(|error| error.to_string())? {
+ napi::ValueType::Boolean => {
+ unsafe { value.cast::<bool>() }.map_err(|error| error.to_string())
+ }
+ napi::ValueType::Number => {
+ let number = js_number(value)?;
+ if !number.is_finite() {
+ return Err("expected a finite boolean number".to_owned());
+ }
+ Ok(number != 0.0)
+ }
+ napi::ValueType::Null | napi::ValueType::Undefined => Ok(false),
+ value_type => Err(format!("expected a boolean, got {value_type:?}")),
+ }
+ }
+
+ fn missing(policy: DefaultPolicy, metadata: &MetadataValues) -> Result<Self, String> {
+ Ok(match policy {
+ DefaultPolicy::MetadataEquals(key, expected) => metadata.value(key)? == Some(expected),
+ _ => false,
+ })
+ }
+}
+
+macro_rules! unsigned_js_value {
+ ($($type:ty),+ $(,)?) => {
+ $(
+ impl FromJsValue for $type {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ let number = js_u64(value, stringify!($type))?;
+ <$type>::try_from(number)
+ .map_err(|_| format!("value does not fit in {}", stringify!($type)))
+ }
+
+ fn missing(
+ _policy: DefaultPolicy,
+ _metadata: &MetadataValues,
+ ) -> Result<Self, String> {
+ Ok(0)
+ }
+ }
+ )+
+ };
+}
+unsigned_js_value!(u8, u16, u64);
+
+impl FromJsValue for DateTime64Micros {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ let value_type = value.get_type().map_err(|error| error.to_string())?;
+ if value_type != napi::ValueType::String {
+ return Err(format!(
+ "expected a UTC timestamp string, got {value_type:?}"
+ ));
+ }
+ let value: String = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ parse_datetime_text(&value, "datetime").map(Self)
+ }
+
+ fn missing(_policy: DefaultPolicy, _metadata: &MetadataValues) -> Result<Self, String> {
+ Err("datetime is required".to_owned())
+ }
+}
+
+impl FromJsValue for Decimal64 {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ match value.get_type().map_err(|error| error.to_string())? {
+ napi::ValueType::String => {
+ let value: String = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ parse_decimal(&value, "decimal").map(Self)
+ }
+ napi::ValueType::Number => {
+ parse_decimal(&js_number(value)?.to_string(), "decimal").map(Self)
+ }
+ value_type => Err(format!(
+ "expected a decimal number or string, got {value_type:?}"
+ )),
+ }
+ }
+
+ fn missing(_policy: DefaultPolicy, _metadata: &MetadataValues) -> Result<Self, String> {
+ Err("decimal is required".to_owned())
+ }
+}
+
+impl<T: FromJsValue> FromJsValue for Option<T> {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ if is_missing(&value)? {
+ Ok(None)
+ } else {
+ T::from_js(value).map(Some)
+ }
+ }
+
+ fn missing(_policy: DefaultPolicy, _metadata: &MetadataValues) -> Result<Self, String> {
+ Ok(None)
+ }
+}
+
+impl<T: FromJsValue> FromJsValue for Vec<T> {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ if is_missing(&value)? {
+ return Ok(Vec::new());
+ }
+ let array = js_array(value)?;
+ (0..array.len())
+ .map(|index| {
+ let value = array
+ .get::<Unknown>(index)
+ .map_err(|error| error.to_string())?
+ .ok_or_else(|| format!("missing array element {index}"))?;
+ T::from_js(value)
+ })
+ .collect()
+ }
+
+ fn missing(_policy: DefaultPolicy, _metadata: &MetadataValues) -> Result<Self, String> {
+ Ok(Vec::new())
+ }
+}
+
+impl<T: FromJsValue> FromJsValue for BTreeMap<String, T> {
+ fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ if is_missing(&value)? {
+ return Ok(BTreeMap::new());
+ }
+ if value.get_type().map_err(|error| error.to_string())? != napi::ValueType::Object {
+ return Err("expected an object map".to_owned());
+ }
+ let object: Object<'_> = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ if object.is_array().map_err(|error| error.to_string())? {
+ return Err("expected an object map, got an array".to_owned());
+ }
+ let keys = object
+ .get_property_names()
+ .map_err(|error| error.to_string())?;
+ let length = keys
+ .get_array_length_unchecked()
+ .map_err(|error| error.to_string())?;
+ let mut result = BTreeMap::new();
+ for index in 0..length {
+ let key: String = keys.get_element(index).map_err(|error| error.to_string())?;
+ // JSONEachRow includes only own enumerable string keys.
+ if !object
+ .has_own_property(&key)
+ .map_err(|error| error.to_string())?
+ {
+ continue;
+ }
+ let value = get_js_property(&object, &key)?;
+ result.insert(key, T::from_js(value)?);
+ }
+ Ok(result)
+ }
+
+ fn missing(_policy: DefaultPolicy, _metadata: &MetadataValues) -> Result<Self, String> {
+ Ok(BTreeMap::new())
+ }
+}
+
+fn js_number(value: Unknown<'_>) -> Result<f64, String> {
+ let number: JsNumber = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ number.get_double().map_err(|error| error.to_string())
+}
+
+fn js_u64(value: Unknown<'_>, type_name: &str) -> Result<u64, String> {
+ match value.get_type().map_err(|error| error.to_string())? {
+ napi::ValueType::Number => {
+ const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
+ let js_number: JsNumber = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ let number = js_number.get_double().map_err(|error| error.to_string())?;
+ if !number.is_finite() || number < 0.0 || number.fract() != 0.0 {
+ return Err(format!("expected a non-negative integral {type_name}"));
+ }
+ if number <= MAX_SAFE_INTEGER {
+ return Ok(number as u64);
+ }
+ // TypeScript's JSONEachRow path serializes large integral Numbers using the
+ // shortest decimal representation (for example, 2**63 becomes
+ // `9223372036854776000`). Parse that scalar spelling rather than casting the
+ // binary float, which would silently change the value before ClickHouse sees it.
+ js_number
+ .coerce_to_string()
+ .map_err(|error| error.to_string())?
+ .into_utf8()
+ .map_err(|error| error.to_string())?
+ .as_str()
+ .map_err(|error| error.to_string())?
+ .parse::<u64>()
+ .map_err(|_| format!("expected a non-negative {type_name} below 2^64"))
+ }
+ value_type => Err(format!("expected a {type_name}, got {value_type:?}")),
+ }
+}
+
+fn js_array(value: Unknown<'_>) -> Result<Array<'_>, String> {
+ if value.get_type().map_err(|error| error.to_string())? != napi::ValueType::Object {
+ return Err("expected an array".to_owned());
+ }
+ let object: Object<'_> = unsafe { value.cast() }.map_err(|error| error.to_string())?;
+ if !object.is_array().map_err(|error| error.to_string())? {
+ return Err("expected an array".to_owned());
+ }
+ unsafe { value.cast() }.map_err(|error| error.to_string())
+}
diff --git a/packages/native/src/native_schema.rs b/packages/native/src/native_schema.rs
index 918be8a7a1..7cc21b0cbc 100644
--- a/packages/native/src/native_schema.rs
+++ b/packages/native/src/native_schema.rs
@@ -1,64 +1,13 @@
//! The insertable part of `events_full` and its prepared Rust row.
//!
//! The macro invocation below is the only per-column declaration. It drives the prepared row,
-//! the live-schema metadata, JSON conversion, and the typed Native column writes together.
+//! column type metadata, JS reads, and typed Native column writes.
use clickhouse::native::builder::BlockBuilder;
-use serde_json::Value;
+use clickhouse::native::encode::Encode;
+use napi::bindgen_prelude::{Object, Unknown};
-use crate::native_codec::{DateTime64Micros, Decimal64, FromJson};
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(crate) enum ColumnKind {
- String,
- DateTime64,
- NullableDateTime64,
- NullableString,
- NullableUInt16,
- Bool,
- UInt8,
- UInt16,
- UInt64,
- Decimal,
- ArrayString,
- MapStringString,
- MapStringUInt64,
- MapStringDecimal,
-}
-
-impl ColumnKind {
- /// Convert the type spelling returned by `system.columns` to the codec's logical type.
- #[cfg(test)]
- pub(crate) fn from_clickhouse_type(value: &str) -> Result<Self, String> {
- let normalized: String = value
- .chars()
- .filter(|character| !character.is_whitespace())
- .collect();
- match normalized.as_str() {
- "String" | "LowCardinality(String)" => Ok(Self::String),
- "DateTime64(6)" => Ok(Self::DateTime64),
- "Nullable(DateTime64(6))" => Ok(Self::NullableDateTime64),
- "Nullable(String)" | "Nullable(LowCardinality(String))" => Ok(Self::NullableString),
- "Nullable(UInt16)" => Ok(Self::NullableUInt16),
- "Bool" => Ok(Self::Bool),
- "UInt8" => Ok(Self::UInt8),
- "UInt16" => Ok(Self::UInt16),
- "UInt64" => Ok(Self::UInt64),
- "Decimal(18,12)" => Ok(Self::Decimal),
- "Array(String)" | "Array(LowCardinality(String))" => Ok(Self::ArrayString),
- "Map(String,String)" | "Map(LowCardinality(String),String)" => {
- Ok(Self::MapStringString)
- }
- "Map(String,UInt64)" | "Map(LowCardinality(String),UInt64)" => {
- Ok(Self::MapStringUInt64)
- }
- "Map(String,Decimal(18,12))" | "Map(LowCardinality(String),Decimal(18,12))" => {
- Ok(Self::MapStringDecimal)
- }
- _ => Err(format!("unsupported events_full column type {value:?}")),
- }
- }
-}
+use crate::native_codec::{DateTime64Micros, Decimal64};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DefaultPolicy {
@@ -69,13 +18,6 @@ pub(crate) enum DefaultPolicy {
MetadataEquals(&'static str, &'static str),
}
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(crate) struct ColumnSpec {
- pub(crate) name: &'static str,
- pub(crate) kind: ColumnKind,
- pub(crate) default_policy: DefaultPolicy,
-}
-
macro_rules! schema_column_name {
($field:ident) => {
stringify!($field)
@@ -85,29 +27,76 @@ macro_rules! schema_column_name {
};
}
-macro_rules! prepared_json_value {
+macro_rules! prepare_metadata_field {
+ (
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
+ $ty:ty,
+ $policy:expr,
+ metadata_names
+ ) => {
+ let $field = $metadata.take_names();
+ };
+ (
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
+ $ty:ty,
+ $policy:expr,
+ metadata_values
+ ) => {
+ let $field = $metadata.take_values();
+ };
+ (
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
+ $ty:ty,
+ $policy:expr $(, $source:ident)?
+ ) => {};
+}
+
+macro_rules! prepare_js_field {
(
- $value:ident,
- $event_bytes:ident,
- event_bytes $(as $name:literal)?,
+ $object:ident,
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
$ty:ty,
$policy:expr,
computed
) => {
- $event_bytes
+ let $field = crate::native_js::required_js_field::<$ty>(
+ $object,
+ schema_column_name!($field $(as $name)?),
+ )?;
};
(
- $value:ident,
- $event_bytes:ident,
+ $object:ident,
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
+ $ty:ty,
+ $policy:expr,
+ metadata_names
+ ) => {};
+ (
+ $object:ident,
+ $metadata:ident,
+ $field:ident $(as $name:literal)?,
+ $ty:ty,
+ $policy:expr,
+ metadata_values
+ ) => {};
+ (
+ $object:ident,
+ $metadata:ident,
$field:ident $(as $name:literal)?,
$ty:ty,
$policy:expr
) => {
- crate::native_codec::from_json_field::<$ty>(
- $value,
+ let $field = crate::native_js::from_js_field::<$ty>(
+ $object,
schema_column_name!($field $(as $name)?),
$policy,
- )?
+ &$metadata,
+ )?;
};
}
@@ -118,43 +107,66 @@ macro_rules! clickhouse_table_schema {
$field:ident $(as $name:literal)? : $ty:ty => $( @ $source:ident )? $policy:expr
),* $(,)?
) => {
- #[derive(Clone, Debug)]
- pub(crate) struct PreparedEvent {
+ #[derive(Debug)]
+ pub(crate) struct PreparedEventRow {
$(pub(crate) $field: $ty,)*
}
-pub(crate) const EVENTS_FULL_INSERT_COLUMNS: &[ColumnSpec] = &[
- $(ColumnSpec {
- name: schema_column_name!($field $(as $name)?),
- kind: <$ty as FromJson>::COLUMN_KIND,
- default_policy: $policy,
- },)*
- ];
-
- impl PreparedEvent {
- /// Convert one prepared ingestion object and compute accounting before typed defaults.
- pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
- // `event_bytes` describes the immutable prepared JSON row. In particular, it
- // intentionally sees raw decimal values and omitted DEFAULT-backed fields.
- let event_bytes = crate::native_codec::event_bytes(value)?;
-
+ impl PreparedEventRow {
+ /// Convert one finalized JavaScript row directly into owned Rust fields.
+ ///
+ /// The schema macro generates typed reads for the declared columns and ignores
+ /// unrelated properties. Only owned typed fields leave the NAPI call.
+ pub(crate) fn from_js(value: Unknown<'_>) -> Result<Self, String> {
+ let object: Object<'_> = match value.get_type().map_err(|error| error.to_string())? {
+ napi::ValueType::Object => unsafe { value.cast() }
+ .map_err(|error| error.to_string())?,
+ value_type => {
+ return Err(format!(
+ "prepared event must be an object, got {value_type:?}"
+ ));
+ }
+ };
+ let mut metadata = crate::native_js::MetadataValues::from_js(&object)?;
+ $(
+ prepare_js_field!(
+ object,
+ metadata,
+ $field $(as $name)?,
+ $ty,
+ $policy $(, $source)?
+ );
+ )*
+ $(
+ prepare_metadata_field!(
+ metadata,
+ $field $(as $name)?,
+ $ty,
+ $policy $(, $source)?
+ );
+ )*
Ok(Self {
$(
- $field: prepared_json_value!(
- value,
- event_bytes,
- $field $(as $name)?,
- $ty,
- $policy $(, $source)?
- ),
+ $field,
)*
})
}
- /// Write this row type through clickhouse-rs's typed `Encode` implementations.
- pub(crate) fn encode_into(
+ /// Return the insertable columns and their Native type names from this declaration.
+ pub(crate) fn columns() -> Vec<(String, String, bool)> {
+ vec![$(
+ (
+ schema_column_name!($field $(as $name)?).to_owned(),
+ <$ty as Encode>::produces().to_string(),
+ $policy != DefaultPolicy::None,
+ ),
+ )*]
+ }
+
+ /// Write shared prepared rows through clickhouse-rs's typed `Encode` implementations.
+ pub(crate) fn encode_arcs(
builder: &mut BlockBuilder,
- rows: &[Self],
+ rows: &[std::sync::Arc<Self>],
) -> Result<(), String> {
$(
let name = schema_column_name!($field $(as $name)?);
@@ -217,8 +229,8 @@ clickhouse_table_schema! {
telemetry_sdk_version: String => DefaultPolicy::None,
blob_storage_file_path: String => DefaultPolicy::None,
ingestion_api_key: String => DefaultPolicy::None,
- ingestion_sdk_name: String => DefaultPolicy::None,
- ingestion_sdk_version: String => DefaultPolicy::None,
+ ingestion_sdk_name: String => DefaultPolicy::Literal("unknown"),
+ ingestion_sdk_version: String => DefaultPolicy::Literal("unknown"),
event_type as "type": String => DefaultPolicy::None,
start_time: DateTime64Micros => DefaultPolicy::None,
created_at: DateTime64Micros => DefaultPolicy::None,
@@ -239,8 +251,8 @@ clickhouse_table_schema! {
tags: Vec<String> => DefaultPolicy::None,
tool_calls: Vec<String> => DefaultPolicy::None,
tool_call_names: Vec<String> => DefaultPolicy::None,
- metadata_names: Vec<String> => DefaultPolicy::None,
- metadata_values: Vec<String> => DefaultPolicy::None,
+ metadata_names: Vec<String> => @metadata_names DefaultPolicy::None,
+ metadata_values: Vec<String> => @metadata_values DefaultPolicy::None,
experiment_metadata_names: Vec<String> => DefaultPolicy::None,
experiment_metadata_values: Vec<String> => DefaultPolicy::None,
experiment_item_metadata_names: Vec<String> => DefaultPolicy::None,
@@ -253,10 +265,3 @@ clickhouse_table_schema! {
usage_pricing_tier_name: Option<String> => DefaultPolicy::None,
tool_definitions: std::collections::BTreeMap<String, String> => DefaultPolicy::None,
}
-
-#[cfg(test)]
-pub(crate) fn find_column(name: &str) -> Option<&'static ColumnSpec> {
- EVENTS_FULL_INSERT_COLUMNS
- .iter()
- .find(|column| column.name == name)
-}
diff --git a/worker/AGENTS.md b/worker/AGENTS.md
index 09c3590986..f4d81a8998 100644
--- a/worker/AGENTS.md
+++ b/worker/AGENTS.md
@@ -47,6 +47,9 @@
- Direct-event replay: `pnpm --filter worker run test:otel-replay` exercises the
production OTEL event phase with isolated ClickHouse tables. Setup and scope:
`src/features/otel-ingestion/README.md`.
+- Native codec checks: `pnpm --filter worker run test:native-codec` selects
+ `nativeCodec` suites. Build the addon first; the command requires ClickHouse
+ whenever the live parity suite is present.
## Shared Package Imports
diff --git a/worker/package.json b/worker/package.json
index 2adf23b298..1eba69a336 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -28,7 +28,7 @@
"refill-billing-event": "dotenv -e ../.env -- tsx src/scripts/refill-billing-event.ts",
"refill-queue-event": "dotenv -e ../.env -- tsx src/scripts/refillQueueEvent/index.ts",
"retry-monitor-bad-query-errors": "dotenv -e ../.env -- tsx src/scripts/retryMonitorBadQueryErrors.ts",
- "test:native-codec": "LANGFUSE_NATIVE_FAIL_IF_CLICKHOUSE_UNAVAILABLE=1 vitest run nativeCodec.integration",
+ "test:native-codec": "LANGFUSE_NATIVE_FAIL_IF_CLICKHOUSE_UNAVAILABLE=1 vitest run nativeCodec",
"test:otel-replay": "vitest run otelReplay"
},
"author": "[email protected]",
diff --git a/worker/src/__tests__/helpers/nativeCodecFixtures.ts b/worker/src/__tests__/helpers/nativeCodecFixtures.ts
deleted file mode 100644
index 64286fbd8a..0000000000
--- a/worker/src/__tests__/helpers/nativeCodecFixtures.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import { readFileSync, readdirSync } from "node:fs";
-import { resolve } from "node:path";
-import type { EventRecordInsertType } from "@langfuse/shared/src/server";
-import type { EventInput } from "../../services/IngestionService/index.js";
-
-// Read the existing trace captures and exercise production createEventRecord/writeEventRecord.
-// Model lookup responses are replayed from captures; no fixture JSON is copied into Rust.
-type JsonObject = Record<string, unknown>;
-const repoRoot = resolve(__dirname, "../../../..");
-
-const parseObject = (value: unknown): JsonObject => {
- if (value && typeof value === "object" && !Array.isArray(value)) {
- return value as JsonObject;
- }
- if (typeof value === "string") {
- try {
- const parsed: unknown = JSON.parse(value);
- return parseObject(parsed);
- } catch {
- return {};
- }
- }
- return {};
-};
-
-const numberMap = (value: unknown): Record<string, number> =>
- Object.fromEntries(
- Object.entries(parseObject(value)).flatMap(([key, item]) => {
- const number = typeof item === "number" ? item : Number(item);
- return Number.isFinite(number) ? [[key, number]] : [];
- }),
- );
-
-const stringArray = (value: unknown): string[] =>
- Array.isArray(value)
- ? value.filter((item): item is string => typeof item === "string")
- : [];
-
-const stringMap = (value: unknown): Record<string, string> =>
- Object.fromEntries(
- Object.entries(parseObject(value)).map(([key, item]) => [
- key,
- typeof item === "string" ? item : JSON.stringify(item),
- ]),
- );
-
-const optionalString = (value: unknown): string | undefined =>
- typeof value === "string" ? value : undefined;
-
-const mergeObjects = (...values: unknown[]): JsonObject =>
- Object.assign({}, ...values.map(parseObject));
-
-const fixtureDirectories = [
- resolve(repoRoot, "packages/shared/scripts/seeder/utils/framework-traces"),
- resolve(repoRoot, "worker/src/__tests__/chatml/framework-traces"),
-];
-
-const fixturePaths = fixtureDirectories
- .flatMap((directory) =>
- readdirSync(directory)
- .filter((name) =>
- directory.endsWith("chatml/framework-traces")
- ? name.endsWith(".trace.json")
- : name.endsWith(".json"),
- )
- .map((name) => resolve(directory, name)),
- )
- .sort();
-
-const eventInputFromCapture = (
- observation: JsonObject,
- trace: JsonObject,
-): EventInput => {
- const isRoot = observation.parentObservationId == null;
- const usageDetails = numberMap(observation.usageDetails);
- const costDetails = numberMap(observation.costDetails);
- const providedUsageDetails = numberMap(observation.providedUsageDetails);
- const providedCostDetails = numberMap(observation.providedCostDetails);
-
- return {
- projectId: String(observation.projectId ?? trace.projectId ?? "fixture"),
- traceId: String(observation.traceId ?? trace.id),
- spanId: String(observation.id),
- parentSpanId:
- typeof observation.parentObservationId === "string"
- ? observation.parentObservationId
- : undefined,
- startTimeISO: String(observation.startTime),
- endTimeISO: String(observation.endTime ?? observation.startTime),
- completionStartTime: optionalString(observation.completionStartTime),
- name: typeof observation.name === "string" ? observation.name : "",
- type: typeof observation.type === "string" ? observation.type : "SPAN",
- environment: String(
- observation.environment ?? trace.environment ?? "default",
- ),
- version:
- typeof observation.version === "string" ? observation.version : undefined,
- release: typeof trace.release === "string" ? trace.release : undefined,
- traceName: typeof trace.name === "string" ? trace.name : undefined,
- tags: Array.isArray(trace.tags)
- ? trace.tags.filter((tag): tag is string => typeof tag === "string")
- : [],
- public: trace.public === true,
- bookmarked: isRoot && trace.bookmarked === true,
- userId: typeof trace.userId === "string" ? trace.userId : undefined,
- sessionId:
- typeof trace.sessionId === "string" ? trace.sessionId : undefined,
- level:
- typeof observation.level === "string" ? observation.level : undefined,
- statusMessage:
- typeof observation.statusMessage === "string"
- ? observation.statusMessage
- : undefined,
- modelName:
- typeof observation.model === "string" ? observation.model : undefined,
- modelId: optionalString(observation.internalModelId),
- modelParameters:
- observation.modelParameters as EventInput["modelParameters"],
- providedUsageDetails:
- Object.keys(providedUsageDetails).length > 0
- ? providedUsageDetails
- : usageDetails,
- usageDetails,
- providedCostDetails:
- Object.keys(providedCostDetails).length > 0
- ? providedCostDetails
- : costDetails,
- costDetails,
- usagePricingTierId: optionalString(observation.usagePricingTierId),
- usagePricingTierName: optionalString(observation.usagePricingTierName),
- promptId: optionalString(observation.promptId),
- promptName: optionalString(observation.promptName),
- promptVersion:
- observation.promptVersion == null
- ? undefined
- : String(observation.promptVersion),
- toolDefinitions: stringMap(observation.toolDefinitions),
- toolCalls: stringArray(observation.toolCalls),
- toolCallNames: stringArray(observation.toolCallNames),
- input: observation.input as string | undefined,
- output: observation.output as string | undefined,
- metadata: mergeObjects(trace.metadata, observation.metadata),
- source: "API",
- ingestionApiKey: "",
- ingestionSdkName: "",
- ingestionSdkVersion: "",
- blobStorageFilePath: "fixtures",
- eventBytes: 0,
- };
-};
-
-export const capturedPreparedRows = async () => {
- const { IngestionService } =
- await import("../../services/IngestionService/index.js");
-
- const normalizedRows: EventRecordInsertType[] = [];
- const capturedGenerationUsage = new Map<
- string,
- Pick<
- EventRecordInsertType,
- | "model_id"
- | "usage_pricing_tier_id"
- | "usage_pricing_tier_name"
- | "usage_details"
- | "cost_details"
- >
- >();
- const writer = {
- addToQueue: (_table: unknown, record: EventRecordInsertType) => {
- normalizedRows.push(record);
- },
- };
- const service = new IngestionService(
- {} as never,
- {} as never,
- writer as never,
- {} as never,
- );
-
- // Avoid external model and prompt lookups while retaining the production method's field mapping.
- // Captured generation enrichment is replayed where the source trace already contains it.
- (service as any).getGenerationUsage = async ({
- observationRecord,
- }: {
- observationRecord: EventRecordInsertType;
- }) => ({
- usage_details: capturedGenerationUsage.get(observationRecord.id)
- ?.usage_details,
- cost_details: capturedGenerationUsage.get(observationRecord.id)
- ?.cost_details,
- internal_model_id: capturedGenerationUsage.get(observationRecord.id)
- ?.model_id,
- usage_pricing_tier_id: capturedGenerationUsage.get(observationRecord.id)
- ?.usage_pricing_tier_id,
- usage_pricing_tier_name: capturedGenerationUsage.get(observationRecord.id)
- ?.usage_pricing_tier_name,
- });
-
- for (const fixturePath of fixturePaths) {
- const fixture = JSON.parse(readFileSync(fixturePath, "utf8")) as {
- trace?: JsonObject;
- observations?: JsonObject[];
- };
- const trace = fixture.trace ?? {};
- for (const observation of fixture.observations ?? []) {
- const eventInput = eventInputFromCapture(observation, trace);
- capturedGenerationUsage.set(eventInput.spanId, {
- usage_details: eventInput.usageDetails ?? {},
- cost_details: eventInput.costDetails ?? {},
- model_id: eventInput.modelId,
- usage_pricing_tier_id: eventInput.usagePricingTierId,
- usage_pricing_tier_name: eventInput.usagePricingTierName,
- });
- const eventRecord = await service.createEventRecord(
- eventInput,
- `fixtures/${fixturePath.split("/").pop()}`,
- );
- await service.writeEventRecord(eventRecord);
- }
- }
-
- return normalizedRows;
-};
diff --git a/worker/src/__tests__/nativeCodec.integration.test.ts b/worker/src/__tests__/nativeCodec.integration.test.ts
deleted file mode 100644
index 229a373029..0000000000
--- a/worker/src/__tests__/nativeCodec.integration.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { execFileSync } from "node:child_process";
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { resolve } from "node:path";
-import { randomUUID } from "node:crypto";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-import {
- clickhouseClient,
- type ClickhouseClientType,
- type EventRecordInsertType,
-} from "@langfuse/shared/src/server";
-import { ClickhouseWriter, TableName } from "../services/ClickhouseWriter";
-import { capturedPreparedRows } from "./helpers/nativeCodecFixtures";
-
-type Row = Record<string, unknown>;
-type Column = { name: string; type: string; default_kind: string };
-type Manifest = {
- eventBytes: number[];
-};
-const nativeDir = resolve(__dirname, "../../../packages/native");
-
-// This suite is run explicitly by test:native-codec and CI. Ordinary worker tests need neither
-// cargo nor a Native-protocol client. The explicit run always fails if ClickHouse is unavailable.
-describe.runIf(
- process.env.LANGFUSE_NATIVE_FAIL_IF_CLICKHOUSE_UNAVAILABLE === "1",
-)("TypeScript and Rust Native ingestion parity", () => {
- let directory: string;
- let columns: Column[];
- const client = clickhouseClient();
-
- const query = (sql: string, input: Buffer = Buffer.alloc(0)) =>
- execFileSync(
- process.env.LANGFUSE_NATIVE_CLICKHOUSE_BIN ?? "clickhouse",
- [
- "client",
- "--host",
- process.env.LANGFUSE_NATIVE_CLICKHOUSE_HOST ?? "127.0.0.1",
- "--port",
- process.env.LANGFUSE_NATIVE_CLICKHOUSE_PORT ?? "9000",
- "--user",
- process.env.CLICKHOUSE_USER ?? "clickhouse",
- "--password",
- process.env.CLICKHOUSE_PASSWORD ?? "clickhouse",
- "--database",
- process.env.CLICKHOUSE_DB ?? "default",
- "--multiquery",
- "--query",
- sql,
- ],
- { input, maxBuffer: 16 * 1024 * 1024, timeout: 30_000 },
- );
-
- const encode = (rows: Row[], maxRowsPerBlock: number): Manifest => {
- const input = resolve(directory, "input.json");
- writeFileSync(input, JSON.stringify({ rows, maxRowsPerBlock }));
- execFileSync(
- "cargo",
- ["run", "--locked", "--example", "native_codec_test_driver"],
- {
- cwd: nativeDir,
- env: {
- ...process.env,
- LANGFUSE_NATIVE_TEST_INPUT: input,
- LANGFUSE_NATIVE_TEST_OUTPUT: directory,
- },
- timeout: 120_000,
- stdio: "pipe",
- },
- );
- return JSON.parse(
- readFileSync(resolve(directory, "manifest.json"), "utf8"),
- ) as Manifest;
- };
-
- beforeAll(async () => {
- query("SELECT 1");
- directory = mkdtempSync(resolve(tmpdir(), "native-codec-"));
- execFileSync("sh", ["scripts/prepare-clickhouse-rs.sh"], {
- cwd: nativeDir,
- timeout: 120_000,
- });
- columns = query(
- "SELECT name, type, default_kind FROM system.columns WHERE database=currentDatabase() AND table='events_full' ORDER BY position FORMAT JSONEachRow",
- )
- .toString()
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as Column);
- }, 120_000);
-
- afterAll(async () => {
- await client.close();
- if (directory) rmSync(directory, { recursive: true, force: true });
- });
-
- const compare = async (rows: Row[], maxRows: number) => {
- const suffix = randomUUID().replaceAll("-", "");
- const jsonTable = `native_codec_json_${suffix}`;
- const nativeTable = `native_codec_native_${suffix}`;
- const manifest = encode(rows, maxRows);
- let writer: ClickhouseWriter | undefined;
- let writerShutdown = false;
- try {
- query(
- `CREATE TABLE ${jsonTable} AS events_full ENGINE=Memory; CREATE TABLE ${nativeTable} AS events_full ENGINE=Memory`,
- );
- // Exercise production writer clamping and JSONEachRow serialization with the regular
- // writer settings while directing only EventsFull to the parity table.
- writer = ClickhouseWriter.getInstance({
- insert: async (params: Parameters<ClickhouseClientType["insert"]>[0]) =>
- client.insert({
- ...params,
- table:
- params.table === TableName.EventsFull ? jsonTable : params.table,
- }),
- } as ClickhouseClientType);
- for (const row of rows)
- writer.addToQueue(
- TableName.EventsFull,
- structuredClone(row) as EventRecordInsertType,
- );
- await writer.shutdown();
- writerShutdown = true;
- expect(writer.queue[TableName.EventsFull]).toHaveLength(0);
- query(
- `INSERT INTO ${nativeTable} FORMAT Native`,
- readFileSync(resolve(directory, "native.bin")),
- );
- // Compare typed values inside ClickHouse: preserve Decimal/UInt64 precision, duplicates,
- // defaults, materialized and alias columns. Map key order is not semantically meaningful.
- const maps = columns
- .filter((c) => c.type.startsWith("Map("))
- .map((c) => c.name);
- const projection = `* EXCEPT (event_bytes, ${maps.join(", ")}), ${maps.map((name) => `mapSort((k, v) -> k, ${name}) AS ${name}`).join(", ")}`;
- const select = (table: string) => `SELECT ${projection} FROM ${table}`;
- const result = JSON.parse(
- query(`SELECT
- (SELECT count() FROM ${jsonTable}) AS json_count,
- (SELECT count() FROM ${nativeTable}) AS native_count,
- (SELECT count() FROM (${select(jsonTable)} EXCEPT ALL ${select(nativeTable)})) AS json_only,
- (SELECT count() FROM (${select(nativeTable)} EXCEPT ALL ${select(jsonTable)})) AS native_only,
- (SELECT sum(event_bytes) FROM ${jsonTable}) AS json_bytes,
- (SELECT sum(event_bytes) FROM ${nativeTable}) AS native_bytes
- SETTINGS asterisk_include_materialized_columns=1, asterisk_include_alias_columns=1 FORMAT JSONEachRow`).toString(),
- ) as Record<string, string | number>;
- expect(Number(result.json_count)).toBe(rows.length);
- expect(Number(result.native_count)).toBe(rows.length);
- expect(Number(result.json_only)).toBe(0);
- expect(Number(result.native_only)).toBe(0);
- expect(BigInt(result.json_bytes)).toBe(
- rows.reduce((sum, row) => sum + BigInt(row.event_bytes as number), 0n),
- );
- expect(BigInt(result.native_bytes)).toBe(
- manifest.eventBytes.reduce((sum, bytes) => sum + BigInt(bytes), 0n),
- );
- } finally {
- try {
- if (writer && !writerShutdown) await writer.shutdown();
- } finally {
- query(
- `DROP TABLE IF EXISTS ${jsonTable}; DROP TABLE IF EXISTS ${nativeTable}`,
- );
- }
- }
- };
-
- it("compares captured traffic through production TS preparation and both writers", async () => {
- const rows = await capturedPreparedRows();
- expect(rows.length).toBeGreaterThan(0);
- // This capture has inferred costs despite explicitly provided zero costs.
- const enriched = rows.find(
- (row) => row.span_id === "0d8f5427-c91a-44c8-86c5-e12d806edd57",
- );
- expect(enriched?.provided_cost_details).toEqual({
- input: 0,
- output: 0,
- total: 0,
- });
- expect(enriched?.cost_details).toEqual({
- input: 0.00147,
- output: 0.0024,
- total: 0.00387,
- });
- await compare(rows, 16);
- }, 120_000);
-});
diff --git a/worker/src/__tests__/nativeCodec.unit.test.ts b/worker/src/__tests__/nativeCodec.unit.test.ts
new file mode 100644
index 0000000000..e5c173a14b
--- /dev/null
+++ b/worker/src/__tests__/nativeCodec.unit.test.ts
@@ -0,0 +1,258 @@
+import { describe, expect, it } from "vitest";
+import { PreparedEvent, encodeClickhouseEvents } from "@langfuse/native";
+import { createEvent } from "@langfuse/shared/src/server";
+import { prepareNativeEvent } from "../services/IngestionService/prepareNativeEvent";
+
+const preparedRow = () => ({
+ project_id: "native-boundary",
+ trace_id: "trace",
+ span_id: "span",
+ start_time: "2026-09-24 00:00:00.123456",
+ created_at: "2026-09-24 00:00:00.123456",
+ updated_at: "2026-09-24 00:00:00.123456",
+ event_ts: "2026-09-24 00:00:00.123456",
+ input: "🔥".repeat(1024),
+ event_bytes: 123,
+ tags: ["original"],
+ usage_details: { input: 42 },
+ cost_details: { input: 0.25 },
+ model_parameters: JSON.stringify({
+ temperature: 1,
+ nested: ["🔥", -0, 1e-7, 2 ** 63, null],
+ omitted: undefined,
+ }),
+});
+
+describe("Native codec NAPI boundary", () => {
+ it("prepares structured model parameters without mutating the TS row or double-encoding strings", async () => {
+ const serialized = '{"temperature":0.2,"nested":["🔥",null]}';
+ for (const [parameters, expected] of [
+ [
+ { temperature: 0.2, nested: ["🔥", null], omitted: undefined },
+ serialized,
+ ],
+ [serialized, serialized],
+ [null, ""],
+ [undefined, ""],
+ ] as const) {
+ const row = {
+ ...createEvent(preparedRow()),
+ model_parameters: parameters,
+ };
+ const original = structuredClone(row);
+
+ const prepared = prepareNativeEvent(row);
+ expect(row).toEqual(original);
+ expect(await encodeClickhouseEvents([prepared], 1)).toEqual(
+ await encodeClickhouseEvents(
+ [new PreparedEvent({ ...row, model_parameters: expected })],
+ 1,
+ ),
+ );
+ }
+ });
+
+ it("owns its snapshot before async encoding, without calling toJSON", async () => {
+ const row = preparedRow();
+ const original = structuredClone(row);
+ Object.assign(row, {
+ toJSON: () => {
+ throw new Error("the NAPI boundary must not serialize rows");
+ },
+ });
+
+ const prepared = new PreparedEvent(row);
+ const handles = Object.assign([prepared], {
+ toJSON: () => {
+ throw new Error("the NAPI boundary must not serialize the batch");
+ },
+ });
+ const pending = encodeClickhouseEvents(handles, 1);
+ row.input = "changed";
+ row.tags[0] = "changed";
+ row.usage_details.input = 99;
+ row.cost_details.input = 99;
+ row.event_bytes = 999;
+ row.model_parameters = "changed";
+ handles.length = 0;
+
+ const blocks = await pending;
+ const expected = await encodeClickhouseEvents(
+ [new PreparedEvent(original)],
+ 1,
+ );
+ expect(blocks).toEqual(expected);
+ expect(prepared.ids).toEqual({
+ project_id: original.project_id,
+ trace_id: original.trace_id,
+ id: original.span_id,
+ });
+ prepared.ids.id = "changed";
+ expect(prepared.ids.id).toBe(original.span_id);
+ expect(await encodeClickhouseEvents([prepared], 1)).toEqual(expected);
+ expect(Buffer.isBuffer(blocks[0].bytes)).toBe(true);
+ expect(blocks[0].bytes.length).toBeGreaterThan(0);
+ });
+
+ it("merges handles into one wire block while retaining the input handles", async () => {
+ const handles = [
+ new PreparedEvent(preparedRow()),
+ new PreparedEvent({ ...preparedRow(), span_id: "second" }),
+ ];
+ const [combined] = await encodeClickhouseEvents(handles, 2);
+ const separate = await encodeClickhouseEvents(handles, 1);
+ expect(combined.rowCount).toBe(2);
+ expect(separate.map((block) => block.rowCount)).toEqual([1, 1]);
+ // Batching writes the schema header once, instead of concatenating two complete blocks.
+ expect(combined.bytes.length).toBeLessThan(
+ separate.reduce((size, block) => size + block.bytes.length, 0),
+ );
+ expect(await encodeClickhouseEvents(handles, 2)).toEqual([combined]);
+ expect(await encodeClickhouseEvents([], 1)).toEqual([]);
+ });
+
+ it("reads metadata once and preserves metadata-backed defaults", async () => {
+ const names = [
+ "evaluator_id",
+ "evaluator_id",
+ "evaluation_rule_id",
+ "job_configuration_id",
+ "evaluator_test",
+ "evaluator_test",
+ ];
+ const values = ["first", "later", "", "fallback", "true", "false"];
+ const trackArrayReads = <T>(items: T[]) => {
+ const reads = items.map(() => 0);
+ const array = [...items];
+ items.forEach((item, index) => {
+ Object.defineProperty(array, index, {
+ configurable: true,
+ enumerable: true,
+ get: () => {
+ reads[index] += 1;
+ return item;
+ },
+ });
+ });
+ return { array, reads };
+ };
+ const trackedNames = trackArrayReads(names);
+ const trackedValues = trackArrayReads(values);
+ let namesReads = 0;
+ let valuesReads = 0;
+ const row = {
+ ...preparedRow(),
+ evaluator_id: null,
+ };
+ Object.defineProperties(row, {
+ metadata_names: {
+ enumerable: true,
+ get: () => {
+ namesReads += 1;
+ return trackedNames.array;
+ },
+ },
+ metadata_values: {
+ enumerable: true,
+ get: () => {
+ valuesReads += 1;
+ return trackedValues.array;
+ },
+ },
+ });
+
+ const prepared = new PreparedEvent(row);
+ expect({ namesReads, valuesReads }).toEqual({
+ namesReads: 1,
+ valuesReads: 1,
+ });
+ expect(trackedNames.reads).toEqual(names.map(() => 1));
+ expect(trackedValues.reads).toEqual(values.map(() => 1));
+ for (const nullishValue of [null, undefined]) {
+ expect(
+ () =>
+ new PreparedEvent({
+ ...preparedRow(),
+ metadata_names: ["evaluator_id"],
+ metadata_values: [nullishValue],
+ }),
+ ).toThrow("evaluator_id");
+ }
+ const metadataDefaults = await encodeClickhouseEvents([prepared], 1);
+ expect(metadataDefaults).toEqual(
+ await encodeClickhouseEvents(
+ [
+ new PreparedEvent({
+ ...preparedRow(),
+ metadata_names: names,
+ metadata_values: values,
+ evaluator_id: "first",
+ evaluation_rule_id: "fallback",
+ evaluator_execution_is_test: true,
+ }),
+ ],
+ 1,
+ ),
+ );
+
+ const overridden = new PreparedEvent({
+ ...preparedRow(),
+ metadata_names: names,
+ metadata_values: values,
+ evaluator_id: "explicit",
+ evaluation_rule_id: "explicit-rule",
+ evaluator_execution_is_test: false,
+ });
+ expect(await encodeClickhouseEvents([overridden], 1)).not.toEqual(
+ metadataDefaults,
+ );
+ });
+
+ it("reads only own enumerable map entries, including an own __proto__ key", async () => {
+ const ownEntries = Object.fromEntries([
+ ["input", 42],
+ ["__proto__", 7],
+ ]);
+ const usage = Object.create(
+ { inherited: 99 },
+ Object.getOwnPropertyDescriptors(ownEntries),
+ );
+ Object.defineProperty(usage, "hidden", { value: 100 });
+ usage[Symbol("symbol")] = 101;
+
+ expect(
+ await encodeClickhouseEvents(
+ [new PreparedEvent({ ...preparedRow(), usage_details: usage })],
+ 1,
+ ),
+ ).toEqual(
+ await encodeClickhouseEvents(
+ [new PreparedEvent({ ...preparedRow(), usage_details: ownEntries })],
+ 1,
+ ),
+ );
+ });
+
+ it.each([
+ ["prompt_version", 65_536],
+ ["prompt_version", 1.5],
+ ["is_deleted", 256],
+ ["event_bytes", -1],
+ ["event_bytes", 2 ** 64],
+ ["usage_details", { input: 1.5 }],
+ ["cost_details", { output: "not-a-number" }],
+ ])("rejects invalid %s during preparation", (field, value) => {
+ expect(
+ () => new PreparedEvent({ ...preparedRow(), [field]: value }),
+ ).toThrow(String(field));
+ });
+
+ it.each([0, -1, 1.5, NaN, Infinity])(
+ "rejects invalid JS block row limit %s",
+ async (maxRows) => {
+ await expect(async () =>
+ encodeClickhouseEvents([new PreparedEvent(preparedRow())], maxRows),
+ ).rejects.toThrow();
+ },
+ );
+});
diff --git a/worker/src/services/IngestionService/prepareNativeEvent.ts b/worker/src/services/IngestionService/prepareNativeEvent.ts
new file mode 100644
index 0000000000..c4c9ef9a20
--- /dev/null
+++ b/worker/src/services/IngestionService/prepareNativeEvent.ts
@@ -0,0 +1,21 @@
+import { PreparedEvent } from "@langfuse/native";
+import type { EventRecordInsertType } from "@langfuse/shared/src/server";
+
+/**
+ * Snapshot a row after overflow handling and byte accounting into Rust. Serialize model parameters
+ * for their ClickHouse String column; keep the caller's structured row available for evaluations.
+ */
+export function prepareNativeEvent(
+ record: Omit<EventRecordInsertType, "model_parameters"> & {
+ model_parameters?: unknown;
+ },
+): PreparedEvent {
+ return new PreparedEvent({
+ ...record,
+ model_parameters:
+ record.model_parameters == null ||
+ typeof record.model_parameters === "string"
+ ? record.model_parameters
+ : JSON.stringify(record.model_parameters),
+ });
+}