Skip to content

Write cluster telemetry to the bucket through a bundled Worker - #8760

Open
ry wants to merge 7 commits into
mainfrom
ry/cluster-telemetry
Open

ry wants to merge 7 commits into
mainfrom
ry/cluster-telemetry

Conversation

@ry

@ry ry commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

A workerd cluster can now keep its traces and logs in its own bucket. WORKERD_OTEL=1 adds a bundled Worker, /workerd/telemetry.js, as the tracing.otlp collector. It writes gzipped NDJSON under services/telemetry/ in the cluster bucket, which DuckDB can query directly. This follows the review: telemetry goes to a Worker over OTLP, not to a native sink.

SELECT name, count(*), median(duration_us)
FROM read_json('s3://bucket/prefix/services/telemetry/traces/**/*.ndjson.gz')
GROUP BY name;
  • TracingOptions gains exportLogs, protocol (httpProtobuf or httpJson) and sampleRatio. Sampling is by trace ID and parent-based. An unsampled invocation makes no spans but still exports its logs.
  • With httpJson, the exporter re-encodes each batch as OTLP/JSON in Rust (src/rust/otlp/json.rs), writing directly with no intermediate tree.
  • The export queue waits up to 1 s or 1 MiB before posting, so the Worker writes about one file per second per signal.
  • OTEL_EXPORTER_OTLP_ENDPOINT, _HEADERS, _PROTOCOL and OTEL_TRACES_SAMPLER_ARG configure a collector without capnp.
  • The Worker writes one file per POST at {traces,logs}/<yyyy>/<mm>/<dd>/<hh>/<unix_ms>-<rand>.ndjson.gz, a row per span or log record. Its header comment documents the columns, which are v0 and unstable. Nothing deletes files; give the bucket a lifecycle rule.
  • Compared with the Parquet version: no new crates, and no tracing.bucket.

This does not add cluster system traces. The spans are the ones #7686 already creates: each invocation, its subrequests and its storage operations. Finding the Durable Object's owner, forwarding to it, activation, the output gate and the bucket write come next, through this exporter.

Measured on a three-node cluster, /get at 64 connections: off 7244 req/s; OTLP endpoint (protobuf) 5684 (-22%); http/json 5200 (-28%); WORKERD_OTEL=1 4384 (-40%); WORKERD_OTEL=1 with OTEL_TRACES_SAMPLER_ARG=0.01 6124 (-15%). No spans lost, and p99 rises only in line with throughput. RSS under load is about 185 MB higher with the bundled Worker than with telemetry off; I haven't tracked that down yet. #8909 removed a per-invocation exception that cost part of this.

Spans carry no node attribute, and requests queued at shutdown are lost.

Tests: otlp_test (JSON encoding), otlp-export-queue-test (the wait), workerd-server_test, workerd-cli_test, and two cluster-test cases (WORKERD_OTEL=1 into the bucket, and a fake collector over http/json).

@ry
ry requested review from a team as code owners November 20, 2026 23:04

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 214e54e0.

This review, of 235852e3

💬 Approved with comments — No blocking issues or concrete production defects. There are six INFO notes: the retention sweep has no test, an out-of-range status code is dropped, an encoder task failure is never logged, an unchecked multiply on the retention value, decoding runs on the event loop, and one crate doc claim is too strong.

