Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions crates/ourios-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ opentelemetry-proto = { version = "0.32", default-features = false, features = [
# §6.4. Truncated blake3 (first 16 bytes) joins audit events back to
# the data record(s) that triggered them in the §6.7 drift query.
blake3 = { version = "1", default-features = false }
# Drives the RFC 0005 §3.3 OTLP-canonical-JSON encoders / decoders
# Drives the RFC 0005 §3.3 Ourios-canonical-JSON encoders / decoders
# (`otlp::canonical`). Pairs with `opentelemetry-proto`'s `with-serde`
# derives so the spec mapping stays single-sourced through the proto
# crate.
serde_json = { version = "1", default-features = false, features = ["std"] }
# crate. `float_roundtrip` is load-bearing, not an optimisation
# preference: serde_json's default float parsing is approximate and
# drifts `decode(encode(x))` by 1–2 ULP for ~12% of arbitrary finite
# f64 (#130) — RFC 0001 §6.1's `stored_bytes ↔ AnyValue` faithfulness
# guarantee requires the correctly-rounded parser.
serde_json = { version = "1", default-features = false, features = ["std", "float_roundtrip"] }
# The OTel metrics **API** only (RFC 0001 §6.8 "Export architecture":
# library crates depend on the lightweight API and resolve instruments
# through `global::meter`; the heavy SDK + OTLP exporter live in
Expand All @@ -47,6 +51,9 @@ ourios-semconv = { path = "../ourios-semconv" }
# through an in-memory reader (no OTLP endpoint) in the §6.8 telemetry
# unit test — same pattern as the compaction-metrics test.
ourios-telemetry = { path = "../ourios-telemetry", features = ["testing"] }
# Property test for the canonical encoding's exact finite-f64
# round-trip (#130).
proptest = "1"
tokio = { version = "1", default-features = false, features = ["rt", "rt-multi-thread", "macros"] }
opentelemetry_sdk = { version = "0.32", default-features = false, features = ["metrics", "testing"] }

Expand Down
174 changes: 152 additions & 22 deletions crates/ourios-core/src/otlp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,11 @@ pub struct OtlpLogRecord {
/// The `body.kind` fork from RFC 0001 §6.2 step 0.
///
/// The `Structured` variant carries the decoded `AnyValue` rather
/// than its OTLP-canonical JSON encoding — canonicalisation is
/// deferred to the storage layer so the in-memory record stays
/// optionality-rich (a future "mine inner field" mode per
/// RFC 0001 §6.1 needs the structured tree, not pre-cached
/// bytes). RFC 0003 §6.4 carries the corresponding amendment.
/// than its Ourios-canonical JSON encoding — the receiver hands the
/// miner the tree verbatim, and canonicalisation happens once, at
/// ingest, inside the miner (RFC 0003 §6.4). Keeping the tree on the
/// in-memory record is what preserves a future "mine inner field"
/// mode (RFC 0001 §6.1): any such hook runs before the encode.
#[derive(Debug, Clone, PartialEq)]
pub enum Body {
/// `LogRecord.body` was `AnyValue::String` — the unwrapped
Expand All @@ -111,14 +111,11 @@ pub enum Body {
/// sentinel template id per §6.1 *Template-key composition*.
///
/// **Wire-export round-trip rule (RFC 0003 implementer note).**
/// The *target* on-disk encoding for `MinedRecord.body` on
/// `Structured` rows is OTLP-canonical JSON per RFC 0005 §3.3.
/// The *current* miner implementation (in
/// `ourios-miner::cluster::ingest_structured`) writes the
/// `Debug` rendering of the decoded `AnyValue` (`format!(
/// "{any_value:?}")`) as an interim placeholder — the
/// canonicalisation PR replaces it before any wire-export
/// path lands. Either way, the future OTLP exporter MUST
/// The on-disk encoding for `MinedRecord.body` on `Structured`
/// rows is the Ourios-canonical JSON per RFC 0005 §3.3, produced
/// by `ourios-miner::cluster::ingest_structured` via this
/// module's `canonical::encode_any_value`. The future OTLP
/// exporter MUST
/// decode the stored bytes back into the matching `AnyValue`
/// variant (the `opentelemetry_proto::tonic::common::v1::
/// any_value::Value` enum — `KvlistValue`, `ArrayValue`,
Expand Down Expand Up @@ -192,14 +189,14 @@ impl Body {
}
}

/// RFC 0005 §3.3 OTLP-canonical-JSON encoding for the columns
/// RFC 0005 §3.3 Ourios-canonical-JSON encoding for the columns
/// the writer stores as `BYTE_ARRAY`: `attributes`,
/// `resource_attributes`, and the `body` column for
/// `body_kind = Structured`.
///
/// The "canonical" rule is the proto3 JSON mapping plus OTLP's
/// specific overrides (camelCase fields, `string`-encoded
/// `uint64`s, base64 for `bytes`, etc.). The
/// `int64`s, base64 for `bytes`, etc.). The
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
/// `opentelemetry-proto` crate's `with-serde` feature already
/// implements that spec on its proto types — these helpers are
/// thin wrappers so callers don't reach for `serde_json`
Expand All @@ -212,6 +209,21 @@ impl Body {
/// re-encoding the same in-memory tree produces byte-identical
/// output across runs — required by RFC0006.7 reproducibility.
///
/// **`f64` exactness (#130).** The encode side already emits
/// shortest-round-trip digits (doubles go through `serde_json`'s
/// Ryu `f64` serializer). The lossy half was **decode**:
/// `serde_json`'s default float parsing is approximate, drifting
/// `decode(encode(x))` by 1–2 ULP for ~12% of arbitrary finite
/// `f64`. This crate therefore requires `serde_json`'s
/// `float_roundtrip` feature (declared in `Cargo.toml`), which
/// makes float parsing correctly rounded and the finite-`f64`
/// round-trip bit-exact — the RFC 0001 §6.1 faithfulness
/// guarantee (`lossy_flag = false`) rests on it. Pinned by the
/// `finite_doubles_round_trip_bit_exact` property test below.
/// Non-finite doubles (`NaN`, ±∞) have no JSON-number form and
/// encode as `null` — bytes that do **not** decode; a known,
/// pre-existing gap independent of #130.
///
/// **Note on "canonical".** RFC 0005 §3.3 uses "canonical" to
/// mean "the single normative encoding the writer / reader
/// agree on," **not** the RFC 8785 canonical-JSON form (sorted
Expand All @@ -226,9 +238,10 @@ pub mod canonical {
/// Encoders are infallible on every `AnyValue` /
/// `Vec<KeyValue>` the type system admits —
/// `opentelemetry-proto`'s `with-serde` ships custom
/// serializers for the proto3-JSON oddities (`f64::NAN`
/// → `"NaN"` string, `i64` → string-encoded JSON number,
/// `bytes` → base64) so the recursive primitives never
/// serializers for the proto3-JSON oddities (`i64` →
/// string-encoded JSON number, `bytes` → base64; non-finite
/// `f64` falls back to `serde_json`'s `null`, not the proto3
/// `"NaN"` strings) so the recursive primitives never
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
/// panic or return an error. The `Encode` arm exists only
/// for `Result`-symmetry with `Decode` and as a defence-
/// in-depth surface if a future `opentelemetry-proto`
Expand All @@ -243,8 +256,8 @@ pub mod canonical {
impl core::fmt::Display for CanonicalJsonError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Encode(e) => write!(f, "OTLP-canonical JSON encode: {e}"),
Self::Decode(e) => write!(f, "OTLP-canonical JSON decode: {e}"),
Self::Encode(e) => write!(f, "Ourios-canonical JSON encode: {e}"),
Self::Decode(e) => write!(f, "Ourios-canonical JSON decode: {e}"),
}
}
}
Expand All @@ -257,7 +270,7 @@ pub mod canonical {
}
}

/// Encode one `AnyValue` to its OTLP-canonical JSON bytes.
/// Encode one `AnyValue` to its Ourios-canonical JSON bytes.
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
/// Used by the writer / miner for `body_kind = Structured`
/// rows (the `body` column stores these bytes).
///
Expand Down Expand Up @@ -287,7 +300,7 @@ pub mod canonical {

/// Encode a `Vec<KeyValue>` (the in-memory shape of
/// `attributes` / `resource_attributes`) to its
/// OTLP-canonical JSON bytes. Stored verbatim in the
/// Ourios-canonical JSON bytes. Stored verbatim in the
/// matching `BYTE_ARRAY` column by the writer.
///
/// # Errors
Expand Down Expand Up @@ -520,6 +533,123 @@ pub mod canonical {
let back = decode_attributes(&bytes).expect("decode");
assert!(back.is_empty());
}

fn double_av(x: f64) -> AnyValue {
AnyValue {
value: Some(any_value::Value::DoubleValue(x)),
}
}

/// #130 regression: without `serde_json`'s
/// `float_roundtrip` feature, decoding the repro value's
/// stored bytes came back one ULP off (`…255e99` →
/// `…257e99`) — the default float parser is approximate.
/// Every finite `f64` must round-trip bit-exactly, the
/// sign of `-0.0` included.
#[test]
fn doubles_round_trip_bit_exact_including_issue_130_repro() {
for x in [
-1.537_408_465_042_525_5e99,
-0.0,
0.0,
f64::MAX,
f64::MIN_POSITIVE,
5e-324,
] {
let bytes = encode_any_value(&double_av(x)).expect("encode");
let back = decode_any_value(&bytes).expect("decode");
let Some(any_value::Value::DoubleValue(y)) = back.value else {
panic!("decoded variant drifted for {x:?}");
};
assert_eq!(
x.to_bits(),
y.to_bits(),
"f64 round-trip not bit-exact for {x:?}: got {y:?} via {}",
String::from_utf8_lossy(&bytes),
);
}
}

/// Non-finite doubles have no JSON-number form; the
/// `with-serde` encoder emits `{"doubleValue":null}` for
/// them (captured empirically — **not** the proto3-JSON
/// `"NaN"` / `"Infinity"` strings). Pinned so an upstream
/// change can't drift stored bytes silently. Decoding
/// these bytes fails — a known, pre-existing gap
/// independent of #130.
#[test]
fn nonfinite_doubles_encode_to_the_null_shape() {
for x in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let bytes = encode_any_value(&double_av(x)).expect("encode");
assert_eq!(bytes, br#"{"doubleValue":null}"#, "drift for {x:?}");
// The other half of the pinned gap: those bytes do not
// decode, so non-finite doubles never round-trip.
assert!(
decode_any_value(&bytes).is_err(),
"the null shape unexpectedly decoded for {x:?}",
);
}
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
}

/// Walks to the single double planted by the round-trip
/// property below, whatever nesting it sits at.
fn planted_double_bits(av: &AnyValue) -> u64 {
match &av.value {
Some(any_value::Value::DoubleValue(x)) => x.to_bits(),
Some(any_value::Value::ArrayValue(array)) => planted_double_bits(&array.values[0]),
Some(any_value::Value::KvlistValue(kvlist)) => planted_double_bits(
kvlist.values[0]
.value
.as_ref()
.expect("kv carries the double"),
),
other => panic!("expected the planted double, got {other:?}"),
}
}

proptest::proptest! {
/// RFC 0001 §6.1 faithfulness for arbitrary finite
/// doubles (#130): `decode(encode(x))` is bit-exact at
/// top level and nested inside array / kvlist.
#[test]
fn finite_doubles_round_trip_bit_exact(bits in proptest::prelude::any::<u64>()) {
let x = f64::from_bits(bits);
proptest::prop_assume!(x.is_finite());

let nestings = [
double_av(x),
AnyValue {
value: Some(any_value::Value::ArrayValue(
opentelemetry_proto::tonic::common::v1::ArrayValue {
values: vec![double_av(x)],
},
)),
},
AnyValue {
value: Some(any_value::Value::KvlistValue(
opentelemetry_proto::tonic::common::v1::KeyValueList {
values: vec![KeyValue {
key: "k".to_string(),
value: Some(double_av(x)),
..Default::default()
}],
},
)),
},
];
for av in nestings {
let bytes = encode_any_value(&av).expect("encode");
let back = decode_any_value(&bytes).expect("decode");
proptest::prop_assert_eq!(
planted_double_bits(&back),
x.to_bits(),
"not bit-exact for {:?} via {}",
x,
String::from_utf8_lossy(&bytes),
);
}
}
}
}
}

Expand Down
23 changes: 23 additions & 0 deletions docs/rfcs/0001-template-miner.md
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,25 @@ get a template extracted.
> `otlp::canonical` (a separate follow-up PR aligns its doc
> comments).

> **Amendment 2026-06-11 (doubles round-trip bit-exactly — #130).**
> The rule below previously left `double` precision implicit, and
> `decode(encode(x))` drifted 1–2 ULP for ~12% of arbitrary finite
> `f64`. Investigating #130 located the loss on the **decode**
> side, not the encoder: the emitter already produces
> shortest-round-trip digits (`serde_json`'s Ryu `f64` formatter —
> `with-serde` adds no custom double formatter), but `serde_json`'s
> default float *parsing* is approximate. The rule now pins both
> halves: doubles are emitted as shortest-round-trip JSON numbers
> and decoded with correctly-rounded float parsing (`serde_json`'s
> `float_roundtrip` feature, declared load-bearing in
> `ourios-core`), so the `f64` round-trip is exact for every
> finite double — the faithfulness guarantee below holds for
> arbitrary doubles, not just "nice" ones. Non-finite doubles
> (`NaN`, ±∞) have no JSON-number form and encode as `null` —
> bytes that do **not** decode back; that pre-existing gap is
> explicitly out of scope here and stays open. No RFC `status`
> change.

The `body` column carries the **Ourios canonical body
encoding** of the `AnyValue`: a proto3-JSON form, defined
below. This is an **Ourios-local deterministic convention, not
Expand All @@ -914,6 +933,10 @@ The concrete rule is the proto3 JSON mapping **as emitted by
- field names in `lowerCamelCase`;
- `int64` / `uint64` values as **decimal strings** (proto3 JSON's
canonical emit form; decoders accept a JSON number or string);
- `double` values as JSON numbers in **shortest-round-trip**
form, decoded with correctly-rounded float parsing —
`decode(encode(x))` is bit-exact for every finite `f64`
(#130; see the 2026-06-11 amendment above);
- `bytes` as **base64**;
- `KvlistValue` and `ArrayValue` element order **preserved as
received — not sorted** (this is explicitly **not** RFC 8785 /
Expand Down
Loading