Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): bound the shadow mismatch confirmation window below (#92343)

James Gill5d324ecde19e
diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rs
index e3153d3eebd9..2cff4084356e 100644
--- a/rust/feature-flags/src/bin/flags_cache_builder.rs
+++ b/rust/feature-flags/src/bin/flags_cache_builder.rs
@@ -25,7 +25,7 @@
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::Arc;
-use std::time::{Duration, Instant};
+use std::time::{Duration, Instant, SystemTime};
use axum::{routing::get, Router};
use chrono::{DateTime, Utc};
@@ -724,7 +724,7 @@ async fn shadow_compare(
};
let diffs = diff_live_entry(&built, &live);
- let observation = tracker.observe(team_id, diffs).await;
+ let observation = tracker.observe(team_id, diffs, SystemTime::now()).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 {
@@ -1254,13 +1254,13 @@ mod tests {
) -> feature_flags::flags::cache_shadow::ShadowObservation {
use common_redis::{MockRedisClient, MockRedisValue};
use feature_flags::flags::cache_shadow::{
- diff_live_entry, MismatchTracker, ShadowLiveEntry,
+ diff_live_entry, MismatchTracker, ShadowLiveEntry, MIN_CONFIRM_INTERVAL,
};
use feature_flags::flags::flag_models::{
EvaluationMetadata, FeatureFlag, HypercacheFlagsWrapper,
};
use std::sync::Arc;
- use std::time::Duration as StdDuration;
+ use std::time::{Duration as StdDuration, SystemTime};
let flag = |has_experiment: bool| -> FeatureFlag {
serde_json::from_value(serde_json::json!({
@@ -1286,9 +1286,10 @@ mod tests {
};
let ttl = StdDuration::from_secs(3600);
+ let first_at = SystemTime::UNIX_EPOCH + StdDuration::from_secs(1_000);
let redis = MockRedisClient::new();
let first = MismatchTracker::new(Arc::new(redis.clone()), ttl)
- .observe(1, diff_live_entry(&built, &live))
+ .observe(1, diff_live_entry(&built, &live), first_at)
.await;
if !confirmed {
return first;
@@ -1302,8 +1303,14 @@ mod tests {
next.get_ret(&call.key, Ok(value));
}
}
+ // The second observation has to sit at least MIN_CONFIRM_INTERVAL past the
+ // first, or the confirmation window is still closed and nothing confirms.
MismatchTracker::new(Arc::new(next), ttl)
- .observe(1, diff_live_entry(&built, &live))
+ .observe(
+ 1,
+ diff_live_entry(&built, &live),
+ first_at + MIN_CONFIRM_INTERVAL,
+ )
.await
}
diff --git a/rust/feature-flags/src/flags/cache_shadow.rs b/rust/feature-flags/src/flags/cache_shadow.rs
index d34e49f2c8e9..19e0896f2dbe 100644
--- a/rust/feature-flags/src/flags/cache_shadow.rs
+++ b/rust/feature-flags/src/flags/cache_shadow.rs
@@ -37,13 +37,13 @@
//! 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::{HashMap, HashSet};
+use std::collections::HashMap;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common_redis::{Client, CustomRedisError};
use common_types::TeamId;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::cohorts::cohort_models::Cohort;
@@ -473,6 +473,74 @@ const STORE_TIMEOUT: Duration = Duration::from_millis(500);
/// some builds and not others.
const MAX_STORED_FINGERPRINTS: usize = 256;
+/// The shortest gap between two observations that can confirm a mismatch, which is
+/// the lower bound on the window `FLAGS_CACHE_SHADOW_MISMATCH_TTL` bounds above.
+/// Two invalidations for one team that fall just outside
+/// `FLAGS_CACHE_COALESCE_WINDOW_MS` become two builds a fraction of a second apart,
+/// and a row written between their two Postgres reads then confirms as a parity
+/// defect. Sized above one cohort recalculation episode, which holds
+/// `is_calculating` for seconds to minutes, and far below the TTL so a quiet team
+/// still confirms persistent drift.
+///
+/// A constant where the TTL beside it is a setting, because this bound tunes shadow
+/// telemetry on a path that never writes the cache and never serves a request. A
+/// change to it can wait for a deploy of this binary.
+pub const MIN_CONFIRM_INTERVAL: Duration = Duration::from_secs(60);
+
+/// The tracker's stored state for one team: each fingerprint from the team's last
+/// shadow build, against the time the first build that saw it observed it.
+///
+/// The time is per fingerprint and not per build, because a team's diff set
+/// changes while one disagreement inside it stays. One timestamp for the whole
+/// set restarts on every such change, and the disagreement that never went away
+/// then never reaches the interval. Teams that rebuild most often would suffer
+/// that most, and those are the teams this instrument exists to watch.
+///
+/// The times are unix seconds and not `Instant`s, because the value is written to
+/// Redis and read by a later process on another pod. An `Instant` is
+/// process-local and cannot be serialized.
+///
+/// Pairs and not a map: `StoredPending` is untagged, so serde buffers the value
+/// before it picks a variant, and that buffer holds every map key as a string. A
+/// `HashMap<u64, _>` reads back from it as a type error, which would report every
+/// stored value as unparseable.
+#[derive(Serialize, Deserialize, Default)]
+struct PendingObservation {
+ first_seen: Vec<(u64, u64)>,
+}
+
+/// The shapes a stored value can have. `Legacy` is the bare fingerprint array
+/// written before the confirmation window had a lower bound, and reading it stops
+/// a deploy from counting every pre-deploy key as a parse failure on
+/// `flags_cache_shadow_tracker_store_errors_total{op="read"}`, which would report
+/// a TTL's worth of read errors that are really a shape change. The variant can
+/// go once a full TTL has elapsed past that deploy.
+///
+/// A legacy value carries no times, so it reads as an empty observation. It must
+/// not confirm: a fingerprint this build cannot date would otherwise count as
+/// arbitrarily old and confirm at once, which is the race the interval filters.
+///
+/// `Current` is first because an untagged enum takes the first variant that
+/// matches, and a bare array cannot deserialize into `PendingObservation`.
+#[derive(Deserialize)]
+#[serde(untagged)]
+enum StoredPending {
+ Current(PendingObservation),
+ /// The fingerprints are never read, but the variant still names their type
+ /// rather than accepting anything. A value that is neither shape has to stay
+ /// a parse error, so that a genuinely corrupt entry keeps reaching the failure
+ /// counter instead of passing as an empty observation.
+ Legacy(#[allow(dead_code)] Vec<u64>),
+}
+
+/// Wall-clock seconds since the unix epoch. A clock set before 1970 resolves to
+/// zero, which stores a time the next build reads as arbitrarily old. That needs
+/// a system clock decades wrong, and the alternative is to fail a diagnostics
+/// build on a clock read.
+fn unix_seconds(now: SystemTime) -> u64 {
+ now.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
+}
+
/// 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>(
@@ -484,11 +552,20 @@ async fn with_timeout<T>(
}
}
-/// 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 tracker has held
+/// the same fingerprint for at least `MIN_CONFIRM_INTERVAL`, across builds no more
+/// than `ttl` apart. 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 window needs both bounds. Without the lower bound, a repeat means only
+/// "the build before this one", and the builder coalesces a team's invalidations
+/// over a window of a few hundred milliseconds, so two invalidations just outside
+/// it become two builds a fraction of a second apart. A row that is being written
+/// between those two Postgres reads then confirms as a parity defect: cohort
+/// recalculation state and a referencing flag's `version` both move on their own
+/// schedule. Without the upper bound, a disagreement Python has since repaired
+/// stays eligible to confirm forever.
///
/// 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
@@ -509,11 +586,16 @@ impl MismatchTracker {
Self { redis, 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
+ /// Fold one shadow build's diffs into the store and split them into confirmed
+ /// and first-sight. A diff confirms when its fingerprint was also in the
+ /// team's previous, unexpired observation *and* that observation is at least
+ /// `MIN_CONFIRM_INTERVAL` old. An empty `diffs` clears the team's pending
/// state.
///
+ /// `now` comes from the caller rather than from a clock read here, so the
+ /// elapsed comparison is stated at the call site and tests can pass literal
+ /// instants.
+ ///
/// 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
@@ -525,7 +607,12 @@ impl MismatchTracker {
/// 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 {
+ pub async fn observe(
+ &self,
+ team_id: TeamId,
+ diffs: Vec<ShadowDiff>,
+ now: SystemTime,
+ ) -> ShadowObservation {
let key = pending_key(team_id);
if diffs.is_empty() {
@@ -535,17 +622,41 @@ impl MismatchTracker {
};
}
+ let now_secs = unix_seconds(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()
+ HashMap::new()
}
};
- if let Err(e) = self.write_pending(key.clone(), &diffs).await {
+ // A fingerprint the tracker already holds keeps the time it was first
+ // stored with, so a disagreement accumulates elapsed time even while the
+ // rest of the team's diff set changes around it. A fingerprint this build
+ // has not seen before starts its window now.
+ //
+ // A stored time can sit ahead of this pod's clock, and it is kept as it
+ // is. Do not clamp it to `now_secs`. The builder pods share no clock, so
+ // "the pod that wrote this ran ahead" and "my own clock is behind" both
+ // read as `at > now_secs`, and a clamp answers both the same way. A pod
+ // running behind would then pull the stored time back to its own clock,
+ // the fingerprint would look older than it is, and a later pod would
+ // confirm before the interval had really elapsed. Keeping the stored time
+ // costs a confirmation delayed by the skew, which is the direction every
+ // other tracker failure takes. See the test named for this.
+ let first_seen: HashMap<u64, u64> = diffs
+ .iter()
+ .take(MAX_STORED_FINGERPRINTS)
+ .map(|d| {
+ let at = prior.get(&d.fingerprint).copied().unwrap_or(now_secs);
+ (d.fingerprint, at)
+ })
+ .collect();
+
+ if let Err(e) = self.write_pending(key.clone(), &first_seen).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
@@ -557,9 +668,14 @@ impl MismatchTracker {
store_errors.extend(self.clear_pending(team_id, key).await);
}
- let (confirmed, first_sight) = diffs
- .into_iter()
- .partition(|d| prior.contains(&d.fingerprint));
+ // `saturating_sub` covers a stored time ahead of this pod's clock, which
+ // resolves to no elapsed time and therefore to first sight.
+ let min_interval = MIN_CONFIRM_INTERVAL.as_secs();
+ let (confirmed, first_sight) = diffs.into_iter().partition(|d| {
+ prior
+ .get(&d.fingerprint)
+ .is_some_and(|at| now_secs.saturating_sub(*at) >= min_interval)
+ });
ShadowObservation {
confirmed,
first_sight,
@@ -567,16 +683,22 @@ impl MismatchTracker {
}
}
- /// 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> {
+ /// The team's previous shadow build, as each fingerprint against the time it
+ /// was first seen. 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<HashMap<u64, 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()))
+ let stored: StoredPending = serde_json::from_str(&raw)
+ .map_err(|e| CustomRedisError::ParseError(e.to_string()))?;
+ Ok(match stored {
+ StoredPending::Current(pending) => pending.first_seen.into_iter().collect(),
+ StoredPending::Legacy(_) => HashMap::new(),
+ })
}
- Err(CustomRedisError::NotFound) => Ok(HashSet::new()),
+ Err(CustomRedisError::NotFound) => Ok(HashMap::new()),
Err(e) => Err(e),
}
}
@@ -584,15 +706,12 @@ impl MismatchTracker {
async fn write_pending(
&self,
key: String,
- diffs: &[ShadowDiff],
+ first_seen: &HashMap<u64, u64>,
) -> 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()))?;
+ let payload = serde_json::to_string(&PendingObservation {
+ first_seen: first_seen.iter().map(|(fp, at)| (*fp, *at)).collect(),
+ })
+ .map_err(|e| CustomRedisError::ParseError(e.to_string()))?;
with_timeout(self.redis.setex(key, payload, self.ttl.as_secs())).await
}
@@ -1030,6 +1149,26 @@ mod tests {
const TRACKER_TTL: Duration = Duration::from_secs(3600);
const PENDING_KEY_TEAM_7: &str = "posthog:1:feature_flags/shadow_mismatch/7";
+ /// A wall clock reading `secs` after the epoch. The tracker compares the
+ /// stored timestamp against the one the caller passes, so a test states both
+ /// instead of reading a real clock.
+ fn at(secs: u64) -> SystemTime {
+ SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
+ }
+
+ /// The first build in a test. Not the epoch itself, so a test that subtracts
+ /// from it stays a valid instant.
+ fn first_build() -> SystemTime {
+ at(1_000)
+ }
+
+ /// The instant a fingerprint first seen at `first_build` becomes eligible to
+ /// confirm. Tests that are not about timing use this for their second build so
+ /// the interval never masks what they do assert.
+ fn window_opens_at() -> SystemTime {
+ first_build() + MIN_CONFIRM_INTERVAL
+ }
+
/// 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> {
@@ -1095,26 +1234,209 @@ mod tests {
#[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;
+ let first = tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
assert!(first.confirmed.is_empty());
assert_eq!(first.first_sight.len(), 1);
assert!(first.store_errors.is_empty());
let second_pod = next_build(&first_pod);
- let second = tracker(&second_pod).observe(7, mismatch_diffs()).await;
+ let second = tracker(&second_pod)
+ .observe(7, mismatch_diffs(), window_opens_at())
+ .await;
assert_eq!(second.confirmed.len(), 1);
assert!(second.first_sight.is_empty());
}
+ #[tokio::test]
+ async fn tracker_does_not_confirm_inside_the_minimum_interval() {
+ // Two of a team's invalidations that fall either side of the coalesce
+ // window become two builds a fraction of a second apart. A row that is
+ // written between their two Postgres reads disagrees on both, and with no
+ // lower bound on the window that counted as a confirmed parity defect.
+ let first_pod = MockRedisClient::new();
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
+
+ let second_pod = next_build(&first_pod);
+ let second = tracker(&second_pod)
+ .observe(
+ 7,
+ mismatch_diffs(),
+ first_build() + Duration::from_millis(600),
+ )
+ .await;
+ assert!(second.confirmed.is_empty());
+ assert_eq!(second.first_sight.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_keeps_the_window_open_across_builds_inside_the_interval() {
+ // The middle build must not restart the window. A team that invalidates
+ // faster than the interval would otherwise never accumulate elapsed time
+ // and could never confirm anything, however wrong its cache entry was.
+ let first_pod = MockRedisClient::new();
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), at(1_000))
+ .await;
+
+ let second_pod = next_build(&first_pod);
+ let second = tracker(&second_pod)
+ .observe(7, mismatch_diffs(), at(1_030))
+ .await;
+ assert!(second.confirmed.is_empty());
+
+ let third_pod = next_build(&second_pod);
+ let third = tracker(&third_pod)
+ .observe(7, mismatch_diffs(), at(1_061))
+ .await;
+ assert_eq!(third.confirmed.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_confirms_a_lasting_diff_while_another_comes_and_goes() {
+ // A team's diff set changes while one disagreement inside it stays. Timing
+ // the whole set instead of each fingerprint restarts the window on every
+ // such change, so the disagreement that never went away never confirms —
+ // and a team whose set churns is a team that rebuilds often, which is the
+ // one this instrument most needs to report on.
+ let lasting = mismatch_diffs();
+ let both = [mismatch_diffs(), other_mismatch_diffs()].concat();
+
+ let first_pod = MockRedisClient::new();
+ tracker(&first_pod)
+ .observe(7, lasting.clone(), at(1_000))
+ .await;
+
+ // The set grows, then shrinks back, both inside the interval.
+ let second_pod = next_build(&first_pod);
+ tracker(&second_pod).observe(7, both, at(1_030)).await;
+
+ let third_pod = next_build(&second_pod);
+ let third = tracker(&third_pod).observe(7, lasting, at(1_061)).await;
+ assert_eq!(third.confirmed.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_does_not_confirm_against_a_clock_that_went_backwards() {
+ // Builder pods do not share a clock. A build on a pod running behind the
+ // one that wrote the observation must resolve to first sight rather than
+ // underflow the elapsed check.
+ let first_pod = MockRedisClient::new();
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
+
+ let second_pod = next_build(&first_pod);
+ let second = tracker(&second_pod)
+ .observe(7, mismatch_diffs(), first_build() - Duration::from_secs(10))
+ .await;
+ assert!(second.confirmed.is_empty());
+ assert_eq!(second.first_sight.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_does_not_confirm_before_the_interval_really_elapsed() {
+ // A pod running behind must not age a fingerprint on the pods that come
+ // after it. Clamping the stored time to the writing pod's own clock looks
+ // like the fix for a time that sits in the future, but the pods share no
+ // clock: a pod that is behind cannot tell itself apart from a writer that
+ // ran ahead. It would store its own earlier clock, and the build after it
+ // would then measure elapsed time from a start that never happened.
+ let ahead_pod = MockRedisClient::new();
+ tracker(&ahead_pod)
+ .observe(7, mismatch_diffs(), at(1_000))
+ .await;
+
+ // 70 seconds behind. Correct on its own build, which reports first sight.
+ let behind_pod = next_build(&ahead_pod);
+ let behind = tracker(&behind_pod)
+ .observe(7, mismatch_diffs(), at(930))
+ .await;
+ assert!(behind.confirmed.is_empty());
+
+ // 40 seconds of real time after the first sighting, against a 60 second
+ // interval. Confirming here would report a race as a parity defect, which
+ // is the whole failure this interval exists to remove.
+ let later_pod = next_build(&behind_pod);
+ let later = tracker(&later_pod)
+ .observe(7, mismatch_diffs(), at(1_040))
+ .await;
+ assert!(later.confirmed.is_empty());
+ assert_eq!(later.first_sight.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_restarts_the_window_when_the_disagreement_changes() {
+ // Different content is a different disagreement, so its window starts at
+ // the build that first saw that content and not at the build before it.
+ let first_pod = MockRedisClient::new();
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), at(1_000))
+ .await;
+
+ let second_pod = next_build(&first_pod);
+ tracker(&second_pod)
+ .observe(7, other_mismatch_diffs(), at(1_030))
+ .await;
+
+ // 70 seconds past the first build, but only 40 past the build that first
+ // saw this content.
+ let third_pod = next_build(&second_pod);
+ let third = tracker(&third_pod)
+ .observe(7, other_mismatch_diffs(), at(1_070))
+ .await;
+ assert!(third.confirmed.is_empty());
+
+ let fourth_pod = next_build(&third_pod);
+ let fourth = tracker(&fourth_pod)
+ .observe(7, other_mismatch_diffs(), at(1_100))
+ .await;
+ assert_eq!(fourth.confirmed.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn tracker_reads_a_stored_value_written_before_the_window_existed() {
+ // The bare fingerprint array is the shape written before `observed_at`
+ // existed. It has to parse, or every key that predates the deploy reports
+ // as a read failure for a whole TTL. It also has to not confirm, because
+ // it carries no timestamp, and treating an absent one as time zero would
+ // make it infinitely old and confirm on this very build.
+ let legacy =
+ serde_json::to_string(&vec![mismatch_diffs()[0].fingerprint]).expect("must serialize");
+ let mut legacy_pod = MockRedisClient::new();
+ legacy_pod.get_ret(PENDING_KEY_TEAM_7, Ok(legacy));
+
+ let first = tracker(&legacy_pod)
+ .observe(7, mismatch_diffs(), at(1_000))
+ .await;
+ assert!(first.store_errors.is_empty());
+ assert!(first.confirmed.is_empty());
+ assert_eq!(first.first_sight.len(), 1);
+
+ // The rewrite carries a timestamp, so the window opens from this build.
+ let next_pod = next_build(&legacy_pod);
+ let later = tracker(&next_pod)
+ .observe(7, mismatch_diffs(), at(1_000) + MIN_CONFIRM_INTERVAL)
+ .await;
+ assert_eq!(later.confirmed.len(), 1);
+ }
+
#[tokio::test]
async fn tracker_clears_pending_state_on_match() {
let first_pod = MockRedisClient::new();
- tracker(&first_pod).observe(7, mismatch_diffs()).await;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
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;
+ let clean = tracker(&second_pod)
+ .observe(7, Vec::new(), window_opens_at())
+ .await;
assert!(clean.is_match());
assert!(clean.store_errors.is_empty());
@@ -1129,9 +1451,17 @@ mod tests {
vec![PENDING_KEY_TEAM_7]
);
- // The earlier sighting no longer counts — mismatch starts over.
+ // The earlier sighting no longer counts — mismatch starts over. Observed
+ // well past the interval, so the window being closed cannot be what makes
+ // this a first sighting.
let third_pod = next_build(&second_pod);
- let after = tracker(&third_pod).observe(7, mismatch_diffs()).await;
+ let after = tracker(&third_pod)
+ .observe(
+ 7,
+ mismatch_diffs(),
+ window_opens_at() + MIN_CONFIRM_INTERVAL,
+ )
+ .await;
assert!(after.confirmed.is_empty());
assert_eq!(after.first_sight.len(), 1);
}
@@ -1139,11 +1469,13 @@ mod tests {
#[tokio::test]
async fn tracker_expires_pending_state_after_ttl() {
let first_pod = MockRedisClient::new();
- tracker(&first_pod).observe(7, mismatch_diffs()).await;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .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.
+ // The TTL on this write is what bounds the confirmation window above, 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);
@@ -1158,7 +1490,9 @@ mod tests {
let mut expired = next_build(&first_pod);
expired.get_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::NotFound));
- let late = tracker(&expired).observe(7, mismatch_diffs()).await;
+ let late = tracker(&expired)
+ .observe(7, mismatch_diffs(), window_opens_at())
+ .await;
assert!(late.confirmed.is_empty());
assert_eq!(late.first_sight.len(), 1);
assert!(late.store_errors.is_empty());
@@ -1169,11 +1503,13 @@ mod tests {
// An edit session produces a different disagreement each save — the
// fingerprint hashes the content, so those never confirm.
let first_pod = MockRedisClient::new();
- tracker(&first_pod).observe(7, mismatch_diffs()).await;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
let second_pod = next_build(&first_pod);
let second = tracker(&second_pod)
- .observe(7, other_mismatch_diffs())
+ .observe(7, other_mismatch_diffs(), window_opens_at())
.await;
assert!(second.confirmed.is_empty());
assert_eq!(second.first_sight.len(), 1);
@@ -1182,10 +1518,14 @@ mod tests {
#[tokio::test]
async fn tracker_is_per_team() {
let first_pod = MockRedisClient::new();
- tracker(&first_pod).observe(7, mismatch_diffs()).await;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
let second_pod = next_build(&first_pod);
- let other_team = tracker(&second_pod).observe(8, mismatch_diffs()).await;
+ let other_team = tracker(&second_pod)
+ .observe(8, mismatch_diffs(), window_opens_at())
+ .await;
assert!(other_team.confirmed.is_empty());
assert_eq!(other_team.first_sight.len(), 1);
}
@@ -1193,12 +1533,16 @@ mod tests {
#[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;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .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;
+ let second = tracker(&second_pod)
+ .observe(7, mismatch_diffs(), window_opens_at())
+ .await;
assert!(second.confirmed.is_empty());
assert_eq!(second.first_sight.len(), 1);
assert_eq!(second.store_errors, vec![TrackerStoreOp::Read]);
@@ -1212,14 +1556,16 @@ mod tests {
// 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;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .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())
+ .observe(7, other_mismatch_diffs(), window_opens_at())
.await;
assert_eq!(second.store_errors, vec![TrackerStoreOp::Write]);
assert_eq!(
@@ -1238,14 +1584,16 @@ mod tests {
// 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;
+ tracker(&first_pod)
+ .observe(7, mismatch_diffs(), first_build())
+ .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())
+ .observe(7, other_mismatch_diffs(), window_opens_at())
.await;
assert_eq!(
second.store_errors,
@@ -1262,7 +1610,9 @@ mod tests {
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;
+ let observation = tracker(&redis)
+ .observe(7, mismatch_diffs(), first_build())
+ .await;
assert!(observation.confirmed.is_empty());
assert_eq!(observation.first_sight.len(), 1);
assert_eq!(observation.store_errors, vec![TrackerStoreOp::Read]);
@@ -1273,13 +1623,13 @@ mod tests {
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))
+ .observe(7, many_mismatch_diffs(over_cap), first_build())
.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))
+ .observe(7, many_mismatch_diffs(over_cap), window_opens_at())
.await;
// Pins the cap, and that a diff inside it confirms. It does not pin which
@@ -1296,7 +1646,7 @@ mod tests {
let mut redis = MockRedisClient::new();
redis.del_ret(PENDING_KEY_TEAM_7, Err(CustomRedisError::Timeout));
- let clean = tracker(&redis).observe(7, Vec::new()).await;
+ let clean = tracker(&redis).observe(7, Vec::new(), first_build()).await;
assert!(clean.is_match());
assert_eq!(clean.store_errors, vec![TrackerStoreOp::Clear]);
}