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(flags): rebuild a definitions entry served from S3 (#105123)

James Gilld1c6e3c8afe3
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 0cb5f35949c4..d52c22ccf6ad 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -527,6 +527,15 @@ Reads on the dedicated instance go to its `-ro` reader endpoint. `NotFound` is u
The flag-definitions self-heal queue follows the write side, not the read side. The Rust endpoint enqueues a rebuild request on the dedicated instance (`State::flags_namespace_redis_client`), and the Celery drain reads the queue from `flag_definitions_hypercache.redis_url` (`products/feature_flags/backend/rebuild_queue.py`). Both resolve from `FLAGS_REDIS_URL`, so the producer and the consumer move together on configuration. They can still split on connection state: a Rust process that cannot reach the dedicated cluster at startup falls back to the shared one and enqueues there for its whole life, while Celery keeps draining the dedicated one. Those teams wait for the hourly verifier. `server.rs` logs that startup failure at error level, and the same failure already sends the flags.json, team-metadata, and remote-config readers to the shared cluster, where Django writes nothing. Django and the Rust fleet deploy independently, so a deploy of one before the other leaves requests on the cluster the other side is not reading. Clean up on the **shared** cluster only, and never on the dedicated one, which holds the live queue once both sides are up. A Rust-first rollout puts the window's requests on the dedicated cluster, where the drain collects them as soon as Django deploys, so they need no cleanup. A Django-first rollout puts them on the shared cluster, where nothing reads them again. Either order also leaves the pre-move queue members and the open circuits on the shared cluster. Run `DEL flag_definitions:rebuild_requests flag_definitions:rebuild_circuit` there after both sides are deployed. The circuit-breaker set is included because only the drain prunes it and the key carries no TTL. The cooldown and failure-streak keys expire on their own.
+`FLAG_DEFINITIONS_REBUILD_ON_S3_HIT_ENABLED` defaults to `false`.
+Set it to `true` on the Rust definitions fleet to rebuild entries that S3 serves after a confirmed Redis miss.
+`FLAG_DEFINITIONS_SELF_HEAL_ENABLED` must also be `true`, and the Celery rebuild drain must run.
+The Rust service reads both settings at startup. Restart its pods after a setting change. The service puts S3-hit requests in a lower-priority queue, so cache misses that return 503 drain first. Both queues use `ZADD NX` so repeated polls keep the first enqueue time. The drain skips a queued team if Redis already holds its payload and ETag.
+
+During rollout, watch `flags_flag_definitions_rebuild_requested_total` by `trigger` and `result`.
+Also watch `posthog_flag_definitions_rebuild_queue_depth` and `posthog_flag_definitions_rebuild_oldest_age_seconds`.
+Set the S3-hit variable to `false` and restart the Rust pods to stop new S3-hit requests. Set self-heal to `false` and restart them to stop both triggers. The Celery drain continues to process requests that are already queued after either setting is disabled.
+
The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache update functions check this setting and skip operations if not set.
## Scheduled tasks
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index c69a5f1f739d..44923f3d3a4d 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -276,16 +276,17 @@ Cache and query health are observable via the `flags_cohort_membership_cache_*`
### Redis
-| Variable | Default | Purpose |
-| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `REDIS_URL` | `redis://localhost:6379/` | Shared Redis primary |
-| `REDIS_READER_URL` | (falls back to `REDIS_URL`) | Shared Redis replica |
-| `FLAGS_REDIS_URL` | (empty) | Dedicated flags Redis primary |
-| `FLAGS_REDIS_READER_URL` | (empty) | Dedicated flags Redis replica |
-| `FLAGS_REDIS_ENABLED` | `false` | Inert. Nothing reads it, so setting it moves no read path |
-| `FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED` | `false` | Serve the `/flags/definitions` payload and its ETag from the dedicated flags Redis instead of the shared one. See [dedicated flags Redis](hypercache-system.md#dedicated-flags-redis) |
-| `REDIS_RESPONSE_TIMEOUT_MS` | `100` | Redis response timeout (capped at 30s) |
-| `REDIS_CONNECTION_TIMEOUT_MS` | `5000` | Redis connection timeout (capped at 60s) |
+| Variable | Default | Purpose |
+| -------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `REDIS_URL` | `redis://localhost:6379/` | Shared Redis primary |
+| `REDIS_READER_URL` | (falls back to `REDIS_URL`) | Shared Redis replica |
+| `FLAGS_REDIS_URL` | (empty) | Dedicated flags Redis primary |
+| `FLAGS_REDIS_READER_URL` | (empty) | Dedicated flags Redis replica |
+| `FLAGS_REDIS_ENABLED` | `false` | Inert. Nothing reads it, so setting it moves no read path |
+| `FLAG_DEFINITIONS_DEDICATED_REDIS_ENABLED` | `false` | Serve the `/flags/definitions` payload and its ETag from the dedicated flags Redis instead of the shared one. See [dedicated flags Redis](hypercache-system.md#dedicated-flags-redis) |
+| `FLAG_DEFINITIONS_REBUILD_ON_S3_HIT_ENABLED` | `false` | Rebuild definitions after an S3 hit and a confirmed Redis miss. Requires `FLAG_DEFINITIONS_SELF_HEAL_ENABLED=true`. See [the rebuild queue](hypercache-system.md#dedicated-flags-redis) |
+| `REDIS_RESPONSE_TIMEOUT_MS` | `100` | Redis response timeout (capped at 30s) |
+| `REDIS_CONNECTION_TIMEOUT_MS` | `5000` | Redis connection timeout (capped at 60s) |
### S3 / HyperCache
diff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.py
index 014dda6f1e0b..5374f6c41c8f 100644
--- a/products/feature_flags/backend/rebuild_queue.py
+++ b/products/feature_flags/backend/rebuild_queue.py
@@ -2,11 +2,17 @@
Self-heal queue for the flag-definitions HyperCache.
The Rust ``/flags/definitions`` endpoint reads cohort-inclusive flag definitions
-straight from HyperCache with no DB fallback, so a missing entry returns 503 until
-something rewrites it. On every such miss the Rust service enqueues the team into a
-Redis sorted set (see ``rust/feature-flags/src/api/flag_definitions.rs``); this
-module drains that set and rebuilds the cache, so a missing entry self-heals within
-~1 minute instead of waiting for the hourly verifier or a manual rewarm.
+straight from HyperCache with no DB fallback. Two states put a team in this queue
+(see ``rust/feature-flags/src/api/flag_definitions.rs``):
+
+- Nothing holds the entry, so the request returns 503 until something rewrites it.
+- Redis lost the entry and S3 still has it, so the request succeeds but carries no
+ ETag, and the SDK re-downloads the payload on every poll.
+
+This module drains the set and rebuilds the cache, so either state self-heals within
+~1 minute instead of waiting for the hourly verifier or a manual rewarm. The rebuild
+writes the payload and the ETag together and re-stamps expiry tracking, which returns
+the team to the normal refresh cycle.
Throttling keeps a permanently-failing team from being rebuilt on a loop:
- a per-team cooldown bounds attempts to one per ``COOLDOWN_SECONDS``, and
@@ -17,7 +23,9 @@ The drain exists for the mass-eviction backlog, so it loads the whole batch in o
DB round (like the verifier) rather than per team.
"""
+import json
import time
+from typing import cast
from django.conf import settings
@@ -25,6 +33,7 @@ import redis as redis_lib
import structlog
from celery.exceptions import SoftTimeLimitExceeded
from prometheus_client import Counter, Gauge
+from redis.exceptions import WatchError
from posthog.models.team import Team
from posthog.redis import get_client
@@ -36,10 +45,12 @@ from products.feature_flags.backend.local_evaluation import (
logger = structlog.get_logger(__name__)
-# Sorted set the Rust service writes misses to (member = team_id, score = enqueue
-# time in epoch MILLIS). MUST match FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the
-# Rust service.
+# Sorted set the Rust service writes rebuild requests to (member = team_id, score =
+# epoch MILLIS). The Rust side writes it with ZADD NX, so the score stays at the first
+# request and repeated polls cannot reorder the queue or reset the age gauge. MUST match
+# FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the Rust service.
REBUILD_REQUESTS_ZSET = "flag_definitions:rebuild_requests"
+S3_REBUILD_REQUESTS_ZSET = "flag_definitions:rebuild_s3_requests"
# Sorted set of teams with an open circuit (member = team_id, score = expiry epoch
# seconds). Doubles as the dead-letter gauge source via ZCARD after pruning.
@@ -66,13 +77,14 @@ REBUILD_PROCESSED = Counter(
)
REBUILD_QUEUE_DEPTH = Gauge(
"posthog_flag_definitions_rebuild_queue_depth",
- "Teams currently waiting in the flag-definitions rebuild queue",
+ "Teams queued or rebuilding in the flag-definitions rebuild queue",
)
REBUILD_OLDEST_AGE = Gauge(
"posthog_flag_definitions_rebuild_oldest_age_seconds",
- # Score refreshes on every re-enqueue, so this is seconds since the oldest queued
- # team's most recent miss, not time-stuck. Read alongside queue_depth.
- "Seconds since the oldest queued team's most recent miss (read with queue_depth)",
+ # The NX write keeps a team's first score, so this measures how long a request has
+ # waited rather than how often the team polls. A drained team that is still broken
+ # re-enters the queue with a new score.
+ "Seconds since the oldest queued rebuild request was made",
)
REBUILD_DEAD_LETTER = Gauge(
"posthog_flag_definitions_rebuild_dead_letter_teams",
@@ -106,6 +118,50 @@ def _redis() -> redis_lib.Redis:
return get_client(flag_definitions_hypercache.redis_url)
+def _discard_unless_rebuilding(redis: redis_lib.Redis, queue: str, cooldown_key: str, member: bytes | str) -> bool:
+ """Return True when the member is no longer queued."""
+ # The cooldown can change while another drain finishes, so check and remove atomically.
+ try:
+ with redis.pipeline() as pipe:
+ pipe.watch(cooldown_key)
+ if cast(bytes | None, pipe.get(cooldown_key)) == b"inflight":
+ return False
+ pipe.multi()
+ pipe.zrem(queue, member)
+ pipe.execute()
+ return True
+ except WatchError:
+ # Leave the member for the owner or the next drain after a concurrent change.
+ return False
+
+
+def _restored_team_ids(team_ids: list[int]) -> set[int]:
+ if not team_ids:
+ return set()
+
+ cache = flag_definitions_hypercache
+ keys = [cache.get_cache_key(team_id) for team_id in team_ids]
+ etag_keys = [cache.get_etag_key(team_id) for team_id in team_ids]
+ try:
+ values = cache.cache_client.get_many(keys + etag_keys)
+ except SoftTimeLimitExceeded:
+ raise
+ except Exception:
+ logger.exception("flag definitions self-heal cache presence check failed")
+ return set()
+
+ restored = set()
+ for team_id, key, etag_key in zip(team_ids, keys, etag_keys):
+ if values.get(etag_key) is None:
+ continue
+ try:
+ if isinstance(json.loads(values[key]), dict):
+ restored.add(team_id)
+ except (KeyError, TypeError, ValueError):
+ continue
+ return restored
+
+
def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]:
"""Drain the rebuild request set and rebuild each team's cache once.
@@ -119,45 +175,71 @@ def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]
REBUILD_DEAD_LETTER.set(redis.zcard(CIRCUIT_ZSET))
_emit_queue_gauges(redis, now)
- stats = {"success": 0, "failure": 0, "skipped_cooldown": 0, "circuit_open": 0}
-
- eligible: list[int] = []
- for raw in redis.zrange(REBUILD_REQUESTS_ZSET, 0, batch_size - 1):
- # Remove first: a still-missing team is re-enqueued by its next miss, so we
- # never drop a genuinely-needed rebuild, but we also don't spin on one entry.
- redis.zrem(REBUILD_REQUESTS_ZSET, raw)
-
- team_id = _parse_team_id(raw)
- if team_id is None:
- continue
-
- if redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None:
- stats["circuit_open"] += 1
- REBUILD_PROCESSED.labels(result="circuit_open").inc()
- continue
-
- # Cooldown bounds attempts even while the team keeps polling and re-enqueuing.
- if not redis.set(COOLDOWN_KEY.format(team_id=team_id), 1, nx=True, ex=COOLDOWN_SECONDS):
- stats["skipped_cooldown"] += 1
- REBUILD_PROCESSED.labels(result="skipped_cooldown").inc()
- continue
-
- eligible.append(team_id)
-
+ stats = {"success": 0, "failure": 0, "restored": 0, "skipped_cooldown": 0, "circuit_open": 0}
+
+ eligible: list[tuple[int, str]] = []
+ # A claimed member stays queued until its rebuild ends. A drain that dies keeps its
+ # claims at the head of the queue for COOLDOWN_SECONDS, so the scan pages past every
+ # member that stays queued. `offset` counts those members. The score bound excludes
+ # requests queued after this drain started, so the scan cannot follow teams that SDK
+ # polls enqueue again behind it.
+ max_score = now * 1000
+ for queue in (REBUILD_REQUESTS_ZSET, S3_REBUILD_REQUESTS_ZSET):
+ offset = 0
+ while len(eligible) < batch_size:
+ page = redis.zrangebyscore(queue, "-inf", max_score, start=offset, num=batch_size - len(eligible))
+ if not page:
+ break
+ restored = _restored_team_ids([team_id for raw in page if (team_id := _parse_team_id(raw)) is not None])
+ for raw in page:
+ team_id = _parse_team_id(raw)
+ if team_id is None:
+ redis.zrem(queue, raw)
+ continue
+ if team_id in restored:
+ redis.zrem(queue, raw)
+ stats["restored"] += 1
+ REBUILD_PROCESSED.labels(result="restored").inc()
+ continue
+
+ cooldown_key = COOLDOWN_KEY.format(team_id=team_id)
+ if redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None:
+ if not _discard_unless_rebuilding(redis, queue, cooldown_key, raw):
+ offset += 1
+ stats["circuit_open"] += 1
+ REBUILD_PROCESSED.labels(result="circuit_open").inc()
+ continue
+
+ # Keep the member while rebuilding so SDK polls cannot enqueue it again.
+ if not redis.set(cooldown_key, "inflight", nx=True, ex=COOLDOWN_SECONDS):
+ if not _discard_unless_rebuilding(redis, queue, cooldown_key, raw):
+ offset += 1
+ stats["skipped_cooldown"] += 1
+ REBUILD_PROCESSED.labels(result="skipped_cooldown").inc()
+ continue
+
+ offset += 1
+ eligible.append((team_id, queue))
+
+ results: dict[int, str] = {}
+ timed_out = False
try:
- results = _rebuild_batch(redis, eligible)
+ results = _rebuild_batch(redis, [team_id for team_id, _ in eligible])
except SoftTimeLimitExceeded:
- # Winding down mid-batch. The cooldown was set up front (it doubles as a mutex
- # against overlapping drains), so un-rebuilt teams would otherwise wait out the
- # full 5-minute cooldown. Release the whole batch's cooldowns so the next drain
- # retries them in ~1 minute; already-rebuilt teams won't re-enqueue, so clearing
- # theirs too is harmless.
- for team_id in eligible:
- redis.delete(COOLDOWN_KEY.format(team_id=team_id))
+ timed_out = True
raise
-
- for ok in results.values():
- result = "success" if ok else "failure"
+ finally:
+ for team_id, queue in eligible:
+ cooldown_key = COOLDOWN_KEY.format(team_id=team_id)
+ with redis.pipeline() as pipe:
+ pipe.zrem(queue, str(team_id))
+ if timed_out or team_id not in results:
+ pipe.delete(cooldown_key)
+ else:
+ pipe.set(cooldown_key, "cooldown", xx=True, keepttl=True)
+ pipe.execute()
+
+ for result in results.values():
stats[result] += 1
REBUILD_PROCESSED.labels(result=result).inc()
@@ -172,7 +254,8 @@ def _emit_unread_cluster_gauge() -> None:
REBUILD_UNREAD_CLUSTER_DEPTH.set(0)
return
try:
- depth = get_client(settings.REDIS_URL).zcard(REBUILD_REQUESTS_ZSET)
+ other = get_client(settings.REDIS_URL)
+ depth = other.zcard(REBUILD_REQUESTS_ZSET) + other.zcard(S3_REBUILD_REQUESTS_ZSET)
except Exception:
logger.exception("flag definitions self-heal unread cluster gauge failed")
return
@@ -180,21 +263,19 @@ def _emit_unread_cluster_gauge() -> None:
def _emit_queue_gauges(redis: redis_lib.Redis, now: float) -> None:
- REBUILD_QUEUE_DEPTH.set(redis.zcard(REBUILD_REQUESTS_ZSET))
+ REBUILD_QUEUE_DEPTH.set(redis.zcard(REBUILD_REQUESTS_ZSET) + redis.zcard(S3_REBUILD_REQUESTS_ZSET))
_emit_unread_cluster_gauge()
- oldest = redis.zrange(REBUILD_REQUESTS_ZSET, 0, 0, withscores=True)
+ oldest = redis.zrange(REBUILD_REQUESTS_ZSET, 0, 0, withscores=True) + redis.zrange(
+ S3_REBUILD_REQUESTS_ZSET, 0, 0, withscores=True
+ )
if oldest:
- # score is the most-recent enqueue time in epoch millis. Rust re-enqueues with
- # zadd (not NX), so a team polled every ~30s keeps its score refreshed: this is
- # "time since last miss", bounded by the SDK poll interval, not "time since first
- # miss". A small value is not proof the queue is healthy — read it with depth.
- _, score_ms = oldest[0]
+ _, score_ms = min(oldest, key=lambda item: item[1])
REBUILD_OLDEST_AGE.set(max(0.0, now - float(score_ms) / 1000.0))
else:
REBUILD_OLDEST_AGE.set(0)
-def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, bool]:
+def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, str]:
"""Rebuild every eligible team from a single batched DB load, then record each
outcome. Mirrors the verifier: one batch_load_fn, then set_cache_value per team
(no per-team load_fn), which is the point of draining in one pass.
@@ -216,27 +297,30 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
try:
teams = list(Team.objects.filter(id__in=team_ids))
teams_by_id = {team.id: team for team in teams}
- payloads = batch_load(teams)
+ restored_ids = _restored_team_ids([team.id for team in teams])
+ pending_teams = [team for team in teams if team.id not in restored_ids]
+ payloads = batch_load(pending_teams) if pending_teams else {}
except SoftTimeLimitExceeded:
raise
except Exception:
logger.exception("flag definitions self-heal batch load failed", team_count=len(team_ids))
- return {team_id: _record_result(redis, team_id, ok=False) for team_id in team_ids}
+ return {team_id: "success" if _record_result(redis, team_id, ok=False) else "failure" for team_id in team_ids}
- results: dict[int, bool] = {}
+ results: dict[int, str] = {}
for team_id in team_ids:
team = teams_by_id.get(team_id)
+ if team is not None and team_id in restored_ids:
+ results[team_id] = "restored"
+ continue
# batch_load leaves out a team whose own build failed.
if team is None or team_id not in payloads:
- results[team_id] = _record_result(redis, team_id, ok=False)
+ results[team_id] = "success" if _record_result(redis, team_id, ok=False) else "failure"
continue
payload = payloads[team_id]
if _skip_write_if_group_mapping_emptied(team, payload):
# personhog lag would cache an emptied group_type_mapping; skip the write
# without counting a failure (that would wrongly advance the circuit breaker).
- # Release the cooldown so the team retries on the next drain once the mapping
- # is available, rather than staying missing for the full cooldown window.
- redis.delete(COOLDOWN_KEY.format(team_id=team_id))
+ # Omit the result so the drain releases the cooldown for the next poll.
continue
try:
flag_definitions_hypercache.set_cache_value(team, payload)
@@ -246,7 +330,7 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
except Exception:
logger.exception("flag definitions self-heal rebuild failed", team_id=team_id)
ok = False
- results[team_id] = _record_result(redis, team_id, ok=ok)
+ results[team_id] = "success" if _record_result(redis, team_id, ok=ok) else "failure"
return results
diff --git a/products/feature_flags/backend/test/test_rebuild_queue.py b/products/feature_flags/backend/test/test_rebuild_queue.py
index af4ea69ea1c0..fce12261755c 100644
--- a/products/feature_flags/backend/test/test_rebuild_queue.py
+++ b/products/feature_flags/backend/test/test_rebuild_queue.py
@@ -23,6 +23,7 @@ from products.feature_flags.backend.rebuild_queue import (
COOLDOWN_KEY,
FAILURE_STREAK_KEY,
REBUILD_REQUESTS_ZSET,
+ S3_REBUILD_REQUESTS_ZSET,
drain_rebuild_requests,
)
@@ -51,14 +52,17 @@ def _rebuilds(error=None, skip_write=False, load_error=None, omit=()):
patch.object(rebuild_queue, "Team") as team,
patch.object(rebuild_queue, "_skip_write_if_group_mapping_emptied", return_value=skip_write),
patch.object(rebuild_queue.flag_definitions_hypercache, "batch_load_fn", new=_load),
+ patch.object(
+ rebuild_queue.flag_definitions_hypercache, "cache_client", new=SimpleNamespace(get_many=lambda keys: {})
+ ),
patch.object(rebuild_queue.flag_definitions_hypercache, "set_cache_value", side_effect=error) as set_cache,
):
team.objects.filter.side_effect = lambda id__in: [SimpleNamespace(id=int(t)) for t in id__in]
yield set_cache
-def _enqueue(client, team_id, score=0):
- client.zadd(REBUILD_REQUESTS_ZSET, {str(team_id): score})
+def _enqueue(client, team_id, score=0, queue=REBUILD_REQUESTS_ZSET):
+ client.zadd(queue, {str(team_id): score})
DEDICATED_REDIS_URL = "redis://flags-dedicated:6379/"
@@ -83,11 +87,123 @@ def _dedicated_cache(registered: bool) -> Iterator[None]:
def test_drain_rebuilds_queued_team_and_clears_it(fake_redis):
_enqueue(fake_redis, 140414)
- with _rebuilds():
+ with _rebuilds() as set_cache:
+
+ def poll_during_rebuild(team, payload):
+ overlap = drain_rebuild_requests(batch_size=1)
+ assert overlap["skipped_cooldown"] == 1
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, str(team.id)) is not None
+ assert fake_redis.zadd(REBUILD_REQUESTS_ZSET, {str(team.id): 1000}, nx=True) == 0
+
+ set_cache.side_effect = poll_during_rebuild
stats = drain_rebuild_requests()
+ next_stats = drain_rebuild_requests()
assert stats["success"] == 1
assert fake_redis.zcard(REBUILD_REQUESTS_ZSET) == 0
+ assert next_stats == {"success": 0, "failure": 0, "restored": 0, "skipped_cooldown": 0, "circuit_open": 0}
+ set_cache.assert_called_once()
+ assert fake_redis.get(COOLDOWN_KEY.format(team_id=140414)) == b"cooldown"
+ assert 0 < fake_redis.ttl(COOLDOWN_KEY.format(team_id=140414)) <= rebuild_queue.COOLDOWN_SECONDS
+
+
+def test_cache_misses_take_priority_over_older_s3_hits(fake_redis):
+ _enqueue(fake_redis, 1, score=1, queue=S3_REBUILD_REQUESTS_ZSET)
+ _enqueue(fake_redis, 2, score=2)
+
+ with _rebuilds() as set_cache:
+ first = drain_rebuild_requests(batch_size=1)
+ second = drain_rebuild_requests(batch_size=1)
+
+ assert first["success"] == second["success"] == 1
+ assert [call.args[0].id for call in set_cache.call_args_list] == [2, 1]
+
+
+def test_restored_redis_entry_skips_rebuild(fake_redis):
+ _enqueue(fake_redis, 3)
+ with _dedicated_cache(registered=False):
+ cache = rebuild_queue.flag_definitions_hypercache
+ with _rebuilds() as set_cache:
+ with patch.object(
+ cache.cache_client,
+ "get_many",
+ return_value={cache.get_cache_key(3): '{"flags": []}', cache.get_etag_key(3): "etag"},
+ ):
+ stats = drain_rebuild_requests()
+
+ assert stats["restored"] == 1
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "3") is None
+ set_cache.assert_not_called()
+
+
+def test_restored_entries_do_not_use_batch_slots(fake_redis):
+ _enqueue(fake_redis, 3, score=1)
+ _enqueue(fake_redis, 4, score=2)
+ cache = rebuild_queue.flag_definitions_hypercache
+ restored = {cache.get_cache_key(3): '{"flags": []}', cache.get_etag_key(3): "etag"}
+ with _rebuilds() as set_cache:
+ with patch.object(cache.cache_client, "get_many", return_value=restored):
+ stats = drain_rebuild_requests(batch_size=1)
+
+ assert stats["restored"] == 1 and stats["success"] == 1
+ assert set_cache.call_args.args[0].id == 4
+
+
+def test_corrupt_redis_entry_does_not_block_other_rebuilds(fake_redis):
+ _enqueue(fake_redis, 3)
+ _enqueue(fake_redis, 4)
+ cache = rebuild_queue.flag_definitions_hypercache
+ values = {
+ cache.get_cache_key(3): "not JSON",
+ cache.get_etag_key(3): "etag",
+ cache.get_cache_key(4): '{"flags": []}',
+ cache.get_etag_key(4): "etag",
+ }
+ with _rebuilds() as set_cache:
+ with patch.object(cache.cache_client, "get_many", return_value=values):
+ stats = drain_rebuild_requests()
+
+ assert stats["restored"] == 1 and stats["success"] == 1
+ assert set_cache.call_args.args[0].id == 3
+
+
+def test_entry_restored_after_claim_skips_batch_load(fake_redis):
+ _enqueue(fake_redis, 3)
+ cache = rebuild_queue.flag_definitions_hypercache
+ restored = {cache.get_cache_key(3): '{"flags": []}', cache.get_etag_key(3): "etag"}
+ with _rebuilds() as set_cache:
+ with patch.object(cache.cache_client, "get_many", side_effect=[{}, restored]):
+ stats = drain_rebuild_requests()
+
+ assert stats["restored"] == 1
+ set_cache.assert_not_called()
+
+
+def test_cache_presence_check_propagates_soft_time_limit(fake_redis):
+ _enqueue(fake_redis, 3)
+ cache = rebuild_queue.flag_definitions_hypercache
+ with _rebuilds():
+ with patch.object(cache.cache_client, "get_many", side_effect=SoftTimeLimitExceeded()):
+ with pytest.raises(SoftTimeLimitExceeded):
+ drain_rebuild_requests()
+
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "3") is not None
+ assert not fake_redis.exists(COOLDOWN_KEY.format(team_id=3))
+
+
+def test_claims_left_by_a_dead_drain_do_not_block_later_teams(fake_redis):
+ for score, team_id in enumerate((1, 2, 3)):
+ _enqueue(fake_redis, team_id, score=score)
+ # A drain killed before its finally block leaves its claims queued at the head.
+ for team_id in (1, 2):
+ fake_redis.set(COOLDOWN_KEY.format(team_id=team_id), "inflight", ex=300)
+
+ with _rebuilds() as set_cache:
+ stats = drain_rebuild_requests(batch_size=2)
+
+ assert [call.args[0].id for call in set_cache.call_args_list] == [3]
+ assert stats["success"] == 1 and stats["skipped_cooldown"] == 2
+ assert fake_redis.zrange(REBUILD_REQUESTS_ZSET, 0, -1) == [b"1", b"2"]
def test_invalid_member_is_discarded_without_rebuild(fake_redis):
@@ -96,7 +212,7 @@ def test_invalid_member_is_discarded_without_rebuild(fake_redis):
stats = drain_rebuild_requests()
assert fake_redis.zcard(REBUILD_REQUESTS_ZSET) == 0
- assert stats == {"success": 0, "failure": 0, "skipped_cooldown": 0, "circuit_open": 0}
+ assert stats == {"success": 0, "failure": 0, "restored": 0, "skipped_cooldown": 0, "circuit_open": 0}
def test_cooldown_prevents_a_second_rebuild_within_the_window(fake_redis):
@@ -111,6 +227,7 @@ def test_cooldown_prevents_a_second_rebuild_within_the_window(fake_redis):
assert stats["skipped_cooldown"] == 1
assert stats["success"] == 0 # not retried during cooldown
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "1") is None
def test_circuit_opens_after_repeated_failures_then_skips(fake_redis):
@@ -128,6 +245,7 @@ def test_circuit_opens_after_repeated_failures_then_skips(fake_redis):
assert stats["circuit_open"] == 1
assert fake_redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, str(team_id)) is None
def test_successful_rebuild_after_circuit_expiry_clears_streak_and_circuit(fake_redis):
@@ -163,6 +281,12 @@ def test_rebuild_exception_is_caught_and_counts_as_failure(fake_redis):
# that advances the streak.
assert stats["failure"] == 1
assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=5)) == b"1"
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "5") is None
+ assert fake_redis.zadd(REBUILD_REQUESTS_ZSET, {"5": 1}, nx=True) == 1
+ fake_redis.delete(COOLDOWN_KEY.format(team_id=5))
+ with _rebuilds():
+ retry = drain_rebuild_requests()
+ assert retry["success"] == 1
def test_batch_load_failure_counts_every_team_as_failure(fake_redis):
@@ -199,6 +323,7 @@ def test_group_mapping_guard_skips_write_without_counting_failure(fake_redis):
set_cache.assert_not_called()
assert stats["success"] == 0 and stats["failure"] == 0
assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=8)) is None
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "8") is None
# Cooldown released so the team retries next drain once the mapping is available.
assert not fake_redis.exists(COOLDOWN_KEY.format(team_id=8))
@@ -211,6 +336,8 @@ def test_soft_time_limit_propagates_and_is_not_counted_as_failure(fake_redis):
drain_rebuild_requests()
assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=3)) is None
+ assert fake_redis.zscore(REBUILD_REQUESTS_ZSET, "3") is None
+ assert fake_redis.zadd(REBUILD_REQUESTS_ZSET, {"3": 1}, nx=True) == 1
# Cooldown released on wind-down so the next drain retries promptly (~1 min).
assert not fake_redis.exists(COOLDOWN_KEY.format(team_id=3))
@@ -235,6 +362,7 @@ def test_request_zset_key_matches_rust_contract():
# Tripwire for the hand-synced cross-language key: a Python-side rename trips here
# and prompts updating FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the Rust service.
assert REBUILD_REQUESTS_ZSET == "flag_definitions:rebuild_requests"
+ assert S3_REBUILD_REQUESTS_ZSET == "flag_definitions:rebuild_s3_requests"
def test_drain_reads_the_dedicated_cluster_and_ignores_the_shared_one():
diff --git a/rust/common/hypercache/src/lib.rs b/rust/common/hypercache/src/lib.rs
index 45ea4cd7f371..ae468f40326e 100644
--- a/rust/common/hypercache/src/lib.rs
+++ b/rust/common/hypercache/src/lib.rs
@@ -177,7 +177,15 @@ enum RawJsonResult {
#[derive(Debug, Clone, PartialEq)]
pub enum CacheSource {
Redis,
+ /// S3 answered after Redis confirmed the key was absent, so the entry is genuinely
+ /// missing from the Redis tier.
S3,
+ /// S3 answered after the Redis read failed, timed out, or returned a value that would
+ /// not decode. Whether the key exists in Redis is unknown. Callers that repair or
+ /// rebuild the Redis tier must act on `S3` only, because acting on this variant would
+ /// write during a Redis incident, when the cluster can least afford it. Canonical logs
+ /// group both variants as "s3".
+ S3AfterRedisError,
Fallback,
}
@@ -187,6 +195,7 @@ impl CacheSource {
match self {
CacheSource::Redis => "redis",
CacheSource::S3 => "s3",
+ CacheSource::S3AfterRedisError => "s3",
CacheSource::Fallback => "fallback",
}
}
@@ -655,12 +664,17 @@ impl HyperCacheReader {
namespace = %self.config.namespace,
"HyperCache hit: S3"
);
- // Repair only a confirmed Redis miss. Reaching S3 on a Redis error or
+ // One branch decides both outcomes, so a repair can never happen on a
+ // source the caller was told to distrust. Reaching S3 on a Redis error or
// timeout means the tier is degraded, and piling detached repair writes
// onto it would only add load.
- if infra_error.is_none() {
- self.spawn_read_repair(redis_cache_key, raw_json);
- }
+ let source = match infra_error {
+ None => {
+ self.spawn_read_repair(redis_cache_key, raw_json);
+ CacheSource::S3
+ }
+ Some(_) => CacheSource::S3AfterRedisError,
+ };
inc(
HYPERCACHE_COUNTER_NAME,
&[
@@ -670,7 +684,7 @@ impl HyperCacheReader {
],
1,
);
- return Ok((Some(data), CacheSource::S3));
+ return Ok((Some(data), source));
}
Ok(Err(HyperCacheError::S3(S3Error::NotFound(_)))) => {
debug!(
@@ -1461,13 +1475,15 @@ mod tests {
#[cfg(feature = "mock-client")]
async fn redis_calls_after_s3_hit(
fixture: &RedisMissS3HitFixture,
+ expected_source: CacheSource,
) -> Vec<common_redis::MockRedisCall> {
let (_, source) = fixture
.reader
.get_with_source(&fixture.team_key)
.await
.unwrap();
- assert_eq!(source, CacheSource::S3);
+ assert_eq!(source, expected_source);
+ assert_eq!(source.as_log_str(), "s3");
tokio::time::sleep(Duration::from_millis(1)).await;
fixture.redis.get_calls()
@@ -1481,7 +1497,7 @@ mod tests {
config.read_repair_ttl_seconds = Some(600);
let fixture = redis_miss_s3_hit_fixture(config, payload);
- let calls = redis_calls_after_s3_hit(&fixture).await;
+ let calls = redis_calls_after_s3_hit(&fixture, CacheSource::S3).await;
let repair = calls
.iter()
@@ -1504,7 +1520,7 @@ mod tests {
async fn test_s3_hit_does_not_repair_redis_by_default() {
// The reader is read-only unless a caller opts in.
let fixture = redis_miss_s3_hit_fixture(create_test_config(), r#"{"key":"value"}"#);
- let calls = redis_calls_after_s3_hit(&fixture).await;
+ let calls = redis_calls_after_s3_hit(&fixture, CacheSource::S3).await;
assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
}
@@ -1517,7 +1533,7 @@ mod tests {
config.enable_etag = true;
let fixture = redis_miss_s3_hit_fixture(config, r#"{"key":"value"}"#);
- let calls = redis_calls_after_s3_hit(&fixture).await;
+ let calls = redis_calls_after_s3_hit(&fixture, CacheSource::S3).await;
assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
}
@@ -1569,7 +1585,7 @@ mod tests {
let fixture =
redis_failure_s3_hit_fixture(config, r#"{"key":"value"}"#, CustomRedisError::Timeout);
- let calls = redis_calls_after_s3_hit(&fixture).await;
+ let calls = redis_calls_after_s3_hit(&fixture, CacheSource::S3AfterRedisError).await;
assert!(calls.iter().all(|c| c.op != "set_nx_ex_with_format"));
}
@@ -2042,7 +2058,7 @@ mod tests {
.await
.unwrap();
- assert_eq!(source, CacheSource::S3);
+ assert_eq!(source, CacheSource::S3AfterRedisError);
assert_eq!(data, Some(expected));
assert!(
redis_handle.get_calls().iter().any(|c| c.key == cache_key),
@@ -2084,7 +2100,7 @@ mod tests {
.await
.unwrap();
- assert_eq!(source, CacheSource::S3);
+ assert_eq!(source, CacheSource::S3AfterRedisError);
assert_eq!(data, Some(expected));
assert!(
redis_handle.get_calls().iter().any(|c| c.key == cache_key),
diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rs
index 35d690263cea..2655d8ac25e4 100644
--- a/rust/common/redis/src/client.rs
+++ b/rust/common/redis/src/client.rs
@@ -390,6 +390,20 @@ impl Client for RedisClient {
Ok(())
}
+ async fn zadd_nx(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError> {
+ let mut conn = self.conn();
+ zadd_nx_command(&k, &member, score)
+ .query_async::<()>(&mut conn)
+ .await?;
+ Ok(())
+ }
+
+ async fn zrem(&self, k: String, member: String) -> Result<(), CustomRedisError> {
+ let mut conn = self.conn();
+ conn.zrem::<_, _, ()>(k, member).await?;
+ Ok(())
+ }
+
async fn hincrby(&self, k: String, v: String, count: i64) -> Result<(), CustomRedisError> {
let mut conn = self.conn();
conn.hincr::<_, _, _, ()>(k, v, count).await?;
@@ -850,10 +864,25 @@ impl RedisClient {
}
}
+fn zadd_nx_command(key: &str, member: &str, score: i64) -> redis::Cmd {
+ let mut command = redis::cmd("ZADD");
+ command.arg(key).arg("NX").arg(score).arg(member);
+ command
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn test_zadd_nx_command_encodes_score_before_member() {
+ let command = zadd_nx_command("rebuilds", "team-1", 100);
+ assert_eq!(
+ command.get_packed_command(),
+ b"*5\r\n$4\r\nZADD\r\n$8\r\nrebuilds\r\n$2\r\nNX\r\n$3\r\n100\r\n$6\r\nteam-1\r\n"
+ );
+ }
+
// Test helper functions to reduce duplication
mod helpers {
use super::*;
@@ -1614,6 +1643,50 @@ mod integration_tests {
}
}
+ // `zadd_nx` is hand-built from `redis::cmd` because the driver exposes no NX helper, so
+ // the argument order is ours to get wrong. `ZADD key NX member score` parses the member
+ // as a score and returns an error the caller only sees as a failed write, which would
+ // leave the rebuild queue silently empty. This pins the order against a real server.
+ #[tokio::test]
+ #[ignore] // Requires Docker; run with: cargo test integration_tests -- --ignored
+ async fn test_zadd_nx_keeps_the_first_score() {
+ let (client, _container) = create_test_client().await;
+ let key = "zadd_nx_score".to_string();
+ let member = "team-1".to_string();
+
+ client
+ .zadd_nx(key.clone(), member.clone(), 100)
+ .await
+ .unwrap();
+ client
+ .zadd_nx(key.clone(), member.clone(), 200)
+ .await
+ .unwrap();
+
+ // The trait has no ZSCORE, so read the score back through a range that admits one
+ // value.
+ let at_first_score = client
+ .zrangebyscore(key.clone(), "100".to_string(), "100".to_string())
+ .await
+ .unwrap();
+ assert_eq!(
+ at_first_score,
+ vec![member.clone()],
+ "the second NX write must leave the first score alone"
+ );
+
+ client.zadd(key.clone(), member.clone(), 200).await.unwrap();
+ let at_new_score = client
+ .zrangebyscore(key.clone(), "200".to_string(), "200".to_string())
+ .await
+ .unwrap();
+ assert_eq!(
+ at_new_score,
+ vec![member],
+ "a plain zadd moves the member, which is the behavior NX exists to avoid"
+ );
+ }
+
/// Helper to create a test client with compression enabled.
/// Uses a low threshold (100 bytes) to ensure compression triggers for test values.
async fn create_test_client_with_compression(
diff --git a/rust/common/redis/src/lib.rs b/rust/common/redis/src/lib.rs
index 640b6ceab786..7c5912061f2b 100644
--- a/rust/common/redis/src/lib.rs
+++ b/rust/common/redis/src/lib.rs
@@ -215,6 +215,12 @@ pub trait Client: Send + Sync {
/// Add a single (member, score) pair to a sorted set.
async fn zadd(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError>;
+ /// Add a (member, score) pair only when the member is absent, so repeated writes keep
+ /// the first score. `zadd` overwrites it.
+ async fn zadd_nx(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError>;
+
+ async fn zrem(&self, k: String, member: String) -> Result<(), CustomRedisError>;
+
async fn hincrby(&self, k: String, v: String, count: i64) -> Result<(), CustomRedisError>;
async fn get(&self, k: String) -> Result<String, CustomRedisError>;
diff --git a/rust/common/redis/src/mock.rs b/rust/common/redis/src/mock.rs
index 16ec17116de9..c5d9b0cedf4a 100644
--- a/rust/common/redis/src/mock.rs
+++ b/rust/common/redis/src/mock.rs
@@ -305,6 +305,21 @@ impl Client for MockRedisClient {
Ok(())
}
+ async fn zadd_nx(
+ &self,
+ key: String,
+ member: String,
+ score: i64,
+ ) -> Result<(), CustomRedisError> {
+ self.record_call("zadd_nx", key, MockRedisValue::MemberScore(member, score));
+ Ok(())
+ }
+
+ async fn zrem(&self, key: String, member: String) -> Result<(), CustomRedisError> {
+ self.record_call("zrem", key, MockRedisValue::String(member));
+ Ok(())
+ }
+
async fn hincrby(
&self,
key: String,
diff --git a/rust/common/redis/src/read_write.rs b/rust/common/redis/src/read_write.rs
index 4f037bc86df8..6f8ef0cfa8f5 100644
--- a/rust/common/redis/src/read_write.rs
+++ b/rust/common/redis/src/read_write.rs
@@ -399,6 +399,14 @@ impl Client for ReadWriteClient {
self.writer.zadd(k, member, score).await
}
+ async fn zadd_nx(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError> {
+ self.writer.zadd_nx(k, member, score).await
+ }
+
+ async fn zrem(&self, k: String, member: String) -> Result<(), CustomRedisError> {
+ self.writer.zrem(k, member).await
+ }
+
async fn set_with_format(
&self,
k: String,
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index 05b304d6b467..5ca325927428 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -21,25 +21,34 @@ use axum::{
http::{HeaderMap, Method, StatusCode},
response::{IntoResponse, Json, Response},
};
-use common_hypercache::{HyperCacheError, KeyType};
+use common_hypercache::{CacheSource, HyperCacheError, KeyType};
use common_metrics::inc;
+use common_redis::Client as RedisClient;
use common_types::TeamId;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::PgPool;
use std::collections::HashSet;
+use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{info, warn};
const ALLOWLIST_TTL_SECS: u64 = 60;
-/// Redis sorted set holding team IDs whose flag-definitions cache is missing and
-/// needs a rebuild. A Celery worker drains it (member = team_id, score = enqueue
-/// time in epoch millis). Must stay in sync with `REBUILD_REQUESTS_ZSET` in
-/// `products/feature_flags/backend/rebuild_queue.py` (pinned by the Python test
-/// `test_request_zset_key_matches_rust_contract`).
+/// Redis sorted set holding team IDs whose flag-definitions Redis entry is gone and
+/// needs a rebuild. A Celery worker drains it (member = team_id, score = the first
+/// request's time in epoch millis, kept by the NX write below). Must stay in sync with
+/// `REBUILD_REQUESTS_ZSET` in `products/feature_flags/backend/rebuild_queue.py` (pinned by
+/// the Python test `test_request_zset_key_matches_rust_contract`).
pub(crate) const FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET: &str = "flag_definitions:rebuild_requests";
+pub(crate) const FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET: &str =
+ "flag_definitions:rebuild_s3_requests";
+
+/// `trigger` label values for `FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER`. The two triggers
+/// ramp independently, so the dashboard has to separate them.
+const REBUILD_TRIGGER_CACHE_MISS: &str = "cache_miss";
+const REBUILD_TRIGGER_S3_HIT: &str = "s3_hit";
static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("RATE_LIMITING_ALLOW_LIST_TEAMS"));
/// Refresh the rate limit allowlist from the database if stale, then update the limiter.
@@ -416,6 +425,13 @@ async fn resolve_team_from_auth(state: &AppState, headers: &HeaderMap) -> Result
Err(FlagError::NoAuthenticationProvided)
}
+fn cache_hit_metric_source_label(source: &CacheSource) -> &'static str {
+ match source {
+ CacheSource::S3AfterRedisError => "s3_after_redis_error",
+ _ => source.as_log_str(),
+ }
+}
+
/// Retrieves the cached response using the pre-initialized HyperCacheReader
///
/// Always uses the cache with cohorts included to match Django's behavior and ensure
@@ -439,7 +455,10 @@ async fn get_from_cache(
let source_name = source.as_log_str();
inc(
FLAG_DEFINITIONS_CACHE_HIT_COUNTER,
- &[("source".to_string(), source_name.to_string())],
+ &[(
+ "source".to_string(),
+ cache_hit_metric_source_label(&source).to_string(),
+ )],
1,
);
info!(
@@ -447,6 +466,12 @@ async fn get_from_cache(
source = source_name,
"Cache hit for flag definitions"
);
+ if should_rebuild_after_hit(
+ &source,
+ *state.config.flag_definitions_rebuild_on_s3_hit_enabled,
+ ) {
+ enqueue_flag_definitions_rebuild(state, team_id, REBUILD_TRIGGER_S3_HIT);
+ }
Ok(data)
}
Err(e) => {
@@ -472,15 +497,24 @@ async fn get_from_cache(
// Self-heal: a genuinely empty cache (not a transient redis/s3/parse
// error) has no DB fallback here, so it would 503 until something
// rewrites it. Enqueue a debounced rebuild request for a Celery worker.
- if reason == "cache_miss" && *state.config.flag_definitions_self_heal_enabled {
- enqueue_flag_definitions_rebuild(state, team_id);
+ if reason == "cache_miss" {
+ enqueue_flag_definitions_rebuild(state, team_id, REBUILD_TRIGGER_CACHE_MISS);
}
Err(FlagError::from(e))
}
}
}
-/// Fire-and-forget enqueue of a flag-definitions rebuild request on cache miss.
+/// Only `CacheSource::S3` qualifies, because only that source proves Redis answered and did
+/// not hold the key. `S3AfterRedisError` reaches S3 because the Redis read failed, timed out,
+/// or would not decode, which says nothing about whether the entry exists. Queueing on that
+/// would enqueue every team served during a Redis incident and point a rebuild storm at the
+/// cluster that is already failing.
+fn should_rebuild_after_hit(source: &CacheSource, enabled: bool) -> bool {
+ enabled && matches!(source, CacheSource::S3)
+}
+
+/// Fire-and-forget enqueue of a flag-definitions rebuild request.
///
/// Writes to a Redis sorted set on the flags-namespace client, because that is where the
/// Django writer lives. The Celery drain derives its Redis from
@@ -501,32 +535,58 @@ async fn get_from_cache(
/// drains. Unifying the queue with the reader severs the queue from the drain whenever the two
/// clusters differ.
///
-/// Re-enqueuing a team only updates its score, so a client polling a missing team
-/// every ~30s occupies a single slot. Spawned so it never adds latency to (or
-/// changes) the failing response.
-fn enqueue_flag_definitions_rebuild(state: &AppState, team_id: i32) {
- let redis = state.flags_namespace_redis_client();
- tokio::spawn(async move {
- let score = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_millis() as i64)
- .unwrap_or(0);
- let result = redis
- .zadd(
- FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string(),
- team_id.to_string(),
- score,
- )
- .await;
- inc(
- FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER,
- &[(
+/// Spawned so it never adds response latency. `write_rebuild_request` holds the write.
+///
+/// `FLAG_DEFINITIONS_SELF_HEAL_ENABLED` is checked here rather than at each call site, so it
+/// stops every trigger. A trigger that also needs its own ramp adds that switch at its call
+/// site.
+fn enqueue_flag_definitions_rebuild(state: &AppState, team_id: i32, trigger: &'static str) {
+ if !*state.config.flag_definitions_self_heal_enabled {
+ return;
+ }
+
+ tokio::spawn(write_rebuild_request(
+ state.flags_namespace_redis_client(),
+ team_id,
+ trigger,
+ ));
+}
+
+async fn write_rebuild_request(
+ redis: Arc<dyn RedisClient + Send + Sync>,
+ team_id: i32,
+ trigger: &'static str,
+) {
+ let score = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(0);
+ // NX, so a team that has been waiting keeps the score it was queued with. An
+ // overwriting write would move it behind requests made later, and the drain takes the
+ // lowest scores first.
+ let result = redis
+ .zadd_nx(
+ if trigger == REBUILD_TRIGGER_S3_HIT {
+ FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET
+ } else {
+ FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET
+ }
+ .to_string(),
+ team_id.to_string(),
+ score,
+ )
+ .await;
+ inc(
+ FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER,
+ &[
+ (
"result".to_string(),
if result.is_ok() { "ok" } else { "error" }.to_string(),
- )],
- 1,
- );
- });
+ ),
+ ("trigger".to_string(), trigger.to_string()),
+ ],
+ 1,
+ );
}
/// Authenticates flag definitions requests using team secret API tokens or personal API keys
@@ -615,6 +675,51 @@ mod tests {
assert_eq!(has_billable_flags(&response), expected);
}
+ #[rstest]
+ #[case::confirmed_redis_miss(CacheSource::S3, true, true)]
+ #[case::redis_read_failed(CacheSource::S3AfterRedisError, true, false)]
+ #[case::served_by_redis(CacheSource::Redis, true, false)]
+ #[case::served_by_fallback(CacheSource::Fallback, true, false)]
+ #[case::switch_off(CacheSource::S3, false, false)]
+ fn test_should_rebuild_after_hit(
+ #[case] source: CacheSource,
+ #[case] enabled: bool,
+ #[case] expected: bool,
+ ) {
+ assert_eq!(should_rebuild_after_hit(&source, enabled), expected);
+ }
+
+ #[rstest]
+ #[case::confirmed_redis_miss(CacheSource::S3, "s3")]
+ #[case::redis_read_failed(CacheSource::S3AfterRedisError, "s3_after_redis_error")]
+ fn test_cache_hit_metric_source_label(#[case] source: CacheSource, #[case] expected: &str) {
+ assert_eq!(cache_hit_metric_source_label(&source), expected);
+ }
+
+ #[tokio::test]
+ async fn test_rebuild_request_does_not_overwrite_an_earlier_score() {
+ let mock = common_redis::MockRedisClient::new();
+ let redis: Arc<dyn RedisClient + Send + Sync> = Arc::new(mock.clone());
+
+ write_rebuild_request(redis.clone(), 42, REBUILD_TRIGGER_S3_HIT).await;
+ write_rebuild_request(redis, 42, REBUILD_TRIGGER_S3_HIT).await;
+
+ let calls = mock.get_calls();
+ assert_eq!(calls.len(), 2, "one queue write per request");
+ for call in calls {
+ assert_eq!(
+ call.op, "zadd_nx",
+ "repeated requests must keep the first score"
+ );
+ assert_eq!(call.key, FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET);
+ assert!(
+ matches!(&call.value, common_redis::MockRedisValue::MemberScore(member, _) if member == "42"),
+ "the member is the team id the drain parses, got {:?}",
+ call.value
+ );
+ }
+ }
+
#[test]
fn test_extract_etag_from_header_weak() {
let val = axum::http::HeaderValue::from_static("W/\"a1b2c3d4e5f6g7h8\"");
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index faed79a74065..91a4aa40b8d1 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -488,6 +488,15 @@ pub struct Config {
#[envconfig(from = "FLAG_DEFINITIONS_SELF_HEAL_ENABLED", default = "true")]
pub flag_definitions_self_heal_enabled: FlexBool,
+ // Second gate on the self-heal path, for the S3-hit trigger only. A cache miss is a 503
+ // and is rare; an S3 hit is a successful response and can be orders of magnitude more
+ // frequent, so the two triggers need separate switches. Default off so the enqueue rate
+ // can be watched in one environment before the rest follow. Has no effect while
+ // FLAG_DEFINITIONS_SELF_HEAL_ENABLED is off, which stays the switch that stops every
+ // enqueue.
+ #[envconfig(from = "FLAG_DEFINITIONS_REBUILD_ON_S3_HIT_ENABLED", default = "false")]
+ pub flag_definitions_rebuild_on_s3_hit_enabled: FlexBool,
+
// Cluster switch for the /flags/definitions reader. When enabled, the flags-with-cohorts
// payload and its ETag both come from the dedicated flags Redis instead of the shared one.
//
@@ -1122,6 +1131,7 @@ impl Config {
flags_redis_reader_url: "".to_string(),
flags_redis_enabled: FlexBool(false),
flag_definitions_self_heal_enabled: FlexBool(false),
+ flag_definitions_rebuild_on_s3_hit_enabled: FlexBool(false),
flag_definitions_dedicated_redis_enabled: FlexBool(false),
redis_response_timeout_ms: 100,
redis_connection_timeout_ms: 5000,
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index 14f35944a4c6..33eaa7097cf1 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -390,8 +390,9 @@ pub const FLAG_DEFINITIONS_ETAG_COUNTER: &str = "flags_flag_definitions_etag_tot
pub const FLAG_DEFINITIONS_READS_DEDICATED_REDIS_GAUGE: &str =
"flags_flag_definitions_reads_dedicated_redis";
-// Flag definitions self-heal: a cache miss enqueued a rebuild request for a Celery
-// worker to drain. Labels: result (ok = enqueued, error = redis zadd failed).
+// Flag definitions self-heal: a request enqueued a rebuild request for a Celery worker to
+// drain. Labels: result (ok = enqueued, error = redis zadd failed), trigger (cache_miss =
+// nothing served the request, s3_hit = Redis lost the entry and S3 answered).
pub const FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER: &str =
"flags_flag_definitions_rebuild_requested_total";
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 4331f284bd03..f5176fddc3d0 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -1,5 +1,7 @@
use crate::{
- api::flag_definitions::FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET,
+ api::flag_definitions::{
+ FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET, FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET,
+ },
cohorts::cohort_models::{Cohort, CohortId, CohortType},
config::{Config, DEFAULT_TEST_CONFIG},
flags::{
@@ -219,24 +221,38 @@ pub async fn setup_redis_client(url: Option<String>) -> Arc<dyn RedisClientTrait
/// Read the members of the flag-definitions self-heal rebuild-requests sorted set.
/// Used by tests asserting the endpoint enqueues (or doesn't) on a cache miss.
pub async fn read_flag_definitions_rebuild_requests(redis_url: &str) -> Vec<String> {
+ read_rebuild_requests(redis_url, FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET).await
+}
+
+pub async fn read_s3_rebuild_requests(redis_url: &str) -> Vec<String> {
+ read_rebuild_requests(redis_url, FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET).await
+}
+
+async fn read_rebuild_requests(redis_url: &str, queue: &str) -> Vec<String> {
let redis = setup_redis_client(Some(redis_url.to_string())).await;
redis
- .zrangebyscore(
- FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string(),
- "-inf".to_string(),
- "+inf".to_string(),
- )
+ .zrangebyscore(queue.to_string(), "-inf".to_string(), "+inf".to_string())
.await
.unwrap_or_default()
}
-/// Clear the flag-definitions self-heal rebuild-requests sorted set. Nothing flushes the
-/// test redis between runs, and team ids restart when the test database is recreated, so a
-/// stale member with a reused id would satisfy a poll on its first read.
-pub async fn clear_flag_definitions_rebuild_requests(redis_url: &str) {
+pub async fn remove_flag_definitions_rebuild_request(redis_url: &str, team_id: i32) {
+ remove_rebuild_request(redis_url, team_id, FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET).await;
+}
+
+pub async fn remove_s3_rebuild_request(redis_url: &str, team_id: i32) {
+ remove_rebuild_request(
+ redis_url,
+ team_id,
+ FLAG_DEFINITIONS_S3_REBUILD_REQUESTS_ZSET,
+ )
+ .await;
+}
+
+async fn remove_rebuild_request(redis_url: &str, team_id: i32, queue: &str) {
let redis = setup_redis_client(Some(redis_url.to_string())).await;
redis
- .del(FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string())
+ .zrem(queue.to_string(), team_id.to_string())
.await
.unwrap();
}
@@ -344,6 +360,40 @@ pub fn published_flag_keys(redis: &MockRedisClient) -> Vec<String> {
keys
}
+/// An S3 client that answers every key with one fixed JSON body. Lets integration tests
+/// force the HyperCache read to fall through an empty Redis and hit S3, which is the state
+/// a team lands in when its Redis entry is evicted while S3 still holds the payload.
+pub struct StaticS3Client(pub String);
+
+#[async_trait]
+impl common_hypercache::S3Client for StaticS3Client {
+ async fn get_string(
+ &self,
+ _bucket: &str,
+ _key: &str,
+ ) -> Result<String, common_hypercache::S3Error> {
+ Ok(self.0.clone())
+ }
+
+ async fn put_string(
+ &self,
+ _bucket: &str,
+ _key: &str,
+ _value: &str,
+ ) -> Result<(), common_hypercache::S3Error> {
+ Ok(())
+ }
+
+ async fn delete(&self, _bucket: &str, _key: &str) -> Result<(), common_hypercache::S3Error> {
+ Ok(())
+ }
+}
+
+/// An S3 client that serves `body` for every key, for injecting into the test server.
+pub fn static_s3_client(body: &str) -> Arc<dyn common_hypercache::S3Client + Send + Sync> {
+ Arc::new(StaticS3Client(body.to_string()))
+}
+
/// Create a HyperCacheReader for tests using the provided Redis client.
/// Uses default test configuration for S3 (which won't be used in most tests
/// since Redis should have the data).
diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rs
index af87b30ef213..c3c3a8fcb76f 100644
--- a/rust/feature-flags/tests/test_flag_definitions.rs
+++ b/rust/feature-flags/tests/test_flag_definitions.rs
@@ -3145,12 +3145,18 @@ async fn test_flag_definitions_billing_counter(#[case] skip_writes: bool) {
/// Poll the self-heal rebuild-requests set until it contains `team_id`, or return
/// false after ~2s. The enqueue runs in a background task, so a bounded retry is
/// needed rather than a single read.
-async fn poll_for_rebuild_enqueue(redis_url: &str, team_id: i32) -> bool {
- use feature_flags::utils::test_utils::read_flag_definitions_rebuild_requests;
+async fn poll_for_rebuild_enqueue(redis_url: &str, team_id: i32, s3_hit: bool) -> bool {
+ use feature_flags::utils::test_utils::{
+ read_flag_definitions_rebuild_requests, read_s3_rebuild_requests,
+ };
use tokio::time::{sleep, Duration};
for _ in 0..40 {
- let members = read_flag_definitions_rebuild_requests(redis_url).await;
+ let members = if s3_hit {
+ read_s3_rebuild_requests(redis_url).await
+ } else {
+ read_flag_definitions_rebuild_requests(redis_url).await
+ };
if members.contains(&team_id.to_string()) {
return true;
}
@@ -3163,7 +3169,9 @@ async fn poll_for_rebuild_enqueue(redis_url: &str, team_id: i32) -> bool {
async fn test_cache_miss_enqueues_rebuild_when_self_heal_enabled() {
use feature_flags::{
config::{Config, FlexBool},
- utils::test_utils::{dummy_s3_client, TestContext},
+ utils::test_utils::{
+ dummy_s3_client, remove_flag_definitions_rebuild_request, TestContext,
+ },
};
use reqwest;
@@ -3175,6 +3183,7 @@ async fn test_cache_miss_enqueues_rebuild_when_self_heal_enabled() {
.create_team_with_secret_token(None, None, None)
.await
.unwrap();
+ remove_flag_definitions_rebuild_request(&config.redis_url, team.id).await;
// Don't populate the cache, and inject a NotFound S3 so the read is a genuine
// cache_miss (the flags test job has no object store, so real S3 would error).
let server =
@@ -3191,7 +3200,7 @@ async fn test_cache_miss_enqueues_rebuild_when_self_heal_enabled() {
assert_eq!(response.status(), 503, "expected a cache-miss 503");
assert!(
- poll_for_rebuild_enqueue(&config.redis_url, team.id).await,
+ poll_for_rebuild_enqueue(&config.redis_url, team.id, false).await,
"team {} should be enqueued for rebuild after a cache-miss 503",
team.id
);
@@ -3202,8 +3211,8 @@ async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {
use feature_flags::{
config::{Config, FlexBool},
utils::test_utils::{
- clear_flag_definitions_rebuild_requests, dummy_s3_client,
- read_flag_definitions_rebuild_requests, TestContext,
+ dummy_s3_client, read_flag_definitions_rebuild_requests,
+ remove_flag_definitions_rebuild_request, TestContext,
},
};
use reqwest;
@@ -3220,10 +3229,8 @@ async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {
.create_team_with_secret_token(None, None, None)
.await
.unwrap();
- // Only the dedicated db is cleared: the shared one is polled concurrently by the
- // sibling self-heal tests in this binary, so the shared assertion below compares
- // membership before and after instead of requiring an empty set.
- clear_flag_definitions_rebuild_requests(&config.flags_redis_url).await;
+ remove_flag_definitions_rebuild_request(&config.flags_redis_url, team.id).await;
+ remove_flag_definitions_rebuild_request(&config.redis_url, team.id).await;
let shared_before = read_flag_definitions_rebuild_requests(&config.redis_url).await;
// Leave both caches unseeded and inject a NotFound S3 so the read is a genuine
@@ -3242,7 +3249,7 @@ async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {
assert_eq!(response.status(), 503, "expected a cache-miss 503");
assert!(
- poll_for_rebuild_enqueue(&config.flags_redis_url, team.id).await,
+ poll_for_rebuild_enqueue(&config.flags_redis_url, team.id, false).await,
"team {} should be enqueued on the dedicated redis, where the drain reads",
team.id
);
@@ -3259,11 +3266,95 @@ async fn test_cache_miss_enqueues_rebuild_on_dedicated_redis() {
);
}
+#[tokio::test]
+async fn test_s3_hit_enqueues_rebuild_and_keeps_first_score() {
+ use feature_flags::{
+ config::{Config, FlexBool},
+ utils::test_utils::{
+ remove_s3_rebuild_request, setup_redis_client, static_s3_client, TestContext,
+ },
+ };
+ use reqwest;
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ let mut config = Config::default_test_config();
+ config.flag_definitions_self_heal_enabled = FlexBool(true);
+ config.flag_definitions_rebuild_on_s3_hit_enabled = FlexBool(true);
+ let context = TestContext::new(Some(&config)).await;
+
+ let (team, secret_token, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ remove_s3_rebuild_request(&config.redis_url, team.id).await;
+
+ let server = common::ServerHandle::for_config_with_s3(
+ config.clone(),
+ Some(static_s3_client(r#"{"flags": [], "cohorts": {}}"#)),
+ )
+ .await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(
+ response.status(),
+ 200,
+ "expected the S3 payload to be served"
+ );
+ assert!(
+ response.headers().get("etag").is_none(),
+ "an S3-served response has no ETag to send, which is what the rebuild repairs"
+ );
+
+ assert!(
+ poll_for_rebuild_enqueue(&config.redis_url, team.id, true).await,
+ "team {} should be enqueued for rebuild after an S3-served response",
+ team.id
+ );
+
+ let redis = setup_redis_client(Some(config.redis_url.clone())).await;
+ let first_score_upper_bound = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as i64;
+ let queue = "flag_definitions:rebuild_s3_requests".to_string();
+ redis
+ .zadd_nx(
+ queue.clone(),
+ team.id.to_string(),
+ first_score_upper_bound + 60_000,
+ )
+ .await
+ .unwrap();
+ let original_score_members = redis
+ .zrangebyscore(
+ queue,
+ "-inf".to_string(),
+ first_score_upper_bound.to_string(),
+ )
+ .await
+ .unwrap();
+ assert!(
+ original_score_members.contains(&team.id.to_string()),
+ "a repeated NX write must keep the first enqueue score"
+ );
+}
+
#[tokio::test]
async fn test_cache_miss_does_not_enqueue_rebuild_when_self_heal_disabled() {
use feature_flags::{
config::Config,
- utils::test_utils::{dummy_s3_client, read_flag_definitions_rebuild_requests, TestContext},
+ utils::test_utils::{
+ dummy_s3_client, read_flag_definitions_rebuild_requests,
+ remove_flag_definitions_rebuild_request, TestContext,
+ },
};
use reqwest;
use tokio::time::{sleep, Duration};
@@ -3276,6 +3367,7 @@ async fn test_cache_miss_does_not_enqueue_rebuild_when_self_heal_disabled() {
.create_team_with_secret_token(None, None, None)
.await
.unwrap();
+ remove_flag_definitions_rebuild_request(&config.redis_url, team.id).await;
// Inject a NotFound S3 so this is a genuine cache_miss: the only reason no enqueue
// happens is the flag being off, not the miss classifying as s3_error.