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.

60.9 KB
Raw Blame
//! Domain layer: the pinned run — lenient payload parse plus `PinnedRun`'s staged validation into a
//! typed, scannable run. Depends on `chunk`, `condition`, `window`, `ids`, and `cohort-core`.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::str::FromStr;

use chrono_tz::{Tz, UTC};
use cohort_core::day_idx_in_tz;
use cohort_core::eligibility::{CohortEligibility, ExcludedReason};
use cohort_core::filters::tree::{BehavioralLeafConfig, BehavioralValue};
use cohort_core::filters::{CohortId, FilterError, TeamFilters, TeamFiltersBuilder, TeamId};
use cohort_core::leaf_state::select::{pick_state_variant, UnsupportedVariant};
use cohort_core::resolve_tz_or_utc;
use cohort_core::EvictionWindow;
use cohort_core::LeafStateKey;
use serde::{Deserialize, Deserializer};
use serde_json::Value;

use super::chunk::{ChunkDomainError, ChunkSpec};
use super::condition::{EventNameSet, Lookback, PinnedCondition};
use super::ids::{ConditionHash, ConditionHashError, DayIdx, RunId, UtcMillis};
use super::window::{Boundary, SeedDomain};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TriggerKind {
    TeamEnablement,
    CohortCreated,
    CohortEdited,
    DisasterRecovery,
}

impl TriggerKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::TeamEnablement => "team_enablement",
            Self::CohortCreated => "cohort_created",
            Self::CohortEdited => "cohort_edited",
            Self::DisasterRecovery => "disaster_recovery",
        }
    }
}

impl FromStr for TriggerKind {
    type Err = UnknownTriggerKind;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "team_enablement" => Ok(Self::TeamEnablement),
            "cohort_created" => Ok(Self::CohortCreated),
            "cohort_edited" => Ok(Self::CohortEdited),
            "disaster_recovery" => Ok(Self::DisasterRecovery),
            other => Err(UnknownTriggerKind(other.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown backfill trigger {0:?}")]
pub struct UnknownTriggerKind(pub String);

/// The only event `flag_evaluations` stores.
const FLAG_CALLED_EVENT: &str = "$feature_flag_called";

/// Mirrors `FLAG_EVALUATIONS_TTL_DAYS` in `posthog/models/flag_evaluations/sql.py`. The Node fork
/// step in `fork-flag-evaluations-step.ts` mirrors it too. Change all three together.
const FLAG_EVALUATIONS_TTL_DAYS: DayIdx = 92;

/// The ClickHouse table a scan reads.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(try_from = "Value")]
pub enum ScanTable {
    /// Also what a payload without `flag_calls_table` reads as.
    #[default]
    Events,
    FlagEvaluations,
}

impl TryFrom<Value> for ScanTable {
    type Error = String;

    /// A derived enum would also accept a one-key object such as `{"flag_evaluations": null}`.
    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value.as_str() {
            Some("events") => Ok(Self::Events),
            Some("flag_evaluations") => Ok(Self::FlagEvaluations),
            _ => Err(format!("unknown flag_calls_table {value}")),
        }
    }
}

impl ScanTable {
    /// The table name, which is also the `table` metric label.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Events => "events",
            Self::FlagEvaluations => "flag_evaluations",
        }
    }

    /// Whether the TTL may already have dropped rows of `domain`'s day at `now_ms`. The TTL is
    /// `toDate(timestamp)` plus [`FLAG_EVALUATIONS_TTL_DAYS`] days, so the day's first rows expire
    /// that many days after the UTC date of the day's start. A team east of UTC starts its day on the UTC date before. Django pins
    /// `flag_evaluations` only for windows inside the TTL. A chunk can still run or retry days
    /// after Django created its run.
    pub fn past_retention(self, domain: &SeedDomain, now_ms: i64) -> bool {
        match self {
            Self::Events => false,
            Self::FlagEvaluations => {
                day_idx_in_tz(domain.utc_range().start().as_i64(), UTC) + FLAG_EVALUATIONS_TTL_DAYS
                    <= day_idx_in_tz(now_ms, UTC)
            }
        }
    }
}

#[derive(Debug)]
pub struct PinnedRun {
    pub run_id: RunId,
    pub team_id: TeamId,
    pub trigger: TriggerKind,
    pub tz: Tz,
    pub boundary: Boundary,
    pub conditions: Vec<PinnedCondition>,
    pub event_names: EventNameSet,
    pub filters: TeamFilters,
    /// The table the run reads `$feature_flag_called` from. Django pins it per run, so every chunk
    /// and every retry reads the same table even if the organization changes where its flag calls
    /// go.
    pub flag_calls_table: ScanTable,
}

/// Proven coverable: [`PinnedRun::validate`] refuses a run with an uncovered participation.
#[derive(Debug)]
pub struct ValidatedPinnedRun {
    pub run: PinnedRun,
    pub warnings: Vec<PinnedWarning>,
}

/// A run proven `seeding` or `trailing` with an established boundary, ready for pinned-payload
/// validation. The `trigger`/`boundary_at_ms` are already typed and present — the store performs
/// the sole `Option`→value narrowing before building this.
#[derive(Debug)]
pub struct PinnedRunSnapshot {
    pub run_id: RunId,
    pub team_id: TeamId,
    pub trigger: TriggerKind,
    pub timezone: String,
    pub boundary_at_ms: i64,
    pub pinned: Value,
    pub participations: Vec<PinnedParticipation>,
}

#[derive(Debug)]
pub struct PinnedParticipation {
    pub cohort_id: CohortId,
    pub pinned_filters: Value,
    pub state: PinnedParticipationState,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PinnedParticipationState {
    Active,
    Superseded,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PinnedDropReason {
    ActionKeyed,
    AbsentFromFrozenCatalog,
    UnsupportedStateVariant(UnsupportedVariant),
    /// Person runs only: the frozen catalog resolves the hash to a non-person-property leaf.
    VariantMismatch,
}

impl PinnedDropReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ActionKeyed => "action_keyed",
            Self::AbsentFromFrozenCatalog => "absent_from_frozen_catalog",
            Self::UnsupportedStateVariant(_) => "unsupported_state_variant",
            Self::VariantMismatch => "variant_mismatch",
        }
    }
}

