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.

fix(capture-apm-metrics): spread series relabels and harden redis writer (#102315)

Frank Hamand14bcc042f9ad
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 30376345ee8e..5a2aa879c6e5 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2311,6 +2311,7 @@ dependencies = [
"opentelemetry-proto 0.29.0",
"prometheus-rw-proto",
"prost 0.13.5",
+ "redis",
"rustls 0.23.37",
"serde",
"serde_json",
diff --git a/rust/capture-apm-metrics/Cargo.toml b/rust/capture-apm-metrics/Cargo.toml
index 1c4e7039adc5..1c54f25a32d8 100644
--- a/rust/capture-apm-metrics/Cargo.toml
+++ b/rust/capture-apm-metrics/Cargo.toml
@@ -34,5 +34,8 @@ siphasher = { workspace = true }
thiserror = { workspace = true }
uuid = { workspace = true }
+[dev-dependencies]
+redis = { workspace = true }
+
[lints]
workspace = true
diff --git a/rust/capture-apm-metrics/README.md b/rust/capture-apm-metrics/README.md
index f6cd0cfe7a9f..307a8f5aa2a9 100644
--- a/rust/capture-apm-metrics/README.md
+++ b/rust/capture-apm-metrics/README.md
@@ -12,8 +12,8 @@ This binary is the metrics half of [`capture-logs`](../capture-logs/README.md).
|----------|---------|-------------|
| REDIS_URL | (none) | Redis that shares the set of recently labelled metric series between pods. Unset means local cache only |
| METRICS_SERIES_LABEL_GATE_ENABLED | false | Strip label maps from repeat metric rows (see below). When false the gate only reports metrics |
-| METRICS_SERIES_LABEL_INTERVAL_SECS | 1800 | How often the labels of one metric series go out |
-| METRICS_SERIES_REDIS_TIMEOUT_MS | 250 | Budget for one Redis write batch |
+| METRICS_SERIES_LABEL_INTERVAL_SECS | 1800 | Longest gap between two labelled rows of one metric series. Each series uses a window up to a quarter shorter, derived from its key |
+| METRICS_SERIES_REDIS_TIMEOUT_MS | 1000 | Budget for one Redis write batch. A batch past it still runs in Redis; the budget is what slows the writer when Redis is slow |
| METRICS_SERIES_REDIS_SEED_TIMEOUT_MS | 15000 | Longest the service waits at startup for the cache seed. After that it starts with a partial cache |
| METRICS_SERIES_REDIS_PULL_TIMEOUT_MS | 5000 | Budget for one periodic pull from Redis |
| METRICS_SERIES_REDIS_PULL_INTERVAL_SECS | 60 | How often the local cache pulls new series from Redis |
@@ -22,13 +22,15 @@ This binary is the metrics half of [`capture-logs`](../capture-logs/README.md).
### Metric series label gate
-Every metric row carries `series_fingerprint`. The label maps (`attributes`, `resource_attributes`) of a series go out on one row per `METRICS_SERIES_LABEL_INTERVAL_SECS`, with `has_labels = true`. All other rows of that series in the window have empty label maps and `has_labels = false`. The ClickHouse rollups build the series and attribute tables from labelled rows only.
+Every metric row carries `series_fingerprint`. The label maps (`attributes`, `resource_attributes`) of a series go out on one row at least every `METRICS_SERIES_LABEL_INTERVAL_SECS`, with `has_labels = true`. Each series shortens that window by a key-derived offset of up to a quarter, so series first seen together do not go out again together, window after window, in one burst. All other rows of that series in the window have empty label maps and `has_labels = false`. The ClickHouse rollups build the series and attribute tables from labelled rows only.
The decision uses a local in-memory cache and never waits on Redis. Redis holds the set of series any pod has labelled: new series are pushed from a background task, and the cache pulls from Redis at startup and every `METRICS_SERIES_REDIS_PULL_INTERVAL_SECS`. Pulls read the set in pages of 50,000 members and merge each page as it arrives; the startup seed stops at `METRICS_SERIES_REDIS_SEED_TIMEOUT_MS` and keeps what it has. A Redis failure only makes labels go out more often.
Pull metrics, all with a `kind` label of `seed` or `periodic`: `capture_metrics_series_redis_pulls` (with `outcome` = `ok`, `timeout`, or `error`), `capture_metrics_series_redis_pull_duration_seconds` (same labels), `capture_metrics_series_redis_pull_pages`, `capture_metrics_series_redis_pull_members_read`, `capture_metrics_series_redis_pull_bytes` (member payload, without protocol framing), and `capture_metrics_series_redis_pulled` (members new to this pod).
-The cache is bounded. When the global or the per-token cap is full, a new series keeps its labels on every row and is not cached or pushed to Redis, until pruning frees a slot. `capture_metrics_series_cache_full` counts those rows.
+Push metrics: `capture_metrics_series_redis_pushed`, `capture_metrics_series_redis_push_failed` (with `outcome` = `timeout` or `error`), and `capture_metrics_series_redis_push_duration_seconds` (with `outcome` = `ok`, `timeout`, or `error`). `capture_metrics_series_redis_queue_full` counts series dropped because the writer could not keep up. The writer uses its own Redis connection, so a large pull page does not hold its batches back. After three flushes or pulls in a row time out, the writer or puller rebuilds its connection, because a half-open socket times out on every command until the kernel gives up on it.
+
+The cache is bounded. When the global or the per-token cap is full, a new series keeps its labels on every row and is not cached or pushed to Redis, until pruning frees a slot. `capture_metrics_series_cache_full` counts those rows, with `cap` = `global` or `token` for the cap that was full. The `token` series also carries the project token that hit the cap, so the project is known without a log lookup. A `token` count with `capture_metrics_series_cache_size` well under the global cap means that token has more live series than `METRICS_SERIES_CACHE_MAX_ENTRIES_PER_TOKEN` allows.
## Classic Prometheus histograms on remote write
diff --git a/rust/capture-apm-metrics/src/config.rs b/rust/capture-apm-metrics/src/config.rs
index c18112391aa1..d7a03f7794b4 100644
--- a/rust/capture-apm-metrics/src/config.rs
+++ b/rust/capture-apm-metrics/src/config.rs
@@ -20,7 +20,7 @@ pub struct Config {
#[envconfig(from = "METRICS_SERIES_LABEL_INTERVAL_SECS", default = "1800")]
pub metrics_series_label_interval_secs: u64,
- #[envconfig(from = "METRICS_SERIES_REDIS_TIMEOUT_MS", default = "250")]
+ #[envconfig(from = "METRICS_SERIES_REDIS_TIMEOUT_MS", default = "1000")]
pub metrics_series_redis_timeout_ms: u64,
/// Total time the service waits at startup for the series cache seed. When
diff --git a/rust/capture-apm-metrics/src/main.rs b/rust/capture-apm-metrics/src/main.rs
index c0fe8f7dc9c5..eaa060caee91 100644
--- a/rust/capture-apm-metrics/src/main.rs
+++ b/rust/capture-apm-metrics/src/main.rs
@@ -27,7 +27,7 @@ use tokio::signal;
use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};
use tower_http::decompression::RequestDecompressionLayer;
use tracing::level_filters::LevelFilter;
-use tracing::{error, info};
+use tracing::{error, info, warn};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
use limiters::token_dropper::TokenDropper;
@@ -104,7 +104,7 @@ async fn start_series_label_gate(config: &Config) -> Arc<SeriesLabelGate> {
let pull_timeout = Duration::from_millis(config.metrics_series_redis_pull_timeout_ms);
let pull_interval = Duration::from_secs(config.metrics_series_redis_pull_interval_secs);
let client: Arc<dyn Client> = match RedisClient::with_config(
- redis_url,
+ redis_url.clone(),
CompressionConfig::disabled(),
RedisValueFormat::Utf8,
Some(pull_timeout),
@@ -123,11 +123,27 @@ async fn start_series_label_gate(config: &Config) -> Arc<SeriesLabelGate> {
}
};
+ let writer_client: Arc<dyn Client> = match RedisClient::with_config(
+ redis_url,
+ CompressionConfig::disabled(),
+ RedisValueFormat::Utf8,
+ Some(redis_timeout),
+ Some(redis_timeout),
+ )
+ .await
+ {
+ Ok(client) => Arc::new(client),
+ Err(e) => {
+ warn!("Could not open a second Redis connection, series label writer shares the pull connection: {e}");
+ Arc::clone(&client)
+ }
+ };
+
let (gate, rx) = SeriesLabelGate::new(window, enabled, limits);
gate.seed_from_redis(client.as_ref(), seed_budget).await;
- gate.spawn_redis_puller(Arc::clone(&client), pull_interval, pull_timeout);
+ gate.spawn_redis_puller(client, pull_interval, pull_timeout);
gate.spawn_pruner();
- spawn_redis_writer(client, rx, redis_timeout, window);
+ spawn_redis_writer(writer_client, rx, redis_timeout, window);
gate
}
diff --git a/rust/capture-apm-metrics/src/series_label_gate.rs b/rust/capture-apm-metrics/src/series_label_gate.rs
index 459d0fb33838..e08c688bbf8e 100644
--- a/rust/capture-apm-metrics/src/series_label_gate.rs
+++ b/rust/capture-apm-metrics/src/series_label_gate.rs
@@ -47,6 +47,7 @@ const WRITER_CHANNEL_CAPACITY: usize = 10_000;
const WRITER_BATCH_SIZE: usize = 500;
const WRITER_FLUSH_INTERVAL: Duration = Duration::from_secs(1);
const PRUNE_INTERVAL: Duration = Duration::from_secs(300);
+const HEAL_AFTER_CONSECUTIVE_TIMEOUTS: u32 = 3;
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
@@ -93,6 +94,39 @@ pub struct CacheLimits {
pub max_entries_per_token: usize,
}
+#[derive(Debug, Clone, Copy)]
+enum Cap {
+ Global,
+ Token,
+}
+
+impl Cap {
+ fn as_str(self) -> &'static str {
+ match self {
+ Cap::Global => "global",
+ Cap::Token => "token",
+ }
+ }
+}
+
+#[derive(Default)]
+struct TimeoutStreak(u32);
+
+impl TimeoutStreak {
+ fn reset(&mut self) {
+ self.0 = 0;
+ }
+
+ fn record(&mut self) -> bool {
+ self.0 += 1;
+ if self.0 < HEAL_AFTER_CONSECUTIVE_TIMEOUTS {
+ return false;
+ }
+ self.0 = 0;
+ true
+ }
+}
+
struct Entry {
last_seen: i64,
/// `None` for a series pulled from Redis, whose token is unknown here.
@@ -163,7 +197,8 @@ impl SeriesLabelGate {
let mut sent = 0u64;
let mut skipped = 0u64;
let mut queue_full = 0u64;
- let mut cache_full = 0u64;
+ let mut global_full = 0u64;
+ let mut token_full = 0u64;
for row in rows.iter_mut() {
let key = gate_key(token, row.series_fingerprint);
@@ -179,9 +214,16 @@ impl SeriesLabelGate {
// pushed to Redis, so other pods never learn about series this
// pod refused to remember.
sent += 1;
- if !self.remember(key, now, Some(token_hash)) {
- cache_full += 1;
- continue;
+ match self.remember(key, now, Some(token_hash)) {
+ Ok(()) => {}
+ Err(Cap::Global) => {
+ global_full += 1;
+ continue;
+ }
+ Err(Cap::Token) => {
+ token_full += 1;
+ continue;
+ }
}
if let Some(tx) = &self.tx {
if tx.try_send((key, now)).is_err() {
@@ -195,64 +237,71 @@ impl SeriesLabelGate {
if queue_full > 0 {
counter!("capture_metrics_series_redis_queue_full").increment(queue_full);
}
- if cache_full > 0 {
- counter!("capture_metrics_series_cache_full", "source" => "request")
- .increment(cache_full);
+ if global_full > 0 {
+ counter!("capture_metrics_series_cache_full", "source" => "request", "cap" => Cap::Global.as_str())
+ .increment(global_full);
+ }
+ if token_full > 0 {
+ let token: Arc<str> = Arc::from(token);
+ counter!("capture_metrics_series_cache_full", "source" => "request", "cap" => Cap::Token.as_str(), "token" => token)
+ .increment(token_full);
}
}
fn seen_within_window(&self, key: u64, now: i64) -> bool {
self.cache
.get(&key)
- .is_some_and(|entry| now - entry.last_seen < self.window_secs)
+ .is_some_and(|entry| now - entry.last_seen < self.window_for(key))
+ }
+
+ fn window_for(&self, key: u64) -> i64 {
+ self.window_secs - expiry_jitter(key, self.window_secs)
}
/// Record that `key` was labelled at `seen_at`. An entry past its window
/// is refreshed in place and keeps its slot. A new entry needs a free slot
- /// under both caps; returns `false` when there is none.
- fn remember(&self, key: u64, seen_at: i64, token_hash: Option<u64>) -> bool {
+ /// under both caps.
+ fn remember(&self, key: u64, seen_at: i64, token_hash: Option<u64>) -> Result<(), Cap> {
match self.cache.entry(key) {
dashmap::Entry::Occupied(mut slot) => {
slot.get_mut().last_seen = seen_at;
- true
+ Ok(())
}
dashmap::Entry::Vacant(slot) => {
- if !self.reserve(token_hash) {
- return false;
- }
+ self.reserve(token_hash)?;
slot.insert(Entry {
last_seen: seen_at,
token_hash,
});
- true
+ Ok(())
}
}
}
/// Take one slot under the global cap and, when the token is known, its
/// per-token cap. Undoes the global take when the per-token cap is full.
- fn reserve(&self, token_hash: Option<u64>) -> bool {
+ fn reserve(&self, token_hash: Option<u64>) -> Result<(), Cap> {
if self.len.fetch_add(1, Ordering::AcqRel) >= self.limits.max_entries {
self.len.fetch_sub(1, Ordering::AcqRel);
- return false;
+ return Err(Cap::Global);
}
let Some(token_hash) = token_hash else {
- return true;
+ return Ok(());
};
let mut count = self.per_token.entry(token_hash).or_insert(0);
if *count >= self.limits.max_entries_per_token {
drop(count);
self.len.fetch_sub(1, Ordering::AcqRel);
- return false;
+ return Err(Cap::Token);
}
*count += 1;
- true
+ Ok(())
}
/// Drop entries older than the window and release their slots.
fn prune(&self, now: i64) {
- self.cache.retain(|_, entry| {
- if now - entry.last_seen < self.window_secs {
+ self.cache.retain(|key, entry| {
+ if now - entry.last_seen < self.window_for(*key) {
return true;
}
self.len.fetch_sub(1, Ordering::AcqRel);
@@ -320,7 +369,9 @@ impl SeriesLabelGate {
.await;
let outcome = match &result {
Ok(()) => "ok",
- Err(PullError::Timeout { .. }) => "timeout",
+ Err(PullError::Timeout { .. }) | Err(PullError::Redis(CustomRedisError::Timeout)) => {
+ "timeout"
+ }
Err(PullError::Redis(_)) => "error",
};
record_pull(kind, outcome, &stats, started.elapsed());
@@ -385,12 +436,12 @@ impl SeriesLabelGate {
let dashmap::Entry::Vacant(slot) = self.cache.entry(key) else {
continue;
};
- if !self.reserve(None) {
+ if self.reserve(None).is_err() {
stats.cache_full += 1;
continue;
}
slot.insert(Entry {
- last_seen: now - seed_jitter(key, self.window_secs),
+ last_seen: now,
token_hash: None,
});
stats.merged += 1;
@@ -408,6 +459,7 @@ impl SeriesLabelGate {
let gate = Arc::clone(self);
tokio::spawn(async move {
let mut since = (gate.clock)() - PULL_OVERLAP_SECS;
+ let mut timeouts = TimeoutStreak::default();
let mut ticker = tokio::time::interval(interval);
ticker.tick().await;
loop {
@@ -419,11 +471,26 @@ impl SeriesLabelGate {
{
Ok(merged) => {
debug!("Pulled {merged} new series from Redis");
+ timeouts.reset();
since = started - PULL_OVERLAP_SECS;
}
Err(e) => {
// `since` stays put, so the next tick re-reads the gap.
debug!("Series label pull from Redis failed: {e}");
+ match &e {
+ PullError::Timeout { .. }
+ | PullError::Redis(CustomRedisError::Timeout) => {
+ if timeouts.record() {
+ client.heal().await;
+ }
+ }
+ PullError::Redis(e) => {
+ timeouts.reset();
+ if e.is_unrecoverable_error() {
+ client.heal().await;
+ }
+ }
+ }
}
}
}
@@ -468,6 +535,7 @@ pub fn spawn_redis_writer(
let ttl_secs = window.as_secs() + REDIS_BUCKET_SECS as u64;
tokio::spawn(async move {
let mut batch: Vec<SeenSeries> = Vec::with_capacity(WRITER_BATCH_SIZE);
+ let mut timeouts = TimeoutStreak::default();
loop {
let Some(first) = rx.recv().await else {
return;
@@ -489,17 +557,36 @@ pub fn spawn_redis_writer(
let commands = zadd_commands(&batch, ttl_secs);
let pushed = batch.len() as u64;
batch.clear();
- match tokio::time::timeout(timeout, client.execute_pipeline(commands)).await {
+ let started = tokio::time::Instant::now();
+ let result = tokio::time::timeout(timeout, client.execute_pipeline(commands)).await;
+ let outcome = match &result {
+ Ok(Ok(_)) => "ok",
+ Ok(Err(CustomRedisError::Timeout)) | Err(_) => "timeout",
+ Ok(Err(_)) => "error",
+ };
+ histogram!("capture_metrics_series_redis_push_duration_seconds", "outcome" => outcome)
+ .record(started.elapsed().as_secs_f64());
+ match result {
Ok(Ok(_)) => {
+ timeouts.reset();
counter!("capture_metrics_series_redis_pushed").increment(pushed);
}
+ Ok(Err(CustomRedisError::Timeout)) | Err(_) => {
+ counter!("capture_metrics_series_redis_push_failed", "outcome" => outcome)
+ .increment(pushed);
+ debug!("Series label push to Redis timed out");
+ if timeouts.record() {
+ client.heal().await;
+ }
+ }
Ok(Err(e)) => {
- counter!("capture_metrics_series_redis_push_failed").increment(pushed);
+ timeouts.reset();
+ counter!("capture_metrics_series_redis_push_failed", "outcome" => outcome)
+ .increment(pushed);
debug!("Series label push to Redis failed: {e}");
- }
- Err(_) => {
- counter!("capture_metrics_series_redis_push_failed").increment(pushed);
- debug!("Series label push to Redis timed out");
+ if e.is_unrecoverable_error() {
+ client.heal().await;
+ }
}
}
}
@@ -521,16 +608,12 @@ fn record_pull(kind: PullKind, outcome: &'static str, stats: &PullStats, elapsed
counter!("capture_metrics_series_redis_pull_bytes", "kind" => kind).increment(stats.bytes);
counter!("capture_metrics_series_redis_pulled", "kind" => kind).increment(stats.merged as u64);
if stats.cache_full > 0 {
- counter!("capture_metrics_series_cache_full", "source" => "pull")
+ counter!("capture_metrics_series_cache_full", "source" => "pull", "cap" => Cap::Global.as_str())
.increment(stats.cache_full);
}
}
-/// A pulled series gets a timestamp that is a little in the past, so that
-/// series seeded together do not all expire in the same second. Without this,
-/// every pod relabels every seeded series at the same moment one window after
-/// startup. The offset is derived from the key so all pods pick the same one.
-fn seed_jitter(key: u64, window_secs: i64) -> i64 {
+fn expiry_jitter(key: u64, window_secs: i64) -> i64 {
let spread = (window_secs / 4).max(1);
(key % spread as u64) as i64
}
@@ -711,7 +794,8 @@ mod tests {
assert_labelled(&rows[0]);
assert_stripped(&rows[1]);
- now.fetch_add(WINDOW.as_secs() as i64 - 1, Ordering::SeqCst);
+ let window = gate.window_for(gate_key("token-a", 7));
+ now.fetch_add(window - 1, Ordering::SeqCst);
let mut rows = vec![row(7)];
gate.apply("token-a", &mut rows);
assert_stripped(&rows[0]);
@@ -722,6 +806,38 @@ mod tests {
assert_labelled(&rows[0]);
}
+ #[test]
+ fn series_first_seen_together_expire_at_different_times() {
+ let (gate, now, _) = gate(true, false);
+
+ let (early, late) = (1..)
+ .flat_map(|a| (a + 1..a + 200).map(move |b| (a, b)))
+ .find(|(a, b)| {
+ gate.window_for(gate_key("token-a", *a)) < gate.window_for(gate_key("token-a", *b))
+ })
+ .expect("two fingerprints with different windows");
+ let early_window = gate.window_for(gate_key("token-a", early));
+ let late_window = gate.window_for(gate_key("token-a", late));
+ assert!(early_window <= WINDOW.as_secs() as i64);
+ assert!(late_window <= WINDOW.as_secs() as i64);
+
+ let mut rows = vec![row(early), row(late)];
+ gate.apply("token-a", &mut rows);
+ assert_labelled(&rows[0]);
+ assert_labelled(&rows[1]);
+
+ now.fetch_add(early_window, Ordering::SeqCst);
+ let mut rows = vec![row(early), row(late)];
+ gate.apply("token-a", &mut rows);
+ assert_labelled(&rows[0]);
+ assert_stripped(&rows[1]);
+
+ now.fetch_add(late_window - early_window, Ordering::SeqCst);
+ let mut rows = vec![row(late)];
+ gate.apply("token-a", &mut rows);
+ assert_labelled(&rows[0]);
+ }
+
#[test]
fn global_cap_leaves_extra_series_labelled_and_uncached() {
let limits = CacheLimits {
@@ -938,20 +1054,18 @@ mod tests {
.unwrap();
assert_eq!(merged, 1);
- // Seeded within the last quarter window, so it is seen but does not
- // expire in lockstep with the other seeded series.
- let seeded_at = gate.seen_at(remote_key).unwrap();
- let pulled_at = START + 1200;
- assert!(seeded_at <= pulled_at && seeded_at > pulled_at - WINDOW.as_secs() as i64 / 4);
+ assert_eq!(gate.seen_at(remote_key), Some(START + 1200));
+ assert_eq!(gate.seen_at(local_key), Some(START));
let mut rows = vec![row(8)];
gate.apply("token-a", &mut rows);
assert_stripped(&rows[0]);
now.fetch_add(600, Ordering::SeqCst);
- let mut rows = vec![row(7)];
+ let mut rows = vec![row(7), row(8)];
gate.apply("token-a", &mut rows);
assert_labelled(&rows[0]);
+ assert_stripped(&rows[1]);
}
#[tokio::test]
@@ -997,6 +1111,72 @@ mod tests {
assert_eq!(expires[0].key, bucket_key(START));
}
+ #[tokio::test]
+ async fn writer_heals_connection_after_unrecoverable_error() {
+ let (tx, rx) = mpsc::channel(WRITER_CHANNEL_CAPACITY);
+ let dropped = CustomRedisError::from(redis::RedisError::from(std::io::Error::new(
+ std::io::ErrorKind::BrokenPipe,
+ "test",
+ )));
+ assert!(dropped.is_unrecoverable_error());
+ let client = MockRedisClient::new().pipeline_error(dropped);
+ let shared: Arc<dyn Client> = Arc::new(client.clone());
+ spawn_redis_writer(shared, rx, Duration::from_millis(250), WINDOW);
+
+ tx.send((42, START)).await.unwrap();
+
+ let deadline = tokio::time::Instant::now() + WRITER_FLUSH_INTERVAL * 5;
+ while !client.get_calls().iter().any(|c| c.op == "heal")
+ && tokio::time::Instant::now() < deadline
+ {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+
+ assert!(client.get_calls().iter().any(|c| c.op == "heal"));
+ }
+
+ #[tokio::test]
+ async fn writer_heals_connection_after_repeated_timeouts() {
+ let (tx, rx) = mpsc::channel(WRITER_CHANNEL_CAPACITY);
+ let client = MockRedisClient::new().pipeline_block(Duration::from_secs(5));
+ let shared: Arc<dyn Client> = Arc::new(client.clone());
+ spawn_redis_writer(shared, rx, Duration::from_millis(20), WINDOW);
+
+ let flushes = HEAL_AFTER_CONSECUTIVE_TIMEOUTS as usize;
+ for key in 0..(WRITER_BATCH_SIZE * flushes) as u64 {
+ tx.send((key, START)).await.unwrap();
+ }
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
+ while !client.get_calls().iter().any(|c| c.op == "heal")
+ && tokio::time::Instant::now() < deadline
+ {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ assert!(client.get_calls().iter().any(|c| c.op == "heal"));
+ }
+
+ #[tokio::test]
+ async fn puller_heals_connection_after_repeated_timeouts() {
+ let (gate, _, _) = gate(true, false);
+ let gate = Arc::new(gate);
+ let client = MockRedisClient::new();
+ let shared: Arc<dyn Client> = Arc::new(client.clone());
+ gate.spawn_redis_puller(shared, Duration::from_millis(10), Duration::ZERO);
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
+ while !client.get_calls().iter().any(|c| c.op == "heal")
+ && tokio::time::Instant::now() < deadline
+ {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ let calls = client.get_calls();
+ assert!(calls.iter().any(|c| c.op == "heal"));
+ assert!(calls.iter().all(|c| c.op == "heal"));
+ }
+
#[test]
fn bucket_keys_cover_the_whole_range() {
let from = 10 * REDIS_BUCKET_SECS - 1;
diff --git a/rust/common/redis/src/mock.rs b/rust/common/redis/src/mock.rs
index c5d9b0cedf4a..9e205f0a15af 100644
--- a/rust/common/redis/src/mock.rs
+++ b/rust/common/redis/src/mock.rs
@@ -247,6 +247,10 @@ pub struct MockRedisCall {
#[async_trait]
impl Client for MockRedisClient {
+ async fn heal(&self) {
+ self.record_call("heal", "", MockRedisValue::None);
+ }
+
async fn zrangebyscore(
&self,
key: String,