diff --git a/Cargo.lock b/Cargo.lock
index 677747710..be24aa8c6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -612,7 +612,7 @@ dependencies = [
"base64 0.23.1",
"bytes",
"futures",
- "prost 0.14.1",
+ "prost",
"prost-types",
"tonic",
"tonic-prost",
@@ -2690,7 +2690,7 @@ dependencies = [
"datafusion-proto-common",
"datafusion-proto-models",
"object_store",
- "prost 0.14.1",
+ "prost",
]
[[package]]
@@ -2701,7 +2701,7 @@ checksum = "6b92415a2442964f180d39cdcd8ff1edd99f9260c1499ba80a396499c2154d11"
dependencies = [
"arrow",
"datafusion-common",
- "prost 0.14.1",
+ "prost",
]
[[package]]
@@ -2712,7 +2712,7 @@ checksum = "62e4c0bd6af4fcabdbe201ee86fbeef2ac423a44e1d8fda56d994c9e2d1d3ad2"
dependencies = [
"datafusion-common",
"datafusion-proto-common",
- "prost 0.14.1",
+ "prost",
]
[[package]]
@@ -4643,7 +4643,7 @@ dependencies = [
"opentelemetry-http",
"opentelemetry-proto",
"opentelemetry_sdk",
- "prost 0.14.1",
+ "prost",
"reqwest 0.13.4",
"serde_json",
"thiserror 2.0.17",
@@ -4662,7 +4662,7 @@ dependencies = [
"const-hex",
"opentelemetry",
"opentelemetry_sdk",
- "prost 0.14.1",
+ "prost",
"serde",
"tonic",
"tonic-prost",
@@ -4858,7 +4858,7 @@ dependencies = [
"prometheus-parse",
"promql-parser",
"proptest",
- "prost 0.13.5",
+ "prost",
"rand 0.8.6",
"rayon",
"rdkafka",
@@ -5265,16 +5265,6 @@ dependencies = [
"unarray",
]
-[[package]]
-name = "prost"
-version = "0.13.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"
-dependencies = [
- "bytes",
- "prost-derive 0.13.5",
-]
-
[[package]]
name = "prost"
version = "0.14.1"
@@ -5282,20 +5272,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d"
dependencies = [
"bytes",
- "prost-derive 0.14.1",
-]
-
-[[package]]
-name = "prost-derive"
-version = "0.13.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
-dependencies = [
- "anyhow",
- "itertools 0.14.0",
- "proc-macro2",
- "quote",
- "syn 2.0.117",
+ "prost-derive",
]
[[package]]
@@ -5317,7 +5294,7 @@ version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72"
dependencies = [
- "prost 0.14.1",
+ "prost",
]
[[package]]
@@ -6842,7 +6819,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66bd50ad6ce1252d87ef024b3d64fe4c3cf54a86fb9ef4c631fdd0ded7aeaa67"
dependencies = [
"bytes",
- "prost 0.14.1",
+ "prost",
"tonic",
]
@@ -6852,7 +6829,7 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a875a902255423d34c1f20838ab374126db8eb41625b7947a1d54113b0b7399"
dependencies = [
- "prost 0.14.1",
+ "prost",
"prost-types",
"tonic",
]
diff --git a/Cargo.toml b/Cargo.toml
index b62d95ff0..12cd7a093 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -198,7 +198,7 @@ rustc-hash = "2.1.2"
futures-core = "0.3.31"
tempfile = "3.20.0"
lazy_static = "1.4.0"
-prost = "0.13.1"
+prost = "0.14.1"
dashmap = "6.2.1"
parking_lot = "0.12.5"
indexmap = { version = "2.14.0", features = ["serde"] }
@@ -265,3 +265,7 @@ codegen-units = 1
[profile.release-thin-lto]
inherits = "release"
lto = "thin"
+
+[[example]]
+name = "otlp_stage"
+path = "scripts/ingest-performance/otlp_stage.rs"
diff --git a/frontend/docs/observability-validation.md b/frontend/docs/observability-validation.md
index 0f081dcc4..26fe30962 100644
--- a/frontend/docs/observability-validation.md
+++ b/frontend/docs/observability-validation.md
@@ -38,7 +38,7 @@ Dependencies require a child span and its parent in the same dataset/time window
JSON HTTP targets `/api/v1/ingest`; OTLP HTTP targets `/v1/logs`, `/v1/metrics` or `/v1/traces`. Dataset creation supplies the matching telemetry type and source (`json`, `otel-logs`, `otel-metrics`, `otel-traces`). Existing metadata must match the selected source/signal before configuration becomes available. Destinations with custom partitions show the required field names and instructions to select/create an unpartitioned dataset or configure a sender manually. Generated configuration, copying and guided verification stay unavailable for those destinations because setup cannot infer valid partition values. JSON input uses logs; other sources choose one signal per dataset.
-Generated collector configuration uses `otlp_http/parseable`, HTTP JSON encoding, `compression: none`, `X-P-Stream`, and an environment variable for the ingest API key. Receivers bind to localhost on ports 4317/4318 and must be adjusted for other deployment arrangements. The native OSS server accepts JSON OTLP HTTP rather than protobuf; its content type is `application/json`. Collector configuration converts compatible sender traffic. Setup does not deploy or start a sender.
+Generated collector configuration uses `otlp_http/parseable`, HTTP protobuf encoding, `compression: none`, `X-P-Stream`, and an environment variable for the ingest API key. Receivers bind to localhost on ports 4317/4318 and must be adjusted for other deployment arrangements. The native OSS server accepts OTLP HTTP as protobuf (`application/x-protobuf`) or JSON (`application/json`); the generated curl sample sends JSON. Collector configuration converts compatible sender traffic. Setup does not deploy or start a sender.
Endpoint validation permits HTTP/HTTPS base URLs and reverse proxy base paths, and rejects embedded credentials, query/fragment strings, variables, whitespace, backslashes and appended ingestion routes. Commands quote shell values and dataset names are validated. Credentials are entered into the sender's environment rather than persisted by this setup. Copy success and failure are visible, with manual copying available when the browser denies clipboard access.
diff --git a/frontend/e2e/ingestion.spec.ts b/frontend/e2e/ingestion.spec.ts
index 1258e3e1f..d7cfdc981 100644
--- a/frontend/e2e/ingestion.spec.ts
+++ b/frontend/e2e/ingestion.spec.ts
@@ -127,8 +127,15 @@ test('demo switches source and signal, blocks incompatible datasets, and copies
await expect(page.getByLabel('Ingestion command', { exact: true })).toHaveCount(0);
await page.getByLabel('Destination dataset', { exact: true }).selectOption('demo_metrics');
await expect(page.getByLabel('Ingestion command', { exact: true })).toContainText('/v1/metrics');
+ // The note under the snippet names the encoding the snippet uses
+ await expect(
+ page.getByText('This configuration uses JSON and sends only metrics to this dataset.'),
+ ).toBeVisible();
await page.getByRole('radio', { name: /^OpenTelemetry Collector/ }).check();
- await expect(page.getByLabel('collector.yaml', { exact: true })).toContainText('encoding: json');
+ await expect(page.getByLabel('collector.yaml', { exact: true })).toContainText('encoding: proto');
+ await expect(
+ page.getByText('This configuration uses protobuf and sends only metrics to this dataset.'),
+ ).toBeVisible();
await expect(page.getByLabel('collector.yaml', { exact: true })).toContainText(
'X-P-Stream: "demo_metrics"',
);
diff --git a/frontend/src/features/ingestion/ConnectionConfig.tsx b/frontend/src/features/ingestion/ConnectionConfig.tsx
index aea82ce68..a455f09a8 100644
--- a/frontend/src/features/ingestion/ConnectionConfig.tsx
+++ b/frontend/src/features/ingestion/ConnectionConfig.tsx
@@ -78,8 +78,9 @@ export function ConnectionConfig({
)}
{options.source !== 'json' && (
- Parseable OSS accepts OTLP over HTTP with JSON encoding. Use a collector to convert
- SDK protobuf traffic. The configuration sends only {options.signal} to this dataset.
+ Parseable OSS accepts OTLP over HTTP with JSON or protobuf encoding. This
+ configuration uses {options.source === 'collector' ? 'protobuf' : 'JSON'} and sends
+ only {options.signal} to this dataset.
)}
diff --git a/frontend/src/features/ingestion/IngestionPage.tsx b/frontend/src/features/ingestion/IngestionPage.tsx
index d0851e98c..5d89e8d46 100644
--- a/frontend/src/features/ingestion/IngestionPage.tsx
+++ b/frontend/src/features/ingestion/IngestionPage.tsx
@@ -209,8 +209,8 @@ function IngestionWorkspace() {
Sending OpenTelemetry?
- Use HTTP with JSON encoding. A collector can receive your SDK's OTLP traffic and forward
- compatible JSON to Parseable.
+ Use OTLP over HTTP with JSON or protobuf encoding. A collector can receive your SDK's
+ OTLP traffic and forward it to Parseable.
{
expect(code).not.toContain('/api/v1/ingest');
});
it.each(['logs', 'metrics', 'traces'] as const)(
- 'builds only the selected collector %s pipeline with JSON encoding',
+ 'builds only the selected collector %s pipeline with protobuf encoding',
(signal) => {
const code = generateIngestionConfig({
endpoint: 'https://example.com/base',
@@ -77,7 +77,7 @@ describe('configuration generation', () => {
signal,
});
expect(code).toContain('otlp_http/parseable:');
- expect(code).toContain('encoding: json');
+ expect(code).toContain('encoding: proto');
expect(code).toContain('compression: none');
expect(code).toContain('Authorization: "Bearer ${env:PARSEABLE_API_KEY}"');
expect(code).toContain(`X-P-Stream: "otel_${signal}"`);
diff --git a/frontend/src/lib/ingestion.ts b/frontend/src/lib/ingestion.ts
index 96ca5d2ee..bb375e62b 100644
--- a/frontend/src/lib/ingestion.ts
+++ b/frontend/src/lib/ingestion.ts
@@ -176,7 +176,8 @@ export function generateIngestionConfig(options: IngestionOptions): string {
const endpoint = options.endpoint.replace(/\/+$/, '');
const signal = options.source === 'json' ? 'logs' : options.signal;
if (options.source === 'collector') {
- // Current collector exporter name; JSON is required by the OSS backend.
+ // Current collector exporter name. Protobuf is the exporter's default and
+ // costs the server less than JSON; the server this UI ships with accepts it.
// Disable default gzip: this backend does not implement body decompression.
return `receivers:
otlp:
@@ -192,7 +193,7 @@ processors:
exporters:
otlp_http/parseable:
endpoint: ${JSON.stringify(endpoint)}
- encoding: json
+ encoding: proto
compression: none
headers:
Authorization: "Bearer \${env:PARSEABLE_API_KEY}"
diff --git a/frontend/story-tests/observability-components.spec.ts b/frontend/story-tests/observability-components.spec.ts
index 4b6477bd4..6eee41a0b 100644
--- a/frontend/story-tests/observability-components.spec.ts
+++ b/frontend/story-tests/observability-components.spec.ts
@@ -526,7 +526,7 @@ test('OTLP signal and destination compatibility gate configuration and collector
await expect(page.locator('.ingestion-code-block pre')).toContainText('"resourceSpans"');
await page.getByRole('radio', { name: /^OpenTelemetry Collector/ }).check();
const collector = page.locator('pre[aria-label="collector.yaml"]');
- await expect(collector).toContainText('encoding: json');
+ await expect(collector).toContainText('encoding: proto');
await expect(collector).toContainText('compression: none');
await expect(collector).toContainText('X-P-Stream: "otel_traces"');
await expect(collector).toContainText('pipelines:\n traces:');
diff --git a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-dark-linux.png b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-dark-linux.png
index 597ab5749..bd1b48ae3 100644
Binary files a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-dark-linux.png and b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-dark-linux.png differ
diff --git a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-light-linux.png b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-light-linux.png
index e7c7b4b98..1e759b985 100644
Binary files a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-light-linux.png and b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-desktop-light-linux.png differ
diff --git a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-dark-linux.png b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-dark-linux.png
index e337ec0f0..3af83c106 100644
Binary files a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-dark-linux.png and b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-dark-linux.png differ
diff --git a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-light-linux.png b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-light-linux.png
index dbbb448e3..1cdaef8a7 100644
Binary files a/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-light-linux.png and b/frontend/story-tests/observability-visuals.spec.ts-snapshots/ingestion-collector-setup-narrow-light-linux.png differ
diff --git a/scripts/ingest-performance/README.md b/scripts/ingest-performance/README.md
index b44cd10f2..83dfae023 100644
--- a/scripts/ingest-performance/README.md
+++ b/scripts/ingest-performance/README.md
@@ -36,3 +36,46 @@ python scripts/ingest-performance/plot.py --burst /abs/results/burst --sustained
The local-store results do not establish S3 ingestion capacity. Multipart memory and failure behavior require separate storage probes. Keep exact build provenance and limitations with any reported figures.
For fixed-work 1/10/100/1000-row request comparisons and timestamp-adjusted compatibility probes, see [small-batch-staging](small-batch-staging/README.md).
+
+## OTLP protobuf and JSON
+
+This comparison uses one release server binary and varies the request encoding.
+Build the server and stage example with the same toolchain and features. Install
+the generated OTLP protobuf bindings in an isolated Python environment. They
+serialize a single typed fixture to both formats, with OTLP JSON hex IDs, and
+require no client build. The timed modes require Linux, passwordless sudo to
+launch and signal perf, working `instructions:u` and `task-clock` counters,
+and perf FIFO control.
+
+```sh
+NEXT_ASSETS_PATH=/abs/frontend/dist cargo build --locked --release --bin parseable --example otlp_stage
+python3 -m venv /abs/otlp-venv
+/abs/otlp-venv/bin/pip install opentelemetry-proto==1.38.0 protobuf==6.32.1
+/abs/otlp-venv/bin/python -B -m unittest discover -s scripts/ingest-performance -p 'test_*.py' -v
+/abs/otlp-venv/bin/python scripts/ingest-performance/otlp.py stage --example target/release/examples/otlp_stage --output /abs/results/otlp-stage --cpus 2
+/abs/otlp-venv/bin/python scripts/ingest-performance/otlp.py http --binary target/release/parseable --output /abs/results/otlp-http --cpus 2,4,6,8
+/abs/otlp-venv/bin/python scripts/ingest-performance/otlp.py verify --binary target/release/parseable --output /abs/results/otlp-verify
+```
+
+Choose CPU IDs available on the host. Both timed modes default to four pairs in
+JSON/protobuf/protobuf/JSON order, repeated twice. The stage run checks exact
+flattened rows before comparing 1, 100 and 5000 records with 4 or 32 attributes
+per record. Its default is 50,000 records per arm per shape. Counters cover the
+in-memory decode, flatten and row destruction; fixture loading and the equality
+check occur before measurement. The HTTP run defaults to 256 timed requests of
+100 records with 4 attributes per arm per signal over one keep-alive connection.
+Change the shape with `--rows`, `--attributes` or `--requests`. After each signal's
+ACK window, the runner checks query counts and every request/row ID, then hashes
+all canonicalized SQL results with `p_timestamp` removed for comparison.
+
+The fixtures use explicit timestamps, two resource attributes, one scope,
+four base record attributes including the two identity fields, and an optional
+set of mixed scalar attributes. They contain string-bodied INFO logs, gauge
+points without implicit `target_info` rows, and server spans without events or
+links. The `verify` mode checks accepted content types and gzip, success
+responses, malformed/truncated requests and the default payload limit with
+chunked bodies for each signal. Each mode writes `summary.json` with paired ratios and min/max, or the
+recorded protocol responses for `verify`. The HTTP CPU measurements include
+server work that overlaps the ACK window and exclude subsequent query and drain
+work. Record the source commit, release profile, features and binary hashes
+alongside your summaries.
diff --git a/scripts/ingest-performance/otlp.py b/scripts/ingest-performance/otlp.py
new file mode 100644
index 000000000..04a5eae38
--- /dev/null
+++ b/scripts/ingest-performance/otlp.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+"""Compare OTLP protobuf and JSON on one release build, with paired perf counters."""
+import argparse
+from contextlib import closing, contextmanager
+import gzip
+import hashlib
+import http.client
+import json
+import os
+from pathlib import Path
+import select
+import signal as signals
+import statistics
+import subprocess
+import time
+
+from otlp_fixtures import CONTENT_TYPES, HTTP_LIMIT, SIGNALS, fixtures
+from run import AUTH, request, run_arm
+
+PERF = ['perf', 'stat', '-x', ';', '--no-big-num', '-e', 'instructions:u,task-clock']
+
+
+def pair_order(pair):
+ return ('json', 'protobuf') if pair % 2 == 0 else ('protobuf', 'json')
+
+
+def counters(path):
+ events = {}
+ for line in path.read_text().splitlines():
+ fields = line.split(';')
+ if len(fields) < 5 or fields[2] not in ('instructions:u', 'task-clock'):
+ continue
+ value, unit, event, _, running = fields[:5]
+ if event in events or value.startswith('<') or not 99 <= float(running) <= 100:
+ raise RuntimeError(f'unusable perf counter in {path}: {line}')
+ events[event] = (value, unit)
+ if set(events) != {'instructions:u', 'task-clock'}:
+ raise RuntimeError(f'missing perf counters in {path}')
+ instructions = int(events['instructions:u'][0])
+ cpu_ms, unit = events['task-clock']
+ if instructions <= 0 or unit != 'msec' or float(cpu_ms) <= 0:
+ raise RuntimeError(f'invalid perf counter values in {path}: {events}')
+ return {'instructions': instructions, 'cpu_s': float(cpu_ms) / 1000}
+
+
+def perf_control(command_fd, ack_fd, command):
+ os.write(command_fd, (command + '\n').encode())
+ ready, _, _ = select.select([ack_fd], [], [], 10)
+ # Some perf versions include the string terminator in the FIFO write.
+ if not ready or os.read(ack_fd, 4096).rstrip(b'\0') != b'ack\n':
+ raise RuntimeError(f'perf did not acknowledge {command}')
+
+
+@contextmanager
+def measure_process(pid, path):
+ # Start disabled, attach to the already-warmed process and all of its threads.
+ ctl = path.with_suffix('.ctl')
+ ack = path.with_suffix('.ack')
+ for fifo in (ctl, ack):
+ os.mkfifo(fifo, 0o600)
+ ctl_fd = os.open(ctl, os.O_RDWR)
+ ack_fd = os.open(ack, os.O_RDWR)
+ try:
+ with path.with_suffix('.log').open('w') as log:
+ # Obtain the privileged child's PID. Signalling the sudo wrapper
+ # can leave perf waiting for the attached server to exit.
+ perf = subprocess.Popen(
+ ['sudo', '-n', 'sh', '-c', 'echo $$; exec "$@"', 'sh'] + PERF
+ + ['-D', '-1', '--control', f'fifo:{ctl},{ack}', '-o', str(path), '-p', str(pid)],
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=log,
+ )
+ perf_pid = None
+ try:
+ if not select.select([perf.stdout], [], [], 10)[0]:
+ raise RuntimeError(f'perf startup timed out, see {log.name}')
+ pid_line = perf.stdout.readline().strip()
+ if not pid_line.isdigit():
+ raise RuntimeError(f'perf did not start, see {log.name}')
+ perf_pid = int(pid_line)
+ perf_control(ctl_fd, ack_fd, 'enable')
+ yield
+ perf_control(ctl_fd, ack_fd, 'disable')
+ finally:
+ try:
+ if perf.poll() is None:
+ if perf_pid is not None:
+ subprocess.run(['sudo', '-n', 'kill', '-INT', str(perf_pid)],
+ check=True, timeout=10)
+ else:
+ perf.terminate()
+ status = perf.wait(timeout=10)
+ finally:
+ perf.stdout.close()
+ if status not in (0, -signals.SIGINT, 128 + signals.SIGINT):
+ raise RuntimeError(f'perf failed with status {status}, see {log.name}')
+ finally:
+ os.close(ack_fd)
+ os.close(ctl_fd)
+ ctl.unlink()
+ ack.unlink()
+
+
+def per_row(measurement, rows):
+ return dict(measurement, rows=rows, instructions_per_row=measurement['instructions'] / rows,
+ cpu_s_per_row=measurement['cpu_s'] / rows)
+
+
+def spread(values):
+ return {'median': statistics.median(values), 'min': min(values), 'max': max(values)}
+
+
+def summarize(pairs):
+ keys = ('instructions_per_row', 'cpu_s_per_row')
+ return {
+ 'pairs': len(pairs),
+ 'arms': {arm: {key: spread([pair[arm][key] for pair in pairs]) for key in keys}
+ for arm in CONTENT_TYPES},
+ 'protobuf_over_json': {
+ key: spread([pair['protobuf'][key] / pair['json'][key] for pair in pairs])
+ for key in keys},
+ }
+
+
+def write_json(path, data):
+ path.write_text(json.dumps(data, indent=2) + '\n')
+
+
+def measure_stage(command, capture):
+ def wait_for(pipe, message, timeout):
+ ready, _, _ = select.select([pipe], [], [], timeout)
+ if not ready or pipe.readline().strip() != message:
+ raise RuntimeError(f'stage binary did not report {message}')
+
+ with subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ text=True) as process:
+ try:
+ wait_for(process.stdout, 'ready', 10)
+ with measure_process(process.pid, capture):
+ process.stdin.write('start\n')
+ process.stdin.flush()
+ wait_for(process.stdout, 'done', 180)
+ process.stdin.close()
+ if process.wait(timeout=10) != 0:
+ raise RuntimeError('stage binary failed')
+ finally:
+ if process.poll() is None:
+ process.kill()
+ return counters(capture)
+
+
+def stage(args):
+ results = []
+ for signal in SIGNALS:
+ for rows in (1, 100, 5000):
+ for width in (4, 32):
+ directory = args.output / f'{signal}-{rows}-{width}'
+ directory.mkdir()
+ paths = {}
+ bodies = fixtures(signal, rows, width)
+ for encoding, body in bodies.items():
+ paths[encoding] = directory / encoding
+ paths[encoding].write_bytes(body)
+ subprocess.run([args.example, signal, 'check', paths['json'], paths['protobuf'],
+ str(rows)], check=True)
+ iterations = (args.records + rows - 1) // rows
+ pairs = []
+ for pair in range(args.pairs):
+ result = {}
+ for encoding in pair_order(pair):
+ capture = directory / f'{pair}-{encoding}.perf'
+ affinity = ['taskset', '-c', args.cpus] if args.cpus else []
+ command = affinity + [args.example, signal, encoding, paths[encoding],
+ str(iterations)]
+ result[encoding] = per_row(measure_stage(command, capture), rows * iterations)
+ pairs.append(result)
+ sizes = {encoding: len(body) / rows for encoding, body in bodies.items()}
+ summary = dict(signal=signal, rows_per_request=rows, attributes_per_row=width,
+ iterations=iterations, bytes_per_row=sizes,
+ protobuf_over_json_bytes=sizes['protobuf'] / sizes['json'],
+ **summarize(pairs))
+ write_json(directory / 'pairs.json', pairs)
+ results.append(summary)
+ write_json(args.output / 'summary.json', results)
+ print(json.dumps(summary), flush=True)
+
+
+def post(conn, signal, stream, encoding, body, headers=None, *, chunked=False):
+ headers = {'Authorization': AUTH, 'Content-Type': CONTENT_TYPES[encoding],
+ 'X-P-Stream': stream, **(headers or {})}
+ if chunked:
+ # A declared oversized Content-Length can close the connection while
+ # sendall is still writing. Chunked delivery exercises the byte limit
+ # with the complete fixture on the wire.
+ view = memoryview(body)
+ body = (view[offset:offset + 65536] for offset in range(0, len(view), 65536))
+ conn.request('POST', f'/v1/{signal}', body, headers, encode_chunked=chunked)
+ response = conn.getresponse()
+ return response.status, response.getheader('Content-Type'), response.read()
+
+
+def expect_response(response, status, body=None):
+ if response[0] != status or (body is not None and response[2] != body):
+ raise AssertionError(f'expected HTTP {status} and body {body!r}; got {response[:2]} '
+ f'and {response[2][:500]!r}')
+
+
+def query(port, sql):
+ # The query engine truncates time bounds to whole minutes.
+ payload = dict(query=sql, startTime='1h', endTime='now+2m', sendNull=True)
+ with closing(http.client.HTTPConnection('127.0.0.1', port, timeout=90)) as conn:
+ result = request(port, 'POST', '/api/v1/query', json.dumps(payload).encode(),
+ connection=conn)
+ return json.loads(result)
+
+
+def query_count(port, stream, expected):
+ # Two aggregates force SQL readback instead of the single-count stats shortcut.
+ result = query(port, f'SELECT COUNT(*) AS n, COUNT(bench_batch) AS identified FROM {stream}')
+ if result != [{'n': expected, 'identified': expected}]:
+ raise AssertionError((stream, 'unexpected count', result, expected))
+
+
+def canonical_rows(rows, first, stop, rows_per_request):
+ # Count all rows separately, then confirm every expected identity exactly once.
+ expected = [(f'{batch:08d}', f'{row:06d}') for batch in range(first, stop)
+ for row in range(rows_per_request)]
+ actual = sorted((r['bench_batch'], r['bench_row']) for r in rows)
+ if actual != expected:
+ raise AssertionError(f'identity mismatch for batches [{first}, {stop}): '
+ f'{len(actual)} actual rows, {len(expected)} expected')
+ normalized = [{key: value for key, value in row.items() if key != 'p_timestamp'} for row in rows]
+ return sorted(json.dumps(row, sort_keys=True, separators=(',', ':')) for row in normalized)
+
+
+def readback(port, stream, requests, rows):
+ query_count(port, stream, requests * rows)
+ digest = hashlib.sha256()
+ chunk = max(1, 5000 // rows)
+ for first in range(0, requests, chunk):
+ stop = min(first + chunk, requests)
+ result = query(port, f"SELECT * FROM {stream} WHERE bench_batch >= '{first:08d}' "
+ f"AND bench_batch < '{stop:08d}'")
+ for canonical in canonical_rows(result, first, stop, rows):
+ digest.update(canonical.encode() + b'\n')
+ return {'count': requests * rows, 'logical_rows_sha256': digest.hexdigest()}
+
+
+def http_benchmark(args):
+ timestamp_ns = time.time_ns() - 300_000_000_000
+ captures = {signal: [] for signal in SIGNALS}
+ for pair in range(args.pairs):
+ measured = {}
+ for encoding in pair_order(pair):
+ def action(port, pid):
+ result = {}
+ arm_dir = args.output / f'pair{pair}-{encoding}'
+ for signal in SIGNALS:
+ # Generate outside the sample window. Requests have unique IDs;
+ # batch 0 warms the same stream and connection (included in readback).
+ bodies = []
+ payload_bytes = 0
+ for batch in range(args.requests + 1):
+ body = fixtures(signal, args.rows, args.attributes, batch,
+ timestamp_ns=timestamp_ns)[encoding]
+ payload_bytes += len(body)
+ if len(body) > HTTP_LIMIT or payload_bytes > 256 * 2**20:
+ raise ValueError(f'{signal}/{encoding}: exceeds body or fixture budget')
+ bodies.append(body)
+ stream = f'bench{signal}'
+ path = arm_dir / f'{signal}.perf'
+ with closing(http.client.HTTPConnection('127.0.0.1', port, timeout=90)) as conn:
+ expect_response(post(conn, signal, stream, encoding, bodies[0]), 200, b'')
+ with measure_process(pid, path):
+ started = time.monotonic()
+ for body in bodies[1:]:
+ expect_response(post(conn, signal, stream, encoding, body), 200, b'')
+ elapsed = time.monotonic() - started
+ result[signal] = dict(per_row(counters(path), args.rows * args.requests),
+ elapsed_s=elapsed, timed_body_bytes=payload_bytes-len(bodies[0]),
+ **readback(port, stream, len(bodies), args.rows))
+ return result
+
+ measured[encoding] = run_arm(args.binary, args.output, encoding, pair, [], args.cpus, action)
+ for signal in SIGNALS:
+ result = {encoding: arm[signal] for encoding, arm in measured.items()}
+ if result['json']['logical_rows_sha256'] != result['protobuf']['logical_rows_sha256']:
+ raise AssertionError((signal, pair, 'encodings returned different logical rows', result))
+ captures[signal].append(result)
+ print(f'{signal} pair {pair + 1}: {result["json"]["count"]} identical logical rows '
+ f'(including warmup)', flush=True)
+
+ summary = {signal: summarize(pairs) for signal, pairs in captures.items()}
+ for signal, item in summary.items():
+ item.update(rows_per_request=args.rows, attributes_per_row=args.attributes,
+ fixture_timestamp_ns=timestamp_ns,
+ requests_per_arm=args.requests, verified_rows_per_arm=captures[signal][0]['json']['count'],
+ bytes_per_row={arm: captures[signal][0][arm]['timed_body_bytes'] / (args.rows * args.requests)
+ for arm in CONTENT_TYPES})
+ write_json(args.output / 'summary.json', summary)
+ print(json.dumps(summary), flush=True)
+
+
+def verify(args):
+ timestamp_ns = time.time_ns() - 300_000_000_000
+
+ def action(port, _pid):
+ results = []
+ for signal in SIGNALS:
+ stream = f'verify{signal}'
+ count = 0
+ with closing(http.client.HTTPConnection('127.0.0.1', port, timeout=90)) as conn:
+ def fixture(padding=0):
+ return fixtures(signal, 1, 4, count, timestamp_ns=timestamp_ns, padding=padding)
+
+ def probe(name, encoding, payload, status=200, headers=None, *, chunked=False):
+ nonlocal count
+ response = post(conn, signal, stream, encoding, payload, headers, chunked=chunked)
+ expect_response(response, status, b'' if status == 200 else None)
+ if status == 200:
+ count += 1
+ query_count(port, stream, count)
+ result = dict(signal=signal, case=name, encoding=encoding,
+ sent_bytes=len(payload), status=response[0],
+ response_content_type=response[1],
+ response_body=response[2].decode(errors='replace'), count=count)
+ results.append(result)
+ print(json.dumps(result), flush=True)
+
+ for encoding in ('protobuf', 'json'):
+ probe('standard', encoding, fixture()[encoding])
+ for name, header in [('parameter', 'application/x-protobuf; charset=utf-8'),
+ ('mixed_case', 'Application/X-Protobuf')]:
+ probe(name, 'protobuf', fixture()['protobuf'],
+ headers={'Content-Type': header})
+ for encoding in CONTENT_TYPES:
+ probe('gzip', encoding, gzip.compress(fixture()[encoding]),
+ headers={'Content-Encoding': 'gzip'})
+
+ valid = fixture()
+ for encoding in CONTENT_TYPES:
+ body = valid[encoding]
+ probe('malformed', encoding, body + b'\0', 400)
+ truncated = body[:-1]
+ if encoding == 'protobuf':
+ truncated = body + truncated # complete resource followed by a cut one
+ probe('truncated', encoding, truncated, 400)
+ oversized = fixture(padding=HTTP_LIMIT)[encoding]
+ probe('oversized_chunked', encoding, oversized, 413, chunked=True)
+ readback(port, stream, count, 1)
+ return results
+
+ results = run_arm(args.binary, args.output, 'verification', 0, [], args.cpus, action)
+ write_json(args.output / 'summary.json', results)
+
+
+def bounded(low, high):
+ def parse(value):
+ number = int(value)
+ if not low <= number <= high:
+ raise argparse.ArgumentTypeError(f'expected a number in [{low}, {high}]')
+ return number
+ return parse
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ subparsers = parser.add_subparsers(dest='mode', required=True)
+ for mode, handler in [('stage', stage), ('http', http_benchmark), ('verify', verify)]:
+ sub = subparsers.add_parser(mode)
+ sub.set_defaults(handler=handler)
+ sub.add_argument('--output', type=Path, required=True)
+ sub.add_argument('--cpus', default='')
+ if mode == 'stage':
+ sub.add_argument('--example', type=Path, required=True)
+ sub.add_argument('--records', type=bounded(1, 10_000_000), default=50_000)
+ else:
+ sub.add_argument('--binary', type=Path, required=True)
+ if mode != 'verify':
+ sub.add_argument('--pairs', type=bounded(1, 32), default=4)
+ if mode == 'http':
+ sub.add_argument('--rows', type=bounded(1, 5000), default=100)
+ sub.add_argument('--attributes', type=bounded(4, 32), default=4)
+ sub.add_argument('--requests', type=bounded(1, 50_000), default=256)
+ args = parser.parse_args()
+ args.output = args.output.resolve()
+ if args.mode == 'stage':
+ args.example = args.example.resolve(strict=True)
+ else:
+ args.binary = args.binary.resolve(strict=True)
+ args.output.mkdir(parents=True, exist_ok=False)
+ args.handler(args)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/ingest-performance/otlp_fixtures.py b/scripts/ingest-performance/otlp_fixtures.py
new file mode 100644
index 000000000..727f797da
--- /dev/null
+++ b/scripts/ingest-performance/otlp_fixtures.py
@@ -0,0 +1,98 @@
+"""One typed OTLP request per fixture, serialized into both wire formats."""
+import json
+
+CONTENT_TYPES = {'json': 'application/json', 'protobuf': 'application/x-protobuf'}
+SIGNALS = ('logs', 'metrics', 'traces')
+HTTP_LIMIT = 10 * 2**20
+TIMESTAMP = 1_792_780_200_000_000_000
+
+
+def fixtures(signal, rows, width, batch=0, *, timestamp_ns=TIMESTAMP, padding=0):
+ # Keep the generated bindings optional for the other harnesses and their tests.
+ from google.protobuf.json_format import MessageToDict
+ from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
+ from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ExportMetricsServiceRequest
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
+
+ def attributes(target, values):
+ fields = {str: 'string_value', int: 'int_value', bool: 'bool_value', float: 'double_value'}
+ for key, value in values:
+ attribute = target.attributes.add(key=key)
+ setattr(attribute.value, fields[type(value)], value)
+
+ if signal == 'logs':
+ message = ExportLogsServiceRequest()
+ resource = message.resource_logs.add()
+ scope = resource.scope_logs.add()
+ records = scope.log_records
+ elif signal == 'metrics':
+ message = ExportMetricsServiceRequest()
+ resource = message.resource_metrics.add()
+ scope = resource.scope_metrics.add()
+ metric = scope.metrics.add(name='system.cpu.utilization', unit='1',
+ description='Fraction of time the CPU was busy')
+ records = metric.gauge.data_points
+ elif signal == 'traces':
+ message = ExportTraceServiceRequest()
+ resource = message.resource_spans.add()
+ scope = resource.scope_spans.add()
+ records = scope.spans
+ else:
+ raise ValueError(signal)
+
+ # The resource describes a host and has no service identity, so Parseable
+ # emits one row per data point without a synthetic target_info sample.
+ attributes(resource.resource, [('host.name', 'test-edge-01'),
+ ('deployment.environment.name', 'staging')])
+ scope.scope.name = 'checkout.telemetry'
+ scope.scope.version = '1.2.3'
+ for index in range(rows):
+ record = records.add()
+ timestamp = timestamp_ns + index * 1_000_000
+ trace_id = (batch * rows + index + 1).to_bytes(16, 'big')
+ span_id = (index + 1).to_bytes(8, 'big')
+ if signal == 'logs':
+ record.time_unix_nano = timestamp
+ record.observed_time_unix_nano = timestamp + 1000
+ record.severity_number = 9
+ record.severity_text = 'INFO'
+ record.body.string_value = f'Processed checkout request for order {10000 + index}'
+ record.trace_id, record.span_id = trace_id, span_id
+ elif signal == 'metrics':
+ record.time_unix_nano = timestamp
+ record.start_time_unix_nano = timestamp - 1_000_000
+ record.as_double = (index % 64) / 64
+ else:
+ record.trace_id, record.span_id = trace_id, span_id
+ record.parent_span_id = b'\x16' * 8
+ record.name = 'POST /checkout'
+ record.kind = 2
+ record.start_time_unix_nano = timestamp
+ record.end_time_unix_nano = timestamp + 12_000_000
+ record.status.code = 1
+
+ values = [('bench_batch', f'{batch:08d}'), ('bench_row', f'{index:06d}'),
+ ('http.response.status_code', 200), ('region', 'us-central')]
+ for field in range(width - len(values)):
+ value = (f'checkout-{index % 29}', index + field, index % 2 == 0, 12.5)[field % 4]
+ values.append((f'attr_{field:02d}', value))
+ if padding:
+ values.append(('bench_padding', 'x' * padding))
+ attributes(record, values)
+
+ payload = MessageToDict(message, use_integers_for_enums=True)
+ # OTLP JSON uses hex for IDs, unlike protobuf's generic JSON mapping.
+ if signal == 'logs':
+ json_records = payload['resourceLogs'][0]['scopeLogs'][0]['logRecords']
+ id_fields = ('trace_id', 'span_id')
+ elif signal == 'traces':
+ json_records = payload['resourceSpans'][0]['scopeSpans'][0]['spans']
+ id_fields = ('trace_id', 'span_id', 'parent_span_id')
+ else:
+ json_records, id_fields = (), ()
+ for source, target in zip(records, json_records):
+ for field in id_fields:
+ head, *tail = field.split('_')
+ target[head + "".join(part.title() for part in tail)] = getattr(source, field).hex()
+ return {'json': json.dumps(payload, separators=(',', ':')).encode(),
+ 'protobuf': message.SerializeToString()}
diff --git a/scripts/ingest-performance/otlp_stage.rs b/scripts/ingest-performance/otlp_stage.rs
new file mode 100644
index 000000000..3f1ae8da7
--- /dev/null
+++ b/scripts/ingest-performance/otlp_stage.rs
@@ -0,0 +1,97 @@
+//! Body bytes to flattened OTLP rows, using the server's default decoding options.
+use std::{env, fs, hint::black_box, io};
+
+use opentelemetry_proto::tonic::{
+ collector::{
+ logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest,
+ trace::v1::ExportTraceServiceRequest,
+ },
+ logs::v1::LogsData,
+ metrics::v1::MetricsData,
+ trace::v1::TracesData,
+};
+use parseable::{
+ otel::{
+ logs::{flatten_otel_logs, flatten_otel_protobuf},
+ metrics::{flatten_otel_metrics_protobuf_with_options, flatten_otel_metrics_with_options},
+ otel_utils::deserialize_otel_json,
+ traces::{flatten_otel_traces, flatten_otel_traces_protobuf},
+ },
+ parseable::DEFAULT_TENANT,
+ utils::json::flatten::{FlattenBudget, FlattenLimits},
+};
+use prost::Message as _;
+use serde::de::DeserializeOwned;
+use serde_json::Value;
+
+#[cfg(all(not(target_env = "msvc"), not(feature = "hotpath")))]
+#[global_allocator]
+static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
+
+fn decode_json(body: &[u8]) -> T {
+ deserialize_otel_json(serde_json::from_slice(body).unwrap(), false).unwrap()
+}
+
+fn stage(signal: &str, encoding: &str, body: &[u8]) -> Vec {
+ let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT);
+ match (signal, encoding) {
+ ("logs", "json") => {
+ flatten_otel_logs(&decode_json::(body), DEFAULT_TENANT, &mut budget).unwrap()
+ }
+ ("logs", "protobuf") => flatten_otel_protobuf(
+ &ExportLogsServiceRequest::decode(body).unwrap(),
+ DEFAULT_TENANT,
+ &mut budget,
+ )
+ .unwrap(),
+ ("metrics", "json") => flatten_otel_metrics_with_options(
+ decode_json::(body),
+ DEFAULT_TENANT,
+ false,
+ ),
+ ("metrics", "protobuf") => flatten_otel_metrics_protobuf_with_options(
+ &ExportMetricsServiceRequest::decode(body).unwrap(),
+ DEFAULT_TENANT,
+ false,
+ ),
+ ("traces", "json") => flatten_otel_traces(&decode_json::(body), DEFAULT_TENANT),
+ ("traces", "protobuf") => flatten_otel_traces_protobuf(
+ &ExportTraceServiceRequest::decode(body).unwrap(),
+ DEFAULT_TENANT,
+ ),
+ _ => panic!("expected logs, metrics or traces and json or protobuf"),
+ }
+}
+
+fn main() {
+ if cfg!(debug_assertions) {
+ panic!("build otlp_stage with --release");
+ }
+ let args: Vec = env::args().skip(1).collect();
+ match args.as_slice() {
+ [signal, mode, json, protobuf, rows] if mode == "check" => {
+ let from_json = stage(signal, "json", &fs::read(json).unwrap());
+ let from_protobuf = stage(signal, "protobuf", &fs::read(protobuf).unwrap());
+ assert_eq!(from_json.len(), rows.parse::().unwrap());
+ assert!(from_json == from_protobuf, "{signal} flattened rows differ");
+ }
+ [signal, encoding, body, iterations] => {
+ let body = fs::read(body).unwrap();
+ let iterations = iterations.parse::().unwrap();
+ assert!(iterations > 0);
+ let mut command = String::new();
+ let input = io::stdin();
+ println!("ready");
+ input.read_line(&mut command).unwrap();
+ assert_eq!(command.trim_end(), "start");
+ for _ in 0..iterations {
+ black_box(stage(signal, encoding, black_box(&body)));
+ }
+ println!("done");
+ // Stay alive until the caller has disabled and read the counters.
+ command.clear();
+ assert_eq!(input.read_line(&mut command).unwrap(), 0);
+ }
+ _ => panic!("otlp_stage SIGNAL (check JSON PROTOBUF ROWS | ENCODING BODY ITERATIONS)"),
+ }
+}
diff --git a/scripts/ingest-performance/test_otlp.py b/scripts/ingest-performance/test_otlp.py
new file mode 100644
index 000000000..dc21876b1
--- /dev/null
+++ b/scripts/ingest-performance/test_otlp.py
@@ -0,0 +1,115 @@
+"""Server-free checks for OTLP fixture, counter and readback oracles."""
+import base64
+import copy
+import importlib.util
+import json
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import Mock
+
+import otlp
+from otlp_fixtures import HTTP_LIMIT, SIGNALS, fixtures
+
+
+class OtlpHarnessTests(unittest.TestCase):
+ def test_abba_order_and_paired_ratio(self):
+ self.assertEqual([otlp.pair_order(i) for i in range(4)],
+ [('json', 'protobuf'), ('protobuf', 'json')] * 2)
+ sample = lambda n: otlp.per_row({'instructions': n, 'cpu_s': n / 100}, 10)
+ pairs = [{'json': sample(60), 'protobuf': sample(30)},
+ {'json': sample(600), 'protobuf': sample(150)}]
+ self.assertEqual(otlp.summarize(pairs)['protobuf_over_json']['instructions_per_row'],
+ {'median': 0.375, 'min': 0.25, 'max': 0.5})
+
+ def test_perf_counters_reject_missing_multiplexed_and_uncounted_events(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / 'perf'
+ task = '700.25;msec;task-clock;123;100.00;;\n'
+ instructions = '13000;;instructions:u;123;100.00;;\n'
+ path.write_text('# perf output\n' + instructions + task)
+ self.assertEqual(otlp.counters(path), {'instructions': 13000, 'cpu_s': 0.70025})
+ for event in ('', instructions.replace('100.00', '38.42'),
+ instructions.replace('13000', ''),
+ instructions * 2):
+ with self.subTest(event=event):
+ path.write_text(event + task)
+ with self.assertRaises(RuntimeError):
+ otlp.counters(path)
+
+ def test_readback_ignores_timestamp_and_order_only(self):
+ rows = [dict(bench_batch='00000000', bench_row=f'{i:06d}', p_timestamp='a', v=i)
+ for i in range(2)]
+ expected = otlp.canonical_rows(rows, 0, 1, 2)
+ other = [dict(row, p_timestamp='b') for row in reversed(rows)]
+ self.assertEqual(otlp.canonical_rows(other, 0, 1, 2), expected)
+ other[0]['v'] = True
+ self.assertNotEqual(otlp.canonical_rows(other, 0, 1, 2), expected)
+ with self.assertRaisesRegex(AssertionError, 'identity mismatch'):
+ otlp.canonical_rows([rows[0], rows[0]], 0, 1, 2)
+
+ def test_perf_control_accepts_nul_terminated_ack(self):
+ cmd_read, cmd_write = os.pipe()
+ ack_read, ack_write = os.pipe()
+ try:
+ os.write(ack_write, b'ack\n\0')
+ otlp.perf_control(cmd_write, ack_read, 'disable')
+ self.assertEqual(os.read(cmd_read, 50), b'disable\n')
+ finally:
+ for fd in (cmd_read, cmd_write, ack_read, ack_write):
+ os.close(fd)
+
+ def test_bad_status_and_nonempty_success_fail(self):
+ with self.assertRaises(AssertionError):
+ otlp.expect_response((503, None, b''), 200, b'')
+ with self.assertRaises(AssertionError):
+ otlp.expect_response((200, 'text/plain', b'error'), 200, b'')
+
+ def test_chunked_probe_sends_every_body_byte(self):
+ connection = Mock()
+ connection.getresponse.return_value.status = 413
+ payload = b'x' * 65536 + b'y'
+ self.assertEqual(otlp.post(connection, 'logs', 'probe', 'protobuf', payload,
+ chunked=True)[0], 413)
+ call = connection.request.call_args
+ self.assertTrue(call.kwargs['encode_chunked'])
+ self.assertNotIn('Content-Length', call.args[3])
+ self.assertEqual([bytes(chunk) for chunk in call.args[2]], [b'x' * 65536, b'y'])
+
+ @unittest.skipUnless(importlib.util.find_spec('opentelemetry'), 'install opentelemetry-proto')
+ def test_fixture_wire_encodings_match(self):
+ from google.protobuf.json_format import ParseDict
+ from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
+ from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ExportMetricsServiceRequest
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
+
+ types = dict(logs=ExportLogsServiceRequest, metrics=ExportMetricsServiceRequest,
+ traces=ExportTraceServiceRequest)
+ for signal in SIGNALS:
+ with self.subTest(signal=signal):
+ bodies = fixtures(signal, 2, 32, batch=5)
+ payload = json.loads(bodies['json'])
+ generic = copy.deepcopy(payload)
+ if signal == 'logs':
+ records = generic['resourceLogs'][0]['scopeLogs'][0]['logRecords']
+ elif signal == 'traces':
+ records = generic['resourceSpans'][0]['scopeSpans'][0]['spans']
+ else:
+ records = generic['resourceMetrics'][0]['scopeMetrics'][0]['metrics'][0]['gauge']['dataPoints']
+ self.assertEqual(len(records), 2)
+ for i, record in enumerate(records):
+ attrs = {attr['key']: attr['value'] for attr in record['attributes']}
+ self.assertEqual(len(attrs), 32)
+ self.assertEqual(attrs['bench_batch'], {'stringValue': '00000005'})
+ self.assertEqual(attrs['bench_row'], {'stringValue': f'{i:06d}'})
+ for key in {'traceId', 'spanId', 'parentSpanId'} & record.keys():
+ record[key] = base64.b64encode(bytes.fromhex(record[key])).decode()
+ parsed = ParseDict(generic, types[signal]())
+ self.assertEqual(parsed, types[signal].FromString(bodies['protobuf']))
+ self.assertTrue(all(len(body) <= HTTP_LIMIT
+ for body in fixtures(signal, 5000, 32).values()))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/ingest.ps1 b/scripts/ingest.ps1
index b1a706578..5421dc160 100644
--- a/scripts/ingest.ps1
+++ b/scripts/ingest.ps1
@@ -79,14 +79,19 @@ function Write-ParseableBanner {
}
function Write-SetupComplete {
- param([string]$StreamName)
+ param(
+ [string]$StreamName,
+ [string]$Encoding = "json"
+ )
+
+ $encodingLabel = if ($Encoding -eq "proto") { "OTLP protobuf" } else { "OTLP JSON" }
$accent = "$([char]27)[38;2;158;158;240m"
$ok = "$([char]27)[38;2;52;211;153m"
$reset = "$([char]27)[0m"
Write-Host ""
Write-Host "${ok}[OK] You're all set!${reset}"
- Write-Host "Host metrics are now being sent to Parseable as OTLP JSON."
+ Write-Host "Host metrics are now being sent to Parseable as ${encodingLabel}."
Write-Host "Dataset: " -NoNewline
Write-Host "${accent}${StreamName}${reset}"
Write-Host "Return to Parseable and click Continue to verify your data."
@@ -341,6 +346,42 @@ function ConvertTo-YamlSingleQuoted {
return "'" + $Value.Replace("'", "''") + "'"
}
+# Returns the exporter encoding to use: "proto" when the server accepts OTLP
+# protobuf, otherwise "json", which every Parseable version accepts.
+# $env:PARSEABLE_OTLP_ENCODING = "json" or "proto" skips the check.
+function Get-OtlpEncoding {
+ param(
+ [string]$Endpoint,
+ [string]$StreamName,
+ [string]$ApiKey,
+ [string]$TenantId
+ )
+
+ if ($env:PARSEABLE_OTLP_ENCODING -ceq "json" -or $env:PARSEABLE_OTLP_ENCODING -ceq "proto") {
+ return $env:PARSEABLE_OTLP_ENCODING
+ }
+
+ try {
+ $headers = @{ "X-API-Key" = $ApiKey; "X-P-Stream" = $StreamName }
+ if (-not [string]::IsNullOrWhiteSpace($TenantId)) {
+ $headers["X-P-Tenant"] = $TenantId
+ }
+
+ # An empty body is a valid export request with nothing in it. Servers
+ # with protobuf support answer 200; older ones answer 400, which throws.
+ $response = Invoke-WebRequest -Uri "$Endpoint/v1/metrics" -Method Post -Headers $headers `
+ -ContentType "application/x-protobuf" -Body ([byte[]]@()) -TimeoutSec 15 -UseBasicParsing
+ if ([int]$response.StatusCode -ge 200 -and [int]$response.StatusCode -lt 300) {
+ return "proto"
+ }
+ }
+ catch {
+ # Fall through to JSON
+ }
+
+ return "json"
+}
+
function Setup-Collector {
param(
[string]$IngestorHost,
@@ -400,6 +441,15 @@ function Setup-Collector {
Install-Collector
+ $otlpEncoding = Get-OtlpEncoding -Endpoint "${ingestorScheme}://${IngestorHost}:${Port}" `
+ -StreamName $StreamName -ApiKey $ApiKey -TenantId $TenantId
+ if ($otlpEncoding -eq "proto") {
+ Write-Info "Server accepts OTLP protobuf"
+ }
+ else {
+ Write-Info "Using OTLP JSON"
+ }
+
$endpoint = ConvertTo-YamlSingleQuoted "${ingestorScheme}://${IngestorHost}:${Port}"
$apiKeyValue = ConvertTo-YamlSingleQuoted $ApiKey
$streamNameValue = ConvertTo-YamlSingleQuoted $StreamName
@@ -430,7 +480,7 @@ function Setup-Collector {
"exporters:",
" otlp_http/parseable:",
" endpoint: $endpoint",
- " encoding: json",
+ " encoding: $otlpEncoding",
" compression: none",
" headers:",
" X-API-Key: $apiKeyValue",
@@ -503,7 +553,7 @@ function Setup-Collector {
Write-Host ""
if (Start-Collector) {
- Write-SetupComplete -StreamName $StreamName
+ Write-SetupComplete -StreamName $StreamName -Encoding $otlpEncoding
}
}
diff --git a/scripts/ingest.sh b/scripts/ingest.sh
index 7eeff6ca9..94e81f67b 100755
--- a/scripts/ingest.sh
+++ b/scripts/ingest.sh
@@ -52,14 +52,62 @@ print_parseable_banner() {
print_setup_complete() {
local stream_name="$1"
+ local encoding_label="OTLP JSON"
+
+ if [ "${2:-json}" = "proto" ]; then
+ encoding_label="OTLP protobuf"
+ fi
echo ""
echo -e "${OK}${BOLD}✓ You're all set!${NC}"
- echo "Host metrics are now being sent to Parseable as OTLP JSON."
+ echo "Host metrics are now being sent to Parseable as ${encoding_label}."
echo -e "Dataset: ${BOLD}${stream_name}${NC}"
echo "Return to Parseable and click Continue to verify your data."
}
+# Prints the exporter encoding to use: "proto" when the server accepts OTLP
+# protobuf, otherwise "json", which every Parseable version accepts.
+# PARSEABLE_OTLP_ENCODING=json|proto skips the check.
+detect_otlp_encoding() {
+ local endpoint="$1"
+ local stream_name="$2"
+ local api_key="$3"
+ local tenant_id="$4"
+ local status
+
+ case "${PARSEABLE_OTLP_ENCODING:-}" in
+ json|proto)
+ echo "$PARSEABLE_OTLP_ENCODING"
+ return 0
+ ;;
+ esac
+
+ # Header values go to curl on stdin, one per line, so a line break in one
+ # of them would add a header.
+ if ! command -v curl > /dev/null 2>&1 \
+ || [[ "$api_key$stream_name$tenant_id" == *[$'\r\n']* ]]; then
+ echo "json"
+ return 0
+ fi
+
+ # An empty body is a valid export request with nothing in it. Servers with
+ # protobuf support answer 200; older ones answer 400.
+ status=$({
+ printf 'Content-Type: application/x-protobuf\n'
+ printf 'X-API-Key: %s\n' "$api_key"
+ printf 'X-P-Stream: %s\n' "$stream_name"
+ if [ -n "$tenant_id" ]; then
+ printf 'X-P-Tenant: %s\n' "$tenant_id"
+ fi
+ } | curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 15 \
+ -X POST -H @- --data-binary '' "$endpoint/v1/metrics" 2> /dev/null) || status=""
+
+ case "$status" in
+ 2??) echo "proto" ;;
+ *) echo "json" ;;
+ esac
+}
+
is_running() {
local process_command
local config_base
@@ -312,6 +360,7 @@ setup_collector() {
local scrapers
local bracketed_host_pattern='^(\[[^]]+\])(:([0-9]+))?$'
local temp_config
+ local otlp_encoding
if [ -z "$ingestor_host" ] || [ -z "$stream_name" ] || [ -z "$api_key" ]; then
print_error "Invalid setup parameters"
@@ -358,6 +407,14 @@ setup_collector() {
install_collector
+ otlp_encoding=$(detect_otlp_encoding "${ingestor_scheme}://${ingestor_host}:${port}" \
+ "$stream_name" "$api_key" "$tenant_id")
+ if [ "$otlp_encoding" = "proto" ]; then
+ print_info "Server accepts OTLP protobuf"
+ else
+ print_info "Using OTLP JSON"
+ fi
+
endpoint_yaml=$(yaml_escape "${ingestor_scheme}://${ingestor_host}:${port}")
api_key_yaml=$(yaml_escape "$api_key")
stream_name_yaml=$(yaml_escape "$stream_name")
@@ -404,7 +461,7 @@ processors:
exporters:
otlp_http/parseable:
endpoint: '$endpoint_yaml'
- encoding: json
+ encoding: $otlp_encoding
compression: none
headers:
X-API-Key: '$api_key_yaml'
@@ -439,7 +496,7 @@ EOF
echo ""
start_collector
- print_setup_complete "$stream_name"
+ print_setup_complete "$stream_name" "$otlp_encoding"
}
case "${1:-}" in
diff --git a/src/alerts/outbound_http_policy.rs b/src/alerts/outbound_http_policy.rs
index 374a48ea6..75b359cfc 100644
--- a/src/alerts/outbound_http_policy.rs
+++ b/src/alerts/outbound_http_policy.rs
@@ -453,7 +453,8 @@ fn denied_ipv6(ip: Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() {
return true;
}
- let first = ip.segments()[0];
+ let segments = ip.segments();
+ let first = segments[0];
if (first & 0xfe00) == 0xfc00 {
return true;
@@ -462,7 +463,11 @@ fn denied_ipv6(ip: Ipv6Addr) -> bool {
return true;
}
- // Block IPv6 transition ranges that can carry embedded IPv4 destinations.
+ // Block IPv6 transition ranges that can carry embedded IPv4 destinations,
+ // including NAT64 WKP (RFC 6052) and local-use (RFC 8215) prefixes.
+ if segments[..6] == [0x0064, 0xff9b, 0, 0, 0, 0] || segments[..3] == [0x0064, 0xff9b, 1] {
+ return true;
+ }
if first == 0x2002 {
return true;
}
@@ -686,6 +691,65 @@ mod tests {
)));
}
+ #[test]
+ fn nat64_addresses_require_private_target_authorization() {
+ for address in [
+ "64:ff9b::7f00:1",
+ "64:ff9b::a9fe:a9fe",
+ "64:ff9b::ac10:fe01",
+ "64:ff9b::808:808",
+ "64:ff9b::",
+ "64:ff9b::ffff:ffff",
+ "64:ff9b:1::c0a8:1",
+ "64:ff9b:1::",
+ "64:ff9b:1:ffff:ffff:ffff:ffff:ffff",
+ ] {
+ let ip = address.parse::().unwrap();
+ let addrs = [socket(ip)];
+ for policy in [
+ AlertTargetPolicyConfig::default(),
+ policy_with(true, &[], &[]),
+ policy_with(false, &["64:ff9b::/96", "64:ff9b:1::/48"], &[]),
+ ] {
+ assert!(
+ matches!(
+ validate_resolved_addrs(address, &addrs, &policy),
+ Err(OutboundPolicyError::PrivateAddressNotAllowed(denied)) if denied == ip
+ ),
+ "{address} must require allow_private and an allowlist match"
+ );
+ }
+
+ let policy = policy_with(true, &["64:ff9b::/96", "64:ff9b:1::/48"], &[]);
+ validate_resolved_addrs(address, &addrs, &policy).unwrap();
+ }
+ }
+
+ #[test]
+ fn addresses_outside_nat64_prefixes_remain_allowed() {
+ for address in [
+ "64:ff9a:ffff:ffff:ffff:ffff:ffff:ffff",
+ "64:ff9b::1:0:0",
+ "64:ff9b:0:ffff:ffff:ffff:ffff:ffff",
+ "64:ff9b:2::",
+ "2606:4700:4700::1111",
+ ] {
+ let addrs = [socket(address.parse().unwrap())];
+ validate_resolved_addrs(address, &addrs, &AlertTargetPolicyConfig::default()).unwrap();
+ }
+ }
+
+ #[test]
+ fn mixed_public_and_nat64_addresses_are_blocked() {
+ let nat64 = "64:ff9b::7f00:1".parse::().unwrap();
+ let addrs = [socket("1.1.1.1".parse().unwrap()), socket(nat64)];
+
+ assert!(matches!(
+ validate_resolved_addrs("example.com", &addrs, &AlertTargetPolicyConfig::default()),
+ Err(OutboundPolicyError::PrivateAddressNotAllowed(ip)) if ip == nat64
+ ));
+ }
+
#[test]
fn conflicting_allow_and_deny_cidrs_are_rejected() {
let policy = policy_with(true, &["10.0.0.0/8"], &["10.1.0.0/16"]);
diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs
index ea8242371..e9b01930e 100644
--- a/src/handlers/http/ingest.rs
+++ b/src/handlers/http/ingest.rs
@@ -34,7 +34,7 @@ use crate::event::format::known_schema::{self, KNOWN_SCHEMA_LIST};
use crate::event::format::{self, EventFormat, LogSource, LogSourceEntry};
use crate::event::{self, FORMAT_KEY, USER_AGENT_KEY};
use crate::handlers::http::modal::utils::ingest_utils::{
- ingest_helper, process_otel_content, validate_stream_for_ingestion,
+ ingest_helper, otel_success_response, process_otel_content, validate_stream_for_ingestion,
};
use crate::handlers::{
DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, TELEMETRY_TYPE_KEY,
@@ -314,7 +314,7 @@ pub async fn handle_otel_logs_ingestion(
process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?;
- Ok(HttpResponse::Ok().finish())
+ Ok(otel_success_response(&req))
}
// Handler for POST /v1/metrics to ingest OTEL metrics
@@ -347,7 +347,7 @@ pub async fn handle_otel_metrics_ingestion(
)
.await?;
- Ok(HttpResponse::Ok().finish())
+ Ok(otel_success_response(&req))
}
// Handler for POST /v1/traces to ingest OTEL traces
@@ -373,7 +373,7 @@ pub async fn handle_otel_traces_ingestion(
process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?;
- Ok(HttpResponse::Ok().finish())
+ Ok(otel_success_response(&req))
}
// Handler for POST /api/v1/logstream/{logstream}
diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs
index 1192f613c..a142de13a 100644
--- a/src/handlers/http/modal/utils/ingest_utils.rs
+++ b/src/handlers/http/modal/utils/ingest_utils.rs
@@ -16,13 +16,18 @@
*
*/
-use actix_web::http::header::USER_AGENT;
+use actix_web::http::header::{CONTENT_TYPE, USER_AGENT};
use actix_web::mime::Mime;
-use actix_web::{HttpRequest, web};
+use actix_web::{HttpRequest, HttpResponse, web};
use chrono::Utc;
+use opentelemetry_proto::tonic::collector::{
+ logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest,
+ trace::v1::ExportTraceServiceRequest,
+};
use opentelemetry_proto::tonic::{
logs::v1::LogsData, metrics::v1::MetricsData, trace::v1::TracesData,
};
+use prost::Message as _;
use rayon::prelude::*;
use serde_json::Value;
use std::collections::HashMap;
@@ -44,8 +49,10 @@ use crate::{
},
},
otel::{
- logs::flatten_otel_logs, metrics::flatten_otel_metrics, otel_utils::deserialize_otel_json,
- traces::flatten_otel_traces,
+ logs::{flatten_otel_logs, flatten_otel_protobuf as flatten_otel_logs_protobuf},
+ metrics::{flatten_otel_metrics, flatten_otel_metrics_protobuf},
+ otel_utils::deserialize_otel_json,
+ traces::{flatten_otel_traces, flatten_otel_traces_protobuf},
},
parseable::{DEFAULT_TENANT, PARSEABLE},
storage::StreamType,
@@ -53,7 +60,7 @@ use crate::{
get_tenant_id_from_request,
json::{
convert_array_to_object,
- flatten::{FlattenBudget, FlattenLimits, convert_to_array},
+ flatten::{FlattenBudget, FlattenLimits, JsonFlattenError, convert_to_array},
},
},
};
@@ -126,6 +133,24 @@ pub async fn process_otel_content(
}
}
+/// Response for an OTEL export request that was ingested in full. OTLP/HTTP
+/// answers in the encoding of the request: for protobuf that is an
+/// `Export*ServiceResponse`, whose full-success form encodes to zero bytes.
+/// JSON requests keep the empty response they always had.
+pub fn otel_success_response(req: &HttpRequest) -> HttpResponse {
+ let protobuf = req
+ .headers()
+ .get(CONTENT_TYPE)
+ .and_then(|h| h.to_str().ok())
+ .and_then(classify_otel_content_type)
+ == Some(OtelContentType::Protobuf);
+ let mut response = HttpResponse::Ok();
+ if protobuf {
+ response.content_type(CONTENT_TYPE_PROTOBUF);
+ }
+ response.finish()
+}
+
/// Payload encodings accepted by the OTEL HTTP endpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OtelContentType {
@@ -189,12 +214,17 @@ fn handle_otel_ingestion(
}
}
Some(OtelContentType::Protobuf) => {
- error!(
- "Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS"
- );
- return Err(PostError::Invalid(anyhow::anyhow!(
- "Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS"
- )));
+ if let Err(e) = flatten_and_push_otel_protobuf(
+ &body,
+ &stream_name,
+ &log_source,
+ &p_custom_fields,
+ telemetry_type,
+ &tenant_id,
+ ) {
+ error!("Ingestion failed for stream {stream_name}: {e}");
+ return Err(e);
+ }
}
None => {
error!(
@@ -217,6 +247,90 @@ fn handle_otel_ingestion(
Ok(())
}
+/// An OTLP/HTTP export request decoded from its protobuf encoding.
+#[derive(Debug)]
+enum OtelProtobufRequest {
+ Logs(ExportLogsServiceRequest),
+ Metrics(ExportMetricsServiceRequest),
+ Traces(ExportTraceServiceRequest),
+}
+
+/// Why an OTLP protobuf body could not be decoded.
+#[derive(Debug, thiserror::Error)]
+enum OtelProtobufError {
+ // prost's message already starts with "failed to decode Protobuf message"
+ #[error(transparent)]
+ Decode(#[from] prost::DecodeError),
+ #[error("Protobuf OTLP ingestion requires an OTLP log source, got {0}")]
+ NotOtel(LogSource),
+}
+
+impl OtelProtobufRequest {
+ /// Decodes the export request that `log_source` selects. The whole body is
+ /// decoded before any row is built, so a body that fails to decode yields
+ /// no rows. A body cut between two top-level entries is still a valid, shorter
+ /// request: the HTTP layer, not this decoder, detects a truncated transfer.
+ fn decode(body: &[u8], log_source: &LogSource) -> Result {
+ match log_source {
+ LogSource::OtelLogs => Ok(Self::Logs(ExportLogsServiceRequest::decode(body)?)),
+ LogSource::OtelMetrics => Ok(Self::Metrics(ExportMetricsServiceRequest::decode(body)?)),
+ LogSource::OtelTraces => Ok(Self::Traces(ExportTraceServiceRequest::decode(body)?)),
+ other => Err(OtelProtobufError::NotOtel(other.clone())),
+ }
+ }
+
+ /// Flattens into the same rows the JSON encoding of this request produces.
+ fn flatten(
+ &self,
+ tenant_id: &str,
+ budget: &mut FlattenBudget,
+ ) -> Result, JsonFlattenError> {
+ match self {
+ Self::Logs(message) => flatten_otel_logs_protobuf(message, tenant_id, budget),
+ Self::Metrics(message) => Ok(flatten_otel_metrics_protobuf(message, tenant_id)),
+ Self::Traces(message) => Ok(flatten_otel_traces_protobuf(message, tenant_id)),
+ }
+ }
+}
+
+/// Protobuf counterpart of the OTEL arms of `flatten_and_push_logs`: the typed
+/// request is decoded straight from the body instead of going through a JSON
+/// value tree, then shares flattening limits and the staging path with JSON.
+/// The body size is capped by the `PayloadConfig` of the OTEL routes.
+fn flatten_and_push_otel_protobuf(
+ body: &[u8],
+ stream_name: &str,
+ log_source: &LogSource,
+ p_custom_fields: &HashMap,
+ telemetry_type: TelemetryType,
+ tenant_id: &Option,
+) -> Result<(), PostError> {
+ let request = OtelProtobufRequest::decode(body, log_source).map_err(|e| {
+ PostError::Invalid(anyhow::anyhow!(
+ "Ingestion failed for stream {stream_name}: {e}"
+ ))
+ })?;
+ let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT);
+ // Verify the dataset fields count
+ verify_dataset_fields_count(stream_name, tenant_id)?;
+ // Shared by every record of this request
+ let mut budget = FlattenBudget::new(FlattenLimits::from_config());
+ let records = request.flatten(tenant_str, &mut budget)?;
+ if !records.is_empty() {
+ push_logs(
+ stream_name,
+ Value::Array(records),
+ log_source,
+ p_custom_fields,
+ None,
+ telemetry_type,
+ tenant_id,
+ &mut budget,
+ )?;
+ }
+ Ok(())
+}
+
#[instrument(
name = "flatten_and_push_logs",
level = "info",
@@ -1012,7 +1126,7 @@ mod tests {
}
#[tokio::test]
- async fn test_process_otel_content_protobuf_variants_still_unsupported() {
+ async fn test_process_otel_content_protobuf_variants_reach_protobuf_decoding() {
let protobuf = [
"application/x-protobuf",
"application/x-protobuf; charset=utf-8",
@@ -1021,17 +1135,198 @@ mod tests {
];
for (telemetry_type, log_source) in OTEL_SIGNALS {
for value in protobuf {
+ // The shared malformed body is not a protobuf message either, so this
+ // fails in the decoder before any PARSEABLE/storage access
let err = run_otel_content(header(value), telemetry_type, &log_source).await;
assert!(matches!(err, PostError::Invalid(_)), "{err:?}");
- assert_bad_request_body(
- &err,
- &format!(
- "Invalid Request: Ingestion failed for stream {OTEL_TEST_STREAM}: Protobuf ingestion is not supported in Parseable OSS"
- ),
- )
- .await;
+ let expected = err.to_string();
+ assert!(
+ expected.starts_with(&format!(
+ "Invalid Request: Ingestion failed for stream {OTEL_TEST_STREAM}: failed to decode Protobuf message: "
+ )),
+ "{log_source} with {value:?}: {expected}"
+ );
+ assert_bad_request_body(&err, &expected).await;
+ }
+ }
+ }
+
+ #[test]
+ fn otel_success_response_answers_in_the_request_encoding() {
+ use actix_web::http::header::CONTENT_TYPE;
+
+ for (request_type, response_type) in [
+ (
+ Some("application/x-protobuf"),
+ Some("application/x-protobuf"),
+ ),
+ (
+ Some("Application/X-Protobuf; charset=utf-8"),
+ Some("application/x-protobuf"),
+ ),
+ (Some("application/json"), None),
+ (None, None),
+ ] {
+ let mut req = TestRequest::default();
+ if let Some(value) = request_type {
+ req = req.insert_header((CONTENT_TYPE, value));
+ }
+ let resp = otel_success_response(&req.to_http_request());
+ assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
+ assert_eq!(
+ resp.headers()
+ .get(CONTENT_TYPE)
+ .map(|v| v.to_str().unwrap()),
+ response_type,
+ "request content type {request_type:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn otel_protobuf_decode_rejects_non_otel_log_source() {
+ let err = OtelProtobufRequest::decode(&[], &LogSource::Json).unwrap_err();
+ assert!(matches!(err, OtelProtobufError::NotOtel(LogSource::Json)));
+ }
+
+ #[test]
+ fn otel_protobuf_body_cut_inside_a_record_fails_to_decode() {
+ use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
+
+ let encoded = ExportLogsServiceRequest {
+ resource_logs: vec![ResourceLogs {
+ scope_logs: vec![ScopeLogs {
+ log_records: vec![LogRecord {
+ severity_text: "INFO".to_string(),
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ }
+ .encode_to_vec();
+
+ assert!(matches!(
+ OtelProtobufRequest::decode(&encoded, &LogSource::OtelLogs),
+ Ok(OtelProtobufRequest::Logs(_))
+ ));
+ // One top-level entry, so every proper prefix ends inside it
+ for len in 1..encoded.len() {
+ assert!(
+ matches!(
+ OtelProtobufRequest::decode(&encoded[..len], &LogSource::OtelLogs),
+ Err(OtelProtobufError::Decode(_))
+ ),
+ "a body cut to {len} of {} bytes must not decode",
+ encoded.len()
+ );
+ }
+ }
+
+ /// The protobuf and JSON encodings of one request must flatten to the same rows.
+ #[test]
+ fn otel_protobuf_and_json_encodings_flatten_to_the_same_rows() {
+ use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value};
+ use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
+ use opentelemetry_proto::tonic::resource::v1::Resource;
+ use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span};
+
+ fn string_attribute(key: &str, value: &str) -> KeyValue {
+ KeyValue {
+ key: key.to_string(),
+ value: Some(AnyValue {
+ value: Some(any_value::Value::StringValue(value.to_string())),
+ }),
+ ..Default::default()
}
}
+ let limits = || FlattenBudget::new(FlattenLimits::DEFAULT);
+
+ let resource = Some(Resource {
+ attributes: vec![string_attribute("service.name", "checkout")],
+ ..Default::default()
+ });
+ let logs = LogsData {
+ resource_logs: vec![ResourceLogs {
+ resource: resource.clone(),
+ scope_logs: vec![ScopeLogs {
+ log_records: vec![
+ LogRecord {
+ time_unix_nano: 1_700_000_000_000_000_000,
+ observed_time_unix_nano: 1_700_000_000_000_000_001,
+ severity_number: 9,
+ severity_text: "INFO".to_string(),
+ body: Some(AnyValue {
+ value: Some(any_value::Value::StringValue("paid".to_string())),
+ }),
+ attributes: vec![string_attribute("order", "42")],
+ trace_id: vec![0xab; 16],
+ span_id: vec![0xcd; 8],
+ ..Default::default()
+ },
+ // Unset timestamps are filled from the clock, so every one is set
+ LogRecord {
+ time_unix_nano: 1_700_000_001_000_000_000,
+ observed_time_unix_nano: 1_700_000_001_000_000_001,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ };
+ let json: LogsData = serde_json::from_value(serde_json::to_value(&logs).unwrap()).unwrap();
+ let protobuf = OtelProtobufRequest::decode(
+ &ExportLogsServiceRequest {
+ resource_logs: logs.resource_logs.clone(),
+ }
+ .encode_to_vec(),
+ &LogSource::OtelLogs,
+ )
+ .unwrap();
+ let from_json = flatten_otel_logs(&json, "tenant", &mut limits()).unwrap();
+ assert_eq!(from_json.len(), 2);
+ assert_eq!(
+ protobuf.flatten("tenant", &mut limits()).unwrap(),
+ from_json
+ );
+
+ let traces = TracesData {
+ resource_spans: vec![ResourceSpans {
+ resource,
+ scope_spans: vec![ScopeSpans {
+ spans: vec![Span {
+ trace_id: vec![0x11; 16],
+ span_id: vec![0x22; 8],
+ name: "charge".to_string(),
+ start_time_unix_nano: 1_700_000_000_000_000_000,
+ end_time_unix_nano: 1_700_000_000_500_000_000,
+ attributes: vec![string_attribute("order", "42")],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ };
+ let json: TracesData =
+ serde_json::from_value(serde_json::to_value(&traces).unwrap()).unwrap();
+ let protobuf = OtelProtobufRequest::decode(
+ &ExportTraceServiceRequest {
+ resource_spans: traces.resource_spans.clone(),
+ }
+ .encode_to_vec(),
+ &LogSource::OtelTraces,
+ )
+ .unwrap();
+ let from_json = flatten_otel_traces(&json, "tenant");
+ assert_eq!(from_json.len(), 1);
+ assert_eq!(
+ protobuf.flatten("tenant", &mut limits()).unwrap(),
+ from_json
+ );
}
#[test]
@@ -1045,3 +1340,6 @@ mod tests {
assert_eq!(custom_fields.get(SOURCE_IP_KEY).unwrap(), "192.0.2.1");
}
}
+
+#[cfg(test)]
+mod otel_protobuf_props;
diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs
new file mode 100644
index 000000000..42dcec73f
--- /dev/null
+++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs
@@ -0,0 +1,2543 @@
+/*
+ * Parseable Server (C) 2022 - 2025 Parseable, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ *
+ */
+
+//! Property tests and seeded deterministic ("DST-style") tests of OTLP/HTTP
+//! protobuf ingestion, checked against the OTLP JSON path.
+//!
+//! The protobuf and JSON paths share the flatteners (they work on the same
+//! typed messages), so the encodings can only diverge where decoding does:
+//! prost on one side, the `with-serde` mapping of `opentelemetry-proto` plus
+//! `deserialize_otel_json` on the other. The differential properties encode one
+//! generated request both ways and require identical rows.
+//!
+//! The JSON mapping can not carry every protobuf message. The differential
+//! properties run over the requests it can carry (`json_representable`); every
+//! excluded construct has its own `json_mapping_*` test below that pins what the
+//! JSON path does with it instead.
+//!
+//! Nothing here touches the `PARSEABLE` global, so every test may be run with a
+//! name filter. The pipeline is followed down to the flattened rows; see
+//! `dst_otlp_mixed_encoding_ingest` for where it stops and why.
+//!
+//! Environment:
+//! - `OTLP_PB_PROPTEST_CASES`: cases per property (defaults keep the run quick)
+//! - `OTLP_PB_PROPTEST_SEED`: u64 seed of the property runs (default 0, so a
+//! default run is deterministic)
+//! - `DST_SEED`, `DST_ITERS`: first seed and number of seeds of the DST scenario
+
+use super::*;
+use crate::otel::metrics::{
+ flatten_otel_metrics_protobuf_with_options, flatten_otel_metrics_with_options,
+};
+use crate::otel::otel_utils::flatten_attributes;
+use crate::utils::json::flatten::FlattenCost;
+use opentelemetry_proto::tonic::common::v1::{
+ AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value,
+};
+use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
+use opentelemetry_proto::tonic::metrics::v1::{
+ Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram,
+ HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary,
+ SummaryDataPoint, exemplar, exponential_histogram_data_point::Buckets, metric,
+ number_data_point, summary_data_point::ValueAtQuantile,
+};
+use opentelemetry_proto::tonic::resource::v1::Resource;
+use opentelemetry_proto::tonic::trace::v1::{
+ ResourceSpans, ScopeSpans, Span, Status,
+ span::{Event, Link},
+};
+use proptest::collection::vec;
+use proptest::prelude::*;
+use proptest::strategy::ValueTree;
+use proptest::test_runner::{
+ Config, RngAlgorithm, TestCaseError, TestCaseResult, TestRng, TestRunner,
+};
+use serde_json::json;
+use std::collections::BTreeMap;
+use std::fmt::Debug;
+use std::hash::{Hash, Hasher};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+const TENANT: &str = "tenant";
+
+// ---------------------------------------------------------------------------
+// Seeds and runners
+// ---------------------------------------------------------------------------
+
+/// SplitMix64, the generator of the DST conventions
+#[derive(Debug, Clone)]
+struct SplitMix64(u64);
+
+impl SplitMix64 {
+ fn next_u64(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ let mut z = self.0;
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ }
+
+ fn below(&mut self, n: u64) -> u64 {
+ self.next_u64() % n.max(1)
+ }
+
+ fn percent(&mut self, pct: u64) -> bool {
+ self.below(100) < pct
+ }
+
+ fn seed32(&mut self) -> [u8; 32] {
+ let mut seed = [0u8; 32];
+ for chunk in seed.chunks_mut(8) {
+ chunk.copy_from_slice(&self.next_u64().to_le_bytes());
+ }
+ seed
+ }
+}
+
+fn env_u64(name: &str) -> Option {
+ std::env::var(name).ok().map(|value| {
+ value
+ .parse()
+ .unwrap_or_else(|_| panic!("{name} must be a u64, got {value:?}"))
+ })
+}
+
+/// A deterministic runner: the same `OTLP_PB_PROPTEST_SEED` gives the same cases
+fn runner(default_cases: u32) -> TestRunner {
+ let cases = env_u64("OTLP_PB_PROPTEST_CASES").map_or(default_cases, |cases| cases as u32);
+ let seed = env_u64("OTLP_PB_PROPTEST_SEED").unwrap_or(0);
+ TestRunner::new_with_rng(
+ Config {
+ cases,
+ failure_persistence: None,
+ max_shrink_iters: 4096,
+ max_shrink_time: 60_000,
+ ..Config::default()
+ },
+ TestRng::from_seed(RngAlgorithm::ChaCha, &SplitMix64(seed).seed32()),
+ )
+}
+
+fn check(name: &str, default_cases: u32, strategy: S, test: impl Fn(S::Value) -> TestCaseResult)
+where
+ S: Strategy,
+ S::Value: Debug,
+{
+ if let Err(error) = runner(default_cases).run(&strategy, test) {
+ panic!(
+ "{name} (OTLP_PB_PROPTEST_SEED={}): {error}",
+ env_u64("OTLP_PB_PROPTEST_SEED").unwrap_or(0)
+ );
+ }
+}
+
+/// One value of `strategy`, drawn deterministically from `rng`
+fn sample(strategy: &BoxedStrategy, rng: &mut SplitMix64) -> T {
+ let mut runner = TestRunner::new_with_rng(
+ Config::default(),
+ TestRng::from_seed(RngAlgorithm::ChaCha, &rng.seed32()),
+ );
+ strategy
+ .new_tree(&mut runner)
+ .expect("generators never reject")
+ .current()
+}
+
+// ---------------------------------------------------------------------------
+// Generators
+// ---------------------------------------------------------------------------
+//
+// `wild` widens the domain to protobuf messages the JSON mapping can not carry:
+// non-finite doubles in plain `double` fields, an `AnyValue` with no value, and
+// `string_value_strindex`. Without it the generators still produce non-finite
+// doubles where the JSON mapping carries them (`Option` histogram
+// sum/min/max, which become null, and summary quantiles, which are "NaN"
+// strings).
+
+fn text() -> BoxedStrategy {
+ prop_oneof![
+ 4 => "[a-z]{0,6}",
+ 1 => Just(String::new()),
+ 1 => Just("ünïcødé 日本語 🎉".to_string()),
+ 1 => Just("\u{0}\t\"\\/\u{7f}\u{2028}\u{feff}".to_string()),
+ 1 => Just(r#"{"x":1}"#.to_string()),
+ 1 => any::().prop_map(|s| s.chars().take(10).collect()),
+ ]
+ .boxed()
+}
+
+/// A small pool, so keys repeat, plus names of fields the flatteners set themselves
+fn key() -> BoxedStrategy {
+ prop_oneof![
+ 4 => prop::sample::select(vec![
+ "", "k", "dup", "a.b", "service.name", "service.instance.id", "service.namespace",
+ "body", "trace_id", "time_unix_nano", "p_log_category", "metric_name",
+ "span_name", "exemplars",
+ ])
+ .prop_map(str::to_string),
+ 1 => text(),
+ ]
+ .boxed()
+}
+
+fn int64() -> BoxedStrategy {
+ prop_oneof![
+ Just(i64::MIN),
+ Just(i64::MAX),
+ Just(0),
+ Just(-1),
+ any::()
+ ]
+ .boxed()
+}
+
+fn finite_f64() -> BoxedStrategy {
+ use prop::num::f64::{NEGATIVE, NORMAL, POSITIVE, SUBNORMAL, ZERO};
+ prop_oneof![
+ 4 => POSITIVE | NEGATIVE | NORMAL | SUBNORMAL | ZERO,
+ 1 => prop::sample::select(vec![
+ 0.0, -0.0, f64::MAX, f64::MIN, f64::MIN_POSITIVE, 5e-324, 0.1 + 0.2, 1e300, -1.5e-300,
+ ]),
+ ]
+ .boxed()
+}
+
+fn any_f64() -> BoxedStrategy {
+ prop_oneof![
+ 4 => finite_f64(),
+ 1 => prop::sample::select(vec![f64::NAN, f64::INFINITY, f64::NEG_INFINITY]),
+ ]
+ .boxed()
+}
+
+/// Whether serde_json reads back exactly the double it writes. It does not
+/// always: the crate is built without serde_json's `float_roundtrip` feature,
+/// see `json_path_reads_some_doubles_one_ulp_off`.
+fn json_round_trips(double: f64) -> bool {
+ !double.is_finite()
+ || serde_json::from_str::(&serde_json::to_string(&double).unwrap())
+ .is_ok_and(|read| read.to_bits() == double.to_bits())
+}
+
+/// A double for a plain `double` field: finite and read back exactly by
+/// serde_json, unless `wild`
+fn plain_f64(wild: bool) -> BoxedStrategy {
+ if wild {
+ any_f64()
+ } else {
+ finite_f64()
+ .prop_filter("serde_json reads it back exactly", |d| json_round_trips(*d))
+ .boxed()
+ }
+}
+
+/// A double the JSON mapping may write as null or "NaN", but otherwise exact
+fn carried_f64() -> BoxedStrategy {
+ any_f64()
+ .prop_filter("serde_json reads it back exactly", |d| json_round_trips(*d))
+ .boxed()
+}
+
+/// Unsigned nanoseconds, never 0: an unset timestamp is filled from the clock
+fn ts() -> BoxedStrategy {
+ prop_oneof![
+ Just(1u64),
+ Just(u64::MAX),
+ Just(1u64 << 63),
+ 1u64..=u64::MAX,
+ 1_600_000_000_000_000_000u64..1_800_000_000_000_000_000,
+ ]
+ .boxed()
+}
+
+fn id() -> BoxedStrategy> {
+ prop_oneof![
+ Just(vec![]),
+ Just(vec![0; 16]),
+ Just(vec![0xff; 16]),
+ Just(vec![0; 8]),
+ Just(vec![0xff; 8]),
+ vec(any::(), 0..20),
+ ]
+ .boxed()
+}
+
+fn count32() -> BoxedStrategy {
+ prop_oneof![Just(0u32), Just(u32::MAX), any::()].boxed()
+}
+
+fn scalar_value(wild: bool) -> BoxedStrategy> {
+ use any_value::Value as V;
+ let representable = prop_oneof![
+ text().prop_map(V::StringValue),
+ any::().prop_map(V::BoolValue),
+ int64().prop_map(V::IntValue),
+ plain_f64(wild).prop_map(V::DoubleValue),
+ vec(any::(), 0..8).prop_map(V::BytesValue),
+ ]
+ .prop_map(Some);
+ if wild {
+ prop_oneof![
+ 6 => representable,
+ 1 => Just(None),
+ 1 => any::().prop_map(|index| Some(V::StringValueStrindex(index))),
+ ]
+ .boxed()
+ } else {
+ representable.boxed()
+ }
+}
+
+fn key_value_of(value: BoxedStrategy) -> BoxedStrategy {
+ (
+ key(),
+ prop::option::weighted(0.9, value),
+ prop_oneof![4 => Just(0), 1 => any::()],
+ )
+ .prop_map(|(key, value, key_strindex)| KeyValue {
+ key,
+ value,
+ key_strindex,
+ })
+ .boxed()
+}
+
+/// Every `AnyValue` variant, with arrays and key-value lists nested up to 3 deep
+fn any_value(wild: bool) -> BoxedStrategy {
+ use any_value::Value as V;
+ scalar_value(wild)
+ .prop_map(|value| AnyValue { value })
+ .prop_recursive(3, 24, 4, |inner| {
+ prop_oneof![
+ vec(inner.clone(), 0..4).prop_map(|values| AnyValue {
+ value: Some(V::ArrayValue(ArrayValue { values })),
+ }),
+ vec(key_value_of(inner), 0..4).prop_map(|values| AnyValue {
+ value: Some(V::KvlistValue(KeyValueList { values })),
+ }),
+ ]
+ })
+ .boxed()
+}
+
+fn attributes(wild: bool) -> BoxedStrategy> {
+ vec(key_value_of(any_value(wild)), 0..4).boxed()
+}
+
+fn resource(wild: bool) -> BoxedStrategy> {
+ prop::option::weighted(
+ 0.8,
+ (attributes(wild), count32()).prop_map(|(attributes, dropped_attributes_count)| Resource {
+ attributes,
+ dropped_attributes_count,
+ ..Default::default()
+ }),
+ )
+ .boxed()
+}
+
+fn scope(wild: bool) -> BoxedStrategy > {
+ prop::option::weighted(
+ 0.8,
+ (text(), text(), attributes(wild), count32()).prop_map(
+ |(name, version, attributes, dropped_attributes_count)| InstrumentationScope {
+ name,
+ version,
+ attributes,
+ dropped_attributes_count,
+ },
+ ),
+ )
+ .boxed()
+}
+
+/// A tree of JSON values, for log bodies that are JSON object text
+fn json_tree() -> BoxedStrategy {
+ prop_oneof![
+ Just(Value::Null),
+ any::().prop_map(Value::Bool),
+ any::().prop_map(Value::from),
+ "[a-z]{0,4}".prop_map(Value::String),
+ ]
+ .prop_recursive(3, 16, 3, |inner| {
+ prop_oneof![
+ vec(inner.clone(), 0..4).prop_map(Value::Array),
+ vec(("[a-c]{1,2}", inner), 0..3)
+ .prop_map(|fields| Value::Object(fields.into_iter().collect())),
+ ]
+ })
+ .boxed()
+}
+
+fn json_object_text() -> BoxedStrategy {
+ vec(("[a-c]{1,2}", json_tree()), 0..4)
+ .prop_map(|fields| Value::Object(fields.into_iter().collect()).to_string())
+ .boxed()
+}
+
+fn log_body(wild: bool) -> BoxedStrategy> {
+ prop::option::weighted(
+ 0.85,
+ prop_oneof![
+ 3 => any_value(wild),
+ 2 => json_object_text().prop_map(|text| AnyValue {
+ value: Some(any_value::Value::StringValue(text)),
+ }),
+ 1 => vec(("[a-c]{1,2}", json_object_text()), 0..3).prop_map(|fields| AnyValue {
+ value: Some(any_value::Value::KvlistValue(KeyValueList {
+ values: fields
+ .into_iter()
+ .map(|(key, text)| KeyValue {
+ key,
+ value: Some(AnyValue {
+ value: Some(any_value::Value::StringValue(text)),
+ }),
+ key_strindex: 0,
+ })
+ .collect(),
+ })),
+ }),
+ ],
+ )
+ .boxed()
+}
+
+fn log_record(wild: bool) -> BoxedStrategy {
+ (
+ (ts(), ts()),
+ prop_oneof![
+ 0..=24i32,
+ Just(i32::MIN),
+ Just(i32::MAX),
+ Just(-1),
+ Just(25)
+ ],
+ prop_oneof![
+ Just(String::new()),
+ prop::sample::select(vec![
+ "INFO",
+ "error",
+ "WARN",
+ "UNSPECIFIED",
+ " unspecified ",
+ "SEVERITY_NUMBER_FATAL4",
+ ])
+ .prop_map(str::to_string),
+ text(),
+ ],
+ log_body(wild),
+ attributes(wild),
+ (count32(), count32()),
+ (id(), id()),
+ text(),
+ )
+ .prop_map(
+ |(
+ (time_unix_nano, observed_time_unix_nano),
+ severity_number,
+ severity_text,
+ body,
+ attributes,
+ (dropped_attributes_count, flags),
+ (trace_id, span_id),
+ event_name,
+ )| LogRecord {
+ time_unix_nano,
+ observed_time_unix_nano,
+ severity_number,
+ severity_text,
+ body,
+ attributes,
+ dropped_attributes_count,
+ flags,
+ trace_id,
+ span_id,
+ event_name,
+ },
+ )
+ .boxed()
+}
+
+fn logs_data(wild: bool) -> BoxedStrategy {
+ let scope_logs = (scope(wild), vec(log_record(wild), 0..4), text()).prop_map(
+ |(scope, log_records, schema_url)| ScopeLogs {
+ scope,
+ log_records,
+ schema_url,
+ },
+ );
+ vec(
+ (resource(wild), vec(scope_logs, 0..3), text()).prop_map(
+ |(resource, scope_logs, schema_url)| ResourceLogs {
+ resource,
+ scope_logs,
+ schema_url,
+ },
+ ),
+ 0..3,
+ )
+ .prop_map(|resource_logs| LogsData { resource_logs })
+ .boxed()
+}
+
+fn span_flags() -> BoxedStrategy {
+ prop_oneof![
+ prop::sample::select(vec![0u32, 1, 255, 256, 512, 768]),
+ any::()
+ ]
+ .boxed()
+}
+
+fn span(wild: bool) -> BoxedStrategy {
+ let event = (ts(), text(), attributes(wild), count32()).prop_map(
+ |(time_unix_nano, name, attributes, dropped_attributes_count)| Event {
+ time_unix_nano,
+ name,
+ attributes,
+ dropped_attributes_count,
+ },
+ );
+ let link = (
+ id(),
+ id(),
+ text(),
+ attributes(wild),
+ count32(),
+ span_flags(),
+ )
+ .prop_map(
+ |(trace_id, span_id, trace_state, attributes, dropped_attributes_count, flags)| Link {
+ trace_id,
+ span_id,
+ trace_state,
+ attributes,
+ dropped_attributes_count,
+ flags,
+ },
+ );
+ let status = prop::option::weighted(
+ 0.7,
+ (text(), prop_oneof![0..=2i32, any::()])
+ .prop_map(|(message, code)| Status { message, code }),
+ );
+ (
+ (id(), id(), text(), id()),
+ (span_flags(), text(), prop_oneof![0..=5i32, any::()]),
+ (ts(), ts()),
+ (attributes(wild), count32()),
+ (vec(event, 0..3), count32()),
+ (vec(link, 0..3), count32()),
+ status,
+ )
+ .prop_map(
+ |(
+ (trace_id, span_id, trace_state, parent_span_id),
+ (flags, name, kind),
+ (start_time_unix_nano, end_time_unix_nano),
+ (attributes, dropped_attributes_count),
+ (events, dropped_events_count),
+ (links, dropped_links_count),
+ status,
+ )| Span {
+ trace_id,
+ span_id,
+ trace_state,
+ parent_span_id,
+ flags,
+ name,
+ kind,
+ start_time_unix_nano,
+ end_time_unix_nano,
+ attributes,
+ dropped_attributes_count,
+ events,
+ dropped_events_count,
+ links,
+ dropped_links_count,
+ status,
+ },
+ )
+ .boxed()
+}
+
+fn traces_data(wild: bool) -> BoxedStrategy {
+ let scope_spans =
+ (scope(wild), vec(span(wild), 0..4), text()).prop_map(|(scope, spans, schema_url)| {
+ ScopeSpans {
+ scope,
+ spans,
+ schema_url,
+ }
+ });
+ vec(
+ (resource(wild), vec(scope_spans, 0..3), text()).prop_map(
+ |(resource, scope_spans, schema_url)| ResourceSpans {
+ resource,
+ scope_spans,
+ schema_url,
+ },
+ ),
+ 0..3,
+ )
+ .prop_map(|resource_spans| TracesData { resource_spans })
+ .boxed()
+}
+
+fn data_point_flags() -> BoxedStrategy {
+ prop_oneof![Just(0u32), Just(1), any::()].boxed()
+}
+
+fn temporality() -> BoxedStrategy {
+ prop_oneof![0..=2i32, any::()].boxed()
+}
+
+fn exemplars(wild: bool) -> BoxedStrategy> {
+ vec(
+ (
+ attributes(wild),
+ ts(),
+ id(),
+ id(),
+ prop::option::weighted(
+ 0.9,
+ prop_oneof![
+ plain_f64(wild).prop_map(exemplar::Value::AsDouble),
+ int64().prop_map(exemplar::Value::AsInt),
+ ],
+ ),
+ )
+ .prop_map(
+ |(filtered_attributes, time_unix_nano, span_id, trace_id, value)| Exemplar {
+ filtered_attributes,
+ time_unix_nano,
+ span_id,
+ trace_id,
+ value,
+ },
+ ),
+ 0..3,
+ )
+ .boxed()
+}
+
+fn number_data_points(wild: bool) -> BoxedStrategy> {
+ vec(
+ (
+ attributes(wild),
+ (ts(), ts()),
+ exemplars(wild),
+ data_point_flags(),
+ prop::option::weighted(
+ 0.9,
+ prop_oneof![
+ plain_f64(wild).prop_map(number_data_point::Value::AsDouble),
+ int64().prop_map(number_data_point::Value::AsInt),
+ ],
+ ),
+ )
+ .prop_map(
+ |(attributes, (start_time_unix_nano, time_unix_nano), exemplars, flags, value)| {
+ NumberDataPoint {
+ attributes,
+ start_time_unix_nano,
+ time_unix_nano,
+ exemplars,
+ flags,
+ value,
+ }
+ },
+ ),
+ 0..3,
+ )
+ .boxed()
+}
+
+fn optional_f64() -> BoxedStrategy> {
+ prop::option::weighted(0.8, carried_f64()).boxed()
+}
+
+fn histogram_data_points(wild: bool) -> BoxedStrategy> {
+ vec(
+ (
+ attributes(wild),
+ (ts(), ts()),
+ (any::(), optional_f64()),
+ (vec(any::(), 0..4), vec(plain_f64(wild), 0..4)),
+ exemplars(wild),
+ data_point_flags(),
+ (optional_f64(), optional_f64()),
+ )
+ .prop_map(
+ |(
+ attributes,
+ (start_time_unix_nano, time_unix_nano),
+ (count, sum),
+ (bucket_counts, explicit_bounds),
+ exemplars,
+ flags,
+ (min, max),
+ )| HistogramDataPoint {
+ attributes,
+ start_time_unix_nano,
+ time_unix_nano,
+ count,
+ sum,
+ bucket_counts,
+ explicit_bounds,
+ exemplars,
+ flags,
+ min,
+ max,
+ },
+ ),
+ 0..3,
+ )
+ .boxed()
+}
+
+fn buckets() -> BoxedStrategy> {
+ prop::option::weighted(
+ 0.7,
+ (any::(), vec(any::(), 0..4)).prop_map(|(offset, bucket_counts)| Buckets {
+ offset,
+ bucket_counts,
+ }),
+ )
+ .boxed()
+}
+
+fn exp_histogram_data_points(wild: bool) -> BoxedStrategy> {
+ vec(
+ (
+ attributes(wild),
+ (ts(), ts()),
+ (any::(), optional_f64(), any::(), any::()),
+ (buckets(), buckets()),
+ (data_point_flags(), exemplars(wild)),
+ (optional_f64(), optional_f64(), plain_f64(wild)),
+ )
+ .prop_map(
+ |(
+ attributes,
+ (start_time_unix_nano, time_unix_nano),
+ (count, sum, scale, zero_count),
+ (positive, negative),
+ (flags, exemplars),
+ (min, max, zero_threshold),
+ )| ExponentialHistogramDataPoint {
+ attributes,
+ start_time_unix_nano,
+ time_unix_nano,
+ count,
+ sum,
+ scale,
+ zero_count,
+ positive,
+ negative,
+ flags,
+ exemplars,
+ min,
+ max,
+ zero_threshold,
+ },
+ ),
+ 0..3,
+ )
+ .boxed()
+}
+
+fn summary_data_points(wild: bool) -> BoxedStrategy> {
+ vec(
+ (
+ attributes(wild),
+ (ts(), ts()),
+ (any::(), plain_f64(wild)),
+ vec(
+ (carried_f64(), carried_f64())
+ .prop_map(|(quantile, value)| ValueAtQuantile { quantile, value }),
+ 0..3,
+ ),
+ data_point_flags(),
+ )
+ .prop_map(
+ |(
+ attributes,
+ (start_time_unix_nano, time_unix_nano),
+ (count, sum),
+ quantile_values,
+ flags,
+ )| SummaryDataPoint {
+ attributes,
+ start_time_unix_nano,
+ time_unix_nano,
+ count,
+ sum,
+ quantile_values,
+ flags,
+ },
+ ),
+ 0..3,
+ )
+ .boxed()
+}
+
+fn metric_data(wild: bool) -> BoxedStrategy> {
+ prop::option::weighted(
+ 0.9,
+ prop_oneof![
+ number_data_points(wild)
+ .prop_map(|data_points| metric::Data::Gauge(Gauge { data_points })),
+ (number_data_points(wild), temporality(), any::()).prop_map(
+ |(data_points, aggregation_temporality, is_monotonic)| metric::Data::Sum(Sum {
+ data_points,
+ aggregation_temporality,
+ is_monotonic,
+ })
+ ),
+ (histogram_data_points(wild), temporality()).prop_map(
+ |(data_points, aggregation_temporality)| metric::Data::Histogram(Histogram {
+ data_points,
+ aggregation_temporality,
+ })
+ ),
+ (exp_histogram_data_points(wild), temporality()).prop_map(
+ |(data_points, aggregation_temporality)| {
+ metric::Data::ExponentialHistogram(ExponentialHistogram {
+ data_points,
+ aggregation_temporality,
+ })
+ }
+ ),
+ summary_data_points(wild)
+ .prop_map(|data_points| metric::Data::Summary(Summary { data_points })),
+ ],
+ )
+ .boxed()
+}
+
+fn metric(wild: bool) -> BoxedStrategy {
+ (text(), text(), text(), attributes(wild), metric_data(wild))
+ .prop_map(|(name, description, unit, metadata, data)| Metric {
+ name,
+ description,
+ unit,
+ metadata,
+ data,
+ })
+ .boxed()
+}
+
+fn metrics_data(wild: bool) -> BoxedStrategy {
+ let scope_metrics =
+ (scope(wild), vec(metric(wild), 0..4), text()).prop_map(|(scope, metrics, schema_url)| {
+ ScopeMetrics {
+ scope,
+ metrics,
+ schema_url,
+ }
+ });
+ vec(
+ (resource(wild), vec(scope_metrics, 0..3), text()).prop_map(
+ |(resource, scope_metrics, schema_url)| ResourceMetrics {
+ resource,
+ scope_metrics,
+ schema_url,
+ },
+ ),
+ 0..3,
+ )
+ .prop_map(|resource_metrics| MetricsData { resource_metrics })
+ .boxed()
+}
+
+fn tight_limits() -> BoxedStrategy {
+ (1usize..16, 1usize..24, 16usize..1024)
+ .prop_map(
+ |(max_rows_per_event, max_rows_per_request, max_bytes_per_request)| FlattenLimits {
+ max_rows_per_event,
+ max_rows_per_request,
+ max_bytes_per_request,
+ },
+ )
+ .boxed()
+}
+
+// ---------------------------------------------------------------------------
+// One request, both encodings
+// ---------------------------------------------------------------------------
+
+/// A request of one signal, held as the JSON-side message type
+#[derive(Debug, Clone)]
+enum Req {
+ Logs(LogsData),
+ Metrics(MetricsData),
+ Traces(TracesData),
+}
+
+impl Req {
+ fn source(&self) -> LogSource {
+ match self {
+ Self::Logs(_) => LogSource::OtelLogs,
+ Self::Metrics(_) => LogSource::OtelMetrics,
+ Self::Traces(_) => LogSource::OtelTraces,
+ }
+ }
+
+ fn telemetry_type(&self) -> TelemetryType {
+ match self {
+ Self::Logs(_) => TelemetryType::Logs,
+ Self::Metrics(_) => TelemetryType::Metrics,
+ Self::Traces(_) => TelemetryType::Traces,
+ }
+ }
+
+ fn name(&self) -> &'static str {
+ match self {
+ Self::Logs(_) => "logs",
+ Self::Metrics(_) => "metrics",
+ Self::Traces(_) => "traces",
+ }
+ }
+
+ /// The protobuf body an OTLP/HTTP client sends
+ fn encode_pb(&self) -> Vec {
+ match self {
+ Self::Logs(data) => ExportLogsServiceRequest {
+ resource_logs: data.resource_logs.clone(),
+ }
+ .encode_to_vec(),
+ Self::Metrics(data) => ExportMetricsServiceRequest {
+ resource_metrics: data.resource_metrics.clone(),
+ }
+ .encode_to_vec(),
+ Self::Traces(data) => ExportTraceServiceRequest {
+ resource_spans: data.resource_spans.clone(),
+ }
+ .encode_to_vec(),
+ }
+ }
+
+ /// The OTLP JSON body, as the `with-serde` mapping of opentelemetry-proto writes it
+ fn encode_json(&self) -> Vec {
+ match self {
+ Self::Logs(data) => serde_json::to_vec(data),
+ Self::Metrics(data) => serde_json::to_vec(data),
+ Self::Traces(data) => serde_json::to_vec(data),
+ }
+ .expect("OTLP messages serialise")
+ }
+
+ fn from_decoded(request: OtelProtobufRequest) -> Self {
+ match request {
+ OtelProtobufRequest::Logs(m) => Self::Logs(LogsData {
+ resource_logs: m.resource_logs,
+ }),
+ OtelProtobufRequest::Metrics(m) => Self::Metrics(MetricsData {
+ resource_metrics: m.resource_metrics,
+ }),
+ OtelProtobufRequest::Traces(m) => Self::Traces(TracesData {
+ resource_spans: m.resource_spans,
+ }),
+ }
+ }
+
+ /// Rows the flatteners build for this request, counted from its structure
+ fn expected_rows(&self) -> usize {
+ match self {
+ Self::Logs(data) => data
+ .resource_logs
+ .iter()
+ .flat_map(|r| &r.scope_logs)
+ .map(|s| s.log_records.len())
+ .sum(),
+ Self::Traces(data) => data
+ .resource_spans
+ .iter()
+ .flat_map(|r| &r.scope_spans)
+ .flat_map(|s| &s.spans)
+ .map(|span| (span.events.len() + span.links.len()).max(1))
+ .sum(),
+ Self::Metrics(data) => data.resource_metrics.iter().map(expected_metric_rows).sum(),
+ }
+ }
+}
+
+fn metric_points(metric: &Metric) -> usize {
+ match &metric.data {
+ Some(metric::Data::Gauge(m)) => m.data_points.len(),
+ Some(metric::Data::Sum(m)) => m.data_points.len(),
+ Some(metric::Data::Histogram(m)) => m.data_points.len(),
+ Some(metric::Data::ExponentialHistogram(m)) => m.data_points.len(),
+ Some(metric::Data::Summary(m)) => m.data_points.len(),
+ None => 0,
+ }
+}
+
+/// One row per data point, one for a metric without data points, none for a
+/// metric without data, and one `target_info` row for a resource with a
+/// Prometheus target identity once a row of it has a string `time_unix_nano`.
+/// The metric's metadata is merged over each of its rows, so a metadata
+/// attribute named `time_unix_nano` decides that (see
+/// `metric_metadata_can_not_supply_the_target_info_timestamp`). Only valid with
+/// nested exemplars (`flatten_exemplars == false`): flat exemplars copy their
+/// attributes over the data point's fields.
+fn expected_metric_rows(resource: &ResourceMetrics) -> usize {
+ let mut rows = 0;
+ let mut timestamped = false;
+ for metric in resource.scope_metrics.iter().flat_map(|s| &s.metrics) {
+ if metric.data.is_none() {
+ continue;
+ }
+ let points = metric_points(metric);
+ rows += points.max(1);
+ // Metadata is copied over each row before its timestamp is read
+ let metadata = flatten_attributes(&metric.metadata);
+ timestamped |= match metadata.get("time_unix_nano") {
+ Some(Value::String(_)) => true,
+ None => points > 0,
+ Some(_) => false,
+ };
+ }
+ let identity = resource.resource.as_ref().is_some_and(|r| {
+ let fields = flatten_attributes(&r.attributes);
+ ["service.name", "service.instance.id"].iter().any(|key| {
+ matches!(
+ fields.get(*key),
+ Some(Value::String(_) | Value::Bool(_) | Value::Number(_))
+ )
+ })
+ });
+ rows + usize::from(identity && timestamped)
+}
+
+/// Why a stage refused a body
+#[derive(Debug, Clone, PartialEq)]
+enum StageError {
+ /// The body is not a message of the signal (protobuf decode, JSON parse or OTLP mapping)
+ Decode(String),
+ /// Flattening went over the limits; the `PostError` text the client gets
+ Flatten(String),
+}
+
+#[derive(Debug)]
+struct Outcome {
+ result: Result, StageError>,
+ /// Flatten budget used by the request
+ used: FlattenCost,
+}
+
+fn flatten_error(error: JsonFlattenError) -> StageError {
+ StageError::Flatten(PostError::from(error).to_string())
+}
+
+/// `flatten_and_push_otel_protobuf` up to the rows it hands to `push_logs`:
+/// decode, then flatten with one budget for the request
+fn pb_stage(
+ source: &LogSource,
+ body: &[u8],
+ limits: FlattenLimits,
+ flatten_exemplars: bool,
+) -> (Option, Outcome) {
+ let mut budget = FlattenBudget::new(limits);
+ let request = match OtelProtobufRequest::decode(body, source) {
+ Ok(request) => request,
+ Err(error) => {
+ return (
+ None,
+ Outcome {
+ result: Err(StageError::Decode(error.to_string())),
+ used: budget.used(),
+ },
+ );
+ }
+ };
+ let result =
+ match &request {
+ // `OtelProtobufRequest::flatten` reads the exemplar flag from the server configuration
+ OtelProtobufRequest::Metrics(message) => Ok(
+ flatten_otel_metrics_protobuf_with_options(message, TENANT, flatten_exemplars),
+ ),
+ _ => request.flatten(TENANT, &mut budget).map_err(flatten_error),
+ };
+ (
+ Some(Req::from_decoded(request)),
+ Outcome {
+ result,
+ used: budget.used(),
+ },
+ )
+}
+
+/// The OTEL arms of `handle_otel_ingestion` and `flatten_and_push_logs` for a
+/// JSON body, up to the rows they hand to `push_logs`
+fn json_stage(
+ source: &LogSource,
+ body: &[u8],
+ limits: FlattenLimits,
+ flatten_exemplars: bool,
+ normalise: bool,
+) -> (Option, Outcome) {
+ let mut budget = FlattenBudget::new(limits);
+ let decode_error = |error: serde_json::Error| Outcome {
+ result: Err(StageError::Decode(error.to_string())),
+ used: FlattenCost::default(),
+ };
+ let json: Value = match serde_json::from_slice(body) {
+ Ok(json) => json,
+ Err(error) => return (None, decode_error(error)),
+ };
+ let (request, result) = match source {
+ LogSource::OtelLogs => match deserialize_otel_json::(json, normalise) {
+ Ok(logs) => {
+ let rows = flatten_otel_logs(&logs, TENANT, &mut budget).map_err(flatten_error);
+ (Req::Logs(logs), rows)
+ }
+ Err(error) => return (None, decode_error(error)),
+ },
+ LogSource::OtelMetrics => match deserialize_otel_json::(json, normalise) {
+ Ok(metrics) => {
+ let rows =
+ flatten_otel_metrics_with_options(metrics.clone(), TENANT, flatten_exemplars);
+ (Req::Metrics(metrics), Ok(rows))
+ }
+ Err(error) => return (None, decode_error(error)),
+ },
+ LogSource::OtelTraces => match deserialize_otel_json::(json, normalise) {
+ Ok(traces) => {
+ let rows = flatten_otel_traces(&traces, TENANT);
+ (Req::Traces(traces), Ok(rows))
+ }
+ Err(error) => return (None, decode_error(error)),
+ },
+ other => panic!("not an OTEL source: {other}"),
+ };
+ (
+ Some(request),
+ Outcome {
+ result,
+ used: budget.used(),
+ },
+ )
+}
+
+// ---------------------------------------------------------------------------
+// What the JSON mapping can carry
+// ---------------------------------------------------------------------------
+
+fn value_representable(value: &AnyValue) -> bool {
+ use any_value::Value as V;
+ match &value.value {
+ None | Some(V::StringValueStrindex(_)) => false,
+ Some(V::DoubleValue(double)) => double.is_finite() && json_round_trips(*double),
+ Some(V::ArrayValue(array)) => array.values.iter().all(value_representable),
+ Some(V::KvlistValue(list)) => attributes_representable(&list.values),
+ Some(V::StringValue(_) | V::BoolValue(_) | V::IntValue(_) | V::BytesValue(_)) => true,
+ }
+}
+
+fn attributes_representable(attributes: &[KeyValue]) -> bool {
+ attributes
+ .iter()
+ .all(|kv| kv.value.as_ref().is_none_or(value_representable))
+}
+
+fn envelope_representable(
+ resource: &Option,
+ scope: Option<&Option>,
+) -> bool {
+ resource
+ .as_ref()
+ .is_none_or(|r| attributes_representable(&r.attributes))
+ && scope
+ .and_then(Option::as_ref)
+ .is_none_or(|s| attributes_representable(&s.attributes))
+}
+
+fn exemplars_representable(exemplars: &[Exemplar]) -> bool {
+ exemplars.iter().all(|e| {
+ attributes_representable(&e.filtered_attributes)
+ && !matches!(e.value, Some(exemplar::Value::AsDouble(d)) if !d.is_finite() || !json_round_trips(d))
+ })
+}
+
+fn metric_representable(metric: &Metric) -> bool {
+ attributes_representable(&metric.metadata)
+ && match &metric.data {
+ None => true,
+ Some(metric::Data::Gauge(Gauge { data_points }))
+ | Some(metric::Data::Sum(Sum { data_points, .. })) => data_points.iter().all(|p| {
+ attributes_representable(&p.attributes)
+ && exemplars_representable(&p.exemplars)
+ && !matches!(p.value, Some(number_data_point::Value::AsDouble(d)) if !d.is_finite() || !json_round_trips(d))
+ }),
+ Some(metric::Data::Histogram(h)) => h.data_points.iter().all(|p| {
+ attributes_representable(&p.attributes)
+ && exemplars_representable(&p.exemplars)
+ && p.explicit_bounds.iter().all(|b| b.is_finite() && json_round_trips(*b))
+ && [p.sum, p.min, p.max].into_iter().flatten().all(json_round_trips)
+ }),
+ Some(metric::Data::ExponentialHistogram(h)) => h.data_points.iter().all(|p| {
+ attributes_representable(&p.attributes)
+ && exemplars_representable(&p.exemplars)
+ && p.zero_threshold.is_finite()
+ && [Some(p.zero_threshold), p.sum, p.min, p.max]
+ .into_iter()
+ .flatten()
+ .all(json_round_trips)
+ }),
+ Some(metric::Data::Summary(s)) => s.data_points.iter().all(|p| {
+ attributes_representable(&p.attributes)
+ && p.sum.is_finite()
+ && json_round_trips(p.sum)
+ && p.quantile_values
+ .iter()
+ .all(|q| json_round_trips(q.quantile) && json_round_trips(q.value))
+ }),
+ }
+}
+
+/// Whether the OTLP JSON mapping of opentelemetry-proto, read back by this
+/// crate's serde_json, carries this request unchanged (non-finite optional
+/// doubles become unset, which the flatteners treat alike). See the
+/// `json_mapping_*` and `json_path_*` tests for what happens otherwise.
+fn json_representable(request: &Req) -> bool {
+ match request {
+ Req::Logs(data) => data.resource_logs.iter().all(|r| {
+ envelope_representable(&r.resource, None)
+ && r.scope_logs.iter().all(|s| {
+ envelope_representable(&None, Some(&s.scope))
+ && s.log_records.iter().all(|l| {
+ attributes_representable(&l.attributes)
+ && l.body.as_ref().is_none_or(value_representable)
+ })
+ })
+ }),
+ Req::Traces(data) => data.resource_spans.iter().all(|r| {
+ envelope_representable(&r.resource, None)
+ && r.scope_spans.iter().all(|s| {
+ envelope_representable(&None, Some(&s.scope))
+ && s.spans.iter().all(|span| {
+ attributes_representable(&span.attributes)
+ && span
+ .events
+ .iter()
+ .all(|e| attributes_representable(&e.attributes))
+ && span
+ .links
+ .iter()
+ .all(|l| attributes_representable(&l.attributes))
+ })
+ })
+ }),
+ Req::Metrics(data) => data.resource_metrics.iter().all(|r| {
+ envelope_representable(&r.resource, None)
+ && r.scope_metrics.iter().all(|s| {
+ envelope_representable(&None, Some(&s.scope))
+ && s.metrics.iter().all(metric_representable)
+ })
+ }),
+ }
+}
+
+/// Sets every unset (zero) timestamp to 1 ns, so that rows do not depend on the
+/// clock. Returns whether any was unset.
+fn fill_unset_timestamps(request: &mut Req) -> bool {
+ let mut filled = false;
+ let mut fill = |ts: &mut u64| {
+ if *ts == 0 {
+ *ts = 1;
+ filled = true;
+ }
+ };
+ match request {
+ Req::Logs(data) => {
+ for record in data
+ .resource_logs
+ .iter_mut()
+ .flat_map(|r| &mut r.scope_logs)
+ .flat_map(|s| &mut s.log_records)
+ {
+ fill(&mut record.time_unix_nano);
+ fill(&mut record.observed_time_unix_nano);
+ }
+ }
+ Req::Traces(data) => {
+ for span in data
+ .resource_spans
+ .iter_mut()
+ .flat_map(|r| &mut r.scope_spans)
+ .flat_map(|s| &mut s.spans)
+ {
+ fill(&mut span.start_time_unix_nano);
+ fill(&mut span.end_time_unix_nano);
+ for event in &mut span.events {
+ fill(&mut event.time_unix_nano);
+ }
+ }
+ }
+ Req::Metrics(data) => {
+ fn fill_exemplars(exemplars: &mut [Exemplar], fill: &mut dyn FnMut(&mut u64)) {
+ for exemplar in exemplars {
+ fill(&mut exemplar.time_unix_nano);
+ }
+ }
+ for metric in data
+ .resource_metrics
+ .iter_mut()
+ .flat_map(|r| &mut r.scope_metrics)
+ .flat_map(|s| &mut s.metrics)
+ {
+ match &mut metric.data {
+ Some(metric::Data::Gauge(Gauge { data_points }))
+ | Some(metric::Data::Sum(Sum { data_points, .. })) => {
+ for p in data_points {
+ fill(&mut p.start_time_unix_nano);
+ fill(&mut p.time_unix_nano);
+ fill_exemplars(&mut p.exemplars, &mut fill);
+ }
+ }
+ Some(metric::Data::Histogram(h)) => {
+ for p in &mut h.data_points {
+ fill(&mut p.start_time_unix_nano);
+ fill(&mut p.time_unix_nano);
+ fill_exemplars(&mut p.exemplars, &mut fill);
+ }
+ }
+ Some(metric::Data::ExponentialHistogram(h)) => {
+ for p in &mut h.data_points {
+ fill(&mut p.start_time_unix_nano);
+ fill(&mut p.time_unix_nano);
+ fill_exemplars(&mut p.exemplars, &mut fill);
+ }
+ }
+ Some(metric::Data::Summary(s)) => {
+ for p in &mut s.data_points {
+ fill(&mut p.start_time_unix_nano);
+ fill(&mut p.time_unix_nano);
+ }
+ }
+ None => {}
+ }
+ }
+ }
+ }
+ filled
+}
+
+// ---------------------------------------------------------------------------
+// 1. Differential properties
+// ---------------------------------------------------------------------------
+
+/// Both encodings of `request` give the same outcome and use the same budget
+fn assert_encodings_agree(
+ request: &Req,
+ limits: FlattenLimits,
+ flatten_exemplars: bool,
+ normalise: bool,
+) -> Result {
+ let source = request.source();
+ let (_, pb) = pb_stage(&source, &request.encode_pb(), limits, flatten_exemplars);
+ let (_, js) = json_stage(
+ &source,
+ &request.encode_json(),
+ limits,
+ flatten_exemplars,
+ normalise,
+ );
+ prop_assert_eq!(
+ &pb.result,
+ &js.result,
+ "protobuf (left) and JSON (right) differ"
+ );
+ prop_assert_eq!(pb.used, js.used, "flatten budget used differs");
+ Ok(pb)
+}
+
+fn differential(request: Req, flatten_exemplars: bool, normalise: bool) -> TestCaseResult {
+ prop_assume!(json_representable(&request));
+ let outcome = assert_encodings_agree(
+ &request,
+ FlattenLimits::DEFAULT,
+ flatten_exemplars,
+ normalise,
+ )?;
+ let rows = outcome
+ .result
+ .map_err(|e| TestCaseError::fail(format!("valid request refused: {e:?}")))?;
+ if !flatten_exemplars {
+ prop_assert_eq!(rows.len(), request.expected_rows());
+ }
+ Ok(())
+}
+
+#[test]
+fn otel_pb_differential_logs() {
+ check(
+ "otel_pb_differential_logs",
+ 96,
+ (logs_data(false), any::()),
+ |(logs, normalise)| differential(Req::Logs(logs), false, normalise),
+ );
+}
+
+#[test]
+fn otel_pb_differential_traces() {
+ check(
+ "otel_pb_differential_traces",
+ 96,
+ (traces_data(false), any::()),
+ |(traces, normalise)| differential(Req::Traces(traces), false, normalise),
+ );
+}
+
+#[test]
+fn otel_pb_differential_metrics() {
+ check(
+ "otel_pb_differential_metrics",
+ 96,
+ (metrics_data(false), any::(), any::()),
+ |(metrics, flatten_exemplars, normalise)| {
+ differential(Req::Metrics(metrics), flatten_exemplars, normalise)
+ },
+ );
+}
+
+/// The wider domain: the protobuf path takes every message, and the JSON path
+/// agrees with it on every one `json_representable` admits. This checks that
+/// predicate, which the differential properties above rely on.
+#[test]
+fn otel_pb_wild_requests_flatten_and_agree_where_json_can_carry_them() {
+ let (carried, not_carried) = (AtomicUsize::new(0), AtomicUsize::new(0));
+ let wild = prop_oneof![
+ logs_data(true).prop_map(Req::Logs),
+ traces_data(true).prop_map(Req::Traces),
+ metrics_data(true).prop_map(Req::Metrics),
+ ];
+ check("otel_pb_wild_requests", 96, wild, |request| {
+ let (_, pb) = pb_stage(
+ &request.source(),
+ &request.encode_pb(),
+ FlattenLimits::DEFAULT,
+ false,
+ );
+ let rows = pb
+ .result
+ .map_err(|e| TestCaseError::fail(format!("protobuf refused: {e:?}")))?;
+ prop_assert_eq!(rows.len(), request.expected_rows());
+ if json_representable(&request) {
+ carried.fetch_add(1, Ordering::Relaxed);
+ assert_encodings_agree(&request, FlattenLimits::DEFAULT, false, false)?;
+ } else {
+ not_carried.fetch_add(1, Ordering::Relaxed);
+ }
+ Ok(())
+ });
+ let (carried, not_carried) = (carried.into_inner(), not_carried.into_inner());
+ println!("otel_pb_wild_requests: json_representable={carried} not={not_carried}");
+ assert!(carried > 0 && not_carried > 0, "{carried} / {not_carried}");
+}
+
+// ---------------------------------------------------------------------------
+// 2. Robustness of the decoder
+// ---------------------------------------------------------------------------
+
+const OTEL_SOURCES: [(LogSource, TelemetryType); 3] = [
+ (LogSource::OtelLogs, TelemetryType::Logs),
+ (LogSource::OtelMetrics, TelemetryType::Metrics),
+ (LogSource::OtelTraces, TelemetryType::Traces),
+];
+
+/// Decoding `body` never panics, is deterministic, and a body that does not
+/// decode is refused by `flatten_and_push_otel_protobuf` with the decode error
+/// before anything is flattened or staged. A body that decodes flattens.
+fn decode_is_total(
+ body: &[u8],
+ source: &LogSource,
+ telemetry_type: TelemetryType,
+) -> TestCaseResult {
+ let first = OtelProtobufRequest::decode(body, source);
+ let second = OtelProtobufRequest::decode(body, source);
+ match (&first, &second) {
+ (Ok(a), Ok(b)) => prop_assert_eq!(
+ Req::from_decoded(clone_request(a)).encode_pb(),
+ Req::from_decoded(clone_request(b)).encode_pb()
+ ),
+ (Err(a), Err(b)) => prop_assert_eq!(a.to_string(), b.to_string()),
+ _ => prop_assert!(false, "decode is not deterministic: {first:?} / {second:?}"),
+ }
+ match first {
+ Ok(request) => {
+ // May hold unset timestamps, so only the shape of the result is checked
+ let (_, outcome) = pb_stage(source, body, FlattenLimits::DEFAULT, false);
+ let request = Req::from_decoded(request);
+ if let Ok(rows) = &outcome.result {
+ prop_assert_eq!(rows.len(), request.expected_rows());
+ } else {
+ // Only the log flatten budget refuses a decoded request
+ prop_assert!(
+ matches!(
+ (&request, &outcome.result),
+ (Req::Logs(_), Err(StageError::Flatten(_)))
+ ),
+ "{:?}",
+ outcome.result
+ );
+ }
+ }
+ Err(error) => {
+ // Returns before the dataset field check, the first use of `PARSEABLE`
+ let refused = flatten_and_push_otel_protobuf(
+ body,
+ "otel_pb_props",
+ source,
+ &HashMap::new(),
+ telemetry_type,
+ &None,
+ )
+ .expect_err("a body that does not decode is refused");
+ prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}");
+ prop_assert_eq!(
+ refused.to_string(),
+ format!("Invalid Request: Ingestion failed for stream otel_pb_props: {error}")
+ );
+ }
+ }
+ Ok(())
+}
+
+fn clone_request(request: &OtelProtobufRequest) -> OtelProtobufRequest {
+ match request {
+ OtelProtobufRequest::Logs(m) => OtelProtobufRequest::Logs(m.clone()),
+ OtelProtobufRequest::Metrics(m) => OtelProtobufRequest::Metrics(m.clone()),
+ OtelProtobufRequest::Traces(m) => OtelProtobufRequest::Traces(m.clone()),
+ }
+}
+
+#[test]
+fn otel_pb_arbitrary_bytes_never_panic() {
+ let decoded = AtomicUsize::new(0);
+ check(
+ "otel_pb_arbitrary_bytes_never_panic",
+ 512,
+ (vec(any::(), 0..256), 0..3usize),
+ |(body, signal)| {
+ let (source, telemetry_type) = &OTEL_SOURCES[signal];
+ if OtelProtobufRequest::decode(&body, source).is_ok() {
+ decoded.fetch_add(1, Ordering::Relaxed);
+ }
+ decode_is_total(&body, source, *telemetry_type)
+ },
+ );
+ println!("otel_pb_arbitrary_bytes: decoded={}", decoded.into_inner());
+}
+
+#[derive(Debug, Clone)]
+enum Mutation {
+ Flip(usize, u8),
+ Set(usize, u8),
+ Insert(usize, u8),
+ Remove(usize),
+}
+
+fn mutate(body: &mut Vec, mutation: &Mutation) {
+ if body.is_empty() {
+ return;
+ }
+ let len = body.len();
+ match *mutation {
+ Mutation::Flip(at, mask) => body[at % len] ^= mask.max(1),
+ Mutation::Set(at, byte) => body[at % len] = byte,
+ Mutation::Insert(at, byte) => body.insert(at % (len + 1), byte),
+ Mutation::Remove(at) => {
+ body.remove(at % len);
+ }
+ }
+}
+
+fn mutation() -> BoxedStrategy {
+ prop_oneof![
+ (any::(), any::()).prop_map(|(at, mask)| Mutation::Flip(at, mask)),
+ (any::(), any::()).prop_map(|(at, byte)| Mutation::Set(at, byte)),
+ (any::(), any::()).prop_map(|(at, byte)| Mutation::Insert(at, byte)),
+ any::().prop_map(Mutation::Remove),
+ ]
+ .boxed()
+}
+
+fn any_request(wild: bool) -> BoxedStrategy {
+ prop_oneof![
+ logs_data(wild).prop_map(Req::Logs),
+ traces_data(wild).prop_map(Req::Traces),
+ metrics_data(wild).prop_map(Req::Metrics),
+ ]
+ .boxed()
+}
+
+#[test]
+fn otel_pb_truncated_encodings_never_panic() {
+ let (decoded, refused) = (AtomicUsize::new(0), AtomicUsize::new(0));
+ check(
+ "otel_pb_truncated_encodings_never_panic",
+ 128,
+ (any_request(true), any::()),
+ |(request, cut)| {
+ let body = request.encode_pb();
+ // An empty request encodes to no bytes, which is a valid (empty) message
+ let body = &body[..cut.index(body.len().max(1)).min(body.len())];
+ match OtelProtobufRequest::decode(body, &request.source()) {
+ Ok(_) => decoded.fetch_add(1, Ordering::Relaxed),
+ Err(_) => refused.fetch_add(1, Ordering::Relaxed),
+ };
+ decode_is_total(body, &request.source(), request.telemetry_type())
+ },
+ );
+ println!(
+ "otel_pb_truncated: decoded={} refused={}",
+ decoded.into_inner(),
+ refused.into_inner()
+ );
+}
+
+#[test]
+fn otel_pb_mutated_encodings_never_panic() {
+ let (decoded, refused) = (AtomicUsize::new(0), AtomicUsize::new(0));
+ check(
+ "otel_pb_mutated_encodings_never_panic",
+ 128,
+ (any_request(true), vec(mutation(), 1..5)),
+ |(request, mutations)| {
+ let mut body = request.encode_pb();
+ for m in &mutations {
+ mutate(&mut body, m);
+ }
+ match OtelProtobufRequest::decode(&body, &request.source()) {
+ Ok(_) => decoded.fetch_add(1, Ordering::Relaxed),
+ Err(_) => refused.fetch_add(1, Ordering::Relaxed),
+ };
+ decode_is_total(&body, &request.source(), request.telemetry_type())
+ },
+ );
+ println!(
+ "otel_pb_mutated: decoded={} refused={}",
+ decoded.into_inner(),
+ refused.into_inner()
+ );
+}
+
+/// A body of one signal sent to another signal's endpoint decodes or is
+/// refused like any other bytes
+#[test]
+fn otel_pb_bodies_sent_to_the_wrong_signal_never_panic() {
+ check(
+ "otel_pb_bodies_sent_to_the_wrong_signal",
+ 128,
+ (any_request(true), 0..3usize),
+ |(request, signal)| {
+ let (source, telemetry_type) = &OTEL_SOURCES[signal];
+ decode_is_total(&request.encode_pb(), source, *telemetry_type)
+ },
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 3. Flatten limits of logs
+// ---------------------------------------------------------------------------
+
+/// Log requests whose bodies expand into rows, against small limits: both
+/// encodings are refused for the same requests with the same error, and charge
+/// the budget alike
+#[test]
+fn otel_pb_log_flatten_limits_match_json() {
+ let outcomes: [AtomicUsize; 4] = Default::default();
+ check(
+ "otel_pb_log_flatten_limits_match_json",
+ 192,
+ (logs_data(false), tight_limits(), any::()),
+ |(logs, limits, normalise)| {
+ let request = Req::Logs(logs);
+ prop_assume!(json_representable(&request));
+ let outcome = assert_encodings_agree(&request, limits, false, normalise)?;
+ let kind = match &outcome.result {
+ Ok(_) => 0,
+ Err(StageError::Flatten(e)) if e.contains("P_MAX_FLATTEN_ROWS_PER_EVENT") => 1,
+ Err(StageError::Flatten(e)) if e.contains("P_MAX_FLATTEN_ROWS_PER_REQUEST") => 2,
+ Err(StageError::Flatten(_)) => 3,
+ Err(StageError::Decode(e)) => {
+ return Err(TestCaseError::fail(format!("decode failed: {e}")));
+ }
+ };
+ outcomes[kind].fetch_add(1, Ordering::Relaxed);
+ Ok(())
+ },
+ );
+ let [ok, per_event, per_request, bytes] = outcomes.map(AtomicUsize::into_inner);
+ println!(
+ "otel_pb_log_flatten_limits: ok={ok} rows_per_event={per_event} rows_per_request={per_request} other_limit={bytes}"
+ );
+ // Not vacuous: the generated requests both pass and hit the limits
+ assert!(ok > 0 && per_event + per_request + bytes > 0);
+}
+
+// ---------------------------------------------------------------------------
+// What the OTLP JSON mapping can not carry
+// ---------------------------------------------------------------------------
+//
+// The JSON path decodes with the `with-serde` mapping of opentelemetry-proto
+// 0.32. These tests pin what it does with messages the protobuf path takes
+// whole, so a dependency upgrade that changes it is noticed.
+
+fn kv(key: &str, value: Option) -> KeyValue {
+ KeyValue {
+ key: key.to_string(),
+ value: Some(AnyValue { value }),
+ key_strindex: 0,
+ }
+}
+
+fn string_kv(key: &str, value: &str) -> KeyValue {
+ kv(key, Some(any_value::Value::StringValue(value.to_string())))
+}
+
+fn one_log(attributes: Vec, body: Option) -> Req {
+ Req::Logs(LogsData {
+ resource_logs: vec![ResourceLogs {
+ scope_logs: vec![ScopeLogs {
+ log_records: vec![LogRecord {
+ time_unix_nano: 1_700_000_000_000_000_000,
+ observed_time_unix_nano: 1_700_000_000_000_000_000,
+ severity_number: 9,
+ attributes,
+ body,
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ })
+}
+
+fn both(request: &Req) -> (Outcome, Outcome) {
+ let source = request.source();
+ let (_, pb) = pb_stage(&source, &request.encode_pb(), FlattenLimits::DEFAULT, false);
+ let (_, js) = json_stage(
+ &source,
+ &request.encode_json(),
+ FlattenLimits::DEFAULT,
+ false,
+ true,
+ );
+ (pb, js)
+}
+
+fn json_text_stage(source: LogSource, json: Value) -> Outcome {
+ json_stage(
+ &source,
+ json.to_string().as_bytes(),
+ FlattenLimits::DEFAULT,
+ false,
+ true,
+ )
+ .1
+}
+
+/// A non-finite `doubleValue` is accepted over protobuf (the flatteners drop
+/// the attribute) but refuses the whole request over JSON: serde_json writes
+/// it as `null`, and the OTLP/JSON spelling `"NaN"` is refused too, since the
+/// mapping reads `doubleValue` as a plain JSON number.
+#[test]
+fn json_mapping_refuses_non_finite_any_value_doubles() {
+ for double in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ let request = one_log(
+ vec![
+ string_kv("kept", "x"),
+ kv("d", Some(any_value::Value::DoubleValue(double))),
+ ],
+ None,
+ );
+ let (pb, js) = both(&request);
+ let rows = pb.result.unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0]["kept"], json!("x"));
+ assert!(rows[0].get("d").is_none(), "{double}: {:?}", rows[0]);
+ assert!(
+ matches!(&js.result, Err(StageError::Decode(e)) if e.contains("null")),
+ "{double}: {:?}",
+ js.result
+ );
+ }
+ for spelling in ["NaN", "Infinity", "-Infinity"] {
+ let js = json_text_stage(
+ LogSource::OtelLogs,
+ json!({"resourceLogs": [{"scopeLogs": [{"logRecords": [{
+ "timeUnixNano": "1700000000000000000",
+ "attributes": [{"key": "d", "value": {"doubleValue": spelling}}]
+ }]}]}]}),
+ );
+ assert!(
+ matches!(&js.result, Err(StageError::Decode(e)) if e.contains("expected f64")),
+ "{spelling}: {:?}",
+ js.result
+ );
+ }
+}
+
+/// An `AnyValue` with no value set (`{}` in JSON, valid in OTLP) is accepted
+/// over protobuf and refuses the whole request over JSON, wherever it is
+#[test]
+fn json_mapping_refuses_empty_any_values() {
+ let empty = || AnyValue { value: None };
+ let cases = [
+ ("attribute", one_log(vec![kv("e", None)], None)),
+ ("body", one_log(vec![], Some(empty()))),
+ (
+ "array element",
+ one_log(
+ vec![kv(
+ "a",
+ Some(any_value::Value::ArrayValue(ArrayValue {
+ values: vec![empty()],
+ })),
+ )],
+ None,
+ ),
+ ),
+ ];
+ for (place, request) in cases {
+ let (pb, js) = both(&request);
+ assert_eq!(pb.result.unwrap().len(), 1, "{place}");
+ assert!(
+ matches!(&js.result, Err(StageError::Decode(e)) if e.contains("no known keys")),
+ "{place}: {:?}",
+ js.result
+ );
+ }
+}
+
+/// `string_value_strindex` (profiles only) is ignored by the flatteners over
+/// protobuf; the JSON mapping does not read it back, so the request is refused
+#[test]
+fn json_mapping_refuses_string_value_strindex() {
+ let request = one_log(
+ vec![
+ string_kv("kept", "x"),
+ kv("s", Some(any_value::Value::StringValueStrindex(7))),
+ ],
+ None,
+ );
+ let (pb, js) = both(&request);
+ let rows = pb.result.unwrap();
+ assert!(rows[0].get("s").is_none());
+ assert!(
+ matches!(&js.result, Err(StageError::Decode(e)) if e.contains("no known keys")),
+ "{:?}",
+ js.result
+ );
+}
+
+fn one_metric(data: metric::Data) -> Req {
+ Req::Metrics(MetricsData {
+ resource_metrics: vec![ResourceMetrics {
+ scope_metrics: vec![ScopeMetrics {
+ metrics: vec![
+ Metric {
+ name: "probe".to_string(),
+ data: Some(data),
+ ..Default::default()
+ },
+ Metric {
+ name: "witness".to_string(),
+ data: Some(metric::Data::Gauge(Gauge {
+ data_points: vec![number_point(number_data_point::Value::AsInt(1))],
+ })),
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ })
+}
+
+fn number_point(value: number_data_point::Value) -> NumberDataPoint {
+ NumberDataPoint {
+ start_time_unix_nano: 1_700_000_000_000_000_000,
+ time_unix_nano: 1_700_000_000_000_000_000,
+ value: Some(value),
+ ..Default::default()
+ }
+}
+
+fn metric_names(rows: &[Value]) -> Vec<&str> {
+ rows.iter()
+ .map(|row| row["metric_name"].as_str().unwrap())
+ .collect()
+}
+
+/// A non-finite gauge or sum value: protobuf stores it as `null`, the JSON
+/// mapping loses the value. `NumberDataPoint.value` is a `#[serde(flatten)]`
+/// `Option`, and serde turns an error inside a flattened `Option` into `None`,
+/// so the data point is kept without `data_point_value`.
+#[test]
+fn json_mapping_drops_non_finite_number_values() {
+ for double in [f64::NAN, f64::INFINITY] {
+ let request = one_metric(metric::Data::Gauge(Gauge {
+ data_points: vec![number_point(number_data_point::Value::AsDouble(double))],
+ }));
+ let (pb, js) = both(&request);
+ let (pb, js) = (pb.result.unwrap(), js.result.unwrap());
+ assert_eq!(metric_names(&pb), ["probe", "witness"]);
+ assert_eq!(metric_names(&js), ["probe", "witness"]);
+ assert_eq!(pb[0]["data_point_value"], Value::Null);
+ assert!(
+ js[0].get("data_point_value").is_none(),
+ "{double}: {}",
+ js[0]
+ );
+ let mut without_value = pb[0].clone();
+ without_value
+ .as_object_mut()
+ .unwrap()
+ .remove("data_point_value");
+ assert_eq!(without_value, js[0]);
+ }
+}
+
+/// Anything the JSON mapping can not read inside a metric's data — an empty
+/// `AnyValue` or non-finite double in a data point attribute, a non-finite
+/// exemplar, histogram bound, summary sum or exponential histogram zero
+/// threshold — silently removes the whole metric over JSON, while the request
+/// still succeeds. `Metric.data` is a flattened `Option` too. Over protobuf the
+/// metric is stored. In production an all-dropped request is a 200 with no rows.
+#[test]
+fn json_mapping_silently_drops_metrics_it_can_not_read() {
+ let nan_attribute = vec![kv("d", Some(any_value::Value::DoubleValue(f64::NAN)))];
+ let empty_attribute = vec![kv("e", None)];
+ let cases: Vec<(&str, metric::Data)> = vec![
+ (
+ "empty AnyValue attribute",
+ metric::Data::Gauge(Gauge {
+ data_points: vec![NumberDataPoint {
+ attributes: empty_attribute,
+ ..number_point(number_data_point::Value::AsInt(1))
+ }],
+ }),
+ ),
+ (
+ "NaN attribute",
+ metric::Data::Sum(Sum {
+ data_points: vec![NumberDataPoint {
+ attributes: nan_attribute,
+ ..number_point(number_data_point::Value::AsInt(1))
+ }],
+ aggregation_temporality: 2,
+ is_monotonic: true,
+ }),
+ ),
+ (
+ "NaN exemplar",
+ metric::Data::Gauge(Gauge {
+ data_points: vec![NumberDataPoint {
+ exemplars: vec![Exemplar {
+ time_unix_nano: 1,
+ value: Some(exemplar::Value::AsDouble(f64::NAN)),
+ ..Default::default()
+ }],
+ ..number_point(number_data_point::Value::AsInt(1))
+ }],
+ }),
+ ),
+ (
+ "infinite histogram bound",
+ metric::Data::Histogram(Histogram {
+ data_points: vec![HistogramDataPoint {
+ start_time_unix_nano: 1,
+ time_unix_nano: 1,
+ count: 1,
+ bucket_counts: vec![0, 1],
+ explicit_bounds: vec![f64::INFINITY],
+ ..Default::default()
+ }],
+ aggregation_temporality: 1,
+ }),
+ ),
+ (
+ "NaN summary sum",
+ metric::Data::Summary(Summary {
+ data_points: vec![SummaryDataPoint {
+ start_time_unix_nano: 1,
+ time_unix_nano: 1,
+ sum: f64::NAN,
+ ..Default::default()
+ }],
+ }),
+ ),
+ (
+ "NaN exponential histogram zero threshold",
+ metric::Data::ExponentialHistogram(ExponentialHistogram {
+ data_points: vec![ExponentialHistogramDataPoint {
+ start_time_unix_nano: 1,
+ time_unix_nano: 1,
+ zero_threshold: f64::NAN,
+ ..Default::default()
+ }],
+ aggregation_temporality: 1,
+ }),
+ ),
+ ];
+ for (case, data) in cases {
+ let request = one_metric(data);
+ let (pb, js) = both(&request);
+ assert_eq!(
+ metric_names(&pb.result.unwrap()),
+ ["probe", "witness"],
+ "{case}"
+ );
+ assert_eq!(metric_names(&js.result.unwrap()), ["witness"], "{case}");
+ }
+
+ // The same with the OTLP/JSON spelling of NaN a protojson client sends
+ let js = json_text_stage(
+ LogSource::OtelMetrics,
+ json!({"resourceMetrics": [{"scopeMetrics": [{"metrics": [{
+ "name": "probe",
+ "summary": {"dataPoints": [{
+ "timeUnixNano": "1700000000000000000",
+ "sum": "NaN",
+ "quantileValues": [{"quantile": 0.5, "value": "NaN"}]
+ }]}
+ }]}]}]}),
+ );
+ assert_eq!(js.result, Ok(vec![]));
+}
+
+/// Over protobuf a NaN summary sum is stored as `null`; the OTLP/JSON spelling
+/// `"NaN"` is read only for quantile values (the one field the mapping
+/// special-cases), which are stored as `null` either way
+#[test]
+fn json_mapping_reads_non_finite_quantiles_and_optional_sums() {
+ let request = one_metric(metric::Data::Summary(Summary {
+ data_points: vec![SummaryDataPoint {
+ start_time_unix_nano: 1,
+ time_unix_nano: 1,
+ sum: 1.5,
+ quantile_values: vec![ValueAtQuantile {
+ quantile: f64::NAN,
+ value: f64::NEG_INFINITY,
+ }],
+ ..Default::default()
+ }],
+ }));
+ let (pb, js) = both(&request);
+ let rows = pb.result.unwrap();
+ assert_eq!(
+ rows[0]["data_point_quantile_values"],
+ json!([{"quantile": null, "value": null}])
+ );
+ assert_eq!(Ok(rows), js.result);
+
+ // Optional histogram sum, min and max become null, which reads back as unset
+ let request = one_metric(metric::Data::Histogram(Histogram {
+ data_points: vec![HistogramDataPoint {
+ start_time_unix_nano: 1,
+ time_unix_nano: 1,
+ sum: Some(f64::NAN),
+ min: Some(f64::NEG_INFINITY),
+ max: Some(f64::INFINITY),
+ ..Default::default()
+ }],
+ aggregation_temporality: 2,
+ }));
+ let (pb, js) = both(&request);
+ let rows = pb.result.unwrap();
+ assert!(rows[0].get("data_point_sum").is_none());
+ assert_eq!(Ok(rows), js.result);
+}
+
+/// The JSON path reads some doubles one ULP off: serde_json writes the
+/// shortest decimal that reads back exactly, but this crate builds serde_json
+/// without `float_roundtrip`, whose faster parser rounds some 17-digit
+/// decimals wrong. Protobuf carries the bits. Found by
+/// `otel_pb_differential_logs` and `otel_pb_differential_traces`; minimal input
+/// a single attribute of this value.
+#[test]
+fn json_path_reads_some_doubles_one_ulp_off() {
+ let double = -4.4597825407728543e-212_f64;
+ let request = one_log(
+ vec![kv("d", Some(any_value::Value::DoubleValue(double)))],
+ None,
+ );
+ let (pb, js) = both(&request);
+ let (pb, js) = (pb.result.unwrap(), js.result.unwrap());
+ assert_eq!(pb[0]["d"].as_f64().unwrap().to_bits(), double.to_bits());
+ let read = js[0]["d"].as_f64().unwrap();
+ assert_eq!(read.to_bits().abs_diff(double.to_bits()), 1, "{read:e}");
+ assert_eq!(
+ serde_json::to_string(&double).unwrap(),
+ "-4.4597825407728543e-212"
+ );
+}
+
+/// How wrong the JSON path's doubles get: a few ULPs at most, and only for
+/// some doubles. The count and the largest error seen are printed.
+#[test]
+fn json_path_double_error_is_a_few_ulps() {
+ let (off, worst) = (AtomicUsize::new(0), AtomicUsize::new(0));
+ check(
+ "json_path_double_error_is_a_few_ulps",
+ 4096,
+ finite_f64(),
+ |double| {
+ let read: f64 = serde_json::from_str(&serde_json::to_string(&double).unwrap()).unwrap();
+ prop_assert_eq!(read.is_sign_negative(), double.is_sign_negative());
+ let ulps = read.to_bits().abs_diff(double.to_bits());
+ if ulps > 0 {
+ off.fetch_add(1, Ordering::Relaxed);
+ worst.fetch_max(ulps as usize, Ordering::Relaxed);
+ prop_assert!(ulps <= 4, "{double:e} read back as {read:e}, {ulps} ULPs");
+ }
+ Ok(())
+ },
+ );
+ println!(
+ "json_path_double_error: inexact={} worst_ulps={}",
+ off.into_inner(),
+ worst.into_inner()
+ );
+}
+
+/// One log record whose attribute `deep` is an array nested `depth` times,
+/// written by hand: prost encodes recursively, and so does serde
+fn deeply_nested_log_body(depth: usize) -> Vec {
+ fn wrap(field: u32, inner: Vec) -> Vec {
+ let mut out = Vec::with_capacity(inner.len() + 11);
+ prost::encoding::encode_key(field, prost::encoding::WireType::LengthDelimited, &mut out);
+ prost::encoding::encode_varint(inner.len() as u64, &mut out);
+ out.extend(inner);
+ out
+ }
+ let mut value = Vec::new(); // AnyValue with no value
+ for _ in 0..depth {
+ value = wrap(5, wrap(1, value)); // AnyValue.array_value -> ArrayValue.values
+ }
+ let mut key_value = wrap(1, b"deep".to_vec()); // KeyValue.key
+ key_value.extend(wrap(2, value)); // KeyValue.value
+ let mut record = Vec::new();
+ prost::encoding::encode_key(1, prost::encoding::WireType::SixtyFourBit, &mut record);
+ record.extend(1u64.to_le_bytes()); // LogRecord.time_unix_nano
+ prost::encoding::encode_key(11, prost::encoding::WireType::SixtyFourBit, &mut record);
+ record.extend(1u64.to_le_bytes()); // LogRecord.observed_time_unix_nano
+ record.extend(wrap(6, key_value)); // LogRecord.attributes
+ // ExportLogsServiceRequest.resource_logs -> ResourceLogs.scope_logs -> ScopeLogs.log_records
+ wrap(1, wrap(2, wrap(2, record)))
+}
+
+/// Deep nesting can not exhaust the stack: prost stops at its recursion limit
+/// of 100 messages and the body is refused. Each encoding refuses at its own
+/// depth (serde_json allows 128 nested JSON containers, three per array level),
+/// so a request nested between the two limits is taken over protobuf only.
+#[test]
+fn nesting_depth_limits_of_both_encodings() {
+ let accepted = |depth: usize| {
+ OtelProtobufRequest::decode(&deeply_nested_log_body(depth), &LogSource::OtelLogs).is_ok()
+ };
+ assert!(accepted(1));
+ for depth in [1_000, 100_000] {
+ let body = deeply_nested_log_body(depth);
+ let error = OtelProtobufRequest::decode(&body, &LogSource::OtelLogs).unwrap_err();
+ assert!(error.to_string().contains("recursion limit"), "{error}");
+ }
+ let pb_max = (1..200)
+ .take_while(|&depth| accepted(depth))
+ .last()
+ .unwrap();
+
+ let json_accepted = |depth: usize| {
+ let mut value = json!({"arrayValue": {}});
+ for _ in 1..depth {
+ value = json!({"arrayValue": {"values": [value]}});
+ }
+ let body = json!({"resourceLogs": [{"scopeLogs": [{"logRecords": [{
+ "timeUnixNano": "1",
+ "observedTimeUnixNano": "1",
+ "attributes": [{"key": "deep", "value": value}]
+ }]}]}]});
+ json_text_stage(LogSource::OtelLogs, body).result.is_ok()
+ };
+ let json_max = (1..200)
+ .take_while(|&depth| json_accepted(depth))
+ .last()
+ .unwrap();
+
+ // The rows of the deepest protobuf request
+ let (_, outcome) = pb_stage(
+ &LogSource::OtelLogs,
+ &deeply_nested_log_body(pb_max),
+ FlattenLimits::DEFAULT,
+ false,
+ );
+ assert_eq!(outcome.result.unwrap().len(), 1);
+ println!("nesting_depth_limits: protobuf={pb_max} json={json_max}");
+ assert_eq!((pb_max, json_max), (47, 39));
+}
+
+/// BUG (pre-existing in the metrics flattener, both encodings, same upstream):
+/// `flatten_metrics_record` merges a metric's `metadata` attributes over the
+/// fields of each of its rows, after `time_unix_nano` and `metric_name` are
+/// set, and `process_resource_metrics` takes the `target_info` timestamp from
+/// any row's `time_unix_nano` string. So a metric without data points whose
+/// metadata has a `time_unix_nano` attribute emits a `target_info` sample
+/// whose timestamp is that attribute: here the string "garbage". (The same
+/// merge lets metadata replace a data point's timestamp or metric name.)
+/// Found by `otel_pb_differential_metrics` with 3000 cases (row count 2, model
+/// 1); this is the minimal input reduced by hand. Expected: no `target_info`
+/// row without a data point, as for a resource whose metrics have none.
+#[test]
+#[ignore = "bug: metric metadata supplies the target_info timestamp, see doc comment"]
+fn metric_metadata_can_not_supply_the_target_info_timestamp() {
+ let request = Req::Metrics(MetricsData {
+ resource_metrics: vec![ResourceMetrics {
+ resource: Some(Resource {
+ attributes: vec![string_kv("service.name", "checkout")],
+ ..Default::default()
+ }),
+ scope_metrics: vec![ScopeMetrics {
+ metrics: vec![Metric {
+ name: "empty".to_string(),
+ metadata: vec![string_kv("time_unix_nano", "garbage")],
+ data: Some(metric::Data::Gauge(Gauge {
+ data_points: vec![],
+ })),
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ });
+ let (pb, js) = both(&request);
+ let rows = pb.result.unwrap();
+ assert_eq!(Ok(rows.clone()), js.result, "the encodings agree");
+ assert_eq!(metric_names(&rows), ["empty"], "rows: {rows:?}");
+}
+
+// ---------------------------------------------------------------------------
+// 4. Seeded deterministic scenario
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+enum Encoding {
+ Protobuf,
+ Json,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+enum Damage {
+ None,
+ Truncated,
+ Mutated,
+ Garbage,
+}
+
+struct Scenario {
+ /// Outcome counts by kind, for the coverage line
+ counts: BTreeMap,
+ /// Digest of everything that does not depend on the clock
+ digest: u64,
+ trace: Vec,
+}
+
+/// One seed: a sequence of generated requests of all three signals, sent in
+/// either encoding, some damaged, some against small flatten limits, through
+/// the decode and flatten stages into a sink of accepted rows.
+///
+/// Invariants per request:
+/// - an undamaged body decodes, and with the default limits flattens;
+/// - a body that does not decode yields no rows, and for protobuf
+/// `flatten_and_push_otel_protobuf` refuses it with the decode error;
+/// - a decoded request yields exactly the rows its structure implies (records;
+/// spans times events and links; data points plus `target_info`), or for
+/// logs a flatten-limit error and no rows;
+/// - every decoded request the JSON mapping can carry gives the same outcome
+/// in the other encoding (unset timestamps of damaged bodies filled first).
+///
+/// Across the run: the sink holds exactly the rows of accepted requests, and
+/// the same seed gives the same run.
+fn run_scenario(seed: u64) -> Result)> {
+ let mut rng = SplitMix64(seed);
+ let mut counts = BTreeMap::::new();
+ let mut trace = Vec::new();
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ let mut sink: Vec = Vec::new();
+ let mut accepted_rows = 0usize;
+ let requests_of = |wild: bool| -> [BoxedStrategy; 3] {
+ [
+ logs_data(wild).prop_map(Req::Logs).boxed(),
+ traces_data(wild).prop_map(Req::Traces).boxed(),
+ metrics_data(wild).prop_map(Req::Metrics).boxed(),
+ ]
+ };
+ let (strategies, wild) = (requests_of(false), requests_of(true));
+ let tight = tight_limits();
+
+ let requests = 6 + rng.below(10);
+ for index in 0..requests {
+ let signal = rng.below(3) as usize;
+ let request = if rng.percent(25) {
+ sample(&wild[signal], &mut rng)
+ } else {
+ sample(&strategies[signal], &mut rng)
+ };
+ let encoding = if rng.percent(50) {
+ Encoding::Protobuf
+ } else {
+ Encoding::Json
+ };
+ // JSON can not encode what it can not carry; such a request goes as protobuf
+ let encoding = if json_representable(&request) {
+ encoding
+ } else {
+ Encoding::Protobuf
+ };
+ let damage = match rng.below(100) {
+ 0..60 => Damage::None,
+ 60..75 => Damage::Truncated,
+ 75..90 => Damage::Mutated,
+ _ => Damage::Garbage,
+ };
+ let limits = if rng.percent(20) {
+ sample(&tight, &mut rng)
+ } else {
+ FlattenLimits::DEFAULT
+ };
+ let mut body = match encoding {
+ Encoding::Protobuf => request.encode_pb(),
+ Encoding::Json => request.encode_json(),
+ };
+ match damage {
+ Damage::None => {}
+ Damage::Truncated => {
+ let len = rng.below(body.len() as u64) as usize;
+ body.truncate(len);
+ }
+ Damage::Mutated => {
+ for _ in 0..1 + rng.below(4) {
+ let m = match rng.below(4) {
+ 0 => Mutation::Flip(rng.next_u64() as usize, rng.next_u64() as u8),
+ 1 => Mutation::Set(rng.next_u64() as usize, rng.next_u64() as u8),
+ 2 => Mutation::Insert(rng.next_u64() as usize, rng.next_u64() as u8),
+ _ => Mutation::Remove(rng.next_u64() as usize),
+ };
+ mutate(&mut body, &m);
+ }
+ }
+ Damage::Garbage => {
+ body = (0..rng.below(64)).map(|_| rng.next_u64() as u8).collect();
+ }
+ }
+ let label = format!(
+ "#{index} {} {encoding:?} {damage:?} limits={limits:?} body={}B",
+ request.name(),
+ body.len()
+ );
+ trace.push(label.clone());
+ let fail =
+ |what: String, trace: &mut Vec| -> Result)> {
+ trace.push(format!(" FAILED: {what}"));
+ Err((format!("{label}: {what}"), std::mem::take(trace)))
+ };
+ let source = request.source();
+
+ let normalise = rng.percent(50);
+ let (decoded, outcome) = match encoding {
+ Encoding::Protobuf => pb_stage(&source, &body, limits, false),
+ Encoding::Json => json_stage(&source, &body, limits, false, normalise),
+ };
+ let kind = match (&decoded, &outcome.result) {
+ (None, Err(StageError::Decode(error))) => {
+ if damage == Damage::None {
+ return fail(format!("undamaged body refused: {error}"), &mut trace);
+ }
+ if encoding == Encoding::Protobuf {
+ let refused = flatten_and_push_otel_protobuf(
+ &body,
+ "dst",
+ &source,
+ &HashMap::new(),
+ request.telemetry_type(),
+ &None,
+ );
+ if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str()))
+ {
+ return fail(
+ format!("entry point did not refuse: {refused:?}"),
+ &mut trace,
+ );
+ }
+ }
+ error.hash(&mut hasher);
+ "decode_refused"
+ }
+ (Some(decoded), Ok(rows)) => {
+ let expected = decoded.expected_rows();
+ if rows.len() != expected {
+ return fail(
+ format!("{} rows, structure implies {expected}", rows.len()),
+ &mut trace,
+ );
+ }
+ let mut replay = decoded.clone();
+ let clock = fill_unset_timestamps(&mut replay);
+ if !clock {
+ serde_json::to_string(rows).unwrap().hash(&mut hasher);
+ }
+ rows.len().hash(&mut hasher);
+ accepted_rows += rows.len();
+ sink.extend(rows.iter().cloned());
+ if damage == Damage::None {
+ "accepted"
+ } else {
+ "damaged_but_accepted"
+ }
+ }
+ (Some(decoded), Err(StageError::Flatten(error))) => {
+ if !matches!(decoded, Req::Logs(_)) || limits == FlattenLimits::DEFAULT {
+ return fail(format!("unexpected flatten refusal: {error}"), &mut trace);
+ }
+ error.hash(&mut hasher);
+ "flatten_limit_refused"
+ }
+ other => return fail(format!("impossible stage result {other:?}"), &mut trace),
+ };
+ trace.push(format!(" -> {kind}"));
+ (index, encoding, damage, kind).hash(&mut hasher);
+ *counts
+ .entry(format!("{}_{kind}_{encoding:?}", request.name()))
+ .or_default() += 1;
+
+ // The other encoding of what was decoded agrees
+ if let Some(mut decoded) = decoded {
+ fill_unset_timestamps(&mut decoded);
+ if json_representable(&decoded) {
+ if let Err(error) = assert_encodings_agree(&decoded, limits, false, normalise) {
+ return fail(format!("encodings disagree: {error}"), &mut trace);
+ }
+ *counts.entry("cross_encoding_checked".into()).or_default() += 1;
+ } else {
+ *counts
+ .entry("cross_encoding_not_representable".into())
+ .or_default() += 1;
+ }
+ }
+ }
+ if sink.len() != accepted_rows {
+ return Err((
+ format!("sink holds {} rows, accepted {accepted_rows}", sink.len()),
+ trace,
+ ));
+ }
+ *counts.entry("rows".into()).or_default() += sink.len() as u64;
+ Ok(Scenario {
+ counts,
+ digest: hasher.finish(),
+ trace,
+ })
+}
+
+/// The seeded scenario, after the DST conventions: `DST_SEED` (default 0) is
+/// the first seed, `DST_ITERS` (default 32) the number of seeds, a failure
+/// prints its seed and trace, and each seed is run twice to check the run is
+/// deterministic.
+///
+/// How far down it goes: decode and flatten, i.e. everything
+/// `flatten_and_push_otel_protobuf` and the OTEL arms of `flatten_and_push_logs`
+/// do before `push_logs`. It stops there because every later step reads the
+/// `PARSEABLE` global:
+/// - `verify_dataset_fields_count` and `push_logs` look the stream up in
+/// `PARSEABLE` (a stream handle passed in, or a lookup trait, would be the seam);
+/// - `FlattenLimits::from_config` reads the server options (the tests pass
+/// limits instead, which is what that function returns);
+/// - `convert_array_to_object` calls `has_more_than_max_allowed_levels`, which
+/// reads `PARSEABLE.options.event_flatten_level`, for schema version V1, even
+/// for OTEL sources, because `should_apply_generic_flattening` tests the depth
+/// before the log source (testing the source first, or passing the level in,
+/// would open `convert_array_to_object` and `json::Event::into_recordbatch`,
+/// which takes `p_timestamp` as an argument, to these tests);
+/// - `Event::process` stages into the stream from `PARSEABLE`.
+///
+/// Rows also depend on the clock wherever a timestamp is unset
+/// (`convert_epoch_nano_to_timestamp`); generated requests set them all, and
+/// damaged bodies that decode with unset ones are compared after filling them.
+#[test]
+fn dst_otlp_mixed_encoding_ingest() {
+ let first = env_u64("DST_SEED").unwrap_or(0);
+ let iterations = env_u64("DST_ITERS").unwrap_or(32);
+ assert!(iterations > 0, "DST_ITERS must be positive");
+ let mut totals = BTreeMap::::new();
+ for seed in first..first + iterations {
+ let run = match run_scenario(seed) {
+ Ok(run) => run,
+ Err((error, trace)) => panic!(
+ "DST otlp_mixed_encoding seed={seed}: {error}\nreplay: DST_SEED={seed} DST_ITERS=1\n{}",
+ trace.join("\n")
+ ),
+ };
+ let again = run_scenario(seed).unwrap_or_else(|(error, _)| {
+ panic!("DST otlp_mixed_encoding seed={seed}: second run failed: {error}")
+ });
+ assert_eq!(
+ run.digest,
+ again.digest,
+ "DST otlp_mixed_encoding seed={seed}: the same seed gave a different run\n{}",
+ run.trace.join("\n")
+ );
+ assert_eq!(run.counts, again.counts, "seed={seed}");
+ for (key, value) in run.counts {
+ *totals.entry(key).or_default() += value;
+ }
+ }
+ println!(
+ "DST_COVERAGE scenario=otlp_mixed_encoding first_seed={first} iterations={iterations} counts={totals:?}"
+ );
+ if iterations >= 32 {
+ // Not vacuous: every kind of outcome happened
+ let seen = |needle: &str| totals.keys().any(|key| key.contains(needle));
+ for needle in [
+ "_accepted_Protobuf",
+ "_accepted_Json",
+ "decode_refused_Protobuf",
+ "decode_refused_Json",
+ "damaged_but_accepted",
+ "flatten_limit_refused",
+ "cross_encoding_checked",
+ "cross_encoding_not_representable",
+ ] {
+ assert!(seen(needle), "no {needle} outcome in {totals:?}");
+ }
+ }
+}
+
+/// The scenario itself is seed-sensitive: different seeds give different runs
+#[test]
+fn dst_otlp_mixed_encoding_seeds_differ() {
+ let digests: std::collections::HashSet = (0..4)
+ .map(|seed| run_scenario(seed).map_err(|(e, _)| e).unwrap().digest)
+ .collect();
+ assert_eq!(digests.len(), 4);
+}
diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs
index 6684dd1bf..f3793b975 100644
--- a/src/otel/metrics.rs
+++ b/src/otel/metrics.rs
@@ -791,6 +791,15 @@ fn process_resource_metrics(
/// and returns a `Vec` of `Value::Object` of the flattened json
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn flatten_otel_metrics(message: MetricsData, tenant_id: &str) -> Vec {
+ flatten_otel_metrics_with_options(message, tenant_id, PARSEABLE.options.otel_flatten_exemplars)
+}
+
+/// Flattens a JSON-decoded metrics request with an explicit exemplar policy.
+pub fn flatten_otel_metrics_with_options(
+ message: MetricsData,
+ tenant_id: &str,
+ flatten_exemplars: bool,
+) -> Vec {
process_resource_metrics(
&message.resource_metrics,
|record| record.resource.as_ref(),
@@ -801,7 +810,7 @@ pub fn flatten_otel_metrics(message: MetricsData, tenant_id: &str) -> Vec
|scope_metric| &scope_metric.metrics,
|metric| metric,
tenant_id,
- PARSEABLE.options.otel_flatten_exemplars,
+ flatten_exemplars,
)
}
@@ -809,6 +818,19 @@ pub fn flatten_otel_metrics(message: MetricsData, tenant_id: &str) -> Vec
pub fn flatten_otel_metrics_protobuf(
message: &ExportMetricsServiceRequest,
tenant_id: &str,
+) -> Vec {
+ flatten_otel_metrics_protobuf_with_options(
+ message,
+ tenant_id,
+ PARSEABLE.options.otel_flatten_exemplars,
+ )
+}
+
+/// Flattens a protobuf metrics request with an explicit exemplar policy.
+pub fn flatten_otel_metrics_protobuf_with_options(
+ message: &ExportMetricsServiceRequest,
+ tenant_id: &str,
+ flatten_exemplars: bool,
) -> Vec {
let span = info_span!(
"flatten_otel_metrics_protobuf",
@@ -827,7 +849,7 @@ pub fn flatten_otel_metrics_protobuf(
|scope_metric| &scope_metric.metrics,
|metric| metric,
tenant_id,
- PARSEABLE.options.otel_flatten_exemplars,
+ flatten_exemplars,
);
span.record("output_count", result.len());