impl fmt::Display for PinnedDropReason {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedStateVariant(unsupported) => {
                write!(formatter, "{} ({unsupported})", self.as_str())
            }
            _ => formatter.write_str(self.as_str()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PinnedWarning {
    TimezoneFallback {
        configured: String,
    },
    ConditionDropped {
        cohort_id: CohortId,
        hash: ConditionHash,
        reason: PinnedDropReason,
    },
    ConditionSuperseded {
        cohort_id: CohortId,
        hash: ConditionHash,
    },
    WindowDaysMismatch {
        cohort_id: CohortId,
        hash: ConditionHash,
        pinned: u32,
        derived: u32,
    },
}

/// Whether the *consumer* composes a cohort of this class at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Composability {
    NeverComposed,
    Composable,
}

/// The seeder freezes its catalog with cascade off, so every ref-bearing cohort reads
/// `Excluded(HasCohortRef)` here while the consumer runs with cascade on and composes it. The
/// seeder also holds only the run's own participations, never the referenced cohorts, so
/// `CycleDetected` and `UnresolvedRef` cannot be trusted either. Only the structural exclusions —
/// decided from the tree and the parse flags alone — classify identically in both services.
///
/// Exhaustive rather than defaulted: a new eligibility variant has to decide here rather than
/// silently join the class whose members are pruned away.
///
/// `_STRUCTURAL_EXCLUSIONS` in `products/cohorts/backend/parity/eligibility.py` copies the
/// `NeverComposed` arm for the Django backfill gate, so change both together. A gate that admits a
/// class this arm refuses creates runs the seeder fails whole.
pub(super) const fn composability(eligibility: CohortEligibility) -> Composability {
    match eligibility {
        CohortEligibility::SingleLeaf(_)
        | CohortEligibility::Stage2Composable
        | CohortEligibility::Stage2ComposableRef => Composability::Composable,
        CohortEligibility::Excluded(reason) => match reason {
            ExcludedReason::NotMultiLeaf
            | ExcludedReason::TopLevelNegation
            | ExcludedReason::EmptyGroup
            | ExcludedReason::HasDroppedLeaf => Composability::NeverComposed,
            ExcludedReason::HasCohortRef
            | ExcludedReason::CycleDetected
            | ExcludedReason::UnresolvedRef => Composability::Composable,
        },
    }
}

/// Why one active participation cannot be seeded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UncoveredReason {
    /// No surviving pinned condition names the cohort, so the scan would emit nothing for it.
    NoSurvivingCondition,
    /// The frozen catalog will not compose the cohort. Seeding it is wasted work the processor
    /// discards without a completion marker, which leaves the run stuck in `reconciling`.
    NotComposable,
}

impl UncoveredReason {
    fn as_str(self) -> &'static str {
        match self {
            Self::NoSurvivingCondition => "no pinned condition survives the frozen catalog",
            Self::NotComposable => "the frozen catalog will not compose it",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UncoveredCohort {
    pub cohort_id: CohortId,
    pub reason: UncoveredReason,
    pub catalog_class: Option<&'static str>,
    pub dropped: Vec<(ConditionHash, PinnedDropReason)>,
}

impl fmt::Display for UncoveredCohort {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "cohort {}", self.cohort_id.0)?;
        if let Some(class) = self.catalog_class {
            write!(formatter, " ({class})")?;
        }
        write!(formatter, ": {}", self.reason.as_str())?;
        if self.dropped.is_empty() {
            return Ok(());
        }
        let dropped = self
            .dropped
            .iter()
            .map(|(hash, reason)| format!("{hash} {reason}"))
            .collect::<Vec<_>>()
            .join(", ");
        write!(formatter, ", dropped {dropped}")
    }
}

/// `fail_run` renders this into the run's `error` column, the only surface naming the refused leaf.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UncoveredParticipations(pub Vec<UncoveredCohort>);

impl fmt::Display for UncoveredParticipations {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} active participation(s) cannot be seeded: ",
            self.0.len()
        )?;
        let clauses = self
            .0
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("; ");
        formatter.write_str(&clauses)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum PinnedError {
    #[error("invalid pinned payload: {0}")]
    Payload(#[from] serde_json::Error),
    #[error("unsupported pinned schema version {0}")]
    SchemaVersion(u32),
    #[error("invalid conditionHash {value:?}: {source}")]
    InvalidConditionHash {
        value: String,
        #[source]
        source: ConditionHashError,
    },
    #[error("cohort {0} appears more than once in the pinned participations")]
    DuplicateParticipation(i32),
    #[error("pinned condition names cohort {0}, which is not an active participation")]
    MissingParticipation(i32),
    #[error(transparent)]
    Filters(#[from] FilterError),
    #[error("frozen catalog metadata is incomplete for condition {0}")]
    IncompleteMetadata(ConditionHash),
    #[error("person run has no pinned person_scan_since")]
    MissingPersonScanSince,
    #[error("{0}")]
    UncoveredParticipations(UncoveredParticipations),
    #[error("surviving person conditions exceed the per-seed hash cap: {0}")]
    PersonConditionsOverCap(usize),
}

#[derive(Debug, Deserialize)]
struct PinnedPayload {
    schema_version: u32,
    conditions: Vec<RawPinnedCondition>,
    #[serde(default)]
    flag_calls_table: ScanTable,
}

#[derive(Debug, Deserialize)]
struct RawPinnedCondition {
    cohort_id: i32,
    condition_hash: String,
    value: Option<String>,
    #[serde(default, deserialize_with = "lenient_i32")]
    time_value: Option<i32>,
    #[serde(default, deserialize_with = "lenient_string")]
    time_interval: Option<String>,
    #[serde(default, deserialize_with = "lenient_string")]
    explicit_datetime: Option<String>,
    #[serde(default, deserialize_with = "lenient_string")]
    explicit_datetime_to: Option<String>,
    #[serde(default, deserialize_with = "lenient_string")]
    operator: Option<String>,
    #[serde(default, deserialize_with = "lenient_i32")]
    operator_value: Option<i32>,
    window_days: u32,
    event_name: Option<String>,
    is_action: bool,
}

/// Coerce a JSON scalar to `Some(i32)` only for an integer in `i32` range; anything else
/// (missing, null, string, float, bool, array, object, out-of-range) becomes `None`, never an
/// error. Replicates the former `json_i32` tolerance byte-for-byte — a plain `Option<i32>` would
/// instead reject a mistyped payload Django is allowed to send.
fn lenient_i32<'de, D>(deserializer: D) -> Result<Option<i32>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Value>::deserialize(deserializer)?;
    Ok(value
        .as_ref()
        .and_then(Value::as_i64)
        .and_then(|number| i32::try_from(number).ok()))
}

/// Coerce a JSON scalar to `Some(String)` only for a string; anything else becomes `None`, never
/// an error. Replicates the former `json_string` tolerance byte-for-byte.
fn lenient_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Value>::deserialize(deserializer)?;
    Ok(value.as_ref().and_then(Value::as_str).map(str::to_string))
}

impl PinnedRun {
    pub fn validate(snapshot: PinnedRunSnapshot) -> Result<ValidatedPinnedRun, PinnedError> {
        let payload = parse_payload(snapshot.pinned)?;
        let mut warnings = Vec::new();
        let tz = resolve_timezone(&snapshot.timezone, &mut warnings);
        let boundary = Boundary::new(UtcMillis::new(snapshot.boundary_at_ms), tz);
        let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;
        let conditions = resolve_conditions(payload.conditions, &participation, &mut warnings)?;
        let event_names = EventNameSet::from_conditions(&conditions);
        let covered = conditions
            .iter()
            .map(|condition| condition.cohort_id)
            .collect();
        participation.prove_covered(&covered, &warnings)?;

        Ok(ValidatedPinnedRun {
            run: PinnedRun {
                run_id: snapshot.run_id,
                team_id: snapshot.team_id,
                trigger: snapshot.trigger,
                tz,
                boundary,
                conditions,
                event_names,
                filters: participation.into_filters(),
                flag_calls_table: payload.flag_calls_table,
            },
            warnings,
        })
    }