Findings: 6 info (6 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 4 info

The sinks are wired consistently. The retention sweep that deletes bucket data has no test, and there are three small robustness gaps.

Recommendation: 💬 Optional Nits

  • [INFO] The retention sweep deletes bucket objects and has no test; its key-slicing logic would be easy to cover with a pure helper. (src/workerd/server/server/telemetry.rs:295)
  • [INFO] take_int removes the attribute before range-checking it, so an out-of-range http.response.status_code is dropped from both the column and attributes. (src/rust/otlp-parquet/lib.rs:368)
  • [INFO] flush_now silently discards a JoinError from the encoding task, losing that flush's rows with no log. (src/workerd/server/server/telemetry.rs:255)
  • [INFO] days * 86_400 is an unchecked multiply on the WORKERD_OTEL_RETENTION value. (src/workerd/server/server/telemetry.rs:109)
View full review
  • The retention sweep is the only code in this change that deletes data, and it has no test. It works by fixed-width slicing of keys and compares the slices as text.
  • take_int removes http.response.status_code before it range-checks the value, so a value that does not fit is lost.
  • When the encoder task panics, flush_now discards the JoinError and logs nothing.
  • WORKERD_OTEL_RETENTION multiplies the day count without an overflow check.

⚡ Performance: 💬 1 info

Decoding and flattening OTLP requests runs synchronously on the event loop.

Recommendation: 💬 Optional Nits

  • [INFO] Decoding and flattening each OTLP request runs inline on the event-loop thread; only the Parquet encode is offloaded. (src/workerd/server/server/telemetry.rs:333)
View full review

Only the Parquet encoding runs on the blocking pool. The prost decode, hex conversion and per-row JSON serialization of attributes all run inline on the event loop.


📝 Documentation: 💬 1 info

The crate doc says nothing in the request is lost, which is broader than what the code keeps.

Recommendation: 💬 Optional Nits

  • [INFO] "nothing in the request is lost" overstates what is kept: scope data, span events and links are not encoded. (src/rust/otlp-parquet/lib.rs:8)
View full review

The crate doc in src/rust/otlp-parquet/lib.rs promises more than the code keeps. Only resource and record attributes are carried over, and fields such as scope, events and links are not.


✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found in the collector URL and header handling or in the bucket writes.


📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues.


Reviewed commit: 235852e3

Comment thread src/workerd/server/server/telemetry.rs Resolved
Comment thread src/rust/otlp-parquet/lib.rs Resolved
Comment thread src/workerd/server/server/telemetry.rs Resolved
Comment thread src/workerd/server/server/telemetry.rs Resolved
Comment thread src/workerd/server/server/telemetry.rs Outdated
tracing::warn!("telemetry: dropping spans that do not decode");
return;
};
sink.add(otlp_parquet::spans(request), Vec::new());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ INFO · Performance

Decoding and flattening each OTLP request runs inline on the event-loop thread; only the Parquet encode is offloaded.

Each call does a prost decode, hex-encodes the IDs, clones service for every row and builds a JSON string for each row's attributes, all on the event loop. This CPU cost grows with the number of spans per request. If the measured throughput loss persists, consider buffering the raw request bytes and doing decode plus flatten inside the existing spawn_blocking closure.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI] Leaving this as is for now. On a test fleet the collector sink, which never decodes, cost the same throughput as the bucket sink, so span creation upstream dominates. It's listed under costs in the description, and we'll revisit it with sampling.

Comment thread src/rust/otlp-parquet/lib.rs Resolved
A cluster can now keep its traces and logs in its own bucket, where
DuckDB queries them in place, or send both to an OpenTelemetry
collector, without a collector service in the config.

`tracing.bucket` hands every OTLP request the exporter encodes to a
Rust sink. It flattens spans and log records into rows, buffers them,
and writes one Parquet file per signal every `flushMs` (default 5 min)
or `flushBytes` (5 MiB) under `<prefix>telemetry/{traces,logs}/<node>/
<yyyy>/<mm>/<dd>/<hh>/`. Encoding runs on tokio's blocking pool. Files
older than `retentionDays` (30) are deleted at startup and every six
hours. Promoted columns: trace and span IDs, name, kind, start,
duration, ok, error, the Durable Object ID (`cell`), url, http_status;
every other attribute goes into an `attributes` JSON column. Log bodies
are rebuilt into console lines, with an Error as its stack.

Without `tracing` in the config, `WORKERD_OTEL` fills it: `1` is the
bucket (with `WORKERD_OTEL_FLUSH_MS`, `_FLUSH_BYTES`, `_RETENTION`), an
http(s) URL is a collector that gets `/v1/traces` and `/v1/logs`, with
`OTEL_EXPORTER_OTLP_HEADERS` on each request. A collector URL is an
in-memory `ExternalServer`, so TLS and header injection reuse it.

The exporter gains a second queue for logs, since a queue batches by
concatenating requests of one message type. `tracing.otlp` stays
traces only. The Parquet writer is its own crate, `src/rust/otlp-
parquet` (parquet 59 without arrow, GZIP through flate2's zlib-rs
backend, which the tree already has); `src/rust/otlp` only makes
`proto` public and drops a `struct_field_names` expectation that
clippy no longer meets on exported types.
@ry
ry force-pushed the ry/cluster-telemetry branch from 235852e to 214e54e Compare November 24, 2026 21:16

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 6a3ae915.

