:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(autoresearch): align training anchors to utc midnight like scoring (#112589)
posthog[bot]980996471859
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.mdindex aa7d20e00b7c..e65cfe6397f2 100644--- a/products/autoresearch/backend/dataset/AGENTS.md+++ b/products/autoresearch/backend/dataset/AGENTS.md@@ -11,9 +11,10 @@ Nothing here trains or scores anything. It is the shared vocabulary that `../traA training example is a `(person, T0, label)` triple: pick an anchor time `T0` for a person, then `label = 1` if the target event fires in `[T0, T0 + horizon_days)`.`T0` is a **deterministic hash of `person_id`**, placed at a fixed fraction of the user's `[first_ts, cutoff_ts)` span, so it is stable across runs and spread across the full lookback rather than clustered at the most-recent feasible point — one row per person, sampled once in their history. A `hash % span` remainder would move every time `cutoff_ts` moved with `now()`.+ **`T0` is always a UTC midnight**, because every scoring run cuts off at the start of the prediction date in UTC (`ScoringWindow` in `../inference/scoring.py`). The labeler snaps the anchor (`anchor_ts`, or `now()`) to the UTC midnight at or before it, so `cutoff_ts` (the anchor minus the horizon) is a midnight. The hash picks one of the midnights from the first one after `first_ts` up to `cutoff_ts`, so every T0 has at least one event before it. A T0 at any second would give the features part-day activity and a cutoff hour that scoring never has, and inflate the holdout score. `build_eligible_count_sql()` uses the same snapped cutoff. Models trained this way carry `anchor_alignment: "utc_day"` (`ANCHOR_ALIGNMENT`) in their metrics.For an event-defined population (`performed_event_within_days` with an event, `ever_performed_event`, `ever_performed_target`), `first_ts` is the user's first population event, not their first event of any kind. The other populations still start the span at the first event of any kind.- Three call sites share this module so they cannot drift: the wizard's live estimate (sampled), the trainer (full materialization with fold split), and inference (per-person cutoff = `now()`).+ Three call sites share this module so they cannot drift: the wizard's live estimate (sampled), the trainer (full materialization with fold split), and inference (cutoff = the start of the prediction date in UTC).That is why the training-side `labeled_anchors` CTE (inside `build_training_features_sql()`) and `build_inference_anchors_sql()` live here rather than next to their callers.**Training anchors are case-control sampled above the budget.** `TrainingSample.plan()` keeps every anchor when the labeled population fits `TRAINING_SAMPLE_BUDGET` (`MATERIALIZE_ROW_LIMIT` times `TRAINING_SAMPLE_HEADROOM`), and the SQL is then the unsampled SQL. Above it, the plan keeps every positive and sets the negative sample rate `r` so the expected sample fills the budget. Positives that alone exceed the budget raise `TrainingSampleTooLarge`.@@ -40,10 +41,10 @@ A pipeline definition is declarative. This package is what turns it into SQL.```textpipeline (target, population, horizon, lookback)│- ├─ build_training_features_sql → labeled_anchors CTE: one T0 per person, hashed,+ ├─ build_training_features_sql → labeled_anchors CTE: one T0 per person, hashed to a UTC midnight,│ └─ + labels + fold spread over lookback — the trainer's labeled population│- └─ build_inference_anchors_sql → cutoff = now(), no labels, no folds+ └─ build_inference_anchors_sql → cutoff = UTC day start, no labels, no folds└─ the scorer's population```diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.pyindex aa34a070de77..810ab2c8dd55 100644--- a/products/autoresearch/backend/dataset/labeling.py+++ b/products/autoresearch/backend/dataset/labeling.py@@ -14,13 +14,20 @@ the target event fires in [T0, T0 + horizon_days). Random T0 (rather thanmost-recent-feasible) keeps T0s spread across the full lookback so the modelgeneralises across time, not just the trailing horizon window.+Every T0 falls on a UTC midnight, and the anchor every training window ends at is+snapped to one, because every scoring run cuts off at the start of the prediction+date in UTC. A T0 at a random second would show the features part-day activity and+a cutoff hour that scoring never has, so the holdout score would not predict the+scoring score.+Per-user T0 cascades through the rest of the ML pipeline:- Feature SQL must read events with `timestamp < cutoff_ts` per user, wherecutoff_ts comes from a joined anchors table (the labeled_anchors CTE attraining time, build_inference_anchors_sql at scoring time).- Holdout split is by user (fold = hash(person_id) % 5) so the same personnever appears in both train and holdout.-- Inference re-uses the same feature SQL with anchors = (person_id, now()).+- Inference re-uses the same feature SQL with anchors = (person_id, cutoff), where+ a scoring run's cutoff is the start of the prediction date in UTC.Integer handling notes:- toUnixTimestamp returns UInt32; we cast to Int64 via toInt so subtractions@@ -67,6 +74,16 @@ TARGET_RELATIVE_KINDS = frozenset({"active_not_performed_target", "ever_performe# population-agnostic.IDENTIFIED_USERS_ONLY = True+SECONDS_PER_DAY = 86400++# Models record this in metrics["anchor_alignment"]. A champion without it trained on+# T0s at any second, so its holdout score is not comparable with a model trained here.+ANCHOR_ALIGNMENT = "utc_day"++# The start of the current UTC day, without a timezone-aware function that HogQL could+# resolve in the project timezone.+_UTC_DAY_START_OF_NOW = "fromUnixTimestamp(intDiv(toInt(toUnixTimestamp(now())), 86400) * 86400)"+# The builders here read identity and person properties from `raw_persons` (see# `_person_rows_sql`), never from `person.*` on an events scan, so these modifiers join no# persons table into them. They pin how `person_id` resolves, so the anchors and the agent's@@ -78,6 +95,11 @@ LABELER_QUERY_MODIFIERS = HogQLQueryModifiers()+def utc_day_start(ts: int) -> int:+ """The UTC midnight at or before ``ts`` (unix seconds)."""+ return ts - ts % SECONDS_PER_DAY++def _identified_users_and_clause() -> str:"""`AND person.is_identified` fragment for an events-table WHERE, or '' when thev1 identified-only scope is disabled. The events table must be unaliased at the@@ -725,17 +747,19 @@ def _build_labeled_users_cte(sample_limit caps user_window for fast wizard previews; None = fullmaterialization (trainer).- anchor_ts (unix seconds) is the instant every window ends at; None = now().- Queries that must agree on the anchor set, such as the training features and- the anchor count, bind the same anchor_ts, because each query reads its own- now() and a person at a window edge can fall in one and not the other.+ anchor_ts (unix seconds) sets the instant every window ends at; None = now().+ Either one is snapped to the UTC midnight at or before it, so the label cutoff+ (the anchor minus the horizon) and every T0 are UTC midnights, as the scoring+ cutoff is. Queries that must agree on the anchor set, such as the training+ features and the anchor count, bind the same anchor_ts, because each query reads+ its own now() and a person at a window edge can fall in one and not the other."""training_properties = (training_population or {}).get("properties", []) if training_population else []compiled_filters = _compile_population_filters(training_properties)target_cond, target_values = build_target_condition(target_event=target_event, target_definition=target_definition, team=team)- now_expr = "fromUnixTimestamp({anchor_ts})" if anchor_ts is not None else "now()"+ now_expr = "fromUnixTimestamp({anchor_ts})" if anchor_ts is not None else _UTC_DAY_START_OF_NOWcompiled_kind = _build_population_kind_conditions(training_population, now_expr=now_expr, anchor_mode=True, target_cond=target_cond)@@ -783,16 +807,18 @@ def _build_labeled_users_cte(# ifNull on the label: a property-filtered action predicate is NULL on rows that lack# the property, and a user whose every in-horizon row is NULL must label 0, not NULL.- # T0 sits at a fixed fraction (hash / 2^31) of the user's [first_ts, cutoff_ts) span. A- # `hash % span` remainder would change every time cutoff_ts moved with now(), handing the- # same person a different T0, features, and label on each run. With a member predicate,- # first_ts is the user's first population event, else their first event of any kind.+ # T0 is the UTC midnight at a fixed fraction (hash / 2^31) of the midnights from the first+ # one after first_ts up to cutoff_ts, which is a midnight too. A `hash % span`+ # remainder would change every time cutoff_ts moved, handing the same person a different+ # T0, features, and label on each run. With a member predicate, first_ts is the user's+ # first population event, else their first event of any kind. A first event exactly at+ # midnight must not become T0, because the person would then have no event before T0.cte = f"""WITH user_window AS (SELECTm.person_id AS person_id,- m.first_ts AS first_ts,- m.cutoff_ts AS cutoff_ts,+ intDiv(m.first_ts, 86400) + 1 AS first_day,+ intDiv(m.cutoff_ts, 86400) AS cutoff_day,p.created_ts AS person_created_tsFROM (SELECT@@ -810,9 +836,9 @@ def _build_labeled_users_cte(SELECTperson_id,person_created_ts,- first_ts- + intDiv((cutoff_ts - first_ts) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)- AS t0_ts+ (first_day+ + intDiv((cutoff_day - first_day + 1) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)+ ) * 86400 AS t0_tsFROM user_window),{labeled_cte} AS (@@ -839,7 +865,7 @@ def _build_labeled_users_cte(**compiled_kind.values,}if anchor_ts is not None:- values["anchor_ts"] = anchor_ts+ values["anchor_ts"] = utc_day_start(anchor_ts)if negative_sample_rate < 1.0:values["negative_sample_threshold"] = negative_sample_threshold(negative_sample_rate)cte += f""" ,@@ -911,7 +937,7 @@ def build_eligible_count_sql(Build a HogQL query returning the count of users eligible to be labeled by therandom-T0 labeler — i.e. users in the training_population with at least one memberevent (the population event, or any event when the population names none) before- now - horizon_days. Used as the UI headline number so the wizard reports+ the start of the current UTC day minus horizon_days, the labeler's cutoff. Used as the UI headline number so the wizard reportsthe full population size, not the sampled subset.Returns two columns: ``eligible`` (the v1 headline — restricted to identified@@ -921,22 +947,24 @@ def build_eligible_count_sql("""training_properties = (training_population or {}).get("properties", []) if training_population else []compiled_filters = _compile_population_filters(training_properties)- # Row mode: the target-relative kinds are evaluated as of now() here, which is an+ # Row mode: the target-relative kinds are evaluated as of the day start here, which is an# approximation of the trainer's per-user-at-T0 semantics — acceptable for an# advisory headline count.target_cond, target_values = _target_condition_for(training_population, target_event=target_event, target_definition=target_definition, team=team)- compiled_kind = _build_population_kind_conditions(training_population, target_cond=target_cond)+ compiled_kind = _build_population_kind_conditions(+ training_population, now_expr=_UTC_DAY_START_OF_NOW, target_cond=target_cond+ )row_parts = compiled_filters.event_parts + compiled_kind.where_partsrow_clause = f" AND ({' AND '.join(row_parts)})" if row_parts else ""member_clause = _member_clause(compiled_filters, compiled_kind)- # A member event before now - horizon is the trainer's `first_ts < cutoff_ts`.+ # A member event before the day start minus the horizon is the trainer's `first_ts < cutoff_ts`.members_sql = ("SELECT person_id FROM events"- " WHERE timestamp >= now() - toIntervalDay({lookback})"- f" AND timestamp < now() - toIntervalDay({{horizon}}){_own_events_excluded_clause()}{member_clause}{row_clause}"+ f" WHERE timestamp >= {_UTC_DAY_START_OF_NOW} - toIntervalDay({{lookback}})"+ f" AND timestamp < {_UTC_DAY_START_OF_NOW} - toIntervalDay({{horizon}}){_own_events_excluded_clause()}{member_clause}{row_clause}")persons_sql = _person_rows_sql(members_sql,diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.pyindex 8a86ce942245..839ea1b63f46 100644--- a/products/autoresearch/backend/dataset/test_labeling.py+++ b/products/autoresearch/backend/dataset/test_labeling.py@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom posthog.test.base import (@@ -39,6 +39,7 @@ from products.autoresearch.backend.dataset.labeling import (rolling_rescore_runs,rolling_selection,strip_sql_comments,+ utc_day_start,)from products.autoresearch.backend.query import run_hogql_rows@@ -457,7 +458,7 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):)self.assertNotIn("now()", cte)self.assertIn("fromUnixTimestamp({anchor_ts})", cte)- self.assertEqual(values["anchor_ts"], 1_700_000_000)+ self.assertEqual(values["anchor_ts"], 1_699_920_000)def test_t0_position_does_not_depend_on_a_moving_modulo(self) -> None:cte, _values = _build_labeled_users_cte(@@ -470,10 +471,10 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):sample_limit=None,)self.assertIn(- "intDiv((cutoff_ts - first_ts) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)",+ "intDiv((cutoff_day - first_day + 1) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)",cte,)- self.assertNotIn("% (cutoff_ts - first_ts)", cte)+ self.assertNotIn("% (cutoff_day - first_day", cte)_DAILY_PAGEVIEWS = [("$pageview", days_ago) for days_ago in range(100, 0, -1)]@@ -613,6 +614,64 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)if expected_positives is not None:assert int(rows[0][1]) == expected_positives+ @parameterized.expand([("one_day", 1), ("three_days", 3), ("seven_days", 7)])+ def test_every_t0_is_a_utc_midnight_that_does_not_move_within_the_anchor_day(+ self, _name: str, horizon_days: int+ ) -> None:+ now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())+ day_start = utc_day_start(int(now.timestamp()))+ label_cutoff = day_start - 86400 - horizon_days * 86400+ first_event_ts: dict[str, int] = {}+ for i in range(20):+ distinct_id = f"user_{i}"+ person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], is_identified=True)+ for days_ago in range(40 - i, 0, -1):+ timestamp = now - timedelta(days=days_ago, hours=5, minutes=i)+ _create_event(team=self.team, event="$pageview", distinct_id=distinct_id, timestamp=timestamp)+ first_event_ts[str(person.uuid)] = int((now - timedelta(days=40 - i, hours=5, minutes=i)).timestamp())+ for i in range(20):+ distinct_id = f"midnight_user_{i}"+ person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], is_identified=True)+ first_event_ts[str(person.uuid)] = label_cutoff - 86400+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=distinct_id,+ timestamp=datetime.fromtimestamp(label_cutoff - 86400, tz=UTC),+ )+ flush_persons_and_events()++ def t0s(anchor_ts: int) -> dict[str, int]:+ cte, values = _build_labeled_users_cte(+ target_event="feature_used",+ target_definition=None,+ team=self.team,+ horizon_days=horizon_days,+ lookback_days=90,+ training_population=None,+ sample_limit=None,+ anchor_ts=anchor_ts,+ )+ rows = run_hogql_rows(+ team=self.team,+ query=HogQLQuery(+ query=f"{cte} SELECT person_id, t0_ts FROM labeled_users",+ values=values,+ modifiers=LABELER_QUERY_MODIFIERS,+ ),+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ )+ return {str(person_id): int(t0_ts) for person_id, t0_ts in rows}++ morning = t0s(day_start - 86400 + 2 * 3600)+ afternoon = t0s(day_start - 86400 + 17 * 3600)++ assert len(morning) == 40+ assert afternoon == morning+ for person_id, t0_ts in morning.items():+ assert t0_ts % 86400 == 0+ assert first_event_ts[person_id] < t0_ts <= label_cutoff+def test_negative_sampling_keeps_every_positive_and_the_training_rows_match_the_count(self) -> None:now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())positives = [f"positive_{i}" for i in range(3)]diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.mdindex 6854e62ff780..d4222fa15a51 100644--- a/products/autoresearch/backend/training/AGENTS.md+++ b/products/autoresearch/backend/training/AGENTS.md@@ -41,6 +41,7 @@ The other half is `../inference/`, which consumes what this package produces andThe rollback changes nothing when the candidate is no longer the champion. A scoring run that started with the candidate fails in `_require_still_champion()` before it emits.A recipe-only champion is not checked.A champion whose scheduled scoring runs failed with a repeatable `failure_kind` on the last two prediction dates, with no success after the first of them, is unscorable (`find_unscorable_champion()` in `../inference/failures.py`). Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_unscorable` in the model metrics, and the fit and the scorability check still roll back a candidate that cannot score either. The brief tells the agent the failure kind and the onset date.+ A champion whose metrics lack `anchor_alignment: "utc_day"` was trained on T0s at any second (see `../dataset/AGENTS.md`), so its holdout score is inflated and is no bar. Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_anchor_change`. Every new model records `anchor_alignment`.- `explanation.py`The `model_explanation` contract: `top_features` (at most `MAX_TOP_FEATURES`, each a `name`, a non-negative `importance` and a `direction` of `positive` or `negative`), plus an optional `method` and `note`. The `complete` serializer enforces it and sorts the features strongest first, and the brief states it.Champions written before the contract stored other shapes (`features` or `feature_importances` lists, a `feature` key, `auc_drop_when_shuffled` or `gain` for the importance, prose directions such as `higher -> less likely`). The rows are not backfilled. `normalize_model_explanation()` maps them on read in the facade and drops entries it cannot read, so the API always returns the typed shape.diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.pyindex 0b366531ac60..4fbb0eea25f2 100644--- a/products/autoresearch/backend/training/promotion.py+++ b/products/autoresearch/backend/training/promotion.py@@ -26,6 +26,7 @@ from posthog.hogql.visitor import clear_locationsfrom posthog.models.scoping import team_scopefrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME+from products.autoresearch.backend.dataset.labeling import ANCHOR_ALIGNMENTfrom products.autoresearch.backend.inference.failures import find_unscorable_championfrom products.autoresearch.backend.inference.sandbox import (SandboxInferenceError,@@ -610,6 +611,9 @@ def _finalize_under_lock(# A champion that cannot score serves nothing, so its holdout score is no bar either. The# fit and the scorability check still run, and roll the candidate back if it cannot score.unscorable = find_unscorable_champion(current)+ # A champion trained on T0s at any second has a holdout score from part-day features that+ # scoring never sees, so the score is inflated and no bar for a model trained on UTC days.+ anchor_changed = current is not None and (current.metrics or {}).get("anchor_alignment") != ANCHOR_ALIGNMENTbeats_champion = current is not None and _beats_incumbent(candidate_score, current.holdout_score or 0.0)promotion_reason = ""@@ -619,6 +623,8 @@ def _finalize_under_lock(promotion_reason = "replaced_stub"elif unscorable is not None:promotion_reason = "replaced_unscorable"+ elif anchor_changed:+ promotion_reason = "replaced_anchor_change"elif beats_champion:promotion_reason = "beat_champion"@@ -646,6 +652,7 @@ def _finalize_under_lock("holdout_auc": candidate_score,"source": "agent_recorded","artifact_bundle": bool(artifact_prefix),+ "anchor_alignment": ANCHOR_ALIGNMENT,**({"promotion_reason": promotion_reason} if promotion_reason else {}),},source_training_run=training_run,diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.pyindex 637593fff8ec..2006b64c9ed0 100644--- a/products/autoresearch/backend/training/runner.py+++ b/products/autoresearch/backend/training/runner.py@@ -319,7 +319,7 @@ def build_agent_description(labeler that produces, for each user in the training population, exactly onelabeled example:- T0_user = a per-user deterministic random point in their history+ T0_user = a per-user deterministic random UTC midnight in their historylabel = 1 if {target.inline_ref} fires in [T0_user, T0_user + {pipeline.horizon_days}), else 0Features for each user MUST be computed strictly as of THAT user's T0 — never@@ -369,10 +369,10 @@ def build_agent_description(**Hard rules:**1. Select `FROM {{anchors}} a` — the framework supplies columns `(person_id, cutoff_ts)`.- At training cutoff_ts is per-user T0. At inference cutoff_ts is the start of the prediction- date in UTC (midnight) for every person. Same SQL, two tables. A feature derived from the- cutoff's time of day or hour varies in training but is constant at scoring. It teaches the- model nothing it can use, so it is not worth building.+ At training cutoff_ts is per-user T0, a UTC midnight. At inference cutoff_ts is the start of+ the prediction date in UTC (midnight) for every person. Same SQL, two tables. Both cutoffs+ fall at midnight, so a feature derived from the cutoff's hour or time of day is constant and+ teaches the model nothing. Do not build one.2. Join events with `e.timestamp < fromUnixTimestamp(a.cutoff_ts)` — strict `<`. The leakage guard.3. Window the lookback: `e.timestamp >= fromUnixTimestamp(a.cutoff_ts) - toIntervalDay({{lookback_days}})`.4. Output `a.person_id AS distinct_id` as the FIRST column, always. Then list the feature@@ -431,10 +431,9 @@ def build_agent_description(whole inference population, under a query time limit. A query that passes training can failat scoring, so a feature must earn its cost in AUC.- For long windows, aggregate to daily (or hourly) counts per person in a subquery before- you join. A training cutoff falls at any time of day, so the bucket that holds it also holds- events after it: join only whole buckets (`day < toStartOfDay(fromUnixTimestamp(a.cutoff_ts))`),- and read the part of the cutoff's day before the cutoff from raw events, with the strict `<`- of rule 2.+ you join. Every cutoff is a UTC midnight, so a UTC day bucket never holds events after it:+ bucket with `toStartOfDay(e.timestamp, 'UTC')` and join `day < fromUnixTimestamp(a.cutoff_ts)`.+ Pass `'UTC'`, because without it the day starts in the project timezone.- Keep windows short on high-volume events such as `$pageview`, and filter on event names early.- Read person properties from the snapshot stored on each event, `poe.properties.*`, and takethe latest value before the cutoff (for example `argMax(e.plan, e.timestamp)` over the joineddiff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.pyindex 65536150d932..d43cc11c06ef 100644--- a/products/autoresearch/backend/training/test_promotion.py+++ b/products/autoresearch/backend/training/test_promotion.py@@ -358,6 +358,26 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):if replaced:assert self._champion().metrics["promotion_reason"] == "replaced_unscorable"+ @parameterized.expand([("part_day_anchors", None, True), ("utc_day_anchors", "utc_day", False)])+ def test_a_champion_trained_on_part_day_anchors_is_replaced_below_the_margin(self, _name, alignment, replaced):+ first = self._run()+ self._iteration(first, number=0, holdout=0.95)+ complete_training_run(first)+ champion = self._champion()+ metrics = {key: value for key, value in champion.metrics.items() if key != "anchor_alignment"}+ champion.metrics = {**metrics, **({"anchor_alignment": alignment} if alignment else {})}+ champion.save(update_fields=["metrics"])++ second = self._run()+ self._iteration(second, number=0, holdout=0.89)+ result = complete_training_run(second)++ assert result["promoted"] is replaced+ assert self._champion().holdout_score == (0.89 if replaced else 0.95)+ assert self._champion().metrics["anchor_alignment"] == "utc_day"+ if replaced:+ assert self._champion().metrics["promotion_reason"] == "replaced_anchor_change"+@parameterized.expand([# SQL without {anchors} reads the outcome window whatever the iteration recorded.