    /// The one cohort every surviving condition belongs to, or `None` when the run spans several.
    ///
    /// A save-triggered run carries exactly one cohort, and naming it lets `query_log_archive`
    /// attribute the scan's cost to that cohort. A team-enablement run spans the team's cohorts,
    /// where any single id would be a misattribution rather than a partial one.
    pub fn sole_cohort_id(&self) -> Option<CohortId> {
        let mut cohort_ids = self.conditions.iter().map(|condition| condition.cohort_id);
        let first = cohort_ids.next()?;
        cohort_ids
            .all(|cohort_id| cohort_id == first)
            .then_some(first)
    }

    /// The table that holds this run's rows of `event_name`.
    pub fn table_for(&self, event_name: &str) -> ScanTable {
        if event_name == FLAG_CALLED_EVENT {
            self.flag_calls_table
        } else {
            ScanTable::Events
        }
    }

    /// The seed domain for a claimed chunk, after proving the chunk belongs to this run/team. Named
    /// here (not in the store) so the store never references a scan/ClickHouse type — cycle break.
    pub fn domain_for(&self, spec: &ChunkSpec) -> Result<SeedDomain, ChunkDomainError> {
        if self.run_id != spec.lease.run_id() || self.team_id != spec.team_id {
            return Err(ChunkDomainError::RunMismatch {
                chunk_run_id: spec.lease.run_id(),
                chunk_team_id: spec.team_id.0,
                pinned_run_id: self.run_id,
                pinned_team_id: self.team_id.0,
            });
        }
        Ok(SeedDomain::new(spec.day, self.tz, spec.s_chunk)?)
    }
}

fn parse_payload(pinned: Value) -> Result<PinnedPayload, PinnedError> {
    let payload: PinnedPayload = serde_json::from_value(pinned)?;
    if payload.schema_version != 1 {
        return Err(PinnedError::SchemaVersion(payload.schema_version));
    }
    Ok(payload)
}

pub(super) fn resolve_timezone(configured: &str, warnings: &mut Vec<PinnedWarning>) -> Tz {
    let tz = resolve_tz_or_utc(configured);
    if configured.parse::<Tz>().is_err() {
        warnings.push(PinnedWarning::TimezoneFallback {
            configured: configured.to_string(),
        });
    }
    tz
}

/// The participations of a run, indexed for dedup-checked lookup with the frozen filter catalog
/// already built from the active cohorts. Shared with the sibling person-run validation.
pub(super) struct ParticipationSet {
    states: HashMap<CohortId, PinnedParticipationState>,
    filters: TeamFilters,
}

impl ParticipationSet {
    pub(super) fn build(
        team_id: TeamId,
        participations: Vec<PinnedParticipation>,
        tz: Tz,
    ) -> Result<Self, PinnedError> {
        let mut states = HashMap::with_capacity(participations.len());
        let mut builder = TeamFiltersBuilder::default();
        for participation in participations {
            if states
                .insert(participation.cohort_id, participation.state)
                .is_some()
            {
                return Err(PinnedError::DuplicateParticipation(
                    participation.cohort_id.0,
                ));
            }
            if participation.state == PinnedParticipationState::Active {
                builder.add_cohort(
                    participation.cohort_id,
                    team_id,
                    &participation.pinned_filters,
                )?;
            }
        }
        Ok(Self {
            states,
            filters: builder.freeze(tz),
        })
    }

    pub(super) fn state(&self, cohort_id: CohortId) -> Option<PinnedParticipationState> {
        self.states.get(&cohort_id).copied()
    }

    pub(super) fn filters(&self) -> &TeamFilters {
        &self.filters
    }

    /// Every active participation must both keep a surviving pinned condition and be a cohort the
    /// frozen catalog composes. Both are pure functions of the frozen row, so this refusal is
    /// permanent and the run is failed rather than retried.
    pub(super) fn prove_covered(
        &self,
        covered: &HashSet<CohortId>,
        warnings: &[PinnedWarning],
    ) -> Result<(), PinnedError> {
        let uncovered = self.uncovered_from(covered);
        if uncovered.is_empty() {
            return Ok(());
        }
        let payload = uncovered
            .into_iter()
            .map(|(cohort_id, reason)| UncoveredCohort {
                cohort_id,
                reason,
                catalog_class: self
                    .filters
                    .eligibility
                    .get(&cohort_id)
                    .copied()
                    .map(CohortEligibility::metric_class),
                dropped: warnings
                    .iter()
                    .filter_map(|warning| match warning {
                        PinnedWarning::ConditionDropped {
                            cohort_id: dropped_for,
                            hash,
                            reason,
                        } if *dropped_for == cohort_id => Some((*hash, *reason)),
                        _ => None,
                    })
                    .collect(),
            })
            .collect();
        Err(PinnedError::UncoveredParticipations(
            UncoveredParticipations(payload),
        ))
    }