This review, of 214e54e0

💬 Approved with comments — No blocking issues or production defects. Five of the six notes from the last review are fixed. One INFO note remains open: decoding and flattening each OTLP request still runs on the event loop, which the pull request description already lists as a known gap.

Findings: 1 info (1 is an inline comment on the diff)

Not opened by the correctness review: 2 changed files it was meant to read
  • deps/rust/Cargo.toml
  • src/rust/otlp/proto.rs

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


⚡ Performance: 💬 1 info

One INFO: decoding and flattening still run on the event loop.

Recommendation: 💬 Optional Nits

  • [INFO] Decoding and flattening each OTLP request runs inline on the event loop; only the Parquet encode is offloaded. (src/workerd/server/server/telemetry.rs:343)
View full review

Only the Parquet encode runs on the blocking pool. telemetry_spans and telemetry_logs decode the request with prost and flatten it on the event loop. Flattening includes the hex conversion and building each row's attributes JSON. The pull request description lists this as a known gap.


✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found:

  • Worker data: span names, attributes and log bodies end up only in Parquet column values and a JSON column built with serde_json.
  • Bucket keys: a key is built only from the signal, the node name, the time and a random tag.
  • Retention sweep: it is limited to the traces/ and logs/ prefixes, and its cutoff is set by the operator.
  • Collector settings: the collector URL is checked for an http or https scheme, a host, and no query or fragment.

📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues.


📋 Code Quality: ✅ LGTM

All four earlier notes are fixed in this commit:

  • Retention sweep tests: the sweep now goes through a pure expired() helper, and telemetry-test.rs tests it.
  • Out-of-range status codes: take_int now range-checks the value before it removes the attribute, so a status code that does not fit stays in attributes.
  • Lost encoder failures: flush_now now logs a failed encoding task.
  • Retention overflow: WORKERD_OTEL_RETENTION now uses checked_mul.

I found no new correctness problems in the flush and buffer handling, the sink and queue wiring in worker-factory-otlp.c++, or how config.rs chooses between the environment variable and the config.


📝 Documentation: ✅ LGTM

No documentation issues found.


Reviewed commit: 214e54e0

Comment thread src/workerd/server/server/telemetry.rs Resolved
ry added 2 commits November 24, 2026 14:47
# Conflicts:
#	deps/rust/cargo-bazel-lock.json
# Conflicts:
#	deps/rust/cargo-bazel-lock.json

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of d3bac92c.

This review, of 6a3ae915

✅ Approved — No new findings. Since the last review, only lockfiles changed, from a merge of main, and they match Cargo.toml. One earlier note about work on the event loop stays open, and the description already lists it as a known gap.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues found in the lockfile updates or the rest of the change.


📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues.


📋 Code Quality: ✅ LGTM

The lockfile updates match deps/rust/Cargo.toml. parquet is pinned to 59 with only the flate2-zlib-rs feature. The proto.rs changes are consistent with proto becoming public. Earlier findings stay fixed.


⚡ Performance: ✅ LGTM

No new performance issues. One earlier note is still open: decoding and flattening each OTLP request runs on the event loop. The pull request description lists this as a known gap.


📝 Documentation: ✅ LGTM

No documentation issues found.


Reviewed commit: 6a3ae915

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of b9549df9.

This review, of d3bac92c

✅ Approved — No findings. Since the last review only lockfiles changed, from a merge of main, and they match Cargo.toml.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues found.


📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues found.


📋 Code Quality: ✅ LGTM

The lockfile updates match deps/rust/Cargo.toml. In the telemetry sink, the buffer is reset on every flush, the bucket keys line up with what the retention sweep expects, and the sweep task does not keep the sink alive.


⚡ Performance: ✅ LGTM

Buffering is bounded by flushBytes, and Parquet encoding runs on the blocking pool. One earlier note is still open: decoding and flattening each request runs on the event loop. The pull request description lists this as a known gap.


📝 Documentation: ✅ LGTM

No documentation issues found.


