: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
perf(error-tracking): score rendezvous candidates once per selection (#67938)
Catalin Irimie6957bc819cdd
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rsindex 253c9f41d8d5..22168832bb94 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/pool.rs@@ -77,6 +77,10 @@ struct EndpointState {channel: Channel,mux: ResolveMux,in_flight: Arc<AtomicUsize>,+ /// Pre-formatted address used as the `endpoint` metric label. Built once+ /// when the endpoint is added so the routing path clones an `Arc` instead+ /// of allocating a fresh `String` per selection (see `rust/CLAUDE.md`).+ endpoint_label: Arc<str>,// Endpoints that DNS no longer reports are marked draining. The mux is// closed so in-flight waiters reroute, and the endpoint is evicted once// local handles have observed the break and dropped.@@ -128,16 +132,24 @@ pub struct EndpointPoolHandle {pub channel: Channel,pub mux: ResolveMux,counter: Arc<AtomicUsize>,+ endpoint_label: Arc<str>,}impl EndpointPoolHandle {- fn new(addr: SocketAddr, channel: Channel, mux: ResolveMux, counter: Arc<AtomicUsize>) -> Self {+ fn new(+ addr: SocketAddr,+ channel: Channel,+ mux: ResolveMux,+ counter: Arc<AtomicUsize>,+ endpoint_label: Arc<str>,+ ) -> Self {counter.fetch_add(1, Ordering::AcqRel);Self {addr,channel,mux,counter,+ endpoint_label,}}}@@ -147,7 +159,7 @@ impl Drop for EndpointPoolHandle {self.counter.fetch_sub(1, Ordering::AcqRel);metrics::gauge!(REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT,- "endpoint" => self.addr.to_string(),+ "endpoint" => self.endpoint_label.clone(),).decrement(1.0);}@@ -474,6 +486,7 @@ impl EndpointPool {channel: state.channel.clone(),mux: state.mux.clone(),counter: state.in_flight.clone(),+ endpoint_label: state.endpoint_label.clone(),});}@@ -511,12 +524,18 @@ impl EndpointPool {}},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))+ // 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+ .into_iter()+ .map(|c| (rendezvous_score(routing_key, &c.endpoint_label), c))+ .collect();+ scored.sort_by(|(a_score, a), (b_score, b)| {+ b_score.cmp(a_score).then(a.addr.cmp(&b.addr))});- match choose_ranked_candidate(candidates, self.config.routing_jitter) {+ let ranked: Vec<Candidate> = scored.into_iter().map(|(_, c)| c).collect();+ match choose_ranked_candidate(ranked, self.config.routing_jitter) {Some(candidate) => candidate,None => {return Err(EndpointPoolError::Empty(classify_empty_reason(@@ -530,10 +549,11 @@ impl EndpointPool {};// Per-endpoint in-flight gauge; emitted only for the chosen endpoint- // (not every candidate) to keep the per-selection allocation bounded.+ // (not every candidate). The label is the endpoint's pre-built+ // `Arc<str>`, so this clone is a refcount bump rather than an alloc.metrics::gauge!(REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT,- "endpoint" => chosen.addr.to_string(),+ "endpoint" => chosen.endpoint_label.clone(),).increment(1.0);@@ -542,6 +562,7 @@ impl EndpointPool {chosen.channel,chosen.mux,chosen.counter,+ chosen.endpoint_label,))}@@ -670,6 +691,7 @@ struct Candidate {channel: Channel,mux: ResolveMux,counter: Arc<AtomicUsize>,+ endpoint_label: Arc<str>,}enum SelectionStrategy<'a> {@@ -693,11 +715,16 @@ fn classify_empty_reason(}}-fn rendezvous_score(routing_key: &str, addr: SocketAddr) -> u64 {+fn rendezvous_score(routing_key: &str, addr_label: &str) -> u64 {+ // SHA-256 (no per-process seed) keeps the key->endpoint mapping identical+ // across every client pod. `addr_label` is the endpoint's pre-formatted+ // address string, so the hashed input matches the historical+ // `SocketAddr::to_string()` bytes exactly — the mapping is stable across a+ // rolling deploy — while the caller avoids re-allocating it per selection.let mut hasher = Sha256::new();hasher.update(routing_key.as_bytes());hasher.update(b"\0");- hasher.update(addr.to_string().as_bytes());+ hasher.update(addr_label.as_bytes());let digest = hasher.finalize();u64::from_be_bytes(digest[0..8].try_into().expect("sha256 digest has 8 bytes"))}@@ -863,6 +890,7 @@ fn build_endpoint_state(channel,mux,in_flight: Arc::new(AtomicUsize::new(0)),+ endpoint_label: Arc::from(addr.to_string()),draining: false,load: Arc::new(StdMutex::new(None)),overload_ejected_until: None,@@ -1112,6 +1140,63 @@ mod test {}}+ #[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+ // the order endpoints were added — otherwise different pods, which see+ // DNS in arbitrary order, would disagree on the sticky endpoint and+ // shred cache locality. Two orderings of the same set must agree.+ let forward = [+ addr("10.0.0.1:50061"),+ addr("10.0.0.2:50061"),+ addr("10.0.0.3:50061"),+ ];+ let reverse = [+ addr("10.0.0.3:50061"),+ addr("10.0.0.2:50061"),+ addr("10.0.0.1:50061"),+ ];+ let key = "team:1:symbol:bundle-order";++ let pool_forward =+ EndpointPool::from_addrs_without_subscriptions(mock_config(), &forward).unwrap();+ inject_uniform_fresh_snapshots(&pool_forward, &forward).await;+ let pool_reverse =+ EndpointPool::from_addrs_without_subscriptions(mock_config(), &reverse).unwrap();+ inject_uniform_fresh_snapshots(&pool_reverse, &reverse).await;++ let chosen_forward = pool_forward.select_for_key(key, &[]).await.unwrap().addr;+ let chosen_reverse = pool_reverse.select_for_key(key, &[]).await.unwrap().addr;+ assert_eq!(chosen_forward, chosen_reverse);+ }++ #[test]+ fn rendezvous_score_is_deterministic_and_stable() {+ let key = "team:1:symbol:bundle-a";+ // Stable across calls (no per-process seed) and distinct per endpoint.+ assert_eq!(+ rendezvous_score(key, "10.0.0.1:50061"),+ rendezvous_score(key, "10.0.0.1:50061")+ );+ assert_ne!(+ rendezvous_score(key, "10.0.0.1:50061"),+ rendezvous_score(key, "10.0.0.2:50061")+ );+ // Port is part of the label, so two ports on one host differ.+ assert_ne!(+ rendezvous_score(key, "10.0.0.1:50061"),+ rendezvous_score(key, "10.0.0.1:50062")+ );+ // The hashed input is the SocketAddr's Display form, so scoring the+ // label matches scoring `addr.to_string()` byte-for-byte. This pins the+ // key->endpoint mapping so it survives a rolling deploy.+ let socket = addr("10.0.0.1:50061");+ assert_eq!(+ rendezvous_score(key, &socket.to_string()),+ rendezvous_score(key, "10.0.0.1:50061")+ );+ }+#[tokio::test]async fn select_for_key_uses_random_routing_when_jitter_is_full() {let addrs = [