: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
feat(error-tracking): load-bias cymbal resolution routing (#69238)
Hugues Pouillot20e7147ad49c
diff --git a/proto/cymbal/resolution/v1/resolution.proto b/proto/cymbal/resolution/v1/resolution.protoindex 40bbfcc43f01..450e12c861a1 100644--- a/proto/cymbal/resolution/v1/resolution.proto+++ b/proto/cymbal/resolution/v1/resolution.proto@@ -126,4 +126,9 @@ message LoadEvent {uint64 sequence = 4;// Optional short human-readable note. Not interpreted by the router.string message = 5;+ // Current server-side exception items in flight on this pod. Routers use+ // this as a soft load signal, not as an admission guarantee.+ uint32 in_flight = 6;+ // Server-side item concurrency cap used to interpret `in_flight`.+ uint32 max_in_flight = 7;}diff --git a/rust/cymbal-proto/tests/contract.rs b/rust/cymbal-proto/tests/contract.rsindex f31b5a3ec855..17aea85b8db3 100644--- a/rust/cymbal-proto/tests/contract.rs+++ b/rust/cymbal-proto/tests/contract.rs@@ -119,11 +119,15 @@ fn load_event_carries_routing_relevant_state_with_sequence() {draining: false,sequence: 7,message: "ok".to_string(),+ in_flight: 11,+ max_in_flight: 64,};let decoded = LoadEvent::decode(event.encode_to_vec().as_slice()).unwrap();assert_eq!(decoded.service_instance_id, "resolver-a");assert_eq!(decoded.sequence, 7);+ assert_eq!(decoded.in_flight, 11);+ assert_eq!(decoded.max_in_flight, 64);assert!(!decoded.draining);}diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex 6e68adf8908d..a0b711d2bfcd 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -43,10 +43,9 @@ endpoint is also excluded from new routing in that cymbal process. Repeatedoverloads double the endpoint cooldown up to`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS`, and a quiet`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it.-`LoadEvent` is only a freshness/draining signal for endpoint routing, not an-overload or dynamic batch-size control plane. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER`-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.+`LoadEvent` carries freshness, draining, and item-concurrency load (`in_flight` / `max_in_flight`).+Cymbal uses that load as a soft routing bias: busier endpoints are less likely to win the rendezvous-ranked candidate list, while stale or draining endpoints remain excluded.+`CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER` flattens traffic across the load-adjusted rendezvous-ranked candidate list: `0.0` sends traffic to the top load-adjusted endpoint, `1.0` makes selection load-weighted across candidates, and intermediate values decay by rank.See [`docs/compatibility.md`](docs/compatibility.md) for the Node consumercompatibility checklist and [`src/modes/resolution/README.md`](src/modes/resolution/README.md)diff --git a/rust/cymbal/docs/compatibility.md b/rust/cymbal/docs/compatibility.mdindex 3d6279b713b1..33738a528191 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 native symbolication convention uses a `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. 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.+- 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 load-adjusted rendezvous-ranked candidate list (`0.0` strict top load-adjusted candidate, `1.0` load-weighted across candidates). `LoadEvent` carries endpoint freshness/draining state plus `in_flight` / `max_in_flight` as a soft routing load signal.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/modes/processing/stages/resolution/remote/pool.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rsindex 22168832bb94..9bce8d3441be 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rs@@ -5,7 +5,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex as StdMutex};use std::time::{Duration, Instant};-use rand::{seq::SliceRandom, Rng};+use rand::Rng;use sha2::{Digest, Sha256};use thiserror::Error;use tokio::sync::{Mutex, Notify};@@ -481,12 +481,18 @@ impl EndpointPool {if snapshot.draining {continue;}+ let local_in_flight = state+ .in_flight+ .load(Ordering::Acquire)+ .min(u32::MAX as usize) as u32;+ let estimated_in_flight = snapshot.in_flight.max(local_in_flight);candidates.push(Candidate {addr: *addr,channel: state.channel.clone(),mux: state.mux.clone(),counter: state.in_flight.clone(),endpoint_label: state.endpoint_label.clone(),+ load_weight: available_capacity_weight(estimated_in_flight, snapshot.max_in_flight),});}@@ -513,8 +519,8 @@ impl EndpointPool {}let chosen = match strategy {- SelectionStrategy::Random => match candidates.choose(&mut rand::thread_rng()) {- Some(candidate) => candidate.clone(),+ SelectionStrategy::Random => match choose_load_weighted_candidate(candidates) {+ Some(candidate) => candidate,None => {return Err(EndpointPoolError::Empty(classify_empty_reason(active_endpoint_count,@@ -527,12 +533,12 @@ impl EndpointPool {// Score each candidate once (O(n)) rather than re-hashing inside// the comparator (O(n log n) hashes). Rank by score desc with a// deterministic addr-asc tie-break, then discard the scores.- let mut scored: Vec<(u64, Candidate)> = candidates+ let mut scored: Vec<(f64, Candidate)> = candidates.into_iter()- .map(|c| (rendezvous_score(routing_key, &c.endpoint_label), c))+ .map(|c| (load_adjusted_rendezvous_score(routing_key, &c), c)).collect();scored.sort_by(|(a_score, a), (b_score, b)| {- b_score.cmp(a_score).then(a.addr.cmp(&b.addr))+ b_score.total_cmp(a_score).then(a.addr.cmp(&b.addr))});let ranked: Vec<Candidate> = scored.into_iter().map(|(_, c)| c).collect();match choose_ranked_candidate(ranked, self.config.routing_jitter) {@@ -692,6 +698,7 @@ struct Candidate {mux: ResolveMux,counter: Arc<AtomicUsize>,endpoint_label: Arc<str>,+ load_weight: f64,}enum SelectionStrategy<'a> {@@ -729,6 +736,18 @@ fn rendezvous_score(routing_key: &str, addr_label: &str) -> u64 {u64::from_be_bytes(digest[0..8].try_into().expect("sha256 digest has 8 bytes"))}+fn load_adjusted_rendezvous_score(routing_key: &str, candidate: &Candidate) -> f64 {+ rendezvous_score(routing_key, &candidate.endpoint_label) as f64 * candidate.load_weight+}++fn available_capacity_weight(in_flight: u32, max_in_flight: u32) -> f64 {+ const MIN_WEIGHT: f64 = 0.01;++ let capacity = max_in_flight.max(1) as f64;+ let saturation = (in_flight as f64 / capacity).clamp(0.0, 1.0);+ (1.0 - saturation).max(MIN_WEIGHT).powi(2)+}+#[derive(Clone, Copy)]enum EndpointRoutingState {Routable,@@ -810,24 +829,59 @@ fn choose_ranked_candidate(candidates: Vec<Candidate>, routing_jitter: f64) -> Oif 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))+ let weights = candidates+ .iter()+ .enumerate()+ .map(|(rank, candidate)| rank_weight(rank, routing_jitter) * candidate.load_weight)+ .collect::<Vec<_>>();++ choose_weighted_candidate(candidates, &weights)+}++fn choose_load_weighted_candidate(candidates: Vec<Candidate>) -> Option<Candidate> {+ let weights = candidates+ .iter()+ .map(|candidate| candidate.load_weight).collect::<Vec<_>>();- let total_weight = weights.iter().sum::<f64>();+ choose_weighted_candidate(candidates, &weights)+}++fn choose_weighted_candidate(candidates: Vec<Candidate>, weights: &[f64]) -> Option<Candidate> {+ if candidates.is_empty() || candidates.len() != weights.len() {+ return None;+ }++ let fallback = candidates.first().cloned();+ let total_weight = weights+ .iter()+ .copied()+ .filter(|weight| *weight > 0.0)+ .sum::<f64>();+ if total_weight <= 0.0 || !total_weight.is_finite() {+ return fallback;+ }+let mut draw = rand::thread_rng().gen_range(0.0..total_weight);- for (candidate, weight) in candidates.into_iter().zip(weights) {+ for (candidate, weight) in candidates.into_iter().zip(weights.iter().copied()) {+ if weight <= 0.0 {+ continue;+ }if draw < weight {return Some(candidate);}draw -= weight;}- Some(top_ranked)+ fallback+}++fn rank_weight(rank: usize, routing_jitter: f64) -> f64 {+ if routing_jitter >= 1.0 {+ return 1.0;+ }+ routing_jitter.powi(rank as i32)}#[cfg(test)]@@ -952,11 +1006,21 @@ mod test {fn fresh_snapshot() -> LoadSnapshot {LoadSnapshot {draining: false,+ in_flight: 0,+ max_in_flight: 64,observed_at: Instant::now(),sequence: 1,}}+ fn loaded_snapshot(in_flight: u32, max_in_flight: u32) -> LoadSnapshot {+ LoadSnapshot {+ in_flight,+ max_in_flight,+ ..fresh_snapshot()+ }+ }+#[tokio::test]async fn new_fails_when_dns_returns_no_endpoints() {let queue = Arc::new(TokioMutex::new(vec![Vec::new()]));@@ -1077,6 +1141,8 @@ mod test {.unwrap();let stale = LoadSnapshot {draining: false,+ in_flight: 0,+ max_in_flight: 64,observed_at: Instant::now() - Duration::from_secs(10),sequence: 1,};@@ -1140,6 +1206,27 @@ mod test {}}+ #[tokio::test]+ async fn select_for_key_penalizes_saturated_preferred_endpoint() {+ let addrs = [+ addr("10.0.0.1:50061"),+ addr("10.0.0.2:50061"),+ addr("10.0.0.3:50061"),+ ];+ let pool = EndpointPool::from_addrs_without_subscriptions(mock_config(), &addrs).unwrap();+ inject_uniform_fresh_snapshots(&pool, &addrs).await;++ let key = "team:1:symbol:bundle-a";+ let preferred = pool.select_for_key(key, &[]).await.unwrap().addr;+ assert!(+ pool.inject_load_snapshot_for_test(preferred, loaded_snapshot(64, 64))+ .await+ );++ let next = pool.select_for_key(key, &[]).await.unwrap().addr;+ assert_ne!(next, preferred);+ }+#[tokio::test]async fn select_for_key_top_choice_is_independent_of_insertion_order() {// Rendezvous ranking must depend only on (routing_key, addr), not on@@ -1241,6 +1328,17 @@ mod test {assert!((ranked_selection_probability(3, 4, 0.5) - (0.125 / total_weight)).abs() < 1e-12);}+ #[test]+ fn available_capacity_weight_drops_as_endpoint_saturates() {+ let empty = available_capacity_weight(0, 64);+ let half = available_capacity_weight(32, 64);+ let full = available_capacity_weight(64, 64);++ assert!(empty > half);+ assert!(half > full);+ assert!(full > 0.0);+ }+#[tokio::test]async fn select_for_key_spreads_distinct_keys_across_endpoints() {let addrs = [diff --git a/rust/cymbal/src/modes/processing/stages/resolution/remote/subscription.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/subscription.rsindex fbfae34fed41..f0ad50fd70c4 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/subscription.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/subscription.rs@@ -33,6 +33,8 @@ use super::client::with_internal_api_secret;#[derive(Clone, Debug)]pub struct LoadSnapshot {pub draining: bool,+ pub in_flight: u32,+ pub max_in_flight: u32,/// Local wall-clock at which this snapshot was received. Used by the pool/// to ignore stale snapshots when routing.pub observed_at: Instant,@@ -221,6 +223,8 @@ fn jitter_for(backoff: Duration) -> Duration {fn snapshot_from_event(event: LoadEvent) -> LoadSnapshot {LoadSnapshot {draining: event.draining,+ in_flight: event.in_flight,+ max_in_flight: event.max_in_flight.max(1),observed_at: Instant::now(),sequence: event.sequence,}@@ -235,10 +239,27 @@ mod tests {let now = Instant::now();let snap = LoadSnapshot {draining: false,+ in_flight: 0,+ max_in_flight: 64,observed_at: now - Duration::from_secs(10),sequence: 1,};assert!(!snap.is_fresh(now, Duration::from_secs(1)));assert!(snap.is_fresh(now, Duration::from_secs(30)));}++ #[test]+ fn snapshot_from_legacy_event_defaults_capacity_to_one() {+ let snapshot = snapshot_from_event(LoadEvent {+ service_instance_id: "legacy".to_string(),+ draining: false,+ sequence: 1,+ message: String::new(),+ in_flight: 0,+ max_in_flight: 0,+ });++ assert_eq!(snapshot.in_flight, 0);+ assert_eq!(snapshot.max_in_flight, 1);+ }}diff --git a/rust/cymbal/src/modes/resolution/README.md b/rust/cymbal/src/modes/resolution/README.mdindex 66782cff1741..a866a53347fd 100644--- a/rust/cymbal/src/modes/resolution/README.md+++ b/rust/cymbal/src/modes/resolution/README.md@@ -47,7 +47,7 @@ events ──HTTP─────▶│ cymbalThe 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 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.+- **`Subscribe`** is endpoint freshness, draining, and soft load state. The cymbal-side `EndpointPool` opens one long-lived stream per pod and treats the latest `LoadEvent` as a freshness snapshot plus an `in_flight` / `max_in_flight` routing bias. `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 affinity and reroute behavior-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.+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 small, stable part of the pod set, maximizing warm-cache locality without coupling the caller to symbol-set internals. The rendezvous score is adjusted by the latest server load snapshot and the caller's own local in-flight count, so highly loaded pods become less likely to receive new work before they return overload outcomes.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.@@ -132,7 +132,7 @@ All variables are prefixed `CYMBAL_REMOTE_RESOLUTION_` and live on `cymbal::conf| `SYMBOL_RESOLUTION_CONCURRENCY` | `64` | Cap on concurrent symbol-resolution operations across all in-flight items. || `MAX_ITEM_CONCURRENCY` | `64` | Process-wide cap on concurrently processed exception items. Excess items receive `ERROR_KIND_OVERLOADED`. || `SERVICE_INSTANCE_ID` | random UUID | Identifier surfaced to callers via `LoadEvent` on the Subscribe stream. |-| `SUBSCRIBE_TICK_INTERVAL_MS` | `1000` | Default `LoadEvent` cadence when callers do not suggest one. |+| `SUBSCRIBE_TICK_INTERVAL_MS` | `1000` | Default `LoadEvent` heartbeat cadence when callers do not suggest one. Load events may be emitted earlier when draining changes or in-flight load crosses coarse thresholds. || `SUBSCRIBE_MIN_TICK_MS` | `100` | Lower bound for the Subscribe tick cadence. || `SUBSCRIBE_MAX_TICK_MS` | `10000` | Upper bound for the Subscribe tick cadence. |@@ -160,7 +160,7 @@ These metric names are exported by the cymbal client unless noted. Definitions l- **Reroute shape**: `cymbal_remote_resolution_reroute_depth{outcome}` records how many endpoint changes happened before the terminal item result. The legacy attempts histogram may still be emitted for dashboard continuity, but new alerts should use reroute depth.- **Protocol error taxonomy**: client-observed `cymbal_remote_resolution_error_kinds_total{kind}` and server-emitted `cymbal_remote_resolution_server_error_kinds_total{kind}` count `ErrorKind` values with bounded labels.- **Overload backpressure**: `cymbal_remote_resolution_overload_escalations_total` counts overloaded item results that are escalated into reroutes. On the server, `grpc_server_load_shed_total{method="Resolve"}` covers gRPC stream admission shedding and `cymbal_remote_resolution_server_in_flight_items` shows active item processing.-- **Endpoint pool health**: `cymbal_remote_resolution_pool_size`, `cymbal_remote_resolution_endpoint_in_flight{endpoint}`, and `cymbal_remote_resolution_endpoint_mux_in_flight{endpoint}` show discovery health, selected endpoint usage, and active mux waiters.+- **Endpoint pool health**: `cymbal_remote_resolution_pool_size`, `cymbal_remote_resolution_endpoint_in_flight{endpoint}`, `cymbal_remote_resolution_endpoint_mux_in_flight{endpoint}`, and server-side `cymbal_remote_resolution_server_in_flight_items` show discovery health, selected endpoint usage, active mux waiters, and the load signal used by routing.- **Per-endpoint local admission**: `cymbal_remote_resolution_endpoint_admission_rejections_total{endpoint, reason}` counts bounded mux queue and closed-stream rejections before an item leaves the cymbal pod.- **Subscribe health**: `cymbal_remote_resolution_load_subscriptions_total{outcome="connected"|"reconnect"}` tracks the freshness/draining stream lifecycle. Sustained reconnects translate into `pool_empty` with `reason="no_fresh_load_snapshots"` because endpoints without fresh snapshots are excluded from selection.diff --git a/rust/cymbal/src/modes/resolution/load_monitor.rs b/rust/cymbal/src/modes/resolution/load_monitor.rsindex 3977573cbffe..da5c408534d6 100644--- a/rust/cymbal/src/modes/resolution/load_monitor.rs+++ b/rust/cymbal/src/modes/resolution/load_monitor.rs@@ -7,6 +7,7 @@ const SERVER_IN_FLIGHT_ITEMS: &str = "cymbal_remote_resolution_server_in_flight_#[derive(Clone, Debug)]pub struct LoadSnapshot {pub in_flight: u32,+ pub max_in_flight: u32,pub draining: bool,}@@ -36,13 +37,22 @@ impl LoadMonitor {}pub fn try_admit(&self) -> bool {- let mut state = self.lock_state();- if state.in_flight >= self.max_in_flight {- return false;+ let should_notify = {+ let mut state = self.lock_state();+ if state.in_flight >= self.max_in_flight {+ return false;+ }++ let old_load_bucket = load_bucket(state.in_flight, self.max_in_flight);+ state.in_flight = state.in_flight.saturating_add(1);+ record_in_flight(state.in_flight);+ old_load_bucket != load_bucket(state.in_flight, self.max_in_flight)+ };++ if should_notify {+ self.notify.notify_waiters();}- state.in_flight = state.in_flight.saturating_add(1);- record_in_flight(state.in_flight);true}@@ -70,6 +80,7 @@ impl LoadMonitor {let state = self.lock_state();LoadSnapshot {in_flight: state.in_flight,+ max_in_flight: self.max_in_flight,draining: state.draining,}}@@ -78,11 +89,13 @@ impl LoadMonitor {let should_notify = {let mut state = self.lock_state();let old_draining = state.draining;+ let old_load_bucket = load_bucket(state.in_flight, self.max_in_flight);update(&mut state);record_in_flight(state.in_flight);old_draining != state.draining+ || old_load_bucket != load_bucket(state.in_flight, self.max_in_flight)};if should_notify {@@ -99,6 +112,22 @@ fn record_in_flight(in_flight: u32) {metrics::gauge!(SERVER_IN_FLIGHT_ITEMS).set(in_flight as f64);}+fn load_bucket(in_flight: u32, max_in_flight: u32) -> u8 {+ if in_flight == 0 {+ return 0;+ }++ let pct = (u64::from(in_flight) * 100) / u64::from(max_in_flight.max(1));+ match pct {+ 0..=24 => 1,+ 25..=49 => 2,+ 50..=74 => 3,+ 75..=89 => 4,+ 90..=99 => 5,+ _ => 6,+ }+}+#[cfg(test)]mod tests {use std::time::Duration;@@ -122,11 +151,47 @@ mod tests {assert!(monitor.snapshot().draining);}+ #[tokio::test]+ async fn notifies_when_load_crosses_thresholds() {+ let monitor = LoadMonitor::new(4);+ let waiter_monitor = monitor.clone();+ let waiter = tokio::spawn(async move {+ waiter_monitor.notified().await;+ });+ tokio::task::yield_now().await;++ monitor.set_in_flight(1);++ tokio::time::timeout(Duration::from_secs(1), waiter)+ .await+ .expect("load threshold change should notify")+ .expect("waiter should not panic");+ }++ #[tokio::test]+ async fn does_not_notify_for_load_changes_within_one_threshold_bucket() {+ let monitor = LoadMonitor::new(100);+ monitor.set_in_flight(1);++ let waiter_monitor = monitor.clone();+ let waiter = tokio::spawn(async move {+ waiter_monitor.notified().await;+ });+ tokio::task::yield_now().await;++ monitor.set_in_flight(2);++ assert!(tokio::time::timeout(Duration::from_millis(20), waiter)+ .await+ .is_err());+ }+#[tokio::test]async fn increment_and_decrement_track_in_flight_lifecycle() {let monitor = LoadMonitor::new(2);monitor.increment_in_flight();assert_eq!(monitor.snapshot().in_flight, 1);+ assert_eq!(monitor.snapshot().max_in_flight, 2);monitor.decrement_in_flight();assert_eq!(monitor.snapshot().in_flight, 0);@@ -145,4 +210,16 @@ mod tests {assert!(monitor.try_admit());assert_eq!(monitor.snapshot().in_flight, 2);}++ #[test]+ fn load_bucket_uses_coarse_thresholds() {+ assert_eq!(load_bucket(0, 100), 0);+ assert_eq!(load_bucket(1, 100), 1);+ assert_eq!(load_bucket(24, 100), 1);+ assert_eq!(load_bucket(25, 100), 2);+ assert_eq!(load_bucket(50, 100), 3);+ assert_eq!(load_bucket(75, 100), 4);+ assert_eq!(load_bucket(90, 100), 5);+ assert_eq!(load_bucket(100, 100), 6);+ }}diff --git a/rust/cymbal/src/modes/resolution/service/subscribe.rs b/rust/cymbal/src/modes/resolution/service/subscribe.rsindex 9430bb1683b7..782fba87bcf8 100644--- a/rust/cymbal/src/modes/resolution/service/subscribe.rs+++ b/rust/cymbal/src/modes/resolution/service/subscribe.rs@@ -54,6 +54,8 @@ pub(super) fn load_event_stream(draining: snapshot.draining,sequence,message: String::new(),+ in_flight: snapshot.in_flight,+ max_in_flight: snapshot.max_in_flight,});}}diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rsindex dd80b14d9c04..0e1c2bd66ebc 100644--- a/rust/cymbal/tests/common/mod.rs+++ b/rust/cymbal/tests/common/mod.rs@@ -109,7 +109,7 @@ impl CymbalResolution for StubServer {type ResolveStream = ResolveStream;type SubscribeStream = SubscribeStream;- /// Default Subscribe behaviour: emit freshness/draining-only `LoadEvent`s+ /// Default Subscribe behaviour: emit freshness/draining/load `LoadEvent`s/// on a fast tick so snapshot-required routing can warm up quickly.async fn subscribe(&self,@@ -129,6 +129,8 @@ impl CymbalResolution for StubServer {draining: false,sequence,message: String::new(),+ in_flight: 0,+ max_in_flight: 64,};if tx.send(Ok(event)).await.is_err() {return;diff --git a/rust/cymbal/tests/resolution_service_tests.rs b/rust/cymbal/tests/resolution_service_tests.rsindex edb0ff3e46c5..c81b6f9ff2b2 100644--- a/rust/cymbal/tests/resolution_service_tests.rs+++ b/rust/cymbal/tests/resolution_service_tests.rs@@ -569,6 +569,8 @@ async fn subscribe_emits_periodic_load_events_with_monotonic_sequence() {assert_eq!(events[1].sequence, 2);assert_eq!(events[2].sequence, 3);assert!(!events[0].draining);+ assert_eq!(events[0].in_flight, 0);+ assert_eq!(events[0].max_in_flight, 4);assert_eq!(events[0].service_instance_id, "test-instance");}