:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): keep shadow mismatch state in redis (#90135)
James Gill5682f6200cf2
diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rsindex 95f104382540..7ca317cf1219 100644--- a/rust/feature-flags/src/bin/flags_cache_builder.rs+++ b/rust/feature-flags/src/bin/flags_cache_builder.rs@@ -102,6 +102,12 @@ const SHADOW_BUILDS: &str = "flags_cache_shadow_builds_total";const SHADOW_MISMATCH: &str = "flags_cache_shadow_mismatch_total";const SHADOW_MISMATCH_FIRST_SIGHT: &str = "flags_cache_shadow_mismatch_first_sight_total";const SHADOW_FAILURES: &str = "flags_cache_shadow_build_failures_total";+// Failures of the mismatch tracker's Redis state, with an `op` label for which+// access failed (read / write / clear). Every one of them costs confirmations and+// none of them fail a build, so like the rest of the shadow telemetry this must+// not feed the real-build failure alert. A sustained rate here means+// SHADOW_MISMATCH is undercounting.+const SHADOW_TRACKER_STORE_ERRORS: &str = "flags_cache_shadow_tracker_store_errors_total";// Per-team wall time for one shadow compare (build + live read + diff). Shadow// teams run sequentially after the batch's real builds, so this is the quantity// that sets how long a batch of shadow work delays the next real invalidation —@@ -178,9 +184,11 @@ struct BuilderConfig {#[envconfig(from = "KAFKA_DLQ_TOPIC", default = "flags_cache_invalidation_dlq")]dlq_topic: String,- /// How long a team's last shadow mismatch stays eligible to confirm a repeat.- /// Long enough that quiet teams (two shadow builds days apart would miss a- /// 1h window) still confirm persistent drift; short enough to bound memory.+ /// How long a team's last shadow mismatch stays eligible to confirm a repeat,+ /// written as the TTL on the tracker's Redis key. Long enough that quiet+ /// teams (two shadow builds days apart would miss a 1h window) still confirm+ /// persistent drift; short enough that a disagreement Python has since+ /// repaired stops counting as the team's previous observation.#[envconfig(from = "FLAGS_CACHE_SHADOW_MISMATCH_TTL", default = "86400")]shadow_mismatch_ttl_seconds: u64,}@@ -271,7 +279,7 @@ async fn main() -> anyhow::Result<()> {.expect("Failed to create database pool");let pg_reader: PostgresReader = Arc::new(pg_pool);- let (writer, live_reader) = build_cache_clients(&infra).await;+ let (writer, live_reader, redis_client) = build_cache_clients(&infra).await;let writer = Arc::new(writer);let live_reader = Arc::new(live_reader);@@ -294,6 +302,7 @@ async fn main() -> anyhow::Result<()> {pg_reader,writer,live_reader,+ redis_client,dlq_producer,builder_cfg,loop_handle.clone(),@@ -307,10 +316,18 @@ async fn main() -> anyhow::Result<()> {}/// Build the cache writer (real builds) and a reader over the same Redis + config-/// (shadow builds). The reader is used Redis-only via `get_typed_from_redis`, so-/// its S3 client is never exercised; sharing the writer's keeps one construction-/// path and one set of connections.-async fn build_cache_clients(infra: &InfraConfig) -> (HyperCacheWriter, HyperCacheReader) {+/// (shadow builds), and hand back the Redis client they share. The reader is used+/// Redis-only via `get_typed_from_redis`, so its S3 client is never exercised;+/// sharing the writer's keeps one construction path and one set of connections.+/// The returned client is the shadow mismatch tracker's store, for the same+/// reason: one connection pool against `FLAGS_REDIS_URL`, not three.+async fn build_cache_clients(+ infra: &InfraConfig,+) -> (+ HyperCacheWriter,+ HyperCacheReader,+ Arc<dyn common_redis::Client + Send + Sync>,+) {tracing::info!("Connecting to Redis");let Some(redis_client) = create_redis_client(&infra.flags_redis_url,@@ -336,8 +353,8 @@ async fn build_cache_clients(infra: &InfraConfig) -> (HyperCacheWriter, HyperCac);let writer = HyperCacheWriter::new(redis_client.clone(), s3_client.clone(), config.clone());- let reader = HyperCacheReader::new_with_s3_client(redis_client, s3_client, config);- (writer, reader)+ let reader = HyperCacheReader::new_with_s3_client(redis_client.clone(), s3_client, config);+ (writer, reader, redis_client)}/// The consumer hot loop. Returns when `shutdown` is cancelled (graceful drain).@@ -347,14 +364,17 @@ async fn consume_loop(pg_reader: PostgresReader,writer: Arc<HyperCacheWriter>,live_reader: Arc<HyperCacheReader>,+ redis_client: Arc<dyn common_redis::Client + Send + Sync>,dlq_producer: FutureProducer<KafkaContext>,cfg: BuilderConfig,health: Handle,shutdown: CancellationToken,) {let coalesce = Duration::from_millis(cfg.coalesce_window_ms);- let mut mismatch_tracker =- MismatchTracker::new(Duration::from_secs(cfg.shadow_mismatch_ttl_seconds));+ let mismatch_tracker = MismatchTracker::new(+ redis_client,+ Duration::from_secs(cfg.shadow_mismatch_ttl_seconds),+ );loop {// Reporting healthy each iteration covers the idle case: with no traffic@@ -435,7 +455,7 @@ async fn consume_loop(let offsets = process_shadow_team(&pg_reader,&live_reader,- &mut mismatch_tracker,+ &mismatch_tracker,team_id,team_batch,)@@ -620,7 +640,7 @@ impl ShadowOutcome {async fn process_shadow_team(pg_reader: &PostgresReader,live_reader: &HyperCacheReader,- tracker: &mut MismatchTracker,+ tracker: &MismatchTracker,team_id: TeamId,team_batch: TeamBatch,) -> Vec<Offset> {@@ -671,7 +691,7 @@ async fn process_shadow_team(async fn shadow_compare(pg_reader: &PostgresReader,live_reader: &HyperCacheReader,- tracker: &mut MismatchTracker,+ tracker: &MismatchTracker,team_id: TeamId,) -> ShadowOutcome {let built = match build_flags_cache(pg_reader.clone(), team_id).await {@@ -691,7 +711,12 @@ async fn shadow_compare(};let diffs = diff_live_entry(&built, &live);- let observation = tracker.observe(team_id, diffs, Instant::now());+ let observation = tracker.observe(team_id, diffs).await;+ // Counted here and not next to the outcome metrics, because a clean build can+ // fail to clear its pending state, and that build reports as a match.+ for op in &observation.store_errors {+ metrics::counter!(SHADOW_TRACKER_STORE_ERRORS, "op" => op.as_label()).increment(1);+ }if observation.is_match() {ShadowOutcome::Match} else {@@ -1204,17 +1229,25 @@ mod tests {/// Build a real `ShadowObservation` through the public diff + tracker API:/// one observation is a first sighting (suppressed), two consecutive ones- /// confirm.- fn shadow_observation(+ /// confirm. The tracker's pending state lives in Redis, so the second+ /// observation has to read what the first wrote. `MockRedisClient` records+ /// writes but serves no reads, so the recorded write is replayed into the+ /// client the second observation reads from.+ ///+ /// `next_build` in `flags::cache_shadow`'s tests does the same replay for the+ /// tracker's own tests. A change to what the mock records has to reach both.+ async fn shadow_observation(confirmed: bool,) -> feature_flags::flags::cache_shadow::ShadowObservation {+ use common_redis::{MockRedisClient, MockRedisValue};use feature_flags::flags::cache_shadow::{diff_live_entry, MismatchTracker, ShadowLiveEntry,};use feature_flags::flags::flag_models::{EvaluationMetadata, FeatureFlag, HypercacheFlagsWrapper,};- use std::time::{Duration as StdDuration, Instant};+ use std::sync::Arc;+ use std::time::Duration as StdDuration;let flag = |has_experiment: bool| -> FeatureFlag {serde_json::from_value(serde_json::json!({@@ -1239,21 +1272,30 @@ mod tests {cohorts: Some(Vec::new()),};- let mut tracker = MismatchTracker::new(StdDuration::from_secs(3600));- let now = Instant::now();- let first = tracker.observe(1, diff_live_entry(&built, &live), now);+ let ttl = StdDuration::from_secs(3600);+ let redis = MockRedisClient::new();+ let first = MismatchTracker::new(Arc::new(redis.clone()), ttl)+ .observe(1, diff_live_entry(&built, &live))+ .await;if !confirmed {return first;}- tracker.observe(- 1,- diff_live_entry(&built, &live),- now + StdDuration::from_secs(1),- )++ let mut next = MockRedisClient::new();+ for call in redis.get_calls() {+ if let ("setex", MockRedisValue::StringWithTTL(value, _)) =+ (call.op.as_str(), call.value)+ {+ next.get_ret(&call.key, Ok(value));+ }+ }+ MismatchTracker::new(Arc::new(next), ttl)+ .observe(1, diff_live_entry(&built, &live))+ .await}- #[test]- fn shadow_outcome_maps_to_exactly_the_documented_labels() {+ #[tokio::test]+ async fn shadow_outcome_maps_to_exactly_the_documented_labels() {// The outcome label is the shadow window's primary telemetry; a wrong// label here misreads the ramp with no other test catching it.let cases = [@@ -1264,11 +1306,11 @@ mod tests {"error",),(- ShadowOutcome::Mismatch(shadow_observation(false)),+ ShadowOutcome::Mismatch(shadow_observation(false).await),"mismatch_suppressed",),(- ShadowOutcome::Mismatch(shadow_observation(true)),+ ShadowOutcome::Mismatch(shadow_observation(true).await),"mismatch_confirmed",),];diff --git a/rust/feature-flags/src/flags/cache_shadow.rs b/rust/feature-flags/src/flags/cache_shadow.rsindex 5508c1c91a98..d34e49f2c8e9 100644--- a/rust/feature-flags/src/flags/cache_shadow.rs+++ b/rust/feature-flags/src/flags/cache_shadow.rs@@ -3,8 +3,10 @@//! A `shadow: true` invalidation asks the builder to prove parity, not to serve://! build the payload exactly as a real invalidation would, diff it against the//! live cache entry Python (Celery) owns, and record the result — never write.-//! This module holds the pure parts: the semantic diff and the repeat-offender-//! suppression. Reading the live entry and emitting metrics stay in the binary.+//! This module holds the semantic diff and the repeat-offender suppression. The+//! diff is pure; the suppression keeps its pending state in the flags Redis+//! tier, because it has to outlive the process. Reading the live entry and+//! emitting metrics stay in the binary.//!//! The diff covers all three top-level payload keys, because all three feed the//! serve path (`flag_definitions_cache.rs` evaluates from `flags`,@@ -35,13 +37,14 @@//! keys: the typed model omits `None` fields on serialize, so a built-side//! `None` against a cached value would otherwise be invisible.-use std::collections::hash_map::DefaultHasher;use std::collections::{HashMap, HashSet};-use std::hash::{Hash, Hasher};-use std::time::{Duration, Instant};+use std::sync::Arc;+use std::time::Duration;+use common_redis::{Client, CustomRedisError};use common_types::TeamId;use serde::Deserialize;+use sha2::{Digest, Sha256};use crate::cohorts::cohort_models::Cohort;use crate::flags::cache_builder::is_evaluable;@@ -117,18 +120,46 @@ pub struct ShadowDiff {fingerprint: u64,}+/// Truncated SHA-256 rather than `DefaultHasher`, because the value is written+/// to Redis and compared by a later process, which can be a different build of+/// this binary. The standard library does not promise `DefaultHasher` gives the+/// same output across Rust versions, so a toolchain bump would change every+/// fingerprint and demote each team's pending mismatch to a first sighting for+/// one build after the deploy. SHA-256 of the same input is the same value in+/// every build, which is what a persisted comparison needs.+///+/// 64 bits of the digest is enough, because a collision would have to be two+/// different disagreements for the same team inside the TTL.fn fingerprint(issue_type: ShadowIssueType,subject: Option<&str>,built: Option<&serde_json::Value>,cached: Option<&serde_json::Value>,) -> u64 {- let mut hasher = DefaultHasher::new();- issue_type.as_label().hash(&mut hasher);- subject.hash(&mut hasher);- built.map(|v| v.to_string()).hash(&mut hasher);- cached.map(|v| v.to_string()).hash(&mut hasher);- hasher.finish()+ let mut hasher = Sha256::new();+ hasher.update(issue_type.as_label().as_bytes());+ for part in [+ subject.map(|s| s.to_string()),+ built.map(|v| v.to_string()),+ cached.map(|v| v.to_string()),+ ] {+ // The marker byte separates the parts and tells an absent part from an+ // empty one. It is not an escape: `subject` is a formatted string that+ // carries whatever bytes a flag key carries, so a part can contain a+ // marker byte and the encoding is not self-delimiting. The part count is+ // fixed at three, which is what keeps distinct disagreements apart in+ // practice. A collision would need a contrived flag key, and would cost+ // one wrongly paired confirmation for one team.+ match part {+ Some(part) => {+ hasher.update([0x01]);+ hasher.update(part.as_bytes());+ }+ None => hasher.update([0x00]),+ }+ }+ let digest = hasher.finalize();+ u64::from_be_bytes(digest[..8].try_into().expect("SHA-256 digest is 32 bytes"))}fn diff(@@ -369,6 +400,9 @@ fn diff_cohorts(built: &[Cohort], live: &[Cohort]) -> Vec<ShadowDiff> {pub struct ShadowObservation {pub confirmed: Vec<ShadowDiff>,pub first_sight: Vec<ShadowDiff>,+ /// Tracker store accesses that failed while this observation was made. The+ /// caller counts them. They never move a diff into `confirmed`.+ pub store_errors: Vec<TrackerStoreOp>,}impl ShadowObservation {@@ -377,82 +411,205 @@ impl ShadowObservation {}}-struct PendingMismatch {- fingerprints: HashSet<u64>,- recorded_at: Instant,+/// Which tracker store access failed. Used as a metric label, so the set must+/// stay small and static.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TrackerStoreOp {+ /// Read of the team's previous observation. The build falls back to first+ /// sight, so confirmations are lost while reads fail.+ Read,+ /// Write of this observation. The previous observation is cleared in its place,+ /// so the team's next shadow build finds nothing to compare against and also+ /// reports first sight.+ Write,+ /// Clear of the team's pending state, either after a clean build or in place of+ /// a write that failed.+ Clear,}-/// Above this many pending teams, expired entries are swept on the next observe.-/// Sized far beyond realistic mismatch volume — it only bounds memory if-/// something goes systemically wrong.-const PENDING_PRUNE_THRESHOLD: usize = 10_000;+impl TrackerStoreOp {+ pub fn as_label(&self) -> &'static str {+ match self {+ Self::Read => "read",+ Self::Write => "write",+ Self::Clear => "clear",+ }+ }+}++/// Redis key for a team's pending mismatch. The `posthog:1:` prefix is how+/// django-redis addresses keys in this tier (see `warm_run_status`). The+/// `feature_flags/shadow_mismatch/` path keeps these keys clear of the cache+/// entries the serve path reads, which are+/// `posthog:1:cache/teams/{team}/feature_flags/flags.json` (see+/// `HYPERCACHE_NAMESPACE` and `HYPERCACHE_OBJECT_NAME` in `cache_writer`): those+/// hold `cache/` in the segment where these hold `feature_flags/`, and Python's+/// hypercache scans match on the `cache/` form.+fn pending_key(team_id: TeamId) -> String {+ format!("posthog:1:feature_flags/shadow_mismatch/{team_id}")+}++/// Cap on one tracker Redis call. `common_hypercache` puts the same bound around+/// its own Redis access, and the tracker needs it for the same reason: a shadow+/// team that waits on Redis delays the real invalidations in the batches behind+/// it. The client's own response timeout cannot carry this, because it is+/// configurable and `FLAGS_REDIS_RESPONSE_TIMEOUT_MS=0` disables it entirely.+const STORE_TIMEOUT: Duration = Duration::from_millis(500);++/// Cap on the fingerprints stored for one team. The state shadow mode exists to+/// find is a systematic builder bug, which makes every flag on every team+/// disagree at once, and the whole set would then be written, held for the TTL,+/// and read back on the team's next build, against the Redis tier the serve path+/// reads from. Past the cap a team confirms only the disagreements that fit, which+/// is the right trade: a team with hundreds of confirmed diffs has already told+/// you what you needed to know. The confirmed log line is capped for the same+/// reason.+///+/// The cap takes the first entries of `diff_live_entry`'s stable order, so a given+/// disagreement either fits on every build or on none, which makes its+/// confirmation deterministic. An unstable subset would leave the aggregate+/// confirmed count about the same, because the next build compares every diff it+/// finds against whatever was stored, but a specific flag would then confirm on+/// some builds and not others.+const MAX_STORED_FINGERPRINTS: usize = 256;++/// Bound one tracker call and report an elapsed timer as the client's own timeout+/// error, so callers have a single error type to handle.+async fn with_timeout<T>(+ call: impl std::future::Future<Output = Result<T, CustomRedisError>>,+) -> Result<T, CustomRedisError> {+ match tokio::time::timeout(STORE_TIMEOUT, call).await {+ Ok(result) => result,+ Err(_elapsed) => Err(CustomRedisError::Timeout),+ }+}-/// In-memory repeat-offender suppression: a mismatch counts only when the same-/// fingerprint shows up on two consecutive shadow builds of the team within-/// `ttl`. A shadow build races Python's own rebuild of the same team, so a-/// single-shot mismatch is expected noise; Python repairs the entry and the next-/// shadow build of the team comes back clean, clearing the pending state.+/// Repeat-offender suppression: a mismatch counts only when the same fingerprint+/// shows up on two consecutive shadow builds of the team within `ttl`. A shadow+/// build races Python's own rebuild of the same team, so a single-shot mismatch+/// is expected noise; Python repairs the entry and the next shadow build of the+/// team comes back clean, clearing the pending state.+///+/// The pending state lives in the flags Redis tier rather than in the process,+/// because builder pods roll and Kafka partitions move between them far more+/// often than the TTL elapses. Process-local state made the real confirmation+/// window "as long as this pod lives", so a team that rebuilds less often than+/// that could never confirm, however wrong its cache entry was.+///+/// Expiry is the TTL on the Redis key. Nothing in this process sweeps or bounds+/// the pending set.pub struct MismatchTracker {+ /// The same client the hypercache writer and reader use.+ redis: Arc<dyn Client + Send + Sync>,ttl: Duration,- pending: HashMap<TeamId, PendingMismatch>,}impl MismatchTracker {- pub fn new(ttl: Duration) -> Self {- Self {- ttl,- pending: HashMap::new(),- }+ pub fn new(redis: Arc<dyn Client + Send + Sync>, ttl: Duration) -> Self {+ Self { redis, ttl }}- /// Fold one shadow build's diffs into the tracker and split them into- /// confirmed (fingerprint also seen on the previous, unexpired observation)- /// and first-sight. An empty `diffs` clears the team's pending state.- pub fn observe(- &mut self,- team_id: TeamId,- diffs: Vec<ShadowDiff>,- now: Instant,- ) -> ShadowObservation {- if self.pending.len() >= PENDING_PRUNE_THRESHOLD {- let ttl = self.ttl;- self.pending- .retain(|_, p| now.duration_since(p.recorded_at) < ttl);- }+ /// Fold one shadow build's diffs into the store and split them into+ /// confirmed (fingerprint also present in the team's previous, unexpired+ /// observation) and first-sight. An empty `diffs` clears the team's pending+ /// state.+ ///+ /// Store failures resolve towards first sight and none of them fail the shadow+ /// build: a mismatch we cannot prove is a repeat is reported as a first+ /// sighting, so an unreachable store loses confirmations rather than inventing+ /// them. The failures come back in `store_errors` to be counted.+ ///+ /// That fallback needs the team's stale pending state gone, and removing it is+ /// itself a store access that can fail. When a clean build's clear fails, or+ /// when a write and the clear that compensates for it both fail, the previous+ /// fingerprints stand until the TTL. A disagreement that then returns byte for+ /// byte can confirm one build early. The counter shows it: `op="clear"` alone,+ /// or `op="write"` together with `op="clear"`.+ pub async fn observe(&self, team_id: TeamId, diffs: Vec<ShadowDiff>) -> ShadowObservation {+ let key = pending_key(team_id);if diffs.is_empty() {- self.pending.remove(&team_id);- return ShadowObservation::default();+ return ShadowObservation {+ store_errors: self.clear_pending(team_id, key).await,+ ..ShadowObservation::default()+ };}- let prior: Option<HashSet<u64>> = self- .pending- .get(&team_id)- .filter(|p| now.duration_since(p.recorded_at) < self.ttl)- .map(|p| p.fingerprints.clone());-- self.pending.insert(- team_id,- PendingMismatch {- fingerprints: diffs.iter().map(|d| d.fingerprint).collect(),- recorded_at: now,- },- );+ let mut store_errors = Vec::new();+ let prior = match self.read_pending(key.clone()).await {+ Ok(prior) => prior,+ Err(e) => {+ tracing::warn!(team_id, error = %e, "Shadow mismatch tracker read failed; counting this build as a first sighting");+ store_errors.push(TrackerStoreOp::Read);+ HashSet::new()+ }+ };- match prior {- Some(previous) => {- let (confirmed, first_sight) = diffs- .into_iter()- .partition(|d| previous.contains(&d.fingerprint));- ShadowObservation {- confirmed,- first_sight,- }+ if let Err(e) = self.write_pending(key.clone(), &diffs).await {+ tracing::warn!(team_id, error = %e, "Shadow mismatch tracker write failed; clearing the team's pending state instead");+ store_errors.push(TrackerStoreOp::Write);+ // A failed SETEX leaves the previous build's fingerprints in place with+ // their own TTL, so the team's next build would compare against an+ // observation from two builds ago and could confirm a disagreement that+ // the build in between did not see. Clearing keeps the fallback at first+ // sight. Redis serves DEL when it refuses a write for `maxmemory`, which+ // is the case that produces this.+ store_errors.extend(self.clear_pending(team_id, key).await);+ }++ let (confirmed, first_sight) = diffs+ .into_iter()+ .partition(|d| prior.contains(&d.fingerprint));+ ShadowObservation {+ confirmed,+ first_sight,+ store_errors,+ }+ }++ /// Fingerprints from the team's previous shadow build. An absent key is how+ /// the TTL expires the window, so it reads as "no previous build" and not as+ /// an error. A value that does not parse is an error, because a stored shape+ /// this build cannot read is worth seeing on the failure counter.+ async fn read_pending(&self, key: String) -> Result<HashSet<u64>, CustomRedisError> {+ match with_timeout(self.redis.get(key)).await {+ Ok(raw) => {+ serde_json::from_str(&raw).map_err(|e| CustomRedisError::ParseError(e.to_string()))+ }+ Err(CustomRedisError::NotFound) => Ok(HashSet::new()),+ Err(e) => Err(e),+ }+ }++ async fn write_pending(+ &self,+ key: String,+ diffs: &[ShadowDiff],+ ) -> Result<(), CustomRedisError> {+ let fingerprints: Vec<u64> = diffs+ .iter()+ .take(MAX_STORED_FINGERPRINTS)+ .map(|d| d.fingerprint)+ .collect();+ let payload = serde_json::to_string(&fingerprints)+ .map_err(|e| CustomRedisError::ParseError(e.to_string()))?;+ with_timeout(self.redis.setex(key, payload, self.ttl.as_secs())).await+ }++ /// Drop the team's pending state, so the next mismatch starts over as a first+ /// sighting. Called after a clean build, and in place of a write that failed.+ ///+ /// A failed clear is the residual described on `observe`. It needs the same+ /// disagreement to come back byte for byte inside the TTL, and the fingerprint+ /// hashes the content, so that is a real recurrence rather than the rebuild+ /// race the suppression exists to filter.+ async fn clear_pending(&self, team_id: TeamId, key: String) -> Vec<TrackerStoreOp> {+ match with_timeout(self.redis.del(key)).await {+ Ok(()) => Vec::new(),+ Err(e) => {+ tracing::warn!(team_id, error = %e, "Shadow mismatch tracker clear failed; the team's pending state stands until it expires");+ vec![TrackerStoreOp::Clear]}- None => ShadowObservation {- confirmed: Vec::new(),- first_sight: diffs,- },}}}@@ -492,8 +649,9 @@ pub fn summarize_diffs(diffs: &[ShadowDiff], max_entries: usize, max_bytes: usiz#[cfg(test)]mod tests {- use std::time::{Duration, Instant};+ use std::time::Duration;+ use common_redis::{MockRedisCall, MockRedisClient, MockRedisValue};use serde_json::json;use super::*;@@ -835,6 +993,32 @@ mod tests {assert!(diff_live_entry(&built, &cached).is_empty());}+ /// Pinned so a change to the hashed parts, the marker bytes, or the digest has+ /// to be made on purpose. The value is written to Redis and compared by a later+ /// process, so its encoding is a cross-process contract like the key string. A+ /// silent change stops every team's pending state from matching for one TTL+ /// window after the deploy, and confirmations drop to zero with nothing saying+ /// why. Called with literal parts rather than through `diff_live_entry`, so a+ /// new field on `FeatureFlag` does not fail it.+ #[test]+ fn fingerprint_encoding_is_pinned() {+ assert_eq!(+ fingerprint(+ ShadowIssueType::FieldMismatch,+ Some("flag 1 (flag-1)"),+ Some(&json!({"has_experiment": false})),+ Some(&json!({"has_experiment": true})),+ ),+ 0x3e37_1bcf_8d31_4c14+ );++ // The all-absent shape, which exercises the other marker byte.+ assert_eq!(+ fingerprint(ShadowIssueType::MissingEvaluationMetadata, None, None, None),+ 0xdcb8_1973_c8ce_a9d4+ );+ }+fn mismatch_diffs() -> Vec<ShadowDiff> {let built = wrapper(vec![flag_from_json(base_flag_json(1))]);let mut cached_json = base_flag_json(1);@@ -843,76 +1027,280 @@ mod tests {diff_live_entry(&built, &cached)}- #[test]- fn tracker_suppresses_first_sight_and_confirms_repeat() {- let mut tracker = MismatchTracker::new(Duration::from_secs(3600));- let now = Instant::now();+ const TRACKER_TTL: Duration = Duration::from_secs(3600);+ const PENDING_KEY_TEAM_7: &str = "posthog:1:feature_flags/shadow_mismatch/7";++ /// One disagreement per flag, for a flag count the caller picks. Used to cross+ /// the store cap.+ fn many_mismatch_diffs(count: i32) -> Vec<ShadowDiff> {+ let built = (1..=count).map(|id| flag_from_json(base_flag_json(id)));+ let cached = (1..=count).map(|id| {+ let mut cached_json = base_flag_json(id);+ cached_json["has_experiment"] = json!(true);+ flag_from_json(cached_json)+ });+ diff_live_entry(&wrapper(built.collect()), &live(cached.collect()))+ }++ /// A disagreement on the same flag with different content, so the fingerprint+ /// differs from `mismatch_diffs`.+ fn other_mismatch_diffs() -> Vec<ShadowDiff> {+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);+ let mut cached_json = base_flag_json(1);+ cached_json["filters"]["groups"][0]["rollout_percentage"] = json!(25.0);+ diff_live_entry(&built, &live(vec![flag_from_json(cached_json)]))+ }++ fn tracker(redis: &MockRedisClient) -> MismatchTracker {+ MismatchTracker::new(Arc::new(redis.clone()), TRACKER_TTL)+ }++ /// The store as the team's next shadow build finds it, in a new process.+ /// `MockRedisClient` records writes but serves no reads, so replaying its+ /// recorded writes into a fresh client is what models state that outlived the+ /// process which wrote it. The tracker holds nothing in memory, so a later+ /// build in the same pod and one in a new pod run the same code path.+ ///+ /// It replays *attempted* writes. The mock records a call whether or not it+ /// returned an error, so a test that injects a write failure must build the+ /// next store itself rather than call this.+ ///+ /// `shadow_observation` in `bin/flags_cache_builder.rs` models the same thing+ /// inline for the outcome-label test. A change to what the mock records has to+ /// reach both.+ fn next_build(prior: &MockRedisClient) -> MockRedisClient {+ let mut next = MockRedisClient::new();+ for call in prior.get_calls() {+ match (call.op.as_str(), call.value) {+ ("setex", MockRedisValue::StringWithTTL(value, _)) => {+ next.get_ret(&call.key, Ok(value));+ }+ ("del", _) => {+ next.get_ret(&call.key, Err(CustomRedisError::NotFound));+ }+ _ => {}+ }+ }+ next+ }- let first = tracker.observe(7, mismatch_diffs(), now);+ fn calls_with_op(redis: &MockRedisClient, op: &str) -> Vec<MockRedisCall> {+ redis+ .get_calls()+ .into_iter()+ .filter(|call| call.op == op)+ .collect()+ }++ #[tokio::test]+ async fn tracker_suppresses_first_sight_and_confirms_repeat_across_a_restart() {+ let first_pod = MockRedisClient::new();+ let first = tracker(&first_pod).observe(7, mismatch_diffs()).await;assert!(first.confirmed.is_empty());assert_eq!(first.first_sight.len(), 1);+ assert!(first.store_errors.is_empty());- let second = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(60));+ let second_pod = next_build(&first_pod);+ let second = tracker(&second_pod).observe(7, mismatch_diffs()).await;assert_eq!(second.confirmed.len(), 1);assert!(second.first_sight.is_empty());}- #[test]- fn tracker_clears_pending_state_on_match() {- let mut tracker = MismatchTracker::new(Duration::from_secs(3600));- let now = Instant::now();+ #[tokio::test]+ async fn tracker_clears_pending_state_on_match() {+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;- tracker.observe(7, mismatch_diffs(), now);- let clean = tracker.observe(7, Vec::new(), now + Duration::from_secs(30));+ let mut second_pod = next_build(&first_pod);+ second_pod.del_ret(PENDING_KEY_TEAM_7, Ok(()));++ let clean = tracker(&second_pod).observe(7, Vec::new()).await;assert!(clean.is_match());+ assert!(clean.store_errors.is_empty());++ // Asserted against the store, not against the next build: an unseeded mock+ // reads as an absent key, so a later first sighting proves nothing about+ // whether the clean build cleared anything.+ assert_eq!(+ calls_with_op(&second_pod, "del")+ .iter()+ .map(|call| call.key.as_str())+ .collect::<Vec<_>>(),+ vec![PENDING_KEY_TEAM_7]+ );// The earlier sighting no longer counts — mismatch starts over.- let after = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(60));+ let third_pod = next_build(&second_pod);+ let after = tracker(&third_pod).observe(7, mismatch_diffs()).await;assert!(after.confirmed.is_empty());assert_eq!(after.first_sight.len(), 1);}- #[test]- fn tracker_expires_pending_state_after_ttl() {- let mut tracker = MismatchTracker::new(Duration::from_secs(100));- let now = Instant::now();+ #[tokio::test]+ async fn tracker_expires_pending_state_after_ttl() {+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;++ // The TTL on this write is the only thing that bounds the confirmation+ // window, and the key is pinned because a tracker write must never land+ // on a cache entry the serve path reads.+ let writes = calls_with_op(&first_pod, "setex");+ assert_eq!(writes.len(), 1);+ assert_eq!(writes[0].key, PENDING_KEY_TEAM_7);+ match writes[0].value.clone() {+ MockRedisValue::StringWithTTL(_, ttl) => assert_eq!(ttl, TRACKER_TTL.as_secs()),+ other => panic!("expected a value with a TTL, got {other:?}"),+ }++ // The mock has no clock, so expiry is modelled as the key being gone by the+ // time the next build reads it. Stated rather than left to the mock's+ // default, so the test still means this if that default changes.+ let mut expired = next_build(&first_pod);+ expired.get_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::NotFound));- tracker.observe(7, mismatch_diffs(), now);- let late = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(101));+ let late = tracker(&expired).observe(7, mismatch_diffs()).await;assert!(late.confirmed.is_empty());assert_eq!(late.first_sight.len(), 1);+ assert!(late.store_errors.is_empty());}- #[test]- fn tracker_treats_different_content_as_first_sight() {+ #[tokio::test]+ async fn tracker_treats_different_content_as_first_sight() {// An edit session produces a different disagreement each save — the// fingerprint hashes the content, so those never confirm.- let mut tracker = MismatchTracker::new(Duration::from_secs(3600));- let now = Instant::now();-- tracker.observe(7, mismatch_diffs(), now);+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;- let built = wrapper(vec![flag_from_json(base_flag_json(1))]);- let mut cached_json = base_flag_json(1);- cached_json["filters"]["groups"][0]["rollout_percentage"] = json!(25.0);- let other = diff_live_entry(&built, &live(vec![flag_from_json(cached_json)]));-- let second = tracker.observe(7, other, now + Duration::from_secs(60));+ let second_pod = next_build(&first_pod);+ let second = tracker(&second_pod)+ .observe(7, other_mismatch_diffs())+ .await;assert!(second.confirmed.is_empty());assert_eq!(second.first_sight.len(), 1);}- #[test]- fn tracker_is_per_team() {- let mut tracker = MismatchTracker::new(Duration::from_secs(3600));- let now = Instant::now();+ #[tokio::test]+ async fn tracker_is_per_team() {+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;- tracker.observe(7, mismatch_diffs(), now);- let other_team = tracker.observe(8, mismatch_diffs(), now + Duration::from_secs(60));+ let second_pod = next_build(&first_pod);+ let other_team = tracker(&second_pod).observe(8, mismatch_diffs()).await;assert!(other_team.confirmed.is_empty());assert_eq!(other_team.first_sight.len(), 1);}+ #[tokio::test]+ async fn tracker_read_failure_falls_back_to_first_sight() {+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;++ let mut second_pod = next_build(&first_pod);+ second_pod.get_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));++ let second = tracker(&second_pod).observe(7, mismatch_diffs()).await;+ assert!(second.confirmed.is_empty());+ assert_eq!(second.first_sight.len(), 1);+ assert_eq!(second.store_errors, vec![TrackerStoreOp::Read]);+ }++ #[tokio::test]+ async fn tracker_write_failure_clears_the_stale_observation() {+ // A failed write leaves the previous build's fingerprints in place with+ // their own TTL. Without the compensating clear, the team's next build+ // compares against an observation from two builds ago and can confirm a+ // disagreement the build in between did not see.+ let mut second_pod = next_build(&{+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;+ first_pod+ });+ second_pod.set_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));+ second_pod.del_ret(PENDING_KEY_TEAM_7, Ok(()));++ let second = tracker(&second_pod)+ .observe(7, other_mismatch_diffs())+ .await;+ assert_eq!(second.store_errors, vec![TrackerStoreOp::Write]);+ assert_eq!(+ calls_with_op(&second_pod, "del")+ .iter()+ .map(|call| call.key.as_str())+ .collect::<Vec<_>>(),+ vec![PENDING_KEY_TEAM_7]+ );+ }++ #[tokio::test]+ async fn tracker_write_and_clear_failure_leaves_the_stale_observation() {+ // Both accesses failing is the residual `observe` documents: the previous+ // fingerprints stand until the TTL, so a disagreement that returns byte for+ // byte can confirm one build early. The counter pair is the only signal.+ let mut second_pod = next_build(&{+ let first_pod = MockRedisClient::new();+ tracker(&first_pod).observe(7, mismatch_diffs()).await;+ first_pod+ });+ second_pod.set_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));+ second_pod.del_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));++ let second = tracker(&second_pod)+ .observe(7, other_mismatch_diffs())+ .await;+ assert_eq!(+ second.store_errors,+ vec![TrackerStoreOp::Write, TrackerStoreOp::Clear]+ );+ assert!(second.confirmed.is_empty());+ }++ #[tokio::test]+ async fn tracker_unreadable_stored_value_is_reported_not_ignored() {+ // A stored value this build cannot parse counts as a read failure rather+ // than an absent key, so a value shape that changed across deploys shows on+ // the counter instead of looking like an expired window.+ let mut redis = MockRedisClient::new();+ redis.get_ret(PENDING_KEY_TEAM_7, Ok("not json".to_string()));++ let observation = tracker(&redis).observe(7, mismatch_diffs()).await;+ assert!(observation.confirmed.is_empty());+ assert_eq!(observation.first_sight.len(), 1);+ assert_eq!(observation.store_errors, vec![TrackerStoreOp::Read]);+ }++ #[tokio::test]+ async fn tracker_confirms_the_diffs_that_fit_the_stored_cap() {+ let over_cap = MAX_STORED_FINGERPRINTS as i32 + 20;+ let first_pod = MockRedisClient::new();+ let first = tracker(&first_pod)+ .observe(7, many_mismatch_diffs(over_cap))+ .await;+ assert_eq!(first.first_sight.len(), over_cap as usize);++ let second_pod = next_build(&first_pod);+ let second = tracker(&second_pod)+ .observe(7, many_mismatch_diffs(over_cap))+ .await;++ // Pins the cap, and that a diff inside it confirms. It does not pin which+ // diffs are stored: the next build compares all of its diffs against the+ // stored set, so any 256 of them produce 256 confirmations. Taking the+ // first entries of a stable order is what makes one flag's disagreement+ // confirm on every build rather than on some.+ assert_eq!(second.confirmed.len(), MAX_STORED_FINGERPRINTS);+ assert_eq!(second.first_sight.len(), 20);+ }++ #[tokio::test]+ async fn tracker_clear_failure_is_reported() {+ let mut redis = MockRedisClient::new();+ redis.del_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));++ let clean = tracker(&redis).observe(7, Vec::new()).await;+ assert!(clean.is_match());+ assert_eq!(clean.store_errors, vec![TrackerStoreOp::Clear]);+ }+#[test]fn summarize_caps_entries_and_reports_remainder() {let diffs = mismatch_diffs();