: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): keep training after the first burst, on a research interval (#116686)
posthog[bot]ef7af9842359
diff --git a/products/autoresearch/AGENTS.md b/products/autoresearch/AGENTS.mdindex 5b7da3ceaaec..107ca8a5f091 100644--- a/products/autoresearch/AGENTS.md+++ b/products/autoresearch/AGENTS.md@@ -39,6 +39,13 @@ Rollout is configured on the flag, and code only asks whether it is on.The real-agent training path additionally needs Tasks access, because it runs in a Tasks sandbox.+## Training schedule++Training never ends, but exploration comes first.+The daily sweep starts research runs on scoring days until a run fails to promote a better model or 5 research runs have run, then one run every `research_interval_days` after the latest run (`backend/training/schedule.py`).+Each run takes `iterations_per_run` iterations, and records why it started in `kickoff_reason`.+`iteration_budget` and `iteration_budget_remaining` are deprecated: nothing scheduled reads them.+## Invariants that cross package boundariesThese are the ones that have actually broken things.diff --git a/products/autoresearch/backend/admin.py b/products/autoresearch/backend/admin.pyindex b839b786afd8..177b59b8dda4 100644--- a/products/autoresearch/backend/admin.py+++ b/products/autoresearch/backend/admin.py@@ -98,7 +98,18 @@ class AutoresearchPipelineAdmin(admin.ModelAdmin):),("Population", {"fields": ("training_population", "inference_population")}),("Output", {"fields": ("output_person_property",)}),- ("Budget & schedule", {"fields": ("iteration_budget", "iteration_budget_remaining", "cadence_days")}),+ (+ "Budget & schedule",+ {+ "fields": (+ "iterations_per_run",+ "research_interval_days",+ "cadence_days",+ "iteration_budget",+ "iteration_budget_remaining",+ )+ },+ ),("Stop criteria", {"fields": ("success_auc", "plateau_iterations")}),("Dates", {"fields": ("created_at", "updated_at", "last_scored_at")}),)diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex 473f931dd098..c99b259cb74b 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -55,6 +55,7 @@ from ..evaluation.segment_thresholds import ()from ..inference.failures import INFERENCE_WORKFLOW_TIMEOUTfrom ..models import (+ RESEARCH_INTERVAL_DAYS_CHOICES as _RESEARCH_INTERVAL_DAYS_CHOICES,AutoresearchIteration,AutoresearchModel,AutoresearchPipeline,@@ -70,6 +71,7 @@ from ..training.explanation import (normalize_model_explanation,)from ..training.recipe_validation import RecipeValidationError, feature_sql_hints, validate_feature_sql, validate_recipe+from ..training.schedule import ScheduleRun, research_schedule, schedule_runs_forfrom ..training.shadow_set import shadow_set_idsfrom .contracts import (ArtifactContent,@@ -185,6 +187,7 @@ class _PipelineActivity:training_run_count: intexperiment_count: intlive_training_run: LiveTrainingRun | None+ schedule_runs: list[ScheduleRun]def _best_so_far_trend(scores: Iterable[tuple[int, float | None]]) -> list[TrainingTrendPoint]:@@ -340,6 +343,7 @@ def _pipeline_activity(training_trends = _champion_training_trends(team_id, champions)likely_counts = _champion_likely_counts(team_id, champions)first_checks = _first_checks_expected(team_id, champions)+ schedule_runs = schedule_runs_for(pipeline_ids, team_id)return {pipeline_id: _PipelineActivity(champion_realized_auc_trend=[@@ -358,6 +362,7 @@ def _pipeline_activity(if pipeline_id in live_runselse None),+ schedule_runs=schedule_runs.get(pipeline_id, []),)for pipeline_id in pipeline_ids}@@ -369,6 +374,11 @@ def _pipeline_to_contract(champion: AutoresearchModel | None = None,activity: _PipelineActivity,) -> Pipeline:+ schedule = research_schedule(+ research_interval_days=row.research_interval_days,+ pipeline_created_at=row.created_at,+ runs=activity.schedule_runs,+ )return Pipeline(id=row.id,name=row.name,@@ -386,6 +396,10 @@ def _pipeline_to_contract(# The column is nullable (an admin can clear it); read that as no budget left# rather than widening the contract type.iteration_budget_remaining=row.iteration_budget_remaining or 0,+ iterations_per_run=row.iterations_per_run,+ research_interval_days=row.research_interval_days,+ training_phase=schedule.phase,+ next_research_at=schedule.next_research_at,success_auc=row.success_auc,plateau_iterations=row.plateau_iterations,output_person_property=row.output_person_property,@@ -465,6 +479,7 @@ def _training_run_to_contract(row: AutoresearchTrainingRun) -> TrainingRun:task_run_id=row.task_run_id,task_url=f"/tasks/{row.task_id}" if row.task_id else None,status=row.status,+ kickoff_reason=row.kickoff_reason,iteration_budget=row.iteration_budget,iteration_count=row.iteration_count,best_holdout_score=row.best_holdout_score,@@ -902,6 +917,8 @@ def get_pipeline_definition(team_id: int, pipeline_id: str | UUID) -> PipelineWrinference_population=row.inference_population or {},cadence_days=row.cadence_days,iteration_budget=row.iteration_budget,+ iterations_per_run=row.iterations_per_run,+ research_interval_days=row.research_interval_days,success_auc=row.success_auc,plateau_iterations=row.plateau_iterations,output_person_property=row.output_person_property,@@ -1417,9 +1434,14 @@ def start_training(pipeline = _claim_pipeline_for_training(team_id, pipeline_id)if not allow_action_target and pipeline.target_definition.get("type") == "action":raise InvalidTarget("An action target needs the action:read scope.")- budget = iteration_budget or pipeline.iteration_budget+ budget = iteration_budget or pipeline.iterations_per_runtry:- training_run = run_training(pipeline=pipeline, iteration_budget=budget, user_id=user_id)+ training_run = run_training(+ pipeline=pipeline,+ iteration_budget=budget,+ user_id=user_id,+ kickoff_reason=AutoresearchTrainingRun.KickoffReason.MANUAL,+ )except Action.DoesNotExist:raise AutoresearchConflict("The pipeline's target action no longer exists.")except (ValueError, SandboxInferenceError) as exc:@@ -1446,7 +1468,8 @@ def open_training_run(row = AutoresearchTrainingRun.objects.create(pipeline=pipeline,status=AutoresearchTrainingRun.Status.RUNNING,- iteration_budget=iteration_budget or pipeline.iteration_budget,+ kickoff_reason=AutoresearchTrainingRun.KickoffReason.MANUAL,+ iteration_budget=iteration_budget or pipeline.iterations_per_run,started_at=django_timezone.now(),)return _training_run_to_contract(row)@@ -2051,6 +2074,9 @@ TEMPLATE_KEY_CHOICES = _TemplateKey.choicesVALIDATION_WARNING_CODES = [code.value for code in _ValidationWarningCode]MODEL_ROLE_CHOICES = AutoresearchModel.Role.choicesTRAINING_RUN_STATUS_CHOICES = AutoresearchTrainingRun.Status.choices+KICKOFF_REASON_CHOICES = AutoresearchTrainingRun.KickoffReason.choices+RESEARCH_INTERVAL_DAYS_CHOICES = list(_RESEARCH_INTERVAL_DAYS_CHOICES)+TRAINING_PHASE_CHOICES = [("explore", "Explore"), ("maintain", "Maintain")]ITERATION_STATUS_CHOICES = AutoresearchIteration.Status.choicesSUGGESTION_PRIORITY_CHOICES = AutoresearchSuggestion.Priority.choicesSUGGESTION_STATUS_CHOICES = AutoresearchSuggestion.Status.choicesdiff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.pyindex d8150caae397..3f8ff7a4b240 100644--- a/products/autoresearch/backend/facade/contracts.py+++ b/products/autoresearch/backend/facade/contracts.py@@ -131,6 +131,10 @@ class Pipeline:cadence_days: intiteration_budget: intiteration_budget_remaining: int+ iterations_per_run: int+ research_interval_days: int | None+ training_phase: str+ next_research_at: datetime | Nonesuccess_auc: float | Noneplateau_iterations: intoutput_person_property: str@@ -231,6 +235,7 @@ class TrainingRun:task_run_id: UUID | Nonetask_url: str | Nonestatus: str+ kickoff_reason: str | Noneiteration_budget: intiteration_count: intbest_holdout_score: float | None@@ -324,6 +329,8 @@ class PipelineWrite:inference_population: dict[str, Any] = field(default_factory=dict)cadence_days: int = 1iteration_budget: int = 50+ iterations_per_run: int = 5+ research_interval_days: int | None = 7success_auc: float | None = Noneplateau_iterations: int = 10output_person_property: str = ""diff --git a/products/autoresearch/backend/migrations/0007_research_schedule.py b/products/autoresearch/backend/migrations/0007_research_schedule.pynew file mode 100644index 000000000000..5656d0d2cc3b--- /dev/null+++ b/products/autoresearch/backend/migrations/0007_research_schedule.py@@ -0,0 +1,59 @@+# Generated by Django 5.2.18 on 2026-10-13 23:41++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("autoresearch", "0006_headlines"),+ ]++ operations = [+ migrations.AddField(+ model_name="autoresearchpipeline",+ name="iterations_per_run",+ field=models.IntegerField(+ db_default=5,+ default=5,+ help_text="Experiments the agent may try in each training run",+ validators=[+ django.core.validators.MinValueValidator(1),+ django.core.validators.MaxValueValidator(50),+ ],+ ),+ ),+ migrations.AddField(+ model_name="autoresearchpipeline",+ name="research_interval_days",+ field=models.IntegerField(+ blank=True,+ choices=[+ (7, "7 days"),+ (14, "14 days"),+ (30, "30 days"),+ (60, "60 days"),+ (90, "90 days"),+ ],+ db_default=7,+ default=7,+ help_text="Days between scheduled research runs once the first burst of daily runs ends",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="autoresearchtrainingrun",+ name="kickoff_reason",+ field=models.CharField(+ blank=True,+ choices=[+ ("explore", "Explore"),+ ("scheduled", "Scheduled"),+ ("rescue", "Rescue"),+ ("manual", "Manual"),+ ],+ max_length=20,+ null=True,+ ),+ ),+ ]diff --git a/products/autoresearch/backend/migrations/max_migration.txt b/products/autoresearch/backend/migrations/max_migration.txtindex 5144920d5934..fdbf38252c7c 100644--- a/products/autoresearch/backend/migrations/max_migration.txt+++ b/products/autoresearch/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_headlines+0007_research_schedulediff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.pyindex 122e07600abf..7e5a1ac1ecab 100644--- a/products/autoresearch/backend/models.py+++ b/products/autoresearch/backend/models.py@@ -21,6 +21,19 @@ def unit_interval_constraint(field: str, name: str) -> models.CheckConstraint:)+class ResearchIntervalDays(models.IntegerChoices):+ """The research intervals a user can pick, in days."""++ DAYS_7 = 7, "7 days"+ DAYS_14 = 14, "14 days"+ DAYS_30 = 30, "30 days"+ DAYS_60 = 60, "60 days"+ DAYS_90 = 90, "90 days"+++RESEARCH_INTERVAL_DAYS_CHOICES = tuple(ResearchIntervalDays.values)++def min_value_constraint(field: str, minimum: int, name: str, *, nullable: bool = False) -> models.CheckConstraint:at_least = models.Q(**{f"{field}__gte": minimum})if nullable:@@ -94,6 +107,21 @@ class AutoresearchPipeline(TeamScopedRootMixin, UUIDModel):iteration_budget_remaining = models.IntegerField(null=True, blank=True, default=None, validators=[MinValueValidator(0)])+ iterations_per_run = models.IntegerField(+ default=5,+ db_default=5,+ validators=[MinValueValidator(1), MaxValueValidator(50)],+ help_text="Experiments the agent may try in each training run",+ )+ # Null means no scheduled research: training starts only when someone asks for it.+ research_interval_days = models.IntegerField(+ null=True,+ blank=True,+ default=7,+ db_default=7,+ choices=ResearchIntervalDays.choices,+ help_text="Days between scheduled research runs once the first burst of daily runs ends",+ )# Stop criteriasuccess_auc = models.FloatField(@@ -302,6 +330,12 @@ class AutoresearchTrainingRun(PipelineScopedModel):COMPLETED = "completed", "Completed"FAILED = "failed", "Failed"+ class KickoffReason(models.TextChoices):+ EXPLORE = "explore", "Explore"+ SCHEDULED = "scheduled", "Scheduled"+ RESCUE = "rescue", "Rescue"+ MANUAL = "manual", "Manual"+pipeline = models.ForeignKey(AutoresearchPipeline, on_delete=models.CASCADE, related_name="training_runs")# Link to the Task/TaskRun sandbox (nullable for stubs).@@ -311,6 +345,8 @@ class AutoresearchTrainingRun(PipelineScopedModel):task_run_id = models.UUIDField(null=True, blank=True, help_text="TaskRun ID in the tasks product sandbox")status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)+ # Null on runs started before the field existed.+ kickoff_reason = models.CharField(max_length=20, choices=KickoffReason.choices, null=True, blank=True)iteration_budget = models.IntegerField(default=50, validators=[MinValueValidator(1)])iteration_count = models.IntegerField(default=0, validators=[MinValueValidator(0)])best_holdout_score = models.FloatField(null=True, blank=True, validators=UNIT_INTERVAL_VALIDATORS)diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex 7e876e33030b..377bf1e2340b 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -42,6 +42,9 @@ RUN_STATUS_CHOICES = api.RUN_STATUS_CHOICESRUN_TYPE_CHOICES = api.RUN_TYPE_CHOICESBASE_RATE_SOURCE_CHOICES = api.BASE_RATE_SOURCE_CHOICESTRAINING_RUN_STATUS_CHOICES = api.TRAINING_RUN_STATUS_CHOICES+KICKOFF_REASON_CHOICES = api.KICKOFF_REASON_CHOICES+RESEARCH_INTERVAL_DAYS_CHOICES = api.RESEARCH_INTERVAL_DAYS_CHOICES+TRAINING_PHASE_CHOICES = api.TRAINING_PHASE_CHOICESITERATION_STATUS_CHOICES = api.ITERATION_STATUS_CHOICESSUGGESTION_PRIORITY_CHOICES = api.SUGGESTION_PRIORITY_CHOICESSUGGESTION_STATUS_CHOICES = api.SUGGESTION_STATUS_CHOICES@@ -662,10 +665,43 @@ class AutoresearchPipelineSerializer(DataclassSerializer):min_value=-2147483648,max_value=2147483647,required=False,- help_text="Total training iterations allowed for the autoresearch loop.",+ help_text="Deprecated: scheduled training no longer reads it. Use iterations_per_run.",)iteration_budget_remaining = serializers.IntegerField(- read_only=True, help_text="Iterations remaining in the current budget."+ read_only=True, help_text="Deprecated: scheduled training no longer reads or spends it."+ )+ iterations_per_run = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Experiments the agent may try in each training run (1-50). Each experiment costs agent time and "+ "queries, so a higher value costs more per run. Scheduled runs and Train now use it."+ ),+ )+ research_interval_days = serializers.ChoiceField(+ choices=RESEARCH_INTERVAL_DAYS_CHOICES,+ read_only=True,+ allow_null=True,+ help_text=(+ "Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. "+ "Null means only when asked: no scheduled research, so the only training cost comes from runs you "+ "start and from rescue runs for a model that cannot score. A shorter interval costs more."+ ),+ )+ training_phase = serializers.ChoiceField(+ choices=TRAINING_PHASE_CHOICES,+ read_only=True,+ help_text=(+ "explore: a research run on each scoring day until a run does not promote a better model, or until "+ "5 research runs have run. maintain: one research run every research_interval_days."+ ),+ )+ next_research_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text=(+ "Start of the UTC day from which the daily sweep can start the next scheduled research run. "+ "Null when research_interval_days is null."+ ),)success_auc = serializers.FloatField(required=False,@@ -795,6 +831,10 @@ class AutoresearchPipelineSerializer(DataclassSerializer):"cadence_days","iteration_budget","iteration_budget_remaining",+ "iterations_per_run",+ "research_interval_days",+ "training_phase",+ "next_research_at","success_auc","plateau_iterations","output_person_property",@@ -877,7 +917,26 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):required=False,min_value=1,max_value=500,- help_text="Total training iterations allowed for the autoresearch loop (1-500). Default: 50.",+ help_text="Deprecated: scheduled training no longer reads it. Use iterations_per_run.",+ )+ iterations_per_run = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=50,+ help_text=(+ "Experiments the agent may try in each training run (1-50). Each experiment costs agent time and "+ "queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5."+ ),+ )+ research_interval_days = serializers.ChoiceField(+ choices=RESEARCH_INTERVAL_DAYS_CHOICES,+ required=False,+ allow_null=True,+ help_text=(+ "Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. "+ "Null means only when asked: no scheduled research, so the only training cost comes from runs you "+ "start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7."+ ),)success_auc = serializers.FloatField(required=False,@@ -926,6 +985,8 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):"inference_population","cadence_days","iteration_budget",+ "iterations_per_run",+ "research_interval_days","success_auc","plateau_iterations","output_person_property",@@ -1290,6 +1351,15 @@ class AutoresearchTrainingRunSerializer(DataclassSerializer):read_only=True,help_text="Run status: pending, running, completed, or failed.",)+ kickoff_reason = serializers.ChoiceField(+ choices=KICKOFF_REASON_CHOICES,+ read_only=True,+ allow_null=True,+ help_text=(+ "Why the run started: explore (the first burst of daily runs), scheduled (the research interval), "+ "rescue (the champion cannot score) or manual (a person or an agent asked). Null for older runs."+ ),+ )iteration_budget = serializers.IntegerField(min_value=-2147483648,max_value=2147483647,@@ -1347,6 +1417,7 @@ class AutoresearchTrainingRunSerializer(DataclassSerializer):"task_run_id","task_url","status",+ "kickoff_reason","iteration_budget","iteration_count","best_holdout_score",@@ -1857,7 +1928,7 @@ class StartTrainingRequestSerializer(serializers.Serializer):required=False,min_value=1,max_value=500,- help_text="Override the pipeline iteration budget for this training run.",+ help_text="Iterations for this training run. Defaults to the pipeline's iterations_per_run.",)@@ -1871,7 +1942,7 @@ class OpenTrainingRunSerializer(serializers.Serializer):required=False,min_value=1,max_value=500,- help_text="Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.",+ help_text="Iteration budget for this run. Defaults to the pipeline's iterations_per_run if omitted.",)diff --git a/products/autoresearch/backend/temporal/AGENTS.md b/products/autoresearch/backend/temporal/AGENTS.mdindex 365a63e1b9aa..0d3caaa129b8 100644--- a/products/autoresearch/backend/temporal/AGENTS.md+++ b/products/autoresearch/backend/temporal/AGENTS.md@@ -2,7 +2,7 @@The scheduled half of autoresearch. Three workflows and four activities, registered on `settings.AUTORESEARCH_TASK_QUEUE` by `start_temporal_worker`, which imports `WORKFLOWS` and `ACTIVITIES` from `__init__.py`.-Scoring, validation and training live in `../inference/`, `../evaluation/`, and `../training/` — the same functions the management commands and the API reach — and the activities call them, so the scheduled path cannot drift from the headless one. What stays here is the sweep's own logic: discovery (cadence, rollout, creator access) and the kickoff's eligibility gates, budget debit and row lock.+Scoring, validation and training live in `../inference/`, `../evaluation/`, and `../training/` — the same functions the management commands and the API reach — and the activities call them, so the scheduled path cannot drift from the headless one. What stays here is the sweep's own logic: discovery (cadence, rollout, creator access) and the kickoff's eligibility gates, research schedule and row lock.## What lives here@@ -42,7 +42,12 @@ Discovery pauses a pipeline whose creator has lost access to the team, and skipsDiscovery also fails every inference run still RUNNING after `INFERENCE_WORKFLOW_TIMEOUT` (`fail_stale_inference_runs()` in `../inference/failures.py`), with `failure_kind` `other`, because a lost worker never records an outcome.A retry of a scheduled scoring attempt fills the RUNNING row of the attempt before it, so one date keeps one row.Kickoff applies the Tasks entitlement and usage gates `/train` applies, launches at most one run per UTC day, and holds the pipeline row lock through the launch, as `start_training` does.-A pipeline with no iteration budget left gets no run, except when `find_unscorable_champion()` finds that its champion cannot score. Then kickoff launches a rescue run of `RESCUE_ITERATION_BUDGET` iterations that does not come out of the budget, at most once in each window of `UNSCORABLE_AFTER_FAILED_DAYS` UTC days, and reports `rescue_unscorable`.+Kickoff then follows the research schedule in `../training/schedule.py`, which it derives from the pipeline's training runs and never stores.+In explore, it starts a run (`explore`) until a completed run does not promote its best model, or until `EXPLORE_RUN_LIMIT` research runs have run. Rescue runs do not count.+In maintain, it starts a run (`scheduled`) once `research_interval_days` calendar days have passed since the latest training run of any kind, and reports `not_due` before that. A null interval reports `manual_only`.+Each run takes the pipeline's `iterations_per_run`. Kickoff does not read or spend `iteration_budget_remaining`.+When no run is due and `find_unscorable_champion()` finds that the champion cannot score, kickoff launches a rescue run of `RESCUE_ITERATION_BUDGET` iterations, at most once in each window of `UNSCORABLE_AFTER_FAILED_DAYS` UTC days, and reports `rescue_unscorable`.+Each run records why it started in `kickoff_reason`. The coordinator body never branches on the kickoff result, because that would break replay.Note that training is launched by an _activity_, not a child workflow, because the actual agent run happens in a Tasks sandbox with its own lifecycle. Autoresearch does not own that workflow; it fires it and the `TaskRun` `post_save` signal (`../training/ingestion.py`) picks the result back up.diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.pyindex 9d8bf019e3be..5247d26b4ddc 100644--- a/products/autoresearch/backend/temporal/test_workflows.py+++ b/products/autoresearch/backend/temporal/test_workflows.py@@ -61,8 +61,8 @@ def _validation(status: str = "completed", error: Optional[str] = None) -> Validreturn ValidationWorkflowResult(dates_validated=1, total_rows=10, status=status, error=error)-def _kickoff(reason: str = "started", error: Optional[str] = None) -> KickoffTrainingResult:- return KickoffTrainingResult(kicked_off=reason == "started", reason=reason, error=error)+def _kickoff(reason: str = "explore", error: Optional[str] = None) -> KickoffTrainingResult:+ return KickoffTrainingResult(kicked_off=reason == "explore", reason=reason, error=error)class TestEvaluatePipelineOutcome(SimpleTestCase):@@ -76,7 +76,7 @@ class TestEvaluatePipelineOutcome(SimpleTestCase):("kickoff_raises", _inference(), _validation(), RuntimeError("boom"), False, 1),("kickoff_errors", _inference(), _validation(), _kickoff(reason="error", error="boom"), False, 1),("kickoff_no_creator", _inference(), _validation(), _kickoff(reason="no_creator", error="boom"), False, 1),- ("kickoff_skip_is_not_failure", _inference(), _validation(), _kickoff(reason="budget_exhausted"), True, 0),+ ("kickoff_skip_is_not_failure", _inference(), _validation(), _kickoff(reason="not_due"), True, 0),("not_due_runs_validation_only", None, _validation(), None, True, 0),("multiple_failures_all_counted",@@ -125,7 +125,6 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):"name": "test pipeline","target_event": "$pageview","status": AutoresearchPipeline.Status.RUNNING,- "iteration_budget_remaining": 20,**overrides,}return AutoresearchPipeline.objects.create(**params)@@ -410,14 +409,11 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))assert result.kicked_off- assert result.reason == "started"mock_run_training.assert_called_once()assert mock_run_training.call_args.kwargs["user_id"] == self.user.id- pipeline.refresh_from_db()- assert pipeline.iteration_budget_remaining == 10@patch("products.autoresearch.backend.temporal.workflows.run_training")- def test_kickoff_without_creator_fails_loudly_and_spends_no_budget(self, mock_run_training: MagicMock) -> None:+ def test_kickoff_without_creator_fails_loudly(self, mock_run_training: MagicMock) -> None:pipeline = self._create_pipeline(created_by=None)result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))@@ -426,8 +422,6 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):assert result.reason == "no_creator"assert result.errormock_run_training.assert_not_called()- pipeline.refresh_from_db()- assert pipeline.iteration_budget_remaining == 20@parameterized.expand([@@ -439,7 +433,7 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):])@patch("products.autoresearch.backend.temporal.workflows.run_training")- def test_kickoff_skips_without_spending_budget(+ def test_kickoff_skips(self,_name: str,run_status: Optional[str],@@ -461,28 +455,65 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):assert result.reason == expected_reasonmock_run_training.assert_not_called()- pipeline.refresh_from_db()- assert pipeline.iteration_budget_remaining == 20@parameterized.expand([- ("unscorable_champion_gets_a_rescue", 0, True, None, "rescue_unscorable"),- ("scorable_champion_stays_exhausted", 0, False, None, "budget_exhausted"),- ("rescue_ran_yesterday", 0, True, datetime(2026, 9, 10, 2, tzinfo=UTC), "rescue_throttled"),- ("rescue_ran_two_days_ago", 0, True, datetime(2026, 9, 9, 2, tzinfo=UTC), "rescue_unscorable"),+ ("new_pipeline_explores", 7, [], False, "explore"),+ (+ "promoting_runs_keep_exploring",+ 7,+ [("explore", "completed", True, 9), ("explore", "completed", True, 10)],+ False,+ "explore",+ ),+ (+ "rescue_runs_do_not_end_the_burst",+ 7,+ [*[("explore", "failed", None, d) for d in (5, 6, 7, 8)], ("rescue", "completed", False, 10)],+ False,+ "explore",+ ),+ ("explore_takes_precedence_over_rescue", 7, [], True, "explore"),+ ("non_promoting_run_ends_the_burst", 7, [("explore", "completed", False, 10)], False, "not_due"),+ (+ "five_runs_end_the_burst_then_interval_passes",+ 7,+ [(None, "failed", None, d) for d in (0, 1, 2, 3, 4)],+ False,+ "scheduled",+ ),+ ("maintain_within_interval", 14, [(None, "failed", None, d) for d in (1, 2, 3, 4, 5)], False, "not_due"),+ (+ "manual_run_resets_the_clock",+ 7,+ [("scheduled", "completed", False, -30), ("manual", "completed", True, 5)],+ False,+ "not_due",+ ),+ ("only_when_asked", None, [], False, "manual_only"),+ ("only_when_asked_still_rescues", None, [], True, "rescue_unscorable"),+ (+ "not_due_rescues_an_unscorable_champion",+ 7,+ [("explore", "completed", False, 8)],+ True,+ "rescue_unscorable",+ ),+ ("rescue_ran_yesterday", None, [("rescue", "failed", None, 10)], True, "rescue_throttled"),])@patch("products.autoresearch.backend.temporal.workflows.run_training")- def test_exhausted_budget_rescues_only_an_unscorable_champion(+ def test_kickoff_follows_the_research_schedule(self,_name: str,- remaining: int,+ research_interval_days: Optional[int],+ prior_runs: list[tuple[Optional[str], str, Optional[bool], int]],unscorable: bool,- last_run_at: Optional[datetime],expected_reason: str,mock_run_training: MagicMock,) -> None:- pipeline = self._create_pipeline(iteration_budget_remaining=remaining)+ with time_machine.travel(datetime(2026, 8, 1, tzinfo=UTC), tick=False):+ pipeline = self._create_pipeline(research_interval_days=research_interval_days, iterations_per_run=8)champion = AutoresearchModel.objects.create(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={"stub": True}, recipe_hash="abc")@@ -495,28 +526,35 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):status=AutoresearchRun.Status.FAILED if unscorable else AutoresearchRun.Status.COMPLETED,metrics={"prediction_date": prediction_date, "failure_kind": "limit_exceeded"} if unscorable else {},)- if last_run_at is not None:- with time_machine.travel(last_run_at, tick=False):+ # The day of each prior run is a day of September 2026; a value below 1 counts back into August.+ for kickoff_reason, run_status, promoted, day in prior_runs:+ with time_machine.travel(datetime(2026, 9, 1, 2, tzinfo=UTC) + timedelta(days=day - 1), tick=False):AutoresearchTrainingRun.objects.create(- pipeline=pipeline, status=AutoresearchTrainingRun.Status.FAILED, iteration_budget=3+ pipeline=pipeline,+ status=run_status,+ kickoff_reason=kickoff_reason,+ iteration_budget=3,+ summary={} if promoted is None else {"champion_promoted": promoted},)with time_machine.travel(datetime(2026, 9, 11, 2, tzinfo=UTC), tick=False):result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))assert result.reason == expected_reason- if expected_reason == "rescue_unscorable":+ if expected_reason in ("explore", "scheduled", "rescue_unscorable"):assert result.kicked_off- assert mock_run_training.call_args.kwargs["iteration_budget"] == RESCUE_ITERATION_BUDGET- assert mock_run_training.call_args.kwargs["rescue"] is True+ kwargs = mock_run_training.call_args.kwargs+ rescue = expected_reason == "rescue_unscorable"+ assert kwargs["iteration_budget"] == (RESCUE_ITERATION_BUDGET if rescue else 8)+ assert kwargs["rescue"] is rescue+ assert kwargs["kickoff_reason"] == ("rescue" if rescue else expected_reason)else:+ assert not result.kicked_offmock_run_training.assert_not_called()- pipeline.refresh_from_db()- assert pipeline.iteration_budget_remaining == remaining@parameterized.expand([("transient_failure_raises", RuntimeError("boom")), ("refused_launch", ValueError("left"))])@patch("products.autoresearch.backend.temporal.workflows.run_training")- def test_failed_launch_spends_no_budget(self, _name: str, error: Exception, mock_run_training: MagicMock) -> None:+ def test_failed_launch(self, _name: str, error: Exception, mock_run_training: MagicMock) -> None:pipeline = self._create_pipeline()mock_run_training.side_effect = error@@ -527,9 +565,6 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))assert result.reason == "not_launchable"- pipeline.refresh_from_db()- assert pipeline.iteration_budget_remaining == 20-@pytest.mark.parametrize("first_pass,expected_passes,expected_failed_run",diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.pyindex b1144c78cd1e..ae16d8155d35 100644--- a/products/autoresearch/backend/temporal/workflows.py+++ b/products/autoresearch/backend/temporal/workflows.py@@ -51,6 +51,7 @@ with workflow.unsafe.imports_passed_through():)from products.autoresearch.backend.query import BATCH_QUERYfrom products.autoresearch.backend.training.runner import run_training+ from products.autoresearch.backend.training.schedule import research_schedule, schedule_runs_forfrom products.tasks.backend.facade.access import get_desktop_access_decisionfrom products.tasks.backend.facade.usage import task_run_usage_limited@@ -630,8 +631,8 @@ def evaluate_pipeline_outcome(@frozenclass KickoffTrainingResult:kicked_off: bool- # "started" | "budget_exhausted" | "already_running" | "already_ran_today" | "not_eligible"- # | "tasks_gated" | "no_creator" | "not_launchable" | "rescue_unscorable" | "rescue_throttled"+ # "explore" | "scheduled" | "not_due" | "manual_only" | "already_running" | "already_ran_today"+ # | "not_eligible" | "tasks_gated" | "no_creator" | "not_launchable" | "rescue_unscorable" | "rescue_throttled"reason: strerror: Optional[str] = None# Why an expected skip happened, without counting it as a failure.@@ -642,7 +643,7 @@ class KickoffTrainingResult:_COORDINATOR_RETRY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5))_KICKOFF_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=10))-# The iterations of a rescue run. It does not come out of the pipeline budget.+# The iterations of a rescue run, which is shorter than a research run.RESCUE_ITERATION_BUDGET = 3@@ -708,11 +709,11 @@ def _pause_orphaned_pipeline(pipeline: AutoresearchPipeline, *, reason: str) ->@activity.defn(name="autoresearch-coordinator.kickoff_training")def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResult:- """Spend part of the iteration budget on a new agent training run, if the pipeline is eligible.+ """Start a scheduled agent training run, if the pipeline's research schedule says one is due.- The deduction, the run row, and its task binding commit together under the pipeline row lock,- as in the facade's ``start_training``. A manual start cannot interleave, and a failed launch- rolls the deduction back. A launch failure raises, so the activity retry applies.+ The run row and its task binding commit together under the pipeline row lock, as in the+ facade's ``start_training``, so a manual start cannot interleave. A launch failure raises,+ so the activity retry applies."""# The gates can call out to billing and flags, so they run before the row lock is taken.with team_scope(inp.team_id):@@ -726,17 +727,6 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResulif pipeline.status != AutoresearchPipeline.Status.RUNNING:return KickoffTrainingResult(kicked_off=False, reason="not_eligible")- # The column is nullable (an admin can clear it); read that as exhausted rather- # than refunding the budget mid-flight.- remaining = pipeline.iteration_budget_remaining or 0- # A champion that cannot score stops all predictions, and only a training run can replace- # it. So an exhausted pipeline still gets a small rescue run that spends no budget.- rescue = remaining <= 0- if rescue:- champion = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()- if find_unscorable_champion(champion) is None:- return KickoffTrainingResult(kicked_off=False, reason="budget_exhausted")-if AutoresearchTrainingRun.objects.filter(pipeline=pipeline,status__in=[AutoresearchTrainingRun.Status.PENDING, AutoresearchTrainingRun.Status.RUNNING],@@ -745,22 +735,41 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul# At most one scheduled run per UTC day. A retry after a lost activity response must not# launch a second paid run once the first has already ended.- today = django_timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)+ now = django_timezone.now()+ today = now.replace(hour=0, minute=0, second=0, microsecond=0)if AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=today).exists():return KickoffTrainingResult(kicked_off=False, reason="already_ran_today")- # At most one rescue run in each window of UNSCORABLE_AFTER_FAILED_DAYS UTC days, so a pipeline- # that no candidate can fix costs a bounded amount.- rescue_window_start = today - timedelta(days=UNSCORABLE_AFTER_FAILED_DAYS - 1)- if (- rescue- and AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=rescue_window_start).exists()- ):- return KickoffTrainingResult(kicked_off=False, reason="rescue_throttled")+ schedule = research_schedule(+ research_interval_days=pipeline.research_interval_days,+ pipeline_created_at=pipeline.created_at,+ runs=schedule_runs_for([pipeline.pk], inp.team_id).get(pipeline.pk, []),+ )+ kickoff_reason: AutoresearchTrainingRun.KickoffReason | None = None+ skip_reason = "not_due"+ if pipeline.research_interval_days is None:+ skip_reason = "manual_only"+ elif schedule.phase == "explore":+ kickoff_reason = AutoresearchTrainingRun.KickoffReason.EXPLORE+ elif schedule.is_due(now):+ kickoff_reason = AutoresearchTrainingRun.KickoffReason.SCHEDULED++ # A champion that cannot score stops all predictions, and only a training run can replace+ # it. So a pipeline with no research run due still gets a small rescue run.+ if kickoff_reason is None:+ champion = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()+ if find_unscorable_champion(champion) is None:+ return KickoffTrainingResult(kicked_off=False, reason=skip_reason)+ # At most one rescue run in each window of UNSCORABLE_AFTER_FAILED_DAYS UTC days, so a+ # pipeline that no candidate can fix costs a bounded amount.+ rescue_window_start = today - timedelta(days=UNSCORABLE_AFTER_FAILED_DAYS - 1)+ if AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=rescue_window_start).exists():+ return KickoffTrainingResult(kicked_off=False, reason="rescue_throttled")+ kickoff_reason = AutoresearchTrainingRun.KickoffReason.RESCUE# Training runs in a Tasks sandbox that requires a real owning user. CLI-created- # pipelines have no creator, so fail before spending budget rather than launching- # a run that would crash in the tasks facade.+ # pipelines have no creator, so fail here rather than launching a run that would+ # crash in the tasks facade.if pipeline.created_by_id is None:error = f"Pipeline {inp.pipeline_id} has no creator; training kickoff requires created_by to own the task"logger.error(@@ -769,20 +778,16 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul)return KickoffTrainingResult(kicked_off=False, reason="no_creator", error=error)+ rescue = kickoff_reason == AutoresearchTrainingRun.KickoffReason.RESCUEtry:with transaction.atomic():- if rescue:- run_training(- pipeline=pipeline,- iteration_budget=RESCUE_ITERATION_BUDGET,- user_id=pipeline.created_by_id,- rescue=True,- )- else:- daily_budget = min(10, remaining)- pipeline.iteration_budget_remaining = remaining - daily_budget- pipeline.save(update_fields=["iteration_budget_remaining"])- run_training(pipeline=pipeline, iteration_budget=daily_budget, user_id=pipeline.created_by_id)+ run_training(+ pipeline=pipeline,+ iteration_budget=RESCUE_ITERATION_BUDGET if rescue else pipeline.iterations_per_run,+ user_id=pipeline.created_by_id,+ rescue=rescue,+ kickoff_reason=kickoff_reason,+ )except (ValueError, SandboxInferenceError, Action.DoesNotExist) as exc:# run_training refuses a departed creator or an unresolvable target before it writes# anything. A retry cannot fix either, so these report instead of raising.@@ -790,7 +795,7 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResulif rescue:logger.info("autoresearch_kickoff_training_rescue", pipeline_id=inp.pipeline_id)return KickoffTrainingResult(kicked_off=True, reason="rescue_unscorable")- return KickoffTrainingResult(kicked_off=True, reason="started")+ return KickoffTrainingResult(kicked_off=True, reason=kickoff_reason.value)def _sweep_access_block(pipeline: AutoresearchPipeline) -> str | None:diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex fa99183f5544..fda8c9b3345a 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -909,15 +909,18 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):# ──────────────────────────────────────── train action ────────────────────────────────────────def test_start_training(self):- pipeline = self._make_pipeline()+ pipeline = self._make_pipeline(iterations_per_run=8)# The run must not exist before the call: the endpoint rejects pipelines that# already have a live run, so the mock creates it the way run_training would.- def _fake_run_training(*, pipeline: AutoresearchPipeline, iteration_budget: int, user_id: Any):+ def _fake_run_training(+ *, pipeline: AutoresearchPipeline, iteration_budget: int, user_id: Any, kickoff_reason: str+ ):return AutoresearchTrainingRun.objects.create(pipeline=pipeline,status=AutoresearchTrainingRun.Status.RUNNING,iteration_budget=iteration_budget,+ kickoff_reason=kickoff_reason,)with patch("products.autoresearch.backend.training.runner.run_training", side_effect=_fake_run_training):@@ -926,6 +929,8 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):assert resp.status_code == status.HTTP_200_OKdata = resp.json()assert data["status"] == "running"+ assert data["iteration_budget"] == 8+ assert data["kickoff_reason"] == "manual"@parameterized.expand([@@ -1106,13 +1111,16 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):pipeline = self._make_trained_pipeline()resp = self.client.patch(f"{self.base_url}/{pipeline.id}/",- {"name": "Renamed", "cadence_days": 3, "iteration_budget": 20},+ {"name": "Renamed", "cadence_days": 3, "iterations_per_run": 8, "research_interval_days": None},format="json",)assert resp.status_code == status.HTTP_200_OK, resp.json()+ assert resp.json()["next_research_at"] is Nonepipeline.refresh_from_db()assert pipeline.name == "Renamed"assert pipeline.cadence_days == 3+ assert pipeline.iterations_per_run == 8+ assert pipeline.research_interval_days is Nonedef test_resubmitting_unchanged_target_after_training_is_allowed(self):pipeline = self._make_trained_pipeline()@@ -1988,6 +1996,9 @@ class TestPipelineCreateSerializerValidation(SimpleTestCase):("cadence_above_max", "cadence_days", 366),("iteration_budget_below_min", "iteration_budget", 0),("iteration_budget_above_max", "iteration_budget", 501),+ ("iterations_per_run_below_min", "iterations_per_run", 0),+ ("iterations_per_run_above_max", "iterations_per_run", 51),+ ("research_interval_days_not_a_choice", "research_interval_days", 10),("plateau_iterations_below_min", "plateau_iterations", 0),("success_auc_below_min", "success_auc", -0.1),("success_auc_above_max", "success_auc", 1.5),diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.pyindex 54347798c2e6..195a02b35735 100644--- a/products/autoresearch/backend/training/runner.py+++ b/products/autoresearch/backend/training/runner.py@@ -890,7 +890,7 @@ def _describe_unscorable_champion(unscorable: UnscorableChampion | None, *, rescif rescue:rescue_text = """- **This is a rescue run.** The pipeline has no iteration budget left, so this run gets a+ **This is a rescue run.** No research run is due for this pipeline, so this run gets asmall fixed budget only to make scoring work again. Prefer a cheap, simple model whose`features.sql` scores today's inference population well inside the query limits over amodel with a higher `holdout_score`."""@@ -941,6 +941,7 @@ def run_training(iteration_budget: int,user_id: int | None,rescue: bool = False,+ kickoff_reason: str = AutoresearchTrainingRun.KickoffReason.MANUAL,) -> AutoresearchTrainingRun:"""Launch a real agent sandbox training run.@@ -972,6 +973,7 @@ def run_training(training_run = AutoresearchTrainingRun.objects.create(pipeline=pipeline,status=AutoresearchTrainingRun.Status.RUNNING,+ kickoff_reason=kickoff_reason,iteration_budget=iteration_budget,started_at=now,)diff --git a/products/autoresearch/backend/training/schedule.py b/products/autoresearch/backend/training/schedule.pynew file mode 100644index 000000000000..4a5e4caae18a--- /dev/null+++ b/products/autoresearch/backend/training/schedule.py@@ -0,0 +1,93 @@+"""When the next scheduled research run of a pipeline is due.++Research has two phases, derived from the pipeline's training runs and never stored.+Explore starts a run on each sweep until a completed run does not promote its best model,+or until ``EXPLORE_RUN_LIMIT`` research runs have run. Maintain starts one run+``research_interval_days`` after the latest training run of any kind, so a manual run resets the clock.+"""++from collections.abc import Iterable+from datetime import UTC, datetime, time, timedelta+from typing import Literal+from uuid import UUID++from posthog.dataclasses import frozen++from ..models import AutoresearchTrainingRun++# Research runs before explore ends, if no run stopped it first. Rescue runs do not count.+EXPLORE_RUN_LIMIT = 5++TrainingPhase = Literal["explore", "maintain"]+++@frozen+class ScheduleRun:+ """The fields of one training run that the schedule reads."""++ kickoff_reason: str | None+ status: str+ champion_promoted: bool | None+ created_at: datetime+++@frozen+class ResearchSchedule:+ phase: TrainingPhase+ # The start of the UTC day from which the sweep may start the next scheduled run.+ # None when the pipeline has no scheduled research.+ next_research_at: datetime | None++ def is_due(self, now: datetime) -> bool:+ return self.next_research_at is not None and now >= self.next_research_at+++def _start_of_day(moment: datetime) -> datetime:+ return datetime.combine(moment.astimezone(UTC).date(), time.min, tzinfo=UTC)+++def _ends_explore(run: ScheduleRun) -> bool:+ return run.status == AutoresearchTrainingRun.Status.COMPLETED and run.champion_promoted is False+++def research_schedule(+ *, research_interval_days: int | None, pipeline_created_at: datetime, runs: Iterable[ScheduleRun]+) -> ResearchSchedule:+ runs = list(runs)+ research_runs = [+ run+ for run in runs+ if run.kickoff_reason != AutoresearchTrainingRun.KickoffReason.RESCUE+ and run.status in (AutoresearchTrainingRun.Status.COMPLETED, AutoresearchTrainingRun.Status.FAILED)+ ]+ exploring = len(research_runs) < EXPLORE_RUN_LIMIT and not any(_ends_explore(run) for run in research_runs)+ phase: TrainingPhase = "explore" if exploring else "maintain"+ if research_interval_days is None:+ return ResearchSchedule(phase=phase, next_research_at=None)+ latest = max((run.created_at for run in runs), default=None)+ if latest is None:+ return ResearchSchedule(phase=phase, next_research_at=_start_of_day(pipeline_created_at))+ # By calendar day, like the scoring cadence: a run starts some time after the daily tick, and an+ # elapsed-time comparison would push each run one sweep later than the interval.+ gap = timedelta(days=1 if exploring else research_interval_days)+ return ResearchSchedule(phase=phase, next_research_at=_start_of_day(latest) + gap)+++def schedule_runs_for(pipeline_ids: Iterable[UUID], team_id: int) -> dict[UUID, list[ScheduleRun]]:+ """The schedule fields of every training run of these pipelines, in one query."""+ runs: dict[UUID, list[ScheduleRun]] = {}+ rows = (+ AutoresearchTrainingRun.objects.for_team(team_id)+ .filter(pipeline_id__in=list(pipeline_ids))+ .values_list("pipeline_id", "kickoff_reason", "status", "summary__champion_promoted", "created_at")+ )+ for pipeline_id, kickoff_reason, status, champion_promoted, created_at in rows:+ runs.setdefault(pipeline_id, []).append(+ ScheduleRun(+ kickoff_reason=kickoff_reason,+ status=status,+ champion_promoted=champion_promoted if isinstance(champion_promoted, bool) else None,+ created_at=created_at,+ )+ )+ return runsdiff --git a/products/autoresearch/backend/training/test_agent_recorded_training.py b/products/autoresearch/backend/training/test_agent_recorded_training.pyindex a049bc4c5a20..171dd3c9ab76 100644--- a/products/autoresearch/backend/training/test_agent_recorded_training.py+++ b/products/autoresearch/backend/training/test_agent_recorded_training.py@@ -104,6 +104,7 @@ class TestAgentRecordedTraining(TeamScopedTestMixin, APIBaseTest):data = resp.json()assert data["status"] == "running"assert data["iteration_budget"] == 7+ assert data["kickoff_reason"] == "manual"run = AutoresearchTrainingRun.objects.get(pk=data["id"], team_id=self.team.pk)assert run.pipeline.pk == self.pipeline.pkassert run.started_at is not Nonediff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.mdindex 683fc904f5eb..88d35f056132 100644--- a/products/autoresearch/frontend/AGENTS.md+++ b/products/autoresearch/frontend/AGENTS.md@@ -18,6 +18,7 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st| `newModel/` | Create-form parts: template chips, definition sentence, Advanced section, readiness checklist, "What happens next". || `autoresearchPipelineLogic.ts` | Detail logic. Also maps the old `?tab=` keys to the four tabs, so saved links still open. || `pipelineLifecycle.ts` | The five lifecycle steps (question set to checked against reality) and which one is current. |+| `trainingScheduleLogic.ts` | Setup tab training schedule: the research interval and experiments per run, their save, and the one-line phase and next run status. || `agentSearch.ts` | The agent's search across training runs: chart points, best score so far, change per experiment within a run, log groups and status brief. || `onlinePerformance.ts` | Accuracy tab helpers over the `online_performance` endpoint: the stat tiles, the realized AUC series, predicted against actual by segment. || `predictionCoverage.ts` | Predictions tab coverage from the runs list: the measured summary and the coverage and score age per day. |@@ -52,7 +53,7 @@ Follow `frontend/src/AGENTS.md` — it applies to product frontends too.- TypeScript with explicit return types; Tailwind utilities rather than inline styles.- Reuse Lemon / quill components instead of hand-rolling tables, badges, or tags.- Any button that fires a request must guard against double-submission — `loading` / `disabledReason` on `LemonButton`, reset on both success and error paths. The lifecycle actions here (train, score, archive, pause, resume) are all network calls, and several are expensive: firing `train` twice starts two sandbox agent runs and spends the budget twice.-- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab, `autoresearch model experiment log filter changed` (with `filter`), `autoresearch model accuracy cutoff changed` (with `cutoff`), `autoresearch model search point clicked` (with `run_id`, `iteration_number`, `status`), `autoresearch model experiment details opened` (with `run_id`, `iteration_number`) when a person opens an experiment's working notes, `autoresearch model suggestion sent` (with `priority`), `autoresearch agent research experiment opened` (with `run_id`, `iteration_number`, `status`, `source`: `chart` or `log`) when a person opens the experiment drawer, `autoresearch agent research steer opened` (with `queued_count`) and `autoresearch agent research full notes opened` (with `run_number`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab, `autoresearch model experiment log filter changed` (with `filter`), `autoresearch model accuracy cutoff changed` (with `cutoff`), `autoresearch model search point clicked` (with `run_id`, `iteration_number`, `status`), `autoresearch model experiment details opened` (with `run_id`, `iteration_number`) when a person opens an experiment's working notes, `autoresearch model suggestion sent` (with `priority`), `autoresearch agent research experiment opened` (with `run_id`, `iteration_number`, `status`, `source`: `chart` or `log`) when a person opens the experiment drawer, `autoresearch agent research steer opened` (with `queued_count`) `autoresearch agent research full notes opened` (with `run_number`) and `autoresearch training schedule changed` (with `research_interval_days` and `iterations_per_run`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.## Copydiff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsxindex cf3e942b07dc..e035090c1261 100644--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx@@ -30,6 +30,10 @@ const pipeline = {cadence_days: 1,iteration_budget: 20,iteration_budget_remaining: 6,+ iterations_per_run: 5,+ research_interval_days: 7,+ training_phase: 'maintain',+ next_research_at: '2026-11-12T00:00:00Z',success_auc: null,plateau_iterations: 5,output_person_property: 'p_file_shared_7d',@@ -250,6 +254,7 @@ const trainingRuns = [{id: 'training-3',pipeline: PIPELINE_ID,+ kickoff_reason: 'scheduled',task_url: null,status: 'failed',iteration_count: 0,@@ -267,6 +272,7 @@ const trainingRuns = [{id: 'training-2',pipeline: PIPELINE_ID,+ kickoff_reason: 'explore',task_url: null,status: 'completed',iteration_count: 5,@@ -290,6 +296,7 @@ const trainingRuns = [{id: 'training-1',pipeline: PIPELINE_ID,+ kickoff_reason: 'manual',task_url: null,status: 'completed',iteration_count: 4,diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex 3f1515e25f1e..ef897e7f95e8 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -7,6 +7,34 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90+ */+export type ResearchIntervalDaysEnumApi = (typeof ResearchIntervalDaysEnumApi)[keyof typeof ResearchIntervalDaysEnumApi]++export const ResearchIntervalDaysEnumApi = {+ Number7: 7,+ Number14: 14,+ Number30: 30,+ Number60: 60,+ Number90: 90,+} as const++/**+ * * `explore` - Explore+ * * `maintain` - Maintain+ */+export type TrainingPhaseEnumApi = (typeof TrainingPhaseEnumApi)[keyof typeof TrainingPhaseEnumApi]++export const TrainingPhaseEnumApi = {+ Explore: 'explore',+ Maintain: 'maintain',+} as const+/*** * `draft` - Draft* * `bootstrapping` - Bootstrapping@@ -218,13 +246,33 @@ export interface AutoresearchPipelineApi {*/cadence_days?: number/**- * Total training iterations allowed for the autoresearch loop.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum -2147483648* @maximum 2147483647*/iteration_budget?: number- /** Iterations remaining in the current budget. */+ /** Deprecated: scheduled training no longer reads or spends it. */readonly iteration_budget_remaining: number+ /** Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. */+ readonly iterations_per_run: number+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ readonly research_interval_days: ResearchIntervalDaysEnumApi | null+ /** explore: a research run on each scoring day until a run does not promote a better model, or until 5 research runs have run. maintain: one research run every research_interval_days.+ *+ * * `explore` - Explore+ * * `maintain` - Maintain */+ readonly training_phase: TrainingPhaseEnumApi+ /**+ * Start of the UTC day from which the daily sweep can start the next scheduled research run. Null when research_interval_days is null.+ * @nullable+ */+ readonly next_research_at: string | null/*** Target AUC threshold. Training stops early if this score is reached.* @nullable@@ -387,11 +435,25 @@ export interface AutoresearchPipelineCreateApi {*/cadence_days?: number/**- * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum 1* @maximum 500*/iteration_budget?: number+ /**+ * Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.+ * @minimum 1+ * @maximum 50+ */+ iterations_per_run?: number+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ research_interval_days?: ResearchIntervalDaysEnumApi | null/*** Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.* @minimum 0@@ -798,6 +860,22 @@ export interface RespondToSuggestionApi {agent_response?: string}+/**+ * * `explore` - Explore+ * * `scheduled` - Scheduled+ * * `rescue` - Rescue+ * * `manual` - Manual+ */+export type AutoresearchTrainingRunKickoffReasonEnumApi =+ (typeof AutoresearchTrainingRunKickoffReasonEnumApi)[keyof typeof AutoresearchTrainingRunKickoffReasonEnumApi]++export const AutoresearchTrainingRunKickoffReasonEnumApi = {+ Explore: 'explore',+ Scheduled: 'scheduled',+ Rescue: 'rescue',+ Manual: 'manual',+} as const+/*** One iteration referenced from a run summary's ladder or dead-ends list.*/@@ -946,6 +1024,13 @@ export interface AutoresearchTrainingRunApi {* * `completed` - Completed* * `failed` - Failed */readonly status: ZendeskImportJobStatusEnumApi+ /** Why the run started: explore (the first burst of daily runs), scheduled (the research interval), rescue (the champion cannot score) or manual (a person or an agent asked). Null for older runs.+ *+ * * `explore` - Explore+ * * `scheduled` - Scheduled+ * * `rescue` - Rescue+ * * `manual` - Manual */+ readonly kickoff_reason: AutoresearchTrainingRunKickoffReasonEnumApi | null/*** Maximum iterations allowed for this run.* @minimum -2147483648@@ -1007,7 +1092,7 @@ export interface PaginatedAutoresearchTrainingRunListApi {*/export interface OpenTrainingRunApi {/**- * Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.+ * Iteration budget for this run. Defaults to the pipeline's iterations_per_run if omitted.* @minimum 1* @maximum 500*/@@ -1535,11 +1620,25 @@ export interface PatchedAutoresearchPipelineCreateApi {*/cadence_days?: number/**- * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum 1* @maximum 500*/iteration_budget?: number+ /**+ * Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.+ * @minimum 1+ * @maximum 50+ */+ iterations_per_run?: number+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ research_interval_days?: ResearchIntervalDaysEnumApi | null/*** Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.* @minimum 0@@ -1749,7 +1848,7 @@ export interface OnlinePerformanceApi {export interface StartTrainingRequestApi {/**- * Override the pipeline iteration budget for this training run.+ * Iterations for this training run. Defaults to the pipeline's iterations_per_run.* @minimum 1* @maximum 500*/diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.tsindex 93db9727c815..540a635bb9f5 100644--- a/products/autoresearch/frontend/generated/api.zod.ts+++ b/products/autoresearch/frontend/generated/api.zod.ts@@ -29,6 +29,8 @@ export const autoresearchCreateBodyCadenceDaysMax = 365export const autoresearchCreateBodyIterationBudgetMax = 500+export const autoresearchCreateBodyIterationsPerRunMax = 50+export const autoresearchCreateBodySuccessAucMin = 0export const autoresearchCreateBodySuccessAucMax = 1@@ -99,7 +101,26 @@ export const AutoresearchCreateBody = /* @__PURE__ */ zod.object({.min(1).max(autoresearchCreateBodyIterationBudgetMax).optional()- .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ .describe('Deprecated: scheduled training no longer reads it. Use iterations_per_run.'),+ iterations_per_run: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyIterationsPerRunMax)+ .optional()+ .describe(+ 'Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.'+ ),+ research_interval_days: zod+ .union([+ zod+ .union([zod.literal(7), zod.literal(14), zod.literal(30), zod.literal(60), zod.literal(90)])+ .describe('\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.\n\n\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'+ ),success_auc: zod.number().min(autoresearchCreateBodySuccessAucMin)@@ -188,7 +209,7 @@ export const AutoresearchTrainingRunsCreateBody = /* @__PURE__ */ zod.min(1).max(autoresearchTrainingRunsCreateBodyIterationBudgetMax).optional()- .describe("Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted."),+ .describe("Iteration budget for this run. Defaults to the pipeline's iterations_per_run if omitted."),}).describe('Input for opening an agent-driven training run.')@@ -506,6 +527,8 @@ export const autoresearchUpdateBodyCadenceDaysMax = 365export const autoresearchUpdateBodyIterationBudgetMax = 500+export const autoresearchUpdateBodyIterationsPerRunMax = 50+export const autoresearchUpdateBodySuccessAucMin = 0export const autoresearchUpdateBodySuccessAucMax = 1@@ -576,7 +599,26 @@ export const AutoresearchUpdateBody = /* @__PURE__ */ zod.object({.min(1).max(autoresearchUpdateBodyIterationBudgetMax).optional()- .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ .describe('Deprecated: scheduled training no longer reads it. Use iterations_per_run.'),+ iterations_per_run: zod+ .number()+ .min(1)+ .max(autoresearchUpdateBodyIterationsPerRunMax)+ .optional()+ .describe(+ 'Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.'+ ),+ research_interval_days: zod+ .union([+ zod+ .union([zod.literal(7), zod.literal(14), zod.literal(30), zod.literal(60), zod.literal(90)])+ .describe('\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.\n\n\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'+ ),success_auc: zod.number().min(autoresearchUpdateBodySuccessAucMin)@@ -624,6 +666,8 @@ export const autoresearchPartialUpdateBodyCadenceDaysMax = 365export const autoresearchPartialUpdateBodyIterationBudgetMax = 500+export const autoresearchPartialUpdateBodyIterationsPerRunMax = 50+export const autoresearchPartialUpdateBodySuccessAucMin = 0export const autoresearchPartialUpdateBodySuccessAucMax = 1@@ -694,7 +738,26 @@ export const AutoresearchPartialUpdateBody = /* @__PURE__ */ zod.object({.min(1).max(autoresearchPartialUpdateBodyIterationBudgetMax).optional()- .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ .describe('Deprecated: scheduled training no longer reads it. Use iterations_per_run.'),+ iterations_per_run: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyIterationsPerRunMax)+ .optional()+ .describe(+ 'Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.'+ ),+ research_interval_days: zod+ .union([+ zod+ .union([zod.literal(7), zod.literal(14), zod.literal(30), zod.literal(60), zod.literal(90)])+ .describe('\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.\n\n\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'+ ),success_auc: zod.number().min(autoresearchPartialUpdateBodySuccessAucMin)@@ -734,7 +797,7 @@ export const AutoresearchTrainCreateBody = /* @__PURE__ */ zod.object({.min(1).max(autoresearchTrainCreateBodyIterationBudgetMax).optional()- .describe('Override the pipeline iteration budget for this training run.'),+ .describe("Iterations for this training run. Defaults to the pipeline's iterations_per_run."),})/**diff --git a/products/autoresearch/frontend/pipeline/SetupTab.tsx b/products/autoresearch/frontend/pipeline/SetupTab.tsxindex 4a82d3f053e7..f021b5b85b7a 100644--- a/products/autoresearch/frontend/pipeline/SetupTab.tsx+++ b/products/autoresearch/frontend/pipeline/SetupTab.tsx@@ -1,15 +1,28 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { LemonSkeleton } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'-import { AutoresearchPipelineApi } from '../generated/api.schemas'+import { AutoresearchPipelineApi, ResearchIntervalDaysEnumApi } from '../generated/api.schemas'+import {+ MAX_ITERATIONS_PER_RUN,+ MIN_ITERATIONS_PER_RUN,+ trainingScheduleLogic,+ trainingScheduleStatus,+} from '../trainingScheduleLogic'import { MetricCard } from './MetricCard'import { PersonPropertySetting } from './PersonPropertySetting'import { SectionCard } from './SectionCard'+const ONLY_WHEN_ASKED = 'only_when_asked'++const RESEARCH_INTERVAL_OPTIONS: { value: ResearchIntervalDaysEnumApi | typeof ONLY_WHEN_ASKED; label: string }[] = [+ ...Object.values(ResearchIntervalDaysEnumApi).map((days) => ({ value: days, label: `Every ${days} days` })),+ { value: ONLY_WHEN_ASKED, label: 'Only when I ask' },+]+export function SetupTab(): JSX.Element {const { pipeline } = useValues(autoresearchPipelineLogic)if (!pipeline) {@@ -20,22 +33,19 @@ export function SetupTab(): JSX.Element {title="Model definition"description={<>- Editing the target, populations, and budget in the UI is coming soon. For now, use the{' '}+ Editing the target and populations in the UI is coming soon. For now, use the{' '}<code>autoresearch</code> API or MCP tools, or recreate the model.</>}><div className="@container">- <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-4">+ <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-3"><MetricCard label="Target event" value={pipeline.target_event} /><MetricCard label="Prediction horizon" value={`${pipeline.horizon_days ?? '—'}d`} /><MetricCard label="Training lookback" value={`${pipeline.training_lookback_days ?? '—'}d`} />- <MetricCard- label="Budget remaining"- value={`${pipeline.iteration_budget_remaining} / ${pipeline.iteration_budget ?? '—'}`}- /></div></div>+ <TrainingScheduleSetting pipeline={pipeline} /><PersonPropertySetting source="setup_tab" /><div><DetailRow label="Output person property">@@ -56,6 +66,53 @@ export function SetupTab(): JSX.Element {)}+function TrainingScheduleSetting({ pipeline }: { pipeline: AutoresearchPipelineApi }): JSX.Element {+ const { schedule, savingSchedule, saveDisabledReason } = useValues(trainingScheduleLogic({ id: pipeline.id }))+ const { setResearchIntervalDays, setIterationsPerRun, saveSchedule } = useActions(+ trainingScheduleLogic({ id: pipeline.id })+ )+ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-end gap-3">+ <label className="flex flex-col gap-1">+ <span className="text-sm font-semibold">Look for a better model</span>+ <LemonSelect+ size="small"+ options={RESEARCH_INTERVAL_OPTIONS}+ value={schedule?.research_interval_days ?? ONLY_WHEN_ASKED}+ onChange={(value) => setResearchIntervalDays(value === ONLY_WHEN_ASKED ? null : value)}+ data-attr="autoresearch-research-interval"+ />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-sm font-semibold">Experiments per run</span>+ <LemonInput+ size="small"+ type="number"+ min={MIN_ITERATIONS_PER_RUN}+ max={MAX_ITERATIONS_PER_RUN}+ className="w-24"+ value={schedule?.iterations_per_run}+ onChange={(value) => setIterationsPerRun(value)}+ data-attr="autoresearch-iterations-per-run"+ />+ </label>+ <LemonButton+ type="primary"+ size="small"+ onClick={saveSchedule}+ loading={savingSchedule}+ disabledReason={saveDisabledReason}+ data-attr="autoresearch-training-schedule-save"+ >+ Save schedule+ </LemonButton>+ </div>+ <p className="text-xs text-secondary mb-0">{trainingScheduleStatus(pipeline)}</p>+ </div>+ )+}+function DetailRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {return (<div className="flex justify-between items-start gap-4 py-2 border-b last:border-0">diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsxindex 9ca6eb2843f4..d55d04eecc28 100644--- a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx@@ -11,7 +11,11 @@ import { urls } from 'scenes/urls'import { runHeadline } from '../agentSearch'import { autoresearchPipelineLogic, trainingRunProgress } from '../autoresearchPipelineLogic'-import { type AutoresearchRunApi, AutoresearchTrainingRunApi } from '../generated/api.schemas'+import {+ type AutoresearchRunApi,+ AutoresearchTrainingRunApi,+ type AutoresearchTrainingRunKickoffReasonEnumApi,+} from '../generated/api.schemas'import { RunFeatureComparison } from './RunFeatureComparison'// Derived from the field rather than the standalone enum: this pending/running/completed/failed@@ -28,6 +32,13 @@ const RUN_STATUS: Record<failed: { type: 'danger', label: 'Failed' },}+const KICKOFF_REASON: Record<AutoresearchTrainingRunKickoffReasonEnumApi, { label: string; tooltip: string }> = {+ explore: { label: 'Exploring', tooltip: 'One of the first daily runs that look for a better model' },+ scheduled: { label: 'Scheduled', tooltip: 'Started on the research schedule set on the Setup tab' },+ rescue: { label: 'Rescue', tooltip: 'A short run to replace a model that stopped scoring' },+ manual: { label: 'Manual', tooltip: 'Started by a person or an agent' },+}+/** The agent-authored report.md for a run, rendered as markdown (with mermaid charts). */function RunReport({ runId }: { runId: string }): JSX.Element | null {const { reportByRun, reportByRunLoading } = useValues(autoresearchPipelineLogic)@@ -117,6 +128,11 @@ export function TrainingRunRow({{duration ? ` · ${duration}` : ''}</span></Tooltip>+ {run.kickoff_reason && (+ <Tooltip title={KICKOFF_REASON[run.kickoff_reason].tooltip}>+ <span>· {KICKOFF_REASON[run.kickoff_reason].label}</span>+ </Tooltip>+ )}{run.task_url && (<Linkto={run.task_url}diff --git a/products/autoresearch/frontend/trainingScheduleLogic.ts b/products/autoresearch/frontend/trainingScheduleLogic.tsnew file mode 100644index 000000000000..ceedd191bcd4--- /dev/null+++ b/products/autoresearch/frontend/trainingScheduleLogic.ts@@ -0,0 +1,170 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { AutoresearchPipelineLogicProps, autoresearchPipelineLogic } from './autoresearchPipelineLogic'+import { autoresearchPartialUpdate } from './generated/api'+import type { AutoresearchPipelineApi, ResearchIntervalDaysEnumApi } from './generated/api.schemas'++export const MIN_ITERATIONS_PER_RUN = 1+export const MAX_ITERATIONS_PER_RUN = 50++export interface TrainingScheduleDraft {+ research_interval_days: ResearchIntervalDaysEnumApi | null+ iterations_per_run: number | undefined+}++/** One line on what training does next, from the saved schedule. */+export function trainingScheduleStatus(pipeline: AutoresearchPipelineApi, now: dayjs.Dayjs = dayjs()): string {+ if (pipeline.research_interval_days === null || !pipeline.next_research_at) {+ return 'Training starts only when you ask for it.'+ }+ if (pipeline.training_phase === 'explore') {+ return 'Exploring: training on each scoring day until a run stops improving the model.'+ }+ const next = dayjs(pipeline.next_research_at)+ if (!next.isAfter(now)) {+ return 'Next research run on the next scoring day.'+ }+ return `Next research run on ${next.format('MMM D')}.`+}++export interface trainingScheduleLogicValues {+ currentTeamId: number | null+ pipeline: AutoresearchPipelineApi | null+ draft: Partial<TrainingScheduleDraft>+ savingSchedule: boolean+ schedule: TrainingScheduleDraft | null+ saveDisabledReason: string | undefined+}++export interface trainingScheduleLogicActions {+ loadPipelineSuccess: (pipeline: AutoresearchPipelineApi | null) => {+ pipeline: AutoresearchPipelineApi | null+ payload?: any+ }+ setResearchIntervalDays: (days: ResearchIntervalDaysEnumApi | null) => {+ days: ResearchIntervalDaysEnumApi | null+ }+ setIterationsPerRun: (iterations: number | undefined) => { iterations: number | undefined }+ resetDraft: () => { value: true }+ saveSchedule: () => { value: true }+ saveScheduleFinished: () => { value: true }+}++export type trainingScheduleLogicType = MakeLogicType<+ trainingScheduleLogicValues,+ trainingScheduleLogicActions,+ AutoresearchPipelineLogicProps+>++export const trainingScheduleLogic = kea<trainingScheduleLogicType>([+ props({} as AutoresearchPipelineLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'autoresearch', 'frontend', 'trainingScheduleLogic', key]),+ connect((props: AutoresearchPipelineLogicProps) => ({+ values: [teamLogic, ['currentTeamId'], autoresearchPipelineLogic(props), ['pipeline']],+ actions: [autoresearchPipelineLogic(props), ['loadPipelineSuccess']],+ })),+ actions({+ setResearchIntervalDays: (days: ResearchIntervalDaysEnumApi | null) => ({ days }),+ setIterationsPerRun: (iterations: number | undefined) => ({ iterations }),+ resetDraft: true,+ saveSchedule: true,+ saveScheduleFinished: true,+ }),+ reducers({+ // The unsaved edits. A field that is not here shows its saved value.+ draft: [+ {} as Partial<TrainingScheduleDraft>,+ {+ setResearchIntervalDays: (state, { days }) => ({ ...state, research_interval_days: days }),+ setIterationsPerRun: (state, { iterations }) => ({ ...state, iterations_per_run: iterations }),+ resetDraft: () => ({}),+ },+ ],+ savingSchedule: [+ false,+ {+ saveSchedule: () => true,+ saveScheduleFinished: () => false,+ },+ ],+ }),+ selectors({+ schedule: [+ (s) => [s.pipeline, s.draft],+ (pipeline: AutoresearchPipelineApi | null, draft: Partial<TrainingScheduleDraft>) =>+ pipeline ? { ...pickSchedule(pipeline), ...draft } : null,+ ],+ saveDisabledReason: [+ (s) => [s.pipeline, s.schedule, s.savingSchedule],+ (+ pipeline: AutoresearchPipelineApi | null,+ schedule: TrainingScheduleDraft | null,+ savingSchedule: boolean+ ): string | undefined => {+ if (savingSchedule) {+ return 'The schedule is saving'+ }+ if (!pipeline || !schedule) {+ return 'The model is loading'+ }+ const iterations = schedule.iterations_per_run+ if (+ iterations === undefined ||+ !Number.isInteger(iterations) ||+ iterations < MIN_ITERATIONS_PER_RUN ||+ iterations > MAX_ITERATIONS_PER_RUN+ ) {+ return `Enter ${MIN_ITERATIONS_PER_RUN} to ${MAX_ITERATIONS_PER_RUN} experiments per run`+ }+ const saved = pickSchedule(pipeline)+ if (+ saved.iterations_per_run === iterations &&+ saved.research_interval_days === schedule.research_interval_days+ ) {+ return 'Change a setting to save'+ }+ return undefined+ },+ ],+ }),+ listeners(({ actions, values, props }) => ({+ saveSchedule: async () => {+ const { schedule, currentTeamId } = values+ if (!schedule || schedule.iterations_per_run === undefined || !currentTeamId) {+ actions.saveScheduleFinished()+ return+ }+ const changes = {+ research_interval_days: schedule.research_interval_days,+ iterations_per_run: schedule.iterations_per_run,+ }+ try {+ actions.loadPipelineSuccess(await autoresearchPartialUpdate(String(currentTeamId), props.id, changes))+ actions.resetDraft()+ posthog.capture('autoresearch training schedule changed', { pipeline_id: props.id, ...changes })+ lemonToast.success('Training schedule saved.')+ } catch {+ posthog.capture('autoresearch model action failed', {+ action: 'training_schedule',+ pipeline_id: props.id,+ })+ lemonToast.error("Couldn't save the training schedule. Try again.")+ } finally {+ actions.saveScheduleFinished()+ }+ },+ })),+])++function pickSchedule(pipeline: AutoresearchPipelineApi): TrainingScheduleDraft {+ return {+ research_interval_days: pipeline.research_interval_days,+ iterations_per_run: pipeline.iterations_per_run,+ }+}diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yamlindex c13208ba9b0b..f4c631233a23 100644--- a/products/autoresearch/mcp/tools.yaml+++ b/products/autoresearch/mcp/tools.yaml@@ -44,7 +44,10 @@ tools:target_event, or from the action name when target_event is omitted, if you do not set it. It must be uniqueamong the project's non-archived pipelines. Scores are written to that person property only whenwrite_person_property is true (default false); prediction events, validation and segments work without it.- After creating, call autoresearch-train-create to start an asynchronous agent training run.+ iterations_per_run (default 5) sets the experiments in each training run. research_interval_days (7, 14, 30,+ 60 or 90, default 7; null means only when asked) sets how often scheduled research runs once the first burst+ of daily runs ends. After creating, call autoresearch-train-create to start an asynchronous agent training+ run.exclude_params:- id- created_by@@ -78,8 +81,10 @@ tools:- target_event- horizon_days- status- - iteration_budget- - iteration_budget_remaining+ - iterations_per_run+ - research_interval_days+ - training_phase+ - next_research_at- last_scored_at- created_at- updated_at@@ -189,8 +194,9 @@ tools:people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts acleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list).Changing write_person_property needs the person:write scope. Prediction events, online validation and- segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two- populations cannot change once a model has been trained.+ segments work with it off. Use iterations_per_run and research_interval_days to change the training+ schedule; null research_interval_days stops scheduled research. target_event, target_definition,+ horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.exclude_params:- id- created_by@@ -465,7 +471,8 @@ tools:and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access,because the run is a cloud sandbox. After a run promotes a champion, the daily 02:00 UTC scoring job scoresthe inference population and emits autoresearch_prediction events. To score now instead, call- autoresearch-score-create once. You can optionally override the iteration_budget for this run. A pipeline+ autoresearch-score-create once. The run uses the pipeline's iterations_per_run unless you override+ iteration_budget for this run. A manual run resets the clock for the next scheduled research run. A pipelinewith an action target also needs the action:read scope.feature_flag: autoresearchautoresearch-training-runs-artifacts-delete-create:@@ -667,6 +674,7 @@ tools:- id- pipeline- status+ - kickoff_reason- iteration_budget- iteration_count- best_holdout_scorediff --git a/products/autoresearch/skills/working-with-autoresearch/SKILL.md b/products/autoresearch/skills/working-with-autoresearch/SKILL.mdindex 1817a84a2669..d44ad93df16c 100644--- a/products/autoresearch/skills/working-with-autoresearch/SKILL.md+++ b/products/autoresearch/skills/working-with-autoresearch/SKILL.md@@ -25,6 +25,10 @@ For example, "which active users will open a report in the next 7 days?".Each scored person gets an `autoresearch_prediction` event with their probability.When the model's `write_person_property` is on, a person who resolves to a current distinct ID also gets the model's output person property, for example `predicted_p_adopt_insights_14d`. It is off by default for new models. Turn it on with `autoresearch-partial-update` before you target people by score in a flag, cohort, workflow or insight. Turning it off removes the property from the people the model scored. Changing the setting needs the `person:write` scope.5. When a prediction date's horizon has passed, online validation checks the scores against what really happened and records **realized AUC**.+6. Training keeps going on a schedule. On each scoring day the model starts a research run (**explore**) until a run does not promote a better model, or until 5 research runs have run.+ After that it starts one research run every `research_interval_days` (**maintain**, default 7) after the latest training run, so a run started by hand resets the clock.+ With `research_interval_days` null the model trains only when someone asks. A champion that cannot score still gets a short rescue run.+ `training_phase` and `next_research_at` on `posthog:autoresearch-retrieve` say where the model is.In the PostHog UI the entity is a **model**. The API and tools call it a **pipeline**. Use "model" when you talk to people.diff --git a/products/autoresearch/skills/working-with-autoresearch/references/defining-a-question.md b/products/autoresearch/skills/working-with-autoresearch/references/defining-a-question.mdindex 0baf39154072..cae9473e5b02 100644--- a/products/autoresearch/skills/working-with-autoresearch/references/defining-a-question.md+++ b/products/autoresearch/skills/working-with-autoresearch/references/defining-a-question.md@@ -43,7 +43,9 @@ Pass the same fields to `posthog:autoresearch-validate-create` and `posthog:auto| `training_population` | Who can be a training example. `{}` means all identified users. || `inference_population` | Who gets scored. Defaults to the training population. Keep the two consistent unless there is a clear reason. || `cadence_days` | Rescore every N days. Default 1. |-| `iteration_budget` | The model's total experiment budget across all training runs. Default 50. Each scheduled retrain takes at most 10 from what remains, and a run started by hand can set its own budget. |+| `iterations_per_run` | The experiments in each training run, 1 to 50. Default 5. Scheduled runs and a run started by hand use it, and a run started by hand can override it. |+| `research_interval_days` | How often scheduled research runs once the first burst ends: 7, 14, 30, 60 or 90 days, or null for only when asked. Default 7. |+| `iteration_budget` | Deprecated. Scheduled training no longer reads or spends it. || `output_person_property` | Optional. Derived from the target and horizon when omitted. |### Population shapesdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 01be6559467c..ba958d1205b5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1090,7 +1090,7 @@}},"autoresearch-create": {- "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. After creating, call autoresearch-train-create to start an asynchronous agent training run.",+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. iterations_per_run (default 5) sets the experiments in each training run. research_interval_days (7, 14, 30, 60 or 90, default 7; null means only when asked) sets how often scheduled research runs once the first burst of daily runs ends. After creating, call autoresearch-train-create to start an asynchronous agent training run.","category": "Autoresearch","feature": "autoresearch","summary": "Create a pipeline",@@ -1180,7 +1180,7 @@"feature_flag": "autoresearch"},"autoresearch-partial-update": {- "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.",+ "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. Use iterations_per_run and research_interval_days to change the training schedule; null research_interval_days stops scheduled research. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.","category": "Autoresearch","feature": "autoresearch","summary": "Update a pipeline",@@ -1300,7 +1300,7 @@"feature_flag": "autoresearch"},"autoresearch-train-create": {- "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily 02:00 UTC scoring job scores the inference population and emits autoresearch_prediction events. To score now instead, call autoresearch-score-create once. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily 02:00 UTC scoring job scores the inference population and emits autoresearch_prediction events. To score now instead, call autoresearch-score-create once. The run uses the pipeline's iterations_per_run unless you override iteration_budget for this run. A manual run resets the clock for the next scheduled research run. A pipeline with an action target also needs the action:read scope.","category": "Autoresearch","feature": "autoresearch","summary": "Start training",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ca7f33410dfc..415be047ad4d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1105,7 +1105,7 @@}},"autoresearch-create": {- "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. After creating, call autoresearch-train-create to start an asynchronous agent training run.",+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. iterations_per_run (default 5) sets the experiments in each training run. research_interval_days (7, 14, 30, 60 or 90, default 7; null means only when asked) sets how often scheduled research runs once the first burst of daily runs ends. After creating, call autoresearch-train-create to start an asynchronous agent training run.","category": "Autoresearch","feature": "autoresearch","summary": "Create a pipeline",@@ -1195,7 +1195,7 @@"feature_flag": "autoresearch"},"autoresearch-partial-update": {- "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.",+ "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. Use iterations_per_run and research_interval_days to change the training schedule; null research_interval_days stops scheduled research. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.","category": "Autoresearch","feature": "autoresearch","summary": "Update a pipeline",@@ -1315,7 +1315,7 @@"feature_flag": "autoresearch"},"autoresearch-train-create": {- "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily 02:00 UTC scoring job scores the inference population and emits autoresearch_prediction events. To score now instead, call autoresearch-score-create once. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily 02:00 UTC scoring job scores the inference population and emits autoresearch_prediction events. To score now instead, call autoresearch-score-create once. The run uses the pipeline's iterations_per_run unless you override iteration_budget for this run. A manual run resets the clock for the next scheduled research run. A pipeline with an action target also needs the action:read scope.","category": "Autoresearch","feature": "autoresearch","summary": "Start training",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6472a6acd236..62dfe3cb771e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14054,6 +14054,36 @@ export namespace Schemas {*/export type AutoresearchPipelineInferencePopulation = { [key: string]: unknown };+ /**+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90+ */+ export type ResearchIntervalDaysEnum = typeof ResearchIntervalDaysEnum[keyof typeof ResearchIntervalDaysEnum];+++ export const ResearchIntervalDaysEnum = {+ Number7: 7,+ Number14: 14,+ Number30: 30,+ Number60: 60,+ Number90: 90,+ } as const;++ /**+ * * `explore` - Explore+ * * `maintain` - Maintain+ */+ export type TrainingPhaseEnum = typeof TrainingPhaseEnum[keyof typeof TrainingPhaseEnum];+++ export const TrainingPhaseEnum = {+ Explore: 'explore',+ Maintain: 'maintain',+ } as const;+/*** * `draft` - Draft* * `bootstrapping` - Bootstrapping@@ -14152,13 +14182,33 @@ export namespace Schemas {*/cadence_days?: number;/**- * Total training iterations allowed for the autoresearch loop.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum -2147483648* @maximum 2147483647*/iteration_budget?: number;- /** Iterations remaining in the current budget. */+ /** Deprecated: scheduled training no longer reads or spends it. */readonly iteration_budget_remaining: number;+ /** Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. */+ readonly iterations_per_run: number;+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ readonly research_interval_days: ResearchIntervalDaysEnum | null;+ /** explore: a research run on each scoring day until a run does not promote a better model, or until 5 research runs have run. maintain: one research run every research_interval_days.+ *+ * * `explore` - Explore+ * * `maintain` - Maintain */+ readonly training_phase: TrainingPhaseEnum;+ /**+ * Start of the UTC day from which the daily sweep can start the next scheduled research run. Null when research_interval_days is null.+ * @nullable+ */+ readonly next_research_at: string | null;/*** Target AUC threshold. Training stops early if this score is reached.* @nullable@@ -14310,11 +14360,25 @@ export namespace Schemas {*/cadence_days?: number;/**- * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum 1* @maximum 500*/iteration_budget?: number;+ /**+ * Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.+ * @minimum 1+ * @maximum 50+ */+ iterations_per_run?: number;+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ research_interval_days?: ResearchIntervalDaysEnum | null;/*** Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.* @minimum 0@@ -14495,6 +14559,22 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * * `explore` - Explore+ * * `scheduled` - Scheduled+ * * `rescue` - Rescue+ * * `manual` - Manual+ */+ export type AutoresearchTrainingRunKickoffReasonEnum = typeof AutoresearchTrainingRunKickoffReasonEnum[keyof typeof AutoresearchTrainingRunKickoffReasonEnum];+++ export const AutoresearchTrainingRunKickoffReasonEnum = {+ Explore: 'explore',+ Scheduled: 'scheduled',+ Rescue: 'rescue',+ Manual: 'manual',+ } as const;+/*** One iteration referenced from a run summary's ladder or dead-ends list.*/@@ -14629,6 +14709,13 @@ export namespace Schemas {* * `completed` - Completed* * `failed` - Failed */readonly status: ZendeskImportJobStatusEnum;+ /** Why the run started: explore (the first burst of daily runs), scheduled (the research interval), rescue (the champion cannot score) or manual (a person or an agent asked). Null for older runs.+ *+ * * `explore` - Explore+ * * `scheduled` - Scheduled+ * * `rescue` - Rescue+ * * `manual` - Manual */+ readonly kickoff_reason: AutoresearchTrainingRunKickoffReasonEnum | null;/*** Maximum iterations allowed for this run.* @minimum -2147483648@@ -69685,7 +69772,7 @@ export namespace Schemas {*/export interface OpenTrainingRun {/**- * Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.+ * Iteration budget for this run. Defaults to the pipeline's iterations_per_run if omitted.* @minimum 1* @maximum 500*/@@ -78971,11 +79058,25 @@ export namespace Schemas {*/cadence_days?: number;/**- * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * Deprecated: scheduled training no longer reads it. Use iterations_per_run.* @minimum 1* @maximum 500*/iteration_budget?: number;+ /**+ * Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.+ * @minimum 1+ * @maximum 50+ */+ iterations_per_run?: number;+ /** Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.+ *+ * * `7` - 7+ * * `14` - 14+ * * `30` - 30+ * * `60` - 60+ * * `90` - 90 */+ research_interval_days?: ResearchIntervalDaysEnum | null;/*** Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.* @minimum 0@@ -108469,7 +108570,7 @@ export namespace Schemas {export interface StartTrainingRequest {/**- * Override the pipeline iteration budget for this training run.+ * Iterations for this training run. Defaults to the pipeline's iterations_per_run.* @minimum 1* @maximum 500*/diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.tsindex 5e6b71341eaf..d1816a99038b 100644--- a/services/mcp/src/generated/autoresearch/api.ts+++ b/services/mcp/src/generated/autoresearch/api.ts@@ -56,6 +56,8 @@ export const autoresearchCreateBodyCadenceDaysMax = 365export const autoresearchCreateBodyIterationBudgetMax = 500+export const autoresearchCreateBodyIterationsPerRunMax = 50+export const autoresearchCreateBodySuccessAucMin = 0export const autoresearchCreateBodySuccessAucMax = 1@@ -126,7 +128,26 @@ export const AutoresearchCreateBody = () => zod.object({.min(1).max(autoresearchCreateBodyIterationBudgetMax).optional()- .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ .describe('Deprecated: scheduled training no longer reads it. Use iterations_per_run.'),+ iterations_per_run: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyIterationsPerRunMax)+ .optional()+ .describe(+ 'Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.'+ ),+ research_interval_days: zod+ .union([+ zod+ .union([zod.literal(7), zod.literal(14), zod.literal(30), zod.literal(60), zod.literal(90)])+ .describe('\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.\n\n\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'+ ),success_auc: zod.number().min(autoresearchCreateBodySuccessAucMin)@@ -336,7 +357,7 @@ export const AutoresearchTrainingRunsCreateBody = () => zod.min(1).max(autoresearchTrainingRunsCreateBodyIterationBudgetMax).optional()- .describe("Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted."),+ .describe("Iteration budget for this run. Defaults to the pipeline's iterations_per_run if omitted."),}).describe('Input for opening an agent-driven training run.')@@ -753,6 +774,8 @@ export const autoresearchPartialUpdateBodyCadenceDaysMax = 365export const autoresearchPartialUpdateBodyIterationBudgetMax = 500+export const autoresearchPartialUpdateBodyIterationsPerRunMax = 50+export const autoresearchPartialUpdateBodySuccessAucMin = 0export const autoresearchPartialUpdateBodySuccessAucMax = 1@@ -823,7 +846,26 @@ export const AutoresearchPartialUpdateBody = () => zod.object({.min(1).max(autoresearchPartialUpdateBodyIterationBudgetMax).optional()- .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ .describe('Deprecated: scheduled training no longer reads it. Use iterations_per_run.'),+ iterations_per_run: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyIterationsPerRunMax)+ .optional()+ .describe(+ 'Experiments the agent may try in each training run (1-50). Each experiment costs agent time and queries, so a higher value costs more per run. Scheduled runs and Train now use it. Default: 5.'+ ),+ research_interval_days: zod+ .union([+ zod+ .union([zod.literal(7), zod.literal(14), zod.literal(30), zod.literal(60), zod.literal(90)])+ .describe('\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Days between scheduled research runs once the first burst of daily runs ends: 7, 14, 30, 60 or 90. Null means only when asked: no scheduled research, so the only training cost comes from runs you start and from rescue runs for a model that cannot score. A shorter interval costs more. Default: 7.\n\n\* `7` - 7\n\* `14` - 14\n\* `30` - 30\n\* `60` - 60\n\* `90` - 90'+ ),success_auc: zod.number().min(autoresearchPartialUpdateBodySuccessAucMin)@@ -912,7 +954,7 @@ export const AutoresearchTrainCreateBody = () => zod.object({.min(1).max(autoresearchTrainCreateBodyIterationBudgetMax).optional()- .describe('Override the pipeline iteration budget for this training run.'),+ .describe("Iterations for this training run. Defaults to the pipeline's iterations_per_run."),})/**diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.tsindex 8019441bec13..a48ec4ea51d0 100644--- a/services/mcp/src/tools/generated/autoresearch.ts+++ b/services/mcp/src/tools/generated/autoresearch.ts@@ -50,6 +50,12 @@ const autoresearchCreate = (): ToolBase<if (params.iteration_budget !== undefined) {body['iteration_budget'] = params.iteration_budget}+ if (params.iterations_per_run !== undefined) {+ body['iterations_per_run'] = params.iterations_per_run+ }+ if (params.research_interval_days !== undefined) {+ body['research_interval_days'] = params.research_interval_days+ }if (params.success_auc !== undefined) {body['success_auc'] = params.success_auc}@@ -102,8 +108,10 @@ const autoresearchList = (): ToolBase<'target_event','horizon_days','status',- 'iteration_budget',- 'iteration_budget_remaining',+ 'iterations_per_run',+ 'research_interval_days',+ 'training_phase',+ 'next_research_at','last_scored_at','created_at','updated_at',@@ -287,6 +295,12 @@ const autoresearchPartialUpdate = (): ToolBase<if (params.iteration_budget !== undefined) {body['iteration_budget'] = params.iteration_budget}+ if (params.iterations_per_run !== undefined) {+ body['iterations_per_run'] = params.iterations_per_run+ }+ if (params.research_interval_days !== undefined) {+ body['research_interval_days'] = params.research_interval_days+ }if (params.success_auc !== undefined) {body['success_auc'] = params.success_auc}@@ -886,6 +900,7 @@ const autoresearchTrainingRunsList = (): ToolBase<'id','pipeline','status',+ 'kickoff_reason','iteration_budget','iteration_count','best_holdout_score',