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_failure_logs endpoint with line traceability (#67033)

Julian Bezfc96cc00b7e7
diff --git a/products/engineering_analytics/AGENTS.md b/products/engineering_analytics/AGENTS.md
new file mode 100644
index 000000000000..3b9eadb16864
--- /dev/null
+++ b/products/engineering_analytics/AGENTS.md
@@ -0,0 +1,12 @@
+# Engineering analytics — read the contract before designing
+
+This is an isolated product with an explicit, locked engineering contract. Before designing or changing
+anything here, read both in full — don't re-derive what's already decided (you'll get it subtly wrong):
+
+
+The decision most often re-derived wrong: **CI ↔ PR linkage is by PR number (the run's `pull_requests`
+association), never head SHA** — a head-SHA join silently drops every push but the latest, because the
+`github_pull_requests` snapshot keeps only the current head. See SPEC §7 (Locked decisions). head SHA is
+a per-commit precision key only; `head_branch` is the capture-time / fork fallback.
diff --git a/products/engineering_analytics/CLAUDE.md b/products/engineering_analytics/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/engineering_analytics/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index ea5f6ca1fdcf..2c61c20717ac 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -143,6 +143,7 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
- `pull_requests` — PR list with head-SHA CI rollup; `date_from` recency window. Capped (newest first) and returned as `{items, truncated, limit}` so the page never silently under-counts against `ci_cards`.
- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`).
- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).
+- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.
**UI:** a read-only scene on the same endpoints via the generated API client — a PR list (CI status, CI duration, age), the count cards (open / stuck >7d / failing CI), and a workflow-health view. Read-only; **no saved views or stateful filters in this phase** (persisted/stateful surfaces are a later, separate decision). Columns that need deferred data — time-in-review, reviewers/approvals, per-check counts, DORA — are out until the event substrate lands (§9).
@@ -176,6 +177,12 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **Provider abstraction deferred.** No `CodeHostProvider` Protocol in v1. GitHub-shaped HogQL lives in the read layer; that boundary is the future Protocol seam — keep canonical types above it, GitHub-isms below.
- **Canonical types live in `facade/contracts.py`** as frozen dataclasses (for the named deep tools). No Django imports, no provider-specific fields.
- **CI granularity = workflow level** (`github_workflow_runs`). Per-check/job breakdown requires a new warehouse endpoint (`github_workflow_jobs`) and is deferred — it is the prerequisite for honest per-PR Depot **cost** (cost is job-level: a run fans into parallel jobs on different runner tiers, so run-level data carries no tier and undercounts). Until it lands, the read layer exposes per-PR **pushes** (distinct head SHAs that triggered CI) and **re-run cycles** (`run_attempt > 1`), attributing runs to a PR via each run's `pull_requests` association — an equality join on PR number, not a head-SHA join (the snapshot is current-state, so a SHA join drops prior pushes). `estimated_cost_usd` is a typed scaffold (always null) until then; the cost model (tier-rate ladder + label→tier parser) lives in `logic/cost.py`.
+- **CI ↔ PR linkage is by PR number (the run's `pull_requests` association), never by head SHA — one rule, every surface.** The curated `ci_rollup` / `runs_by_pr`, `pr_runs` / `pr_cost` / `pr_lifecycle`, and the CI **failure-logs** surface all attribute the same way. Three keys, three roles:
+ - **`pr_number`** — _the attribution key_. Taken from each run's `pull_requests`, keyed on `(repo_owner, repo_name, pr_number)` with `pr_number > 0`. Stable across pushes; a head-SHA join silently drops every push but the latest, because the `github_pull_requests` snapshot retains only the current head — undercounting exactly the multi-push PRs.
+ - **`head_branch`** — _capture-time / pre-PR / fork fallback_. The agent (and the LLM-cost join) can stamp the branch before a PR exists, and fork-originated runs carry a branch even though GitHub leaves their `pull_requests` **empty** (a documented, unresolved security limitation). Branch is reused across PRs over time, so branch-keyed reads must be time-bounded.
+ - **`head_sha`** — _per-commit precision only_, never the attribution key. Always the run/job webhook head SHA (the branch tip = `gh pr view --json headRefOid`); **never** the ephemeral `pull_request` merge SHA (`refs/pull/N/merge`), which is checked out but is not a real commit.
+ - Cardinality: a run ↔ PR is **0..N** (push-only runs and fork PRs have no association; one commit can head several PRs). Treat pr_number attribution as a possibly-empty, possibly-multi set, never a guaranteed single value. v1 credits a run to the **first** PR in its association (see `pr_runs`).
+ - **The Logs surface inherits this.** Emitted CI failure logs carry `attributes['run_id']` (plus `job_id` / `branch` / `conclusion`); `ci_failure_logs` resolves a PR to its run_ids through the same `pull_requests` attribution (reusing `pr_runs`), then filters the Logs product by `run_id` — no head-SHA join, no merge SHA, all pushes captured. Fork PRs (no association) degrade to a run_id / branch lookup.
- **Warehouse columns are strings + Nullable JSON; the builders parse and `ifNull`-guard.** The real GitHub source lands timestamps as strings and the nested objects (`user`/`head`/`base`/`labels`/`repository`/`pull_requests`) as Nullable. Curated builders therefore parse every timestamp with HogQL `parseDateTimeBestEffort` (which maps to ClickHouse `parseDateTime64BestEffortOrNull` — that raw CH name is not exposed in HogQL) and `ifNull`-unwrap any Nullable column before an array function (`JSONExtractArrayRaw` / `splitByChar`), because ClickHouse rejects an Array nested inside a Nullable. `source_schema.py` mirrors these exact types so the seed and tests exercise the real path — violating this contract 500'd every endpoint on real data while idealized-fixture tests stayed green.
- **Bot detection** defined once in the read layer: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time recipes (an explicit column flag + a default filter the skill applies). First-class in any future bot-impact analysis — don't strip them at the substrate.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 99ee5681f9b1..b69e2b02c75a 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -23,6 +23,7 @@ from posthog.models.team import Team
from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
+ CIFailureLogs,
GitHubSource,
PRCostSummary,
PRLifecycle,
@@ -102,6 +103,19 @@ def list_pr_runs(
)
+def get_ci_failure_logs(
+ *,
+ team: Team,
+ pr_number: int,
+ repo: str,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> CIFailureLogs:
+ return logic.build_ci_failure_logs(
+ curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ )
+
+
def list_workflow_runs(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index dd9cdf6fa787..e64813c06356 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -331,6 +331,61 @@ class PRLifecycle:
metric_quality: MetricQuality = MetricQuality.PARTIAL
+@dataclass(frozen=True)
+class CIFailureLogLine:
+ """One line of a job's failure log. ``original_line`` is the line's 1-based position in the full
+ pre-thinning log, or None for a ``... N lines omitted ...`` marker between kept blocks — the gap
+ between consecutive ``original_line`` values is how many lines were elided. The number is the only
+ durable anchor back to the original, which isn't stored and which GitHub expires.
+ """
+
+ original_line: int | None
+ text: str
+
+
+@dataclass(frozen=True)
+class CIJobFailureLog:
+ """One failed CI job's thinned failure log, as ordered lines. The worker fetches logs for failed
+ jobs only, so every job here is a failure. ``lines`` is the thinned failure region (errors plus
+ surrounding context, with omission markers) in order; capped per job, with ``truncated`` set when
+ the job had more.
+ """
+
+ job_id: int
+ run_id: int
+ # Raw job conclusion passthrough ('failure' / 'timed_out' / ...).
+ conclusion: str
+ # Git branch the run was triggered on, or '' when unknown.
+ branch: str
+ # Total lines in the full job log before thinning — the denominator for each line's original_line;
+ # 0 when unknown (a record emitted before orig_total stamping).
+ original_total_lines: int
+ line_count: int
+ lines: list[CIFailureLogLine]
+ truncated: bool
+
+
+@dataclass(frozen=True)
+class CIFailureLogs:
+ """Thinned CI failure logs for one pull request, grouped by failed job.
+
+ Attribution follows the locked rule (SPEC §7): the PR is resolved to its workflow runs via the
+ ``pull_requests`` association (all pushes, never a head-SHA join that would drop earlier ones),
+ then logs are joined by ``run_id``. ``runs_attributed`` is how many runs the PR resolved to;
+ ``logs_available`` is False when no failure-log records were found for those runs — CI hasn't
+ failed, the logs aged out of the short Logs retention, or (fork PRs) the runs carry no PR
+ association to resolve.
+ """
+
+ pr_number: int
+ repo: RepoRef
+ runs_attributed: int
+ logs_available: bool
+ jobs: list[CIJobFailureLog]
+ # True when the overall line cap across all jobs was hit.
+ truncated: bool
+
+
@dataclass(frozen=True)
class CIStatusRollup:
"""A PR's CI, collapsed from the latest workflow run per workflow on its head
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 5ba1078afe09..ed0f2b0c4b77 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -15,6 +15,7 @@ from posthog.utils import relative_date_parse
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
+ CIFailureLogs,
GitHubSource,
PRCostSummary,
PRLifecycle,
@@ -30,6 +31,7 @@ from products.engineering_analytics.backend.logic.quarantine import (
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cards
+from products.engineering_analytics.backend.logic.queries.ci_failure_logs import query_ci_failure_logs
from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_cost, query_workflow_runner_costs
from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle
from products.engineering_analytics.backend.logic.queries.pr_runs import query_pr_runs
@@ -73,6 +75,13 @@ def build_pr_runs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | N
return query_pr_runs(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+def build_ci_failure_logs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> CIFailureLogs:
+ owner, name = _split_repo(repo)
+ if not (owner and name):
+ raise ValueError("repo must be in 'owner/name' format")
+ return query_ci_failure_logs(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+
+
def build_pr_cost(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> PRCostSummary:
owner, name = _split_repo(repo)
if not (owner and name):
diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.py
index 4b4bf11bd041..48063538a035 100644
--- a/products/engineering_analytics/backend/logic/job_logs/activity.py
+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py
@@ -24,7 +24,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter
from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_job_log
-from products.engineering_analytics.backend.logic.job_logs.thinning import thin_log
+from products.engineering_analytics.backend.logic.job_logs.thinning import thin_log_lines
logger = structlog.get_logger(__name__)
@@ -76,6 +76,8 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str
"repo": inputs.repo,
"branch": inputs.branch or "",
"conclusion": inputs.conclusion or "",
+ # Total lines in the full log before thinning — the denominator for each line's orig_line.
+ "orig_total": len(archive.splitlines()),
}
# CI failure logs are team-level operational data: they ride the owning team's project Logs
@@ -83,7 +85,7 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str
# source's resource-level access control. Don't emit anything a logs:read holder shouldn't see.
def _thin_and_emit() -> int:
# Failures-only today; pass a different ThinningConfig once all-jobs ingestion lands.
- thinned = thin_log(archive)
+ thinned = thin_log_lines(archive)
with JobLogsEmitter(endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT, token=log_ingest_token) as emitter:
# run_id→trace, job_id→span so the Logs UI can group a whole run and isolate one job.
return emitter.emit_log_archive(
diff --git a/products/engineering_analytics/backend/logic/job_logs/constants.py b/products/engineering_analytics/backend/logic/job_logs/constants.py
new file mode 100644
index 000000000000..93a859f36cff
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/job_logs/constants.py
@@ -0,0 +1,7 @@
+# Shared between the emit and read sides of the CI job-logs feature.
+
+# The OTel ``service.name`` the worker emits CI failure logs under, and the value the failure-logs
+# read query (`ci_failure_logs`) filters on. Kept here — not imported across the two sides — so a
+# rename can't silently desync them: a mismatch returns no logs (`logs_available: false`) for every
+# PR, with no error. Defined in a dependency-free module so the read path doesn't pull the OTel SDK.
+CI_LOGS_SERVICE_NAME = "github-ci-logs"
diff --git a/products/engineering_analytics/backend/logic/job_logs/emitter.py b/products/engineering_analytics/backend/logic/job_logs/emitter.py
index fdea901b6827..ddce0d1e54fd 100644
--- a/products/engineering_analytics/backend/logic/job_logs/emitter.py
+++ b/products/engineering_analytics/backend/logic/job_logs/emitter.py
@@ -22,14 +22,14 @@ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.trace import TraceFlags
-logger = structlog.get_logger(__name__)
+from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME as _SERVICE_NAME
+from products.engineering_analytics.backend.logic.job_logs.thinning import ThinnedLine
-_SERVICE_NAME = "github-ci-logs"
+logger = structlog.get_logger(__name__)
# GitHub prefixes every raw log line with an RFC3339 UTC timestamp, then the content:
# 2026-06-25T09:14:02.1234567Z ##[error]Process completed with exit code 1
_LINE = re.compile(r"^(?P<ts>\d{4}-\d{2}-\d{2}T[0-9:.]+Z)\s?(?P<body>.*)$")
-_SCALAR = (str, int, float, bool)
def _parse_ns(ts: str) -> int | None:
@@ -89,29 +89,43 @@ class JobLogsEmitter:
def emit_log_archive(
self,
- archive_text: str,
+ lines: list[ThinnedLine],
*,
attributes: Mapping[str, object],
trace_id: str | int | None = 0,
span_id: str | int | None = 0,
) -> int:
- """Emit one Logs record per non-empty line. Returns the number of records emitted.
+ """Emit one Logs record per non-empty thinned line. Returns the number of records emitted.
``trace_id``/``span_id`` map the GitHub run/job onto OTLP trace/span so the Logs UI can group
a whole workflow run (trace) and isolate one job (span); unmappable ids fall back to 0
(unset). They MUST be set: the encoder treats 0 as unset and calls ``int(trace_flags)``, so
the SDK's None default would crash serialization of the whole batch and nothing would land.
+
+ Each record carries ``seq`` (its 0-based position in the emitted output) and, for a kept line,
+ ``orig_line`` (its 1-based line in the full pre-thinning log). ``seq`` is the read-side sort
+ key — omission markers carry no timestamp, so timestamp can't order them; ``orig_line`` is the
+ durable anchor back to the original (which isn't stored and expires).
"""
if not self._enabled:
return 0
- attrs = {key: value for key, value in attributes.items() if isinstance(value, _SCALAR)}
+ # Stringify every attribute value: the logs pipeline only indexes string-typed attributes into
+ # the queryable map (logs34 stores them via JSONExtractString), so a numeric attribute would be
+ # invisible to `attributes['...']` reads — and the failure-logs endpoint filters on exactly
+ # these (run_id / job_id / seq / orig_line / orig_total).
+ base_attrs: dict[str, str] = {
+ key: str(value) for key, value in attributes.items() if isinstance(value, (str, int, float, bool))
+ }
trace, span = _otel_id(trace_id, 16), _otel_id(span_id, 8)
emitted = 0
- for raw in archive_text.splitlines():
- match = _LINE.match(raw)
- body, timestamp = (match.group("body"), _parse_ns(match.group("ts"))) if match else (raw, None)
+ for line in lines:
+ match = _LINE.match(line.text)
+ body, timestamp = (match.group("body"), _parse_ns(match.group("ts"))) if match else (line.text, None)
if not body.strip():
continue
+ attrs: dict[str, str] = {**base_attrs, "seq": str(emitted)}
+ if line.original_line_number is not None:
+ attrs["orig_line"] = str(line.original_line_number)
severity_text, severity_number = _severity(body)
self._logger.emit(
LogRecord(
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py
index dcf186adf3cf..c39595f33073 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py
@@ -23,9 +23,9 @@ class _FakeEmitter:
def __exit__(self, *_args):
return None
- def emit_log_archive(self, archive, **_kwargs):
- self.archive = archive
- return len(archive.splitlines())
+ def emit_log_archive(self, lines, **_kwargs):
+ self.lines = lines
+ return len(lines)
def _patch(monkeypatch, *, acquired=True, archive="l1\nl2\nl3"):
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py b/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py
index 33c6f0930a6e..866764b21be3 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py
@@ -5,22 +5,35 @@ from opentelemetry.sdk._logs.export import InMemoryLogExporter
from parameterized import parameterized
from products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter
+from products.engineering_analytics.backend.logic.job_logs.thinning import ThinnedLine
_ATTRS = {"job_id": 42, "run_id": 7, "branch": "main", "conclusion": "failure"}
-def _emit(archive: str, attributes=_ATTRS):
+def _lines(archive: str) -> list[ThinnedLine]:
+ # An un-thinned archive: every line kept, numbered 1..N (the small-log passthrough shape).
+ return [ThinnedLine(text, index + 1) for index, text in enumerate(archive.splitlines())]
+
+
+def _emit_lines(lines: list[ThinnedLine], attributes=_ATTRS):
exporter = InMemoryLogExporter()
with JobLogsEmitter(exporter=exporter) as emitter:
- emitted = emitter.emit_log_archive(archive, attributes=attributes)
+ emitted = emitter.emit_log_archive(lines, attributes=attributes)
return emitted, [d.log_record for d in exporter.get_finished_logs()]
+def _emit(archive: str, attributes=_ATTRS):
+ return _emit_lines(_lines(archive), attributes)
+
+
def _encode_one(*, trace_id, span_id):
exporter = InMemoryLogExporter()
with JobLogsEmitter(exporter=exporter) as emitter:
emitter.emit_log_archive(
- "2026-06-25T09:14:02.000000Z ##[error]boom", attributes=_ATTRS, trace_id=trace_id, span_id=span_id
+ [ThinnedLine("2026-06-25T09:14:02.000000Z ##[error]boom", 1)],
+ attributes=_ATTRS,
+ trace_id=trace_id,
+ span_id=span_id,
)
encoded = encode_logs(exporter.get_finished_logs()) # must not raise
return encoded.resource_logs[0].scope_logs[0].log_records[0]
@@ -70,11 +83,33 @@ def test_emits_per_line_with_parsed_timestamp_severity_and_attributes():
"##[error]Process completed with exit code 1",
]
assert [r.severity_text for r in records] == ["INFO", "WARN", "ERROR"]
- assert all(dict(r.attributes) == _ATTRS for r in records)
+ # Attributes are stringified — the logs pipeline only indexes string-typed values into the
+ # queryable map, so an int attribute would be unreadable by `attributes['...']`.
+ assert all(all(record.attributes[key] == str(value) for key, value in _ATTRS.items()) for record in records)
expected_ns = int(datetime(2026, 6, 25, 9, 14, 2, 123456, tzinfo=UTC).timestamp() * 1_000_000_000)
assert records[0].timestamp == expected_ns
+def test_stamps_seq_and_orig_line_so_thinned_lines_stay_anchored_and_ordered():
+ # The thinned log drops most lines, so each kept line carries its original 1-based position
+ # (orig_line) — the only durable anchor once the full log expires — and every record carries seq
+ # (emit order) so the reader can order them. Omission markers (no original line) carry seq but no
+ # orig_line. Values are stringified so they land in the queryable string attribute map (a numeric
+ # attribute is dropped from it). Without this the failure region is contiguous and unlocatable.
+ _, records = _emit_lines(
+ [
+ ThinnedLine("2026-06-25T09:14:02.000000Z first", 1),
+ ThinnedLine("... 4810 lines omitted ...", None),
+ ThinnedLine("2026-06-25T09:14:50.000000Z ##[error]boom", 4812),
+ ]
+ )
+ assert [r.body for r in records] == ["first", "... 4810 lines omitted ...", "##[error]boom"]
+ assert [r.attributes["seq"] for r in records] == ["0", "1", "2"]
+ assert records[0].attributes["orig_line"] == "1"
+ assert "orig_line" not in records[1].attributes # a marker has no original line
+ assert records[2].attributes["orig_line"] == "4812"
+
+
def test_skips_blank_lines():
# Blank/whitespace-only lines must not become empty Logs records (noise in the corpus).
emitted, records = _emit("2026-06-25T09:14:02.000000Z real line\n\n \n")
@@ -86,17 +121,18 @@ def test_drops_non_scalar_attributes():
# OTEL attributes accept scalars only; a Mapping-valued attribute must be dropped, not crash
# or serialize garbage, while scalar attributes survive.
_, records = _emit("2026-06-25T09:14:02.000000Z x", attributes={"job_id": 1, "nested": {"a": 1}})
- assert dict(records[0].attributes) == {"job_id": 1}
+ assert records[0].attributes["job_id"] == "1"
+ assert "nested" not in records[0].attributes
def test_noop_when_unconfigured():
# With no exporter, endpoint, or token, the emitter must be a safe no-op (return 0, no crash)
# so the worker is harmless until the Logs lane is wired in.
- assert JobLogsEmitter().emit_log_archive("2026-06-25T09:14:02.000000Z x", attributes=_ATTRS) == 0
+ assert JobLogsEmitter().emit_log_archive(_lines("2026-06-25T09:14:02.000000Z x"), attributes=_ATTRS) == 0
def test_noop_when_token_missing():
# Endpoint set but no token must also no-op — we never emit unauthenticated (it would 401 and
# the records would be lost), and a half-configured lane shouldn't crash the worker.
emitter = JobLogsEmitter(endpoint="http://localhost:8010/i/v1/logs", token=None)
- assert emitter.emit_log_archive("2026-06-25T09:14:02.000000Z x", attributes=_ATTRS) == 0
+ assert emitter.emit_log_archive(_lines("2026-06-25T09:14:02.000000Z x"), attributes=_ATTRS) == 0
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
index 46aa3d436880..077c06d705d9 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
@@ -1,6 +1,6 @@
from parameterized import parameterized
-from products.engineering_analytics.backend.logic.job_logs.thinning import ThinningConfig, thin_log
+from products.engineering_analytics.backend.logic.job_logs.thinning import ThinningConfig, thin_log, thin_log_lines
_CAP = ThinningConfig().max_lines
@@ -46,3 +46,22 @@ class TestThinLog:
content = [line for line in out.splitlines() if "lines omitted" not in line]
assert len(content) <= _CAP
+
+ def test_thin_log_lines_anchors_kept_lines_to_original_positions(self):
+ # Each kept line keeps its 1-based original position (the only durable anchor once the full
+ # log expires); omission markers carry None. A regression here makes a thinned line
+ # unlocatable in the real log.
+ noise = [f"downloading package {i}" for i in range(2000)]
+ lines = thin_log_lines("\n".join([*noise, "##[error]Process completed with exit code 1."]))
+
+ last = lines[-1]
+ assert last.text == "##[error]Process completed with exit code 1."
+ assert last.original_line_number == 2001 # 2000 noise lines (1..2000), then the failure at 2001
+ assert any(line.original_line_number is None and "lines omitted" in line.text for line in lines)
+
+ def test_thin_log_lines_numbers_every_line_when_under_cap(self):
+ assert [(line.text, line.original_line_number) for line in thin_log_lines("a\nb\nc")] == [
+ ("a", 1),
+ ("b", 2),
+ ("c", 3),
+ ]
diff --git a/products/engineering_analytics/backend/logic/job_logs/thinning.py b/products/engineering_analytics/backend/logic/job_logs/thinning.py
index 0253d48b4c27..a77b1dc0eefe 100644
--- a/products/engineering_analytics/backend/logic/job_logs/thinning.py
+++ b/products/engineering_analytics/backend/logic/job_logs/thinning.py
@@ -46,20 +46,32 @@ class ThinningConfig:
FAILURE_THINNING = ThinningConfig()
[email protected](frozen=True)
+class ThinnedLine:
+ """One line of a thinned log. ``original_line_number`` is the line's 1-based position in the full
+ pre-thinning log; None for a synthetic ``... N lines omitted ...`` marker. The number is the only
+ durable anchor back to the original — the full log isn't stored and GitHub expires it.
+ """
+
+ text: str
+ original_line_number: int | None
+
+
def _matches_marker(line: str, markers: tuple[str, ...]) -> bool:
return any(marker in line for marker in markers)
-def thin_log(text: str, config: ThinningConfig = FAILURE_THINNING) -> str:
- """Return the failure-relevant slice of ``text`` with omitted gaps marked. Pure; no I/O.
+def thin_log_lines(text: str, config: ThinningConfig = FAILURE_THINNING) -> list[ThinnedLine]:
+ """Return the failure-relevant slice of ``text`` as lines, each tagged with its 1-based position in
+ the full log (None for an omission marker). Pure; no I/O.
- Logs at or under ``config.max_lines`` are returned unchanged — thinning only kicks in once a log
- is large enough to be worth trimming, so small failures keep full fidelity.
+ Logs at or under ``config.max_lines`` pass through untouched (every line kept, numbered) so small
+ failures keep full fidelity; larger logs collapse the noise to ``... N lines omitted ...`` markers.
"""
lines = text.splitlines()
total = len(lines)
if total <= config.max_lines:
- return text
+ return [ThinnedLine(line, index + 1) for index, line in enumerate(lines)]
keep: set[int] = set()
for index, line in enumerate(lines):
@@ -74,13 +86,18 @@ def thin_log(text: str, config: ThinningConfig = FAILURE_THINNING) -> str:
# Bias to the end: the final summary matters more than the first of many failures.
selected = selected[-config.max_lines :]
- out: list[str] = []
+ out: list[ThinnedLine] = []
if selected and selected[0] > 0:
- out.append(f"... {selected[0]} lines omitted ...")
+ out.append(ThinnedLine(f"... {selected[0]} lines omitted ...", None))
previous: int | None = None
for index in selected:
if previous is not None and index > previous + 1:
- out.append(f"... {index - previous - 1} lines omitted ...")
- out.append(lines[index])
+ out.append(ThinnedLine(f"... {index - previous - 1} lines omitted ...", None))
+ out.append(ThinnedLine(lines[index], index + 1))
previous = index
- return "\n".join(out)
+ return out
+
+
+def thin_log(text: str, config: ThinningConfig = FAILURE_THINNING) -> str:
+ """Text rendering of :func:`thin_log_lines` — kept lines joined, omission markers inline."""
+ return "\n".join(line.text for line in thin_log_lines(text, config))
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index a33e6910e24d..7a60d1edda3d 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -22,6 +22,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.clickhouse.workload import Workload
from posthog.models.team import Team
from products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tables
@@ -167,6 +168,7 @@ class CuratedGitHubSource:
*,
query_type: str,
placeholders: dict[str, ast.Expr] | None = None,
+ workload: Workload = Workload.DEFAULT,
) -> HogQLQueryResponse:
"""Parse + execute a curated HogQL query for this team.
@@ -179,6 +181,10 @@ class CuratedGitHubSource:
for system / Temporal / CLI contexts; that build has no user to honor the ACL with and would fail
closed (strip every warehouse table), so those reads bypass it — the warehouse team's sanctioned
escape hatch for userless callers.
+
+ ``workload`` routes the read to a non-default ClickHouse cluster (e.g. ``Workload.LOGS`` for the
+ ``logs`` table). The warehouse-ACL reasoning above governs warehouse tables only and is a no-op
+ for such reads — those tables carry no per-table ACL, so the ``team_id`` scope is their boundary.
"""
uac = self._user_access_control
with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=self._team.pk):
@@ -186,6 +192,9 @@ class CuratedGitHubSource:
query=parse_select(sql, placeholders=placeholders),
team=self._team,
query_type=query_type,
+ # The logs table lives on a separate ClickHouse cluster (Workload.LOGS); warehouse
+ # reads use the default. Callers pass the workload that matches the tables they query.
+ workload=workload,
# Forward the real user, not just the access control: a userless build drops the access
# control and fails closed (see _compute_system_table_access_decision), so the user is what
# lets HogQL honor the per-table warehouse ACL.
diff --git a/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py b/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py
new file mode 100644
index 000000000000..173301777057
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py
@@ -0,0 +1,134 @@
+"""HogQL assembly of a pull request's CI failure logs from the Logs product.
+
+The CI job-logs worker emits one Logs record per failure-line, tagged with the GitHub ``run_id`` /
+``job_id`` (service ``github-ci-logs``). This resolves a PR to its workflow runs via the same
+``pull_requests`` attribution as ``pr_runs`` (SPEC §7 — never a head-SHA join, so every push is
+captured), then reads the Logs product joined on ``run_id`` and groups the lines per failed job.
+
+Two caps bound the response: ``_PER_JOB_CAP`` lines per job, and ``_LINE_CAP`` lines overall. Rows
+come back newest-run-first, so when the overall cap bites it drops the *oldest* runs (the newest push
+— what a caller usually wants — is returned whole) and the tail job it clips is flagged ``truncated``.
+
+Reads the ``logs`` table, not the warehouse — the failure logs live in the Logs product.
+"""
+
+import dataclasses
+from itertools import groupby
+
+from posthog.hogql import ast
+
+from posthog.clickhouse.workload import Workload
+
+from products.engineering_analytics.backend.facade.contracts import (
+ CIFailureLogLine,
+ CIFailureLogs,
+ CIJobFailureLog,
+ RepoRef,
+)
+from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME as _SERVICE_NAME
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.pr_runs import query_pr_runs
+
+# Overall safety bound on lines pulled per call (one Logs record == one line) — an incident across
+# many runs mustn't return an unbounded body.
+_LINE_CAP = 2000
+# Per-job line cap so one job can't crowd the others out of the overall cap.
+_PER_JOB_CAP = 300
+
+# Newest run first (so the overall LIMIT drops the oldest runs, not the latest push), then job, then
+# seq — the emitter's 0-based emit order, since omission markers carry no timestamp to order by.
+# run_id / job_id / orig_total / orig_line are string map values; one record is one line.
+_SELECT = """
+ SELECT
+ attributes['run_id'] AS run_id,
+ attributes['job_id'] AS job_id,
+ attributes['conclusion'] AS conclusion,
+ attributes['branch'] AS branch,
+ attributes['orig_total'] AS orig_total,
+ attributes['orig_line'] AS orig_line,
+ body
+ FROM logs
+ WHERE service_name = {service_name} AND attributes['run_id'] IN {run_ids}
+ ORDER BY toInt(attributes['run_id']) DESC, toInt(attributes['job_id']), toInt(attributes['seq'])
+ LIMIT {line_cap}
+"""
+
+
+def _to_int(value: str | None) -> int:
+ try:
+ return int(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return 0
+
+
+def _group_jobs(rows: list[tuple]) -> list[CIJobFailureLog]:
+ # Rows arrive grouped by (run_id, job_id) and ordered by seq within a job, so consecutive rows of a
+ # job are contiguous and in order — group them, cap the lines, and carry the per-job conclusion /
+ # branch / orig_total (same on every line of a job) from the first row.
+ jobs: list[CIJobFailureLog] = []
+ for (run_id, job_id), group in groupby(rows, key=lambda row: (row[0], row[1])):
+ group_rows = list(group)
+ first = group_rows[0]
+ # orig_line is absent ('' from the map) on omission markers, and a real line is 1-based, so
+ # `or None` maps the empty/zero case to "no original line".
+ lines = [CIFailureLogLine(original_line=_to_int(row[5]) or None, text=row[6]) for row in group_rows]
+ capped = lines[:_PER_JOB_CAP]
+ jobs.append(
+ CIJobFailureLog(
+ job_id=_to_int(job_id),
+ run_id=_to_int(run_id),
+ conclusion=first[2] or "",
+ branch=first[3] or "",
+ original_total_lines=_to_int(first[4]),
+ line_count=len(capped),
+ lines=capped,
+ truncated=len(lines) > _PER_JOB_CAP,
+ )
+ )
+ return jobs
+
+
+def query_ci_failure_logs(
+ *,
+ curated: CuratedGitHubSource,
+ pr_number: int,
+ repo_owner: str,
+ repo_name: str,
+) -> CIFailureLogs:
+ repo = RepoRef(provider="github", owner=repo_owner, name=repo_name)
+ runs = query_pr_runs(curated=curated, pr_number=pr_number, repo_owner=repo_owner, repo_name=repo_name)
+ run_ids = [run.id for run in runs]
+ if not run_ids:
+ # No runs attributed (CI hasn't run, or a fork PR with no association) — nothing to join on.
+ return CIFailureLogs(
+ pr_number=pr_number, repo=repo, runs_attributed=0, logs_available=False, jobs=[], truncated=False
+ )
+
+ response = curated.run(
+ _SELECT,
+ query_type="engineering_analytics.ci_failure_logs",
+ placeholders={
+ "service_name": ast.Constant(value=_SERVICE_NAME),
+ "run_ids": ast.Constant(value=[str(run_id) for run_id in run_ids]),
+ # +1 so a full page tells us the overall cap was hit (more lines exist than returned).
+ "line_cap": ast.Constant(value=_LINE_CAP + 1),
+ },
+ # The logs table lives on the LOGS ClickHouse cluster, not the warehouse default.
+ workload=Workload.LOGS,
+ )
+ rows = response.results or []
+ overall_truncated = len(rows) > _LINE_CAP
+ jobs = _group_jobs(rows[:_LINE_CAP])
+ if overall_truncated and jobs:
+ # The overall cap clips the tail of the oldest run still in range (rows are newest-run-first),
+ # so that last job's lines are an undercount, not a complete log — flag it rather than let its
+ # per-job `truncated` read False and pass as whole.
+ jobs[-1] = dataclasses.replace(jobs[-1], truncated=True)
+ return CIFailureLogs(
+ pr_number=pr_number,
+ repo=repo,
+ runs_attributed=len(run_ids),
+ logs_available=bool(rows),
+ jobs=jobs,
+ truncated=overall_truncated,
+ )
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 187b34b806d2..800781071d28 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -12,6 +12,9 @@ from rest_framework_dataclasses.serializers import DataclassSerializer
from products.engineering_analytics.backend.facade.contracts import (
Author,
CICardSummary,
+ CIFailureLogLine,
+ CIFailureLogs,
+ CIJobFailureLog,
CIStatusRollup,
GitHubSource,
PRCostSummary,
@@ -114,6 +117,63 @@ class PRLifecycleSerializer(DataclassSerializer):
}
+class CIFailureLogLineSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = CIFailureLogLine
+ extra_kwargs = {
+ "original_line": {
+ "help_text": "1-based line number in the full pre-thinning job log, or null for a "
+ "'... N lines omitted ...' marker. The gap between consecutive values is how many lines were elided.",
+ "allow_null": True,
+ },
+ "text": {"help_text": "The log line text, or the omission-marker text."},
+ }
+
+
+class CIJobFailureLogSerializer(DataclassSerializer):
+ lines = CIFailureLogLineSerializer(
+ many=True, help_text="The thinned failure-log lines in original order, with omission markers."
+ )
+
+ class Meta:
+ dataclass = CIJobFailureLog
+ extra_kwargs = {
+ "job_id": {"help_text": "GitHub Actions job id of the failed job."},
+ "run_id": {"help_text": "Workflow run id the job belongs to."},
+ "conclusion": {
+ "help_text": "Job conclusion ('failure', 'timed_out', ...). Only failed jobs have logs.",
+ },
+ "branch": {"help_text": "Git branch the run was triggered on, or '' when unknown."},
+ "original_total_lines": {
+ "help_text": "Total lines in the full job log before thinning (the denominator for each line's "
+ "original_line); 0 when unknown.",
+ },
+ "line_count": {"help_text": "Number of lines returned for this job (after the per-job cap)."},
+ "truncated": {"help_text": "True when the job had more failure lines than the per-job cap."},
+ }
+
+
+class CIFailureLogsSerializer(DataclassSerializer):
+ repo = RepoRefSerializer(help_text="Repository the pull request belongs to.")
+ jobs = CIJobFailureLogSerializer(
+ many=True, help_text="Failed CI jobs with their thinned failure logs, grouped by job."
+ )
+
+ class Meta:
+ dataclass = CIFailureLogs
+ extra_kwargs = {
+ "pr_number": {"help_text": "Pull request number the failure logs are for."},
+ "runs_attributed": {
+ "help_text": "Workflow runs attributed to the PR (across all its pushes) that were searched for logs.",
+ },
+ "logs_available": {
+ "help_text": "False when no failure logs were found — CI hasn't failed, the logs aged out of the "
+ "short Logs retention, or a fork PR carries no run association to resolve.",
+ },
+ "truncated": {"help_text": "True when the overall line cap across all jobs was hit."},
+ }
+
+
class WorkflowRunDetailSerializer(DataclassSerializer):
repo = RepoRefSerializer(help_text="Repository the run belongs to.")
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index abdbd70d06d4..ef5029c8081b 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -29,6 +29,7 @@ from products.engineering_analytics.backend.facade.contracts import (
)
from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
+ CIFailureLogsSerializer,
GitHubSourceSerializer,
PRCostSummarySerializer,
PRLifecycleSerializer,
@@ -128,6 +129,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"pr_lifecycle",
"quarantine",
"pr_runs",
+ "ci_failure_logs",
"pr_cost",
"workflow_run",
"workflow_runs",
@@ -352,6 +354,57 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return _bad_request(exc, fallback="Invalid repo or source_id")
return Response(WorkflowRunDetailSerializer(instance=runs, many=True).data)
+ @extend_schema(
+ operation_id="engineering_analytics_ci_failure_logs",
+ parameters=[
+ OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Pull request number whose CI failure logs to fetch.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: CIFailureLogsSerializer,
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
+ },
+ description=(
+ "The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to "
+ "its workflow runs via the pull_requests association (all of the PR's pushes, not just the "
+ "latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the "
+ "worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs "
+ "aged out of the short Logs retention, or a fork PR has no run association. Each line carries "
+ "its original 1-based line number in the full pre-thinning log; lines are the failure region "
+ "(errors plus surrounding context, with omission markers), capped per job and overall."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def ci_failure_logs(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
+ try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
+ result = api.get_ci_failure_logs(
+ team=self.team,
+ pr_number=pr_number,
+ repo=repo,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(CIFailureLogsSerializer(instance=result).data)
+
@extend_schema(
operation_id="engineering_analytics_pr_cost",
parameters=[
diff --git a/products/engineering_analytics/backend/tests/test_ci_failure_logs.py b/products/engineering_analytics/backend/tests/test_ci_failure_logs.py
new file mode 100644
index 000000000000..38754d7a4278
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_ci_failure_logs.py
@@ -0,0 +1,96 @@
+from types import SimpleNamespace
+
+from unittest import mock
+
+from products.engineering_analytics.backend.facade.contracts import RepoRef, WorkflowRunDetail
+from products.engineering_analytics.backend.logic.queries import ci_failure_logs as module
+
+
+def _run(run_id: int) -> WorkflowRunDetail:
+ return WorkflowRunDetail(
+ repo=RepoRef(provider="github", owner="o", name="r"),
+ id=run_id,
+ workflow_name="CI",
+ head_sha="sha",
+ head_branch="main",
+ status="completed",
+ conclusion="failure",
+ run_started_at=None,
+ updated_at=None,
+ duration_seconds=None,
+ run_attempt=1,
+ pr_number=5,
+ )
+
+
+# Rows mimic the logs query output, ordered by (run_id, job_id, seq):
+# (run_id, job_id, conclusion, branch, orig_total, orig_line, body)
+def _query(rows, runs):
+ curated = mock.Mock()
+ curated.run.return_value = SimpleNamespace(results=rows)
+ with mock.patch.object(module, "query_pr_runs", return_value=runs):
+ return module.query_ci_failure_logs(curated=curated, pr_number=5, repo_owner="o", repo_name="r"), curated
+
+
+def test_groups_by_job_and_anchors_each_line_to_its_original_position():
+ # The whole point of the endpoint: failures grouped per job, each line keeping its 1-based original
+ # line number (markers → None), so an agent can locate the failure in the full log. A regression in
+ # grouping, the orig_line/orig_total mapping, or the marker handling would surface here.
+ rows = [
+ ("100", "9", "failure", "main", "5000", "1", "first"),
+ ("100", "9", "failure", "main", "5000", "", "... 4810 lines omitted ..."),
+ ("100", "9", "failure", "main", "5000", "4812", "##[error]boom"),
+ ("100", "10", "timed_out", "main", "200", "7", "slow step"),
+ ]
+ result, _ = _query(rows, [_run(100)])
+
+ assert result.runs_attributed == 1
+ assert result.logs_available is True
+ assert [job.job_id for job in result.jobs] == [9, 10]
+
+ job9 = result.jobs[0]
+ assert (job9.conclusion, job9.original_total_lines) == ("failure", 5000)
+ assert [(line.original_line, line.text) for line in job9.lines] == [
+ (1, "first"),
+ (None, "... 4810 lines omitted ..."),
+ (4812, "##[error]boom"),
+ ]
+ assert result.jobs[1].conclusion == "timed_out"
+
+
+def test_no_attributed_runs_short_circuits_without_querying_logs():
+ # A fork PR (no pull_requests association) or a PR with no CI resolves to zero runs — return
+ # unavailable and never touch the logs cluster, rather than running an empty IN () query.
+ result, curated = _query(rows=[], runs=[])
+ assert (result.runs_attributed, result.logs_available, result.jobs) == (0, False, [])
+ curated.run.assert_not_called()
+
+
+def test_per_job_lines_are_capped(monkeypatch):
+ # One noisy job must not blow the per-job cap; the excess is dropped and truncated flags it.
+ monkeypatch.setattr(module, "_PER_JOB_CAP", 2)
+ rows = [("100", "9", "failure", "main", "9", str(i + 1), f"line{i}") for i in range(5)]
+ result, _ = _query(rows, [_run(100)])
+
+ job = result.jobs[0]
+ assert job.line_count == 2
+ assert len(job.lines) == 2
+ assert job.truncated is True
+
+
+def test_overall_cap_flags_the_clipped_tail_job(monkeypatch):
+ # When the overall cap clips mid-job, that tail job's lines are an undercount, not a complete log —
+ # it must read truncated so a consumer isn't misled into thinking it has the whole failure.
+ monkeypatch.setattr(module, "_LINE_CAP", 3)
+ rows = [
+ ("200", "9", "failure", "main", "10", "1", "a1"),
+ ("200", "9", "failure", "main", "10", "2", "a2"),
+ ("100", "8", "failure", "main", "10", "1", "b1"), # only line of job 8 that survives the cap
+ ("100", "8", "failure", "main", "10", "2", "b2"), # dropped by the overall cap
+ ]
+ result, _ = _query(rows, [_run(200), _run(100)])
+
+ assert result.truncated is True
+ assert [job.job_id for job in result.jobs] == [9, 8]
+ assert result.jobs[0].truncated is False # job 9 is whole, within the cap
+ assert result.jobs[-1].truncated is True # job 8 was clipped by the overall cap
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index b60d7691f644..4aec8240f596 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -18,6 +18,59 @@ export interface CICardSummaryApi {
failing_ci: number
}
+export interface RepoRefApi {
+ /** Code host provider, e.g. 'github'. */
+ provider: string
+ /** Repository owner or organization. */
+ owner: string
+ /** Repository name. */
+ name: string
+}
+
+export interface CIFailureLogLineApi {
+ /**
+ * 1-based line number in the full pre-thinning job log, or null for a '... N lines omitted ...' marker. The gap between consecutive values is how many lines were elided.
+ * @nullable
+ */
+ original_line: number | null
+ /** The log line text, or the omission-marker text. */
+ text: string
+}
+
+export interface CIJobFailureLogApi {
+ /** The thinned failure-log lines in original order, with omission markers. */
+ lines: CIFailureLogLineApi[]
+ /** GitHub Actions job id of the failed job. */
+ job_id: number
+ /** Workflow run id the job belongs to. */
+ run_id: number
+ /** Job conclusion ('failure', 'timed_out', ...). Only failed jobs have logs. */
+ conclusion: string
+ /** Git branch the run was triggered on, or '' when unknown. */
+ branch: string
+ /** Total lines in the full job log before thinning (the denominator for each line's original_line); 0 when unknown. */
+ original_total_lines: number
+ /** Number of lines returned for this job (after the per-job cap). */
+ line_count: number
+ /** True when the job had more failure lines than the per-job cap. */
+ truncated: boolean
+}
+
+export interface CIFailureLogsApi {
+ /** Repository the pull request belongs to. */
+ repo: RepoRefApi
+ /** Failed CI jobs with their thinned failure logs, grouped by job. */
+ jobs: CIJobFailureLogApi[]
+ /** Pull request number the failure logs are for. */
+ pr_number: number
+ /** Workflow runs attributed to the PR (across all its pushes) that were searched for logs. */
+ runs_attributed: number
+ /** False when no failure logs were found — CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR carries no run association to resolve. */
+ logs_available: boolean
+ /** True when the overall line cap across all jobs was hit. */
+ truncated: boolean
+}
+
export interface WorkflowCostApi {
/** GitHub Actions workflow name this cost is for. */
workflow_name: string
@@ -83,15 +136,6 @@ export interface AuthorApi {
is_bot: boolean
}
-export interface RepoRefApi {
- /** Code host provider, e.g. 'github'. */
- provider: string
- /** Repository owner or organization. */
- owner: string
- /** Repository name. */
- name: string
-}
-
/**
* * `open` - OPEN
* * `closed` - CLOSED
@@ -601,6 +645,21 @@ export type EngineeringAnalyticsCiCardsParams = {
source_id?: string
}
+export type EngineeringAnalyticsCiFailureLogsParams = {
+ /**
+ * Pull request number whose CI failure logs to fetch.
+ */
+ pr_number: number
+ /**
+ * 'owner/name' repository the pull request belongs to.
+ */
+ repo: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsPrCostParams = {
/**
* Pull request number to estimate cost for.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 99b5f5f6cc84..b9ff79e9d683 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -10,7 +10,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
CICardSummaryApi,
+ CIFailureLogsApi,
EngineeringAnalyticsCiCardsParams,
+ EngineeringAnalyticsCiFailureLogsParams,
EngineeringAnalyticsPrCostParams,
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPrRunsParams,
@@ -64,6 +66,39 @@ export const engineeringAnalyticsCiCards = async (
})
}
+export const getEngineeringAnalyticsCiFailureLogsUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsCiFailureLogsParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/ci_failure_logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/ci_failure_logs/`
+}
+
+/**
+ * The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to its workflow runs via the pull_requests association (all of the PR's pushes, not just the latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association. Each line carries its original 1-based line number in the full pre-thinning log; lines are the failure region (errors plus surrounding context, with omission markers), capped per job and overall.
+ */
+export const engineeringAnalyticsCiFailureLogs = async (
+ projectId: string,
+ params: EngineeringAnalyticsCiFailureLogsParams,
+ options?: RequestInit
+): Promise<CIFailureLogsApi> => {
+ return apiMutator<CIFailureLogsApi>(getEngineeringAnalyticsCiFailureLogsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsPrCostUrl = (projectId: string, params: EngineeringAnalyticsPrCostParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index e4901263f631..93a1305a789b 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -12,6 +12,25 @@ tools:
engineering-analytics-ci-cards:
operation: engineering_analytics_ci_cards
enabled: false
+ engineering-analytics-ci-failure-logs:
+ operation: engineering_analytics_ci_failure_logs
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: CI failure logs for a PR
+ description: >
+ The thinned CI failure logs for a pull request, grouped by failed job — reach for this to answer "why did
+ this PR's CI fail". Each failed job returns its failure region (the error lines plus surrounding context,
+ with "... N lines omitted ..." markers) as ordered lines, and every line carries its original 1-based line
+ number in the full pre-thinning log so you can locate it in the raw GitHub log. The PR is resolved to ALL
+ its workflow runs across every push (via the pull_requests association, not the latest commit), so earlier
+ pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the
+ short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the
+ run/job metadata behind these logs.
engineering-analytics-pr-cost:
operation: engineering_analytics_pr_cost
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8fdd2d8ccfdf..cd9fa1672d27 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2334,6 +2334,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-ci-failure-logs": {
+ "description": "The thinned CI failure logs for a pull request, grouped by failed job — reach for this to answer \"why did this PR's CI fail\". Each failed job returns its failure region (the error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, and every line carries its original 1-based line number in the full pre-thinning log so you can locate it in the raw GitHub log. The PR is resolved to ALL its workflow runs across every push (via the pull_requests association, not the latest commit), so earlier pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the run/job metadata behind these logs.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "CI failure logs for a PR",
+ "title": "CI failure logs for a PR",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-pr-cost": {
"description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
"category": "Engineering analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a83ed2b4b3a6..3c6163276a75 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2378,6 +2378,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-ci-failure-logs": {
+ "description": "The thinned CI failure logs for a pull request, grouped by failed job — reach for this to answer \"why did this PR's CI fail\". Each failed job returns its failure region (the error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, and every line carries its original 1-based line number in the full pre-thinning log so you can locate it in the raw GitHub log. The PR is resolved to ALL its workflow runs across every push (via the pull_requests association, not the latest commit), so earlier pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the run/job metadata behind these logs.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "CI failure logs for a PR",
+ "title": "CI failure logs for a PR",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-pr-cost": {
"description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
"category": "Engineering analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 897460913810..4f0cc8253306 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11864,6 +11864,59 @@ export namespace Schemas {
failing_ci: number;
}
+ export interface CIFailureLogLine {
+ /**
+ * 1-based line number in the full pre-thinning job log, or null for a '... N lines omitted ...' marker. The gap between consecutive values is how many lines were elided.
+ * @nullable
+ */
+ original_line: number | null;
+ /** The log line text, or the omission-marker text. */
+ text: string;
+ }
+
+ export interface RepoRef {
+ /** Code host provider, e.g. 'github'. */
+ provider: string;
+ /** Repository owner or organization. */
+ owner: string;
+ /** Repository name. */
+ name: string;
+ }
+
+ export interface CIJobFailureLog {
+ /** The thinned failure-log lines in original order, with omission markers. */
+ lines: CIFailureLogLine[];
+ /** GitHub Actions job id of the failed job. */
+ job_id: number;
+ /** Workflow run id the job belongs to. */
+ run_id: number;
+ /** Job conclusion ('failure', 'timed_out', ...). Only failed jobs have logs. */
+ conclusion: string;
+ /** Git branch the run was triggered on, or '' when unknown. */
+ branch: string;
+ /** Total lines in the full job log before thinning (the denominator for each line's original_line); 0 when unknown. */
+ original_total_lines: number;
+ /** Number of lines returned for this job (after the per-job cap). */
+ line_count: number;
+ /** True when the job had more failure lines than the per-job cap. */
+ truncated: boolean;
+ }
+
+ export interface CIFailureLogs {
+ /** Repository the pull request belongs to. */
+ repo: RepoRef;
+ /** Failed CI jobs with their thinned failure logs, grouped by job. */
+ jobs: CIJobFailureLog[];
+ /** Pull request number the failure logs are for. */
+ pr_number: number;
+ /** Workflow runs attributed to the PR (across all its pushes) that were searched for logs. */
+ runs_attributed: number;
+ /** False when no failure logs were found — CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR carries no run association to resolve. */
+ logs_available: boolean;
+ /** True when the overall line cap across all jobs was hit. */
+ truncated: boolean;
+ }
+
export interface CIMDVerificationToken {
readonly id: string;
/** @maxLength 40 */
@@ -30623,15 +30676,6 @@ export namespace Schemas {
excluded_jobs: number;
}
- export interface RepoRef {
- /** Code host provider, e.g. 'github'. */
- provider: string;
- /** Repository owner or organization. */
- owner: string;
- /** Repository name. */
- name: string;
- }
-
export interface PullRequest {
/** The pull request author. */
author: Author;
@@ -61172,6 +61216,21 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsCiFailureLogsParams = {
+ /**
+ * Pull request number whose CI failure logs to fetch.
+ */
+ pr_number: number;
+ /**
+ * 'owner/name' repository the pull request belongs to.
+ */
+ repo: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsPrCostParams = {
/**
* Pull request number to estimate cost for.
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index e56d7410fde2..dc4aa5222417 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -3,11 +3,33 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 7 enabled ops
+ * PostHog API - MCP 8 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
+/**
+ * The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to its workflow runs via the pull_requests association (all of the PR's pushes, not just the latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association. Each line carries its original 1-based line number in the full pre-thinning log; lines are the failure region (errors plus surrounding context, with omission markers), capped per job and overall.
+ */
+export const EngineeringAnalyticsCiFailureLogsParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const EngineeringAnalyticsCiFailureLogsQueryParams = /* @__PURE__ */ zod.object({
+ pr_number: zod.number().describe('Pull request number whose CI failure logs to fetch.'),
+ repo: zod.string().describe("'owner/name' repository the pull request belongs to."),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+})
+
/**
* Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet.
*/
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 0c4dbc78804d..0708e7a2eaac 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ EngineeringAnalyticsCiFailureLogsQueryParams,
EngineeringAnalyticsPrCostQueryParams,
EngineeringAnalyticsPrLifecycleQueryParams,
EngineeringAnalyticsPullRequestsQueryParams,
@@ -13,6 +14,29 @@ import {
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const EngineeringAnalyticsCiFailureLogsSchema = EngineeringAnalyticsCiFailureLogsQueryParams
+
+const engineeringAnalyticsCiFailureLogs = (): ToolBase<
+ typeof EngineeringAnalyticsCiFailureLogsSchema,
+ Schemas.CIFailureLogs
+> => ({
+ name: 'engineering-analytics-ci-failure-logs',
+ schema: EngineeringAnalyticsCiFailureLogsSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsCiFailureLogsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.CIFailureLogs>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/ci_failure_logs/`,
+ query: {
+ pr_number: params.pr_number,
+ repo: params.repo,
+ source_id: params.source_id,
+ },
+ })
+ return result
+ },
+})
+
const EngineeringAnalyticsPrCostSchema = EngineeringAnalyticsPrCostQueryParams
const engineeringAnalyticsPrCost = (): ToolBase<typeof EngineeringAnalyticsPrCostSchema, Schemas.PRCostSummary> => ({
@@ -173,6 +197,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'engineering-analytics-ci-failure-logs': engineeringAnalyticsCiFailureLogs,
'engineering-analytics-pr-cost': engineeringAnalyticsPrCost,
'engineering-analytics-sources': engineeringAnalyticsSources,
'engineering-analytics-workflow-jobs': engineeringAnalyticsWorkflowJobs,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-ci-failure-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-ci-failure-logs.json
new file mode 100644
index 000000000000..85d2e2b42fbc
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-ci-failure-logs.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "pr_number": {
+ "description": "Pull request number whose CI failure logs to fetch.",
+ "type": "number"
+ },
+ "repo": {
+ "description": "'owner/name' repository the pull request belongs to.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
+ }
+ },
+ "required": ["pr_number", "repo"],
+ "type": "object"
+}