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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/openshell-supervisor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ Console JSON is installed independently of optional file appenders and uses an I

## OTLP agent trace relay

The `otlp_relay` module forwards the workload's OTLP/HTTP protobuf trace exports to the collector named by `OPENSHELL_OTLP_AGENT_ENDPOINT`, over the transport named by `OPENSHELL_OTLP_AGENT_PROTOCOL` (`grpc` when unset, or `http/protobuf`). Each export carries the collector headers from the launch bundle's `agent_otlp_headers` and, for an `https` collector, verifies it and authenticates with `agent_otlp_tls`; the supervisor's own span and OCSF exporters use the `traces_` and `ocsf_` fields the same way. The gateway sets those variables only when `[openshell.gateway.otlp.agent]` is enabled, so trace export alone leaves the relay inactive. Metrics and logs exports to the relay are acknowledged and discarded. The workload exports to the reserved address `192.0.0.8:4318`; the sandbox broker stages that connection to the supervisor, and the network proxy hands the stream to the relay's HTTP/1.1 receiver through the generic reserved-destination hook instead of evaluating policy. The receiver replaces the `openshell.sandbox.id` and `openshell.telemetry.source=agent` resource attributes, pushes the re-encoded batch into a bounded buffer, and a single export task forwards the encoded batches to the collector with a lazy connection.
The `otlp_relay` module forwards the workload's OTLP/HTTP protobuf trace, log, and metrics exports to the collector named by `OPENSHELL_OTLP_AGENT_ENDPOINT`, over the transport named by `OPENSHELL_OTLP_AGENT_PROTOCOL` (`grpc` when unset, or `http/protobuf`). Each export carries the collector headers from the launch bundle's `agent_otlp_headers` and, for an `https` collector, verifies it and authenticates with `agent_otlp_tls`; the supervisor's own span and OCSF exporters use the `traces_` and `ocsf_` fields the same way. The gateway sets those variables only when `[openshell.gateway.otlp.agent]` is enabled, so trace export alone leaves the relay inactive. The workload exports to the reserved address `192.0.0.8:4318`; the sandbox broker stages that connection to the supervisor, and the network proxy hands the stream to the relay's HTTP/1.1 receiver through the generic reserved-destination hook instead of evaluating policy. The receiver replaces the `openshell.sandbox.id` and `openshell.telemetry.source=agent` resource attributes, pushes the re-encoded batch into the bounded buffer of its signal, and a single export task forwards the encoded batches to the collector with a lazy connection.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor: The limits paragraph of this README section (line 137) still says 32 buffered batches and about 67 MiB, but the relay now buffers up to 48 batches (about 100 MiB).

Why this matters: new_buffer (buffer.rs:77-87) creates a 32-slot trace queue plus two 8-slot queues, each slot holding up to MAX_ENRICHED_BYTES (about 2.08 MiB), and the doc comment on that constant (mod.rs:87-89) already says about 100 MiB. With all three queues full behind a slow collector, each sandbox supervisor pins about 33 MiB more than README.md:137 documents, so the stated total of roughly 115 MiB is really about 148 MiB. Anyone who sizes supervisor memory from this paragraph under-provisions.

Suggested fix: Update README.md:137 to 32 trace plus 8 logs plus 8 metrics batches and about 100 MiB of buffered batches.

Source: production agent (also flagged by: architecture agent, gator agent)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a561522.


Limits are fixed: 2 MiB per request body, at most 512 `ResourceSpans` entries, 256 KiB of encoded `Resource` fields, and 8192 resource attributes per request (each of these answers 413), a 10 second header-read timeout, 16 concurrent connections, 32 buffered batches, and a 5 second deadline per export attempt. Only the resources are decoded; spans are copied byte for byte, at most two requests at a time. Worst-case memory attributable to the agent is about 67 MiB of buffered batches, plus 32 MiB of bodies awaiting enrichment across the 16 connections, plus about 12 MiB for the two enrichments in progress, plus about 4 MiB for the batch being exported and its encoded copy. A full buffer answers 503 with `Retry-After`. Without an agent endpoint nothing starts and the proxy refuses the relay address. After the agent exits, `run_sandbox_with_backend` flushes buffered batches for up to 5 seconds before it reports the exit to the gateway, then logs a final summary of rejected and failed counts. Flushes skip the wait while the most recent export failed, and batches still pending when the relay is dropped without a flush count as failed. The supervisor tells the sandbox runtime through `AgentSpec::otlp_relay_active` whether the relay runs, and the runtime injects the generic `OTEL_EXPORTER_OTLP_*` defaults only then.

