: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
feat(autoresearch): run scoring and validation queries as offline batch queries (#110923)
posthog[bot]942f8bed18fe
diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.pyindex 2cb113f9cf23..135210cfd063 100644--- a/products/autoresearch/backend/evaluation/online_validation.py+++ b/products/autoresearch/backend/evaluation/online_validation.py@@ -42,7 +42,7 @@ from products.autoresearch.backend.dataset.labeling import ()from products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_userfrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun-from products.autoresearch.backend.query import HogQLResult, run_hogql+from products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult, QueryContext, run_hogqllogger = structlog.get_logger(__name__)@@ -113,7 +113,11 @@ class _ModelValidation:def run_online_validation_for_pipeline(- pipeline: AutoresearchPipeline, *, user: User | None = None+ pipeline: AutoresearchPipeline,+ *,+ user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,+ claim_deadline: datetime | None = None,) -> list[AutoresearchRun]:"""Validate every matured prediction date that has no completed validation yet.@@ -125,6 +129,13 @@ def run_online_validation_for_pipeline(``calibration_error`` on each model that emitted predictions.``user`` is who HogQL applies access control for; it defaults to the pipeline's creator.+ ``query_context`` is the ClickHouse budget of every query. The Temporal activity passes+ ``BATCH_QUERY``, and the API request path keeps the interactive limit.++ After ``claim_deadline`` the pass claims no more dates, but it always claims at least one,+ so a pass makes progress whatever the deadline. The dates it does not reach stay pending+ for the next pass. The Temporal activity sets the deadline so that the last date it claims+ still finishes inside the attempt timeout."""team = pipeline.teamacting_user = _acting_user(team=team, pipeline=pipeline, user=user)@@ -134,11 +145,22 @@ def run_online_validation_for_pipeline(return []results: list[AutoresearchRun] = []- for item in pending:+ for index, item in enumerate(pending):+ if results and claim_deadline is not None and django_timezone.now() >= claim_deadline:+ logger.info(+ "autoresearch_validation_dates_deferred",+ pipeline_id=str(pipeline.pk),+ dates_deferred=len(pending) - index,+ )+ breakrun = _claim_date(pipeline, item)if run is None:continue- results.append(_validate_claimed_date(team=team, pipeline=pipeline, run=run, pending=item, user=acting_user))+ results.append(+ _validate_claimed_date(+ team=team, pipeline=pipeline, run=run, pending=item, user=acting_user, query_context=query_context+ )+ )return results@@ -293,6 +315,7 @@ def _validate_claimed_date(run: AutoresearchRun,pending: PendingValidationDate,user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> AutoresearchRun:"""Compute realized metrics for every model that emitted predictions on the date, then@@ -302,10 +325,17 @@ def _validate_claimed_date(eligible for the next pass and the other dates in this pass are unaffected."""try:- predictions = _fetch_predictions(team=team, pipeline=pipeline, pending=pending, user=user)+ predictions = _fetch_predictions(+ team=team, pipeline=pipeline, pending=pending, user=user, query_context=query_context+ )n_predicted = sum(len(model.p_y_by_person) for model in predictions.values())realized = _fetch_realized_labels(- team=team, pipeline=pipeline, pending=pending, n_predicted=n_predicted, user=user+ team=team,+ pipeline=pipeline,+ pending=pending,+ n_predicted=n_predicted,+ user=user,+ query_context=query_context,)per_model = {model_id: _ModelValidation(@@ -417,7 +447,12 @@ def _prediction_values(pipeline: AutoresearchPipeline, pending: PendingValidatiodef _fetch_predictions(- *, team: Team, pipeline: AutoresearchPipeline, pending: PendingValidationDate, user: User+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ pending: PendingValidationDate,+ user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> dict[str, _ModelPredictions]:"""``{model_id: predictions}`` for every model the inference runs say scored the date.@@ -449,6 +484,7 @@ def _fetch_predictions(user=user,limit=pending.expected_rows + 1,what="Predictions",+ query_context=query_context,)roles: dict[str, str] = {}@@ -481,7 +517,13 @@ def _fetch_predictions(def _fetch_realized_labels(- *, team: Team, pipeline: AutoresearchPipeline, pending: PendingValidationDate, n_predicted: int, user: User+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ pending: PendingValidationDate,+ n_predicted: int,+ user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> frozenset[str]:"""The predicted persons who performed the pipeline's target inside the outcome window.@@ -512,11 +554,28 @@ def _fetch_realized_labels("window_start": pending.window_start,"window_end": pending.window_end,}- result = _query(team=team, sql=sql, values=values, user=user, limit=n_predicted + 1, what="Realized labels")+ result = _query(+ team=team,+ sql=sql,+ values=values,+ user=user,+ limit=n_predicted + 1,+ what="Realized labels",+ query_context=query_context,+ )return frozenset(str(row[0]) for row in result.rows if row[0])-def _query(*, team: Team, sql: str, values: dict[str, Any], user: User, limit: int, what: str) -> HogQLResult:+def _query(+ *,+ team: Team,+ sql: str,+ values: dict[str, Any],+ user: User,+ limit: int,+ what: str,+ query_context: QueryContext = INTERACTIVE_QUERY,+) -> HogQLResult:"""Run a query as the acting user, fresh, with an explicit bound.@@ -534,6 +593,7 @@ def _query(*, team: Team, sql: str, values: dict[str, Any], user: User, limit: iquery=HogQLQuery(query=bounded_sql, values={**values, "limit": limit}, modifiers=LABELER_QUERY_MODIFIERS),user=user,execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ query_context=query_context,)except Exception as exc:logger.exception("autoresearch_validation_query_failed", team_id=team.pk, what=what)diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.pyindex 20f99c6a4815..2d47ded6b7e7 100644--- a/products/autoresearch/backend/evaluation/test_online_validation.py+++ b/products/autoresearch/backend/evaluation/test_online_validation.py@@ -25,7 +25,7 @@ from products.autoresearch.backend.evaluation.online_validation import (run_online_validation_for_pipeline,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun-from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.query import BATCH_QUERY, HogQLResultfrom products.autoresearch.backend.testing import TeamScopedTestMixinFROZEN_NOW = "2026-09-11T12:00:00Z"@@ -324,7 +324,7 @@ def _fake_hogql("""Answer the prediction query with ``predictions`` and the label query with ``labels``, recording each call."""state = {"labels_failed": False}- def side_effect(*, team, query, user, execution_mode):+ def side_effect(*, team, query, user, execution_mode, query_context):if "argMax" in query.query:return HogQLResult(columns=["model_id", "person_id", "p_y", "emitted_role"], rows=predictions)if fail_labels_once and not state["labels_failed"]:@@ -352,7 +352,7 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"], ["user-1"]])with patch.object(online_validation, "run_hogql", hogql):- runs = run_online_validation_for_pipeline(self.pipeline)+ runs = run_online_validation_for_pipeline(self.pipeline, query_context=BATCH_QUERY)assert [r.status for r in runs] == [AutoresearchRun.Status.COMPLETED]run = runs[0]@@ -370,6 +370,7 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):assert find_pending_validation_dates(self.pipeline) == []prediction_call, label_call = hogql.call_args_list+ assert prediction_call.kwargs["query_context"] == label_call.kwargs["query_context"] == BATCH_QUERYassert prediction_call.kwargs["user"] == self.userassert prediction_call.kwargs["query"].values["limit"] == 5assert prediction_call.kwargs["query"].values["model_ids"] == (str(self.champion.pk),)@@ -414,6 +415,28 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):]assert "Realized labels query failed" in runs[0].error+ @parameterized.expand(+ [+ ("deadline_passed", timedelta(0), ["2026-09-01"], [date(2026, 9, 2)]),+ ("deadline_ahead", timedelta(minutes=1), ["2026-09-01", "2026-09-02"], []),+ ]+ )+ def test_a_claim_deadline_leaves_the_rest_of_the_backlog_pending(+ self, _name, deadline_offset, validated, still_pending+ ):+ _inference_run(self.pipeline, self.champion, date(2026, 9, 2), rows_scored=4)+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"]])++ with patch.object(online_validation, "run_hogql", hogql):+ runs = run_online_validation_for_pipeline(+ self.pipeline, claim_deadline=django_timezone.now() + deadline_offset+ )++ assert [(r.metrics["prediction_date"], r.status) for r in runs] == [+ (d, AutoresearchRun.Status.COMPLETED) for d in validated+ ]+ assert [p.prediction_date for p in find_pending_validation_dates(self.pipeline)] == still_pending+@parameterized.expand([("completed", AutoresearchRun.Status.COMPLETED),diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.mdindex 86616042791c..adc9b109da75 100644--- a/products/autoresearch/backend/inference/AGENTS.md+++ b/products/autoresearch/backend/inference/AGENTS.md@@ -30,6 +30,21 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fitInference rows are checked against the anchor count on both paths (`count_inference_anchors()`), and training rows against the labeled anchor count (`count_training_anchors()`, at the negative sample rate the rows were drawn at), because feature SQL that inner joins or filters a joined table in `WHERE` drops people without any row looking wrong.`_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to one current `distinct_id` through personhog (`get_persons_by_uuids`), never from event history, because an id read off old events can belong to someone else after a merge or split.+## Query budget++Every HogQL query goes through `run_hogql()` in `../query.py` with a `QueryContext`: a limit context, which sets `max_execution_time`, and a ClickHouse workload. The entry point chooses it and passes it down explicitly. No code decides it from where it runs.++| Path | Context | Limit and workload |+| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------- |+| Scoring from `activity_run_inference` (sweep and manual `/score`), both routes, with their anchor and population counts | `BATCH_QUERY` | `QUERY_ASYNC` (`HOGQL_INCREASED_MAX_EXECUTION_TIME`, 600 s), `OFFLINE` |+| Online validation from `activity_run_validation` | `BATCH_QUERY` | `QUERY_ASYNC`, `OFFLINE` |+| `fit_champion_model()` at training completion, `materialize-features`, `/validate`, `/validate_online` | `INTERACTIVE_QUERY` (the default) | `QUERY` (60 s), `DEFAULT` |+| Management commands | `INTERACTIVE_QUERY` (the default) | `QUERY`, `DEFAULT` |++Scoring and validation are batch work that nobody waits on, so they get the batch limit. A path inside a web request keeps the interactive limit, because a 600 s query would outlive the request.+Training stays interactive on purpose: feature SQL that materializes within 60 s at training has ten times that budget at scoring, so the stricter bar is at the gate. When a request path moves to Temporal, give it `BATCH_QUERY`.+The activity timeouts in `../temporal/workflows.py` cover several batch queries in sequence at the full limit. Keep them that way when you add a query to either path.+## The emitted event```textdiff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.pyindex 2911b8471240..051bb224ce8a 100644--- a/products/autoresearch/backend/inference/sandbox.py+++ b/products/autoresearch/backend/inference/sandbox.py@@ -74,7 +74,7 @@ from products.autoresearch.backend.dataset.labeling import (build_training_features_sql,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline-from products.autoresearch.backend.query import run_hogql+from products.autoresearch.backend.query import INTERACTIVE_QUERY, QueryContext, run_hogqlfrom products.autoresearch.backend.training.artifacts import (MAX_ARTIFACT_BYTES,ArtifactBundle,@@ -236,6 +236,7 @@ def score_via_sandbox(model: AutoresearchModel,cutoff_ts: int | None = None,user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> SandboxScoreResult:"""Predict run: score the inference population with the champion's persisted model.@@ -266,7 +267,12 @@ def score_via_sandbox()score_rows = _materialize_score_data(- team=team, pipeline=pipeline, feature_sql=bundle.features_sql, cutoff_ts=cutoff_ts, user=acting_user+ team=team,+ pipeline=pipeline,+ feature_sql=bundle.features_sql,+ cutoff_ts=cutoff_ts,+ user=acting_user,+ query_context=query_context,)n_train = int((model.metrics or {}).get("n_train") or 0)# A population that matches nobody today is a real zero, not a failure: retrying cannot@@ -433,6 +439,7 @@ def _materialize_score_data(feature_sql: str,cutoff_ts: int | None = None,user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> list[dict[str, Any]]:"""Predict run materialization: the bundle's feature SQL against the inference anchors@@ -450,8 +457,12 @@ def _materialize_score_data(target_definition=pipeline.target_definition,team=team,)- score_rows = _materialize_rows(team=team, sql=score_sql, values=score_values, user=user)- expected = count_inference_anchors(team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user)+ score_rows = _materialize_rows(+ team=team, sql=score_sql, values=score_values, user=user, query_context=query_context+ )+ expected = count_inference_anchors(+ team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context+ )_validate_rows_key_one_person(score_rows, source="inference feature_sql", expected_count=expected)logger.info("autoresearch_score_materialized", pipeline_id=str(pipeline.pk), n_score=len(score_rows), cutoff_ts=cutoff_ts@@ -460,14 +471,21 @@ def _materialize_score_data(def measure_training_sample(- *, team: Team, pipeline: AutoresearchPipeline, anchor_ts: int | None = None, user: User | None = None+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ anchor_ts: int | None = None,+ user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> TrainingSample:"""Count the whole labeled population and its positives, and choose the negative sample ratethat fits it under the training budget. The counts are aggregates, so no row cap applies."""sql, values = _labeler_sql(team=team, pipeline=pipeline, anchor_ts=anchor_ts)- row = _count_rows(team=team, sql=sql, values=values, user=user, what="Training population")+ row = _count_rows(+ team=team, sql=sql, values=values, user=user, what="Training population", query_context=query_context+ )population, positives = int(row[0] or 0), int(row[1] or 0)try:return TrainingSample.plan(population=population, positives=positives)@@ -498,6 +516,7 @@ def count_training_anchors(anchor_ts: int | None = None,user: User | None = None,negative_sample_rate: float = 1.0,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> int:"""How many labeled anchors the trainer materializes at ``negative_sample_rate``, so feature SQL@@ -507,11 +526,18 @@ def count_training_anchors(sql, values = _labeler_sql(team=team, pipeline=pipeline, anchor_ts=anchor_ts, negative_sample_rate=negative_sample_rate)- return _count(team=team, sql=sql, values=values, user=user, what="Training anchor count")+ return _count(+ team=team, sql=sql, values=values, user=user, what="Training anchor count", query_context=query_context+ )def count_inference_anchors(- *, team: Team, pipeline: AutoresearchPipeline, cutoff_ts: int | None = None, user: User | None = None+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ cutoff_ts: int | None = None,+ user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> int:"""How many people the inference anchors hold, so a feature query that drops some of them@@ -527,16 +553,37 @@ def count_inference_anchors(team=team,)return _count(- team=team, sql=f"SELECT count() FROM ({anchors_sql.strip()})", values=values, user=user, what="Anchor count"+ team=team,+ sql=f"SELECT count() FROM ({anchors_sql.strip()})",+ values=values,+ user=user,+ what="Anchor count",+ query_context=query_context,)-def _count(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> int:+def _count(+ *,+ team: Team,+ sql: str,+ values: dict[str, Any],+ user: User | None,+ what: str,+ query_context: QueryContext = INTERACTIVE_QUERY,+) -> int:"""Run a query whose first column of its first row is the count the caller wants."""- return int(_count_rows(team=team, sql=sql, values=values, user=user, what=what)[0])+ return int(_count_rows(team=team, sql=sql, values=values, user=user, what=what, query_context=query_context)[0])-def _count_rows(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> list[Any]:+def _count_rows(+ *,+ team: Team,+ sql: str,+ values: dict[str, Any],+ user: User | None,+ what: str,+ query_context: QueryContext = INTERACTIVE_QUERY,+) -> list[Any]:"""Run a query that returns one aggregate row, and return that row."""try:tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)@@ -545,6 +592,7 @@ def _count_rows(*, team: Team, sql: str, values: dict[str, Any], user: User | Noquery=HogQLQuery(query=sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),user=user,execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ query_context=query_context,)except Exception as exc:raise SandboxInferenceError(f"{what} query failed: {exc}") from exc@@ -563,7 +611,12 @@ def _validate_rows_key_one_person(def _materialize_rows(- *, team: Team, sql: str, values: dict[str, Any], user: User | None = None+ *,+ team: Team,+ sql: str,+ values: dict[str, Any],+ user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> list[dict[str, Any]]:"""Run a HogQL query and return rows as dicts, coercing person_id (distinct_id) to str."""bounded_sql = sql.rstrip().rstrip(";") + f"\nLIMIT {_MATERIALIZE_ROW_LIMIT}"@@ -576,6 +629,7 @@ def _materialize_rows(query=HogQLQuery(query=bounded_sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),user=user,execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ query_context=query_context,)except Exception as exc:raise SandboxInferenceError(f"Feature query failed: {exc}") from excdiff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pyindex aa9ac74eba51..c8af45db4f55 100644--- a/products/autoresearch/backend/inference/scoring.py+++ b/products/autoresearch/backend/inference/scoring.py@@ -75,7 +75,7 @@ from products.autoresearch.backend.inference.sandbox import (validate_runnable_feature_sql,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun-from products.autoresearch.backend.query import HogQLResult, run_hogql+from products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult, QueryContext, run_hogqlfrom products.autoresearch.backend.training.recipe_validation import (RecipeValidationError,validate_model_class,@@ -211,6 +211,7 @@ def run_inference_for_pipeline(prediction_date: date | None = None,user: User | None = None,run: AutoresearchRun | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> AutoresearchRun:"""Top-level inference entry point. Creates an AutoresearchRun, scores users,@@ -226,6 +227,9 @@ def run_inference_for_pipeline(``run`` is a row the caller created before it dispatched the scoring, so the callercan return it at once. A retry of the same attempt passes the same row again.++ ``query_context`` is the ClickHouse budget of every scoring query. The Temporal+ activity passes ``BATCH_QUERY``."""window = ScoringWindow.for_date(prediction_date)if run is None:@@ -240,7 +244,9 @@ def run_inference_for_pipeline(try:team = pipeline.teamacting_user = _acting_user(team=team, pipeline=pipeline, user=user)- scored = score_population(team=team, pipeline=pipeline, model=model, window=window, user=acting_user)+ scored = score_population(+ team=team, pipeline=pipeline, model=model, window=window, user=acting_user, query_context=query_context+ )emitted = _emit_predictions(team=team, pipeline=pipeline, model=model, run=run, scored=scored, window=window, user=acting_user)@@ -331,6 +337,7 @@ def score_population(model: AutoresearchModel,window: ScoringWindow,user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> ScoredPopulation:"""Score the inference population with ``model`` and return the rows without emitting.@@ -350,7 +357,9 @@ def score_population(sample rate is applied here, once, so no route can correct twice or not at all."""return _apply_prior_correction(- _score_population_raw(team=team, pipeline=pipeline, model=model, window=window, user=user)+ _score_population_raw(+ team=team, pipeline=pipeline, model=model, window=window, user=user, query_context=query_context+ ))@@ -361,13 +370,21 @@ def _score_population_raw(model: AutoresearchModel,window: ScoringWindow,user: User | None = None,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> ScoredPopulation:_check_prediction_date(team=team, pipeline=pipeline, window=window)acting_user = _acting_user(team=team, pipeline=pipeline, user=user)cutoff_ts = window.cutoff_tsif model.artifact_prefix:- result = score_via_sandbox(team=team, pipeline=pipeline, model=model, cutoff_ts=cutoff_ts, user=acting_user)+ result = score_via_sandbox(+ team=team,+ pipeline=pipeline,+ model=model,+ cutoff_ts=cutoff_ts,+ user=acting_user,+ query_context=query_context,+ )return ScoredPopulation(rows=result.scored_rows, holdout_auc=result.holdout_auc, negative_sample_rate=model.negative_sample_rate)@@ -382,7 +399,9 @@ def _score_population_raw()recipe = model.model_recipe or {}if recipe.get("stub"):- rows = _fetch_stub_feature_rows(team=team, pipeline=pipeline, recipe=recipe, user=acting_user)+ rows = _fetch_stub_feature_rows(+ team=team, pipeline=pipeline, recipe=recipe, user=acting_user, query_context=query_context+ )return ScoredPopulation(rows=_score_rows(rows), holdout_auc=model.holdout_score)feature_sql = str(recipe.get("feature_sql") or "")@@ -390,7 +409,14 @@ def _score_population_raw(validate_runnable_feature_sql(feature_sql, source="Champion recipe feature_sql")except SandboxInferenceError as exc:raise InferenceRunError(str(exc)) from exc- return _score_via_anchors(team=team, pipeline=pipeline, recipe=recipe, cutoff_ts=cutoff_ts, user=acting_user)+ return _score_via_anchors(+ team=team,+ pipeline=pipeline,+ recipe=recipe,+ cutoff_ts=cutoff_ts,+ user=acting_user,+ query_context=query_context,+ )def _emit_predictions(@@ -530,7 +556,15 @@ def _require_still_champion(model: AutoresearchModel) -> None:# ── Queries ────────────────────────────────────────────────────────────────────────-def _query(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> HogQLResult:+def _query(+ *,+ team: Team,+ sql: str,+ values: dict[str, Any],+ user: User | None,+ what: str,+ query_context: QueryContext = INTERACTIVE_QUERY,+) -> HogQLResult:"""Run a person-keyed query as the acting user, fresh, bounded at ``_MATERIALIZE_ROW_LIMIT``.@@ -548,6 +582,7 @@ def _query(*, team: Team, sql: str, values: dict[str, Any], user: User | None, wquery=HogQLQuery(query=bounded_sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),user=user,execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ query_context=query_context,)except Exception as exc:logger.exception("autoresearch_inference_query_failed", team_id=team.pk, what=what)@@ -599,7 +634,12 @@ def _feature_lookback_days(pipeline: AutoresearchPipeline) -> int:def _fetch_stub_feature_rows(- *, team: Team, pipeline: AutoresearchPipeline, recipe: dict[str, Any], user: User+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ recipe: dict[str, Any],+ user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> list[dict[str, Any]]:"""Run a stub recipe's feature SQL restricted to the inference population.@@ -628,8 +668,14 @@ def _fetch_stub_feature_rows(if population is not None:sql = f"SELECT * FROM ({feature_sql}) AS f WHERE f.distinct_id IN ({population.sql})"values = population.values- rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Feature"))- expected = _count_population(team=team, population=population, user=user) if population is not None else None+ rows = _person_rows(+ _query(team=team, sql=sql, values=values, user=user, what="Feature", query_context=query_context)+ )+ expected = (+ _count_population(team=team, population=population, user=user, query_context=query_context)+ if population is not None+ else None+ )_require_one_row_per_person(rows, source="stub feature_sql", expected_count=expected)return rows@@ -666,13 +712,16 @@ def _population_query(return _PopulationQuery(sql=f"SELECT person_id FROM ({anchors_sql.strip()})", values=values)-def _count_population(*, team: Team, population: _PopulationQuery, user: User) -> int:+def _count_population(+ *, team: Team, population: _PopulationQuery, user: User, query_context: QueryContext = INTERACTIVE_QUERY+) -> int:result = _query(team=team,sql=f"SELECT count() FROM ({population.sql})",values=population.values,user=user,what="Population count",+ query_context=query_context,)if len(result.rows) != 1 or not result.rows[0]:raise InferenceRunError("Population count query did not return a single row")@@ -720,6 +769,7 @@ def _score_via_anchors(recipe: dict[str, Any],cutoff_ts: int | None,user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> ScoredPopulation:"""Score with an agent recipe that has no bundle.@@ -733,10 +783,15 @@ def _score_via_anchors("""feature_sql = str(recipe.get("feature_sql") or "").replace("{lookback_days}", str(_feature_lookback_days(pipeline)))training_rows, negative_sample_rate = _fetch_training_rows(- team=team, pipeline=pipeline, feature_sql=feature_sql, user=user+ team=team, pipeline=pipeline, feature_sql=feature_sql, user=user, query_context=query_context)inference_rows = _fetch_inference_rows(- team=team, pipeline=pipeline, feature_sql=feature_sql, cutoff_ts=cutoff_ts, user=user+ team=team,+ pipeline=pipeline,+ feature_sql=feature_sql,+ cutoff_ts=cutoff_ts,+ user=user,+ query_context=query_context,)if not inference_rows:logger.warning("autoresearch_no_inference_rows", pipeline_id=str(pipeline.pk))@@ -754,7 +809,12 @@ def _score_via_anchors(def _fetch_training_rows(- *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ feature_sql: str,+ user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> tuple[list[dict[str, Any]], float]:"""The recipe's feature SQL against the labeled anchors: one row per person with ``__label``@@ -762,7 +822,9 @@ def _fetch_training_rows("""anchor_ts = int(django_timezone.now().timestamp())try:- sample = measure_training_sample(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)+ sample = measure_training_sample(+ team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user, query_context=query_context+ )except SandboxInferenceError as exc:raise InferenceRunError(str(exc)) from excsql, values = build_training_features_sql(@@ -776,7 +838,9 @@ def _fetch_training_rows(anchor_ts=anchor_ts,negative_sample_rate=sample.negative_sample_rate,)- rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Training features"))+ rows = _person_rows(+ _query(team=team, sql=sql, values=values, user=user, what="Training features", query_context=query_context)+ )try:expected = count_training_anchors(team=team,@@ -784,6 +848,7 @@ def _fetch_training_rows(anchor_ts=anchor_ts,user=user,negative_sample_rate=sample.negative_sample_rate,+ query_context=query_context,)except SandboxInferenceError as exc:raise InferenceRunError(str(exc)) from exc@@ -799,7 +864,13 @@ def _fetch_training_rows(def _fetch_inference_rows(- *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, cutoff_ts: int | None, user: User+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ feature_sql: str,+ cutoff_ts: int | None,+ user: User,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> list[dict[str, Any]]:"""The recipe's feature SQL against the inference anchors: one row per eligible person.@@ -817,9 +888,13 @@ def _fetch_inference_rows(target_definition=pipeline.target_definition,team=team,)- rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Inference features"))+ rows = _person_rows(+ _query(team=team, sql=sql, values=values, user=user, what="Inference features", query_context=query_context)+ )try:- expected = count_inference_anchors(team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user)+ expected = count_inference_anchors(+ team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context+ )except SandboxInferenceError as exc:raise InferenceRunError(str(exc)) from exc_require_one_row_per_person(rows, source="inference feature_sql", expected_count=expected)diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.pyindex fa2e5c6d616c..accf350f0bbb 100644--- a/products/autoresearch/backend/inference/test_inference.py+++ b/products/autoresearch/backend/inference/test_inference.py@@ -32,7 +32,7 @@ from products.autoresearch.backend.inference.scoring import (score_population,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun-from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.query import BATCH_QUERY, HogQLResultfrom products.autoresearch.backend.testing import TeamScopedTestMixin_STUB_RECIPE = {@@ -413,10 +413,16 @@ class TestRecipeRouting(TeamScopedTestMixin, BaseTest):scored = ScoredPopulation(rows=[{"distinct_id": "p1", "p_y": 0.5}], holdout_auc=0.66)with patch.object(scoring, "_score_via_anchors", return_value=scored) as anchored:result = score_population(- team=self.team, pipeline=pipeline, model=model, window=ScoringWindow.for_date(), user=self.user+ team=self.team,+ pipeline=pipeline,+ model=model,+ window=ScoringWindow.for_date(),+ user=self.user,+ query_context=BATCH_QUERY,)assert result == ScoredPopulation(rows=[{"distinct_id": "p1", "p_y": 0.5, "p_y_raw": 0.5}], holdout_auc=0.66)anchored.assert_called_once()+ assert anchored.call_args.kwargs["query_context"] == BATCH_QUERY@parameterized.expand([("bundle", "score_via_sandbox"), ("recipe", "_score_via_anchors")])def test_live_run_binds_every_query_to_the_start_of_the_day(self, _name, scorer):@@ -523,9 +529,12 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):)mock_run.side_effect = self._feature_then_count([["user-1"], ["user-3"]], count=2)- rows = _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)+ rows = _fetch_stub_feature_rows(+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user, query_context=BATCH_QUERY+ )assert {r["distinct_id"] for r in rows} == {"user-1", "user-3"}+ assert [call.kwargs["query_context"] for call in mock_run.call_args_list] == [BATCH_QUERY, BATCH_QUERY]sql, values = self._sent(mock_run)assert "f.distinct_id IN (SELECT person_id FROM (SELECT id AS person_id" in sqlassert "argMax(ifNull((properties[{pop_k_0}] = {pop_0}), 0), version) = 1" in sql@@ -720,9 +729,13 @@ class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):feature_sql=_ANCHORS_FEATURE_SQL,cutoff_ts=1_700_000_000,user=self.user,+ query_context=BATCH_QUERY,)assert mock_run_hogql.call_args.kwargs["query"].values["cutoff_ts"] == 1_700_000_000assert count.call_args.kwargs["cutoff_ts"] == 1_700_000_000+ assert (+ mock_run_hogql.call_args.kwargs["query_context"] == count.call_args.kwargs["query_context"] == BATCH_QUERY+ )def test_training_rows_and_anchor_count_bind_one_instant(self):pipeline = self._make_pipeline()@@ -734,8 +747,18 @@ class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):return_value=HogQLResult(columns=["eligible", "positives"], rows=[[0, 0]]),) as count_run,):- _fetch_training_rows(team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user)+ _fetch_training_rows(+ team=self.team,+ pipeline=pipeline,+ feature_sql=_ANCHORS_FEATURE_SQL,+ user=self.user,+ query_context=BATCH_QUERY,+ )features_query, count_query = features_run.call_args.kwargs["query"], count_run.call_args.kwargs["query"]+ sent_contexts = [+ call.kwargs["query_context"] for call in features_run.call_args_list + count_run.call_args_list+ ]+ assert sent_contexts == [BATCH_QUERY] * 3assert "now()" not in features_query.query and "now()" not in count_query.queryassert features_query.values["anchor_ts"] == count_query.values["anchor_ts"]diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.pyindex 049482d1b4f0..88f8689fcbcd 100644--- a/products/autoresearch/backend/inference/test_sandbox_inference.py+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py@@ -37,7 +37,7 @@ from products.autoresearch.backend.inference.sandbox import ()from products.autoresearch.backend.inference.scoring import run_inference_for_pipelinefrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun-from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.query import BATCH_QUERY, INTERACTIVE_QUERY, HogQLResultfrom products.autoresearch.backend.testing import TeamScopedTestMixinfrom products.autoresearch.backend.training.artifacts import ArtifactBundle, BundleNotFoundfrom products.tasks.backend.facade.sandbox import ExecutionResult@@ -157,6 +157,8 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):data = materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")sample_query, features_query, count_query = (call.kwargs["query"] for call in run_hogql.call_args_list)+ # Training runs inside a web request, so it keeps the interactive limit.+ assert all(call.kwargs["query_context"] == INTERACTIVE_QUERY for call in run_hogql.call_args_list)assert all("now()" not in query.query for query in (sample_query, features_query, count_query))assert sample_query.values["anchor_ts"] == features_query.values["anchor_ts"] == count_query.values["anchor_ts"]assert data.feature_cols == ["events_total", "pageviews"]@@ -182,15 +184,16 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):def test_score_data_is_inference_only_no_labels(self):pipeline = self._pipeline()with (- patch.object(sandbox_inference, "count_inference_anchors", return_value=len(_SCORE_ROWS)),+ patch.object(sandbox_inference, "count_inference_anchors", return_value=len(_SCORE_ROWS)) as count,patch.object(sandbox_inference, "_materialize_rows", return_value=_SCORE_ROWS) as run,):score_rows = _materialize_score_data(- team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}"+ team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}", query_context=BATCH_QUERY)# exactly one query (inference anchors only) — no training/holdout materializationassert run.call_count == 1+ assert run.call_args.kwargs["query_context"] == count.call_args.kwargs["query_context"] == BATCH_QUERYassert [r["distinct_id"] for r in score_rows] == ["s1", "s2"]@parameterized.expand(@@ -700,15 +703,18 @@ class TestInferenceRouting(TeamScopedTestMixin, BaseTest):))with (- patch("products.autoresearch.backend.inference.scoring.score_via_sandbox", return_value=sandbox_result),+ patch(+ "products.autoresearch.backend.inference.scoring.score_via_sandbox", return_value=sandbox_result+ ) as score,patch("products.autoresearch.backend.inference.scoring._resolve_distinct_ids", return_value={}),patch("products.autoresearch.backend.inference.scoring.capture_batch_internal", emit),):- run = run_inference_for_pipeline(pipeline=pipeline, model=model)+ run = run_inference_for_pipeline(pipeline=pipeline, model=model, query_context=BATCH_QUERY)assert run.status == AutoresearchRun.Status.COMPLETEDassert run.rows_scored == 2assert run.metrics["sandbox"] is True+ assert score.call_args.kwargs["query_context"] == BATCH_QUERYassert run.metrics["holdout_auc"] == 0.71assert emit.call_count == 1assert len(emit.call_args.kwargs["events"]) == 2diff --git a/products/autoresearch/backend/query.py b/products/autoresearch/backend/query.pyindex 9e26085176a3..9154faaef4d0 100644--- a/products/autoresearch/backend/query.py+++ b/products/autoresearch/backend/query.py@@ -2,6 +2,9 @@ from typing import Anyfrom posthog.schema import CacheMissResponse, HogQLQuery, QueryStatusResponse+from posthog.hogql.constants import LimitContext++from posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozenfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunnerfrom posthog.hogql_queries.query_runner import ExecutionMode@@ -13,6 +16,22 @@ class AutoresearchQueryError(Exception):pass+@frozen+class QueryContext:+ """The ClickHouse budget a query runs under: its limit context (which sets `max_execution_time`) and workload."""++ limit_context: LimitContext+ workload: Workload+++# A query inside a web request keeps the 60 s interactive limit, because a longer query+# would outlive the request.+INTERACTIVE_QUERY = QueryContext(limit_context=LimitContext.QUERY, workload=Workload.DEFAULT)+# Scoring and online validation run in a Temporal activity that nobody waits on, so they+# get the increased batch limit and run on the offline workload.+BATCH_QUERY = QueryContext(limit_context=LimitContext.QUERY_ASYNC, workload=Workload.OFFLINE)++@frozenclass HogQLResult:columns: list[str]@@ -32,6 +51,7 @@ def run_hogql(query: HogQLQuery,user: User | None = None,execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> HogQLResult:"""Run a HogQL query under a blocking execution mode and return its columns and rows.@@ -47,7 +67,13 @@ def run_hogql(and keeps "the query returned nothing" distinct from "the query did not run",which callers here read as a real zero."""- response = HogQLQueryRunner(query=query, team=team, user=user).run(execution_mode=execution_mode)+ response = HogQLQueryRunner(+ query=query,+ team=team,+ user=user,+ limit_context=query_context.limit_context,+ workload=query_context.workload,+ ).run(execution_mode=execution_mode)if isinstance(response, CacheMissResponse | QueryStatusResponse):raise AutoresearchQueryError(f"HogQL query did not execute: got {type(response).__name__}")return HogQLResult(@@ -63,5 +89,6 @@ def run_hogql_rows(query: HogQLQuery,user: User | None = None,execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ query_context: QueryContext = INTERACTIVE_QUERY,) -> list[list[Any]]:- return run_hogql(team=team, query=query, user=user, execution_mode=execution_mode).rows+ return run_hogql(team=team, query=query, user=user, execution_mode=execution_mode, query_context=query_context).rowsdiff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.pyindex fbcc941e742c..582a8f8f57a8 100644--- a/products/autoresearch/backend/temporal/test_workflows.py+++ b/products/autoresearch/backend/temporal/test_workflows.py@@ -6,6 +6,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase+from django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom temporalio.exceptions import ApplicationError@@ -19,7 +20,9 @@ from products.autoresearch.backend.models import (AutoresearchRun,AutoresearchTrainingRun,)+from products.autoresearch.backend.query import BATCH_QUERYfrom products.autoresearch.backend.temporal.workflows import (+ _VALIDATION_ATTEMPT_TIMEOUT,InferenceWorkflowResult,KickoffTrainingInput,KickoffTrainingResult,@@ -221,6 +224,30 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):mock_inference.assert_not_called()mock_validation.assert_not_called()+ @parameterized.expand([("inference",), ("validation",)])+ @patch("products.autoresearch.backend.temporal.workflows.run_online_validation_for_pipeline", return_value=[])+ @patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")+ def test_activities_run_their_queries_as_batch_work(+ self, step: str, mock_inference: MagicMock, mock_validation: MagicMock+ ) -> None:+ pipeline = self._create_pipeline()+ env = ActivityEnvironment()+ if step == "inference":+ AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={"stub": True}, recipe_hash="abc"+ )+ mock_inference.return_value = MagicMock(pk="run-1", rows_scored=0, status="completed", error="")+ env.run(+ activity_run_inference,+ RunInferenceInput(pipeline_id=str(pipeline.id), team_id=self.team.id, prediction_date="2026-09-11"),+ )+ assert mock_inference.call_args.kwargs["query_context"] == BATCH_QUERY+ else:+ env.run(activity_run_validation, RunValidationInput(pipeline_id=str(pipeline.id), team_id=self.team.id))+ assert mock_validation.call_args.kwargs["query_context"] == BATCH_QUERY+ claim_deadline = mock_validation.call_args.kwargs["claim_deadline"]+ assert django_timezone.now() < claim_deadline < django_timezone.now() + _VALIDATION_ATTEMPT_TIMEOUT+@parameterized.expand([("scheduled", False), ("manual", True)])@patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")def test_inference_refuses_a_deleted_action_target(diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.pyindex 3a93c0c1b403..06fcbbe4077d 100644--- a/products/autoresearch/backend/temporal/workflows.py+++ b/products/autoresearch/backend/temporal/workflows.py@@ -40,6 +40,7 @@ with workflow.unsafe.imports_passed_through():AutoresearchRun,AutoresearchTrainingRun,)+ from products.autoresearch.backend.query import BATCH_QUERYfrom products.autoresearch.backend.training.runner import run_trainingfrom products.tasks.backend.facade.access import get_desktop_access_decisionfrom products.tasks.backend.facade.usage import task_run_usage_limited@@ -136,6 +137,7 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:prediction_date=date.fromisoformat(inp.prediction_date),user=user,run=manual_run,+ query_context=BATCH_QUERY,)return RunInferenceResult(run_id=str(run.pk),@@ -188,7 +190,8 @@ def inference_workflow_id(pipeline_id: str, prediction_date: str) -> str:# ── Workflow ─────────────────────────────────────────────────────────────────-# Scoring can take minutes for large populations.+# Scoring can take minutes for large populations. The recipe path runs at most five batch+# queries in sequence, so one attempt covers all of them at the full limit._SCORE_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))_SCORE_ATTEMPT_TIMEOUT = timedelta(hours=2)# A lost worker is detected in minutes rather than at the end of a multi-hour attempt.@@ -285,20 +288,27 @@ class RunValidationResult:# Validation does all its work (HogQL + sklearn) inside a single activity to# keep the Temporal payload small — we only return summary counts, not raw data._VALIDATION_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))-_VALIDATION_ATTEMPT_TIMEOUT = timedelta(hours=1)-_VALIDATION_WORKFLOW_TIMEOUT = timedelta(hours=3)+# Each date runs two batch queries of up to HOGQL_INCREASED_MAX_EXECUTION_TIME (600 s) each.+# An attempt claims another date only while that worst case, plus the metrics and writes, still+# fits in the attempt. The rest of a larger backlog stays pending for the next sweep, so the+# attempt completes instead of timing out part-way.+_VALIDATION_ATTEMPT_TIMEOUT = timedelta(hours=2)+_VALIDATION_DATE_RESERVE = timedelta(minutes=30)+# Covers both attempts plus their backoff, as for inference.+_VALIDATION_WORKFLOW_TIMEOUT = timedelta(hours=5)@activity.defn(name="autoresearch-validation.run_validation")def activity_run_validation(inp: RunValidationInput) -> RunValidationResult:"""Find all matured unvalidated prediction dates and validate each one."""+ claim_deadline = django_timezone.now() + _VALIDATION_ATTEMPT_TIMEOUT - _VALIDATION_DATE_RESERVEwith HeartbeaterSync(), team_scope(inp.team_id):pipeline = AutoresearchPipeline.objects.select_related("team__organization", "created_by").get(pk=inp.pipeline_id)if pipeline.status not in _LIVE_STATUSES or _sweep_access_block(pipeline):return RunValidationResult(dates_validated=0, total_rows=0, status="skipped")- runs = run_online_validation_for_pipeline(pipeline)+ runs = run_online_validation_for_pipeline(pipeline, query_context=BATCH_QUERY, claim_deadline=claim_deadline)# A per-date failure is recorded on its own run rather than raised, so inspect the# statuses here. Reporting completed regardless would leave the retry policy unused# even when every matured date failed; the coordinator isolates the failure per