Reviewed commit: d3bac92c

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 12.11604% with 515 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.46%. Comparing base (2688566) to head (d3bac92).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/rust/otlp-parquet/lib.rs 0.00% 223 Missing ⚠️
src/workerd/server/server/telemetry.rs 4.93% 212 Missing ⚠️
src/workerd/server/server/config.rs 26.22% 45 Missing ⚠️
src/workerd/server/factory/worker-factory-otlp.c++ 55.76% 19 Missing and 4 partials ⚠️
src/workerd/server/cluster/cluster.rs 0.00% 4 Missing ⚠️
src/workerd/server/factory/worker-factory.c++ 78.94% 3 Missing and 1 partial ⚠️
src/workerd/server/tests/cluster/cluster-worker.js 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8760      +/-   ##
==========================================
- Coverage   67.61%   67.46%   -0.16%     
==========================================
  Files         871      873       +2     
  Lines      220304   220869     +565     
  Branches    32941    32952      +11     
==========================================
+ Hits       148959   149008      +49     
- Misses      51847    52359     +512     
- Partials    19498    19502       +4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@danlapid danlapid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this! Being able to query traces and logs with DuckDB, with no collector to run, is a great story for self-hosters. Same direction as on #8172 and #8507, though: I'd like the sink to be "just a worker" rather than a second native mode of the exporter.

1. Make the sink a bundled worker that tracing.otlp points at

tracing.otlp is already a ServiceDesignator. The exporter POSTs OTLP/HTTP to it, batches up to 1 MiB, and doesn't trace that service's own invocations. So a bundled /workerd/telemetry.js can be the collector with no new mechanism:

services = [
  (name = "workerd:telemetry", worker = (
    modules = [(name = "telemetry.js", bundled = "/workerd/telemetry.js")],
    bindings = [(name = "STORE", service = "<bucket>")])),
  ...
],
tracing = (otlp = "workerd:telemetry"),

WORKERD_OTEL=1 then just generates this config. TracingBucket, telemetry.rs, the exporter's sink mode, factory_new_bucket_exporter and the otlp-parquet crate all go away, along with the 16 crates parquet pulls in (chrono, num-bigint, half, twox-hash, const-random, the windows-* crates, and so on).

The work moves into JS: decoding OTLP protobuf (or having the exporter send OTLP/JSON, which the spec allows), and writing Parquet. A small JS Parquet writer is fine; gzip NDJSON would also do to start, since DuckDB reads it in place too.

2. Local dev and single-node self-hosting

Today the sink requires Config.cluster, so neither gets anything. With the worker, STORE is a disk locally, or the bucket service on a local disk since #8507, and the same files and the same DuckDB queries work everywhere.

3. Logs on the tracing.otlp path

The capnp tracing.otlp path passes export_logs = false, so logs only go out through WORKERD_OTEL=<url> and the bucket sink. Sending logs to /v1/logs on the configured service would fix that for any collector, and it's the one native change the worker approach needs.

4. Losing data on shutdown

Rows buffered at shutdown are dropped, and with the five-minute default that loses up to five minutes of telemetry on every restart and rolling upgrade, which is exactly when you'd want it. If the worker writes one file per export POST it receives, nothing is held in memory and this goes away. If it buffers to make bigger files, it should flush while draining.

5. Retention

Every node lists the whole telemetry/ prefix, for all nodes, every six hours. At the defaults that's about 17k files per node, so the listing work grows with the square of the node count. In the worker this could be a cron trigger that only lists expired hour prefixes, or simply the bucket's lifecycle rule, documented next to the multipart one from #8507.

6. Smaller things

  • Standard env vars: WORKERD_OTEL=<url> duplicates OTEL_EXPORTER_OTLP_ENDPOINT, while the PR already reads OTEL_EXPORTER_OTLP_HEADERS. Using the standard endpoint variable makes existing OTel setups just work.
  • Sampling: every trace without an upstream decision is sampled, and the PR measures about 35% throughput cost on a CPU-bound path, from span creation. Fine for an opt-in feature, but a ratio sampler (OTEL_TRACES_SAMPLER_ARG) would make it something we can recommend for production self-hosting.

Never letting a failed upload hold up requests is the right call, and the exporter's queue already gives the worker that for free. Happy to talk it through if there's a reason the sink needs to be native 🙂

ry added 3 commits November 25, 2026 10:36
Dan's review: the receiving side should be a Worker, as Workers
Observability's OTLP receptor is in production, not native code in
workerd.

- /workerd/telemetry.js, a bundled OTLP/JSON collector, writes each
  POST as one gzipped NDJSON file in a bucket service, a row per span
  or log record. WORKERD_OTEL=1 adds it and its bucket service to the
  config and points tracing.otlp at it.
