diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml new file mode 100644 index 00000000000..42bb6267b2e --- /dev/null +++ b/.github/workflows/buildtest.yml @@ -0,0 +1,146 @@ +name: Compare build corpus +run-name: Corpus comparison (${{ inputs.candidate_ref || github.sha }}) +on: + push: + branches: ['release-[0-9]*'] + workflow_dispatch: + inputs: + base_ref: + description: Baseline commit or branch (defaults to the latest stable PoB release) + type: string + candidate_ref: + description: Candidate commit or branch (defaults to the selected workflow revision) + type: string + expected_digest: + description: Optional SHA-256 of the exact corpus response + type: string + strict: + description: Fail when a stat changes value or is added or removed + default: false + type: boolean + override_verdict: + description: Pass blocking comparison findings after maintainer review + default: false + type: boolean + +permissions: + contents: read + +jobs: + compare: + name: Compare build corpus + if: ${{ !github.event.deleted }} + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - name: Check out comparison tools and fixtures + uses: actions/checkout@v4 + with: + path: harness + persist-credentials: false + sparse-checkout: | + spec/corpus + spec/TestBuilds + runtime/lua + - name: Find latest stable PoB release + id: stable + if: ${{ !inputs.base_ref }} + env: + GH_TOKEN: ${{ github.token }} + run: | + tag=$(gh api repos/PathOfBuildingCommunity/PathOfBuilding/releases/latest --jq .tag_name) + test -n "$tag" + echo "ref=refs/tags/$tag" >> "$GITHUB_OUTPUT" + echo "STABLE_TAG=$tag" >> "$GITHUB_ENV" + - name: Test comparison tools + run: | + python3 -m unittest discover -s harness/spec/corpus -p 'test_*.py' + sh harness/spec/corpus/test_verdict.sh + - name: Check out baseline + uses: actions/checkout@v4 + with: + path: base + repository: ${{ inputs.base_ref && github.repository || 'PathOfBuildingCommunity/PathOfBuilding' }} + ref: ${{ inputs.base_ref || steps.stable.outputs.ref }} + persist-credentials: false + - name: Check out candidate + uses: actions/checkout@v4 + with: + path: candidate + ref: ${{ inputs.candidate_ref || github.sha }} + persist-credentials: false + - name: Pin corpus and comparison inputs + id: inputs + env: + EXPECTED: ${{ inputs.expected_digest }} + run: | + mkdir -p "$RUNNER_TEMP/corpus-results" "$RUNNER_TEMP/corpus-base" + curl --fail --silent --show-error --retry 3 --retry-delay 2 --retry-all-errors \ + --max-time 60 --max-filesize 16777216 \ + https://api.pob.codes/test-builds/corpus -o "$RUNNER_TEMP/corpus.json" + digest=$(sha256sum "$RUNNER_TEMP/corpus.json" | cut -d ' ' -f 1) + if [[ -n "$EXPECTED" && "$EXPECTED" != "$digest" ]]; then echo "Corpus digest changed"; exit 1; fi + base=$(git -C base rev-parse HEAD) + candidate=$(git -C candidate rev-parse HEAD) + tools=$(git -C harness rev-parse HEAD:spec/corpus HEAD:spec/TestBuilds HEAD:runtime/lua | sha256sum | cut -d ' ' -f 1) + echo "key=corpus-v1-$base-$digest-$tools" >> "$GITHUB_OUTPUT" + echo "BASE_SHA=$base" >> "$GITHUB_ENV" + echo "CANDIDATE_SHA=$candidate" >> "$GITHUB_ENV" + - name: Restore calculated baseline + id: cache + uses: actions/cache/restore@v4 + with: + key: ${{ steps.inputs.outputs.key }} + path: ${{ runner.temp }}/corpus-base + - name: Compare both revisions + env: + STRICT: ${{ inputs.strict }} + OVERRIDE_VERDICT: ${{ inputs.override_verdict }} + run: | + docker build -t pob-corpus harness/spec/corpus + docker run --rm --network none --user "$(id -u):$(id -g)" \ + -v "$PWD/harness:/harness:ro" -v "$PWD/base:/base:ro" -v "$PWD/candidate:/candidate:ro" \ + -v "$RUNNER_TEMP/corpus.json:/corpus.json:ro" -v "$RUNNER_TEMP/corpus-results:/results" \ + -v "$RUNNER_TEMP/corpus-base:/baseline" -e BASE_SHA -e CANDIDATE_SHA -e STRICT -e OVERRIDE_VERDICT \ + pob-corpus sh /harness/spec/corpus/run.sh + - name: Check baseline completeness + id: completed + if: ${{ !cancelled() && steps.cache.outcome == 'success' && steps.cache.outputs.cache-hit != 'true' }} + run: | + if test -f "$RUNNER_TEMP/corpus-base/complete"; then echo "save=true" >> "$GITHUB_OUTPUT"; fi + - uses: actions/cache/save@v4 + if: ${{ !cancelled() && steps.completed.outputs.save == 'true' }} + with: + key: ${{ steps.inputs.outputs.key }} + path: ${{ runner.temp }}/corpus-base + - name: Write the build comparison report + if: ${{ !cancelled() }} + env: + STRICT: ${{ inputs.strict }} + OVERRIDE_VERDICT: ${{ inputs.override_verdict }} + BASE_REPO: ${{ inputs.base_ref && github.repository || 'PathOfBuildingCommunity/PathOfBuilding' }} + BASELINE_CACHE_HIT: ${{ steps.cache.outputs.cache-hit }} + run: | + python3 harness/spec/corpus/report.py "$RUNNER_TEMP/corpus-results" "$RUNNER_TEMP/corpus.json" \ + harness "$GITHUB_REPOSITORY" "$(git -C harness rev-parse HEAD)" + - uses: actions/upload-artifact@v4 + id: report + if: ${{ !cancelled() }} + with: + name: build-diff-output + path: ${{ runner.temp }}/corpus-results/report/ + - name: Show the result + if: ${{ !cancelled() }} + env: + REPORT_URL: ${{ steps.report.outputs.artifact-url }} + run: | + if test -s "$RUNNER_TEMP/corpus-results/actions-summary.md"; then + cat "$RUNNER_TEMP/corpus-results/actions-summary.md" >> "$GITHUB_STEP_SUMMARY" + else + echo '# Failed - Report unavailable' >> "$GITHUB_STEP_SUMMARY" + echo 'Open the first failed step in the Actions log for the error.' >> "$GITHUB_STEP_SUMMARY" + fi + if test -n "$REPORT_URL"; then + printf '\n[Download the full report and build list](%s)\n' "$REPORT_URL" >> "$GITHUB_STEP_SUMMARY" + fi + printf '\n[How the PoB Codes test corpus is selected and maintained](https://pob.codes/content/test-corpus/)\n' >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f9e2e420064..d33d032b61d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,9 +13,11 @@ on: jobs: release: runs-on: ubuntu-latest + outputs: + release_pr: ${{ steps.prepare.outputs.pull-request-number }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: ref: 'dev' - name: Generate Release notes @@ -35,7 +37,8 @@ jobs: chmod +x .github/tweak_changelogs.sh .github/tweak_changelogs.sh "v${{ github.event.inputs.releaseVersion }}" - name: Create Pull Request - uses: peter-evans/create-pull-request@v5 + id: prepare + uses: peter-evans/create-pull-request@v7 with: draft: true title: Release ${{ github.event.inputs.releaseVersion }} @@ -44,4 +47,21 @@ jobs: Draft release of ${{ github.event.inputs.releaseVersion }}. Edits will be made as necessary to prepare the codebase for release. + + See the Checks tab for the build corpus comparison against the latest stable release. + See [how the PoB Codes test corpus is selected and maintained](https://pob.codes/content/test-corpus/). commit-message: 'Prepare release ${{ github.event.inputs.releaseVersion }}' + start-corpus-check: + needs: release + if: ${{ needs.release.outputs.release_pr }} + runs-on: ubuntu-latest + permissions: + actions: write + steps: + # A branch push made by the release job's GITHUB_TOKEN does not start push workflows. + - name: Start comparison on the prepared release branch + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_BRANCH: release-${{ inputs.releaseVersion }} + run: gh workflow run buildtest.yml --repo "$GH_REPO" --ref "$RELEASE_BRANCH" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aabec92049a..dfccdc16b92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -318,6 +318,8 @@ It is a good idea to prefer Docker due to it having a very reliable Lua setup. B 3. Run `luarocks install busted` 4. Run `busted --lua=luajit` to run the tests. You can also use e.g. `-p TestUtils_spec.lua` to run a specific file. +Release candidates automatically run the [build corpus comparison](spec/corpus/README.md). You can also run it manually to compare two PoB revisions on the same public builds. + ### Debugging tests When running tests with a docker container it is possible to use EmmyLua for debugging. Paste in the following right under `function launch:OnInit()` in `./src/Launch.lua`: ```lua diff --git a/spec/corpus/BuildStats.lua b/spec/corpus/BuildStats.lua new file mode 100644 index 00000000000..5981c055eaa --- /dev/null +++ b/spec/corpus/BuildStats.lua @@ -0,0 +1,17 @@ +-- Preserve PoB's saved display stats and append scalar calculation results. +-- Nested tables include live actor, item and skill objects with cycles. +return function(xml, output, element) + local saved, extra = {}, {} + for _, child in ipairs(xml) do + if child.elem == element then saved[child.attrib.stat] = true end + end + for key, value in pairs(output) do + if type(key) == "string" and not saved[key] and (type(value) == "number" or type(value) == "boolean") then + extra[#extra + 1] = key + end + end + table.sort(extra) + for _, key in ipairs(extra) do + xml[#xml + 1] = { elem = element, attrib = { stat = key, value = tostring(output[key]) } } + end +end diff --git a/spec/corpus/Calculate.lua b/spec/corpus/Calculate.lua new file mode 100644 index 00000000000..0f57c694f17 --- /dev/null +++ b/spec/corpus/Calculate.lua @@ -0,0 +1,53 @@ +local batch, cursorPath, outDir = assert(arg[1]), assert(arg[2]), assert(arg[3]) +local startAt = assert(tonumber(arg[4])) +local zlib = require("zlib") +local appendStats = dofile("/harness/spec/corpus/BuildStats.lua") +dofile("HeadlessWrapper.lua") +assert(build and not launch.promptMsg, launch.promptMsg or "PoB failed to start") + +-- SimpleGraphic supplies these functions in the desktop application. The +-- headless definitions are stubs, including the inflater used by Timeless jewels. +function Inflate(data) + return (zlib.inflate(47)(data)) +end +function Deflate(data) + return (zlib.deflate()(data, "finish")) +end + +local save = build.Save +function build:Save(xml) + save(self, xml) + local output = self.calcsTab.mainOutput + appendStats(xml, output, "PlayerStat") + if output.Minion then appendStats(xml, output.Minion, "MinionStat") end +end + +local function write(path, value) + local file = assert(io.open(path, "wb")) + assert(file:write(value)) + assert(file:close()) +end + +local index = 0 +for name in io.lines(batch) do + index = index + 1 + if index >= startAt then + write(cursorPath, tostring(index)) + write(cursorPath .. ".stage", "loading") + local file = assert(io.open("/results/inputs/" .. name .. ".xml", "rb")) + local xml = file:read("*a") + file:close() + io.stderr:write("Loading ", name, "\n") + local start = os.clock() + local document, err = common.xml.ParseXML(xml) + assert(document and not err and document[1].elem == "PathOfBuilding", "Invalid PoB XML") + loadBuildFromXML(xml, name) + assert(not launch.promptMsg, launch.promptMsg) + assert(not build.abortSave and type(build.calcsTab.mainOutput.Life) == "number", "No calculated player output") + local elapsed = os.clock() - start + write(cursorPath .. ".stage", "saving") + io.stderr:write("Saving ", name, "\n") + write(outDir .. "/" .. name .. ".build", assert(build:SaveDB("Cache"))) + write(outDir .. "/" .. name .. ".time", tostring(elapsed * 1000)) + end +end diff --git a/spec/corpus/DiffOutput.lua b/spec/corpus/DiffOutput.lua new file mode 100644 index 00000000000..9a261162e8d --- /dev/null +++ b/spec/corpus/DiffOutput.lua @@ -0,0 +1,49 @@ +-- https://stackoverflow.com/questions/19326368/iterate-over-lines-including-blank-lines +local function splitLines(s) + if s:sub(-1)~="\n" then s=s.."\n" end + return s:gmatch("(.-)\n") +end + +local function buildOutputMap(filecontent) + local playerOutput = {} + local minionOutput = {} + for line in splitLines(filecontent) do + local stat = line:match(']+)') + local key, val = stat and stat:match('stat="(.-)"'), stat and stat:match('value="(.-)"') + if key then + playerOutput[key] = val + else + local stat = line:match(']+)') + local key, val = stat and stat:match('stat="(.-)"'), stat and stat:match('value="(.-)"') + if key then + minionOutput[key] = val + end + end + end + return playerOutput, minionOutput +end + +local function readBuild(path) + local file = assert(io.open(path, "r")) + local player, minion = buildOutputMap(file:read("*a")) + file:close() + return player, minion +end + +local function compare(actor, before, after) + local function record(key) + assert(not key:find("[%c]"), "Invalid stat name") + print(table.concat({ arg[3], actor, key, before[key] or "", after[key] or "" }, "\t")) + end + for key, value in pairs(before) do + if after[key] ~= value then record(key) end + end + for key in pairs(after) do + if before[key] == nil then record(key) end + end +end + +local playerAfter, minionAfter = readBuild(arg[1]) +local playerBefore, minionBefore = readBuild(arg[2]) +compare("Player", playerBefore, playerAfter) +compare("Minion", minionBefore, minionAfter) diff --git a/spec/corpus/Dockerfile b/spec/corpus/Dockerfile new file mode 100644 index 00000000000..342675dc57c --- /dev/null +++ b/spec/corpus/Dockerfile @@ -0,0 +1,3 @@ +FROM ghcr.io/pathofbuildingcommunity/pathofbuilding-tests@sha256:171dc3da232b8c874882e4ae3b3aa4a6e130a6c9450a31904b312435a6bf5daf +RUN apk add --no-cache git libxml2-utils zlib-dev && luarocks install lua-zlib 1.4-0 +ENV HOME=/tmp diff --git a/spec/corpus/FetchTestBuilds.lua b/spec/corpus/FetchTestBuilds.lua new file mode 100644 index 00000000000..3239d5330dc --- /dev/null +++ b/spec/corpus/FetchTestBuilds.lua @@ -0,0 +1,42 @@ +local json = require("dkjson") +local base64 = require("base64") +local sha256 = require("sha2").sha256 +local zlib = require("zlib") +local corpusFile, inputs = assert(arg[1]), assert(arg[2]) + +local input = assert(io.open(corpusFile, "rb")) +assert(input:seek("end") <= 16 * 1024 * 1024, "Oversized corpus") +input:seek("set") +local corpus, _, err = json.decode(input:read("*a")) +input:close() +assert(corpus and not err and corpus.schemaVersion == 2 and type(corpus.snapshotId) == "string", "Invalid corpus") +assert(corpus.count == #corpus.builds and corpus.count > 0 and corpus.count <= 750, "Invalid corpus count") + +local function write(path, content) + local file = assert(io.open(path, "wb")) + assert(file:write(content)) + assert(file:close()) +end + +local seen = {} +for _, entry in ipairs(corpus.builds) do + local code, hash = entry.code, entry.sha256 + assert(#code <= 150 * 1024 and code:match("^[%w_+/=%-]+$"), "Invalid encoded build") + assert(sha256(code) == hash and not seen[hash], "Incorrect or duplicate build SHA-256") + seen[hash] = true + local compressed = base64.decode(code:gsub("-", "+"):gsub("_", "/")) + local inflate, chunks, size, eof = zlib.inflate(), {}, 0, false + for offset = 1, #compressed, 1024 do + assert(not eof, "Trailing compressed input") + local chunk, finished, consumed = inflate(compressed:sub(offset, offset + 1023)) + size = size + #chunk + assert(size <= 4 * 1024 * 1024 and (not finished or consumed == #compressed), "Invalid inflated build") + chunks[#chunks + 1], eof = chunk, finished + end + assert(eof and size > 0, "Incomplete compressed build") + write(inputs .. "/" .. hash .. ".xml", table.concat(chunks)) + local tags = entry.criteria or {} + for _, tag in ipairs(tags) do assert(tag:match("^[a-z0-9%-]+$"), "Invalid criterion") end + write(inputs .. "/" .. hash .. ".tags", table.concat(tags, ", ")) +end +print(string.format("Corpus %s: %d verified API builds", corpus.snapshotId, corpus.count)) diff --git a/spec/corpus/README.md b/spec/corpus/README.md new file mode 100644 index 00000000000..d0582efa5ef --- /dev/null +++ b/spec/corpus/README.md @@ -0,0 +1,57 @@ +# Build corpus comparison + +**Release candidates.** Preparing a release with **Release next version** starts a comparison on the prepared release branch. Later maintainer pushes to that branch start a new comparison on the updated commit. Open **Compare build corpus** in the release PR's **Checks** tab to read the result before publishing. Each run compares its candidate commit against the latest published stable community release at the start of the run. The report records both commit hashes. Stat changes are advisory. A candidate crash or incomplete candidate run fails the check, including a crash shared with the baseline. A baseline-only failure remains visible but does not fail the check because the candidate completed that build. The workflow does not enforce a merge or publication policy. + +**Manual runs.** Select **Actions → Compare build corpus → Run workflow**. Leave the baseline blank to use the latest stable release or enter a baseline from this repository. The candidate defaults to the selected workflow revision. To measure repeatability, enter the same commit for both revisions. A maintainer can select **override verdict** after reviewing the findings to pass candidate failures, shared failures, or strict stat changes without hiding them. The override cannot bypass a checkout, download, or other workflow failure that prevents a complete report from being produced. + +Each run fetches one [PoB Codes corpus](https://api.pob.codes/test-builds/corpus), records its snapshot ID and response SHA-256, verifies the SHA-256 of each encoded build, and decodes the inputs once. Supply the optional response digest to require the same snapshot across runs. A snapshot change then stops the run before calculations. Both PoB revisions load every corpus entry and the same checked-in XML fixtures. See [how the corpus is selected and maintained](https://pob.codes/content/test-corpus/). + +## Reading the result + +Open the job summary in GitHub Actions. The first line gives the result. A stopped build appears first, with the revision that stopped, the build link, and the error PoB returned when available. A candidate failure is blocking whether or not the baseline also failed, unless a maintainer explicitly overrides the verdict on a manual run. If a build failed on the baseline alone, the candidate finished that build and the report marks it fixed, but a stat comparison was impossible. + +**Stat changes.** The summary counts existing values that changed separately from stats added or removed. A missing value and a reported zero are different. The same build can contribute to multiple categories. Filter the **Change type** column in `stat-changes.csv` to inspect one category. Each build with changes to existing values has a table showing the player or minion stat, its baseline value, and its candidate value. For widespread changes, the report also shows which stats changed on the most builds. Changes are advisory by default. Selecting **strict** makes any stat change fail the check unless a maintainer overrides the verdict. Failure of the candidate to load, calculate, save, or complete also fails unless overridden. A baseline-only failure is a non-blocking fixed-build warning. + +**Timing.** The summary shows the median of the percentage changes for individual builds that finished on both revisions and had a positive baseline time. CPU time covers parsing, loading and calculating the build. It excludes saving. The report says whether the baseline timing was calculated in this run or restored from an earlier complete run. Garbage collection can charge work from earlier builds to a later build. Timing never changes the verdict, including in strict mode. + +**Saved files.** A saved XML difference means PoB wrote different output for the same input. This includes its calculated stats. Saved XML differences are informational. + +**Downloads.** Open **build-diff-output** under **Artifacts** or use the download link in the job summary. + +| File | When to open it | +| --- | --- | +| `summary.md` | Read the full report, including every affected build and its changes. GitHub shows a shorter overview for large reports. | +| `builds.csv` | Look up a full build ID, a verified link, or the outcome for any input. | +| `timings.csv` | Find both CPU times in milliseconds for every completed pair, including unchanged times. Positive percentages mean the candidate used more CPU time. A zero baseline leaves the percentage blank. | +| `stat-changes.csv` | Filter changed stats across builds or copy exact values. Created only when stats change. | + +Fixtures link to their XML at the tested harness revision. For public corpus builds the report checks that the hosted code matches the input before linking. If the link cannot be verified within the lookup window, search the build list for its identifier. The inventory includes unchanged builds as well. If the run stops before completing its comparison, the report names the failed run and directs you to the Actions log. + +The baseline cache is keyed by the exact baseline commit, corpus response, comparison tools, image definition and fixtures. Only complete baselines are cached. Each run calculates the candidate. GitHub cache eviction makes the next run recalculate the baseline. + +## Run locally + +From the checkout containing this harness, point `BASE` and `CANDIDATE` at clean checkouts of the revisions to compare. The test container reads both without modifying either. This example uses a new baseline directory. + +```sh +BASE=/absolute/path/to/base +CANDIDATE=/absolute/path/to/candidate +run=$(mktemp -d) +mkdir "$run/results" "$run/baseline" +curl -fsS --retry 3 --retry-delay 2 --retry-all-errors --max-filesize 16777216 \ + https://api.pob.codes/test-builds/corpus -o "$run/corpus.json" +docker build -t pob-corpus spec/corpus +export BASE_SHA="$(git -C "$BASE" rev-parse HEAD)" CANDIDATE_SHA="$(git -C "$CANDIDATE" rev-parse HEAD)" +export STRICT=false +export OVERRIDE_VERDICT=false +status=0 +docker run --rm --network none --user "$(id -u):$(id -g)" \ + -v "$PWD:/harness:ro" -v "$BASE:/base:ro" -v "$CANDIDATE:/candidate:ro" \ + -v "$run/corpus.json:/corpus.json:ro" -v "$run/results:/results" -v "$run/baseline:/baseline" \ + -e STRICT -e OVERRIDE_VERDICT pob-corpus sh /harness/spec/corpus/run.sh || status=$? +# Use your fork name here if that is where the harness commit lives. +python3 spec/corpus/report.py "$run/results" "$run/corpus.json" . \ + PathOfBuildingCommunity/PathOfBuilding "$(git rev-parse HEAD)" || exit $? +cat "$run/results/report/summary.md" +exit "$status" +``` diff --git a/spec/corpus/batch.sh b/spec/corpus/batch.sh new file mode 100644 index 00000000000..0bdc57cc954 --- /dev/null +++ b/spec/corpus/batch.sh @@ -0,0 +1,31 @@ +#!/bin/sh +set -eu +batch=$1 +out=$2 +cursor="$batch.cursor" +next=1 +log=$(mktemp) +trap 'rm -f "$log"' EXIT +count=$(wc -l < "$batch") +while [ "$next" -le "$count" ]; do + rm -f "$cursor" "$cursor.stage" + if luajit /harness/spec/corpus/Calculate.lua "$batch" "$cursor" "$out" "$next" > "$log" 2>&1; then + cat "$log" + break + else + status=$? + cat "$log" >&2 + fi + # A native crash can terminate Lua before it can report an error. Its last + # flushed cursor identifies the build. Resume the remaining inputs in a fresh PoB. + if [ ! -s "$cursor" ]; then + echo "PoB failed to start (exit $status)" >&2 + exit "$status" + fi + index=$(cat "$cursor") + name=$(sed -n "${index}p" "$batch") + reason=$(sed -n "/In 'OnFrame':/{s/.*In 'OnFrame': //;p;q;}" "$log") + if [ -z "$reason" ]; then reason=$(sed -n 's/^luajit: //p' "$log" | head -n 1); fi + printf '%s\t%s\t%s\n' "$status" "$(cat "$cursor.stage")" "$reason" > "$out/$name.error" + next=$((index + 1)) +done diff --git a/spec/corpus/report.py b/spec/corpus/report.py new file mode 100644 index 00000000000..2072025af27 --- /dev/null +++ b/spec/corpus/report.py @@ -0,0 +1,351 @@ +"""Write the report published by the release workflow from the offline comparison.""" +import base64 +import csv +import hashlib +import html +import json +import os +import re +import sys +import time +import xml.etree.ElementTree as ET +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +from decimal import Decimal, InvalidOperation +from http.client import HTTPException +from pathlib import Path +from statistics import median +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import urlopen + + +def safe(value): + """Keep data from build exports inside a Markdown table cell.""" + text = html.escape(str(value)) + return re.sub(r"([\\|*_\[\]~\x60])", r"\\\1", " ".join(text.split())) + + +def number(count, singular, plural=None): + return f"{count:,} {singular if count == 1 else plural or singular + 's'}" + + +def stat_name(key): + words = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", key) + words = re.sub(r"([A-Z])([A-Z][a-z])", r"\1 \2", words) + return safe(words.replace("Dot", "DoT")) + + +def display_value(raw): + if raw == "": + return "Absent" + try: + value = Decimal(raw) + if value.is_finite() and abs(value.adjusted()) < 30: + return f"{value:,.2f}".rstrip("0").rstrip(".") + except InvalidOperation: + pass + return safe(raw) + + +def values(before, after): + left, right = display_value(before), display_value(after) + # Small changes must remain visible even when the rounded values match. + return (safe(before), safe(after)) if left == right else (left, right) + + +def public_url(code, deadline): + token = base64.urlsafe_b64encode(hashlib.sha1(code).digest()).decode() + for size in (11, 20): + remaining = deadline - time.monotonic() + if remaining <= 0: + break + build_id = token[:size] + try: + with urlopen(f"https://api.pob.codes/{build_id}/raw", timeout=min(4, remaining)) as response: + if response.read(len(code) + 2).rstrip(b"\r\n") == code: + return "https://pob.codes/b/" + build_id + ("0" if build_id.endswith("_") else "") + except HTTPError as error: + if error.code != 404: + break + except (OSError, HTTPException): + break + return "" + + +class Builds: + def __init__(self, results, corpus, harness, repo, revision, ids, findings): + self.names = {} + self.urls = {} + self.tags = {} + fixtures = {"fixture-" + p.stem.replace(" ", "-"): p for p in (harness / "spec/TestBuilds").rglob("*.xml")} + entries = {b["sha256"]: b for b in corpus["builds"]} + for key in ids: + if key in fixtures: + path = fixtures[key] + self.names[key] = path.stem + self.urls[key] = f"https://github.com/{repo}/blob/{revision}/{quote(path.relative_to(harness).as_posix())}" + continue + self.tags[key] = entries[key].get("criteria", []) + label = "Corpus build" + try: + with (results / "inputs" / (key + ".xml")).open("rb") as source: + for _, node in ET.iterparse(source, events=("start",)): + if node.tag == "Build": + cls = node.get("ascendClassName") + if cls in (None, "", "None"): + cls = node.get("className", "character") + label = f"Level {node.get('level', '?')} {cls}" + break + except (OSError, ET.ParseError): + pass + self.names[key] = f"{label} ({key[:12]})" + # Link checks are best effort. A provider outage must not hold up a release. + lookup = [key for key in dict.fromkeys(findings) if key in entries] + deadline = time.monotonic() + 45 + with ThreadPoolExecutor(max_workers=4) as pool: + urls = pool.map(lambda key: public_url(entries[key]["code"].encode("ascii"), deadline), lookup) + self.urls.update(zip(lookup, urls)) + + def link(self, key): + label = safe(self.names[key]) + url = self.urls.get(key) + return f"[{label}]({url})" if url else label + + +def rows(path): + return [line.split("\t") for line in path.read_text(encoding="utf-8").splitlines()] + + +def table(headers, records): + return ["| " + " | ".join(row) + " |" for row in [headers, ["---"] * len(headers), *records]] + + +def revision_link(repo, sha): + if re.fullmatch(r"[0-9a-f]{40}", sha): + return f"[{sha[:12]}](https://github.com/{repo}/commit/{sha})" + return safe(sha) + + +def write_report(results, corpus_file, harness, repo, revision): + output = results / "report" + output.mkdir(parents=True, exist_ok=True) + summary = output / "summary.md" + preview = results / "actions-summary.md" + if not (results / "compared.txt").is_file(): + message = ("# Failed - Comparison did not finish\n\n" + "PoB could not finish comparing the builds. Open the first failed step in the Actions log " + "for the error. A complete list of changes is unavailable.\n") + summary.write_text(message, encoding="utf-8") + preview.write_text(message, encoding="utf-8") + return + + raw_corpus = corpus_file.read_bytes() + corpus = json.loads(raw_corpus) + ids = (results / "builds.txt").read_text().splitlines() + compared = int((results / "compared.txt").read_text()) + categories = {kind: defaultdict(list) for kind in ("Value changed", "Added", "Removed")} + existing, added, removed = categories.values() + for key, actor, stat, before, after in rows(results / "stats.tsv"): + kind = "Added" if before == "" else "Removed" if after == "" else "Value changed" + categories[kind][key].append((actor, stat, before, after)) + failures = [line.split("\t", 4) for line in (results / "errors.tsv").read_text(encoding="utf-8", errors="replace").splitlines()] + failed = {key for _, key, _, _, _ in failures} + candidate_failed = {key for side, key, *_ in failures if side == "candidate"} + baseline_only = failed - candidate_failed + if len(ids) != len(set(ids)) or compared + len(failed) != len(ids): + raise ValueError("Build counts do not match the comparison results") + xml = (results / "xml-changes.txt").read_text().splitlines() + timings = rows(results / "timing.tsv") + builds = Builds(results, corpus, harness, repo, revision, ids, + [*(r[1] for r in failures), *existing, *removed, *added, *xml, *(r[0] for r in timings)]) + strict = os.environ.get("STRICT", "false").lower() == "true" + override = os.environ.get("OVERRIDE_VERDICT", "false").lower() == "true" + changed = any(categories.values()) + blocking = bool(candidate_failed or (strict and changed)) + overridden = blocking and override + verdict = "Passed by maintainer override" if overridden else "Failed" if blocking else "Passed" + if candidate_failed: + title = f"Candidate stopped on {number(len(candidate_failed), 'build')}" + elif baseline_only: + title = f"Candidate fixed {number(len(baseline_only), 'baseline failure')}" + elif existing: + title = f"Existing stat values changed on {number(len(existing), 'build')}" + elif added or removed: + title = "Only the set of reported stats changed" + else: + title = "All builds had matching stats" + lines = [f"# {verdict} - {title}", "", + f"Compared {compared:,} of {number(len(ids), 'build')}. " + f"{number(len(corpus['builds']), 'build')} came from PoB.codes and " + f"{len(ids) - len(corpus['builds'])} from PoB’s test files.", ""] + + if overridden: + lines += ["**Maintainer override.** This manual run would normally fail, but its blocking verdict was overridden. " + "All findings remain visible below.", ""] + elif blocking: + lines += ["**Maintainer action.** To accept these findings, run **Compare build corpus** manually on this " + "release branch and select **override verdict**. The report will retain all findings and record " + "the override.", ""] + + if compared: + lines += [f"**Existing stat values changed on {number(len(existing), 'build')}.** " + f"{number(compared - len(existing), 'completed build')} kept the same values for every stat present in both versions.", ""] + if changed: + lines += table(["Difference", "Builds affected", "Individual differences"], [ + (label, f"{len(group):,}", f"{sum(map(len, group.values())):,}") + for label, group in (("Existing value changed", existing), ("Stat added", added), ("Stat removed", removed)) + ]) + ["", "A build can appear in more than one row. A newly reported zero counts as an addition.", ""] + if failures: + lines += ["## Builds that stopped", ""] + by_build = defaultdict(set) + for side, key, *_ in failures: + by_build[key].add(side) + for side, key, status, stage, reason in failures: + other_side = "baseline" if side == "candidate" else "candidate" + comparison = f"The {other_side} finished." if other_side not in by_build[key] else "Both revisions stopped." + lines += [f"- {builds.link(key)}. The **{side}** stopped while {safe(stage)} this build (exit {safe(status)}). {comparison}", + " - " + (safe(reason[:400]) if reason else "PoB did not return an error message. See the calculation log.")] + lines.append("") + if candidate_failed: + lines += ["Candidate failures normally block the check, including a failure shared with the baseline.", ""] + if baseline_only: + lines += [f"The candidate finished {number(len(baseline_only), 'build')} that stopped on the baseline. " + "These fixed baseline failures are visible but do not block the check; their stats could not be compared.", ""] + if changed: + lines += [("Strict mode normally fails on any of the three types of difference." if strict else + "Stat differences are advisory for this run."), ""] + if len(existing) > 5: + examples = {} + for key, changes in existing.items(): + for actor, stat, before, after in changes: + examples.setdefault((actor, stat), (key, before, after)) + frequency = Counter((a, s) for entries in existing.values() for a, s, _, _ in entries) + common = sorted(frequency, key=lambda k: (-frequency[k], k)) + top_rows = [] + for actor, stat in common[:10]: + key, before, after = examples[actor, stat] + top_rows.append((actor, stat_name(stat), str(frequency[actor, stat]), + builds.link(key), *values(before, after))) + lines += ["## Existing values that changed on the most builds", "", + "Before and after are shown for one affected build per row.", ""] + table( + ["Whose stat", "Stat", "Builds", "Example build", "Before", "After"], top_rows) + [""] + changes_pct = [] + with (output / "timings.csv").open("w", newline="", encoding="utf-8") as stream: + writer = csv.writer(stream) + writer.writerow(["Build", "Build ID", "Build URL", "Baseline CPU ms", "Candidate CPU ms", "Change (%)"]) + for key, before, after in timings: + baseline = Decimal(before) + percent = "" + if baseline > 0: + change = 100 * (Decimal(after) - baseline) / baseline + changes_pct.append(change) + percent = f"{change:.2f}" + writer.writerow([builds.names[key], key, builds.urls.get(key, ""), before, after, percent]) + lines += ["## Timing", ""] + if changes_pct: + typical = round(median(changes_pct), 1) + direction = "more" if typical > 0 else "less" + difference = f"**{abs(typical):.1f}% {direction} CPU time**" if typical else "**the same CPU time** to the nearest 0.1%" + lines.append(f"The candidate used {difference} to load and calculate a build " + f"(median across {number(len(changes_pct), 'build')}).") + else: + lines.append("No builds had timing measurements with a positive baseline to compare.") + cache_hit = os.environ.get("BASELINE_CACHE_HIT", "false").lower() == "true" + timing_source = ("The baseline timings were restored from an earlier complete run. " if cache_hit else + "The baseline timings were calculated in this run. ") + lines += [timing_source + "Timing varies between runs and does not affect the result. " + "See **timings.csv** for individual measurements.", ""] + overview = lines.copy() + if existing: + lines += ["## Existing values by build", "", "Before is the baseline. After is the candidate. " + "Values are rounded for reading. See **stat-changes.csv** for exact values.", ""] + for key in sorted(existing, key=lambda k: (-len(existing[k]), builds.names[k])): + lines += [f"### {builds.link(key)}", ""] + changes = [(actor, stat_name(stat), *values(before, after)) + for actor, stat, before, after in sorted(existing[key])] + lines += table(["Whose stat", "Stat", "Before", "After"], changes) + [""] + + for heading, group, value_label in (("Stats added", added, "Candidate value"), + ("Stats removed", removed, "Baseline value")): + if not group: + continue + by_stat = defaultdict(list) + for key, changes in group.items(): + for actor, stat, before, after in changes: + by_stat[actor, stat].append((key, after if after != "" else before)) + records = [] + for actor, stat in sorted(by_stat, key=lambda item: (-len(by_stat[item]), item)): + examples = by_stat[actor, stat] + key, raw = examples[0] + records.append((actor, stat_name(stat), str(len(examples)), builds.link(key), display_value(raw))) + header = ["Whose stat", "Stat", "Builds", "Example build", value_label] + intro = [f"## {heading}", "", "One example per stat. The CSV lists every affected build.", ""] + lines += intro + table(header, records) + [""] + overview += intro + table(header, records[:5]) + [""] + + if changed: + with (output / "stat-changes.csv").open("w", newline="", encoding="utf-8") as stream: + writer = csv.writer(stream) + writer.writerow(["Build", "Build ID", "Build URL", "Whose stat", "PoB stat", "Before", "After", "Change type"]) + for kind, group in categories.items(): + for key in sorted(group): + for actor, stat, before, after in sorted(group[key]): + writer.writerow([builds.names[key], key, builds.urls.get(key, ""), actor, stat, before, after, kind]) + + if xml: + lines += ["## Builds that saved differently", "", + "Both revisions received the same input. PoB wrote different XML for the builds below. " + "The saved output includes calculated stats, so a stat change can also appear here.", ""] + lines += ["- " + builds.link(k) for k in xml] + [""] + metadata = ["## Run details", ""] + for label, var in (("Baseline", "BASE_SHA"), ("Candidate", "CANDIDATE_SHA")): + slug = os.environ.get("BASE_REPO", repo) if label == "Baseline" else repo + tag = safe(os.environ.get("STABLE_TAG", "")) if label == "Baseline" else "" + ref = revision_link(slug, os.environ[var]) + metadata.append(f"- {label}: {tag} {ref}" if tag else f"- {label}: {ref}") + metadata += [f"- Corpus snapshot: {safe(corpus['snapshotId'])}", + f"- Snapshot SHA-256: \x60{hashlib.sha256(raw_corpus).hexdigest()}\x60", + f"- Baseline calculations: {'restored from cache' if cache_hit else 'calculated in this run'}"] + lines += metadata + summary.write_text("\n".join(lines) + "\n", encoding="utf-8") + with (output / "builds.csv").open("w", newline="", encoding="utf-8") as stream: + writer = csv.writer(stream) + writer.writerow(["Build", "Build ID", "Build URL", "Result", "Corpus criteria", "Existing values changed", "Stats added", "Stats removed"]) + for key in ids: + if key in candidate_failed: + outcome = "Candidate failed" + elif key in baseline_only: + outcome = "Fixed in candidate" + elif key in existing: + outcome = "Existing values changed" + elif key in added or key in removed: + outcome = "Only additions or removals" + else: + outcome = "Stats matched" + writer.writerow([builds.names[key], key, builds.urls.get(key, ""), outcome, ", ".join(builds.tags.get(key, [])), + *(len(group.get(key, ())) if key not in failed else "" for group in categories.values())]) + if summary.stat().st_size <= 60_000 and len(lines) <= 350: + preview.write_bytes(summary.read_bytes()) + else: + # GitHub caps job summaries at 1 MiB. The download always retains every finding. + shortened = overview + if len(failures) > 5: + start = shortened.index("## Builds that stopped") + 2 + end = start + 2 * len(failures) + shortened = shortened[:start + 10] + [f"Showing 5 of {number(len(failures), 'failures')}."] + shortened[end:] + shortened += ["", f"Saved XML differed for {number(len(xml), 'build')}."] + shortened += ["", "Download **build-diff-output** and open **summary.md** for every affected build, " + "its values before and after, and the list of builds that saved differently.", ""] + preview.write_text("\n".join(shortened + metadata) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + results = Path(sys.argv[1]) + write_report(results, Path(sys.argv[2]), Path(sys.argv[3]), *sys.argv[4:]) + # Apply the copy/paste rule to every published file, including text supplied by PoB. + for path in [results / "actions-summary.md", *(results / "report").iterdir()]: + data = path.read_bytes() + clean = data.replace("\u00b7".encode("utf-8"), b"-") + if clean != data: + path.write_bytes(clean) diff --git a/spec/corpus/run.sh b/spec/corpus/run.sh new file mode 100644 index 00000000000..da65e3fcecb --- /dev/null +++ b/spec/corpus/run.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# Container mounts: /harness, /base and /candidate are read-only; /results and /baseline are writable. +set -eu +export LC_ALL=C +tools=/harness/spec/corpus +results=/results +inputs=$results/inputs +mkdir "$inputs" "$results/candidate" "$results/batches" +export LUA_PATH="/harness/runtime/lua/?.lua;/harness/runtime/lua/?/init.lua;;" +luajit "$tools/FetchTestBuilds.lua" /corpus.json "$inputs" > "$results/snapshot.txt" +cat "$results/snapshot.txt" + +find /harness/spec/TestBuilds -name '*.xml' | sort | while IFS= read -r fixture; do + name=$(basename "$fixture" .xml | tr ' ' '-') + dest="$inputs/fixture-$name" + test ! -e "$dest.xml" + cp "$fixture" "$dest.xml" + echo 'checked-in fixture' > "$dest.tags" +done +(cd "$inputs"; for file in *.xml; do echo "${file%.xml}"; done) > "$results/builds.txt" +split -l 50 "$results/builds.txt" "$results/batches/batch-" +expected=$(wc -l < "$results/builds.txt") + +calculate() ( + cd "$1/src" + export LUA_PATH="../runtime/lua/?.lua;../runtime/lua/?/init.lua;;" + find "$results/batches" -name 'batch-??' -print0 | sort -z | xargs -0 -P "${BUILD_JOBS:-2}" -I '{}' sh "$tools/batch.sh" '{}' "$2" + actual=$(find "$2" -name '*.build' | wc -l) + echo "Calculated $actual of $expected inputs for $1" +) + +if [ ! -f /baseline/complete ]; then + calculate /base /baseline + if [ "$(find /baseline -name '*.build' | wc -l)" -eq "$expected" ] && [ -z "$(find /baseline -name '*.error' -print -quit)" ]; then + cp "$results/builds.txt" /baseline/complete + fi +else + cmp /baseline/complete "$results/builds.txt" + echo "Reused $expected baseline calculations" +fi +calculate /candidate "$results/candidate" + +# The report writer reads only these records. Write the completion marker last. +: > "$results/stats.tsv" +: > "$results/timing.tsv" +: > "$results/xml-changes.txt" +: > "$results/errors.tsv" +compared=0 +while IFS= read -r name; do + base="/baseline/$name" + head="$results/candidate/$name" + if [ -f "$base.error" ] || [ -f "$head.error" ]; then + for side in baseline candidate; do + if [ "$side" = baseline ]; then file="$base"; else file="$head"; fi + if [ -f "$file.error" ]; then + printf '%s\t%s\t%s\n' "$side" "$name" "$(cat "$file.error")" >> "$results/errors.tsv" + fi + done + continue + fi + luajit "$tools/DiffOutput.lua" "$head.build" "$base.build" "$name" >> "$results/stats.tsv" + xmllint --nonet --exc-c14n "$head.build" > /tmp/head.xml + xmllint --nonet --exc-c14n "$base.build" > /tmp/base.xml + if ! cmp -s /tmp/head.xml /tmp/base.xml; then echo "$name" >> "$results/xml-changes.txt"; fi + printf '%s\t%s\t%s\n' "$name" "$(cat "$base.time")" "$(cat "$head.time")" >> "$results/timing.tsv" + compared=$((compared + 1)) +done < "$results/builds.txt" +printf '%s\n' "$compared" > "$results/compared.txt" +sh "$tools/verdict.sh" "$results" "${STRICT:-false}" "${OVERRIDE_VERDICT:-false}" diff --git a/spec/corpus/test_report.py b/spec/corpus/test_report.py new file mode 100644 index 00000000000..1107edb5c03 --- /dev/null +++ b/spec/corpus/test_report.py @@ -0,0 +1,92 @@ +import csv +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from report import write_report + + +class ReportVerdictTest(unittest.TestCase): + def render(self, errors="", stats="", strict=False, override=False, cache_hit=False): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + results = root / "results" + harness = root / "harness" + fixture_dir = harness / "spec" / "TestBuilds" + results.mkdir() + fixture_dir.mkdir(parents=True) + fixture = "fixture-sample" + (fixture_dir / "sample.xml").write_text("", encoding="utf-8") + (results / "builds.txt").write_text(fixture + "\n", encoding="utf-8") + (results / "compared.txt").write_text("0\n" if errors else "1\n", encoding="utf-8") + (results / "errors.tsv").write_text(errors, encoding="utf-8") + (results / "stats.tsv").write_text(stats, encoding="utf-8") + (results / "timing.tsv").write_text("", encoding="utf-8") + (results / "xml-changes.txt").write_text("", encoding="utf-8") + corpus = root / "corpus.json" + corpus.write_text('{"snapshotId":"test-snapshot","builds":[]}', encoding="utf-8") + environment = { + "BASE_SHA": "a" * 40, + "CANDIDATE_SHA": "b" * 40, + "STRICT": str(strict).lower(), + "OVERRIDE_VERDICT": str(override).lower(), + "BASELINE_CACHE_HIT": str(cache_hit).lower(), + } + with patch.dict(os.environ, environment, clear=True): + write_report(results, corpus, harness, "example/repo", "c" * 40) + summary = (results / "report" / "summary.md").read_text(encoding="utf-8") + with (results / "report" / "builds.csv").open(encoding="utf-8", newline="") as stream: + build = next(csv.DictReader(stream)) + return summary, build + + def test_all_completed_builds_pass(self): + summary, build = self.render() + self.assertTrue(summary.startswith("# Passed - All builds had matching stats")) + self.assertEqual(build["Result"], "Stats matched") + + def test_baseline_only_failure_passes_as_fixed(self): + error = "baseline\tfixture-sample\t1\tloading\tknown failure\n" + summary, build = self.render(errors=error, cache_hit=True) + self.assertTrue(summary.startswith("# Passed - Candidate fixed 1 baseline failure")) + self.assertIn("fixed baseline failures are visible but do not block", summary) + self.assertIn("restored from an earlier complete run", summary) + self.assertEqual(build["Result"], "Fixed in candidate") + + def test_candidate_only_failure_blocks(self): + error = "candidate\tfixture-sample\t1\tsaving\tnew failure\n" + summary, build = self.render(errors=error) + self.assertTrue(summary.startswith("# Failed - Candidate stopped on 1 build")) + self.assertIn("Candidate failures normally block the check", summary) + self.assertIn("select **override verdict**", summary) + self.assertEqual(build["Result"], "Candidate failed") + + def test_candidate_failure_can_be_overridden(self): + error = "candidate\tfixture-sample\t1\tsaving\tknown failure\n" + summary, build = self.render(errors=error, override=True) + self.assertTrue(summary.startswith("# Passed by maintainer override - Candidate stopped on 1 build")) + self.assertIn("All findings remain visible below", summary) + self.assertEqual(build["Result"], "Candidate failed") + + def test_shared_failure_blocks(self): + errors = ("baseline\tfixture-sample\t1\tloading\tknown failure\n" + "candidate\tfixture-sample\t1\tloading\tstill failing\n") + summary, build = self.render(errors=errors) + self.assertTrue(summary.startswith("# Failed - Candidate stopped on 1 build")) + self.assertIn("Both revisions stopped.", summary) + self.assertEqual(build["Result"], "Candidate failed") + + def test_strict_stat_change_blocks(self): + stat = "fixture-sample\tPlayer\tLife\t100\t101\n" + summary, _ = self.render(stats=stat, strict=True) + self.assertTrue(summary.startswith("# Failed - Existing stat values changed on 1 build")) + + def test_strict_stat_change_can_be_overridden(self): + stat = "fixture-sample\tPlayer\tLife\t100\t101\n" + summary, _ = self.render(stats=stat, strict=True, override=True) + self.assertTrue(summary.startswith("# Passed by maintainer override - Existing stat values changed on 1 build")) + + +if __name__ == "__main__": + unittest.main() diff --git a/spec/corpus/test_verdict.sh b/spec/corpus/test_verdict.sh new file mode 100644 index 00000000000..183b284c7fd --- /dev/null +++ b/spec/corpus/test_verdict.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu +tools=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +: > "$work/errors.tsv" +: > "$work/stats.tsv" + +expect_status() { + expected=$1 + strict=$2 + override=$3 + actual=0 + sh "$tools/verdict.sh" "$work" "$strict" "$override" || actual=$? + if [ "$actual" -ne "$expected" ]; then + echo "Expected status $expected, got $actual" >&2 + exit 1 + fi +} + +expect_status 0 false false +printf 'baseline\tbuild\t1\tloading\tknown failure\n' > "$work/errors.tsv" +expect_status 0 false false +printf 'candidate\tbuild\t1\tloading\tnew failure\n' > "$work/errors.tsv" +expect_status 1 false false +expect_status 0 false true +printf 'baseline\tbuild\t1\tloading\tknown failure\n' > "$work/errors.tsv" +printf 'candidate\tbuild\t1\tloading\tstill failing\n' >> "$work/errors.tsv" +expect_status 1 false false +expect_status 0 false true +: > "$work/errors.tsv" +printf 'build\tPlayer\tLife\t100\t101\n' > "$work/stats.tsv" +expect_status 0 false false +expect_status 1 true false +expect_status 0 true true diff --git a/spec/corpus/verdict.sh b/spec/corpus/verdict.sh new file mode 100644 index 00000000000..d9a0300701e --- /dev/null +++ b/spec/corpus/verdict.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +results=$1 +strict=${2:-false} +override=${3:-false} + +if [ "$override" = true ]; then + exit 0 +fi + +if awk -F '\t' '$1 == "candidate" { found = 1 } END { exit found ? 0 : 1 }' "$results/errors.tsv"; then + exit 1 +fi +if [ "$strict" = true ] && [ -s "$results/stats.tsv" ]; then + exit 1 +fi