Skip to content

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

fix(aio): count failed backfill starts and explain what a run covered (#107615)

Bernat Torres317ba249010b
diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.py
index ef731743998e..b4fa042d058c 100644
--- a/posthog/temporal/ai_observability/evaluation_backfill.py
+++ b/posthog/temporal/ai_observability/evaluation_backfill.py
@@ -153,6 +153,8 @@ class AdvanceCursorInputs:
dispatched_delta: int
skipped_delta: int
exhausted: bool
+ # Defaulted so an advance recorded before this field existed still deserializes.
+ failed_delta: int = 0
@frozen
@@ -313,6 +315,7 @@ def _advance_backfill_cursor(inputs: AdvanceCursorInputs) -> AdvanceCursorOutput
updates: dict[str, Any] = {
"dispatched_count": F("dispatched_count") + inputs.dispatched_delta,
"skipped_count": F("skipped_count") + inputs.skipped_delta,
+ "failed_count": F("failed_count") + inputs.failed_delta,
}
if inputs.new_cursor_timestamp is not None:
updates["cursor_timestamp"] = datetime.fromisoformat(inputs.new_cursor_timestamp)
@@ -339,6 +342,7 @@ def _advance_backfill_cursor(inputs: AdvanceCursorInputs) -> AdvanceCursorOutput
team_id=inputs.team_id,
dispatched=inputs.dispatched_delta,
skipped=inputs.skipped_delta,
+ failed=inputs.failed_delta,
exhausted=inputs.exhausted,
applied=bool(updated),
)
@@ -389,7 +393,10 @@ def _measure_backfill_remainder(inputs: MeasureRemainderInputs) -> None:
rerun_existing=False,
)
in_flight = row.dispatched_count + row.skipped_count
- remaining = max(0, scope.to_evaluate - in_flight)
+ # A unit that failed to start has no evaluation on the way, so the discount cannot absorb it,
+ # unless something else graded it meanwhile and it left the ungraded count.
+ floor = 0 if row.rerun_existing else min(row.failed_count, scope.to_evaluate)
+ remaining = max(floor, scope.to_evaluate - in_flight)
EvaluationBackfill.objects.for_team(inputs.team_id).filter(pk=inputs.backfill_id).update(remaining_count=remaining)
logger.info(
"llma.evaluation_backfill_remainder",
@@ -448,8 +455,8 @@ class EvaluationBackfillWorkflow(PostHogWorkflow):
)
# A page whose children mostly went out must not be re-dispatched because one start
# raised: the retry would collide with every child already running. The unit that failed
- # is left to a later backfill, and counted as neither dispatched nor skipped, because
- # skipped means the live path already graded it.
+ # is left to a later backfill and counted as failed, not skipped, because skipped means
+ # the live path already has it.
results = await asyncio.gather(
*(self._start_child(inputs, tick, candidate) for candidate in found.candidates),
return_exceptions=True,
@@ -473,6 +480,7 @@ class EvaluationBackfillWorkflow(PostHogWorkflow):
new_cursor_unit_id=found.next_cursor_unit_id,
dispatched_delta=dispatched,
skipped_delta=skipped,
+ failed_delta=len(failed),
exhausted=found.exhausted,
),
start_to_close_timeout=ACTIVITY_TIMEOUT,
diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.py
index ed1b134cc743..46af86ad9ef8 100644
--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py
+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py
@@ -194,7 +194,7 @@ class TestEvaluationBackfillWorkflow:
assert (advance.dispatched_delta, advance.skipped_delta) == (2, 1)
@pytest.mark.asyncio
- async def test_a_start_failure_counts_as_neither_dispatched_nor_skipped(self) -> None:
+ async def test_a_start_failure_counts_as_failed(self) -> None:
mocks = _BackfillMocks(
activity_results={
prepare_evaluation_backfill_tick_activity: _tick(),
@@ -208,7 +208,7 @@ class TestEvaluationBackfillWorkflow:
await _run(mocks)
advance = _advance_input(mocks)
- assert (advance.dispatched_delta, advance.skipped_delta) == (2, 0)
+ assert (advance.dispatched_delta, advance.skipped_delta, advance.failed_delta) == (2, 0, 1)
@pytest.mark.asyncio
async def test_exhausted_page_finishes_without_continue_as_new(self) -> None:
@@ -443,7 +443,12 @@ def _activity_inputs(backfill_data) -> EvaluationBackfillInputs:
def _advance(
- backfill_data, *, dispatched_delta: int = 1, skipped_delta: int = 0, exhausted: bool = False
+ backfill_data,
+ *,
+ dispatched_delta: int = 1,
+ skipped_delta: int = 0,
+ failed_delta: int = 0,
+ exhausted: bool = False,
) -> AdvanceCursorInputs:
return AdvanceCursorInputs(
backfill_id=str(backfill_data["backfill"].id),
@@ -454,6 +459,7 @@ def _advance(
new_cursor_unit_id="u3",
dispatched_delta=dispatched_delta,
skipped_delta=skipped_delta,
+ failed_delta=failed_delta,
exhausted=exhausted,
)
@@ -461,17 +467,33 @@ def _advance(
@pytest.mark.django_db(transaction=True)
class TestEvaluationBackfillActivities:
@pytest.mark.parametrize(
- "dispatched,skipped,counted,expected",
+ "dispatched,skipped,failed,rerun,counted,expected",
[
- (1, 15, 14, 0),
- (3000, 0, 3000, 0),
- (1, 0, 5, 4),
+ (1, 15, 0, False, 14, 0),
+ (3000, 0, 0, False, 3000, 0),
+ (1, 0, 0, False, 5, 4),
+ (0, 3, 1, False, 1, 1),
+ (0, 3, 1, False, 0, 0),
+ (0, 3, 1, True, 1, 0),
],
)
def test_remainder_discounts_every_unit_the_run_covered(
- self, backfill_data, dispatched: int, skipped: int, counted: int, expected: int
+ self,
+ backfill_data,
+ dispatched: int,
+ skipped: int,
+ failed: int,
+ rerun: bool,
+ counted: int,
+ expected: int,
) -> None:
- _update_backfill(backfill_data, dispatched_count=dispatched, skipped_count=skipped)
+ _update_backfill(
+ backfill_data,
+ dispatched_count=dispatched,
+ skipped_count=skipped,
+ failed_count=failed,
+ rerun_existing=rerun,
+ )
with patch(
"posthog.temporal.ai_observability.evaluation_backfill.count_backfill_candidates",
@@ -582,13 +604,14 @@ class TestEvaluationBackfillActivities:
assert result.exhausted
def test_advance_is_idempotent_on_retry(self, backfill_data) -> None:
- advance = _advance(backfill_data, dispatched_delta=3, skipped_delta=1)
+ advance = _advance(backfill_data, dispatched_delta=3, skipped_delta=1, failed_delta=2)
first = async_to_sync(advance_evaluation_backfill_cursor_activity)(advance)
second = async_to_sync(advance_evaluation_backfill_cursor_activity)(advance)
backfill_data["backfill"].refresh_from_db()
- assert (backfill_data["backfill"].dispatched_count, backfill_data["backfill"].skipped_count) == (3, 1)
+ row = backfill_data["backfill"]
+ assert (row.dispatched_count, row.skipped_count, row.failed_count) == (3, 1, 2)
assert backfill_data["backfill"].cursor_unit_id == "u3"
assert not first.finished
# The second call matched nothing because the first already moved the cursor. Reading that
diff --git a/products/ai_observability/backend/api/evaluation_backfills.py b/products/ai_observability/backend/api/evaluation_backfills.py
index b44a56547de3..fa514c061875 100644
--- a/products/ai_observability/backend/api/evaluation_backfills.py
+++ b/products/ai_observability/backend/api/evaluation_backfills.py
@@ -225,6 +225,7 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):
"total_count",
"dispatched_count",
"skipped_count",
+ "failed_count",
"remaining_count",
"created_by",
"created_at",
@@ -237,9 +238,14 @@ class EvaluationBackfillSerializer(serializers.ModelSerializer):
"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."},
- "total_count": {"help_text": "Units matched at creation; the ceiling on dispatched_count."},
+ "total_count": {
+ "help_text": "Units matched at creation. Units that land in the window later can take dispatched_count and skipped_count past it."
+ },
"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."
+ },
"remaining_count": {
"help_text": (
"Units still holding no result when the run finished, counted at that moment. "
diff --git a/products/ai_observability/backend/migrations/0058_evaluationbackfill_failed_count.py b/products/ai_observability/backend/migrations/0058_evaluationbackfill_failed_count.py
new file mode 100644
index 000000000000..c2b73e9f8318
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0058_evaluationbackfill_failed_count.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.17 on 2026-09-28 14:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0057_evaluationbackfill_remaining_count"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="evaluationbackfill",
+ name="failed_count",
+ field=models.PositiveIntegerField(
+ db_default=0,
+ default=0,
+ help_text="Units whose evaluation failed to start. They stay without a result and count as remaining.",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="evaluationbackfill",
+ name="total_count",
+ field=models.PositiveIntegerField(
+ help_text="Units matched at creation. Units that land in the window later can take the run past it."
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 335b55997bcc..e8e6269c609a 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0057_evaluationbackfill_remaining_count
+0058_evaluationbackfill_failed_count
diff --git a/products/ai_observability/backend/models/evaluation_backfill.py b/products/ai_observability/backend/models/evaluation_backfill.py
index c1c6ff2dcc42..fc31563e6877 100644
--- a/products/ai_observability/backend/models/evaluation_backfill.py
+++ b/products/ai_observability/backend/models/evaluation_backfill.py
@@ -44,11 +44,18 @@ class EvaluationBackfill(TeamScopedRootMixin, UUIDModel):
cursor_timestamp = models.DateTimeField(null=True, blank=True)
cursor_unit_id = models.TextField(blank=True, default="")
- total_count = models.PositiveIntegerField(help_text="Units matched at creation; the ceiling on dispatched_count.")
+ total_count = models.PositiveIntegerField(
+ 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)
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.",
+ )
remaining_count = models.PositiveIntegerField(
null=True,
blank=True,
diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts b/products/ai_observability/frontend/evaluations/backfillConditions.test.ts
index bbd853d973ff..5df3ca88ce8d 100644
--- a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts
+++ b/products/ai_observability/frontend/evaluations/backfillConditions.test.ts
@@ -4,6 +4,7 @@ import type { EvaluationBackfillApi } from '../generated/api.schemas'
import {
backfillCoveredCount,
backfillLateArrivalCount,
+ backfillLiveCoveredCount,
backfillRangeDateFormat,
backfillSamplingLabel,
backfillTotalCount,
@@ -66,4 +67,30 @@ describe('backfillCoveredCount', () => {
expect(backfillTotalCount(backfill(overrides))).toEqual(total)
expect(backfillLateArrivalCount(backfill(overrides))).toEqual(late)
})
+
+ it.each([
+ [
+ 'the live path graded what the walk never reached',
+ { total_count: 4, dispatched_count: 0, skipped_count: 3 },
+ 1,
+ ],
+ ['a finished run the walk fully handled', { total_count: 3, dispatched_count: 2, skipped_count: 1 }, 0],
+ [
+ 'units still owed are not counted as covered',
+ { total_count: 4, dispatched_count: 0, skipped_count: 3, remaining_count: 1 },
+ 0,
+ ],
+ [
+ 'a rerun dispatches every unit',
+ { total_count: 4, dispatched_count: 0, skipped_count: 3, rerun_existing: true },
+ 0,
+ ],
+ [
+ 'an unmeasured run has no answer yet',
+ { total_count: 4, dispatched_count: 0, skipped_count: 3, remaining_count: null },
+ 0,
+ ],
+ ])('%s', (_case, overrides, expected) => {
+ expect(backfillLiveCoveredCount(backfill(overrides))).toEqual(expected)
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.ts b/products/ai_observability/frontend/evaluations/backfillConditions.ts
index d341a0130371..5f0878398f5d 100644
--- a/products/ai_observability/frontend/evaluations/backfillConditions.ts
+++ b/products/ai_observability/frontend/evaluations/backfillConditions.ts
@@ -38,3 +38,11 @@ export function backfillCoveredCount(backfill: EvaluationBackfillApi): number {
: backfill.dispatched_count + backfill.skipped_count
return clamp(covered, 0, total)
}
+
+/** 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)
+}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
index efb484fbad7a..c7ea878746fb 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
@@ -34,6 +34,7 @@ import type {
import {
backfillCoveredCount,
backfillLateArrivalCount,
+ backfillLiveCoveredCount,
backfillRangeDateFormat,
backfillSamplingLabel,
backfillTotalCount,
@@ -63,7 +64,8 @@ function backfillLeftBehindLabel(backfill: EvaluationBackfillApi): string | null
if (!backfill.remaining_count) {
return null
}
- return `${pluralize(backfill.remaining_count, backfill.target)} weren't evaluated. Start another backfill over this range to retry them.`
+ 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'}.`
}
function backfillUnitPlural(backfill: EvaluationBackfillApi): string {
@@ -452,6 +454,7 @@ export function EvaluationBackfillsTab({
expandedRowRender: (backfill) => {
const leftBehind = backfillLeftBehindLabel(backfill)
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 gap-2 min-w-0">
@@ -484,8 +487,15 @@ export function EvaluationBackfillsTab({
<span>
{backfill.dispatched_count.toLocaleString('en-US')} started,{' '}
{backfill.skipped_count.toLocaleString('en-US')} skipped, out of{' '}
- {pluralize(backfillTotalCount(backfill), backfill.target)}
- {backfill.rerun_existing ? ' in range' : ' that had no result'}
+ {pluralize(
+ backfill.rerun_existing
+ ? backfillTotalCount(backfill)
+ : backfill.total_count,
+ backfill.target
+ )}
+ {backfill.rerun_existing
+ ? ' in range'
+ : " that hadn't been evaluated when the backfill began"}
</span>
</div>
{lateArrivals > 0 && (
@@ -494,6 +504,13 @@ export function EvaluationBackfillsTab({
backfill started, so it covered more than the first count found.
</div>
)}
+ {liveCovered > 0 && (
+ <div className="text-muted">
+ {pluralize(liveCovered, backfill.target)}{' '}
+ {liveCovered === 1 ? 'was' : 'were'} evaluated automatically before the
+ backfill reached {liveCovered === 1 ? 'it' : 'them'}.
+ </div>
+ )}
{leftBehind && <div className="text-warning">{leftBehind}</div>}
</div>
<LemonButton
diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
index 32661b7b65f1..17753f54aa82 100644
--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
@@ -82,6 +82,7 @@ function backfill(overrides: Partial<EvaluationBackfillApi> = {}): EvaluationBac
total_count: 10,
dispatched_count: 8,
skipped_count: 2,
+ failed_count: 0,
remaining_count: null,
created_by: null,
created_at: '2024-01-02T00:00:00Z',
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 5fbf9e37a616..edeacac39eeb 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -2043,12 +2043,14 @@ export interface EvaluationBackfillApi {
readonly conditions: readonly EvaluationBackfillConditionApi[]
/** Whether units with an existing result are evaluated again. */
readonly rerun_existing: boolean
- /** Units matched at creation; the ceiling on dispatched_count. */
+ /** Units matched at creation. Units that land in the window later can take dispatched_count and skipped_count past it. */
readonly total_count: number
/** Units the backfill has started an evaluation for so far. */
readonly dispatched_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. */
+ 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.
* @nullable
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 985e10dc9733..c8f7f3bd7944 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38796,12 +38796,14 @@ export namespace Schemas {
readonly conditions: readonly EvaluationBackfillCondition[];
/** Whether units with an existing result are evaluated again. */
readonly rerun_existing: boolean;
- /** Units matched at creation; the ceiling on dispatched_count. */
+ /** Units matched at creation. Units that land in the window later can take dispatched_count and skipped_count past it. */
readonly total_count: number;
/** Units the backfill has started an evaluation for so far. */
readonly dispatched_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. */
+ 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.
* @nullable