Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions .github/workflows/telemetry-cost-contract.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ name: Telemetry Cost Contract (reusable)
# write token even for a fork or Dependabot PR. Constraints (identical to linear-ticket.yml):
# * the signal workflow checks out nothing, runs no PR content, emits no artifact/cache;
# * this validator never downloads that run's artifacts/caches and never checks out the PR
# branch or merge commit — detection reads ONLY the `patch` fragments
# `GET .../pulls/{n}/files` returns (GitHub-owned metadata, not a checkout);
# branch or merge commit — detection reads ONLY GitHub-rendered diff text: the `patch`
# fragments `GET .../pulls/{n}/files` returns, plus the whole-PR unified diff from
# `GET .../pulls/{n}` (`application/vnd.github.diff`) for any file whose `patch` GitHub
# omitted past its per-file render ceiling. Same trust class, neither is a checkout;
# * every PR-derived value (branch, title, body, labels, diff patch text) is untrusted
# DATA, passed through env, never shell-interpolated.
# The job runs on the DEFAULT branch, so its job-level check must NOT be the required merge
Expand All @@ -28,6 +30,15 @@ name: Telemetry Cost Contract (reusable)
# enforce: false, soft-fail: false green status; only the job summary and marker comment
# carry the verdict. The silent variant.
#
# WHICH red, in the two non-green modes, is itself part of the contract:
# state `failure` the contract was broken — a new billable call site with no Cost impact
# section. This gate's actual verdict.
# state `error` this gate could NOT reach a verdict (no readable diff content for a
# changed file, even from the whole-PR diff). Never reported as `failure`:
# "I could not look" must not emit the same signal as "you broke it", or
# a silently-degraded gate reads as coverage. Both block under
# `enforce: true`, so fail-closed is unaffected.
#
# PERMISSIONS the caller must grant (validated by GitHub at STARTUP, before any `if:`):
# actions: read # read the triggering workflow_run
# contents: read # checkout THIS repo's scripts (no PR code is ever checked out)
Expand Down
48 changes: 36 additions & 12 deletions scripts/telemetry-cost-contract/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,47 @@ matching this repo's convention.

| File | Role |
|---|---|
| `lib.py` | Pure, network-free core — `patterns` parsing, diff-added-line extraction, the detection match (`first_match`), the `## Cost impact` section check, failure-category selection and copy. Imported by `validate.py` and the test suite. |
| `validate.py` | The side-effecting orchestration: resolve the PR from the `workflow_run` event, skip unprotected base branches, read changed files with diff patches via `GET .../pulls/{n}/files` (GitHub-owned metadata, no checkout), apply the gate, publish the `Telemetry cost contract` commit status, and maintain the single marker PR comment. GitHub via the `gh` CLI. Imports `lib.py`. |
| `lib.py` | Pure, network-free core — `patterns` parsing, diff-added-line extraction, whole-PR-diff splitting (`split_unified_diff`), the detection match (`first_match`), the `## Cost impact` section check, failure-category selection, per-category status state and copy. Imported by `validate.py` and the test suite. |
| `validate.py` | The side-effecting orchestration: resolve the PR from the `workflow_run` event, skip unprotected base branches, read changed files with diff patches via `GET .../pulls/{n}/files` (GitHub-owned metadata, no checkout), recover any omitted `patch` from the whole-PR unified diff, apply the gate, publish the `Telemetry cost contract` commit status, and maintain the single marker PR comment. GitHub via the `gh` CLI. Imports `lib.py`. |
| `tests/` | Hermetic `unittest` suite over the pure core — no network. |

## The invariant

A PR turns red for a cost-impact verdict when an **added** diff line matches a
caller-configured pattern AND the PR body has no non-empty `## Cost impact` section AND the PR
carries no exemption label. Detection reads only the `patch` fragments GitHub's changed-files
API already returns — nothing here checks out the PR branch or executes PR content, which is
what makes it safe to run in the privileged `workflow_run` validator job on a fork or
Dependabot PR.

Separately, the validator also fails closed — publishing red with no cost-impact verdict at
all — on infrastructure failure: the changed-file lookup erroring, or a changed file with
added content but no renderable `patch` (`changed_files_unavailable`). This can block a
required check in enforce mode even though no matching line was ever found; it is a
"couldn't verify" signal, not a cost-impact finding. See
carries no exemption label. Detection reads only GitHub-rendered diff text — the `patch`
fragments the changed-files API returns, plus the whole-PR unified diff (`GET .../pulls/{n}`
under `application/vnd.github.diff`) for any file whose `patch` GitHub omitted. Nothing here
checks out the PR branch or executes PR content, which is what makes it safe to run in the
privileged `workflow_run` validator job on a fork or Dependabot PR.

