Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(error-tracking): add cymbal accepted routing (#61185)

Hugues Pouillota818a49f81bb
diff --git a/proto/cymbal/resolution/v1/resolution.proto b/proto/cymbal/resolution/v1/resolution.proto
index 1009a5bf0ec7..4c35321edafb 100644
--- a/proto/cymbal/resolution/v1/resolution.proto
+++ b/proto/cymbal/resolution/v1/resolution.proto
@@ -36,7 +36,8 @@ message ResolveItem {
uint32 deadline_ms = 5;
}
-// ResolveOutcome is the terminal server outcome for one ResolveItem id.
+// ResolveOutcome is a server outcome for one ResolveItem id. Accepted is an
+// admission signal; Done, Error, and Retry are terminal outcomes.
message ResolveOutcome {
uint64 id = 1;
@@ -44,9 +45,15 @@ message ResolveOutcome {
Done done = 2;
Error error = 3;
Retry retry = 4;
+ Accepted accepted = 5;
}
}
+// Accepted means the pod admitted the item and will process it. It is emitted
+// before the terminal outcome so callers can distinguish routing acceptance
+// from full resolution completion.
+message Accepted {}
+
// Done means the item completed and contains the resolved exception payload.
message Done {
// Serialized rust/cymbal Exception after frame resolution and exception
diff --git a/rust/cymbal-proto/tests/contract.rs b/rust/cymbal-proto/tests/contract.rs
index 3f0264082363..a62fd1c2ac45 100644
--- a/rust/cymbal-proto/tests/contract.rs
+++ b/rust/cymbal-proto/tests/contract.rs
@@ -1,6 +1,6 @@
use cymbal_proto::cymbal::resolution::v1::{
- resolve_outcome, Done, Error, ErrorKind, LoadEvent, ResolveItem, ResolveOutcome, Retry,
- SubscribeRequest,
+ resolve_outcome, Accepted, Done, Error, ErrorKind, LoadEvent, ResolveItem, ResolveOutcome,
+ Retry, SubscribeRequest,
};
use prost::Message;
@@ -50,6 +50,10 @@ fn resolve_outcome_echoes_id_and_carries_done_error_or_retry() {
},
ResolveOutcome {
id: 4,
+ result: Some(resolve_outcome::Result::Accepted(Accepted {})),
+ },
+ ResolveOutcome {
+ id: 5,
result: Some(resolve_outcome::Result::Error(Error {
kind: ErrorKind::Overloaded as i32,
message: "server overloaded".to_string(),
@@ -80,6 +84,10 @@ fn resolve_outcome_echoes_id_and_carries_done_error_or_retry() {
));
assert!(matches!(
decoded[3].result,
+ Some(resolve_outcome::Result::Accepted(_))
+ ));
+ assert!(matches!(
+ decoded[4].result,
Some(resolve_outcome::Result::Error(Error {
kind,
..
@@ -87,7 +95,7 @@ fn resolve_outcome_echoes_id_and_carries_done_error_or_retry() {
));
assert_eq!(
decoded.iter().map(|outcome| outcome.id).collect::<Vec<_>>(),
- vec![1, 2, 3, 4]
+ vec![1, 2, 3, 4, 5]
);
}
diff --git a/rust/cymbal-resolution/README.md b/rust/cymbal-resolution/README.md
index ff80276e68e8..8c3c9436a52d 100644
--- a/rust/cymbal-resolution/README.md
+++ b/rust/cymbal-resolution/README.md
@@ -44,7 +44,7 @@ events ──HTTP─────▶│ cymbal
The contract is intentionally split across two streams:
-- **`Resolve`** is bidirectional work traffic. The caller sends independent `ResolveItem`s, each with a per-stream id, `team_id`, serialized exception JSON, JSON `metadata` bytes, and an item deadline. The server emits exactly one terminal `ResolveOutcome` with the same id: `Done`, `Retry`, or `Error`.
+- **`Resolve`** is bidirectional work traffic. The caller sends independent `ResolveItem`s, each with a per-stream id, `team_id`, serialized exception JSON, JSON `metadata` bytes, and an item deadline. The server emits an `Accepted` outcome when it admits an item, then exactly one terminal `ResolveOutcome` with the same id: `Done`, `Retry`, or `Error`.
- **`Subscribe`** is endpoint freshness and draining state. The cymbal-side `EndpointPool` opens one long-lived stream per pod and treats the latest `LoadEvent` as a freshness snapshot. `LoadEvent` does not carry overload state or suggested batch sizing.
`Error.kind` is the shared control-flow surface:
@@ -84,7 +84,7 @@ Remote resolution is opt-in on the cymbal side. There is intentionally **no sile
Routing is per team. The caller's `EndpointPool` rendezvous-hashes `team:{team_id}` against the pod set so every exception from a given team prefers a single pod, maximizing warm-cache locality without coupling the caller to symbol-set internals.
-Each endpoint owns one bidirectional Resolve mux with a bounded outbound queue and one waiter per in-flight item. Queue admission failure, stream break, endpoint drain, and endpoint eviction all fail affected items as `ERROR_KIND_OVERLOADED`; the per-item retry layer excludes that endpoint and reroutes only those items. A `Retry` outcome uses the generic retry policy. Terminal `ErrorKind`s fail the current all-or-nothing rollout path.
+Each endpoint owns one bidirectional Resolve mux with a bounded outbound queue and one waiter per in-flight item. Queue admission failure, stream break, endpoint drain, and endpoint eviction all fail affected items as `ERROR_KIND_OVERLOADED`; the per-item retry layer excludes that endpoint and reroutes only those items. A `Retry` outcome uses the generic retry policy. Cymbal also holds a process-local routing semaphore for items trying to find an accepting pod; a permit is acquired before routing, released on `Accepted`, and otherwise held until routing exhausts or fails terminally. Terminal `ErrorKind`s fail the current all-or-nothing rollout path.
### Disabling / rolling back
@@ -115,6 +115,7 @@ All variables are prefixed `CYMBAL_REMOTE_RESOLUTION_` and live on `cymbal::conf
| `CYMBAL_REMOTE_RESOLUTION_RETRY_BACKOFF_MS` | `50` | Base retry backoff before jitter. |
| `CYMBAL_REMOTE_RESOLUTION_RETRY_MAX_BACKOFF_MS` | `1000` | Maximum retry backoff after exponential scaling and jitter. |
| `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE` | `0.0` | Deterministic event-level remote rollout rate. |
+| `CYMBAL_REMOTE_RESOLUTION_ROUTING_ACCEPTANCE_CONCURRENCY` | `10` | Maximum number of items per cymbal process that can wait concurrently for a pod to emit `Accepted`. |
| `CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_TICK_HINT_MS` | `1000` | Cadence hint sent on `SubscribeRequest`; snapshots are considered fresh for two ticks. |
| `CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_RECONNECT_BACKOFF_MS` | `500` | Backoff between subscription reconnect attempts when a stream terminates. |
diff --git a/rust/cymbal-resolution/src/service/resolve.rs b/rust/cymbal-resolution/src/service/resolve.rs
index febf4358aba4..88771090f61b 100644
--- a/rust/cymbal-resolution/src/service/resolve.rs
+++ b/rust/cymbal-resolution/src/service/resolve.rs
@@ -11,7 +11,7 @@ use cymbal::stages::resolution::frame::FrameResolver;
use cymbal::stages::resolution::ResolutionStage;
use cymbal::types::Exception;
use cymbal_proto::cymbal::resolution::v1::{
- resolve_outcome, Done, Error as ItemError, ResolveItem, ResolveOutcome,
+ resolve_outcome, Accepted, Done, Error as ItemError, ResolveItem, ResolveOutcome,
};
use super::codes;
@@ -71,6 +71,11 @@ pub(super) async fn run_resolve(
let item_tx = tx.clone();
let item_stage = stage.clone();
+ if !send_accepted(&tx, item.id).await {
+ load_monitor.decrement_in_flight();
+ record_resolve_duration(started_at, "cancelled");
+ return;
+ }
let in_flight_guard = InFlightGuard::new(load_monitor.clone());
tokio::spawn(async move {
let processed = process_item(item_stage, item, in_flight_guard).await;
@@ -86,6 +91,15 @@ pub(super) async fn run_resolve(
record_resolve_duration(started_at, "completed");
}
+async fn send_accepted(tx: &mpsc::Sender<Result<ResolveOutcome, Status>>, id: u64) -> bool {
+ tx.send(Ok(ResolveOutcome {
+ id,
+ result: Some(resolve_outcome::Result::Accepted(Accepted {})),
+ }))
+ .await
+ .is_ok()
+}
+
async fn send_overloaded(
tx: &mpsc::Sender<Result<ResolveOutcome, Status>>,
id: u64,
diff --git a/rust/cymbal-resolution/tests/service_tests.rs b/rust/cymbal-resolution/tests/service_tests.rs
index 8e20f91a6c2b..66319c75f194 100644
--- a/rust/cymbal-resolution/tests/service_tests.rs
+++ b/rust/cymbal-resolution/tests/service_tests.rs
@@ -183,6 +183,22 @@ async fn spawn_test_channel(service: CymbalResolutionService) -> Channel {
async fn resolve_items(
service: CymbalResolutionService,
items: Vec<ResolveItem>,
+) -> Vec<ResolveOutcome> {
+ resolve_items_with_accepted(service, items)
+ .await
+ .into_iter()
+ .filter(|outcome| {
+ !matches!(
+ outcome_result(outcome),
+ resolve_outcome::Result::Accepted(_)
+ )
+ })
+ .collect()
+}
+
+async fn resolve_items_with_accepted(
+ service: CymbalResolutionService,
+ items: Vec<ResolveItem>,
) -> Vec<ResolveOutcome> {
let channel = spawn_test_channel(service).await;
let mut client = CymbalResolutionClient::new(channel);
@@ -274,6 +290,26 @@ async fn bidi_resolve_stream_resolves_multiple_items_and_echoes_ids() {
}
}
+#[tokio::test]
+async fn admitted_items_emit_accepted_before_terminal_outcome() {
+ let service = make_service(FakeResolver::default());
+ let exc = raw_exception("RuntimeError");
+
+ let outcomes = resolve_items_with_accepted(service, vec![make_item(41, &exc)]).await;
+
+ assert_eq!(outcomes.len(), 2);
+ assert_eq!(outcomes[0].id, 41);
+ assert!(matches!(
+ outcome_result(&outcomes[0]),
+ resolve_outcome::Result::Accepted(_)
+ ));
+ assert_eq!(outcomes[1].id, 41);
+ assert!(matches!(
+ outcome_result(&outcomes[1]),
+ resolve_outcome::Result::Done(_)
+ ));
+}
+
#[tokio::test]
async fn raw_frames_are_resolved_into_done_payload() {
let raw_frame = sample_raw_frame();
diff --git a/rust/cymbal/README.md b/rust/cymbal/README.md
index 5fa901e6d05c..5b91f85e3b0d 100644
--- a/rust/cymbal/README.md
+++ b/rust/cymbal/README.md
@@ -32,7 +32,10 @@ resolvers and then rejoin the same properties/grouping/linking pipeline.
Backpressure is result-only on the `Resolve` stream: overload is surfaced as
`ResolveOutcome.Error { kind: ERROR_KIND_OVERLOADED }`, which the cymbal client
-reroutes with overload-specific backoff. When
+reroutes with overload-specific backoff. Pods emit `ResolveOutcome.Accepted`
+after they admit an item; cymbal limits concurrent unaccepted routing attempts
+with a process-local semaphore and releases the permit when acceptance arrives.
+When
`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS` is non-zero, the overloaded
endpoint is also excluded from new routing in that cymbal process. Repeated
overloads double the endpoint cooldown up to
diff --git a/rust/cymbal/docs/compatibility.md b/rust/cymbal/docs/compatibility.md
index dede87a02066..13301ae48748 100644
--- a/rust/cymbal/docs/compatibility.md
+++ b/rust/cymbal/docs/compatibility.md
@@ -29,6 +29,6 @@ No generated type changes are needed:
- Unsampled events use the local exception and frame resolvers.
- Sampled remote exceptions are grouped per team, flattened into `ResolveItem`s, and submitted over per-endpoint bidirectional `Resolve` streams.
- Resolver-specific context is carried in `ResolveItem.metadata` as JSON bytes. The current Apple symbolication convention uses an `apple_debug_images_json` key.
-- Per-item `ResolveOutcome.Error.kind` is the control-flow surface. `ERROR_KIND_OVERLOADED` is result-only backpressure and triggers item reroute. If `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS` is non-zero, the overloaded endpoint is also temporarily excluded from new routing in that cymbal process. Repeated overloads double that cooldown up to `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS`, and a quiet `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER` controls how much routing flattens across the rendezvous-ranked candidate list (`0.0` strict rank-0 sticky, `1.0` uniform across candidates). `LoadEvent` is only endpoint freshness/draining state.
+- Per-item `ResolveOutcome.Error.kind` is the control-flow surface. `ERROR_KIND_OVERLOADED` is result-only backpressure and triggers item reroute. Accepted items emit `ResolveOutcome.Accepted` before their terminal outcome; cymbal releases its routing permit on that acceptance signal. If `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS` is non-zero, the overloaded endpoint is also temporarily excluded from new routing in that cymbal process. Repeated overloads double that cooldown up to `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS`, and a quiet `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER` controls how much routing flattens across the rendezvous-ranked candidate list (`0.0` strict rank-0 sticky, `1.0` uniform across candidates). `LoadEvent` is only endpoint freshness/draining state.
This means Node request chunking limits protect cymbal's public HTTP body size, while cymbal's private gRPC path owns exception-level routing, reroute depth, and overload handling.
diff --git a/rust/cymbal/src/app_context.rs b/rust/cymbal/src/app_context.rs
index cc55fc33ee57..0a0d6cd2d5d5 100644
--- a/rust/cymbal/src/app_context.rs
+++ b/rust/cymbal/src/app_context.rs
@@ -327,10 +327,7 @@ async fn build_remote_resolution(
let refresh_task = crate::stages::resolution::remote::pool::spawn_refresh_task(pool.clone());
Ok((
- Some(RemoteResolutionContext {
- pool,
- config: remote_config,
- }),
+ Some(RemoteResolutionContext::new(pool, remote_config)),
Some(refresh_task),
))
}
diff --git a/rust/cymbal/src/config.rs b/rust/cymbal/src/config.rs
index b88ade47073b..65cece5191b0 100644
--- a/rust/cymbal/src/config.rs
+++ b/rust/cymbal/src/config.rs
@@ -275,6 +275,14 @@ pub struct Config {
#[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER", default = "0.0")]
pub remote_resolution_routing_jitter: f64,
+ /// Maximum number of remote resolution items that can concurrently wait
+ /// for a pod to accept routing ownership.
+ #[envconfig(
+ from = "CYMBAL_REMOTE_RESOLUTION_ROUTING_ACCEPTANCE_CONCURRENCY",
+ default = "10"
+ )]
+ pub remote_resolution_routing_acceptance_concurrency: usize,
+
/// Tick cadence hint sent on `SubscribeRequest.tick_hint_ms` to the
/// cymbal-resolution freshness/draining stream. The server clamps to its own bounds
/// (see cymbal-resolution `SUBSCRIBE_MIN_TICK_MS`/`SUBSCRIBE_MAX_TICK_MS`),
diff --git a/rust/cymbal/src/stages/resolution/remote/config.rs b/rust/cymbal/src/stages/resolution/remote/config.rs
index 97fb6b2f0430..464cc766e5ff 100644
--- a/rust/cymbal/src/stages/resolution/remote/config.rs
+++ b/rust/cymbal/src/stages/resolution/remote/config.rs
@@ -34,6 +34,9 @@ pub struct RemoteResolutionConfig {
/// Rank-distribution factor for selecting among rendezvous-ranked candidates.
/// `0.0` is fully sticky to rank 0; `1.0` is uniform across candidates.
pub routing_jitter: f64,
+ /// Maximum number of items that can concurrently wait for a pod to accept
+ /// routing ownership.
+ pub routing_acceptance_concurrency: usize,
/// Cadence hint sent on `SubscribeRequest.tick_hint_ms`. The server may
/// clamp this; the caller relies on whatever cadence the server settles on.
/// Doubles as the freshness window: snapshots older than `2 *
@@ -88,6 +91,9 @@ impl RemoteResolutionConfig {
),
sample_rate: normalized_probability(config.remote_resolution_sample_rate),
routing_jitter: normalized_probability(config.remote_resolution_routing_jitter),
+ routing_acceptance_concurrency: config
+ .remote_resolution_routing_acceptance_concurrency
+ .max(1),
subscribe_tick_hint: Duration::from_millis(
config.remote_resolution_subscribe_tick_hint_ms.max(1),
),
diff --git a/rust/cymbal/src/stages/resolution/remote/mux.rs b/rust/cymbal/src/stages/resolution/remote/mux.rs
index 6f278e40e3db..6c783c36fca6 100644
--- a/rust/cymbal/src/stages/resolution/remote/mux.rs
+++ b/rust/cymbal/src/stages/resolution/remote/mux.rs
@@ -9,16 +9,15 @@ use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
+#[cfg(test)]
use std::time::Duration;
use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_client::CymbalResolutionClient;
use cymbal_proto::cymbal::resolution::v1::{
resolve_outcome, Error, ErrorKind, ResolveItem, ResolveOutcome,
};
-use futures::future::join_all;
use futures::StreamExt;
-use thiserror::Error;
-use tokio::sync::{mpsc, oneshot};
+use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_stream::wrappers::ReceiverStream;
use tonic::transport::Channel;
@@ -47,7 +46,13 @@ struct ResolveMuxInner {
struct Waiter {
caller_id: u64,
- tx: oneshot::Sender<Result<ResolveOutcome, MuxItemError>>,
+ tx: mpsc::Sender<Result<ResolveOutcome, RemoteCallError>>,
+}
+
+pub(super) struct ResolveItemSession {
+ pub(super) outcomes: mpsc::Receiver<Result<ResolveOutcome, RemoteCallError>>,
+ inner: Option<Arc<ResolveMuxInner>>,
+ stream_id: u64,
}
#[derive(Debug, Clone)]
@@ -89,31 +94,27 @@ impl StreamFailure {
}
}
-#[derive(Debug, Error)]
-enum MuxItemError {
- #[error("remote resolution stream queue is full")]
- QueueFull { caller_id: u64 },
- #[error("remote resolution stream is closed")]
- Closed { caller_id: u64 },
- #[error("remote resolution stream failed: {failure:?}")]
- StreamFailed {
- caller_id: u64,
- failure: StreamFailure,
- },
- #[error("remote resolution waiter was dropped")]
- WaiterDropped { caller_id: u64 },
- #[error("remote resolution item deadline exceeded after {deadline:?}")]
- Deadline { deadline: Duration },
-}
+impl ResolveItemSession {
+ pub(super) fn cancel(&self) {
+ if let Some(inner) = &self.inner {
+ inner.remove_waiter(self.stream_id);
+ }
+ }
-impl MuxItemError {
- fn caller_id(&self) -> Option<u64> {
- match self {
- MuxItemError::QueueFull { caller_id }
- | MuxItemError::Closed { caller_id }
- | MuxItemError::StreamFailed { caller_id, .. }
- | MuxItemError::WaiterDropped { caller_id } => Some(*caller_id),
- MuxItemError::Deadline { .. } => None,
+ #[cfg(test)]
+ async fn wait_terminal(
+ mut self,
+ deadline: Duration,
+ ) -> Result<ResolveOutcome, RemoteCallError> {
+ match tokio::time::timeout(deadline, self.outcomes.recv()).await {
+ Ok(Some(result)) => result,
+ Ok(None) => Err(RemoteCallError::Retryable(Status::unavailable(
+ "remote resolution session was dropped",
+ ))),
+ Err(_) => {
+ self.cancel();
+ Err(RemoteCallError::Deadline(deadline))
+ }
}
}
}
@@ -142,40 +143,48 @@ impl ResolveMux {
Self { inner }
}
- /// Submit a group of logical items through this endpoint stream.
- ///
- /// Local admission failures and stream breaks become synthetic overloaded
- /// item outcomes so the existing retry layer reroutes them through the same
- /// overload path as server-side `ERROR_KIND_OVERLOADED` responses. A local
- /// deadline still returns a retryable call error because the caller should
- /// retry the whole logical chunk with its remaining retry budget.
- pub async fn resolve_many(
- &self,
- items: Vec<ResolveItem>,
- deadline: Duration,
- ) -> Result<Vec<ResolveOutcome>, RemoteCallError> {
- let results = join_all(items.into_iter().map(|item| self.submit(item, deadline))).await;
- let mut outcomes = Vec::with_capacity(results.len());
- for result in results {
- match result {
- Ok(outcome) => outcomes.push(outcome),
- Err(MuxItemError::Deadline { deadline }) => {
- return Err(RemoteCallError::Deadline(deadline));
- }
- Err(MuxItemError::StreamFailed { failure, .. }) if !failure.retryable => {
- return Err(failure.to_remote_error());
+ pub(super) fn submit_session(&self, mut item: ResolveItem) -> ResolveItemSession {
+ let caller_id = item.id;
+ if self.is_closed() {
+ self.inner.record_admission_rejection("closed");
+ return immediate_session(overloaded_outcome(
+ caller_id,
+ "remote resolution stream is closed".to_string(),
+ ));
+ }
+
+ let stream_id = self.inner.next_stream_id();
+ item.id = stream_id;
+ let (tx, rx) = mpsc::channel(2);
+ {
+ let mut waiters = self.inner.waiters.lock().expect("waiter map poisoned");
+ waiters.insert(stream_id, Waiter { caller_id, tx });
+ self.inner.record_waiter_count(waiters.len());
+ }
+
+ if let Err(err) = self.inner.outbound.try_send(item) {
+ self.inner.remove_waiter(stream_id);
+ let (reason, message) = match err {
+ mpsc::error::TrySendError::Full(_) => {
+ self.inner.record_admission_rejection("queue_full");
+ ("queue_full", "remote resolution stream queue is full")
}
- Err(err) => {
- let Some(caller_id) = err.caller_id() else {
- return Err(RemoteCallError::Retryable(Status::unavailable(
- err.to_string(),
- )));
- };
- outcomes.push(overloaded_outcome(caller_id, err.to_string()));
+ mpsc::error::TrySendError::Closed(_) => {
+ self.inner.record_admission_rejection("closed");
+ ("closed", "remote resolution stream is closed")
}
- }
+ };
+ return immediate_session(overloaded_outcome(
+ caller_id,
+ format!("{message} ({reason})"),
+ ));
+ }
+
+ ResolveItemSession {
+ outcomes: rx,
+ inner: Some(self.inner.clone()),
+ stream_id,
}
- Ok(outcomes)
}
pub fn close(&self) {
@@ -202,50 +211,6 @@ impl ResolveMux {
self.inner.closed.load(Ordering::Acquire)
}
- async fn submit(
- &self,
- mut item: ResolveItem,
- deadline: Duration,
- ) -> Result<ResolveOutcome, MuxItemError> {
- let caller_id = item.id;
- if self.is_closed() {
- self.inner.record_admission_rejection("closed");
- return Err(MuxItemError::Closed { caller_id });
- }
-
- let stream_id = self.inner.next_stream_id();
- item.id = stream_id;
- let (tx, rx) = oneshot::channel();
- {
- let mut waiters = self.inner.waiters.lock().expect("waiter map poisoned");
- waiters.insert(stream_id, Waiter { caller_id, tx });
- self.inner.record_waiter_count(waiters.len());
- }
-
- if let Err(err) = self.inner.outbound.try_send(item) {
- self.inner.remove_waiter(stream_id);
- return match err {
- mpsc::error::TrySendError::Full(_) => {
- self.inner.record_admission_rejection("queue_full");
- Err(MuxItemError::QueueFull { caller_id })
- }
- mpsc::error::TrySendError::Closed(_) => {
- self.inner.record_admission_rejection("closed");
- Err(MuxItemError::Closed { caller_id })
- }
- };
- }
-
- match tokio::time::timeout(deadline, rx).await {
- Ok(Ok(result)) => result,
- Ok(Err(_)) => Err(MuxItemError::WaiterDropped { caller_id }),
- Err(_) => {
- self.inner.remove_waiter(stream_id);
- Err(MuxItemError::Deadline { deadline })
- }
- }
- }
-
#[cfg(test)]
fn waiter_count(&self) -> usize {
self.inner
@@ -270,10 +235,20 @@ impl ResolveMuxInner {
}
fn complete(&self, mut outcome: ResolveOutcome) {
+ let is_terminal = !matches!(outcome.result, Some(resolve_outcome::Result::Accepted(_)));
let waiter = {
let mut waiters = self.waiters.lock().expect("waiter map poisoned");
- let waiter = waiters.remove(&outcome.id);
- self.record_waiter_count(waiters.len());
+ let waiter = if is_terminal {
+ waiters.remove(&outcome.id)
+ } else {
+ waiters.get(&outcome.id).map(|waiter| Waiter {
+ caller_id: waiter.caller_id,
+ tx: waiter.tx.clone(),
+ })
+ };
+ if is_terminal {
+ self.record_waiter_count(waiters.len());
+ }
waiter
};
let Some(waiter) = waiter else {
@@ -285,7 +260,7 @@ impl ResolveMuxInner {
return;
};
outcome.id = waiter.caller_id;
- drop(waiter.tx.send(Ok(outcome)));
+ drop(waiter.tx.try_send(Ok(outcome)));
}
fn fail_all(&self, failure: StreamFailure) {
@@ -296,10 +271,15 @@ impl ResolveMuxInner {
drained
};
for waiter in waiters {
- drop(waiter.tx.send(Err(MuxItemError::StreamFailed {
- caller_id: waiter.caller_id,
- failure: failure.clone(),
- })));
+ let result = if failure.retryable {
+ Ok(overloaded_outcome(
+ waiter.caller_id,
+ failure.message.clone(),
+ ))
+ } else {
+ Err(failure.to_remote_error())
+ };
+ drop(waiter.tx.try_send(result));
}
}
@@ -321,6 +301,16 @@ impl ResolveMuxInner {
}
}
+fn immediate_session(outcome: ResolveOutcome) -> ResolveItemSession {
+ let (tx, rx) = mpsc::channel(1);
+ drop(tx.try_send(Ok(outcome)));
+ ResolveItemSession {
+ outcomes: rx,
+ inner: None,
+ stream_id: 0,
+ }
+}
+
async fn run_stream(
inner: Arc<ResolveMuxInner>,
channel: Channel,
@@ -490,10 +480,14 @@ mod tests {
let (addr, channel) = spawn_test_channel(service).await;
let mux = ResolveMux::new(addr, channel, "test-secret".to_string(), 8);
- let outcomes = mux
- .resolve_many(vec![item(101), item(102)], Duration::from_secs(1))
- .await
- .expect("resolve through mux");
+ let outcomes = futures::future::join_all([item(101), item(102)].into_iter().map(|item| {
+ mux.submit_session(item)
+ .wait_terminal(Duration::from_secs(1))
+ }))
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()
+ .expect("resolve through mux");
assert_eq!(
outcomes
.iter()
@@ -502,10 +496,11 @@ mod tests {
vec![101, 102]
);
- let outcomes = mux
- .resolve_many(vec![item(103)], Duration::from_secs(1))
+ let outcomes = [mux
+ .submit_session(item(103))
+ .wait_terminal(Duration::from_secs(1))
.await
- .expect("resolve through existing mux");
+ .expect("resolve through existing mux")];
assert_eq!(outcomes[0].id, 103);
assert_eq!(stream_count.load(Ordering::Acquire), 1);
@@ -523,10 +518,11 @@ mod tests {
let mux = ResolveMux::new(addr, channel, "test-secret".to_string(), 1);
mux.close();
- let outcomes = mux
- .resolve_many(vec![item(7)], Duration::from_secs(1))
+ let outcomes = [mux
+ .submit_session(item(7))
+ .wait_terminal(Duration::from_secs(1))
.await
- .expect("closed mux maps to overloaded item outcome");
+ .expect("closed mux maps to overloaded item outcome")];
assert_eq!(outcomes[0].id, 7);
assert!(matches!(
outcomes[0].result,
diff --git a/rust/cymbal/src/stages/resolution/remote/pool.rs b/rust/cymbal/src/stages/resolution/remote/pool.rs
index 71dfcc4c08c9..253c9f41d8d5 100644
--- a/rust/cymbal/src/stages/resolution/remote/pool.rs
+++ b/rust/cymbal/src/stages/resolution/remote/pool.rs
@@ -894,6 +894,7 @@ mod test {
retry_max_backoff: Duration::from_millis(2),
sample_rate: 1.0,
routing_jitter: 0.0,
+ routing_acceptance_concurrency: 10,
overload_ejection_initial: Duration::ZERO,
overload_ejection_max: Duration::ZERO,
overload_ejection_decay: Duration::from_secs(30),
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver.rs b/rust/cymbal/src/stages/resolution/remote/resolver.rs
index 5e12f62643b3..6d67b477cf04 100644
--- a/rust/cymbal/src/stages/resolution/remote/resolver.rs
+++ b/rust/cymbal/src/stages/resolution/remote/resolver.rs
@@ -3,6 +3,7 @@ use std::time::{Duration, Instant};
use cymbal_proto::cymbal::resolution::v1::ResolveItem;
use futures::future::join_all;
+use tokio::sync::Semaphore;
use crate::{
error::UnhandledError,
@@ -32,6 +33,18 @@ use retry::resolve_work_item;
pub struct RemoteResolutionContext {
pub pool: Arc<EndpointPool>,
pub config: RemoteResolutionConfig,
+ pub routing_semaphore: Arc<Semaphore>,
+}
+
+impl RemoteResolutionContext {
+ pub fn new(pool: Arc<EndpointPool>, config: RemoteResolutionConfig) -> Self {
+ let routing_acceptance_concurrency = config.routing_acceptance_concurrency;
+ Self {
+ pool,
+ config,
+ routing_semaphore: Arc::new(Semaphore::new(routing_acceptance_concurrency)),
+ }
+ }
}
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs
index 881a46b46fa9..3675d3f98d2d 100644
--- a/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs
+++ b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs
@@ -6,9 +6,11 @@ use std::net::SocketAddr;
use std::time::{Duration, Instant};
use rand::Rng;
+use tokio::sync::OwnedSemaphorePermit;
use tracing::warn;
use cymbal_proto::cymbal::resolution::v1::{resolve_outcome, ErrorKind, ResolveOutcome};
+use tonic::Status;
use crate::error::UnhandledError;
use crate::metric_consts::{
@@ -18,6 +20,8 @@ use crate::metric_consts::{
};
use crate::types::Exception;
+use crate::stages::resolution::remote::{client::RemoteCallError, mux::ResolveItemSession};
+
use super::{RemoteResolutionContext, RemoteWorkItem, ResolvedRemoteItem};
pub(super) async fn resolve_work_item(
@@ -29,9 +33,13 @@ pub(super) async fn resolve_work_item(
let mut excluded_endpoints: Vec<SocketAddr> = Vec::new();
let mut last_error: Option<String> = None;
let mut attempts_used = 0u32;
+ let mut routing_permit = None;
for attempt in 0..max_attempts {
attempts_used = attempt + 1;
+ if routing_permit.is_none() {
+ routing_permit = Some(acquire_routing_permit(ctx).await?);
+ }
let remaining = remaining_deadline(deadline)?;
let handle = match ctx
.pool
@@ -63,16 +71,21 @@ pub(super) async fn resolve_work_item(
let endpoint = handle.addr;
let start = Instant::now();
- let outcome = handle
- .mux
- .resolve_many(vec![work_item.to_item(remaining)], remaining)
- .await;
+ let permit = routing_permit
+ .take()
+ .expect("routing permit must be acquired before selecting an endpoint");
+ let session = handle.mux.submit_session(work_item.to_item(remaining));
+ let outcome = wait_for_terminal_or_acceptance(session, remaining, permit).await;
let elapsed_ms = start.elapsed().as_millis() as f64;
drop(handle);
let outcomes = match outcome {
- Ok(outcomes) => outcomes,
- Err(err) if err.is_retryable() => {
+ Ok((outcome, permit)) => {
+ routing_permit = permit;
+ vec![outcome]
+ }
+ Err((err, permit)) if err.is_retryable() => {
+ routing_permit = permit;
metrics::counter!(
REMOTE_RESOLUTION_REQUESTS,
"outcome" => "transport_retry",
@@ -95,7 +108,7 @@ pub(super) async fn resolve_work_item(
}
continue;
}
- Err(err) => {
+ Err((err, _permit)) => {
metrics::counter!(
REMOTE_RESOLUTION_REQUESTS,
"outcome" => "terminal",
@@ -197,6 +210,42 @@ pub(super) async fn resolve_work_item(
)))
}
+async fn wait_for_terminal_or_acceptance(
+ mut session: ResolveItemSession,
+ deadline: Duration,
+ permit: OwnedSemaphorePermit,
+) -> Result<
+ (ResolveOutcome, Option<OwnedSemaphorePermit>),
+ (RemoteCallError, Option<OwnedSemaphorePermit>),
+> {
+ let mut permit = Some(permit);
+ let sleep = tokio::time::sleep(deadline);
+ tokio::pin!(sleep);
+
+ loop {
+ tokio::select! {
+ outcome = session.outcomes.recv() => {
+ let Some(outcome) = outcome else {
+ return Err((RemoteCallError::Retryable(Status::unavailable("remote resolution session was dropped")), permit));
+ };
+ let outcome = match outcome {
+ Ok(outcome) => outcome,
+ Err(err) => return Err((err, permit)),
+ };
+ if matches!(outcome.result, Some(resolve_outcome::Result::Accepted(_))) {
+ drop(permit.take());
+ continue;
+ }
+ return Ok((outcome, permit));
+ }
+ _ = &mut sleep => {
+ session.cancel();
+ return Err((RemoteCallError::Deadline(deadline), permit));
+ }
+ }
+ }
+}
+
fn single_outcome(
token: u64,
outcomes: Vec<ResolveOutcome>,
@@ -290,6 +339,10 @@ fn classify_outcome(
)),
}
}
+ resolve_outcome::Result::Accepted(_) => Err(terminal_item_error(
+ work_item.token,
+ "remote resolution returned accepted without a terminal outcome".to_string(),
+ )),
}
}
@@ -300,6 +353,18 @@ fn terminal_item_error(token: u64, message: String) -> UnhandledError {
))
}
+async fn acquire_routing_permit(
+ ctx: &RemoteResolutionContext,
+) -> Result<OwnedSemaphorePermit, UnhandledError> {
+ ctx.routing_semaphore
+ .clone()
+ .acquire_owned()
+ .await
+ .map_err(|_| {
+ UnhandledError::Other("remote resolution routing semaphore closed".to_string())
+ })
+}
+
fn remaining_deadline(deadline: Instant) -> Result<Duration, UnhandledError> {
deadline
.checked_duration_since(Instant::now())
diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rs
index 988b2eb8bdd2..3440d975bd5f 100644
--- a/rust/cymbal/tests/common/mod.rs
+++ b/rust/cymbal/tests/common/mod.rs
@@ -37,8 +37,8 @@ use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::{
CymbalResolution, CymbalResolutionServer,
};
use cymbal_proto::cymbal::resolution::v1::{
- resolve_outcome, Done, Error as ItemError, ErrorKind, LoadEvent, ResolveItem, ResolveOutcome,
- Retry, SubscribeRequest,
+ resolve_outcome, Accepted, Done, Error as ItemError, ErrorKind, LoadEvent, ResolveItem,
+ ResolveOutcome, Retry, SubscribeRequest,
};
use futures::{Stream, StreamExt};
use tokio::sync::mpsc;
@@ -73,6 +73,9 @@ pub enum ServerBehavior {
/// Echo each item back as Done with the input exception unchanged but
/// sleep `delay` before emitting each outcome.
HappyDelayed { delay: Duration },
+ /// Emit Accepted immediately, then emit Done after `delay` without blocking
+ /// reads for subsequent items.
+ AcceptedThenDoneDelayed { delay: Duration },
/// Fail the Resolve stream during setup with Status::Unavailable.
AlwaysUnavailable,
/// Fail the Resolve stream during setup with Status::InvalidArgument.
@@ -170,12 +173,22 @@ impl CymbalResolution for StubServer {
match behavior {
ServerBehavior::Happy => {
+ send_outcome(&tx, accepted_outcome(&item)).await;
send_outcome(&tx, done_outcome(&item)).await;
}
ServerBehavior::HappyDelayed { delay } => {
+ send_outcome(&tx, accepted_outcome(&item)).await;
tokio::time::sleep(delay).await;
send_outcome(&tx, done_outcome(&item)).await;
}
+ ServerBehavior::AcceptedThenDoneDelayed { delay } => {
+ send_outcome(&tx, accepted_outcome(&item)).await;
+ let item_tx = tx.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(delay).await;
+ send_outcome(&item_tx, done_outcome(&item)).await;
+ });
+ }
ServerBehavior::Retry => {
send_outcome(&tx, retry_outcome(&item)).await;
}
@@ -185,18 +198,22 @@ impl CymbalResolution for StubServer {
}
ServerBehavior::InterruptAfterFirst => {
if seen == 1 {
+ send_outcome(&tx, accepted_outcome(&item)).await;
send_outcome(&tx, done_outcome(&item)).await;
let _ignored = tx
.send(Err(Status::internal("simulated interruption")))
.await;
return;
}
+ send_outcome(&tx, accepted_outcome(&item)).await;
send_outcome(&tx, done_outcome(&item)).await;
}
ServerBehavior::ErrorAfterFirst { kind } => {
if seen == 1 {
+ send_outcome(&tx, accepted_outcome(&item)).await;
send_outcome(&tx, done_outcome(&item)).await;
} else {
+ send_outcome(&tx, accepted_outcome(&item)).await;
send_outcome(&tx, error_outcome(&item, kind)).await;
}
}
@@ -218,6 +235,13 @@ async fn send_outcome(tx: &mpsc::Sender<Result<ResolveOutcome, Status>>, outcome
let _ignored = tx.send(Ok(outcome)).await;
}
+fn accepted_outcome(item: &ResolveItem) -> ResolveOutcome {
+ ResolveOutcome {
+ id: item.id,
+ result: Some(resolve_outcome::Result::Accepted(Accepted {})),
+ }
+}
+
fn done_outcome(item: &ResolveItem) -> ResolveOutcome {
ResolveOutcome {
id: item.id,
@@ -322,6 +346,7 @@ pub fn make_config_with_sample_rate(
retry_max_backoff: Duration::from_millis(2),
sample_rate,
routing_jitter: 0.0,
+ routing_acceptance_concurrency: 10,
overload_ejection_initial: Duration::ZERO,
overload_ejection_max: Duration::ZERO,
overload_ejection_decay: Duration::from_secs(30),
@@ -343,7 +368,7 @@ pub async fn make_ctx(
if !addrs.is_empty() {
wait_until_routable(&pool).await;
}
- RemoteResolutionContext { pool, config }
+ RemoteResolutionContext::new(pool, config)
}
pub async fn make_ctx_with_sample_rate(
@@ -357,7 +382,7 @@ pub async fn make_ctx_with_sample_rate(
if !addrs.is_empty() {
wait_until_routable(&pool).await;
}
- RemoteResolutionContext { pool, config }
+ RemoteResolutionContext::new(pool, config)
}
/// Wait until the pool has at least one routable endpoint (a fresh
diff --git a/rust/cymbal/tests/remote_resolution.rs b/rust/cymbal/tests/remote_resolution.rs
index 42fd080bfca4..acc6335c20fd 100644
--- a/rust/cymbal/tests/remote_resolution.rs
+++ b/rust/cymbal/tests/remote_resolution.rs
@@ -350,6 +350,32 @@ async fn load_events_do_not_shrink_streamed_item_submission() {
assert_eq!(items.lock().unwrap().len(), 10);
}
+#[tokio::test]
+async fn accepted_outcomes_release_routing_slots_before_terminal_completion() {
+ let (addr, _streams, items) =
+ spawn_recording_stub_server(ServerBehavior::AcceptedThenDoneDelayed {
+ delay: Duration::from_millis(300),
+ })
+ .await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 1.0).await;
+ let events: Vec<_> = (0..11)
+ .map(|i| {
+ Ok(build_event_with_symbol_refs(
+ Uuid::from_u128(600 + i),
+ &["x"],
+ ))
+ })
+ .collect();
+
+ let task = tokio::spawn(remote_stage(ctx).process(Batch::from(events)));
+ tokio::time::sleep(Duration::from_millis(100)).await;
+
+ assert_eq!(items.lock().unwrap().len(), 11);
+ task.await
+ .expect("join remote resolution")
+ .expect("stage processed");
+}
+
#[tokio::test]
async fn metadata_encodes_apple_debug_images_as_json_field() {
let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
diff --git a/rust/cymbal/tests/remote_resolution_hardening.rs b/rust/cymbal/tests/remote_resolution_hardening.rs
index 8c3e22aa16c6..976ff9963f89 100644
--- a/rust/cymbal/tests/remote_resolution_hardening.rs
+++ b/rust/cymbal/tests/remote_resolution_hardening.rs
@@ -145,10 +145,7 @@ async fn endpoint_refresh_closes_draining_mux_and_reroutes_in_flight_item() {
.await
.expect("build pool");
wait_until_routable(&pool).await;
- let ctx = RemoteResolutionContext {
- pool: Arc::clone(&pool),
- config,
- };
+ let ctx = RemoteResolutionContext::new(Arc::clone(&pool), config);
let task = tokio::spawn(process_one(remote_stage(ctx), build_event(1)));
tokio::time::sleep(Duration::from_millis(75)).await;
diff --git a/rust/cymbal/tests/remote_resolution_subscribe.rs b/rust/cymbal/tests/remote_resolution_subscribe.rs
index 99515d71b95a..8176588999d8 100644
--- a/rust/cymbal/tests/remote_resolution_subscribe.rs
+++ b/rust/cymbal/tests/remote_resolution_subscribe.rs
@@ -121,6 +121,7 @@ fn pool_config(host: &str, tick_hint: Duration) -> RemoteResolutionConfig {
retry_max_backoff: Duration::from_millis(2),
sample_rate: 1.0,
routing_jitter: 0.0,
+ routing_acceptance_concurrency: 10,
overload_ejection_initial: Duration::ZERO,
overload_ejection_max: Duration::ZERO,
overload_ejection_decay: Duration::from_secs(30),