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.

feat(engineering-analytics): add CI investigation views and skill (#70556)

Julian Bez966820298a7a
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 8e66c6570cbf..1adc37fdc8a3 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -151,11 +151,16 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
All time-windowed access uses `date_from` / `date_to` per PostHog convention (relative `-30d` or ISO8601).
-### Exposed warehouse view
+### Exposed warehouse views
-One warehouse view is exposed so insights, subscriptions, other products, and agents (via
-`execute-sql`) can query per-job CI cost directly — the only surface where the curated read layer
+Three warehouse views are exposed so insights, subscriptions, other products, and agents (via
+`execute-sql`) can query the curated CI substrate directly — the only surface where the read layer
is reachable as data rather than through the named endpoints.
+All three share one gate: a team gets them only when it has a GitHub source with **both** the
+`workflow_runs` and `workflow_jobs` endpoints synced (`resolve_job_cost_source_pairs`), so they
+appear together or not at all, and `get_expected_warehouse_views` stays coherent.
+
+#### `engineering_analytics_job_costs`
- **Name:** `engineering_analytics_job_costs`, provisioned per-team as a `DataWarehouseSavedQuery`
(the revenue-analytics managed-viewset mechanism, kind `engineering_analytics`).
@@ -184,6 +189,64 @@ is reachable as data rather than through the named endpoints.
`estimated_cost_usd` in ClickHouse. Cost is therefore computed exactly once, in one place; there is
no separate Python cost rollup for the endpoints to drift from the view.
+#### `engineering_analytics_ci_job_history`
+
+The per-job-attempt history with commit attribution — the stable substrate for green/red boundary
+analysis ("master went red at SHA X, authored by Y, via PR Z"). Composes the same
+`workflow_jobs` LEFT JOIN `workflow_runs` shape as `job_costs`, unioned across qualifying sources.
+
+- **Grain:** one row per job attempt (a retry appears once per attempt). Jobs whose run row is
+ missing (the LEFT JOIN) are kept, not dropped; ClickHouse fills the unmatched run side with type
+ defaults (empty repo/sha, `pr_number` 0) rather than NULL, so a missing run reads as empty
+ attribution.
+- **Columns:** `repo_owner`, `repo_name`, `workflow_name`, `job_name`, `run_id`, `run_attempt`,
+ `head_branch`, `head_sha` (the run's), `status`, `conclusion`, `created_at`, `started_at`,
+ `completed_at`, `duration_seconds`, `pr_number`, `commit_author_name`, `commit_author_email`,
+ `commit_message`, `commit_pr_number`. Column order is the locked contract (it fixes the UNION ALL
+ order and the saved-query schema).
+- **Two PR keys, by design (SPEC §7):** `pr_number` is the runs builder's association-derived
+ number — kept as `0` when the run has no `pull_requests` association (master pushes, fork PRs),
+ not nulled. `commit_pr_number` is parsed from the head commit's squash-merge suffix via
+ `accurateCastOrNull(regexpExtract(commit_message, '(?m)[(]#([0-9]+)[)]$'), 'Int64')` — anchored to a
+ line end so a revert's quoted inner `(#N)` never wins over the reverting PR's own suffix. This is
+ how a **master push run** gets PR attribution at all, since its `pull_requests` association is
+ empty. On an unjoined run, `pr_number` reads 0 (type default) and `commit_pr_number` NULL.
+- **Commit attribution rule:** `commit_author_name` / `commit_author_email` / `commit_message` come
+ from the run's `head_commit` Nullable-JSON column (`ifNull(head_commit, '{}')`, then
+ `JSONExtractString(…, 'author', 'name')` / `('author', 'email')` / `('message')`). The shared
+ `workflow_runs` builder deliberately does **not** surface commit fields (other embedders don't
+ need them); this view reads them through its own minimal projection over the raw runs table,
+ LEFT-JOINed on `run_id` alone, rather than widening the shared builder. Joining on `run_attempt`
+ too would blank attribution for earlier-attempt jobs after a re-run: the runs snapshot upserts by
+ `id`, so only the newest attempt's row exists, and attribution is attempt-invariant anyway (a
+ re-run is the same commit). `head_commit` is a new Nullable(String) column on
+ `WORKFLOW_RUNS_COLUMNS`.
+
+#### `engineering_analytics_ci_failures`
+
+Row-level fingerprinted CI failure lines from the **Logs** product (`logs` table, not the
+warehouse), for a failure index over the green/red boundary. Team-global (logs aren't
+source-scoped), so no per-source resolution — one view, still gated on the qualifying GitHub source
+above so it appears with `ci_job_history`.
+
+- **Grain:** one row per pytest `FAILED <nodeid>` line —
+ `FROM logs WHERE service_name = 'github-ci-logs' AND regexpExtract(body, 'FAILED ([^[:space:]]+::[^[:space:]]+)') != ''`.
+ The `::` requirement is the pytest discriminator: real CI logs contain `FAILED` in other contexts
+ (env dumps, stage markers) that would otherwise produce junk fingerprints. (HogQL string literals
+ reject `\s`/`\d` escapes, so the regexes use POSIX/char classes instead.)
+- **Columns:** `timestamp`, `test_id` (the `FAILED` node id), `error_signature`, `fingerprint`,
+ `branch`, `head_sha`, `repo`, `workflow_name`, `job_name`, `run_id`, `job_id`, `run_attempt`,
+ `conclusion`. The attribute-map fields ride the emitted log record; `run_id` / `job_id` are
+ `accurateCastOrNull(…, 'Int64')`-cast so they join `ci_job_history` and the raw `github_*` tables.
+- **Fingerprint recipe:** `error_signature` is the trailing `" - <detail>"` with volatile bits
+ normalized — `replaceRegexpAll(…, '[0-9a-fA-F-]{8,}|[0-9]+', 'N')`, truncated to 200 — so two runs of
+ the same failure share it (NULL when there's no trailing detail). `fingerprint` is
+ `concat(test_id, ' | ', <normalized signature>)`, the group key.
+- **pytest-only v1 caveat:** the recipe only matches pytest `FAILED` lines; jest / playwright /
+ cargo failure lines are **not** fingerprinted yet. The recipe lives in code (not a stored
+ materialization) on purpose, so it can evolve by PR as more runners are covered and re-render into
+ a team's view on the next sync.
+
## 6. Delivery shape
Vertical slices, each independently mergeable. The near-term path:
diff --git a/products/engineering_analytics/backend/facade/warehouse_views.py b/products/engineering_analytics/backend/facade/warehouse_views.py
index 4f484c735323..8a6ed6f06891 100644
--- a/products/engineering_analytics/backend/facade/warehouse_views.py
+++ b/products/engineering_analytics/backend/facade/warehouse_views.py
@@ -9,13 +9,19 @@ provider-neutral ``ExpectedWarehouseView`` contract.
from posthog.models.team import Team
from products.engineering_analytics.backend.facade.contracts import ExpectedWarehouseView
-from products.engineering_analytics.backend.logic.views import job_costs
+from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs
def get_expected_warehouse_views(team: Team) -> list[ExpectedWarehouseView]:
"""The team's exposed warehouse views. Empty when the team has no GitHub source with both the
- workflow_runs and workflow_jobs endpoints synced (so no view is created for such teams)."""
- query = job_costs.build_team_view(team)
- if query is None:
- return []
- return [ExpectedWarehouseView(name=job_costs.VIEW_NAME, query=query, fields=job_costs.FIELDS)]
+ workflow_runs and workflow_jobs endpoints synced (so no view is created for such teams).
+
+ All three views share that same qualifying-source gate, so they appear together or not at all:
+ per-job cost, per-job-attempt history with commit attribution, and fingerprinted CI failure lines.
+ """
+ views: list[ExpectedWarehouseView] = []
+ for module in (job_costs, ci_job_history, ci_failures):
+ query = module.build_team_view(team)
+ if query is not None:
+ views.append(ExpectedWarehouseView(name=module.VIEW_NAME, query=query, fields=module.FIELDS))
+ return views
diff --git a/products/engineering_analytics/backend/logic/views/ci_failures.py b/products/engineering_analytics/backend/logic/views/ci_failures.py
new file mode 100644
index 000000000000..82a2a8542ea0
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/views/ci_failures.py
@@ -0,0 +1,119 @@
+"""Row-level fingerprinted CI failure lines from the Logs product — the failure-index substrate.
+
+The CI job-logs worker emits one Logs record per failure line (service ``github-ci-logs``, see
+``job_logs``). This view keeps only the pytest ``FAILED <nodeid>`` lines and turns each into a
+fingerprinted row so a caller can count "how often is this exact failure happening, and on which
+branches / SHAs / PRs" without re-deriving the fingerprint recipe every time.
+
+One row per pytest FAILED line. ``test_id`` is the node id from ``FAILED <id>``; ``error_signature``
+is the trailing ``" - <detail>"`` with volatile bits normalized to ``N`` (long hex/uuid blobs and
+digit runs) so two runs of the same failure share a signature; ``fingerprint`` is
+``test_id | signature`` — the group key. The run/branch/repo/job attributes ride the emitted log
+record, and ``run_id`` / ``job_id`` are cast to Int so they join against ``ci_job_history`` and the
+raw ``github_*`` tables.
+
+The fingerprint recipe is **pytest-only v1** — jest / playwright / cargo failure lines don't match
+``FAILED <id>`` and are not fingerprinted yet. The recipe lives in code (not a stored materialization)
+on purpose, so it can evolve by PR as more test runners are covered, re-rendering into a team's view
+on the next sync.
+
+Reads the ``logs`` table, not the warehouse — the failure lines live in the Logs product. Team-global
+(logs aren't source-scoped), so there is no per-source resolution; the view is still gated on the team
+having a qualifying GitHub source so it appears alongside ``ci_job_history``. Nothing here is
+registered as a global HogQL view; it is provisioned per-team as a non-materialized
+``DataWarehouseSavedQuery`` by data_modeling's managed-viewset sync.
+"""
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, IntegerDatabaseField, StringDatabaseField
+
+from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME
+from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+# Public view name — stable contract for insights, subscriptions, other products, and execute-sql.
+VIEW_NAME = "engineering_analytics_ci_failures"
+
+# Public column contract (order fixes the saved-query schema). ``nullable=True`` where a value can be
+# absent: no trailing detail → NULL signature; an unstamped conclusion attribute → NULL conclusion.
+FIELDS: dict[str, FieldOrTable] = {
+ "timestamp": DateTimeDatabaseField(name="timestamp"),
+ "test_id": StringDatabaseField(name="test_id"),
+ "error_signature": StringDatabaseField(name="error_signature", nullable=True),
+ "fingerprint": StringDatabaseField(name="fingerprint"),
+ "branch": StringDatabaseField(name="branch"),
+ "head_sha": StringDatabaseField(name="head_sha"),
+ "repo": StringDatabaseField(name="repo"),
+ "workflow_name": StringDatabaseField(name="workflow_name"),
+ "job_name": StringDatabaseField(name="job_name"),
+ "run_id": IntegerDatabaseField(name="run_id"),
+ "job_id": IntegerDatabaseField(name="job_id"),
+ "run_attempt": IntegerDatabaseField(name="run_attempt", nullable=True),
+ "conclusion": StringDatabaseField(name="conclusion", nullable=True),
+}
+
+# ``__SERVICE_NAME__`` is substituted with the constant below (a plain identifier, not user input) —
+# .replace, not an f-string, so the ``{8,}`` regex quantifier doesn't collide with f-string braces.
+# The inner layer extracts test_id + the normalized signature; the outer layer derives error_signature
+# (NULL when empty) and the fingerprint off those projected columns (a same-SELECT alias can't feed
+# another expression). Volatile bits — long hex/uuid runs and digit runs — collapse to ``N`` so the
+# same failure across runs shares a signature, truncated to keep the group key bounded.
+_SELECT = """
+ SELECT
+ `timestamp`,
+ test_id,
+ nullIf(signature, '') AS error_signature,
+ concat(test_id, ' | ', signature) AS fingerprint,
+ branch,
+ head_sha,
+ repo,
+ workflow_name,
+ job_name,
+ run_id,
+ job_id,
+ run_attempt,
+ conclusion
+ FROM (
+ SELECT
+ `timestamp`,
+ -- The '::' requirement is what makes this pytest-specific: CI log lines containing FAILED
+ -- in other contexts (env dumps, stage markers) carry no '::' node id and are dropped.
+ -- Primary: non-greedy capture up to the FIRST ' - ' separator (pytest short-summary format),
+ -- which keeps spaces inside parameterized ids like test_x[user 123]. Fallback: the no-space
+ -- form, for FAILED lines without a ' - ' detail suffix. Residual limitation: a param value
+ -- containing a literal ' - ' still truncates at it — regex can't disambiguate that from the
+ -- message separator.
+ coalesce(nullIf(regexpExtract(body, 'FAILED (.+?::.*?) - '), ''), regexpExtract(body, 'FAILED ([^[:space:]]+::[^[:space:]]+)')) AS test_id,
+ substring(replaceRegexpAll(regexpExtract(body, ' - (.*)$'), '[0-9a-fA-F-]{8,}|[0-9]+', 'N'), 1, 200) AS signature,
+ attributes['branch'] AS branch,
+ attributes['head_sha'] AS head_sha,
+ attributes['repo'] AS repo,
+ attributes['workflow_name'] AS workflow_name,
+ attributes['job_name'] AS job_name,
+ accurateCastOrNull(attributes['run_id'], 'Int64') AS run_id,
+ accurateCastOrNull(attributes['job_id'], 'Int64') AS job_id,
+ accurateCastOrNull(attributes['run_attempt'], 'Int64') AS run_attempt,
+ nullIf(attributes['conclusion'], '') AS conclusion
+ FROM logs
+ WHERE service_name = '__SERVICE_NAME__' AND regexpExtract(body, 'FAILED ([^[:space:]]+::[^[:space:]]+)') != ''
+ )
+"""
+
+
+def build_query() -> str:
+ """The failure-line SELECT over the team's Logs. No per-source table — logs are team-global."""
+ return _SELECT.replace("__SERVICE_NAME__", CI_LOGS_SERVICE_NAME)
+
+
+def build_team_view(team: "Team") -> str | None:
+ """The view body, or None when the team has no qualifying GitHub source.
+
+ Gated on the same ``resolve_job_cost_source_pairs`` condition as ``ci_job_history`` so the two
+ views always appear together — a team without a synced GitHub jobs/runs source gets neither.
+ """
+ if not resolve_job_cost_source_pairs(team):
+ return None
+ return build_query()
diff --git a/products/engineering_analytics/backend/logic/views/ci_job_history.py b/products/engineering_analytics/backend/logic/views/ci_job_history.py
new file mode 100644
index 000000000000..2ca458bb2d2e
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -0,0 +1,183 @@
+"""Per-job-attempt CI history with commit attribution — the green/red boundary substrate.
+
+Composes the curated ``workflow_jobs`` and ``workflow_runs`` builders (one row per job attempt,
+jobs LEFT JOIN runs) exactly like ``job_costs``, but instead of the cost model it exposes commit
+attribution: who authored the head commit, its message, and which PR the run belongs to. That is
+what lets a caller answer "master went red at SHA X, authored by Y, via PR Z" — the boundary
+analysis the CI-breakage investigation skill runs.
+
+``build_query`` renders the SELECT for one GitHub source; ``build_team_view`` unions every
+qualifying source. The jobs↔runs join is a LEFT JOIN on ``run_id`` alone: the runs warehouse
+snapshot upserts by ``id`` and keeps only the newest attempt's row per run, so requiring
+``run_attempt`` equality would blank attribution for every earlier-attempt job after a re-run.
+Attribution is attempt-invariant (a re-run is the same commit), so joining on ``run_id`` is
+correct; ``run_attempt`` in the output comes from the jobs side. A LEFT JOIN so a job attempt is
+never dropped when its run row is missing. ClickHouse fills the unmatched run side with type
+defaults (empty repo/sha, ``pr_number`` 0), not NULL — HogQL doesn't set ``join_use_nulls`` — so a
+missing run reads as empty attribution rather than a real repo.
+
+Commit attribution comes from the run's ``head_commit`` Nullable-JSON column, which the shared
+``workflow_runs`` builder deliberately does not surface (other embedders — cost, health, PR list —
+don't need it, and the builder stays lean). Rather than widen the shared builder, this module reads
+the commit fields through its own minimal projection over the raw runs table and LEFT JOINs it on
+``run_id`` — the ``head_commit`` JSON is ``ifNull``-unwrapped before ``JSONExtractString``
+because a Nullable column can't feed the extractor.
+
+Two PR keys, by design: ``pr_number`` is the runs builder's association-derived number (0 when the
+run has no ``pull_requests`` association — pushes to master, fork PRs), and ``commit_pr_number`` is
+parsed from the squash-merge message's ``(#NNNN)`` suffix. The latter is how a master push run gets
+PR attribution at all, since its ``pull_requests`` association is empty (SPEC §7).
+
+``created_at_raw`` is the unparsed jobs ``created_at`` string riding alongside the parsed
+``created_at``. Consumers windowing this view pair their precise ``created_at`` bound with a coarse
+``created_at_raw >= '<YYYY-MM-DD>'`` floor a day below the window — ISO strings compare
+lexicographically, and a raw-string predicate is the only one the parquet scan can prune on (a
+parsed-column predicate hits a computed column and forces a full scan). ``created_at`` stays the
+precise filter; the raw twin just lets the jobs scan skip.
+
+Nothing here is registered as a global HogQL view; it is provisioned per-team as a non-materialized
+``DataWarehouseSavedQuery`` by data_modeling's managed-viewset sync (kind ``engineering_analytics``).
+"""
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, IntegerDatabaseField, StringDatabaseField
+
+from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs
+from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+# Public view name — stable contract for insights, subscriptions, other products, and execute-sql.
+VIEW_NAME = "engineering_analytics_ci_job_history"
+
+# Public column contract (order fixes the UNION ALL column order across sources and the saved-query
+# schema). ``nullable=True`` on the columns that can genuinely be NULL (the parsed timestamps, a
+# queued job's conclusion/completed_at, a run's raw head_sha, and commit_pr_number when there's no
+# ``(#NNNN)``); the attribution columns stay nullable for parity with job_costs even though a join
+# miss fills them with type defaults rather than NULL (see the module docstring).
+FIELDS: dict[str, FieldOrTable] = {
+ "repo_owner": StringDatabaseField(name="repo_owner", nullable=True),
+ "repo_name": StringDatabaseField(name="repo_name", nullable=True),
+ "workflow_name": StringDatabaseField(name="workflow_name"),
+ "job_name": StringDatabaseField(name="job_name"),
+ "run_id": IntegerDatabaseField(name="run_id"),
+ "run_attempt": IntegerDatabaseField(name="run_attempt"),
+ "head_branch": StringDatabaseField(name="head_branch"),
+ "head_sha": StringDatabaseField(name="head_sha", nullable=True),
+ "status": StringDatabaseField(name="status"),
+ "conclusion": StringDatabaseField(name="conclusion", nullable=True),
+ "created_at": DateTimeDatabaseField(name="created_at", nullable=True),
+ "created_at_raw": StringDatabaseField(name="created_at_raw", nullable=True),
+ "started_at": DateTimeDatabaseField(name="started_at", nullable=True),
+ "completed_at": DateTimeDatabaseField(name="completed_at", nullable=True),
+ "duration_seconds": IntegerDatabaseField(name="duration_seconds", nullable=True),
+ "pr_number": IntegerDatabaseField(name="pr_number", nullable=True),
+ "commit_author_name": StringDatabaseField(name="commit_author_name", nullable=True),
+ "commit_author_email": StringDatabaseField(name="commit_author_email", nullable=True),
+ "commit_message": StringDatabaseField(name="commit_message", nullable=True),
+ "commit_pr_number": IntegerDatabaseField(name="commit_pr_number", nullable=True),
+}
+
+
+def _head_commit_query(runs_table: str) -> str:
+ """The run's commit attribution, keyed on ``run_id`` alone — attribution is attempt-invariant.
+
+ ``ifNull``-unwraps the Nullable ``head_commit`` JSON to ``'{}'`` before extracting, so a run
+ with no landed commit object yields empty strings rather than a Nullable-into-extractor error.
+ """
+ return f"""
+ SELECT
+ run_id,
+ JSONExtractString(head_commit, 'author', 'name') AS commit_author_name,
+ JSONExtractString(head_commit, 'author', 'email') AS commit_author_email,
+ JSONExtractString(head_commit, 'message') AS commit_message
+ FROM (
+ SELECT
+ id AS run_id,
+ ifNull(head_commit, '{{}}') AS head_commit
+ FROM {runs_table}
+ )
+ """
+
+
+def build_query(*, jobs_table: str, runs_table: str) -> str:
+ """The per-job-attempt history SELECT for one GitHub source: curated jobs LEFT JOIN curated runs,
+ plus the run's commit attribution.
+
+ Two layers so ``commit_pr_number`` can be derived from ``commit_message``: the inner join layer
+ projects the raw columns (including ``commit_message`` from the head-commit projection), and the
+ outer layer extracts the squash-merge PR number off that projected column — a same-SELECT alias
+ can't feed another expression, so the extraction lives one level up.
+ """
+ jobs = workflow_jobs.build_query(jobs_table)
+ runs = workflow_runs.build_query(runs_table)
+ head_commits = _head_commit_query(runs_table)
+
+ return f"""
+ SELECT
+ repo_owner,
+ repo_name,
+ workflow_name,
+ job_name,
+ run_id,
+ run_attempt,
+ head_branch,
+ head_sha,
+ status,
+ conclusion,
+ created_at,
+ created_at_raw,
+ started_at,
+ completed_at,
+ duration_seconds,
+ pr_number,
+ commit_author_name,
+ commit_author_email,
+ commit_message,
+ -- Anchored to a line end ((?m) — the squash title): an unanchored match would take the
+ -- FIRST (#N) in the message, misattributing reverts ('Revert "x (#A)" (#B)') to the
+ -- reverted PR instead of the reverting one.
+ accurateCastOrNull(regexpExtract(commit_message, '(?m)[(]#([0-9]+)[)]$'), 'Int64') AS commit_pr_number
+ FROM (
+ SELECT
+ r.repo_owner AS repo_owner,
+ r.repo_name AS repo_name,
+ j.workflow_name AS workflow_name,
+ j.name AS job_name,
+ j.run_id AS run_id,
+ j.run_attempt AS run_attempt,
+ j.head_branch AS head_branch,
+ r.head_sha AS head_sha,
+ j.status AS status,
+ j.conclusion AS conclusion,
+ j.created_at AS created_at,
+ j.created_at_raw AS created_at_raw,
+ j.started_at AS started_at,
+ j.completed_at AS completed_at,
+ j.duration_seconds AS duration_seconds,
+ -- The runs builder emits 0 for a run with no PR association; keep that semantic (a
+ -- LEFT-JOIN miss also reads 0 — type default). commit_pr_number is the push-run fallback.
+ r.pr_number AS pr_number,
+ hc.commit_author_name AS commit_author_name,
+ hc.commit_author_email AS commit_author_email,
+ hc.commit_message AS commit_message
+ FROM ({jobs}) AS j
+ LEFT JOIN ({runs}) AS r ON j.run_id = r.id
+ LEFT JOIN ({head_commits}) AS hc ON j.run_id = hc.run_id
+ )
+ """
+
+
+def build_team_view(team: "Team") -> str | None:
+ """The full view body for a team: every GitHub source with both runs and jobs synced, unioned.
+
+ None when the team has no qualifying source (no view is created). Gated on the same
+ ``resolve_job_cost_source_pairs`` condition as ``job_costs`` so the exposed views stay coherent.
+ """
+ pairs = resolve_job_cost_source_pairs(team)
+ if not pairs:
+ return None
+ selects = [build_query(jobs_table=jobs_table, runs_table=runs_table) for jobs_table, runs_table in pairs]
+ return "\nUNION ALL\n".join(selects)
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 9ffe477fb70c..7da2737084b2 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -49,6 +49,10 @@ WORKFLOW_RUNS_COLUMNS: dict[str, dict[str, str]] = {
"run_attempt": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
"pull_requests": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"repository": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ # The run's head commit object (author, message, id) verbatim as JSON. Carries the commit
+ # attribution the ci_job_history view extracts; a push run's PR number rides its squash-merge
+ # message when the pull_requests association is empty (master pushes). Nullable like every column.
+ "head_commit": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
}
# Contract for the incoming ``github_workflow_jobs`` warehouse source (job-level CI: queue
diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
index 88ae93413aa6..7b8f41241eaa 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
@@ -11,6 +11,11 @@ Same two-layer shape as ``workflow_runs``: the inner SELECT parses timestamps wi
``parseDateTimeBestEffortOrNull`` (a queued/running job has no start/finish) and unwraps Nullable
JSON with ``ifNull``; the outer SELECT derives the duration off the parsed columns.
+The raw ``created_at`` string rides along as ``created_at_raw`` (unparsed) because ISO-8601 strings
+compare correctly lexicographically. A parsed-column predicate never pushes down to the parquet/S3
+scan, so a raw-column floor (``created_at_raw >= '<date>'``) is the only windowing predicate the scan
+can prune on — the parsed ``created_at`` stays the precise filter, the raw twin lets the scan skip.
+
Embedded as a subquery by the jobs query module (see ``_curated``); nothing registers a global view.
"""
@@ -29,6 +34,7 @@ def build_query(table_name: str) -> str:
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,
@@ -49,8 +55,9 @@ def build_query(table_name: str) -> str:
-- HogQL maps parseDateTimeBestEffort to the OrNull variant, so an empty/queued '' lands
-- as NULL with no explicit nullIf — same as the runs builder.
parseDateTimeBestEffort(created_at) AS created_at,
+ created_at_raw,
parseDateTimeBestEffort(started_at) AS started_at,
parseDateTimeBestEffort(completed_at) AS completed_at
- FROM {table_name}
+ FROM (SELECT *, created_at AS created_at_raw FROM {table_name})
)
"""
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index fdd0845e9c56..f4cfadd700a6 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -86,12 +86,14 @@ def _flatten_pr(pr: dict[str, Any]) -> dict[str, Any]:
def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:
- scalar_keys = [key for key in WORKFLOW_RUNS_COLUMNS if key not in ("repository", "pull_requests")]
+ json_keys = ("repository", "pull_requests", "head_commit")
+ scalar_keys = [key for key in WORKFLOW_RUNS_COLUMNS if key not in json_keys]
return {
# .get() tolerates a pre-existing fixture captured before run_attempt / pull_requests were added.
**{key: run.get(key) for key in scalar_keys},
"repository": json.dumps(run["repository"]),
"pull_requests": json.dumps(run.get("pull_requests", [])),
+ "head_commit": json.dumps(run.get("head_commit", {})),
}
diff --git a/products/engineering_analytics/backend/tests/test_ci_views.py b/products/engineering_analytics/backend/tests/test_ci_views.py
new file mode 100644
index 000000000000..c4d0a1aebc49
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_ci_views.py
@@ -0,0 +1,354 @@
+import json
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+import pandas as pd
+
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client import sync_execute
+
+from products.engineering_analytics.backend.facade.warehouse_views import get_expected_warehouse_views
+from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME
+from products.engineering_analytics.backend.logic.sources import WORKFLOW_JOBS_SCHEMA, WORKFLOW_RUNS_SCHEMA
+from products.engineering_analytics.backend.logic.views import ci_failures, ci_job_history, job_costs
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ WORKFLOW_JOBS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
+
+TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.ci_views"
+GITHUB_SOURCE_PREFIX = "myprefix"
+
+_BASE = "2026-01-01 10:00:00"
+_LATER = "2026-01-01 10:10:00"
+
+
+def _job_row(job_id: int, run_id: int, name: str) -> dict[str, Any]:
+ return {
+ "id": job_id,
+ "run_id": run_id,
+ "run_attempt": 1,
+ "name": name,
+ "workflow_name": "Backend CI",
+ "status": "completed",
+ "conclusion": "failure",
+ "head_sha": f"jobsha{job_id}",
+ "head_branch": "master",
+ "labels": "[]",
+ "runner_name": "runner-x",
+ "runner_group_name": "",
+ "created_at": _BASE,
+ "started_at": _BASE,
+ "completed_at": _LATER,
+ "steps": "[]",
+ }
+
+
+def _run_row(
+ run_id: int, head_sha: str, pull_requests: list[dict], head_commit: dict, run_attempt: int = 1
+) -> dict[str, Any]:
+ return {
+ "id": run_id,
+ "name": "Backend CI",
+ "head_sha": head_sha,
+ "head_branch": "master",
+ "status": "completed",
+ "conclusion": "failure",
+ "created_at": _BASE,
+ "run_started_at": _BASE,
+ "updated_at": _LATER,
+ "run_attempt": run_attempt,
+ "pull_requests": json.dumps(pull_requests),
+ "repository": json.dumps({"full_name": "PostHog/posthog"}),
+ "head_commit": json.dumps(head_commit),
+ }
+
+
+class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
+ """The generated ci_job_history SQL must expose exactly the FIELDS columns and correctly derive
+ commit attribution — the substrate the green/red boundary analysis reads. Skips when object
+ storage is unreachable so the suite still runs without the dev stack."""
+
+ def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
+ df = pd.DataFrame(rows, columns=list(columns.keys()))
+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)
+ df.to_csv(tmp.name, index=False)
+ tmp.close()
+ self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
+ try:
+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
+ csv_path=Path(tmp.name),
+ table_name=base_name,
+ table_columns=columns,
+ test_bucket=TEST_BUCKET,
+ team=self.team,
+ source_prefix=GITHUB_SOURCE_PREFIX,
+ )
+ except PermissionError as err:
+ self.skipTest(f"object storage unavailable: {err}")
+ self.addCleanup(cleanup)
+ return table.name
+
+ def test_exposes_fields_and_derives_commit_attribution(self) -> None:
+ jobs_table = self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(1, run_id=100, name="job-a"),
+ _job_row(2, run_id=200, name="job-b"),
+ # A job whose run row is missing — the LEFT JOIN must keep it with NULL attribution.
+ _job_row(3, run_id=999, name="job-c"),
+ _job_row(4, run_id=300, name="job-d"),
+ # A first-attempt job whose run row was upserted by a re-run (run_attempt 2): the
+ # run_id-only join must still attach the run's attribution.
+ _job_row(5, run_id=400, name="job-e"),
+ ],
+ )
+ runs_table = self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [
+ _run_row(
+ 100,
+ head_sha="runsha100",
+ pull_requests=[{"number": 5}],
+ head_commit={
+ "author": {"name": "Alice", "email": "[email protected]"},
+ "message": "fix(ci): thing (#4242)",
+ },
+ ),
+ # No pull_requests association (a master push): pr_number stays 0, and the only PR
+ # attribution comes from the (#NNNN) squash-merge suffix — here deliberately absent.
+ _run_row(
+ 200,
+ head_sha="runsha200",
+ pull_requests=[],
+ head_commit={"author": {"name": "Bob"}, "message": "chore: no pr suffix"},
+ ),
+ # A revert: the message carries the reverted PR's (#N) inside quotes AND the revert
+ # PR's own suffix — the anchored extraction must attribute the reverting PR.
+ _run_row(
+ 300,
+ head_sha="runsha300",
+ pull_requests=[],
+ head_commit={
+ "author": {"name": "Carol"},
+ "message": 'Revert "feat(ci): thing (#4242)" (#4300)\n\nThis reverts commit abc.',
+ },
+ ),
+ # The runs snapshot keeps only the newest attempt's row per id — this run was re-run,
+ # so its row carries run_attempt 2 while the seeded job above is attempt 1.
+ _run_row(
+ 400,
+ head_sha="runsha400",
+ pull_requests=[],
+ head_commit={"author": {"name": "Dave"}, "message": "fix: rerun me"},
+ run_attempt=2,
+ ),
+ ],
+ )
+
+ query = ci_job_history.build_query(jobs_table=jobs_table, runs_table=runs_table)
+
+ columns = execute_hogql_query(
+ query=f"SELECT * FROM ({query})", team=self.team, query_type="engineering_analytics.test"
+ ).columns
+ assert columns == list(ci_job_history.FIELDS)
+
+ select = ", ".join(ci_job_history.FIELDS)
+ rows = execute_hogql_query(
+ query=f"SELECT {select} FROM ({query}) ORDER BY job_name",
+ team=self.team,
+ query_type="engineering_analytics.test",
+ ).results
+ by_job = {row[list(ci_job_history.FIELDS).index("job_name")]: row for row in rows}
+ field_index = {name: i for i, name in enumerate(ci_job_history.FIELDS)}
+
+ def value(job_name: str, field: str) -> Any:
+ return by_job[job_name][field_index[field]]
+
+ # Run with a PR association + a (#NNNN) merge suffix: both PR keys resolve, commit attribution
+ # comes off head_commit, and head_sha is the run's (not the job's) sha.
+ assert value("job-a", "pr_number") == 5
+ assert value("job-a", "commit_author_name") == "Alice"
+ assert value("job-a", "commit_author_email") == "[email protected]"
+ assert value("job-a", "commit_message") == "fix(ci): thing (#4242)"
+ assert value("job-a", "commit_pr_number") == 4242
+ assert (value("job-a", "repo_owner"), value("job-a", "repo_name")) == ("PostHog", "posthog")
+ assert value("job-a", "head_sha") == "runsha100"
+ # created_at_raw carries the unparsed source string (the scan-pruning floor rides on this),
+ # not the parsed datetime — so it must equal the raw value, distinct from parsed created_at.
+ assert value("job-a", "created_at_raw") == _BASE
+
+ # Master push: pr_number 0 (builder semantics kept, not nulled), no (#NNNN) → commit_pr_number NULL.
+ assert value("job-b", "pr_number") == 0
+ assert value("job-b", "commit_author_name") == "Bob"
+ assert value("job-b", "commit_pr_number") is None
+ assert value("job-b", "commit_message") == "chore: no pr suffix"
+
+ # Revert commit: two (#N) occurrences — the anchored extraction must credit the reverting
+ # PR (#4300), never the reverted one quoted in the title (#4242).
+ assert value("job-d", "commit_pr_number") == 4300
+
+ # Unjoined run: the LEFT JOIN keeps the job attempt (an INNER join would drop it — the guard
+ # here). ClickHouse fills the unmatched run side with type defaults, so attribution is empty
+ # (not a real repo) and no PR resolves off the absent commit message.
+ assert "job-c" in by_job
+ assert value("job-c", "repo_owner") == ""
+ assert value("job-c", "commit_pr_number") is None
+
+ # Re-run: the runs row was upserted to attempt 2 while this job is attempt 1 — the
+ # run_id-only join must still carry the run's attribution (an attempt-equality join blanks it).
+ assert value("job-e", "run_attempt") == 1
+ assert value("job-e", "commit_author_name") == "Dave"
+ assert value("job-e", "head_sha") == "runsha400"
+
+ def test_union_all_of_two_sources_parses_and_stacks(self) -> None:
+ # build_team_view stitches per-source SELECTs with UNION ALL; the columns must line up across
+ # the boundary. Unioning one source's SELECT with itself proves the shape agrees and stacks.
+ jobs_table = self._create_table(
+ "github_workflow_jobs", WORKFLOW_JOBS_COLUMNS, [_job_row(1, run_id=100, name="job-a")]
+ )
+ runs_table = self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [_run_row(100, head_sha="s", pull_requests=[{"number": 1}], head_commit={"message": "m"})],
+ )
+ query = ci_job_history.build_query(jobs_table=jobs_table, runs_table=runs_table)
+ unioned = "\nUNION ALL\n".join([query, query])
+ rows = execute_hogql_query(
+ query=f"SELECT count() FROM ({unioned})", team=self.team, query_type="engineering_analytics.test"
+ ).results
+ assert rows[0][0] == 2
+
+
+class TestCIFailuresView(ClickhouseTestMixin, BaseTest):
+ """The generated ci_failures SQL must fingerprint pytest FAILED lines from the Logs product and
+ ignore everything else — the failure-index substrate."""
+
+ def _insert_logs(self, rows: list[dict[str, Any]]) -> None:
+ payload = "".join(json.dumps({"team_id": self.team.id, **row}) + "\n" for row in rows)
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{payload}")
+
+ def _log(self, body: str, attributes: dict[str, str], minute: int = 0) -> dict[str, Any]:
+ # attributes_map_str keys carry the "__str" suffix the logs table strips for the queryable
+ # `attributes` map (see logs34 mapApply), so a HogQL `attributes['run_id']` reads "run_id__str".
+ return {
+ "timestamp": f"2026-06-23 12:{minute:02d}:00.000000",
+ "body": body,
+ "service_name": CI_LOGS_SERVICE_NAME,
+ "attributes_map_str": {f"{key}__str": value for key, value in attributes.items()},
+ }
+
+ def test_fingerprints_pytest_failures_and_skips_other_lines(self) -> None:
+ attrs = {
+ "run_id": "100",
+ "job_id": "9",
+ "run_attempt": "1",
+ "branch": "master",
+ "head_sha": "abc123",
+ "repo": "PostHog/posthog",
+ "workflow_name": "Backend CI",
+ "job_name": "test (3)",
+ "conclusion": "failure",
+ }
+ self._insert_logs(
+ [
+ # A failure with a trailing detail carrying volatile bits (a count and a hex blob).
+ self._log(
+ "FAILED posthog/api/test_foo.py::TestFoo::test_bar - AssertionError: got 42 at 0xdeadbeefcafe1234",
+ attrs,
+ minute=0,
+ ),
+ # A failure with no " - detail" — its signature is empty, so error_signature is NULL.
+ self._log("FAILED posthog/api/test_baz.py::test_qux", attrs, minute=1),
+ # Not a pytest FAILED line — must be filtered out by the WHERE clause.
+ self._log("PASSED posthog/api/test_ok.py::test_ok", attrs, minute=2),
+ # Contains FAILED but no '::' node id (runner env-dump noise seen in real CI logs) —
+ # must not produce a junk fingerprint.
+ self._log("E2E_TESTS: FAILED [1] (stage: build)", attrs, minute=3),
+ # A parameterized id with a space inside [...] — the extraction must keep the full
+ # node id (not truncate at the space) and normalize only the signature, never the id.
+ self._log("FAILED tests/test_api.py::test_status[user 123] - AssertionError: boom", attrs, minute=4),
+ ]
+ )
+
+ rows = execute_hogql_query(
+ query=ci_failures.build_query(), team=self.team, query_type="engineering_analytics.test"
+ ).results
+ by_test = {row[list(ci_failures.FIELDS).index("test_id")]: row for row in rows}
+ field_index = {name: i for i, name in enumerate(ci_failures.FIELDS)}
+
+ # The PASSED line is excluded; only the real FAILED node ids survive — including the
+ # parameterized one, whose id keeps the space inside [...] untruncated and unnormalized.
+ assert set(by_test) == {
+ "posthog/api/test_foo.py::TestFoo::test_bar",
+ "posthog/api/test_baz.py::test_qux",
+ "tests/test_api.py::test_status[user 123]",
+ }
+ assert by_test["tests/test_api.py::test_status[user 123]"][field_index["error_signature"]] == (
+ "AssertionError: boom"
+ )
+
+ detailed = by_test["posthog/api/test_foo.py::TestFoo::test_bar"]
+
+ def value(field: str) -> Any:
+ return detailed[field_index[field]]
+
+ # Volatile bits (the digit run and the long hex blob) normalize to N so re-runs share a signature.
+ assert value("error_signature") == "AssertionError: got N at NxN"
+ assert value("fingerprint") == "posthog/api/test_foo.py::TestFoo::test_bar | AssertionError: got N at NxN"
+ assert value("run_id") == 100
+ assert value("job_id") == 9
+ assert value("run_attempt") == 1
+ assert value("branch") == "master"
+ assert value("repo") == "PostHog/posthog"
+ assert value("conclusion") == "failure"
+
+ # No trailing detail → empty signature → NULL error_signature, but the fingerprint still forms.
+ no_detail = by_test["posthog/api/test_baz.py::test_qux"]
+ assert no_detail[field_index["error_signature"]] is None
+ assert no_detail[field_index["fingerprint"]] == "posthog/api/test_baz.py::test_qux | "
+
+
+class TestExpectedWarehouseViews(BaseTest):
+ """The facade must expose all three views together for a qualifying GitHub source, and nothing
+ for a team without one — so a consumer sees a coherent set, never a partial one."""
+
+ def _qualifying_source(self) -> ExternalDataSource:
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="gh",
+ connection_id="gh",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=GITHUB_SOURCE_PREFIX,
+ )
+ for schema_name, endpoint in ((WORKFLOW_RUNS_SCHEMA, "workflow_runs"), (WORKFLOW_JOBS_SCHEMA, "workflow_jobs")):
+ table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name=f"{GITHUB_SOURCE_PREFIX}github_{endpoint}",
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ url_pattern="",
+ external_data_source=source,
+ columns={},
+ )
+ ExternalDataSchema.objects.create(
+ team=self.team, source=source, name=schema_name, table=table, should_sync=True
+ )
+ return source
+
+ def test_no_source_exposes_no_views(self) -> None:
+ assert get_expected_warehouse_views(self.team) == []
+
+ def test_qualifying_source_exposes_all_three_views(self) -> None:
+ self._qualifying_source()
+ names = {view.name for view in get_expected_warehouse_views(self.team)}
+ assert names == {job_costs.VIEW_NAME, ci_job_history.VIEW_NAME, ci_failures.VIEW_NAME}
diff --git a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
new file mode 100644
index 000000000000..eabfff6eb39f
--- /dev/null
+++ b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
@@ -0,0 +1,118 @@
+---
+name: investigating-ci-failures
+description: >
+ Investigates a specific CI failure to a verdict: whose fault, which commit, who wrote it, and
+ whether it's fixed. Use for "who broke master", "why did this test fail in CI", "is this failure
+ my PR's fault or everyone's", "is this test flaky or actually broken", "when did this failure
+ start". Works from the engineering_analytics warehouse views (engineering_analytics_ci_failures,
+ engineering_analytics_ci_job_history) plus the CI failure logs. Not for aggregate CI health, cost,
+ or merge bottlenecks (use diagnosing-ci-and-merge-bottlenecks) and not for building saved insights
+ (use turning-engineering-analytics-into-insights).
+---
+
+# Investigating CI failures
+
+The job: take one failing test or one red run and get to a verdict a developer can act on —
+_yours / trunk-borne / flaky_, and when trunk-borne: the culprit SHA, its author, the PR, and
+whether a fix already landed. Everything below is derivation over data that already exists; you
+never need to re-run CI to answer.
+
+Two warehouse views are the substrate (both non-materialized — always current, query them freely):
+
+- **`engineering_analytics_ci_failures`** — one row per pytest `FAILED <nodeid>` line from CI logs,
+ pre-fingerprinted (`fingerprint` = test id + digit/hex-normalized error). Group by `fingerprint`
+ to get first/last seen, occurrence count, and branch spread.
+- **`engineering_analytics_ci_job_history`** — one row per job attempt with `conclusion` AND commit
+ attribution: `head_sha`, `commit_author_name`, `commit_message`, `commit_pr_number` (parsed from
+ the squash-merge suffix — the only PR attribution a master push run has). This is where greens
+ live; the logs are failure-only, so every "when did it turn red / green again" question must come
+ from here, never from the logs.
+
+Copy-ready SQL for every step is in [references/investigation-queries.md](./references/investigation-queries.md).
+
+## The three failure shapes
+
+Fingerprint the failure first (query 1 in the references), then read its shape — the classification
+falls out of three columns:
+
+| Shape | Reading | Next step |
+| --------------------------------------- | ------------------------------- | ---------------------------------------------------- |
+| 1 branch, any window | That PR's own problem | Read its failure lines; done |
+| Many branches, dense burst, hits master | Trunk break (master is/was red) | Boundary query → culprit (below) |
+| Many branches, sporadic over days/weeks | Flaky | Corroborate with `engineering-analytics-flaky-tests` |
+
+Why cross-branch means trunk: PR CI runs the PR **merged with master**, so one bad master commit
+fails every concurrently-running PR. A failure appearing on many unrelated branches in a tight
+window is the signature of a master-merge break, not of those PRs' code. Tell the asker explicitly
+when their PR is not at fault — that is usually the single most valuable sentence in the answer.
+
+## Trunk break → culprit
+
+Run the boundary query (query 2): master-only job history for the failing job, ordered by
+`created_at`. The pattern reads directly:
+
+```text
+... success success | failure failure ... failure | success ...
+ ^ first red = the culprit row ^ first green = the fix row
+```
+
+The culprit row carries everything: `head_sha`, `commit_author_name`, `commit_message` (which names
+what changed), `commit_pr_number`. The first-green row identifies the fix the same way. Confidence
+check before naming anyone: does the culprit commit plausibly touch the failing area (its message /
+PR diff vs the failing test's module)? A boundary landing on an unrelated commit means sharding or
+timing noise — widen the window and check the adjacent commit before asserting.
+
+Then verify the failure window in `ci_failures` matches (first_seen just after the culprit merged,
+last_seen shortly after the fix as the PR queue drained). Mismatch = you're looking at two
+different problems sharing a test.
+
+## Flaky → corroborate, don't guess
+
+Sporadic shape alone is suggestive, not proof. The `engineering-analytics-flaky-tests` MCP tool reads per-test CI spans
+(rerun-pass signal — a test that failed then passed on retry in the same job) and is the stronger
+signal where it has coverage. Counts only, never rates: passing runs below the emitter's duration
+threshold aren't recorded, so there is no honest denominator.
+
+## Caveats you must carry into every answer
+
+- **The logs are failure-only.** No green baseline exists in `ci_failures`; absence of a
+ fingerprint is weak evidence (the job may simply not have run). Greens come from
+ `ci_job_history` only.
+- **Fingerprints are pytest-only (v1).** Jest / playwright / cargo failures appear in the raw
+ failure logs but are not in `ci_failures`. For those, fall back to grouped triage via the
+ `engineering-analytics-master-failures` / `engineering-analytics-ci-failure-logs` MCP tools.
+- **Freshness differs per source.** Logs stream in near-real-time; the warehouse jobs/runs tables
+ arrive via webhook sync and can lag. During a live incident, start from `ci_failures` and check
+ the warehouse's `max(created_at)` before trusting a boundary (query 5). A boundary computed
+ against a stale warehouse names the wrong commit.
+- **A run's `conclusion` can be stale** until the `workflow_run` webhook settles it (SPEC §9) —
+ treat a very recent "failure-free" tail with suspicion.
+- **Retries:** `run_attempt > 1` rows are the same job re-run. A failure that clears on attempt 2
+ is flake signal; one that fails through attempt 5+ is deterministic.
+- **Reverts:** a revert shows up as a _new_ first-green (or first-red) commit whose
+ `commit_pr_number` is the reverting PR — attribution follows the revert, not the original.
+- **Time-bound every logs query.** The failure-log stream is large; unbounded scans hit the read
+ cap. 14 days covers almost every investigation.
+- **Pair the warehouse twin too.** A `ci_job_history` query windowed on `created_at` alone forces a
+ full jobs scan — the parsed timestamp is a computed column the parquet scan can't prune on. Add a
+ coarse `created_at_raw >= '<YYYY-MM-DD>'` string floor (a day below the window) alongside the
+ precise `created_at` bound so the scan skips; `created_at` stays the exact filter.
+
+## Choosing a surface
+
+| Question | Use |
+| -------------------------------------- | ---------------------------------------------------------------------- |
+| "Why did MY PR's CI fail?" | `engineering-analytics-ci-failure-logs` MCP tool (PR-scoped, grouped) |
+| "Who broke master / when did X start?" | The two views, workflow above |
+| "Is X flaky?" | Shape from `ci_failures` + the flaky-tests tool |
+| "What's failing on master right now?" | `engineering-analytics-master-failures` MCP tool (grouped triage feed) |
+| "Is CI slow / expensive / PRs stuck?" | The `diagnosing-ci-and-merge-bottlenecks` skill |
+| "Save this as a dashboard/insight" | The `turning-engineering-analytics-into-insights` skill |
+
+## Output expectations
+
+Lead with the verdict and the exoneration/blame in plain words ("not your PR — master was broken
+between 08:01 and 09:58 UTC by #68727; fixed by #68855"), then the evidence: the boundary rows, the
+fingerprint window, occurrence/branch counts. Name the author factually (they authored the culprit
+commit), never accusatorially — the commit message and PR link let the reader judge the change, and
+half the time the "culprit" was a reasonable change with an unmocked test dependency.
diff --git a/products/engineering_analytics/skills/investigating-ci-failures/references/investigation-queries.md b/products/engineering_analytics/skills/investigating-ci-failures/references/investigation-queries.md
new file mode 100644
index 000000000000..71876f3a009f
--- /dev/null
+++ b/products/engineering_analytics/skills/investigating-ci-failures/references/investigation-queries.md
@@ -0,0 +1,139 @@
+# Investigation queries
+
+Copy-ready HogQL for each step of the investigation workflow. All of these run via `execute-sql`
+(or `posthog:execute-sql` through MCP). The two views are non-materialized — results are always
+current. Adjust windows to the question; 14 days covers almost every investigation.
+
+## 1. Fingerprint a failure (the index query)
+
+Start here whenever the input is a failing test name or an error string. Loose `ILIKE` beats an
+exact match — test ids get truncated and re-sharded in reports.
+
+```sql
+SELECT
+ fingerprint,
+ min(timestamp) AS first_seen,
+ max(timestamp) AS last_seen,
+ count() AS occurrences,
+ uniqExact(branch) AS branches,
+ countIf(branch = 'master') AS master_hits
+FROM engineering_analytics_ci_failures
+WHERE timestamp >= now() - INTERVAL 14 DAY
+ AND test_id ILIKE '%<part of the test name>%' -- or: error_signature ILIKE '%<error text>%'
+GROUP BY fingerprint
+ORDER BY last_seen DESC
+```
+
+Shape reading: `branches = 1` → that branch's own problem. `branches` high + `first_seen`/`last_seen`
+tight + `master_hits > 0` → trunk break. `branches` high + window spanning days/weeks with gaps →
+flaky.
+
+## 2. Boundary query (trunk break → culprit + fix)
+
+Master-only history for the failing job, around the failure window from query 1. The first
+`failure` row after a `success` run is the culprit; the first `success` after the red streak is the
+fix.
+
+```sql
+SELECT
+ substring(head_sha, 1, 11) AS sha,
+ conclusion,
+ created_at,
+ run_attempt,
+ commit_author_name,
+ commit_pr_number,
+ substring(commit_message, 1, 100) AS message
+FROM engineering_analytics_ci_job_history
+WHERE head_branch = 'master'
+ AND job_name = '<failing job name>' -- e.g. 'Product tests (data-warehouse (1/2))'
+ AND created_at >= <first_seen - 2h> AND created_at < <last_seen + 2h>
+ AND created_at_raw >= '<window start date minus 1 day, YYYY-MM-DD>'
+ORDER BY created_at ASC
+```
+
+The `created_at_raw` floor lets the warehouse scan prune — the parsed `created_at` filter alone hits
+a computed column and forces a full jobs scan. It's coarse (a whole-day, string floor a day below the
+window), so keep the precise `created_at` bounds too; the raw floor only shrinks what the scan reads.
+
+Shard suffixes matter: `job_name` includes the `(1/2)` shard. If the test moved shards, run once
+per shard or match with `job_name LIKE 'Product tests (data-warehouse%'`.
+
+## 3. Failure detail for one fingerprint
+
+The actual error lines behind a fingerprint, newest first — for reading the traceback context and
+confirming two occurrences really are the same failure.
+
+```sql
+SELECT timestamp, branch, substring(head_sha, 1, 11) AS sha, run_id, job_name, error_signature
+FROM engineering_analytics_ci_failures
+WHERE timestamp >= now() - INTERVAL 14 DAY
+ AND fingerprint = '<fingerprint from query 1>'
+ORDER BY timestamp DESC
+LIMIT 50
+```
+
+`run_id` links each row to `ci_job_history` (and to the GitHub UI:
+`https://github.com/<owner>/<repo>/actions/runs/<run_id>`).
+
+## 4. What's new on master (novelty scan)
+
+Fingerprints first seen recently that have hit master — the "did anything just break" sweep.
+
+```sql
+SELECT fingerprint, min(timestamp) AS first_seen, count() AS occurrences, uniqExact(branch) AS branches
+FROM engineering_analytics_ci_failures
+WHERE timestamp >= now() - INTERVAL 7 DAY
+GROUP BY fingerprint
+HAVING min(timestamp) >= now() - INTERVAL 1 DAY AND countIf(branch = 'master') > 0
+ORDER BY occurrences DESC
+```
+
+## 5. Warehouse freshness check
+
+Run before trusting a boundary during a live incident — a stale warehouse names the wrong commit.
+Logs stream near-real-time; the jobs table arrives via webhook sync.
+
+```sql
+SELECT max(created_at) AS newest_job_row, now() - max(created_at) AS lag
+FROM engineering_analytics_ci_job_history
+```
+
+If `lag` exceeds ~15 minutes, do the classification from `ci_failures` now and defer the
+culprit-naming boundary query until the warehouse catches up (or corroborate the boundary commit
+against `git log` before naming it).
+
+## 6. Deterministic or retry-passing?
+
+Track the investigated fingerprint itself across retry attempts, not just the job's conclusion — a
+different failure can keep the job red after this fingerprint cleared. Only runs where the
+fingerprint ever appeared are considered.
+
+```sql
+SELECT
+ h.run_id,
+ h.run_attempt,
+ h.conclusion AS job_conclusion,
+ f.run_id != 0 AS fingerprint_present
+FROM engineering_analytics_ci_job_history AS h
+LEFT JOIN (
+ SELECT DISTINCT run_id, run_attempt
+ FROM engineering_analytics_ci_failures
+ WHERE timestamp >= now() - INTERVAL 7 DAY AND fingerprint = '<fingerprint from query 1>'
+) AS f ON h.run_id = f.run_id AND h.run_attempt = f.run_attempt
+WHERE h.job_name = '<failing job name>'
+ AND h.created_at >= now() - INTERVAL 7 DAY
+ AND h.created_at_raw >= '<8 days ago, YYYY-MM-DD>'
+ AND h.run_id IN (
+ SELECT DISTINCT run_id FROM engineering_analytics_ci_failures
+ WHERE timestamp >= now() - INTERVAL 7 DAY AND fingerprint = '<fingerprint from query 1>'
+ )
+ORDER BY h.run_id, h.run_attempt
+```
+
+Reading: `fingerprint_present` dropping on a later attempt while the job goes green = retry-passed
+(flake signal). Fingerprint present through the last attempt = deterministic. Fingerprint absent but
+the job still red = a different failure holds the job red — don't attribute it to this one.
+
+The `created_at_raw` floor lets the warehouse scan prune — the parsed `created_at` filter alone hits
+a computed column and forces a full jobs scan. It's coarse (a whole-day, string floor a day below the
+7-day window), so keep the precise `created_at` bound too.