Skip to content

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

fix(autoresearch): bind one anchor instant per training materialization (#109983)

posthog[bot]2a59a758f402
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index 3eb5799fcd56..5450a6d7673c 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -593,6 +593,7 @@ def _build_labeled_users_cte(
lookback_days: int,
training_population: dict[str, Any] | None,
sample_limit: int | None,
+ anchor_ts: int | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Build the WITH clause that materialises the labeled_users table:
@@ -610,18 +611,26 @@ def _build_labeled_users_cte(
sample_limit caps user_window for fast wizard previews; None = full
materialization (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.
"""
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
)
- compiled_kind = _build_population_kind_conditions(training_population, anchor_mode=True, target_cond=target_cond)
+ now_expr = "fromUnixTimestamp({anchor_ts})" if anchor_ts is not None else "now()"
+ compiled_kind = _build_population_kind_conditions(
+ training_population, now_expr=now_expr, anchor_mode=True, target_cond=target_cond
+ )
member_clause = _member_clause(compiled_filters, compiled_kind)
superset_clause = f" AND ({' AND '.join(compiled_kind.where_parts)})" if compiled_kind.where_parts else ""
member_scan = (
- "timestamp >= now() - toIntervalDay({lookback})"
- f" AND timestamp < now(){_own_events_excluded_clause()}{member_clause}{superset_clause}"
+ f"timestamp >= {now_expr} - toIntervalDay({{lookback}})"
+ f" AND timestamp < {now_expr}{_own_events_excluded_clause()}{member_clause}{superset_clause}"
)
persons_sql = _person_rows_sql(
f"SELECT person_id FROM events WHERE {member_scan}",
@@ -673,7 +682,7 @@ def _build_labeled_users_cte(
SELECT
person_id,
toInt(toUnixTimestamp(min(timestamp))) AS first_ts,
- toInt(toUnixTimestamp(now() - toIntervalDay({{horizon}}))) AS cutoff_ts
+ toInt(toUnixTimestamp({now_expr} - toIntervalDay({{horizon}}))) AS cutoff_ts
FROM events
WHERE {member_scan}
GROUP BY person_id
@@ -701,8 +710,8 @@ def _build_labeled_users_cte(
), 0) AS positive
FROM events e
INNER JOIN user_t0 u ON e.person_id = u.person_id
- WHERE e.timestamp >= now() - toIntervalDay({{lookback}})
- AND e.timestamp < now(){_own_events_excluded_clause("e.")}{label_scan_clause}
+ WHERE e.timestamp >= {now_expr} - toIntervalDay({{lookback}})
+ AND e.timestamp < {now_expr}{_own_events_excluded_clause("e.")}{label_scan_clause}
GROUP BY u.person_id, u.t0_ts{anchor_having}
)
"""
@@ -713,6 +722,8 @@ def _build_labeled_users_cte(
**compiled_filters.values,
**compiled_kind.values,
}
+ if anchor_ts is not None:
+ values["anchor_ts"] = anchor_ts
return cte, values
@@ -725,6 +736,7 @@ def build_random_t0_labeler_sql(
sample_limit: int | None = None,
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
+ anchor_ts: int | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Build a HogQL query that returns one row of (eligible, positives) for a
@@ -745,6 +757,7 @@ def build_random_t0_labeler_sql(
lookback_days=lookback_days,
training_population=training_population,
sample_limit=sample_limit,
+ anchor_ts=anchor_ts,
)
sql = f"""
{cte}
@@ -989,6 +1002,7 @@ def build_training_features_sql(
training_population: dict[str, Any] | None,
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
+ anchor_ts: int | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Build the composite training-time query:
@@ -1008,6 +1022,7 @@ def build_training_features_sql(
lookback_days=lookback_days,
training_population=training_population,
sample_limit=None,
+ anchor_ts=anchor_ts,
)
anchors_subquery = "(SELECT person_id, t0_ts AS cutoff_ts FROM labeled_anchors)"
substituted_feature_sql = _substitute_anchors(feature_sql, anchors_subquery)
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index 93865c8585d2..6cab0a54f643 100644
--- a/products/autoresearch/backend/dataset/test_labeling.py
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -416,6 +416,21 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):
for fragment in forbidden:
self.assertNotIn(fragment, cte)
+ def test_bound_anchor_replaces_every_now(self) -> None:
+ cte, values = _build_labeled_users_cte(
+ target_event="checkout",
+ target_definition=None,
+ team=None,
+ horizon_days=7,
+ lookback_days=90,
+ training_population={"kind": "ever_performed_event", "event": "signed_up"},
+ sample_limit=None,
+ anchor_ts=1_700_000_000,
+ )
+ self.assertNotIn("now()", cte)
+ self.assertIn("fromUnixTimestamp({anchor_ts})", cte)
+ self.assertEqual(values["anchor_ts"], 1_700_000_000)
+
def test_t0_position_does_not_depend_on_a_moving_modulo(self) -> None:
cte, _values = _build_labeled_users_cte(
target_event="checkout",
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index f8278411eed7..1201fd3ec249 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -1082,7 +1082,13 @@ def materialize_features(
sandbox_id = _resolve_run_sandbox_id(training_run)
team = Team.objects.get(pk=team_id)
try:
- data = materialize_training_data(team=team, pipeline=training_run.pipeline, feature_sql=features_sql, user=user)
+ data = materialize_training_data(
+ team=team,
+ pipeline=training_run.pipeline,
+ feature_sql=features_sql,
+ user=user,
+ anchor_ts=training_run.anchor_ts,
+ )
except (SandboxInferenceError, RecipeValidationError) as exc:
raise AutoresearchConflict(f"Feature materialization failed: {exc}") from exc
if not data.train_rows:
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 4c3897a57ef7..185911e5f11a 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -45,6 +45,8 @@ from dataclasses import field
from decimal import Decimal
from typing import Any, Protocol
+from django.utils import timezone as django_timezone
+
import pandas as pd
import pyarrow as pa
import structlog
@@ -171,11 +173,14 @@ def fit_champion_model(
prefix: str,
bundle: ArtifactBundle | None = None,
user: User | None = None,
+ anchor_ts: int | None = None,
) -> dict[str, Any]:
"""
Train run: fit the champion against the LABELED training population and persist
the resulting ``model.pkl`` under ``prefix``. Idempotent: it overwrites any prior fit.
+ Pass the training run's ``anchor_ts`` so the fit sees the anchor set the agent scored.
+
``predict.py`` runs once against the holdout features before the model is persisted,
so a bundle whose two scripts disagree fails here rather than on the first cadence.
@@ -190,7 +195,9 @@ def fit_champion_model(
acting_user = _resolve_acting_user(team=team, pipeline=pipeline, user=user)
_validate_bundle_feature_sql(bundle)
- data = materialize_training_data(team=team, pipeline=pipeline, feature_sql=bundle.features_sql, user=acting_user)
+ data = materialize_training_data(
+ team=team, pipeline=pipeline, feature_sql=bundle.features_sql, user=acting_user, anchor_ts=anchor_ts
+ )
if not data.train_rows:
raise SandboxInferenceError("No training rows to fit on")
if not data.feature_cols:
@@ -344,14 +351,21 @@ def _feature_lookback_days(pipeline: AutoresearchPipeline) -> int:
def materialize_training_data(
- *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User | None = None
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ feature_sql: str,
+ user: User | None = None,
+ anchor_ts: int | None = None,
) -> MaterializedData:
"""
Train run materialization: the bundle's feature SQL against the LABELED training
anchors (per-user random T0, with __label + __fold). Splits train/holdout by fold
so the bundle never sees __fold. The labeler window is the pipeline's configured
- training_lookback_days.
+ training_lookback_days, ending at ``anchor_ts`` (default: now).
"""
+ if anchor_ts is None:
+ anchor_ts = int(django_timezone.now().timestamp())
feature_sql_resolved = feature_sql.replace("{lookback_days}", str(_feature_lookback_days(pipeline)))
train_sql, train_values = build_training_features_sql(
feature_sql=feature_sql_resolved,
@@ -361,9 +375,10 @@ def materialize_training_data(
horizon_days=pipeline.horizon_days,
lookback_days=pipeline.training_lookback_days,
training_population=pipeline.training_population,
+ anchor_ts=anchor_ts,
)
training_rows = _materialize_rows(team=team, sql=train_sql, values=train_values, user=user)
- expected = count_training_anchors(team=team, pipeline=pipeline, user=user)
+ expected = count_training_anchors(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
_validate_rows_key_one_person(training_rows, source="training feature_sql", expected_count=expected)
# The training wrapper LEFT JOINs the labels onto the feature rows. A feature row
# whose distinct_id matched no anchor comes back with NULL label and fold, and the
@@ -419,10 +434,13 @@ def _materialize_score_data(
return score_rows
-def count_training_anchors(*, team: Team, pipeline: AutoresearchPipeline, user: User | None = None) -> int:
+def count_training_anchors(
+ *, team: Team, pipeline: AutoresearchPipeline, anchor_ts: int, user: User | None = None
+) -> int:
"""
How many labeled anchors the trainer materializes, so feature SQL that drops some of them
- fails: a selection-biased fit and a distorted holdout AUC look valid row by row.
+ fails: a selection-biased fit and a distorted holdout AUC look valid row by row. Pass the
+ ``anchor_ts`` the feature query bound, or the two counts can differ at a window edge.
"""
sql, values = build_random_t0_labeler_sql(
target_event=pipeline.target_event,
@@ -432,6 +450,7 @@ def count_training_anchors(*, team: Team, pipeline: AutoresearchPipeline, user:
lookback_days=pipeline.training_lookback_days,
training_population=pipeline.training_population,
sample_limit=None,
+ anchor_ts=anchor_ts,
)
return _count(team=team, sql=sql, values=values, user=user, what="Training anchor count")
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index 8fa0157a0820..989d94cc38ee 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -684,6 +684,7 @@ def _fetch_training_rows(
*, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User
) -> list[dict[str, Any]]:
"""The recipe's feature SQL against the labeled anchors: one row per person with ``__label`` and ``__fold``."""
+ anchor_ts = int(django_timezone.now().timestamp())
sql, values = build_training_features_sql(
feature_sql=feature_sql,
target_event=pipeline.target_event,
@@ -692,10 +693,11 @@ def _fetch_training_rows(
horizon_days=pipeline.horizon_days,
lookback_days=pipeline.training_lookback_days,
training_population=pipeline.training_population,
+ anchor_ts=anchor_ts,
)
rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Training features"))
try:
- expected = count_training_anchors(team=team, pipeline=pipeline, user=user)
+ expected = count_training_anchors(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
except SandboxInferenceError as exc:
raise InferenceRunError(str(exc)) from exc
_require_one_row_per_person(rows, source="training feature_sql", expected_count=expected)
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index 5932eb2e78a8..201582b88fc4 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -12,7 +12,10 @@ from parameterized import parameterized
from posthog.api.capture import CaptureInternalResult
from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME
-from products.autoresearch.backend.inference import scoring
+from products.autoresearch.backend.inference import (
+ sandbox as sandbox_inference,
+ scoring,
+)
from products.autoresearch.backend.inference.sandbox import _MATERIALIZE_ROW_LIMIT, SandboxScoreResult
from products.autoresearch.backend.inference.scoring import (
InferenceRunError,
@@ -692,6 +695,19 @@ class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):
assert mock_run_hogql.call_args.kwargs["query"].values["cutoff_ts"] == 1_700_000_000
assert count.call_args.kwargs["cutoff_ts"] == 1_700_000_000
+ def test_training_rows_and_anchor_count_bind_one_instant(self):
+ pipeline = self._make_pipeline()
+ with (
+ patch.object(scoring, "run_hogql", return_value=HogQLResult(columns=[], rows=[])) as features_run,
+ patch.object(
+ sandbox_inference, "run_hogql", return_value=HogQLResult(columns=["eligible"], rows=[[0]])
+ ) as count_run,
+ ):
+ _fetch_training_rows(team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user)
+ features_query, count_query = features_run.call_args.kwargs["query"], count_run.call_args.kwargs["query"]
+ assert "now()" not in features_query.query and "now()" not in count_query.query
+ assert features_query.values["anchor_ts"] == count_query.values["anchor_ts"]
+
@parameterized.expand(
[
("duplicate_person", [["p1", 1, 0, 1], ["p1", 2, 1, 2]]),
diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.py
index ff03ae1c4fc2..ae658af1eb1c 100644
--- a/products/autoresearch/backend/inference/test_sandbox_inference.py
+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py
@@ -144,11 +144,21 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):
def test_training_data_splits_folds_and_extracts_feature_cols(self):
pipeline = self._pipeline()
with (
- patch.object(sandbox_inference, "count_training_anchors", return_value=len(_TRAINING_ROWS)),
- patch.object(sandbox_inference, "_materialize_rows", return_value=_TRAINING_ROWS),
+ patch.object(
+ sandbox_inference,
+ "run_hogql",
+ side_effect=[
+ HogQLResult(columns=list(_TRAINING_ROWS[0]), rows=[list(r.values()) for r in _TRAINING_ROWS]),
+ HogQLResult(columns=["eligible", "positives"], rows=[[len(_TRAINING_ROWS), 2]]),
+ ],
+ ) as run_hogql,
):
data = materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")
+ # Each query would read its own now(), so a person at a window edge could be in one and not the other.
+ features_query, count_query = (c.kwargs["query"] for c in run_hogql.call_args_list)
+ assert "now()" not in features_query.query and "now()" not in count_query.query
+ assert features_query.values["anchor_ts"] == count_query.values["anchor_ts"]
assert data.feature_cols == ["events_total", "pageviews"]
assert [r["distinct_id"] for r in data.train_rows] == ["p1", "p2"]
assert [r["distinct_id"] for r in data.holdout_rows] == ["p3"]
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
index 06a3d41a40ed..3f64849d8dea 100644
--- a/products/autoresearch/backend/models.py
+++ b/products/autoresearch/backend/models.py
@@ -324,6 +324,11 @@ class AutoresearchTrainingRun(PipelineScopedModel):
min_value_constraint("iteration_count", 0, "autoresearch_training_run_iteration_count_nonnegative"),
]
+ @property
+ def anchor_ts(self) -> int:
+ """The instant this run labels against, so its materializations and its completion fit share one anchor set."""
+ return int((self.started_at or self.created_at).timestamp())
+
class AutoresearchIteration(PipelineScopedModel):
"""One recipe attempt within a training run."""
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index b373faccde42..5d79e652e52f 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -337,19 +337,24 @@ def _activate_pipeline(pipeline: AutoresearchPipeline) -> None:
pipeline.save(update_fields=["status", "updated_at"])
-def _schedule_champion_fit(*, pipeline: AutoresearchPipeline, prefix: str, training_run_id: str) -> None:
+def _schedule_champion_fit(
+ *, pipeline: AutoresearchPipeline, prefix: str, training_run: AutoresearchTrainingRun
+) -> None:
"""The train run produces the serving artifact: fit the champion and persist model.pkl so
predict runs are pure inference. Deferred to on_commit, because the sandbox and the
object-storage write are side effects that must not run inside the atomic block, and the
fit only makes sense once the row is durably committed. A failure leaves the champion
- without a model.pkl, and every scoring run then fails until a later promotion fits one."""
+ without a model.pkl, and every scoring run then fails until a later promotion fits one.
+ The fit labels at the run's anchor instant, so it sees the anchor set the agent scored."""
+ training_run_id = str(training_run.id)
+ anchor_ts = training_run.anchor_ts
def _fit_after_commit() -> None:
# Every failure is caught, not only SandboxInferenceError: the run is already
# committed, so raising here would report a failed completion for a finished run
# that a retry can only answer with its no-op.
try:
- fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix)
+ fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix, anchor_ts=anchor_ts)
except Exception:
logger.exception("autoresearch_champion_fit_failed", training_run_id=training_run_id, prefix=prefix)
@@ -469,7 +474,7 @@ def _finalize_under_lock(
# A rejected challenger is not fitted: inference reads the champion only, and no path
# promotes a challenger row later, so its fit would cost a sandbox run for nothing.
if artifact_prefix:
- _schedule_champion_fit(pipeline=pipeline, prefix=artifact_prefix, training_run_id=str(training_run.id))
+ _schedule_champion_fit(pipeline=pipeline, prefix=artifact_prefix, training_run=training_run)
return {
"promoted": promoted,
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
index 5e834734c7fa..a0542590d9ca 100644
--- a/products/autoresearch/backend/training/test_promotion.py
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -362,6 +362,19 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
# The next run reads this summary as the champion it has to beat.
assert second.summary["champion_model_class"] == "xgboost.XGBClassifier"
+ def test_champion_fit_labels_at_the_run_anchor_the_agent_scored(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+ with patch("products.autoresearch.backend.training.promotion.fit_champion_model") as fit:
+ with self.captureOnCommitCallbacks(execute=True):
+ complete_training_run(run)
+
+ assert run.started_at is not None
+ assert fit.call_args.kwargs["anchor_ts"] == int(run.started_at.timestamp())
+
def test_a_failed_champion_fit_does_not_fail_a_committed_completion(self):
run = self._run()
self._iteration(run, number=0, holdout=0.8)