From ac88a1beaaed88c2d498cb76315097da3f113168 Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 13:18:10 -0800 Subject: [PATCH 01/11] Port the cached PoB build comparison to a manual corpus workflow --- .github/workflows/buildtest.yml | 107 ++++++++++++++++++++++++++++++++ spec/corpus/BuildStats.lua | 17 +++++ spec/corpus/BuildSummary.lua | 66 ++++++++++++++++++++ spec/corpus/Calculate.lua | 51 +++++++++++++++ spec/corpus/DiffOutput.lua | 74 ++++++++++++++++++++++ spec/corpus/DiffRuntime.lua | 11 ++++ spec/corpus/Dockerfile | 3 + spec/corpus/FetchTestBuilds.lua | 42 +++++++++++++ spec/corpus/README.md | 28 +++++++++ spec/corpus/batch.sh | 26 ++++++++ spec/corpus/run.sh | 80 ++++++++++++++++++++++++ 11 files changed, 505 insertions(+) create mode 100644 .github/workflows/buildtest.yml create mode 100644 spec/corpus/BuildStats.lua create mode 100644 spec/corpus/BuildSummary.lua create mode 100644 spec/corpus/Calculate.lua create mode 100644 spec/corpus/DiffOutput.lua create mode 100644 spec/corpus/DiffRuntime.lua create mode 100644 spec/corpus/Dockerfile create mode 100644 spec/corpus/FetchTestBuilds.lua create mode 100644 spec/corpus/README.md create mode 100644 spec/corpus/batch.sh create mode 100644 spec/corpus/run.sh diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml new file mode 100644 index 00000000000..b064ad356ea --- /dev/null +++ b/.github/workflows/buildtest.yml @@ -0,0 +1,107 @@ +name: Compare build corpus +run-name: Corpus comparison (${{ inputs.candidate_ref || github.sha }}) +on: + workflow_dispatch: + inputs: + base_ref: + description: Baseline commit or branch + required: true + 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 on calculated-stat differences + default: false + type: boolean + +permissions: + contents: read + +jobs: + compare: + 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: Check out baseline + uses: actions/checkout@v4 + with: + path: base + ref: ${{ inputs.base_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 --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" + echo "Corpus response SHA-256: $digest" >> "$GITHUB_STEP_SUMMARY" + - 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 }} + 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 \ + 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: Summarize + if: ${{ !cancelled() }} + run: | + if test -s "$RUNNER_TEMP/corpus-results/summary.md"; then + cat "$RUNNER_TEMP/corpus-results/summary.md" >> "$GITHUB_STEP_SUMMARY" + else + echo 'Comparison did not complete. See the failed step.' >> "$GITHUB_STEP_SUMMARY" + fi + - uses: actions/upload-artifact@v4 + if: ${{ !cancelled() }} + with: + name: build-diff-output + path: | + ${{ runner.temp }}/corpus-results/*.md + ${{ runner.temp }}/corpus-results/*.txt 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/BuildSummary.lua b/spec/corpus/BuildSummary.lua new file mode 100644 index 00000000000..26efc75a408 --- /dev/null +++ b/spec/corpus/BuildSummary.lua @@ -0,0 +1,66 @@ +-- Summarize the existing stat report without changing which differences count. +local function summarize(lines, compared, baseRef, headRef) + local builds, stats, build = {}, {}, nil + local changedBuilds, changedValues = 0, 0 + for line in lines do + build = line:match("^## Output Diff for (.+)%.build$") or build + local stat, actor = line:match("^(.-) Mismatch in (%a+) outputs:") + if stat then + assert(build, "Stat difference has no build name") + local head = assert(lines():match("^%s*head Output: (.*)$"), "Missing head value") + local base = assert(lines():match("^%s*dev Output: (.*)$"), "Missing base value") + if not builds[build] then + builds[build] = true + changedBuilds = changedBuilds + 1 + end + local key = actor .. "." .. stat + local entry = stats[key] or { key = key, count = 0, build = build, base = base, head = head } + entry.count = entry.count + 1 + stats[key] = entry + changedValues = changedValues + 1 + end + end + local function escape(value) + return tostring(value):gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub("|", "|"):gsub("`", "`") + end + local rows = {} + for _, entry in pairs(stats) do rows[#rows + 1] = entry end + -- Put common player results first; this affects presentation only. + local priority = { ["player.Life"] = 1, ["player.Mana"] = 2, ["player.EnergyShield"] = 3, + ["player.TotalDPS"] = 4, ["player.CombinedDPS"] = 5, ["player.FullDPS"] = 6 } + table.sort(rows, function(a, b) + local ap, bp = priority[a.key] or 7, priority[b.key] or 7 + if ap ~= bp then return ap < bp end + if a.count ~= b.count then return a.count > b.count end + return a.key < b.key + end) + local output = { + "## Build comparison summary", "", + changedBuilds > 0 and "**Changes found: review required.**" or "**No calculated-stat differences found.**", "", + string.format("Compared **%d builds**. **%d builds** have calculated-stat differences (**%d changed values**).", compared, changedBuilds, changedValues), "", + "Base: `" .. escape(baseRef) .. "`. Candidate: `" .. escape(headRef) .. "`.", "", + } + if #rows > 0 then + output[#output + 1] = string.format("Showing %d of %d changed stats, with one example for each. Common player results appear first; other stats are ordered by affected build count.", math.min(25, #rows), #rows) + output[#output + 1] = "" + output[#output + 1] = "| Stat | Affected builds | Example build | Before | After |" + output[#output + 1] = "| --- | ---: | --- | ---: | ---: |" + for index = 1, math.min(25, #rows) do + local entry = rows[index] + local name = entry.build + if #name == 64 and name:match("^%x+$") then name = name:sub(1, 12) end + output[#output + 1] = string.format("| %s | %d | %s | %s | %s |", escape(entry.key), entry.count, escape(name), escape(entry.base), escape(entry.head)) + end + output[#output + 1] = "" + end + output[#output + 1] = "Strict mode fails on calculated-stat differences. Saved XML and timing differences are informational." + output[#output + 1] = "" + output[#output + 1] = "Full differences are in the **build-diff-output** artifact. API build identifiers above are shortened to 12 characters for searching the full report." + return table.concat(output, "\n"), changedBuilds +end + +if arg and arg[0]:match("BuildSummary%.lua$") then + local output = summarize(io.lines(assert(arg[1])), assert(tonumber(arg[2])), assert(arg[3]), assert(arg[4])) + print(output) +end +return summarize diff --git a/spec/corpus/Calculate.lua b/spec/corpus/Calculate.lua new file mode 100644 index 00000000000..e1707b8ab2a --- /dev/null +++ b/spec/corpus/Calculate.lua @@ -0,0 +1,51 @@ +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 + local file = assert(io.open("/results/inputs/" .. name .. ".xml", "rb")) + local xml = file:read("*a") + file:close() + write(cursorPath, tostring(index)) + 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 + 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..949c36ba44e --- /dev/null +++ b/spec/corpus/DiffOutput.lua @@ -0,0 +1,74 @@ +-- 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 headhnd = io.open(arg[1], "r") +local devhnd = io.open(arg[2], "r") + +if headhnd and devhnd then + local playerHEADOutput, minionHEADOutput = buildOutputMap(headhnd:read("*a")) + local playerDEVOutput, minionDEVOutput = buildOutputMap(devhnd:read("*a")) + local mismatch = {} + local mismatchFound = false + for key, val in pairs(playerHEADOutput) do + if not playerDEVOutput[key] or playerDEVOutput[key] ~= val then + mismatch[key] = {devOutput = playerDEVOutput[key], headOutput = val} + mismatchFound = true + end + end + for key, val in pairs(playerDEVOutput) do + if not mismatch[key] and (not playerHEADOutput[key] or playerHEADOutput[key] ~= val) then + mismatch[key] = {headOutput = playerHEADOutput[key], devOutput = val} + mismatchFound = true + end + end + for key, val in pairs(mismatch) do + print(key .. " Mismatch in player outputs: ") + print("\t" .."head Output: " .. tostring(val["headOutput"])) + print("\t" .."dev Output: " .. tostring(val["devOutput"])) + end + mismatch = {} + for key, val in pairs(minionHEADOutput) do + if not minionDEVOutput[key] or minionDEVOutput[key] ~= val then + mismatch[key] = {devOutput = minionDEVOutput[key], headOutput = val} + mismatchFound = true + end + end + for key, val in pairs(minionDEVOutput) do + if not mismatch[key] and (not minionHEADOutput[key] or minionHEADOutput[key] ~= val) then + mismatch[key] = {headOutput = minionHEADOutput[key], devOutput = val} + mismatchFound = true + end + end + for key, val in pairs(mismatch) do + print(key .. " Mismatch in minion outputs: ") + print("\t" .."head Output: " .. tostring(val["headOutput"])) + print("\t" .."dev Output: " .. tostring(val["devOutput"])) + end + if mismatchFound then + os.exit(1) -- Make the exit codes of the script match the exit codes of the diff utility + end +else + os.exit(2) +end \ No newline at end of file diff --git a/spec/corpus/DiffRuntime.lua b/spec/corpus/DiffRuntime.lua new file mode 100644 index 00000000000..de6be37b9c4 --- /dev/null +++ b/spec/corpus/DiffRuntime.lua @@ -0,0 +1,11 @@ +local function runtime(path) + local file = assert(io.open(path, "r")) + local value = assert(tonumber(file:read("*a"))) + file:close() + return value +end +local head, base = runtime(arg[1]), runtime(arg[2]) +if base > 0 and math.abs(head / base - 1) >= 0.1 then + print(string.format("%s CPU time: %.1f ms -> %.1f ms (%+.0f%%)", arg[3], base, head, (head / base - 1) * 100)) + os.exit(1) +end 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..1f5be32f19f --- /dev/null +++ b/spec/corpus/README.md @@ -0,0 +1,28 @@ +# Manual build corpus comparison + +Select **Actions → Compare build corpus → Run workflow**. Choose a baseline commit and a candidate commit from this repository. The candidate defaults to the selected workflow revision. Running a control with the same commit on both sides measures repeatability. The workflow runs only on manual dispatch. + +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. + +The check fails for import errors, missing outputs, aborted calculations and incomplete comparisons. A crash report identifies the revision side, build hash and saved corpus criteria. Remaining inputs in that batch resume in a fresh PoB process. The summary compares saved player and minion stats and additional scalar numeric and boolean outputs. Enable **strict** to fail on any stat difference. Timing and saved-XML changes are informational. Download **build-diff-output** for the per-build reports. + +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 --max-filesize 16777216 https://api.pob.codes/test-builds/corpus -o "$run/corpus.json" +docker build -t pob-corpus spec/corpus +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 BASE_SHA="$(git -C "$BASE" rev-parse HEAD)" -e CANDIDATE_SHA="$(git -C "$CANDIDATE" rev-parse HEAD)" \ + pob-corpus sh /harness/spec/corpus/run.sh +cat "$run/results/summary.md" +``` diff --git a/spec/corpus/batch.sh b/spec/corpus/batch.sh new file mode 100644 index 00000000000..eff68260522 --- /dev/null +++ b/spec/corpus/batch.sh @@ -0,0 +1,26 @@ +#!/bin/sh +set -eu +batch=$1 +out=$2 +cursor="$batch.cursor" +next=1 +count=$(wc -l < "$batch") +while [ "$next" -le "$count" ]; do + rm -f "$cursor" + if luajit /harness/spec/corpus/Calculate.lua "$batch" "$cursor" "$out" "$next"; then + break + else + status=$? + 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") + tags=$(cat "/results/inputs/$name.tags") + printf '%s (exit %s) %s\n' "$name" "$status" "$tags" | tee "$out/$name.error" >&2 + next=$((index + 1)) +done diff --git a/spec/corpus/run.sh b/spec/corpus/run.sh new file mode 100644 index 00000000000..531979c54e4 --- /dev/null +++ b/spec/corpus/run.sh @@ -0,0 +1,80 @@ +#!/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" + +: > "$results/stat-diffs.txt" +: > "$results/import-errors.txt" +: > "$results/other-diffs.txt" +compared=0 +while IFS= read -r name; do + base="/baseline/$name" + head="$results/candidate/$name" + if [ -f "$base.error" ] || [ -f "$head.error" ]; then + if [ -f "$base.error" ]; then printf 'Base: ' >> "$results/import-errors.txt"; cat "$base.error" >> "$results/import-errors.txt"; fi + if [ -f "$head.error" ]; then printf 'Candidate: ' >> "$results/import-errors.txt"; cat "$head.error" >> "$results/import-errors.txt"; fi + continue + fi + if output=$(luajit "$tools/DiffOutput.lua" "$head.build" "$base.build"); then : + else + status=$? + [ "$status" -eq 1 ] || exit "$status" + printf '## Output Diff for %s.build\n%s\n' "$name" "$output" >> "$results/stat-diffs.txt" + fi + 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 "Saved XML changed: $name" >> "$results/other-diffs.txt"; fi + if output=$(luajit "$tools/DiffRuntime.lua" "$head.time" "$base.time" "$name"); then : + else + status=$? + [ "$status" -eq 1 ] || exit "$status" + printf '%s\n' "$output" >> "$results/other-diffs.txt" + fi + compared=$((compared + 1)) +done < "$results/builds.txt" +luajit "$tools/BuildSummary.lua" "$results/stat-diffs.txt" "$compared" "$BASE_SHA" "$CANDIDATE_SHA" > "$results/summary.md" +cat "$results/snapshot.txt" >> "$results/summary.md" +if [ -s "$results/import-errors.txt" ]; then + printf '\n**Import or calculation failures**\n\n' >> "$results/summary.md" + head -n 15 "$results/import-errors.txt" >> "$results/summary.md" + exit 1 +fi +test "$compared" -eq "$expected" +if [ "${STRICT:-false}" = true ] && [ -s "$results/stat-diffs.txt" ]; then exit 1; fi From 34557da4de5daa182cbf37f9b77f54066a4c80f0 Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 13:25:12 -0800 Subject: [PATCH 02/11] Link the manual corpus runner from the testing guide --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aabec92049a..30d2cd1888b 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. +To compare two PoB revisions on the same public builds, run the [manual build corpus comparison](spec/corpus/README.md). + ### 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 From ce423a327b7d3f893de9276ea6dffd71edbd265a Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 15:05:33 -0800 Subject: [PATCH 03/11] Compare prepared release candidates against the latest stable PoB release --- .github/workflows/buildtest.yml | 20 +++++++++++++++++--- .github/workflows/release.yml | 19 +++++++++++++++++++ CONTRIBUTING.md | 2 +- spec/corpus/README.md | 6 ++++-- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index b064ad356ea..64f39fee994 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -1,11 +1,12 @@ 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 - required: true + 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) @@ -23,6 +24,8 @@ permissions: jobs: compare: + name: Compare build corpus + if: ${{ !github.event.deleted }} runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -35,11 +38,22 @@ jobs: 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 baseline: \`$tag\`" >> "$GITHUB_STEP_SUMMARY" - name: Check out baseline uses: actions/checkout@v4 with: path: base - ref: ${{ inputs.base_ref }} + 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f9e2e420064..595f18914ef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,8 @@ on: jobs: release: runs-on: ubuntu-latest + outputs: + release_pr: ${{ steps.prepare.outputs.pull-request-number }} steps: - name: Checkout uses: actions/checkout@v3 @@ -35,6 +37,7 @@ jobs: chmod +x .github/tweak_changelogs.sh .github/tweak_changelogs.sh "v${{ github.event.inputs.releaseVersion }}" - name: Create Pull Request + id: prepare uses: peter-evans/create-pull-request@v5 with: draft: true @@ -44,4 +47,20 @@ 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. 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 30d2cd1888b..dfccdc16b92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -318,7 +318,7 @@ 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. -To compare two PoB revisions on the same public builds, run the [manual build corpus comparison](spec/corpus/README.md). +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`: diff --git a/spec/corpus/README.md b/spec/corpus/README.md index 1f5be32f19f..ba8bb9542fc 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -1,6 +1,8 @@ -# Manual build corpus comparison +# Build corpus comparison -Select **Actions → Compare build corpus → Run workflow**. Choose a baseline commit and a candidate commit from this repository. The candidate defaults to the selected workflow revision. Running a control with the same commit on both sides measures repeatability. The workflow runs only on manual dispatch. +**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. Crashes and incomplete runs fail the check. 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. 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. From 0ac1638db2c8bbd27791c25c8b78f433f1d1d16e Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 16:02:18 -0800 Subject: [PATCH 04/11] Link corpus examples and failed builds to verified exports and fixtures --- .github/workflows/buildtest.yml | 6 ++++ spec/corpus/README.md | 5 ++- spec/corpus/link_summary.py | 63 +++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 spec/corpus/link_summary.py diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 64f39fee994..05738e49c87 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -104,6 +104,12 @@ jobs: with: key: ${{ steps.inputs.outputs.key }} path: ${{ runner.temp }}/corpus-base + - name: Link reported builds + if: ${{ !cancelled() }} + run: | + if test -s "$RUNNER_TEMP/corpus-results/summary.md"; then + python3 harness/spec/corpus/link_summary.py "$RUNNER_TEMP/corpus-results/summary.md" "$RUNNER_TEMP/corpus.json" harness "$GITHUB_REPOSITORY" "$(git -C harness rev-parse HEAD)" + fi - name: Summarize if: ${{ !cancelled() }} run: | diff --git a/spec/corpus/README.md b/spec/corpus/README.md index ba8bb9542fc..77361fb43bd 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -6,7 +6,7 @@ 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. -The check fails for import errors, missing outputs, aborted calculations and incomplete comparisons. A crash report identifies the revision side, build hash and saved corpus criteria. Remaining inputs in that batch resume in a fresh PoB process. The summary compares saved player and minion stats and additional scalar numeric and boolean outputs. Enable **strict** to fail on any stat difference. Timing and saved-XML changes are informational. Download **build-diff-output** for the per-build reports. +The check fails for import errors, missing outputs, aborted calculations and incomplete comparisons. A crash report identifies the revision side, build hash and saved corpus criteria. Remaining inputs in that batch resume in a fresh PoB process. The summary compares saved player and minion stats and additional scalar numeric and boolean outputs. Enable **strict** to fail on any stat difference. Timing and saved-XML changes are informational. Example and failure identifiers link to PoB.codes when its raw endpoint serves the tested export. Checked-in fixtures link to the XML at the harness commit on GitHub. An unavailable export keeps its plain identifier. Download **build-diff-output** for the per-build reports. 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. @@ -26,5 +26,8 @@ docker run --rm --network none --user "$(id -u):$(id -g)" \ -v "$run/corpus.json:/corpus.json:ro" -v "$run/results:/results" -v "$run/baseline:/baseline" \ -e BASE_SHA="$(git -C "$BASE" rev-parse HEAD)" -e CANDIDATE_SHA="$(git -C "$CANDIDATE" rev-parse HEAD)" \ pob-corpus sh /harness/spec/corpus/run.sh +# Use the GitHub repository that contains this harness commit. +python3 spec/corpus/link_summary.py "$run/results/summary.md" "$run/corpus.json" . \ + PathOfBuildingCommunity/PathOfBuilding "$(git rev-parse HEAD)" cat "$run/results/summary.md" ``` diff --git a/spec/corpus/link_summary.py b/spec/corpus/link_summary.py new file mode 100644 index 00000000000..ba909c442de --- /dev/null +++ b/spec/corpus/link_summary.py @@ -0,0 +1,63 @@ +"""Link examples and failed inputs after the offline calculation has finished.""" + +import base64 +import hashlib +import json +import re +import sys +from functools import lru_cache +from http.client import HTTPException +from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import urlopen + + +def link_summary(report, corpus, harness, repository, revision): + entries = {} + for build in json.loads(corpus.read_bytes())["builds"]: + digest = build["sha256"] + entries[digest] = build + prefix = digest[:12] + entries[prefix] = build if prefix not in entries else None + fixtures = { + "fixture-" + path.stem.replace(" ", "-"): path.relative_to(harness).as_posix() + for path in (harness / "spec/TestBuilds").rglob("*.xml") + } + + @lru_cache(None) + def link(name): + if name in fixtures: + return f"[{name}](https://github.com/{repository}/blob/{revision}/{quote(fixtures[name])})" + build = entries.get(name) + if build: + code = build["code"].encode("ascii") + token = base64.urlsafe_b64encode(hashlib.sha1(code).digest()).decode() + for length in (11, 20): + build_id = token[:length] + try: + with urlopen(f"https://api.pob.codes/{build_id}/raw", timeout=5) as response: + if response.read(len(code) + 2).rstrip(b"\r\n") == code: + suffix = "0" if build_id.endswith("_") else "" + return f"[{name}](https://pob.codes/b/{build_id}{suffix})" + except HTTPError as error: + if error.code != 404: + break + except (OSError, HTTPException): + break + return name + + lines = report.read_text(encoding="utf-8").splitlines(keepends=True) + for i, line in enumerate(lines): + if line.startswith("| "): + cells = line.split(" | ") + if len(cells) == 5: + cells[2] = link(cells[2]) + lines[i] = " | ".join(cells) + elif match := re.match(r"^(Base|Candidate): (\S+) \(exit ", line): + lines[i] = line[:match.start(2)] + link(match[2]) + line[match.end(2):] + report.write_text("".join(lines), encoding="utf-8") + + +if __name__ == "__main__": + link_summary(*(Path(arg) for arg in sys.argv[1:4]), *sys.argv[4:]) From 090ea54aa432b12c56daec0a39612670af1c6d37 Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 16:19:08 -0800 Subject: [PATCH 05/11] Show failed builds and stat changes together in one release report --- .github/workflows/buildtest.yml | 40 +++-- spec/corpus/BuildSummary.lua | 66 -------- spec/corpus/Calculate.lua | 4 +- spec/corpus/DiffOutput.lua | 69 +++----- spec/corpus/DiffRuntime.lua | 11 -- spec/corpus/README.md | 33 +++- spec/corpus/batch.sh | 13 +- spec/corpus/link_summary.py | 63 -------- spec/corpus/report.py | 269 ++++++++++++++++++++++++++++++++ spec/corpus/run.sh | 42 ++--- 10 files changed, 368 insertions(+), 242 deletions(-) delete mode 100644 spec/corpus/BuildSummary.lua delete mode 100644 spec/corpus/DiffRuntime.lua delete mode 100644 spec/corpus/link_summary.py create mode 100644 spec/corpus/report.py diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 05738e49c87..328b1461d6e 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -47,7 +47,7 @@ jobs: tag=$(gh api repos/PathOfBuildingCommunity/PathOfBuilding/releases/latest --jq .tag_name) test -n "$tag" echo "ref=refs/tags/$tag" >> "$GITHUB_OUTPUT" - echo "Stable baseline: \`$tag\`" >> "$GITHUB_STEP_SUMMARY" + echo "STABLE_TAG=$tag" >> "$GITHUB_ENV" - name: Check out baseline uses: actions/checkout@v4 with: @@ -77,7 +77,6 @@ jobs: echo "key=corpus-v1-$base-$digest-$tools" >> "$GITHUB_OUTPUT" echo "BASE_SHA=$base" >> "$GITHUB_ENV" echo "CANDIDATE_SHA=$candidate" >> "$GITHUB_ENV" - echo "Corpus response SHA-256: $digest" >> "$GITHUB_STEP_SUMMARY" - name: Restore calculated baseline id: cache uses: actions/cache/restore@v4 @@ -104,24 +103,31 @@ jobs: with: key: ${{ steps.inputs.outputs.key }} path: ${{ runner.temp }}/corpus-base - - name: Link reported builds - if: ${{ !cancelled() }} - run: | - if test -s "$RUNNER_TEMP/corpus-results/summary.md"; then - python3 harness/spec/corpus/link_summary.py "$RUNNER_TEMP/corpus-results/summary.md" "$RUNNER_TEMP/corpus.json" harness "$GITHUB_REPOSITORY" "$(git -C harness rev-parse HEAD)" - fi - - name: Summarize + - name: Write the build comparison report if: ${{ !cancelled() }} + env: + STRICT: ${{ inputs.strict }} + BASE_REPO: ${{ inputs.base_ref && github.repository || 'PathOfBuildingCommunity/PathOfBuilding' }} run: | - if test -s "$RUNNER_TEMP/corpus-results/summary.md"; then - cat "$RUNNER_TEMP/corpus-results/summary.md" >> "$GITHUB_STEP_SUMMARY" - else - echo 'Comparison did not complete. See the failed step.' >> "$GITHUB_STEP_SUMMARY" - fi + 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/*.md - ${{ runner.temp }}/corpus-results/*.txt + 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 diff --git a/spec/corpus/BuildSummary.lua b/spec/corpus/BuildSummary.lua deleted file mode 100644 index 26efc75a408..00000000000 --- a/spec/corpus/BuildSummary.lua +++ /dev/null @@ -1,66 +0,0 @@ --- Summarize the existing stat report without changing which differences count. -local function summarize(lines, compared, baseRef, headRef) - local builds, stats, build = {}, {}, nil - local changedBuilds, changedValues = 0, 0 - for line in lines do - build = line:match("^## Output Diff for (.+)%.build$") or build - local stat, actor = line:match("^(.-) Mismatch in (%a+) outputs:") - if stat then - assert(build, "Stat difference has no build name") - local head = assert(lines():match("^%s*head Output: (.*)$"), "Missing head value") - local base = assert(lines():match("^%s*dev Output: (.*)$"), "Missing base value") - if not builds[build] then - builds[build] = true - changedBuilds = changedBuilds + 1 - end - local key = actor .. "." .. stat - local entry = stats[key] or { key = key, count = 0, build = build, base = base, head = head } - entry.count = entry.count + 1 - stats[key] = entry - changedValues = changedValues + 1 - end - end - local function escape(value) - return tostring(value):gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub("|", "|"):gsub("`", "`") - end - local rows = {} - for _, entry in pairs(stats) do rows[#rows + 1] = entry end - -- Put common player results first; this affects presentation only. - local priority = { ["player.Life"] = 1, ["player.Mana"] = 2, ["player.EnergyShield"] = 3, - ["player.TotalDPS"] = 4, ["player.CombinedDPS"] = 5, ["player.FullDPS"] = 6 } - table.sort(rows, function(a, b) - local ap, bp = priority[a.key] or 7, priority[b.key] or 7 - if ap ~= bp then return ap < bp end - if a.count ~= b.count then return a.count > b.count end - return a.key < b.key - end) - local output = { - "## Build comparison summary", "", - changedBuilds > 0 and "**Changes found: review required.**" or "**No calculated-stat differences found.**", "", - string.format("Compared **%d builds**. **%d builds** have calculated-stat differences (**%d changed values**).", compared, changedBuilds, changedValues), "", - "Base: `" .. escape(baseRef) .. "`. Candidate: `" .. escape(headRef) .. "`.", "", - } - if #rows > 0 then - output[#output + 1] = string.format("Showing %d of %d changed stats, with one example for each. Common player results appear first; other stats are ordered by affected build count.", math.min(25, #rows), #rows) - output[#output + 1] = "" - output[#output + 1] = "| Stat | Affected builds | Example build | Before | After |" - output[#output + 1] = "| --- | ---: | --- | ---: | ---: |" - for index = 1, math.min(25, #rows) do - local entry = rows[index] - local name = entry.build - if #name == 64 and name:match("^%x+$") then name = name:sub(1, 12) end - output[#output + 1] = string.format("| %s | %d | %s | %s | %s |", escape(entry.key), entry.count, escape(name), escape(entry.base), escape(entry.head)) - end - output[#output + 1] = "" - end - output[#output + 1] = "Strict mode fails on calculated-stat differences. Saved XML and timing differences are informational." - output[#output + 1] = "" - output[#output + 1] = "Full differences are in the **build-diff-output** artifact. API build identifiers above are shortened to 12 characters for searching the full report." - return table.concat(output, "\n"), changedBuilds -end - -if arg and arg[0]:match("BuildSummary%.lua$") then - local output = summarize(io.lines(assert(arg[1])), assert(tonumber(arg[2])), assert(arg[3]), assert(arg[4])) - print(output) -end -return summarize diff --git a/spec/corpus/Calculate.lua b/spec/corpus/Calculate.lua index e1707b8ab2a..0f57c694f17 100644 --- a/spec/corpus/Calculate.lua +++ b/spec/corpus/Calculate.lua @@ -32,10 +32,11 @@ 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() - write(cursorPath, tostring(index)) io.stderr:write("Loading ", name, "\n") local start = os.clock() local document, err = common.xml.ParseXML(xml) @@ -44,6 +45,7 @@ for name in io.lines(batch) do 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)) diff --git a/spec/corpus/DiffOutput.lua b/spec/corpus/DiffOutput.lua index 949c36ba44e..9a261162e8d 100644 --- a/spec/corpus/DiffOutput.lua +++ b/spec/corpus/DiffOutput.lua @@ -23,52 +23,27 @@ local function buildOutputMap(filecontent) return playerOutput, minionOutput end -local headhnd = io.open(arg[1], "r") -local devhnd = io.open(arg[2], "r") +local function readBuild(path) + local file = assert(io.open(path, "r")) + local player, minion = buildOutputMap(file:read("*a")) + file:close() + return player, minion +end -if headhnd and devhnd then - local playerHEADOutput, minionHEADOutput = buildOutputMap(headhnd:read("*a")) - local playerDEVOutput, minionDEVOutput = buildOutputMap(devhnd:read("*a")) - local mismatch = {} - local mismatchFound = false - for key, val in pairs(playerHEADOutput) do - if not playerDEVOutput[key] or playerDEVOutput[key] ~= val then - mismatch[key] = {devOutput = playerDEVOutput[key], headOutput = val} - mismatchFound = true - end - end - for key, val in pairs(playerDEVOutput) do - if not mismatch[key] and (not playerHEADOutput[key] or playerHEADOutput[key] ~= val) then - mismatch[key] = {headOutput = playerHEADOutput[key], devOutput = val} - mismatchFound = true - end - end - for key, val in pairs(mismatch) do - print(key .. " Mismatch in player outputs: ") - print("\t" .."head Output: " .. tostring(val["headOutput"])) - print("\t" .."dev Output: " .. tostring(val["devOutput"])) - end - mismatch = {} - for key, val in pairs(minionHEADOutput) do - if not minionDEVOutput[key] or minionDEVOutput[key] ~= val then - mismatch[key] = {devOutput = minionDEVOutput[key], headOutput = val} - mismatchFound = true - end - end - for key, val in pairs(minionDEVOutput) do - if not mismatch[key] and (not minionHEADOutput[key] or minionHEADOutput[key] ~= val) then - mismatch[key] = {headOutput = minionHEADOutput[key], devOutput = val} - mismatchFound = true - end - end - for key, val in pairs(mismatch) do - print(key .. " Mismatch in minion outputs: ") - print("\t" .."head Output: " .. tostring(val["headOutput"])) - print("\t" .."dev Output: " .. tostring(val["devOutput"])) - end - if mismatchFound then - os.exit(1) -- Make the exit codes of the script match the exit codes of the diff utility +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 -else - os.exit(2) -end \ No newline at end of file +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/DiffRuntime.lua b/spec/corpus/DiffRuntime.lua deleted file mode 100644 index de6be37b9c4..00000000000 --- a/spec/corpus/DiffRuntime.lua +++ /dev/null @@ -1,11 +0,0 @@ -local function runtime(path) - local file = assert(io.open(path, "r")) - local value = assert(tonumber(file:read("*a"))) - file:close() - return value -end -local head, base = runtime(arg[1]), runtime(arg[2]) -if base > 0 and math.abs(head / base - 1) >= 0.1 then - print(string.format("%s CPU time: %.1f ms -> %.1f ms (%+.0f%%)", arg[3], base, head, (head / base - 1) * 100)) - os.exit(1) -end diff --git a/spec/corpus/README.md b/spec/corpus/README.md index 77361fb43bd..5447af872d7 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -6,7 +6,23 @@ 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. -The check fails for import errors, missing outputs, aborted calculations and incomplete comparisons. A crash report identifies the revision side, build hash and saved corpus criteria. Remaining inputs in that batch resume in a fresh PoB process. The summary compares saved player and minion stats and additional scalar numeric and boolean outputs. Enable **strict** to fail on any stat difference. Timing and saved-XML changes are informational. Example and failure identifiers link to PoB.codes when its raw endpoint serves the tested export. Checked-in fixtures link to the XML at the harness commit on GitHub. An unavailable export keeps its plain identifier. Download **build-diff-output** for the per-build reports. +## Reading the result + +Open the job summary in GitHub Actions. The first line gives the result. A failed build appears first, with the revision that failed, the build link, and the error PoB returned when available. If a build failed on the baseline alone, the candidate finished that build but a comparison was impossible. + +**Stat changes.** Each affected build 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. Failure to load, calculate, save, or complete the comparison always fails it. + +**Time and saved files.** CPU time measures the work spent parsing, loading and calculating a build. It excludes saving. The report lists measurements that differ by at least 10% in either direction. A single sample can vary between runs. A saved XML difference means PoB wrote different output for the same input. This includes its calculated stats. Both observations 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. | +| `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. @@ -21,13 +37,16 @@ run=$(mktemp -d) mkdir "$run/results" "$run/baseline" curl -fsS --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 +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 BASE_SHA="$(git -C "$BASE" rev-parse HEAD)" -e CANDIDATE_SHA="$(git -C "$CANDIDATE" rev-parse HEAD)" \ - pob-corpus sh /harness/spec/corpus/run.sh -# Use the GitHub repository that contains this harness commit. -python3 spec/corpus/link_summary.py "$run/results/summary.md" "$run/corpus.json" . \ - PathOfBuildingCommunity/PathOfBuilding "$(git rev-parse HEAD)" -cat "$run/results/summary.md" + -e STRICT 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 index eff68260522..0bdc57cc954 100644 --- a/spec/corpus/batch.sh +++ b/spec/corpus/batch.sh @@ -4,13 +4,17 @@ 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" - if luajit /harness/spec/corpus/Calculate.lua "$batch" "$cursor" "$out" "$next"; then + 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. @@ -20,7 +24,8 @@ while [ "$next" -le "$count" ]; do fi index=$(cat "$cursor") name=$(sed -n "${index}p" "$batch") - tags=$(cat "/results/inputs/$name.tags") - printf '%s (exit %s) %s\n' "$name" "$status" "$tags" | tee "$out/$name.error" >&2 + 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/link_summary.py b/spec/corpus/link_summary.py deleted file mode 100644 index ba909c442de..00000000000 --- a/spec/corpus/link_summary.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Link examples and failed inputs after the offline calculation has finished.""" - -import base64 -import hashlib -import json -import re -import sys -from functools import lru_cache -from http.client import HTTPException -from pathlib import Path -from urllib.error import HTTPError -from urllib.parse import quote -from urllib.request import urlopen - - -def link_summary(report, corpus, harness, repository, revision): - entries = {} - for build in json.loads(corpus.read_bytes())["builds"]: - digest = build["sha256"] - entries[digest] = build - prefix = digest[:12] - entries[prefix] = build if prefix not in entries else None - fixtures = { - "fixture-" + path.stem.replace(" ", "-"): path.relative_to(harness).as_posix() - for path in (harness / "spec/TestBuilds").rglob("*.xml") - } - - @lru_cache(None) - def link(name): - if name in fixtures: - return f"[{name}](https://github.com/{repository}/blob/{revision}/{quote(fixtures[name])})" - build = entries.get(name) - if build: - code = build["code"].encode("ascii") - token = base64.urlsafe_b64encode(hashlib.sha1(code).digest()).decode() - for length in (11, 20): - build_id = token[:length] - try: - with urlopen(f"https://api.pob.codes/{build_id}/raw", timeout=5) as response: - if response.read(len(code) + 2).rstrip(b"\r\n") == code: - suffix = "0" if build_id.endswith("_") else "" - return f"[{name}](https://pob.codes/b/{build_id}{suffix})" - except HTTPError as error: - if error.code != 404: - break - except (OSError, HTTPException): - break - return name - - lines = report.read_text(encoding="utf-8").splitlines(keepends=True) - for i, line in enumerate(lines): - if line.startswith("| "): - cells = line.split(" | ") - if len(cells) == 5: - cells[2] = link(cells[2]) - lines[i] = " | ".join(cells) - elif match := re.match(r"^(Base|Candidate): (\S+) \(exit ", line): - lines[i] = line[:match.start(2)] + link(match[2]) + line[match.end(2):] - report.write_text("".join(lines), encoding="utf-8") - - -if __name__ == "__main__": - link_summary(*(Path(arg) for arg in sys.argv[1:4]), *sys.argv[4:]) diff --git a/spec/corpus/report.py b/spec/corpus/report.py new file mode 100644 index 00000000000..0a3b574e6c3 --- /dev/null +++ b/spec/corpus/report.py @@ -0,0 +1,269 @@ +"""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 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()) + stats = defaultdict(list) + for key, actor, stat, before, after in rows(results / "stats.tsv"): + stats[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} + 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 = [] + for key, before, after in rows(results / "timing.tsv"): + a, b = float(before), float(after) + if a > 0 and abs(b - a) >= a * 0.1: + timings.append((key, a, b)) + timings.sort(key=lambda row: -abs(row[2] - row[1])) + builds = Builds(results, corpus, harness, repo, revision, ids, + [*(r[1] for r in failures), *stats, *(r[0] for r in timings), *xml]) + strict = os.environ.get("STRICT", "false").lower() == "true" + changed = sum(map(len, stats.values())) + verdict = "Failed" if failures or (strict and changed) else "Passed" + if failures: + sides = {row[0] for row in failures} + if len(sides) == 1: + title = f"{next(iter(sides)).capitalize()} failed on {number(len(failed), 'build')}" + else: + title = f"PoB failed on {number(len(failed), 'build')}" + elif changed: + title = f"Stats changed for {number(len(stats), 'build')}" + 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 failures: + lines += ["## Builds that failed", ""] + for side, key, status, stage, reason in failures: + lines += [f"- {builds.link(key)} · The **{side}** stopped while {safe(stage)} this build (exit {safe(status)}).", + " - " + (safe(reason) if reason else "PoB did not return an error message. See the calculation log.")] + lines.append("") + if changed: + lines += [f"{number(changed, 'stat value')} changed across {number(len(stats), 'build')}. " + + ("Strict mode makes a stat change fail this run." if strict else + "Stat changes are reported for review and do not fail this run."), ""] + elif failures: + lines += [f"Stats matched for all {compared:,} builds that finished.", ""] if compared else ["No build produced results on both revisions.", ""] + if len(stats) > 5: + examples = {} + for key, changes in stats.items(): + for actor, stat, before, after in changes: + examples.setdefault((actor, stat), (key, before, after)) + frequency = Counter((a, s) for entries in stats.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 += ["## Stats 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) + [""] + overview = lines.copy() + if changed: + lines += ["## Stat changes by build", "", "Before is the baseline. After is the candidate. " + "Values are rounded for reading. The accompanying CSV keeps the exact PoB values.", ""] + 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"]) + for key in sorted(stats, key=lambda k: (-len(stats[k]), builds.names[k])): + lines += [f"### {builds.link(key)}", ""] + changes = [] + for actor, stat, before, after in sorted(stats[key]): + writer.writerow([builds.names[key], key, builds.urls.get(key, ""), actor, stat, before, after]) + changes.append((actor, stat_name(stat), *values(before, after))) + lines += table(["Whose stat", "Stat", "Before", "After"], changes) + [""] + + if timings or xml: + lines += ["## Other observations", "", "These observations do not affect the result.", ""] + if timings: + lines += ["### Time spent loading and calculating", "", + "CPU time measures processor work for one build, from reading its XML into PoB through calculating its stats. " + "The measurement ends before saving.", + "Each row is a single measurement that changed by at least 10%. Repeat the run to check a suspected slowdown.", ""] + lines += table(["Build", "Baseline", "Candidate", "Change"], + [(builds.link(k), f"{a:,.1f} ms", f"{b:,.1f} ms", f"{100*(b/a-1):+.1f}%") for k, a, b in timings]) + [""] + 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"] + 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"]) + for key in ids: + outcome = "Failed to compare" if key in failed else "Stats changed" if key in stats else "Stats matched" + writer.writerow([builds.names[key], key, builds.urls.get(key, ""), outcome, ", ".join(builds.tags.get(key, []))]) + 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 failed") + 2 + end = start + 2 * len(failures) + shortened = shortened[:start + 10] + [f"Showing 5 of {number(len(failures), 'failures')}."] + shortened[end:] + shortened += ["", f"Timing changed by at least 10% for {number(len(timings), 'build')}. " + 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 all timing and saved XML observations.", ""] + preview.write_text("\n".join(shortened + metadata) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + write_report(*(Path(arg) for arg in sys.argv[1:4]), *sys.argv[4:]) diff --git a/spec/corpus/run.sh b/spec/corpus/run.sh index 531979c54e4..6c3971cfc0d 100644 --- a/spec/corpus/run.sh +++ b/spec/corpus/run.sh @@ -40,41 +40,31 @@ else fi calculate /candidate "$results/candidate" -: > "$results/stat-diffs.txt" -: > "$results/import-errors.txt" -: > "$results/other-diffs.txt" +# 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 - if [ -f "$base.error" ]; then printf 'Base: ' >> "$results/import-errors.txt"; cat "$base.error" >> "$results/import-errors.txt"; fi - if [ -f "$head.error" ]; then printf 'Candidate: ' >> "$results/import-errors.txt"; cat "$head.error" >> "$results/import-errors.txt"; fi + 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 - if output=$(luajit "$tools/DiffOutput.lua" "$head.build" "$base.build"); then : - else - status=$? - [ "$status" -eq 1 ] || exit "$status" - printf '## Output Diff for %s.build\n%s\n' "$name" "$output" >> "$results/stat-diffs.txt" - 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 "Saved XML changed: $name" >> "$results/other-diffs.txt"; fi - if output=$(luajit "$tools/DiffRuntime.lua" "$head.time" "$base.time" "$name"); then : - else - status=$? - [ "$status" -eq 1 ] || exit "$status" - printf '%s\n' "$output" >> "$results/other-diffs.txt" - fi + 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" -luajit "$tools/BuildSummary.lua" "$results/stat-diffs.txt" "$compared" "$BASE_SHA" "$CANDIDATE_SHA" > "$results/summary.md" -cat "$results/snapshot.txt" >> "$results/summary.md" -if [ -s "$results/import-errors.txt" ]; then - printf '\n**Import or calculation failures**\n\n' >> "$results/summary.md" - head -n 15 "$results/import-errors.txt" >> "$results/summary.md" - exit 1 -fi +printf '%s\n' "$compared" > "$results/compared.txt" test "$compared" -eq "$expected" -if [ "${STRICT:-false}" = true ] && [ -s "$results/stat-diffs.txt" ]; then exit 1; fi +if [ "${STRICT:-false}" = true ] && [ -s "$results/stats.tsv" ]; then exit 1; fi From 031980874d6dd2fc5d3038f770040865efb25c89 Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 16:20:02 -0800 Subject: [PATCH 06/11] Clarify which revision finished each failed build and normalize report encoding --- .github/workflows/buildtest.yml | 2 +- spec/corpus/report.py | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 328b1461d6e..c896aee3110 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -125,7 +125,7 @@ jobs: 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 '# 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 diff --git a/spec/corpus/report.py b/spec/corpus/report.py index 0a3b574e6c3..ddaaddf8354 100644 --- a/spec/corpus/report.py +++ b/spec/corpus/report.py @@ -165,7 +165,7 @@ def write_report(results, corpus_file, harness, repo, revision): if failures: sides = {row[0] for row in failures} if len(sides) == 1: - title = f"{next(iter(sides)).capitalize()} failed on {number(len(failed), 'build')}" + title = f"{next(iter(sides)).capitalize()} stopped on {number(len(failed), 'build')}" else: title = f"PoB failed on {number(len(failed), 'build')}" elif changed: @@ -179,9 +179,14 @@ def write_report(results, corpus_file, harness, repo, revision): if failures: lines += ["## Builds that failed", ""] + by_build = defaultdict(set) + for side, key, *_ in failures: + by_build[key].add(side) for side, key, status, stage, reason in failures: - lines += [f"- {builds.link(key)} · The **{side}** stopped while {safe(stage)} this build (exit {safe(status)}).", - " - " + (safe(reason) if reason else "PoB did not return an error message. See the calculation log.")] + 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 changed: lines += [f"{number(changed, 'stat value')} changed across {number(len(stats), 'build')}. " @@ -207,7 +212,7 @@ def write_report(results, corpus_file, harness, repo, revision): overview = lines.copy() if changed: lines += ["## Stat changes by build", "", "Before is the baseline. After is the candidate. " - "Values are rounded for reading. The accompanying CSV keeps the exact PoB values.", ""] + "Values are rounded for reading. See **stat-changes.csv** for exact values.", ""] 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"]) From e536aad1aabe0fc8348277354950efec61dfff31 Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 19:46:59 -0800 Subject: [PATCH 07/11] Separate stat changes and summarize corpus timing --- .github/workflows/buildtest.yml | 4 +- spec/corpus/README.md | 7 +- spec/corpus/report.py | 156 +++++++++++++++++++++----------- 3 files changed, 112 insertions(+), 55 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index c896aee3110..697d280e9a6 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -15,7 +15,7 @@ on: description: Optional SHA-256 of the exact corpus response type: string strict: - description: Fail on calculated-stat differences + description: Fail when a stat changes value or is added or removed default: false type: boolean @@ -125,7 +125,7 @@ jobs: 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 '# 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 diff --git a/spec/corpus/README.md b/spec/corpus/README.md index 5447af872d7..83846b2e8c8 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -10,9 +10,11 @@ Each run fetches one [PoB Codes corpus](https://api.pob.codes/test-builds/corpus Open the job summary in GitHub Actions. The first line gives the result. A failed build appears first, with the revision that failed, the build link, and the error PoB returned when available. If a build failed on the baseline alone, the candidate finished that build but a comparison was impossible. -**Stat changes.** Each affected build 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. Failure to load, calculate, save, or complete the comparison always fails it. +**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. Failure to load, calculate, save, or complete the comparison always fails it. -**Time and saved files.** CPU time measures the work spent parsing, loading and calculating a build. It excludes saving. The report lists measurements that differ by at least 10% in either direction. A single sample can vary between runs. A saved XML difference means PoB wrote different output for the same input. This includes its calculated stats. Both observations are informational. +**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. A cached baseline can come from an earlier 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. @@ -20,6 +22,7 @@ Open the job summary in GitHub Actions. The first line gives the result. A faile | --- | --- | | `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. diff --git a/spec/corpus/report.py b/spec/corpus/report.py index ddaaddf8354..67e6a99c4c2 100644 --- a/spec/corpus/report.py +++ b/spec/corpus/report.py @@ -14,6 +14,7 @@ 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 @@ -132,7 +133,7 @@ def write_report(results, corpus_file, harness, repo, revision): summary = output / "summary.md" preview = results / "actions-summary.md" if not (results / "compared.txt").is_file(): - message = ("# Failed · Comparison did not finish\n\n" + 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") @@ -143,24 +144,21 @@ def write_report(results, corpus_file, harness, repo, revision): corpus = json.loads(raw_corpus) ids = (results / "builds.txt").read_text().splitlines() compared = int((results / "compared.txt").read_text()) - stats = defaultdict(list) + 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"): - stats[key].append((actor, stat, before, after)) + 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} 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 = [] - for key, before, after in rows(results / "timing.tsv"): - a, b = float(before), float(after) - if a > 0 and abs(b - a) >= a * 0.1: - timings.append((key, a, b)) - timings.sort(key=lambda row: -abs(row[2] - row[1])) + timings = rows(results / "timing.tsv") builds = Builds(results, corpus, harness, repo, revision, ids, - [*(r[1] for r in failures), *stats, *(r[0] for r in timings), *xml]) + [*(r[1] for r in failures), *existing, *removed, *added, *xml, *(r[0] for r in timings)]) strict = os.environ.get("STRICT", "false").lower() == "true" - changed = sum(map(len, stats.values())) + changed = any(categories.values()) verdict = "Failed" if failures or (strict and changed) else "Passed" if failures: sides = {row[0] for row in failures} @@ -168,15 +166,25 @@ def write_report(results, corpus_file, harness, repo, revision): title = f"{next(iter(sides)).capitalize()} stopped on {number(len(failed), 'build')}" else: title = f"PoB failed on {number(len(failed), 'build')}" - elif changed: - title = f"Stats changed for {number(len(stats), 'build')}" + 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}", "", + 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 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 failed", ""] by_build = defaultdict(set) @@ -185,56 +193,88 @@ def write_report(results, corpus_file, harness, repo, revision): 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}", + 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 changed: - lines += [f"{number(changed, 'stat value')} changed across {number(len(stats), 'build')}. " - + ("Strict mode makes a stat change fail this run." if strict else - "Stat changes are reported for review and do not fail this run."), ""] - elif failures: - lines += [f"Stats matched for all {compared:,} builds that finished.", ""] if compared else ["No build produced results on both revisions.", ""] - if len(stats) > 5: + lines += [("Strict mode 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 stats.items(): + 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 stats.values() for a, s, _, _ in entries) + 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 += ["## Stats that changed on the most builds", "", + 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.") + lines += ["Timing varies between runs and does not affect the result. See **timings.csv** for individual measurements.", ""] overview = lines.copy() - if changed: - lines += ["## Stat changes by build", "", "Before is the baseline. After is the candidate. " + 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"]) - for key in sorted(stats, key=lambda k: (-len(stats[k]), builds.names[k])): - lines += [f"### {builds.link(key)}", ""] - changes = [] - for actor, stat, before, after in sorted(stats[key]): - writer.writerow([builds.names[key], key, builds.urls.get(key, ""), actor, stat, before, after]) - changes.append((actor, stat_name(stat), *values(before, after))) - lines += table(["Whose stat", "Stat", "Before", "After"], changes) + [""] + 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 timings or xml: - lines += ["## Other observations", "", "These observations do not affect the result.", ""] - if timings: - lines += ["### Time spent loading and calculating", "", - "CPU time measures processor work for one build, from reading its XML into PoB through calculating its stats. " - "The measurement ends before saving.", - "Each row is a single measurement that changed by at least 10%. Repeat the run to check a suspected slowdown.", ""] - lines += table(["Build", "Baseline", "Candidate", "Change"], - [(builds.link(k), f"{a:,.1f} ms", f"{b:,.1f} ms", f"{100*(b/a-1):+.1f}%") for k, a, b in timings]) + [""] if xml: - lines += ["### Builds that saved differently", "", + 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] + [""] @@ -250,10 +290,18 @@ def write_report(results, corpus_file, harness, repo, revision): 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"]) + writer.writerow(["Build", "Build ID", "Build URL", "Result", "Corpus criteria", "Existing values changed", "Stats added", "Stats removed"]) for key in ids: - outcome = "Failed to compare" if key in failed else "Stats changed" if key in stats else "Stats matched" - writer.writerow([builds.names[key], key, builds.urls.get(key, ""), outcome, ", ".join(builds.tags.get(key, []))]) + if key in failed: + outcome = "Failed to compare" + 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: @@ -263,12 +311,18 @@ def write_report(results, corpus_file, harness, repo, revision): start = shortened.index("## Builds that failed") + 2 end = start + 2 * len(failures) shortened = shortened[:start + 10] + [f"Showing 5 of {number(len(failures), 'failures')}."] + shortened[end:] - shortened += ["", f"Timing changed by at least 10% for {number(len(timings), 'build')}. " - f"Saved XML differed for {number(len(xml), 'build')}."] + 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 all timing and saved XML observations.", ""] + "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__": - write_report(*(Path(arg) for arg in sys.argv[1:4]), *sys.argv[4:]) + 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) From bbb42f4938100ea30187330ddd95ce78bbe1078b Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 22:49:45 -0800 Subject: [PATCH 08/11] Refine corpus failure policy and workflow checks --- .github/workflows/buildtest.yml | 8 +++- .github/workflows/release.yml | 4 +- spec/corpus/README.md | 11 ++--- spec/corpus/report.py | 38 ++++++++++------ spec/corpus/run.sh | 3 +- spec/corpus/test_report.py | 78 +++++++++++++++++++++++++++++++++ spec/corpus/test_verdict.sh | 31 +++++++++++++ spec/corpus/verdict.sh | 11 +++++ 8 files changed, 161 insertions(+), 23 deletions(-) create mode 100644 spec/corpus/test_report.py create mode 100644 spec/corpus/test_verdict.sh create mode 100644 spec/corpus/verdict.sh diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 697d280e9a6..73ea4660eb8 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -48,6 +48,10 @@ jobs: 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: @@ -67,7 +71,8 @@ jobs: EXPECTED: ${{ inputs.expected_digest }} run: | mkdir -p "$RUNNER_TEMP/corpus-results" "$RUNNER_TEMP/corpus-base" - curl --fail --silent --show-error --max-time 60 --max-filesize 16777216 \ + 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 @@ -108,6 +113,7 @@ jobs: env: STRICT: ${{ inputs.strict }} 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)" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 595f18914ef..72ddde6164a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,7 +17,7 @@ jobs: 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 @@ -38,7 +38,7 @@ jobs: .github/tweak_changelogs.sh "v${{ github.event.inputs.releaseVersion }}" - name: Create Pull Request id: prepare - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v7 with: draft: true title: Release ${{ github.event.inputs.releaseVersion }} diff --git a/spec/corpus/README.md b/spec/corpus/README.md index 83846b2e8c8..417d70ada7a 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -1,6 +1,6 @@ # 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. Crashes and incomplete runs fail the check. The workflow does not enforce a merge or publication policy. +**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. @@ -8,11 +8,11 @@ Each run fetches one [PoB Codes corpus](https://api.pob.codes/test-builds/corpus ## Reading the result -Open the job summary in GitHub Actions. The first line gives the result. A failed build appears first, with the revision that failed, the build link, and the error PoB returned when available. If a build failed on the baseline alone, the candidate finished that build but a comparison was impossible. +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. 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. Failure to load, calculate, save, or complete the comparison always fails it. +**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. Failure of the candidate to load, calculate, save, or complete always fails it. 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. A cached baseline can come from an earlier run. Garbage collection can charge work from earlier builds to a later build. Timing never changes the verdict, including in strict mode. +**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. @@ -38,7 +38,8 @@ BASE=/absolute/path/to/base CANDIDATE=/absolute/path/to/candidate run=$(mktemp -d) mkdir "$run/results" "$run/baseline" -curl -fsS --max-filesize 16777216 https://api.pob.codes/test-builds/corpus -o "$run/corpus.json" +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 diff --git a/spec/corpus/report.py b/spec/corpus/report.py index 67e6a99c4c2..a7b8fabefa6 100644 --- a/spec/corpus/report.py +++ b/spec/corpus/report.py @@ -151,6 +151,8 @@ def write_report(results, corpus_file, harness, repo, revision): 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() @@ -159,13 +161,11 @@ def write_report(results, corpus_file, harness, repo, revision): [*(r[1] for r in failures), *existing, *removed, *added, *xml, *(r[0] for r in timings)]) strict = os.environ.get("STRICT", "false").lower() == "true" changed = any(categories.values()) - verdict = "Failed" if failures or (strict and changed) else "Passed" - if failures: - sides = {row[0] for row in failures} - if len(sides) == 1: - title = f"{next(iter(sides)).capitalize()} stopped on {number(len(failed), 'build')}" - else: - title = f"PoB failed on {number(len(failed), 'build')}" + verdict = "Failed" if candidate_failed or (strict and changed) 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: @@ -186,7 +186,7 @@ def write_report(results, corpus_file, harness, repo, revision): 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 failed", ""] + lines += ["## Builds that stopped", ""] by_build = defaultdict(set) for side, key, *_ in failures: by_build[key].add(side) @@ -196,6 +196,11 @@ def write_report(results, corpus_file, harness, repo, revision): 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 += ["Any candidate failure blocks 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 fails on any of the three types of difference." if strict else "Stat differences are advisory for this run."), ""] @@ -235,7 +240,11 @@ def write_report(results, corpus_file, harness, repo, revision): f"(median across {number(len(changes_pct), 'build')}).") else: lines.append("No builds had timing measurements with a positive baseline to compare.") - lines += ["Timing varies between runs and does not affect the result. See **timings.csv** for individual measurements.", ""] + 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. " @@ -285,15 +294,18 @@ def write_report(results, corpus_file, harness, repo, revision): 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"- 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 failed: - outcome = "Failed to compare" + 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: @@ -308,7 +320,7 @@ def write_report(results, corpus_file, harness, repo, revision): # GitHub caps job summaries at 1 MiB. The download always retains every finding. shortened = overview if len(failures) > 5: - start = shortened.index("## Builds that failed") + 2 + 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')}."] diff --git a/spec/corpus/run.sh b/spec/corpus/run.sh index 6c3971cfc0d..114c2ebc689 100644 --- a/spec/corpus/run.sh +++ b/spec/corpus/run.sh @@ -66,5 +66,4 @@ while IFS= read -r name; do compared=$((compared + 1)) done < "$results/builds.txt" printf '%s\n' "$compared" > "$results/compared.txt" -test "$compared" -eq "$expected" -if [ "${STRICT:-false}" = true ] && [ -s "$results/stats.tsv" ]; then exit 1; fi +sh "$tools/verdict.sh" "$results" "${STRICT:-false}" diff --git a/spec/corpus/test_report.py b/spec/corpus/test_report.py new file mode 100644 index 00000000000..0eafbe470da --- /dev/null +++ b/spec/corpus/test_report.py @@ -0,0 +1,78 @@ +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, 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(), + "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("Any candidate failure blocks the check", 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")) + + +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..91ccbc9f4e0 --- /dev/null +++ b/spec/corpus/test_verdict.sh @@ -0,0 +1,31 @@ +#!/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 + actual=0 + sh "$tools/verdict.sh" "$work" "$strict" || actual=$? + if [ "$actual" -ne "$expected" ]; then + echo "Expected status $expected, got $actual" >&2 + exit 1 + fi +} + +expect_status 0 false +printf 'baseline\tbuild\t1\tloading\tknown failure\n' > "$work/errors.tsv" +expect_status 0 false +printf 'candidate\tbuild\t1\tloading\tnew failure\n' > "$work/errors.tsv" +expect_status 1 false +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 +: > "$work/errors.tsv" +printf 'build\tPlayer\tLife\t100\t101\n' > "$work/stats.tsv" +expect_status 0 false +expect_status 1 true diff --git a/spec/corpus/verdict.sh b/spec/corpus/verdict.sh new file mode 100644 index 00000000000..1132e716d68 --- /dev/null +++ b/spec/corpus/verdict.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +results=$1 +strict=${2:-false} + +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 From e30cb7cebfaffd21e8538e512edbfd27dbf80fed Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 22:52:26 -0800 Subject: [PATCH 09/11] Link corpus workflow to public documentation --- .github/workflows/buildtest.yml | 1 + .github/workflows/release.yml | 1 + spec/corpus/README.md | 2 +- spec/corpus/test_verdict.sh | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 73ea4660eb8..b04993f3869 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -137,3 +137,4 @@ jobs: 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 72ddde6164a..d33d032b61d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,6 +49,7 @@ jobs: 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 diff --git a/spec/corpus/README.md b/spec/corpus/README.md index 417d70ada7a..f523e702624 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -4,7 +4,7 @@ **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. -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. +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 diff --git a/spec/corpus/test_verdict.sh b/spec/corpus/test_verdict.sh index 91ccbc9f4e0..15ecbf8ce82 100644 --- a/spec/corpus/test_verdict.sh +++ b/spec/corpus/test_verdict.sh @@ -1,6 +1,6 @@ #!/bin/sh set -eu -tools=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +tools=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) work=$(mktemp -d) trap 'rm -rf "$work"' EXIT : > "$work/errors.tsv" From 4ccba66086402cea18ef7bbe7417b4e4880df27b Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 23:12:56 -0800 Subject: [PATCH 10/11] Allow maintainers to override corpus verdicts --- .github/workflows/buildtest.yml | 8 +++++++- spec/corpus/README.md | 9 +++++---- spec/corpus/report.py | 13 ++++++++++--- spec/corpus/run.sh | 2 +- spec/corpus/test_report.py | 17 +++++++++++++++-- spec/corpus/test_verdict.sh | 18 +++++++++++------- spec/corpus/verdict.sh | 5 +++++ 7 files changed, 54 insertions(+), 18 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index b04993f3869..42bb6267b2e 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -18,6 +18,10 @@ on: 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 @@ -91,12 +95,13 @@ jobs: - 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 \ + -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 @@ -112,6 +117,7 @@ jobs: 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: | diff --git a/spec/corpus/README.md b/spec/corpus/README.md index f523e702624..d0582efa5ef 100644 --- a/spec/corpus/README.md +++ b/spec/corpus/README.md @@ -2,15 +2,15 @@ **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. +**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. 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. +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. Failure of the candidate to load, calculate, save, or complete always fails it. A baseline-only failure is a non-blocking fixed-build warning. +**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. @@ -43,11 +43,12 @@ curl -fsS --retry 3 --retry-delay 2 --retry-all-errors --max-filesize 16777216 \ 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 pob-corpus sh /harness/spec/corpus/run.sh || status=$? + -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 $? diff --git a/spec/corpus/report.py b/spec/corpus/report.py index a7b8fabefa6..d3e99e87e07 100644 --- a/spec/corpus/report.py +++ b/spec/corpus/report.py @@ -160,8 +160,11 @@ def write_report(results, corpus_file, harness, repo, revision): 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()) - verdict = "Failed" if candidate_failed or (strict and changed) else "Passed" + 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: @@ -177,6 +180,10 @@ def write_report(results, corpus_file, harness, repo, revision): 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.", ""] + 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.", ""] @@ -197,12 +204,12 @@ def write_report(results, corpus_file, harness, repo, revision): " - " + (safe(reason[:400]) if reason else "PoB did not return an error message. See the calculation log.")] lines.append("") if candidate_failed: - lines += ["Any candidate failure blocks the check, including a failure shared with the baseline.", ""] + 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 fails on any of the three types of difference." if strict else + 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 = {} diff --git a/spec/corpus/run.sh b/spec/corpus/run.sh index 114c2ebc689..da65e3fcecb 100644 --- a/spec/corpus/run.sh +++ b/spec/corpus/run.sh @@ -66,4 +66,4 @@ while IFS= read -r name; do compared=$((compared + 1)) done < "$results/builds.txt" printf '%s\n' "$compared" > "$results/compared.txt" -sh "$tools/verdict.sh" "$results" "${STRICT:-false}" +sh "$tools/verdict.sh" "$results" "${STRICT:-false}" "${OVERRIDE_VERDICT:-false}" diff --git a/spec/corpus/test_report.py b/spec/corpus/test_report.py index 0eafbe470da..c78f5af6e25 100644 --- a/spec/corpus/test_report.py +++ b/spec/corpus/test_report.py @@ -9,7 +9,7 @@ class ReportVerdictTest(unittest.TestCase): - def render(self, errors="", stats="", strict=False, cache_hit=False): + def render(self, errors="", stats="", strict=False, override=False, cache_hit=False): with tempfile.TemporaryDirectory() as directory: root = Path(directory) results = root / "results" @@ -31,6 +31,7 @@ def render(self, errors="", stats="", strict=False, cache_hit=False): "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): @@ -57,7 +58,14 @@ 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("Any candidate failure blocks the check", summary) + self.assertIn("Candidate failures normally block the check", 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): @@ -73,6 +81,11 @@ def test_strict_stat_change_blocks(self): 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 index 15ecbf8ce82..183b284c7fd 100644 --- a/spec/corpus/test_verdict.sh +++ b/spec/corpus/test_verdict.sh @@ -9,23 +9,27 @@ trap 'rm -rf "$work"' EXIT expect_status() { expected=$1 strict=$2 + override=$3 actual=0 - sh "$tools/verdict.sh" "$work" "$strict" || actual=$? + 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 +expect_status 0 false false printf 'baseline\tbuild\t1\tloading\tknown failure\n' > "$work/errors.tsv" -expect_status 0 false +expect_status 0 false false printf 'candidate\tbuild\t1\tloading\tnew failure\n' > "$work/errors.tsv" -expect_status 1 false +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 +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 -expect_status 1 true +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 index 1132e716d68..d9a0300701e 100644 --- a/spec/corpus/verdict.sh +++ b/spec/corpus/verdict.sh @@ -2,6 +2,11 @@ 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 From c888c52407ef51acc55bca335c669810c2b497ee Mon Sep 17 00:00:00 2001 From: AdamZ Date: Fri, 27 Nov 2026 23:17:05 -0800 Subject: [PATCH 11/11] Explain how to override corpus verdicts --- spec/corpus/report.py | 4 ++++ spec/corpus/test_report.py | 1 + 2 files changed, 5 insertions(+) diff --git a/spec/corpus/report.py b/spec/corpus/report.py index d3e99e87e07..2072025af27 100644 --- a/spec/corpus/report.py +++ b/spec/corpus/report.py @@ -183,6 +183,10 @@ def write_report(results, corpus_file, harness, repo, revision): 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')}.** " diff --git a/spec/corpus/test_report.py b/spec/corpus/test_report.py index c78f5af6e25..1107edb5c03 100644 --- a/spec/corpus/test_report.py +++ b/spec/corpus/test_report.py @@ -59,6 +59,7 @@ def test_candidate_only_failure_blocks(self): 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):