    /// The active cohorts this run cannot seed, ascending. A cohort absent from `covered` has no
    /// surviving condition; one the catalog refuses to compose would be seeded into a reconcile the
    /// processor discards.
    fn uncovered_from(&self, covered: &HashSet<CohortId>) -> Vec<(CohortId, UncoveredReason)> {
        let mut uncovered = self
            .states
            .iter()
            .filter(|(_, state)| **state == PinnedParticipationState::Active)
            .filter_map(|(cohort_id, _)| {
                if !covered.contains(cohort_id) {
                    Some((*cohort_id, UncoveredReason::NoSurvivingCondition))
                } else if self.refuses_to_compose(*cohort_id) {
                    Some((*cohort_id, UncoveredReason::NotComposable))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        uncovered.sort_unstable_by_key(|(cohort_id, _)| *cohort_id);
        uncovered
    }

    /// Whether the consumer would refuse to compose this cohort. The seeder's own catalog cannot
    /// decide the reference classes, so [`composability`] leaves them out and this proof does too.
    fn refuses_to_compose(&self, cohort_id: CohortId) -> bool {
        self.filters
            .eligibility
            .get(&cohort_id)
            .copied()
            .is_some_and(|class| composability(class) == Composability::NeverComposed)
    }

    fn into_filters(self) -> TeamFilters {
        self.filters
    }
}

fn resolve_conditions(
    raw_conditions: Vec<RawPinnedCondition>,
    participation: &ParticipationSet,
    warnings: &mut Vec<PinnedWarning>,
) -> Result<Vec<PinnedCondition>, PinnedError> {
    let mut conditions = Vec::with_capacity(raw_conditions.len());
    for raw in raw_conditions {
        let cohort_id = CohortId(raw.cohort_id);
        let Some(state) = participation.state(cohort_id) else {
            return Err(PinnedError::MissingParticipation(raw.cohort_id));
        };
        let hash = ConditionHash::parse(&raw.condition_hash).map_err(|source| {
            PinnedError::InvalidConditionHash {
                value: raw.condition_hash.clone(),
                source,
            }
        })?;
        if state == PinnedParticipationState::Superseded {
            warnings.push(PinnedWarning::ConditionSuperseded { cohort_id, hash });
            continue;
        }
        let lookback = match derive_lookback(&raw, hash, &participation.filters)? {
            LookbackResolution::Dropped(reason) => {
                warnings.push(PinnedWarning::ConditionDropped {
                    cohort_id,
                    hash,
                    reason,
                });
                continue;
            }
            LookbackResolution::Resolved(lookback) => lookback,
        };
        let derived = derived_window_days(lookback);
        if raw.window_days != derived {
            warnings.push(PinnedWarning::WindowDaysMismatch {
                cohort_id,
                hash,
                pinned: raw.window_days,
                derived,
            });
        }
        let event_name = raw
            .event_name
            .expect("a resolved condition always carries a concrete event name");
        conditions.push(PinnedCondition {
            cohort_id,
            hash,
            event_name,
            lookback,
        });
    }
    Ok(conditions)
}

const fn derived_window_days(lookback: Lookback) -> u32 {
    match lookback {
        Lookback::SlidingDays(days) => days,
        Lookback::SubDay | Lookback::FixedRange { .. } => 0,
    }
}

/// The outcome of resolving one raw condition against the frozen catalog: either a scannable
/// [`Lookback`] to store, or a drop reason surfaced as a warning and never stored.
enum LookbackResolution {
    Resolved(Lookback),
    Dropped(PinnedDropReason),
}

fn derive_lookback(
    raw: &RawPinnedCondition,
    hash: ConditionHash,
    filters: &TeamFilters,
) -> Result<LookbackResolution, PinnedError> {
    if raw.is_action {
        return Ok(LookbackResolution::Dropped(PinnedDropReason::ActionKeyed));
    }
    let Some(value) = raw.value.as_deref().and_then(BehavioralValue::from_wire) else {
        return Ok(LookbackResolution::Dropped(
            PinnedDropReason::AbsentFromFrozenCatalog,
        ));
    };
    // The event name is not hashed into the key, but a condition without one never matched a
    // catalog leaf, so it stays a drop.
    let Some(event_name) = raw.event_name.as_ref() else {
        return Ok(LookbackResolution::Dropped(
            PinnedDropReason::AbsentFromFrozenCatalog,
        ));
    };
    let leaf = BehavioralLeafConfig {
        condition_hash: hash.as_bytes(),
        value,
        event_key: event_name.clone(),
        time_value: raw.time_value,
        operator_value: raw.operator_value,
        time_interval: raw.time_interval.clone(),
        operator: raw.operator.clone(),
        explicit_datetime: raw.explicit_datetime.clone(),
        explicit_datetime_to: raw.explicit_datetime_to.clone(),
        leaf_state_key: LeafStateKey([0; 16]),
        state_variant: None,
        negated: false,
    }
    .with_state_key();
    if let Err(unsupported) = pick_state_variant(&leaf) {
        return Ok(LookbackResolution::Dropped(
            PinnedDropReason::UnsupportedStateVariant(unsupported),
        ));
    }
    // The shape is one the catalog keeps, so a miss here means the pinned scalars differ from the
    // ones the frozen filters were parsed from, not that the leaf was refused.
    let Some(meta) = filters.by_lsk.get(&leaf.leaf_state_key) else {
        return Ok(LookbackResolution::Dropped(
            PinnedDropReason::AbsentFromFrozenCatalog,
        ));
    };
    if meta.condition_hash != hash.as_bytes() {
        return Err(PinnedError::IncompleteMetadata(hash));
    }
    let lookback = match (meta.window, meta.window_days) {
        (Some(EvictionWindow::RelativeDays { days }), _) => Lookback::SlidingDays(days),
        (Some(EvictionWindow::RelativeSeconds { .. }), _) => Lookback::SubDay,
        (Some(EvictionWindow::Explicit { from_day, to_day }), _) => {
            Lookback::FixedRange { from_day, to_day }
        }
        (None, Some(days)) => Lookback::SlidingDays(days),
        (None, None) => return Err(PinnedError::IncompleteMetadata(hash)),
    };
    Ok(LookbackResolution::Resolved(lookback))
}

#[cfg(test)]
pub(crate) mod test_runs {
    use std::collections::BTreeMap;

    use cohort_core::filters::{CohortId, TeamId};
    use serde_json::{json, Value};
    use uuid::Uuid;

    use super::{
        PinnedParticipation, PinnedParticipationState, PinnedRun, PinnedRunSnapshot, ScanTable,
        TriggerKind,
    };
    use crate::domain::ids::RunId;
    use crate::domain::row_filter::test_catalog::event_is;

    /// One `performed_event` condition of a [`run_with`] run. `body` is its bytecode without the
    /// `_H` header.
    pub(crate) struct RunLeaf<'a> {
        pub(crate) cohort_id: i32,
        pub(crate) hash: &'a str,
        pub(crate) event: &'a str,
        pub(crate) body: Vec<Value>,
    }

    pub(crate) fn bytecode(event: &str) -> Value {
        json!(["_H", 1, 32, event, 32, "event", 1, 1, 11])
    }

    pub(crate) fn condition(
        cohort_id: i32,
        hash: &str,
        value: &str,
        event_name: Option<&str>,
        window_days: u32,
    ) -> Value {
        json!({
            "cohort_id": cohort_id,
            "condition_hash": hash,
            "value": value,
            "time_value": null,
            "time_interval": null,
            "explicit_datetime": null,
            "explicit_datetime_to": null,
            "operator": null,
            "operator_value": null,
            "window_days": window_days,
            "event_name": event_name,
            "is_action": event_name.is_none(),
        })
    }

    pub(crate) fn snapshot(
        pinned: Value,
        participations: Vec<PinnedParticipation>,
    ) -> PinnedRunSnapshot {
        PinnedRunSnapshot {
            run_id: RunId(Uuid::nil()),
            team_id: TeamId(2),
            trigger: TriggerKind::TeamEnablement,
            timezone: "UTC".to_string(),
            boundary_at_ms: 1_800_000_000_000,
            pinned,
            participations,
        }
    }

    /// A validated run of team 2 in UTC, pinned to `flag_calls_table`, with every leaf over the
    /// last `window_days` days and every named cohort active.
    pub(crate) fn run_with(
        flag_calls_table: ScanTable,
        window_days: u32,
        leaves: &[RunLeaf<'_>],
    ) -> PinnedRun {
        let mut payload_conditions = Vec::new();
        let mut values_by_cohort: BTreeMap<i32, Vec<Value>> = BTreeMap::new();
        for leaf in leaves {
            let mut raw = condition(
                leaf.cohort_id,
                leaf.hash,
                "performed_event",
                Some(leaf.event),
                window_days,
            );
            raw["time_value"] = json!(window_days);
            raw["time_interval"] = json!("day");
            payload_conditions.push(raw);
            let mut bytecode = vec![json!("_H"), json!(1)];
            bytecode.extend(leaf.body.iter().cloned());
            values_by_cohort
                .entry(leaf.cohort_id)
                .or_default()
                .push(json!({
                    "type": "behavioral",
                    "value": "performed_event",
                    "key": leaf.event,
                    "conditionHash": leaf.hash,
                    "time_value": window_days,
                    "time_interval": "day",
                    "bytecode": bytecode,
                }));
        }
        let participations = values_by_cohort
            .into_iter()
            .map(|(cohort_id, values)| PinnedParticipation {
                cohort_id: CohortId(cohort_id),
                pinned_filters: json!({ "properties": { "type": "AND", "values": values } }),
                state: PinnedParticipationState::Active,
            })
            .collect();
        let event_names = leaves.iter().map(|leaf| leaf.event).collect::<Vec<_>>();
        PinnedRun::validate(snapshot(
            json!({
                "schema_version": 1,
                "flag_calls_table": flag_calls_table.as_str(),
                "conditions": payload_conditions,
                "event_names": event_names,
            }),
            participations,
        ))
        .expect("the fixture run validates")
        .run
    }

    /// A validated `events` run carrying one 7-day `performed_event` condition per
    /// `(cohort, event)` pair. Each hash is the event name padded to 16 characters.
    pub(crate) fn run_over(conditions: &[(i32, &str)]) -> PinnedRun {
        let hashes = conditions
            .iter()
            .map(|(_, event_name)| format!("{event_name:0<16}"))
            .collect::<Vec<_>>();
        let leaves = conditions
            .iter()
            .zip(&hashes)
            .map(|((cohort_id, event), hash)| RunLeaf {
                cohort_id: *cohort_id,
                hash,
                event,
                body: event_is(event),
            })
            .collect::<Vec<_>>();
        run_with(ScanTable::Events, 7, &leaves)
    }
}

#[cfg(test)]
mod tests {
    use super::super::condition_analysis::{ConditionAnalyses, ConditionClass};
    use chrono::NaiveDate;
    use chrono_tz::Australia::Sydney;
    use chrono_tz::UTC;
    use cohort_core::{day_idx_of_naive_date, start_of_day_ms_in_tz};
    use serde_json::json;

    use super::super::ids::SChunkMs;
    use super::test_runs::{bytecode, condition, run_over, snapshot};
    use super::*;

    const BYTECODE: &[Value] = &[];

    #[test]
    fn validation_rejects_unknown_schema_and_malformed_hashes() {
        let filters = json!({ "properties": { "type": "AND", "values": [] } });
        let participation = || PinnedParticipation {
            cohort_id: CohortId(1),
            pinned_filters: filters.clone(),
            state: PinnedParticipationState::Active,
        };
        let unknown = snapshot(
            json!({ "schema_version": 2, "conditions": [], "event_names": [] }),
            vec![participation()],
        );
        assert!(matches!(
            PinnedRun::validate(unknown),
            Err(PinnedError::SchemaVersion(2))
        ));

        for malformed in ["0123456789abcde", "0123456789abcdefg"] {
            let invalid = snapshot(
                json!({
                    "schema_version": 1,
                    "conditions": [condition(1, malformed, "performed_event", Some("x"), 0)],
                    "event_names": ["x"],
                }),
                vec![participation()],
            );
            assert!(matches!(
                PinnedRun::validate(invalid),
                Err(PinnedError::InvalidConditionHash { .. })
            ));
        }
    }

    #[test]
    fn invalid_timezone_falls_back_once_and_keeps_the_run_loadable() {
        let mut input = snapshot(
            json!({ "schema_version": 1, "conditions": [], "event_names": [] }),
            vec![],
        );
        input.timezone = "not/a-zone".to_string();
        let validated = PinnedRun::validate(input).unwrap();
        assert_eq!(validated.run.tz, UTC);
        assert_eq!(
            validated.warnings,
            vec![PinnedWarning::TimezoneFallback {
                configured: "not/a-zone".to_string(),
            }]
        );
    }

    fn pinned_with_flag_calls_table(value: Option<Value>) -> PinnedRunSnapshot {
        let mut pinned = json!({ "schema_version": 1, "conditions": [], "event_names": [] });
        if let Some(value) = value {
            pinned["flag_calls_table"] = value;
        }
        snapshot(pinned, vec![])
    }

    #[test]
    fn the_flag_calls_table_reads_events_when_absent_and_each_known_name_as_itself() {
        for (value, expected) in [
            (None, ScanTable::Events),
            (Some("events"), ScanTable::Events),
            (Some("flag_evaluations"), ScanTable::FlagEvaluations),
        ] {
            let validated =
                PinnedRun::validate(pinned_with_flag_calls_table(value.map(Value::from)))
                    .unwrap_or_else(|error| panic!("{value:?} failed: {error}"));
            assert_eq!(validated.run.flag_calls_table, expected, "{value:?}");
        }
    }

    /// Scanning `events` for a value the seeder cannot read would give a cohort in a
    /// flag-evaluations-only organization an empty history that still counts as backfilled.
    #[test]
    fn a_flag_calls_table_the_seeder_cannot_read_fails_the_run() {
        for value in [
            json!("FLAG_EVALUATIONS"),
            json!(" events"),
            json!(""),
            json!(null),
            json!(1),
            json!(["flag_evaluations"]),
            json!({ "table": "flag_evaluations" }),
            json!({ "flag_evaluations": null }),
        ] {
            let error = PinnedRun::validate(pinned_with_flag_calls_table(Some(value.clone())))
                .map(|validated| validated.run.flag_calls_table)
                .expect_err(&format!("{value} validated"));
            assert!(
                error.to_string().contains("flag_calls_table"),
                "{value}: the error does not name the key: {error}"
            );
        }
    }

    #[test]
    fn a_flag_evaluations_day_is_past_retention_once_the_ttl_reaches_its_first_utc_date() {
        // Sydney's day 1 starts on 1970-01-01 in UTC, the date the TTL counts its first rows from.
        for (tz, expires_ms) in [
            (UTC, start_of_day_ms_in_tz(93, UTC)),
            (Sydney, start_of_day_ms_in_tz(92, UTC)),
        ] {
            let domain = SeedDomain::new(1, tz, SChunkMs(200_000_000)).unwrap();
            for (now_ms, expired) in [(expires_ms - 1, false), (expires_ms, true)] {
                assert_eq!(
                    ScanTable::FlagEvaluations.past_retention(&domain, now_ms),
                    expired,
                    "{tz} at {now_ms}"
                );
                assert!(
                    !ScanTable::Events.past_retention(&domain, now_ms),
                    "{tz} at {now_ms}"
                );
            }
        }
    }

    #[test]
    fn lookbacks_come_from_the_frozen_catalog_across_all_participations() {
        let hashes = [
            "daily00000000000",
            "relative30d00000",
            "absolute00000000",
            "hourly0000000000",
            "action0000000000",
            "secondpart000000",
        ];
        assert!(hashes.iter().all(|hash| hash.len() == 16));
        let first_filters = json!({
            "properties": { "type": "AND", "values": [
                { "type": "behavioral", "value": "performed_event", "key": "daily", "conditionHash": hashes[0], "time_value": 7, "time_interval": "day", "bytecode": bytecode("daily") },
                { "type": "behavioral", "value": "performed_event", "key": "relative", "conditionHash": hashes[1], "explicit_datetime": "-30d", "bytecode": bytecode("relative") },
                { "type": "behavioral", "value": "performed_event", "key": "absolute", "conditionHash": hashes[2], "explicit_datetime": "2026-01-03", "explicit_datetime_to": "2026-01-05", "bytecode": bytecode("absolute") },
                { "type": "behavioral", "value": "performed_event", "key": "hourly", "conditionHash": hashes[3], "time_value": 5, "time_interval": "hour", "bytecode": bytecode("hourly") },
            ]}
        });
        let second_filters = json!({
            "properties": { "type": "AND", "values": [
                { "type": "behavioral", "value": "performed_event_multiple", "key": "second", "conditionHash": hashes[5], "time_value": 14, "time_interval": "day", "operator": "gte", "operator_value": 2, "bytecode": bytecode("second") },
            ]}
        });

        let mut conditions = vec![
            condition(1, hashes[0], "performed_event", Some("daily"), 7),
            condition(1, hashes[1], "performed_event", Some("relative"), 0),
            condition(1, hashes[2], "performed_event", Some("absolute"), 0),
            condition(1, hashes[3], "performed_event", Some("hourly"), 0),
            condition(1, hashes[4], "performed_event", None, 7),
            condition(2, hashes[5], "performed_event_multiple", Some("second"), 14),
        ];
        conditions[0]["time_value"] = json!(7);
        conditions[0]["time_interval"] = json!("day");
        conditions[1]["explicit_datetime"] = json!("-30d");
        conditions[2]["explicit_datetime"] = json!("2026-01-03");
        conditions[2]["explicit_datetime_to"] = json!("2026-01-05");
        conditions[3]["time_value"] = json!(5);
        conditions[3]["time_interval"] = json!("hour");
        conditions[5]["time_value"] = json!(14);
        conditions[5]["time_interval"] = json!("day");
        conditions[5]["operator"] = json!("gte");
        conditions[5]["operator_value"] = json!(2);

        let validated = PinnedRun::validate(snapshot(
            json!({
                "schema_version": 1,
                "conditions": conditions,
                "event_names": ["absolute", "daily", "hourly", "relative", "second"],
            }),
            vec![
                PinnedParticipation {
                    cohort_id: CohortId(1),
                    pinned_filters: first_filters,
                    state: PinnedParticipationState::Active,
                },
                PinnedParticipation {
                    cohort_id: CohortId(2),
                    pinned_filters: second_filters,
                    state: PinnedParticipationState::Active,
                },
            ],
        ))
        .unwrap();

        let day = |year, month, day| {
            day_idx_of_naive_date(NaiveDate::from_ymd_opt(year, month, day).unwrap())
        };
        // The action-keyed condition (`hashes[4]`, no event name) resolves to a drop and is absent
        // from the stored conditions; its `ConditionDropped` warning is asserted below. Its leaf is
        // deliberately not in the pinned filters: a dropped leaf makes the whole cohort
        // `Excluded(HasDroppedLeaf)`, which fails the run before any of this is reached.
        let expected = [
            Lookback::SlidingDays(7),
            Lookback::SlidingDays(30),
            Lookback::FixedRange {
                from_day: Some(day(2026, 1, 3)),
                to_day: Some(day(2026, 1, 5)),
            },
            Lookback::SubDay,
            Lookback::SlidingDays(14),
        ];
        assert_eq!(
            validated
                .run
                .conditions
                .iter()
                .map(|condition| condition.lookback)
                .collect::<Vec<_>>(),
            expected,
        );
        assert!(validated
            .run
            .filters
            .behavioral_by_event_name
            .contains_key("second"));
        assert!(validated
            .warnings
            .contains(&PinnedWarning::WindowDaysMismatch {
                cohort_id: CohortId(1),
                hash: ConditionHash::parse(hashes[1]).unwrap(),
                pinned: 0,
                derived: 30,
            }));
        assert!(validated
            .warnings
            .contains(&PinnedWarning::ConditionDropped {
                cohort_id: CohortId(1),
                hash: ConditionHash::parse(hashes[4]).unwrap(),
                reason: PinnedDropReason::ActionKeyed,
            }));
    }

    #[test]
    fn superseded_participations_are_known_but_excluded_from_the_scan_catalog() {
        let active_hash = "active0000000000";
        let superseded_hash = "superseded000000";
        let filters = |event_name: &str, hash: &str| {
            json!({
                "properties": { "type": "AND", "values": [{
                    "type": "behavioral",
                    "value": "performed_event",
                    "key": event_name,
                    "conditionHash": hash,
                    "time_value": 7,
                    "time_interval": "day",
                    "bytecode": bytecode(event_name),
                }]}
            })
        };
        let mut active_condition =
            condition(1, active_hash, "performed_event", Some("active-event"), 7);
        active_condition["time_value"] = json!(7);
        active_condition["time_interval"] = json!("day");
        let mut superseded_condition = condition(
            2,
            superseded_hash,
            "performed_event",
            Some("superseded-event"),
            7,
        );
        superseded_condition["time_value"] = json!(7);
        superseded_condition["time_interval"] = json!("day");
        let payload = json!({
            "schema_version": 1,
            "conditions": [active_condition, superseded_condition],
            "event_names": ["active-event", "superseded-event"],
        });
        let participations = vec![
            PinnedParticipation {
                cohort_id: CohortId(1),
                pinned_filters: filters("active-event", active_hash),
                state: PinnedParticipationState::Active,
            },
            PinnedParticipation {
                cohort_id: CohortId(2),
                pinned_filters: filters("superseded-event", superseded_hash),
                state: PinnedParticipationState::Superseded,
            },
        ];

        let validated = PinnedRun::validate(snapshot(payload.clone(), participations)).unwrap();
        assert_eq!(validated.run.conditions.len(), 1);
        assert_eq!(validated.run.conditions[0].cohort_id, CohortId(1));
        assert_eq!(validated.run.event_names.as_slice(), &["active-event"]);
        assert!(validated
            .run
            .filters
            .behavioral_by_event_name
            .contains_key("active-event"));
        assert!(!validated
            .run
            .filters
            .behavioral_by_event_name
            .contains_key("superseded-event"));
        assert!(validated
            .warnings
            .contains(&PinnedWarning::ConditionSuperseded {
                cohort_id: CohortId(2),
                hash: ConditionHash::parse(superseded_hash).unwrap(),
            }));

        let unknown = PinnedRun::validate(snapshot(
            payload.clone(),
            vec![PinnedParticipation {
                cohort_id: CohortId(1),
                pinned_filters: filters("active-event", active_hash),
                state: PinnedParticipationState::Active,
            }],
        ));
        assert!(matches!(unknown, Err(PinnedError::MissingParticipation(2))));

        let retired = PinnedRun::validate(snapshot(
            payload,
            vec![
                PinnedParticipation {
                    cohort_id: CohortId(1),
                    pinned_filters: filters("active-event", active_hash),
                    state: PinnedParticipationState::Superseded,
                },
                PinnedParticipation {
                    cohort_id: CohortId(2),
                    pinned_filters: filters("superseded-event", superseded_hash),
                    state: PinnedParticipationState::Superseded,
                },
            ],
        ))
        .expect("a run whose every participation is superseded retires rather than failing");
        assert!(retired.run.conditions.is_empty());
    }

    #[test]
    fn a_partially_covered_run_fails_rather_than_seeding_the_covered_sibling() {
        let covered_hash = "covered000000000";
        let action_hash = "action0000000000";
        let covered_filters = json!({
            "properties": { "type": "AND", "values": [{
                "type": "behavioral",
                "value": "performed_event",
                "key": "covered-event",
                "conditionHash": covered_hash,
                "time_value": 7,
                "time_interval": "day",
                "bytecode": bytecode("covered-event"),
            }]}
        });
        let mut covered_condition =
            condition(1, covered_hash, "performed_event", Some("covered-event"), 7);
        covered_condition["time_value"] = json!(7);
        covered_condition["time_interval"] = json!("day");
        let payload = json!({
            "schema_version": 1,
            "conditions": [
                covered_condition,
                condition(2, action_hash, "performed_event", None, 7),
            ],
            "event_names": ["covered-event"],
        });
        let participations = vec![
            PinnedParticipation {
                cohort_id: CohortId(1),
                pinned_filters: covered_filters,
                state: PinnedParticipationState::Active,
            },
            PinnedParticipation {
                cohort_id: CohortId(2),
                pinned_filters: json!({ "properties": { "type": "AND", "values": [] } }),
                state: PinnedParticipationState::Active,
            },
        ];

        let error = PinnedRun::validate(snapshot(payload, participations)).unwrap_err();
        let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
            panic!("expected an uncovered-participation failure, got {error}");
        };
        assert_eq!(
            uncovered,
            vec![UncoveredCohort {
                cohort_id: CohortId(2),
                reason: UncoveredReason::NoSurvivingCondition,
                catalog_class: Some("excluded_empty_group"),
                dropped: vec![(
                    ConditionHash::parse(action_hash).unwrap(),
                    PinnedDropReason::ActionKeyed,
                )],
            }]
        );
    }

    /// `sole_cohort_id` picks the cohort a scan's `log_comment` is charged to, so it must name one
    /// only when every surviving condition agrees. Naming a cohort on a run that spans two would
    /// charge one cohort for the other's scan cost in `query_log_archive`.
    #[test]
    fn a_cohort_is_named_only_when_every_surviving_condition_shares_it() {
        assert_eq!(
            run_over(&[(1, "alpha"), (1, "beta")]).sole_cohort_id(),
            Some(CohortId(1)),
            "several conditions on one cohort still name that cohort"
        );
        assert_eq!(
            run_over(&[(1, "alpha"), (2, "beta")]).sole_cohort_id(),
            None,
            "a run spanning two cohorts must name neither"
        );
        // A run with nothing left to scan attributes to no cohort. This falls out of `next()?` on
        // an empty iterator rather than from a branch, so it is pinned here on purpose.
        assert_eq!(
            run_over(&[]).sole_cohort_id(),
            None,
            "a run with no surviving conditions must name no cohort"
        );
    }

    /// A validated run classifies the same way every time it is validated. Determinism is what a
    /// later projection pass depends on: a chunk retried on another replica re-validates the same
    /// payload, and two replicas that disagreed about a condition's read set would scan two
    /// different column sets for the same chunk.
    #[test]
    fn a_revalidated_run_classifies_its_conditions_identically() {
        let event_only = "eventonly0000000";
        let projectable = "projectable00000";
        // `properties.plan == 'paid' AND event == 'signup'`, in the compiler's emission order.
        let property_bytecode = json!([
            "_H",
            1,
            32,
            "paid",
            32,
            "plan",
            32,
            "properties",
            1,
            2,
            11,
            32,
            "signup",
            32,
            "event",
            1,
            1,
            11,
            3,
            2
        ]);
        let catalog = json!({
            "properties": { "type": "AND", "values": [
                { "type": "behavioral", "value": "performed_event", "key": "purchase", "conditionHash": event_only, "time_value": 7, "time_interval": "day", "bytecode": bytecode("purchase") },
                { "type": "behavioral", "value": "performed_event", "key": "signup", "conditionHash": projectable, "time_value": 7, "time_interval": "day", "bytecode": property_bytecode },
            ]}
        });
        let payload = || {
            let mut first = condition(1, event_only, "performed_event", Some("purchase"), 7);
            first["time_value"] = json!(7);
            first["time_interval"] = json!("day");
            let mut second = condition(1, projectable, "performed_event", Some("signup"), 7);
            second["time_value"] = json!(7);
            second["time_interval"] = json!("day");
            snapshot(
                json!({
                    "schema_version": 1,
                    "conditions": [first, second],
                    "event_names": ["purchase", "signup"],
                }),
                vec![PinnedParticipation {
                    cohort_id: CohortId(1),
                    pinned_filters: catalog.clone(),
                    state: PinnedParticipationState::Active,
                }],
            )
        };

        let validated = PinnedRun::validate(payload()).unwrap().run;
        let census = ConditionAnalyses::build(&validated.conditions, &validated.filters)
            .census(&validated.conditions);
        assert_eq!(census.count(ConditionClass::EventOnly), 1);
        assert_eq!(census.count(ConditionClass::Projectable), 1);
        assert_eq!(census.count(ConditionClass::FullColumns), 0);
        assert_eq!(census.count(ConditionClass::Unanalyzable), 0);
        assert_eq!(
            census.render_reads(),
            "purchase=[event] signup=[event,properties.plan]"
        );

        let revalidated = PinnedRun::validate(payload()).unwrap().run;
        assert_eq!(
            ConditionAnalyses::build(&revalidated.conditions, &revalidated.filters)
                .census(&revalidated.conditions),
            census
        );
    }

    #[test]
    fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_the_parse() {
        let hash = "lenient000000000";
        // The window comes from `explicit_datetime`, which the mistyped payload keeps, so only the
        // key differs and `pick_state_variant` does not steal the drop label below.
        let catalog = json!({
            "properties": { "type": "AND", "values": [
                { "type": "behavioral", "value": "performed_event", "key": "evt", "conditionHash": hash, "time_value": 7, "time_interval": "day", "explicit_datetime": "-30d", "bytecode": bytecode("evt") },
            ]}
        });
        let validate = |condition: Value| {
            PinnedRun::validate(snapshot(
                json!({ "schema_version": 1, "conditions": [condition], "event_names": ["evt"] }),
                vec![PinnedParticipation {
                    cohort_id: CohortId(1),
                    pinned_filters: catalog.clone(),
                    state: PinnedParticipationState::Active,
                }],
            ))
        };
        let pinned = |time_value: Value, time_interval: Value| {
            let mut raw = condition(1, hash, "performed_event", Some("evt"), 30);
            raw["time_value"] = time_value;
            raw["time_interval"] = time_interval;
            raw["explicit_datetime"] = json!("-30d");
            raw
        };

        // Well-typed scalars resolve against the frozen catalog.
        let resolved = validate(pinned(json!(7), json!("day"))).unwrap();
        assert_eq!(
            resolved
                .run
                .conditions
                .iter()
                .map(|condition| condition.lookback)
                .collect::<Vec<_>>(),
            [Lookback::SlidingDays(30)],
        );

        // Mistyped scalars coerce to None exactly as json_i32/json_string did, so the parse still
        // succeeds where a plain `Option<i32>` would reject the payload. They change the leaf-state
        // key, so the condition misses the catalog. A key miss is not a refused shape, so it keeps
        // `AbsentFromFrozenCatalog`.
        let error = validate(pinned(json!("7"), json!(5))).unwrap_err();
        let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
            panic!("expected an uncovered-participation failure, got {error}");
        };
        assert_eq!(
            uncovered,
            vec![UncoveredCohort {
                cohort_id: CohortId(1),
                reason: UncoveredReason::NoSurvivingCondition,
                catalog_class: Some("single_leaf"),
                dropped: vec![(
                    ConditionHash::parse(hash).unwrap(),
                    PinnedDropReason::AbsentFromFrozenCatalog,
                )],
            }]
        );
    }

    /// A cohort keeping one leaf and losing another is `Excluded(HasDroppedLeaf)`, so the processor
    /// discards its reconcile tile with no completion marker. Coverage read per surviving condition
    /// would call the cohort covered off its kept leaf, seed it, and leave the run stuck in
    /// `reconciling` — the wedge this failure exists to prevent, one stage later.
    #[test]
    fn a_cohort_the_catalog_will_not_compose_fails_the_run_even_with_a_surviving_condition() {
        let kept_hash = "kept000000000000";
        let dropped_hash = "dropped000000000";
        let leaf = |event: &str, hash: &str, code: Value| {
            json!({
                "type": "behavioral",
                "value": "performed_event",
                "key": event,
                "conditionHash": hash,
                "time_value": 7,
                "time_interval": "day",
                "bytecode": code,
            })
        };
        let pinned_condition = |hash: &str, event: &str| {
            let mut raw = condition(1, hash, "performed_event", Some(event), 7);
            raw["time_value"] = json!(7);
            raw["time_interval"] = json!("day");
            raw
        };

        let error = PinnedRun::validate(snapshot(
            json!({
                "schema_version": 1,
                "conditions": [
                    pinned_condition(kept_hash, "kept-event"),
                    pinned_condition(dropped_hash, "dropped-event"),
                ],
                "event_names": ["dropped-event", "kept-event"],
            }),
            vec![PinnedParticipation {
                cohort_id: CohortId(1),
                pinned_filters: json!({
                    "properties": { "type": "AND", "values": [
                        leaf("kept-event", kept_hash, bytecode("kept-event")),
                        // The HogVM refuses an empty program, so the catalog drops this leaf.
                        leaf("dropped-event", dropped_hash, json!(BYTECODE)),
                    ]}
                }),
                state: PinnedParticipationState::Active,
            }],
        ))
        .unwrap_err();

        let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
            panic!("expected an uncovered-participation failure, got {error}");
        };
        assert_eq!(
            uncovered,
            vec![UncoveredCohort {
                cohort_id: CohortId(1),
                reason: UncoveredReason::NotComposable,
                catalog_class: Some("excluded_has_dropped_leaf"),
                dropped: vec![(
                    ConditionHash::parse(dropped_hash).unwrap(),
                    PinnedDropReason::AbsentFromFrozenCatalog,
                )],
            }]
        );
    }