- TracingOptions gains exportLogs, protocol (httpProtobuf or httpJson)
  and sampleRatio. JSON is re-encoded natively from each protobuf
  batch (src/rust/otlp/json.rs).
- OTEL_EXPORTER_OTLP_ENDPOINT replaces WORKERD_OTEL=<url>, with
  OTEL_EXPORTER_OTLP_PROTOCOL and OTEL_TRACES_SAMPLER_ARG.
- Removes tracing.bucket, the Rust sink, src/rust/otlp-parquet and the
  parquet crate with its 16 dependencies.
encode_json built a serde_json::Value tree for each batch, then
serialized and dropped it, all on the event loop: on a 4-vCPU node it
was about 190 us of each request's event-loop time with every trace
exported. It now writes the JSON as it walks the decoded request.

The export queue posted as soon as anything was pending, so the
bundled telemetry Worker wrote a file per invocation when idle and
about 3,400 a minute per node under load. A request now waits up to a
second to be batched with later ones; a full 1 MiB batch still goes at
once. otlp-tracing-test's collector records each invocation's
ResourceSpans, since one POST may now carry several.
@ry ry changed the title Write cluster telemetry as Parquet to the bucket Write cluster telemetry to the bucket through a bundled Worker Nov 26, 2026

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 14db54fc.

This review, of b9549df9

💬 Approved with comments — No correctness, security or data-loss defects found in the bundled telemetry Worker, the OTLP/JSON encoder or the export-queue linger. The remaining notes cover missing tests for the environment config and sampling, JSON encoding on the event loop, and one comment that could be more precise.

Findings: 3 info · 1 suggestion (4 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 2 info

Encoder, linger batching and sampling look correct. The new environment-config method and the sampling path have no direct tests.

Recommendation: 💬 Optional Nits

  • [INFO] Config::with_telemetry_environment has no unit test for its error and precedence branches. (src/workerd/server/cli/config.rs:246)
  • [INFO] The trace-ID sampling decision and its parent-based override have no direct test. (src/workerd/server/factory/worker-factory.c++:1053)
View full review
  • Config::with_telemetry_environment has no unit test (src/workerd/server/cli/config.rs:246). It has several error and precedence branches: a bad WORKERD_OTEL value, a conflict with OTEL_EXPORTER_OTLP_ENDPOINT, a bad sampler ratio, a config that already sets tracing, and a reserved workerd-telemetry* service name. Its sibling with_shutdown_delay_environment has tests in cli/config-test.rs. The cluster test covers only the happy path.
  • The trace-ID sampling decision has no direct test (src/workerd/server/factory/worker-factory.c++:1053). Every test uses the default ratio of 1, so three cases go untested: a ratio below 1, a parent-sampled override, and an unsampled invocation that still exports its logs.

I also checked the rest and found no problems: the pendingBytes accounting in the export queue stays consistent; the JSON encoder writes hex IDs, string 64-bit integers and null for non-finite doubles; and the is_some() guard on OtlpTracing::collector is correct.


⚡ Performance: 💬 1 info

With httpJson, the OTLP/JSON re-encode runs on the event loop. The linger batching is bounded.

Recommendation: 💬 Optional Nits

  • [INFO] With httpJson, the decode and JSON re-encode of each batch (up to about 1 MiB) run synchronously on the event loop. (src/workerd/server/factory/worker-factory-otlp.c++:36)
View full review
  • INFO: With httpJson, CollectorTransport::post decodes and re-encodes each batch as JSON (up to about 1 MiB) inline on the event loop, then copies the result into a new kj::heapArray (src/workerd/server/factory/worker-factory-otlp.c++:36-39). Batching means this now runs once per batch rather than once per request, but a large batch can still block the loop for a few milliseconds.

The export-queue linger is bounded. Only the single run() task waits on the timer, and the queue-full drop still caps memory.


📝 Documentation: 💬 1 suggestion

One comment overstates how environment variables are handled when tracing is set.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] The comment says the environment variables are ignored when tracing is set, but invalid values are still rejected before that check. (src/workerd/server/workerd.capnp:394)
View full review
  • The new TracingOptions header says that with tracing set, the variables "are ignored with a warning" (src/workerd/server/workerd.capnp:394). That is not fully true: with_telemetry_environment validates WORKERD_OTEL and OTEL_TRACES_SAMPLER_ARG before it checks root.has_tracing() (src/workerd/server/cli/config.rs:248-273), so an invalid value is still an error.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found. The OTLP/JSON encoder escapes strings through serde_json, and its keys are static. The telemetry Worker accepts only POSTs to /v1/traces and /v1/logs, and it builds object keys from the clock and a random value, never from the request. The CLI refuses a config that already has a service with the reserved name prefix. The collector endpoint URL is validated, and HTTPS uses verified TLS.


📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues found.


Reviewed commit: b9549df9

/// `workerd-telemetry-store` at `telemetry`, and points `tracing` at them: traces and logs, as
/// OTLP/JSON, sampled at `OTEL_TRACES_SAMPLER_ARG`. See `TracingOptions` in workerd.capnp.
/// `var` reads an environment variable. A config that sets `tracing` keeps it, with a warning.
pub fn with_telemetry_environment(self, var: Env<'_>) -> Result<Self, String> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ INFO · Code Quality

Config::with_telemetry_environment has no unit test for its error and precedence branches.

This method has several error and precedence branches, and none of them has a unit test: an invalid WORKERD_OTEL value, a conflict with OTEL_EXPORTER_OTLP_ENDPOINT, a bad OTEL_TRACES_SAMPLER_ARG, a config that already sets tracing (warn and keep), and a reserved workerd-telemetry* service name. The cluster test covers only the happy path. Consider adding cases to cli/config-test.rs, next to the with_shutdown_delay_environment tests. They could also check the generated config: the two added services, the STORE binding, protocol, sampleRatio and exportLogs.

// Standalone export samples traces without an upstream decision, by trace ID. Set the
// invocation's context so user spans and subrequests inherit the same flags.
bool sampled =
ratio >= 1 || invocation.getTraceId().getLow() < static_cast<uint64_t>(ratio * 0x1p64);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ INFO · Code Quality

The trace-ID sampling decision and its parent-based override have no direct test.

Every test runs with the default sampleRatio of 1, so three things are never tested: the getLow() < ratio * 2^64 threshold, the parent-based override through getTraceFlags(), and the case where an unsampled invocation still exports logs. A test with sampleRatio = 0 would cover all three. It should check that no spans are posted, that logs still are, and that a parent-sampled trace still exports its spans.

kj::Promise<void> post(kj::Array<const kj::byte> request) override {
auto contentType = "application/x-protobuf"_kj;
if (json) {
auto body = rust::otlp::encode_json(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ INFO · Performance

With httpJson, the decode and JSON re-encode of each batch (up to about 1 MiB) run synchronously on the event loop.

With httpJson, encode_json runs inline on the event-loop thread: a prost decode of the whole batch, then the JSON write. The result is then copied again into a new kj::heapArray. Batching keeps this to once per batch, but a batch near 1 MiB can still hold up the loop for a few milliseconds. If this shows up in profiles, consider moving the encode to a worker thread, or handing the Rust Vec to the body without the extra copy.

# collector at `<endpoint>/v1/traces` and `<endpoint>/v1/logs`, with
# `OTEL_EXPORTER_OTLP_HEADERS` (comma-separated `name=value`, values percent-encoded) on each
# request and `OTEL_EXPORTER_OTLP_PROTOCOL` (`http/protobuf`, the default, or `http/json`).
# Either way, `OTEL_TRACES_SAMPLER_ARG` sets `sampleRatio`. With `tracing` set, the variables are

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 SUGGESTION · Documentation

The comment says the environment variables are ignored when tracing is set, but invalid values are still rejected before that check.

This line says that when the config sets tracing, the environment variables are ignored with a warning. In with_telemetry_environment, though, an invalid WORKERD_OTEL value or an invalid OTEL_TRACES_SAMPLER_ARG returns an error before root.has_tracing() is checked. Consider saying that valid settings are ignored with a warning, but invalid values are still rejected.

The traces and logs queues post to the same service, so the bridge
takes one channel and the C++ side shares it, rather than Rust making
two. exportsLogs and sampleRatio become fields of OtlpExporter in place
of two getter functions. postOtlpTraces has one caller and loses its
default content type. Long comment lines are rewrapped.

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 Approved with comments — No correctness, security or data-loss defects found. The remaining INFO and SUGGESTION notes cover missing tests, JSON encoding on the event loop and one imprecise comment.

Findings: 3 info · 1 suggestion

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 2 info

No defects. Two notes on missing tests are still open.

Recommendation: 💬 Optional Nits

  • [INFO] Config::with_telemetry_environment has no unit test for its error and precedence branches. (src/workerd/server/cli/config.rs:246)
  • [INFO] The trace-ID sampling decision and the parent-based override have no direct test. (src/workerd/server/factory/worker-factory.c++:1052)
View full review
  • with_telemetry_environment has no unit test for its error and precedence branches.
  • The trace-ID sampling decision and the parent-based override have no direct test.

No problems in the export-queue linger accounting or the shared collector channel.


⚡ Performance: 💬 1 info

With httpJson, each batch is still re-encoded on the event loop.

Recommendation: 💬 Optional Nits

  • [INFO] With httpJson, the decode and JSON re-encode of each batch (up to about 1 MiB) run synchronously on the event loop. (src/workerd/server/factory/worker-factory-otlp.c++:41)
View full review

With httpJson, CollectorTransport::post decodes and re-encodes each batch as JSON (up to about 1 MiB) inline on the event loop, then copies the result into a new array. The export-queue linger is bounded.


📝 Documentation: 💬 1 suggestion

One comment overstates what happens to the environment variables when tracing is set.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] The comment says the environment variables are ignored when tracing is set, but invalid values are still rejected before that check. (src/workerd/server/workerd.capnp:394)
View full review

The TracingOptions comment says the variables are ignored when tracing is set, but invalid values are still rejected first.


✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found. The telemetry Worker accepts only POSTs to /v1/traces and /v1/logs, and it builds object keys from the clock and a random value, never from the request. The CLI refuses a config that already has a workerd-telemetry* service. The collector endpoint is validated, and HTTPS uses verified TLS. The export queue stays bounded.


📖 AGENTS.md: ✅ LGTM

No AGENTS.md issues found.


Reviewed commit: 14db54fc

@danlapid danlapid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is exactly the shape I was hoping for. The sink is a bundled worker that tracing.otlp points at, the native additions are generic exporter options any collector can use (exportLogs, protocol, sampleRatio, the standard OTEL_* variables), there are no new crates, and retention is left to the bucket's lifecycle rule.

A few things:

  1. Local dev with WORKERD_OTEL=1. Without a cluster, the generated workerd-telemetry-store bucket has no localDisk, so startup fails with "A bucket service requires Config.cluster, or localDisk…". telemetry.js only PUTs, and a writable disk creates parent directories on PUT, so a plain disk works as STORE. Without a cluster, could WORKERD_OTEL=1 bind STORE to a writable disk under the local state directory? The header would then say STORE is a bucket or a writable disk. That gives local dev the same files and the same DuckDB queries.
  2. OTEL_EXPORTER_OTLP_ENDPOINT is read by the server library. OtlpTracing::from_config calls std::env::var itself. So any embedder of the server, or a workerd test run, starts exporting whenever the variable is in its environment, and containers with a collector sidecar often set it. WORKERD_OTEL is handled in the CLI by rewriting the config. I'd handle the endpoint the same way, so the library is driven only by config. The endpoint's path prefix could become a TracingOptions field.
  3. Node identity. Spans carry no node attribute, and the files are no longer split by node, so in a cluster you can't tell which node a span came from. Setting the standard service.instance.id resource attribute to the node's ID would fix that for every collector.
  4. The extra ~185 MB of RSS. I'd want this tracked down before WORKERD_OTEL=1 is something we recommend. A guess: each POST holds up to 1 MiB of OTLP/JSON parsed into objects, plus the rows, the joined string, the gzip stream and the arrayBuffer copy, all at once, and up to 16 POSTs run concurrently. Building the NDJSON straight from the parsed request, and streaming the gzip into the PUT if the bucket service accepts a body of unknown length, would cut most of that.
  5. Tests. I agree with the bot on the two gaps. with_telemetry_environment's error and precedence branches can sit next to the shutdown-delay tests in cli/config-test.rs. A sampleRatio = 0 case would cover the threshold, the parent-based override, and logs still exporting from unsampled invocations.

Nits:

  • The cell column comes from cloudflare.durable_object.id. durable_object_id would be clearer to people querying it.
  • Requests still queued at shutdown are lost. With the 1 s linger that's small, but flushing the queue while draining would close it entirely. Fine as a follow-up.

Really nice turnaround 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants