: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
"""
Training result ingestion: finalize a completed TaskRun for an autoresearch pipeline.
The agent records iterations live (autoresearch-training-runs-iterations-create), uploads
its model bundle (autoresearch-training-runs-artifacts-upload-create), and finalizes the
run itself (autoresearch-training-runs-complete-create). This handler is the safety net
for the case where the TaskRun ends without the agent having called complete: if it
recorded iterations, we finalize through the same server-side promotion flow; otherwise
the run produced nothing and is marked failed.
Entry point:
- handle_task_run_completed(task_run): called from the TaskRun post_save signal
registered in apps.py. Runs synchronously in the Temporal worker thread.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Protocol
from uuid import UUID
from django.db import transaction
from django.utils import timezone as django_timezone
import structlog
from products.autoresearch.backend.models import AutoresearchIteration, AutoresearchPipeline, AutoresearchTrainingRun
from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run
from products.tasks.backend.facade.api import TaskRunStatus
logger = structlog.get_logger(__name__)
class FinishedTaskRun(Protocol):
"""The fields of a terminal ``TaskRun`` that this product reads, so the tasks model stays off its import path."""
@property
def id(self) -> UUID: ...
@property
def team_id(self) -> int: ...
@property
def status(self) -> str: ...
@property
def state(self) -> object: ...
@property
def error_message(self) -> str | None: ...
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
def _task_run_satisfies_contract(run: TaskRun) -> FinishedTaskRun:
# A tasks-side rename or type change of a field read here fails mypy instead of ingestion.
# ty has no Django plugin, so it cannot see the team_id attribute the team foreign key adds.
return run # ty: ignore[invalid-return-type]
def handle_task_run_completed(task_run: FinishedTaskRun) -> None:
"""
Finalize a completed (or failed/cancelled) TaskRun for an autoresearch pipeline.
Called from the post_save signal in apps.py. Safe to call multiple times — the
training_run status check prevents double-finalization. Normally the agent finalizes
the run itself via the complete tool, in which case the run is no longer RUNNING by
the time this fires and we no-op.
"""
state = task_run.state if isinstance(task_run.state, dict) else {}
training_run_id = state.get("autoresearch_training_run_id")
if not training_run_id:
return
try:
training_run = (
AutoresearchTrainingRun.objects.for_team(task_run.team_id)
.select_related("pipeline__team")
.get(id=training_run_id)
)
except AutoresearchTrainingRun.DoesNotExist:
logger.warning(
"autoresearch_training_run_not_found",
task_run_id=str(task_run.id),
training_run_id=training_run_id,
)
return
# The state marker names a run; task_run_id, stamped server-side at dispatch, proves the binding.
if training_run.task_run_id != task_run.id:
logger.warning(
"autoresearch_training_run_task_run_mismatch",
task_run_id=str(task_run.id),
training_run_id=training_run_id,
bound_task_run_id=str(training_run.task_run_id),
)
return
# Idempotency guard: only act on a still-running run. If the agent already called
# complete, the run is COMPLETED/FAILED and there is nothing to do.
if training_run.status != AutoresearchTrainingRun.Status.RUNNING:
logger.info(
"autoresearch_training_run_already_processed",
training_run_id=training_run_id,
status=training_run.status,
)
return
if task_run.status in {TaskRunStatus.FAILED, TaskRunStatus.CANCELLED}:
_mark_failed(training_run, error=task_run.error_message or "TaskRun did not complete successfully")
return
# The agent ended without calling complete. If it recorded iterations, finalize through
# the promotion flow (which also attaches an uploaded bundle as the champion's artifact).
# If it recorded nothing, the run produced no candidate model — fail it.
if not AutoresearchIteration.objects.filter(training_run=training_run).exists():
_mark_failed(training_run, error="Agent recorded no iterations before the run ended.")
return
try:
complete_training_run(training_run)
except PromotionError as e:
logger.exception(
"autoresearch_agent_recorded_complete_failed",
training_run_id=training_run_id,
task_run_id=str(task_run.id),
)
_mark_failed(training_run, error=str(e))
except Exception:
logger.exception(
"autoresearch_agent_recorded_complete_failed",
training_run_id=training_run_id,
task_run_id=str(task_run.id),
)
_mark_failed(training_run, error="Agent-recorded run completion failed — see server logs")
def _mark_failed(training_run: AutoresearchTrainingRun, error: str) -> None:
with transaction.atomic():
# The status was read before the agent's own complete request may have committed.
# Re-read under the same lock completion takes, so a run that promoted a champion in
# that window is not flipped to FAILED (which would also revert its pipeline to draft).
locked = AutoresearchTrainingRun.objects.select_for_update().get(pk=training_run.pk)
if locked.status != AutoresearchTrainingRun.Status.RUNNING:
logger.info(
"autoresearch_training_failure_skipped_after_completion",
training_run_id=str(locked.pk),
status=locked.status,
)
return
_apply_failure(locked, error)
def _apply_failure(training_run: AutoresearchTrainingRun, error: str) -> None:
training_run.status = AutoresearchTrainingRun.Status.FAILED
training_run.completed_at = django_timezone.now()
training_run.error = error[:2000]
training_run.save(update_fields=["status", "completed_at", "error"])
# If this was the inaugural run, the pipeline is sitting in BOOTSTRAPPING with no
# champion behind it — drop it back to DRAFT so it doesn't look "live" after a failure.
# Conditional: a sibling run may have taken the pipeline live since this row was read.
AutoresearchPipeline.objects.filter(
pk=training_run.pipeline_id,
team_id=training_run.team_id,
status=AutoresearchPipeline.Status.BOOTSTRAPPING,
).update(status=AutoresearchPipeline.Status.DRAFT, updated_at=django_timezone.now())
logger.warning(
"autoresearch_training_failed",
training_run_id=str(training_run.pk),
pipeline_id=str(training_run.pipeline_id),
error=error,
)