Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 91 additions & 9 deletions crates/ourios-bench/src/c1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
//! count.

use ourios_core::otlp::OtlpLogRecord;
use ourios_core::record::MinedRecord;
use ourios_core::record::{BodyKind, MinedRecord};
use ourios_miner::reconstruct::reconstruct;
use ourios_miner::tree::OwnedToken;

Expand Down Expand Up @@ -77,14 +77,28 @@ impl C1Accumulator {
self.lossy_count = self.lossy_count.saturating_add(1);
return;
}
// Non-lossy. §3.4.2 says we count this record in the
// denominator regardless of whether the snapshot
// lookup succeeds; an absent snapshot for a non-lossy
// record is the harness's "RFC 0001 §6.1 contract
// violation" hard error (and the harness has already
// returned `BenchError::Pipeline` before we get
// here), so in practice we always see `Some(...)`
// for non-lossy.
// Structured-body records are excluded from C1's
// denominator. Per RFC 0001 §6.4 / RFC 0003 §6.4,
// reconstruction for structured bodies is a
// storage-layer round-trip (decode the stored
// `AnyValue` bytes) — *not* template + params — so the
// template-based reconstruction C1 measures doesn't
// apply. Mirrors the lossy-flag exclusion above.
// `lossy_count` still tracks low-confidence parses
// separately; structured records aren't necessarily
// low-confidence, just a different reconstruction
// path.
if matches!(emitted.body_kind, BodyKind::Structured) {
return;
}
// Non-lossy, string body. §3.4.2 says we count this
// record in the denominator regardless of whether the
// snapshot lookup succeeds; an absent snapshot for a
// non-lossy string record is the harness's "RFC 0001
// §6.1 contract violation" hard error (and the harness
// has already returned `BenchError::Pipeline` before
// we get here), so in practice we always see
// `Some(...)` for non-lossy strings.
self.non_lossy_total = self.non_lossy_total.saturating_add(1);
let Some(template) = snapshot else {
// Defensive — should be unreachable per the
Expand Down Expand Up @@ -299,4 +313,72 @@ mod tests {
assert_eq!(m.expected, "beta", "expected = the ingested line");
assert_eq!(m.actual, "alpha", "actual = what reconstruct produced");
}

/// `BodyKind::Structured` records are excluded from C1's
/// denominator. Per RFC 0001 §6.4 / RFC 0003 §6.4,
/// reconstruction for structured bodies is a storage-layer
/// round-trip (decode the stored `AnyValue` bytes) — *not*
/// template + params — so the template-based reconstruction
/// C1 measures doesn't apply. Pins the harness/C1
/// contract fix that the OTLP fixture's kvlistValue body
/// surfaced (the harness's `templates_for()` correctly
/// returns no leaf for the sentinel template id RFC 0001
/// §6.1 assigns to `(severity, scope, BodyKind::Structured)`,
/// so the snapshot lookup is skipped upstream and C1's
/// denominator skip is the symmetric guarantee here).
#[test]
fn structured_body_record_is_excluded_from_denominator() {
use ourios_core::otlp::OtlpLogRecord;
use ourios_core::record::{BodyKind, MinedRecord};
use ourios_core::tenant::TenantId;

let emitted = MinedRecord {
tenant_id: TenantId::new("bench-tenant"),
// Sentinel template id is not a real Drain leaf;
// exact value doesn't matter for this exclusion
// test, only `body_kind`.
template_id: 42,
template_version: 1,
severity_number: 9,
severity_text: None,
scope_name: None,
scope_version: None,
time_unix_nano: 0,
observed_time_unix_nano: None,
attributes: Vec::new(),
dropped_attributes_count: 0,
resource_attributes: Vec::new(),
trace_id: None,
span_id: None,
flags: 0,
event_name: None,
body_kind: BodyKind::Structured,
params: Vec::new(),
separators: vec![String::new()],
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
body: None,
confidence: 1.0,
lossy_flag: false,
};
let input = OtlpLogRecord {
tenant_id: TenantId::new("bench-tenant"),
..Default::default()
};

let mut acc = C1Accumulator::new();
// The harness passes `snapshot = None` for structured
// records (its own `want_snapshot` excludes them too).
acc.record(&input, &emitted, None);
let c1 = acc.finalize();

assert_eq!(
c1.non_lossy_total, 0,
"structured records are excluded from the denominator",
);
assert_eq!(c1.non_lossy_reconstruct_ok, 0);
// Structured ≠ lossy (separate axes). `all_total`
// still counts the record, so the lossy ratio's
// denominator stays honest, but the structured record
// doesn't appear in `lossy_count`.
assert!(c1.lossy_flag_ratio.abs() < f64::EPSILON);
}
}
143 changes: 94 additions & 49 deletions crates/ourios-bench/src/corpus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@
//! - **OTLP/JSON Lines** (`*.jsonl`, `*.json`) — RFC 0006 §3.1's
//! OTLP-LogsData migration. One OTLP `LogsData` per line
//! (the [OTel File Exporter] format the collector emits). Each
//! wire `LogRecord`'s envelope is preserved 1:1 onto the
//! [`OtlpLogRecord`] per the RFC 0003 §6.6 shape — severity,
//! scope, attributes, resource attributes, trace context, body.
//! `time_unix_nano` is taken from the wire (file-static =
//! run-reproducible). String bodies become `Body::String`;
//! any other `AnyValue` becomes `Body::Structured`.
//! wire `LogRecord`'s envelope maps onto the [`OtlpLogRecord`]
//! per the RFC 0003 §6.6 shape for severity, scope, trace
//! context, and body. `attributes` and `resource_attributes`
//! are currently stripped (set to empty `Vec`s) pending the
//! RFC 0005 §3.3 `KeyValue` canonical-JSON encoder in the
//! Parquet writer — see `map_log_record`. `time_unix_nano` is
//! taken from the wire (file-static = run-reproducible).
//! String bodies become `Body::String`; any other `AnyValue`
//! becomes `Body::Structured` (though writing the structured
//! variant requires the same canonicalisation PR, so today's
//! committed CI fixture stays string-body-only).
//!
//! This is the path RFC 0003 §6.5 itself names as the MVP bench
//! route — "the MVP bench reads OTLP from the on-disk corpus,
Expand Down Expand Up @@ -61,7 +66,7 @@ use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use opentelemetry_proto::tonic::common::v1::{InstrumentationScope, KeyValue};
use opentelemetry_proto::tonic::common::v1::InstrumentationScope;
use opentelemetry_proto::tonic::logs::v1::{LogRecord, LogsData};
use ourios_core::otlp::{Body, OtlpLogRecord};
use ourios_core::tenant::TenantId;
Expand Down Expand Up @@ -380,34 +385,32 @@ fn ingest_otlp_jsonl(
detail: format!("parse OTLP/JSON at {}:{}: {e}", path.display(), idx + 1),
})?;
for rl in logs_data.resource_logs {
// Resource attributes are copied onto every
// record in the `ResourceLogs` group per the
// `OtlpLogRecord` doc-comment ("inherited from
// `Resource.attributes` and copied onto every
// record under that `ResourceLogs` group"). Hoist
// the borrow once so the per-record map doesn't
// re-extract.
let resource_attrs: Vec<KeyValue> =
rl.resource.map(|r| r.attributes).unwrap_or_default();
// `rl.resource.attributes` would normally be copied
// onto every record in the group, but the bench
// currently strips both `attributes` and
// `resource_attributes` per the RFC 0005 §3.3
// KeyValue canonicalisation gap (see
// `map_log_record`). When that lands the resource
// attrs need re-introducing here as a per-group
// hoist.
for sl in rl.scope_logs {
let scope = sl.scope;
for lr in sl.log_records {
lines.push(map_log_record(
tenant.clone(),
&resource_attrs,
scope.as_ref(),
lr,
));
lines.push(map_log_record(tenant.clone(), scope.as_ref(), lr));
}
}
}
}
Ok(())
}

