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(cymbal): add remote symbol resolution via gRPC service (#60289)

Hugues Pouillotc3443bd04bd4
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index 23285465c8a2..80a0c76d5172 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -31,6 +31,10 @@
dockerfile: ./rust/Dockerfile
project: 8dq0xkk0ck
+- image: cymbal-resolution
+ dockerfile: ./rust/Dockerfile
+ project: 8dq0xkk0ck
+
- image: embedding-worker
dockerfile: ./rust/Dockerfile
project: 8dq0xkk0ck
diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.yml
index c2b9c3fbddd2..d639921d564c 100644
--- a/.github/workflows/rust-docker-build.yml
+++ b/.github/workflows/rust-docker-build.yml
@@ -20,6 +20,8 @@ on:
paths:
- 'rust/**'
- '.github/workflows/rust-docker-build.yml'
+ - '.github/workflows/_rust-build-images.yml'
+ - '.github/rust-images.yml'
branches:
- 'master'
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 5e357003a13c..793103832e99 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -229,6 +229,16 @@ procs:
layer: Product services
tech: Rust
+ cymbal-resolution:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service cymbal-resolution
+ capability: error_symbolication
+ ready_pattern: 'gRPC server listening on *'
+ groups:
+ layer: Product services
+ tech: Rust
+
embedding-worker:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 2759d77cb700..b468c712c173 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -110,7 +110,12 @@ case "$RS_SVC" in
;;
cymbal)
- export RUST_LOG=debug,rdkafka=warn
+ # Only cymbal crates at debug; everything else at info to keep the dev
+ # log readable. rdkafka stays explicitly at warn because its info-level
+ # output is still noisy. Unconditional export — flox activate exports its
+ # own RUST_LOG, so a conditional default would silently inherit that and
+ # match no cymbal modules.
+ export RUST_LOG=info,cymbal=debug,cymbal_resolution=debug,cymbal_proto=debug,rdkafka=warn
export RUST_BACKTRACE=1
export OBJECT_STORAGE_BUCKET=posthog
export FRAME_CACHE_TTL_SECONDS=1
@@ -124,6 +129,49 @@ case "$RS_SVC" in
export ISSUE_BUCKETS_REDIS_URL="$DEFAULT_REDIS"
export SIGNALS_API_BASE_URL="${SIGNALS_API_BASE_URL:-http://localhost:8000}" # Used to emit signals, via the internal API
export INTERNAL_API_SECRET="${INTERNAL_API_SECRET:-posthog123}"
+ # Route exception resolution through the local cymbal-resolution pod so
+ # the new gRPC seam is exercised end-to-end during dev. Flip
+ # CYMBAL_REMOTE_RESOLUTION_ENABLED=false to fall back to inline local
+ # resolution if cymbal-resolution isn't running.
+ export CYMBAL_REMOTE_RESOLUTION_ENABLED="${CYMBAL_REMOTE_RESOLUTION_ENABLED:-true}"
+ # Production defaults to SAMPLE_RATE=0.0 so flipping ENABLED is a no-op
+ # until rollout is ramped explicitly. In dev we want every event to
+ # exercise the remote path so the seam is actually tested.
+ export CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE="${CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE:-1.0}"
+ export CYMBAL_REMOTE_RESOLUTION_HOST="${CYMBAL_REMOTE_RESOLUTION_HOST:-127.0.0.1}"
+ export CYMBAL_REMOTE_RESOLUTION_PORT="${CYMBAL_REMOTE_RESOLUTION_PORT:-50061}"
+ # Keep cadence tight on the dev box so routing reacts quickly to
+ # whatever load you induce by hand.
+ export CYMBAL_REMOTE_RESOLUTION_DNS_REFRESH_SECS="${CYMBAL_REMOTE_RESOLUTION_DNS_REFRESH_SECS:-5}"
+ export CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_TICK_HINT_MS="${CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_TICK_HINT_MS:-500}"
+ ;;
+
+ cymbal-resolution)
+ # Symbol-resolution service that cymbal offloads to via cymbal.resolution.v1.
+ # Uses cymbal::app_context::build_symbol_resolver which only connects to
+ # Postgres and S3 — NOT Kafka, NOT Redis, NOT signals. That's why this
+ # block is so much narrower than the cymbal block: anything cymbal needs
+ # for the fingerprinting / issue path is genuinely irrelevant here.
+ # Only cymbal crates at debug; everything else at info. Unconditional
+ # export — flox activate exports its own RUST_LOG, so a conditional
+ # default would silently inherit that and match no cymbal modules.
+ export RUST_LOG=info,cymbal=debug,cymbal_resolution=debug,cymbal_proto=debug,rdkafka=warn
+ export RUST_BACKTRACE=1
+ # S3 / MinIO bucket for symbol-file fetches.
+ export OBJECT_STORAGE_BUCKET=posthog
+ # Frame cache tuning — values are intentionally tiny in dev so cache
+ # behaviour is observable without warming.
+ export FRAME_CACHE_TTL_SECONDS=1
+ export FRAME_RESULT_TTL_MINUTES=0
+ # Source-map / debug-file fetches may target cluster-internal hosts.
+ export ALLOW_INTERNAL_IPS="true"
+ # Listen on loopback only in dev. 50061 is the contract default; 9106 keeps
+ # us clear of the personhog-* metrics ports (9100-9105) and flags-consumer.
+ export GRPC_ADDRESS="${GRPC_ADDRESS:-127.0.0.1:50061}"
+ export METRICS_PORT="${METRICS_PORT:-9106}"
+ export INTERNAL_API_SECRET="${INTERNAL_API_SECRET:-posthog123}"
+ # Match the dev cymbal cadence so the load bus updates often.
+ export SUBSCRIBE_TICK_INTERVAL_MS="${SUBSCRIBE_TICK_INTERVAL_MS:-500}"
;;
embedding-worker)
diff --git a/proto/README.md b/proto/README.md
index 4b644981b95a..4b6eccf5db5a 100644
--- a/proto/README.md
+++ b/proto/README.md
@@ -7,6 +7,8 @@ Language-agnostic protobuf definitions for PostHog services.
```text
proto/
├── buf.yaml
+├── cymbal/ # Cymbal internal services
+│ └── resolution/v1/ # Exception-level symbol resolution
├── kafka_assigner/ # Kafka partition assignment
└── personhog/ # Person data service
├── types/v1/
@@ -18,6 +20,7 @@ proto/
| Proto | Rust | Python |
| ----------------- | -------------------------------------------- | -------------------------------------------------------- |
+| `cymbal/` | `rust/cymbal-proto` (auto via tonic) | — |
| `personhog/` | `rust/personhog-proto` (auto via tonic) | `posthog/personhog_client/proto/generated/` (checked in) |
| `kafka_assigner/` | `rust/kafka-assigner-proto` (auto via tonic) | — |
diff --git a/proto/cymbal/resolution/v1/resolution.proto b/proto/cymbal/resolution/v1/resolution.proto
new file mode 100644
index 000000000000..1009a5bf0ec7
--- /dev/null
+++ b/proto/cymbal/resolution/v1/resolution.proto
@@ -0,0 +1,122 @@
+syntax = "proto3";
+package cymbal.resolution.v1;
+
+// CymbalResolution is the internal API used by cymbal to offload symbol
+// resolution work. Cymbal remains the owner of HTTP /process ingestion,
+// grouping, issue linking, suppression, alerting, and final response shaping.
+//
+// Connection model
+// ----------------
+// * Resolve is a bidirectional stream of independent exception-level items.
+// Each ResolveItem carries a per-stream id that is echoed on exactly one
+// ResolveOutcome. Retry outcomes are caller-side reroute/backoff signals.
+// * Subscribe is a long-lived server stream of LoadEvent messages emitted on a
+// periodic tick. Callers use the latest LoadEvent for routing decisions.
+service CymbalResolution {
+ // Resolve resolves exception-level symbol-resolution items. The server admits
+ // each item independently and streams outcomes as they complete.
+ rpc Resolve(stream ResolveItem) returns (stream ResolveOutcome);
+
+ // Subscribe opens a long-lived freshness/draining stream for one server instance.
+ rpc Subscribe(SubscribeRequest) returns (stream LoadEvent);
+}
+
+// ResolveItem is one exception-level symbol-resolution request. The id is a
+// per-stream correlation token chosen by the caller and echoed by the server.
+message ResolveItem {
+ uint64 id = 1;
+ int32 team_id = 2;
+ // Serialized rust/cymbal Exception before frame and exception remapping.
+ bytes exception_json = 3;
+ // Serialized resolution metadata. The current convention is JSON bytes with
+ // resolver-specific keys such as `apple_debug_images_json`.
+ bytes metadata = 4;
+ // Deadline for this logical exception in milliseconds. The server may shed
+ // stale items instead of starting work it cannot return in time.
+ uint32 deadline_ms = 5;
+}
+
+// ResolveOutcome is the terminal server outcome for one ResolveItem id.
+message ResolveOutcome {
+ uint64 id = 1;
+
+ oneof result {
+ Done done = 2;
+ Error error = 3;
+ Retry retry = 4;
+ }
+}
+
+// Done means the item completed and contains the resolved exception payload.
+message Done {
+ // Serialized rust/cymbal Exception after frame resolution and exception
+ // remapping. It replaces only the submitted exception item, not the full
+ // event or exception list.
+ bytes resolved_exception_json = 1;
+}
+
+// Error is a terminal item failure. The kind enum is the shared control-flow
+// surface; callers should not parse message text.
+message Error {
+ ErrorKind kind = 1;
+ string message = 2;
+ // Optional structured diagnostics. Implementations must not require callers
+ // to understand this field for control flow.
+ bytes details_json = 3;
+}
+
+enum ErrorKind {
+ ERROR_KIND_UNSPECIFIED = 0;
+ // The request payload or metadata did not match the cymbal-resolution wire
+ // contract. This is an internal caller/protocol error.
+ ERROR_KIND_INVALID_PAYLOAD = 1;
+ // The request was well-formed, but user-provided symbol data or stack data
+ // is bad and should be sent to DLQ rather than retried.
+ ERROR_KIND_POISON = 2;
+ // The handler encountered an unexpected internal error while resolving.
+ ERROR_KIND_UNHANDLED = 3;
+ // The pod is resource exhausted. Callers should reroute/back off using
+ // overload policy rather than generic retry policy.
+ ERROR_KIND_OVERLOADED = 4;
+}
+
+// Retry means the service did not complete the item and cymbal may retry or
+// reroute it according to caller-side policy. Overload has a dedicated variant
+// so resource exhaustion can use a separate caller policy.
+message Retry {
+ string code = 1;
+ string message = 2;
+ // Optional server hint in milliseconds. A zero value means no hint.
+ uint32 retry_after_ms = 3;
+}
+
+// SubscribeRequest opens a long-lived stream of LoadEvent ticks. v1 is
+// intentionally tiny: callers describe themselves for logs and may hint a
+// cadence, but the server has the final say so a misbehaving caller cannot
+// induce excess work.
+message SubscribeRequest {
+ // Free-form identifier for the subscribing process. Used in server logs and
+ // metrics labels; not interpreted otherwise. Recommended format is
+ // `<service>/<instance>`.
+ string subscriber_id = 1;
+ // Caller-preferred tick cadence, in milliseconds. The server may clamp this
+ // to a safe range; a zero value means "use the server default". This is a
+ // hint and not a contract.
+ uint32 tick_hint_ms = 2;
+}
+
+// LoadEvent is one freshness/draining tick. Emitted independently of any
+// Resolve work. Callers should treat the latest LoadEvent per endpoint as the
+// routing-relevant snapshot.
+message LoadEvent {
+ // Stable identity of the cymbal-resolution pod that emitted this event.
+ string service_instance_id = 1;
+ // True when the pod is preparing to shut down. Routers should stop sending
+ // new work; in-flight requests are still served.
+ bool draining = 3;
+ // Monotonic per-subscription sequence assigned by the server, starting at 1
+ // for the first tick of each Subscribe stream.
+ uint64 sequence = 4;
+ // Optional short human-readable note. Not interpreted by the router.
+ string message = 5;
+}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 02d2f134a97b..5a81a0e97a15 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2639,6 +2639,8 @@ dependencies = [
"common-metrics",
"common-redis",
"common-types",
+ "cymbal-proto",
+ "cymbal-resolution",
"envconfig",
"futures",
"health",
@@ -2651,6 +2653,7 @@ dependencies = [
"posthog-rs 0.3.7",
"posthog-symbol-data",
"proguard",
+ "rand 0.8.5",
"rdkafka",
"regex",
"reqwest 0.12.28",
@@ -2664,6 +2667,8 @@ dependencies = [
"thiserror 2.0.18",
"tiktoken-rs",
"tokio",
+ "tokio-stream",
+ "tonic 0.12.3",
"tower 0.4.13",
"tracing",
"tracing-subscriber",
@@ -2671,6 +2676,41 @@ dependencies = [
"zip 4.6.1",
]
+[[package]]
+name = "cymbal-proto"
+version = "0.1.0"
+dependencies = [
+ "prost 0.13.5",
+ "tonic 0.12.3",
+ "tonic-build 0.12.3",
+]
+
+[[package]]
+name = "cymbal-resolution"
+version = "0.1.0"
+dependencies = [
+ "async-stream",
+ "async-trait",
+ "axum 0.7.9",
+ "common-alloc",
+ "common-metrics",
+ "cymbal",
+ "cymbal-proto",
+ "envconfig",
+ "futures",
+ "metrics",
+ "personhog-common",
+ "posthog-rs 0.3.7",
+ "serde_json",
+ "subtle",
+ "tokio",
+ "tokio-stream",
+ "tonic 0.12.3",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
[[package]]
name = "darling"
version = "0.20.11"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index b94130bb8830..0667eaeff245 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -35,6 +35,8 @@ members = [
"cyclotron-node",
"cyclotron-janitor",
"cymbal",
+ "cymbal-proto",
+ "cymbal-resolution",
"embedding-worker",
"common/geoip",
"common/hogvm",
@@ -95,6 +97,7 @@ async-compression = { version = "0.4", features = [
"brotli",
"zstd",
] }
+async-stream = "0.3"
async-trait = "0.1.74"
axum = { version = "0.7.5", features = ["http2", "macros", "matched-path"] }
axum-client-ip = "0.6.0"
diff --git a/rust/cymbal-proto/Cargo.toml b/rust/cymbal-proto/Cargo.toml
new file mode 100644
index 000000000000..cf68987e1311
--- /dev/null
+++ b/rust/cymbal-proto/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "cymbal-proto"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+prost = { workspace = true }
+tonic = { workspace = true }
+
+[build-dependencies]
+tonic-build = { workspace = true }
+
+[package.metadata.cargo-shear]
+ignored = ["prost"]
+
+[lints]
+workspace = true
diff --git a/rust/cymbal-proto/README.md b/rust/cymbal-proto/README.md
new file mode 100644
index 000000000000..e9de2c82f0a7
--- /dev/null
+++ b/rust/cymbal-proto/README.md
@@ -0,0 +1,14 @@
+# cymbal-proto
+
+Rust bindings for Cymbal internal gRPC APIs.
+
+Proto definitions live in the top-level [`/proto/cymbal`](/proto/cymbal) directory.
+The first package is `cymbal.resolution.v1`, a resolution-specific API for offloading exception-level symbol resolution from `rust/cymbal` to the planned `rust/cymbal-resolution` service.
+
+## Building
+
+```bash
+cargo build -p cymbal-proto
+```
+
+Rust bindings regenerate automatically through `tonic-build` when the crate builds.
diff --git a/rust/cymbal-proto/build.rs b/rust/cymbal-proto/build.rs
new file mode 100644
index 000000000000..0d2385a3e4d8
--- /dev/null
+++ b/rust/cymbal-proto/build.rs
@@ -0,0 +1,14 @@
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let proto_root = std::env::var("PROTO_ROOT").unwrap_or_else(|_| "../../proto".to_string());
+
+ tonic_build::configure()
+ .build_server(true)
+ .build_client(true)
+ .compile_protos(
+ &[format!(
+ "{proto_root}/cymbal/resolution/v1/resolution.proto"
+ )],
+ &[proto_root],
+ )?;
+ Ok(())
+}
diff --git a/rust/cymbal-proto/src/lib.rs b/rust/cymbal-proto/src/lib.rs
new file mode 100644
index 000000000000..658aea2282b6
--- /dev/null
+++ b/rust/cymbal-proto/src/lib.rs
@@ -0,0 +1,7 @@
+pub mod cymbal {
+ pub mod resolution {
+ pub mod v1 {
+ tonic::include_proto!("cymbal.resolution.v1");
+ }
+ }
+}
diff --git a/rust/cymbal-proto/tests/contract.rs b/rust/cymbal-proto/tests/contract.rs
new file mode 100644
index 000000000000..3f0264082363
--- /dev/null
+++ b/rust/cymbal-proto/tests/contract.rs
@@ -0,0 +1,121 @@
+use cymbal_proto::cymbal::resolution::v1::{
+ resolve_outcome, Done, Error, ErrorKind, LoadEvent, ResolveItem, ResolveOutcome, Retry,
+ SubscribeRequest,
+};
+use prost::Message;
+
+#[test]
+fn resolve_item_serializes_exception_payload_with_correlation_id_and_deadline() {
+ let item = ResolveItem {
+ id: 7,
+ team_id: 42,
+ exception_json: br#"{"type":"Error"}"#.to_vec(),
+ metadata: br#"{"apple_debug_images_json":[]}"#.to_vec(),
+ deadline_ms: 1_500,
+ };
+
+ let decoded = ResolveItem::decode(item.encode_to_vec().as_slice()).unwrap();
+
+ assert_eq!(decoded.id, 7);
+ assert_eq!(decoded.team_id, 42);
+ assert_eq!(decoded.exception_json, br#"{"type":"Error"}"#);
+ assert_eq!(decoded.metadata, br#"{"apple_debug_images_json":[]}"#);
+ assert_eq!(decoded.deadline_ms, 1_500);
+}
+
+#[test]
+fn resolve_outcome_echoes_id_and_carries_done_error_or_retry() {
+ let outcomes = [
+ ResolveOutcome {
+ id: 1,
+ result: Some(resolve_outcome::Result::Done(Done {
+ resolved_exception_json: br#"{"type":"ResolvedError"}"#.to_vec(),
+ })),
+ },
+ ResolveOutcome {
+ id: 2,
+ result: Some(resolve_outcome::Result::Error(Error {
+ kind: ErrorKind::InvalidPayload as i32,
+ message: "exception_json could not be decoded".to_string(),
+ details_json: b"{}".to_vec(),
+ })),
+ },
+ ResolveOutcome {
+ id: 3,
+ result: Some(resolve_outcome::Result::Retry(Retry {
+ code: "transient".to_string(),
+ message: "try again later".to_string(),
+ retry_after_ms: 25,
+ })),
+ },
+ ResolveOutcome {
+ id: 4,
+ result: Some(resolve_outcome::Result::Error(Error {
+ kind: ErrorKind::Overloaded as i32,
+ message: "server overloaded".to_string(),
+ details_json: b"{}".to_vec(),
+ })),
+ },
+ ];
+
+ let decoded: Vec<ResolveOutcome> = outcomes
+ .iter()
+ .map(|outcome| ResolveOutcome::decode(outcome.encode_to_vec().as_slice()).unwrap())
+ .collect();
+
+ assert!(matches!(
+ decoded[0].result,
+ Some(resolve_outcome::Result::Done(_))
+ ));
+ assert!(matches!(
+ decoded[1].result,
+ Some(resolve_outcome::Result::Error(_))
+ ));
+ assert!(matches!(
+ decoded[2].result,
+ Some(resolve_outcome::Result::Retry(Retry {
+ retry_after_ms: 25,
+ ..
+ }))
+ ));
+ assert!(matches!(
+ decoded[3].result,
+ Some(resolve_outcome::Result::Error(Error {
+ kind,
+ ..
+ })) if kind == ErrorKind::Overloaded as i32
+ ));
+ assert_eq!(
+ decoded.iter().map(|outcome| outcome.id).collect::<Vec<_>>(),
+ vec![1, 2, 3, 4]
+ );
+}
+
+#[test]
+fn subscribe_request_round_trips_caller_hint_and_identity() {
+ let request = SubscribeRequest {
+ subscriber_id: "cymbal/pod-1".to_string(),
+ tick_hint_ms: 500,
+ };
+
+ let decoded = SubscribeRequest::decode(request.encode_to_vec().as_slice()).unwrap();
+
+ assert_eq!(decoded.subscriber_id, "cymbal/pod-1");
+ assert_eq!(decoded.tick_hint_ms, 500);
+}
+
+#[test]
+fn load_event_carries_routing_relevant_state_with_sequence() {
+ let event = LoadEvent {
+ service_instance_id: "resolver-a".to_string(),
+ draining: false,
+ sequence: 7,
+ message: "ok".to_string(),
+ };
+
+ 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!(!decoded.draining);
+}
diff --git a/rust/cymbal-resolution/Cargo.toml b/rust/cymbal-resolution/Cargo.toml
new file mode 100644
index 000000000000..59c463f4f25b
--- /dev/null
+++ b/rust/cymbal-resolution/Cargo.toml
@@ -0,0 +1,35 @@
+[package]
+name = "cymbal-resolution"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+cymbal = { path = "../cymbal" }
+cymbal-proto = { path = "../cymbal-proto" }
+personhog-common = { path = "../personhog-common" }
+common-alloc = { path = "../common/alloc" }
+common-metrics = { path = "../common/metrics" }
+
+async-stream = { workspace = true }
+axum = { workspace = true }
+envconfig = { workspace = true }
+futures = { workspace = true }
+metrics = { workspace = true }
+posthog-rs = { workspace = true }
+serde_json = { workspace = true }
+subtle = "2.6"
+tokio = { workspace = true }
+tokio-stream = "0.1"
+tonic = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+async-trait = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tokio-stream = "0.1"
+
+[lints]
+workspace = true
diff --git a/rust/cymbal-resolution/README.md b/rust/cymbal-resolution/README.md
new file mode 100644
index 000000000000..ff80276e68e8
--- /dev/null
+++ b/rust/cymbal-resolution/README.md
@@ -0,0 +1,217 @@
+# cymbal-resolution
+
+gRPC service that owns exception-level symbol resolution for PostHog error tracking.
+It speaks `cymbal.resolution.v1` and is used by the [`cymbal`](../cymbal) ingestion binary when remote resolution is enabled.
+
+## Architecture
+
+```text
+ ┌────────────────────────────────────────────────────┐
+events ──HTTP─────▶│ cymbal │
+ │ /process pipeline │
+ │ │
+ │ ┌──────────────────────────────────────────────┐ │
+ │ │ ResolutionStage │ │
+ │ │ - partitions events into local/remote │ │
+ │ │ - builds ResolveItems at resolution time │ │
+ │ └──────────────────────┬───────────────────────┘ │
+ │ │ sampled remote events │
+ │ ┌──────────────────────▼───────────────────────┐ │
+ │ │ EndpointPool │ │
+ │ │ - DNS-discovered endpoints │ │
+ │ │ - per-endpoint Resolve mux │ │
+ │ │ - Subscribe freshness snapshots │ │
+ │ └──────────────┬─────────────────┬─────────────┘ │
+ └─────────────────┼─────────────────┼────────────────┘
+ │ │
+ │ Resolve │ Subscribe
+ │ long-lived bidi │ long-lived stream
+ │ stream carrying │ carrying LoadEvent
+ │ ResolveItem / │ ticks
+ │ ResolveOutcome │
+ ▼ ▼
+ ┌────────────────────────────────────────────────────┐
+ │ cymbal-resolution │
+ │ │
+ │ Resolve handler │
+ │ - admits each item independently │
+ │ - emits one terminal outcome per item │
+ │ │
+ │ Subscribe handler │
+ │ - emits freshness/draining ticks │
+ └────────────────────────────────────────────────────┘
+```
+
+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`.
+- **`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:
+
+- `ERROR_KIND_INVALID_PAYLOAD` means the exception payload or `metadata` bytes do not match the wire convention.
+- `ERROR_KIND_POISON` is reserved for well-formed user-provided symbol/stack data that should not be retried.
+- `ERROR_KIND_UNHANDLED` is an unexpected resolver failure.
+- `ERROR_KIND_OVERLOADED` is result-only backpressure. Callers reroute the item with overload-specific backoff.
+
+The proto lives at [`proto/cymbal/resolution/v1/resolution.proto`](../../proto/cymbal/resolution/v1/resolution.proto).
+
+## Rollout model
+
+Remote resolution is opt-in on the cymbal side. There is intentionally **no silent local fallback** for events sampled into the remote path: when the pool cannot satisfy a sampled remote item, cymbal surfaces an `UnhandledError` for that event so the failure is visible rather than masked. Events not selected by `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE` are not remote attempts; they run through the inline local exception/frame resolvers.
+
+| Mode | Cymbal env vars | Resolution path |
+| ---- | --------------- | --------------- |
+| Local | `CYMBAL_REMOTE_RESOLUTION_ENABLED=false` (default) | Inline local resolver inside `cymbal` |
+| Sampled remote | `CYMBAL_REMOTE_RESOLUTION_ENABLED=true`, sampled by `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE` | gRPC to the `cymbal-resolution` pool, no fallback |
+| Unsampled local | `CYMBAL_REMOTE_RESOLUTION_ENABLED=true`, not sampled by `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE` | Inline local resolver inside `cymbal` |
+
+### Enabling remote mode
+
+1. Deploy `cymbal-resolution` pods behind a headless Kubernetes service so each pod is reachable by IP. `cymbal` resolves the service hostname via DNS and opens one channel per returned address.
+2. Confirm the pods are serving:
+ - `/_liveness` returns `ok`
+ - `/_readiness` returns `ok`
+ - `cymbal_remote_resolution_pool_size` becomes non-zero on cymbal pods once they are pointed at the service.
+3. Set on `cymbal` pods:
+ - `CYMBAL_REMOTE_RESOLUTION_ENABLED=true`
+ - `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE=<0.0..=1.0>` (defaults to `0.0`, so enabling alone routes no traffic)
+ - `CYMBAL_REMOTE_RESOLUTION_HOST=<service-hostname>`
+ - `CYMBAL_REMOTE_RESOLUTION_PORT=50061` (default)
+4. Roll cymbal pods. Startup eagerly resolves DNS and fails loudly if the host is empty, no addresses come back, or no endpoint produces a fresh non-draining `LoadEvent` during the readiness window.
+
+### 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.
+
+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.
+
+### Disabling / rolling back
+
+Set `CYMBAL_REMOTE_RESOLUTION_ENABLED=false` on the cymbal pods and roll. That fully reverts to local resolution; no data-plane state needs to be flushed and the `cymbal-resolution` pods can keep running without harm.
+
+For a partial rollback, lower `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE`. The decision is deterministic by `(team_id, event_uuid)`, so the same event keeps the same local/remote decision across retries, pods, and process restarts.
+
+### Compatibility with the Node error-tracking consumer
+
+The Node consumer still talks only to cymbal's HTTP `POST /process` endpoint. Cymbal preserves the response array shape and input ordering after internal remote resolution, so Node-side request chunking by HTTP body size remains valid and no generated type changes are needed. See [`cymbal/docs/compatibility.md`](../cymbal/docs/compatibility.md).
+
+## Configuration
+
+### Cymbal client (`cymbal` binary)
+
+All variables are prefixed `CYMBAL_REMOTE_RESOLUTION_` and live on `cymbal::config::Config`.
+
+| Env var | Default | Purpose |
+| ------- | ------- | ------- |
+| `CYMBAL_REMOTE_RESOLUTION_ENABLED` | `false` | Master switch. `true` routes sampled exception resolution through the remote pool. |
+| `CYMBAL_REMOTE_RESOLUTION_HOST` | _empty_ | Service hostname resolved via DNS. Required when enabled; empty value fails boot. |
+| `CYMBAL_REMOTE_RESOLUTION_PORT` | `50061` | gRPC port the pods listen on. Must match the server-side `GRPC_ADDRESS` port. |
+| `INTERNAL_API_SECRET` | _empty_ | Shared secret sent as `X-Internal-Api-Secret` on every `Resolve` and `Subscribe` RPC. Required when remote mode is enabled. |
+| `CYMBAL_REMOTE_RESOLUTION_DNS_REFRESH_SECS` | `30` | How often DNS is re-resolved and the pool reconciled. |
+| `CYMBAL_REMOTE_RESOLUTION_DEADLINE_MS` | `15000` | Shared per-event remote deadline used by all item reroutes. |
+| `CYMBAL_REMOTE_RESOLUTION_CONNECT_TIMEOUT_MS` | `1000` | Per-endpoint TCP/HTTP2 connect timeout. |
+| `CYMBAL_REMOTE_RESOLUTION_MAX_RETRIES` | `2` | Caller-side reroutes after transport, overload, or `Retry` outcomes. |
+| `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_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. |
+
+### Cymbal-resolution server (`cymbal-resolution` binary)
+
+| Env var | Default | Purpose |
+| ------- | ------- | ------- |
+| `GRPC_ADDRESS` | `0.0.0.0:50061` | Bind address for the gRPC server. |
+| `METRICS_PORT` | `9101` | HTTP port for `/_liveness`, `/_readiness`, and `/metrics`. |
+| `INTERNAL_API_SECRET` | _empty_ | Shared secret required as `X-Internal-Api-Secret` metadata on every gRPC request. Empty configuration rejects all RPCs. |
+| `MAX_CONCURRENT_REQUESTS` | `256` | Hard cap on in-flight gRPC streams. Excess returns `UNAVAILABLE` from the gRPC load-shed layer. `0` disables the cap. |
+| `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_MIN_TICK_MS` | `100` | Lower bound for the Subscribe tick cadence. |
+| `SUBSCRIBE_MAX_TICK_MS` | `10000` | Upper bound for the Subscribe tick cadence. |
+
+The server inherits the narrow subset of cymbal's env-var surface needed by `build_symbol_resolver` and internal gRPC authentication: `INTERNAL_API_SECRET`, Postgres, object storage, symbol-store cache/resolver tuning, and outbound HTTP controls. It does not connect to Kafka, Redis, or the signals API.
+
+Shared-secret callers are service-scoped today, so authenticated cymbal pods are permitted to resolve all teams. If future callers carry a team-scoped identity, the `Resolve` handler must reject any `ResolveItem.team_id` outside the caller's allowed team set before scheduling resolution work.
+
+## Operator guidance
+
+### Health and discovery endpoints
+
+| Surface | Where | Notes |
+| ------- | ----- | ----- |
+| Liveness | `GET :{METRICS_PORT}/_liveness` | Static `ok`. Use to detect crashed pods. |
+| Readiness | `GET :{METRICS_PORT}/_readiness` | Static `ok` today; safe to flip to a real probe later. |
+| Prometheus metrics | `GET :{METRICS_PORT}/metrics` | Includes `cymbal_remote_resolution_*` and generic `grpc_server_*`. |
+| gRPC | `:{GRPC_ADDRESS}` `cymbal.resolution.v1.CymbalResolution` | Headless service DNS name → one channel per pod. |
+
+### Reading the metrics
+
+These metric names are exported by the cymbal client unless noted. Definitions live in [`cymbal/src/metric_consts.rs`](../cymbal/src/metric_consts.rs) and the server's Resolve/LoadMonitor modules.
+
+- **Rollout decisions**: `cymbal_remote_resolution_sampling_total{decision="remote"|"local"}`. `local` during a partial rollout is expected and is not fallback.
+- **Item attempts and latency**: `cymbal_remote_resolution_requests_total{outcome, reason?}` and `cymbal_remote_resolution_latency_ms`. The counter is emitted on logical item attempts; `reason` is only a bounded transport status tag.
+- **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.
+- **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.
+
+### Failure interpretation cheat sheet
+
+| Symptom | Likely cause | Suggested response |
+| ------- | ------------ | ------------------ |
+| `pool_empty` spikes after cymbal startup | DNS refresh removed every endpoint, Subscribe has not produced fresh snapshots, or every endpoint reports draining | Inspect the `reason` label (`no_endpoints`, `no_fresh_load_snapshots`, `all_endpoints_draining`); startup fails for these states while remote resolution is enabled. |
+| `sampling_total{decision="local"}` rises while remote errors stay flat | Expected partial rollout or lower sample rate | No action unless the configured sample rate is wrong. |
+| `transport_retry{reason="unavailable"}` + `grpc_server_load_shed_total` | Server is at `MAX_CONCURRENT_REQUESTS` | Scale server pods or raise the cap after capacity-checking. |
+| `error_kinds_total{kind="overloaded"}` + rising reroute depth | Item-level overload backpressure | Scale server pods, tune item concurrency, or lower sample rate. |
+| `endpoint_admission_rejections_total{reason="queue_full"}` | Local mux queue saturated before the item reached gRPC | Scale endpoints or increase the mux queue only after checking memory. |
+| `transport_retry{reason="deadline_exceeded"}` with low load | Caller-side deadline shorter than worst-case resolution | Raise `CYMBAL_REMOTE_RESOLUTION_DEADLINE_MS`. |
+| `error_kinds_total{kind="invalid_payload"}` | Wire-format or metadata mismatch | Check deploy skew and the metadata JSON convention. |
+| `requests_total{outcome="exhausted"}` sustained | Pool unhealthy or reroute budget too small for current failures | Investigate server health; consider rollback. |
+| `pool_size` drops on a stable cluster | DNS refresh evicting endpoints | Confirm the headless service still resolves; check for pod restarts. |
+| `pool_empty` with `pool_size > 0` | Snapshot-required routing excluded every pod | Inspect the `reason` label plus `load_subscriptions_total{outcome="reconnect"}` and Subscribe logs. |
+
+### Logs to look for
+
+`cymbal-resolution` server-side warnings to watch:
+
+- `unhandled error during resolution` — per-item failure, surfaces as `ERROR_KIND_UNHANDLED`.
+- `rejecting item with invalid payload` — malformed exception JSON or `metadata`; surfaces as `ERROR_KIND_INVALID_PAYLOAD`.
+- `limiter closed mid-request, asking caller to retry` — symbol-resolution limiter was closed, currently expected only during shutdown/tests.
+- `item deadline expired` — the item deadline elapsed before work completed; surfaces as `ERROR_KIND_OVERLOADED`.
+
+Client-side warnings on the cymbal pods:
+
+- `remote resolution dns refresh failed` — DNS refresh task swallowed an error and will retry next tick.
+- `remote resolution transport-level retry` — caller-side transport retry classification, tagged with a bounded reason.
+- `remote resolution returned item overload` — an overloaded result was escalated into a per-item reroute.
+- `remote resolution outcome id did not match submitted item` — the mux ignored an outcome for another id.
+
+Logs intentionally do not include raw routing keys as metric labels. Routing keys can contain symbol-set references, so cymbal uses bounded counters/histograms and endpoint labels only where the endpoint set is bounded by discovery.
+
+## Code organization
+
+- **Service (`cymbal-resolution`)**
+ - [`src/main.rs`](src/main.rs) — process bootstrap, gRPC + metrics servers, layer stack (`GrpcMetricsLayer`, `GrpcLoadShedLayer`).
+ - [`src/config.rs`](src/config.rs) — server `Config` (env-driven).
+ - [`src/app_context.rs`](src/app_context.rs) — constructs an `AppContext` by reusing cymbal's `AppContext::from_config` to materialize a `SymbolResolver`, then dedicates a semaphore for symbol-resolution concurrency.
+ - [`src/service.rs`](src/service.rs) and [`src/service/resolve.rs`](src/service/resolve.rs) — gRPC handlers and `ErrorKind` mapping.
+- **Client (`cymbal/src/stages/resolution/remote/`)**
+ - `config.rs` — `RemoteResolutionConfig`.
+ - `dns.rs` — `DnsResolver` trait + tokio-backed default.
+ - `pool.rs` — `EndpointPool`, DNS refresh, endpoint lifecycle, Subscribe freshness, and mux ownership.
+ - `mux.rs` — per-endpoint bidirectional Resolve stream, waiter demux, local admission, and stream-break cleanup.
+ - `subscription.rs` — long-lived per-endpoint Subscribe task.
+ - `resolver.rs` — event partitioning, work-item construction, per-exception reroute, and response reassembly.
+- **Proto contract** — [`proto/cymbal/resolution/v1/resolution.proto`](../../proto/cymbal/resolution/v1/resolution.proto).
+
+## Tests
+
+- `cargo test -p cymbal-proto` — proto contract round-trips for `ResolveItem`, `ResolveOutcome`, `ErrorKind`, `Retry`, and `LoadEvent`.
+- `cargo test -p cymbal-resolution` — service-level bidirectional streaming, accounting, overload behavior, invalid payload handling, unhandled errors, and Subscribe freshness/draining coverage.
+- `cargo test -p cymbal` — client-side endpoint pool, mux, integration tests against in-process tonic stubs, end-to-end Subscribe routing, and parity vs local mode.
diff --git a/rust/cymbal-resolution/src/app_context.rs b/rust/cymbal-resolution/src/app_context.rs
new file mode 100644
index 000000000000..1316bf075c04
--- /dev/null
+++ b/rust/cymbal-resolution/src/app_context.rs
@@ -0,0 +1,67 @@
+use std::sync::Arc;
+
+use cymbal::app_context::build_symbol_resolver;
+use cymbal::config::Config as CymbalConfig;
+use cymbal::error::UnhandledError;
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use tokio::sync::Semaphore;
+
+use crate::config::Config;
+use crate::load_monitor::LoadMonitor;
+
+/// Process-wide handles required to serve `cymbal.resolution.v1`.
+///
+/// v1 reuses cymbal's symbol-resolution stack (catalog + frame cache + PG-
+/// backed resolved-frame reuse) via [`build_symbol_resolver`]. That builder
+/// only connects to Postgres and S3 — Kafka producers, Redis, the issue
+/// cache, signals, and the remote-resolution pool are intentionally NOT
+/// started here. cymbal-resolution owns symbol resolution only.
+pub struct AppContext {
+ pub symbol_resolver: Arc<dyn SymbolResolver>,
+ pub symbol_resolution_limiter: Arc<Semaphore>,
+ pub load_monitor: LoadMonitor,
+ pub config: Config,
+ pub service_instance_id: String,
+}
+
+impl AppContext {
+ pub async fn from_config(
+ config: Config,
+ cymbal_config: &CymbalConfig,
+ ) -> Result<Self, UnhandledError> {
+ let symbol_resolver = build_symbol_resolver(cymbal_config).await?;
+ Ok(Self::from_resolver(
+ config,
+ symbol_resolver,
+ // Use a dedicated limiter for this service so its concurrency
+ // surface is independent of any cymbal-side configuration.
+ None,
+ ))
+ }
+
+ /// Constructor for tests and integrations that already own a resolver. The
+ /// optional limiter override is used by tests that need to force the
+ /// permit acquisition path; production callers pass `None`.
+ pub fn from_resolver(
+ config: Config,
+ symbol_resolver: Arc<dyn SymbolResolver>,
+ symbol_resolution_limiter: Option<Arc<Semaphore>>,
+ ) -> Self {
+ let symbol_resolution_limiter = symbol_resolution_limiter.unwrap_or_else(|| {
+ Arc::new(Semaphore::new(config.symbol_resolution_concurrency.max(1)))
+ });
+ let max_item_concurrency = config.max_item_concurrency.max(1);
+ let load_monitor = LoadMonitor::new(max_item_concurrency as u32);
+ let service_instance_id = config
+ .service_instance_id
+ .clone()
+ .unwrap_or_else(|| uuid::Uuid::now_v7().to_string());
+ Self {
+ symbol_resolver,
+ symbol_resolution_limiter,
+ load_monitor,
+ config,
+ service_instance_id,
+ }
+ }
+}
diff --git a/rust/cymbal-resolution/src/auth.rs b/rust/cymbal-resolution/src/auth.rs
new file mode 100644
index 000000000000..d542ddef7025
--- /dev/null
+++ b/rust/cymbal-resolution/src/auth.rs
@@ -0,0 +1,108 @@
+use subtle::ConstantTimeEq;
+use tonic::{Request, Status};
+
+pub const INTERNAL_API_SECRET_HEADER: &str = "x-internal-api-secret";
+
+#[derive(Clone)]
+pub struct InternalApiSecretInterceptor {
+ expected_secret: String,
+}
+
+impl InternalApiSecretInterceptor {
+ pub fn new(expected_secret: impl Into<String>) -> Self {
+ Self {
+ expected_secret: expected_secret.into(),
+ }
+ }
+
+ #[allow(clippy::result_large_err)]
+ pub fn authenticate(&self, request: Request<()>) -> Result<Request<()>, Status> {
+ let expected_secret = self.expected_secret.trim();
+ if expected_secret.is_empty() {
+ return Err(Status::unauthenticated(
+ "internal API secret is not configured",
+ ));
+ }
+
+ let Some(provided_secret) = request.metadata().get(INTERNAL_API_SECRET_HEADER) else {
+ return Err(Status::unauthenticated("missing internal API secret"));
+ };
+
+ let provided_secret = provided_secret
+ .to_str()
+ .map_err(|_| Status::unauthenticated("invalid internal API secret"))?
+ .trim();
+
+ if provided_secret.is_empty() {
+ return Err(Status::unauthenticated("missing internal API secret"));
+ }
+
+ if provided_secret
+ .as_bytes()
+ .ct_eq(expected_secret.as_bytes())
+ .into()
+ {
+ Ok(request)
+ } else {
+ Err(Status::unauthenticated("invalid internal API secret"))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::str::FromStr;
+ use tonic::metadata::MetadataValue;
+ use tonic::Code;
+
+ fn request_with_secret(secret: &str) -> Request<()> {
+ let mut request = Request::new(());
+ request.metadata_mut().insert(
+ INTERNAL_API_SECRET_HEADER,
+ MetadataValue::from_str(secret).unwrap(),
+ );
+ request
+ }
+
+ #[test]
+ fn allows_matching_secret() {
+ let auth = InternalApiSecretInterceptor::new("test-secret");
+ assert!(auth
+ .authenticate(request_with_secret("test-secret"))
+ .is_ok());
+ }
+
+ #[test]
+ fn trims_configured_and_provided_secret() {
+ let auth = InternalApiSecretInterceptor::new(" test-secret\n");
+ assert!(auth
+ .authenticate(request_with_secret("test-secret "))
+ .is_ok());
+ }
+
+ #[test]
+ fn rejects_missing_secret() {
+ let auth = InternalApiSecretInterceptor::new("test-secret");
+ let err = auth.authenticate(Request::new(())).unwrap_err();
+ assert_eq!(err.code(), Code::Unauthenticated);
+ }
+
+ #[test]
+ fn rejects_mismatched_secret() {
+ let auth = InternalApiSecretInterceptor::new("test-secret");
+ let err = auth
+ .authenticate(request_with_secret("wrong-secret"))
+ .unwrap_err();
+ assert_eq!(err.code(), Code::Unauthenticated);
+ }
+
+ #[test]
+ fn rejects_when_not_configured() {
+ let auth = InternalApiSecretInterceptor::new("");
+ let err = auth
+ .authenticate(request_with_secret("test-secret"))
+ .unwrap_err();
+ assert_eq!(err.code(), Code::Unauthenticated);
+ }
+}
diff --git a/rust/cymbal-resolution/src/config.rs b/rust/cymbal-resolution/src/config.rs
new file mode 100644
index 000000000000..b0af30a6e034
--- /dev/null
+++ b/rust/cymbal-resolution/src/config.rs
@@ -0,0 +1,67 @@
+use std::net::SocketAddr;
+
+use envconfig::Envconfig;
+
+#[derive(Envconfig, Clone)]
+pub struct Config {
+ /// gRPC bind address for the cymbal.resolution.v1 server.
+ #[envconfig(from = "GRPC_ADDRESS", default = "0.0.0.0:50061")]
+ pub grpc_address: SocketAddr,
+
+ /// HTTP bind port for liveness, readiness, and Prometheus metrics.
+ #[envconfig(from = "METRICS_PORT", default = "9101")]
+ pub metrics_port: u16,
+
+ /// Shared secret required on every gRPC request via X-Internal-Api-Secret.
+ #[envconfig(from = "INTERNAL_API_SECRET", default = "")]
+ pub internal_api_secret: String,
+
+ /// Cap on concurrent gRPC requests accepted by the server before fast
+ /// load shedding kicks in. Beyond this, callers receive `UNAVAILABLE`
+ /// and retry against another pod — preferred over hidden queue growth
+ /// on the symbol-resolution semaphore. Zero disables the limit; the
+ /// non-zero default keeps fail-fast semantics by default.
+ #[envconfig(from = "MAX_CONCURRENT_REQUESTS", default = "256")]
+ pub max_concurrent_requests: usize,
+
+ /// Cap on concurrent symbol-resolution operations across all in-flight
+ /// requests. Reuses the same semantic as cymbal's
+ /// `SYMBOL_RESOLUTION_CONCURRENCY` knob. Items beyond this wait on the
+ /// internal semaphore until the request deadline; sustained pressure
+ /// surfaces as per-item `ErrorKind::Overloaded` outcomes when the limiter
+ /// is closed.
+ #[envconfig(from = "SYMBOL_RESOLUTION_CONCURRENCY", default = "64")]
+ pub symbol_resolution_concurrency: usize,
+
+ /// Process-wide cap on concurrent item (exception) processing across all
+ /// in-flight `Resolve` requests. Replaces the previous per-request
+ /// `REQUEST_ITEM_CONCURRENCY` so total item parallelism stays bounded
+ /// regardless of how many concurrent RPCs are open. Symbol work is
+ /// governed separately by `SYMBOL_RESOLUTION_CONCURRENCY`.
+ #[envconfig(from = "MAX_ITEM_CONCURRENCY", default = "64")]
+ pub max_item_concurrency: usize,
+
+ /// Service instance identifier surfaced to callers via `LoadEvent` on
+ /// the Subscribe stream. Defaults to a random uuid generated at boot
+ /// when not provided.
+ #[envconfig(from = "SERVICE_INSTANCE_ID")]
+ pub service_instance_id: Option<String>,
+
+ /// Default cadence for the freshness/draining `Subscribe` RPC in
+ /// milliseconds. Callers may suggest a cadence via
+ /// `SubscribeRequest.tick_hint_ms`; the server clamps to
+ /// `[subscribe_min_tick_ms, subscribe_max_tick_ms]` so a misbehaving
+ /// caller cannot induce excess work.
+ #[envconfig(from = "SUBSCRIBE_TICK_INTERVAL_MS", default = "1000")]
+ pub subscribe_tick_interval_ms: u64,
+
+ /// Lower bound for the load-event tick cadence. Hints below this are
+ /// clamped up.
+ #[envconfig(from = "SUBSCRIBE_MIN_TICK_MS", default = "100")]
+ pub subscribe_min_tick_ms: u64,
+
+ /// Upper bound for the load-event tick cadence. Hints above this are
+ /// clamped down so a misconfigured caller cannot make the stream stale.
+ #[envconfig(from = "SUBSCRIBE_MAX_TICK_MS", default = "10000")]
+ pub subscribe_max_tick_ms: u64,
+}
diff --git a/rust/cymbal-resolution/src/item_limiter.rs b/rust/cymbal-resolution/src/item_limiter.rs
new file mode 100644
index 000000000000..49df40e5814d
--- /dev/null
+++ b/rust/cymbal-resolution/src/item_limiter.rs
@@ -0,0 +1,61 @@
+use std::sync::Arc;
+
+use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore, TryAcquireError};
+
+/// Process-wide admission gate for exception item processing.
+#[derive(Clone, Debug)]
+pub struct ItemLimiter {
+ semaphore: Arc<Semaphore>,
+ max_permits: usize,
+}
+
+impl ItemLimiter {
+ pub fn new(max_permits: usize) -> Self {
+ let max_permits = max_permits.max(1);
+ Self {
+ semaphore: Arc::new(Semaphore::new(max_permits)),
+ max_permits,
+ }
+ }
+
+ pub fn from_semaphore(semaphore: Arc<Semaphore>, max_permits: usize) -> Self {
+ Self {
+ semaphore,
+ max_permits: max_permits.max(1),
+ }
+ }
+
+ pub async fn acquire_owned(&self) -> Result<OwnedSemaphorePermit, AcquireError> {
+ self.semaphore.clone().acquire_owned().await
+ }
+
+ pub fn try_acquire_owned(&self) -> Result<OwnedSemaphorePermit, TryAcquireError> {
+ self.semaphore.clone().try_acquire_owned()
+ }
+
+ pub fn available_permits(&self) -> usize {
+ self.semaphore.available_permits()
+ }
+
+ pub fn max_permits(&self) -> usize {
+ self.max_permits
+ }
+
+ pub fn close(&self) {
+ self.semaphore.close();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ItemLimiter;
+
+ #[tokio::test]
+ async fn max_permits_remains_the_configured_capacity() {
+ let limiter = ItemLimiter::new(3);
+ let _permit = limiter.acquire_owned().await.unwrap();
+
+ assert_eq!(limiter.max_permits(), 3);
+ assert_eq!(limiter.available_permits(), 2);
+ }
+}
diff --git a/rust/cymbal-resolution/src/lib.rs b/rust/cymbal-resolution/src/lib.rs
new file mode 100644
index 000000000000..43ce4a55a5e3
--- /dev/null
+++ b/rust/cymbal-resolution/src/lib.rs
@@ -0,0 +1,6 @@
+pub mod app_context;
+pub mod auth;
+pub mod config;
+pub mod item_limiter;
+pub mod load_monitor;
+pub mod service;
diff --git a/rust/cymbal-resolution/src/load_monitor.rs b/rust/cymbal-resolution/src/load_monitor.rs
new file mode 100644
index 000000000000..3977573cbffe
--- /dev/null
+++ b/rust/cymbal-resolution/src/load_monitor.rs
@@ -0,0 +1,148 @@
+use std::sync::{Arc, Mutex};
+
+use tokio::sync::Notify;
+
+const SERVER_IN_FLIGHT_ITEMS: &str = "cymbal_remote_resolution_server_in_flight_items";
+
+#[derive(Clone, Debug)]
+pub struct LoadSnapshot {
+ pub in_flight: u32,
+ pub draining: bool,
+}
+
+/// Tracks in-flight item processing and admits work up to `max_in_flight`.
+/// Overload is reported only as per-item Resolve outcomes, not through the
+/// Subscribe stream.
+#[derive(Clone, Debug)]
+pub struct LoadMonitor {
+ state: Arc<Mutex<LoadState>>,
+ notify: Arc<Notify>,
+ max_in_flight: u32,
+}
+
+#[derive(Clone, Copy, Debug, Default)]
+struct LoadState {
+ in_flight: u32,
+ draining: bool,
+}
+
+impl LoadMonitor {
+ pub fn new(max_in_flight: u32) -> Self {
+ Self {
+ state: Arc::new(Mutex::new(LoadState::default())),
+ notify: Arc::new(Notify::new()),
+ max_in_flight: max_in_flight.max(1),
+ }
+ }
+
+ pub fn try_admit(&self) -> bool {
+ let mut state = self.lock_state();
+ if state.in_flight >= self.max_in_flight {
+ return false;
+ }
+
+ state.in_flight = state.in_flight.saturating_add(1);
+ record_in_flight(state.in_flight);
+ true
+ }
+
+ pub fn set_in_flight(&self, in_flight: u32) {
+ self.update_state(|state| state.in_flight = in_flight);
+ }
+
+ pub fn increment_in_flight(&self) {
+ self.update_state(|state| state.in_flight = state.in_flight.saturating_add(1));
+ }
+
+ pub fn decrement_in_flight(&self) {
+ self.update_state(|state| state.in_flight = state.in_flight.saturating_sub(1));
+ }
+
+ pub fn set_draining(&self, draining: bool) {
+ self.update_state(|state| state.draining = draining);
+ }
+
+ pub async fn notified(&self) {
+ self.notify.notified().await;
+ }
+
+ pub fn snapshot(&self) -> LoadSnapshot {
+ let state = self.lock_state();
+ LoadSnapshot {
+ in_flight: state.in_flight,
+ draining: state.draining,
+ }
+ }
+
+ fn update_state(&self, update: impl FnOnce(&mut LoadState)) {
+ let should_notify = {
+ let mut state = self.lock_state();
+ let old_draining = state.draining;
+
+ update(&mut state);
+ record_in_flight(state.in_flight);
+
+ old_draining != state.draining
+ };
+
+ if should_notify {
+ self.notify.notify_waiters();
+ }
+ }
+
+ fn lock_state(&self) -> std::sync::MutexGuard<'_, LoadState> {
+ self.state.lock().expect("load monitor state poisoned")
+ }
+}
+
+fn record_in_flight(in_flight: u32) {
+ metrics::gauge!(SERVER_IN_FLIGHT_ITEMS).set(in_flight as f64);
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use super::*;
+
+ #[tokio::test]
+ async fn notifies_when_draining_changes() {
+ let monitor = LoadMonitor::new(3);
+ let waiter_monitor = monitor.clone();
+ let waiter = tokio::spawn(async move {
+ waiter_monitor.notified().await;
+ });
+ tokio::task::yield_now().await;
+
+ monitor.set_draining(true);
+ tokio::time::timeout(Duration::from_secs(1), waiter)
+ .await
+ .expect("draining change should notify")
+ .expect("waiter should not panic");
+ assert!(monitor.snapshot().draining);
+ }
+
+ #[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);
+
+ monitor.decrement_in_flight();
+ assert_eq!(monitor.snapshot().in_flight, 0);
+ }
+
+ #[test]
+ fn try_admit_checks_and_increments_under_one_lock() {
+ let monitor = LoadMonitor::new(2);
+
+ assert!(monitor.try_admit());
+ assert!(monitor.try_admit());
+ assert!(!monitor.try_admit());
+ assert_eq!(monitor.snapshot().in_flight, 2);
+
+ monitor.decrement_in_flight();
+ assert!(monitor.try_admit());
+ assert_eq!(monitor.snapshot().in_flight, 2);
+ }
+}
diff --git a/rust/cymbal-resolution/src/main.rs b/rust/cymbal-resolution/src/main.rs
new file mode 100644
index 000000000000..c13a36a6cb68
--- /dev/null
+++ b/rust/cymbal-resolution/src/main.rs
@@ -0,0 +1,226 @@
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+use std::time::Duration;
+
+use axum::{http::StatusCode, routing::get, Router};
+use cymbal::config::Config as CymbalConfig;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolutionServer;
+use cymbal_resolution::app_context::AppContext;
+use cymbal_resolution::auth::InternalApiSecretInterceptor;
+use cymbal_resolution::config::Config;
+use cymbal_resolution::load_monitor::LoadMonitor;
+use cymbal_resolution::service::{CymbalResolutionService, ServiceConfig};
+use envconfig::Envconfig;
+use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};
+use tokio::sync::watch;
+use tokio::task::JoinHandle;
+use tonic::transport::Server;
+use tracing::level_filters::LevelFilter;
+use tracing_subscriber::fmt;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::EnvFilter;
+
+common_alloc::used!();
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ init_tracing();
+
+ let config = Config::init_from_env().expect("Invalid cymbal-resolution configuration");
+ let cymbal_config = CymbalConfig::init_with_defaults().expect("Invalid cymbal configuration");
+ init_posthog_client(&cymbal_config).await;
+
+ tracing::info!("Starting cymbal-resolution service");
+ tracing::info!("gRPC address: {}", config.grpc_address);
+ tracing::info!("Metrics port: {}", config.metrics_port);
+
+ let app_context = AppContext::from_config(config.clone(), &cymbal_config)
+ .await
+ .expect("Failed to build cymbal-resolution app context");
+
+ let (shutdown_tx, shutdown_rx) = watch::channel(false);
+ let draining = Arc::new(AtomicBool::new(false));
+ let drain_notice = Duration::from_millis(config.subscribe_tick_interval_ms).saturating_mul(2);
+ let _shutdown_handle = spawn_shutdown_listener(
+ shutdown_tx.clone(),
+ draining.clone(),
+ app_context.load_monitor.clone(),
+ drain_notice,
+ );
+ let metrics_handle =
+ spawn_metrics_server(config.metrics_port, shutdown_rx.clone(), draining.clone());
+
+ let service_config = ServiceConfig::from(&config);
+ let service = CymbalResolutionService::new(
+ app_context.symbol_resolver.clone(),
+ app_context.symbol_resolution_limiter.clone(),
+ app_context.load_monitor.clone(),
+ app_context.service_instance_id.clone(),
+ service_config,
+ draining,
+ );
+ let auth_interceptor = InternalApiSecretInterceptor::new(config.internal_api_secret.clone());
+
+ let listener = tokio::net::TcpListener::bind(config.grpc_address).await?;
+ let incoming = tracked_tcp_incoming(listener);
+
+ tracing::info!("gRPC server listening on {}", config.grpc_address);
+
+ let server_result = Server::builder()
+ .http2_keepalive_interval(Some(Duration::from_secs(30)))
+ .http2_keepalive_timeout(Some(Duration::from_secs(20)))
+ .layer(GrpcMetricsLayer::default().with_processing_time_header())
+ .layer(GrpcLoadShedLayer::new(config.max_concurrent_requests))
+ // The cymbal client submits exception-level ResolveItems. The server
+ // relies on tonic's 4 MiB per-message default; an oversized item
+ // surfaces as `InvalidArgument`. Future: signal "send smaller" back
+ // via `LoadEvent`.
+ .add_service(CymbalResolutionServer::with_interceptor(
+ service,
+ move |request| auth_interceptor.authenticate(request),
+ ))
+ .serve_with_incoming_shutdown(incoming, wait_for_shutdown(shutdown_rx))
+ .await;
+
+ let _ignored = shutdown_tx.send(true);
+ if let Err(err) = metrics_handle.await {
+ tracing::warn!(error = %err, "metrics server task failed during shutdown");
+ }
+ server_result?;
+
+ Ok(())
+}
+
+async fn init_posthog_client(config: &CymbalConfig) {
+ match &config.posthog_api_key {
+ Some(key) => {
+ let ph_config = posthog_rs::ClientOptionsBuilder::default()
+ .api_key(key.clone())
+ .api_endpoint(config.posthog_endpoint.clone())
+ .build()
+ .expect("Invalid PostHog client configuration");
+ posthog_rs::init_global(ph_config)
+ .await
+ .expect("Failed to initialize PostHog client");
+ tracing::info!("PostHog client initialized");
+ }
+ None => {
+ posthog_rs::disable_global();
+ tracing::warn!("PostHog client disabled");
+ }
+ }
+}
+
+fn init_tracing() {
+ let log_layer = fmt::layer()
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_level(true);
+
+ tracing_subscriber::registry()
+ .with(log_layer)
+ .with(
+ EnvFilter::builder()
+ .with_default_directive(LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .init();
+}
+
+fn spawn_metrics_server(
+ port: u16,
+ shutdown_rx: watch::Receiver<bool>,
+ draining: Arc<AtomicBool>,
+) -> JoinHandle<()> {
+ tokio::spawn(async move {
+ let readiness_draining = draining.clone();
+ let router = Router::new()
+ .route("/_liveness", get(|| async { "ok" }))
+ .route(
+ "/_readiness",
+ get(move || readiness(readiness_draining.clone())),
+ );
+ let router = common_metrics::setup_metrics_routes_for_product(router, "cymbal-resolution");
+
+ let bind = format!("0.0.0.0:{port}");
+ tracing::info!("Metrics server listening on {}", bind);
+ let listener = match tokio::net::TcpListener::bind(&bind).await {
+ Ok(listener) => listener,
+ Err(e) => {
+ tracing::error!("Metrics server bind error: {e}");
+ return;
+ }
+ };
+ if let Err(e) = axum::serve(listener, router)
+ .with_graceful_shutdown(wait_for_shutdown(shutdown_rx))
+ .await
+ {
+ tracing::error!("Metrics server error: {e}");
+ }
+ })
+}
+
+fn spawn_shutdown_listener(
+ shutdown_tx: watch::Sender<bool>,
+ draining: Arc<AtomicBool>,
+ load_monitor: LoadMonitor,
+ drain_notice: Duration,
+) -> JoinHandle<()> {
+ tokio::spawn(async move {
+ shutdown_signal().await;
+ tracing::info!(
+ drain_notice_ms = drain_notice.as_millis() as u64,
+ "shutdown signal received, marking cymbal-resolution as draining",
+ );
+ draining.store(true, Ordering::Relaxed);
+ load_monitor.set_draining(true);
+ tokio::time::sleep(drain_notice).await;
+ tracing::info!("drain notice elapsed, stopping cymbal-resolution");
+ let _ignored = shutdown_tx.send(true);
+ })
+}
+
+async fn readiness(draining: Arc<AtomicBool>) -> (StatusCode, &'static str) {
+ if draining.load(Ordering::Relaxed) {
+ return (StatusCode::SERVICE_UNAVAILABLE, "draining");
+ }
+
+ (StatusCode::OK, "ok")
+}
+
+async fn wait_for_shutdown(mut shutdown_rx: watch::Receiver<bool>) {
+ if *shutdown_rx.borrow() {
+ return;
+ }
+
+ while shutdown_rx.changed().await.is_ok() {
+ if *shutdown_rx.borrow() {
+ return;
+ }
+ }
+}
+
+#[cfg(unix)]
+async fn shutdown_signal() {
+ use tokio::signal::unix::{signal, SignalKind};
+
+ let mut sigterm = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
+ tokio::select! {
+ result = tokio::signal::ctrl_c() => {
+ if let Err(err) = result {
+ tracing::warn!(error = %err, "failed to listen for Ctrl+C");
+ }
+ }
+ _ = sigterm.recv() => {}
+ }
+}
+
+#[cfg(not(unix))]
+async fn shutdown_signal() {
+ if let Err(err) = tokio::signal::ctrl_c().await {
+ tracing::warn!(error = %err, "failed to listen for Ctrl+C");
+ }
+}
diff --git a/rust/cymbal-resolution/src/service.rs b/rust/cymbal-resolution/src/service.rs
new file mode 100644
index 000000000000..07feea214783
--- /dev/null
+++ b/rust/cymbal-resolution/src/service.rs
@@ -0,0 +1,132 @@
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use cymbal::stages::resolution::ResolutionStage;
+use std::pin::Pin;
+
+use crate::load_monitor::LoadMonitor;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolution;
+use cymbal_proto::cymbal::resolution::v1::{
+ LoadEvent, ResolveItem, ResolveOutcome, SubscribeRequest,
+};
+
+use futures::Stream;
+use tokio::sync::mpsc;
+use tokio::sync::Semaphore;
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::{Request, Response, Status};
+use tracing::info;
+
+pub mod codes;
+mod config;
+mod resolve;
+mod subscribe;
+
+pub use config::ServiceConfig;
+
+use resolve::run_resolve;
+use subscribe::{load_event_stream, SubscribeRuntime};
+
+/// Channel buffer for streamed outcomes. Sized to absorb a short backlog while
+/// the caller drains; not a queue replacement for backpressure.
+const OUTCOME_CHANNEL_BUFFER: usize = 64;
+
+pub struct CymbalResolutionService {
+ symbol_resolver: Arc<dyn SymbolResolver>,
+ symbol_resolution_limiter: Arc<Semaphore>,
+ load_monitor: LoadMonitor,
+ service_instance_id: Arc<str>,
+ service_config: ServiceConfig,
+}
+
+impl CymbalResolutionService {
+ pub fn new(
+ symbol_resolver: Arc<dyn SymbolResolver>,
+ symbol_resolution_limiter: Arc<Semaphore>,
+ load_monitor: LoadMonitor,
+ service_instance_id: impl Into<Arc<str>>,
+ service_config: ServiceConfig,
+ draining: Arc<AtomicBool>,
+ ) -> Self {
+ load_monitor.set_draining(draining.load(Ordering::Relaxed));
+ Self {
+ symbol_resolver,
+ symbol_resolution_limiter,
+ load_monitor,
+ service_instance_id: service_instance_id.into(),
+ service_config,
+ }
+ }
+
+ fn resolution_stage(&self) -> ResolutionStage {
+ ResolutionStage {
+ symbol_resolver: self.symbol_resolver.clone(),
+ symbol_resolution_limiter: self.symbol_resolution_limiter.clone(),
+ // The cymbal-resolution server never enables remote mode itself;
+ // it is the server side that cymbal talks to. Local resolution is
+ // the only valid path here.
+ remote: None,
+ }
+ }
+}
+
+type ResolveStream = Pin<Box<dyn Stream<Item = Result<ResolveOutcome, Status>> + Send>>;
+type SubscribeStream = Pin<Box<dyn Stream<Item = Result<LoadEvent, Status>> + Send>>;
+
+#[tonic::async_trait]
+impl CymbalResolution for CymbalResolutionService {
+ type ResolveStream = ResolveStream;
+ type SubscribeStream = SubscribeStream;
+
+ async fn resolve(
+ &self,
+ request: Request<tonic::Streaming<ResolveItem>>,
+ ) -> Result<Response<Self::ResolveStream>, Status> {
+ let input = request.into_inner();
+
+ let stage = self.resolution_stage();
+
+ let (tx, rx) = mpsc::channel::<Result<ResolveOutcome, Status>>(OUTCOME_CHANNEL_BUFFER);
+
+ let load_monitor = self.load_monitor.clone();
+
+ tokio::spawn(async move {
+ run_resolve(input, stage, tx, load_monitor).await;
+ });
+
+ let stream = ReceiverStream::new(rx);
+ let boxed: ResolveStream = Box::pin(stream);
+ Ok(Response::new(boxed))
+ }
+
+ async fn subscribe(
+ &self,
+ request: Request<SubscribeRequest>,
+ ) -> Result<Response<Self::SubscribeStream>, Status> {
+ let req = request.into_inner();
+ let tick = self.service_config.resolve_tick_interval(req.tick_hint_ms);
+ let subscriber_id = if req.subscriber_id.is_empty() {
+ "<anonymous>".to_string()
+ } else {
+ req.subscriber_id.clone()
+ };
+ info!(
+ subscriber = %subscriber_id,
+ tick_ms = tick.as_millis() as u64,
+ "load event subscription opened",
+ );
+
+ let stream = load_event_stream(SubscribeRuntime {
+ service_instance_id: self.service_instance_id.clone(),
+ load_monitor: self.load_monitor.clone(),
+ tick,
+ subscriber_id,
+ });
+
+ let boxed: SubscribeStream = Box::pin(stream);
+ Ok(Response::new(boxed))
+ }
+}
diff --git a/rust/cymbal-resolution/src/service/codes.rs b/rust/cymbal-resolution/src/service/codes.rs
new file mode 100644
index 000000000000..fcbb1008c4c3
--- /dev/null
+++ b/rust/cymbal-resolution/src/service/codes.rs
@@ -0,0 +1,4 @@
+//! Error taxonomy surfaced to the caller in v1. The shared wire enum lives in
+//! cymbal-proto so client and server classify failures without parsing strings.
+
+pub use cymbal_proto::cymbal::resolution::v1::ErrorKind;
diff --git a/rust/cymbal-resolution/src/service/config.rs b/rust/cymbal-resolution/src/service/config.rs
new file mode 100644
index 000000000000..fb2f14770354
--- /dev/null
+++ b/rust/cymbal-resolution/src/service/config.rs
@@ -0,0 +1,70 @@
+use std::time::Duration;
+
+/// Configuration handed to the gRPC service. Subset of [`crate::config::Config`]
+/// that the handler actually needs; isolating it lets tests construct the
+/// service without touching the env-var surface.
+#[derive(Clone, Debug)]
+pub struct ServiceConfig {
+ pub default_tick_interval: Duration,
+ pub min_tick_interval: Duration,
+ pub max_tick_interval: Duration,
+}
+
+impl From<&crate::config::Config> for ServiceConfig {
+ fn from(cfg: &crate::config::Config) -> Self {
+ Self {
+ default_tick_interval: Duration::from_millis(cfg.subscribe_tick_interval_ms),
+ min_tick_interval: Duration::from_millis(cfg.subscribe_min_tick_ms),
+ max_tick_interval: Duration::from_millis(cfg.subscribe_max_tick_ms),
+ }
+ }
+}
+
+impl ServiceConfig {
+ /// Resolve the effective tick cadence for a Subscribe stream given an
+ /// optional caller hint. `0` means "use the server default"; other values
+ /// are clamped to `[min, max]`.
+ pub fn resolve_tick_interval(&self, hint_ms: u32) -> Duration {
+ let candidate = if hint_ms == 0 {
+ self.default_tick_interval
+ } else {
+ Duration::from_millis(hint_ms as u64)
+ };
+ let lo = self.min_tick_interval;
+ let hi = self.max_tick_interval.max(lo);
+ candidate.clamp(lo, hi)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolve_tick_interval_uses_default_when_hint_is_zero() {
+ let cfg = ServiceConfig {
+ default_tick_interval: Duration::from_millis(1000),
+ min_tick_interval: Duration::from_millis(100),
+ max_tick_interval: Duration::from_millis(5000),
+ };
+ assert_eq!(cfg.resolve_tick_interval(0), Duration::from_millis(1000));
+ }
+
+ #[test]
+ fn resolve_tick_interval_clamps_hint_to_bounds() {
+ let cfg = ServiceConfig {
+ default_tick_interval: Duration::from_millis(1000),
+ min_tick_interval: Duration::from_millis(100),
+ max_tick_interval: Duration::from_millis(5000),
+ };
+ // Below the floor — clamped up.
+ assert_eq!(cfg.resolve_tick_interval(10), Duration::from_millis(100));
+ // Above the ceiling — clamped down.
+ assert_eq!(
+ cfg.resolve_tick_interval(60_000),
+ Duration::from_millis(5000)
+ );
+ // Inside the band — taken as-is.
+ assert_eq!(cfg.resolve_tick_interval(750), Duration::from_millis(750));
+ }
+}
diff --git a/rust/cymbal-resolution/src/service/resolve.rs b/rust/cymbal-resolution/src/service/resolve.rs
new file mode 100644
index 000000000000..2c81f7484ec7
--- /dev/null
+++ b/rust/cymbal-resolution/src/service/resolve.rs
@@ -0,0 +1,269 @@
+use std::time::{Duration, Instant};
+
+use tokio::sync::mpsc;
+use tonic::{Status, Streaming};
+use tracing::{debug, warn};
+
+use cymbal::error::UnhandledError;
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::resolution::exception::ExceptionResolver;
+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,
+};
+
+use super::codes;
+use crate::load_monitor::LoadMonitor;
+
+const RESOLVE_REQUEST_DURATION_MS: &str = "cymbal_remote_resolution_server_request_duration_ms";
+const SERVER_ERROR_KINDS: &str = "cymbal_remote_resolution_server_error_kinds_total";
+
+pub(super) async fn run_resolve(
+ mut input: Streaming<ResolveItem>,
+ stage: ResolutionStage,
+ tx: mpsc::Sender<Result<ResolveOutcome, Status>>,
+ load_monitor: LoadMonitor,
+) {
+ let started_at = Instant::now();
+
+ loop {
+ let item = tokio::select! {
+ _ = tx.closed() => {
+ record_resolve_duration(started_at, "cancelled");
+ return;
+ }
+ maybe_item = input.message() => {
+ match maybe_item {
+ Ok(Some(item)) => item,
+ Ok(None) => break,
+ Err(err) => {
+ warn!(error = %err, "resolve input stream failed");
+ record_resolve_duration(started_at, "input_error");
+ return;
+ }
+ }
+ }
+ };
+
+ if item.deadline_ms == 0 {
+ if !send_overloaded(&tx, item.id, "item deadline expired", 0).await {
+ record_resolve_duration(started_at, "cancelled");
+ return;
+ }
+ continue;
+ }
+
+ if !load_monitor.try_admit() {
+ if !send_overloaded(&tx, item.id, "server overloaded", 0).await {
+ record_resolve_duration(started_at, "cancelled");
+ return;
+ }
+ continue;
+ }
+
+ let item_tx = tx.clone();
+ let item_stage = stage.clone();
+ let in_flight_guard = InFlightGuard::new(load_monitor.clone());
+ tokio::spawn(async move {
+ let processed = process_item(item_stage, item, in_flight_guard).await;
+ let _ignored = item_tx
+ .send(Ok(ResolveOutcome {
+ id: processed.id,
+ result: Some(processed.result),
+ }))
+ .await;
+ });
+ }
+
+ record_resolve_duration(started_at, "completed");
+}
+
+async fn send_overloaded(
+ tx: &mpsc::Sender<Result<ResolveOutcome, Status>>,
+ id: u64,
+ message: impl Into<String>,
+ _retry_after_ms: u32,
+) -> bool {
+ tx.send(Ok(ResolveOutcome {
+ id,
+ result: Some(error_result(codes::ErrorKind::Overloaded, message.into())),
+ }))
+ .await
+ .is_ok()
+}
+
+struct ProcessedItem {
+ id: u64,
+ result: resolve_outcome::Result,
+}
+
+struct InFlightGuard {
+ load_monitor: LoadMonitor,
+}
+
+impl InFlightGuard {
+ fn new(load_monitor: LoadMonitor) -> Self {
+ Self { load_monitor }
+ }
+}
+
+impl Drop for InFlightGuard {
+ fn drop(&mut self) {
+ self.load_monitor.decrement_in_flight();
+ }
+}
+
+async fn process_item(
+ stage: ResolutionStage,
+ item: ResolveItem,
+ in_flight_guard: InFlightGuard,
+) -> ProcessedItem {
+ let id = item.id;
+ let deadline = Duration::from_millis(item.deadline_ms as u64);
+ let _in_flight_guard = in_flight_guard;
+
+ let result = match tokio::time::timeout(deadline, resolve_item(&stage, &item)).await {
+ Ok(Ok(resolved)) => resolve_outcome::Result::Done(Done {
+ resolved_exception_json: resolved,
+ }),
+ Ok(Err(ItemFailure::InvalidPayload(msg))) => {
+ debug!(
+ id,
+ error = %msg,
+ "rejecting item with invalid payload",
+ );
+ error_result(codes::ErrorKind::InvalidPayload, msg)
+ }
+ Ok(Err(ItemFailure::Overloaded(msg))) => {
+ warn!(id, "limiter closed mid-request, asking caller to retry");
+ error_result(codes::ErrorKind::Overloaded, msg)
+ }
+ Ok(Err(ItemFailure::Unhandled(err))) => {
+ warn!(
+ id,
+ error = %err,
+ "unhandled error during resolution",
+ );
+ error_result(codes::ErrorKind::Unhandled, err)
+ }
+ Err(_) => error_result(
+ codes::ErrorKind::Overloaded,
+ "item deadline expired".to_string(),
+ ),
+ };
+
+ ProcessedItem { id, result }
+}
+
+fn error_result(kind: codes::ErrorKind, message: String) -> resolve_outcome::Result {
+ metrics::counter!(SERVER_ERROR_KINDS, "kind" => error_kind_label(kind)).increment(1);
+ resolve_outcome::Result::Error(ItemError {
+ kind: kind as i32,
+ message,
+ details_json: Vec::new(),
+ })
+}
+
+fn error_kind_label(kind: codes::ErrorKind) -> &'static str {
+ match kind {
+ codes::ErrorKind::Unspecified => "unspecified",
+ codes::ErrorKind::InvalidPayload => "invalid_payload",
+ codes::ErrorKind::Poison => "poison",
+ codes::ErrorKind::Unhandled => "unhandled",
+ codes::ErrorKind::Overloaded => "overloaded",
+ }
+}
+
+fn record_resolve_duration(started_at: Instant, outcome: &'static str) {
+ metrics::histogram!(RESOLVE_REQUEST_DURATION_MS, "outcome" => outcome)
+ .record(started_at.elapsed().as_secs_f64() * 1000.0);
+}
+
+enum ItemFailure {
+ InvalidPayload(String),
+ Overloaded(String),
+ Unhandled(String),
+}
+
+async fn resolve_item(stage: &ResolutionStage, item: &ResolveItem) -> Result<Vec<u8>, ItemFailure> {
+ let exception: Exception = serde_json::from_slice(&item.exception_json)
+ .map_err(|e| ItemFailure::InvalidPayload(format!("invalid exception_json: {e}")))?;
+
+ let debug_images = apple_debug_images_from_metadata(&item.metadata)?;
+
+ let resolved = resolve_one_exception(stage.clone(), item.team_id, exception, debug_images)
+ .await
+ .map_err(|e| match e {
+ ResolveOneError::Overloaded => {
+ ItemFailure::Overloaded("symbol-resolution limiter unavailable".to_string())
+ }
+ ResolveOneError::Unhandled(err) => ItemFailure::Unhandled(err),
+ })?;
+
+ serde_json::to_vec(&resolved)
+ .map_err(|e| ItemFailure::Unhandled(format!("serialize resolved exception: {e}")))
+}
+
+fn apple_debug_images_from_metadata(metadata: &[u8]) -> Result<Vec<AppleDebugImage>, ItemFailure> {
+ if metadata.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let metadata: serde_json::Value = serde_json::from_slice(metadata)
+ .map_err(|e| ItemFailure::InvalidPayload(format!("invalid metadata: {e}")))?;
+ let Some(debug_images) = metadata.get("apple_debug_images_json") else {
+ return Ok(Vec::new());
+ };
+ serde_json::from_value(debug_images.clone()).map_err(|e| {
+ ItemFailure::InvalidPayload(format!("invalid metadata.apple_debug_images_json: {e}"))
+ })
+}
+
+enum ResolveOneError {
+ Overloaded,
+ Unhandled(String),
+}
+
+async fn resolve_one_exception(
+ stage: ResolutionStage,
+ team_id: i32,
+ exception: Exception,
+ debug_images: Vec<AppleDebugImage>,
+) -> Result<Exception, ResolveOneError> {
+ let exception = if ExceptionResolver::is_java_exception(&exception) {
+ let _permit = acquire_permit(&stage).await?;
+ stage
+ .symbol_resolver
+ .resolve_java_exception(team_id, exception)
+ .await
+ .map_err(to_unhandled)?
+ } else if ExceptionResolver::is_dart_exception(&exception) {
+ let _permit = acquire_permit(&stage).await?;
+ stage
+ .symbol_resolver
+ .resolve_dart_exception(team_id, exception)
+ .await
+ .map_err(to_unhandled)?
+ } else {
+ exception
+ };
+
+ FrameResolver::resolve_exception_frames(team_id, exception, &debug_images, stage)
+ .await
+ .map_err(to_unhandled)
+}
+
+async fn acquire_permit(
+ stage: &ResolutionStage,
+) -> Result<tokio::sync::OwnedSemaphorePermit, ResolveOneError> {
+ stage
+ .acquire_symbol_resolution_permit()
+ .await
+ .map_err(|_| ResolveOneError::Overloaded)
+}
+
+fn to_unhandled(err: UnhandledError) -> ResolveOneError {
+ ResolveOneError::Unhandled(err.to_string())
+}
diff --git a/rust/cymbal-resolution/src/service/subscribe.rs b/rust/cymbal-resolution/src/service/subscribe.rs
new file mode 100644
index 000000000000..61c5759ba55c
--- /dev/null
+++ b/rust/cymbal-resolution/src/service/subscribe.rs
@@ -0,0 +1,60 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use futures::Stream;
+use tonic::Status;
+use tracing::info;
+
+use crate::load_monitor::LoadMonitor;
+use cymbal_proto::cymbal::resolution::v1::LoadEvent;
+
+pub(super) struct SubscribeRuntime {
+ pub(super) service_instance_id: Arc<str>,
+ pub(super) load_monitor: LoadMonitor,
+ pub(super) tick: Duration,
+ pub(super) subscriber_id: String,
+}
+
+/// Logs the subscription closing when the generator future is dropped — which
+/// happens both when the client disconnects (tonic drops the stream) and when
+/// the loop is otherwise cancelled. Mirrors the "opened" log at the call site.
+struct CloseLog {
+ subscriber_id: String,
+}
+
+impl Drop for CloseLog {
+ fn drop(&mut self) {
+ info!(subscriber = %self.subscriber_id, "load event subscription closed");
+ }
+}
+
+pub(super) fn load_event_stream(
+ runtime: SubscribeRuntime,
+) -> impl Stream<Item = Result<LoadEvent, Status>> {
+ async_stream::stream! {
+ let _close_log = CloseLog { subscriber_id: runtime.subscriber_id };
+
+ let mut ticker = tokio::time::interval(runtime.tick);
+ // First tick fires immediately so the caller sees state without waiting
+ // a full period; thereafter Delay matches the pool's polling expectation
+ // (skip missed ticks instead of bursting catch-up events).
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ let mut sequence: u64 = 0;
+
+ loop {
+ tokio::select! {
+ _ = ticker.tick() => {}
+ _ = runtime.load_monitor.notified() => {}
+ }
+
+ sequence += 1;
+ let snapshot = runtime.load_monitor.snapshot();
+ yield Ok(LoadEvent {
+ service_instance_id: runtime.service_instance_id.as_ref().to_string(),
+ draining: snapshot.draining,
+ sequence,
+ message: String::new(),
+ });
+ }
+ }
+}
diff --git a/rust/cymbal-resolution/tests/service_tests.rs b/rust/cymbal-resolution/tests/service_tests.rs
new file mode 100644
index 000000000000..8e20f91a6c2b
--- /dev/null
+++ b/rust/cymbal-resolution/tests/service_tests.rs
@@ -0,0 +1,603 @@
+use std::sync::{
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ Arc,
+};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use cymbal::error::{ResolveError, UnhandledError};
+use cymbal::frames::{Frame, RawFrame};
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use cymbal::symbol_store::{chunk_id::OrChunkId, proguard::ProguardRef};
+use cymbal::types::operator::TeamId;
+use cymbal::types::{Exception, Stacktrace};
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_client::CymbalResolutionClient;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolution;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolutionServer;
+use cymbal_proto::cymbal::resolution::v1::{
+ resolve_outcome, ErrorKind, ResolveItem, ResolveOutcome, SubscribeRequest,
+};
+use cymbal_resolution::load_monitor::LoadMonitor;
+use cymbal_resolution::service::{CymbalResolutionService, ServiceConfig};
+use futures::StreamExt;
+use tokio::sync::Semaphore;
+use tonic::transport::{Channel, Server};
+use tonic::Request;
+
+#[derive(Default)]
+struct FakeResolver {
+ fail_unhandled: bool,
+ resolved_frames: Vec<Frame>,
+}
+
+#[async_trait]
+impl SymbolResolver for FakeResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ if self.fail_unhandled {
+ return Err(UnhandledError::Other("forced resolver failure".to_string()));
+ }
+ Ok(self.resolved_frames.clone())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("fake resolver does not need java class resolution for these tests")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ unreachable!("fake resolver does not need dart name resolution for these tests")
+ }
+}
+
+struct SlowResolver {
+ delay: Duration,
+ first_call_delay: Option<Duration>,
+ active: Arc<AtomicUsize>,
+ max_active: Arc<AtomicUsize>,
+ started: Arc<AtomicUsize>,
+}
+
+#[async_trait]
+impl SymbolResolver for SlowResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ let call_index = self.started.fetch_add(1, Ordering::AcqRel);
+ let active = self.active.fetch_add(1, Ordering::AcqRel) + 1;
+ update_max(&self.max_active, active);
+
+ let delay = if call_index == 0 {
+ self.first_call_delay.unwrap_or(self.delay)
+ } else {
+ self.delay
+ };
+ tokio::time::sleep(delay).await;
+ self.active.fetch_sub(1, Ordering::AcqRel);
+ Ok(Vec::new())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("slow resolver does not need java class resolution for these tests")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ unreachable!("slow resolver does not need dart name resolution for these tests")
+ }
+}
+
+fn update_max(max_active: &AtomicUsize, candidate: usize) {
+ let mut current = max_active.load(Ordering::Acquire);
+ while candidate > current {
+ match max_active.compare_exchange(current, candidate, Ordering::AcqRel, Ordering::Acquire) {
+ Ok(_) => return,
+ Err(actual) => current = actual,
+ }
+ }
+}
+
+fn fast_service_config() -> ServiceConfig {
+ ServiceConfig {
+ default_tick_interval: Duration::from_millis(20),
+ min_tick_interval: Duration::from_millis(1),
+ max_tick_interval: Duration::from_secs(1),
+ }
+}
+
+fn make_service(resolver: FakeResolver) -> CymbalResolutionService {
+ make_service_with_config(
+ Arc::new(resolver),
+ Arc::new(Semaphore::new(4)),
+ 4,
+ fast_service_config(),
+ )
+}
+
+fn make_service_with_config(
+ resolver: Arc<dyn SymbolResolver>,
+ symbol_resolution_limiter: Arc<Semaphore>,
+ max_in_flight: u32,
+ service_config: ServiceConfig,
+) -> CymbalResolutionService {
+ CymbalResolutionService::new(
+ resolver,
+ symbol_resolution_limiter,
+ LoadMonitor::new(max_in_flight),
+ "test-instance",
+ service_config,
+ Arc::new(AtomicBool::new(false)),
+ )
+}
+
+async fn spawn_test_channel(service: CymbalResolutionService) -> Channel {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind test server");
+ let addr = listener.local_addr().expect("test server local addr");
+ let incoming = futures::stream::unfold(listener, |listener| async {
+ Some((listener.accept().await.map(|(stream, _)| stream), listener))
+ });
+
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(CymbalResolutionServer::new(service))
+ .serve_with_incoming(incoming)
+ .await
+ .expect("test gRPC server exits cleanly");
+ });
+
+ Channel::from_shared(format!("http://{addr}"))
+ .expect("valid test endpoint")
+ .connect()
+ .await
+ .expect("connect to test server")
+}
+
+async fn resolve_items(
+ service: CymbalResolutionService,
+ items: Vec<ResolveItem>,
+) -> Vec<ResolveOutcome> {
+ let channel = spawn_test_channel(service).await;
+ let mut client = CymbalResolutionClient::new(channel);
+ let response = client
+ .resolve(Request::new(futures::stream::iter(items)))
+ .await
+ .expect("resolve returns response");
+ let mut stream = response.into_inner();
+ let mut outcomes = Vec::new();
+ while let Some(outcome) = stream.next().await {
+ outcomes.push(outcome.expect("outcome must not be status error"));
+ }
+ outcomes
+}
+
+fn raw_exception(exception_type: &str) -> Exception {
+ Exception {
+ exception_id: None,
+ exception_type: exception_type.to_string(),
+ exception_message: "boom".to_string(),
+ mechanism: None,
+ module: None,
+ thread_id: None,
+ stack: Some(Stacktrace::Raw { frames: vec![] }),
+ }
+}
+
+fn make_item(id: u64, exc: &Exception) -> ResolveItem {
+ ResolveItem {
+ id,
+ team_id: 7,
+ exception_json: serde_json::to_vec(exc).expect("serialize exception"),
+ metadata: Vec::new(),
+ deadline_ms: 1_000,
+ }
+}
+
+fn make_item_with_metadata(id: u64, exc: &Exception, metadata: Vec<u8>) -> ResolveItem {
+ ResolveItem {
+ id,
+ metadata,
+ ..make_item(id, exc)
+ }
+}
+
+fn outcome_result(outcome: &ResolveOutcome) -> &resolve_outcome::Result {
+ outcome.result.as_ref().expect("outcome result present")
+}
+
+fn error_kind(outcome: &ResolveOutcome) -> ErrorKind {
+ let resolve_outcome::Result::Error(error) = outcome_result(outcome) else {
+ panic!("expected error outcome, got {outcome:?}");
+ };
+ ErrorKind::try_from(error.kind).expect("known error kind")
+}
+
+fn assert_no_retry(outcomes: &[ResolveOutcome]) {
+ assert!(
+ outcomes
+ .iter()
+ .all(|outcome| !matches!(outcome_result(outcome), resolve_outcome::Result::Retry(_))),
+ "server overload must be an ErrorKind, not a Retry outcome: {outcomes:?}",
+ );
+}
+
+#[tokio::test]
+async fn bidi_resolve_stream_resolves_multiple_items_and_echoes_ids() {
+ let service = make_service(FakeResolver::default());
+ let exc = raw_exception("RuntimeError");
+
+ let outcomes = resolve_items(service, vec![make_item(41, &exc), make_item(42, &exc)]).await;
+
+ assert_eq!(outcomes.len(), 2);
+ assert_eq!(
+ outcomes
+ .iter()
+ .map(|outcome| outcome.id)
+ .collect::<Vec<_>>(),
+ vec![41, 42]
+ );
+ for outcome in outcomes {
+ let resolve_outcome::Result::Done(done) = outcome_result(&outcome) else {
+ panic!("expected Done outcome, got {outcome:?}");
+ };
+ let resolved: Exception = serde_json::from_slice(&done.resolved_exception_json)
+ .expect("valid resolved exception");
+ assert_eq!(resolved.exception_type, "RuntimeError");
+ assert!(matches!(resolved.stack, Some(Stacktrace::Resolved { .. })));
+ }
+}
+
+#[tokio::test]
+async fn raw_frames_are_resolved_into_done_payload() {
+ let raw_frame = sample_raw_frame();
+ let mut resolver_frame = sample_resolved_frame(&raw_frame);
+ resolver_frame.frame_id = raw_frame.frame_id(123, 99);
+ let service = make_service(FakeResolver {
+ fail_unhandled: false,
+ resolved_frames: vec![resolver_frame],
+ });
+ let mut exc = raw_exception("RuntimeError");
+ exc.stack = Some(Stacktrace::Raw {
+ frames: vec![raw_frame.clone()],
+ });
+
+ let outcomes = resolve_items(service, vec![make_item(1, &exc)]).await;
+ assert_eq!(outcomes.len(), 1);
+ let resolve_outcome::Result::Done(done) = outcome_result(&outcomes[0]) else {
+ panic!("expected Done outcome, got {:?}", outcomes[0]);
+ };
+ let resolved: Exception =
+ serde_json::from_slice(&done.resolved_exception_json).expect("valid resolved exception");
+
+ let Some(Stacktrace::Resolved { frames }) = resolved.stack else {
+ panic!("raw stack must be replaced with resolved frames");
+ };
+ let expected_wire_frame: Frame = serde_json::from_value(
+ serde_json::to_value(sample_resolved_frame(&raw_frame)).expect("serialize expected frame"),
+ )
+ .expect("deserialize expected wire frame");
+ assert_eq!(frames, vec![expected_wire_frame]);
+}
+
+#[tokio::test]
+async fn bidi_resolve_stream_emits_outcomes_as_items_complete_out_of_order() {
+ let active = Arc::new(AtomicUsize::new(0));
+ let max_active = Arc::new(AtomicUsize::new(0));
+ let started = Arc::new(AtomicUsize::new(0));
+ let service = make_service_with_config(
+ Arc::new(SlowResolver {
+ delay: Duration::from_millis(5),
+ first_call_delay: Some(Duration::from_millis(80)),
+ active,
+ max_active: max_active.clone(),
+ started: started.clone(),
+ }),
+ Arc::new(Semaphore::new(8)),
+ 8,
+ fast_service_config(),
+ );
+ let mut exc = raw_exception("RuntimeError");
+ exc.stack = Some(Stacktrace::Raw {
+ frames: vec![sample_raw_frame()],
+ });
+ let items = (1..=4).map(|id| make_item(id, &exc)).collect();
+
+ let outcomes = resolve_items(service, items).await;
+
+ assert_eq!(started.load(Ordering::Acquire), 4);
+ assert!(
+ max_active.load(Ordering::Acquire) > 1,
+ "items should be processed concurrently",
+ );
+ assert_eq!(outcomes.len(), 4);
+ assert_ne!(
+ outcomes[0].id, 1,
+ "a faster later item should complete before the slower first item",
+ );
+ assert!(outcomes
+ .iter()
+ .all(|outcome| matches!(outcome_result(outcome), resolve_outcome::Result::Done(_))));
+}
+
+#[tokio::test]
+async fn invalid_payload_and_metadata_formats_are_invalid_payload_errors() {
+ let service = make_service(FakeResolver::default());
+ let exc = raw_exception("RuntimeError");
+ let outcomes = resolve_items(
+ service,
+ vec![
+ ResolveItem {
+ id: 1,
+ team_id: 7,
+ exception_json: b"not-json".to_vec(),
+ metadata: Vec::new(),
+ deadline_ms: 1_000,
+ },
+ make_item_with_metadata(2, &exc, b"not-json".to_vec()),
+ make_item_with_metadata(
+ 3,
+ &exc,
+ br#"{"apple_debug_images_json":"not-a-list"}"#.to_vec(),
+ ),
+ ],
+ )
+ .await;
+
+ assert_eq!(outcomes.len(), 3);
+ for outcome in outcomes {
+ assert_eq!(error_kind(&outcome), ErrorKind::InvalidPayload);
+ }
+}
+
+#[tokio::test]
+async fn unhandled_resolver_failure_classifies_as_unhandled_error() {
+ let service = make_service(FakeResolver {
+ fail_unhandled: true,
+ ..Default::default()
+ });
+ let mut exc = raw_exception("RuntimeError");
+ exc.stack = Some(Stacktrace::Raw {
+ frames: vec![sample_raw_frame()],
+ });
+
+ let outcomes = resolve_items(service, vec![make_item(1, &exc)]).await;
+
+ assert_eq!(outcomes.len(), 1);
+ assert_eq!(outcomes[0].id, 1);
+ assert_eq!(error_kind(&outcomes[0]), ErrorKind::Unhandled);
+}
+
+#[tokio::test]
+async fn load_monitor_overload_is_an_overloaded_error_outcome_only() {
+ let active = Arc::new(AtomicUsize::new(0));
+ let max_active = Arc::new(AtomicUsize::new(0));
+ let started = Arc::new(AtomicUsize::new(0));
+ let service = make_service_with_config(
+ Arc::new(SlowResolver {
+ delay: Duration::from_millis(80),
+ first_call_delay: None,
+ active,
+ max_active,
+ started,
+ }),
+ Arc::new(Semaphore::new(8)),
+ 1,
+ fast_service_config(),
+ );
+ let mut exc = raw_exception("RuntimeError");
+ exc.stack = Some(Stacktrace::Raw {
+ frames: vec![sample_raw_frame()],
+ });
+
+ let outcomes = resolve_items(service, vec![make_item(1, &exc), make_item(2, &exc)]).await;
+
+ assert_no_retry(&outcomes);
+ let overloaded = outcomes
+ .iter()
+ .find(|outcome| outcome.id == 2)
+ .expect("second item should be rejected by max_in_flight");
+ assert_eq!(error_kind(overloaded), ErrorKind::Overloaded);
+ let completed = outcomes
+ .iter()
+ .find(|outcome| outcome.id == 1)
+ .expect("first admitted item should complete");
+ assert!(matches!(
+ outcome_result(completed),
+ resolve_outcome::Result::Done(_)
+ ));
+}
+
+#[tokio::test]
+async fn symbol_limiter_overload_is_an_overloaded_error_outcome_only() {
+ let limiter = Arc::new(Semaphore::new(1));
+ let _permit = limiter.clone().acquire_owned().await.unwrap();
+ limiter.close();
+ let service = make_service_with_config(
+ Arc::new(FakeResolver::default()),
+ limiter,
+ 4,
+ fast_service_config(),
+ );
+
+ let outcomes = resolve_items(service, vec![make_item(1, &java_exception_for_overload())]).await;
+
+ assert_eq!(outcomes.len(), 1);
+ assert_no_retry(&outcomes);
+ assert_eq!(error_kind(&outcomes[0]), ErrorKind::Overloaded);
+}
+
+fn java_exception_for_overload() -> Exception {
+ let frame_json = serde_json::json!({
+ "platform": "java",
+ "module": "com.example",
+ "filename": "A.java",
+ "function": "f",
+ "in_app": true,
+ });
+ let frame: RawFrame = serde_json::from_value(frame_json).expect("valid java frame");
+ Exception {
+ exception_id: None,
+ exception_type: "Boom".to_string(),
+ exception_message: "msg".to_string(),
+ mechanism: None,
+ module: Some("com.example".to_string()),
+ thread_id: None,
+ stack: Some(Stacktrace::Raw {
+ frames: vec![frame],
+ }),
+ }
+}
+
+fn sample_raw_frame() -> RawFrame {
+ let json = serde_json::json!({
+ "platform": "web:javascript",
+ "filename": "a.js",
+ "function": "f",
+ "in_app": true,
+ "lineno": 1,
+ "colno": 1,
+ });
+ serde_json::from_value(json).expect("valid raw frame")
+}
+
+fn sample_resolved_frame(raw_frame: &RawFrame) -> Frame {
+ Frame {
+ frame_id: raw_frame.frame_id(7, 0),
+ mangled_name: "f".to_string(),
+ line: Some(42),
+ column: Some(7),
+ source: Some("src/app.ts".to_string()),
+ module: Some("app".to_string()),
+ in_app: true,
+ resolved_name: Some("renderCheckout".to_string()),
+ lang: "javascript".to_string(),
+ resolved: true,
+ resolve_failure: None,
+ synthetic: false,
+ suspicious: false,
+ junk_drawer: None,
+ code_variables: None,
+ context: None,
+ release: None,
+ }
+}
+
+#[tokio::test]
+async fn subscribe_emits_periodic_load_events_with_monotonic_sequence() {
+ let service = make_service(FakeResolver::default());
+ let response = service
+ .subscribe(Request::new(SubscribeRequest {
+ subscriber_id: "test-subscriber".to_string(),
+ tick_hint_ms: 0,
+ }))
+ .await
+ .expect("subscribe returns response");
+ let mut stream = response.into_inner();
+
+ let mut events = Vec::new();
+ for _ in 0..3 {
+ let event = stream
+ .next()
+ .await
+ .expect("stream open")
+ .expect("event without status error");
+ events.push(event);
+ }
+ drop(stream);
+
+ assert_eq!(events.len(), 3);
+ assert_eq!(events[0].sequence, 1);
+ assert_eq!(events[1].sequence, 2);
+ assert_eq!(events[2].sequence, 3);
+ assert!(!events[0].draining);
+ assert_eq!(events[0].service_instance_id, "test-instance");
+}
+
+#[tokio::test]
+async fn subscribe_reflects_draining_state() {
+ let draining = Arc::new(AtomicBool::new(true));
+ let service = CymbalResolutionService::new(
+ Arc::new(FakeResolver::default()),
+ Arc::new(Semaphore::new(4)),
+ LoadMonitor::new(4),
+ "draining-test",
+ fast_service_config(),
+ draining,
+ );
+ let response = service
+ .subscribe(Request::new(SubscribeRequest {
+ subscriber_id: "draining-watcher".to_string(),
+ tick_hint_ms: 0,
+ }))
+ .await
+ .expect("subscribe returns response");
+ let mut stream = response.into_inner();
+
+ let event = stream.next().await.expect("stream open").expect("event ok");
+ assert!(event.draining);
+ assert_eq!(event.service_instance_id, "draining-test");
+}
+
+#[tokio::test]
+async fn subscribe_clamps_caller_hint_to_server_bounds() {
+ let service = make_service(FakeResolver::default());
+ let response = service
+ .subscribe(Request::new(SubscribeRequest {
+ subscriber_id: "fast-caller".to_string(),
+ tick_hint_ms: 0,
+ }))
+ .await
+ .expect("subscribe accepts default hints");
+ let mut stream = response.into_inner();
+ let event = stream.next().await.expect("at least one event").unwrap();
+ assert_eq!(event.sequence, 1);
+}
+
+#[tokio::test]
+async fn subscribe_terminates_when_caller_drops_stream() {
+ let service = make_service(FakeResolver::default());
+ let response = service
+ .subscribe(Request::new(SubscribeRequest::default()))
+ .await
+ .unwrap();
+ let mut stream = response.into_inner();
+ let _first = stream.next().await.unwrap();
+ drop(stream);
+
+ tokio::time::sleep(Duration::from_millis(30)).await;
+
+ let response = service
+ .subscribe(Request::new(SubscribeRequest::default()))
+ .await
+ .unwrap();
+ let mut stream2 = response.into_inner();
+ let event = stream2.next().await.unwrap().unwrap();
+ assert_eq!(event.sequence, 1, "new subscription restarts sequence at 1");
+}
diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.toml
index 4f76f5cea35c..910c0b0239c4 100644
--- a/rust/cymbal/Cargo.toml
+++ b/rust/cymbal/Cargo.toml
@@ -20,6 +20,7 @@ common-kafka = { path = "../common/kafka" }
common-types = { path = "../common/types" }
common-dns = { path = "../common/dns" }
common-redis = { path = "../common/redis" }
+cymbal-proto = { path = "../cymbal-proto" }
posthog-symbol-data = { path = "../common/symbol_data" }
hogvm = { path = "../common/hogvm" }
thiserror = { workspace = true }
@@ -42,16 +43,20 @@ posthog-rs = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
regex = { workspace = true }
+rand = { workspace = true }
futures.workspace = true
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
-tower.workspace = true
tiktoken-rs.workspace = true
+tonic = { workspace = true }
+tokio-stream = "0.1"
[dev-dependencies]
+cymbal-resolution = { path = "../cymbal-resolution" }
httpmock = { workspace = true }
mockall = { workspace = true }
insta = { version = "1.46.0", features = ["json", "redactions"] }
+tower.workspace = true
[lints]
workspace = true
diff --git a/rust/cymbal/README.md b/rust/cymbal/README.md
index e2b7c62ccb96..c08e0501321b 100644
--- a/rust/cymbal/README.md
+++ b/rust/cymbal/README.md
@@ -2,6 +2,44 @@
You throw 'em, we catch 'em.
+Cymbal owns the HTTP ingress and full processing pipeline (fingerprinting,
+suppression, Kafka producers, issue linking). Symbol resolution can run
+either inline inside the cymbal binary (default) or be offloaded to the
+[`cymbal-resolution`](../cymbal-resolution/README.md) gRPC service via the
+`cymbal.resolution.v1` contract. The remote path is opt-in via
+`CYMBAL_REMOTE_RESOLUTION_ENABLED=true` and has **no silent local fallback**
+— see the [cymbal-resolution README](../cymbal-resolution/README.md) for
+rollout, configuration, and operator guidance.
+
+## Remote resolution behavior
+
+The public HTTP contract stays `POST /process`: callers send an array of
+events and receive an equally sized array in the same order, with `null` in a
+slot only when the normal cymbal pipeline suppresses that event. The
+Node.js error-tracking consumer can keep using its existing DNS/team routing
+and HTTP body-size chunking because remote symbol resolution happens behind
+the same cymbal HTTP boundary.
+
+When remote resolution is enabled, `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE`
+controls a deterministic event-level rollout. Events selected for remote
+processing are grouped per team, flattened into exception-level `ResolveItem`s,
+and submitted over a bidirectional `Resolve` stream. Each item carries JSON
+`metadata` bytes for resolver-specific context such as
+`apple_debug_images_json`, and each terminal `ResolveOutcome` is correlated by
+item id. Sampled remote attempts do not fall back to local resolution if the
+remote pool fails; unsampled events use the inline local exception and frame
+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. `LoadEvent` is only a
+freshness/draining signal for endpoint routing, not an overload or dynamic
+batch-size control plane.
+
+See [`docs/compatibility.md`](docs/compatibility.md) for the Node consumer
+compatibility checklist and [`../cymbal-resolution/README.md`](../cymbal-resolution/README.md)
+for rollout and dashboard guidance.
+
### Terms
We use a lot of terms in this and other error tracking code, with implied meanings. Here are some of them:
diff --git a/rust/cymbal/docs/compatibility.md b/rust/cymbal/docs/compatibility.md
new file mode 100644
index 000000000000..a868ec93c372
--- /dev/null
+++ b/rust/cymbal/docs/compatibility.md
@@ -0,0 +1,34 @@
+# Cymbal HTTP compatibility
+
+Remote symbol resolution is an internal implementation detail of cymbal.
+The external Node.js error-tracking consumer contract stays unchanged.
+
+## `/process` request and response
+
+- Node still sends `POST /process` to cymbal with an array of `AnyEvent`-shaped exception events.
+- Cymbal still returns an array with the same length and ordering as the request.
+- Each non-null response entry is the same `AnyEvent` shape with updated `properties`.
+- `null` entries keep their existing meaning: the event was suppressed by the normal cymbal pipeline.
+- Remote resolution only changes how cymbal fills the exception list before properties, grouping, linking, suppression, and alerting continue.
+
+## Node-side chunking
+
+`nodejs/src/ingestion/error-tracking/cymbal/client.ts` chunks HTTP requests by estimated original event body size before they reach cymbal.
+That remains valid with remote resolution enabled because cymbal preserves the HTTP boundary and performs private exception-level gRPC work after it receives an HTTP chunk.
+
+No generated type changes are needed:
+
+- the Node request type remains `CymbalRequest`
+- the Node response type remains `(CymbalResponse | null)[]`
+- the internal `cymbal.resolution.v1` gRPC messages are not exposed to Node
+
+## Remote rollout controls behind the HTTP boundary
+
+- `CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE` deterministically chooses remote vs local resolution per event.
+- Sampled events use the remote pool and do not silently fall back to local resolution on remote failures.
+- 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; `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 00f1cce76b0d..cc55fc33ee57 100644
--- a/rust/cymbal/src/app_context.rs
+++ b/rust/cymbal/src/app_context.rs
@@ -5,7 +5,10 @@ use moka::future::{Cache, CacheBuilder};
use rdkafka::producer::FutureProducer;
use sqlx::{postgres::PgPoolOptions, PgPool};
use std::{sync::Arc, time::Duration};
-use tokio::sync::{Mutex, Semaphore};
+use tokio::{
+ sync::{Mutex, Semaphore},
+ task::JoinHandle,
+};
use tracing::info;
use uuid::Uuid;
@@ -13,6 +16,10 @@ use crate::{
config::{get_aws_config, init_global_state, Config},
error::UnhandledError,
signals::{MaybeSignalClient, SignalClient},
+ stages::resolution::remote::{
+ dns::TokioDnsResolver, pool::EndpointPool, resolver::RemoteResolutionContext,
+ RemoteResolutionConfig,
+ },
stages::resolution::symbol::{local::LocalSymbolResolver, SymbolResolver},
symbol_store::{
apple::AppleProvider,
@@ -40,6 +47,12 @@ pub struct AppContext {
pub symbol_resolver: Arc<dyn SymbolResolver>,
pub symbol_resolution_limiter: Arc<Semaphore>,
pub process_request_limiter: Arc<Semaphore>,
+ /// When set, cymbal's resolution stage routes exception resolution to the
+ /// remote `cymbal-resolution` service pool instead of running the local
+ /// resolver. Built once at startup; the endpoint pool refreshes itself in
+ /// the background.
+ pub remote_resolution: Option<RemoteResolutionContext>,
+ remote_resolution_refresh_task: Option<JoinHandle<()>>,
pub config: Config,
pub team_manager: TeamManager,
@@ -52,6 +65,114 @@ pub struct AppContext {
pub issue_cache: Cache<(TeamId, String), Uuid>,
}
+impl Drop for AppContext {
+ fn drop(&mut self) {
+ if let Some(handle) = &self.remote_resolution_refresh_task {
+ handle.abort();
+ }
+ }
+}
+
+/// Build just the symbol-resolution stack from env config: connects to
+/// Postgres, builds the S3 client, calls [`init_global_state`], and
+/// returns a fully-wired `SymbolResolver`. **Does not** start Kafka
+/// producers, Redis clients, signals, the issue cache, or the remote-
+/// resolution pool — those belong to the full cymbal pipeline and are
+/// constructed by [`AppContext::from_config`].
+///
+/// Used by `cymbal-resolution`, the standalone gRPC service that only
+/// needs symbol resolution; keeping this separate stops cymbal-resolution
+/// pods from holding Kafka/Redis connections they never use.
+pub async fn build_symbol_resolver(
+ config: &Config,
+) -> Result<Arc<dyn SymbolResolver>, UnhandledError> {
+ init_global_state(config);
+ let options = PgPoolOptions::new().max_connections(config.max_pg_connections);
+ let posthog_pool = options.connect(&config.database_url).await?;
+ let s3 = aws_sdk_s3::Client::from_conf(get_aws_config(config).await);
+ let s3_client: Arc<dyn BlobClient> = Arc::new(S3Client::new(s3));
+ s3_client.ping_bucket(&config.object_storage_bucket).await?;
+ let catalog = build_catalog(config, s3_client, posthog_pool.clone());
+ Ok(Arc::new(LocalSymbolResolver::new(
+ config,
+ catalog,
+ posthog_pool,
+ )))
+}
+
+/// Build the symbol-store [`Catalog`] from already-constructed S3 and PG
+/// handles. Internal helper shared by [`AppContext::new`] and
+/// [`build_symbol_resolver`] so the provider wiring doesn't drift.
+fn build_catalog(
+ config: &Config,
+ s3_client: Arc<dyn BlobClient>,
+ posthog_pool: PgPool,
+) -> Arc<Catalog> {
+ let ss_cache = Arc::new(Mutex::new(SymbolSetCache::new(
+ config.symbol_store_cache_max_bytes,
+ )));
+
+ let smp = SourcemapProvider::new(config).with_chunk_id_rescue(
+ posthog_pool.clone(),
+ s3_client.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ let smp_chunk = ChunkIdFetcher::new(
+ smp,
+ s3_client.clone(),
+ posthog_pool.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ let smp_saving = Saving::new(
+ smp_chunk,
+ posthog_pool.clone(),
+ s3_client.clone(),
+ config.object_storage_bucket.clone(),
+ config.ss_prefix.clone(),
+ );
+ let smp_caching = Caching::new(smp_saving, ss_cache.clone());
+ // We want to fetch each sourcemap from the outside world exactly once,
+ // and if it isn't in the cache, load/parse it from s3 exactly once too.
+ // Limiting the per symbol set reference concurrency to 1 ensures this.
+ let smp_atmostonce = concurrency::AtMostOne::new(smp_caching);
+
+ let hmp_chunk = ChunkIdFetcher::new(
+ HermesMapProvider {},
+ s3_client.clone(),
+ posthog_pool.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ // Skip the saving layer for HermesMapProvider, since it'll never fetch
+ // something from the outside world.
+ let hmp_caching = Caching::new(hmp_chunk, ss_cache.clone());
+ let hmp_atmostonce = concurrency::AtMostOne::new(hmp_caching);
+
+ let pgp_chunk = ChunkIdFetcher::new(
+ ProguardProvider {},
+ s3_client.clone(),
+ posthog_pool.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ let pgp_caching = Caching::new(pgp_chunk, ss_cache.clone());
+ let pgp_atmostonce = concurrency::AtMostOne::new(pgp_caching);
+
+ let apple_chunk = ChunkIdFetcher::new(
+ AppleProvider {},
+ s3_client.clone(),
+ posthog_pool.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ let apple_caching = Caching::new(apple_chunk, ss_cache);
+ let apple_atmostonce = concurrency::AtMostOne::new(apple_caching);
+
+ Arc::new(Catalog::new(
+ smp_atmostonce,
+ hmp_atmostonce,
+ pgp_atmostonce,
+ apple_atmostonce,
+ ))
+}
+
impl AppContext {
pub async fn from_config(config: &Config) -> Result<Self, UnhandledError> {
let options = PgPoolOptions::new().max_connections(config.max_pg_connections);
@@ -119,71 +240,10 @@ impl AppContext {
s3_client.ping_bucket(&config.object_storage_bucket).await?;
- let ss_cache = Arc::new(Mutex::new(SymbolSetCache::new(
- config.symbol_store_cache_max_bytes,
- )));
-
- let smp = SourcemapProvider::new(config).with_chunk_id_rescue(
- posthog_pool.clone(),
- s3_client.clone(),
- config.object_storage_bucket.clone(),
- );
- let smp_chunk = ChunkIdFetcher::new(
- smp,
- s3_client.clone(),
- posthog_pool.clone(),
- config.object_storage_bucket.clone(),
- );
- let smp_saving = Saving::new(
- smp_chunk,
- posthog_pool.clone(),
- s3_client.clone(),
- config.object_storage_bucket.clone(),
- config.ss_prefix.clone(),
- );
- let smp_caching = Caching::new(smp_saving, ss_cache.clone());
- // We want to fetch each sourcemap from the outside world
- // exactly once, and if it isn't in the cache, load/parse
- // it from s3 exactly once too. Limiting the per symbol set
- // reference concurrency to 1 ensures this.
- let smp_atmostonce = concurrency::AtMostOne::new(smp_caching);
-
- let hmp_chunk = ChunkIdFetcher::new(
- HermesMapProvider {},
- s3_client.clone(),
- posthog_pool.clone(),
- config.object_storage_bucket.clone(),
- );
- // We skip the saving layer for HermesMapProvider, since it'll never fetch something from the outside world.
- let hmp_caching = Caching::new(hmp_chunk, ss_cache.clone());
- let hmp_atmostonce = concurrency::AtMostOne::new(hmp_caching);
-
- let pgp_chunk = ChunkIdFetcher::new(
- ProguardProvider {},
- s3_client.clone(),
- posthog_pool.clone(),
- config.object_storage_bucket.clone(),
- );
- let pgp_caching = Caching::new(pgp_chunk, ss_cache.clone());
- let pgp_atmostonce = concurrency::AtMostOne::new(pgp_caching);
-
- let apple_chunk = ChunkIdFetcher::new(
- AppleProvider {},
- s3_client.clone(),
- posthog_pool.clone(),
- config.object_storage_bucket.clone(),
- );
- let apple_caching = Caching::new(apple_chunk, ss_cache.clone());
- let apple_atmostonce = concurrency::AtMostOne::new(apple_caching);
+ let catalog = build_catalog(config, s3_client, posthog_pool.clone());
info!("AppContext initialized");
- let catalog = Arc::new(Catalog::new(
- smp_atmostonce,
- hmp_atmostonce,
- pgp_atmostonce,
- apple_atmostonce,
- ));
let team_manager = TeamManager::new(config);
let signal_client = if config.signals_api_base_url.is_empty() {
@@ -210,6 +270,9 @@ impl AppContext {
.time_to_live(Duration::from_secs(config.issue_cache_ttl_seconds))
.build();
+ let (remote_resolution, remote_resolution_refresh_task) =
+ build_remote_resolution(config).await?;
+
Ok(Self {
health_registry,
immediate_producer,
@@ -224,6 +287,50 @@ impl AppContext {
signal_client,
symbol_resolver,
issue_cache,
+ remote_resolution,
+ remote_resolution_refresh_task,
})
}
}
+
+async fn build_remote_resolution(
+ config: &Config,
+) -> Result<(Option<RemoteResolutionContext>, Option<JoinHandle<()>>), UnhandledError> {
+ if !config.remote_resolution_enabled {
+ return Ok((None, None));
+ }
+
+ let remote_config = RemoteResolutionConfig::from_config(config)?;
+ info!(
+ host = %remote_config.host,
+ port = remote_config.port,
+ deadline_ms = remote_config.request_deadline.as_millis() as u64,
+ dns_refresh_secs = remote_config.dns_refresh.as_secs(),
+ max_retries = remote_config.max_retries,
+ sample_rate = remote_config.sample_rate,
+ "remote resolution enabled, building endpoint pool"
+ );
+
+ let resolver = Arc::new(TokioDnsResolver);
+ let pool = EndpointPool::new(remote_config.clone(), resolver)
+ .await
+ .map_err(|e| {
+ UnhandledError::Other(format!("failed to build remote resolution pool: {e}"))
+ })?;
+ let readiness_timeout = std::cmp::max(
+ remote_config.subscribe_tick_hint.saturating_mul(3),
+ remote_config.connect_timeout,
+ );
+ pool.wait_ready(readiness_timeout).await.map_err(|e| {
+ UnhandledError::Other(format!("remote resolution pool did not become ready: {e}"))
+ })?;
+ let refresh_task = crate::stages::resolution::remote::pool::spawn_refresh_task(pool.clone());
+
+ Ok((
+ Some(RemoteResolutionContext {
+ pool,
+ config: remote_config,
+ }),
+ Some(refresh_task),
+ ))
+}
diff --git a/rust/cymbal/src/config.rs b/rust/cymbal/src/config.rs
index a21c5f8356d8..f3c70dc8e6d0 100644
--- a/rust/cymbal/src/config.rs
+++ b/rust/cymbal/src/config.rs
@@ -178,6 +178,91 @@ pub struct Config {
#[envconfig(default = "")]
pub internal_api_secret: String,
+
+ // ----------------------------------------------------------------------
+ // Remote resolution (cymbal.resolution.v1) — Batch 3 client integration.
+ //
+ // When `remote_resolution_enabled` is true, cymbal routes exception-level
+ // symbol resolution through the configured `cymbal-resolution` service
+ // pool instead of running the local resolver inline. There is no silent
+ // local fallback: if the pool can't satisfy the request, the stage
+ // surfaces the failure to its caller. Local mode (the default) is
+ // unchanged.
+ // ----------------------------------------------------------------------
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_ENABLED", default = "false")]
+ pub remote_resolution_enabled: bool,
+
+ /// Hostname of the cymbal-resolution service. Resolved via DNS, then each
+ /// returned address gets its own gRPC channel in the endpoint pool.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_HOST", default = "")]
+ pub remote_resolution_host: String,
+
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_PORT", default = "50061")]
+ pub remote_resolution_port: u16,
+
+ /// How often to re-resolve the configured hostname and refresh the pool.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_DNS_REFRESH_SECS", default = "30")]
+ pub remote_resolution_dns_refresh_secs: u64,
+
+ /// Per-call deadline for a single Resolve RPC, in milliseconds. The
+ /// stage enforces this independently of any transport-level keepalive.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_DEADLINE_MS", default = "15000")]
+ pub remote_resolution_deadline_ms: u64,
+
+ /// Connection establishment timeout for a single endpoint, in
+ /// milliseconds. Endpoints that exceed this are skipped for routing.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_CONNECT_TIMEOUT_MS", default = "1000")]
+ pub remote_resolution_connect_timeout_ms: u64,
+
+ /// Maximum number of caller-side retries against the endpoint pool when
+ /// transport, load shedding, or explicit `retry` outcomes are observed.
+ /// `0` disables retries; the first attempt still runs.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_MAX_RETRIES", default = "2")]
+ pub remote_resolution_max_retries: u32,
+
+ /// Initial backoff applied between caller-side retries, in milliseconds.
+ /// Each subsequent attempt doubles the wait (capped at
+ /// `CYMBAL_REMOTE_RESOLUTION_RETRY_MAX_BACKOFF_MS`), plus up to ~50% random
+ /// jitter so a fleet of cymbal pods does not synchronize retries against a
+ /// briefly-overloaded upstream.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_RETRY_BACKOFF_MS", default = "50")]
+ pub remote_resolution_retry_backoff_ms: u64,
+
+ /// Upper bound on the retry backoff window, in milliseconds. The exponential
+ /// schedule never sleeps longer than this between attempts.
+ #[envconfig(
+ from = "CYMBAL_REMOTE_RESOLUTION_RETRY_MAX_BACKOFF_MS",
+ default = "1000"
+ )]
+ pub remote_resolution_retry_max_backoff_ms: u64,
+
+ /// Deterministic event-level rollout sample for remote resolution.
+ /// Defaults to `0.0` so flipping `CYMBAL_REMOTE_RESOLUTION_ENABLED=true`
+ /// alone does not start sending traffic — the rollout has to be ramped
+ /// explicitly. Values outside 0.0..=1.0 are clamped by
+ /// `RemoteResolutionConfig`, matching the defensive normalization used
+ /// by adjacent duration knobs.
+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE", default = "0.0")]
+ pub remote_resolution_sample_rate: f64,
+
+ /// 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`),
+ /// so this is only a hint.
+ #[envconfig(
+ from = "CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_TICK_HINT_MS",
+ default = "1000"
+ )]
+ pub remote_resolution_subscribe_tick_hint_ms: u64,
+
+ /// Backoff between reconnect attempts when a per-endpoint subscription
+ /// stream terminates, in milliseconds. Kept small so a transient blip
+ /// doesn't keep the pool blind for long.
+ #[envconfig(
+ from = "CYMBAL_REMOTE_RESOLUTION_SUBSCRIBE_RECONNECT_BACKOFF_MS",
+ default = "500"
+ )]
+ pub remote_resolution_subscribe_reconnect_backoff_ms: u64,
}
impl Config {
diff --git a/rust/cymbal/src/metric_consts.rs b/rust/cymbal/src/metric_consts.rs
index 9f1059863f34..66ab6af93db4 100644
--- a/rust/cymbal/src/metric_consts.rs
+++ b/rust/cymbal/src/metric_consts.rs
@@ -126,3 +126,23 @@ pub const FINGERPRINT_GENERATOR_OPERATOR: &str = "cymbal_exception_fingerprint_g
pub const RULE_SUPPRESSED_EVENTS: &str = "cymbal_rule_suppressed_events";
pub const SUPPRESSION_RULES_TRIED: &str = "cymbal_suppression_rules_tried";
pub const SUPPRESSION_RULES_DISABLED: &str = "cymbal_suppression_rules_disabled";
+
+// Remote resolution observability. Keep labels bounded: endpoint labels are
+// limited to the discovered pod set, and protocol failures are classified by
+// fixed enums rather than free-form messages.
+pub const REMOTE_RESOLUTION_REQUESTS: &str = "cymbal_remote_resolution_requests_total";
+pub const REMOTE_RESOLUTION_LATENCY: &str = "cymbal_remote_resolution_latency_ms";
+pub const REMOTE_RESOLUTION_SAMPLING: &str = "cymbal_remote_resolution_sampling_total";
+pub const REMOTE_RESOLUTION_POOL_SIZE: &str = "cymbal_remote_resolution_pool_size";
+pub const REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT: &str =
+ "cymbal_remote_resolution_endpoint_in_flight";
+pub const REMOTE_RESOLUTION_ENDPOINT_MUX_IN_FLIGHT: &str =
+ "cymbal_remote_resolution_endpoint_mux_in_flight";
+pub const REMOTE_RESOLUTION_ENDPOINT_ADMISSION_REJECTIONS: &str =
+ "cymbal_remote_resolution_endpoint_admission_rejections_total";
+pub const REMOTE_RESOLUTION_ERROR_KINDS: &str = "cymbal_remote_resolution_error_kinds_total";
+pub const REMOTE_RESOLUTION_OVERLOAD_ESCALATIONS: &str =
+ "cymbal_remote_resolution_overload_escalations_total";
+pub const REMOTE_RESOLUTION_REROUTE_DEPTH: &str = "cymbal_remote_resolution_reroute_depth";
+pub const REMOTE_RESOLUTION_LOAD_SUBSCRIPTIONS: &str =
+ "cymbal_remote_resolution_load_subscriptions_total";
diff --git a/rust/cymbal/src/posthog_utils.rs b/rust/cymbal/src/posthog_utils.rs
index 1e46f83e4b30..fa8539e79681 100644
--- a/rust/cymbal/src/posthog_utils.rs
+++ b/rust/cymbal/src/posthog_utils.rs
@@ -14,14 +14,14 @@ pub fn capture_issue_created(team_id: i32, issue_id: Uuid, sentry_integration: b
event
.insert_prop("sentry_integration", sentry_integration)
.unwrap();
- spawning_capture(event);
+ spawning_capture(ISSUE_CREATED, event);
}
pub fn capture_issue_reopened(team_id: i32, issue_id: Uuid) {
let mut event = Event::new_anon(ISSUE_REOPENED);
event.insert_prop("team_id", team_id).unwrap();
event.insert_prop("issue_id", issue_id.to_string()).unwrap();
- spawning_capture(event);
+ spawning_capture(ISSUE_REOPENED, event);
}
pub fn capture_symbol_set_saved(team_id: i32, set_ref: &str, storage_ptr: &str, was_retry: bool) {
@@ -30,7 +30,7 @@ pub fn capture_symbol_set_saved(team_id: i32, set_ref: &str, storage_ptr: &str,
event.insert_prop("set_ref", set_ref).unwrap();
event.insert_prop("storage_ptr", storage_ptr).unwrap();
event.insert_prop("was_retry", was_retry).unwrap();
- spawning_capture(event);
+ spawning_capture(SYMBOL_SET_SAVED, event);
}
pub fn capture_symbol_set_deleted(team_id: i32, set_ref: &str, storage_ptr: Option<&str>) {
@@ -40,13 +40,17 @@ pub fn capture_symbol_set_deleted(team_id: i32, set_ref: &str, storage_ptr: Opti
if let Some(ptr) = storage_ptr {
event.insert_prop("storage_ptr", ptr).unwrap();
}
- spawning_capture(event);
+ spawning_capture(SYMBOL_SET_DELETED, event);
}
-pub fn spawning_capture(event: Event) {
+pub fn spawning_capture(event_name: &'static str, event: Event) {
+ if posthog_rs::global_is_disabled() {
+ return;
+ }
+
tokio::spawn(async move {
if let Err(e) = posthog_rs::capture(event).await {
- error!("Error capturing issue created event: {:?}", e);
+ error!(event = event_name, error = ?e, "Error capturing PostHog event");
}
});
}
diff --git a/rust/cymbal/src/stages/resolution/frame.rs b/rust/cymbal/src/stages/resolution/frame.rs
index 98543fc4abed..c3b186b73b00 100644
--- a/rust/cymbal/src/stages/resolution/frame.rs
+++ b/rust/cymbal/src/stages/resolution/frame.rs
@@ -77,9 +77,22 @@ impl FrameResolver {
) -> Result<Vec<Frame>, UnhandledError> {
let _permit = ctx.acquire_symbol_resolution_permit().await?;
- ctx.symbol_resolver
+ let mut resolved_frames = ctx
+ .symbol_resolver
.resolve_raw_frame(team_id, frame, debug_images)
- .await
+ .await?;
+
+ // The frame id is part of the caller/frontend lookup contract. Keep it
+ // tied to the submitted raw frame here instead of trusting resolver
+ // implementations to preserve the raw_id/part shape.
+ resolved_frames
+ .iter_mut()
+ .enumerate()
+ .for_each(|(index, resolved_frame)| {
+ resolved_frame.frame_id = frame.frame_id(team_id, index);
+ });
+
+ Ok(resolved_frames)
}
}
diff --git a/rust/cymbal/src/stages/resolution/mod.rs b/rust/cymbal/src/stages/resolution/mod.rs
index 4c189486ae3c..08a6220e9ad3 100644
--- a/rust/cymbal/src/stages/resolution/mod.rs
+++ b/rust/cymbal/src/stages/resolution/mod.rs
@@ -5,6 +5,7 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore};
pub mod exception;
pub mod frame;
pub mod properties;
+pub mod remote;
pub mod symbol;
use crate::{
@@ -13,7 +14,10 @@ use crate::{
metric_consts::RESOLUTION_STAGE,
stages::pipeline::ExceptionEventPipelineItem,
stages::resolution::{
- exception::ExceptionResolver, frame::FrameResolver, properties::PropertiesResolver,
+ exception::ExceptionResolver,
+ frame::FrameResolver,
+ properties::PropertiesResolver,
+ remote::resolver::{resolve_batch, RemoteResolutionContext},
symbol::SymbolResolver,
},
types::{
@@ -26,6 +30,12 @@ use crate::{
pub struct ResolutionStage {
pub symbol_resolver: Arc<dyn SymbolResolver>,
pub symbol_resolution_limiter: Arc<Semaphore>,
+ /// When `Some`, the resolution stage can route sampled events through the
+ /// remote `cymbal.resolution.v1` client path. Unsampled events still use
+ /// local exception+frame resolution. There is no local fallback for events
+ /// selected for remote processing: if the remote pool can't serve the
+ /// request, the orchestration layer surfaces an unhandled error.
+ pub remote: Option<RemoteResolutionContext>,
}
impl From<&Arc<AppContext>> for ResolutionStage {
@@ -33,6 +43,7 @@ impl From<&Arc<AppContext>> for ResolutionStage {
Self {
symbol_resolver: app_context.as_ref().symbol_resolver.clone(),
symbol_resolution_limiter: app_context.as_ref().symbol_resolution_limiter.clone(),
+ remote: app_context.as_ref().remote_resolution.clone(),
}
}
}
@@ -58,6 +69,20 @@ impl Stage for ResolutionStage {
}
async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
+ if let Some(remote) = self.remote.clone() {
+ // Remote mode: the stage owns orchestration across the incoming
+ // batch, including deterministic rollout sampling. Sampled events
+ // use grouped exception-level Resolve items, and unsampled events use
+ // the local exception/frame operators. PropertiesResolver still
+ // runs afterwards because it operates on the resolved exception
+ // list shape independently of how exception/frame resolution was
+ // performed.
+ return resolve_batch(batch, remote, self.clone())
+ .await?
+ .apply_operator(PropertiesResolver, self.clone())
+ .await;
+ }
+
batch
.apply_operator(ExceptionResolver, self.clone())
.await?
diff --git a/rust/cymbal/src/stages/resolution/remote/client.rs b/rust/cymbal/src/stages/resolution/remote/client.rs
new file mode 100644
index 000000000000..92c5f1168b20
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/client.rs
@@ -0,0 +1,126 @@
+use std::str::FromStr;
+use std::time::Duration;
+
+use thiserror::Error;
+use tonic::metadata::MetadataValue;
+use tonic::{Code, Request, Status};
+
+pub const INTERNAL_API_SECRET_HEADER: &str = "x-internal-api-secret";
+
+/// Errors observable by the remote resolver's retry logic. The `retryable`
+/// half is what cymbal will retry against another endpoint; `terminal` is
+/// surfaced as a handled error so the rest of `/process` can move on.
+#[derive(Debug, Error)]
+pub enum RemoteCallError {
+ #[error("remote resolution rpc returned retryable status {0:?}")]
+ Retryable(Status),
+ #[error("remote resolution rpc returned terminal status {0:?}")]
+ Terminal(Status),
+ #[error("remote resolution rpc deadline exceeded after {0:?}")]
+ Deadline(Duration),
+}
+
+impl RemoteCallError {
+ pub fn is_retryable(&self) -> bool {
+ matches!(
+ self,
+ RemoteCallError::Retryable(_) | RemoteCallError::Deadline(_)
+ )
+ }
+
+ /// Short tag suitable for metric labels. Keeps the cardinality bounded
+ /// to the gRPC code set plus "deadline" so dashboards can distinguish
+ /// transport classes without exploding labels.
+ pub fn reason_tag(&self) -> &'static str {
+ match self {
+ RemoteCallError::Deadline(_) => "deadline",
+ RemoteCallError::Retryable(status) | RemoteCallError::Terminal(status) => {
+ code_tag(status.code())
+ }
+ }
+ }
+}
+
+fn code_tag(code: Code) -> &'static str {
+ match code {
+ Code::Ok => "ok",
+ Code::Cancelled => "cancelled",
+ Code::Unknown => "unknown",
+ Code::InvalidArgument => "invalid_argument",
+ Code::DeadlineExceeded => "deadline_exceeded",
+ Code::NotFound => "not_found",
+ Code::AlreadyExists => "already_exists",
+ Code::PermissionDenied => "permission_denied",
+ Code::ResourceExhausted => "resource_exhausted",
+ Code::FailedPrecondition => "failed_precondition",
+ Code::Aborted => "aborted",
+ Code::OutOfRange => "out_of_range",
+ Code::Unimplemented => "unimplemented",
+ Code::Internal => "internal",
+ Code::Unavailable => "unavailable",
+ Code::DataLoss => "data_loss",
+ Code::Unauthenticated => "unauthenticated",
+ }
+}
+
+pub(crate) fn with_internal_api_secret<T>(
+ mut request: Request<T>,
+ internal_api_secret: &str,
+) -> Result<Request<T>, Box<Status>> {
+ let secret = internal_api_secret.trim();
+ if secret.is_empty() {
+ return Err(Box::new(Status::unauthenticated(
+ "internal API secret is not configured",
+ )));
+ }
+ let value = MetadataValue::from_str(secret).map_err(|_| {
+ Box::new(Status::unauthenticated(
+ "invalid internal API secret metadata",
+ ))
+ })?;
+ request
+ .metadata_mut()
+ .insert(INTERNAL_API_SECRET_HEADER, value);
+ Ok(request)
+}
+
+pub(crate) fn classify_status(status: Status) -> RemoteCallError {
+ match status.code() {
+ // Transport/availability/timeouts → retry against another endpoint.
+ Code::Unavailable
+ | Code::ResourceExhausted
+ | Code::DeadlineExceeded
+ | Code::Aborted
+ | Code::Cancelled
+ | Code::Unknown
+ | Code::Internal => RemoteCallError::Retryable(status),
+ // Everything else (InvalidArgument, NotFound, PermissionDenied, …) is
+ // terminal; retrying will keep failing the same way.
+ _ => RemoteCallError::Terminal(status),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn with_internal_api_secret_adds_expected_metadata() {
+ let request = with_internal_api_secret(Request::new(()), " test-secret\n").unwrap();
+ assert_eq!(
+ request
+ .metadata()
+ .get(INTERNAL_API_SECRET_HEADER)
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "test-secret"
+ );
+ }
+
+ #[test]
+ fn with_internal_api_secret_rejects_empty_secret() {
+ let err = with_internal_api_secret(Request::new(()), " ").unwrap_err();
+ assert_eq!(err.code(), Code::Unauthenticated);
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/config.rs b/rust/cymbal/src/stages/resolution/remote/config.rs
new file mode 100644
index 000000000000..094d463ee0c8
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/config.rs
@@ -0,0 +1,100 @@
+use std::time::Duration;
+
+use crate::config::Config;
+use crate::error::UnhandledError;
+
+/// Narrowed view of [`crate::config::Config`] containing only the fields used
+/// by the remote resolution client. Keeping a dedicated struct lets the pool,
+/// DNS, and resolver modules be exercised in tests without touching cymbal's
+/// full env-var surface.
+#[derive(Clone)]
+pub struct RemoteResolutionConfig {
+ pub host: String,
+ pub port: u16,
+ /// Shared secret attached to every cymbal-resolution gRPC request.
+ pub internal_api_secret: String,
+ pub dns_refresh: Duration,
+ pub request_deadline: Duration,
+ pub connect_timeout: Duration,
+ pub max_retries: u32,
+ /// Initial backoff between retries; doubles each attempt up to `retry_max_backoff`.
+ pub retry_backoff: Duration,
+ /// Ceiling for the exponential retry backoff window.
+ pub retry_max_backoff: Duration,
+ /// Event-level deterministic sample rate for sending eligible events to
+ /// 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,
+ /// 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 *
+ /// subscribe_tick_hint` are treated as "no signal" and the pool excludes
+ /// the endpoint from routing. Coupling staleness to the tick removes a knob
+ /// that previously had to be tuned in lockstep.
+ pub subscribe_tick_hint: Duration,
+ /// Backoff applied before a per-endpoint subscription task reconnects after
+ /// the stream ends or errors. Kept small so a transient blip doesn't leave
+ /// the pool routing on stale data for long.
+ pub subscribe_reconnect_backoff: Duration,
+}
+
+impl RemoteResolutionConfig {
+ pub fn from_config(config: &Config) -> Result<Self, UnhandledError> {
+ if config.remote_resolution_host.trim().is_empty() {
+ return Err(UnhandledError::Other(
+ "remote resolution enabled but CYMBAL_REMOTE_RESOLUTION_HOST is empty".to_string(),
+ ));
+ }
+ if config.internal_api_secret.trim().is_empty() {
+ return Err(UnhandledError::Other(
+ "remote resolution enabled but INTERNAL_API_SECRET is empty".to_string(),
+ ));
+ }
+ Ok(Self {
+ host: config.remote_resolution_host.clone(),
+ port: config.remote_resolution_port,
+ internal_api_secret: config.internal_api_secret.clone(),
+ dns_refresh: Duration::from_secs(config.remote_resolution_dns_refresh_secs.max(1)),
+ request_deadline: Duration::from_millis(config.remote_resolution_deadline_ms.max(1)),
+ connect_timeout: Duration::from_millis(
+ config.remote_resolution_connect_timeout_ms.max(1),
+ ),
+ max_retries: config.remote_resolution_max_retries,
+ retry_backoff: Duration::from_millis(config.remote_resolution_retry_backoff_ms.max(1)),
+ retry_max_backoff: Duration::from_millis(
+ config
+ .remote_resolution_retry_max_backoff_ms
+ .max(config.remote_resolution_retry_backoff_ms.max(1)),
+ ),
+ sample_rate: normalized_sample_rate(config.remote_resolution_sample_rate),
+ subscribe_tick_hint: Duration::from_millis(
+ config.remote_resolution_subscribe_tick_hint_ms.max(1),
+ ),
+ subscribe_reconnect_backoff: Duration::from_millis(
+ config
+ .remote_resolution_subscribe_reconnect_backoff_ms
+ .max(1),
+ ),
+ })
+ }
+}
+
+fn normalized_sample_rate(sample_rate: f64) -> f64 {
+ if !sample_rate.is_finite() {
+ return 1.0;
+ }
+ sample_rate.clamp(0.0, 1.0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::normalized_sample_rate;
+
+ #[test]
+ fn sample_rate_is_clamped_to_valid_range() {
+ assert_eq!(normalized_sample_rate(-0.5), 0.0);
+ assert_eq!(normalized_sample_rate(0.25), 0.25);
+ assert_eq!(normalized_sample_rate(1.5), 1.0);
+ assert_eq!(normalized_sample_rate(f64::NAN), 1.0);
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/dns.rs b/rust/cymbal/src/stages/resolution/remote/dns.rs
new file mode 100644
index 000000000000..f07ab0df09cb
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/dns.rs
@@ -0,0 +1,30 @@
+use std::io;
+use std::net::SocketAddr;
+
+use async_trait::async_trait;
+use tokio::net::lookup_host;
+
+/// DNS resolver abstraction. Production uses `TokioDnsResolver`; tests
+/// substitute a deterministic fake so endpoint-pool behavior can be exercised
+/// without touching the network.
+#[async_trait]
+pub trait DnsResolver: Send + Sync + 'static {
+ async fn resolve(&self, host: &str, port: u16) -> io::Result<Vec<SocketAddr>>;
+}
+
+/// Default DNS resolver backed by tokio's async `lookup_host`. Unlike
+/// `common_dns::PublicIPv4Resolver`, this does not filter out private/cluster
+/// IPv4 addresses — the cymbal-resolution service typically lives on a
+/// cluster-internal hostname (e.g. `cymbal-resolution.posthog.svc.cluster.local`),
+/// so filtering by globally-routable IP would remove every legitimate target.
+#[derive(Default, Debug)]
+pub struct TokioDnsResolver;
+
+#[async_trait]
+impl DnsResolver for TokioDnsResolver {
+ async fn resolve(&self, host: &str, port: u16) -> io::Result<Vec<SocketAddr>> {
+ let target = format!("{host}:{port}");
+ let addrs = lookup_host(target).await?.collect::<Vec<_>>();
+ Ok(addrs)
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/mod.rs b/rust/cymbal/src/stages/resolution/remote/mod.rs
new file mode 100644
index 000000000000..04c5236b476a
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/mod.rs
@@ -0,0 +1,21 @@
+//! Remote `cymbal.resolution.v1` client integration.
+//!
+//! When `Config::remote_resolution_enabled` is set, the resolution stage
+//! routes exception-level symbol resolution through the `cymbal-resolution`
+//! service via a caller-owned endpoint pool instead of running
+//! [`crate::stages::resolution::symbol::local::LocalSymbolResolver`] inline.
+//!
+//! There is intentionally no silent local fallback: if the pool cannot
+//! satisfy a request, the stage surfaces an unhandled error for the batch
+//! instead of falling back to local resolution.
+
+pub mod client;
+pub mod config;
+pub mod dns;
+pub mod mux;
+pub mod pool;
+pub mod resolver;
+pub mod subscription;
+
+pub use config::RemoteResolutionConfig;
+pub use pool::EndpointPool;
diff --git a/rust/cymbal/src/stages/resolution/remote/mux.rs b/rust/cymbal/src/stages/resolution/remote/mux.rs
new file mode 100644
index 000000000000..6f278e40e3db
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/mux.rs
@@ -0,0 +1,537 @@
+//! Per-endpoint bidirectional Resolve stream mux.
+//!
+//! A mux owns exactly one long-lived `Resolve` stream for one endpoint. Callers
+//! submit independent [`ResolveItem`]s through a bounded local queue; the mux
+//! allocates per-stream ids, writes items to the gRPC request stream, and
+//! demultiplexes [`ResolveOutcome`]s back to per-item waiters.
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+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::task::JoinHandle;
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::transport::Channel;
+use tonic::{Code, Request, Status};
+use tracing::warn;
+
+use crate::metric_consts::{
+ REMOTE_RESOLUTION_ENDPOINT_ADMISSION_REJECTIONS, REMOTE_RESOLUTION_ENDPOINT_MUX_IN_FLIGHT,
+};
+
+use super::client::{classify_status, with_internal_api_secret, RemoteCallError};
+
+#[derive(Clone)]
+pub struct ResolveMux {
+ inner: Arc<ResolveMuxInner>,
+}
+
+struct ResolveMuxInner {
+ addr: SocketAddr,
+ outbound: mpsc::Sender<ResolveItem>,
+ waiters: Mutex<HashMap<u64, Waiter>>,
+ task: Mutex<Option<JoinHandle<()>>>,
+ next_token: AtomicU64,
+ closed: AtomicBool,
+}
+
+struct Waiter {
+ caller_id: u64,
+ tx: oneshot::Sender<Result<ResolveOutcome, MuxItemError>>,
+}
+
+#[derive(Debug, Clone)]
+struct StreamFailure {
+ code: Code,
+ message: String,
+ retryable: bool,
+}
+
+impl StreamFailure {
+ fn from_status(status: Status) -> Self {
+ let classified = classify_status(status);
+ match classified {
+ RemoteCallError::Retryable(status) => Self {
+ code: status.code(),
+ message: status.message().to_string(),
+ retryable: true,
+ },
+ RemoteCallError::Terminal(status) => Self {
+ code: status.code(),
+ message: status.message().to_string(),
+ retryable: false,
+ },
+ RemoteCallError::Deadline(deadline) => Self {
+ code: Code::DeadlineExceeded,
+ message: format!("deadline exceeded after {deadline:?}"),
+ retryable: true,
+ },
+ }
+ }
+
+ fn to_remote_error(&self) -> RemoteCallError {
+ let status = Status::new(self.code, self.message.clone());
+ if self.retryable {
+ RemoteCallError::Retryable(status)
+ } else {
+ RemoteCallError::Terminal(status)
+ }
+ }
+}
+
+#[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 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,
+ }
+ }
+}
+
+impl ResolveMux {
+ pub fn new(
+ addr: SocketAddr,
+ channel: Channel,
+ internal_api_secret: String,
+ queue_capacity: usize,
+ ) -> Self {
+ let (outbound, inbound) = mpsc::channel(queue_capacity.max(1));
+ let inner = Arc::new(ResolveMuxInner {
+ addr,
+ outbound,
+ waiters: Mutex::new(HashMap::new()),
+ task: Mutex::new(None),
+ next_token: AtomicU64::new(1),
+ closed: AtomicBool::new(false),
+ });
+ let task_inner = inner.clone();
+ let task = tokio::spawn(async move {
+ run_stream(task_inner, channel, inbound, internal_api_secret).await;
+ });
+ *inner.task.lock().expect("mux task slot poisoned") = Some(task);
+ 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());
+ }
+ 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()));
+ }
+ }
+ }
+ Ok(outcomes)
+ }
+
+ pub fn close(&self) {
+ if self.inner.closed.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ if let Some(task) = self
+ .inner
+ .task
+ .lock()
+ .expect("mux task slot poisoned")
+ .take()
+ {
+ task.abort();
+ }
+ self.inner.fail_all(StreamFailure {
+ code: Code::Unavailable,
+ message: "remote resolution stream closed by endpoint lifecycle".to_string(),
+ retryable: true,
+ });
+ }
+
+ pub fn is_closed(&self) -> bool {
+ 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
+ .waiters
+ .lock()
+ .expect("waiter map poisoned")
+ .len()
+ }
+}
+
+impl ResolveMuxInner {
+ fn next_stream_id(&self) -> u64 {
+ let token = self.next_token.fetch_add(1, Ordering::AcqRel);
+ debug_assert_ne!(token, 0, "stream token counter wrapped");
+ token
+ }
+
+ fn remove_waiter(&self, stream_id: u64) {
+ let mut waiters = self.waiters.lock().expect("waiter map poisoned");
+ waiters.remove(&stream_id);
+ self.record_waiter_count(waiters.len());
+ }
+
+ fn complete(&self, mut outcome: ResolveOutcome) {
+ let waiter = {
+ let mut waiters = self.waiters.lock().expect("waiter map poisoned");
+ let waiter = waiters.remove(&outcome.id);
+ self.record_waiter_count(waiters.len());
+ waiter
+ };
+ let Some(waiter) = waiter else {
+ warn!(
+ endpoint = %self.addr,
+ stream_id = outcome.id,
+ "remote resolution outcome had no waiter"
+ );
+ return;
+ };
+ outcome.id = waiter.caller_id;
+ drop(waiter.tx.send(Ok(outcome)));
+ }
+
+ fn fail_all(&self, failure: StreamFailure) {
+ let waiters: Vec<Waiter> = {
+ let mut waiters = self.waiters.lock().expect("waiter map poisoned");
+ let drained = waiters.drain().map(|(_, waiter)| waiter).collect();
+ self.record_waiter_count(0);
+ drained
+ };
+ for waiter in waiters {
+ drop(waiter.tx.send(Err(MuxItemError::StreamFailed {
+ caller_id: waiter.caller_id,
+ failure: failure.clone(),
+ })));
+ }
+ }
+
+ fn record_waiter_count(&self, count: usize) {
+ metrics::gauge!(
+ REMOTE_RESOLUTION_ENDPOINT_MUX_IN_FLIGHT,
+ "endpoint" => self.addr.to_string(),
+ )
+ .set(count as f64);
+ }
+
+ fn record_admission_rejection(&self, reason: &'static str) {
+ metrics::counter!(
+ REMOTE_RESOLUTION_ENDPOINT_ADMISSION_REJECTIONS,
+ "endpoint" => self.addr.to_string(),
+ "reason" => reason,
+ )
+ .increment(1);
+ }
+}
+
+async fn run_stream(
+ inner: Arc<ResolveMuxInner>,
+ channel: Channel,
+ inbound: mpsc::Receiver<ResolveItem>,
+ internal_api_secret: String,
+) {
+ let outbound = ReceiverStream::new(inbound);
+ let request = match with_internal_api_secret(Request::new(outbound), &internal_api_secret) {
+ Ok(request) => request,
+ Err(status) => {
+ inner.closed.store(true, Ordering::Release);
+ inner.fail_all(StreamFailure::from_status(*status));
+ return;
+ }
+ };
+
+ let mut client = CymbalResolutionClient::new(channel);
+ let response = client.resolve(request).await;
+
+ let mut response_stream = match response {
+ Ok(response) => response.into_inner(),
+ Err(status) => {
+ warn!(endpoint = %inner.addr, error = %status, "remote resolution stream failed to open");
+ inner.closed.store(true, Ordering::Release);
+ inner.fail_all(StreamFailure::from_status(status));
+ return;
+ }
+ };
+
+ loop {
+ match response_stream.next().await {
+ Some(Ok(outcome)) => inner.complete(outcome),
+ Some(Err(status)) => {
+ warn!(endpoint = %inner.addr, error = %status, "remote resolution stream broke");
+ inner.closed.store(true, Ordering::Release);
+ inner.fail_all(StreamFailure::from_status(status));
+ return;
+ }
+ None => {
+ warn!(endpoint = %inner.addr, "remote resolution stream ended");
+ inner.closed.store(true, Ordering::Release);
+ inner.fail_all(StreamFailure {
+ code: Code::Unavailable,
+ message: "remote resolution stream ended".to_string(),
+ retryable: true,
+ });
+ return;
+ }
+ }
+ }
+}
+
+fn overloaded_outcome(id: u64, message: String) -> ResolveOutcome {
+ ResolveOutcome {
+ id,
+ result: Some(resolve_outcome::Result::Error(Error {
+ kind: ErrorKind::Overloaded as i32,
+ message,
+ details_json: Vec::new(),
+ })),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::pin::Pin;
+ use std::sync::atomic::AtomicUsize;
+ use std::sync::Mutex as StdMutex;
+
+ use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::{
+ CymbalResolution, CymbalResolutionServer,
+ };
+ use cymbal_proto::cymbal::resolution::v1::{Done, LoadEvent, SubscribeRequest};
+ use futures::Stream;
+ use tokio_stream::wrappers::ReceiverStream;
+ use tonic::transport::{Endpoint, Server};
+ use tonic::Response;
+
+ use super::*;
+
+ #[derive(Clone, Default)]
+ struct RecordingService {
+ received_ids: Arc<StdMutex<Vec<u64>>>,
+ stream_count: Arc<AtomicUsize>,
+ }
+
+ #[tonic::async_trait]
+ impl CymbalResolution for RecordingService {
+ type ResolveStream = Pin<Box<dyn Stream<Item = Result<ResolveOutcome, Status>> + Send>>;
+ type SubscribeStream = Pin<Box<dyn Stream<Item = Result<LoadEvent, Status>> + Send>>;
+
+ async fn resolve(
+ &self,
+ request: Request<tonic::Streaming<ResolveItem>>,
+ ) -> Result<Response<Self::ResolveStream>, Status> {
+ self.stream_count.fetch_add(1, Ordering::AcqRel);
+ let mut inbound = request.into_inner();
+ let (tx, rx) = mpsc::channel(8);
+ let received_ids = self.received_ids.clone();
+ tokio::spawn(async move {
+ while let Some(item) = inbound.next().await {
+ let item = item.expect("test request item");
+ received_ids
+ .lock()
+ .expect("received ids poisoned")
+ .push(item.id);
+ let outcome = ResolveOutcome {
+ id: item.id,
+ result: Some(resolve_outcome::Result::Done(Done {
+ resolved_exception_json: item.exception_json,
+ })),
+ };
+ tx.send(Ok(outcome)).await.expect("test receiver is alive");
+ }
+ });
+ Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
+ }
+
+ async fn subscribe(
+ &self,
+ _request: Request<SubscribeRequest>,
+ ) -> Result<Response<Self::SubscribeStream>, Status> {
+ Ok(Response::new(Box::pin(futures::stream::empty())))
+ }
+ }
+
+ async fn spawn_test_channel(service: RecordingService) -> (SocketAddr, Channel) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind test server");
+ let addr = listener.local_addr().expect("test server addr");
+ let incoming = futures::stream::unfold(listener, |listener| async {
+ Some((listener.accept().await.map(|(stream, _)| stream), listener))
+ });
+
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(CymbalResolutionServer::new(service))
+ .serve_with_incoming(incoming)
+ .await
+ .expect("test gRPC server exits cleanly");
+ });
+
+ let channel = Endpoint::from_shared(format!("http://{addr}"))
+ .expect("valid test endpoint")
+ .connect()
+ .await
+ .expect("connect test channel");
+ (addr, channel)
+ }
+
+ fn item(id: u64) -> ResolveItem {
+ ResolveItem {
+ id,
+ team_id: 7,
+ exception_json: format!("exception-{id}").into_bytes(),
+ metadata: Vec::new(),
+ deadline_ms: 1_000,
+ }
+ }
+
+ #[tokio::test]
+ async fn resolve_many_reuses_one_stream_and_restores_caller_ids() {
+ let service = RecordingService::default();
+ let received_ids = service.received_ids.clone();
+ let stream_count = service.stream_count.clone();
+ 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");
+ assert_eq!(
+ outcomes
+ .iter()
+ .map(|outcome| outcome.id)
+ .collect::<Vec<_>>(),
+ vec![101, 102]
+ );
+
+ let outcomes = mux
+ .resolve_many(vec![item(103)], Duration::from_secs(1))
+ .await
+ .expect("resolve through existing mux");
+ assert_eq!(outcomes[0].id, 103);
+
+ assert_eq!(stream_count.load(Ordering::Acquire), 1);
+ assert_eq!(
+ received_ids.lock().expect("received ids poisoned").clone(),
+ vec![1, 2, 3]
+ );
+ assert_eq!(mux.waiter_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn closed_mux_returns_overloaded_outcome_without_blocking() {
+ let service = RecordingService::default();
+ let (addr, channel) = spawn_test_channel(service).await;
+ 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))
+ .await
+ .expect("closed mux maps to overloaded item outcome");
+ assert_eq!(outcomes[0].id, 7);
+ assert!(matches!(
+ outcomes[0].result,
+ Some(resolve_outcome::Result::Error(ref err)) if err.kind == ErrorKind::Overloaded as i32
+ ));
+ assert_eq!(mux.waiter_count(), 0);
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/pool.rs b/rust/cymbal/src/stages/resolution/remote/pool.rs
new file mode 100644
index 000000000000..e09288fcac89
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/pool.rs
@@ -0,0 +1,966 @@
+use std::collections::HashMap;
+use std::fmt;
+use std::net::SocketAddr;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::{Duration, Instant};
+
+use rand::seq::SliceRandom;
+use sha2::{Digest, Sha256};
+use thiserror::Error;
+use tokio::sync::{Mutex, Notify};
+use tonic::transport::{Channel, Endpoint};
+use tracing::{info, warn};
+
+use super::config::RemoteResolutionConfig;
+use super::dns::DnsResolver;
+use super::mux::ResolveMux;
+use super::subscription::{spawn_subscription, LoadCell, LoadSnapshot, SubscriptionHandle};
+use crate::metric_consts::{REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT, REMOTE_RESOLUTION_POOL_SIZE};
+
+const RESOLVE_MUX_QUEUE_CAPACITY: usize = 64;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum EndpointPoolEmptyReason {
+ NoEndpoints,
+ NoFreshLoadSnapshots,
+ AllEndpointsDraining,
+}
+
+impl EndpointPoolEmptyReason {
+ pub fn as_metric_tag(self) -> &'static str {
+ match self {
+ Self::NoEndpoints => "no_endpoints",
+ Self::NoFreshLoadSnapshots => "no_fresh_load_snapshots",
+ Self::AllEndpointsDraining => "all_endpoints_draining",
+ }
+ }
+}
+
+impl fmt::Display for EndpointPoolEmptyReason {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::NoEndpoints => "no DNS endpoints",
+ Self::NoFreshLoadSnapshots => "no fresh load snapshots",
+ Self::AllEndpointsDraining => "all endpoints draining",
+ })
+ }
+}
+
+/// Errors returned by [`EndpointPool::select`] and [`EndpointPool::refresh`].
+#[derive(Debug, Error)]
+pub enum EndpointPoolError {
+ #[error("remote resolution pool is empty ({0})")]
+ Empty(EndpointPoolEmptyReason),
+ #[error("dns resolution failed for {host}:{port}: {source}")]
+ Dns {
+ host: String,
+ port: u16,
+ #[source]
+ source: std::io::Error,
+ },
+ #[error("invalid endpoint uri {addr}: {source}")]
+ InvalidEndpoint {
+ addr: SocketAddr,
+ #[source]
+ source: tonic::transport::Error,
+ },
+}
+
+struct EndpointState {
+ channel: Channel,
+ mux: ResolveMux,
+ in_flight: Arc<AtomicUsize>,
+ // 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.
+ draining: bool,
+ /// Latest server-reported load snapshot. Updated by the subscription task
+ /// when one is attached; reads on the routing path are cheap.
+ load: LoadCell,
+ /// Background task subscribing to this endpoint's freshness/draining stream. `None`
+ /// when subscriptions are disabled (test pools constructed via
+ /// [`EndpointPool::from_addrs_without_subscriptions`]).
+ subscription: Option<SubscriptionHandle>,
+}
+
+#[derive(Default)]
+struct PoolInner {
+ endpoints: HashMap<SocketAddr, EndpointState>,
+}
+
+/// Pool of gRPC channels addressed by resolved `SocketAddr`. Refreshed
+/// periodically from DNS. Routes via one of two strategies — rendezvous
+/// hashing on a routing key ([`SelectionStrategy::ByKey`]) or a random pick
+/// ([`SelectionStrategy::Random`]) — over endpoints with a fresh, non-
+/// non-draining load snapshot; retires endpoints that DNS removed.
+pub struct EndpointPool {
+ config: RemoteResolutionConfig,
+ resolver: Arc<dyn DnsResolver>,
+ inner: Mutex<PoolInner>,
+ /// Notified when a subscription reports a fresh non-draining snapshot, so
+ /// readiness checks can wait for actual routability.
+ ready: Arc<Notify>,
+ /// When false, the pool does not spawn per-endpoint subscription tasks.
+ /// Used by tests that drive endpoint state manually.
+ enable_subscriptions: bool,
+}
+
+/// RAII handle to a selected endpoint. Holds the in-flight counter increment
+/// for the duration of the borrow and releases it on drop. The `Channel` is
+/// `Clone` and internally `Arc`-shared, so cloning it for a request is cheap.
+pub struct EndpointPoolHandle {
+ pub addr: SocketAddr,
+ pub channel: Channel,
+ pub mux: ResolveMux,
+ counter: Arc<AtomicUsize>,
+}
+
+impl EndpointPoolHandle {
+ fn new(addr: SocketAddr, channel: Channel, mux: ResolveMux, counter: Arc<AtomicUsize>) -> Self {
+ counter.fetch_add(1, Ordering::AcqRel);
+ Self {
+ addr,
+ channel,
+ mux,
+ counter,
+ }
+ }
+}
+
+impl Drop for EndpointPoolHandle {
+ fn drop(&mut self) {
+ self.counter.fetch_sub(1, Ordering::AcqRel);
+ metrics::gauge!(
+ REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT,
+ "endpoint" => self.addr.to_string(),
+ )
+ .decrement(1.0);
+ }
+}
+
+impl EndpointPool {
+ pub async fn new(
+ config: RemoteResolutionConfig,
+ resolver: Arc<dyn DnsResolver>,
+ ) -> Result<Arc<Self>, EndpointPoolError> {
+ let pool = Arc::new(Self {
+ config,
+ resolver,
+ inner: Mutex::new(PoolInner::default()),
+ ready: Arc::new(Notify::new()),
+ enable_subscriptions: true,
+ });
+ // Eagerly seed the pool so the first request doesn't pay a full DNS
+ // cost. Refresh errors propagate so AppContext bootstrap can fail
+ // loudly when the host is misconfigured.
+ pool.refresh().await?;
+ if pool.inner.lock().await.endpoints.is_empty() {
+ return Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::NoEndpoints,
+ ));
+ }
+ Ok(pool)
+ }
+
+ /// Build a pool from a pre-resolved list of addresses with subscriptions
+ /// enabled. Used by integration tests that point at a real stub server.
+ pub fn from_addrs(
+ config: RemoteResolutionConfig,
+ addrs: &[SocketAddr],
+ ) -> Result<Arc<Self>, EndpointPoolError> {
+ Self::from_addrs_inner(config, addrs, true)
+ }
+
+ /// Build a pool from a pre-resolved list of addresses without spawning
+ /// subscription tasks. Used by unit tests that exercise routing logic
+ /// against manually-injected load snapshots.
+ pub fn from_addrs_without_subscriptions(
+ config: RemoteResolutionConfig,
+ addrs: &[SocketAddr],
+ ) -> Result<Arc<Self>, EndpointPoolError> {
+ Self::from_addrs_inner(config, addrs, false)
+ }
+
+ fn from_addrs_inner(
+ config: RemoteResolutionConfig,
+ addrs: &[SocketAddr],
+ enable_subscriptions: bool,
+ ) -> Result<Arc<Self>, EndpointPoolError> {
+ let pool = Arc::new(Self {
+ config: config.clone(),
+ // Dummy resolver — `refresh` should not be called in this mode.
+ resolver: Arc::new(super::dns::TokioDnsResolver),
+ inner: Mutex::new(PoolInner::default()),
+ ready: Arc::new(Notify::new()),
+ enable_subscriptions,
+ });
+ let mut inner = pool.inner.try_lock().expect("freshly constructed pool");
+ for addr in addrs {
+ let mut state = build_endpoint_state(*addr, &config)?;
+ if enable_subscriptions {
+ state.subscription = Some(spawn_subscription(
+ *addr,
+ state.channel.clone(),
+ state.load.clone(),
+ config.subscribe_tick_hint,
+ config.subscribe_reconnect_backoff,
+ config.internal_api_secret.clone(),
+ pool.ready.clone(),
+ ));
+ }
+ inner.endpoints.insert(*addr, state);
+ }
+ metrics::gauge!(REMOTE_RESOLUTION_POOL_SIZE).set(inner.endpoints.len() as f64);
+ drop(inner);
+ Ok(pool)
+ }
+
+ /// Resolve the configured hostname and reconcile the channel map. New
+ /// addresses get a fresh channel; addresses that disappeared from DNS are
+ /// marked draining and evicted once their in-flight counter reaches zero.
+ pub async fn refresh(&self) -> Result<(), EndpointPoolError> {
+ let resolved = self
+ .resolver
+ .resolve(&self.config.host, self.config.port)
+ .await
+ .map_err(|source| EndpointPoolError::Dns {
+ host: self.config.host.clone(),
+ port: self.config.port,
+ source,
+ });
+
+ let resolved = resolved?;
+
+ let mut inner = self.inner.lock().await;
+ let mut still_present = std::collections::HashSet::new();
+ for addr in &resolved {
+ still_present.insert(*addr);
+ let needs_rebuild = inner
+ .endpoints
+ .get(addr)
+ .is_some_and(|state| state.mux.is_closed());
+ if inner.endpoints.contains_key(addr) && !needs_rebuild {
+ let state = inner.endpoints.get_mut(addr).expect("endpoint exists");
+ // Re-add: any prior draining flag is cleared.
+ state.draining = false;
+ continue;
+ }
+ if needs_rebuild {
+ info!(endpoint = %addr, "rebuilding closed remote resolution endpoint mux");
+ if let Some(state) = inner.endpoints.remove(addr) {
+ state.mux.close();
+ if let Some(handle) = state.subscription {
+ handle.cancel();
+ }
+ }
+ }
+ match build_endpoint_state(*addr, &self.config) {
+ Ok(mut state) => {
+ info!(endpoint = %addr, "added remote resolution endpoint");
+ if self.enable_subscriptions {
+ state.subscription = Some(spawn_subscription(
+ *addr,
+ state.channel.clone(),
+ state.load.clone(),
+ self.config.subscribe_tick_hint,
+ self.config.subscribe_reconnect_backoff,
+ self.config.internal_api_secret.clone(),
+ self.ready.clone(),
+ ));
+ }
+ inner.endpoints.insert(*addr, state);
+ }
+ Err(err) => {
+ warn!(endpoint = %addr, error = %err, "skipping endpoint with invalid uri");
+ }
+ }
+ }
+
+ // Mark previously-known endpoints not in DNS as draining; evict
+ // immediately if they have no in-flight requests.
+ let to_remove: Vec<SocketAddr> = inner
+ .endpoints
+ .iter_mut()
+ .filter_map(|(addr, state)| {
+ if !still_present.contains(addr) {
+ state.draining = true;
+ state.mux.close();
+ if state.in_flight.load(Ordering::Acquire) == 0 {
+ Some(*addr)
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ })
+ .collect();
+ for addr in to_remove {
+ info!(endpoint = %addr, "evicted drained remote resolution endpoint");
+ if let Some(state) = inner.endpoints.remove(&addr) {
+ state.mux.close();
+ if let Some(handle) = state.subscription {
+ handle.cancel();
+ }
+ }
+ }
+
+ let healthy_count = inner
+ .endpoints
+ .values()
+ .filter(|state| !state.draining)
+ .count();
+ metrics::gauge!(REMOTE_RESOLUTION_POOL_SIZE).set(healthy_count as f64);
+
+ Ok(())
+ }
+
+ /// Select an endpoint at random among those with a fresh, non-draining load snapshot. Missing, stale, and draining
+ /// snapshots are excluded from routing.
+ ///
+ /// Production routes via [`Self::select_for_key`] for warm-cache locality;
+ /// this entry point is retained for tests and as a fallback for callers
+ /// that have no useful routing key. `exclude` lists endpoints already
+ /// tried this round so retries avoid them.
+ pub async fn select(
+ &self,
+ exclude: &[SocketAddr],
+ ) -> Result<EndpointPoolHandle, EndpointPoolError> {
+ self.select_inner(SelectionStrategy::Random, exclude).await
+ }
+
+ /// Select an endpoint using rendezvous hashing for the supplied routing
+ /// key. This keeps events that need the same symbol set sticky to one
+ /// cymbal-resolution pod, improving warm-cache locality while still
+ /// spreading distinct keys across the pool. Draining endpoints are
+ /// excluded. `exclude` lists endpoints already tried this round; the
+ /// highest-ranked endpoint not in that set is chosen, so retries
+ /// deterministically avoid the endpoint that just failed.
+ pub async fn select_for_key(
+ &self,
+ routing_key: &str,
+ exclude: &[SocketAddr],
+ ) -> Result<EndpointPoolHandle, EndpointPoolError> {
+ if routing_key.is_empty() {
+ return self.select(exclude).await;
+ }
+ self.select_inner(SelectionStrategy::ByKey { routing_key }, exclude)
+ .await
+ }
+
+ async fn select_inner(
+ &self,
+ strategy: SelectionStrategy<'_>,
+ exclude: &[SocketAddr],
+ ) -> Result<EndpointPoolHandle, EndpointPoolError> {
+ let inner = self.inner.lock().await;
+ if inner.endpoints.is_empty() {
+ return Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::NoEndpoints,
+ ));
+ }
+
+ let now = Instant::now();
+ // Snapshot is fresh for two tick periods after observation. Deriving
+ // staleness from the tick avoids a separate config knob and keeps the
+ // freshness window scaled to whatever cadence the subscription is
+ // running at.
+ let stale_after = self.config.subscribe_tick_hint.saturating_mul(2);
+
+ // Snapshot-required routing: a pod is only routable when its server-
+ // reported LoadEvent snapshot is non-None AND fresh AND not
+ // draining. There is no caller-side fallback — guessing load
+ // from the local in-flight counter is strictly worse than using the
+ // server's own signal, and silently routing on guesses defeats the
+ // purpose of the Subscribe stream. If all pods are excluded, the
+ // caller sees pool_empty with a reason label and retries with backoff.
+ // Bootstrap therefore waits for one Subscribe tick before routing
+ // begins.
+ let mut candidates: Vec<Candidate> = Vec::with_capacity(inner.endpoints.len());
+ let mut active_endpoint_count = 0usize;
+ let mut saw_missing_or_stale_snapshot = false;
+ for (addr, state) in inner.endpoints.iter() {
+ if state.draining {
+ continue;
+ }
+ active_endpoint_count += 1;
+ let Some(snapshot) = state.load.lock().ok().and_then(|guard| guard.clone()) else {
+ saw_missing_or_stale_snapshot = true;
+ continue;
+ };
+ if !snapshot.is_fresh(now, stale_after) {
+ saw_missing_or_stale_snapshot = true;
+ continue;
+ }
+ if snapshot.draining {
+ continue;
+ }
+ candidates.push(Candidate {
+ addr: *addr,
+ channel: state.channel.clone(),
+ mux: state.mux.clone(),
+ counter: state.in_flight.clone(),
+ });
+ }
+
+ if candidates.is_empty() {
+ return Err(EndpointPoolError::Empty(classify_empty_reason(
+ active_endpoint_count,
+ saw_missing_or_stale_snapshot,
+ )));
+ }
+
+ // Prefer endpoints not yet tried this round. If every candidate has
+ // been tried (e.g. a single-endpoint pool, or all others excluded),
+ // fall back to the full set — retrying a pod after backoff beats
+ // failing the batch when it's the only option left.
+ let untried_count = candidates
+ .iter()
+ .filter(|c| !exclude.contains(&c.addr))
+ .count();
+ if untried_count > 0 {
+ candidates.retain(|c| !exclude.contains(&c.addr));
+ }
+
+ let chosen = match strategy {
+ SelectionStrategy::Random => candidates
+ .choose(&mut rand::thread_rng())
+ .expect("non-empty candidates")
+ .clone(),
+ 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")
+ }
+ };
+
+ // Per-endpoint in-flight gauge; emitted only for the chosen endpoint
+ // (not every candidate) to keep the per-selection allocation bounded.
+ metrics::gauge!(
+ REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT,
+ "endpoint" => chosen.addr.to_string(),
+ )
+ .increment(1.0);
+
+ Ok(EndpointPoolHandle::new(
+ chosen.addr,
+ chosen.channel,
+ chosen.mux,
+ chosen.counter,
+ ))
+ }
+
+ /// Wait until at least one endpoint is actually routable: present in DNS,
+ /// not draining, and carrying a fresh non-draining load snapshot.
+ pub async fn wait_ready(&self, timeout: Duration) -> Result<(), EndpointPoolError> {
+ let timeout_at = tokio::time::Instant::now() + timeout;
+ let mut last_reason: EndpointPoolEmptyReason;
+
+ loop {
+ let notified = self.ready.notified();
+ match self.routing_availability().await {
+ Ok(()) => return Ok(()),
+ Err(reason) => last_reason = reason,
+ }
+ tokio::select! {
+ _ = notified => {}
+ _ = tokio::time::sleep_until(timeout_at) => {
+ return Err(EndpointPoolError::Empty(last_reason));
+ }
+ }
+ }
+ }
+
+ async fn routing_availability(&self) -> Result<(), EndpointPoolEmptyReason> {
+ let inner = self.inner.lock().await;
+ if inner.endpoints.is_empty() {
+ return Err(EndpointPoolEmptyReason::NoEndpoints);
+ }
+ let mut active_endpoint_count = 0usize;
+ let mut saw_missing_or_stale_snapshot = false;
+ let now = Instant::now();
+ let stale_after = self.config.subscribe_tick_hint.saturating_mul(2);
+ for state in inner.endpoints.values() {
+ if state.draining {
+ continue;
+ }
+ active_endpoint_count += 1;
+ let Some(snapshot) = state.load.lock().ok().and_then(|guard| guard.clone()) else {
+ saw_missing_or_stale_snapshot = true;
+ continue;
+ };
+ if !snapshot.is_fresh(now, stale_after) {
+ saw_missing_or_stale_snapshot = true;
+ continue;
+ }
+ if !snapshot.draining {
+ return Ok(());
+ }
+ }
+ Err(classify_empty_reason(
+ active_endpoint_count,
+ saw_missing_or_stale_snapshot,
+ ))
+ }
+
+ /// Test/observability helper: snapshot the current endpoints.
+ pub async fn endpoints(&self) -> Vec<SocketAddr> {
+ let inner = self.inner.lock().await;
+ let mut addrs: Vec<SocketAddr> = inner
+ .endpoints
+ .iter()
+ .filter(|(_, state)| !state.draining)
+ .map(|(addr, _)| *addr)
+ .collect();
+ addrs.sort();
+ addrs
+ }
+
+ /// Test-only: inject a synthetic load snapshot for an endpoint so the
+ /// routing logic can be exercised without standing up a real subscription.
+ /// Returns `false` if the endpoint isn't tracked.
+ #[doc(hidden)]
+ pub async fn inject_load_snapshot_for_test(
+ &self,
+ addr: SocketAddr,
+ snapshot: LoadSnapshot,
+ ) -> bool {
+ let inner = self.inner.lock().await;
+ let Some(state) = inner.endpoints.get(&addr) else {
+ return false;
+ };
+ if let Ok(mut slot) = state.load.lock() {
+ let should_notify = !snapshot.draining;
+ *slot = Some(snapshot);
+ if should_notify {
+ self.ready.notify_waiters();
+ }
+ return true;
+ }
+ false
+ }
+}
+
+#[derive(Clone)]
+struct Candidate {
+ addr: SocketAddr,
+ channel: Channel,
+ mux: ResolveMux,
+ counter: Arc<AtomicUsize>,
+}
+
+enum SelectionStrategy<'a> {
+ Random,
+ ByKey { routing_key: &'a str },
+}
+
+fn classify_empty_reason(
+ active_endpoint_count: usize,
+ saw_missing_or_stale_snapshot: bool,
+) -> EndpointPoolEmptyReason {
+ if active_endpoint_count == 0 {
+ EndpointPoolEmptyReason::AllEndpointsDraining
+ } else if saw_missing_or_stale_snapshot {
+ EndpointPoolEmptyReason::NoFreshLoadSnapshots
+ } else {
+ EndpointPoolEmptyReason::AllEndpointsDraining
+ }
+}
+
+fn rendezvous_score(routing_key: &str, addr: SocketAddr) -> u64 {
+ let mut hasher = Sha256::new();
+ hasher.update(routing_key.as_bytes());
+ hasher.update(b"\0");
+ hasher.update(addr.to_string().as_bytes());
+ let digest = hasher.finalize();
+ u64::from_be_bytes(digest[0..8].try_into().expect("sha256 digest has 8 bytes"))
+}
+
+/// Start a background task that periodically calls [`EndpointPool::refresh`].
+/// Returns the join handle so callers can shut it down when needed.
+pub fn spawn_refresh_task(pool: Arc<EndpointPool>) -> tokio::task::JoinHandle<()> {
+ let interval = pool.config.dns_refresh;
+ tokio::spawn(async move {
+ let mut ticker = tokio::time::interval(interval);
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ ticker.tick().await;
+ if let Err(err) = pool.refresh().await {
+ warn!(error = %err, "remote resolution dns refresh failed");
+ }
+ }
+ })
+}
+
+fn build_endpoint_state(
+ addr: SocketAddr,
+ config: &RemoteResolutionConfig,
+) -> Result<EndpointState, EndpointPoolError> {
+ // tonic's `Endpoint` parses the URI and applies channel options. Using
+ // `connect_lazy()` keeps cold endpoints out of the connect path until
+ // they're actually selected, which matters for k8s rolling pods.
+ let uri = format!("http://{addr}");
+ let endpoint = Endpoint::from_shared(uri)
+ .map_err(|source| EndpointPoolError::InvalidEndpoint { addr, source })?;
+ let endpoint = endpoint
+ .connect_timeout(config.connect_timeout)
+ .tcp_keepalive(Some(Duration::from_secs(30)))
+ .keep_alive_while_idle(true);
+ let channel = endpoint.connect_lazy();
+ let mux = ResolveMux::new(
+ addr,
+ channel.clone(),
+ config.internal_api_secret.clone(),
+ RESOLVE_MUX_QUEUE_CAPACITY,
+ );
+ Ok(EndpointState {
+ channel,
+ mux,
+ in_flight: Arc::new(AtomicUsize::new(0)),
+ draining: false,
+ load: Arc::new(StdMutex::new(None)),
+ subscription: None,
+ })
+}
+
+#[cfg(test)]
+mod test {
+ use std::io;
+
+ use async_trait::async_trait;
+ use tokio::sync::Mutex as TokioMutex;
+
+ use super::*;
+
+ fn mock_config() -> RemoteResolutionConfig {
+ RemoteResolutionConfig {
+ host: "cymbal-resolution.test".to_string(),
+ port: 50061,
+ internal_api_secret: "test-secret".to_string(),
+ dns_refresh: Duration::from_secs(1),
+ request_deadline: Duration::from_secs(5),
+ connect_timeout: Duration::from_millis(500),
+ max_retries: 2,
+ retry_backoff: Duration::from_millis(1),
+ retry_max_backoff: Duration::from_millis(2),
+ sample_rate: 1.0,
+ subscribe_tick_hint: Duration::from_millis(50),
+ subscribe_reconnect_backoff: Duration::from_millis(50),
+ }
+ }
+
+ struct FakeResolver(Arc<TokioMutex<Vec<Vec<SocketAddr>>>>);
+
+ #[async_trait]
+ impl DnsResolver for FakeResolver {
+ async fn resolve(&self, _host: &str, _port: u16) -> io::Result<Vec<SocketAddr>> {
+ let mut queued = self.0.lock().await;
+ if queued.is_empty() {
+ Err(io::Error::other("no more fixtures"))
+ } else {
+ Ok(queued.remove(0))
+ }
+ }
+ }
+
+ fn addr(s: &str) -> SocketAddr {
+ s.parse().unwrap()
+ }
+
+ fn fresh_snapshot() -> LoadSnapshot {
+ LoadSnapshot {
+ draining: false,
+ observed_at: Instant::now(),
+ sequence: 1,
+ }
+ }
+
+ #[tokio::test]
+ async fn new_fails_when_dns_returns_no_endpoints() {
+ let queue = Arc::new(TokioMutex::new(vec![Vec::new()]));
+ let result = EndpointPool::new(mock_config(), Arc::new(FakeResolver(queue))).await;
+ assert!(matches!(
+ result,
+ Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::NoEndpoints
+ ))
+ ));
+ }
+
+ #[tokio::test]
+ async fn refresh_adds_new_endpoints_and_drains_removed_ones() {
+ let queue = Arc::new(TokioMutex::new(vec![
+ vec![addr("10.0.0.1:50061"), addr("10.0.0.2:50061")],
+ vec![addr("10.0.0.2:50061"), addr("10.0.0.3:50061")],
+ ]));
+ let pool = EndpointPool::new(mock_config(), Arc::new(FakeResolver(queue.clone())))
+ .await
+ .unwrap();
+ assert_eq!(
+ pool.endpoints().await,
+ vec![addr("10.0.0.1:50061"), addr("10.0.0.2:50061")]
+ );
+
+ pool.refresh().await.unwrap();
+ assert_eq!(
+ pool.endpoints().await,
+ vec![addr("10.0.0.2:50061"), addr("10.0.0.3:50061")]
+ );
+ }
+
+ /// Inject a fresh snapshot on every endpoint of `pool` so
+ /// snapshot-required routing has all endpoints to choose from.
+ async fn inject_uniform_fresh_snapshots(pool: &Arc<EndpointPool>, addrs: &[SocketAddr]) {
+ for a in addrs {
+ assert!(
+ pool.inject_load_snapshot_for_test(*a, fresh_snapshot())
+ .await
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn select_returns_empty_when_no_endpoint_has_a_fresh_snapshot() {
+ // Snapshot-required routing: with no LoadEvent received yet, every
+ // pod is excluded. select() surfaces Empty so the caller can retry
+ // with backoff while subscriptions warm up.
+ let pool = EndpointPool::from_addrs_without_subscriptions(
+ mock_config(),
+ &[addr("10.0.0.1:50061"), addr("10.0.0.2:50061")],
+ )
+ .unwrap();
+ assert!(matches!(
+ pool.select(&[]).await,
+ Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::NoFreshLoadSnapshots
+ ))
+ ));
+ }
+
+ #[tokio::test]
+ async fn select_reports_all_draining_when_every_fresh_snapshot_is_draining() {
+ let pool = EndpointPool::from_addrs_without_subscriptions(
+ mock_config(),
+ &[addr("10.0.0.1:50061"), addr("10.0.0.2:50061")],
+ )
+ .unwrap();
+ let mut draining = fresh_snapshot();
+ draining.draining = true;
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.1:50061"), draining.clone())
+ .await
+ );
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.2:50061"), draining)
+ .await
+ );
+
+ assert!(matches!(
+ pool.select(&[]).await,
+ Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::AllEndpointsDraining
+ ))
+ ));
+ }
+
+ #[tokio::test]
+ async fn wait_ready_requires_a_fresh_non_draining_snapshot() {
+ let pool = EndpointPool::from_addrs_without_subscriptions(
+ mock_config(),
+ &[addr("10.0.0.1:50061")],
+ )
+ .unwrap();
+ assert!(matches!(
+ pool.wait_ready(Duration::from_millis(1)).await,
+ Err(EndpointPoolError::Empty(
+ EndpointPoolEmptyReason::NoFreshLoadSnapshots
+ ))
+ ));
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.1:50061"), fresh_snapshot())
+ .await
+ );
+ pool.wait_ready(Duration::from_millis(1)).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn select_excludes_endpoints_with_stale_snapshots() {
+ // A pod whose snapshot is older than the freshness window is excluded
+ // from routing — the pool does NOT fall back to caller-side
+ // in-flight estimation. The remaining fresh pod is the only candidate.
+ let pool = EndpointPool::from_addrs_without_subscriptions(
+ mock_config(),
+ &[addr("10.0.0.1:50061"), addr("10.0.0.2:50061")],
+ )
+ .unwrap();
+ let stale = LoadSnapshot {
+ draining: false,
+ observed_at: Instant::now() - Duration::from_secs(10),
+ sequence: 1,
+ };
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.1:50061"), stale)
+ .await
+ );
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.2:50061"), fresh_snapshot())
+ .await
+ );
+
+ // .1 is stale and excluded; .2 is the only candidate.
+ for _ in 0..5 {
+ let handle = pool.select(&[]).await.unwrap();
+ assert_eq!(handle.addr, addr("10.0.0.2:50061"));
+ }
+ }
+
+ #[tokio::test]
+ async fn select_spreads_randomly_across_fresh_healthy_endpoints() {
+ 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;
+
+ // All endpoints are fresh and healthy, so random selection should
+ // reach every one of them over enough draws.
+ let mut picks = std::collections::HashSet::new();
+ for _ in 0..200 {
+ picks.insert(pool.select(&[]).await.unwrap().addr);
+ }
+ assert_eq!(picks.len(), addrs.len());
+ }
+
+ #[tokio::test]
+ async fn select_for_key_is_sticky_for_the_same_key() {
+ 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 first = pool
+ .select_for_key("team:1:symbol:bundle-a", &[])
+ .await
+ .unwrap()
+ .addr;
+ for _ in 0..10 {
+ let next = pool
+ .select_for_key("team:1:symbol:bundle-a", &[])
+ .await
+ .unwrap()
+ .addr;
+ assert_eq!(next, first);
+ }
+ }
+
+ #[tokio::test]
+ async fn select_for_key_spreads_distinct_keys_across_endpoints() {
+ 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 mut picks = std::collections::HashSet::new();
+ for idx in 0..64 {
+ let handle = pool
+ .select_for_key(&format!("team:1:symbol:bundle-{idx}"), &[])
+ .await
+ .unwrap();
+ picks.insert(handle.addr);
+ }
+
+ assert!(
+ picks.len() > 1,
+ "distinct routing keys should not all route to one endpoint"
+ );
+ }
+
+ #[tokio::test]
+ async fn select_for_key_avoids_excluded_endpoints_on_retry() {
+ 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 first = pool
+ .select_for_key("team:1:symbol:bundle-a", &[])
+ .await
+ .unwrap()
+ .addr;
+ // Excluding the first pick forces the next-ranked endpoint.
+ let retry = pool
+ .select_for_key("team:1:symbol:bundle-a", &[first])
+ .await
+ .unwrap()
+ .addr;
+ assert_ne!(retry, first);
+
+ // Excluding both forces the third; the result is stable (rendezvous
+ // ranking, not rotation).
+ let third = pool
+ .select_for_key("team:1:symbol:bundle-a", &[first, retry])
+ .await
+ .unwrap()
+ .addr;
+ assert_ne!(third, first);
+ assert_ne!(third, retry);
+ }
+
+ #[tokio::test]
+ async fn select_for_key_excludes_draining_endpoints() {
+ let addrs = [addr("10.0.0.1:50061"), addr("10.0.0.2:50061")];
+ let pool = EndpointPool::from_addrs_without_subscriptions(mock_config(), &addrs).unwrap();
+
+ let mut draining = fresh_snapshot();
+ draining.draining = true;
+ assert!(pool.inject_load_snapshot_for_test(addrs[0], draining).await);
+ assert!(
+ pool.inject_load_snapshot_for_test(addrs[1], fresh_snapshot())
+ .await
+ );
+
+ let handle = pool
+ .select_for_key("team:1:symbol:force-away-from-draining", &[])
+ .await
+ .unwrap();
+ assert_eq!(handle.addr, addrs[1]);
+ }
+
+ #[tokio::test]
+ async fn select_excludes_endpoints_reporting_draining() {
+ let pool = EndpointPool::from_addrs_without_subscriptions(
+ mock_config(),
+ &[addr("10.0.0.1:50061"), addr("10.0.0.2:50061")],
+ )
+ .unwrap();
+ let mut bad = fresh_snapshot();
+ bad.draining = true;
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.1:50061"), bad)
+ .await
+ );
+ assert!(
+ pool.inject_load_snapshot_for_test(addr("10.0.0.2:50061"), fresh_snapshot())
+ .await
+ );
+
+ // Draining endpoints are excluded even when they have fresh snapshots.
+ let handle = pool.select(&[]).await.unwrap();
+ assert_eq!(handle.addr, addr("10.0.0.2:50061"));
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver.rs b/rust/cymbal/src/stages/resolution/remote/resolver.rs
new file mode 100644
index 000000000000..5e12f62643b3
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/resolver.rs
@@ -0,0 +1,343 @@
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cymbal_proto::cymbal::resolution::v1::ResolveItem;
+use futures::future::join_all;
+
+use crate::{
+ error::UnhandledError,
+ stages::{
+ pipeline::ExceptionEventPipelineItem,
+ resolution::{
+ exception::ExceptionResolver, frame::FrameResolver, remote::pool::EndpointPool,
+ ResolutionStage,
+ },
+ },
+ types::{batch::Batch, exception_properties::ExceptionProperties, Exception, ExceptionList},
+};
+
+use super::config::RemoteResolutionConfig;
+
+mod chunk;
+mod partition;
+mod retry;
+
+use chunk::group_events_by_key;
+use partition::partition_batch;
+use retry::resolve_work_item;
+
+/// Context handed to the remote orchestration layer. Cheap to clone because
+/// both the pool handle and config are `Arc`/`Clone`-friendly.
+#[derive(Clone)]
+pub struct RemoteResolutionContext {
+ pub pool: Arc<EndpointPool>,
+ pub config: RemoteResolutionConfig,
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Top-level pipeline
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Resolve a whole stage batch through the remote pool.
+///
+/// Flow:
+/// 1. Partition the batch into errored / empty-passthrough / local / remote.
+/// 2. Resolve local events inline (same path as no-remote mode).
+/// 3. Group remote events by routing key, submit one logical work item per
+/// exception, and let each item reroute independently through the mux.
+/// 4. Assemble back into the original batch order.
+///
+/// Each event passes through exactly one bucket and writes itself into the
+/// output exactly once. There is no shared mutation across RPC boundaries.
+pub async fn resolve_batch(
+ batch: Batch<ExceptionEventPipelineItem>,
+ ctx: RemoteResolutionContext,
+ local_stage: ResolutionStage,
+) -> Result<Batch<ExceptionEventPipelineItem>, UnhandledError> {
+ let batch_len = batch.len();
+ let partition = partition_batch(batch, ctx.config.sample_rate)?;
+
+ let local_resolved = resolve_local_events(partition.local, local_stage).await?;
+ let remote_resolved = resolve_remote_events(&ctx, partition.remote).await?;
+
+ assemble_output(
+ batch_len,
+ partition.errors,
+ partition.empty,
+ local_resolved,
+ remote_resolved,
+ )
+}
+
+fn assemble_output(
+ batch_len: usize,
+ errors: Vec<(usize, ExceptionEventPipelineItem)>,
+ empty: Vec<(usize, ExceptionEventPipelineItem)>,
+ local: Vec<(usize, ExceptionEventPipelineItem)>,
+ remote: Vec<(usize, ExceptionEventPipelineItem)>,
+) -> Result<Batch<ExceptionEventPipelineItem>, UnhandledError> {
+ let mut output: Vec<Option<ExceptionEventPipelineItem>> =
+ (0..batch_len).map(|_| None).collect();
+ for (idx, item) in errors.into_iter().chain(empty).chain(local).chain(remote) {
+ output[idx] = Some(item);
+ }
+ let resolved: Vec<ExceptionEventPipelineItem> = output
+ .into_iter()
+ .enumerate()
+ .map(|(idx, slot)| {
+ slot.ok_or_else(|| {
+ UnhandledError::Other(format!("remote resolution left output slot {idx} unfilled"))
+ })
+ })
+ .collect::<Result<_, _>>()?;
+ Ok(Batch::from(resolved))
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Shared data types: an event, exception work item, and resolved slot
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// A sampled-remote event with its wire payloads pre-serialized.
+///
+/// Owning the serialized bytes alongside the event means each `RemoteEvent`
+/// moves through the work-item → RPC → apply pipeline by value. No shared
+/// mutable state, no `Option<>` sentinels in the RPC layer, no wire-level
+/// batch bookkeeping.
+struct RemoteEvent {
+ batch_index: usize,
+ evt: ExceptionProperties,
+ /// One serialized exception per `evt.exception_list` entry, in order.
+ exception_jsons: Vec<Vec<u8>>,
+ /// Shared across this event's exceptions on the wire. The proto carries
+ /// it per-item; this is the per-event source bytes we clone from.
+ metadata: Vec<u8>,
+}
+
+impl RemoteEvent {
+ fn item_count(&self) -> usize {
+ self.evt.exception_list.len()
+ }
+}
+
+struct RemoteEventSlot {
+ batch_index: usize,
+ evt: ExceptionProperties,
+ resolved: Vec<Option<Exception>>,
+}
+
+/// One logical exception-level item. `token` is client-side only: the mux may
+/// replace it with a per-stream token and restores it before returning.
+struct RemoteWorkItem {
+ token: u64,
+ routing_key: String,
+ event_slot: usize,
+ exception_slot: usize,
+ item: ResolveItem,
+}
+
+impl RemoteWorkItem {
+ fn to_item(&self, deadline: Duration) -> ResolveItem {
+ let mut item = self.item.clone();
+ item.id = self.token;
+ item.deadline_ms = deadline.as_millis().clamp(1, u32::MAX as u128) as u32;
+ item
+ }
+}
+
+struct ResolvedRemoteItem {
+ event_slot: usize,
+ exception_slot: usize,
+ exception: Exception,
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Local resolution path (passthrough to the inline stage)
+// ─────────────────────────────────────────────────────────────────────────────
+
+async fn resolve_local_events(
+ local_events: Vec<(usize, ExceptionProperties)>,
+ local_stage: ResolutionStage,
+) -> Result<Vec<(usize, ExceptionEventPipelineItem)>, UnhandledError> {
+ if local_events.is_empty() {
+ return Ok(Vec::new());
+ }
+ let (indexes, events): (Vec<usize>, Vec<ExceptionProperties>) =
+ local_events.into_iter().unzip();
+ let batch = Batch::from(events.into_iter().map(Ok).collect::<Vec<_>>())
+ .apply_operator(ExceptionResolver, local_stage.clone())
+ .await?
+ .apply_operator(FrameResolver, local_stage)
+ .await?;
+ Ok(indexes.into_iter().zip(batch.into_iter()).collect())
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Remote resolution path: group → flatten → reroute independently → apply
+// ─────────────────────────────────────────────────────────────────────────────
+
+async fn resolve_remote_events(
+ ctx: &RemoteResolutionContext,
+ events: Vec<RemoteEvent>,
+) -> Result<Vec<(usize, ExceptionEventPipelineItem)>, UnhandledError> {
+ if events.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let (mut event_slots, work_items) = build_work_items(events)?;
+ let deadline = Instant::now()
+ .checked_add(ctx.config.request_deadline)
+ .unwrap_or_else(Instant::now);
+
+ let resolved = join_all(
+ work_items
+ .into_iter()
+ .map(|work_item| resolve_work_item(ctx, work_item, deadline)),
+ )
+ .await;
+
+ for result in resolved {
+ let item = result?;
+ let Some(event_slot) = event_slots.get_mut(item.event_slot) else {
+ return Err(UnhandledError::Other(format!(
+ "remote resolution returned invalid event slot {}",
+ item.event_slot
+ )));
+ };
+ let Some(slot) = event_slot.resolved.get_mut(item.exception_slot) else {
+ return Err(UnhandledError::Other(format!(
+ "remote resolution returned invalid exception slot {} for event slot {}",
+ item.exception_slot, item.event_slot
+ )));
+ };
+ if slot.replace(item.exception).is_some() {
+ return Err(UnhandledError::Other(format!(
+ "remote resolution filled event slot {} exception slot {} twice",
+ item.event_slot, item.exception_slot
+ )));
+ }
+ }
+
+ event_slots
+ .into_iter()
+ .map(|mut event| {
+ let exceptions = event
+ .resolved
+ .into_iter()
+ .enumerate()
+ .map(|(exception_slot, slot)| {
+ slot.ok_or_else(|| {
+ UnhandledError::Other(format!(
+ "remote resolution left event slot {} exception slot {exception_slot} unfilled",
+ event.batch_index
+ ))
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ event.evt.exception_list = ExceptionList::from(exceptions);
+ Ok((event.batch_index, Ok(event.evt)))
+ })
+ .collect()
+}
+
+fn build_work_items(
+ events: Vec<RemoteEvent>,
+) -> Result<(Vec<RemoteEventSlot>, Vec<RemoteWorkItem>), UnhandledError> {
+ let mut event_slots = Vec::new();
+ let mut work_items = Vec::new();
+ let mut next_token = 1u64;
+
+ for (routing_key, events_for_key) in group_events_by_key(events) {
+ for event in events_for_key {
+ let event_slot = event_slots.len();
+ let item_count = event.item_count();
+ let team_id = event.evt.team_id;
+
+ for (exception_slot, exception_json) in
+ event.exception_jsons.iter().cloned().enumerate()
+ {
+ let token = next_token;
+ next_token = next_token.checked_add(1).ok_or_else(|| {
+ UnhandledError::Other(
+ "remote resolution work item token overflowed".to_string(),
+ )
+ })?;
+ work_items.push(RemoteWorkItem {
+ token,
+ routing_key: routing_key.clone(),
+ event_slot,
+ exception_slot,
+ item: ResolveItem {
+ id: token,
+ team_id,
+ exception_json,
+ metadata: event.metadata.clone(),
+ deadline_ms: 0,
+ },
+ });
+ }
+
+ event_slots.push(RemoteEventSlot {
+ batch_index: event.batch_index,
+ evt: event.evt,
+ resolved: (0..item_count).map(|_| None).collect(),
+ });
+ }
+ }
+
+ Ok((event_slots, work_items))
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+ use uuid::Uuid;
+
+ use super::*;
+
+ #[test]
+ fn build_work_items_assigns_client_tokens_and_slots_without_batch_ids() {
+ let events = vec![fake_remote_event(2, 3, 2), fake_remote_event(1, 7, 1)];
+ let (event_slots, work_items) = build_work_items(events).expect("build work items");
+
+ assert_eq!(event_slots.len(), 2);
+ assert_eq!(work_items.len(), 3);
+ assert_eq!(
+ work_items.iter().map(|item| item.token).collect::<Vec<_>>(),
+ vec![1, 2, 3]
+ );
+ assert_eq!(
+ work_items
+ .iter()
+ .map(|item| (item.event_slot, item.exception_slot))
+ .collect::<Vec<_>>(),
+ vec![(0, 0), (1, 0), (1, 1)]
+ );
+ assert!(work_items.iter().all(|item| item.item.deadline_ms == 0));
+ }
+
+ fn fake_remote_event(team_id: i32, batch_index: usize, n_exceptions: usize) -> RemoteEvent {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": (0..n_exceptions)
+ .map(|i| json!({
+ "type": "Error",
+ "value": format!("boom-{i}"),
+ }))
+ .collect::<Vec<_>>()
+ }))
+ .expect("valid exception properties");
+ evt.team_id = team_id;
+ evt.uuid = Uuid::from_u128(0xABCD_0000_0000_0000 ^ (batch_index as u128));
+
+ let exception_jsons = evt
+ .exception_list
+ .iter()
+ .map(|exc| serde_json::to_vec(exc).expect("serialize exception"))
+ .collect();
+ RemoteEvent {
+ batch_index,
+ evt,
+ exception_jsons,
+ metadata: Vec::new(),
+ }
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver/chunk.rs b/rust/cymbal/src/stages/resolution/remote/resolver/chunk.rs
new file mode 100644
index 000000000000..446949eeaf4f
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/resolver/chunk.rs
@@ -0,0 +1,102 @@
+//! Group remote events by routing key. Work is submitted per exception; this
+//! module keeps only the routing-key helpers shared with the pool.
+
+use std::collections::BTreeMap;
+
+use crate::types::exception_properties::ExceptionProperties;
+
+use super::RemoteEvent;
+
+/// Group events by their per-team routing key. `BTreeMap` keeps the key
+/// iteration order deterministic.
+pub(super) fn group_events_by_key(events: Vec<RemoteEvent>) -> BTreeMap<String, Vec<RemoteEvent>> {
+ let mut by_key: BTreeMap<String, Vec<RemoteEvent>> = BTreeMap::new();
+ for event in events {
+ by_key
+ .entry(routing_key_for_event(&event.evt))
+ .or_default()
+ .push(event);
+ }
+ by_key
+}
+
+fn routing_key_for_event(evt: &ExceptionProperties) -> String {
+ // Per-team routing: every exception of an event hashes to the same pod
+ // via rendezvous selection in `EndpointPool::select_for_key`. One team's
+ // bursts land on one preferred pod. Overload spillover is driven by
+ // per-item outcomes from the resolver.
+ format!("team:{}", evt.team_id)
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+ use uuid::Uuid;
+
+ use super::*;
+
+ #[test]
+ fn routing_key_is_per_team_regardless_of_exception_internals() {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": [{
+ "type": "Error",
+ "value": "boom",
+ "stacktrace": {
+ "type": "raw",
+ "frames": [{
+ "platform": "web:javascript",
+ "filename": "https://example.com/app.js",
+ "function": "minified",
+ "lineno": 1,
+ "colno": 2,
+ "chunk_id": "chunk-a"
+ }]
+ }
+ }]
+ }))
+ .expect("valid exception properties");
+ evt.team_id = 7;
+ assert_eq!(routing_key_for_event(&evt), "team:7");
+ }
+
+ #[test]
+ fn group_events_by_key_separates_events_by_team() {
+ let events = vec![
+ fake_remote_event(1, 0, 1),
+ fake_remote_event(2, 1, 1),
+ fake_remote_event(1, 2, 1),
+ fake_remote_event(2, 3, 1),
+ ];
+ let grouped = group_events_by_key(events);
+ let keys: Vec<&String> = grouped.keys().collect();
+ assert_eq!(keys, vec!["team:1", "team:2"]);
+ assert_eq!(grouped["team:1"].len(), 2);
+ assert_eq!(grouped["team:2"].len(), 2);
+ }
+
+ fn fake_remote_event(team_id: i32, batch_index: usize, n_exceptions: usize) -> RemoteEvent {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": (0..n_exceptions)
+ .map(|i| json!({
+ "type": "Error",
+ "value": format!("boom-{i}"),
+ }))
+ .collect::<Vec<_>>()
+ }))
+ .expect("valid exception properties");
+ evt.team_id = team_id;
+ evt.uuid = Uuid::from_u128(0xABCD_0000_0000_0000 ^ (batch_index as u128));
+
+ let exception_jsons = evt
+ .exception_list
+ .iter()
+ .map(|exc| serde_json::to_vec(exc).expect("serialize exception"))
+ .collect();
+ RemoteEvent {
+ batch_index,
+ evt,
+ exception_jsons,
+ metadata: Vec::new(),
+ }
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver/partition.rs b/rust/cymbal/src/stages/resolution/remote/resolver/partition.rs
new file mode 100644
index 000000000000..f2eeaf3a6bc9
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/resolver/partition.rs
@@ -0,0 +1,144 @@
+//! Split a stage batch into errored / empty / local / remote buckets and
+//! decide, per event, whether it samples into remote resolution.
+
+use sha2::{Digest, Sha256};
+
+use crate::error::UnhandledError;
+use crate::metric_consts::REMOTE_RESOLUTION_SAMPLING;
+use crate::stages::pipeline::ExceptionEventPipelineItem;
+use crate::types::{batch::Batch, exception_properties::ExceptionProperties};
+
+use super::RemoteEvent;
+
+pub(super) struct Partition {
+ pub(super) errors: Vec<(usize, ExceptionEventPipelineItem)>,
+ pub(super) empty: Vec<(usize, ExceptionEventPipelineItem)>,
+ pub(super) local: Vec<(usize, ExceptionProperties)>,
+ pub(super) remote: Vec<RemoteEvent>,
+}
+
+pub(super) fn partition_batch(
+ batch: Batch<ExceptionEventPipelineItem>,
+ sample_rate: f64,
+) -> Result<Partition, UnhandledError> {
+ let mut errors = Vec::new();
+ let mut empty = Vec::new();
+ let mut local = Vec::new();
+ let mut remote = Vec::new();
+
+ for (batch_index, item) in batch.into_iter().enumerate() {
+ let evt = match item {
+ Ok(evt) => evt,
+ Err(err) => {
+ errors.push((batch_index, Err(err)));
+ continue;
+ }
+ };
+
+ if evt.exception_list.is_empty() {
+ empty.push((batch_index, Ok(evt)));
+ continue;
+ }
+
+ if should_route_event_to_remote(&evt, sample_rate) {
+ metrics::counter!(REMOTE_RESOLUTION_SAMPLING, "decision" => "remote").increment(1);
+ remote.push(prepare_remote_event(batch_index, evt)?);
+ } else {
+ metrics::counter!(REMOTE_RESOLUTION_SAMPLING, "decision" => "local").increment(1);
+ local.push((batch_index, evt));
+ }
+ }
+
+ Ok(Partition {
+ errors,
+ empty,
+ local,
+ remote,
+ })
+}
+
+fn prepare_remote_event(
+ batch_index: usize,
+ evt: ExceptionProperties,
+) -> Result<RemoteEvent, UnhandledError> {
+ let exception_jsons: Vec<Vec<u8>> = evt
+ .exception_list
+ .iter()
+ .map(|exc| serde_json::to_vec(exc).map_err(UnhandledError::from))
+ .collect::<Result<_, _>>()?;
+ let metadata = if evt.debug_images.is_empty() {
+ Vec::new()
+ } else {
+ serde_json::to_vec(&serde_json::json!({
+ "apple_debug_images_json": evt.debug_images,
+ }))
+ .map_err(UnhandledError::from)?
+ };
+ Ok(RemoteEvent {
+ batch_index,
+ evt,
+ exception_jsons,
+ metadata,
+ })
+}
+
+fn should_route_event_to_remote(evt: &ExceptionProperties, sample_rate: f64) -> bool {
+ if sample_rate <= 0.0 {
+ return false;
+ }
+ if sample_rate >= 1.0 {
+ return true;
+ }
+
+ let mut hasher = Sha256::new();
+ hasher.update(evt.team_id.to_be_bytes());
+ hasher.update(evt.uuid.as_bytes());
+ let digest = hasher.finalize();
+ let bucket_bytes: [u8; 8] = digest[..8]
+ .try_into()
+ .expect("sha256 digest always contains at least 8 bytes");
+ let bucket = u64::from_be_bytes(bucket_bytes) as f64 / ((u64::MAX as f64) + 1.0);
+ bucket < sample_rate
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+ use uuid::Uuid;
+
+ use super::*;
+
+ #[test]
+ fn sampling_decision_is_stable_for_same_team_and_event_uuid() {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": [{
+ "type": "Error",
+ "value": "boom"
+ }]
+ }))
+ .expect("valid exception properties");
+ evt.team_id = 123;
+ evt.uuid = Uuid::from_u128(0x123456789abcdef);
+
+ let first = should_route_event_to_remote(&evt, 0.37);
+ for _ in 0..100 {
+ assert_eq!(should_route_event_to_remote(&evt, 0.37), first);
+ }
+ }
+
+ #[test]
+ fn sampling_decision_respects_rate_boundaries() {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": [{
+ "type": "Error",
+ "value": "boom"
+ }]
+ }))
+ .expect("valid exception properties");
+ evt.team_id = 123;
+ evt.uuid = Uuid::from_u128(0x123456789abcdef);
+
+ assert!(!should_route_event_to_remote(&evt, 0.0));
+ assert!(should_route_event_to_remote(&evt, 1.0));
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs
new file mode 100644
index 000000000000..2940ffe1502b
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs
@@ -0,0 +1,477 @@
+//! Per-exception reroute layer: submit one logical item to the selected
+//! endpoint mux, classify its terminal outcome, and retry/reroute only that
+//! item until its shared deadline or retry budget is exhausted.
+
+use std::net::SocketAddr;
+use std::time::{Duration, Instant};
+
+use rand::Rng;
+use tracing::warn;
+
+use cymbal_proto::cymbal::resolution::v1::{resolve_outcome, ErrorKind, ResolveOutcome};
+
+use crate::error::UnhandledError;
+use crate::metric_consts::{
+ REMOTE_RESOLUTION_ERROR_KINDS, REMOTE_RESOLUTION_LATENCY,
+ REMOTE_RESOLUTION_OVERLOAD_ESCALATIONS, REMOTE_RESOLUTION_REQUESTS,
+ REMOTE_RESOLUTION_REROUTE_DEPTH,
+};
+use crate::types::Exception;
+
+use super::{RemoteResolutionContext, RemoteWorkItem, ResolvedRemoteItem};
+
+pub(super) async fn resolve_work_item(
+ ctx: &RemoteResolutionContext,
+ work_item: RemoteWorkItem,
+ deadline: Instant,
+) -> Result<ResolvedRemoteItem, UnhandledError> {
+ let max_attempts = ctx.config.max_retries.saturating_add(1);
+ let mut excluded_endpoints: Vec<SocketAddr> = Vec::new();
+ let mut last_error: Option<String> = None;
+ let mut attempts_used = 0u32;
+
+ for attempt in 0..max_attempts {
+ attempts_used = attempt + 1;
+ let remaining = remaining_deadline(deadline)?;
+ let handle = match ctx
+ .pool
+ .select_for_key(&work_item.routing_key, &excluded_endpoints)
+ .await
+ {
+ Ok(handle) => handle,
+ Err(err) => {
+ let reason = match &err {
+ crate::stages::resolution::remote::pool::EndpointPoolError::Empty(reason) => {
+ reason.as_metric_tag()
+ }
+ _ => "unknown",
+ };
+ metrics::counter!(
+ REMOTE_RESOLUTION_REQUESTS,
+ "outcome" => "pool_empty",
+ "reason" => reason,
+ )
+ .increment(1);
+ last_error = Some(format!("pool unavailable: {err}"));
+ if attempt + 1 < max_attempts {
+ sleep_with_deadline(generic_retry_backoff_for(ctx, attempt, None), deadline)
+ .await?;
+ }
+ continue;
+ }
+ };
+
+ let endpoint = handle.addr;
+ let start = Instant::now();
+ let outcome = handle
+ .mux
+ .resolve_many(vec![work_item.to_item(remaining)], remaining)
+ .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() => {
+ metrics::counter!(
+ REMOTE_RESOLUTION_REQUESTS,
+ "outcome" => "transport_retry",
+ "reason" => err.reason_tag(),
+ )
+ .increment(1);
+ warn!(
+ endpoint = %endpoint,
+ token = work_item.token,
+ attempt,
+ error = %err,
+ reason = err.reason_tag(),
+ "remote resolution transport-level retry for item"
+ );
+ excluded_endpoints.push(endpoint);
+ last_error = Some(err.to_string());
+ if attempt + 1 < max_attempts {
+ sleep_with_deadline(generic_retry_backoff_for(ctx, attempt, None), deadline)
+ .await?;
+ }
+ continue;
+ }
+ Err(err) => {
+ metrics::counter!(
+ REMOTE_RESOLUTION_REQUESTS,
+ "outcome" => "terminal",
+ "reason" => err.reason_tag(),
+ )
+ .increment(1);
+ record_reroute_depth("terminal", attempts_used);
+ return Err(UnhandledError::Other(format!(
+ "remote resolution failed terminally for item {}: {err}",
+ work_item.token
+ )));
+ }
+ };
+
+ metrics::histogram!(REMOTE_RESOLUTION_LATENCY).record(elapsed_ms);
+ let Some(outcome) = single_outcome(work_item.token, outcomes)? else {
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "missing_items")
+ .increment(1);
+ last_error = Some(format!(
+ "missing item outcome from {endpoint} for token {}",
+ work_item.token
+ ));
+ if attempt + 1 < max_attempts {
+ sleep_with_deadline(generic_retry_backoff_for(ctx, attempt, None), deadline)
+ .await?;
+ }
+ continue;
+ };
+
+ let decision = match classify_outcome(&work_item, outcome) {
+ Ok(decision) => decision,
+ Err(err) => {
+ record_reroute_depth("terminal_item", attempts_used);
+ return Err(err);
+ }
+ };
+
+ match decision {
+ ItemDecision::Done(exception) => {
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "ok").increment(1);
+ record_reroute_depth("ok", attempts_used);
+ return Ok(ResolvedRemoteItem {
+ event_slot: work_item.event_slot,
+ exception_slot: work_item.exception_slot,
+ exception,
+ });
+ }
+ ItemDecision::Overloaded(message) => {
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "overloaded_item")
+ .increment(1);
+ metrics::counter!(REMOTE_RESOLUTION_OVERLOAD_ESCALATIONS).increment(1);
+ warn!(
+ endpoint = %endpoint,
+ token = work_item.token,
+ attempt,
+ "remote resolution returned item overload; rerouting with overload policy"
+ );
+ excluded_endpoints.push(endpoint);
+ last_error = Some(format!(
+ "per-item Overloaded outcome from {endpoint}: {message}"
+ ));
+ if attempt + 1 < max_attempts {
+ sleep_with_deadline(overload_backoff_for(ctx, attempt), deadline).await?;
+ }
+ }
+ ItemDecision::Retry {
+ message,
+ retry_after,
+ } => {
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "retryable_item")
+ .increment(1);
+ warn!(
+ endpoint = %endpoint,
+ token = work_item.token,
+ attempt,
+ "remote resolution returned item retry; rerouting"
+ );
+ excluded_endpoints.push(endpoint);
+ last_error = Some(format!("per-item Retry outcome from {endpoint}: {message}"));
+ if attempt + 1 < max_attempts {
+ sleep_with_deadline(
+ generic_retry_backoff_for(ctx, attempt, retry_after),
+ deadline,
+ )
+ .await?;
+ }
+ }
+ }
+ }
+
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "exhausted").increment(1);
+ record_reroute_depth("exhausted", attempts_used);
+ Err(UnhandledError::Other(format!(
+ "remote resolution exhausted retries for item {} ({} attempt(s)): {}",
+ work_item.token,
+ max_attempts,
+ last_error.unwrap_or_else(|| "no recorded cause".to_string()),
+ )))
+}
+
+fn single_outcome(
+ token: u64,
+ outcomes: Vec<ResolveOutcome>,
+) -> Result<Option<ResolveOutcome>, UnhandledError> {
+ let mut matching = None;
+ for outcome in outcomes {
+ if outcome.id != token {
+ warn!(
+ token,
+ outcome_id = outcome.id,
+ "remote resolution outcome id did not match submitted item; ignoring outcome"
+ );
+ continue;
+ }
+ if matching.replace(outcome).is_some() {
+ return Err(UnhandledError::Other(format!(
+ "remote resolution returned duplicate outcome for item {token}"
+ )));
+ }
+ }
+ Ok(matching)
+}
+
+#[derive(Debug)]
+enum ItemDecision {
+ Done(Exception),
+ Overloaded(String),
+ Retry {
+ message: String,
+ retry_after: Option<Duration>,
+ },
+}
+
+fn classify_outcome(
+ work_item: &RemoteWorkItem,
+ outcome: ResolveOutcome,
+) -> Result<ItemDecision, UnhandledError> {
+ let Some(result) = outcome.result else {
+ return Err(terminal_item_error(
+ work_item.token,
+ "remote resolution outcome had no result".to_string(),
+ ));
+ };
+
+ match result {
+ resolve_outcome::Result::Done(done) => {
+ let exception = serde_json::from_slice::<Exception>(&done.resolved_exception_json)
+ .map_err(|err| {
+ terminal_item_error(
+ work_item.token,
+ format!("invalid_done_payload: failed to parse resolved exception: {err}"),
+ )
+ })?;
+ Ok(ItemDecision::Done(exception))
+ }
+ resolve_outcome::Result::Retry(retry) => {
+ let retry_after = (retry.retry_after_ms > 0)
+ .then(|| Duration::from_millis(retry.retry_after_ms as u64));
+ Ok(ItemDecision::Retry {
+ message: retry.message,
+ retry_after,
+ })
+ }
+ resolve_outcome::Result::Error(err) => {
+ let kind = ErrorKind::try_from(err.kind).unwrap_or(ErrorKind::Unspecified);
+ metrics::counter!(REMOTE_RESOLUTION_ERROR_KINDS, "kind" => error_kind_label(kind))
+ .increment(1);
+ match kind {
+ ErrorKind::Overloaded => Ok(ItemDecision::Overloaded(err.message)),
+ ErrorKind::Poison => Err(terminal_item_error(
+ work_item.token,
+ format!(
+ "remote resolution returned poison item; failing batch under all-or-nothing policy until DLQ plumbing is added: {}",
+ err.message
+ ),
+ )),
+ ErrorKind::InvalidPayload | ErrorKind::Unhandled => Err(terminal_item_error(
+ work_item.token,
+ format!(
+ "remote resolution returned terminal item error {}: {}",
+ kind.as_str_name(),
+ err.message
+ ),
+ )),
+ ErrorKind::Unspecified => Err(terminal_item_error(
+ work_item.token,
+ format!(
+ "remote resolution returned unspecified item error: {}",
+ err.message
+ ),
+ )),
+ }
+ }
+ }
+}
+
+fn terminal_item_error(token: u64, message: String) -> UnhandledError {
+ metrics::counter!(REMOTE_RESOLUTION_REQUESTS, "outcome" => "items_failed").increment(1);
+ UnhandledError::Other(format!(
+ "remote resolution item {token} failed terminally; failing batch under all-or-nothing rollout policy ({message})"
+ ))
+}
+
+fn remaining_deadline(deadline: Instant) -> Result<Duration, UnhandledError> {
+ deadline
+ .checked_duration_since(Instant::now())
+ .ok_or_else(|| {
+ UnhandledError::Other(
+ "remote resolution item deadline elapsed before completion".to_string(),
+ )
+ })
+}
+
+async fn sleep_with_deadline(backoff: Duration, deadline: Instant) -> Result<(), UnhandledError> {
+ let remaining = remaining_deadline(deadline)?;
+ tokio::time::sleep(backoff.min(remaining)).await;
+ Ok(())
+}
+
+/// Exponential backoff with jitter for the n-th retry (0-indexed). Each step
+/// doubles the base, capped at `retry_max_backoff`; up to ~50% random jitter
+/// is added so a fleet of cymbal pods doesn't synchronize retries.
+fn generic_retry_backoff_for(
+ ctx: &RemoteResolutionContext,
+ retry_index: u32,
+ retry_after: Option<Duration>,
+) -> Duration {
+ let computed = jittered_backoff(ctx, retry_index);
+ retry_after
+ .map(|hint| hint.max(computed).min(ctx.config.retry_max_backoff))
+ .unwrap_or(computed)
+}
+
+fn overload_backoff_for(ctx: &RemoteResolutionContext, retry_index: u32) -> Duration {
+ jittered_backoff(ctx, retry_index)
+}
+
+fn jittered_backoff(ctx: &RemoteResolutionContext, retry_index: u32) -> Duration {
+ let base_ms = ctx.config.retry_backoff.as_millis() as u64;
+ let cap_ms = ctx.config.retry_max_backoff.as_millis() as u64;
+ let exp = retry_index.min(16);
+ let scaled = base_ms.saturating_mul(1u64 << exp).min(cap_ms);
+ let jitter = if scaled == 0 {
+ 0
+ } else {
+ rand::thread_rng().gen_range(0..=scaled / 2)
+ };
+ Duration::from_millis(scaled.saturating_add(jitter).min(cap_ms))
+}
+
+fn record_reroute_depth(outcome: &'static str, attempts_used: u32) {
+ metrics::histogram!(REMOTE_RESOLUTION_REROUTE_DEPTH, "outcome" => outcome)
+ .record(attempts_used.saturating_sub(1) as f64);
+}
+
+fn error_kind_label(kind: ErrorKind) -> &'static str {
+ match kind {
+ ErrorKind::Unspecified => "unspecified",
+ ErrorKind::InvalidPayload => "invalid_payload",
+ ErrorKind::Poison => "poison",
+ ErrorKind::Unhandled => "unhandled",
+ ErrorKind::Overloaded => "overloaded",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use cymbal_proto::cymbal::resolution::v1::{Done, Error, Retry};
+
+ use super::*;
+
+ #[test]
+ fn classify_outcome_parses_done_exception() {
+ let work_item = work_item(7);
+ let outcome = ResolveOutcome {
+ id: 7,
+ result: Some(resolve_outcome::Result::Done(Done {
+ resolved_exception_json: serde_json::to_vec(&exception("Resolved"))
+ .expect("valid exception"),
+ })),
+ };
+
+ let decision = classify_outcome(&work_item, outcome).expect("done outcome");
+ assert!(matches!(decision, ItemDecision::Done(exc) if exc.exception_type == "Resolved"));
+ }
+
+ #[test]
+ fn classify_outcome_reroutes_overload() {
+ let work_item = work_item(7);
+ let outcome = error_outcome(ErrorKind::Overloaded, "busy");
+ let decision = classify_outcome(&work_item, outcome).expect("overload reroutes");
+ assert!(matches!(decision, ItemDecision::Overloaded(message) if message == "busy"));
+ }
+
+ #[test]
+ fn classify_outcome_reroutes_retry_with_hint() {
+ let work_item = work_item(7);
+ let outcome = ResolveOutcome {
+ id: 7,
+ result: Some(resolve_outcome::Result::Retry(Retry {
+ code: "transient".to_string(),
+ message: "try again".to_string(),
+ retry_after_ms: 25,
+ })),
+ };
+ let decision = classify_outcome(&work_item, outcome).expect("retry reroutes");
+ assert!(matches!(
+ decision,
+ ItemDecision::Retry { retry_after: Some(duration), .. } if duration == Duration::from_millis(25)
+ ));
+ }
+
+ #[test]
+ fn classify_outcome_treats_poison_as_terminal_all_or_nothing() {
+ let work_item = work_item(7);
+ let err = classify_outcome(&work_item, error_outcome(ErrorKind::Poison, "bad symbols"))
+ .unwrap_err();
+ assert!(err.to_string().contains("DLQ plumbing"));
+ assert!(err.to_string().contains("all-or-nothing"));
+ }
+
+ #[test]
+ fn classify_outcome_treats_invalid_payload_and_unhandled_as_terminal() {
+ let work_item = work_item(7);
+ for kind in [ErrorKind::InvalidPayload, ErrorKind::Unhandled] {
+ let err = classify_outcome(&work_item, error_outcome(kind, "boom")).unwrap_err();
+ assert!(err.to_string().contains(kind.as_str_name()));
+ assert!(err.to_string().contains("failing batch"));
+ }
+ }
+
+ #[test]
+ fn single_outcome_ignores_unrelated_ids() {
+ let outcome = ResolveOutcome {
+ id: 10,
+ result: None,
+ };
+ assert!(single_outcome(7, vec![outcome]).unwrap().is_none());
+ }
+
+ fn error_outcome(kind: ErrorKind, message: &str) -> ResolveOutcome {
+ ResolveOutcome {
+ id: 7,
+ result: Some(resolve_outcome::Result::Error(Error {
+ kind: kind as i32,
+ message: message.to_string(),
+ details_json: Vec::new(),
+ })),
+ }
+ }
+
+ fn work_item(token: u64) -> RemoteWorkItem {
+ RemoteWorkItem {
+ token,
+ routing_key: "team:1".to_string(),
+ event_slot: 0,
+ exception_slot: 0,
+ item: cymbal_proto::cymbal::resolution::v1::ResolveItem {
+ id: token,
+ team_id: 1,
+ exception_json: Vec::new(),
+ metadata: Vec::new(),
+ deadline_ms: 0,
+ },
+ }
+ }
+
+ fn exception(exception_type: &str) -> Exception {
+ Exception {
+ exception_id: None,
+ exception_type: exception_type.to_string(),
+ exception_message: "boom".to_string(),
+ mechanism: None,
+ module: None,
+ thread_id: None,
+ stack: None,
+ }
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/remote/subscription.rs b/rust/cymbal/src/stages/resolution/remote/subscription.rs
new file mode 100644
index 000000000000..fbfae34fed41
--- /dev/null
+++ b/rust/cymbal/src/stages/resolution/remote/subscription.rs
@@ -0,0 +1,244 @@
+//! Per-endpoint subscription client for the `cymbal.resolution.v1` load
+//! event bus.
+//!
+//! Each pooled gRPC channel runs a long-lived `Subscribe` stream in the
+//! background. The latest [`LoadSnapshot`] is stashed on the endpoint state
+//! and consulted by [`super::pool::EndpointPool::select_for_key`] to route
+//! the rendezvous-ranked endpoint that is not draining. The
+//! subscription is cooperative: stream termination triggers a small
+//! backoff (with jitter) and a reconnect, so a transient blip leaves the
+//! snapshot cleared and the pool stops routing to that endpoint rather than
+//! silently considering it healthy forever.
+
+use std::net::SocketAddr;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_client::CymbalResolutionClient;
+use cymbal_proto::cymbal::resolution::v1::{LoadEvent, SubscribeRequest};
+use futures::StreamExt;
+use rand::Rng;
+use tokio::sync::Notify;
+use tokio::task::JoinHandle;
+use tonic::transport::Channel;
+use tonic::Request;
+use tracing::{debug, info, warn};
+
+use crate::metric_consts::REMOTE_RESOLUTION_LOAD_SUBSCRIPTIONS;
+
+use super::client::with_internal_api_secret;
+
+/// Snapshot of an endpoint's server-reported load. Stored in an `Arc<Mutex<…>>`
+/// per endpoint and refreshed by the subscription task.
+#[derive(Clone, Debug)]
+pub struct LoadSnapshot {
+ pub draining: bool,
+ /// Local wall-clock at which this snapshot was received. Used by the pool
+ /// to ignore stale snapshots when routing.
+ pub observed_at: Instant,
+ /// Sequence number from the server. Useful for diagnostics when stream
+ /// restarts reset the count.
+ pub sequence: u64,
+}
+
+impl LoadSnapshot {
+ pub fn is_fresh(&self, now: Instant, stale_after: Duration) -> bool {
+ now.duration_since(self.observed_at) < stale_after
+ }
+}
+
+/// Cell holding the latest load snapshot for one endpoint. Wrapped in an
+/// `Arc<Mutex<…>>` so the subscription writer and the pool reader can share
+/// it cheaply.
+pub type LoadCell = Arc<Mutex<Option<LoadSnapshot>>>;
+
+/// Handle returned from [`spawn_subscription`]. Holds the cancellation
+/// notifier and the join handle so the pool can stop the task when an
+/// endpoint is evicted.
+pub struct SubscriptionHandle {
+ pub cancel: Arc<Notify>,
+ pub join: JoinHandle<()>,
+}
+
+impl SubscriptionHandle {
+ /// Signal the subscription task to stop. The task will exit at the next
+ /// await point — either when receiving an event or when its backoff timer
+ /// fires.
+ pub fn cancel(&self) {
+ self.cancel.notify_waiters();
+ }
+}
+
+/// Spawn a background task that subscribes to one endpoint's freshness/draining stream
+/// and keeps `cell` populated with the latest [`LoadSnapshot`]. The task
+/// reconnects automatically on stream end or error, with a fixed backoff so
+/// a misbehaving server doesn't spin a hot reconnect loop.
+pub fn spawn_subscription(
+ addr: SocketAddr,
+ channel: Channel,
+ cell: LoadCell,
+ tick_hint: Duration,
+ reconnect_backoff: Duration,
+ internal_api_secret: String,
+ ready: Arc<Notify>,
+) -> SubscriptionHandle {
+ let cancel = Arc::new(Notify::new());
+ let cancel_clone = cancel.clone();
+ let subscriber_id = format!("cymbal/{addr}");
+
+ let join = tokio::spawn(async move {
+ let backoff = reconnect_backoff;
+ loop {
+ let outcome = run_subscription_once(
+ channel.clone(),
+ cell.clone(),
+ tick_hint,
+ subscriber_id.clone(),
+ cancel_clone.clone(),
+ internal_api_secret.clone(),
+ ready.clone(),
+ )
+ .await;
+ match outcome {
+ SubscriptionExit::Cancelled => {
+ debug!(endpoint = %addr, "load subscription cancelled");
+ return;
+ }
+ SubscriptionExit::Reconnect(reason) => {
+ metrics::counter!(
+ REMOTE_RESOLUTION_LOAD_SUBSCRIPTIONS,
+ "outcome" => "reconnect",
+ )
+ .increment(1);
+ // Add up to 50% jitter so a fleet of cymbal pods doesn't
+ // synchronize their reconnects after a shared upstream
+ // restart and hammer the server in lockstep.
+ let jittered = backoff + jitter_for(backoff);
+ warn!(
+ endpoint = %addr,
+ reason = %reason,
+ backoff_ms = jittered.as_millis() as u64,
+ "load subscription ended; will reconnect after backoff"
+ );
+ // Reset the snapshot so the pool stops routing on the
+ // stale value while the stream is down.
+ if let Ok(mut slot) = cell.lock() {
+ *slot = None;
+ }
+ tokio::select! {
+ _ = cancel_clone.notified() => return,
+ _ = tokio::time::sleep(jittered) => {}
+ }
+ }
+ }
+ }
+ });
+
+ SubscriptionHandle { cancel, join }
+}
+
+enum SubscriptionExit {
+ Cancelled,
+ Reconnect(String),
+}
+
+async fn run_subscription_once(
+ channel: Channel,
+ cell: LoadCell,
+ tick_hint: Duration,
+ subscriber_id: String,
+ cancel: Arc<Notify>,
+ internal_api_secret: String,
+ ready: Arc<Notify>,
+) -> SubscriptionExit {
+ let mut client = CymbalResolutionClient::new(channel);
+ let request = SubscribeRequest {
+ subscriber_id,
+ tick_hint_ms: u32::try_from(tick_hint.as_millis()).unwrap_or(u32::MAX),
+ };
+
+ let request = match with_internal_api_secret(Request::new(request), &internal_api_secret) {
+ Ok(request) => request,
+ Err(status) => {
+ return SubscriptionExit::Reconnect(format!("subscribe auth metadata error: {status}"))
+ }
+ };
+ let subscribe = client.subscribe(request);
+ let response = tokio::select! {
+ _ = cancel.notified() => return SubscriptionExit::Cancelled,
+ res = subscribe => res,
+ };
+ let mut stream = match response {
+ Ok(resp) => {
+ metrics::counter!(
+ REMOTE_RESOLUTION_LOAD_SUBSCRIPTIONS,
+ "outcome" => "connected",
+ )
+ .increment(1);
+ resp.into_inner()
+ }
+ Err(status) => {
+ return SubscriptionExit::Reconnect(format!("subscribe rpc rejected: {status}"));
+ }
+ };
+
+ loop {
+ let next = tokio::select! {
+ _ = cancel.notified() => return SubscriptionExit::Cancelled,
+ item = stream.next() => item,
+ };
+ match next {
+ Some(Ok(event)) => {
+ let snapshot = snapshot_from_event(event);
+ let should_notify = !snapshot.draining;
+ if let Ok(mut slot) = cell.lock() {
+ *slot = Some(snapshot);
+ }
+ if should_notify {
+ ready.notify_waiters();
+ }
+ }
+ Some(Err(status)) => {
+ return SubscriptionExit::Reconnect(format!("subscribe stream error: {status}"));
+ }
+ None => {
+ info!("load subscription stream ended cleanly; reconnecting");
+ return SubscriptionExit::Reconnect("stream closed".to_string());
+ }
+ }
+ }
+}
+
+fn jitter_for(backoff: Duration) -> Duration {
+ let max_jitter_ms = (backoff.as_millis() as u64) / 2;
+ if max_jitter_ms == 0 {
+ return Duration::ZERO;
+ }
+ let offset = rand::thread_rng().gen_range(0..=max_jitter_ms);
+ Duration::from_millis(offset)
+}
+
+fn snapshot_from_event(event: LoadEvent) -> LoadSnapshot {
+ LoadSnapshot {
+ draining: event.draining,
+ observed_at: Instant::now(),
+ sequence: event.sequence,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn freshness_window_distinguishes_recent_and_old_snapshots() {
+ let now = Instant::now();
+ let snap = LoadSnapshot {
+ draining: false,
+ 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)));
+ }
+}
diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rs
new file mode 100644
index 000000000000..c4fe6051312f
--- /dev/null
+++ b/rust/cymbal/tests/common/mod.rs
@@ -0,0 +1,470 @@
+//! Shared fixtures for remote-resolution integration tests.
+//!
+//! `tests/common/mod.rs` is the canonical place to put helpers that multiple
+//! integration test binaries (`tests/remote_resolution.rs`,
+//! `tests/remote_resolution_hardening.rs`,
+//! `tests/remote_resolution_parity.rs`, …) reuse. Keep new fixtures here
+//! rather than duplicating them per test file so failure-mode tests can be
+//! extended without re-writing the in-process gRPC stub.
+
+#![allow(dead_code)]
+
+use std::net::SocketAddr;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use async_trait::async_trait;
+use cymbal::error::{ResolveError, UnhandledError};
+use cymbal::frames::{Frame, RawFrame};
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::pipeline::ExceptionEventPipelineItem;
+use cymbal::stages::resolution::{
+ remote::{
+ config::RemoteResolutionConfig, pool::EndpointPool, resolver::RemoteResolutionContext,
+ },
+ symbol::SymbolResolver,
+ ResolutionStage,
+};
+use cymbal::symbol_store::chunk_id::OrChunkId;
+use cymbal::symbol_store::proguard::ProguardRef;
+use cymbal::types::{
+ batch::Batch, exception_properties::ExceptionProperties, operator::TeamId, stage::Stage,
+ Exception, ExceptionList, Stacktrace,
+};
+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,
+};
+use futures::{Stream, StreamExt};
+use tokio::sync::mpsc;
+use tokio::sync::Semaphore;
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::{Request, Response, Status};
+use uuid::Uuid;
+
+pub type ResolveStream = Pin<Box<dyn Stream<Item = Result<ResolveOutcome, Status>> + Send>>;
+pub type SubscribeStream = Pin<Box<dyn Stream<Item = Result<LoadEvent, Status>> + Send>>;
+
+/// Fixture stub for the cymbal.resolution.v1 server. Streams are recorded
+/// separately from items: the mux opens one long-lived bidi stream per
+/// endpoint, while tests usually care about the individual ResolveItems that
+/// actually crossed that stream.
+#[derive(Clone)]
+pub struct StubServer {
+ pub behavior: ServerBehavior,
+ pub streams: Arc<Mutex<Vec<SocketAddr>>>,
+ pub items: Arc<Mutex<Vec<ResolveItem>>>,
+ pub addr: SocketAddr,
+ pub stream_counter: Arc<AtomicU32>,
+}
+
+/// Catalog of behaviors a test stub can advertise. Keep failure modes here so
+/// the integration suite stays fixture-driven and the bidi protocol shape is
+/// shared across remote-resolution tests.
+#[derive(Clone)]
+pub enum ServerBehavior {
+ /// Echo each item back as Done with the input exception unchanged.
+ Happy,
+ /// Echo each item back as Done with the input exception unchanged but
+ /// sleep `delay` before emitting each outcome.
+ HappyDelayed { delay: Duration },
+ /// Fail the Resolve stream during setup with Status::Unavailable.
+ AlwaysUnavailable,
+ /// Fail the Resolve stream during setup with Status::InvalidArgument.
+ AlwaysInvalidArgument,
+ /// Delay stream setup long enough for caller deadlines to fire.
+ SlowerThanDeadline { sleep: Duration },
+ /// Emit Retry outcomes for every item on this stream.
+ Retry,
+ /// Emit ErrorKind::Overloaded outcomes for every item on this stream.
+ Overloaded,
+ /// Emit one Done for the first item then break the stream with Internal.
+ InterruptAfterFirst,
+ /// Emit the first item as Done and every subsequent item as Error.
+ ErrorAfterFirst { kind: ErrorKind },
+}
+
+impl StubServer {
+ pub fn new(behavior: ServerBehavior, addr: SocketAddr) -> Self {
+ Self {
+ behavior,
+ streams: Arc::new(Mutex::new(Vec::new())),
+ items: Arc::new(Mutex::new(Vec::new())),
+ addr,
+ stream_counter: Arc::new(AtomicU32::new(0)),
+ }
+ }
+}
+
+#[tonic::async_trait]
+impl CymbalResolution for StubServer {
+ type ResolveStream = ResolveStream;
+ type SubscribeStream = SubscribeStream;
+
+ /// Default Subscribe behaviour: emit freshness/draining-only `LoadEvent`s
+ /// on a fast tick so snapshot-required routing can warm up quickly.
+ async fn subscribe(
+ &self,
+ _request: Request<SubscribeRequest>,
+ ) -> Result<Response<Self::SubscribeStream>, Status> {
+ let (tx, rx) = mpsc::channel(2);
+ let instance = format!("stub-{}", self.addr);
+ tokio::spawn(async move {
+ let mut sequence = 0u64;
+ let mut ticker = tokio::time::interval(Duration::from_millis(25));
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ ticker.tick().await;
+ sequence += 1;
+ let event = LoadEvent {
+ service_instance_id: instance.clone(),
+ draining: false,
+ sequence,
+ message: String::new(),
+ };
+ if tx.send(Ok(event)).await.is_err() {
+ return;
+ }
+ }
+ });
+ Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
+ }
+
+ async fn resolve(
+ &self,
+ request: Request<tonic::Streaming<ResolveItem>>,
+ ) -> Result<Response<Self::ResolveStream>, Status> {
+ self.streams.lock().unwrap().push(self.addr);
+ self.stream_counter.fetch_add(1, Ordering::SeqCst);
+
+ match self.behavior.clone() {
+ ServerBehavior::AlwaysUnavailable => Err(Status::unavailable("forced shed")),
+ ServerBehavior::AlwaysInvalidArgument => {
+ Err(Status::invalid_argument("forced bad request"))
+ }
+ ServerBehavior::SlowerThanDeadline { sleep } => {
+ tokio::time::sleep(sleep).await;
+ Err(Status::deadline_exceeded("server slow"))
+ }
+ behavior => {
+ let mut inbound = request.into_inner();
+ let (tx, rx) = mpsc::channel(16);
+ let items = self.items.clone();
+ tokio::spawn(async move {
+ let mut seen = 0usize;
+ while let Some(next) = inbound.next().await {
+ let item = match next {
+ Ok(item) => item,
+ Err(err) => {
+ let _ignored = tx.send(Err(err)).await;
+ return;
+ }
+ };
+ items.lock().unwrap().push(item.clone());
+ seen += 1;
+
+ match behavior {
+ ServerBehavior::Happy => {
+ send_outcome(&tx, done_outcome(&item)).await;
+ }
+ ServerBehavior::HappyDelayed { delay } => {
+ tokio::time::sleep(delay).await;
+ send_outcome(&tx, done_outcome(&item)).await;
+ }
+ ServerBehavior::Retry => {
+ send_outcome(&tx, retry_outcome(&item)).await;
+ }
+ ServerBehavior::Overloaded => {
+ send_outcome(&tx, error_outcome(&item, ErrorKind::Overloaded))
+ .await;
+ }
+ ServerBehavior::InterruptAfterFirst => {
+ if seen == 1 {
+ send_outcome(&tx, done_outcome(&item)).await;
+ let _ignored = tx
+ .send(Err(Status::internal("simulated interruption")))
+ .await;
+ return;
+ }
+ send_outcome(&tx, done_outcome(&item)).await;
+ }
+ ServerBehavior::ErrorAfterFirst { kind } => {
+ if seen == 1 {
+ send_outcome(&tx, done_outcome(&item)).await;
+ } else {
+ send_outcome(&tx, error_outcome(&item, kind)).await;
+ }
+ }
+ ServerBehavior::AlwaysUnavailable
+ | ServerBehavior::AlwaysInvalidArgument
+ | ServerBehavior::SlowerThanDeadline { .. } => unreachable!(
+ "stream setup failures return before spawning the bidi task"
+ ),
+ }
+ }
+ });
+ Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
+ }
+ }
+ }
+}
+
+async fn send_outcome(tx: &mpsc::Sender<Result<ResolveOutcome, Status>>, outcome: ResolveOutcome) {
+ let _ignored = tx.send(Ok(outcome)).await;
+}
+
+fn done_outcome(item: &ResolveItem) -> ResolveOutcome {
+ ResolveOutcome {
+ id: item.id,
+ result: Some(resolve_outcome::Result::Done(Done {
+ resolved_exception_json: item.exception_json.clone(),
+ })),
+ }
+}
+
+fn retry_outcome(item: &ResolveItem) -> ResolveOutcome {
+ ResolveOutcome {
+ id: item.id,
+ result: Some(resolve_outcome::Result::Retry(Retry {
+ code: "retry".to_string(),
+ message: "try later".to_string(),
+ retry_after_ms: 0,
+ })),
+ }
+}
+
+fn error_outcome(item: &ResolveItem, kind: ErrorKind) -> ResolveOutcome {
+ ResolveOutcome {
+ id: item.id,
+ result: Some(resolve_outcome::Result::Error(ItemError {
+ kind: kind as i32,
+ message: format!("forced {} from stub", kind.as_str_name()),
+ details_json: Vec::new(),
+ })),
+ }
+}
+
+/// Bind to an OS-assigned local port, drop the listener, and spawn a tonic
+/// server. Returns the address once a probe TCP connect succeeds, so callers
+/// never dial before the bind has actually happened.
+pub async fn spawn_stub_server(
+ behavior: ServerBehavior,
+) -> (SocketAddr, Arc<Mutex<Vec<ResolveItem>>>) {
+ let (addr, _streams, items) = spawn_recording_stub_server(behavior).await;
+ (addr, items)
+}
+
+pub async fn spawn_recording_stub_server(
+ behavior: ServerBehavior,
+) -> (
+ SocketAddr,
+ Arc<Mutex<Vec<SocketAddr>>>,
+ Arc<Mutex<Vec<ResolveItem>>>,
+) {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+ let stub = StubServer::new(behavior, addr);
+ let streams = stub.streams.clone();
+ let items = stub.items.clone();
+
+ tokio::spawn(async move {
+ let _outcome = tonic::transport::Server::builder()
+ .add_service(CymbalResolutionServer::new(stub))
+ .serve(addr)
+ .await;
+ });
+
+ for _ in 0..40 {
+ if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() {
+ return (addr, streams, items);
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("test stub server failed to come up at {addr}");
+}
+
+/// Reserve a local TCP port without keeping a listener bound to it. The
+/// returned address is therefore guaranteed not to accept connections, which
+/// is what `connection-refused` failure tests need.
+pub fn unbound_addr() -> SocketAddr {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+ addr
+}
+
+pub fn make_config(max_retries: u32, deadline: Duration) -> RemoteResolutionConfig {
+ make_config_with_sample_rate(max_retries, deadline, 1.0)
+}
+
+pub fn make_config_with_sample_rate(
+ max_retries: u32,
+ deadline: Duration,
+ sample_rate: f64,
+) -> RemoteResolutionConfig {
+ RemoteResolutionConfig {
+ host: "test-only".to_string(),
+ port: 0,
+ internal_api_secret: "test-secret".to_string(),
+ dns_refresh: Duration::from_secs(60),
+ request_deadline: deadline,
+ connect_timeout: Duration::from_secs(1),
+ max_retries,
+ // Tests run with near-zero backoff so retries don't drag suite latency;
+ // production defaults are tuned for thundering-herd mitigation.
+ retry_backoff: Duration::from_millis(1),
+ retry_max_backoff: Duration::from_millis(2),
+ sample_rate,
+ // Subscription cadence is irrelevant for tests that don't wire the
+ // subscription client — kept short so tests that do consume it run
+ // quickly when they opt in via a dedicated pool builder.
+ subscribe_tick_hint: Duration::from_millis(50),
+ subscribe_reconnect_backoff: Duration::from_millis(50),
+ }
+}
+
+pub async fn make_ctx(
+ addrs: &[SocketAddr],
+ max_retries: u32,
+ deadline: Duration,
+) -> RemoteResolutionContext {
+ let config = make_config(max_retries, deadline);
+ let pool = EndpointPool::from_addrs(config.clone(), addrs).expect("build pool");
+ if !addrs.is_empty() {
+ wait_until_routable(&pool).await;
+ }
+ RemoteResolutionContext { pool, config }
+}
+
+pub async fn make_ctx_with_sample_rate(
+ addrs: &[SocketAddr],
+ max_retries: u32,
+ deadline: Duration,
+ sample_rate: f64,
+) -> RemoteResolutionContext {
+ let config = make_config_with_sample_rate(max_retries, deadline, sample_rate);
+ let pool = EndpointPool::from_addrs(config.clone(), addrs).expect("build pool");
+ if !addrs.is_empty() {
+ wait_until_routable(&pool).await;
+ }
+ RemoteResolutionContext { pool, config }
+}
+
+/// Wait until the pool has at least one routable endpoint (a fresh
+/// `LoadEvent` snapshot has arrived). Snapshot-required routing means an
+/// empty pool persists until the per-endpoint Subscribe stream delivers its
+/// first event; without this small warm-up tests race the first tick and
+/// observe spurious `pool_empty` failures.
+pub async fn wait_until_routable(pool: &Arc<cymbal::stages::resolution::remote::EndpointPool>) {
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ if pool.select(&[]).await.is_ok() {
+ return;
+ }
+ if Instant::now() >= deadline {
+ panic!("pool never became routable within warm-up window");
+ }
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+#[derive(Default)]
+pub struct NoopResolver;
+
+#[async_trait]
+impl SymbolResolver for NoopResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ Ok(Vec::new())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("integration fixtures do not exercise Java class resolution")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ unreachable!("integration fixtures do not exercise Dart name resolution")
+ }
+}
+
+pub fn remote_stage(ctx: RemoteResolutionContext) -> ResolutionStage {
+ ResolutionStage {
+ symbol_resolver: Arc::new(NoopResolver),
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: Some(ctx),
+ }
+}
+
+pub fn local_stage() -> ResolutionStage {
+ ResolutionStage {
+ symbol_resolver: Arc::new(NoopResolver),
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: None,
+ }
+}
+
+pub async fn process_one(
+ stage: ResolutionStage,
+ evt: ExceptionProperties,
+) -> Result<ExceptionProperties, UnhandledError> {
+ let batch: Batch<ExceptionEventPipelineItem> = Batch::from(vec![Ok(evt)]);
+ let result = stage.process(batch).await?;
+ let mut items: Vec<_> = result.into_iter().collect();
+ assert_eq!(items.len(), 1, "single-event batch must produce one output");
+ Ok(items.remove(0).expect("event must not be EventError"))
+}
+
+pub fn build_event(num_exceptions: usize) -> ExceptionProperties {
+ let exceptions: Vec<Exception> = (0..num_exceptions)
+ .map(|i| Exception {
+ exception_id: None,
+ exception_type: format!("Boom{i}"),
+ exception_message: format!("message {i}"),
+ mechanism: None,
+ module: None,
+ thread_id: None,
+ stack: Some(Stacktrace::Raw { frames: vec![] }),
+ })
+ .collect();
+ ExceptionProperties {
+ exception_list: ExceptionList::from(exceptions),
+ exception_sources: None,
+ exception_types: None,
+ exception_messages: None,
+ exception_functions: None,
+ exception_handled: None,
+ exception_releases: Default::default(),
+ fingerprint: None,
+ proposed_fingerprint: None,
+ fingerprint_record: None,
+ issue_id: None,
+ proposed_issue_name: None,
+ proposed_issue_description: None,
+ debug_images: Vec::new(),
+ props: Default::default(),
+ uuid: Uuid::now_v7(),
+ timestamp: String::new(),
+ team_id: 7,
+ issue: None,
+ }
+}
diff --git a/rust/cymbal/tests/event.rs b/rust/cymbal/tests/event.rs
index ccabcf20d5bc..08f83fcbae0c 100644
--- a/rust/cymbal/tests/event.rs
+++ b/rust/cymbal/tests/event.rs
@@ -23,6 +23,7 @@ use uuid::Uuid;
use crate::utils::MockS3Client;
+mod common;
mod utils;
const STORAGE_BUCKET: &str = "test-bucket";
@@ -189,6 +190,44 @@ impl TestHarness {
.await
}
+ async fn post_events_with_remote_resolution<T: DeserializeOwned>(
+ &self,
+ events: Vec<AnyEvent>,
+ addr: std::net::SocketAddr,
+ ) -> (StatusCode, T) {
+ utils::get_response_with_config(
+ self.db.clone(),
+ STORAGE_BUCKET.to_string(),
+ || {
+ Request::builder()
+ .method("POST")
+ .header("content-type", "application/json")
+ .uri("/process")
+ .body(Body::from(serde_json::to_vec(&events).unwrap()))
+ .unwrap()
+ },
+ Arc::new(Self::create_s3_mock()),
+ |config| {
+ config.remote_resolution_enabled = true;
+ config.remote_resolution_host = "127.0.0.1".to_string();
+ config.remote_resolution_port = addr.port();
+ config.internal_api_secret = "test-secret".to_string();
+ // Snapshot-required routing: give the pool a small retry
+ // budget with fast backoff so the first Subscribe tick can
+ // populate the load snapshot before we give up.
+ config.remote_resolution_max_retries = 3;
+ config.remote_resolution_retry_backoff_ms = 25;
+ config.remote_resolution_retry_max_backoff_ms = 100;
+ // Fast tick so the snapshot arrives within the first retry
+ // window even when the stub server runs at default cadence.
+ config.remote_resolution_subscribe_tick_hint_ms = 25;
+ config.remote_resolution_sample_rate = 1.0;
+ config.remote_resolution_dns_refresh_secs = 3600;
+ },
+ )
+ .await
+ }
+
async fn post_event<T: DeserializeOwned>(&self, event: &AnyEvent) -> (StatusCode, T) {
self.post_events(vec![event.clone()]).await
}
@@ -552,3 +591,51 @@ async fn handles_missing_sourcemap(db: PgPool) {
"[].id" => "REDACTED",
});
}
+
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn remote_resolution_http_process_streams_same_team_events_as_items(db: PgPool) {
+ // Per-team routing collapses all of a team's exceptions onto one routing
+ // key, but the final gRPC contract sends them as independent streamed
+ // ResolveItems. The HTTP response shape must still preserve input order
+ // and length.
+ let harness = TestHarness::new(db);
+ let (addr, _streams, items) =
+ common::spawn_recording_stub_server(common::ServerBehavior::Happy).await;
+ let first = load_static_event("javascript_chunk_id");
+ let second = load_static_event("javascript_chunk_id_2");
+ let expected_uuids = [first.uuid, second.uuid];
+
+ let (status, body): (_, SuccessResponse) = harness
+ .post_events_with_remote_resolution(vec![first, second], addr)
+ .await;
+
+ assert!(status.is_success(), "Expected success, got {status:?}");
+ assert_eq!(body.0.len(), 2, "HTTP response length must match request");
+ assert_eq!(
+ body.0[0].as_ref().map(|event| event.uuid),
+ Some(expected_uuids[0])
+ );
+ assert_eq!(
+ body.0[1].as_ref().map(|event| event.uuid),
+ Some(expected_uuids[1])
+ );
+
+ let recorded = items.lock().unwrap();
+ assert_eq!(
+ recorded.len(),
+ 2,
+ "the stream must carry one item per submitted exception",
+ );
+
+ let mut payloads = recorded
+ .iter()
+ .map(|item| String::from_utf8(item.exception_json.clone()).expect("exception JSON is utf8"))
+ .collect::<Vec<_>>();
+ payloads.sort();
+ assert!(payloads
+ .iter()
+ .any(|payload| payload.contains("\"chunk_id\":\"1234\"")));
+ assert!(payloads
+ .iter()
+ .any(|payload| payload.contains("\"chunk_id\":\"124\"")));
+}
diff --git a/rust/cymbal/tests/remote_resolution.rs b/rust/cymbal/tests/remote_resolution.rs
new file mode 100644
index 000000000000..42fd080bfca4
--- /dev/null
+++ b/rust/cymbal/tests/remote_resolution.rs
@@ -0,0 +1,618 @@
+//! Integration tests for the Batch 3 remote-resolution client path.
+//!
+//! Shared fixtures live in `tests/common/mod.rs`; this file owns the original
+//! Batch 3 acceptance tests covering the happy path, transport retries, and
+//! the contract that there is no silent local fallback when remote mode is
+//! enabled. Failure-mode hardening tests added in Batch 4 live in
+//! `tests/remote_resolution_hardening.rs`.
+
+mod common;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common::{
+ build_event, local_stage, make_ctx, make_ctx_with_sample_rate, process_one, remote_stage,
+ spawn_recording_stub_server, spawn_stub_server, ServerBehavior,
+};
+
+use cymbal::error::{ResolveError, UnhandledError};
+use cymbal::frames::{Frame, RawFrame};
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use cymbal::stages::resolution::ResolutionStage;
+use cymbal::symbol_store::chunk_id::OrChunkId;
+use cymbal::symbol_store::proguard::ProguardRef;
+use cymbal::types::batch::Batch;
+use cymbal::types::exception_properties::ExceptionProperties;
+use cymbal::types::operator::TeamId;
+use cymbal::types::stage::Stage;
+use cymbal::types::Stacktrace;
+use serde_json::json;
+use sha2::{Digest, Sha256};
+use tokio::sync::Semaphore;
+use uuid::Uuid;
+
+#[derive(Default)]
+struct CountingResolver {
+ raw_frame_calls: AtomicUsize,
+ dart_name_calls: AtomicUsize,
+}
+
+#[async_trait]
+impl SymbolResolver for CountingResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ self.raw_frame_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(Vec::new())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("sampling integration fixtures do not exercise Java resolution")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ self.dart_name_calls.fetch_add(1, Ordering::SeqCst);
+ Ok("ResolvedDart".to_string())
+ }
+}
+
+fn remote_stage_with_resolver(
+ ctx: cymbal::stages::resolution::remote::resolver::RemoteResolutionContext,
+ resolver: Arc<CountingResolver>,
+) -> ResolutionStage {
+ ResolutionStage {
+ symbol_resolver: resolver,
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: Some(ctx),
+ }
+}
+
+fn build_dart_event() -> ExceptionProperties {
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": [{
+ "type": "minified:Foo",
+ "value": "boom",
+ "stacktrace": {
+ "type": "raw",
+ "frames": [{
+ "platform": "web:javascript",
+ "filename": "https://example.com/app.js",
+ "function": "a",
+ "lineno": 1,
+ "colno": 2,
+ "chunk_id": "chunk-a"
+ }]
+ }
+ }]
+ }))
+ .expect("valid exception properties");
+ evt.team_id = 7;
+ evt.uuid = Uuid::from_u128(42);
+ evt
+}
+
+fn build_event_with_symbol_refs(uuid: Uuid, symbol_refs: &[&str]) -> ExceptionProperties {
+ let exceptions: Vec<serde_json::Value> = symbol_refs
+ .iter()
+ .enumerate()
+ .map(|(idx, symbol_ref)| {
+ json!({
+ "type": format!("Boom{idx}"),
+ "value": format!("message {idx}"),
+ "stacktrace": {
+ "type": "raw",
+ "frames": [{
+ "platform": "web:javascript",
+ "filename": "https://example.com/app.js",
+ "function": "minified",
+ "lineno": 1,
+ "colno": 2,
+ "chunk_id": symbol_ref
+ }]
+ }
+ })
+ })
+ .collect();
+ let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ "$exception_list": exceptions
+ }))
+ .expect("valid exception properties");
+ evt.team_id = 7;
+ evt.uuid = uuid;
+ evt
+}
+
+fn sampling_bucket(team_id: i32, uuid: Uuid) -> f64 {
+ let mut hasher = Sha256::new();
+ hasher.update(team_id.to_be_bytes());
+ hasher.update(uuid.as_bytes());
+ let digest = hasher.finalize();
+ let bucket_bytes: [u8; 8] = digest[..8]
+ .try_into()
+ .expect("sha256 digest always contains at least 8 bytes");
+ u64::from_be_bytes(bucket_bytes) as f64 / ((u64::MAX as f64) + 1.0)
+}
+
+fn uuid_for_sampling_decision(team_id: i32, sample_rate: f64, want_remote: bool) -> Uuid {
+ for candidate in 1..10_000u128 {
+ let uuid = Uuid::from_u128(candidate);
+ if (sampling_bucket(team_id, uuid) < sample_rate) == want_remote {
+ return uuid;
+ }
+ }
+ panic!("failed to find deterministic sampling fixture");
+}
+
+#[tokio::test]
+async fn happy_path_preserves_batch_event_and_exception_order() {
+ let (addr, _) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+ let evt_a = build_event(3);
+ let evt_b = build_event(2);
+ let expected_uuids = [evt_a.uuid, evt_b.uuid];
+ let expected_types: Vec<Vec<_>> = [&evt_a, &evt_b]
+ .into_iter()
+ .map(|evt| {
+ evt.exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect()
+ })
+ .collect();
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt_a), Ok(evt_b)]))
+ .await
+ .expect("stage processed");
+ let resolved: Vec<_> = result
+ .into_iter()
+ .map(|item| item.expect("event must not be EventError"))
+ .collect();
+
+ assert_eq!(resolved.len(), 2);
+ assert_eq!(resolved[0].uuid, expected_uuids[0]);
+ assert_eq!(resolved[1].uuid, expected_uuids[1]);
+ let resolved_types: Vec<Vec<_>> = resolved
+ .iter()
+ .map(|evt| {
+ evt.exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect()
+ })
+ .collect();
+ assert_eq!(resolved_types, expected_types);
+ for (resolved_evt, expected_evt_types) in resolved.iter().zip(expected_types.iter()) {
+ let mut expected_properties = expected_evt_types.clone();
+ expected_properties.sort();
+ let mut resolved_properties = resolved_evt.exception_types.clone().unwrap_or_default();
+ resolved_properties.sort();
+ assert_eq!(resolved_properties, expected_properties);
+ }
+}
+
+#[tokio::test]
+async fn local_mode_ignores_remote_pool_when_remote_is_disabled() {
+ let (_addr, hits) = spawn_stub_server(ServerBehavior::AlwaysInvalidArgument).await;
+ let evt = build_event(3);
+ let original_types: Vec<_> = evt
+ .exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect();
+
+ let resolved = process_one(local_stage(), evt)
+ .await
+ .expect("no unhandled error");
+
+ assert_eq!(resolved.exception_list.len(), 3);
+ let resolved_types: Vec<_> = resolved
+ .exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect();
+ assert_eq!(resolved_types, original_types);
+ let mut expected_properties = original_types.clone();
+ expected_properties.sort();
+ let mut resolved_properties = resolved.exception_types.unwrap_or_default();
+ resolved_properties.sort();
+ assert_eq!(resolved_properties, expected_properties);
+ assert!(
+ hits.lock().unwrap().is_empty(),
+ "disabled remote mode must not call the remote pool"
+ );
+}
+
+#[tokio::test]
+async fn sample_rate_zero_routes_eligible_events_locally_without_remote_calls() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 0.0).await;
+ let evt = build_event(1);
+
+ let resolved = process_one(remote_stage(ctx), evt)
+ .await
+ .expect("sampled-local event should resolve locally");
+
+ assert!(
+ hits.lock().unwrap().is_empty(),
+ "sample_rate=0.0 must not call cymbal-resolution"
+ );
+ assert!(matches!(
+ resolved
+ .exception_list
+ .first()
+ .and_then(|e| e.stack.as_ref()),
+ Some(Stacktrace::Resolved { .. })
+ ));
+ assert_eq!(resolved.exception_types, Some(vec!["Boom0".to_string()]));
+}
+
+#[tokio::test]
+async fn sample_rate_one_routes_all_eligible_events_remotely() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 1.0).await;
+ let evt_a = build_event(1);
+ let evt_b = build_event(2);
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt_a), Ok(evt_b)]))
+ .await
+ .expect("stage processed");
+ assert_eq!(result.len(), 2);
+
+ assert_eq!(
+ hits.lock().unwrap().len(),
+ 3,
+ "sample_rate=1.0 should submit one streamed item per exception"
+ );
+}
+
+#[tokio::test]
+async fn exceptions_with_same_routing_key_submit_independent_stream_items() {
+ let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+ let evt_a = build_event_with_symbol_refs(Uuid::from_u128(101), &["shared-bundle"]);
+ let evt_b = build_event_with_symbol_refs(Uuid::from_u128(102), &["shared-bundle"]);
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt_a), Ok(evt_b)]))
+ .await
+ .expect("stage processed");
+ assert_eq!(result.len(), 2);
+
+ let items = items.lock().unwrap();
+ assert_eq!(items.len(), 2, "each exception should be a streamed item");
+ assert!(items.iter().all(|item| item.team_id == 7));
+ assert!(items.iter().all(|item| item.deadline_ms > 0));
+ assert_ne!(items[0].id, items[1].id, "stream ids must be unique");
+}
+
+#[tokio::test]
+async fn distinct_symbol_sets_are_streamed_as_independent_items_under_team_routing() {
+ let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+ let evt = build_event_with_symbol_refs(Uuid::from_u128(201), &["bundle-a", "bundle-b"]);
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt)]))
+ .await
+ .expect("stage processed");
+ assert_eq!(result.len(), 1);
+
+ let items = items.lock().unwrap();
+ assert_eq!(items.len(), 2);
+ let exception_types: Vec<String> = items
+ .iter()
+ .map(|item| {
+ let exc: cymbal::types::Exception =
+ serde_json::from_slice(&item.exception_json).expect("valid exception json");
+ exc.exception_type
+ })
+ .collect();
+ assert_eq!(exception_types, vec!["Boom0", "Boom1"]);
+}
+
+#[tokio::test]
+async fn load_events_do_not_shrink_streamed_item_submission() {
+ let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 1.0).await;
+ let events: Vec<_> = (0..10)
+ .map(|i| {
+ Ok(build_event_with_symbol_refs(
+ Uuid::from_u128(500 + i),
+ &["x"],
+ ))
+ })
+ .collect();
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(events))
+ .await
+ .expect("stage processed");
+ assert_eq!(result.len(), 10);
+ assert_eq!(items.lock().unwrap().len(), 10);
+}
+
+#[tokio::test]
+async fn metadata_encodes_apple_debug_images_as_json_field() {
+ let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+ let mut evt = build_event(1);
+ evt.debug_images = vec![AppleDebugImage {
+ debug_id: "ABCDEF".to_string(),
+ image_addr: "0x100000000".to_string(),
+ image_vmaddr: Some("0x100000000".to_string()),
+ image_size: Some(4096),
+ code_file: Some("Example.app/Example".to_string()),
+ image_type: Some("macho".to_string()),
+ arch: Some("arm64".to_string()),
+ }];
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt)]))
+ .await
+ .expect("stage processed");
+ assert_eq!(result.len(), 1);
+
+ let items = items.lock().unwrap();
+ assert_eq!(items.len(), 1);
+ let metadata: serde_json::Value =
+ serde_json::from_slice(&items[0].metadata).expect("metadata is json");
+ assert_eq!(
+ metadata["apple_debug_images_json"][0]["debug_id"],
+ serde_json::Value::String("ABCDEF".to_string())
+ );
+}
+
+#[tokio::test]
+async fn per_item_overloaded_outcomes_reroute_independently() {
+ let (overloaded_addr, overloaded_items) = spawn_stub_server(ServerBehavior::Overloaded).await;
+ let (good_addr, good_items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[overloaded_addr, good_addr], 3, Duration::from_secs(5)).await;
+ let evt = build_event_with_symbol_refs(Uuid::from_u128(401), &["bundle-a", "bundle-b"]);
+
+ let result = remote_stage(ctx)
+ .process(Batch::from(vec![Ok(evt)]))
+ .await
+ .expect("stage processed after per-item reroute");
+ let resolved: Vec<_> = result
+ .into_iter()
+ .map(|item| item.expect("event must not be EventError"))
+ .collect();
+ assert_eq!(resolved[0].exception_list.len(), 2);
+ assert_eq!(good_items.lock().unwrap().len(), 2);
+ assert!(
+ overloaded_items.lock().unwrap().len() <= 2,
+ "items may hash directly to the healthy endpoint, but overload retries must not duplicate successes"
+ );
+}
+
+#[tokio::test]
+async fn mixed_sampled_remote_and_unsampled_local_events_preserve_output_ordering() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let sample_rate = 0.5;
+ let remote_uuid = uuid_for_sampling_decision(7, sample_rate, true);
+ let local_uuid = uuid_for_sampling_decision(7, sample_rate, false);
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), sample_rate).await;
+ let resolver = Arc::new(CountingResolver::default());
+ let mut local_evt = build_dart_event();
+ local_evt.uuid = local_uuid;
+ let remote_evt = build_event_with_symbol_refs(remote_uuid, &["remote-bundle"]);
+
+ let result = remote_stage_with_resolver(ctx, resolver.clone())
+ .process(Batch::from(vec![
+ Ok(local_evt.clone()),
+ Ok(remote_evt.clone()),
+ ]))
+ .await
+ .expect("stage processed");
+ let resolved: Vec<_> = result
+ .into_iter()
+ .map(|item| item.expect("event must not be EventError"))
+ .collect();
+
+ assert_eq!(resolved.len(), 2);
+ assert_eq!(resolved[0].uuid, local_uuid);
+ assert_eq!(resolved[1].uuid, remote_uuid);
+ assert_eq!(hits.lock().unwrap().len(), 1);
+ assert_eq!(resolver.dart_name_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(resolved[0].exception_list[0].exception_type, "ResolvedDart");
+ assert_eq!(resolved[1].exception_list[0].exception_type, "Boom0");
+}
+
+#[tokio::test]
+async fn partial_sample_rate_is_deterministic_for_same_event() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 0.5).await;
+ let mut evt = build_event(1);
+ evt.team_id = 77;
+ evt.uuid = Uuid::from_u128(0x1234);
+
+ for _ in 0..8 {
+ let _resolved = process_one(remote_stage(ctx.clone()), evt.clone())
+ .await
+ .expect("stage processed");
+ }
+
+ let remote_calls = hits.lock().unwrap().len();
+ assert!(
+ remote_calls == 0 || remote_calls == 8,
+ "same team_id + event UUID must make the same sampling decision across retries; got {remote_calls} remote calls"
+ );
+}
+
+#[tokio::test]
+async fn sampled_remote_failure_does_not_fall_back_to_local_resolution() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::AlwaysUnavailable).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 1.0).await;
+ let resolver = Arc::new(CountingResolver::default());
+
+ let err = process_one(
+ remote_stage_with_resolver(ctx, resolver.clone()),
+ build_dart_event(),
+ )
+ .await
+ .expect_err("sampled remote failure must surface");
+
+ assert!(format!("{err}").contains("exhausted"));
+ assert!(hits.lock().unwrap().is_empty());
+ assert_eq!(resolver.dart_name_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(resolver.raw_frame_calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn unsampled_events_run_local_exception_frame_and_properties_resolvers() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 0.0).await;
+ let resolver = Arc::new(CountingResolver::default());
+
+ let resolved = process_one(
+ remote_stage_with_resolver(ctx, resolver.clone()),
+ build_dart_event(),
+ )
+ .await
+ .expect("unsampled event should resolve locally");
+
+ assert!(hits.lock().unwrap().is_empty());
+ assert_eq!(resolver.dart_name_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(resolver.raw_frame_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(resolved.exception_list[0].exception_type, "ResolvedDart");
+ assert!(matches!(
+ resolved.exception_list[0].stack.as_ref(),
+ Some(Stacktrace::Resolved { .. })
+ ));
+ assert_eq!(
+ resolved.exception_types,
+ Some(vec!["ResolvedDart".to_string()])
+ );
+}
+
+#[tokio::test]
+async fn transport_unavailable_retries_against_another_endpoint() {
+ // Use a single Unavailable endpoint so the very first attempt fails; the
+ // pool then has to rotate to the Happy endpoint on retry. This sidesteps
+ // round-robin selection order, which otherwise leaves the test dependent
+ // on the OS-assigned port ordering.
+ let (bad_addr, bad_hits) = spawn_stub_server(ServerBehavior::AlwaysUnavailable).await;
+ let (good_addr, good_hits) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[bad_addr, good_addr], 4, Duration::from_secs(5)).await;
+ let evt = build_event(1);
+
+ let resolved = process_one(remote_stage(ctx), evt)
+ .await
+ .expect("stage succeeded");
+ assert_eq!(resolved.exception_list.len(), 1);
+
+ assert!(
+ bad_hits.lock().unwrap().is_empty(),
+ "setup-level Unavailable should fail before any items are processed"
+ );
+ assert_eq!(
+ good_hits.lock().unwrap().len(),
+ 1,
+ "good endpoint must serve the successful retry"
+ );
+}
+
+#[tokio::test]
+async fn per_item_retry_outcome_triggers_caller_side_reroute() {
+ let (retry_addr, retry_items) = spawn_stub_server(ServerBehavior::Retry).await;
+ let (good_addr, good_items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[retry_addr, good_addr], 3, Duration::from_secs(5)).await;
+ let evt = build_event(1);
+
+ let resolved = process_one(remote_stage(ctx), evt)
+ .await
+ .expect("stage succeeded");
+ assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(good_items.lock().unwrap().len(), 1);
+ assert!(retry_items.lock().unwrap().len() <= 1);
+}
+
+#[tokio::test]
+async fn terminal_setup_status_closes_mux_without_processing_items() {
+ let (addr, streams, items) =
+ spawn_recording_stub_server(ServerBehavior::AlwaysInvalidArgument).await;
+ let ctx = make_ctx(&[addr], 1, Duration::from_secs(5)).await;
+ let evt = build_event(1);
+
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("closed mux must surface as unhandled error");
+
+ let msg = format!("{err}");
+ assert!(
+ msg.contains("exhausted"),
+ "expected exhaustion after closed stream, got: {msg}"
+ );
+ assert!(items.lock().unwrap().is_empty());
+ assert_eq!(streams.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn caller_deadline_on_slow_item_surfaces_without_local_fallback() {
+ let (slow_addr, _) = spawn_stub_server(ServerBehavior::HappyDelayed {
+ delay: Duration::from_millis(400),
+ })
+ .await;
+ let ctx = make_ctx(&[slow_addr], 1, Duration::from_millis(100)).await;
+ let evt = build_event(1);
+
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("shared item deadline must surface");
+ assert!(
+ format!("{err}").contains("deadline"),
+ "expected deadline error, got: {err}"
+ );
+}
+
+#[tokio::test]
+async fn empty_pool_fails_clearly_without_local_fallback() {
+ let ctx = make_ctx(&[], 0, Duration::from_secs(1)).await;
+ let evt = build_event(1);
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("empty pool must surface as unhandled error");
+ let msg = format!("{err}");
+ assert!(
+ msg.contains("pool unavailable"),
+ "expected pool-empty error, got: {msg}"
+ );
+}
+
+#[tokio::test]
+async fn exhausting_retries_returns_unhandled_error_with_no_local_fallback() {
+ let (addr, hits) = spawn_stub_server(ServerBehavior::AlwaysUnavailable).await;
+ let ctx = make_ctx(&[addr], 1, Duration::from_secs(5)).await;
+ let evt = build_event(1);
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("exhausted retries must surface as unhandled error");
+ let msg = format!("{err}");
+ assert!(
+ msg.contains("exhausted"),
+ "expected exhaustion error, got: {msg}"
+ );
+ assert!(
+ hits.lock().unwrap().is_empty(),
+ "setup-level Unavailable should fail before any items are processed"
+ );
+}
diff --git a/rust/cymbal/tests/remote_resolution_hardening.rs b/rust/cymbal/tests/remote_resolution_hardening.rs
new file mode 100644
index 000000000000..8c3e22aa16c6
--- /dev/null
+++ b/rust/cymbal/tests/remote_resolution_hardening.rs
@@ -0,0 +1,210 @@
+//! Failure-mode hardening tests for the remote resolution client.
+//!
+//! These tests exercise the final bidi `ResolveItem` / `ResolveOutcome`
+//! protocol: transport failures, stream breaks, per-item terminal errors,
+//! caller cancellation, and endpoint lifecycle cleanup.
+
+mod common;
+
+use std::io;
+use std::net::SocketAddr;
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common::{
+ build_event, make_config, make_ctx, process_one, remote_stage, spawn_stub_server, unbound_addr,
+ wait_until_routable, ServerBehavior,
+};
+use cymbal::stages::resolution::remote::dns::DnsResolver;
+use cymbal::stages::resolution::remote::resolver::RemoteResolutionContext;
+use cymbal_proto::cymbal::resolution::v1::ErrorKind;
+use tokio::sync::Mutex as TokioMutex;
+
+#[tokio::test]
+async fn connection_refused_endpoint_is_classified_as_retryable() {
+ let bad = unbound_addr();
+ let (good, good_items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[bad, good], 4, Duration::from_secs(2)).await;
+ let evt = build_event(1);
+
+ let resolved = process_one(remote_stage(ctx), evt)
+ .await
+ .expect("connection refused must not surface as terminal");
+ assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(good_items.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn stream_interruption_reroutes_in_flight_items() {
+ for _ in 0..20 {
+ let (interrupted, interrupted_items) =
+ spawn_stub_server(ServerBehavior::InterruptAfterFirst).await;
+ let (good, good_items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[interrupted, good], 4, Duration::from_secs(2)).await;
+ let selected = ctx
+ .pool
+ .select_for_key("team:7", &[])
+ .await
+ .expect("pool warmed")
+ .addr;
+ if selected != interrupted {
+ continue;
+ }
+
+ let resolved = process_one(remote_stage(ctx), build_event(2))
+ .await
+ .expect("interrupted stream must reroute remaining items");
+ assert_eq!(resolved.exception_list.len(), 2);
+ assert_eq!(interrupted_items.lock().unwrap().len(), 1);
+ assert_eq!(good_items.lock().unwrap().len(), 1);
+ return;
+ }
+ panic!("failed to build fixture where rendezvous routing selected interrupted endpoint");
+}
+
+#[tokio::test]
+async fn server_per_item_terminal_error_fails_batch_under_all_or_nothing_policy() {
+ let (lossy, _) = spawn_stub_server(ServerBehavior::ErrorAfterFirst {
+ kind: ErrorKind::InvalidPayload,
+ })
+ .await;
+ let ctx = make_ctx(&[lossy], 1, Duration::from_secs(2)).await;
+ let evt = build_event(3);
+
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("server per-item Error must fail the batch");
+ let msg = format!("{err}");
+ assert!(
+ msg.contains("items_failed") || msg.contains("failed terminally"),
+ "expected per-item-error failure surface, got: {msg}"
+ );
+}
+
+#[tokio::test]
+async fn caller_drops_future_before_deadline_releases_pool_slot() {
+ let (addr, _items) = spawn_stub_server(ServerBehavior::HappyDelayed {
+ delay: Duration::from_millis(500),
+ })
+ .await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+ let pool = Arc::clone(&ctx.pool);
+ let evt = build_event(1);
+
+ let result = tokio::time::timeout(
+ Duration::from_millis(100),
+ process_one(remote_stage(ctx.clone()), evt),
+ )
+ .await;
+ assert!(
+ result.is_err(),
+ "remote resolution should still be in-flight when the caller times out"
+ );
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let _handle = pool.select(&[]).await.expect("pool should still be usable");
+}
+
+#[tokio::test]
+async fn accounting_preserves_order_and_team_id_on_resolved_payloads() {
+ let (addr, _items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(2)).await;
+ let evt = build_event(5);
+
+ let original_types: Vec<String> = evt
+ .exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect();
+ let original_team_id = evt.team_id;
+
+ let resolved = process_one(remote_stage(ctx), evt)
+ .await
+ .expect("happy path");
+
+ let resolved_types: Vec<String> = resolved
+ .exception_list
+ .iter()
+ .map(|e| e.exception_type.clone())
+ .collect();
+ assert_eq!(resolved_types, original_types, "slots must be preserved");
+ assert_eq!(resolved.team_id, original_team_id);
+}
+
+#[tokio::test]
+async fn endpoint_refresh_closes_draining_mux_and_reroutes_in_flight_item() {
+ let (old_addr, old_items) = spawn_stub_server(ServerBehavior::HappyDelayed {
+ delay: Duration::from_millis(500),
+ })
+ .await;
+ let (new_addr, new_items) = spawn_stub_server(ServerBehavior::Happy).await;
+ let resolver = Arc::new(QueuedResolver::new(vec![vec![old_addr], vec![new_addr]]));
+ let config = make_config(50, Duration::from_secs(3));
+ let pool = cymbal::stages::resolution::remote::EndpointPool::new(config.clone(), resolver)
+ .await
+ .expect("build pool");
+ wait_until_routable(&pool).await;
+ let ctx = RemoteResolutionContext {
+ pool: Arc::clone(&pool),
+ config,
+ };
+
+ let task = tokio::spawn(process_one(remote_stage(ctx), build_event(1)));
+ tokio::time::sleep(Duration::from_millis(75)).await;
+ pool.refresh().await.expect("refresh to new endpoint");
+ wait_until_routable(&pool).await;
+
+ let resolved = task
+ .await
+ .expect("join remote resolution")
+ .expect("drained mux should reroute item");
+ assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(old_items.lock().unwrap().len(), 1);
+ assert_eq!(new_items.lock().unwrap().len(), 1);
+ assert_eq!(pool.endpoints().await, vec![new_addr]);
+}
+
+#[tokio::test]
+async fn pool_with_only_draining_endpoints_fails_fast_without_local_fallback() {
+ let ctx = make_ctx(&[], 0, Duration::from_millis(50)).await;
+ let evt = build_event(1);
+
+ let start = std::time::Instant::now();
+ let err = process_one(remote_stage(ctx), evt)
+ .await
+ .expect_err("empty pool must fail fast");
+ let elapsed = start.elapsed();
+
+ assert!(
+ elapsed < Duration::from_millis(200),
+ "fast-fail expected, took {elapsed:?}"
+ );
+ assert!(
+ format!("{err}").contains("pool unavailable"),
+ "expected pool-unavailable error: {err}"
+ );
+}
+
+struct QueuedResolver {
+ results: TokioMutex<Vec<Vec<SocketAddr>>>,
+}
+
+impl QueuedResolver {
+ fn new(results: Vec<Vec<SocketAddr>>) -> Self {
+ Self {
+ results: TokioMutex::new(results),
+ }
+ }
+}
+
+#[async_trait]
+impl DnsResolver for QueuedResolver {
+ async fn resolve(&self, _host: &str, _port: u16) -> io::Result<Vec<SocketAddr>> {
+ let mut results = self.results.lock().await;
+ if results.is_empty() {
+ return Err(io::Error::other("no more resolver fixtures"));
+ }
+ Ok(results.remove(0))
+ }
+}
diff --git a/rust/cymbal/tests/remote_resolution_parity.rs b/rust/cymbal/tests/remote_resolution_parity.rs
new file mode 100644
index 000000000000..6959c8c7e9c1
--- /dev/null
+++ b/rust/cymbal/tests/remote_resolution_parity.rs
@@ -0,0 +1,197 @@
+//! Parity tests for Batch 4.
+//!
+//! These tests stand up an in-process `cymbal-resolution` service backed by a
+//! shared fake `SymbolResolver`, run the same exception through both the
+//! local `ResolutionStage` (`remote = None`) and the remote stage
+//! (`remote = Some(ctx)`), and assert the resulting `ExceptionList` is
+//! byte-for-byte identical after JSON round-tripping. Parity is the v1
+//! correctness guarantee: when remote mode is enabled, callers must observe
+//! the same resolved frames they would have seen locally.
+//!
+//! Fixtures live in `tests/common/mod.rs`. Add new resolution types here as
+//! they become supported by the remote service.
+
+mod common;
+
+use std::net::SocketAddr;
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common::{build_event, make_ctx};
+use cymbal::error::{ResolveError, UnhandledError};
+use cymbal::frames::{Frame, RawFrame};
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use cymbal::stages::resolution::ResolutionStage;
+use cymbal::symbol_store::chunk_id::OrChunkId;
+use cymbal::symbol_store::proguard::ProguardRef;
+use cymbal::types::batch::Batch;
+use cymbal::types::operator::TeamId;
+use cymbal::types::stage::Stage;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolutionServer;
+use cymbal_resolution::load_monitor::LoadMonitor;
+use cymbal_resolution::service::{CymbalResolutionService, ServiceConfig};
+use tokio::sync::Semaphore;
+
+/// Fake symbol resolver shared by both sides of the parity comparison. Every
+/// resolution method is deterministic and produces the same output for the
+/// same input — the point is that any divergence in the resolved
+/// `ExceptionList` must come from plumbing differences, not from non-determinism.
+#[derive(Default)]
+struct FakeResolver;
+
+#[async_trait]
+impl SymbolResolver for FakeResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ Ok(Vec::new())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("parity fixtures do not exercise Java class resolution")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ unreachable!("parity fixtures do not exercise Dart name resolution")
+ }
+}
+
+async fn spawn_cymbal_resolution_with_resolver(resolver: Arc<dyn SymbolResolver>) -> SocketAddr {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+ let limiter = Arc::new(Semaphore::new(4));
+ let service_config = ServiceConfig {
+ default_tick_interval: Duration::from_millis(50),
+ min_tick_interval: Duration::from_millis(10),
+ max_tick_interval: Duration::from_secs(1),
+ };
+ let service = CymbalResolutionService::new(
+ resolver,
+ limiter,
+ LoadMonitor::new(4),
+ "parity-stub",
+ service_config,
+ Arc::new(AtomicBool::new(false)),
+ );
+
+ tokio::spawn(async move {
+ let _outcome = tonic::transport::Server::builder()
+ .add_service(CymbalResolutionServer::new(service))
+ .serve(addr)
+ .await;
+ });
+
+ for _ in 0..40 {
+ if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() {
+ return addr;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("cymbal-resolution server failed to come up at {addr}");
+}
+
+fn local_stage(resolver: Arc<dyn SymbolResolver>) -> ResolutionStage {
+ ResolutionStage {
+ symbol_resolver: resolver,
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: None,
+ }
+}
+
+fn remote_stage(
+ resolver: Arc<dyn SymbolResolver>,
+ remote: cymbal::stages::resolution::remote::resolver::RemoteResolutionContext,
+) -> ResolutionStage {
+ ResolutionStage {
+ // The symbol_resolver field is unused in remote mode, but
+ // ResolutionStage requires one. Pass the same fake so any accidental
+ // local fallback would still produce parity-matching output.
+ symbol_resolver: resolver,
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: Some(remote),
+ }
+}
+
+async fn run_stage(
+ stage: ResolutionStage,
+ evt: cymbal::types::exception_properties::ExceptionProperties,
+) -> cymbal::types::exception_properties::ExceptionProperties {
+ let batch: Batch<cymbal::stages::pipeline::ExceptionEventPipelineItem> =
+ Batch::from(vec![Ok(evt)]);
+ let result = stage.process(batch).await.expect("stage processed");
+ let mut items: Vec<_> = result.into_iter().collect();
+ assert_eq!(items.len(), 1, "single-event batch must produce one output");
+ items.remove(0).expect("event must not be EventError")
+}
+
+#[tokio::test]
+async fn local_and_remote_stages_produce_identical_exception_list_for_empty_stacks() {
+ let resolver: Arc<dyn SymbolResolver> = Arc::new(FakeResolver);
+ let addr = spawn_cymbal_resolution_with_resolver(resolver.clone()).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+
+ let evt = build_event(3);
+ let local_out = run_stage(local_stage(resolver.clone()), evt.clone()).await;
+ let remote_out = run_stage(remote_stage(resolver, ctx), evt).await;
+
+ // Compare via JSON round-trip so the test stays robust against
+ // Exception's #[serde(skip_serializing_if = "Option::is_none")] fields and
+ // the difference in how `Stacktrace::Raw` vs `Stacktrace::Resolved`
+ // serialize.
+ let local_json = serde_json::to_value(&local_out.exception_list).unwrap();
+ let remote_json = serde_json::to_value(&remote_out.exception_list).unwrap();
+ assert_eq!(local_json, remote_json, "exception_list parity");
+
+ // Properties derived by PropertiesResolver should also match in both
+ // paths, since they're computed from the (parity-checked) exception_list.
+ // `exception_types` / `exception_messages` come back through cymbal's
+ // `unique_by` helper, which round-trips through a HashSet — order is
+ // therefore implementation-defined per run, so we compare as sorted sets.
+ fn sorted(input: Option<Vec<String>>) -> Vec<String> {
+ let mut out = input.unwrap_or_default();
+ out.sort();
+ out
+ }
+ assert_eq!(
+ sorted(local_out.exception_types),
+ sorted(remote_out.exception_types)
+ );
+ assert_eq!(
+ sorted(local_out.exception_messages),
+ sorted(remote_out.exception_messages)
+ );
+ assert_eq!(local_out.exception_handled, remote_out.exception_handled);
+}
+
+#[tokio::test]
+async fn parity_holds_for_empty_exception_list() {
+ let resolver: Arc<dyn SymbolResolver> = Arc::new(FakeResolver);
+ let addr = spawn_cymbal_resolution_with_resolver(resolver.clone()).await;
+ let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
+
+ let evt = build_event(0);
+ let local_out = run_stage(local_stage(resolver.clone()), evt.clone()).await;
+ let remote_out = run_stage(remote_stage(resolver, ctx), evt).await;
+
+ assert_eq!(local_out.exception_list.len(), 0);
+ assert_eq!(remote_out.exception_list.len(), 0);
+ assert_eq!(local_out.exception_types, remote_out.exception_types);
+ assert_eq!(local_out.exception_messages, remote_out.exception_messages);
+}
diff --git a/rust/cymbal/tests/remote_resolution_subscribe.rs b/rust/cymbal/tests/remote_resolution_subscribe.rs
new file mode 100644
index 000000000000..df9aaa319916
--- /dev/null
+++ b/rust/cymbal/tests/remote_resolution_subscribe.rs
@@ -0,0 +1,162 @@
+//! End-to-end coverage for the freshness/draining `Subscribe` RPC and
+//! pool routing on server-reported health.
+//!
+//! These tests bring up a real cymbal-resolution server with a fake symbol
+//! resolver, build an `EndpointPool` pointed at it, and verify that the
+//! pool's per-endpoint subscription task actually fills the load snapshot
+//! and biases routing accordingly. The unit-level pool/subscription tests
+//! validate the in-process logic; this file exercises the gRPC wire as well.
+
+mod common;
+
+use std::net::SocketAddr;
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use cymbal::error::{ResolveError, UnhandledError};
+use cymbal::frames::{Frame, RawFrame};
+use cymbal::langs::apple::AppleDebugImage;
+use cymbal::stages::resolution::remote::{EndpointPool, RemoteResolutionConfig};
+use cymbal::stages::resolution::symbol::SymbolResolver;
+use cymbal::symbol_store::chunk_id::OrChunkId;
+use cymbal::symbol_store::proguard::ProguardRef;
+use cymbal::types::operator::TeamId;
+use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolutionServer;
+use cymbal_resolution::load_monitor::LoadMonitor;
+use cymbal_resolution::service::{CymbalResolutionService, ServiceConfig};
+use tokio::sync::Semaphore;
+
+#[derive(Default)]
+struct EmptyResolver;
+
+#[async_trait]
+impl SymbolResolver for EmptyResolver {
+ async fn resolve_raw_frame(
+ &self,
+ _team_id: TeamId,
+ _frame: &RawFrame,
+ _debug_images: &[AppleDebugImage],
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ Ok(Vec::new())
+ }
+
+ async fn resolve_java_class(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: OrChunkId<ProguardRef>,
+ _class: String,
+ ) -> Result<String, ResolveError> {
+ unreachable!("not exercised by subscribe tests")
+ }
+
+ async fn resolve_dart_minified_name(
+ &self,
+ _team_id: TeamId,
+ _symbolset_ref: String,
+ _minified_name: &str,
+ ) -> Result<String, ResolveError> {
+ unreachable!("not exercised by subscribe tests")
+ }
+}
+
+/// Spawn a real cymbal-resolution server with the given item-admission
+/// limiter and load-event capacity suggestion.
+async fn spawn_real_server(item_limiter: Arc<Semaphore>, max_in_flight: u32) -> SocketAddr {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+
+ let resolver: Arc<dyn SymbolResolver> = Arc::new(EmptyResolver);
+ // Fast tick so the test doesn't pay a second per iteration; min above zero
+ // so the server clamps any hint up safely.
+ let service_config = ServiceConfig {
+ default_tick_interval: Duration::from_millis(25),
+ min_tick_interval: Duration::from_millis(5),
+ max_tick_interval: Duration::from_secs(1),
+ };
+ // Symbol limiter is irrelevant for these tests because EmptyResolver
+ // never acquires; size it generously so it never gates anything.
+ let symbol_limiter = Arc::new(Semaphore::new(64));
+ // Degraded signal disabled (threshold 0); these tests don't exercise it.
+ let load_monitor = LoadMonitor::new(max_in_flight);
+ load_monitor
+ .set_in_flight(max_in_flight.saturating_sub(item_limiter.available_permits() as u32));
+ let service = CymbalResolutionService::new(
+ resolver,
+ symbol_limiter,
+ load_monitor,
+ format!("real-{addr}"),
+ service_config,
+ Arc::new(AtomicBool::new(false)),
+ );
+
+ tokio::spawn(async move {
+ let _outcome = tonic::transport::Server::builder()
+ .add_service(CymbalResolutionServer::new(service))
+ .serve(addr)
+ .await;
+ });
+
+ for _ in 0..40 {
+ if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() {
+ return addr;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("real cymbal-resolution server failed to come up at {addr}");
+}
+
+fn pool_config(host: &str, tick_hint: Duration) -> RemoteResolutionConfig {
+ RemoteResolutionConfig {
+ host: host.to_string(),
+ port: 0,
+ internal_api_secret: "test-secret".to_string(),
+ dns_refresh: Duration::from_secs(60),
+ request_deadline: Duration::from_secs(2),
+ connect_timeout: Duration::from_secs(1),
+ max_retries: 0,
+ retry_backoff: Duration::from_millis(1),
+ retry_max_backoff: Duration::from_millis(2),
+ sample_rate: 1.0,
+ subscribe_tick_hint: tick_hint,
+ subscribe_reconnect_backoff: Duration::from_millis(20),
+ }
+}
+
+#[tokio::test]
+async fn pool_routes_across_endpoints_with_fresh_load_events() {
+ // Both pods serve Subscribe ticks at a fast cadence so the pool's
+ // per-endpoint snapshot fills within a few hundred ms. After that,
+ // select() should route across the healthy endpoint set.
+ let pod_a_limiter = Arc::new(Semaphore::new(8));
+ let pod_b_limiter = Arc::new(Semaphore::new(8));
+
+ let pod_a = spawn_real_server(pod_a_limiter.clone(), 8).await;
+ let pod_b = spawn_real_server(pod_b_limiter.clone(), 8).await;
+
+ let pool = EndpointPool::from_addrs(
+ pool_config("test", Duration::from_millis(25)),
+ &[pod_a, pod_b],
+ )
+ .expect("build pool");
+
+ // Give the subscription tasks a few ticks to populate both snapshots.
+ // The server's tick is 25ms; 500ms is generous but keeps the test snappy.
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ // Random selection across the fresh, healthy set: over many picks both
+ // pods must appear (and only those two — every pick is a known pod).
+ let mut picks = std::collections::HashSet::new();
+ for _ in 0..50 {
+ let handle = pool.select(&[]).await.expect("select succeeds");
+ assert!(handle.addr == pod_a || handle.addr == pod_b);
+ picks.insert(handle.addr);
+ }
+ assert_eq!(
+ picks.len(),
+ 2,
+ "both fresh pods should be selected over time"
+ );
+}
diff --git a/rust/cymbal/tests/utils.rs b/rust/cymbal/tests/utils.rs
index 5e45a319415f..f63d8f2fce14 100644
--- a/rust/cymbal/tests/utils.rs
+++ b/rust/cymbal/tests/utils.rs
@@ -35,9 +35,21 @@ pub(crate) async fn get_response<T: for<'de> Deserialize<'de>>(
storage_bucket: String,
request_factory: impl Fn() -> Request<Body>,
s3_client: Arc<MockS3Client>,
+) -> (StatusCode, T) {
+ get_response_with_config(db, storage_bucket, request_factory, s3_client, |_| {}).await
+}
+
+#[allow(dead_code)]
+pub(crate) async fn get_response_with_config<T: for<'de> Deserialize<'de>>(
+ db: PgPool,
+ storage_bucket: String,
+ request_factory: impl Fn() -> Request<Body>,
+ s3_client: Arc<MockS3Client>,
+ configure: impl FnOnce(&mut Config),
) -> (StatusCode, T) {
let mut config = Config::init_with_defaults().unwrap();
config.object_storage_bucket = storage_bucket.clone();
+ configure(&mut config);
let issue_buckets_redis_client = Arc::new(MockRedisClient::new());