: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
fix(aio): report backfill coverage the run actually achieved (#106940)
Bernat Torresd6bef69a9dce
diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.pyindex fe48f1a16177..ef731743998e 100644--- a/posthog/temporal/ai_observability/evaluation_backfill.py+++ b/posthog/temporal/ai_observability/evaluation_backfill.py@@ -28,6 +28,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetimefrom posthog.temporal.ai_observability.evaluation_types import EVALUATION_WORKFLOW_PREFIXESfrom posthog.temporal.ai_observability.evaluation_workflow_activities import RunEvaluationInputs+from posthog.temporal.ai_observability.metrics import increment_backfill_remainder_outcomefrom posthog.temporal.ai_observability.run_aggregate_evaluation import (INGESTION_LAG_MARGIN_SECONDS,RunAggregateEvaluationInputs,@@ -158,7 +159,6 @@ class AdvanceCursorInputs:class MeasureRemainderInputs:backfill_id: strteam_id: int- in_flight: int@frozen@@ -365,9 +365,14 @@ def _measure_backfill_remainder(inputs: MeasureRemainderInputs) -> None:Counting the remainder here says whether anything was left behind, and the one query it costsruns per backfill rather than per tick.- `start_child_workflow` returns once a child has started, so the last page's verdicts are still- travelling through the judge and ingestion while this counts. Discounting them is what keeps a- backfill small enough to finish in one tick from reporting every unit it evaluated as owed.+ `start_child_workflow` returns once a child has started, so verdicts are still travelling+ through the judge and ingestion while this counts. Discounting what the run covered is what+ keeps a backfill that outruns the judge from reporting every unit it handled as owed. A skipped+ unit counts too: the live path holds it, so its verdict is on the way just the same.++ The discount overshoots when a verdict lands mid-run: that unit leaves the count while the+ discount still holds it, so a unit that will never produce one can read as covered. Only a+ count taken after the settle horizon separates the two."""row = EvaluationBackfill.objects.for_team(inputs.team_id).select_related("evaluation").get(pk=inputs.backfill_id)team = Team.objects.get(pk=inputs.team_id)@@ -383,7 +388,8 @@ def _measure_backfill_remainder(inputs: MeasureRemainderInputs) -> None:# question is what holds no result at all.rerun_existing=False,)- remaining = max(0, scope.to_evaluate - inputs.in_flight)+ in_flight = row.dispatched_count + row.skipped_count+ remaining = max(0, 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",@@ -391,7 +397,7 @@ def _measure_backfill_remainder(inputs: MeasureRemainderInputs) -> None:team_id=inputs.team_id,remaining=remaining,counted=scope.to_evaluate,- in_flight=inputs.in_flight,+ in_flight=in_flight,)@@ -480,18 +486,18 @@ class EvaluationBackfillWorkflow(PostHogWorkflow):try:await temporalio.workflow.execute_activity(measure_evaluation_backfill_remainder_activity,- MeasureRemainderInputs(- backfill_id=inputs.backfill_id, team_id=inputs.team_id, in_flight=dispatched- ),+ MeasureRemainderInputs(backfill_id=inputs.backfill_id, team_id=inputs.team_id),start_to_close_timeout=timedelta(seconds=120),schedule_to_close_timeout=ACTIVITY_SCHEDULE_TO_CLOSE,retry_policy=ACTIVITY_RETRY_POLICY,)+ increment_backfill_remainder_outcome("success")except Exception as error:# The walk is done either way, so failing the tick here would spend a consecutive# failure and log at exception level over a number the row can live without.if is_cancelled_exception(error):raise+ increment_backfill_remainder_outcome("failed")temporalio.workflow.logger.warning("llma.evaluation_backfill_remainder_failed", extra={"backfill_id": inputs.backfill_id})diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex 55978abaa762..7ee64cc752d7 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -159,6 +159,22 @@ def increment_emit_event_outcome(outcome: str) -> None:counter.add(1)+def increment_backfill_remainder_outcome(outcome: str) -> None:+ """Track whether a backfill learned what its window still owed (success/failed).++ The walk is done either way, so a failure here is swallowed rather than retried, and the row+ keeps a null count. Without this counter the only trace is one workflow log line.+ """+ if not activity.in_activity() and not workflow.in_workflow():+ return+ meter = get_metric_meter({"outcome": outcome})+ counter = meter.create_counter(+ "llma_eval_backfill_remainder_outcome",+ "Outcome of the backfill remainder measurement (success/failed)",+ )+ counter.add(1)++def record_schedule_to_start_latency(activity_type: str, latency_ms: int) -> None:"""Record queue depth indicator for alerting."""meter = get_metric_meter({"activity_type": activity_type})diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.pyindex a3586cfd9f96..ed1b134cc743 100644--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py@@ -24,6 +24,7 @@ from posthog.temporal.ai_observability.evaluation_backfill import (EvaluationBackfillWorkflow,FindCandidatesInputs,FindCandidatesOutput,+ MeasureRemainderInputs,PrepareTickOutput,TickAction,advance_evaluation_backfill_cursor_activity,@@ -39,7 +40,7 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import ()from posthog.temporal.ai_observability.run_aggregate_evaluation import RunAggregateEvaluationInputs-from products.ai_observability.backend.backfill_candidates import BackfillCandidate, CandidatePage+from products.ai_observability.backend.backfill_candidates import BackfillCandidate, BackfillScope, CandidatePagefrom products.ai_observability.backend.models.evaluation_backfill import EvaluationBackfill, EvaluationBackfillStatusfrom products.ai_observability.backend.models.evaluations import Evaluation@@ -226,11 +227,6 @@ class TestEvaluationBackfillWorkflow:assert called.index(measure_evaluation_backfill_remainder_activity) > called.index(advance_evaluation_backfill_cursor_activity)- measure = next(- call for fn, call in mocks.activity_calls if fn is measure_evaluation_backfill_remainder_activity- )- # The children this tick started have not produced verdicts yet, so the count discounts them.- assert measure.in_flight == 1continue_as_new.assert_not_called()@pytest.mark.asyncio@@ -464,6 +460,30 @@ def _advance(@pytest.mark.django_db(transaction=True)class TestEvaluationBackfillActivities:+ @pytest.mark.parametrize(+ "dispatched,skipped,counted,expected",+ [+ (1, 15, 14, 0),+ (3000, 0, 3000, 0),+ (1, 0, 5, 4),+ ],+ )+ def test_remainder_discounts_every_unit_the_run_covered(+ self, backfill_data, dispatched: int, skipped: int, counted: int, expected: int+ ) -> None:+ _update_backfill(backfill_data, dispatched_count=dispatched, skipped_count=skipped)++ with patch(+ "posthog.temporal.ai_observability.evaluation_backfill.count_backfill_candidates",+ return_value=BackfillScope(to_evaluate=counted, already_judged=0),+ ):+ async_to_sync(measure_evaluation_backfill_remainder_activity)(+ MeasureRemainderInputs(backfill_id=str(backfill_data["backfill"].id), team_id=backfill_data["team"].id)+ )++ backfill_data["backfill"].refresh_from_db()+ assert backfill_data["backfill"].remaining_count == expected+@pytest.mark.parametrize("status", [EvaluationBackfillStatus.COMPLETED, EvaluationBackfillStatus.CANCELLED, None])def test_prepare_returns_finished_for_missing_or_terminal_row(self, backfill_data, status) -> None:inputs = _activity_inputs(backfill_data)diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts b/products/ai_observability/frontend/evaluations/backfillConditions.test.tsindex 02db49c1c9d6..bbd853d973ff 100644--- a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts+++ b/products/ai_observability/frontend/evaluations/backfillConditions.test.ts@@ -1,7 +1,13 @@import { dayjs } from 'lib/dayjs'import type { EvaluationBackfillApi } from '../generated/api.schemas'-import { backfillCoveredCount, backfillRangeDateFormat, backfillSamplingLabel } from './backfillConditions'+import {+ backfillCoveredCount,+ backfillLateArrivalCount,+ backfillRangeDateFormat,+ backfillSamplingLabel,+ backfillTotalCount,+} from './backfillConditions'function backfill(overrides: Partial<EvaluationBackfillApi> = {}): EvaluationBackfillApi {return {@@ -43,9 +49,21 @@ describe('backfillCoveredCount', () => {['a finished run that left work counts the rest', { remaining_count: 3 }, 5],['an unmeasured run counts what the walk handled', { remaining_count: null }, 3],['a running one counts what the walk handled', { status: 'running' as const, remaining_count: null }, 3],- ['a remainder above the total cannot go negative', { total_count: 1, remaining_count: 2 }, 0],- ['coverage never exceeds the total', { status: 'running' as const, total_count: 1, remaining_count: null }, 1],+ [+ 'a remainder above the total cannot go negative',+ { total_count: 1, dispatched_count: 0, skipped_count: 0, remaining_count: 2 },+ 0,+ ],+ ['a run that handled more than its estimate counts all of it', { dispatched_count: 10, skipped_count: 0 }, 10],])('%s', (_case, overrides, expected) => {expect(backfillCoveredCount(backfill(overrides))).toEqual(expected)})++ it.each([+ ['the estimate stands while the walk handled less', {}, 8, 0],+ ['the total rises to what the walk found', { dispatched_count: 10, skipped_count: 0 }, 10, 2],+ ])('%s', (_case, overrides, total, late) => {+ expect(backfillTotalCount(backfill(overrides))).toEqual(total)+ expect(backfillLateArrivalCount(backfill(overrides))).toEqual(late)+ })})diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.ts b/products/ai_observability/frontend/evaluations/backfillConditions.tsindex 7f7860d77227..d341a0130371 100644--- a/products/ai_observability/frontend/evaluations/backfillConditions.ts+++ b/products/ai_observability/frontend/evaluations/backfillConditions.ts@@ -20,13 +20,21 @@ export function backfillRangeDateFormat(start: string, end: string, now: dayjs.Dreturn sameYear ? 'MMM D' : 'MMM D, YYYY'}+/** Raised, never replaced: a run whose units the live path graded mid-walk handles fewer than it+ * was created for, and those units are covered too. */+export function backfillTotalCount(backfill: EvaluationBackfillApi): number {+ return Math.max(backfill.total_count, backfill.dispatched_count + backfill.skipped_count)+}++export function backfillLateArrivalCount(backfill: EvaluationBackfillApi): number {+ return backfillTotalCount(backfill) - backfill.total_count+}+export function backfillCoveredCount(backfill: EvaluationBackfillApi): number {- // A finished run knows what the window still owed. Until then, coverage is what the walk itself- // handled. The total is the estimate taken at creation while the remainder is counted later, so- // an event arriving in between can leave more owed than the total ever held.+ const total = backfillTotalCount(backfill)const covered =backfill.status === 'completed' && backfill.remaining_count !== null- ? backfill.total_count - backfill.remaining_count+ ? total - backfill.remaining_count: backfill.dispatched_count + backfill.skipped_count- return clamp(covered, 0, backfill.total_count)+ return clamp(covered, 0, total)}diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsxindex 1af9457e247d..efb484fbad7a 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx@@ -31,7 +31,13 @@ import type {EvaluationBackfillConditionApi,EvaluationBackfillStatusEnumApi,} from '../../generated/api.schemas'-import { backfillCoveredCount, backfillRangeDateFormat, backfillSamplingLabel } from '../backfillConditions'+import {+ backfillCoveredCount,+ backfillLateArrivalCount,+ backfillRangeDateFormat,+ backfillSamplingLabel,+ backfillTotalCount,+} from '../backfillConditions'import { evaluationBackfillsLogic } from '../evaluationBackfillsLogic'import { EvaluationTriggers } from './EvaluationTriggers'@@ -263,6 +269,7 @@ export function EvaluationBackfillsTab({// walk never saw it.const measured = backfill.status === 'completed' && backfill.remaining_count !== nullconst covered = backfillCoveredCount(backfill)+ const total = backfillTotalCount(backfill)return (<Tooltiptitle={@@ -273,7 +280,7 @@ export function EvaluationBackfillsTab({><div className="min-w-24"><span className="whitespace-nowrap" translate="no">- {covered.toLocaleString('en-US')} / {backfill.total_count.toLocaleString('en-US')}+ {covered.toLocaleString('en-US')} / {total.toLocaleString('en-US')}</span>{backfill.dispatched_count > 0 && (<span className="text-muted whitespace-nowrap">@@ -283,7 +290,7 @@ export function EvaluationBackfillsTab({)}<LemonProgressclassName="mt-1"- percent={backfill.total_count > 0 ? (covered / backfill.total_count) * 100 : 0}+ percent={total > 0 ? (covered / total) * 100 : 0}strokeColor={backfill.status === 'running' ? undefined : 'var(--border)'}/></div>@@ -444,6 +451,7 @@ export function EvaluationBackfillsTab({onRowCollapse: (backfill) => collapseBackfill(backfill.id),expandedRowRender: (backfill) => {const leftBehind = backfillLeftBehindLabel(backfill)+ const lateArrivals = backfillLateArrivalCount(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">@@ -476,10 +484,16 @@ export function EvaluationBackfillsTab({<span>{backfill.dispatched_count.toLocaleString('en-US')} started,{' '}{backfill.skipped_count.toLocaleString('en-US')} skipped, out of{' '}- {pluralize(backfill.total_count, backfill.target)}+ {pluralize(backfillTotalCount(backfill), backfill.target)}{backfill.rerun_existing ? ' in range' : ' that had no result'}</span></div>+ {lateArrivals > 0 && (+ <div className="text-muted">+ {pluralize(lateArrivals, backfill.target)} arrived in this range after the+ backfill started, so it covered more than the first count found.+ </div>+ )}{leftBehind && <div className="text-warning">{leftBehind}</div>}</div><LemonButton