fix(786,789): make the new proofs exercise the shipped detectors, and rename advisory -> report-only

Round three, reviewed twice in parallel (Codex gpt-5.6 and a cold Claude brief). Both converged
independently on the same two MEDIUM findings, which are the branch's own defect class reproduced
by its most recent commits: a test asserting a guarantee it does not provide.

1. THE PROOFS DID NOT EXERCISE THE CODE THEY NAMED. `test_MUTATION_a_DUPLICATE_row_is_reported`
   rebuilt the comparison with its own `len(set(...))`, and `test_MUTATION_a_SHADOWING_env_key_is_
   reported` built a synthetic dict and intersected it by hand. Both stayed GREEN with the live
   check disarmed — a behavioural test wearing a MUTATION name, which is exactly what
   `testing.guard-ships-with-mutation-proof` excludes.

   `duplicate_row_faults(rows)` and `env_shadow_faults(docs)` are now named detectors; the live
   test and its proof both call them. Verified by reproducing the reviewers' own demonstrations
   against the fix:
     duplicate detector neutered -> REDDENED "the DETECTOR did not report a second row for ..."
     shadow    detector neutered -> REDDENED "the DETECTOR did not report a shadowing job-level key"

2. `test_a_commented_out_marker_does_NOT_count` CLAIMED TO GUARD A TEXT-SCAN REGRESSION AND DID
   NOT. It re-implemented the read inline and never called `declared_roles`. One reviewer built a
   comment-blind grep reader reproducing all 17 current values byte-identically and ran every
   non-parametrised test in the file: nothing went red.

   `declared_roles(paths=None)` now takes an injectable population, so the test drives the REAL
   reader over a fixture, asserts the fault function reports it, and pins that a live marker in the
   same shape is still read (so the assertion cannot be satisfied by a reader returning None for
   everything). Verified: installing the grep reader now reddens it.

RENAMED `advisory` -> `report-only`. docs/ci-cd.md already calls `functional-e2e` an advisory job
in a DIFFERENT sense — not a required context, though it can certainly fail — while this branch
declares that job `guard`. A reader would infer the wrong marker for exactly the job whose marker
is `guard`. The value is now unambiguous, its Kind is `REPORT-ONLY`, and the manifest's declared
`expect` string moved in lockstep with the message it matches.

The rename also caught its own adjacent defect: `REPORT-ONLY` contains a hyphen, which the row
regex's `[A-Z]+` Kind group did not match, so the docs-reminder row stopped parsing. That surfaced
as a loud red naming the job — the fail-closed property documented one commit earlier, working.
Widened to `[A-Z-]+`, matching the `BEHAVIOUR-ONLY` convention in the sibling table.

Nine further accuracy findings, each measured before fixing:
  * "would therefore flag every job" — false. git/jq/python3/curl flag 4 of 8. And the REASON was
    wrong too: `small` is git-only and provisions Python via actions/setup-python, while `build`
    runs on stock ubuntu-latest, so "the bare runner has them" conflated two lanes. They are
    excluded because they do not DISCRIMINATE.
  * "four lines from the container: block" / "in one diff hunk" — false. Measured 6, 58, 6, 7, 7;
    `migrations` has the whole `services:` block in between. The property the guard rests on is
    INDEPENDENCE, not proximity, and the docs now say so.
  * "the merge semantics never have to be relied upon" — too strong. The check proves no NAME
    COLLISION; it does not prove the runner merges. That evidence is in-repo and live and is now
    cited: `build`'s Smoke step declares its own step-level `env:` and consumes workflow-level
    `${IMAGE}` on the same line, on every push to main.
  * "every malformed row fails closed" — over-broad. A malformed DUPLICATE is invisible: its job is
    already satisfied by the well-formed row. Stated.
  * The `scan` Blocks cell said "a marked job's run: body"; the ban's scope is DELIMITER_BAN_JOBS
    (the required contexts PLUS `build`), which is wider, and `scan` carries no `if:` so it runs on
    PRs too.
  * The functional-e2e row credited `e2e-local.sh` (TOOLING, only boots the instance) for curl
    assertions that live in `e2e-functional.sh` (GUARD).
  * `report-only` was defined nowhere; now defined as a verdict the job cannot enforce, with the
    limit stated (nothing detects a `guard` job whose checks are all continue-on-error).
  * "inline rows carry Proof: NONE" was stated universally while two rows cite a pytest; hedged,
    and each such row names which PART it covers.
  * "Exactly three jobs are `none`" was an unchecked prose enumeration in three sites, in a branch
    that deleted one for that reason. Removed; the markers are the source.
  * Plus: the ci-cd tool list was short by `dotnet-ef` and `playwright`; docs/README said only a
    `guard` job needs a row; "all three checks fail together" read as the opposite of "go blind";
    and #774's unrealised consequence is now subjunctive rather than past tense.