Expand Down
102 changes: 78 additions & 24 deletions crates/openshell-supervisor/src/otlp_relay/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Bounded buffer of enriched, encoded trace batches between the receiver
//! and the export task.
//! Bounded buffers of enriched, encoded batches between the receiver and the
//! export task, one per signal.
//!
//! Sending never blocks and never drops silently: a full buffer surfaces as
//! [`BufferFull`] so the receiver can answer 503 and the agent SDK retries.

use bytes::Bytes;
use tokio::sync::mpsc;

use super::Signal;

/// The buffer has no room for another batch.
#[derive(Debug, PartialEq, Eq)]
pub enum SendError {
Expand All @@ -34,62 +36,114 @@ impl std::error::Error for SendError {}
/// Not `Clone`: the receiver holds the only sender, so closing the buffer
/// at shutdown ends the export task's input.
pub struct BatchSender {
tx: mpsc::Sender<Bytes>,
queues: [mpsc::Sender<Bytes>; Signal::ALL.len()],
}

impl BatchSender {
/// Buffers `batch` without waiting.
pub fn try_send(&self, batch: Bytes) -> Result<(), SendError> {
self.tx.try_send(batch).map_err(|error| match error {
mpsc::error::TrySendError::Full(_) => SendError::BufferFull,
mpsc::error::TrySendError::Closed(_) => SendError::BufferClosed,
})
/// Buffers `batch` of `signal` without waiting.
pub fn try_send(&self, signal: Signal, batch: Bytes) -> Result<(), SendError> {
self.queues[signal.index()]
.try_send(batch)
.map_err(|error| match error {
mpsc::error::TrySendError::Full(_) => SendError::BufferFull,
mpsc::error::TrySendError::Closed(_) => SendError::BufferClosed,
})
}
}

/// Consumer side, held by the export task.
pub struct BatchReceiver {
rx: mpsc::Receiver<Bytes>,
queues: [mpsc::Receiver<Bytes>; Signal::ALL.len()],
}

impl BatchReceiver {
/// Next buffered batch in arrival order, or `None` once every sender has
/// been dropped and the buffer is drained.
pub async fn recv(&mut self) -> Option<Bytes> {
self.rx.recv().await
/// Next buffered batch, or `None` once every sender has been dropped and
/// the buffer is drained. Traces go before logs and logs before metrics
/// when several are waiting; arrival order holds within a signal.
pub async fn recv(&mut self) -> Option<(Signal, Bytes)> {
let [traces, logs, metrics] = &mut self.queues;
tokio::select! {
biased;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important: BatchReceiver::recv drains the three queues with a biased select in fixed order, so logs and metrics are exported only when the trace queue is empty at that moment. While traces arrive at least as fast as the collector completes exports, logs and metrics are starved completely.

Why this matters: The single export task (mod.rs:548) exports one batch per collector round trip. With a remote collector at about 200 ms per export (5 batches per second) and an agent that posts more than 5 trace batches per second (a per-span SimpleSpanProcessor, or several processes), traces.recv() is ready on every call and the logs and metrics branches are never taken. Their 8-slot queues fill, every later /v1/logs and /v1/metrics POST gets 503 (receiver.rs:325-329), the SDK retries and then drops the data, and at shutdown the 5 second flush bound is also spent on traces first. The comment at mod.rs:112-114 and the configuration docs say the separate buffers exist so that one signal cannot crowd out the others, which holds for admission but not for the drain order.

Suggested fix: Drain fairly: rotate the starting queue on each call (round robin), or drop biased; so tokio picks a random ready branch, and adjust the doc comment on ordering. If strict trace priority is intended, bound it (for example at most N consecutive trace batches while another queue is non-empty) and correct the 'cannot crowd out' statements.

Source: correctness agent (also flagged by: architecture agent, production agent, gator agent)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a561522: dropped biased, queues drain at random.

Some(batch) = traces.recv() => Some((Signal::Traces, batch)),
Some(batch) = logs.recv() => Some((Signal::Logs, batch)),
Some(batch) = metrics.recv() => Some((Signal::Metrics, batch)),
else => None,
}
}
}

/// Creates a buffer holding at most `capacity` batches.
/// Creates a buffer holding at most `capacity` trace batches and a quarter
/// of that, rounded up, for each of logs and metrics.
pub fn new_buffer(capacity: usize) -> (BatchSender, BatchReceiver) {
let (tx, rx) = mpsc::channel(capacity);
(BatchSender { tx }, BatchReceiver { rx })
let (senders, receivers): (Vec<_>, Vec<_>) = Signal::ALL
.map(|signal| {
let capacity = match signal {
Signal::Traces => capacity,
Signal::Logs | Signal::Metrics => capacity.div_ceil(4),
};
mpsc::channel(capacity)
})
.into_iter()
.unzip();
(
BatchSender {
queues: senders.try_into().expect("one queue per signal"),
},
BatchReceiver {
queues: receivers.try_into().expect("one queue per signal"),
},
)
}

#[cfg(test)]
mod tests {
use super::*;

const T: Signal = Signal::Traces;

#[tokio::test]
async fn capacity_is_honoured_and_full_is_reported() {
let (tx, mut rx) = new_buffer(32);
for i in 0..32u8 {
tx.try_send(Bytes::from(vec![i])).unwrap();
tx.try_send(T, Bytes::from(vec![i])).unwrap();
}
assert_eq!(
tx.try_send(Bytes::from_static(b"x")),
tx.try_send(T, Bytes::from_static(b"x")),
Err(SendError::BufferFull)
);
assert_eq!(rx.recv().await.unwrap(), Bytes::from(vec![0u8]));
tx.try_send(Bytes::from_static(b"x")).unwrap();
assert_eq!(rx.recv().await.unwrap(), (T, Bytes::from(vec![0u8])));
tx.try_send(T, Bytes::from_static(b"x")).unwrap();
}

#[tokio::test]
async fn a_full_signal_does_not_block_the_others() {
let (tx, mut rx) = new_buffer(32);
for _ in 0..8 {
tx.try_send(Signal::Logs, Bytes::from_static(b"l")).unwrap();
}
assert_eq!(
tx.try_send(Signal::Logs, Bytes::from_static(b"l")),
Err(SendError::BufferFull)
);
tx.try_send(Signal::Metrics, Bytes::from_static(b"m"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor: The metrics queue capacity is never asserted: a_full_signal_does_not_block_the_others fills only the logs queue and sends a single metrics batch.

Why this matters: new_buffer (buffer.rs:80-83) sizes logs and metrics in one match arm, but this test (buffer.rs:119-133) checks the bound for logs only, and the relay-level flood test buffer_never_exceeds_capacity_under_flood (mod.rs:1515) posts traces only. Judged by inspection and not executed: splitting the arm so that Signal::Metrics => capacity (or any larger value) would not be caught by any existing test, while an agent could then keep 32 instead of 8 metrics batches of about 2 MiB each in supervisor memory. That bound is documented (configuration.mdx: logs and metrics buffer 8 each) and is part of the memory estimate for agent-controlled input in mod.rs:87-96.

Suggested fix: In the buffer test, fill the metrics queue to 8 as well and assert that the ninth send returns BufferFull; optionally flood each signal at relay level and assert 32, 8 and 8 accepted.

Source: test-quality agent

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a561522.

.unwrap();
tx.try_send(T, Bytes::from_static(b"t")).unwrap();
assert_eq!(rx.recv().await.unwrap().0, T);
assert_eq!(rx.recv().await.unwrap().0, Signal::Logs);
}

#[tokio::test]
async fn recv_returns_none_after_the_sender_drops() {
let (tx, mut rx) = new_buffer(4);
tx.try_send(Bytes::from_static(b"a")).unwrap();
tx.try_send(T, Bytes::from_static(b"a")).unwrap();
tx.try_send(Signal::Metrics, Bytes::from_static(b"b"))
.unwrap();
drop(tx);
assert_eq!(rx.recv().await.unwrap(), Bytes::from_static(b"a"));
assert_eq!(rx.recv().await.unwrap(), (T, Bytes::from_static(b"a")));
assert_eq!(
rx.recv().await.unwrap(),
(Signal::Metrics, Bytes::from_static(b"b"))
);
assert!(rx.recv().await.is_none());
}

Expand All @@ -98,7 +152,7 @@ mod tests {
let (tx, rx) = new_buffer(4);
drop(rx);
assert_eq!(
tx.try_send(Bytes::from_static(b"a")),
tx.try_send(T, Bytes::from_static(b"a")),
Err(SendError::BufferClosed)
);
}
Expand Down
51 changes: 49 additions & 2 deletions crates/openshell-supervisor/src/otlp_relay/enrichment.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Resource attribution for relayed agent traces.
//! Resource attribution for relayed agent traces, logs, and metrics.
//!
//! The three export requests share one wire layout for this purpose: the
//! repeated `ResourceSpans`, `ResourceLogs`, or `ResourceMetrics` entries are
//! field 1 of the request and each carries its `Resource` in field 1, so the
//! walk below serves every signal. Names in this module follow the trace
//! schema.
//!
//! Every forwarded `ResourceSpans` entry carries exactly two supervisor-owned
//! resource attributes. Agent-supplied values for those keys are always
Expand Down Expand Up @@ -113,7 +119,7 @@ pub enum EnrichError {
impl std::fmt::Display for EnrichError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Malformed(error) => write!(f, "malformed ExportTraceServiceRequest: {error}"),
Self::Malformed(error) => write!(f, "malformed OTLP export request: {error}"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor: The EnrichError Display impl was generalized only for Malformed; the other client-visible messages still name resource_spans, so logs and metrics exporters get an error about a field their request does not have.

Why this matters: receiver.rs:287-296 puts the Display text into the google.rpc.Status body, so a POST /v1/logs with 513 ResourceLogs entries returns HTTP 413 'more than 512 resource_spans entries' (enrichment.rs:124), and a field 1 that is not length-delimited on /v1/metrics yields 'malformed OTLP export request: resource_spans is not length-delimited' (line 177). Trace-schema names are fine for internal identifiers, but these strings leave the module, and configuration.mdx:1124 promises that the message states the reason.

Suggested fix: Use signal-neutral wording such as 'more than 512 resource entries' and 'resource entry is not length-delimited', or pass the Signal into enrich and name the matching field.

Source: architecture agent

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a561522.

Self::TooManyResourceSpans => {
write!(f, "more than {MAX_RESOURCE_SPANS} resource_spans entries")
}
Expand Down Expand Up @@ -396,12 +402,53 @@ fn string_attribute(key: &str, value: &str) -> KeyValue {

#[cfg(test)]
pub mod test_util {
use openshell_otel_test_support::relay::string_attribute;
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value};
use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics;
use opentelemetry_proto::tonic::resource::v1::Resource;
use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span};
use prost::Message;

/// A logs and a metrics export, each with one resource that spoofs the
/// sandbox id. The log record's body is `agent-log`.
pub fn logs_and_metrics_requests() -> (ExportLogsServiceRequest, ExportMetricsServiceRequest) {
let resource = || {
Some(Resource {
attributes: vec![
string_attribute("service.name", "unit-agent"),
string_attribute(super::SANDBOX_ID_KEY, "evil"),
],
..Default::default()
})
};
let logs = ExportLogsServiceRequest {
resource_logs: vec![ResourceLogs {
resource: resource(),
scope_logs: vec![ScopeLogs {
log_records: vec![LogRecord {
body: Some(AnyValue {
value: Some(any_value::Value::StringValue("agent-log".into())),
}),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
};
let metrics = ExportMetricsServiceRequest {
resource_metrics: vec![ResourceMetrics {
resource: resource(),
..Default::default()
}],
};
(logs, metrics)
}

/// Builds a protobuf-encoded request with one span named `span_name` and
/// the given string resource attributes.
pub fn encoded_request(span_name: &str, attributes: &[(&str, &str)]) -> Vec<u8> {
Expand Down
Loading