### Why there are two reads, not one

`GET .../pulls/{n}/files` silently drops a file's `patch` past a per-file render ceiling, and
that ceiling is low enough that one large generated client or JSON fixture in an otherwise
ordinary PR used to take the whole gate out. The whole-PR diff endpoint's ceiling is far
higher, so `lib.split_unified_diff` recovers those files' hunks and `validate.py` splices
them into the changed-file entries before detection runs. The recovered fragments are shaped
exactly like the API's `patch` field — hunks only, no `diff --git`/`---`/`+++` headers — so
`first_match` consumes them unchanged, and a `+++ b/<path>` header can never be mistaken for
an added line. Recovery is logged as a `::warning::` and recorded in the job summary in both
directions; a gate that quietly stops checking is worse than no gate, because it reads as
coverage.

### Two non-success states, and the difference matters

Separately, the validator fails closed — no cost-impact verdict at all — when it cannot read
a changed file's content from **either** source, when a recovered fragment does not account
for all of that file's reported `additions`, or when the changed-file lookup itself errors
(`changed_files_unavailable`). In the two reporting modes that publish a red status that is
the commit-status state **`error`**, never `failure`, and the same now goes for the
pre-verdict infrastructure failures (PR fetch, ambiguous PR resolution, unreadable branch
protection, a non-`pull_request` trigger).

`failure` is this gate's verdict that the contract was broken; `error` is this gate reporting
it could not reach a verdict. Both are non-success, so a required context still blocks in
enforce mode and the exit code is unchanged — distinguishable is not the same as permissive —
but "I could not look" no longer emits the same signal as "you broke it", for a human or for
a tool reading the status. See
[`docs/callers/telemetry-cost-contract.md`](../../docs/callers/telemetry-cost-contract.md) for
the caller setup and rollout.
171 changes: 161 additions & 10 deletions scripts/telemetry-cost-contract/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
zero-consumer custom metrics C2 found months after merge get caught at PR time instead.

Detection reads ONLY GitHub-owned PR metadata — the `patch` fragments `GET
.../pulls/{n}/files` returns for each changed file — never a checkout of the PR branch. That
is what makes this safe to run on a fork PR's privileged `workflow_run` validator: the
untrusted diff text is pattern-MATCHED, never executed or interpolated.
.../pulls/{n}/files` returns for each changed file, plus the whole-PR unified diff from `GET
.../pulls/{n}` under the `application/vnd.github.diff` media type when the former omits a
file's `patch` — never a checkout of the PR branch. Both are the same trust class (rendered
by GitHub, delivered as text) and neither is a checkout, which is what makes this safe to run
on a fork PR's privileged `workflow_run` validator: the untrusted diff text is
pattern-MATCHED, never executed or interpolated.

Side-effecting orchestration (resolve the PR, read its files, publish the commit status,
upsert the comment) lives in validate.py, which imports this. Standard library only, matching
Expand Down Expand Up @@ -142,6 +145,129 @@ def first_match(files: list[dict], patterns: list[re.Pattern]) -> tuple[str, str
return None


_DIFF_HEADER_RE = re.compile(r"^diff --git ", re.MULTILINE)


_C_ESCAPE_BYTES = {
"a": 0x07, "b": 0x08, "f": 0x0C, "n": 0x0A, "r": 0x0D, "t": 0x09, "v": 0x0B,
"\\": 0x5C, '"': 0x22,
}


def _unquote_c_bytes(inner: str) -> bytes:
"""Decode git's C-style quoting to the RAW BYTES it encodes.

Decoding to bytes is the whole point, and ``.decode("unicode_escape")`` is the trap:
under the default ``core.quotePath``, git renders a non-ASCII path as octal-escaped
**UTF-8 bytes** (``"b/caf\\303\\251.go"``). ``unicode_escape`` maps each of those bytes to
its own code point and yields ``café.go``, which never matches the API's ``café.go`` — so
recovery silently never worked for a non-ASCII filename. Collect the bytes here and let
the caller decode them as UTF-8 once, which is what git actually wrote.
"""
out = bytearray()
index = 0
while index < len(inner):
char = inner[index]
if char != "\\":
out.extend(char.encode("utf-8", "surrogateescape"))
index += 1
continue
if index + 1 >= len(inner): # trailing lone backslash: keep it literally
out.append(0x5C)
break
nxt = inner[index + 1]
if nxt in _C_ESCAPE_BYTES:
out.append(_C_ESCAPE_BYTES[nxt])
index += 2
elif nxt in "01234567":
digits = ""
cursor = index + 1
while cursor < len(inner) and len(digits) < 3 and inner[cursor] in "01234567":
digits += inner[cursor]
cursor += 1
out.append(int(digits, 8) & 0xFF)
index = cursor
else: # unknown escape: keep the escaped character
out.extend(nxt.encode("utf-8", "surrogateescape"))
index += 2
return bytes(out)


def _unquote_diff_path(raw: str) -> str:
"""The path out of a ``+++ b/...`` line, undoing git's C-style quoting when present.

git quotes a path containing a space, a quote, a control character or a non-ASCII byte
(``+++ "b/a b.go"``) unless ``core.quotePath=false``, so a naive ``line[6:]`` yields
``a b.go"`` for exactly the large generated/fixture files this recovery path exists to read.

Whitespace is stripped SURGICALLY — at most one trailing TAB, which is the separator git
appends after an unquoted name — and never with ``strip()``. A general strip silently
maps the distinct paths ``foo.js`` and ``foo.js `` (a trailing space is a legal filename
character that git does not quote) onto the same key, and ``split_unified_diff``'s
assignment is last-wins: an oversized ``foo.js`` carrying a billable call plus a small
benign ``foo.js `` would mark the real file recovered-and-clean from the WRONG file's
hunks. ``split_unified_diff`` additionally fails closed on any duplicate key, so the two
guards are independent.
"""
text = raw[:-1] if raw.endswith("\t") else raw
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
text = _unquote_c_bytes(text[1:-1]).decode("utf-8", "surrogateescape")
return text[2:] if text.startswith("b/") else text


def split_unified_diff(diff_text: str) -> dict[str, str]:
"""Per-file, hunk-only diff fragments out of a WHOLE-PR unified diff, keyed by new path.

The recovery half of the unscannable-file problem. ``GET .../pulls/{n}/files`` omits a
file's ``patch`` past GitHub's per-file render ceiling, but ``GET .../pulls/{n}`` with the
``application/vnd.github.diff`` media type still returns that file's hunks — same class of
GitHub-owned metadata, still no checkout of the PR branch, so the fork-safety contract is
unchanged. Measured against a live consumer repo on 2026-11-25: an 18.3 MB whole-PR diff
whose largest JSON fixture (+289,490 lines) carries no API `patch` is fully present here,
as is every generated-client file that had taken the gate out.

Each returned value is shaped EXACTLY like GitHub's ``patch`` field — it starts at the
first ``@@`` hunk header, with the ``diff --git``/``index``/``---``/``+++``/mode lines
dropped — so ``added_lines`` and ``first_match`` consume it unchanged. That shape is the
whole point and is not cosmetic: a full multi-file diff DOES carry ``+++ b/<path>`` header
lines, which ``_ADDED_LINE_RE`` would otherwise report as an added line with content
``++ b/<path>``, inventing added content nobody wrote (and a caller pattern matching
``+`` or a path fragment would fire on it).

A section with no ``@@`` at all contributes no entry: that is a pure rename, a mode
change, or a genuinely binary file (``Binary files a/x and b/y differ``). Returning
nothing for those is correct and keeps ``unscannable_files`` failing closed on a real
binary rather than passing it as recovered-and-clean.

A path that resolves TWICE yields no entry either, rather than last-wins. Two sections
cannot legitimately claim one new path in a single PR diff, so a duplicate means either
a quoting edge this parser read wrong or file content that forged a section header — and
in both cases the honest answer is that this file was not read. Dropping it leaves it
unscannable, which fails closed; keeping the last one would hand the gate a fragment
from the wrong source and call it a clean scan.
"""
collected: list[tuple[str, str]] = []
bounds = [m.start() for m in _DIFF_HEADER_RE.finditer(diff_text or "")]
for index, start in enumerate(bounds):
end = bounds[index + 1] if index + 1 < len(bounds) else len(diff_text)
lines = diff_text[start:end].split("\n")
name = None
hunk_at = None
for offset, line in enumerate(lines):
if line.startswith("+++ "):
candidate = _unquote_diff_path(line[4:])
if candidate and candidate != "/dev/null":
name = candidate
elif line.startswith("@@"):
hunk_at = offset
break
if not name or hunk_at is None:
continue
collected.append((name, "\n".join(lines[hunk_at:]).rstrip("\n")))
seen = [name for name, _ in collected]
return {name: fragment for name, fragment in collected if seen.count(name) == 1}


def unscannable_files(files: list[dict]) -> list[str]:
"""Filenames whose diff content this check could not see at all.

Expand All @@ -151,6 +277,11 @@ def unscannable_files(files: list[dict]) -> list[str]:
``additions > 0`` must be treated as unscannable rather than silently passed as "no
match" — a padded or oversized new telemetry module is exactly the case this gate exists
to catch, and ``first_match`` alone cannot distinguish it from a harmless binary asset.

Call this AGAIN after splicing in whatever ``split_unified_diff`` recovered: the API's
per-file ``patch`` ceiling is far lower than the whole-PR diff endpoint's, so in practice
almost every file this returns on the first pass IS readable, and only a still-nonempty
list after recovery is a genuine cannot-verify (a real binary).
"""
names = []
for entry in files or []:
Expand Down Expand Up @@ -217,13 +348,32 @@ def enforce_enabled(raw: str | None) -> bool:
"this change must not regress.{exemption}"
),
"changed_files_unavailable": (
"This check could not be completed because the PR's changed-file list (with diff "
"patches) could not be read completely. A partial list could miss the very file that "
"This check could not be completed because the PR's changed files could not be read "
"completely — either the changed-file list itself was unreadable, or a file's diff "
"content was missing from both the changed-files API and the whole-PR unified diff "
"(the specific cause is named below). A partial read could miss the very file that "
"added a billable call site, so this fails closed instead of declaring a partial scan "
"clean. This is an infrastructure error, not a verdict on cost impact."
"clean. This is an infrastructure error, not a verdict on cost impact, and in the two "
"reporting modes that publish a red status it is the commit-status state `error` "
"rather than `failure`, so it is distinguishable from a real contract violation both "
"by eye and by any tool reading the status."
),
}

# The commit-status state each failing category publishes. These are deliberately DIFFERENT,
# and that is the point: `failure` is this gate's verdict that the contract was broken, while
# `error` is this gate reporting that it could not reach a verdict at all. Collapsing both to
# `failure` is what made the gate lie in the direction that costs the most — a PR carrying a
# red "could not verify" is indistinguishable at a glance from a real failing test, and it
# pushes the PR to `mergeable_state: unstable` either way. Measured on a consumer repo three
# days into the warn-only pilot (2026-11-25): 8 of the 10 red statuses across 339 open PRs
# were this category, and all 8 were substantively clean. Both states are non-success, so
# fail-closed behaviour under `enforce: true` is unchanged: a required context still blocks.
_FAILING_STATE = {
"missing_cost_impact": "failure",
"changed_files_unavailable": "error",
}


def failure_guidance(category: str, exempt_label: str = "") -> str:
"""The fixed, category-specific paragraph for the PR comment and job summary.
Expand All @@ -247,8 +397,8 @@ def failure_guidance(category: str, exempt_label: str = "") -> str:
}

_ADVISORY = (
"> ⚠️ **Advisory — this check is warn-only.** It is reported as failing so it shows up in "
"the PR's check list, but nothing this workflow does blocks a merge: what blocks is this "
"> ⚠️ **Advisory — this check is warn-only.** It is reported as not passing so it shows up "
"in the PR's check list, but nothing this workflow does blocks a merge: what blocks is this "
"repository's ruleset requiring the `Telemetry cost contract` status context, and a "
"warn-only pilot is meant to run *before* that context is required. If your merge button "
"is actually blocked on `Telemetry cost contract`, the context is already required while "
Expand Down Expand Up @@ -279,18 +429,19 @@ def failure_outcome(category: str, enforce: bool, soft_fail: bool) -> FailureOut
if category not in _GUIDANCE:
raise KeyError(category)
headline = _STATUS_HEADLINE[category]
state = _FAILING_STATE[category]
if enforce:
return FailureOutcome(
verdict=f"❌ fail ({category})",
state="failure",
state=state,
description=headline,
exit_code=1,
advisory=False,
)
if soft_fail:
return FailureOutcome(
verdict=f"❌ fail ({category}) — warn-only",
state="failure",
state=state,
description=f"Warn-only: {headline[0].lower()}{headline[1:]}",
exit_code=0,
advisory=True,
Expand Down
Loading
Loading