Suite: 1178 passed, 2 skipped, 1 known flake (test_hook_fire_log's production-log guard, which
compares mtimes under the SHARED ~/.cache/ersatztv/hook-fire/ — four session logs were written
during the window; 78 passed in isolation. ersatztv#809/#822, evidence posted there).

Refs #786
Refs #789
This commit is contained in:
2026-08-28 22:14:44 +02:00
parent 2cc97743c0
commit e855a79999
9 changed files with 197 additions and 111 deletions
+1 -1
View File
@@ -174,7 +174,7 @@ jobs:
runs-on: small # seconds-long git diff; keep it off the build runners
if: github.event_name == 'pull_request'
env:
CI_JOB_ROLE: advisory
CI_JOB_ROLE: report-only
steps:
- name: Checkout
uses: actions/checkout@v4
+1 -1
View File
@@ -32,7 +32,7 @@ doc below, or that changes which sections a task signal points to.**
| Testing a surface gated by config / an env var / a credential | `docs/decisions/records/testing/deny-path-at-production-config-value.md` — cover the setting absent, at its production value, and each opt-out, and assert the DENY branch |
| Touching a full-replace write path or a hand-built request object | `docs/decisions/records/testing/full-replace-asserts-field-list.md` — derive the field list from the DTO and assert set equality; reconcile by id where child state exists. In the SPA the same rule is enforced by the type system: `docs/spa-conventions.md` §4b — build the body as `Complete<T>`, annotating BOTH the wrapper parameter and every construction site |
| Writing or editing any doc, or answering a review finding in prose | `docs/decisions/records/docs/no-session-narrative.md` — the doc records the END STATE; the path to it goes in the commit message. Apply the who-benefits test, and read the carve-out before you cut (dated measurements, stated snapshot boundaries and tested-and-rejected results stay) |
| Adding, renaming or removing a workflow JOB | `docs/ci-cd.md` → "Per-job declarations" — every job declares `env.CI_JOB_ROLE` (and, in `docker-build.yml`, `env.CI_EXECUTION_CLASS`); a missing or unknown value fails `scripts/tests/test_workflow_job_guards.py` / `…/test_ci_image_pin_population.py`, and a `guard` job also needs a row in `docs/guard-inventory.md` → "Workflow-job guards". Rationale: `docs/decisions/records/testing/workflow-declares-its-own-job-metadata.md` |
| Adding, renaming or removing a workflow JOB | `docs/ci-cd.md` → "Per-job declarations" — every job declares `env.CI_JOB_ROLE` (and, in `docker-build.yml`, `env.CI_EXECUTION_CLASS`); a missing or unknown value fails `scripts/tests/test_workflow_job_guards.py` / `…/test_ci_image_pin_population.py`, and a `guard` **or `report-only`** job also needs a row in `docs/guard-inventory.md` → "Workflow-job guards". Rationale: `docs/decisions/records/testing/workflow-declares-its-own-job-metadata.md` |
| Adding / changing / deleting a guard file | `docs/guard-inventory.md` — every guard's row is machine-checked by `scripts/tests/test_guard_inventory.py`, so a new guard must acquire a row before the suite goes green, and a row graded `MUTATION` must also acquire a declared clause in `scripts/tests/mutation_manifest.py` |
| Writing code that reads live Gitea/remote state and then acts on it | `docs/decisions/records/process/check-and-use-pins-a-version.md`, then `docs/remote-state-inventory.md` — a new executable under `scripts/` (**excluding `scripts/tests/`**), `.claude/hooks/`, `.husky/` or `.gitea/workflows/` must acquire a row there before `scripts/tests/test_remote_state_inventory.py` goes green |
| Finding every site that references a symbol (multi-site fix/sweep) | `docs/local-lsp-tooling.md` — which of the three surfaces answers, and why a delegated agent must be pointed at an MCP server (`csharp-lsp`, or `serena` after an `activate_project`) rather than the `LSP` tool, which no subagent has been observed to reach |
+23 -14
View File
@@ -351,7 +351,7 @@ derives its expected set from the workflow instead of from a literal list in the
| Marker | Values | Scope | Derived by |
| --- | --- | --- | --- |
| `CI_EXECUTION_CLASS` | `toolchain`, `bare-runner` | `docker-build.yml` only — the sole workflow using the toolchain image | `scripts/tests/test_ci_image_pin_population.py` |
| `CI_JOB_ROLE` | `guard`, `advisory`, `none` | every tracked workflow | `scripts/tests/test_workflow_job_guards.py` |
| `CI_JOB_ROLE` | `guard`, `report-only`, `none` | every tracked workflow | `scripts/tests/test_workflow_job_guards.py` |
**A missing marker and an unrecognised value both fail the suite.** Neither defaults: a scheme whose
absent value reads as some safe class stops applying the moment a job is added and nobody notices.
@@ -359,9 +359,12 @@ absent value reads as some safe class stops applying the moment a job is added a
**`CI_JOB_ROLE` is decided by what the job PRODUCES.** A `guard` job's output is a **verdict**; a
`none` job's output is an **artifact**, and a red there means the build did not work rather than that
an invariant was violated. `docker-build.yml::build` publishes an image and smoke-tests it, and is
`none`. Exactly three jobs are `none` — the two image publishers and `renovate`. Every
`guard`/`advisory` job holds a row in `docs/guard-inventory.md` → "Workflow-job guards",
cross-checked both ways.
`none`. Which jobs are `none` is read off the markers rather than listed here — a list in prose is a
second copy of the workflow that rots on the next job added. Every `guard`/`report-only` job holds a
row in `docs/guard-inventory.md` → "Workflow-job guards", cross-checked both ways.
`report-only` is the third value: a verdict the job **cannot enforce**, because every check step
carries `continue-on-error: true`.
**A rejected alternative, so it is not re-adopted:** "a guard enforces an invariant about the
*repository*, so a job exercising the *product* is `none`" reads as more principled and is wrong —
@@ -372,16 +375,22 @@ contexts on `main`, i.e. precisely where a failure to fire is fail-open against
equality between two *derived* sets is blind to a member leaving both at once, so a job that loses
its `container:` block leaves the declared and the pinned set together and the comparison stays
balanced. That needs an anchor that does not move with the block — and a reviewed literal was the
only one available. The marker is the same anchor, better placed: the claim and the reality land in
one diff hunk.
only one available. The marker is the same anchor, better placed: it lives in the job it describes,
so it is reachable by anyone reading that job and it moves with the job when the job is renamed.
(Not "in the same hunk" — measured, the marker sits 6–7 lines from the `container:` block in four
jobs and **58** in `migrations`, where the `services:` block sits between them. Proximity is a
convenience; the property the guard rests on is that the marker does not move when the block does.)
**Its cost is adjacency**, so the scheme does not stop there. A literal in a distant file survives a
careless workflow edit; a marker four lines from the `container:` block can go with it. So
**Its cost is proximity**, so the scheme does not stop there. A literal in a distant file survives a
careless workflow edit; a marker a handful of lines from the `container:` block can go with it. So
`test_no_job_needs_the_toolchain_without_declaring_it` derives the requirement a third time — from
each job's own step bodies, looking for tools that exist only in the CI image (`dotnet`, `node`,
`npm`, `npx`, `ffmpeg`, `ffprobe`, `reportgenerator`; **not** `git`/`jq`/`python3`/`curl`, which the
bare runner also has). That check depends on neither the marker nor the block, and it is the only
one that catches a .NET step **moved** into a bare-runner job, where no set changes at all.
each job's own step bodies, looking for tools that exist only in the CI image (`dotnet`,
`dotnet-ef`, `node`, `npm`, `npx`, `ffmpeg`, `ffprobe`, `playwright`, `reportgenerator` — the list
lives in `TOOLCHAIN_ONLY_TOOLS`, and this sentence is a summary of it, not a second copy to keep in
sync). `git`/`jq`/`python3`/`curl` are **excluded** because they do not discriminate: the
bare-runner lanes provide or provision them too. That check depends on neither the marker nor the
block, and it is the only one that catches a .NET step **moved** into a bare-runner job, where no
set changes at all.
It is a **necessary condition only**: a job whose *only* toolchain use sat behind a script would be
invisible to it. Measured — the blind-spot set is **empty today**: all five declared toolchain jobs
@@ -389,8 +398,8 @@ are detected directly, `functional-e2e` included (it runs `dotnet restore` and `
steps before handing off to `scripts/e2e-local.sh`). The converse is still not asserted, because a
future job could be written that way and a red on a correct tree is how a guard gets deleted.
**The residual, stated because it is the one that matters.** All three checks fail together under
one plausible edit: drop the `container:` block, flip the marker, *and* move the invocation into a
**The residual, stated because it is the one that matters.** All three checks go BLIND together
(none of them reddens) under one plausible edit: drop the `container:` block, flip the marker, *and* move the invocation into a
script. Both set comparisons then stay balanced and the step scan sees no token. What bounds this is
the failure **mode**, not its likelihood — the job runs a missing binary and dies with
`dotnet: command not found`, loud and immediate, where ersatztv#774's original defect sent a
+1 -1
View File
@@ -219,7 +219,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `testing.scripted-playout-golden-deferred` | The `PlayoutBuildGoldenTests` in-memory golden net covers Sequential (YAML) as of #381. Scripted's *end-to-end pipeline* is excluded — `ScriptedPlayoutBuilder` runs a user-authored external program that drives the engine over HTTP loopback, which the in-memory harness can't pin — so that full-pipeline (integration) harness is deferred to #563. But the scheduling *behavior* those scripts drive lives entirely in the in-process `SchedulingEngine` (the `ScriptedScheduleController` is a 1:1 pass-through to it), which IS directly unit/golden-testable; the earlier "Scripted is un-golden-able by construction" framing overstated the constraint by conflating transport with engine. #395 extracts that shared switch to `ContentEnumeratorBuilder` and adds a direct regression net (`ContentEnumeratorBuilderTests`) over it. | 2026-07-22 | [link](records/testing/scripted-playout-golden-deferred.md) |
| `testing.troubleshoot-path-cannot-test-branding` | Verify logo/watermark/bug changes through a real channel playout — a green troubleshoot run proves nothing about branding. | 2026-07-21 | [link](records/testing/troubleshoot-path-cannot-test-branding.md) |
| `testing.verification-code-needs-its-own-proof` | VERIFICATION CODE IS CODE UNDER TEST. The obligation in `testing.guard-ships-with-mutation-proof` attaches to whatever emits a PASS/FAIL somebody acts on — a smoke test, a timeout wrapper, an operator-run checker, the harness that applies the mutations — and NOT only to files sitting in the guard population or named like guards; every one of the five defects measured below was in code nobody had counted as a guard. THE DISCRIMINATOR IS WHETHER A PROOF TEST CAN DRIVE THE CONSTRUCT HERMETICALLY, NOT WHETHER CI RUNS IT, and the difference is load-bearing rather than pedantic: `.claude/hooks/*.sh` and `.husky/pre-push` are operator-run and CI never fires them AS HOOKS, yet several of them carry `MUTATION` rows — among them `pretooluse-bom-guard.sh`, `pretooluse-worktree-guard.sh` and `.husky/pre-push` — because a pytest proof drives them in a sandbox. A does-CI-run-it test would sort those already-proven guards into the exempt branch. (Most of the remaining hooks are graded `NONE`; that is unproven debt, not evidence for the other discriminator.) "IT NEEDS A REAL SERVER" IS AN EXEMPTION CLAIM AND IT IS USUALLY FALSE: `scripts/mcp_smoke.py` takes its config path and server name as POSITIONAL ARGUMENTS, so a test hands it a synthetic config in a tmpdir pointing at a stub responder and drives it with no gitignored `.mcp.json` and no language server, which is how it is proven in `scripts/tests/test_mcp_smoke.py`. That coverage is a SUBSET and no count of it is kept here: the file's own docstring enumerates the cases it drives and names what it does not, so there is a list rather than a number to keep in step with it. A checker is never excused because its CALLER cannot run in CI. WHERE THE PROOF LIVES: the checker itself needs NO `docs/guard-inventory.md` row, because that population is derived from workflow and hook call sites and a transitively-reached script is rejected as a phantom; the proof goes in an ordinary `scripts/tests/test_*.py`, which joins the population automatically and carries the row, while the manifest entry names THAT test as `guard` and the checker as `target`. That shape already exists for `mutation_harness_lib.py` and needs no change to any population. ONLY WHAT NO PROOF TEST CAN DRIVE HERMETICALLY falls back to a WITNESSED NEGATIVE CONTROL — the failure path executed once, the false-green form reproduced, both recorded in the PR, and its decay stated because nothing re-runs it. `scripts/check-local-lsp.sh` is the genuine case: it asserts developer-machine installs (a global `csharp-ls`, a `host/fxr` under `DOTNET_ROOT`, a root `node_modules`) that no runner has. STOP-AND-SUBTRACT, adopted here as this record's own threshold: when a review round's finding was CREATED by the previous round's fix and that happens TWICE CONSECUTIVELY, delete the layer generating them rather than guarding it. READING THE CONSTRUCT IS NOT EXECUTING IT: ShellCheck 0.11.0 flagged NEITHER of the two shell defects below, and each is indistinguishable from correct by reading. | 2026-08-28 | [link](records/testing/verification-code-needs-its-own-proof.md) |
| `testing.workflow-declares-its-own-job-metadata` | A population of workflow JOBS is declared by the workflow itself, one machine-readable marker per job under `env:`, and every set a guard compares is DERIVED from those markers rather than from a literal list in the checker. A missing marker and an unrecognised value are both HARD FAILURES, never a default: a scheme whose absent value reads as some safe class stops applying the moment somebody adds a job and forgets, and the job nobody remembered to mark is the job nobody reviewed. Two markers exist under this rule. `CI_EXECUTION_CLASS` (toolchain / bare-runner) replaced the `TOOLCHAIN_JOBS` and `BARE_RUNNER_JOBS` literals in `test_ci_image_pin_population.py` (#789). `CI_JOB_ROLE` (guard / advisory / none) is the population of workflow-job guards that `docs/guard-inventory.md` was blind to (#786), and it is decided by what the job PRODUCES: a `guard` job output is a VERDICT, a `none` job output is an ARTIFACT, and a red in a `none` job means the build did not work rather than that an invariant was violated. `docker-build.yml::build` publishes an image and smoke-tests it and is `none`; exactly three jobs are `none`, the two image publishers and `renovate`. TWO READINGS ARE REJECTED and recorded so neither returns. Anything-that-can-fail makes every job a guard and the table distinguishes nothing. And the more principled-sounding repository-versus-product split is worse: it puts `test` and `migrations` outside the population, and those are the two REQUIRED status contexts on `main`, precisely where a failure to fire is fail-OPEN against branch protection and precisely the gap #786 exists to close. WHY THE MARKER BEATS THE LITERAL it replaced, since the literal had a real justification: set equality between two DERIVED sets is blind to a member leaving both at once, so a job that loses its `container:` block leaves the declared and the pinned set together and the comparison stays balanced. The population therefore needs an anchor that does not move with the thing it guards, and a reviewed literal was the only one available. The marker is that anchor and is strictly better placed: it lives NEXT TO the job, so the claim and the reality appear in one diff hunk. THE COST IS ADJACENCY and must be paid explicitly rather than argued away — a literal in a distant file survives a careless workflow edit, whereas a marker four lines from the `container:` block can be deleted along with it in one plausible slip. So a marker scheme is not sufficient on its own: it ships with a THIRD derivation independent of both the marker and the thing it describes. For the toolchain class that is `jobs_whose_steps_need_the_toolchain`, which reads the job OWN step bodies for tools present only in the CI image, and it is the only one of the three that can see the failure #789 was filed for — a .NET-dependent step MOVED into a bare-runner job, where no set changes and every equality stays balanced. That third check is NECESSARY-CONDITION ONLY and says so: step text cannot see a tool reached only through a script, so visible use implies the declaration and the converse is not asserted. MEASURED rather than asserted — the blind-spot set is EMPTY today, all five declared toolchain jobs being detected directly. AND THE RESIDUAL IS REAL: all three checks fail together under one edit that drops the container block, flips the marker AND moves the invocation into a script. What bounds it is the failure MODE — the job then dies on a missing binary, loudly, where the original defect sent a REQUIRED check green on the bare runner. A silent pass traded for a noisy crash, not a hole closed. Filtering to the jobs that visibly invoke a tool is legitimate subject selection for a PER-MEMBER property under `testing.guard-derives-population-from-source`, not a filtered completeness claim; the completeness claims are that every job declares a marker and that the two sets match both ways. WHAT THIS DOES NOT DO, stated because the checks read stronger than they are: it proves every job was CLASSIFIED by someone and that the table and the workflow agree, never that the classification is CORRECT, and an inline YAML assertion cannot be proven to work without running the job, so such rows carry `Proof: NONE` rather than borrowing a neighbouring file proof. | 2026-08-28 | [link](records/testing/workflow-declares-its-own-job-metadata.md) |
| `testing.workflow-declares-its-own-job-metadata` | A population of workflow JOBS is declared by the workflow itself, one machine-readable marker per job under `env:`, and every set a guard compares is DERIVED from those markers rather than from a literal list in the checker. A missing marker and an unrecognised value are both HARD FAILURES, never a default: a scheme whose absent value reads as some safe class stops applying the moment somebody adds a job and forgets, and the job nobody remembered to mark is the job nobody reviewed. Two markers exist under this rule. `CI_EXECUTION_CLASS` (toolchain / bare-runner) replaced the `TOOLCHAIN_JOBS` and `BARE_RUNNER_JOBS` literals in `test_ci_image_pin_population.py` (#789). `CI_JOB_ROLE` (guard / report-only / none) is the population of workflow-job guards that `docs/guard-inventory.md` was blind to (#786), and it is decided by what the job PRODUCES: a `guard` job output is a VERDICT, a `none` job output is an ARTIFACT, and a red in a `none` job means the build did not work rather than that an invariant was violated. `docker-build.yml::build` publishes an image and smoke-tests it and is `none`; exactly three jobs are `none`, the two image publishers and `renovate`. TWO READINGS ARE REJECTED and recorded so neither returns. Anything-that-can-fail makes every job a guard and the table distinguishes nothing. And the more principled-sounding repository-versus-product split is worse: it puts `test` and `migrations` outside the population, and those are the two REQUIRED status contexts on `main`, precisely where a failure to fire is fail-OPEN against branch protection and precisely the gap #786 exists to close. THE VALUE IS `report-only` AND NOT `advisory` ON PURPOSE: `docs/ci-cd.md` already calls `functional-e2e` an advisory job in a different sense — not a required context, though it can certainly fail — so reusing the word would make a reader infer the wrong marker for exactly the job whose marker is `guard`. WHY THE MARKER BEATS THE LITERAL it replaced, since the literal had a real justification: set equality between two DERIVED sets is blind to a member leaving both at once, so a job that loses its `container:` block leaves the declared and the pinned set together and the comparison stays balanced. The population therefore needs an anchor that does not move with the thing it guards, and a reviewed literal was the only one available. The marker is that anchor and is strictly better placed: it lives NEXT TO the job, so a reviewer of that job reaches it, and it moves with the job when the job is renamed. THE COST IS ADJACENCY and must be paid explicitly rather than argued away — a literal in a distant file survives a careless workflow edit, whereas a marker a handful of lines from the `container:` block can be deleted along with it in one plausible slip. So a marker scheme is not sufficient on its own: it ships with a THIRD derivation independent of both the marker and the thing it describes. For the toolchain class that is `jobs_whose_steps_need_the_toolchain`, which reads the job OWN step bodies for tools present only in the CI image, and it is the only one of the three that can see the failure #789 was filed for — a .NET-dependent step MOVED into a bare-runner job, where no set changes and every equality stays balanced. That third check is NECESSARY-CONDITION ONLY and says so: step text cannot see a tool reached only through a script, so visible use implies the declaration and the converse is not asserted. MEASURED rather than asserted — the blind-spot set is EMPTY today, all five declared toolchain jobs being detected directly. AND THE RESIDUAL IS REAL: all three checks fail together under one edit that drops the container block, flips the marker AND moves the invocation into a script. What bounds it is the failure MODE — the job then dies on a missing binary, loudly, where the original defect would send a REQUIRED check green on the bare runner. A silent pass traded for a noisy crash, not a hole closed. Filtering to the jobs that visibly invoke a tool is legitimate subject selection for a PER-MEMBER property under `testing.guard-derives-population-from-source`, not a filtered completeness claim; the completeness claims are that every job declares a marker and that the two sets match both ways. WHAT THIS DOES NOT DO, stated because the checks read stronger than they are: it proves every job was CLASSIFIED by someone and that the table and the workflow agree, never that the classification is CORRECT, and an inline YAML assertion cannot be proven to work without running the job, so such a row carries `Proof: NONE` unless a pytest genuinely covers PART of it — `ci-image-pin` and `set-verdict-status` each cite one, and each row says which part, because a proof reference that covers a fraction of a job must not read as covering the job. | 2026-08-28 | [link](records/testing/workflow-declares-its-own-job-metadata.md) |
## Review due
@@ -5,9 +5,9 @@ status: active
since: '2026-08-28'
supersedes: none
superseded-by: none
rule: 'A population of workflow JOBS is declared by the workflow itself, one machine-readable marker per job under `env:`, and every set a guard compares is DERIVED from those markers rather than from a literal list in the checker. A missing marker and an unrecognised value are both HARD FAILURES, never a default: a scheme whose absent value reads as some safe class stops applying the moment somebody adds a job and forgets, and the job nobody remembered to mark is the job nobody reviewed. Two markers exist under this rule. `CI_EXECUTION_CLASS` (toolchain / bare-runner) replaced the `TOOLCHAIN_JOBS` and `BARE_RUNNER_JOBS` literals in `test_ci_image_pin_population.py` (#789). `CI_JOB_ROLE` (guard / advisory / none) is the population of workflow-job guards that `docs/guard-inventory.md` was blind to (#786), and it is decided by what the job PRODUCES: a `guard` job output is a VERDICT, a `none` job output is an ARTIFACT, and a red in a `none` job means the build did not work rather than that an invariant was violated. `docker-build.yml::build` publishes an image and smoke-tests it and is `none`; exactly three jobs are `none`, the two image publishers and `renovate`. TWO READINGS ARE REJECTED and recorded so neither returns. Anything-that-can-fail makes every job a guard and the table distinguishes nothing. And the more principled-sounding repository-versus-product split is worse: it puts `test` and `migrations` outside the population, and those are the two REQUIRED status contexts on `main`, precisely where a failure to fire is fail-OPEN against branch protection and precisely the gap #786 exists to close. WHY THE MARKER BEATS THE LITERAL it replaced, since the literal had a real justification: set equality between two DERIVED sets is blind to a member leaving both at once, so a job that loses its `container:` block leaves the declared and the pinned set together and the comparison stays balanced. The population therefore needs an anchor that does not move with the thing it guards, and a reviewed literal was the only one available. The marker is that anchor and is strictly better placed: it lives NEXT TO the job, so the claim and the reality appear in one diff hunk. THE COST IS ADJACENCY and must be paid explicitly rather than argued away — a literal in a distant file survives a careless workflow edit, whereas a marker four lines from the `container:` block can be deleted along with it in one plausible slip. So a marker scheme is not sufficient on its own: it ships with a THIRD derivation independent of both the marker and the thing it describes. For the toolchain class that is `jobs_whose_steps_need_the_toolchain`, which reads the job OWN step bodies for tools present only in the CI image, and it is the only one of the three that can see the failure #789 was filed for — a .NET-dependent step MOVED into a bare-runner job, where no set changes and every equality stays balanced. That third check is NECESSARY-CONDITION ONLY and says so: step text cannot see a tool reached only through a script, so visible use implies the declaration and the converse is not asserted. MEASURED rather than asserted — the blind-spot set is EMPTY today, all five declared toolchain jobs being detected directly. AND THE RESIDUAL IS REAL: all three checks fail together under one edit that drops the container block, flips the marker AND moves the invocation into a script. What bounds it is the failure MODE — the job then dies on a missing binary, loudly, where the original defect sent a REQUIRED check green on the bare runner. A silent pass traded for a noisy crash, not a hole closed. Filtering to the jobs that visibly invoke a tool is legitimate subject selection for a PER-MEMBER property under `testing.guard-derives-population-from-source`, not a filtered completeness claim; the completeness claims are that every job declares a marker and that the two sets match both ways. WHAT THIS DOES NOT DO, stated because the checks read stronger than they are: it proves every job was CLASSIFIED by someone and that the table and the workflow agree, never that the classification is CORRECT, and an inline YAML assertion cannot be proven to work without running the job, so such rows carry `Proof: NONE` rather than borrowing a neighbouring file proof.'
rule: 'A population of workflow JOBS is declared by the workflow itself, one machine-readable marker per job under `env:`, and every set a guard compares is DERIVED from those markers rather than from a literal list in the checker. A missing marker and an unrecognised value are both HARD FAILURES, never a default: a scheme whose absent value reads as some safe class stops applying the moment somebody adds a job and forgets, and the job nobody remembered to mark is the job nobody reviewed. Two markers exist under this rule. `CI_EXECUTION_CLASS` (toolchain / bare-runner) replaced the `TOOLCHAIN_JOBS` and `BARE_RUNNER_JOBS` literals in `test_ci_image_pin_population.py` (#789). `CI_JOB_ROLE` (guard / report-only / none) is the population of workflow-job guards that `docs/guard-inventory.md` was blind to (#786), and it is decided by what the job PRODUCES: a `guard` job output is a VERDICT, a `none` job output is an ARTIFACT, and a red in a `none` job means the build did not work rather than that an invariant was violated. `docker-build.yml::build` publishes an image and smoke-tests it and is `none`; exactly three jobs are `none`, the two image publishers and `renovate`. TWO READINGS ARE REJECTED and recorded so neither returns. Anything-that-can-fail makes every job a guard and the table distinguishes nothing. And the more principled-sounding repository-versus-product split is worse: it puts `test` and `migrations` outside the population, and those are the two REQUIRED status contexts on `main`, precisely where a failure to fire is fail-OPEN against branch protection and precisely the gap #786 exists to close. THE VALUE IS `report-only` AND NOT `advisory` ON PURPOSE: `docs/ci-cd.md` already calls `functional-e2e` an advisory job in a different sense — not a required context, though it can certainly fail — so reusing the word would make a reader infer the wrong marker for exactly the job whose marker is `guard`. WHY THE MARKER BEATS THE LITERAL it replaced, since the literal had a real justification: set equality between two DERIVED sets is blind to a member leaving both at once, so a job that loses its `container:` block leaves the declared and the pinned set together and the comparison stays balanced. The population therefore needs an anchor that does not move with the thing it guards, and a reviewed literal was the only one available. The marker is that anchor and is strictly better placed: it lives NEXT TO the job, so a reviewer of that job reaches it, and it moves with the job when the job is renamed. THE COST IS ADJACENCY and must be paid explicitly rather than argued away — a literal in a distant file survives a careless workflow edit, whereas a marker a handful of lines from the `container:` block can be deleted along with it in one plausible slip. So a marker scheme is not sufficient on its own: it ships with a THIRD derivation independent of both the marker and the thing it describes. For the toolchain class that is `jobs_whose_steps_need_the_toolchain`, which reads the job OWN step bodies for tools present only in the CI image, and it is the only one of the three that can see the failure #789 was filed for — a .NET-dependent step MOVED into a bare-runner job, where no set changes and every equality stays balanced. That third check is NECESSARY-CONDITION ONLY and says so: step text cannot see a tool reached only through a script, so visible use implies the declaration and the converse is not asserted. MEASURED rather than asserted — the blind-spot set is EMPTY today, all five declared toolchain jobs being detected directly. AND THE RESIDUAL IS REAL: all three checks fail together under one edit that drops the container block, flips the marker AND moves the invocation into a script. What bounds it is the failure MODE — the job then dies on a missing binary, loudly, where the original defect would send a REQUIRED check green on the bare runner. A silent pass traded for a noisy crash, not a hole closed. Filtering to the jobs that visibly invoke a tool is legitimate subject selection for a PER-MEMBER property under `testing.guard-derives-population-from-source`, not a filtered completeness claim; the completeness claims are that every job declares a marker and that the two sets match both ways. WHAT THIS DOES NOT DO, stated because the checks read stronger than they are: it proves every job was CLASSIFIED by someone and that the table and the workflow agree, never that the classification is CORRECT, and an inline YAML assertion cannot be proven to work without running the job, so such a row carries `Proof: NONE` unless a pytest genuinely covers PART of it — `ci-image-pin` and `set-verdict-status` each cite one, and each row says which part, because a proof reference that covers a fraction of a job must not read as covering the job.'
signals: 'CI_EXECUTION_CLASS · CI_JOB_ROLE · per-job marker · workflow declares its own metadata · TOOLCHAIN_JOBS removed · BARE_RUNNER_JOBS removed · missing marker is a hard failure · unknown marker value is a hard failure · the anchor that does not move · adjacency is the cost · third derivation from the job own steps · toolchain-only tools · a step MOVED into a bare-runner job · guard jobs vs guard files · role records purpose not failability · paths: `scripts/tests/test_ci_image_pin_population.py`, `scripts/tests/test_workflow_job_guards.py`, `docs/guard-inventory.md`, `.gitea/workflows/docker-build.yml` · issues: #786, #789, #774, #787, #806'
mechanics: '`CI_EXECUTION_CLASS` is scoped to `docker-build.yml`, the only workflow using the toolchain image — a claim `test_docker_build_is_the_ONLY_workflow_pinning_the_toolchain_image` checks against the tracked workflow set. `CI_JOB_ROLE` spans every tracked workflow. Both populations come from the GIT INDEX per `testing.guard-derives-population-from-source`. The toolchain-only tool list is drawn from `docker/ci/Dockerfile` and deliberately excludes git, jq, python3 and curl, which the bare runner also has and which would therefore flag every job.'
mechanics: '`CI_EXECUTION_CLASS` is scoped to `docker-build.yml`, the only workflow using the toolchain image — a claim `test_docker_build_is_the_ONLY_workflow_pinning_the_toolchain_image` checks against the tracked workflow set. `CI_JOB_ROLE` spans every tracked workflow. Both populations come from the GIT INDEX per `testing.guard-derives-population-from-source`. The toolchain-only tool list is drawn from `docker/ci/Dockerfile` and deliberately excludes git, jq, python3 and curl. The reason is that they do not DISCRIMINATE: the bare-runner lanes provide or provision them (`small` ships git and adds Python via `actions/setup-python`; `build` runs on `ubuntu-latest`), so a match on one says nothing about whether the job needs the toolchain image. Measured, they flag 4 of the 8 jobs, not all of them.'
---
**A hand-written list of workflow jobs is a filter frozen at authoring time** — correct the day it
@@ -27,10 +27,12 @@ does not move — and in 2026-08 the only anchor available was a reviewed list.
The workflow can hold the anchor itself. `env.CI_EXECUTION_CLASS` is just as independent of the
`container:` block as a literal in a Python file is, and it is better placed: a reviewer editing the
job sees the declaration and the reality in one hunk.
job reaches it, and it moves with the job when the job is renamed or removed. Not "in the same
hunk": measured, the marker sits 6-7 lines from the `container:` block in four jobs and 58 in
`migrations`, where the `services:` block sits between them.
The cost is that same adjacency. A literal three directories away survives a careless workflow edit;
a marker four lines from the block does not. That is why the scheme is not a marker alone. The third
The cost is that same proximity. A literal three directories away survives a careless workflow edit;
a marker a handful of lines from the block does not. That is why the scheme is not a marker alone. The third
derivation — reading each job's own steps for tools that exist only in the CI image — depends on
neither the marker nor the block, so removing the pair together still reddens.
+14 -6
View File
@@ -257,8 +257,14 @@ were outside every population here until #786; `pr-checks.yml:ci-image-pin`, whi
invariant it did not check (#774), was sitting in exactly that gap.
**"Which jobs are guards" is a judgement the filesystem cannot supply**, so it is declared where the
job is: every job in every tracked workflow carries `env.CI_JOB_ROLE`, one of `guard`, `advisory` or
`none`. `scripts/tests/test_workflow_job_guards.py` derives the population from the parsed workflows
job is: every job in every tracked workflow carries `env.CI_JOB_ROLE`, one of `guard`, `report-only` or
`none`. `report-only` is the third value and needs its own sentence, because "guard vs none" does not
imply it: a `report-only` job produces a **verdict it cannot enforce** — every check step carries
`continue-on-error: true`, so it reports and never fails. `docs-reminder` is the only one.
Note the limit: nothing detects a `guard` job whose checks are all `continue-on-error`, because the
checker compares the marker against the ROW, never against the job's ability to fail.
`scripts/tests/test_workflow_job_guards.py` derives the population from the parsed workflows
in the **git index** and asserts set equality against this table in both directions — a new guard job
acquires a row before the suite goes green, and a row naming a job that stopped being a guard is
reported too.
@@ -286,7 +292,9 @@ clean description of it.
`Assertion` says where the logic actually lives, because that determines what a proof could even
look like: an **inline** assertion cannot be unit-tested without running the job, so most carry
`NONE` and say so, rather than borrowing credibility from a neighbouring file's proof.
`NONE` and say so, rather than borrowing credibility from a neighbouring file's proof. Two inline
rows do cite a pytest — `ci-image-pin` and `set-verdict-status` — and each names which PART of the
job it covers, because a proof reference that covers a fraction must not read as covering the job.
| Job | Blocks | Kind | Assertion | Proof |
| --- | --- | --- | --- | --- |
@@ -294,12 +302,12 @@ look like: an **inline** assertion cannot be unit-tested without running the job
| `docker-build.yml::toolchain-preflight` | a merge, through the COMBINED commit status the consent gate reads (#598). **Not** the other jobs: nothing `needs:` it and it is not a required context, so it reports rather than gates. It exists because a job that CONSUMED the vanished image could not run to say so (#772) | GUARD | `scripts/ci-toolchain-image-resolves.sh` | that script's row above |
| `docker-build.yml::test` | a merge — the REQUIRED context `Build ErsatzTV Image / Build & test (.NET) (pull_request)` | GUARD | the `dotnet test` / `npm test` suites, which include the C# and TypeScript structural guards named in scope-limit item 2 above | `scripts/ci-step-ran.sh` covers a dropped step — every consequential step `mark`s and the final step `assert`s, which is the mechanism `test_ci_dropped_step_guard.py` enforces on this job; the suites carry their own assertions |
| `docker-build.yml::migrations` | a merge — the REQUIRED context `Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request)` | GUARD | `dotnet ef migrations has-pending-model-changes` plus apply-to-fresh-DB, per provider | `scripts/ci-step-ran.sh` covers a dropped step — same `mark`/`assert` mechanism, enforced on this job by `test_ci_dropped_step_guard.py` |
| `docker-build.yml::functional-e2e` | a PR or a push to `main`, on a broken curl or UI contract | GUARD | `scripts/e2e-local.sh` + `scripts/e2e-ui.sh` | those scripts' rows above (both `TOOLING`); no dropped-step guard — see the decision table below |
| `docker-build.yml::scan` | the release path, when a banned expression delimiter appears in a marked job's `run:` body | GUARD | `scripts/tests/test_ci_dropped_step_guard.py`, `…/test_ci_release_path_scan_job.py`, `scripts/ci-prove-ban-detects.sh` | those files' rows above |
| `docker-build.yml::functional-e2e` | a PR or a push to `main`, on a broken HTTP contract or UI flow | GUARD | `scripts/e2e-functional.sh` (the HTTP contract assertions) and `scripts/e2e-ui.sh` (the Playwright flows). `scripts/e2e-local.sh` only BOOTS the instance they run against and asserts nothing — it is `TOOLING` above, and naming it here would credit the coverage to the one script that does not provide it | `scripts/e2e-functional.sh`'s row above (`GUARD`, `NONE`); no dropped-step guard — see the decision table below |
| `docker-build.yml::scan` | a merge and the release path, when a banned expression delimiter appears in the `run:` body of a delimiter-ban job (`DELIMITER_BAN_JOBS` = the required contexts **plus `build`**, which is wider than the marked set). It carries no `if:`, so it runs on PRs too and a red blocks through the combined status | GUARD | `scripts/tests/test_ci_dropped_step_guard.py`, `…/test_ci_release_path_scan_job.py`, `scripts/ci-prove-ban-detects.sh` | those files' rows above |
| `docker-build.yml::api-docs` | a PR whose committed OpenAPI spec, endpoint index or SPA client types are stale | GUARD | inline — `git diff --exit-code` after re-running `scripts/update-openapi.sh` | NONE |
| `docker-build.yml::format` | a PR whose changed `.cs` files do not conform to `.editorconfig` | GUARD | inline — `dotnet format --verify-no-changes` | NONE |
| `pr-checks.yml::ci-image-pin` | a PR whose `ersatztv-ci` pin is not the 7-char sha of the last commit to touch `docker/ci` | GUARD | inline | `test_ci_image_pin_population.py::test_a_single_job_losing_its_pin_is_DETECTED` covers the POPULATION half only; the git-history half has no test |
| `pr-checks.yml::docs-reminder` | **nothing.** Both of its check steps — and the `Set up Python` between them — carry `continue-on-error: true`, so no finding it makes can fail the job. (`Checkout` does not, so the job can still go red on infrastructure — never on a finding.) | ADVISORY | inline + `scripts/check-doc-narrative.py` | n/a — it cannot go red |
| `pr-checks.yml::docs-reminder` | **nothing.** Both of its check steps — and the `Set up Python` between them — carry `continue-on-error: true`, so no finding it makes can fail the job. (`Checkout` does not, so the job can still go red on infrastructure — never on a finding.) | REPORT-ONLY | inline + `scripts/check-doc-narrative.py` | n/a — it cannot go red |
| `pr-checks.yml::decisions-guard` | a PR whose decision records fail lifecycle validation, whose catalog is stale, or whose kickoff file drifted | GUARD | `scripts/decisions_validate.py`, `scripts/build_decisions_catalog.py`, `scripts/check-kickoff-guard.sh` | those scripts' rows above |
| `pr-checks.yml::prove-fix` | a PR whose `Proves:` trailer names a test that passes without the fix | GUARD | inline + `scripts/prove-fix.sh` | that script's row above |
| `pr-checks.yml::script-tests` | a PR failing ruff or the `scripts/tests` suite — this job is the RUNNER for every `scripts/tests/` row above | GUARD | inline (the ruff population guards) + pytest | the suite it runs |
+1 -1
View File
@@ -206,7 +206,7 @@ MUTATIONS: tuple[Mutation, ...] = (
replacement="| `pr-checks.yml::ci-image-pin-RENAMED` |",
proof="test_workflow_job_guards.py::test_the_inventory_covers_exactly_the_guard_JOBS_that_exist",
granularity=CLAUSE,
expect="guard/advisory but have NO row in",
expect="guard/report-only but have NO row in",
why="THE GUARD IS A TEST, so the mutation goes into the guarded ARTIFACT — the workflow-job "
"table — rather than into the checker, per the checker-guard exception. RENAMED rather than "
"deleted, so the row count is unchanged and the red cannot come from an empty table: the "
+26 -12
View File
@@ -78,13 +78,21 @@ _DOC = yaml.safe_load(WORKFLOW.read_text())
#
# `env.CI_EXECUTION_CLASS` is that anchor, and it is a strictly better one than the literal: it is
# still an independent declaration (deleting a `container:` block leaves the marker behind, so the
# job stays in the expected set and the comparison goes red), but it lives NEXT TO the job it
# describes instead of in a Python file three directories away. A reviewer reading the workflow diff
# sees the claim and the reality in one hunk.
# job stays in the expected set and the comparison goes red), but it lives IN THE JOB it describes
# instead of in a Python file three directories away — so it is reachable by anyone reading that job,
# and it moves with the job when the job is renamed or removed.
#
# THE COST, stated rather than left for review to find: adjacency cuts both ways. The literal sat in
# a file a careless workflow edit would not touch; the marker sits four lines from the `container:`
# block, so deleting both together is one plausible slip rather than two deliberate acts. That is
# NOT "in the same diff hunk", which an earlier version of this note claimed. MEASURED distance from
# each `container:` block to its marker: test 6 lines, functional-e2e 6, api-docs 7, format 7 —
# and migrations 58, because the whole `services:` block sits between them. A container-only edit to
# `migrations` shows no marker in its hunk at all. Adjacency is a convenience that mostly holds; the
# property the guard actually rests on is INDEPENDENCE — the marker does not move when the
# `container:` block does.
#
# THE COST, stated rather than left for review to find: proximity cuts both ways. The literal sat in
# a file a careless workflow edit would not touch; the marker sits a handful of lines from the
# `container:` block in four of the five jobs, so deleting both together is one plausible slip
# rather than two deliberate acts. That is
# why this file does not stop at the marker. `test_no_job_needs_the_toolchain_without_declaring_it`
# below derives the requirement a THIRD time — from the job's own steps — and it is independent of
# both the marker and the container block, so removing the pair still goes red. It is also the check
@@ -102,8 +110,12 @@ EXECUTION_CLASSES = frozenset({TOOLCHAIN, BARE_RUNNER})
# Tools present ONLY in the CI toolchain image, used to derive a job's toolchain requirement from
# its own steps. Drawn from docker/ci/Dockerfile: the image adds the .NET SDK, the two dotnet global
# tools, Node/npm and Playwright on top of the ffmpeg base. Deliberately EXCLUDED are `git`, `jq`,
# `python3`, `curl` and `tar` — the Dockerfile installs them, but the bare runner has them too, so
# they discriminate nothing and would flag every job.
# `python3`, `curl` and `tar`. The Dockerfile installs them, but they do not DISCRIMINATE: the
# bare-runner lanes provide or provision them too — `small` is git-only and adds Python via
# `actions/setup-python` where a job needs it, and `build` runs on stock `ubuntu-latest`. So a match
# on one says nothing about whether the job needs the toolchain image. MEASURED, not assumed: those
# tokens flag 4 of the 8 jobs, so "would flag every job" would have been the wrong reason and the
# wrong number.
TOOLCHAIN_ONLY_TOOLS = (
"dotnet",
"dotnet-ef",
@@ -270,8 +282,9 @@ def jobs_whose_steps_need_the_toolchain(doc) -> dict[str, set[str]]:
balanced (nothing is in either set) and this check sees no token, so nothing reddens. That is a
real hole and it is stated rather than argued away. What bounds it is the failure MODE, not the
probability: the job then runs a missing binary and dies with `dotnet: command not found`, which
is loud and immediate — unlike ersatztv#774's original defect, where a required check went GREEN
on the bare runner having silently skipped the toolchain. Trading a silent pass for a noisy
is loud and immediate — unlike ersatztv#774's original defect, where a required check WOULD go
green on the bare runner having silently skipped the toolchain. (Subjunctive on purpose: that
hole was found and closed by inspection, and no run of it was ever observed.) Trading a silent pass for a noisy
crash is the point of the change; it is not a claim that the hole is closed.
"""
out = {}
@@ -388,8 +401,9 @@ def test_no_job_needs_the_toolchain_without_declaring_it():
"these jobs run a tool that exists ONLY in the CI toolchain image, on the bare runner:\n "
+ "\n ".join(faults)
+ f"\n\nEither declare {EXECUTION_CLASS_KEY}: {TOOLCHAIN} and add the container: block, or "
"move the step back. The bare runner has git/jq/python3/curl and nothing else from "
"docker/ci/Dockerfile."
"move the step back. Neither bare-runner lane provides the CI image's toolchain: `small` "
"is git-only (Python is added by actions/setup-python where a job needs it) and `build` "
"runs on a stock ubuntu-latest."
)
+123 -70
View File
@@ -20,8 +20,14 @@ WHAT THE MARKER MEANS, because the obvious wrong readings make the population us
WHAT THE JOB PRODUCES: a `guard` job's output is a VERDICT, a `none` job's output is an ARTIFACT.
A `none` job can still go red — that is an ERROR in producing the thing, not a finding about the
repo. `docker-build.yml::build` publishes an image and smoke-tests it, and is `none`; a failed smoke
test means the build did not work. Exactly three jobs are `none`: the two image publishers and
`renovate`.
test means the build did not work. Which jobs are `none` is read off the markers, not listed here:
a list in prose is a second copy of the workflow that rots on the next job added.
`report-only` is the third value and needs saying, because "guard vs none" does not imply it: a
`report-only` job produces a VERDICT IT CANNOT ENFORCE — every check step carries
`continue-on-error: true`. The limit, since this file is where someone will look for it: nothing
here detects a `guard` job whose checks are all `continue-on-error`. The comparison is marker
against ROW, never marker against the job's ability to fail.
TWO READINGS THAT DO NOT WORK, recorded so neither is re-adopted. "Any job containing a step that
can fail" makes every job a guard and the table distinguishes nothing. "A guard enforces an invariant
@@ -58,22 +64,27 @@ SECTION = "Workflow-job guards (ersatztv#786)"
WORKFLOWS = (".gitea/workflows", ("*.yml", "*.yaml"))
ROLE_KEY = "CI_JOB_ROLE"
GUARD, ADVISORY, NONE = "guard", "advisory", "none"
GUARD, REPORT_ONLY, NONE = "guard", "report-only", "none"
# A VOCABULARY, not a population — the legal values of the marker, not a list of jobs.
ROLES = frozenset({GUARD, ADVISORY, NONE})
ROLES = frozenset({GUARD, REPORT_ONLY, NONE})
# role -> the Kind the row must carry. `none` is absent by construction: it takes no row.
ROLE_KIND = {GUARD: "GUARD", ADVISORY: "ADVISORY"}
ROLE_KIND = {GUARD: "GUARD", REPORT_ONLY: "REPORT-ONLY"}
# Keyed on the `<workflow>.yml::<job>` shape of the first cell, so this cannot match a row of the
# file-guard table (or any other) even before `inventory_section()` narrows the text.
#
# A MALFORMED ROW FAILS CLOSED, which is the property that makes a regex acceptable here at all.
# `[^|]*` for the Blocks cell means a raw `|` inside it (a code span such as `grep … | cut …`)
# stops the row matching — and an unmatched row is an ABSENT row, which the set equality reports as
# a guard job with no entry. Measured: injecting a pipe into one Blocks cell reddens
# `test_the_inventory_covers_exactly_the_guard_JOBS_that_exist` naming that job. The failure is a
# loud red on a correct-looking table, never a silently skipped row.
_ROW = re.compile(r"^\|\s*`([a-z0-9.-]+\.ya?ml::[A-Za-z0-9_-]+)`\s*\|([^|]*)\|\s*([A-Z]+)\s*\|", re.M)
# A MALFORMED ROW FOR AN OTHERWISE-UNLISTED JOB FAILS CLOSED, and the qualifier is the whole of it.
# `[^|]*` for the Blocks cell means a raw `|` inside it (a code span such as `grep … | cut …`) stops
# the row matching. When that job has no OTHER row, the unmatched row is an ABSENT row and the set
# equality reports a guard job with no entry — measured: injecting a pipe into one Blocks cell
# reddens `test_the_inventory_covers_exactly_the_guard_JOBS_that_exist` naming that job.
#
# THE CASE IT DOES NOT COVER, because an earlier version of this note claimed "every malformed row":
# a malformed DUPLICATE is invisible. Its job is already satisfied by the well-formed row, so set
# equality holds, `duplicate_row_faults` never sees the second occurrence, and the Kind check has
# nothing to compare. A contradictory row that also happens to be malformed therefore passes. No
# checker here can see it; a reader can.
_ROW = re.compile(r"^\|\s*`([a-z0-9.-]+\.ya?ml::[A-Za-z0-9_-]+)`\s*\|([^|]*)\|\s*([A-Z-]+)\s*\|", re.M)
def workflow_files() -> list[Path]:
@@ -82,14 +93,18 @@ def workflow_files() -> list[Path]:
return tracked_paths(*WORKFLOWS)
def declared_roles() -> dict[str, str | None]:
def declared_roles(paths: list[Path] | None = None) -> dict[str, str | None]:
"""`<workflow>::<job>` -> the role it declares, or None where the marker is absent.
None is KEPT rather than dropped: an unmarked job is the defect `role_faults` reports, and a dict
that silently omitted it could not report anything.
`paths` defaults to the tracked population and exists so a proof can drive THIS function over a
fixture. Without the seam a test wanting to check the reader had to re-implement the read, which
is how a proof ends up asserting a fact about PyYAML instead of about the checker.
"""
out: dict[str, str | None] = {}
for path in workflow_files():
for path in paths if paths is not None else workflow_files():
doc = yaml.safe_load(path.read_text()) or {}
for jid, job in (doc.get("jobs") or {}).items():
if not isinstance(job, dict):
@@ -99,6 +114,32 @@ def declared_roles() -> dict[str, str | None]:
return out
def env_shadow_faults(docs: list[tuple[str, dict]] | None = None) -> list[str]:
"""THE DETECTOR for a job-level `env:` key that shadows a workflow-level one.
`docs` is `(name, parsed workflow)` pairs and defaults to the tracked population, so the proof
below drives THIS function over a fixture instead of rebuilding the set intersection itself —
a proof that reimplements the comparison stays green when the shipped one is disarmed.
"""
if docs is None:
docs = [(p.name, yaml.safe_load(p.read_text()) or {}) for p in workflow_files()]
faults = []
for name, doc in docs:
workflow_env = set(doc.get("env") or {})
if not workflow_env:
continue
for jid, job in (doc.get("jobs") or {}).items():
if not isinstance(job, dict):
continue
clash = workflow_env & set(job.get("env") or {})
if clash:
faults.append(
f"{name}::{jid} declares job-level {sorted(clash)}, which also exists at "
"workflow level. The job value WINS and the workflow value is silently lost."
)
return faults
def role_faults(roles: dict[str, str | None]) -> list[str]:
"""MISSING OR UNKNOWN IS A HARD FAILURE.
@@ -138,6 +179,23 @@ def inventory_row_list() -> list[tuple[str, str]]:
return [(job.strip(), kind.strip()) for job, _blocks, kind in _ROW.findall(inventory_section())]
def duplicate_row_faults(rows: list[tuple[str, str]]) -> list[str]:
"""THE DETECTOR, named so its live test and its mutation proof share one implementation.
An earlier draft inlined this loop in the live test and had the proof rebuild the comparison
with its own `len(set(...))`. That proof stayed green with the live check disarmed, because it
was exercising arithmetic it had written itself rather than the code that ships — the shape
`testing.guard-ships-with-mutation-proof` calls a behavioural test dressed as a proof.
"""
seen: dict[str, str] = {}
dupes = []
for job, kind in rows:
if job in seen:
dupes.append(f"'{job}' has rows claiming {seen[job]} and {kind}")
seen[job] = kind
return dupes
def inventory_jobs() -> dict[str, str]:
"""`<workflow>::<job>` -> Kind. One entry per job; see `test_no_job_has_TWO_rows`.
@@ -194,12 +252,12 @@ def test_the_inventory_covers_exactly_the_guard_JOBS_that_exist():
declared = {j for j, r in declared_roles().items() if r in ROLE_KIND}
listed = set(inventory_jobs())
assert declared - listed == set(), (
f"these workflow jobs declare {ROLE_KEY} guard/advisory but have NO row in "
f"these workflow jobs declare {ROLE_KEY} guard/report-only but have NO row in "
f"`## {SECTION}` — {sorted(declared - listed)}. Add a row saying what each blocks, where "
"its assertion lives and what proof it carries."
)
assert listed - declared == set(), (
f"`## {SECTION}` has rows for jobs that no longer declare a guard/advisory role — "
f"`## {SECTION}` has rows for jobs that no longer declare a guard/report-only role — "
f"{sorted(listed - declared)}. Either the job was renamed or removed, or its marker "
"changed; the row must follow."
)
@@ -210,18 +268,13 @@ def test_no_job_has_TWO_rows():
`inventory_jobs()` is a dict, so a second row for the same job silently overwrites the first and
set equality still holds in both directions. The realistic arrival is a merge conflict or a
copy/paste that leaves an `ADVISORY` and a `GUARD` row for one job: the table then states both,
copy/paste that leaves a `REPORT-ONLY` and a `GUARD` row for one job: the table then states both,
the checker picks whichever is later, and nothing reports the contradiction. Counting rows
against distinct keys is the only place that can see it.
"""
rows = inventory_row_list()
assert rows, "the table parsed to zero rows, so this check would be vacuous"
seen = {}
dupes = []
for job, kind in rows:
if job in seen:
dupes.append(f"'{job}' has rows claiming {seen[job]} and {kind}")
seen[job] = kind
dupes = duplicate_row_faults(rows)
assert not dupes, (
f"`## {SECTION}` lists the same job more than once:\n "
+ "\n ".join(dupes)
@@ -233,20 +286,17 @@ def test_no_job_has_TWO_rows():
def test_MUTATION_a_DUPLICATE_row_is_reported():
"""Proof for the check above, with its own negative control."""
rows = inventory_row_list()
assert len(rows) == len({j for j, _ in rows}), (
"NEGATIVE CONTROL FAILED: the unmutated table already contains a duplicate."
)
assert not duplicate_row_faults(rows), "NEGATIVE CONTROL FAILED: the unmutated table already contains a duplicate."
victim = rows[0][0]
mutated = rows + [(victim, "ADVISORY" if rows[0][1] != "ADVISORY" else "GUARD")]
assert len(mutated) != len({j for j, _ in mutated}), (
"a second row for an existing job was not detectable by the row/key count"
)
mutated = rows + [(victim, "REPORT-ONLY" if rows[0][1] != "REPORT-ONLY" else "GUARD")]
faults = duplicate_row_faults(mutated)
assert faults and victim in faults[0], f"the DETECTOR did not report a second row for '{victim}': {faults}"
def test_each_row_carries_the_KIND_its_marker_declares():
"""The row and the workflow must not disagree about WHICH kind.
Set equality alone is satisfied by an `advisory` job holding a `GUARD` row — the table would then
Set equality alone is satisfied by a `report-only` job holding a `GUARD` row — the table would then
claim a merge-blocking check where the workflow has one that cannot fail. `docs-reminder` is
exactly that job (`continue-on-error: true` on every check step), so the case is live, not
hypothetical.
@@ -272,28 +322,20 @@ def test_no_job_env_key_SHADOWS_a_workflow_level_one():
workflow-level value — and the loss is invisible: the job still runs, just with the shared
compiler back on.
Raised by cold review as an unmeasured assumption. Rather than measure the merge once and write
the result in prose, the risk is removed: no marker or future job-level variable may collide
with a workflow-level name, so the merge semantics never have to be relied upon at all.
THAT THE SCOPES MERGE RATHER THAN REPLACE is not assumed here, and the evidence is in-repo and
live: `build`'s "Smoke + IPTV E2E" step declares its own step-level `env:`
(`SMOKE_SHORT_SHA`, `SMOKE_RUN_ID`) and on the same line consumes the WORKFLOW-level `${IMAGE}`
— `IMG="${IMAGE}:${SMOKE_SHORT_SHA}"` — on every push to `main`. A replacing runner would have
broken that long ago.
So this check is not what proves merging; it removes the remaining exposure, which is a NAME
COLLISION. Merging is only safe while no job-level key shadows a workflow-level one, and that is
a property of the files rather than of the runner, so it is the half worth asserting here.
It also catches the reverse mistake — someone "documenting" `REGISTRY` on a job and pinning it to
a stale value.
"""
faults = []
for path in workflow_files():
doc = yaml.safe_load(path.read_text()) or {}
workflow_env = set(doc.get("env") or {})
if not workflow_env:
continue
for jid, job in (doc.get("jobs") or {}).items():
if not isinstance(job, dict):
continue
clash = workflow_env & set(job.get("env") or {})
if clash:
faults.append(
f"{path.name}::{jid} declares job-level {sorted(clash)}, which also exists at "
"workflow level. The job value WINS and the workflow value is silently lost."
)
faults = env_shadow_faults()
assert not faults, "job-level env shadows a workflow-level env key:\n " + "\n ".join(faults)
@@ -303,10 +345,14 @@ def test_MUTATION_a_SHADOWING_env_key_is_reported():
"env": {"UseSharedCompilation": "false"},
"jobs": {"a": {"env": {"CI_JOB_ROLE": "none"}}},
}
wf = set(doc["env"])
assert not (wf & set(doc["jobs"]["a"]["env"])), "NEGATIVE CONTROL FAILED: unmutated doc collides"
assert not env_shadow_faults([("fixture.yml", doc)]), (
"NEGATIVE CONTROL FAILED: the unmutated fixture already reports a collision"
)
doc["jobs"]["a"]["env"]["UseSharedCompilation"] = "true"
assert wf & set(doc["jobs"]["a"]["env"]), "a shadowing job-level key was not detected"
faults = env_shadow_faults([("fixture.yml", doc)])
assert faults and "UseSharedCompilation" in faults[0], (
f"the DETECTOR did not report a shadowing job-level key: {faults}"
)
# ------------------------------------------------------------------------------------------------
@@ -400,14 +446,14 @@ def test_MUTATION_a_PHANTOM_row_is_reported():
def test_MUTATION_a_row_whose_KIND_disagrees_is_reported():
"""`advisory` holding a `GUARD` row must not pass — the case `docs-reminder` makes live."""
"""`report-only` holding a `GUARD` row must not pass — the case `docs-reminder` makes live."""
roles = declared_roles()
advisory = [j for j, r in roles.items() if r == ADVISORY]
assert advisory, "no advisory job exists, so this proof is vacuous"
report_only = [j for j, r in roles.items() if r == REPORT_ONLY]
assert report_only, "no report-only job exists, so this proof is vacuous"
listed = dict(inventory_jobs())
listed[advisory[0]] = "GUARD"
listed[report_only[0]] = "GUARD"
faults = [j for j, kind in listed.items() if ROLE_KIND.get(roles.get(j)) != kind]
assert faults, "an advisory job carrying a GUARD row was accepted"
assert faults, "a report-only job carrying a GUARD row was accepted"
def test_a_workflow_job_added_without_a_marker_is_DETECTED():
@@ -433,22 +479,29 @@ def test_the_marker_is_read_from_the_PARSED_yaml_not_a_text_search():
def test_a_commented_out_marker_does_NOT_count(tmp_path):
"""A commented-out marker must read as ABSENT, and `role_faults` must say so.
"""A commented-out marker must read as ABSENT — asserted through `declared_roles` ITSELF.
Drives the real reader and the real fault function over a workflow written to disk, rather than
asserting that PyYAML ignores comments — which is a fact about PyYAML that this suite does not
own and that no change here could break. The failure it guards is a reader that ever switched
to a text scan: `grep CI_JOB_ROLE` would find the commented line and report the job classified.
An earlier draft called `yaml.safe_load` on a literal and asserted comments are not values. That
is a fact about PyYAML, which this suite does not own and no change here could break: replacing
`declared_roles` with a grep-based reader left that version GREEN. It now drives the real reader
over a real file through the `paths` seam, so a reader that ever became a text scan fails here.
"""
wf = tmp_path / "commented.yml"
wf.write_text("jobs:\n x:\n env:\n # CI_JOB_ROLE: guard\n OTHER: 1\n steps: []\n")
doc = yaml.safe_load(wf.read_text()) or {}
job = doc["jobs"]["x"]
value = (job.get("env") or {}).get(ROLE_KEY)
assert value is None, f"a commented-out marker was read as {value!r}"
# The checker's own fault function must report it, not merely fail to see it.
assert role_faults({"commented.yml::x": value}), (
"a job whose only marker is commented out was accepted as classified"
roles = declared_roles([wf])
assert roles == {"commented.yml::x": None}, (
f"the real reader returned {roles!r}; a commented-out marker must read as absent"
)
# And the text a grep-based reader would match IS present in the file, which is the whole point.
# And the fault function must REPORT it, not merely fail to see it.
assert role_faults(roles), "a job whose only marker is commented out was accepted as classified"
# The text a grep-based reader would match IS in the file — which is what makes this a real
# guard against the parser regressing to a text scan rather than a restatement of YAML rules.
assert ROLE_KEY in wf.read_text()
# A REAL marker in the same shape must still be read, so the assertion above cannot be satisfied
# by a reader that returns None for everything.
ok = tmp_path / "live.yml"
ok.write_text("jobs:\n x:\n env:\n CI_JOB_ROLE: guard\n steps: []\n")
assert declared_roles([ok]) == {"live.yml::x": GUARD}, "the reader stopped seeing a real marker"