/// Map one wire `LogRecord` (plus its inherited resource
/// attributes and `InstrumentationScope`) into the
/// [`OtlpLogRecord`] shape RFC 0003 §6.6 pins. Severity
/// Map one wire `LogRecord` (plus its `InstrumentationScope`)
/// into the [`OtlpLogRecord`] shape RFC 0003 §6.6 pins. The
/// resource attributes hoisted by the caller would normally
/// fan out per record (per the §6.6 contract) but are stripped
/// alongside `log_record.attributes` until the RFC 0005 §3.3
/// canonicalisation PR lands — see the comment in-body.
/// Severity
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/// clamps wire `i32` into the OTLP-defined `0..=24` band
/// (`0` = UNSPECIFIED, `1..=24` = TRACE..FATAL with sub-
/// levels), matching the receiver-boundary narrowing the
Expand All @@ -418,7 +421,6 @@ fn ingest_otlp_jsonl(
/// whether the wire delivered `""` or omitted the field.
fn map_log_record(
tenant: TenantId,
resource_attrs: &[KeyValue],
scope: Option<&InstrumentationScope>,
lr: LogRecord,
) -> OtlpLogRecord {
Expand All @@ -431,9 +433,22 @@ fn map_log_record(
severity_text: empty_to_none(lr.severity_text),
scope_name: scope.and_then(|s| empty_to_none(s.name.clone())),
scope_version: scope.and_then(|s| empty_to_none(s.version.clone())),
attributes: lr.attributes,
// `attributes` and `resource_attributes` are dropped
// until the RFC 0005 §3.3 KeyValue canonical-JSON
// encoding lands in the Parquet writer — non-empty
// `Vec<KeyValue>` columns are explicitly rejected
// today (see `ourios-parquet/src/record_batch.rs`,
// "canonical-JSON encoding of {count} KeyValue
// entries is deferred…"). Until then a 1:1 OTLP
// envelope mapping would crash the bench's writer on
// any record with even one attribute. Restore both
// assignments to `lr.attributes` /
// `resource_attrs.to_vec()` once canonicalisation
// lands; the loader test pins the current strip so
// that change forces the test to update.
attributes: Vec::new(),
dropped_attributes_count: lr.dropped_attributes_count,
resource_attributes: resource_attrs.to_vec(),
resource_attributes: Vec::new(),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Trace / span ids are wire-typed as `Vec<u8>` but
// OTLP fixes their length (16 / 8 bytes). Reject any
// other length to `None` rather than panicking — a
Expand Down Expand Up @@ -622,8 +637,11 @@ mod tests {
assert_eq!(load.total_files, 1, "the sample dir has one .jsonl file");
assert_eq!(
load.lines.len(),
4,
"3 LogsData lines × (1 + 2 + 1) records = 4",
3,
"2 LogsData lines × (1 + 2) records = 3 — the kvlistValue\
record lives in `structured_body_maps_to_body_structured` \
instead so the committed fixture stays Parquet-writable \
(RFC 0005 §3.3 canonicalisation pending)",
);
assert!(load.raw_bytes > 0, "raw_bytes counts the .jsonl file size");

Expand All @@ -639,41 +657,68 @@ mod tests {
assert_eq!(first.scope_name.as_deref(), Some("bench.scope"));
assert_eq!(first.scope_version.as_deref(), Some("1.0.0"));
assert_eq!(first.flags, 1);
assert_eq!(first.attributes.len(), 1, "one log attribute on record 0");
assert_eq!(
first.resource_attributes.len(),
2,
"two resource attributes (service.name + host.name)",
);
// `attributes` and `resource_attributes` are pinned
// empty — the loader currently strips them per the
// RFC 0005 §3.3 KeyValue canonicalisation gap (see
// `map_log_record`'s comment). The wire delivers
// `user.id=42` on this record + service.name /
// host.name on the resource; both round to `[]` until
// canonicalisation lands and we revert the strip.
// Pinning the strip here means the revert PR has to
// update this test, closing the loop.
assert!(first.attributes.is_empty());
assert!(first.resource_attributes.is_empty());
assert_eq!(
line_bytes(first),
Some("user 42 logged in".as_bytes()),
"Body::String unwraps to the wire string",
);

// Second LogsData has 2 records — both should land,
// sharing the resource attribute (only service.name on
// that line).
// Second LogsData has 2 records — both should land
// with the same stripped envelope.
let second = &load.lines[1];
assert_eq!(second.severity_number, 13, "WARN");
assert_eq!(line_bytes(second), Some("slow query: 1843ms".as_bytes()));
assert_eq!(second.resource_attributes.len(), 1);
assert!(second.resource_attributes.is_empty());
let third = &load.lines[2];
assert_eq!(third.severity_number, 17, "ERROR");
assert_eq!(line_bytes(third), Some("connection refused".as_bytes()));
}

/// `body.kvlistValue` (and anything that isn't `stringValue`)
/// stays on the record as `Body::Structured(AnyValue)`,
/// **not** flattened to text or dropped. Per RFC 0003 §6.4
/// the receiver hands the miner the decoded `AnyValue`
/// verbatim; canonicalisation is the storage layer's job at
/// write time. `line_bytes` returns `None` on these records
/// (C1's denominator excludes them).
/// `body.kvlistValue` (and anything that isn't
/// `stringValue`) stays on the record as
/// `Body::Structured(AnyValue)`, **not** flattened to text
/// or dropped. Per RFC 0003 §6.4 the receiver hands the
/// miner the decoded `AnyValue` verbatim; canonicalisation
/// is the storage layer's job at write time. `line_bytes`
/// returns `None` on these records (C1's denominator
/// excludes them — see `c1::record`).
///
/// Uses an inline-synthetic fixture rather than the
/// committed `sample.jsonl` because the bench's downstream
/// Parquet writer can't yet *serialise* `Body::Structured`
/// rows (the same RFC 0005 §3.3 canonicalisation gap that
/// blocks `attributes`). Keeping the structured-mapping
/// coverage inline lets the committed fixture stay
/// end-to-end-Parquet-writable for CI workflow runs.
#[test]
fn otlp_structured_body_maps_to_body_structured() {
let load = load(&otlp_sample_dir()).expect("sample loads");
let structured = &load.lines[3];
use std::io::Write;
let tmp = tempfile::TempDir::new().expect("temp dir");
let path = tmp.path().join("structured.jsonl");
let mut file = std::fs::File::create(&path).expect("create");
file.write_all(
b"{\"resourceLogs\":[{\"scopeLogs\":[{\"logRecords\":\
[{\"timeUnixNano\":\"1775127483000000000\",\
\"severityNumber\":9,\"severityText\":\"INFO\",\
\"body\":{\"kvlistValue\":{\"values\":\
[{\"key\":\"event\",\"value\":{\"stringValue\":\"startup\"}}]}}}]}]}]}\n",
)
.expect("write");
drop(file);

let load = load(tmp.path()).expect("sample loads");
let structured = &load.lines[0];
assert!(
matches!(structured.body, Some(Body::Structured(_))),
"kvlistValue body must round-trip as Body::Structured, got {:?}",
Expand Down
Loading
Loading