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): add shadow compare mode to the flags cache builder (#87891)

James Gill6502bbac29b5
diff --git a/products/feature_flags/backend/flags_cache_messages.py b/products/feature_flags/backend/flags_cache_messages.py
index d484118b07a7..06704e83e136 100644
--- a/products/feature_flags/backend/flags_cache_messages.py
+++ b/products/feature_flags/backend/flags_cache_messages.py
@@ -6,10 +6,19 @@ Consumer: rust/feature-flags flags-cache-builder.
The fixture at rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json
is the contract. The Python side round-trips against it in
products/feature_flags/backend/test/test_flags_cache_messages.py. The Rust consumer
-(PR 2) will round-trip against the same fixture so schema drift fails the build
-on either side. Bumping `version` requires running both producers (old + new)
-and both consumers (old + new) in parallel during the migration — do not bump
-it without a written rollout plan.
+round-trips against the same fixture so schema drift fails the build on either
+side. Bumping `version` requires running both producers (old + new) and both
+consumers (old + new) in parallel during the migration — do not bump it without
+a written rollout plan.
+
+The Rust consumer additionally understands an optional ``shadow: bool`` field
+(fixture: flags_cache_invalidation_v1_shadow.json): on ``shadow: true`` it
+builds the payload but never writes the cache, diffing the build against the
+live entry instead (parity telemetry for teams Celery still owns). The shadow
+publisher will add the field here when it lands; until then this model stays
+without it so no producer can emit shadow messages before every deployed
+consumer understands them. When adding it, serialize ``shadow=False`` by
+*omitting* the key to keep real invalidations byte-identical to v1.
"""
from typing import Literal
diff --git a/rust/common/hypercache/src/lib.rs b/rust/common/hypercache/src/lib.rs
index 0d30f6d5e886..45ea4cd7f371 100644
--- a/rust/common/hypercache/src/lib.rs
+++ b/rust/common/hypercache/src/lib.rs
@@ -793,6 +793,28 @@ impl HyperCacheReader {
Ok(data)
}
+ /// Fetch from Redis only — no S3 fallback and no read repair. For callers that
+ /// need to observe exactly what the Redis tier holds right now (e.g. shadow
+ /// verification comparing a fresh build against the live entry) rather than the
+ /// best available copy. Returns `Ok(None)` for the `__missing__` sentinel and
+ /// `Err(HyperCacheError::CacheMiss)` when the key is absent; a Redis timeout
+ /// surfaces as `Err(HyperCacheError::Timeout)` instead of cascading to S3.
+ pub async fn get_typed_from_redis<T: DeserializeOwned>(
+ &self,
+ key: &KeyType,
+ ) -> Result<Option<T>, HyperCacheError> {
+ let redis_cache_key = self.config.get_redis_cache_key(key);
+ match timeout(
+ self.config.redis_timeout,
+ self.try_get_typed_from_redis::<T>(&redis_cache_key),
+ )
+ .await
+ {
+ Ok(result) => result,
+ Err(_) => Err(HyperCacheError::Timeout("redis timeout".to_string())),
+ }
+ }
+
/// Read the companion ETag string for `key` from Redis, if present.
///
/// The ETag is written atomically alongside the payload by `HyperCacheWriter::set_with_etag`
@@ -1846,6 +1868,69 @@ mod tests {
serde_pickle::to_vec(&json_string, Default::default()).unwrap()
}
+ #[tokio::test]
+ async fn test_get_typed_from_redis_hit() {
+ let expected = make_test_flags();
+ let pickled = pickle_json(&expected);
+
+ let mut mock_redis = MockRedisClient::new();
+ let cache_key = create_test_config().get_redis_cache_key(&KeyType::int(42));
+ mock_redis.get_raw_bytes_ret(&cache_key, Ok(pickled));
+
+ let reader = create_test_reader_with_mocks(mock_redis, create_dummy_s3_client());
+ let data = reader
+ .get_typed_from_redis::<TestFlags>(&KeyType::int(42))
+ .await
+ .unwrap();
+
+ assert_eq!(data, Some(expected));
+ }
+
+ #[tokio::test]
+ async fn test_get_typed_from_redis_sentinel_returns_none() {
+ let sentinel_pickled =
+ serde_pickle::to_vec(&HYPER_CACHE_EMPTY_VALUE, Default::default()).unwrap();
+
+ let mut mock_redis = MockRedisClient::new();
+ let cache_key = create_test_config().get_redis_cache_key(&KeyType::int(99));
+ mock_redis.get_raw_bytes_ret(&cache_key, Ok(sentinel_pickled));
+
+ let reader = create_test_reader_with_mocks(mock_redis, create_dummy_s3_client());
+ let data = reader
+ .get_typed_from_redis::<TestFlags>(&KeyType::int(99))
+ .await
+ .unwrap();
+
+ assert_eq!(data, None);
+ }
+
+ /// A Redis miss must surface as `CacheMiss` even when S3 holds the value —
+ /// the whole point of the Redis-only getter is that it never cascades.
+ #[cfg(feature = "mock-client")]
+ #[tokio::test]
+ async fn test_get_typed_from_redis_miss_does_not_fall_back_to_s3() {
+ let payload = serde_json::to_string(&make_test_flags()).unwrap();
+ let fixture = redis_miss_s3_hit_fixture(create_test_config(), &payload);
+
+ // First prove S3 really holds the value — the cascading read returns it —
+ // so the Redis-only miss below is a refusal to fall back, not a vacuous
+ // pass against an empty fixture.
+ let (cascaded, source) = fixture
+ .reader
+ .get_typed_with_source::<TestFlags>(&fixture.team_key)
+ .await
+ .unwrap();
+ assert_eq!(source, CacheSource::S3);
+ assert_eq!(cascaded, Some(make_test_flags()));
+
+ let result = fixture
+ .reader
+ .get_typed_from_redis::<TestFlags>(&fixture.team_key)
+ .await;
+
+ assert!(matches!(result, Err(HyperCacheError::CacheMiss)));
+ }
+
#[tokio::test]
async fn test_get_typed_with_source_redis_hit() {
let expected = make_test_flags();
diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rs
index 3a347d89ccff..95f104382540 100644
--- a/rust/feature-flags/src/bin/flags_cache_builder.rs
+++ b/rust/feature-flags/src/bin/flags_cache_builder.rs
@@ -15,6 +15,12 @@
//!
//! The lazy request-path fill stays as the final safety net: a stuck consumer
//! degrades latency, not correctness.
+//!
+//! Messages marked `shadow: true` take a separate path: build the payload as
+//! usual, then diff it against the live Redis entry instead of writing —
+//! parity telemetry for teams the Python (Celery) builder still owns. Shadow
+//! work never writes, never DLQs, and never touches the real-build metrics;
+//! see `flags::cache_shadow`.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
@@ -25,7 +31,7 @@ use axum::{routing::get, Router};
use chrono::{DateTime, Utc};
use common_database::{get_pool, PostgresReader};
use common_hypercache::writer::HyperCacheWriter;
-use common_hypercache::HyperCacheError;
+use common_hypercache::{HyperCacheError, HyperCacheReader, KeyType};
use common_kafka::config::{ConsumerConfig, KafkaConfig};
use common_kafka::kafka_consumer::{Offset, RecvErr, SingleTopicConsumer};
use common_kafka::kafka_producer::{
@@ -44,6 +50,9 @@ use tracing_subscriber::EnvFilter;
use feature_flags::flags::cache_builder::build_flags_cache;
use feature_flags::flags::cache_invalidation::FlagsCacheInvalidation;
+use feature_flags::flags::cache_shadow::{
+ diff_live_entry, summarize_diffs, MismatchTracker, ShadowLiveEntry, ShadowObservation,
+};
use feature_flags::flags::cache_writer::{self, persist_flags_cache, PersistOutcome};
use feature_flags::server::create_redis_client;
@@ -83,6 +92,27 @@ const KAFKA_RECV_ERRORS: &str = "flags_cache_builder_kafka_recv_errors_total";
const DLQ_PRODUCED: &str = "flags_cache_builder_dlq_produced_total";
const COALESCED_TEAMS: &str = "flags_cache_builder_coalesced_teams";
+// Shadow-compare metrics. Deliberately disjoint from the real-build metrics:
+// BUILDS_TOTAL{result=failure} feeds the FlagsCacheBuilderBuildFailureRate page,
+// and a shadow build failing must never page — the team is still served by the
+// Python builder. Every shadow build increments exactly one SHADOW_BUILDS outcome
+// (match / mismatch_confirmed / mismatch_suppressed / live_entry_missing / error),
+// so the unlabelled sum is the processed count.
+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";
+// 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 —
+// the head-of-line span to watch during the producer-side ramp. Seconds-shaped,
+// same buckets as the real-build duration histogram.
+const SHADOW_BUILD_DURATION_SECONDS: &str = "flags_cache_shadow_build_duration_seconds";
+
+/// Caps on the confirmed-mismatch log line (see `summarize_diffs`).
+const SHADOW_LOG_MAX_ENTRIES: usize = 20;
+const SHADOW_LOG_MAX_BYTES: usize = 4096;
+
const E2E_LATENCY_BUCKETS: &[f64] = &[0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0];
/// Seconds buckets for the build-duration histogram. Our histograms are
/// seconds-shaped, so both are overridden off `common_metrics`' ms-shaped default.
@@ -147,6 +177,12 @@ 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.
+ #[envconfig(from = "FLAGS_CACHE_SHADOW_MISMATCH_TTL", default = "86400")]
+ shadow_mismatch_ttl_seconds: u64,
}
/// All offsets and timing for a single team's coalesced invalidations. Generic
@@ -235,7 +271,9 @@ async fn main() -> anyhow::Result<()> {
.expect("Failed to create database pool");
let pg_reader: PostgresReader = Arc::new(pg_pool);
- let writer = Arc::new(build_writer(&infra).await);
+ let (writer, live_reader) = build_cache_clients(&infra).await;
+ let writer = Arc::new(writer);
+ let live_reader = Arc::new(live_reader);
let consumer = SingleTopicConsumer::new(kafka_cfg.clone(), consumer_cfg)
.expect("Failed to create Kafka consumer");
@@ -255,6 +293,7 @@ async fn main() -> anyhow::Result<()> {
consumer,
pg_reader,
writer,
+ live_reader,
dlq_producer,
builder_cfg,
loop_handle.clone(),
@@ -267,7 +306,11 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
-async fn build_writer(infra: &InfraConfig) -> HyperCacheWriter {
+/// 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) {
tracing::info!("Connecting to Redis");
let Some(redis_client) = create_redis_client(
&infra.flags_redis_url,
@@ -284,26 +327,34 @@ async fn build_writer(infra: &InfraConfig) -> HyperCacheWriter {
};
let redis_client: Arc<dyn common_redis::Client + Send + Sync> = redis_client;
- cache_writer::build_writer(
- redis_client,
+ let endpoint = Some(infra.object_storage_endpoint.as_str());
+ let s3_client = cache_writer::create_s3_client(&infra.object_storage_region, endpoint).await;
+ let config = cache_writer::make_cache_config(
&infra.object_storage_region,
&infra.object_storage_bucket,
- Some(infra.object_storage_endpoint.as_str()),
- )
- .await
+ endpoint,
+ );
+
+ 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)
}
/// The consumer hot loop. Returns when `shutdown` is cancelled (graceful drain).
+#[allow(clippy::too_many_arguments)]
async fn consume_loop(
consumer: SingleTopicConsumer,
pg_reader: PostgresReader,
writer: Arc<HyperCacheWriter>,
+ live_reader: Arc<HyperCacheReader>,
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));
loop {
// Reporting healthy each iteration covers the idle case: with no traffic
@@ -320,12 +371,12 @@ async fn consume_loop(
continue;
}
- let (by_team, had_kafka_error) = coalesce_batch(batch);
- if by_team.is_empty() {
+ let coalesced = coalesce_batch(batch);
+ if coalesced.real.is_empty() && coalesced.shadow.is_empty() {
// Batch held only poison pills or receive errors. Poison offsets were
// auto-stored by json_recv, so commit to avoid reprocessing them.
commit_offsets(&consumer);
- if had_kafka_error {
+ if coalesced.had_kafka_error {
// A receive error stores no offset, so there's nothing to make
// progress on until the broker recovers — back off rather than
// hot-loop on immediate errors.
@@ -334,17 +385,19 @@ async fn consume_loop(
continue;
}
- metrics::histogram!(COALESCED_TEAMS).record(by_team.len() as f64);
+ if !coalesced.real.is_empty() {
+ metrics::histogram!(COALESCED_TEAMS).record(coalesced.real.len() as f64);
+ }
let mut interrupted = false;
// Collect every processed offset and store the per-partition max once, at
- // the end of the batch. `by_team` is a HashMap, so we build teams in
+ // the end of the batch. `real`/`shadow` are HashMaps, so we build teams in
// arbitrary order; storing each team's offsets as we go could check-point a
// partition *backwards* (one partition carries many teams' interleaved
// messages), needlessly reprocessing on the next restart. See
// `store_max_offsets_per_partition`.
let mut batch_offsets: Vec<Offset> = Vec::new();
- for (team_id, team_batch) in by_team {
+ for (team_id, team_batch) in coalesced.real {
// Stop between teams once shutdown is signalled: a large batch (up to
// max_batch unique teams, each with retry backoff) could otherwise
// outrun the graceful-shutdown budget and be killed mid-build.
@@ -367,6 +420,30 @@ async fn consume_loop(
batch_offsets.extend(offsets);
}
+ // Shadow teams run after every real build, so within a batch shadow
+ // work never delays a serve-path write. Across batches it can: the next
+ // fetch waits for this loop, so a shadow-heavy batch adds head-of-line
+ // delay to the real builds behind it. SHADOW_BUILD_DURATION_SECONDS measures
+ // that delay; the producer-side gate is the lever if it grows.
+ if !interrupted {
+ for (team_id, team_batch) in coalesced.shadow {
+ if shutdown.is_cancelled() {
+ interrupted = true;
+ break;
+ }
+ health.report_healthy();
+ let offsets = process_shadow_team(
+ &pg_reader,
+ &live_reader,
+ &mut mismatch_tracker,
+ team_id,
+ team_batch,
+ )
+ .await;
+ batch_offsets.extend(offsets);
+ }
+ }
+
if interrupted {
// Don't store or commit a partially processed batch. Kafka commits a
// single per-partition high-water mark, and one partition holds many
@@ -391,15 +468,40 @@ async fn consume_loop(
tracing::info!("Consumer loop draining; offsets committed up to last fully processed batch");
}
-/// Dedupe a fetched batch by `team_id`, counting received messages and errors.
+/// A fetched batch deduped by `team_id`, split by delivery mode. Real and shadow
+/// invalidations never coalesce with each other: a shadow message must not be
+/// absorbed into a real build (that would serve-write a team Python owns), and a
+/// real message must not be downgraded into a compare-only pass.
+struct CoalescedBatch {
+ real: HashMap<TeamId, TeamBatch>,
+ shadow: HashMap<TeamId, TeamBatch>,
+ had_kafka_error: bool,
+}
+
+/// Fold one message into the map matching its delivery mode. Split out from
+/// `coalesce_batch` so the real/shadow routing is testable without constructing
+/// `Offset` values.
+fn fold_message<O>(
+ real: &mut HashMap<TeamId, TeamBatch<O>>,
+ shadow: &mut HashMap<TeamId, TeamBatch<O>>,
+ team_id: TeamId,
+ is_shadow: bool,
+ emitted_at: DateTime<Utc>,
+ offset: O,
+) {
+ let target = if is_shadow { shadow } else { real };
+ TeamBatch::fold_into(target, team_id, emitted_at, offset);
+}
+
+/// Dedupe a fetched batch by `team_id` within each delivery mode, counting
+/// received messages and errors.
/// Poison pills (parse failures) already had their offsets stored by `json_recv`;
/// Kafka receive errors stored nothing. Returns the per-team work plus whether a
/// Kafka receive error occurred, so the caller can back off instead of hot-looping
/// while the broker is unreachable.
-fn coalesce_batch(
- batch: Vec<Result<(FlagsCacheInvalidation, Offset), RecvErr>>,
-) -> (HashMap<TeamId, TeamBatch>, bool) {
- let mut by_team: HashMap<TeamId, TeamBatch> = HashMap::new();
+fn coalesce_batch(batch: Vec<Result<(FlagsCacheInvalidation, Offset), RecvErr>>) -> CoalescedBatch {
+ let mut real: HashMap<TeamId, TeamBatch> = HashMap::new();
+ let mut shadow: HashMap<TeamId, TeamBatch> = HashMap::new();
let mut received: u64 = 0;
let mut had_kafka_error = false;
@@ -407,7 +509,14 @@ fn coalesce_batch(
match result {
Ok((msg, offset)) => {
received += 1;
- TeamBatch::fold_into(&mut by_team, msg.team_id, msg.emitted_at, offset);
+ fold_message(
+ &mut real,
+ &mut shadow,
+ msg.team_id,
+ msg.shadow,
+ msg.emitted_at,
+ offset,
+ );
}
// A receive error is a broker/transport problem, not a bad message:
// nothing was consumed and no offset was stored. Track it apart from
@@ -425,7 +534,11 @@ fn coalesce_batch(
}
metrics::counter!(MESSAGES_RECEIVED).increment(received);
- (by_team, had_kafka_error)
+ CoalescedBatch {
+ real,
+ shadow,
+ had_kafka_error,
+ }
}
/// Build one team's cache, routing to the DLQ on terminal failure, and return the
@@ -471,6 +584,121 @@ async fn process_team(
team_batch.offsets
}
+/// Outcome of a single shadow compare, mapped 1:1 onto a `SHADOW_BUILDS` outcome
+/// label via `as_label`.
+enum ShadowOutcome {
+ Match,
+ Mismatch(ShadowObservation),
+ /// No live Redis entry to compare against — Python may simply not have
+ /// built the team yet. Counted, never alarmed on.
+ LiveEntryMissing,
+ /// The shadow build or the live-entry read failed. Dropped and counted on
+ /// the shadow-only failure counter — never the real-build failure metric
+ /// (which pages) and never the DLQ (which is the real path's triage queue).
+ Failed(BuildFailure),
+}
+
+impl ShadowOutcome {
+ /// The `SHADOW_BUILDS{outcome}` label. Every outcome maps to exactly one
+ /// label, so the counter's unlabelled sum is the processed count.
+ fn as_label(&self) -> &'static str {
+ match self {
+ Self::Match => "match",
+ Self::LiveEntryMissing => "live_entry_missing",
+ Self::Failed(_) => "error",
+ Self::Mismatch(observation) if observation.confirmed.is_empty() => {
+ "mismatch_suppressed"
+ }
+ Self::Mismatch(_) => "mismatch_confirmed",
+ }
+ }
+}
+
+/// Run one team's shadow compare and emit its telemetry. Never writes to the
+/// cache (no writer in reach), never DLQs, and always returns the offsets so a
+/// failing shadow message can't wedge the partition.
+async fn process_shadow_team(
+ pg_reader: &PostgresReader,
+ live_reader: &HyperCacheReader,
+ tracker: &mut MismatchTracker,
+ team_id: TeamId,
+ team_batch: TeamBatch,
+) -> Vec<Offset> {
+ let start = Instant::now();
+ let outcome = shadow_compare(pg_reader, live_reader, tracker, team_id).await;
+ // Recorded for every outcome: the per-team wall time delays the next batch
+ // whether the compare matched, mismatched, or failed.
+ metrics::histogram!(SHADOW_BUILD_DURATION_SECONDS).record(start.elapsed().as_secs_f64());
+ metrics::counter!(SHADOW_BUILDS, "outcome" => outcome.as_label()).increment(1);
+ match outcome {
+ ShadowOutcome::Match | ShadowOutcome::LiveEntryMissing => {}
+ ShadowOutcome::Failed(failure) => {
+ metrics::counter!(SHADOW_FAILURES, "category" => failure.category).increment(1);
+ tracing::warn!(team_id, category = failure.category, error = %failure.message, "Shadow build failed; dropping (not DLQ'd)");
+ }
+ ShadowOutcome::Mismatch(observation) => {
+ for diff in &observation.confirmed {
+ metrics::counter!(SHADOW_MISMATCH, "issue_type" => diff.issue_type.as_label())
+ .increment(1);
+ }
+ for diff in &observation.first_sight {
+ metrics::counter!(SHADOW_MISMATCH_FIRST_SIGHT, "issue_type" => diff.issue_type.as_label())
+ .increment(1);
+ }
+ if !observation.confirmed.is_empty() {
+ tracing::error!(
+ team_id,
+ diff = %summarize_diffs(&observation.confirmed, SHADOW_LOG_MAX_ENTRIES, SHADOW_LOG_MAX_BYTES),
+ "Shadow compare mismatch persisted across consecutive builds"
+ );
+ }
+ }
+ }
+
+ team_batch.offsets
+}
+
+/// Build the team's payload exactly as a real invalidation would, then diff it
+/// against the live Redis entry instead of persisting it. Redis-only read: the
+/// point is what the serve path's cache tier holds right now, and an S3 cascade
+/// would blur "Python hasn't built this team yet" into a comparison.
+///
+/// The read shares the hypercache reader's miss-reason counter
+/// (`hypercache_redis_miss_reason{reason="not_found"}`), so shadow builds of
+/// teams Python hasn't built yet count there too. The builder is its own scrape
+/// job, so dashboards scoped to the flags service are unaffected — but
+/// aggregations of that counter across jobs should filter the builder out.
+async fn shadow_compare(
+ pg_reader: &PostgresReader,
+ live_reader: &HyperCacheReader,
+ tracker: &mut MismatchTracker,
+ team_id: TeamId,
+) -> ShadowOutcome {
+ let built = match build_flags_cache(pg_reader.clone(), team_id).await {
+ Ok(built) => built,
+ Err(e) => return ShadowOutcome::Failed(BuildFailure::database(e)),
+ };
+
+ let live = match live_reader
+ .get_typed_from_redis::<ShadowLiveEntry>(&KeyType::int(team_id))
+ .await
+ {
+ Ok(Some(live)) => live,
+ // The `__missing__` sentinel and an absent key both mean "nothing to
+ // compare against", not drift.
+ Ok(None) | Err(HyperCacheError::CacheMiss) => return ShadowOutcome::LiveEntryMissing,
+ Err(e) => return ShadowOutcome::Failed(BuildFailure::from_live_read(e)),
+ };
+
+ let diffs = diff_live_entry(&built, &live);
+ let observation = tracker.observe(team_id, diffs, Instant::now());
+ if observation.is_match() {
+ ShadowOutcome::Match
+ } else {
+ ShadowOutcome::Mismatch(observation)
+ }
+}
+
/// A terminal build failure tagged with the tier that failed, so the error metric
/// and DLQ headers can attribute it — that tier (database / redis / s3 / serialize)
/// is the triage signal the DLQ exists to provide. `category` is a fixed set of
@@ -490,6 +718,22 @@ impl BuildFailure {
}
}
+ /// A failure reading the live entry during a shadow compare. `Json`/`Pickle`
+ /// mean the cached bytes didn't parse into the typed model (`cache_parse` —
+ /// distinct from the write path's `serialize`); everything else is the Redis
+ /// tier, including timeouts. `CacheMiss` never reaches here — the caller
+ /// maps it to `LiveEntryMissing` first.
+ fn from_live_read(err: HyperCacheError) -> Self {
+ let category = match err {
+ HyperCacheError::Json(_) | HyperCacheError::Pickle(_) => "cache_parse",
+ _ => "redis",
+ };
+ Self {
+ category,
+ message: err.to_string(),
+ }
+ }
+
/// A failure persisting the built cache, attributed to the HyperCache tier that
/// failed. `Timeout`/`CacheMiss`/`Pickle` don't occur on the write path, so they
/// fall through to `other`.
@@ -730,7 +974,7 @@ fn spawn_metrics_server(
.route("/_liveness", get(move || async move { liveness.check() }));
// Reuse the crate's shared recorder/router setup (prometheus install +
- // /metrics + product label + HTTP metrics middleware), overriding the two
+ // /metrics + product label + HTTP metrics middleware), overriding the
// seconds-shaped histograms off its ms-shaped default buckets.
let overrides = [
(
@@ -741,6 +985,10 @@ fn spawn_metrics_server(
Matcher::Full(E2E_LATENCY_SECONDS.to_string()),
E2E_LATENCY_BUCKETS,
),
+ (
+ Matcher::Full(SHADOW_BUILD_DURATION_SECONDS.to_string()),
+ BUILD_DURATION_BUCKETS,
+ ),
];
let router = setup_metrics_routes_for_product_with_overrides(
health_router,
@@ -767,8 +1015,8 @@ mod tests {
use chrono::{DateTime, TimeZone, Utc};
use super::{
- max_per_partition, retry_backoff, truncate_for_header, BuildFailure, TeamBatch,
- DLQ_ERROR_HEADER_MAX,
+ fold_message, max_per_partition, retry_backoff, truncate_for_header, BuildFailure,
+ ShadowOutcome, TeamBatch, DLQ_ERROR_HEADER_MAX,
};
// (partition, offset) pairs; keyed and valued by the two fields.
@@ -809,6 +1057,64 @@ mod tests {
assert_eq!(offsets, &vec![0, 1, 2]);
}
+ /// Route a list of (team_id, shadow, emitted_at, offset) through the same
+ /// `fold_message` the consumer uses and return the two maps' offsets.
+ fn route(
+ items: Vec<(i32, bool, DateTime<Utc>, u64)>,
+ ) -> (HashMap<i32, Vec<u64>>, HashMap<i32, Vec<u64>>) {
+ let mut real: HashMap<i32, TeamBatch<u64>> = HashMap::new();
+ let mut shadow: HashMap<i32, TeamBatch<u64>> = HashMap::new();
+ for (team_id, is_shadow, emitted_at, offset) in items {
+ fold_message(
+ &mut real,
+ &mut shadow,
+ team_id,
+ is_shadow,
+ emitted_at,
+ offset,
+ );
+ }
+ let flatten = |map: HashMap<i32, TeamBatch<u64>>| {
+ map.into_iter()
+ .map(|(team, batch)| (team, batch.offsets))
+ .collect()
+ };
+ (flatten(real), flatten(shadow))
+ }
+
+ #[test]
+ fn shadow_messages_never_reach_the_real_build_map() {
+ // The real map is the only route to a cache write; a shadow message
+ // landing there would serve-write a team Python still owns.
+ let (real, shadow) = route(vec![(7, true, ts(100), 0), (7, true, ts(200), 1)]);
+ assert!(real.is_empty());
+ assert_eq!(shadow[&7], vec![0, 1]);
+ }
+
+ #[test]
+ fn real_and_shadow_messages_for_one_team_do_not_coalesce() {
+ // A mixed batch must produce both a real build and a shadow compare —
+ // absorbing either into the other changes what gets written.
+ let (real, shadow) = route(vec![(7, false, ts(100), 0), (7, true, ts(200), 1)]);
+ assert_eq!(real[&7], vec![0]);
+ assert_eq!(shadow[&7], vec![1]);
+ }
+
+ #[test]
+ fn absent_shadow_field_routes_to_the_real_build_map() {
+ // Pre-shadow producers keep exactly today's behavior: `shadow` is absent
+ // on the wire, deserializes to false, and the message builds for real.
+ let msg: super::FlagsCacheInvalidation = serde_json::from_str(
+ r#"{"version": 1, "team_id": 7, "operation": "invalidate", "emitted_at": "2026-04-23T10:37:00Z"}"#,
+ )
+ .expect("v1 message without shadow must parse");
+ assert!(!msg.shadow);
+
+ let (real, shadow) = route(vec![(msg.team_id, msg.shadow, msg.emitted_at, 0)]);
+ assert_eq!(real[&7], vec![0]);
+ assert!(shadow.is_empty());
+ }
+
#[test]
fn coalesce_groups_offsets_per_team() {
let got = coalesce(vec![(1, ts(50), 10), (2, ts(60), 20), (1, ts(40), 11)]);
@@ -874,6 +1180,103 @@ mod tests {
);
}
+ #[test]
+ fn build_failure_attributes_live_read_errors_to_their_tier() {
+ use common_hypercache::HyperCacheError;
+ use common_redis::CustomRedisError;
+
+ // Shadow live-read categories: parse failures mean the cached bytes
+ // don't fit the typed model (persistent, worth triaging apart), while
+ // Redis/timeout errors are the transport tier.
+ let cases = [
+ (
+ HyperCacheError::Json(serde_json::from_str::<i32>("x").unwrap_err()),
+ "cache_parse",
+ ),
+ (HyperCacheError::Pickle("bad pickle".into()), "cache_parse"),
+ (HyperCacheError::Redis(CustomRedisError::Timeout), "redis"),
+ (HyperCacheError::Timeout("redis timeout".into()), "redis"),
+ ];
+ for (err, expected) in cases {
+ assert_eq!(BuildFailure::from_live_read(err).category, expected);
+ }
+ }
+
+ /// Build a real `ShadowObservation` through the public diff + tracker API:
+ /// one observation is a first sighting (suppressed), two consecutive ones
+ /// confirm.
+ fn shadow_observation(
+ confirmed: bool,
+ ) -> feature_flags::flags::cache_shadow::ShadowObservation {
+ 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};
+
+ let flag = |has_experiment: bool| -> FeatureFlag {
+ serde_json::from_value(serde_json::json!({
+ "id": 1,
+ "team_id": 1,
+ "key": "flag-1",
+ "filters": {"groups": []},
+ "active": true,
+ "deleted": false,
+ "has_experiment": has_experiment,
+ }))
+ .expect("flag json must parse")
+ };
+ let built = HypercacheFlagsWrapper {
+ flags: vec![flag(false)],
+ evaluation_metadata: EvaluationMetadata::default(),
+ cohorts: Some(Vec::new()),
+ };
+ let live = ShadowLiveEntry {
+ flags: vec![flag(true)],
+ evaluation_metadata: Some(EvaluationMetadata::default()),
+ 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);
+ if !confirmed {
+ return first;
+ }
+ tracker.observe(
+ 1,
+ diff_live_entry(&built, &live),
+ now + StdDuration::from_secs(1),
+ )
+ }
+
+ #[test]
+ 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 = [
+ (ShadowOutcome::Match, "match"),
+ (ShadowOutcome::LiveEntryMissing, "live_entry_missing"),
+ (
+ ShadowOutcome::Failed(BuildFailure::database("pg unreachable")),
+ "error",
+ ),
+ (
+ ShadowOutcome::Mismatch(shadow_observation(false)),
+ "mismatch_suppressed",
+ ),
+ (
+ ShadowOutcome::Mismatch(shadow_observation(true)),
+ "mismatch_confirmed",
+ ),
+ ];
+ for (outcome, expected) in cases {
+ assert_eq!(outcome.as_label(), expected);
+ }
+ }
+
#[test]
fn truncate_for_header_stays_within_cap_on_char_boundary() {
// Multibyte chars (3 bytes each) so the cap lands mid-character: the
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index b722fbf82f35..782078b19387 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -70,7 +70,7 @@ pub async fn build_flags_cache(
/// Do not widen this to the rest of that set (survey, evaluation runtime, evaluation
/// contexts): those are request-scoped, so blanking on them would strip targeting that
/// other requests still need.
-fn is_evaluable(flag: &FeatureFlag) -> bool {
+pub(crate) fn is_evaluable(flag: &FeatureFlag) -> bool {
flag.active && !flag.deleted
}
diff --git a/rust/feature-flags/src/flags/cache_invalidation.rs b/rust/feature-flags/src/flags/cache_invalidation.rs
index f35d6090a952..54b36892293f 100644
--- a/rust/feature-flags/src/flags/cache_invalidation.rs
+++ b/rust/feature-flags/src/flags/cache_invalidation.rs
@@ -3,9 +3,10 @@
//! Producer: Django signal handlers in `products/feature_flags/backend/flags_cache.py`.
//! Consumer: the `flags-cache-builder` binary in this crate.
//!
-//! The fixture at `rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json`
-//! is the contract. Both this crate and the Python side round-trip against that same
-//! on-disk file (`products/feature_flags/backend/test/test_flags_cache_messages.py`),
+//! The fixtures at `rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json`
+//! and `flags_cache_invalidation_v1_shadow.json` are the contract. Both this crate and
+//! the Python side round-trip against the same on-disk files
+//! (`products/feature_flags/backend/test/test_flags_cache_messages.py`),
//! so a schema drift on either side fails CI. The Rust struct mirrors the Python
//! model's strictness field-for-field: unknown fields rejected, only `version: 1`,
//! only `operation: "invalidate"`, and a timezone-aware `emitted_at`.
@@ -42,6 +43,16 @@ pub struct FlagsCacheInvalidation {
/// ISO 8601, UTC. `DateTime<Utc>` requires an explicit offset, so a naive
/// timestamp (no `Z`/offset) is rejected — matching Python's `AwareDatetime`.
pub emitted_at: DateTime<Utc>,
+ /// Shadow invalidation: the consumer builds the payload as usual but never
+ /// writes it — instead it diffs the build against the live cache entry and
+ /// records the result (parity telemetry for teams Celery still owns and
+ /// serve-writes). Absent or `false` means a real invalidation, so producers
+ /// predating this field are unaffected. `skip_serializing_if` keeps `false`
+ /// off the wire, so serialized real invalidations (including DLQ replays)
+ /// stay byte-compatible with pre-shadow consumers and Python's
+ /// `extra="forbid"` model.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub shadow: bool,
}
impl FlagsCacheInvalidation {
@@ -52,6 +63,7 @@ impl FlagsCacheInvalidation {
team_id,
operation: Operation::Invalidate,
emitted_at,
+ shadow: false,
}
}
}
@@ -60,6 +72,10 @@ fn version_1() -> u8 {
1
}
+fn is_false(value: &bool) -> bool {
+ !*value
+}
+
/// Reject any `version` other than 1. A future schema change bumps this
/// deliberately, alongside the dual-producer/dual-consumer rollout the module
/// docs call for.
diff --git a/rust/feature-flags/src/flags/cache_shadow.rs b/rust/feature-flags/src/flags/cache_shadow.rs
new file mode 100644
index 000000000000..5508c1c91a98
--- /dev/null
+++ b/rust/feature-flags/src/flags/cache_shadow.rs
@@ -0,0 +1,942 @@
+//! Shadow-compare support for the `flags-cache-builder` consumer.
+//!
+//! 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.
+//!
+//! The diff covers all three top-level payload keys, because all three feed the
+//! serve path (`flag_definitions_cache.rs` evaluates from `flags`,
+//! `evaluation_metadata`, and `cohorts` as cached, with no read-time repair):
+//!
+//! - `flags`: per-flag comparison mirroring the Python verifier's definition of
+//! parity (`verify_team_flags` in `products/feature_flags/backend/flags_cache.py`)
+//! — flag-set equality by id, field-level comparison, missing-in-cache and
+//! stale-in-cache detection, an unevaluable stale row tolerated, and `filters`
+//! exempted when both sides agree the flag is unevaluable (the writers blank
+//! those; entries predating blanking still hold the full blob).
+//! - `evaluation_metadata`: full value comparison, not just the presence check
+//! the Python verifier does. That verifier compares Python-written state
+//! against a Python DB read, so its metadata can't disagree with itself; here
+//! the Rust reimplementation of dependency staging is exactly what's under test.
+//! - `cohorts`: per-cohort comparison by id, for the same reason — the Rust
+//! cohort BFS is a reimplementation that can truncate or diverge, and the
+//! serve path evaluates cohort-filtered flags from this cached array. A live
+//! entry with no `cohorts` key predates the field and is skipped, since the
+//! service falls back to its own cohort load for such entries.
+//!
+//! Parity is per team, not per byte: both sides are deserialized through the
+//! same typed models before comparing, so JSON key order, absent-vs-null
+//! optional fields, and serialization formatting can never register as
+//! mismatches. Unlike the Python verifier's "compare only DB-side keys" rule
+//! (which tolerates stale extra keys in raw cache JSON — the typed round-trip
+//! already drops those), the field loop here walks the union of both sides'
+//! 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 common_types::TeamId;
+use serde::Deserialize;
+
+use crate::cohorts::cohort_models::Cohort;
+use crate::flags::cache_builder::is_evaluable;
+use crate::flags::flag_models::{
+ EvaluationMetadata, FeatureFlag, FeatureFlagId, HypercacheFlagsWrapper,
+};
+
+/// The slice of a live cache entry the shadow diff reads. Deserialized leniently
+/// (unknown fields are ignored; `evaluation_metadata` and `cohorts` may be
+/// absent in entries predating them) so an old-shape entry surfaces as a
+/// semantic mismatch or a skip below rather than a parse failure.
+#[derive(Debug, Deserialize)]
+pub struct ShadowLiveEntry {
+ #[serde(default)]
+ pub flags: Vec<FeatureFlag>,
+ #[serde(default)]
+ pub evaluation_metadata: Option<EvaluationMetadata>,
+ #[serde(default)]
+ pub cohorts: Option<Vec<Cohort>>,
+}
+
+/// One issue class per diff entry; used as the `issue_type` metric label, so the
+/// set must stay small and static.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ShadowIssueType {
+ /// Live entry has no `evaluation_metadata` key (pre-metadata entry shape).
+ MissingEvaluationMetadata,
+ /// Live entry's `evaluation_metadata` value differs from the fresh build's.
+ EvaluationMetadataMismatch,
+ /// Flag present in the fresh build but absent from the live entry.
+ MissingInCache,
+ /// Evaluable flag present in the live entry but absent from the fresh build.
+ StaleInCache,
+ /// Flag present on both sides with differing field values.
+ FieldMismatch,
+ /// Cohort present in the fresh build but absent from the live entry.
+ CohortMissingInCache,
+ /// Cohort present in the live entry but absent from the fresh build.
+ CohortStaleInCache,
+ /// Cohort present on both sides with differing field values.
+ CohortFieldMismatch,
+}
+
+impl ShadowIssueType {
+ pub fn as_label(&self) -> &'static str {
+ match self {
+ Self::MissingEvaluationMetadata => "missing_evaluation_metadata",
+ Self::EvaluationMetadataMismatch => "evaluation_metadata_mismatch",
+ Self::MissingInCache => "missing_in_cache",
+ Self::StaleInCache => "stale_in_cache",
+ Self::FieldMismatch => "field_mismatch",
+ Self::CohortMissingInCache => "cohort_missing_in_cache",
+ Self::CohortStaleInCache => "cohort_stale_in_cache",
+ Self::CohortFieldMismatch => "cohort_field_mismatch",
+ }
+ }
+}
+
+/// One semantic difference between the fresh build and the live entry.
+#[derive(Debug, Clone)]
+pub struct ShadowDiff {
+ pub issue_type: ShadowIssueType,
+ /// What differs: `"flag 42 (checkout)"` or `"cohort 7"`. `None` for
+ /// team-level issues (the evaluation-metadata ones).
+ pub subject: Option<String>,
+ /// Differing field names; populated for the field-mismatch issue types.
+ pub fields: Vec<String>,
+ /// Content hash of the disagreement, used by `MismatchTracker` to decide
+ /// whether the *same* mismatch persisted across two consecutive shadow
+ /// builds. Hashing the values (not just the subject + issue type) keeps an
+ /// edit session — where each save races Python's rebuild with *different*
+ /// content — from ever counting as a repeat.
+ fingerprint: u64,
+}
+
+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()
+}
+
+fn diff(
+ issue_type: ShadowIssueType,
+ subject: String,
+ built: Option<&serde_json::Value>,
+ cached: Option<&serde_json::Value>,
+ fields: Vec<String>,
+) -> ShadowDiff {
+ ShadowDiff {
+ issue_type,
+ fingerprint: fingerprint(issue_type, Some(&subject), built, cached),
+ subject: Some(subject),
+ fields,
+ }
+}
+
+/// Field names whose values differ between two serialized objects, over the
+/// union of both sides' keys (see the module doc for why the union), skipping
+/// `skip_key` when given. Sorted for deterministic logs and fingerprints.
+fn differing_fields(
+ built: &serde_json::Value,
+ cached: &serde_json::Value,
+ skip_key: Option<&str>,
+) -> Vec<String> {
+ let (Some(built_map), Some(cached_map)) = (built.as_object(), cached.as_object()) else {
+ return Vec::new();
+ };
+ let mut fields: Vec<String> = built_map
+ .keys()
+ .chain(cached_map.keys().filter(|k| !built_map.contains_key(*k)))
+ .filter(|key| Some(key.as_str()) != skip_key)
+ .filter(|key| built_map.get(*key) != cached_map.get(*key))
+ .cloned()
+ .collect();
+ fields.sort_unstable();
+ fields
+}
+
+/// Semantically diff a fresh build against the live cache entry. Empty result
+/// means parity across all three payload keys.
+pub fn diff_live_entry(built: &HypercacheFlagsWrapper, live: &ShadowLiveEntry) -> Vec<ShadowDiff> {
+ // Mirrors the Python verifier's MISSING_EVALUATION_METADATA early return:
+ // an entry that old predates the current payload shape, so a per-flag diff
+ // would only bury the actual finding.
+ let Some(live_metadata) = &live.evaluation_metadata else {
+ return vec![ShadowDiff {
+ issue_type: ShadowIssueType::MissingEvaluationMetadata,
+ subject: None,
+ fields: Vec::new(),
+ fingerprint: fingerprint(ShadowIssueType::MissingEvaluationMetadata, None, None, None),
+ }];
+ };
+
+ let mut diffs: Vec<ShadowDiff> = Vec::new();
+
+ if *live_metadata != built.evaluation_metadata {
+ let built_value = serde_json::to_value(&built.evaluation_metadata).unwrap_or_default();
+ let cached_value = serde_json::to_value(live_metadata).unwrap_or_default();
+ diffs.push(ShadowDiff {
+ issue_type: ShadowIssueType::EvaluationMetadataMismatch,
+ subject: None,
+ fields: differing_fields(&built_value, &cached_value, None),
+ fingerprint: fingerprint(
+ ShadowIssueType::EvaluationMetadataMismatch,
+ None,
+ Some(&built_value),
+ Some(&cached_value),
+ ),
+ });
+ }
+
+ diffs.extend(diff_flags(&built.flags, &live.flags));
+
+ // A live entry without the `cohorts` key predates the field; the service
+ // falls back to its own cohort load for such entries, so there is nothing
+ // wrong being served from it and nothing to compare.
+ if let Some(live_cohorts) = &live.cohorts {
+ let built_cohorts = built.cohorts.as_deref().unwrap_or(&[]);
+ diffs.extend(diff_cohorts(built_cohorts, live_cohorts));
+ }
+
+ diffs
+}
+
+fn diff_flags(built: &[FeatureFlag], live: &[FeatureFlag]) -> Vec<ShadowDiff> {
+ let built_by_id: HashMap<FeatureFlagId, &FeatureFlag> =
+ built.iter().map(|f| (f.id, f)).collect();
+ let cached_by_id: HashMap<FeatureFlagId, &FeatureFlag> =
+ live.iter().map(|f| (f.id, f)).collect();
+
+ let mut diffs: Vec<(FeatureFlagId, ShadowDiff)> = Vec::new();
+
+ for flag in built {
+ let subject = format!("flag {} ({})", flag.id, flag.key);
+ match cached_by_id.get(&flag.id) {
+ None => {
+ let built_value = serde_json::to_value(flag).unwrap_or_default();
+ diffs.push((
+ flag.id,
+ diff(
+ ShadowIssueType::MissingInCache,
+ subject,
+ Some(&built_value),
+ None,
+ Vec::new(),
+ ),
+ ));
+ }
+ Some(cached) => {
+ if let Some(d) = compare_flag_fields(flag, cached) {
+ diffs.push((flag.id, d));
+ }
+ }
+ }
+ }
+
+ for flag in live {
+ if built_by_id.contains_key(&flag.id) {
+ continue;
+ }
+ // An unevaluable cached row is invisible to the matcher, so its
+ // presence is not drift — same tolerance as the Python verifier.
+ if !is_evaluable(flag) {
+ continue;
+ }
+ let cached_value = serde_json::to_value(flag).unwrap_or_default();
+ diffs.push((
+ flag.id,
+ diff(
+ ShadowIssueType::StaleInCache,
+ format!("flag {} ({})", flag.id, flag.key),
+ None,
+ Some(&cached_value),
+ Vec::new(),
+ ),
+ ));
+ }
+
+ diffs.sort_by_key(|(id, _)| *id);
+ diffs.into_iter().map(|(_, d)| d).collect()
+}
+
+/// Field-level comparison of one flag present on both sides. `filters` is
+/// exempt when both sides agree the flag is unevaluable — only the cache
+/// writers blank filters, and entries predating blanking still hold the full
+/// blob the matcher never reads.
+fn compare_flag_fields(built: &FeatureFlag, cached: &FeatureFlag) -> Option<ShadowDiff> {
+ let built_value = serde_json::to_value(built).unwrap_or_default();
+ let cached_value = serde_json::to_value(cached).unwrap_or_default();
+ let both_unevaluable = !is_evaluable(built) && !is_evaluable(cached);
+ let skip = both_unevaluable.then_some("filters");
+
+ let fields = differing_fields(&built_value, &cached_value, skip);
+ if fields.is_empty() {
+ return None;
+ }
+ Some(diff(
+ ShadowIssueType::FieldMismatch,
+ format!("flag {} ({})", built.id, built.key),
+ Some(&built_value),
+ Some(&cached_value),
+ fields,
+ ))
+}
+
+/// Per-cohort comparison by id, order-insensitive (the Rust builder sorts by
+/// id; Python appends in load order). No unevaluable tolerance: both writers
+/// emit exactly the referenced set, so any set or field difference is drift.
+fn diff_cohorts(built: &[Cohort], live: &[Cohort]) -> Vec<ShadowDiff> {
+ let built_by_id: HashMap<i32, &Cohort> = built.iter().map(|c| (c.id, c)).collect();
+ let cached_by_id: HashMap<i32, &Cohort> = live.iter().map(|c| (c.id, c)).collect();
+
+ let mut diffs: Vec<(i32, ShadowDiff)> = Vec::new();
+
+ for cohort in built {
+ let subject = format!("cohort {}", cohort.id);
+ match cached_by_id.get(&cohort.id) {
+ None => {
+ let built_value = serde_json::to_value(cohort).unwrap_or_default();
+ diffs.push((
+ cohort.id,
+ diff(
+ ShadowIssueType::CohortMissingInCache,
+ subject,
+ Some(&built_value),
+ None,
+ Vec::new(),
+ ),
+ ));
+ }
+ Some(cached) => {
+ let built_value = serde_json::to_value(cohort).unwrap_or_default();
+ let cached_value = serde_json::to_value(cached).unwrap_or_default();
+ let fields = differing_fields(&built_value, &cached_value, None);
+ if !fields.is_empty() {
+ diffs.push((
+ cohort.id,
+ diff(
+ ShadowIssueType::CohortFieldMismatch,
+ subject,
+ Some(&built_value),
+ Some(&cached_value),
+ fields,
+ ),
+ ));
+ }
+ }
+ }
+ }
+
+ for cohort in live {
+ if built_by_id.contains_key(&cohort.id) {
+ continue;
+ }
+ let cached_value = serde_json::to_value(cohort).unwrap_or_default();
+ diffs.push((
+ cohort.id,
+ diff(
+ ShadowIssueType::CohortStaleInCache,
+ format!("cohort {}", cohort.id),
+ None,
+ Some(&cached_value),
+ Vec::new(),
+ ),
+ ));
+ }
+
+ diffs.sort_by_key(|(id, _)| *id);
+ diffs.into_iter().map(|(_, d)| d).collect()
+}
+
+/// The tracker's judgement on one shadow build's diffs: which mismatches were
+/// also present (same fingerprint) on the team's previous shadow build — those
+/// count — and which are first sightings, suppressed as probable races against
+/// Python's own rebuild of the team.
+#[derive(Debug, Default)]
+pub struct ShadowObservation {
+ pub confirmed: Vec<ShadowDiff>,
+ pub first_sight: Vec<ShadowDiff>,
+}
+
+impl ShadowObservation {
+ pub fn is_match(&self) -> bool {
+ self.confirmed.is_empty() && self.first_sight.is_empty()
+ }
+}
+
+struct PendingMismatch {
+ fingerprints: HashSet<u64>,
+ recorded_at: Instant,
+}
+
+/// 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;
+
+/// 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.
+pub struct MismatchTracker {
+ ttl: Duration,
+ pending: HashMap<TeamId, PendingMismatch>,
+}
+
+impl MismatchTracker {
+ pub fn new(ttl: Duration) -> Self {
+ Self {
+ ttl,
+ pending: HashMap::new(),
+ }
+ }
+
+ /// 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);
+ }
+
+ if diffs.is_empty() {
+ self.pending.remove(&team_id);
+ return 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,
+ },
+ );
+
+ match prior {
+ Some(previous) => {
+ let (confirmed, first_sight) = diffs
+ .into_iter()
+ .partition(|d| previous.contains(&d.fingerprint));
+ ShadowObservation {
+ confirmed,
+ first_sight,
+ }
+ }
+ None => ShadowObservation {
+ confirmed: Vec::new(),
+ first_sight: diffs,
+ },
+ }
+ }
+}
+
+/// Render diffs for a log line, capped in entries and bytes: at full shadow
+/// volume an unbounded dump of a large team's field diffs would swamp the
+/// log pipeline.
+pub fn summarize_diffs(diffs: &[ShadowDiff], max_entries: usize, max_bytes: usize) -> String {
+ let mut out = String::new();
+ let mut rendered = 0;
+ for diff in diffs.iter().take(max_entries) {
+ let label = diff.issue_type.as_label();
+ let head = match &diff.subject {
+ Some(subject) => format!("{subject}: {label}"),
+ None => label.to_string(),
+ };
+ let entry = if diff.fields.is_empty() {
+ head
+ } else {
+ format!("{head}[{}]", diff.fields.join(","))
+ };
+ let separator = if out.is_empty() { 0 } else { 2 };
+ if out.len() + separator + entry.len() > max_bytes {
+ break;
+ }
+ if !out.is_empty() {
+ out.push_str("; ");
+ }
+ out.push_str(&entry);
+ rendered += 1;
+ }
+ if rendered < diffs.len() {
+ out.push_str(&format!("; +{} more", diffs.len() - rendered));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::{Duration, Instant};
+
+ use serde_json::json;
+
+ use super::*;
+
+ fn flag_from_json(value: serde_json::Value) -> FeatureFlag {
+ serde_json::from_value(value).expect("flag json must parse")
+ }
+
+ fn base_flag_json(id: i32) -> serde_json::Value {
+ json!({
+ "id": id,
+ "team_id": 1,
+ "key": format!("flag-{id}"),
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100.0}]},
+ "active": true,
+ "deleted": false,
+ "has_experiment": false,
+ })
+ }
+
+ fn base_cohort_json(id: i32) -> serde_json::Value {
+ json!({
+ "id": id,
+ "team_id": 1,
+ "name": format!("cohort-{id}"),
+ "deleted": false,
+ "filters": {"properties": {"type": "OR", "values": []}},
+ "is_calculating": false,
+ "is_static": false,
+ "errors_calculating": 0,
+ "groups": [],
+ })
+ }
+
+ fn cohort_from_json(value: serde_json::Value) -> Cohort {
+ serde_json::from_value(value).expect("cohort json must parse")
+ }
+
+ fn wrapper(flags: Vec<FeatureFlag>) -> HypercacheFlagsWrapper {
+ HypercacheFlagsWrapper {
+ flags,
+ evaluation_metadata: EvaluationMetadata::default(),
+ cohorts: Some(Vec::new()),
+ }
+ }
+
+ fn live(flags: Vec<FeatureFlag>) -> ShadowLiveEntry {
+ ShadowLiveEntry {
+ flags,
+ evaluation_metadata: Some(EvaluationMetadata::default()),
+ cohorts: Some(Vec::new()),
+ }
+ }
+
+ fn issue_types(diffs: &[ShadowDiff]) -> Vec<ShadowIssueType> {
+ diffs.iter().map(|d| d.issue_type).collect()
+ }
+
+ #[test]
+ fn identical_sides_match() {
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let cached = live(vec![flag_from_json(base_flag_json(1))]);
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn key_order_only_difference_is_a_match() {
+ // Same content, keys in a different order and rollout as int vs float —
+ // parity is semantic, not byte-for-byte.
+ let built = wrapper(vec![flag_from_json(json!({
+ "id": 1,
+ "team_id": 1,
+ "key": "flag-1",
+ "active": true,
+ "deleted": false,
+ "has_experiment": false,
+ "filters": {"groups": [{"rollout_percentage": 100.0, "properties": []}]},
+ }))]);
+ let cached: ShadowLiveEntry = serde_json::from_value(json!({
+ "evaluation_metadata": {
+ "dependency_stages": [],
+ "flags_with_missing_deps": [],
+ "transitive_deps": {},
+ },
+ "cohorts": [],
+ "flags": [{
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
+ "has_experiment": false,
+ "deleted": false,
+ "active": true,
+ "key": "flag-1",
+ "team_id": 1,
+ "id": 1,
+ }],
+ }))
+ .expect("live entry must parse");
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn null_optional_field_matches_absent_field() {
+ // Python's serializer can emit explicit nulls where the typed model
+ // omits the key; both deserialize to None, so this must not be drift.
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let mut cached_json = base_flag_json(1);
+ cached_json["filters"]["payloads"] = serde_json::Value::Null;
+ cached_json["evaluation_runtime"] = serde_json::Value::Null;
+ let cached = live(vec![flag_from_json(cached_json)]);
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn field_change_reports_field_mismatch_with_field_names() {
+ 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!(50.0);
+ cached_json["has_experiment"] = json!(true);
+ let cached = live(vec![flag_from_json(cached_json)]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(issue_types(&diffs), vec![ShadowIssueType::FieldMismatch]);
+ assert_eq!(diffs[0].fields, vec!["filters", "has_experiment"]);
+ assert_eq!(diffs[0].subject.as_deref(), Some("flag 1 (flag-1)"));
+ }
+
+ #[test]
+ fn built_none_field_against_cached_value_is_a_mismatch() {
+ // The typed model omits None fields on serialize, so a union-of-keys
+ // walk is required to see a cached-only value like this one.
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let mut cached_json = base_flag_json(1);
+ cached_json["bucketing_identifier"] = json!("device_id");
+ let cached = live(vec![flag_from_json(cached_json)]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(issue_types(&diffs), vec![ShadowIssueType::FieldMismatch]);
+ assert_eq!(diffs[0].fields, vec!["bucketing_identifier"]);
+ }
+
+ #[test]
+ fn missing_flag_reports_missing_in_cache() {
+ let built = wrapper(vec![
+ flag_from_json(base_flag_json(1)),
+ flag_from_json(base_flag_json(2)),
+ ]);
+ let cached = live(vec![flag_from_json(base_flag_json(1))]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(issue_types(&diffs), vec![ShadowIssueType::MissingInCache]);
+ assert_eq!(diffs[0].subject.as_deref(), Some("flag 2 (flag-2)"));
+ }
+
+ #[test]
+ fn stale_active_flag_reports_stale_in_cache() {
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let cached = live(vec![
+ flag_from_json(base_flag_json(1)),
+ flag_from_json(base_flag_json(2)),
+ ]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(issue_types(&diffs), vec![ShadowIssueType::StaleInCache]);
+ assert_eq!(diffs[0].subject.as_deref(), Some("flag 2 (flag-2)"));
+ }
+
+ #[test]
+ fn stale_unevaluable_flag_is_tolerated() {
+ // Matcher-invisible rows aren't drift — mirrors the Python verifier.
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let mut stale = base_flag_json(2);
+ stale["active"] = json!(false);
+ let cached = live(vec![
+ flag_from_json(base_flag_json(1)),
+ flag_from_json(stale),
+ ]);
+
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn blanked_filters_on_unevaluable_flag_are_tolerated() {
+ // Fresh build blanks unevaluable filters; a live entry predating
+ // blanking still holds the full blob. Both agree the flag is
+ // unevaluable, so `filters` is exempt.
+ let mut built_json = base_flag_json(1);
+ built_json["active"] = json!(false);
+ built_json["filters"] = json!({"groups": []});
+ let mut cached_json = base_flag_json(1);
+ cached_json["active"] = json!(false);
+ let built = wrapper(vec![flag_from_json(built_json)]);
+ let cached = live(vec![flag_from_json(cached_json)]);
+
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn active_disagreement_still_reports() {
+ // The blanked-filters exemption requires both sides unevaluable; a
+ // disagreement about `active` itself is always drift.
+ let mut cached_json = base_flag_json(1);
+ cached_json["active"] = json!(false);
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let cached = live(vec![flag_from_json(cached_json)]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(issue_types(&diffs), vec![ShadowIssueType::FieldMismatch]);
+ assert!(diffs[0].fields.contains(&"active".to_string()));
+ }
+
+ #[test]
+ fn missing_evaluation_metadata_short_circuits() {
+ let built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ let cached = ShadowLiveEntry {
+ flags: vec![],
+ evaluation_metadata: None,
+ cohorts: Some(Vec::new()),
+ };
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(
+ issue_types(&diffs),
+ vec![ShadowIssueType::MissingEvaluationMetadata]
+ );
+ assert_eq!(diffs[0].subject, None);
+ }
+
+ #[test]
+ fn evaluation_metadata_value_difference_reports() {
+ // The Python verifier only checks presence; here the Rust dependency
+ // staging is under test, so the value must match too.
+ let mut built = wrapper(vec![flag_from_json(base_flag_json(1))]);
+ built.evaluation_metadata = EvaluationMetadata {
+ dependency_stages: vec![vec![1]],
+ flags_with_missing_deps: vec![],
+ transitive_deps: [(1, Default::default())].into(),
+ };
+ let mut cached = live(vec![flag_from_json(base_flag_json(1))]);
+ cached.evaluation_metadata = Some(EvaluationMetadata {
+ dependency_stages: vec![vec![1]],
+ flags_with_missing_deps: vec![1],
+ transitive_deps: [(1, Default::default())].into(),
+ });
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(
+ issue_types(&diffs),
+ vec![ShadowIssueType::EvaluationMetadataMismatch]
+ );
+ assert_eq!(diffs[0].fields, vec!["flags_with_missing_deps"]);
+ assert_eq!(diffs[0].subject, None);
+ }
+
+ #[test]
+ fn equal_evaluation_metadata_matches_regardless_of_map_order() {
+ // transitive_deps is a map and stages are sorted by construction, so
+ // equal metadata built independently must compare equal.
+ let metadata = || EvaluationMetadata {
+ dependency_stages: vec![vec![1, 2]],
+ flags_with_missing_deps: vec![],
+ transitive_deps: [(1, Default::default()), (2, Default::default())].into(),
+ };
+ let mut built = wrapper(vec![]);
+ built.evaluation_metadata = metadata();
+ let mut cached = live(vec![]);
+ cached.evaluation_metadata = Some(metadata());
+
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn cohort_field_difference_reports_with_field_names() {
+ let mut built = wrapper(vec![]);
+ built.cohorts = Some(vec![cohort_from_json(base_cohort_json(7))]);
+ let mut cached_json = base_cohort_json(7);
+ cached_json["filters"] = json!({"properties": {"type": "AND", "values": []}});
+ let mut cached = live(vec![]);
+ cached.cohorts = Some(vec![cohort_from_json(cached_json)]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(
+ issue_types(&diffs),
+ vec![ShadowIssueType::CohortFieldMismatch]
+ );
+ assert_eq!(diffs[0].fields, vec!["filters"]);
+ assert_eq!(diffs[0].subject.as_deref(), Some("cohort 7"));
+ }
+
+ #[test]
+ fn cohort_set_differences_report_missing_and_stale() {
+ // A truncated Rust cohort BFS shows up as cohort_missing_in_cache on
+ // the live side or stale on the built side — both must be visible.
+ let mut built = wrapper(vec![]);
+ built.cohorts = Some(vec![
+ cohort_from_json(base_cohort_json(1)),
+ cohort_from_json(base_cohort_json(2)),
+ ]);
+ let mut cached = live(vec![]);
+ cached.cohorts = Some(vec![
+ cohort_from_json(base_cohort_json(1)),
+ cohort_from_json(base_cohort_json(3)),
+ ]);
+
+ let diffs = diff_live_entry(&built, &cached);
+ assert_eq!(
+ issue_types(&diffs),
+ vec![
+ ShadowIssueType::CohortMissingInCache,
+ ShadowIssueType::CohortStaleInCache,
+ ]
+ );
+ assert_eq!(diffs[0].subject.as_deref(), Some("cohort 2"));
+ assert_eq!(diffs[1].subject.as_deref(), Some("cohort 3"));
+ }
+
+ #[test]
+ fn cohort_null_optional_field_matches_absent_field() {
+ // Python's _serialize_cohort emits explicit nulls for empty optionals;
+ // the typed model omits them. Not drift.
+ let mut cached_json = base_cohort_json(7);
+ cached_json["description"] = serde_json::Value::Null;
+ cached_json["query"] = serde_json::Value::Null;
+ let mut built = wrapper(vec![]);
+ built.cohorts = Some(vec![cohort_from_json(base_cohort_json(7))]);
+ let mut cached = live(vec![]);
+ cached.cohorts = Some(vec![cohort_from_json(cached_json)]);
+
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ #[test]
+ fn live_entry_without_cohorts_key_skips_cohort_compare() {
+ // Entries predating the cohorts field carry none; the service falls
+ // back to its own cohort load for them, so absence is not drift.
+ let mut built = wrapper(vec![]);
+ built.cohorts = Some(vec![cohort_from_json(base_cohort_json(1))]);
+ let mut cached = live(vec![]);
+ cached.cohorts = None;
+
+ assert!(diff_live_entry(&built, &cached).is_empty());
+ }
+
+ fn 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["has_experiment"] = json!(true);
+ let cached = live(vec![flag_from_json(cached_json)]);
+ 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();
+
+ let first = tracker.observe(7, mismatch_diffs(), now);
+ assert!(first.confirmed.is_empty());
+ assert_eq!(first.first_sight.len(), 1);
+
+ let second = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(60));
+ 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();
+
+ tracker.observe(7, mismatch_diffs(), now);
+ let clean = tracker.observe(7, Vec::new(), now + Duration::from_secs(30));
+ assert!(clean.is_match());
+
+ // The earlier sighting no longer counts — mismatch starts over.
+ let after = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(60));
+ 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();
+
+ tracker.observe(7, mismatch_diffs(), now);
+ let late = tracker.observe(7, mismatch_diffs(), now + Duration::from_secs(101));
+ assert!(late.confirmed.is_empty());
+ assert_eq!(late.first_sight.len(), 1);
+ }
+
+ #[test]
+ 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 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));
+ 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();
+
+ tracker.observe(7, mismatch_diffs(), now);
+ let other_team = tracker.observe(8, mismatch_diffs(), now + Duration::from_secs(60));
+ assert!(other_team.confirmed.is_empty());
+ assert_eq!(other_team.first_sight.len(), 1);
+ }
+
+ #[test]
+ fn summarize_caps_entries_and_reports_remainder() {
+ let diffs = mismatch_diffs();
+ let mut many: Vec<ShadowDiff> = Vec::new();
+ for _ in 0..5 {
+ many.extend(diffs.iter().cloned());
+ }
+
+ let summary = summarize_diffs(&many, 2, 4096);
+ assert_eq!(summary.matches("flag 1").count(), 2);
+ assert!(summary.ends_with("; +3 more"));
+ }
+
+ #[test]
+ fn summarize_caps_bytes() {
+ let diffs = mismatch_diffs();
+ let summary = summarize_diffs(&diffs, 10, 8);
+ assert_eq!(summary, "; +1 more");
+ assert!(summary.len() <= 8 + "; +1 more".len());
+ }
+
+ #[test]
+ fn summarize_renders_fields() {
+ let summary = summarize_diffs(&mismatch_diffs(), 10, 4096);
+ assert_eq!(summary, "flag 1 (flag-1): field_mismatch[has_experiment]");
+ }
+}
diff --git a/rust/feature-flags/src/flags/mod.rs b/rust/feature-flags/src/flags/mod.rs
index 68cbdbd23fc0..eb427eba2021 100644
--- a/rust/feature-flags/src/flags/mod.rs
+++ b/rust/feature-flags/src/flags/mod.rs
@@ -1,5 +1,6 @@
pub mod cache_builder;
pub mod cache_invalidation;
+pub mod cache_shadow;
pub mod cache_writer;
pub mod feature_flag_list;
pub mod flag_analytics;
diff --git a/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1_shadow.json b/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1_shadow.json
new file mode 100644
index 000000000000..4005cf1f2ff5
--- /dev/null
+++ b/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1_shadow.json
@@ -0,0 +1,7 @@
+{
+ "version": 1,
+ "team_id": 12345,
+ "operation": "invalidate",
+ "emitted_at": "2026-04-23T10:37:00.000Z",
+ "shadow": true
+}
diff --git a/rust/feature-flags/tests/flags_cache_invalidation_schema.rs b/rust/feature-flags/tests/flags_cache_invalidation_schema.rs
index 1c091f679824..217e24b2946c 100644
--- a/rust/feature-flags/tests/flags_cache_invalidation_schema.rs
+++ b/rust/feature-flags/tests/flags_cache_invalidation_schema.rs
@@ -12,6 +12,7 @@ use rstest::rstest;
use serde_json::{json, Value};
const FIXTURE: &str = include_str!("fixtures/flags_cache_invalidation_v1.json");
+const SHADOW_FIXTURE: &str = include_str!("fixtures/flags_cache_invalidation_v1_shadow.json");
#[test]
fn fixture_round_trips() {
@@ -20,6 +21,9 @@ fn fixture_round_trips() {
assert_eq!(parsed.version, 1);
assert_eq!(parsed.team_id, 12345);
assert_eq!(parsed.operation, Operation::Invalidate);
+ // A fixture without the field must read as a real invalidation, so producers
+ // predating shadow mode keep exactly today's behavior.
+ assert!(!parsed.shadow);
let expected_emitted_at = "2026-04-23T10:37:00Z"
.parse::<DateTime<Utc>>()
.expect("expected timestamp must parse");
@@ -28,12 +32,39 @@ fn fixture_round_trips() {
// Re-serialize and reparse — the struct must survive a full round-trip even
// though chrono drops the fixture's zero `.000` fractional seconds (both are
// valid ISO 8601; the schema, not the byte formatting, is the contract).
+ let serialized = serde_json::to_string(&parsed).expect("must serialize");
+ // `shadow: false` stays off the wire so real invalidations (including DLQ
+ // replays) remain byte-compatible with the pre-shadow schema.
+ assert!(!serialized.contains("shadow"));
+ let reparsed: FlagsCacheInvalidation = serde_json::from_str(&serialized).expect("must reparse");
+ assert_eq!(reparsed, parsed);
+}
+
+#[test]
+fn shadow_fixture_round_trips() {
+ let parsed: FlagsCacheInvalidation =
+ serde_json::from_str(SHADOW_FIXTURE).expect("shadow fixture must parse");
+
+ assert_eq!(parsed.version, 1);
+ assert_eq!(parsed.team_id, 12345);
+ assert_eq!(parsed.operation, Operation::Invalidate);
+ assert!(parsed.shadow);
+
let reparsed: FlagsCacheInvalidation =
serde_json::from_str(&serde_json::to_string(&parsed).expect("must serialize"))
.expect("must reparse");
assert_eq!(reparsed, parsed);
}
+#[test]
+fn explicit_shadow_false_parses_as_real_invalidation() {
+ let mut payload = valid_base();
+ payload["shadow"] = json!(false);
+ let parsed: FlagsCacheInvalidation =
+ serde_json::from_value(payload).expect("explicit shadow: false must parse");
+ assert!(!parsed.shadow);
+}
+
fn valid_base() -> Value {
json!({
"version": 1,
@@ -51,6 +82,7 @@ fn valid_base() -> Value {
#[case::unknown_operation("operation", json!("clear"))]
#[case::naive_datetime("emitted_at", json!("2026-04-23T10:37:00"))]
#[case::extra_field("unknown_field", json!("oops"))]
+#[case::non_bool_shadow("shadow", json!(1))]
fn rejects_invalid_payload(#[case] field: &str, #[case] value: Value) {
let mut payload = valid_base();
payload[field] = value;