: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(aio): show interrupted backfills and offer retry remaining (#117544)
Bernat Torres4af6db223e78
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex bb29483fb61d..ac85fb24d9e6 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -179,6 +179,15 @@ Users do not need to include items that already have a result to retry them.A provider rejection of an invalid token setting does not count as a truncated reply.The playground keeps the provider's explanation so users can correct the setting before trying again.+## Backfill recovery++A backfill that stops on its own shows as **Interrupted**, with a stop reason.+A backfill a user stops shows as **Cancelled**.+An interrupted backfill preserves completed results.+**Retry remaining** creates a new backfill with the original date range and filters, using the current evaluation settings.+It preserves usable existing results and retries units without usable results.+It is not available for a backfill that re-ran existing results.+## Result encodingBoolean online evaluations write their raw verdict to `$ai_evaluation_result`.diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.pyindex b3622ddedd41..26f75160a7d5 100644--- a/posthog/temporal/ai_observability/evaluation_backfill.py+++ b/posthog/temporal/ai_observability/evaluation_backfill.py@@ -216,6 +216,14 @@ def cancel_backfill(team_id: int, backfill_id: str | UUID) -> int:)+def interrupt_backfill(team_id: int, backfill_id: str | UUID, reason: str) -> int:+ return (+ EvaluationBackfill.objects.for_team(team_id)+ .filter(pk=backfill_id, status=EvaluationBackfillStatus.RUNNING)+ .update(status=EvaluationBackfillStatus.INTERRUPTED, status_reason=reason, finished_at=timezone.now())+ )++def report_backfill_finished(team_id: int, backfill_id: str, *, status: str | None = None, stop_reason: str | None = None) -> None:@@ -235,9 +243,8 @@ def report_backfill_finished(properties={"backfill_id": str(row.pk),"evaluation_id": str(row.evaluation_id),- # Failed and stopped runs are both stored as cancelled, so only the caller can tell them apart."status": status or row.status,- "stop_reason": stop_reason,+ "stop_reason": stop_reason or row.status_reason or None,"target": row.target,"evaluation_type": row.evaluation.evaluation_type,"rerun_existing": row.rerun_existing,@@ -248,6 +255,8 @@ def report_backfill_finished("remaining_count": row.remaining_count,# Each dispatched evaluation emits one billed $ai_evaluation event."billed_evaluations": row.dispatched_count,+ "completed_count": row.completed_count,+ "evaluation_skipped_count": row.evaluation_skipped_count,"duration_seconds": (finished_at - row.created_at).total_seconds(),},groups=groups(row.team.organization, row.team),@@ -257,7 +266,7 @@ def report_backfill_finished(def _fail_backfill(inputs: EvaluationBackfillInputs) -> None:- if cancel_backfill(inputs.team_id, inputs.backfill_id):+ if interrupt_backfill(inputs.team_id, inputs.backfill_id, "execution_failed"):report_backfill_finished(inputs.team_id, inputs.backfill_id, status="failed")@@ -279,19 +288,19 @@ def _prepare_backfill_tick(inputs: EvaluationBackfillInputs) -> PrepareTickOutpuevaluation = row.evaluation# Three ways an evaluation can no longer produce a run, all ending the backfill. An unknown- # evaluation type has no workflow id prefix, so cancelling here keeps that failure in an+ # evaluation type has no workflow id prefix, so interrupting here keeps that failure in an# activity rather than raising a KeyError inside workflow code. A disabled evaluation ends the# backfill too, because nothing would tell the loop the evaluation came back, so holding the# cursor would leave the row RUNNING and the workflow ticking forever.if evaluation.deleted or not evaluation.enabled or evaluation.evaluation_type not in EVALUATION_WORKFLOW_PREFIXES:- if cancel_backfill(inputs.team_id, inputs.backfill_id):- stop_reason = (- "evaluation_deleted"- if evaluation.deleted- else "evaluation_disabled"- if not evaluation.enabled- else "unsupported_evaluation_type"- )+ stop_reason = (+ "evaluation_deleted"+ if evaluation.deleted+ else "evaluation_disabled"+ if not evaluation.enabled+ else "unsupported_evaluation_type"+ )+ if interrupt_backfill(inputs.team_id, inputs.backfill_id, stop_reason):report_backfill_finished(inputs.team_id, inputs.backfill_id, status="stopped", stop_reason=stop_reason)return PrepareTickOutput(action=TickAction.FINISHED)diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.pyindex 8809f1f0981f..30816f0c5ac4 100644--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py@@ -558,6 +558,8 @@ class TestEvaluationBackfillActivities:"failed_count": 1,"remaining_count": 1,"billed_evaluations": 6,+ "completed_count": None,+ "evaluation_skipped_count": 0,"duration_seconds": 300.0,"stop_reason": None,}@@ -602,7 +604,8 @@ class TestEvaluationBackfillActivities:async_to_sync(fail_evaluation_backfill_activity)(_activity_inputs(backfill_data))backfill_data["backfill"].refresh_from_db()- assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.INTERRUPTED+ assert backfill_data["backfill"].status_reason == "execution_failed"@pytest.mark.parametrize("status", [EvaluationBackfillStatus.COMPLETED, EvaluationBackfillStatus.CANCELLED, None])def test_prepare_returns_finished_for_missing_or_terminal_row(self, backfill_data, status) -> None:@@ -636,7 +639,8 @@ class TestEvaluationBackfillActivities:assert result.action == TickAction.FINISHEDbackfill_data["backfill"].refresh_from_db()- assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.INTERRUPTED+ assert backfill_data["backfill"].status_reason == stop_reasonassert backfill_data["backfill"].finished_at is not Noneassert [(event["status"], event["stop_reason"]) for event in _finished_events(capture)] == [("stopped", stop_reason)diff --git a/products/ai_observability/backend/api/evaluation_backfills.py b/products/ai_observability/backend/api/evaluation_backfills.pyindex 9a62f33ba586..26f803e0a733 100644--- a/products/ai_observability/backend/api/evaluation_backfills.py+++ b/products/ai_observability/backend/api/evaluation_backfills.py@@ -43,6 +43,7 @@ from posthog.temporal.ai_observability.evaluation_backfill import (EvaluationBackfillInputs,backfill_workflow_id,cancel_backfill,+ interrupt_backfill,report_backfill_finished,settle_horizon,)@@ -219,6 +220,7 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):fields = ["id","status",+ "status_reason","target","window_start","window_end",@@ -226,6 +228,8 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):"rerun_existing","total_count","dispatched_count",+ "completed_count",+ "evaluation_skipped_count","skipped_count","failed_count","remaining_count",@@ -236,7 +240,8 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):read_only_fields = fieldsextra_kwargs = {"id": {"help_text": "Backfill identifier."},- "status": {"help_text": "running while the walk is dispatching, then completed or cancelled."},+ "status": {"help_text": "Running, completed, interrupted by an error, or cancelled by a user."},+ "status_reason": {"help_text": "Reason an interrupted backfill stopped; empty otherwise."},"window_start": {"help_text": "Inclusive start of the window, by unit timestamp."},"window_end": {"help_text": "Exclusive end of the window."},"rerun_existing": {"help_text": "Whether units with an existing result are evaluated again."},@@ -246,12 +251,11 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):"dispatched_count": {"help_text": "Units the backfill has started an evaluation for so far."},"skipped_count": {"help_text": "Units the live path had already covered, so nothing was dispatched."},"failed_count": {- "help_text": "Units whose evaluation failed to start. They have no result and count toward remaining_count."+ "help_text": "Units whose evaluation failed to start or finish. Legacy runs only counted start failures."},"remaining_count": {"help_text": (- "Units still holding no result when the run finished, counted at that moment. "- "Zero means the window is covered, whoever graded it."+ "Units left to retry after completion. Legacy runs estimated this before evaluations finished.")},"created_at": {"help_text": "When the backfill was created."},@@ -536,7 +540,7 @@ class EvaluationBackfillViewSet(team_id=self.team_id,workflow_id=workflow_id,)- if cancel_backfill(self.team_id, backfill.pk):+ if interrupt_backfill(self.team_id, backfill.pk, "workflow_not_running"):report_backfill_finished(self.team_id, str(backfill.pk), status="failed", stop_reason="workflow_not_running")diff --git a/products/ai_observability/backend/api/test/test_evaluation_backfills.py b/products/ai_observability/backend/api/test/test_evaluation_backfills.pyindex 90162e7a1218..6685f29094f0 100644--- a/products/ai_observability/backend/api/test/test_evaluation_backfills.py+++ b/products/ai_observability/backend/api/test/test_evaluation_backfills.py@@ -297,7 +297,8 @@ class TestEvaluationBackfillsApi(APIBaseTest):assert response.status_code == status.HTTP_201_CREATED, response.json()stale.refresh_from_db()- assert stale.status == EvaluationBackfillStatus.CANCELLED+ assert stale.status == EvaluationBackfillStatus.INTERRUPTED+ assert stale.status_reason == "workflow_not_running"assert stale.finished_at is not Nonefinished = [call.kwargs["properties"]@@ -355,9 +356,9 @@ class TestEvaluationBackfillsApi(APIBaseTest):response = self.client.get(f"{self.url}/")assert response.status_code == status.HTTP_200_OK, response.json()- assert response.json()["results"][0]["status"] == EvaluationBackfillStatus.CANCELLED+ assert response.json()["results"][0]["status"] == EvaluationBackfillStatus.INTERRUPTEDstale.refresh_from_db()- assert stale.status == EvaluationBackfillStatus.CANCELLED+ assert stale.status == EvaluationBackfillStatus.INTERRUPTED@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(7))@patch(f"{API_MODULE}.sync_connect", side_effect=RuntimeError("temporal down"))diff --git a/products/ai_observability/backend/migrations/0064_backfill_execution_outcomes.py b/products/ai_observability/backend/migrations/0064_backfill_execution_outcomes.pynew file mode 100644index 000000000000..642fa61574a6--- /dev/null+++ b/products/ai_observability/backend/migrations/0064_backfill_execution_outcomes.py@@ -0,0 +1,69 @@+# Generated by Django 5.2.18 on 2026-10-07 14:57++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0063_evaluation_directory_only_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="evaluationbackfill",+ name="completed_count",+ field=models.PositiveIntegerField(+ blank=True,+ default=None,+ help_text="Evaluations that finished with a verdict. Null for legacy runs.",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="evaluationbackfill",+ name="evaluation_skipped_count",+ field=models.PositiveIntegerField(+ db_default=0,+ default=0,+ help_text="Evaluations that finished with a recorded skip instead of a verdict.",+ ),+ ),+ migrations.AddField(+ model_name="evaluationbackfill",+ name="status_reason",+ field=models.CharField(blank=True, db_default="", default="", max_length=64),+ ),+ migrations.AlterField(+ model_name="evaluationbackfill",+ name="failed_count",+ field=models.PositiveIntegerField(+ db_default=0,+ default=0,+ help_text="Units whose evaluation failed to start or finish. Legacy runs only counted start failures.",+ ),+ ),+ migrations.AlterField(+ model_name="evaluationbackfill",+ name="remaining_count",+ field=models.PositiveIntegerField(+ blank=True,+ default=None,+ help_text="Units that failed to produce a result when the run ended. Legacy runs estimate this by counting missing results and discounting dispatched work. Null means unknown.",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="evaluationbackfill",+ name="status",+ field=models.CharField(+ choices=[+ ("running", "Running"),+ ("completed", "Completed"),+ ("cancelled", "Cancelled"),+ ("interrupted", "Interrupted"),+ ],+ default="running",+ max_length=16,+ ),+ ),+ ]diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txtindex d96ef60af697..7b11118beab0 100644--- a/products/ai_observability/backend/migrations/max_migration.txt+++ b/products/ai_observability/backend/migrations/max_migration.txt@@ -1 +1 @@-0063_evaluation_directory_only_index+0064_backfill_execution_outcomesdiff --git a/products/ai_observability/backend/models/evaluation_backfill.py b/products/ai_observability/backend/models/evaluation_backfill.pyindex fc31563e6877..c63492019b5e 100644--- a/products/ai_observability/backend/models/evaluation_backfill.py+++ b/products/ai_observability/backend/models/evaluation_backfill.py@@ -8,6 +8,7 @@ class EvaluationBackfillStatus(models.TextChoices):RUNNING = "running", "Running"COMPLETED = "completed", "Completed"CANCELLED = "cancelled", "Cancelled"+ INTERRUPTED = "interrupted", "Interrupted"ACTIVE_BACKFILL_STATUSES = (EvaluationBackfillStatus.RUNNING,)@@ -29,6 +30,7 @@ class EvaluationBackfill(TeamScopedRootMixin, UUIDModel):status = models.CharField(max_length=16, choices=EvaluationBackfillStatus.choices, default=EvaluationBackfillStatus.RUNNING)+ status_reason = models.CharField(max_length=64, blank=True, default="", db_default="")# Frozen at creation so an edit to the evaluation mid-run does not change what the walk matches.target = models.CharField(max_length=20, help_text="Evaluation target frozen at creation.")@@ -48,23 +50,27 @@ class EvaluationBackfill(TeamScopedRootMixin, UUIDModel):help_text="Units matched at creation. Units that land in the window later can take the run past it.")dispatched_count = models.PositiveIntegerField(default=0)+ completed_count = models.PositiveIntegerField(+ null=True, blank=True, default=None, help_text="Evaluations that finished with a verdict. Null for legacy runs."+ )+ evaluation_skipped_count = models.PositiveIntegerField(+ default=0, db_default=0, help_text="Evaluations that finished with a recorded skip instead of a verdict."+ )skipped_count = models.PositiveIntegerField(default=0, help_text="Units whose child workflow already existed, so the live path had them.")failed_count = models.PositiveIntegerField(default=0,db_default=0,- help_text="Units whose evaluation failed to start. They stay without a result and count as remaining.",+ help_text="Units whose evaluation failed to start or finish. Legacy runs only counted start failures.",)remaining_count = models.PositiveIntegerField(null=True,blank=True,default=None,help_text=(- "Units the run finished without a result for, counted when it ended rather than "- "inferred, and discounting the evaluations it had just started. A run leaves one "- "behind when its evaluation could not start or came back unusable, and running the "- "backfill again picks it up. Null means nothing counted the window."+ "Units that failed to produce a result when the run ended. Legacy runs estimate this "+ "by counting missing results and discounting dispatched work. Null means unknown."),)diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts b/products/ai_observability/frontend/evaluations/backfillConditions.test.tsindex 5df3ca88ce8d..18db5a892168 100644--- a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts+++ b/products/ai_observability/frontend/evaluations/backfillConditions.test.ts@@ -22,6 +22,24 @@ function backfill(overrides: Partial<EvaluationBackfillApi> = {}): EvaluationBac}describe('backfillConditions', () => {+ it.each([+ ['running', null, 4, 0],+ ['completed', 2, 6, 2],+ ] as const)(+ 'counts finished outcomes without treating failed executions as covered while %s',+ (status, remaining, covered, liveCovered) => {+ const run = backfill({+ status,+ completed_count: 2,+ evaluation_skipped_count: 1,+ skipped_count: 1,+ dispatched_count: 5,+ failed_count: 2,+ remaining_count: remaining,+ })+ expect([backfillCoveredCount(run), backfillLiveCoveredCount(run)]).toEqual([covered, liveCovered])+ }+ )it.each([[undefined, '100% sampled'],[100, '100% sampled'],diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.ts b/products/ai_observability/frontend/evaluations/backfillConditions.tsindex 5f0878398f5d..52a862b69c3d 100644--- a/products/ai_observability/frontend/evaluations/backfillConditions.ts+++ b/products/ai_observability/frontend/evaluations/backfillConditions.ts@@ -35,14 +35,21 @@ export function backfillCoveredCount(backfill: EvaluationBackfillApi): number {const covered =backfill.status === 'completed' && backfill.remaining_count !== null? total - backfill.remaining_count- : backfill.dispatched_count + backfill.skipped_count+ : backfillHandledCount(backfill) + backfill.skipped_countreturn clamp(covered, 0, total)}+/** Runs that tracked outcomes count only finished evaluations, so a failed run is not covered. */+function backfillHandledCount(backfill: EvaluationBackfillApi): number {+ return backfill.completed_count != null+ ? backfill.completed_count + backfill.evaluation_skipped_count+ : backfill.dispatched_count+}+/** A rerun dispatches every unit, so only a run over ungraded units has a gap the live path filled. */export function backfillLiveCoveredCount(backfill: EvaluationBackfillApi): number {if (backfill.rerun_existing || backfill.status !== 'completed' || backfill.remaining_count === null) {return 0}- return Math.max(0, backfillCoveredCount(backfill) - backfill.dispatched_count - backfill.skipped_count)+ return Math.max(0, backfillCoveredCount(backfill) - backfillHandledCount(backfill) - backfill.skipped_count)}diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsxindex 8c60a363a33f..0e219c0824f6 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx@@ -54,6 +54,7 @@ const BACKFILL_STATUS_TAG: Record<EvaluationBackfillStatusEnumApi, { label: strirunning: { label: 'Running', type: 'primary' },completed: { label: 'Completed', type: 'success' },cancelled: { label: 'Cancelled', type: 'muted' },+ interrupted: { label: 'Interrupted', type: 'warning' },}const WINDOW_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:mm' }@@ -65,7 +66,7 @@ function backfillLeftBehindLabel(backfill: EvaluationBackfillApi): string | nullreturn null}const one = backfill.remaining_count === 1- return `${pluralize(backfill.remaining_count, backfill.target)} ${one ? "wasn't" : "weren't"} evaluated. Start another backfill over this range to retry ${one ? 'it' : 'them'}.`+ return `${pluralize(backfill.remaining_count, backfill.target)} ${one ? "wasn't" : "weren't"} evaluated. Retry remaining to try ${one ? 'it' : 'them'} again.`}function backfillUnitPlural(backfill: EvaluationBackfillApi): string {@@ -95,6 +96,13 @@ interface EvaluationBackfillsTabProps {onConfigurationClick: () => void}+const INTERRUPTED_REASON_MESSAGES: Record<string, string> = {+ evaluation_disabled:+ 'The evaluation was disabled. Check its configuration and provider key, then re-enable it and retry remaining.',+ execution_failed: 'The backfill kept hitting errors, so it stopped. Retry remaining to try again.',+ workflow_not_running: 'The backfill stopped unexpectedly. Retry remaining to continue where it left off.',+}+export function EvaluationBackfillsTab({evaluationId,userAccessLevel,@@ -108,6 +116,8 @@ export function EvaluationBackfillsTab({clampedWindow,conditions,creatingBackfill,+ evaluation,+ hasActiveBackfill,estimate,estimateError,estimateLoading,@@ -127,6 +137,7 @@ export function EvaluationBackfillsTab({setRerunExisting,createBackfill,cancelBackfill,+ retryBackfill,expandBackfill,collapseBackfill,loadBackfills,@@ -162,6 +173,7 @@ export function EvaluationBackfillsTab({{title: 'Range',key: 'window',+ className: '@max-[32rem]/backfills:hidden',// `timestampStyle="absolute"` suppresses the Today/Yesterday substitution, so two rows// can be compared as exact instants. TZLabel's timezone popover still holds the time of day.render: (_, backfill) => {@@ -190,14 +202,21 @@ export function EvaluationBackfillsTab({key: 'status',render: (_, backfill) => {const statusTag = (- <LemonTag type={BACKFILL_STATUS_TAG[backfill.status].type}>- {BACKFILL_STATUS_TAG[backfill.status].label}+ <LemonTag+ type={+ backfill.status === 'completed' && backfill.failed_count+ ? 'warning'+ : BACKFILL_STATUS_TAG[backfill.status].type+ }+ >+ {backfill.status === 'completed' && backfill.failed_count+ ? 'Completed with errors'+ : BACKFILL_STATUS_TAG[backfill.status].label}</LemonTag>)return (<div className="flex items-center gap-1 flex-wrap">- {/* A completed row means every unit was sent out, not that every evaluation has finished. */}- {backfill.status === 'completed' ? (+ {backfill.status === 'completed' && backfill.completed_count == null ? (<Tooltiptitle={`Each ${backfill.target} is evaluated on its own, so the last results can take a few minutes to appear in the Runs tab.`}>@@ -206,6 +225,21 @@ export function EvaluationBackfillsTab({) : (statusTag)}+ <span className="hidden w-full text-muted @max-[32rem]/backfills:block">+ <TZLabel+ time={backfill.window_start}+ timestampStyle="absolute"+ formatDate="MMM D"+ formatTime=""+ />+ {' – '}+ <TZLabel+ time={backfill.window_end}+ timestampStyle="absolute"+ formatDate="MMM D"+ formatTime=""+ />+ </span></div>)},@@ -213,6 +247,7 @@ export function EvaluationBackfillsTab({{title: 'Scope',key: 'conditions',+ className: '@max-[48rem]/backfills:hidden',render: (_, backfill) => {// The Scope cell shows one condition set and folds the rest behind a "+N more".const [first, ...rest] = backfill.conditions@@ -264,22 +299,20 @@ export function EvaluationBackfillsTab({},},{- title: 'Covered',+ title: 'Progress',key: 'progress',render: (_, backfill) => {- // While the walk runs, coverage is what it has handled: started, or skipped because- // the live path had the unit already. Once it ends, the measured remainder is the- // truer number, because a unit the live path judged mid-run is covered too and the- // walk never saw it.const measured = backfill.status === 'completed' && backfill.remaining_count !== nullconst covered = backfillCoveredCount(backfill)const total = backfillTotalCount(backfill)return (<Tooltiptitle={- measured- ? `How many ${backfillUnitPlural(backfill)} hold a result, counted when the run ended. The evaluation grades new data on its own, so it covers some of them without this run.`- : `How many ${backfillUnitPlural(backfill)} this backfill has started evaluating or skipped because the evaluation already had them. It does not track which of them have finished.`+ backfill.completed_count != null+ ? `${backfill.completed_count.toLocaleString('en-US')} evaluated, ${backfill.evaluation_skipped_count.toLocaleString('en-US')} skipped, ${backfill.skipped_count.toLocaleString('en-US')} already handled, ${backfill.failed_count.toLocaleString('en-US')} failed.`+ : measured+ ? `Estimated coverage when this run ended. This older backfill did not track execution outcomes.`+ : `How many ${backfillUnitPlural(backfill)} this backfill has started evaluating or skipped because the evaluation already had them. It does not track which of them have finished.`}><div className="min-w-24">@@ -289,7 +322,10 @@ export function EvaluationBackfillsTab({{backfill.dispatched_count > 0 && (<span className="text-muted whitespace-nowrap">{' '}- · {backfill.dispatched_count.toLocaleString('en-US')} started+ ·{' '}+ {backfill.completed_count != null+ ? `${backfill.completed_count.toLocaleString('en-US')} evaluated`+ : `${backfill.dispatched_count.toLocaleString('en-US')} started`}</span>)}<LemonProgress@@ -305,11 +341,13 @@ export function EvaluationBackfillsTab({{title: 'Created',key: 'created_at',+ className: '@max-[48rem]/backfills:hidden',render: (_, backfill) => <TZLabel time={backfill.created_at} />,},{title: 'Created by',key: 'created_by',+ className: '@max-[48rem]/backfills:hidden',render: (_, backfill) =>backfill.created_by ? (<ProfilePicture user={backfill.created_by as UserBasicType} size="md" showName />@@ -342,12 +380,50 @@ export function EvaluationBackfillsTab({</AccessControlAction>}/>+ ) : backfill.status !== 'completed' || !!backfill.failed_count || !!backfill.remaining_count ? (+ <AccessControlAction+ resourceType={AccessControlResourceType.Evaluation}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}+ >+ <LemonButton+ size="small"+ loading={transitioningIds.includes(backfill.id)}+ data-attr="llma-eval-backfill-retry-remaining"+ disabledReason={+ backfill.rerun_existing+ ? "Retry isn't available for a backfill that re-ran existing results. Start a new backfill instead."+ : evaluation && backfill.target !== evaluation.target+ ? `This backfill ran on ${backfillUnitPlural(backfill)}, but the evaluation now runs on ${pluralize(2, evaluation.target, undefined, false)}. Start a new backfill instead.`+ : !evaluation?.enabled+ ? 'Re-enable the evaluation before retrying.'+ : hasActiveBackfill || creatingBackfill || transitioningIds.length > 0+ ? 'Wait for the active backfill operation to finish.'+ : undefined+ }+ onClick={() =>+ LemonDialog.open({+ title: 'Retry remaining evaluations?',+ description:+ 'This starts a new backfill with the same filters and date range, trimmed to the last 30 days, using the current evaluation settings. Existing results are kept. New evaluations are billed as usual.',+ primaryButton: {+ children: 'Retry remaining',+ onClick: () => retryBackfill(backfill.id),+ 'data-attr': 'llma-eval-backfill-retry-remaining-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ >+ Retry remaining+ </LemonButton>+ </AccessControlAction>) : null,},]return (- <div className="flex flex-col gap-4 max-w-6xl">+ <div className="@container/backfills flex flex-col gap-4 max-w-6xl"><div className="rounded border p-4 flex flex-col gap-3"><div><h3 className="mb-1">Evaluate past {unitPlural}</h3>@@ -458,8 +534,21 @@ export function EvaluationBackfillsTab({const lateArrivals = backfillLateArrivalCount(backfill)const liveCovered = backfillLiveCoveredCount(backfill)return (- <div className="flex items-center justify-between gap-4 px-2 py-3">+ <div className="flex flex-col items-start justify-between gap-4 px-2 py-3 @min-[48rem]/backfills:flex-row @min-[48rem]/backfills:items-center"><div className="flex flex-col gap-2 min-w-0">+ {backfill.status === 'interrupted' && (+ <LemonBanner type="warning">+ {(backfill.status_reason &&+ INTERRUPTED_REASON_MESSAGES[backfill.status_reason]) ??+ 'The backfill stopped before finishing. Check the evaluation configuration, then retry remaining.'}+ </LemonBanner>+ )}+ {!!backfill.failed_count && (+ <span>+ {backfill.failed_count.toLocaleString('en-US')} failed. Retry remaining to+ try again.+ </span>+ )}{backfill.conditions.map((condition, index) => (<div key={index} className="flex items-center gap-1 flex-wrap"><ConditionSetScope@@ -472,7 +561,7 @@ export function EvaluationBackfillsTab({</div>))}<div className="flex items-center gap-2 flex-wrap text-muted">- <span className="flex items-center gap-1">+ <span className="flex items-center gap-1 flex-wrap"><TZLabeltime={backfill.window_start}timestampStyle="absolute"diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.tsindex dd8f3b88ef60..7ced196e097d 100644--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts@@ -82,6 +82,9 @@ function backfill(overrides: Partial<EvaluationBackfillApi> = {}): EvaluationBacrerun_existing: false,total_count: 10,dispatched_count: 8,+ completed_count: null,+ evaluation_skipped_count: 0,+ status_reason: '',skipped_count: 2,failed_count: 0,remaining_count: null,@@ -619,4 +622,82 @@ describe('evaluationBackfillsLogic', () => {expect(cancelMock).toHaveBeenCalledWith(expect.any(String), EVALUATION_ID, 'backfill-1')await expectLogic(logic).toMatchValues({ transitioningIds: [] })})++ it.each(['backfill-1', 'backfill-2'])(+ 'guards a concurrent retry of %s and keeps existing results',+ async (secondId) => {+ const previous = backfill({ status: 'interrupted', rerun_existing: true })+ listMock.mockResolvedValue({+ count: 2,+ results: [previous, backfill({ id: 'backfill-2', status: 'interrupted' })],+ })+ await mountAndSettle()+ let finish!: (value: EvaluationBackfillApi) => void+ createMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve+ })+ )++ logic.actions.retryBackfill(previous.id)+ logic.actions.retryBackfill(secondId)+ expect(createMock).toHaveBeenCalledTimes(1)+ expect(createMock).toHaveBeenCalledWith(expect.any(String), EVALUATION_ID, {+ window_start: previous.window_start,+ window_end: previous.window_end,+ conditions: previous.conditions.map((condition, index) => ({ ...condition, id: `retry-${index}` })),+ rerun_existing: false,+ })+ expect(new Set(logic.values.transitioningIds)).toEqual(new Set([previous.id]))+ expect(logic.values.startDisabledReason).toEqual('Wait for the current retry or cancel to finish')+ finish(backfill({ status: 'running' }))+ await expectLogic(logic).toDispatchActions(['transitionBackfillDone', 'loadBackfills'])+ expect(logic.values.transitioningIds).toEqual([])+ }+ )++ it('refuses a retry after the evaluation target changed', async () => {+ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'interrupted' })] })+ await mountAndSettle()+ saveEvaluation({ target: 'trace' })++ logic.actions.retryBackfill('backfill-1')+ await expectLogic(logic).toDispatchActions(['transitionBackfillDone'])++ expect(createMock).not.toHaveBeenCalled()+ expect(logic.values.transitioningIds).toEqual([])+ })++ it('lets a retry run again after a rejected one and reports each click', async () => {+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ listMock.mockResolvedValue({+ count: 1,+ results: [backfill({ status: 'interrupted', status_reason: 'execution_failed' })],+ })+ await mountAndSettle()+ createMock.mockRejectedValueOnce(new Error('nope'))++ logic.actions.retryBackfill('backfill-1')+ await expectLogic(logic).toDispatchActions(['transitionBackfillDone'])+ expect(toastError).toHaveBeenCalled()+ expect(logic.values.transitioningIds).toEqual([])++ createMock.mockResolvedValueOnce(backfill({ status: 'running' }))+ logic.actions.retryBackfill('backfill-1')+ await expectLogic(logic).toDispatchActions(['transitionBackfillDone'])++ expect(createMock).toHaveBeenCalledTimes(2)+ expect(capture.mock.calls.filter(([event]) => event === 'llma evaluation backfill retry clicked')).toEqual(+ Array(2).fill([+ 'llma evaluation backfill retry clicked',+ {+ evaluation_id: EVALUATION_ID,+ backfill_id: 'backfill-1',+ status: 'interrupted',+ status_reason: 'execution_failed',+ },+ ])+ )+ })})diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.tsindex d8f0e9c52eb0..a310c241f3a9 100644--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts@@ -179,6 +179,9 @@ export interface evaluationBackfillsLogicActions {estimate: EvaluationBackfillEstimateApirequestedWindow: BackfillWindow | null}+ retryBackfill: (id: string) => {+ id: string+ }seedConditions: (conditions: EvaluationConditionSet[]) => {conditions: EvaluationConditionSet[]}@@ -215,6 +218,7 @@ export interface evaluationBackfillsLogicMeta {) => EvaluationTargetEnumApistartDisabledReason: (hasActiveBackfill: boolean,+ transitioningIds: string[],conditions: EvaluationConditionSet[],estimate: EvaluationBackfillEstimateApi | null,estimateLoading: boolean,@@ -269,6 +273,7 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([createBackfill: true,createBackfillDone: (succeeded: boolean) => ({ succeeded }),cancelBackfill: (id: string) => ({ id }),+ retryBackfill: (id: string) => ({ id }),transitionBackfillDone: (id: string) => ({ id }),expandBackfill: (id: string) => ({ id }),collapseBackfill: (id: string) => ({ id }),@@ -353,6 +358,7 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([[] as string[],{cancelBackfill: (state, { id }) => [...state, id],+ retryBackfill: (state, { id }) => [...state, id],transitionBackfillDone: (state, { id }) => state.filter((i) => i !== id),},],@@ -387,9 +393,17 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([): EvaluationTargetEnumApi => estimate?.unit ?? evaluation?.target ?? 'generation',],startDisabledReason: [- (s) => [s.hasActiveBackfill, s.conditions, s.estimate, s.estimateLoading, s.estimateError],+ (s) => [+ s.hasActiveBackfill,+ s.transitioningIds,+ s.conditions,+ s.estimate,+ s.estimateLoading,+ s.estimateError,+ ],(hasActiveBackfill: boolean,+ transitioningIds: string[],conditions: EvaluationConditionSet[],estimate: EvaluationBackfillEstimateApi | null,estimateLoading: boolean,@@ -398,6 +412,9 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([if (hasActiveBackfill) {return 'This evaluation already has a running backfill'}+ if (transitioningIds.length > 0) {+ return 'Wait for the current retry or cancel to finish'+ }// Checked before the count, which reads as an empty range rather than as a 0% sample.if (hasUnsetConditionRollout(conditions)) {return 'Set a sampling percentage above 0% for every condition set'@@ -625,6 +642,47 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([actions.transitionBackfillDone(id)}},+ retryBackfill: async ({ id }) => {+ const teamId = teamLogic.values.currentTeamId+ const backfill = values.backfills.find((run) => run.id === id)+ if (cache.retryingBackfill) {+ if (cache.retryingBackfill !== id) {+ actions.transitionBackfillDone(id)+ }+ return+ }+ // Conditions are written for one target, so a retry under another would grade the wrong units.+ if (!teamId || !backfill || backfill.target !== values.evaluation?.target) {+ actions.transitionBackfillDone(id)+ return+ }+ cache.retryingBackfill = id+ posthog.capture('llma evaluation backfill retry clicked', {+ evaluation_id: props.evaluationId,+ backfill_id: id,+ status: backfill.status,+ status_reason: backfill.status_reason,+ })+ try {+ await evaluationsBackfillsCreate(String(teamId), props.evaluationId, {+ window_start: backfill.window_start,+ window_end: backfill.window_end,+ conditions: backfill.conditions.map((condition, index) => ({+ ...condition,+ id: `retry-${index}`,+ })),+ rerun_existing: false,+ })+ cache.recountWhenIdle = true+ lemonToast.success('Retry started. Existing results will be kept.')+ } catch (error) {+ lemonToast.error(backfillErrorMessage(error, 'Couldn’t retry this backfill. Try again.'))+ } finally {+ cache.retryingBackfill = false+ actions.transitionBackfillDone(id)+ actions.loadBackfills(true)+ }+ },}}),diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex b106a98e4e7b..cd592a7d48f4 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -2172,6 +2172,7 @@ export interface PaginatedEvaluationListApi {* * `running` - Running* * `completed` - Completed* * `cancelled` - Cancelled+ * * `interrupted` - Interrupted*/export type EvaluationBackfillStatusEnumApi =(typeof EvaluationBackfillStatusEnumApi)[keyof typeof EvaluationBackfillStatusEnumApi]@@ -2180,6 +2181,7 @@ export const EvaluationBackfillStatusEnumApi = {Running: 'running',Completed: 'completed',Cancelled: 'cancelled',+ Interrupted: 'interrupted',} as constexport type EvaluationBackfillConditionApiPropertiesItem = { [key: string]: unknown }@@ -2197,12 +2199,15 @@ export interface EvaluationBackfillConditionApi {export interface EvaluationBackfillApi {/** Backfill identifier. */readonly id: string- /** running while the walk is dispatching, then completed or cancelled.+ /** Running, completed, interrupted by an error, or cancelled by a user.** * `running` - Running* * `completed` - Completed- * * `cancelled` - Cancelled */+ * * `cancelled` - Cancelled+ * * `interrupted` - Interrupted */readonly status: EvaluationBackfillStatusEnumApi+ /** Reason an interrupted backfill stopped; empty otherwise. */+ readonly status_reason: string/** What one unit is, frozen at creation: a generation, a trace, or a session.** * `generation` - Generation@@ -2221,12 +2226,19 @@ export interface EvaluationBackfillApi {readonly total_count: number/** Units the backfill has started an evaluation for so far. */readonly dispatched_count: number+ /**+ * Evaluations that finished with a verdict. Null for legacy runs.+ * @nullable+ */+ readonly completed_count: number | null+ /** Evaluations that finished with a recorded skip instead of a verdict. */+ readonly evaluation_skipped_count: number/** Units the live path had already covered, so nothing was dispatched. */readonly skipped_count: number- /** Units whose evaluation failed to start. They have no result and count toward remaining_count. */+ /** Units whose evaluation failed to start or finish. Legacy runs only counted start failures. */readonly failed_count: number/**- * Units still holding no result when the run finished, counted at that moment. Zero means the window is covered, whoever graded it.+ * Units left to retry after completion. Legacy runs estimated this before evaluations finished.* @nullable*/readonly remaining_count: number | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fa5597dfd4a2..f6395f4a128f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42563,6 +42563,7 @@ export namespace Schemas {* * `running` - Running* * `completed` - Completed* * `cancelled` - Cancelled+ * * `interrupted` - Interrupted*/export type EvaluationBackfillStatusEnum = typeof EvaluationBackfillStatusEnum[keyof typeof EvaluationBackfillStatusEnum];@@ -42571,6 +42572,7 @@ export namespace Schemas {Running: 'running',Completed: 'completed',Cancelled: 'cancelled',+ Interrupted: 'interrupted',} as const;export type EvaluationBackfillConditionPropertiesItem = { [key: string]: unknown };@@ -42588,12 +42590,15 @@ export namespace Schemas {export interface EvaluationBackfill {/** Backfill identifier. */readonly id: string;- /** running while the walk is dispatching, then completed or cancelled.+ /** Running, completed, interrupted by an error, or cancelled by a user.** * `running` - Running* * `completed` - Completed- * * `cancelled` - Cancelled */+ * * `cancelled` - Cancelled+ * * `interrupted` - Interrupted */readonly status: EvaluationBackfillStatusEnum;+ /** Reason an interrupted backfill stopped; empty otherwise. */+ readonly status_reason: string;/** What one unit is, frozen at creation: a generation, a trace, or a session.** * `generation` - Generation@@ -42612,12 +42617,19 @@ export namespace Schemas {readonly total_count: number;/** Units the backfill has started an evaluation for so far. */readonly dispatched_count: number;+ /**+ * Evaluations that finished with a verdict. Null for legacy runs.+ * @nullable+ */+ readonly completed_count: number | null;+ /** Evaluations that finished with a recorded skip instead of a verdict. */+ readonly evaluation_skipped_count: number;/** Units the live path had already covered, so nothing was dispatched. */readonly skipped_count: number;- /** Units whose evaluation failed to start. They have no result and count toward remaining_count. */+ /** Units whose evaluation failed to start or finish. Legacy runs only counted start failures. */readonly failed_count: number;/**- * Units still holding no result when the run finished, counted at that moment. Zero means the window is covered, whoever graded it.+ * Units left to retry after completion. Legacy runs estimated this before evaluations finished.* @nullable*/readonly remaining_count: number | null;