: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(engineering-analytics): flag re-run copies without a window sort (#91931)
Andy Zhaocb887890c3f6
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex fa7d007991d7..b4a325921b49 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -107,7 +107,7 @@ They are non-materialized: the rendered SQL is persisted per team and re-synced- Cost runs off Depot's billed clock, not `duration_seconds` (§6). `billable_seconds` is that clock; `duration_seconds` stays the full wall-clock GitHub reports.- Cost is defined once, in `logic/cost.py`, rendered to HogQL; a ClickHouse-backed parity test asserts the view equals the Python model. The endpoint cost queries read the same rendered SELECT (via `_curated.job_cost_source()`), so there is no second cost path to drift.- `is_merge_queue` splits merge-queue gate spend from the rest without anyone re-deriving what a gate branch is. Both this view and `ci_job_history` carry it, so neither answers "what does the queue cost" by pattern-matching a branch name.-- **The view carries no scan floor, so filter it tightly.** It is stored SQL with no window of its own, and the `is_rerun_copy` window means an unfiltered `SELECT` sorts the team's whole job history. Insights and `execute-sql` should bound `created_at` (and, for a scan the engine can actually prune, keep the bound close). The product's own endpoint queries pass `created_floor` instead (§6).+- **The view carries no scan floor, so filter it tightly.** It is stored SQL with no window of its own, so an unfiltered `SELECT` reads the team's whole job history, and the `is_rerun_copy` duplicate scan always aggregates all of it. Insights and `execute-sql` should bound `created_at` (and, for a scan the engine can actually prune, keep the bound close). The product's own endpoint queries pass `created_floor` instead (§6). Memory stays bounded either way: the flag comes from a narrow duplicate-key join, never a window function, because a window sorts every column of the whole scan in memory.#### `engineering_analytics_ci_job_history`@@ -145,9 +145,9 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- `duration_seconds` is deliberately left alone — queue and duration UX is about the window GitHub reports. Only the cost columns read the billed clock, and `logic/cost.py` defines it once for both the Python model and the rendered SQL.- **A GitHub "re-run failed jobs" copy is not an execution — flagged once, in the `workflow_jobs` builder.** When a run is partially re-run, GitHub's jobs API lists every already-passed job again under the new `run_attempt` with new job ids but the earlier attempt's exact `started_at` / `completed_at` (`filter=latest` returns them too, so the source can't drop them). A row is a copy when the same `(run_id, name, started_at, completed_at)` exists at a lower `run_attempt`; `is_rerun_copy` says so, and `logic/cost.py`'s `render_is_billable_job` is the one predicate every cost consumer partitions on. Copies are a few percent of job rows and minutes; counting them over-reported CI spend, retry pressure, and duration samples by that much.- Copies are flagged, never filtered at the substrate: the exposed views keep one row per job attempt, matching what GitHub shows for the run, and each consumer decides. Cost drops them; so do the per-job aggregates (a copy would double every duration sample and report a retry nobody performed). Red/green reads keep them — a copy is a green re-listing of a green job, so it changes no verdict.- - The flag is a window over `(run_id, name, started_at, completed_at)`, which blocks a caller's outer `created_at_raw` predicate from pruning the scan. Windowed callers pass `created_floor=True` so the same coarse floor lands **below** the window instead (see the `workflow_jobs` builder); `job_costs.build_query` and `_curated.job_cost_source()` thread it through for the cost surfaces.+ - The flag comes from a duplicate-key join, never a window function: a five-column scan aggregates the duplicated `(run_id, name, started_at, completed_at)` groups, and each job LEFT JOINs against them. A window function would sort the whole scan in memory, and the exposed views have no floor to bound it. A caller's outer `created_at_raw` predicate never reaches the duplicate scan, so windowed callers pass `created_floor=True`, which floors both scans (see the `workflow_jobs` builder); `job_costs.build_query` and `_curated.job_cost_source()` thread it through for the cost surfaces.- The floor's slack depends on which clock the query windows (`_workflow_filters`). One day when it filters the job's own `created_at` — that only absorbs a timezone offset. A week when it filters the RUN's start, which every cost surface does: a re-run's runs row carries only its newest attempt's `run_started_at`, so its earlier attempts' job rows — the ones that actually ran — were created before the window. A tight floor there would cut them and silently under-report the re-run, undoing the `run_id`-only join above.- - Two cost queries stay unfloored on purpose: single-PR cost and the PR-list cost rollup are keyed by PR number, not a window, and no cheap date bound exists for either (see `pr_cost.py`). The per-run job breakdown is unfloored too — it filters `run_id`, the window's leading partition column.+ - Two cost queries stay unfloored on purpose: single-PR cost and the PR-list cost rollup are keyed by PR number, not a window, and no cheap date bound exists for either (see `pr_cost.py`). The per-run job breakdown is unfloored too: it filters `run_id`, which prunes the jobs scan, and the five-column duplicate scan is cheap even unbounded.- **Warehouse columns are strings + Nullable JSON; the builders parse and `ifNull`-guard.** Timestamps parse via `parseDateTimeBestEffort`; Nullable columns unwrap before any array function (ClickHouse rejects an Array inside a Nullable). `source_schema.py` mirrors the real landed types so seed and tests exercise the real path; violating this 500'd every endpoint on real data while idealized fixtures stayed green.- **The warehouse views are managed data, not code registration.** "No global HogQL views" locks out `Database.create_for` (core importing the product, every team's per-query hot path). A per-team `DataWarehouseSavedQuery`, synced only for qualifying teams, reopens nothing: it exists so cost and CI history are queryable by insights, subscriptions, and `execute-sql`.- **Workflow pass rate uses verdicts, not every completed run.** `success` is a pass. `failure`, `timed_out`, `startup_failure`, and `stale` are decisive failures. Skipped, cancelled, neutral, action-required, unsettled, and unknown outcomes reached no pass-or-fail verdict, so they stay in run volume but not the rate. The backend query layer owns this classification; frontend summaries over raw run rows mirror it in `lifecycle.ts`.diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 5e015bc2fb17..3b94046db6ba 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -195,7 +195,7 @@ class CuratedGitHubSource:``created_floor`` adds the raw-string scan floor inside the builder — callers must register{job_created_floor} (see run_started_floor_constant). A windowed caller needs it: the builder's- ``is_rerun_copy`` window blocks an outer ``created_at_raw`` predicate from pruning the scan."""+ ``is_rerun_copy`` duplicate scan reads no ``created_at_raw``, so only the floor bounds it."""if not self._tables.workflow_jobs:return Nonereturn f"({workflow_jobs.build_query(self._tables.workflow_jobs, created_floor=created_floor)})"@@ -317,8 +317,8 @@ class CuratedGitHubSource:``created_floor`` adds the raw-string scan floor inside the jobs builder — callers mustregister {job_created_floor} (see run_windowed_job_created_floor_constant, the right slack forthe run-windowed predicates every cost query uses). Every windowed caller wants it: the cost- source's window predicates read the RUN's columns and so can never prune the jobs scan, which- the ``is_rerun_copy`` window would otherwise sort in full on every call.+ source's window predicates read the RUN's columns and so can never prune the jobs scan, and+ the ``is_rerun_copy`` duplicate scan would otherwise aggregate the full history on every call."""if not self._tables.workflow_jobs:return Nonediff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.pyindex cd80f71c1025..84ef16eb9aab 100644--- a/products/engineering_analytics/backend/logic/views/job_costs.py+++ b/products/engineering_analytics/backend/logic/views/job_costs.py@@ -158,9 +158,9 @@ def build_query(``created_floor`` threads the jobs builder's raw-string scan floor (its ``{job_created_floor}``placeholder, which the caller must register) down to the jobs scan. Every windowed cost queryshould pass it: the window predicate reads the RUN's attributes, so it can never prune the jobs- side, and without a floor the ``is_rerun_copy`` window sorts the team's whole job history on every- call. The public saved view can't take one — it is stored SQL with no window of its own — so it is- built without it and its consumers filter it themselves.+ side, and without a floor the ``is_rerun_copy`` duplicate scan aggregates the team's whole job+ history on every call. The public saved view can't take one — it is stored SQL with no window of+ its own — so it is built without it and its consumers filter it themselves."""jobs = workflow_jobs.build_query(jobs_table, created_floor=created_floor)runs = workflow_runs.build_query(runs_table)diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.pyindex 72a58ceeb5c5..4cb5722cf861 100644--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py@@ -25,22 +25,29 @@ copied verbatim from the attempt that actually ran (a partial re-run of a largepassed job and re-runs only the failed ones; GitHub's ``filter=latest`` returns the re-listings too, sothe source can't drop them). Those rows are re-listings, not executions — nothing ran and Depot billednothing — and they are a few percent of job rows and minutes. A row is a copy when the same-``(run_id, name, started_at, completed_at)`` exists at a LOWER ``run_attempt``, which is the window-below. Consumers counting executions (cost, retry pressure, duration percentiles) must exclude them;-the flag is defined here so nobody re-derives it.+``(run_id, name, started_at, completed_at)`` exists at a LOWER ``run_attempt``. Consumers counting+executions (cost, retry pressure, duration percentiles) must exclude them; the flag is defined here+so nobody re-derives it.++A narrow aggregate scan finds the duplicated ``(run_id, name, started_at, completed_at)`` groups,+and each job LEFT JOINs against them. Never compute this flag with a window function: a window sorts+every selected column of its whole input in memory, and an outer date filter cannot pass a window+step. The exposed views have no scan floor, so a windowed flag made every query sort the team's+entire job history and exceed the per-query memory limit. The aggregate reads five columns and keeps+only the duplicated groups, so memory scales with the re-runs, not the history.The raw ``created_at`` string rides along as ``created_at_raw`` (unparsed) because ISO-8601 stringscompare correctly lexicographically. A parsed-column predicate never pushes down to the parquet/S3scan, so a raw-column floor (``created_at_raw >= '<date>'``) is the only windowing predicate the scancan prune on — the parsed ``created_at`` stays the precise filter, the raw twin lets the scan skip.-A caller's own outer ``created_at_raw`` predicate no longer prunes, though: it sits above the-``is_rerun_copy`` window, and ClickHouse can only push a filter below a window step when it reads-partition-by columns. Windowed callers therefore pass ``created_floor=True``, which puts the same-coarse floor in an innermost prefilter on the RAW column — below the window, where the scan can still-use it — and register the ``{job_created_floor}`` placeholder (see ``run_started_floor_constant``,-shared with the runs builder). The trade is exact: a run whose earlier attempt falls below the floor-loses the evidence that its later attempt is a copy, so a boundary re-run reads as billable — the same-coarseness the floor already has, and why the floor sits a day below the window.+A caller's own outer ``created_at_raw`` predicate can prune the jobs scan, but never the duplicate+scan, which reads no ``created_at_raw``. Windowed callers therefore pass ``created_floor=True`` and+register the ``{job_created_floor}`` placeholder (see ``run_started_floor_constant``, shared with+the runs builder). The floor is a prefilter on the RAW column inside the shared table source, so it+bounds both scans. The trade is exact: a run whose+earlier attempt falls below the floor loses the evidence that its later attempt is a copy, so a+boundary re-run reads as billable — the same coarseness the floor already has, and why the floor sits+a day below the window.Embedded as a subquery by the jobs query module (see ``_curated``); nothing registers a global view."""@@ -56,54 +63,48 @@ _FIRST_STEP_STARTED_AT = (")")-# A row GitHub re-listed under a later attempt without re-running it (see the module docstring): the-# same run, job name, and exact start/finish already exist at a lower attempt. Both timestamps must be-# present — two still-queued attempts of the same job both carry NULL and are not copies of each other.-_IS_RERUN_COPY = """ifNull(- started_at IS NOT NULL- AND completed_at IS NOT NULL- AND run_attempt > min(run_attempt) OVER (- PARTITION BY run_id, name, started_at, completed_at- ),- 0- )"""-def build_query(table_name: str, *, created_floor: bool = False) -> str:# The floor must live in its OWN innermost SELECT on the raw string column, like the runs# builder's: the parsing SELECT below aliases parseDateTimeBestEffort(created_at) AS created_at,- # so a WHERE there would compare the parsed DateTime against the floor string.+ # so a WHERE there would compare the parsed DateTime against the floor string. Both the jobs scan+ # and the duplicate scan read this source, so the one floor bounds both.table_source = (f"(SELECT * FROM {table_name} WHERE created_at >= {{job_created_floor}})" if created_floor else table_name)return f"""SELECT- id,- run_id,- run_attempt,- name,- workflow_name,- head_sha,- head_branch,- status,- conclusion,- labels,- runner_name,- created_at,- created_at_raw,- started_at,- completed_at,- if(status = 'completed', dateDiff('second', started_at, completed_at), NULL) AS duration_seconds,+ job.id AS id,+ job.run_id AS run_id,+ job.run_attempt AS run_attempt,+ job.name AS name,+ job.workflow_name AS workflow_name,+ job.head_sha AS head_sha,+ job.head_branch AS head_branch,+ job.status AS status,+ job.conclusion AS conclusion,+ job.labels AS labels,+ job.runner_name AS runner_name,+ job.created_at AS created_at,+ job.created_at_raw AS created_at_raw,+ job.started_at AS started_at,+ job.completed_at AS completed_at,+ if(job.status = 'completed', dateDiff('second', job.started_at, job.completed_at), NULL) AS duration_seconds,-- Queue wait: webhook creation to first execution. NULL while still queued.- if(started_at IS NOT NULL, dateDiff('second', created_at, started_at), NULL) AS queue_seconds,+ if(job.started_at IS NOT NULL, dateDiff('second', job.created_at, job.started_at), NULL) AS queue_seconds,-- Runner boot: the job's start to its first step's start. NULL when steps aren't synced;-- clamped so a skewed pair can never hand the cost model a negative correction.if(- started_at IS NOT NULL AND first_step_started_at IS NOT NULL,- greatest(dateDiff('second', started_at, first_step_started_at), 0),+ job.started_at IS NOT NULL AND job.first_step_started_at IS NOT NULL,+ greatest(dateDiff('second', job.started_at, job.first_step_started_at), 0),NULL) AS provisioning_seconds,- {_IS_RERUN_COPY} AS is_rerun_copy+ -- A matched row shares its exact start/finish with another attempt of the same job; it is+ -- a copy when a LOWER attempt exists. An unmatched row (single occurrence, or NULL+ -- timestamps, which never match the join keys) reads first_attempt as NULL, so the+ -- comparison yields 0. min(run_attempt) stays Nullable, which makes the LEFT JOIN+ -- non-match default NULL rather than 0 (a 0 default would flag every unmatched row).+ ifNull(job.run_attempt > dupes.first_attempt, 0) AS is_rerun_copyFROM (SELECTid,@@ -125,5 +126,25 @@ def build_query(table_name: str, *, created_floor: bool = False) -> str:parseDateTimeBestEffort(completed_at) AS completed_at,{_FIRST_STEP_STARTED_AT} AS first_step_started_atFROM (SELECT *, created_at AS created_at_raw FROM {table_source})- )+ ) AS job+ -- The duplicated (run_id, name, started_at, completed_at) groups: the re-run copies plus+ -- their originals, from a scan that reads only these five columns. The HAVING drops the+ -- NULL-timestamp groups too: two still-queued attempts of the same job both carry NULL and+ -- are not copies of each other. The key aliases avoid shadowing the raw columns, so the+ -- GROUP BY unambiguously names the parsed values.+ LEFT JOIN (+ SELECT+ run_id,+ name,+ parseDateTimeBestEffort(started_at) AS started_key,+ parseDateTimeBestEffort(completed_at) AS completed_key,+ min(run_attempt) AS first_attempt+ FROM {table_source}+ GROUP BY run_id, name, started_key, completed_key+ HAVING count() > 1 AND started_key IS NOT NULL AND completed_key IS NOT NULL+ ) AS dupes+ ON job.run_id = dupes.run_id+ AND job.name = dupes.name+ AND job.started_at = dupes.started_key+ AND job.completed_at = dupes.completed_key"""