Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(capture-logs): add bytes_uncompressed field for per-row byte accounting (#59480)

Daniel Visca7c890ad91d8c
diff --git a/nodejs/src/logs-ingestion/log-record-avro.test.ts b/nodejs/src/logs-ingestion/log-record-avro.test.ts
index 4ab65929d09b..442983728057 100644
--- a/nodejs/src/logs-ingestion/log-record-avro.test.ts
+++ b/nodejs/src/logs-ingestion/log-record-avro.test.ts
@@ -99,6 +99,11 @@ const LOG_RECORD_SCHEMA = avro.parse(`{
"values": "string"
}],
"doc": "A map of custom string-valued attributes associated with the log."
+ },
+ {
+ "name": "bytes_uncompressed",
+ "type": ["null", "long"],
+ "doc": "Logical content size of the row (sum of byte lengths of string/map fields). Used by drop-rule accounting; does not include fixed-width numeric or timestamp fields."
}
]
}`)
@@ -209,6 +214,7 @@ describe('log-record-avro', () => {
instrumentation_scope: '[email protected]',
event_name: null,
attributes: { key: 'value1' },
+ bytes_uncompressed: 123,
},
{
uuid: 'test-uuid-2',
@@ -225,6 +231,7 @@ describe('log-record-avro', () => {
instrumentation_scope: '[email protected]',
event_name: null,
attributes: { key: 'value2' },
+ bytes_uncompressed: 456,
},
]
@@ -251,6 +258,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -260,6 +268,33 @@ describe('log-record-avro', () => {
expect(decoded).toEqual(records)
})
+ it('preserves bytes_uncompressed across encode/decode', async () => {
+ const records: LogRecord[] = [
+ {
+ uuid: 'with-bytes',
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: null,
+ observed_timestamp: null,
+ body: 'hello world',
+ severity_text: null,
+ severity_number: null,
+ service_name: null,
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ bytes_uncompressed: 789,
+ },
+ ]
+
+ const encoded = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', records)
+ const [_, __, decoded] = await decodeLogRecords(encoded)
+
+ expect(decoded[0].bytes_uncompressed).toBe(789)
+ })
+
it('rejects promise for invalid buffer', async () => {
const invalidBuffer = Buffer.from('not avro data')
@@ -386,6 +421,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -417,6 +453,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
{
uuid: 'test-uuid-2',
@@ -433,6 +470,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -469,6 +507,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -499,6 +538,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -534,6 +574,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: { note: '[email protected]' },
+ bytes_uncompressed: null,
},
]
@@ -565,6 +606,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: { note: '[email protected]' },
+ bytes_uncompressed: null,
},
]
@@ -600,6 +642,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -631,6 +674,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
{
uuid: 'test-uuid-2',
@@ -647,6 +691,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -677,6 +722,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
@@ -728,6 +774,7 @@ describe('log-record-avro', () => {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: null,
},
]
diff --git a/nodejs/src/logs-ingestion/log-record-avro.ts b/nodejs/src/logs-ingestion/log-record-avro.ts
index 44a7b58899d0..9a1dae498e80 100644
--- a/nodejs/src/logs-ingestion/log-record-avro.ts
+++ b/nodejs/src/logs-ingestion/log-record-avro.ts
@@ -42,6 +42,7 @@ export interface LogRecord {
instrumentation_scope: string | null
event_name: string | null
attributes: Record<string, string> | null
+ bytes_uncompressed?: number | null
}
export async function decodeLogRecords(buffer: Buffer): Promise<[avro.Type | undefined, string, LogRecord[]]> {
diff --git a/rust/capture-logs/src/avro_schema.rs b/rust/capture-logs/src/avro_schema.rs
index f848a8fa7b26..ce404391532f 100644
--- a/rust/capture-logs/src/avro_schema.rs
+++ b/rust/capture-logs/src/avro_schema.rs
@@ -85,6 +85,11 @@ pub const AVRO_SCHEMA: &str = r#"
"values": "string"
}],
"doc": "A map of custom string-valued attributes associated with the log."
+ },
+ {
+ "name": "bytes_uncompressed",
+ "type": ["null", "long"],
+ "doc": "Logical content size of the row (sum of byte lengths of string/map fields). Used by drop-rule accounting; does not include fixed-width numeric or timestamp fields."
}
]
}"#;
diff --git a/rust/capture-logs/src/endpoints/datadog.rs b/rust/capture-logs/src/endpoints/datadog.rs
index d579bd539e46..2fca92dbd521 100644
--- a/rust/capture-logs/src/endpoints/datadog.rs
+++ b/rust/capture-logs/src/endpoints/datadog.rs
@@ -240,25 +240,25 @@ pub fn datadog_log_to_kafka_row(
attributes.insert("$originalTimestamp".to_string(), original.to_rfc3339());
}
- (
- KafkaLogRow {
- uuid: Uuid::now_v7().to_string(),
- trace_id,
- span_id,
- trace_flags: 0,
- timestamp,
- observed_timestamp: Utc::now(),
- body: message.unwrap_or_default(),
- severity_text,
- severity_number,
- service_name: service.unwrap_or_default(),
- resource_attributes,
- instrumentation_scope,
- event_name,
- attributes,
- },
- was_overridden,
- )
+ let row = KafkaLogRow {
+ uuid: Uuid::now_v7().to_string(),
+ trace_id,
+ span_id,
+ trace_flags: 0,
+ timestamp,
+ observed_timestamp: Utc::now(),
+ body: message.unwrap_or_default(),
+ severity_text,
+ severity_number,
+ service_name: service.unwrap_or_default(),
+ resource_attributes,
+ instrumentation_scope,
+ event_name,
+ attributes,
+ bytes_uncompressed: None,
+ }
+ .with_computed_bytes();
+ (row, was_overridden)
}
#[derive(Deserialize, Debug)]
diff --git a/rust/capture-logs/src/log_record.rs b/rust/capture-logs/src/log_record.rs
index 089f126a80be..fa18f163a84a 100644
--- a/rust/capture-logs/src/log_record.rs
+++ b/rust/capture-logs/src/log_record.rs
@@ -38,9 +38,40 @@ pub struct KafkaLogRow {
pub instrumentation_scope: String,
pub event_name: String,
pub attributes: HashMap<String, String>,
+ pub bytes_uncompressed: Option<i64>,
+}
+
+/// Sum byte lengths of the row's string and map content. Fixed-width fields
+/// (timestamps, trace_flags, severity_number) are excluded — only variable-length
+/// payload is counted. Distinct from the Kafka header `bytes_uncompressed`, which
+/// is the raw HTTP body size for the whole batch.
+pub fn compute_kafka_log_row_bytes(row: &KafkaLogRow) -> i64 {
+ let mut total: usize = 0;
+ total = total.saturating_add(row.uuid.len());
+ total = total.saturating_add(row.trace_id.len());
+ total = total.saturating_add(row.span_id.len());
+ total = total.saturating_add(row.body.len());
+ total = total.saturating_add(row.severity_text.len());
+ total = total.saturating_add(row.service_name.len());
+ total = total.saturating_add(row.instrumentation_scope.len());
+ total = total.saturating_add(row.event_name.len());
+ for (k, v) in &row.resource_attributes {
+ total = total.saturating_add(k.len()).saturating_add(v.len());
+ }
+ for (k, v) in &row.attributes {
+ total = total.saturating_add(k.len()).saturating_add(v.len());
+ }
+ i64::try_from(total).unwrap_or(i64::MAX)
}
impl KafkaLogRow {
+ /// Set `bytes_uncompressed` from the row's variable-length content. Consuming
+ /// builder; the `mut self` is encapsulated and never escapes.
+ pub(crate) fn with_computed_bytes(mut self) -> Self {
+ self.bytes_uncompressed = Some(compute_kafka_log_row_bytes(&self));
+ self
+ }
+
pub fn new(
record: LogRecord,
resource: Option<Resource>,
@@ -129,7 +160,9 @@ impl KafkaLogRow {
event_name,
service_name,
attributes,
- };
+ bytes_uncompressed: None,
+ }
+ .with_computed_bytes();
debug!("log: {:?}", log_row);
Ok((log_row, was_overridden))
@@ -318,6 +351,107 @@ pub fn any_value_to_string(value: AnyValue) -> String {
#[cfg(test)]
mod tests {
use super::*;
+ use apache_avro::{Codec, Reader, Schema, Writer};
+
+ use crate::avro_schema::AVRO_SCHEMA;
+
+ fn sample_row() -> KafkaLogRow {
+ let mut resource_attributes = HashMap::new();
+ resource_attributes.insert("host.name".to_string(), "localhost".to_string());
+ let mut attributes = HashMap::new();
+ attributes.insert("k".to_string(), "v".to_string());
+ KafkaLogRow {
+ uuid: "uuid-1234".to_string(),
+ trace_id: "tid".to_string(),
+ span_id: "sid".to_string(),
+ trace_flags: 0,
+ timestamp: Utc::now(),
+ observed_timestamp: Utc::now(),
+ body: "hello".to_string(),
+ severity_text: "info".to_string(),
+ severity_number: 9,
+ service_name: "svc".to_string(),
+ resource_attributes,
+ instrumentation_scope: "scope@1".to_string(),
+ event_name: "evt".to_string(),
+ attributes,
+ bytes_uncompressed: None,
+ }
+ }
+
+ #[test]
+ fn test_compute_kafka_log_row_bytes_sums_string_and_map_lengths() {
+ let row = sample_row();
+ // string fields: uuid(9) + trace_id(3) + span_id(3) + body(5) + severity_text(4)
+ // + service_name(3) + instrumentation_scope(7) + event_name(3) = 37
+ // maps: resource_attributes "host.name"(9)+"localhost"(9)=18; attributes "k"(1)+"v"(1)=2
+ // total = 37 + 18 + 2 = 57
+ assert_eq!(compute_kafka_log_row_bytes(&row), 57);
+ }
+
+ #[test]
+ fn test_compute_kafka_log_row_bytes_excludes_fixed_width_fields() {
+ // Two rows differing only in fixed-width numeric/timestamp fields should compute
+ // identical bytes_uncompressed.
+ let mut a = sample_row();
+ a.trace_flags = 0;
+ a.severity_number = 1;
+ let mut b = sample_row();
+ b.trace_flags = u32::MAX;
+ b.severity_number = i32::MIN;
+ b.timestamp = a.timestamp + TimeDelta::days(1);
+ assert_eq!(
+ compute_kafka_log_row_bytes(&a),
+ compute_kafka_log_row_bytes(&b),
+ );
+ }
+
+ #[test]
+ fn test_bytes_uncompressed_serialises_into_avro_payload() {
+ // We don't deserialise back into KafkaLogRow because apache_avro's `from_value`
+ // can't resolve `["null", T]` unions into non-Option struct fields (the existing
+ // pattern used for body/attributes/etc.). Instead, decode to the raw Avro Value
+ // and assert the new field is present with the expected long.
+ use apache_avro::types::Value;
+
+ let mut row = sample_row();
+ row.bytes_uncompressed = Some(compute_kafka_log_row_bytes(&row));
+ let expected = row.bytes_uncompressed.unwrap();
+
+ let schema = Schema::parse_str(AVRO_SCHEMA).expect("schema parses");
+ let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null);
+ writer.append_ser(&row).expect("append_ser ok");
+ let payload = writer.into_inner().expect("flush ok");
+
+ let reader = Reader::new(payload.as_slice()).expect("reader ok");
+ let mut found_long: Option<i64> = None;
+ for value in reader {
+ let value = value.expect("decode ok");
+ if let Value::Record(fields) = value {
+ for (name, field_value) in fields {
+ if name == "bytes_uncompressed" {
+ if let Value::Union(_, inner) = field_value {
+ if let Value::Long(v) = *inner {
+ found_long = Some(v);
+ }
+ }
+ }
+ }
+ }
+ }
+ assert_eq!(found_long, Some(expected));
+ }
+
+ #[test]
+ fn test_new_populates_bytes_uncompressed() {
+ let log_record = LogRecord::default();
+ let (row, _) = KafkaLogRow::new(log_record, None, None).expect("ok");
+ assert!(row.bytes_uncompressed.is_some());
+ assert_eq!(
+ row.bytes_uncompressed.unwrap(),
+ compute_kafka_log_row_bytes(&row),
+ );
+ }
#[test]
fn test_override_timestamp_within_range_is_unchanged() {
diff --git a/rust/capture-logs/src/trace_record.rs b/rust/capture-logs/src/trace_record.rs
index 19dfc82ab4b7..97aa84e205d5 100644
--- a/rust/capture-logs/src/trace_record.rs
+++ b/rust/capture-logs/src/trace_record.rs
@@ -48,9 +48,47 @@ pub struct KafkaTraceRow {
pub dropped_links_count: i32,
pub status_code: i32,
pub status_message: String,
+ pub bytes_uncompressed: Option<i64>,
+}
+
+/// Sum byte lengths of the row's string, map, and array content. Fixed-width
+/// fields (timestamps, kind, flags, status_code, dropped_*_count) are excluded —
+/// only variable-length payload is counted. Distinct from the Kafka header
+/// `bytes_uncompressed`, which is the raw HTTP body size for the whole batch.
+pub fn compute_kafka_trace_row_bytes(row: &KafkaTraceRow) -> i64 {
+ let mut total: usize = 0;
+ total = total.saturating_add(row.uuid.len());
+ total = total.saturating_add(row.trace_id.len());
+ total = total.saturating_add(row.span_id.len());
+ total = total.saturating_add(row.parent_span_id.len());
+ total = total.saturating_add(row.trace_state.len());
+ total = total.saturating_add(row.name.len());
+ total = total.saturating_add(row.service_name.len());
+ total = total.saturating_add(row.instrumentation_scope.len());
+ total = total.saturating_add(row.status_message.len());
+ for (k, v) in &row.resource_attributes {
+ total = total.saturating_add(k.len()).saturating_add(v.len());
+ }
+ for (k, v) in &row.attributes {
+ total = total.saturating_add(k.len()).saturating_add(v.len());
+ }
+ for event in &row.events {
+ total = total.saturating_add(event.len());
+ }
+ for link in &row.links {
+ total = total.saturating_add(link.len());
+ }
+ i64::try_from(total).unwrap_or(i64::MAX)
}
impl KafkaTraceRow {
+ /// Set `bytes_uncompressed` from the row's variable-length content. Consuming
+ /// builder; the `mut self` is encapsulated and never escapes.
+ fn with_computed_bytes(mut self) -> Self {
+ self.bytes_uncompressed = Some(compute_kafka_trace_row_bytes(&self));
+ self
+ }
+
pub fn new(
span: Span,
resource: Option<Resource>,
@@ -184,7 +222,9 @@ impl KafkaTraceRow {
dropped_links_count: span.dropped_links_count as i32,
status_code,
status_message,
- };
+ bytes_uncompressed: None,
+ }
+ .with_computed_bytes();
debug!("trace span: {:?}", row);
Ok((row, was_overridden))
@@ -208,12 +248,15 @@ fn extract_string_from_resource(attributes: &HashMap<String, String>, key: &str)
#[cfg(test)]
mod tests {
use super::*;
+ use apache_avro::{Codec, Reader, Schema, Writer};
use chrono::{TimeDelta, Utc};
use opentelemetry_proto::tonic::{
common::v1::{any_value, AnyValue, KeyValue},
trace::v1::{span::Event, span::Link, Span, Status},
};
+ use crate::traces_avro_schema::TRACES_AVRO_SCHEMA;
+
fn make_span() -> Span {
let now_nanos = Utc::now().timestamp_nanos_opt().unwrap() as u64;
Span {
@@ -244,6 +287,87 @@ mod tests {
}
}
+ #[test]
+ fn test_compute_kafka_trace_row_bytes_sums_string_map_and_array_lengths() {
+ let mut resource_attributes = HashMap::new();
+ resource_attributes.insert("host.name".to_string(), "localhost".to_string());
+ let mut attributes = HashMap::new();
+ attributes.insert("a".to_string(), "b".to_string());
+ let row = KafkaTraceRow {
+ uuid: "uuid-1".to_string(),
+ trace_id: "tid".to_string(),
+ span_id: "sid".to_string(),
+ parent_span_id: "psid".to_string(),
+ trace_state: "ts".to_string(),
+ name: "op".to_string(),
+ kind: 0,
+ flags: 0,
+ timestamp: Utc::now(),
+ end_time: Utc::now(),
+ observed_timestamp: Utc::now(),
+ service_name: "svc".to_string(),
+ resource_attributes,
+ instrumentation_scope: "scope".to_string(),
+ attributes,
+ dropped_attributes_count: 0,
+ events: vec!["{}".to_string()],
+ dropped_events_count: 0,
+ links: vec!["{}".to_string()],
+ dropped_links_count: 0,
+ status_code: 0,
+ status_message: "ok".to_string(),
+ bytes_uncompressed: None,
+ };
+ // strings: uuid(6) + tid(3) + sid(3) + psid(4) + ts(2) + op(2) + svc(3) + scope(5) + ok(2) = 30
+ // resource_attributes: host.name(9)+localhost(9)=18; attributes a(1)+b(1)=2
+ // events 1 entry of "{}"(2); links 1 entry of "{}"(2) = 4
+ // total = 30 + 18 + 2 + 4 = 54
+ assert_eq!(compute_kafka_trace_row_bytes(&row), 54);
+ }
+
+ #[test]
+ fn test_bytes_uncompressed_serialises_into_avro_payload() {
+ // Decode to raw Avro Value rather than struct: apache_avro's `from_value` can't
+ // resolve `["null", T]` unions into the existing non-Option fields on KafkaTraceRow.
+ use apache_avro::types::Value;
+
+ let (row, _) = KafkaTraceRow::new(make_span(), None, None).expect("ok");
+ let expected = row.bytes_uncompressed.expect("populated");
+
+ let schema = Schema::parse_str(TRACES_AVRO_SCHEMA).expect("schema parses");
+ let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null);
+ writer.append_ser(&row).expect("append_ser ok");
+ let payload = writer.into_inner().expect("flush ok");
+
+ let reader = Reader::new(payload.as_slice()).expect("reader ok");
+ let mut found_long: Option<i64> = None;
+ for value in reader {
+ let value = value.expect("decode ok");
+ if let Value::Record(fields) = value {
+ for (name, field_value) in fields {
+ if name == "bytes_uncompressed" {
+ if let Value::Union(_, inner) = field_value {
+ if let Value::Long(v) = *inner {
+ found_long = Some(v);
+ }
+ }
+ }
+ }
+ }
+ }
+ assert_eq!(found_long, Some(expected));
+ }
+
+ #[test]
+ fn test_new_populates_bytes_uncompressed() {
+ let (row, _) = KafkaTraceRow::new(make_span(), None, None).expect("ok");
+ assert!(row.bytes_uncompressed.is_some());
+ assert_eq!(
+ row.bytes_uncompressed.unwrap(),
+ compute_kafka_trace_row_bytes(&row),
+ );
+ }
+
#[test]
fn test_basic_span_conversion() {
let span = make_span();
diff --git a/rust/capture-logs/src/traces_avro_schema.rs b/rust/capture-logs/src/traces_avro_schema.rs
index b92098b3bdca..fa1d63fda94c 100644
--- a/rust/capture-logs/src/traces_avro_schema.rs
+++ b/rust/capture-logs/src/traces_avro_schema.rs
@@ -134,6 +134,11 @@ pub const TRACES_AVRO_SCHEMA: &str = r#"
"name": "status_message",
"type": ["null", "string"],
"doc": "Status message"
+ },
+ {
+ "name": "bytes_uncompressed",
+ "type": ["null", "long"],
+ "doc": "Logical content size of the row (sum of byte lengths of string/map/array fields). Used by drop-rule accounting; does not include fixed-width numeric or timestamp fields."
}
]
}"#;