: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cymbal): rank routing jitter distribution (#61133)
Hugues Pouillot8b79c2fccbce
diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex bbac0d91f154..5fa901e6d05c 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -40,8 +40,8 @@ overloads double the endpoint cooldown up to`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it.`LoadEvent` is only a freshness/draining signal for endpoint routing, not anoverload or dynamic batch-size control plane. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER`-can probabilistically blend strict sticky routing (`0.0`) with fully random routing (`1.0`)-when hot-key distribution needs extra spread.+flattens traffic across the rendezvous-ranked candidate list: `0.0` sends all traffic to+the top-ranked endpoint, `1.0` is uniform across candidates, and intermediate values decay by rank.See [`docs/compatibility.md`](docs/compatibility.md) for the Node consumercompatibility checklist and [`../cymbal-resolution/README.md`](../cymbal-resolution/README.md)diff --git a/rust/cymbal/docs/compatibility.md b/rust/cymbal/docs/compatibility.mdindex c73e7fe28d81..dede87a02066 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 often routing ignores the sticky rendezvous endpoint in favor of a random endpoint (`0.0` strict sticky, `1.0` fully random). `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. 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/config.rs b/rust/cymbal/src/config.rsindex 454389f36553..b88ade47073b 100644--- a/rust/cymbal/src/config.rs+++ b/rust/cymbal/src/config.rs@@ -269,9 +269,9 @@ pub struct Config {#[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE", default = "0.0")]pub remote_resolution_sample_rate: f64,- /// Probability of routing a remote resolution item randomly instead of- /// using sticky rendezvous routing. `0.0` is fully sticky, `1.0` is fully- /// random, and intermediate values probabilistically blend both modes.+ /// Flattens remote resolution routing across the rendezvous-ranked candidate+ /// list. `0.0` sends all traffic to the top-ranked endpoint, `1.0` is+ /// uniform across all candidates, and intermediate values decay by rank.#[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER", default = "0.0")]pub remote_resolution_routing_jitter: f64,diff --git a/rust/cymbal/src/stages/resolution/remote/config.rs b/rust/cymbal/src/stages/resolution/remote/config.rsindex bc206a37a3f1..97fb6b2f0430 100644--- a/rust/cymbal/src/stages/resolution/remote/config.rs+++ b/rust/cymbal/src/stages/resolution/remote/config.rs@@ -31,8 +31,8 @@ pub struct RemoteResolutionConfig {/// cymbal-resolution. Defaults to 0.0 in [`Config`] so enabling remote mode/// alone does not start sending traffic until rollout is ramped explicitly.pub sample_rate: f64,- /// Probability of selecting a random endpoint instead of the sticky- /// rendezvous endpoint for a routing key.+ /// 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,/// Cadence hint sent on `SubscribeRequest.tick_hint_ms`. The server may/// clamp this; the caller relies on whatever cadence the server settles on.diff --git a/rust/cymbal/src/stages/resolution/remote/pool.rs b/rust/cymbal/src/stages/resolution/remote/pool.rsindex 309ffa019f1f..71dfcc4c08c9 100644--- a/rust/cymbal/src/stages/resolution/remote/pool.rs+++ b/rust/cymbal/src/stages/resolution/remote/pool.rs@@ -409,9 +409,6 @@ impl EndpointPool {if routing_key.is_empty() {return self.select(exclude).await;}- if should_jitter_route(self.config.routing_jitter) {- return self.select(exclude).await;- }self.select_inner(SelectionStrategy::ByKey { routing_key }, exclude).await}@@ -503,17 +500,32 @@ impl EndpointPool {}let chosen = match strategy {- SelectionStrategy::Random => candidates- .choose(&mut rand::thread_rng())- .expect("non-empty candidates")- .clone(),+ SelectionStrategy::Random => match candidates.choose(&mut rand::thread_rng()) {+ Some(candidate) => candidate.clone(),+ None => {+ return Err(EndpointPoolError::Empty(classify_empty_reason(+ active_endpoint_count,+ ejected_endpoint_count,+ saw_missing_or_stale_snapshot,+ )));+ }+ },SelectionStrategy::ByKey { routing_key } => {candidates.sort_by(|a, b| {rendezvous_score(routing_key, b.addr).cmp(&rendezvous_score(routing_key, a.addr)).then(a.addr.cmp(&b.addr))});- candidates.into_iter().next().expect("non-empty candidates")+ match choose_ranked_candidate(candidates, self.config.routing_jitter) {+ Some(candidate) => candidate,+ None => {+ return Err(EndpointPoolError::Empty(classify_empty_reason(+ active_endpoint_count,+ ejected_endpoint_count,+ saw_missing_or_stale_snapshot,+ )));+ }+ }}};@@ -766,14 +778,48 @@ fn record_endpoint_states(inner: &PoolInner, now: Instant, stale_after: Duration}}-fn should_jitter_route(routing_jitter: f64) -> bool {+fn choose_ranked_candidate(candidates: Vec<Candidate>, routing_jitter: f64) -> Option<Candidate> {+ let top_ranked = candidates.first()?.clone();+ if routing_jitter <= 0.0 || candidates.len() == 1 {+ return Some(top_ranked);+ }+ if routing_jitter >= 1.0 {+ return candidates.choose(&mut rand::thread_rng()).cloned();+ }++ let weights = (0..candidates.len())+ .map(|rank| routing_jitter.powi(rank as i32))+ .collect::<Vec<_>>();+ let total_weight = weights.iter().sum::<f64>();+ let mut draw = rand::thread_rng().gen_range(0.0..total_weight);++ for (candidate, weight) in candidates.into_iter().zip(weights) {+ if draw < weight {+ return Some(candidate);+ }+ draw -= weight;+ }++ Some(top_ranked)+}++#[cfg(test)]+fn ranked_selection_probability(rank: usize, candidate_count: usize, routing_jitter: f64) -> f64 {+ if candidate_count == 0 || rank >= candidate_count {+ return 0.0;+ }if routing_jitter <= 0.0 {- return false;+ return if rank == 0 { 1.0 } else { 0.0 };}if routing_jitter >= 1.0 {- return true;+ return 1.0 / candidate_count as f64;}- rand::thread_rng().gen_bool(routing_jitter)++ let rank_weight = routing_jitter.powi(rank as i32);+ let total_weight = (0..candidate_count)+ .map(|candidate_rank| routing_jitter.powi(candidate_rank as i32))+ .sum::<f64>();+ rank_weight / total_weight}/// Start a background task that periodically calls [`EndpointPool::refresh`].@@ -1093,6 +1139,22 @@ mod test {);}+ #[test]+ fn routing_jitter_probability_decays_by_rank() {+ assert_eq!(ranked_selection_probability(0, 4, 0.0), 1.0);+ assert_eq!(ranked_selection_probability(1, 4, 0.0), 0.0);++ for rank in 0..4 {+ assert!((ranked_selection_probability(rank, 4, 1.0) - 0.25).abs() < f64::EPSILON);+ }++ let total_weight = 1.0 + 0.5 + 0.25 + 0.125;+ assert!((ranked_selection_probability(0, 4, 0.5) - (1.0 / total_weight)).abs() < 1e-12);+ assert!((ranked_selection_probability(1, 4, 0.5) - (0.5 / total_weight)).abs() < 1e-12);+ assert!((ranked_selection_probability(2, 4, 0.5) - (0.25 / total_weight)).abs() < 1e-12);+ assert!((ranked_selection_probability(3, 4, 0.5) - (0.125 / total_weight)).abs() < 1e-12);+ }+#[tokio::test]async fn select_for_key_spreads_distinct_keys_across_endpoints() {let addrs = [