    #[test]
    fn a_windowless_performed_event_leaf_fails_the_run_closed() {
        let hash = "c8236865303eb463";
        let event = "navbar starred item added";
        let participation = PinnedParticipation {
            cohort_id: CohortId(1),
            pinned_filters: json!({
                "properties": { "type": "AND", "values": [{
                    "type": "behavioral",
                    "value": "performed_event",
                    "key": event,
                    "event_type": "events",
                    "negation": false,
                    "conditionHash": hash,
                    "event_filters": [
                        { "key": "item_type", "type": "event", "value": "insight", "operator": "exact" },
                    ],
                    "bytecode": bytecode(event),
                }]}
            }),
            state: PinnedParticipationState::Active,
        };

        let error = PinnedRun::validate(snapshot(
            json!({
                "schema_version": 1,
                "conditions": [condition(1, hash, "performed_event", Some(event), 0)],
                "event_names": [event],
            }),
            vec![participation],
        ))
        .unwrap_err();

        let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
            panic!("expected an uncovered-participation failure, got {error}");
        };
        assert_eq!(
            uncovered,
            vec![UncoveredCohort {
                cohort_id: CohortId(1),
                reason: UncoveredReason::NoSurvivingCondition,
                catalog_class: Some("excluded_has_dropped_leaf"),
                dropped: vec![(
                    ConditionHash::parse(hash).unwrap(),
                    PinnedDropReason::UnsupportedStateVariant(UnsupportedVariant::MissingWindow),
                )],
            }]
        );
    }

    #[test]
    fn the_persisted_failure_names_each_cohort_its_class_its_reason_and_every_dropped_hash() {
        let rendered = UncoveredParticipations(vec![
            UncoveredCohort {
                cohort_id: CohortId(574801),
                reason: UncoveredReason::NoSurvivingCondition,
                catalog_class: Some("excluded_has_dropped_leaf"),
                dropped: vec![(
                    ConditionHash::parse("c8236865303eb463").unwrap(),
                    PinnedDropReason::UnsupportedStateVariant(UnsupportedVariant::MissingWindow),
                )],
            },
            UncoveredCohort {
                cohort_id: CohortId(9),
                reason: UncoveredReason::NoSurvivingCondition,
                catalog_class: Some("excluded_has_dropped_leaf"),
                dropped: Vec::new(),
            },
            UncoveredCohort {
                cohort_id: CohortId(11),
                reason: UncoveredReason::NotComposable,
                catalog_class: Some("excluded_top_level_negation"),
                dropped: Vec::new(),
            },
        ])
        .to_string();

        assert_eq!(
            rendered,
            "3 active participation(s) cannot be seeded: \
             cohort 574801 (excluded_has_dropped_leaf): no pinned condition survives the frozen \
             catalog, dropped c8236865303eb463 unsupported_state_variant \
             (performed_event leaf has no resolvable window); \
             cohort 9 (excluded_has_dropped_leaf): no pinned condition survives the frozen catalog; \
             cohort 11 (excluded_top_level_negation): the frozen catalog will not compose it"
        );
    }
}