diff --git a/.github/race-weights b/.github/race-weights index 252fe2ad..695332e0 100644 --- a/.github/race-weights +++ b/.github/race-weights @@ -19,6 +19,11 @@ # on 2026-11-18, against 16 to 26 s before, because the picture-sizes preset # plans its 21 pictures at their smallest twice (tfg preset show, a dry run). # Each weighs what it took where it paid, the rest the most any of them paid. +# The two guards of the plan on several goroutines took 85.0 s and 24.6 s in +# their first part, on an EPYC 7763, on 2026-11-18. The review of the pull +# request that brought them made them dearer the same day - a heavier range, +# a jxl coded while it plans - and on the owner's machine under -race they +# went from 47.0 to 47.7 s and from 11.3 to 24.0 s, so 86.2 and 52.2. # # A test that is not here and takes 60 s or more fails its part with the line # to add. A test that is here and no longer exists fails every part. @@ -35,6 +40,7 @@ unlisted 0.58 124.3 TestFreeBoxesCarryPaddingOfAnyLength 99.9 TestEveryBase64TextSizeIsExact 93.8 TestAFilmPictureLargerThanAnyAV1LevelIsRefusedNotBroken +86.2 TestAPlanIsTheSameHoweverManyFilesArePlannedAtOnce 84.3 TestEveryFormatsMapIsTheOneItsStructureReadsBack 68.2 TestADeclaredDefaultIsTheOneTheFormatUses 65.9 TestNoGeneratorHoldsTheWholeFileInMemory @@ -52,6 +58,7 @@ unlisted 0.58 55.6 TestTheArchiveScanLooksIntoTheArchivesInside 55.3 TestAFilmOfANamedSizeKeepsEveryPictureInsideItsReserve 52.2 TestChoosingAToolLaysTheScreenOutAsIfItOpenedWithIt +52.2 TestThePicturesPlannedAtOnceHoldNoMoreThanTheMemorySettingLeaves 52.0 TestEveryLanguageDescribesEverythingTheProgramCanProduce 38.6 TestAContainerStopsBetweenTheFilesItPlans 37.5 TestEveryPictureNamedAfterARefusalShowsOne diff --git a/.github/scripts/guard_part.sh b/.github/scripts/guard_part.sh new file mode 100644 index 00000000..feebb0aa --- /dev/null +++ b/.github/scripts/guard_part.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Which guards one part of a job runs, and whether it ran every one of them. +# +# guard_part.sh pick PART PARTS LISTED [flag...] writes mine.txt +# guard_part.sh ran LOG fails on a test never started +# +# The guards are split over the parts of three jobs of ci.yml - the tests on +# each system, coverage and the race detector - because one process of them +# reached the eighteen minutes it is given on Windows and macOS (O361). This is +# the one place the three agree on how a part is picked and how it is checked. +# +# pick asks the test binary for its tests, with the flags it will be built with +# (the race job passes -race, because a file in the package builds only without +# it), and keeps the ones race_parts.py lays into this part by the weights in +# .github/race-weights. Listed rather than written down, so a new guard cannot +# be missed by a list kept by hand. It fails when the index the job was given is +# not the one the matrix lists, or below the total, and when the part is given +# no test - go test with nothing to run passes. +# +# ran fails when the log of a part (go test -v) never started a test the part +# was given, by name rather than by count, so a stray line that looks like a +# start cannot stand in for a test that did not run. +set -euo pipefail + +# python3 where it runs, python otherwise: the Windows runner may carry only +# the second, and a python3 there can be the stub that sends you to the store. +python_here() { + local py + for py in python3 python; do + if "$py" -c 'import sys' >/dev/null 2>&1; then + echo "$py" + return + fi + done + echo "neither python3 nor python runs here, and the split of the guards is a Python script." >&2 + exit 1 +} + +pick() { + local part=$1 parts=$2 listed=$3 + shift 3 + if [ "$part" != "$listed" ] || [ "$part" -ge "$parts" ]; then + echo "job $part of $parts is part $listed in the matrix, and the split needs the two equal and below the total." + echo "List strategy.matrix.part as 0, 1, 2 and on, in order, and check the context names in this step's env." + exit 1 + fi + go test -tags "$(cat .github/build-tags)" ./internal/guard/ "$@" -list '.*' > listed.txt || { cat listed.txt; exit 1; } + grep -E '^(Test|Fuzz|Example)' listed.txt > names.txt || { echo "the test binary listed no Test, Fuzz or Example function. What it printed:"; cat listed.txt; exit 1; } + # Without carriage returns: Python on Windows ends its lines with them, and a + # name with one never equals the name go test prints when it starts it. + "$(python_here)" .github/scripts/race_parts.py split names.txt .github/race-weights "$part" "$parts" | tr -d '\r' > mine.txt + local planned + planned=$(wc -l < mine.txt) + echo "part $part of $parts runs $planned of $(wc -l < names.txt) tests" + if [ "$planned" -eq 0 ]; then + echo "part $part of $parts was given no test - the checksum of no listed name lands here." + echo "With this few tests, use fewer parts in strategy.matrix.part." + exit 1 + fi +} + +ran() { + local log=$1 missing + missing=$(comm -23 <(sort mine.txt) <(sed -n 's/^=== RUN \([^/]*\)$/\1/p' "$log" | tr -d '\r' | sort -u)) + if [ -n "$missing" ]; then + echo "this part was given $(wc -l < mine.txt) tests and never ran these:" + echo "$missing" + echo "Each of these is a name the part did not reach, or a test the binary skipped before it started." + exit 1 + fi +} + +case "${1:-}" in + pick) shift; pick "$@" ;; + ran) shift; ran "$@" ;; + *) echo "usage: guard_part.sh pick PART PARTS LISTED [flag...] | ran LOG" >&2; exit 2 ;; +esac diff --git a/.github/scripts/race_parts.py b/.github/scripts/race_parts.py index 0d82b803..56d4138a 100644 --- a/.github/scripts/race_parts.py +++ b/.github/scripts/race_parts.py @@ -2,6 +2,7 @@ race_parts.py split NAMES WEIGHTS PART PARTS > mine.txt race_parts.py unlisted WEIGHTS LOG + race_parts.py verdict WHAT JOBS split prints the names of NAMES (one per line, as go test -list gives them) that part PART of PARTS runs. The tests WEIGHTS names are laid out by their @@ -14,7 +15,11 @@ does not name took UNLISTED_CEILING seconds or more. Such a test is laid out as if it were light, and the parts stop being even without anything saying so. -Both fail closed, with a sentence that names what to change: a weight for a +verdict reads the jobs of a workflow run and fails unless every part of WHAT +ran and passed. The checks main's rules require are those verdicts, because a +part carries its number in its name and the rules name jobs. + +They fail closed, with a sentence that names what to change: a weight for a test the binary does not list (renamed or removed), a line that is not a weight, a name given twice, no "unlisted" line, or a part outside the parts. """ @@ -35,6 +40,9 @@ # which ended the script with a traceback instead of passing the line by. TOP = re.compile(r"^--- (?:PASS|FAIL|SKIP): (\S+) \(([0-9]+(?:\.[0-9]+)?)s\)$") +# A job of a part as ci.yml names it: "guards on windows-latest (part 1 of 2)". +PART_NAME = re.compile(r"^(.+) \(part ([0-9]+) of ([0-9]+)\)$") + def refuse(message): print(message, file=sys.stderr) @@ -137,14 +145,54 @@ def check_unlisted(weights_path, log_path): "as if they were light:\n%s\nAdd each line above to %s." % (UNLISTED_CEILING, lines, weights_path)) +def verdict(what, jobs_path): + """Fail unless every part of WHAT ran in this workflow and passed. + + JOBS is the jobs of the run, a name and a conclusion to a line with a tab + between, as the verdict jobs of ci.yml ask the API for them. A part is a + job named WHAT (part I of N). Every N has to agree, every I below N has to + be there once, and every one has to have succeeded - a part that never ran + is as red as one that failed, because its tests ran nowhere. + """ + found, counts = {}, set() + for line in read_lines(jobs_path, "list of jobs"): + name, _, conclusion = line.partition("\t") + named = PART_NAME.match(name.strip()) + if not named or named.group(1) != what: + continue + part, parts = int(named.group(2)), int(named.group(3)) + if part in found: + refuse("two jobs of this run are part %d of %s." % (part, what)) + found[part] = conclusion.strip() + counts.add(parts) + if not found: + refuse("no job of this run is a part of %s, so nothing says its tests passed." % what) + if len(counts) != 1: + refuse("the parts of %s disagree about how many there are: %s." % (what, ", ".join(sorted(str(n) for n in counts)))) + parts = counts.pop() + failed = False + for part in range(parts): + conclusion = found.get(part, "") + print("part %d of %d of %s: %s" % (part, parts, what, conclusion or "did not run in this workflow")) + failed = failed or conclusion != "success" + for part in sorted(p for p in found if p >= parts): + print("part %d of %s is past its %d parts, so the matrix and the number in the name disagree" % (part, what, parts)) + failed = True + if failed: + sys.exit(1) + + def main(): args = sys.argv[1:] if len(args) == 5 and args[0] == "split": split(*args[1:]) elif len(args) == 3 and args[0] == "unlisted": check_unlisted(*args[1:]) + elif len(args) == 3 and args[0] == "verdict": + verdict(*args[1:]) else: - refuse("usage: race_parts.py split NAMES WEIGHTS PART PARTS | race_parts.py unlisted WEIGHTS LOG") + refuse("usage: race_parts.py split NAMES WEIGHTS PART PARTS | race_parts.py unlisted WEIGHTS LOG" + " | race_parts.py verdict WHAT JOBS") if __name__ == "__main__": diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 251a8b1b..7a5befe4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ env: jobs: test: - name: test on ${{ matrix.os }} + name: guards on ${{ matrix.os }} (part ${{ matrix.part }} of ${{ matrix.parts }}) # A hung job otherwise holds a runner until the GitHub default of six # hours. Remeasured 2026-09-03, because the sentence here said "the matrix # runs in about a minute" and had not been true for a long time: the test @@ -39,10 +39,29 @@ jobs: # and its own numbers now, and fuzzing is given 5 minutes a target by its # own loop. timeout-minutes: 20 + # Two parts on each system, the owner's decision of 2026-11-18 (O361). In + # one process the guards took 995 s on Windows on main that day, against + # the 1080 s of the test step's timeout, and 1080 s - the timeout - on + # Windows and macOS for the pull request after it. The same package had + # taken 621 to 744 s four days earlier, and it grows with every guard. + # The race job met the same wall in September and split for the same + # reason: a timeout raised once and met again is the wrong shape. The + # guards are laid out by .github/race-weights through + # .github/scripts/guard_part.sh, the way the race job lays out its own. + # + # parts is the length of part, stated beside it, because the name cannot + # count a list. A part outside the parts fails when it picks its tests, + # and a part missing from the list fails the verdict below, which counts + # the parts it finds against the number in their names. + # + # The steps that are not the guards - formatting, vet, the dependency + # list, the two builds and the other packages - run in part 0 alone. strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] + part: [0, 1] + parts: [2] runs-on: ${{ matrix.os }} env: # The engine, the command line and the tests build without CGO on every @@ -87,14 +106,17 @@ jobs: cache: true - name: formatting + if: matrix.part == 0 run: | test -z "$(gofmt -l .)" || { echo "gofmt found unformatted files:"; gofmt -l .; exit 1; } shell: bash - name: vet + if: matrix.part == 0 run: go vet -tags "$(cat .github/build-tags)" ./... - name: the dependency list has not grown by accident + if: matrix.part == 0 # Every dependency is a licence question and a byte stability # question. A new one arriving as somebody's transitive import has # to be visible rather than discovered later. @@ -287,7 +309,7 @@ jobs: echo "the command line binary links only: $linked" shell: bash - - name: test + - name: the guards of this part # The timeout is stated for the reason the race job and the coverage # gate both state theirs: Go allows ten minutes PER PACKAGE by default, # this job allows twenty for all of it, and internal/guard is one @@ -300,12 +322,41 @@ jobs: # on windows, 491 s on macOS. macOS therefore had 109 s of room under a # limit nobody had chosen, and the same fleet was measured swinging by # more than 25 percent between two runs of one branch. - run: go test -tags "$(cat .github/build-tags)" ./... -count=1 -timeout 18m + # + # The part's tests reach the binary through a file (TFG_GUARD_PART, + # read by TestMain in internal/guard/guardpart_test.go), not through + # -run: half the package is about 34 000 characters of names, and + # Windows hands a program at most 32 767. -v so the log names every + # test it started, for the check after the run, and its time. + env: + PART: ${{ matrix.part }} + PARTS: ${{ matrix.parts }} + run: | + set -euo pipefail + bash .github/scripts/guard_part.sh pick "$PART" "$PARTS" "$PART" + TFG_GUARD_PART=mine.txt go test -tags "$(cat .github/build-tags)" ./internal/guard/ -count=1 -timeout 18m -v 2>&1 | tee part.log + bash .github/scripts/guard_part.sh ran part.log + shell: bash + + - name: the other packages + # Every package outside internal/guard, in part 0 alone. None holds a + # test today, and one written there has to run as well. The list goes + # to go test through xargs: the bash of macOS is 3.2 and has no + # mapfile (TestAJobOnMacOSUsesOnlyWhatItsBashHas). + if: ${{ !cancelled() && matrix.part == 0 }} + timeout-minutes: 5 + run: | + set -euo pipefail + go list -tags "$(cat .github/build-tags)" ./... | grep -v '/internal/guard$' > others.txt + xargs go test -tags "$(cat .github/build-tags)" -count=1 -timeout 4m < others.txt + shell: bash - name: build the command line binary + if: matrix.part == 0 run: go build -tags "$(cat .github/build-tags)" ./cmd/tfg - name: build the window binary + if: matrix.part == 0 # The toolkit arrived on 2026-08-05 and this step still passes, which # is the point of how it was wired in. Reaching the toolkit's app # package needs CGO and, on Linux, X11 development headers no runner @@ -343,6 +394,47 @@ jobs: fi shell: bash + verdict: + name: test on ${{ matrix.os }} + # The name the ruleset of main requires, which the test job carried until + # it was split into parts (O361). A job of its own rather than a renamed + # check, so main's rules did not have to change, and one for each system, + # so a red Windows part does not turn ubuntu red. race_parts.py verdict is + # what decides, and the coverage gate asks it the same question. + # + # always() rather than the default, because a job whose needs failed is + # skipped, and a required check that was skipped counts as passed. This + # one runs whatever happened and decides from what the parts concluded. + needs: test + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + # Reads the jobs of this run and the script that judges them. filter=latest + # answers with the newest attempt of every job, so a part that failed and + # was run again is judged by the run that counts. + permissions: + contents: read + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: every part of the guards on this system passed + env: + GH_TOKEN: ${{ github.token }} + OS: ${{ matrix.os }} + run: | + set -euo pipefail + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs?filter=latest&per_page=100" --paginate \ + --jq '.jobs[] | [.name, (.conclusion // "none")] | @tsv' > jobs.tsv + python3 .github/scripts/race_parts.py verdict "guards on $OS" jobs.tsv + shell: bash + imports: name: import table of the window binary # One guard, in a job of its own, because it is the one guard that builds @@ -1050,8 +1142,9 @@ jobs: # is .github/build-tags, which every command of the job reads and which # decides the files it compiles - the same reason as go.mod, named by # an outside review of the pull request that split the job. And so are - # the weights and the script that lay its parts out (O298), since a - # change to either decides which guards each part runs. + # the weights and the scripts that lay its parts out and check them + # (O298), and the TestMain that hands a part its tests (O361), since a + # change to any of them decides which guards each part runs. # # Anything unclear counts as touched. A first push, a branch with no # comparable parent, a pull request event with no before - all answer @@ -1060,7 +1153,7 @@ jobs: # in somebody else's file. run: | set -euo pipefail - watched='internal/format/registry.go internal/damage/damage.go cmd/tfg/main.go internal/gui/window/run.go internal/gui/run_cgo.go internal/gui/window/tidy.go internal/audit/parallel.go internal/engine/parallel.go internal/tool/tool.go internal/gui/window/tools.go internal/gui/window/work.go internal/gui/window/closing.go internal/gui/window/dropping.go internal/format/video/ahead.go go.mod .github/workflows/ci.yml .github/build-tags .github/race-weights .github/scripts/race_parts.py' + watched='internal/format/registry.go internal/damage/damage.go cmd/tfg/main.go internal/gui/window/run.go internal/gui/run_cgo.go internal/gui/window/tidy.go internal/audit/parallel.go internal/engine/parallel.go internal/tool/tool.go internal/gui/window/tools.go internal/gui/window/work.go internal/gui/window/closing.go internal/gui/window/dropping.go internal/format/video/ahead.go go.mod .github/workflows/ci.yml .github/build-tags .github/race-weights .github/scripts/race_parts.py .github/scripts/guard_part.sh internal/guard/guardpart_test.go' # On a pull request there is no "before" - the field belongs to a push # - so this asked for something empty and every pull request answered # "touched". That quietly undid the decision of 2026-08-20, because @@ -1174,6 +1267,33 @@ jobs: sudo apt-get install -y --no-install-recommends libgl1-mesa-dev libwayland-dev libx11-dev libxkbcommon-dev xorg-dev shell: bash + - name: the modules, fetched again when the proxy breaks off + # O364. The module cache setup-go restores is saved by the job that + # finishes first, and that one builds without CGO, so this job fetches + # the toolkit's Linux modules on every run - 28 of them on main + # (2026-11-16). On 2026-11-18 proxy.golang.org broke a stream off in + # the middle twice ("stream error ... INTERNAL_ERROR"), and go test + # ended "[setup failed]" before it reached a test. Three tries with a + # pause between them: a dropped stream is fetched again, and a proxy + # that is down still fails the job, by name. With no argument go mod + # download fetches every module go.mod requires, which since go 1.17 + # is every module a build or test of this module needs. + timeout-minutes: 10 + run: | + set -euo pipefail + for try in 1 2 3; do + if go mod download; then + exit 0 + fi + echo "go mod download failed on try $try of 3" + if [ "$try" -lt 3 ]; then + sleep 20 + fi + done + echo "go mod download failed three times. The proxy is down or a module is gone, see the errors above." + exit 1 + shell: bash + - name: the machine this part runs on # O298, 2026-11-03. Part 2 ran past its twenty minutes in one run of # three since 2026-10-26, main included, and the log named the runner's @@ -1200,8 +1320,9 @@ jobs: # the declared files lives in internal/guard, so this and that one # answer different halves of the same worry. # - # Which tests are this part's is worked out here, from the test binary, - # rather than written down. A list kept by hand would miss the next + # Which tests are this part's is worked out from the test binary, by + # .github/scripts/guard_part.sh for every job split into parts, rather + # than written down. A list kept by hand would miss the next # guard somebody adds, and miss it green. The list is asked with -race, # because a file in the package builds only without it, and it keeps # Fuzz and Example because go test runs those as tests too. @@ -1240,31 +1361,11 @@ jobs: LISTED: ${{ matrix.part }} run: | set -euo pipefail - if [ "$PART" != "$LISTED" ] || [ "$PART" -ge "$PARTS" ]; then - echo "job $PART of $PARTS is part $LISTED in the matrix, and the split needs the two equal and below the total." - echo "List strategy.matrix.part as 0, 1, 2 and on, in order, and check the context names in this step's env." - exit 1 - fi - go test -tags "$(cat .github/build-tags)" ./internal/guard/ -race -list '.*' > listed.txt || { cat listed.txt; exit 1; } - grep -E '^(Test|Fuzz|Example)' listed.txt > names.txt || { echo "the test binary listed no Test, Fuzz or Example function. What it printed:"; cat listed.txt; exit 1; } - python3 .github/scripts/race_parts.py split names.txt .github/race-weights "$PART" "$PARTS" > mine.txt - planned=$(wc -l < mine.txt) - echo "part $PART of $PARTS runs $planned of $(wc -l < names.txt) tests" - if [ "$planned" -eq 0 ]; then - echo "part $PART of $PARTS was given no test - the checksum of no listed name lands here." - echo "With this few tests, use fewer parts in strategy.matrix.part." - exit 1 - fi + bash .github/scripts/guard_part.sh pick "$PART" "$PARTS" "$LISTED" -race head -n 1 /proc/stat > stat-before.txt date +%s > time-before.txt - go test -tags "$(cat .github/build-tags)" ./internal/guard/ -count=1 -race -timeout 20m -v -run "^($(paste -sd'|' mine.txt))\$" 2>&1 | tee part.log - missing=$(comm -23 <(sort mine.txt) <(sed -n 's/^=== RUN \([^/]*\)$/\1/p' part.log | sort -u)) - if [ -n "$missing" ]; then - echo "part $PART was given $planned tests and never ran these:" - echo "$missing" - echo "Each of these is a name the -run pattern did not reach, or a test the binary skipped before it started." - exit 1 - fi + TFG_GUARD_PART=mine.txt go test -tags "$(cat .github/build-tags)" ./internal/guard/ -count=1 -race -timeout 20m -v 2>&1 | tee part.log + bash .github/scripts/guard_part.sh ran part.log python3 .github/scripts/race_parts.py unlisted .github/race-weights part.log shell: bash @@ -1324,9 +1425,21 @@ jobs: shell: bash coverage: - name: coverage gate + name: coverage (part ${{ matrix.part }} of ${{ matrix.parts }}) runs-on: ubuntu-latest timeout-minutes: 20 + # Two parts, for the reason the test job has two (O361): one process took + # 861 s of its 1080 on main on 2026-11-18 and 1036 s on the pull request + # after it. Each part measures its own guards and hands its profile to the + # gate below, which adds them up. A block two parts both ran is counted + # once with the counts of both, because go tool cover merges blocks of the + # same place - measured that day on two guards: 9.9% and 16.5% apart, 16.6% + # added up and 16.6% run together. + strategy: + fail-fast: false + matrix: + part: [0, 1] + parts: [2] env: CGO_ENABLED: "0" steps: @@ -1368,17 +1481,92 @@ jobs: # generates files for twenty four formats. Eighteen minutes sits under # the job's own ceiling on purpose, so a genuinely stuck run still fails # as a test with output rather than as a killed job without any. - run: > - go test -tags "$(cat .github/build-tags)" ./... -count=1 -covermode=atomic - -coverpkg=./internal/...,./cmd/... - -coverprofile=coverage.out -timeout 18m + # + # This part's guards reach the binary through a file, the way the test + # job hands its parts over (guard_part.sh). + env: + PART: ${{ matrix.part }} + PARTS: ${{ matrix.parts }} + run: | + set -euo pipefail + bash .github/scripts/guard_part.sh pick "$PART" "$PARTS" "$PART" + TFG_GUARD_PART=mine.txt go test -tags "$(cat .github/build-tags)" ./internal/guard/ -count=1 -covermode=atomic \ + -coverpkg=./internal/...,./cmd/... -coverprofile="coverage-$PART.out" -timeout 18m -v 2>&1 | tee part.log + bash .github/scripts/guard_part.sh ran part.log + shell: bash + + - name: measure the other packages + # Every package outside internal/guard, in part 0 alone, so a test + # written there counts towards the gate as it did when one command + # measured the whole tree. + if: ${{ !cancelled() && matrix.part == 0 }} + timeout-minutes: 5 + run: | + set -euo pipefail + go list -tags "$(cat .github/build-tags)" ./... | grep -v '/internal/guard$' > others.txt + mapfile -t others < others.txt + go test -tags "$(cat .github/build-tags)" -count=1 -covermode=atomic -coverpkg=./internal/...,./cmd/... \ + -coverprofile=coverage-others.out -timeout 4m "${others[@]}" + shell: bash + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: coverage-part-${{ matrix.part }} + path: coverage-*.out + if-no-files-found: error + retention-days: 3 + + coverage-gate: + name: coverage gate + # The name the ruleset of main requires. always(), for the reason the + # verdict of the test job gives: a skipped required check counts as + # passed, so this runs whatever the parts did and fails unless every one + # of them succeeded. + needs: coverage + if: always() + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ env.GO_VERSION }} + check-latest: false + cache: true + + - name: every part measured + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs?filter=latest&per_page=100" --paginate \ + --jq '.jobs[] | [.name, (.conclusion // "none")] | @tsv' > jobs.tsv + python3 .github/scripts/race_parts.py verdict "coverage" jobs.tsv + shell: bash + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: coverage-part-* + path: profiles + merge-multiple: true - name: gate # The threshold lives in exactly one place, .github/coverage-threshold. # It rises with coverage and is never lowered to turn a red run green. # Lowering it is a decision for the owner, not a way to get unblocked. + # + # The profiles of the parts are one profile once the line naming the + # mode is said once. run: | set -euo pipefail + ls profiles/coverage-*.out + { echo "mode: atomic"; tail -q -n +2 profiles/coverage-*.out; } > coverage.out threshold=$(tr -d '[:space:]' < .github/coverage-threshold) actual=$(go tool cover -func=coverage.out | awk '/^total:/ {gsub("%","",$3); print $3}') echo "coverage ${actual}% - threshold ${threshold}%" diff --git a/.gitignore b/.gitignore index b25b5529..f35217a2 100644 --- a/.gitignore +++ b/.gitignore @@ -71,6 +71,13 @@ coverage.out coverage.html /covdata/ +# The log of a part of the guards in ci.yml (go test -v | tee part.log). The +# guards read every file git could commit, untracked ones as well, and this one +# grows while they run with the paths the tests print. On Windows those lie in +# the runner's profile, and the guard against private content read them there. +# TestTheLogOfAPartIsAFileGitIgnores holds this line to the log ci.yml writes. +/part.log + # --------------------------------------------------------------------------- # Editors and operating systems # --------------------------------------------------------------------------- diff --git a/CHANGELOG.md b/CHANGELOG.md index edd38a03..39ed7e2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -263,6 +263,23 @@ because it turns other people's test suites red. ### Changed +- **Many pictures are ready to write several times sooner.** Before the + first file is written, every file is worked out, and a picture is drawn to + do it - now on every processor at once. On 16 threads, + `--dry-run` of 2000 PNG pictures of 640x480 takes 2.6 s rather than 16 s, + and a size too small for them is refused in 6.5 s rather than 33 s. Ranges + of sizes, PDF and Office files gain too, and text is as fast as before. The + files are the same, and pictures worked out at once stay inside the memory + setting. +- **Adding or copying a batch on the Several batches screen folds the + batches above it.** The batch you just made is open under them, and each + folded batch shows in one line what it holds. Click a batch's title to open + it again. If Generate or Preview is refused because of a box in a folded + batch, that batch opens by itself. Batches below a copy stay as they were. +- **Scrolling a long list on the Several batches screen is smoother.** Folded + batches cost almost nothing to scroll past. With forty batches open, each + turn of the mouse wheel takes the window about 8 to 11 ms rather than 15 to + 20 ms, inside the time of one screen refresh. - **A value to type stands out from the words describing it.** In the explanation behind a field, a value you type as it is - `screens` and `all` for the groups of `picture-sizes`, `10mb` for a size, `{index:04}` in a file diff --git a/internal/engine/batchminimum.go b/internal/engine/batchminimum.go index a0fb0767..044f1f18 100644 --- a/internal/engine/batchminimum.go +++ b/internal/engine/batchminimum.go @@ -84,6 +84,23 @@ type batchWalk struct { desc format.Descriptor targetSeed uint64 damaged string + // run is what the memory setting lets the run hold (planstretch.go). + run int64 + // position is the target's place in the recipe, counted from one, and + // ext the ending of its files - what planning.file gives each of them. + position int + ext string +} + +// planAt plans file idx of the target, from nought, at size bytes. +func (w batchWalk) planAt(ctx context.Context, idx int, size int64) answer { + // Per target and index, never from a stream the run shares - untouchable + // rule 2, and the reason two runs of one recipe write the same bytes. + seed := core.FileSeed(w.targetSeed, idx) + r := requestFor(w.t, idx, seed, w.damaged) + r.Bytes = size + p, err := planFile(ctx, w.t, w.desc, r) + return answer{plan: p, err: err, seed: seed} } // everyFile is where the walk ended. @@ -113,7 +130,13 @@ type everyFile struct { // and height set encodes while it plans, so ten thousand of them is the time // their plan takes, measured in docs/SIZE-FIXES-2026-11-16.md. It holds nothing // per file, so a million files cost time and no memory, and the run's context -// is asked before every plan, so a stop is a stop. +// is asked before every stretch, so a stop is a stop. +// +// The files are asked a stretch at a time (planstretch.go), one file a +// goroutine, and their answers are read in the order of the walk. A file read +// after a refusal was asked at the size before the raise, so its answer is +// thrown away and it is asked again - which makes every raise, every file +// that raised it and so the reason the refusal gives the same at any width. // // The ceiling is for a generator that never accepts, which would otherwise walk // one byte at a time without end. A raise never goes down, so nothing cycles, @@ -121,35 +144,58 @@ type everyFile struct { // size - format.SmallestRounds - so n files may raise it n times that. func (w batchWalk) sizeEveryFileTakes(ctx context.Context, first int, below *format.BelowMinimumError) (everyFile, error) { n := len(w.t.Sizes) - got := everyFile{size: max(below.Minimum, below.Requested+1), last: below} - raises, ceiling := 0, format.SmallestRounds*n - for idx, inARow := first, 0; inARow < n; { + s := &walking{n: n, first: first, idx: first, ceiling: format.SmallestRounds * n, + got: everyFile{size: max(below.Minimum, below.Requested+1), last: below}} + ask := func(i int) answer { return w.planAt(ctx, i%n, s.got.size) } + pace := pace{run: w.run} + got := make([]answer, widthFor(n)) + for s.inARow < n { if err := ctx.Err(); err != nil { return everyFile{}, err } - r := requestFor(w.t, idx, core.FileSeed(w.targetSeed, idx), w.damaged) - r.Bytes = got.size - _, err := planFile(ctx, w.t, w.desc, r) - if err == nil { - inARow++ - idx = (idx + 1) % n + k, width := pace.stretch(n-s.inARow, 1, s.got.size, len(got)) + planStretch(&pace, got[:k], s.idx, width, ask) + if err := s.take(got[:k], &pace, w.desc.ID); err != nil { + return everyFile{}, err + } + } + return s.got, nil +} + +// walking is where the walk of sizeEveryFileTakes stands: the file to ask +// next, how many in a row accepted the size, and how often it was raised. +type walking struct { + n, first, idx, inARow int + raises, ceiling int + got everyFile +} + +// take reads the answers of one stretch in order, up to the first refusal, +// which raises the size for the next. +func (s *walking) take(answers []answer, pace *pace, id string) error { + for _, a := range answers { + if a.err == nil { + pace.saw(a.plan) + s.inARow++ + s.idx = (s.idx + 1) % s.n continue } var refused *format.BelowMinimumError - if !errors.As(err, &refused) { + if !errors.As(a.err, &refused) { // A refusal about something else, or a stop the format noticed // first. Either is the answer somebody needs, so it goes out as it // came. - return everyFile{}, err + return a.err } - if raises++; raises > ceiling { - return everyFile{}, core.Defect(fmt.Errorf("%s: the size every one of %d files accepts did not settle in %d raises, the last at %d B", - w.desc.ID, n, ceiling, got.size)) + if s.raises++; s.raises > s.ceiling { + return core.Defect(fmt.Errorf("%s: the size every one of %d files accepts did not settle in %d raises, the last at %d B", + id, s.n, s.ceiling, s.got.size)) } - got.size = max(refused.Minimum, got.size+1) - got.last, got.differ, inARow = refused, got.differ || idx != first, 0 + s.got.size = max(refused.Minimum, s.got.size+1) + s.got.last, s.got.differ, s.inARow = refused, s.got.differ || s.idx != s.first, 0 + return nil } - return got, nil + return nil } // refusal is the refusal for a batch whose size moved past the one the first diff --git a/internal/engine/drawsizes.go b/internal/engine/drawsizes.go index b5fc0c10..aed7451d 100644 --- a/internal/engine/drawsizes.go +++ b/internal/engine/drawsizes.go @@ -41,13 +41,16 @@ import ( // SmallestAccepted is called from guards and from the window, where that wrapper // is not in hand. Merging them would mean handing a planner in, which buys less // than it costs. -func firstWritable(ctx context.Context, desc format.Descriptor, r format.Request, from, limit int64) (int64, error) { +// +// The plan it answers with is the one at that size, for what it says the file +// holds (planstretch.go). +func firstWritable(ctx context.Context, desc format.Descriptor, r format.Request, from, limit int64) (int64, format.Plan, error) { var first error for at := from; at <= limit; { r.Bytes = at - _, err := planWithoutCrashing(ctx, desc, r) + p, err := planWithoutCrashing(ctx, desc, r) if err == nil { - return at, nil + return at, p, nil } if first == nil { first = err @@ -56,11 +59,11 @@ func firstWritable(ctx context.Context, desc format.Descriptor, r format.Request if !errors.As(err, &below) || below.Minimum <= at { // Not a refusal about the size, or one that names no way forward. // Either way there is nothing to jump to. - return 0, err + return 0, format.Plan{}, err } at = below.Minimum } - return 0, first + return 0, format.Plan{}, first } // drawSizes settles the size of every file of a range target. @@ -108,7 +111,7 @@ func firstWritable(ctx context.Context, desc format.Descriptor, r format.Request // size stopped in 0.01 s (docs/STABILITY-REVIEW-2026-10-26.md, R05). // format.PlanWith asks the context before anything else, and a stop is not a // refusal about the size, so firstWritable hands it straight back. -func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSeed uint64) error { +func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSeed uint64, run int64) error { damaged := t.Damage.Label() first := requestFor(t, 0, core.FileSeed(targetSeed, 0), damaged) @@ -124,7 +127,7 @@ func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSee // UTF-16, the band above a PNG's encoded picture - is a different thing: // nobody can be expected to enumerate those, and snapping inside the range // is the answer. - floor, err := firstWritable(ctx, desc, first, 0, t.Range.Max) + floor, _, err := firstWritable(ctx, desc, first, 0, t.Range.Max) if err != nil { // The floor is above the whole range, so nothing in it is writable. return err @@ -138,35 +141,74 @@ func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSee } } - span := uint64(t.Range.Max - t.Range.Min) t.SizeMoved = make([]bool, len(t.Sizes)) - - for i := range t.Sizes { - want := t.Range.Min - if span != 0 { - // Per index, never from a running stream. Raising a count then - // leaves the sizes of the earlier files alone, which is rule 2 and - // the reason core.SizeSeed takes an index at all. - r := core.NewRand(core.SizeSeed(targetSeed, i)) - want = t.Range.Min + int64(r.Uint64N(span+1)) + draw := func(i int) drawn { return drawOne(ctx, t, desc, targetSeed, damaged, i) } + pace := pace{run: run} + got := make([]drawn, min(len(t.Sizes), widthFor(len(t.Sizes))*planStretchPerWriter)) + for from := 0; from < len(t.Sizes); { + n, width := pace.stretch(len(t.Sizes)-from, planStretchPerWriter, t.Range.Max, len(got)) + planStretch(&pace, got[:n], from, width, draw) + if err := settleDrawn(t, from, got[:n], &pace); err != nil { + return err } + from += n + } + return nil +} - req := requestFor(t, i, core.FileSeed(targetSeed, i), damaged) - - got, err := firstWritable(ctx, desc, req, want, t.Range.Max) - if err != nil && want > t.Range.Min { - // Nothing writable from the draw upwards. The bottom of the range - // can still hold something - a draw landing on the last odd number - // of a range has nowhere above it and plenty below - so the range is - // only empty once THAT fails too. After a stop this second try - // hands the stop back at its first probe. - got, err = firstWritable(ctx, desc, req, t.Range.Min, t.Range.Max) - } - if err != nil { - return err +// settleDrawn gives the files of one stretch of a range their sizes, in order, +// and stops at the first that could not be drawn. +func settleDrawn(t *Target, from int, got []drawn, pace *pace) error { + for j, d := range got { + if d.err != nil { + return d.err } - t.SizeMoved[i] = got != want - t.Sizes[i] = got + t.SizeMoved[from+j] = d.size != d.want + t.Sizes[from+j] = d.size + pace.saw(d.plan) } return nil } + +// drawn is what drawing the size of one file of a range came to: the size the +// seed drew, the writable size it settled on, and of the plan at that size +// only what pace reads. The whole plan stays behind, because a stretch holds +// up to a hundred and twenty eight of these at once and a plan can carry its +// file - a PDF plans its whole document - while the plan that is written is +// made again once the sizes are settled. +type drawn struct { + want, size int64 + plan format.Plan + err error +} + +// drawOne draws the size of file i of a range target and settles it on one +// the format can write. +// +// One file, asking nothing of the others, so the files of a range are drawn a +// stretch at a time beside each other (planstretch.go) and read in order - +// the first that fails is the one a draw of one file at a time stopped at. +func drawOne(ctx context.Context, t *Target, desc format.Descriptor, targetSeed uint64, damaged string, i int) drawn { + want := t.Range.Min + if span := uint64(t.Range.Max - t.Range.Min); span != 0 { + // Per index, never from a running stream. Raising a count then + // leaves the sizes of the earlier files alone, which is rule 2 and + // the reason core.SizeSeed takes an index at all. + r := core.NewRand(core.SizeSeed(targetSeed, i)) + want = t.Range.Min + int64(r.Uint64N(span+1)) + } + + req := requestFor(t, i, core.FileSeed(targetSeed, i), damaged) + + got, plan, err := firstWritable(ctx, desc, req, want, t.Range.Max) + if err != nil && want > t.Range.Min { + // Nothing writable from the draw upwards. The bottom of the range + // can still hold something - a draw landing on the last odd number + // of a range has nowhere above it and plenty below - so the range is + // only empty once THAT fails too. After a stop this second try + // hands the stop back at its first probe. + got, plan, err = firstWritable(ctx, desc, req, t.Range.Min, t.Range.Max) + } + return drawn{want: want, size: got, err: err, + plan: format.Plan{Bytes: plan.Bytes, Holds: plan.Holds, PlanHolds: plan.PlanHolds}} +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 5708ffa0..13c9e157 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -269,8 +269,9 @@ func (f PlannedFile) Damaged() bool { // what a part does rather than how long it is: this answers "is this target // askable at all", and the loop it was taken out of answers "what files does it // come to". seen carries across targets because a duplicate id is a fact about -// the run rather than about one entry. -func settleTarget(ctx context.Context, t *Target, opt Options, seen map[string]bool) (format.Descriptor, error) { +// the run rather than about one entry, and run is what the memory setting lets +// the run hold, which the draw of a range is kept inside (planstretch.go). +func settleTarget(ctx context.Context, t *Target, opt Options, seen map[string]bool, run int64) (format.Descriptor, error) { if t.ID == "" { return format.Descriptor{}, &RecipeError{Setting: SettingID, Detail: core.Says("engine.NoID", "a target has no id"), @@ -328,7 +329,7 @@ func settleTarget(ctx context.Context, t *Target, opt Options, seen map[string]b // for every registered format. It was removed rather than kept as defence // nobody can verify. if t.Range.Used { - if err := drawSizes(ctx, t, desc, core.TargetSeed(opt.Seed, t.ID)); err != nil { + if err := drawSizes(ctx, t, desc, core.TargetSeed(opt.Seed, t.ID), run); err != nil { return format.Descriptor{}, err } } @@ -404,7 +405,7 @@ func PlanContext(ctx context.Context, targets []Target, opt Options) ([]PlannedF // rather than at the first file because constructing it is what takes the // reference point, and that has to happen before any of the plan exists. limits := opt.memoryLimits() - pl.budget = newPlanMemory(opt.Memory, limits) + pl.budget, pl.run = newPlanMemory(opt.Memory, limits), limits.Run HandToRuntime(limits) // The manifest lands beside the files, so its name is a name too. A path @@ -465,7 +466,7 @@ func PlanContext(ctx context.Context, targets []Target, opt Options) ([]PlannedF // Everything refused from here down is refused about one target, so it // carries which one. See atTarget for what that is worth and what it // deliberately leaves alone. - desc, err := settleTarget(ctx, t, opt, seen) + desc, err := settleTarget(ctx, t, opt, seen, pl.run) if err != nil { return nil, atTarget(i+1, t, err) } diff --git a/internal/engine/parallel.go b/internal/engine/parallel.go index d62ce88c..0a1432fa 100644 --- a/internal/engine/parallel.go +++ b/internal/engine/parallel.go @@ -31,7 +31,12 @@ import ( // Why it exists. Writing the files is what a run is: measured on 2026-09-06, // after P7 stopped planning from encoding the picture twice, planning a run of // 300 PNGs is 51 ms and writing it is 2741 ms - 2% against 98%. So the write -// loop is the whole of what is left to parallelise, and the plan is not. +// loop came first. The plan followed on 2026-11-18 (O355), once a picture +// given its width and height was found to encode while it plans: two thousand +// PNGs of 640x480 took 25.6 s to plan and ten thousand 76 s, one file at a +// time, and a size refused for such a batch about twice that. beside, at the +// end of this file, is the whole of what planning runs at once, and +// planstretch.go says how much of it. // // Measured with tools/probes/writeparallel, which writes a real planned run // with N goroutines in ONE process - the shape this file has, rather than the @@ -652,3 +657,44 @@ func (c *countingWriter) Write(p []byte) (int, error) { } return n, err } + +// beside fills out with ask(from), ask(from+1) and so on, one answer for each +// place in it, on width goroutines - the files of one stretch of a plan +// (planstretch.go). +// +// Answers by place rather than by finishing order, for the reason writeAll +// does: the caller reads them in the order a plan of one file at a time would +// have reached them, so the first refusal it meets is the one that plan would +// have stopped at, and the files after it are thrown away unread. That is +// what keeps the plan, the names and every refusal the same at any width. +// +// Width one is the loop it replaces, on this goroutine. A machine with one +// processor, or a stretch the memory setting holds to one file at a time, +// starts nothing. +// +// It asks no context. ask plans a file, and planning asks the context before +// anything else (format.PlanWith), so after a stop every place left answers +// with the stop at once. +func beside[T any](out []T, from, width int, ask func(i int) T) { + if width <= 1 || len(out) <= 1 { + for j := range out { + out[j] = ask(from + j) + } + return + } + var next atomic.Int64 + var wg sync.WaitGroup + for range min(width, len(out)) { + wg.Go(func() { askInTurn(&next, out, from, ask) }) + } + wg.Wait() +} + +// askInTurn is one goroutine of beside: it takes the next place nobody has +// taken and answers it, until there are none. A function of its own for the +// reason drain is one. +func askInTurn[T any](next *atomic.Int64, out []T, from int, ask func(i int) T) { + for j := int(next.Add(1)) - 1; j < len(out); j = int(next.Add(1)) - 1 { + out[j] = ask(from + j) + } +} diff --git a/internal/engine/planmemory.go b/internal/engine/planmemory.go index 3619b286..bf4d2582 100644 --- a/internal/engine/planmemory.go +++ b/internal/engine/planmemory.go @@ -1,6 +1,7 @@ package engine import ( + "math" "reflect" "runtime" "runtime/metrics" @@ -239,6 +240,25 @@ func (p *planMemory) account(targetIndex, filesSoFar int) error { } } +// ahead is how many more files may be planned before the next reading, the +// longest stretch of the plan (planstretch.go) that does not carry it past +// one. Unlimited without a ceiling. +// +// NO GUARD PROVES THIS, and what it buys says why. Without it the plan is +// still refused, at the same reading or one earlier, because the files a +// stretch planned past the reading are held by then and counted too. What it +// keeps is the PEAK: a stretch of a dear shape - a pdf of a thousand pages is +// 5 MB of plan a file - planned past the reading is a hundred and twenty eight +// such files the ceiling did not get to weigh first. Seeing that needs the +// peak of the heap while a plan near its ceiling is built, which this process +// does not keep, and a guard sampling it would be a guard on a clock. +func (p *planMemory) ahead() int { + if p == nil { + return math.MaxInt + } + return max(p.nextAt-p.seen, 1) +} + // stepFor is how many more files may go by before the next reading. // // It brings the reading forward to land inside the headroom that is left, so diff --git a/internal/engine/planstretch.go b/internal/engine/planstretch.go new file mode 100644 index 00000000..f147bd9b --- /dev/null +++ b/internal/engine/planstretch.go @@ -0,0 +1,158 @@ +package engine + +import ( + "time" + + "github.com/donislawdev/TestingFilesGenerator/internal/format" +) + +// How much of one target is planned at once (O355). +// +// The files of a target are planned a stretch at a time, the files of a +// stretch beside each other (beside, in parallel.go), and their answers are +// read in order before the next stretch starts. So a plan of many pictures +// takes as long as its widest stretch rather than as every file in a row, +// while everything decided per file - its name, the run's total, a refusal - +// is still decided one file after the other, in the order it always was. +// +// A stretch is shared out only when its files are worth it. A file that plans +// in a few microseconds - text, JSON - gains nothing from goroutines and pays +// for handing it to one: measured on 2026-11-18 with tools/probes/plan-ab.py, +// a hundred thousand text files planned 3% slower beside each other, while two +// thousand PNGs planned 5.8 times faster and twenty thousand PDFs 1.6 times +// (docs/PLAN-AND-WHEEL-2026-11-18.md). So every stretch is timed, and the next +// one goes on this goroutine while a file costs less than planWorthSharing. +// The clock decides how fast, never what: the plan is the same either way. +// +// Three limits on a stretch shared out, each from something a plan of one +// file at a time had without asking. +// +// - The first file of a target is planned alone. A target refused at its +// first file - the commonest refusal there is, a size its format cannot +// make - is then refused at the cost of one file rather than of a +// stretch, and that one file says what a file of the target holds. +// - What the files planned at once hold stays inside what the memory +// setting leaves (the same room the writers are held to, roomLeft). A +// picture plans by drawing and encoding itself, so sixteen of them at once +// hold sixteen pictures. How much one holds is known only once it is +// planned, so a file not yet planned is taken to hold as much as the +// dearest one so far - or more, in proportion to its size, since a picture +// that is not given its width and height grows with the bytes asked for. +// What a file holds is the larger of what writing it holds (Plan.Holds) +// and what planning it held (Plan.PlanHolds): a jxl or avif given its +// width and height is coded while it plans and holds nothing while it is +// written, and its plan is where sixteen of them would meet. +// - A stretch never passes the next reading of the plan's ceiling +// (planMemory.ahead), so a plan that crosses the ceiling is refused at the +// file it was refused at before, not a stretch later. +// +// A run that is cancelled loses at most one stretch of work it did not need, +// and a target refused part way through plans at most one stretch past the +// file that refused. + +// planStretchPerWriter is how many files a stretch of the plan gives each +// goroutine before they all wait for the slowest. +// +// A stretch ends when its last file is planned, so the goroutines that finish +// first stand idle while it is - about one file's time per stretch, and a +// longer stretch shares that over more files. A refusal part way through a +// stretch throws the rest of it away, and a longer stretch throws away more. +// The walk of a refused batch (batchminimum.go) refuses part way through by +// design, so it takes one file a goroutine, where a stretch costs one file's +// time whatever it holds and never more than asking one file at a time. +const planStretchPerWriter = 8 + +// planWorthSharing is the least planning one file has to take for the files +// of a stretch to be planned beside each other. +// +// Measured on 2026-11-18, the time of a file planned alone: text, JSON and CSV +// under what the clock of Windows can tell apart, a PDF of 16 kB 50 us, a DOCX +// 107 us, a PNG of 640x480 7.4 ms - and a PDF already plans 1.6 times faster +// shared out. The clock of Windows moves in ticks, so a stretch of text now +// and then reads as a tick and the next stretch is shared out, which the one +// after takes back. That costs a stretch, never a different plan. +const planWorthSharing = 20 * time.Microsecond + +// pace is what one target has shown so far about what its files hold. +type pace struct { + // run is what the memory setting lets the run hold, nought for no limit + // (core.MemoryLimits.Run). + run int64 + // seen says a file of the target has been planned, so most and perByte + // mean something. + seen bool + // most is the most a planned file of the target holds. + most int64 + // perByte is the most a planned file held for each byte it plans to be, + // for files asked for more bytes than any so far. + perByte float64 + // cost is what planning one file took in the last stretch: the stretch's + // time, times the goroutines it had, over its files. + cost time.Duration +} + +// saw takes in one planned file of the target: what it holds, the larger of +// what writing it holds and what planning it held. +func (p *pace) saw(plan format.Plan) { + p.seen = true + held := max(plan.Holds, plan.PlanHolds) + p.most = max(p.most, held) + if plan.Bytes > 0 { + p.perByte = max(p.perByte, float64(held)/float64(plan.Bytes)) + } +} + +// holds is what a file of the target asked for size bytes is taken to hold. +func (p *pace) holds(size int64) int64 { + return max(p.most, int64(p.perByte*float64(size))) +} + +// stretch is how many of the remaining files to plan next, and on how many +// goroutines. perWriter is planStretchPerWriter or one, largest the most +// bytes any of the remaining files is asked for, and most the most files the +// caller takes at once: what its buffer of answers holds, and fewer when the +// ceiling of the plan is read again sooner (planMemory.ahead). +// +// The buffer is the caller's to state because widthFor is read again here and +// GOMAXPROCS can rise between the two readings - Go moves it when the +// processors a container may use change - and a stretch wider than the buffer +// it was sized by would be an index out of range. +func (p *pace) stretch(remaining, perWriter int, largest int64, most int) (files, width int) { + if !p.seen || remaining <= 1 || most <= 1 { + return 1, 1 + } + width = widthFor(remaining) + if width <= 1 { + return 1, 1 + } + if p.cost < planWorthSharing { + // Files too cheap to share out, a stretch of them on this goroutine, + // timed again so a target whose files grow dearer is shared out after + // all. + return min(remaining, width*perWriter, most), 1 + } + if one := p.holds(largest); p.run > 0 && one > 0 { + width = min(width, int(max(roomLeft(p.run, int64(width)*one)/one, 1))) + } + if width <= 1 { + return 1, 1 + } + return min(remaining, width*perWriter, most), min(width, most) +} + +// planStretch plans the files of one stretch (beside) and times them for the +// next stretch's decision. +func planStretch[T any](p *pace, out []T, from, width int, ask func(i int) T) { + start := time.Now() + beside(out, from, width, ask) + p.cost = time.Since(start) * time.Duration(width) / time.Duration(max(len(out), 1)) +} + +// answer is what planning one file came to, and the seed it was planned with. +// The seed travels with the plan so the file is written and recorded with the +// one its plan was made from, worked out in one place (batchWalk.planAt). +type answer struct { + plan format.Plan + err error + seed uint64 +} diff --git a/internal/engine/plantarget.go b/internal/engine/plantarget.go index 9f7c78e1..bef7463b 100644 --- a/internal/engine/plantarget.go +++ b/internal/engine/plantarget.go @@ -3,6 +3,7 @@ package engine import ( "context" "fmt" + "slices" "github.com/donislawdev/TestingFilesGenerator/internal/core" "github.com/donislawdev/TestingFilesGenerator/internal/format" @@ -28,127 +29,154 @@ type planning struct { // reserve is how long a list the plan takes at its first file - see // planCapacity for how long, and startList for when. reserve int + // run is what the memory setting lets the run hold, which the files + // planned at once are kept inside (planstretch.go). + run int64 } // files plans every file of one target and adds them to the run. // // position is the target's place in the recipe, counted from one, and it is // what every refusal below carries so a window can mark the right box. +// +// The files are planned a stretch at a time and taken in order +// (planstretch.go), so what file does with each is what it did when they were +// planned one at a time. func (pl *planning) files(ctx context.Context, t *Target, desc format.Descriptor, targetSeed uint64, position int) error { // One ending for every file of the target, because it follows the // target's settings and every file shares them. - ext := desc.ExtensionFor(t.Properties) - damaged := t.Damage.Label() - for idx, size := range t.Sizes { - fileSeed := core.FileSeed(targetSeed, idx) - - r := requestFor(t, idx, fileSeed, damaged) - r.Bytes = size - p, err := planFile(ctx, t, desc, r) - if err != nil { - walk := batchWalk{t: t, desc: desc, targetSeed: targetSeed, damaged: damaged} - return atTarget(position, t, refusedForTheBatch(ctx, walk, idx, err)) - } - - // A size drawn from the range that this format cannot write was moved - // to the nearest one it can. Silence is banned, so it is said here. - // - // The wording carries NO number on purpose. Notes are grouped by their - // text, so a number would make every file its own line - 25 000 of them - // on a big run, which is what buried the one note that mattered before - // grouping arrived. Which files moved is still exact in the manifest, - // because the note sits on each of their entries. - if idx < len(t.SizeMoved) && t.SizeMoved[idx] { - p.Notes = append(p.Notes, format.Note{ - Code: "size_moved", - Detail: core.Says("engine.SizeMoved", "A size drawn from the range is not one this format can write, so the nearest size it can write was used instead. The file is still inside the range that was asked for."), - }) + walk := batchWalk{t: t, desc: desc, targetSeed: targetSeed, damaged: t.Damage.Label(), run: pl.run, + position: position, ext: desc.ExtensionFor(t.Properties)} + ask := func(idx int) answer { return walk.planAt(ctx, idx, t.Sizes[idx]) } + largest := slices.Max(t.Sizes) + pace := pace{run: pl.run} + got := make([]answer, min(len(t.Sizes), widthFor(len(t.Sizes))*planStretchPerWriter)) + for from := 0; from < len(t.Sizes); { + n, width := pace.stretch(len(t.Sizes)-from, planStretchPerWriter, largest, min(pl.budget.ahead(), len(got))) + planStretch(&pace, got[:n], from, width, ask) + if err := pl.stretch(ctx, walk, from, got[:n], &pace); err != nil { + return err } + from += n + } + return nil +} - name, err := renderName(t, ext, idx) - if err != nil { - return atTarget(position, t, err) - } - // Two files heading for one name means one of them would be - // destroyed by the other, and the manifest would still describe - // both. A manifest that quietly lost a file looks complete and - // reaches the test suite as a false truth. - // - // "One name" is not "the same string", and reading it that way cost - // exactly what this check exists to prevent. Most filesystems people - // run this on keep the case somebody typed and match without it - - // NTFS, APFS and exFAT do, ext4 does not - so "report.txt" and - // "REPORT.TXT" are two files on one machine and one file on the - // next. Measured on Windows, 2026-08-03: exit 0, two entries in the - // manifest, one file on the disk, and "tfg verify" failing on the - // tool's own output a second later. - // - // Case is not the only way to spell one name twice. An accented - // letter is one code point, U+00E9, and it is also the plain letter - // followed by a combining accent, U+0301. Both are valid UTF-8 and - // they print identically. APFS normalises what it is given, so on - // macOS the two spellings are one file, while NTFS and ext4 keep - // them apart. Measured there 2026-08-04: exit 0, two entries in the - // manifest, one file on the disk, and "tfg verify" failing on the - // tool's own output a second later - the same defect the case rule - // exists to stop, reached by spelling a letter the other way. - // - // So the key folds case and normalises, and neither alone is - // enough: case folding does not bring the two spellings together - // and normalising does not bring REPORT.TXT to report.txt. - // - // Refused everywhere rather than only where it bites, the same as a - // path separator and for the same reason: a recipe travels between - // machines by design, and one that quietly loses a file on somebody - // else's is worse than one refused on both. Producing such a pair on - // purpose belongs to the name laboratory and its archive mode, D10. - // No address, deliberately, and this is the one refusal here that - // keeps it. Two targets produce the pair, so naming one of them - // would send somebody to a box that is not wrong on its own - and - // which of the two to change is theirs to decide. The sentence - // names both ids, which is what a person needs and what a window - // cannot place either way. - if err := claimFileName(pl.names, position, t.ID, name); err != nil { +// stretch adds the planned files of one stretch to the run, in order, and +// stops at the first that refuses. +func (pl *planning) stretch(ctx context.Context, walk batchWalk, from int, got []answer, pace *pace) error { + for j, a := range got { + if err := pl.file(ctx, walk, from+j, a); err != nil { return err } + pace.saw(a.plan) + } + return nil +} - if pl.totalBytes, err = core.AddSizes(pl.totalBytes, p.Bytes); err != nil { - // The size of this target, for the same reason as the ceiling - // above: the total belongs to the run, the box somebody can - // change belongs to a target. - return &RecipeError{ - Setting: core.TargetAddress(position, format.SettingSize), - Detail: core.Says("engine.RunTooLarge", "target %q brings the run to a size that is too large to measure", core.A("Target", t.ID)), - Because: core.SaidOf(err)} - } +// file adds one planned file of a target to the run, or refuses the run with +// what planning it came to. +func (pl *planning) file(ctx context.Context, walk batchWalk, idx int, a answer) error { + t, p, position := walk.t, a.plan, walk.position + if a.err != nil { + return atTarget(position, t, refusedForTheBatch(ctx, walk, idx, a.err)) + } - // Here, after every check above, and not before the first target - - // see startList for why. - if err := pl.startList(ctx); err != nil { - return err - } - pl.out = append(pl.out, PlannedFile{ - ID: fmt.Sprintf("f_%04d", len(pl.out)+1), - Target: t, - Index: idx, - Name: name, - Seed: fileSeed, - Desc: desc, - Plan: p, + // A size drawn from the range that this format cannot write was moved + // to the nearest one it can. Silence is banned, so it is said here. + // + // The wording carries NO number on purpose. Notes are grouped by their + // text, so a number would make every file its own line - 25 000 of them + // on a big run, which is what buried the one note that mattered before + // grouping arrived. Which files moved is still exact in the manifest, + // because the note sits on each of their entries. + if idx < len(t.SizeMoved) && t.SizeMoved[idx] { + p.Notes = append(p.Notes, format.Note{ + Code: "size_moved", + Detail: core.Says("engine.SizeMoved", "A size drawn from the range is not one this format can write, so the nearest size it can write was used instead. The file is still inside the range that was asked for."), }) + } - // What the plan costs, rather than how many files are in it. See - // planmemory.go for why the count alone could not see this. - if err := pl.budget.account(position, len(pl.out)); err != nil { - return err - } - // Asked here rather than per target, because one target of ten - // thousand pictures is the case this is for. - if err := ctx.Err(); err != nil { - return err - } + name, err := renderName(t, walk.ext, idx) + if err != nil { + return atTarget(position, t, err) } - return nil + // Two files heading for one name means one of them would be + // destroyed by the other, and the manifest would still describe + // both. A manifest that quietly lost a file looks complete and + // reaches the test suite as a false truth. + // + // "One name" is not "the same string", and reading it that way cost + // exactly what this check exists to prevent. Most filesystems people + // run this on keep the case somebody typed and match without it - + // NTFS, APFS and exFAT do, ext4 does not - so "report.txt" and + // "REPORT.TXT" are two files on one machine and one file on the + // next. Measured on Windows, 2026-08-03: exit 0, two entries in the + // manifest, one file on the disk, and "tfg verify" failing on the + // tool's own output a second later. + // + // Case is not the only way to spell one name twice. An accented + // letter is one code point, U+00E9, and it is also the plain letter + // followed by a combining accent, U+0301. Both are valid UTF-8 and + // they print identically. APFS normalises what it is given, so on + // macOS the two spellings are one file, while NTFS and ext4 keep + // them apart. Measured there 2026-08-04: exit 0, two entries in the + // manifest, one file on the disk, and "tfg verify" failing on the + // tool's own output a second later - the same defect the case rule + // exists to stop, reached by spelling a letter the other way. + // + // So the key folds case and normalises, and neither alone is + // enough: case folding does not bring the two spellings together + // and normalising does not bring REPORT.TXT to report.txt. + // + // Refused everywhere rather than only where it bites, the same as a + // path separator and for the same reason: a recipe travels between + // machines by design, and one that quietly loses a file on somebody + // else's is worse than one refused on both. Producing such a pair on + // purpose belongs to the name laboratory and its archive mode, D10. + // No address, deliberately, and this is the one refusal here that + // keeps it. Two targets produce the pair, so naming one of them + // would send somebody to a box that is not wrong on its own - and + // which of the two to change is theirs to decide. The sentence + // names both ids, which is what a person needs and what a window + // cannot place either way. + if err := claimFileName(pl.names, position, t.ID, name); err != nil { + return err + } + + if pl.totalBytes, err = core.AddSizes(pl.totalBytes, p.Bytes); err != nil { + // The size of this target, for the same reason as the ceiling + // above: the total belongs to the run, the box somebody can + // change belongs to a target. + return &RecipeError{ + Setting: core.TargetAddress(position, format.SettingSize), + Detail: core.Says("engine.RunTooLarge", "target %q brings the run to a size that is too large to measure", core.A("Target", t.ID)), + Because: core.SaidOf(err)} + } + + // Here, after every check above, and not before the first target - + // see startList for why. + if err := pl.startList(ctx); err != nil { + return err + } + pl.out = append(pl.out, PlannedFile{ + ID: fmt.Sprintf("f_%04d", len(pl.out)+1), + Target: t, + Index: idx, + Name: name, + Seed: a.seed, + Desc: walk.desc, + Plan: p, + }) + + // What the plan costs, rather than how many files are in it. See + // planmemory.go for why the count alone could not see this. + if err := pl.budget.account(position, len(pl.out)); err != nil { + return err + } + // Asked here rather than per target, because one target of ten + // thousand pictures is the case this is for. + return ctx.Err() } // startList takes the list of the plan at its first file, as long as diff --git a/internal/format/avif/avif.go b/internal/format/avif/avif.go index a88ab443..0b70e91e 100644 --- a/internal/format/avif/avif.go +++ b/internal/format/avif/avif.go @@ -218,10 +218,14 @@ func (generator) Plan(r format.Request) (format.Plan, error) { carries, p.Notes = imagelabel.Claim(carries, m.width, m.height, len(label), p.Notes) p.Properties[format.PropertyLabelEmbedded] = carries p.Memo = m + // Coded while writing or while planning, and whichever did it held the + // picture and the encoder's work - see holdsPerPixel. The plan says which, + // so the writers wait for room only when they code, and the planner plans + // fewer at once when it does. if m.coded == nil { - // Coded while writing rather than while planning, so the writer holds - // the picture and the encoder's work - see holdsPerPixel. p.Holds = holdsPerPixel * int64(m.width) * int64(m.height) + } else { + p.PlanHolds = holdsPerPixel * int64(m.width) * int64(m.height) } return p, nil } diff --git a/internal/format/format.go b/internal/format/format.go index a02c62ef..65d6fb18 100644 --- a/internal/format/format.go +++ b/internal/format/format.go @@ -792,6 +792,14 @@ type Plan struct { // Like Work, it is a cost only the format knows, and like Work it never // reaches the manifest. Holds int64 + // PlanHolds is how much memory planning the file took at once, counted + // the way Holds is - nought for every format whose plan is arithmetic. + // A picture coded while it plans holds its pixels and the encoder's work + // then and only the coded bytes after, so its Holds is nought and this is + // not. Read by the planner alone (engine/planstretch.go), which plans as + // many files at once as the memory setting leaves room for, and takes the + // larger of the two. + PlanHolds int64 } // PropertyLabelEmbedded is the key a generator sets to say whether the label diff --git a/internal/format/jxl/jxl.go b/internal/format/jxl/jxl.go index 3c62d3ad..05c1f47f 100644 --- a/internal/format/jxl/jxl.go +++ b/internal/format/jxl/jxl.go @@ -270,10 +270,14 @@ func (generator) Plan(r format.Request) (format.Plan, error) { carries, p.Notes = imagelabel.Claim(carries, m.width, m.height, len(label), p.Notes) p.Properties[format.PropertyLabelEmbedded] = carries p.Memo = m + // Coded while writing or while planning, and whichever did it held the + // picture and the encoder's work - see holdsPerPixel. The plan says which, + // so the writers wait for room only when they code, and the planner plans + // fewer at once when it does. if m.coded == nil { - // Coded while writing rather than while planning, so the writer holds - // the picture and the encoder's work - see holdsPerPixel. p.Holds = holdsPerPixel * int64(m.width) * int64(m.height) + } else { + p.PlanHolds = holdsPerPixel * int64(m.width) * int64(m.height) } return p, nil } diff --git a/internal/guard/concurrency_test.go b/internal/guard/concurrency_test.go index 2ab99f71..aa7525c4 100644 --- a/internal/guard/concurrency_test.go +++ b/internal/guard/concurrency_test.go @@ -119,7 +119,7 @@ var mayBeConcurrent = map[string]string{ // // Numbers, the instrument, and the two mistakes made getting them: // docs/PERFORMANCE-REVIEW-2026-09-05.md section 14. - "internal/engine/parallel.go": "the planned files are written beside each other, and nothing else in the package does", + "internal/engine/parallel.go": "the planned files are written beside each other, the files of a stretch of the plan are planned beside each other, and nothing else in the package does either", // A film is its pictures, each a whole picture through gav1d on one // goroutine: the owner's thirty minute 1920x1080 film was 611.7 s on one // core of sixteen, and the window's estimate from the bytes said three diff --git a/internal/guard/foldedbatch_test.go b/internal/guard/foldedbatch_test.go index 122fabac..171e54c1 100644 --- a/internal/guard/foldedbatch_test.go +++ b/internal/guard/foldedbatch_test.go @@ -1,6 +1,7 @@ package guard import ( + "slices" "strings" "testing" @@ -157,6 +158,74 @@ func TestAFoldedBatchSaysWhatIsInIt(t *testing.T) { } } +// openBatches is which batches stand open, from the first. +func openBatches(t *testing.T, o fyne.CanvasObject) []bool { + t.Helper() + var open []bool + for i := 1; i <= batchFolds(o); i++ { + open = append(open, foldTitled(t, o, "", text.BatchHeading(i)).Open()) + } + return open +} + +// TestANewBatchIsTheOneOpen keeps a list built with Add batch a list of heads +// with the batch just made open under them - foldAbove, the owner's choice of +// 2026-11-18 (O356). The window measures every shown field before each frame +// it draws after a notch of the wheel: forty open batches cost it 11 ms a +// notch, forty folded too little to read. +// +// A copy folds the batches above it and leaves the ones below as they were, +// so a batch somebody opened further down stays open. +func TestANewBatchIsTheOneOpen(t *testing.T) { + screen := window.NewRecipe(newFakeHost(t)) + batches := screen.Object() + if got := openBatches(t, batches); !slices.Equal(got, []bool{true}) { + t.Fatalf("the screen opened with batches open %v, not one open batch, so what follows is not asked of a fresh screen", got) + } + + // The first batch opened again between the presses, so a rule folding only + // the batch that was last would leave it open: every batch above folds. + pressNamed(t, batches, text.ButtonAddBatch()) + openFold(t, batches, "", text.BatchHeading(1)) + pressNamed(t, batches, text.ButtonAddBatch()) + if got := openBatches(t, batches); !slices.Equal(got, []bool{false, false, true}) { + t.Errorf("after %q with the first batch opened again the batches stand open %v, wanted only the last one open", + text.ButtonAddBatch(), got) + } + + // Four batches standing open, open, folded, open, and the second copied. + // The copy stands third and open. The first folds as well as the second, + // so a rule folding only the batch copied is told apart, and the two below + // keep what they had - one folded, one open. + pressNamed(t, batches, text.ButtonAddBatch()) + openFold(t, batches, "", text.BatchHeading(1)) + openFold(t, batches, "", text.BatchHeading(2)) + if got := openBatches(t, batches); !slices.Equal(got, []bool{true, true, false, true}) { + t.Fatalf("the four batches stand open %v before the copy, not [true true false true], so the copy below is not asked about what it is meant to be", got) + } + nthButton(t, batches, text.ButtonDuplicateBatch(), 2).OnTapped() + if got := openBatches(t, batches); !slices.Equal(got, []bool{false, false, true, false, true}) { + t.Errorf("after copying the second of four batches they stand open %v, wanted [false false true false true]: "+ + "every batch down to the one copied folds, the copy is open and what is below it keeps its state", got) + } +} + +// nthButton is the n-th button saying label in the tree, counted from one - +// pressNamed takes the last. +func nthButton(t *testing.T, o fyne.CanvasObject, label string, n int) *parts.Button { + t.Helper() + var found []*parts.Button + walk(o, func(obj fyne.CanvasObject) { + if b, ok := obj.(*parts.Button); ok && b.Text == label { + found = append(found, b) + } + }) + if len(found) < n { + t.Fatalf("there are %d %q buttons on the screen, and this asks for number %d", len(found), label, n) + } + return found[n-1] +} + // TestARefusalOpensTheBatchItIsAbout is the guard that lets this screen fold at // all, and it is worth saying why in full. // @@ -185,7 +254,10 @@ func TestARefusalOpensTheBatchItIsAbout(t *testing.T) { // Counted by a field NAME rather than by what was typed, because what is // typed lives in an entry and the words on the screen are labels. Two - // batches with one folded leave one of each name showing. + // batches with one folded leave one of each name showing. Adding the + // second folded the first (foldAbove), so the first is opened again - + // openFold asserts it was shut - and the refused one folded. + openFold(t, batches, "", text.BatchHeading(1)) foldBatch(t, batches, 2) if got := strings.Count(shownText(batches), text.FieldNameTemplate()); got != 1 { t.Fatalf("batch 2 was folded and %d boxes called %q are still on the screen, so this guard "+ diff --git a/internal/guard/foldhead_test.go b/internal/guard/foldhead_test.go index 766d19a4..36d743d4 100644 --- a/internal/guard/foldhead_test.go +++ b/internal/guard/foldhead_test.go @@ -76,23 +76,43 @@ func TestTheWholeHeadRowOfAFoldOpensAndShutsIt(t *testing.T) { t.Error("the row was pressed with the pointer and drew the keyboard mark") } - // A button in the head does its own job and leaves the fold alone. A - // press on it goes to the button, which is on top of the row - and if the - // row answered as well, pressing Duplicate would also shut the batch. + // A button in the head does its own job: a press on it goes to the + // button, which is on top of the row, so the batch is copied rather than + // the row toggled. + // + // What the fold of batch 1 is afterwards no longer says whether the row + // answered too: a copy folds the batch it came from since 2026-11-18 + // (foldAbove). So the row is read as the button's own work begins - still + // open, or the press reached the row first - and what the copy does is + // asserted after: the batch above shut, the copy open under it. duplicate := buttonNamed(screen, text.ButtonDuplicateBatch()) if duplicate == nil { t.Fatalf("batch 1 has no %q button", text.ButtonDuplicateBatch()) } - before, batches := head.Open(), batchFolds(screen) + if !head.Open() { + t.Fatalf("batch 1 is shut before %q is pressed, so a press that also toggled its row could not be seen", text.ButtonDuplicateBatch()) + } + copyBatch, openWhenCopied := duplicate.OnTapped, false + duplicate.OnTapped = func() { + openWhenCopied = head.Open() + copyBatch() + } + batches := batchFolds(screen) buttonAt := fyne.CurrentApp().Driver().AbsolutePositionForObject(duplicate) test.TapCanvas(c, buttonAt.Add(fyne.NewPos(duplicate.Size().Width/2, duplicate.Size().Height/2))) if got := batchFolds(screen); got != batches+1 { t.Fatalf("pressing %q left %d batch(es) where %d were expected, so the press did not land on the button", text.ButtonDuplicateBatch(), got, batches+1) } - head = foldTitled(t, screen, "", text.BatchHeading(1)) - if head.Open() != before { - t.Errorf("pressing %q in the head of batch 1 also toggled the fold (open %v -> %v)", text.ButtonDuplicateBatch(), before, head.Open()) + if !openWhenCopied { + t.Errorf("pressing %q shut the row of batch 1 before the copy was made - a press on a button in the head goes to the button alone", + text.ButtonDuplicateBatch()) + } + if foldTitled(t, screen, "", text.BatchHeading(1)).Open() { + t.Errorf("pressing %q in the head of batch 1 left batch 1 open - a copy folds the batch above it", text.ButtonDuplicateBatch()) + } + if !foldTitled(t, screen, "", text.BatchHeading(2)).Open() { + t.Errorf("pressing %q in the head of batch 1 left the copy shut - the batch just made is the one open", text.ButtonDuplicateBatch()) } } diff --git a/internal/guard/gridasks_test.go b/internal/guard/gridasks_test.go new file mode 100644 index 00000000..b7533ada --- /dev/null +++ b/internal/guard/gridasks_test.go @@ -0,0 +1,129 @@ +package guard + +import ( + "fmt" + "image/color" + "slices" + "testing" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/canvas" + "fyne.io/fyne/v2/container" + + "github.com/donislawdev/TestingFilesGenerator/internal/gui/parts" +) + +// What a form grid asks its fields for, counted (O356). +// +// The toolkit asks every shown object for its smallest size before each +// frame it draws after a change - a notch of the wheel is one - and every +// answer asks everything inside it again. So a layout that asks a child +// twice makes every level above it pay twice. The grid asked a field five +// times a pass, and on 2026-11-18 forty batches on the batch screen cost +// 19.5 ms of the window's time per notch, past a frame. Asked once, the +// same forty cost 11 ms (docs/PLAN-AND-WHEEL-2026-11-18.md section 2). +// +// Nothing a person sees changes when a grid asks twice - the stored +// screens draw the same - so this is the one thing that would say so. + +// sizeAsked stands in a grid and counts how often it is asked for its size. +type sizeAsked struct { + *canvas.Rectangle + times int +} + +func newSizeAsked() *sizeAsked { + return &sizeAsked{Rectangle: canvas.NewRectangle(color.Transparent)} +} + +func (s *sizeAsked) MinSize() fyne.Size { + s.times++ + return fyne.NewSize(60, 24) +} + +// askingTwice is a layout that asks its child twice - the defect, planted, +// for the check to find. +type askingTwice struct{} + +func (askingTwice) MinSize(objects []fyne.CanvasObject) fyne.Size { + _ = objects[0].MinSize() + return objects[0].MinSize() +} + +func (askingTwice) Layout(objects []fyne.CanvasObject, size fyne.Size) { + objects[0].Resize(size) +} + +// countedGrid is a grid with something counted in every kind of place a grid +// asks about: the box of a field and what stands after it, a field whose +// refusal is on the screen, a field in a group of settings - a grid inside +// the grid - and a sentence across the row. A box to tick stands among them +// with something counted added to its column, since its own parts are the +// toolkit's: the grid levels a box to tick by the column it asked already, +// and asking it again would count two there. sentence wraps what stands +// across the row, so the canary can plant a layout there. +func countedGrid(t *testing.T, sentence func(fyne.CanvasObject) fyne.CanvasObject) (fyne.CanvasObject, map[string]*sizeAsked) { + t.Helper() + counted := map[string]*sizeAsked{} + leaf := func(name string) *sizeAsked { + counted[name] = newSizeAsked() + return counted[name] + } + plain := parts.FieldSaying("Plain", parts.NoDetail, false, nil, leaf("the box of a field")) + trailed := parts.FieldSaying("Trailed", parts.NoDetail, false, leaf("what stands after a box"), leaf("the box before it")) + refused := parts.FieldSaying("Refused", parts.NoDetail, true, nil, leaf("the box of a refused field")) + refused.Area.Say("this field is refused, so its refusal stands under the row") + if !refused.Area.Object().Visible() { + t.Fatal("the refusal under a field is not shown, so the grid is not asked about one") + } + group := parts.NewInnerFolding("Group", parts.FieldSaying("Inside", parts.NoDetail, false, nil, leaf("a box in a group of settings")).Object) + if !group.IsOpen() { + t.Fatal("the group of settings is folded, so the grid inside it is not asked") + } + tick := parts.ToggleSaying("Tick", parts.NoDetail, parts.NewToggle(nil)) + tick.Object.(*fyne.Container).Add(leaf("the column of a box to tick")) + grid := parts.Grid(plain.Object, trailed.Object, tick.Object, refused.Object, group.Object(), + parts.Wide(sentence(leaf("a sentence across the row")))) + return grid, counted +} + +// askedOnce asks a grid for its size once and says every counted thing that +// was not asked exactly once. +func askedOnce(grid fyne.CanvasObject, counted map[string]*sizeAsked) []string { + for _, c := range counted { + c.times = 0 + } + grid.MinSize() + var wrong []string + for name, c := range counted { + if c.times != 1 { + wrong = append(wrong, fmt.Sprintf("%s was asked %d time(s)", name, c.times)) + } + } + slices.Sort(wrong) + return wrong +} + +// TestAGridAsksEveryPartOfAFieldForItsSizeOnce asks a grid for its size once +// and requires every counted thing in it to have been asked exactly once - +// not twice, which is the cost, and not never, which would be a field the +// grid did not reach. +func TestAGridAsksEveryPartOfAFieldForItsSizeOnce(t *testing.T) { + ourTheme(t) + + planted, plantedCounted := countedGrid(t, func(o fyne.CanvasObject) fyne.CanvasObject { + return container.New(askingTwice{}, o) + }) + // Exactly the sentence planted, asked exactly twice, and nothing else + // wrong: a canary that took any complaint would pass on a sentence the + // grid never asked at all. + want := []string{"a sentence across the row was asked 2 time(s)"} + if wrong := askedOnce(planted, plantedCounted); !slices.Equal(wrong, want) { + t.Fatalf("canary: a sentence behind a layout that asks it twice gave %q, not %q - this check cannot see a grid that asks twice", wrong, want) + } + + grid, counted := countedGrid(t, func(o fyne.CanvasObject) fyne.CanvasObject { return o }) + for _, w := range askedOnce(grid, counted) { + t.Errorf("one pass of a grid's size: %s, wanted once. A layout that asks a child more than once a pass is paid again at every level above it, every frame after a change (O356)", w) + } +} diff --git a/internal/guard/guardpart_test.go b/internal/guard/guardpart_test.go new file mode 100644 index 00000000..6704b67d --- /dev/null +++ b/internal/guard/guardpart_test.go @@ -0,0 +1,202 @@ +package guard + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "time" +) + +// TestMain lets a job of ci.yml run the part of the guards it was handed in a +// file, rather than on its command line. +// +// Why a file. The guards are split over the parts of three jobs - the tests on +// each system, coverage and the race detector - because one process of them +// took 995 to 1080 s of an eighteen minute limit on Windows and macOS +// (2026-11-18, O361). A part is a list of test names. The race job hands its +// list to go test as one -run pattern, and on Linux that is fine. Half of this +// package is about 34 000 characters of names, and Windows hands a program at +// most 32 767 characters of command line, so the same pattern cannot reach a +// test binary there. A file can. +// +// The file is taken only when nobody asked for tests by name or for the list. +// Several guards run this binary again with -test.run, to have one test run in +// a process of its own, and the child inherits the variable: it has to run the +// one test it was started for, not the whole part over again. +func TestMain(m *testing.M) { + flag.Parse() + if err := runThePartListed(os.Getenv(guardPartVariable)); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + os.Exit(m.Run()) +} + +// guardPartVariable names the file of test names one part runs. ci.yml sets +// it, and this is the one place in Go that reads it. +const guardPartVariable = "TFG_GUARD_PART" + +// guardName is a name go test -list prints for this package, and nothing else: +// a name is joined into a pattern, so a stray character would change what the +// pattern matches rather than fail. +var guardName = regexp.MustCompile(`^(Test|Fuzz|Example)[A-Za-z0-9_]*$`) + +// runThePartListed points -test.run at the names in the file at path, one or +// more to a line. Nothing happens when path is empty or a run or a list was +// asked for by name. +// +// A relative path is read from the root of the module, where ci.yml writes +// the file and runs go test. go test starts this binary in the package's own +// directory, and read from there the same path names a file that is not +// there. +func runThePartListed(path string) error { + if path == "" || flag.Lookup("test.run").Value.String() != "" || flag.Lookup("test.list").Value.String() != "" { + return nil + } + if !filepath.IsAbs(path) { + root, err := moduleRoot() + if err != nil { + return fmt.Errorf("%s names %s, a path read from the root of the module, and the root cannot be found: %w", guardPartVariable, path, err) + } + path = filepath.Join(root, path) + } + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("%s names %s as the tests to run, and it cannot be read: %w", guardPartVariable, path, err) + } + names := strings.Fields(string(data)) + if len(names) == 0 { + return fmt.Errorf("%s names %s as the tests to run, and it lists none. A part given no test would pass having run nothing", guardPartVariable, path) + } + for _, name := range names { + if !guardName.MatchString(name) { + return fmt.Errorf("%s names %s as the tests to run, and %q in it is not a test name go test -list prints", guardPartVariable, path, name) + } + } + return flag.Set("test.run", "^("+strings.Join(names, "|")+")$") +} + +// TestAPartRunsTheTestsItIsHandedAndNoOther runs this binary again with a part +// of two cheap guards and asks which tests started. +// +// The first two children are started the way ci.yml starts a part: the file +// at the root of a module, named by a path relative to it, and the binary in +// the package's directory below, where go test starts it. Handed the file, the +// two in it run and nothing else. Handed the file and one test by name, only +// that test runs - the child a guard starts. The third is handed an empty file +// by its full path and refuses, having read it, before running anything. A +// TestMain that ignored the file would run all of the package, so every child +// has a deadline and a part that reached a third test fails here in seconds +// rather than in eighteen minutes. +func TestAPartRunsTheTestsItIsHandedAndNoOther(t *testing.T) { + part := []string{"TestAGridAsksEveryPartOfAFieldForItsSizeOnce", "TestANewBatchIsTheOneOpen"} + module := t.TempDir() + writeOrFail(t, filepath.Join(module, "go.mod"), []byte("module part\n")) + writeOrFail(t, filepath.Join(module, "mine.txt"), []byte(strings.Join(part, "\n")+"\n")) + inPackage := filepath.Join(module, "internal", "guard") + if err := os.MkdirAll(inPackage, 0o755); err != nil { + t.Fatal(err) + } + empty := filepath.Join(t.TempDir(), "empty.txt") + writeOrFail(t, empty, []byte("\n")) + + ran, out, err := runPart(t, inPackage, "mine.txt") + if err != nil || !slices.Equal(ran, part) { + t.Fatalf("handed %v in mine.txt at the root of the module, as ci.yml hands a part, the binary ran %v (%v):\n%s", part, ran, err, out) + } + ran, out, err = runPart(t, inPackage, "mine.txt", "-test.run=^"+part[1]+"$") + if err != nil || !slices.Equal(ran, part[1:]) { + t.Fatalf("handed the part and asked for %s by name, the binary ran %v (%v), and a guard's child would run the part again:\n%s", part[1], ran, err, out) + } + ran, out, err = runPart(t, "", empty) + if err == nil || len(ran) != 0 || !strings.Contains(out, guardPartVariable+" names "+empty+" as the tests to run, and it lists none") { + t.Fatalf("handed an empty part, the binary ran %v (%v) without refusing in words naming %s and the file it read:\n%s", ran, err, guardPartVariable, out) + } +} + +// TestTheLogOfAPartIsAFileGitIgnores asks git whether it ignores the log each +// job of ci.yml that runs a part of the guards writes their output into. +// +// The guards read every file git could commit, the untracked ones as well, so +// a log in the working tree is read by them while it grows. On Windows the +// tests print paths in the runner's profile, and the guard against private +// content failed on the log of its own part (2026-11-18). Linux and macOS keep +// their temporary directories outside any home, so one system of three shows +// it, and only in a part where that guard runs after a test printed a path. +func TestTheLogOfAPartIsAFileGitIgnores(t *testing.T) { + root := repoRoot(t) + // The check has to be able to say no, for a file nobody tracks either. + if gitIgnores(t, root, "a-log-no-rule-ignores.txt") { + t.Fatal("git says it ignores a-log-no-rule-ignores.txt, so this check cannot tell an ignored log from another") + } + data, err := os.ReadFile(filepath.Join(root, ".github", "workflows", "ci.yml")) + if err != nil { + t.Fatal(err) + } + // One line of shell to a command: coverage carries its pipe to tee on + // the line after the package. + text := strings.ReplaceAll(strings.ReplaceAll(string(data), "\r\n", "\n"), "\\\n", " ") + tee := regexp.MustCompile(`\./internal/guard/ [^\n]*\| tee (\S+)`) + jobs := ciJobs(text) + for _, job := range []string{"test", "race", "coverage"} { + logs := tee.FindAllStringSubmatch(jobs[job], -1) + if len(logs) == 0 { + t.Errorf("the %s job of ci.yml writes no log of the guards with tee, and it runs a part of them: this check reached nothing there", job) + } + for _, log := range logs { + if !gitIgnores(t, root, log[1]) { + t.Errorf("the %s job writes the output of its part of the guards to %s, and git does not ignore it. The guards read it while it grows, and on Windows it carries paths in the runner's profile. Ignore it in .gitignore", job, log[1]) + } + } + } +} + +// gitIgnores asks git whether it ignores path, relative to root. It skips the +// test where git cannot answer, as gitOutput does. +func gitIgnores(t *testing.T, root, path string) bool { + t.Helper() + cmd := exec.Command("git", "check-ignore", "-q", "--", path) + cmd.Dir = root + err := cmd.Run() + var exit *exec.ExitError + switch { + case err == nil: + return true + case errors.As(err, &exit) && exit.ExitCode() == 1: + return false + default: + t.Skipf("git could not answer whether it ignores %s, so this cannot be read here: %v", path, err) + return false + } +} + +// runPart runs this test binary in dir, or in this package's directory when +// dir is empty, with the part file and args. It returns the top level tests +// that started, sorted - they start in the order of the source, not of the +// file. +func runPart(t *testing.T, dir, part string, args ...string) (ran []string, out string, err error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], append([]string{"-test.v", "-test.count=1", "-test.timeout=90s"}, args...)...) + cmd.Dir = dir + defer func() { slices.Sort(ran) }() + cmd.Env = append(slices.DeleteFunc(os.Environ(), func(kv string) bool { + return strings.HasPrefix(kv, guardPartVariable+"=") + }), guardPartVariable+"="+part) + raw, err := cmd.CombinedOutput() + for _, line := range strings.Split(string(raw), "\n") { + if name, ok := strings.CutPrefix(strings.TrimSpace(line), "=== RUN "); ok && !strings.Contains(name, "/") { + ran = append(ran, name) + } + } + return ran, string(raw), err +} diff --git a/internal/guard/macosbash_test.go b/internal/guard/macosbash_test.go new file mode 100644 index 00000000..b259b55d --- /dev/null +++ b/internal/guard/macosbash_test.go @@ -0,0 +1,164 @@ +package guard + +import ( + "errors" + "fmt" + "io/fs" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +// TestAJobOnMacOSUsesOnlyWhatItsBashHas reads every job of every workflow that +// runs on macOS, and the scripts and local actions its steps name, for what +// the bash of a macOS runner cannot run. +// +// A macOS runner's bash is 3.2, and what bash 4 brought works on the two +// other systems of a matrix and ends the step 127 on the third, which nobody +// writing on Windows or Linux sees. mapfile ran on the Linux and Windows +// runners and ended the step of the test job that runs the other packages 127 +// on macOS (2026-11-18), with the trap already written down in +// docs/MACOS-SIGNING.md section 11. +// +// A job runs on macOS when its text, comments aside, names a macos- runner, +// in runs-on or in its matrix. A job that names one and keeps a step off it +// with an if is counted too, which only asks more of it. +func TestAJobOnMacOSUsesOnlyWhatItsBashHas(t *testing.T) { + for _, c := range []struct { + name string + workflow string + files map[string]string + want []string + }{ + {"mapfile on macOS", macJob("mapfile -t others < others.txt"), nil, []string{"canary.yml mac: mapfile"}}, + {"readarray on macOS", macJob("readarray -t others < others.txt"), nil, []string{"canary.yml mac: readarray"}}, + {"an associative array", macJob("declare -A seen"), nil, []string{"canary.yml mac: an associative array"}}, + {"lower case by expansion", macJob(`echo "${name,,}"`), nil, []string{"canary.yml mac: case changed by expansion"}}, + {"the timeout command", macJob("timeout 30 ./tfg version"), nil, []string{"canary.yml mac: the timeout command"}}, + {"a script the job names", macJob("bash .github/scripts/x.sh"), map[string]string{".github/scripts/x.sh": "readarray -t a < f\n"}, []string{"canary.yml mac, .github/scripts/x.sh: readarray"}}, + {"a local action the job uses", macJob("true") + " - uses: ./.github/actions/y\n", map[string]string{".github/actions/y/action.yml": "runs:\n steps:\n - run: mapfile -t a < f\n"}, []string{"canary.yml mac, .github/actions/y/action.yml: mapfile"}}, + {"the same on Linux", "on: push\njobs:\n linux:\n runs-on: ubuntu-latest\n steps:\n - run: mapfile -t a < f\n", nil, nil}, + {"what is not the construct", macJob("go test ./... -timeout 18m # mapfile here would end 127") + " timeout-minutes: 5\n", map[string]string{}, nil}, + } { + read := func(path string) (string, error) { + if text, ok := c.files[path]; ok { + return text, nil + } + return "", fs.ErrNotExist + } + faults, _, err := macOSBashFaults(map[string]string{"canary.yml": c.workflow}, read) + if err != nil || !slices.Equal(faults, c.want) { + t.Fatalf("canary %q: found %q (%v), want %q - the check cannot be trusted with the real workflows", c.name, faults, err, c.want) + } + } + + root := repoRoot(t) + paths, err := filepath.Glob(filepath.Join(root, ".github", "workflows", "*.yml")) + if err != nil || len(paths) == 0 { + t.Fatalf("no workflow under .github/workflows (%v)", err) + } + workflows := map[string]string{} + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + workflows[filepath.Base(path)] = string(data) + } + read := func(path string) (string, error) { + data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(path))) + return string(data), err + } + faults, reached, err := macOSBashFaults(workflows, read) + if err != nil { + t.Fatal(err) + } + // The test job of ci.yml runs on macOS and hands its part to a script, + // so a reading that missed either would be green over nothing. + for _, want := range []string{"ci.yml test", ".github/scripts/guard_part.sh"} { + if !slices.Contains(reached, want) { + t.Fatalf("the check did not reach %s, and it runs on macOS. It reached %q", want, reached) + } + } + if len(faults) > 0 { + t.Fatalf("a job on macOS runs what bash 3.2 does not have:\n %s\nWrite it for bash 3.2 - a while read loop, xargs, tr for case, gtimeout or a deadline in the program - or in Python.", strings.Join(faults, "\n ")) + } +} + +// macJob is a workflow of one job on macOS whose one step runs line. +func macJob(line string) string { + return "on: push\njobs:\n mac:\n runs-on: macos-latest\n steps:\n - run: " + line + "\n" +} + +// bash4Only is what a macOS runner's bash 3.2 does not have, each with the +// name a fault is reported by. +var bash4Only = []struct { + name string + is *regexp.Regexp +}{ + {"mapfile", regexp.MustCompile(`\bmapfile\b`)}, + {"readarray", regexp.MustCompile(`\breadarray\b`)}, + {"an associative array", regexp.MustCompile(`\b(declare|local|typeset)\s+-[A-Za-z]*A`)}, + {"case changed by expansion", regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*(,,?|\^\^?)\}`)}, + // coreutils, not part of macOS. The flag -timeout of go test and the key + // timeout-minutes are neither preceded by a space nor followed by one. + {"the timeout command", regexp.MustCompile(`(^|[\s;&|(])timeout\s+[0-9]`)}, +} + +// localScript is a script of the repository a step names, and localAction a +// composite action of the repository a step uses. +var ( + localScript = regexp.MustCompile(`\.github/scripts/[A-Za-z0-9_.-]+\.sh\b`) + localAction = regexp.MustCompile(`uses:\s*\./(\.github/actions/[A-Za-z0-9_.-]+)`) +) + +// macOSBashFaults reads every job of workflows that runs on macOS, with the +// scripts and local actions it names, and returns each construct of bash4Only +// it finds, as "workflow job[, file]: name", in the order read. reached is every job and +// file it read, for the caller to ask that it reached what it has to. +func macOSBashFaults(workflows map[string]string, read func(path string) (string, error)) (faults, reached []string, err error) { + for _, workflow := range slices.Sorted(maps.Keys(workflows)) { + jobs := ciJobs(workflows[workflow]) + for _, job := range slices.Sorted(maps.Keys(jobs)) { + block := jobs[job] + if !strings.Contains(block, "macos-") { + continue + } + where := workflow + " " + job + reached = append(reached, where) + texts := map[string]string{"": block} + for _, path := range localScript.FindAllString(block, -1) { + texts[path] = "" + } + for _, m := range localAction.FindAllStringSubmatch(block, -1) { + texts[m[1]+"/action.yml"] = "" + } + for _, path := range slices.Sorted(maps.Keys(texts)) { + text := texts[path] + at := where + if path != "" { + got, err := read(path) + if errors.Is(err, fs.ErrNotExist) && strings.HasSuffix(path, "/action.yml") { + got, err = read(strings.TrimSuffix(path, ".yml") + ".yaml") + } + if err != nil { + return nil, nil, fmt.Errorf("%s names %s, and it cannot be read: %w", where, path, err) + } + text, at = got, where+", "+path + reached = append(reached, path) + } + text = withoutYamlComments(text) + for _, b := range bash4Only { + if b.is.MatchString(text) { + faults = append(faults, at+": "+b.name) + } + } + } + } + } + return faults, reached, nil +} diff --git a/internal/guard/mutation/entries.py b/internal/guard/mutation/entries.py index 113c3091..de6b5e95 100644 --- a/internal/guard/mutation/entries.py +++ b/internal/guard/mutation/entries.py @@ -1024,10 +1024,11 @@ # The regression surface claimed this was proven by mutation and it was # not: no entry here named a locality test. Found 2026-08-01 by the # coverage guard, not by reading. + # Repointed 2026-11-18 (#252): the seed is worked out once, in batchWalk.planAt, and travels with the plan. The target's place stands in for the files before it "the file seed comes from a stream shared by the whole run", - "internal/engine/plantarget.go", - "core.FileSeed(targetSeed, idx)", - "core.FileSeed(targetSeed, idx+len(pl.out))", + "internal/engine/batchminimum.go", + "seed := core.FileSeed(w.targetSeed, idx)", + "seed := core.FileSeed(w.targetSeed, idx+w.position)", # Reordering only. Checked one test at a time: the same substitution # leaves the other three locality guards green, because a target # appended at the end shifts nothing before it. Naming a test that @@ -1050,10 +1051,11 @@ ( # Raising a count rewrites the files that were already there, which is # the failure somebody meets after generating a fixture set twice. + # Repointed 2026-11-18 (#252): the seed is worked out once, in batchWalk.planAt, and travels with the plan. "the file seed depends on how many files the target holds", - "internal/engine/plantarget.go", - "core.FileSeed(targetSeed, idx)", - "core.FileSeed(targetSeed, idx+len(t.Sizes))", + "internal/engine/batchminimum.go", + "seed := core.FileSeed(w.targetSeed, idx)", + "seed := core.FileSeed(w.targetSeed, idx+len(w.t.Sizes))", "TestRaisingTheCountLeavesTheEarlierFilesIdentical", ), ( @@ -7834,10 +7836,11 @@ # timeout of its own, so Go's ten minutes a package decides instead of # the twenty the job declares. The run then PANICS out of whichever test # was running, which reads as a broken test rather than a busy runner. + # Repointed 2026-11-18 (#252): the test job runs its guards in parts (O361). "a workflow runs the whole suite without stating a timeout", ".github/workflows/ci.yml", - './... -count=1 -timeout 18m\n\n - name: build the command line binary', - './... -count=1\n\n - name: build the command line binary', + "./internal/guard/ -count=1 -timeout 18m -v 2>&1", + "./internal/guard/ -count=1 -v 2>&1", "TestEveryWholeTreeTestRunStatesItsOwnTimeout", ), ( @@ -8685,24 +8688,27 @@ # --- a drawn size is snapped to one the format can write, and the move is # reported (2026-09-08, O190) --- ( + # Repointed 2026-11-18 (#252): a range is drawn a stretch at a time, drawOne and settleDrawn. "a drawn size goes back to being used whether the format can write it or not", "internal/engine/drawsizes.go", - "\t\tt.Sizes[i] = got", - "\t\tt.Sizes[i] = want", + "\t\tt.Sizes[from+j] = d.size", + "\t\tt.Sizes[from+j] = d.want", "TestASizeTheFormatCannotWriteIsMovedInsideTheRange", ), ( + # Repointed 2026-11-18 (#252): a range is drawn a stretch at a time, drawOne and settleDrawn. "a size is moved to fit the format and nothing records that it was", "internal/engine/drawsizes.go", - "\t\tt.SizeMoved[i] = got != want", - "\t\tt.SizeMoved[i] = false", + "\t\tt.SizeMoved[from+j] = d.size != d.want", + "\t\tt.SizeMoved[from+j] = false", "TestAMovedSizeIsReported", ), ( + # Repointed 2026-11-18 (#252): planning.file attaches the note, one level less deep. "the note about a moved size is attached to every file of a range", "internal/engine/plantarget.go", - "\t\tif idx < len(t.SizeMoved) && t.SizeMoved[idx] {", - "\t\tif idx < len(t.Sizes) {", + "\tif idx < len(t.SizeMoved) && t.SizeMoved[idx] {", + "\tif idx < len(t.Sizes) {", "TestAMovedSizeIsReported", ), ( @@ -8720,10 +8726,11 @@ "TestARangeHoldingNoWritableSizeIsRefusedBeforeAnyFile", ), ( + # Repointed 2026-11-18 (#252): a range is drawn a stretch at a time, drawOne and settleDrawn. "snapping starts from somewhere that depends on how many files were asked for", "internal/engine/drawsizes.go", - "\t\tgot, err := firstWritable(ctx, desc, req, want, t.Range.Max)", - "\t\tgot, err := firstWritable(ctx, desc, req, want+int64(len(t.Sizes)), t.Range.Max)", + "\tgot, plan, err := firstWritable(ctx, desc, req, want, t.Range.Max)", + "\tgot, plan, err := firstWritable(ctx, desc, req, want+int64(len(t.Sizes)), t.Range.Max)", "TestSnappingStillLeavesTheEarlierFilesAlone", ), # --- HTML is a whole page or only the blocks that sit inside one @@ -10645,10 +10652,11 @@ # --- the form in columns, groups that say what they are, and a refusal # that offers its own fix (2026-09-23, the layout prototype) --- ( + # Repointed 2026-11-18 (#252): spanOf reads what the grid asked once (gridasks.go). "every field takes a whole row of the form again", "internal/gui/parts/grid.go", - "func spanOf(o fyne.CanvasObject, column float32) int {\n", - "func spanOf(o fyne.CanvasObject, column float32) int {\n\treturn GridColumns\n", + "func spanOf(p placed, column float32) int {\n", + "func spanOf(p placed, column float32) int {\n\treturn GridColumns\n", "TestShortFieldsShareARowAndTakeOneColumnEach", ), ( @@ -15860,19 +15868,21 @@ # R05: a probe of the range draw plans the file with a context of its # own again, so a stop waits for the whole draw. The range under the # pdf floor is refused by the format in both halves of the guard. + # Repointed 2026-11-18 (#252): the probe of a draw is firstWritable's. "a range draws its sizes without looking at the stop", "internal/engine/drawsizes.go", - "_, err := planWithoutCrashing(ctx, desc, r)", - "_, err := planWithoutCrashing(context.Background(), desc, r)", + "p, err := planWithoutCrashing(ctx, desc, r)", + "p, err := planWithoutCrashing(context.Background(), desc, r)", "TestARangeStopsWhileItsSizesAreDrawn", ), ( # The same, one layer up: the engine stops handing its context to the # draw, which is the shape the draw had from 2026-09-08 until R05. + # Repointed 2026-11-18 (#252): the draw takes the run's memory limit as well. "the engine draws the sizes of a range with a context of its own", "internal/engine/engine.go", - "if err := drawSizes(ctx, t, desc, core.TargetSeed(opt.Seed, t.ID)); err != nil {", - "if err := drawSizes(context.Background(), t, desc, core.TargetSeed(opt.Seed, t.ID)); err != nil {", + "if err := drawSizes(ctx, t, desc, core.TargetSeed(opt.Seed, t.ID), run); err != nil {", + "if err := drawSizes(context.Background(), t, desc, core.TargetSeed(opt.Seed, t.ID), run); err != nil {", "TestARangeStopsWhileItsSizesAreDrawn", ), ( @@ -15897,10 +15907,11 @@ # The class guard on its own: a context from nothing in the engine, in # a place no behaviour guard of R05 or R09 looks at. Only the walk over # the source sees it, which is why that walk exists. + # Repointed 2026-11-18 (#252): the stop is asked once a file, at the end of planning.file. "the engine makes a context from nothing in a place nobody listed", "internal/engine/plantarget.go", - "// thousand pictures is the case this is for.\n\t\tif err := ctx.Err(); err != nil {", - "// thousand pictures is the case this is for.\n\t\tif err := context.Background().Err(); err != nil {", + "// thousand pictures is the case this is for.\n\treturn ctx.Err()", + "// thousand pictures is the case this is for.\n\treturn context.Background().Err()", "TestAContextIsMadeFromNothingOnlyWhereItIsMeantToStart", ), ( @@ -16059,10 +16070,11 @@ ( # Planning works to the old two gigabytes whatever the setting says - # the ceiling that could not be moved, which is R02. + # Repointed 2026-11-18 (#252): the run's limit is set beside the ceiling, and stays. "planning ignores the memory setting and works to the old ceiling", "internal/engine/engine.go", - "pl.budget = newPlanMemory(opt.Memory, limits)", - "pl.budget = newPlanMemory(opt.Memory, core.MemoryLimits{Plan: core.MaxPlanBytes})", + "pl.budget, pl.run = newPlanMemory(opt.Memory, limits), limits.Run", + "pl.budget, pl.run = newPlanMemory(opt.Memory, core.MemoryLimits{Plan: core.MaxPlanBytes}), limits.Run", "TestThePlanCeilingIsTheMemorySetting", ), ( @@ -16100,17 +16112,19 @@ ( # A jxl chosen from the ladder is coded while writing and declares # nothing, so the setting cannot see it. + # Repointed 2026-11-18 (#252): the plan says PlanHolds when it codes and Holds when the writer does. "a jxl coded while writing declares nothing", "internal/format/jxl/jxl.go", - "\tif m.coded == nil {\n\t\t// Coded while writing", - "\tif false && m.coded == nil {\n\t\t// Coded while writing", + "\tif m.coded == nil {\n\t\tp.Holds = holdsPerPixel", + "\tif false && m.coded == nil {\n\t\tp.Holds = holdsPerPixel", "TestEveryPictureItChoosesSaysWhatWritingItHolds", ), ( + # Repointed 2026-11-18 (#252): the plan says PlanHolds when it codes and Holds when the writer does. "an avif coded while writing declares nothing", "internal/format/avif/avif.go", - "\tif m.coded == nil {\n\t\t// Coded while writing", - "\tif false && m.coded == nil {\n\t\t// Coded while writing", + "\tif m.coded == nil {\n\t\tp.Holds = holdsPerPixel", + "\tif false && m.coded == nil {\n\t\tp.Holds = holdsPerPixel", "TestEveryPictureItChoosesSaysWhatWritingItHolds", ), ( @@ -16574,9 +16588,10 @@ "TestTheRaceSplitRefusesWeightsItCannotTrust", ), ( + # Repointed 2026-11-18 (#252): every job split into parts picks its part in guard_part.sh (O361). "the race job stops laying its parts out by the weights", - ".github/workflows/ci.yml", - 'python3 .github/scripts/race_parts.py split names.txt .github/race-weights "$PART" "$PARTS" > mine.txt', + ".github/scripts/guard_part.sh", + "\"$(python_here)\" .github/scripts/race_parts.py split names.txt .github/race-weights \"$part\" \"$parts\" | tr -d '\\r' > mine.txt", "cp names.txt mine.txt", "TestTheRaceJobLaysItsPartsOutByTheWeights", ), @@ -16595,9 +16610,10 @@ "TestEveryGuardRunsInExactlyOneRacePart", ), ( + # Repointed 2026-11-18 (#252): the list names the script that picks a part and the TestMain that hands it over (O361). "a pull request that changes only the race weights or the script laying them out merges with the race job skipped", ".github/workflows/ci.yml", - " .github/build-tags .github/race-weights .github/scripts/race_parts.py'", + " .github/build-tags .github/race-weights .github/scripts/race_parts.py .github/scripts/guard_part.sh internal/guard/guardpart_test.go'", " .github/build-tags'", "TestTheRaceJobLaysItsPartsOutByTheWeights", ), @@ -17683,10 +17699,11 @@ "TestTheOTLPCheckRefusesWhatAJSONReaderLetsThrough", ), ( + # Repointed 2026-11-18 (#252): the ending is worked out with the walk of a target. "the engine names every file by the format's own extension, whatever was chosen", "internal/engine/plantarget.go", - "ext := desc.ExtensionFor(t.Properties)", - "ext := desc.Extension", + "position: position, ext: desc.ExtensionFor(t.Properties)}", + "position: position, ext: desc.Extension}", "TestEveryFileIsNamedForTheSettingsItWasMadeWith", ), ( diff --git a/internal/guard/mutationcoverage_test.go b/internal/guard/mutationcoverage_test.go index eb80e6cf..40c4bdf1 100644 --- a/internal/guard/mutationcoverage_test.go +++ b/internal/guard/mutationcoverage_test.go @@ -235,6 +235,33 @@ var provenByProbe = map[string]string{ "TestSmallestIsOfferedForExactlyTheFormatsTheEngineTakesItFor": "a canary of its own - a window offering smallest for every " + "format has to disagree with the engine - a reach check that the engine both took and refused smallest, and broken by " + "hand on 2026-11-17 by offering smallest for every format: red on both screens.", + "TestAPlanIsTheSameHoweverManyFilesArePlannedAtOnce": "a canary of its own - two plans of different seeds have to be " + + "told apart - a reach check that the pictures were planned beside each other and that each refusal case is refused, " + + "and broken by hand on 2026-11-18 three ways: answers put in the wrong place, the walk reading past a refusal and " + + "nothing ever planned beside anything: red each time.", + "TestThePicturesPlannedAtOnceHoldNoMoreThanTheMemorySettingLeaves": "a reach check of its own - with room to spare the " + + "pictures have to be seen planned beside each other - and broken by hand on 2026-11-18 by dropping the memory bound " + + "and by not planning the first file of a target alone: red both times.", + "TestANewBatchIsTheOneOpen": "a reach check of its own - the screen has to open with one open batch and the " + + "first batch has to be shut before it is opened again - and broken by hand on 2026-11-18 by taking out what " + + "foldAbove sets: red, every batch left open.", + "TestAPartRunsTheTestsItIsHandedAndNoOther": "three children of its own, one of them a refusal, each with a deadline - " + + "and broken by hand on 2026-11-18 by a TestMain that ignores the file: red after 90 s, the child ran the whole package " + + "from its first test. Broken by hand again that day by a TestMain that reads a relative path from the package's " + + "directory, as every part of the first run of the parts did: red, mine.txt cannot be read.", + "TestAVerdictPassesOnlyWhenEveryPartRanAndPassed": "a table of runs, the first of which has to pass, so the refusals " + + "are not the script refusing everything.", + "TestTheLogOfAPartIsAFileGitIgnores": "a canary of its own - a name no rule ignores has to be found not ignored - " + + "and it asks that it reached the log of the test, race and coverage jobs. Broken by hand on 2026-11-18 by taking " + + "/part.log out of .gitignore: red in all three jobs.", + "TestAJobOnMacOSUsesOnlyWhatItsBashHas": "a table of canaries of its own - each construct in a job on macOS, in a " + + "script it names and in a local action it uses has to be found, the same on Linux and a comment have not to be - " + + "and it asks that it reached the test job of ci.yml and the script that job hands its part to.", + "TestAVerdictOfPartsRunsWhateverThePartsDid": "a canary of its own - the test job's verdict read with if: success() " + + "has to be found wrong.", + "TestAGridAsksEveryPartOfAFieldForItsSizeOnce": "a canary of its own - a sentence behind a layout that asks it twice " + + "has to be found - every counted thing asked exactly once, so a field the grid never reached is red too, and run on " + + "2026-11-18 against the grid before the change: red, a field asked 5 times and a field in a group 15.", "TestAValueToTypeIsTheSameInEveryLanguage": "a canary of its own - a translation that changed `all` into `wszystko` " + "has to disagree - a reach check of how many marked texts the catalogues and the site carry, and broken by hand on " + "2026-11-18 by changing one value in the Polish registry and by making no value ever a value: red both times.", @@ -507,7 +534,9 @@ var provenByProbe = map[string]string{ } var ( - testDeclaration = regexp.MustCompile(`(?m)^func (Test\w+)\(`) + // A guard takes *testing.T. TestMain takes *testing.M and is how go test + // starts the package (guardpart_test.go), not a guard of anything. + testDeclaration = regexp.MustCompile(`(?m)^func (Test\w+)\(\w+ \*testing\.T\)`) // Either quote: Python writes a string in single quotes as readily as in // double ones, and an entry written by repr() comes out in single. With // only the double quote read, nine of the guards this reported as unproven diff --git a/internal/guard/packages_test.go b/internal/guard/packages_test.go index b0f499d5..86f453a1 100644 --- a/internal/guard/packages_test.go +++ b/internal/guard/packages_test.go @@ -1,6 +1,8 @@ package guard import ( + "errors" + "fmt" "go/build" "io/fs" "os" @@ -32,17 +34,28 @@ type pkg struct { // repoRoot walks up from this test file until it finds go.mod. func repoRoot(t *testing.T) string { t.Helper() + root, err := moduleRoot() + if err != nil { + t.Fatal(err) + } + return root +} + +// moduleRoot walks up from the working directory - the package's own, where +// go test starts the binary - until it finds go.mod. TestMain needs it before +// there is a test to fail, so it reports rather than fails. +func moduleRoot() (string, error) { dir, err := os.Getwd() if err != nil { - t.Fatalf("working directory: %v", err) + return "", fmt.Errorf("working directory: %w", err) } for { if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { - return dir + return dir, nil } parent := filepath.Dir(dir) if parent == dir { - t.Fatal("go.mod not found above the test directory") + return "", errors.New("go.mod not found above the test directory") } dir = parent } diff --git a/internal/guard/partverdict_test.go b/internal/guard/partverdict_test.go new file mode 100644 index 00000000..349f47da --- /dev/null +++ b/internal/guard/partverdict_test.go @@ -0,0 +1,100 @@ +package guard + +import ( + "path/filepath" + "strings" + "testing" +) + +// The test job and coverage of ci.yml run in parts, and main's rules require +// one check per system and one for coverage under the names those jobs had +// before (O361). A verdict job carries each of those names and asks +// race_parts.py verdict whether every part ran and passed. + +// TestAVerdictPassesOnlyWhenEveryPartRanAndPassed hands the verdict the jobs of +// a run, the way the API lists them, and asks it about the guards on one +// system. +// +// Every refusal is one way a run could look green while a part of the guards +// ran nowhere: a part that failed, a part missing from the matrix, a part that +// was cancelled, two jobs claiming one part, parts that disagree about how many +// there are. The first case passes, so the refusals are not the script +// refusing everything. +func TestAVerdictPassesOnlyWhenEveryPartRanAndPassed(t *testing.T) { + python := pythonForGate(t) + other := "guards on ubuntu-latest (part 0 of 2)\tfailure" + cases := []struct { + name string + jobs []string + pass bool + }{ + {"every part passed, a part elsewhere failed", []string{ + "guards on windows-latest (part 0 of 2)\tsuccess", "guards on windows-latest (part 1 of 2)\tsuccess", other}, true}, + {"one part failed", []string{ + "guards on windows-latest (part 0 of 2)\tsuccess", "guards on windows-latest (part 1 of 2)\tfailure"}, false}, + {"one part never ran", []string{"guards on windows-latest (part 0 of 2)\tsuccess", other}, false}, + {"one part was cancelled", []string{ + "guards on windows-latest (part 0 of 2)\tcancelled", "guards on windows-latest (part 1 of 2)\tsuccess"}, false}, + {"two jobs are one part", []string{ + "guards on windows-latest (part 0 of 2)\tsuccess", "guards on windows-latest (part 0 of 2)\tsuccess", + "guards on windows-latest (part 1 of 2)\tsuccess"}, false}, + {"the parts disagree about their number", []string{ + "guards on windows-latest (part 0 of 2)\tsuccess", "guards on windows-latest (part 1 of 3)\tsuccess"}, false}, + {"a part past the number", []string{ + "guards on windows-latest (part 0 of 1)\tsuccess", "guards on windows-latest (part 1 of 1)\tsuccess"}, false}, + {"no part at all", []string{other}, false}, + } + for _, c := range cases { + jobs := writeLines(t, "jobs.tsv", c.jobs...) + out, errOut, code := runRaceParts(t, python, "verdict", "guards on windows-latest", jobs) + if (code == 0) != c.pass { + t.Errorf("%s: the verdict exited %d, and it should %s:\n%s%s", c.name, code, map[bool]string{true: "pass", false: "fail"}[c.pass], out, errOut) + } + } +} + +// TestAVerdictOfPartsRunsWhateverThePartsDid holds every verdict job of ci.yml +// to running after its parts whatever they concluded. +// +// A job whose needs failed is skipped by default, and GitHub counts a skipped +// required check as passed. A verdict without always() would therefore turn +// a red part into a green merge - silently, which is the one failure that +// matters here. The canary is the same reading of a verdict without it. +func TestAVerdictOfPartsRunsWhateverThePartsDid(t *testing.T) { + jobs := ciJobs(readFile(t, filepath.Join(repoRoot(t), ".github", "workflows", "ci.yml"))) + verdicts := 0 + for id, block := range jobs { + if !strings.Contains(block, "race_parts.py verdict ") { + continue + } + verdicts++ + if problem := verdictProblem(block); problem != "" { + t.Errorf("the job %s of ci.yml %s", id, problem) + } + } + for _, id := range []string{"verdict", "coverage-gate"} { + if !strings.Contains(jobs[id], "race_parts.py verdict ") { + t.Errorf("ci.yml has no job %s asking for a verdict on parts, and main's rules require the check it carries", id) + } + } + if verdicts < 2 { + t.Errorf("ci.yml holds %d verdict jobs, and there are two: the tests on each system and coverage", verdicts) + } + canary := strings.Replace(jobs["verdict"], "if: always()", "if: success()", 1) + if verdictProblem(canary) == "" { + t.Error("a verdict job without always() was read as fine, so the check above proves nothing") + } +} + +// verdictProblem says what is wrong with one verdict job, or nothing. +func verdictProblem(block string) string { + switch { + case !strings.Contains(block, "\n needs: "): + return "asks for a verdict on parts it does not wait for (no needs:)" + case !strings.Contains(block, "\n if: always()\n"): + return "is skipped when a part fails, and a skipped required check counts as passed. Give it if: always()" + case !strings.Contains(block, "actions: read"): + return "cannot read the jobs of its run without actions: read" + } + return "" +} diff --git a/internal/guard/planbeside_test.go b/internal/guard/planbeside_test.go new file mode 100644 index 00000000..c3f08218 --- /dev/null +++ b/internal/guard/planbeside_test.go @@ -0,0 +1,307 @@ +package guard + +import ( + "fmt" + "maps" + "reflect" + "runtime" + "slices" + "sort" + "strings" + "testing" + "time" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" + "github.com/donislawdev/TestingFilesGenerator/internal/damage" + "github.com/donislawdev/TestingFilesGenerator/internal/engine" + _ "github.com/donislawdev/TestingFilesGenerator/internal/format/all" +) + +// The files of a target are planned a stretch at a time on several goroutines +// and read in order (internal/engine/planstretch.go, O355). Two promises stand +// on that, and each has a test here. +// +// The plan is the same at any width - every name, every number, every byte a +// file will have and every refusal, word for word. That is D11 one step +// earlier than generatorbytes_test.go looks: the bytes of a file follow from +// its plan, and a plan that moved with the number of processors would be a +// hash that moves with the machine. Under the race detector in CI the same +// test is also the one that plans every format beside itself, so a generator +// whose Plan shares something it writes is a red race job rather than a file +// that is different once in a thousand runs. +// +// The pictures planned at once hold no more than the memory setting leaves. +// A picture plans by drawing and encoding itself, so planning sixteen at once +// holds sixteen pictures, the thing the memory setting is for. + +// planWidths are the two numbers of processors the plans are compared at. One +// is the plan of one file at a time, eight is more stretches than any case +// below has files for. +var planWidths = [2]int{1, 8} + +// besideCases are the shapes that reach each of the three loops planned in +// stretches: the files of a target, the draw of a range, and the walk to the +// size every file of a refused batch accepts - for files that are alike and +// for files that are not (O353). And a damage, which plans every file through +// a generator of the engine's own wrapped round the format's. +func besideCases() map[string][]engine.Target { + pictures := func() map[string]string { return map[string]string{"width": "640", "height": "480"} } + return map[string][]engine.Target{ + "png pictures": {{ID: "p", Format: "png", Sizes: engine.Uniform(40, 2<<20), Label: true, Properties: pictures()}}, + "a range of png": {{ID: "r", Format: "png", Sizes: make([]int64, 40), Label: true, + Range: engine.SizeRange{Used: true, Min: 2 << 10, Max: 96 << 10}, + // 320 by 240 rather than smaller: it encodes to 1573 B, under the + // range, and takes long enough to plan that a stretch of the draw + // is still running when plannersBeside looks (64 by 64 was over + // between two readings, one run in three). + Properties: map[string]string{"width": "320", "height": "240"}}}, + "png refused at its first file": {{ID: "f", Format: "png", Sizes: engine.Uniform(24, 1), Label: true, Properties: pictures()}}, + "jpg refused, its files unlike": {{ID: "j", Format: "jpg", Sizes: engine.Uniform(24, 36000), Label: true, Properties: pictures()}}, + "damaged pictures": {{ID: "d", Format: "png", Sizes: engine.Uniform(24, 64<<10), Label: true, Properties: pictures(), + Damage: damage.Chain{{ID: damage.Truncate, Values: damage.Values{damage.SettingMissing: "50"}}}}}, + "two targets": { + {ID: "a", Format: "jpg", Sizes: engine.Uniform(12, 64<<10), Label: true}, + {ID: "b", Format: "pdf", Sizes: engine.Uniform(12, 16<<10), Label: true}, + }, + } +} + +func TestAPlanIsTheSameHoweverManyFilesArePlannedAtOnce(t *testing.T) { + was := runtime.GOMAXPROCS(0) + t.Cleanup(func() { runtime.GOMAXPROCS(was) }) + opt := engine.Options{OutDir: t.TempDir(), Seed: 7, Command: "test"} + + // Canary: two plans that differ by their seed have to be told apart, or a + // comparison that saw nothing would pass every case below. Both accepted + // and whole, so the difference is the seed's and not a refusal's. + runtime.GOMAXPROCS(1) + one, oneErr := engine.Plan(besideCases()["png pictures"], opt) + other, otherErr := engine.Plan(besideCases()["png pictures"], engine.Options{OutDir: opt.OutDir, Seed: 8, Command: "test"}) + if oneErr != nil || otherErr != nil || len(one) != 40 || len(other) != 40 { + t.Fatalf("canary: the two plans compared were not both whole (%d files, %v; %d files, %v)", len(one), oneErr, len(other), otherErr) + } + if planParts(one, nil, other, nil) == "" { + t.Fatal("canary: two plans of different seeds compare as one - this test cannot see a plan that moved") + } + + // Every format, through the first case that pins its bytes, at three + // files: one planned alone and two beside each other. One case a format + // rather than all of them, because under the race detector every case is + // ten times dearer and a format beside itself once is what it is asked. + cases := map[string][]engine.Target{} + golden := goldenCases() + goldenNames := make([]string, 0, len(golden)) + for name := range golden { + goldenNames = append(goldenNames, name) + } + sort.Strings(goldenNames) + for _, name := range goldenNames { + target := golden[name] + if _, taken := cases["golden "+target.Format]; !taken { + target.Sizes = engine.Uniform(3, target.Sizes[0]) + cases["golden "+target.Format] = []engine.Target{target} + } + } + for name, targets := range besideCases() { + cases[name] = targets + } + names := make([]string, 0, len(cases)) + for name := range cases { + names = append(names, name) + } + sort.Strings(names) + + most := map[string]int{} + for _, name := range names { + var planned [2][]engine.PlannedFile + var errs [2]error + for i, width := range planWidths { + runtime.GOMAXPROCS(width) + targets := append([]engine.Target(nil), cases[name]...) + for path, seen := range plannersBeside(func() { planned[i], errs[i] = engine.Plan(targets, opt) }) { + most[path] = max(most[path], seen) + } + } + if why := planParts(planned[0], errs[0], planned[1], errs[1]); why != "" { + t.Errorf("%s planned at %d processors and at %d is not the same plan: %s", name, planWidths[0], planWidths[1], why) + } + if reached := reachedRefusal(name, errs[1]); reached != "" { + t.Errorf("%s: %s", name, reached) + } + // A case that is not named for a refusal has to be planned whole, or + // two refusals alike would compare as one plan and pass. + if want := filesOf(cases[name]); !strings.Contains(name, "refused") && (errs[1] != nil || len(planned[1]) != want) { + t.Errorf("%s was planned to %d of its %d files: %v", name, len(planned[1]), want, errs[1]) + } + } + + // The state this is about, asserted rather than assumed: at eight + // processors each of the three loops planned files beside each other, so + // none of the comparisons above compared one way of planning with itself. + for _, path := range slices.Sorted(maps.Keys(plannerPaths)) { + if most[path] < 2 { + t.Errorf("at most %d goroutines planned %s beside each other at %d processors - nothing of it was planned "+ + "at once, so its plans above were compared with themselves", most[path], path, planWidths[1]) + } + } +} + +// filesOf is how many files targets ask for. +func filesOf(targets []engine.Target) int { + n := 0 + for _, target := range targets { + n += len(target.Sizes) + } + return n +} + +func TestThePicturesPlannedAtOnceHoldNoMoreThanTheMemorySettingLeaves(t *testing.T) { + was := runtime.GOMAXPROCS(8) + t.Cleanup(func() { runtime.GOMAXPROCS(was) }) + const mib = int64(1) << 20 + // Two pictures, each holding about 12 MB while it is made, in 16 MB of + // room - room for one with megabytes to spare, since the heap this test + // reads is not the heap the engine reads a moment later. A png of 1500 by + // 1500 holds 11.25 MB while it is drawn and says so for the writer + // (Holds). A jxl of 600 by 600 is coded while it plans, holds 12.2 MB + // then and nothing while it is written, so only its plan says so + // (PlanHolds) - the case a planner reading Holds alone let through. + // + // After a target of text, so the pictures are not the first files of the + // run: the first file of every target is planned alone because nothing + // yet says what its files hold, and at the first file of a run the + // ceiling of the plan would hold it alone anyway. + pictures := map[string]engine.Target{ + "png": {ID: "big", Format: "png", Sizes: engine.Uniform(6, 24*mib), Properties: map[string]string{"width": "1500", "height": "1500"}}, + "jxl": {ID: "big", Format: "jxl", Sizes: engine.Uniform(6, 2*mib), Properties: map[string]string{"width": "600", "height": "600"}}, + } + for _, id := range slices.Sorted(maps.Keys(pictures)) { + targets := []engine.Target{{ID: "notes", Format: "txt", Sizes: engine.Uniform(1, 4096)}, pictures[id]} + files := filesOf(targets) + plan := func(room int64) (int, []engine.PlannedFile) { + runtime.GC() + var m runtime.MemStats + runtime.ReadMemStats(&m) + opt := engine.Options{OutDir: t.TempDir(), Seed: 7, Command: "test", Memory: core.MemoryOf(int64(m.HeapAlloc) + room)} + var err error + var planned []engine.PlannedFile + seen := plannersBeside(func() { planned, err = engine.Plan(append([]engine.Target(nil), targets...), opt) }) + if err != nil || len(planned) != files { + t.Fatalf("planning %d files of %s in %d MB of room gave %d: %v", files, id, room/mib, len(planned), err) + } + return seen[targetFiles], planned + } + + // The reach: with room to spare the pictures are planned beside each + // other, so the count below can see them when they are - and the + // picture holds what this is about where it is said to. + seen, planned := plan(2 << 30) + if seen < 2 { + t.Fatalf("%s: with 2 GB of room at most %d goroutines planned beside each other - this test cannot see "+ + "pictures planned at once", id, seen) + } + if p := planned[1].Plan; max(p.Holds, p.PlanHolds) < 10*mib { + t.Fatalf("%s: a picture of the case says it holds %d B writing and %d B planning, so the room below "+ + "does not hold it to one at a time", id, p.Holds, p.PlanHolds) + } + if seen, _ := plan(16 * mib); seen > 1 { + t.Errorf("%s: %d goroutines planned pictures that hold about 12 MB each in 16 MB of room - the plan went "+ + "past the memory setting, which leaves room for one at a time", id, seen) + } + } +} + +// reachedRefusal says how a case named for a refusal missed it, or nothing. A +// case that stopped refusing would compare two accepted plans and stay green +// while the walk of a refused batch went unasked. +func reachedRefusal(name string, err error) string { + switch { + case !strings.Contains(name, "refused"): + return "" + case err == nil: + return "is not refused any more, so the walk to the size every file accepts is not compared" + case strings.Contains(name, "unlike") && !strings.Contains(err.Error(), "files is different"): + return "is refused without saying its files differ, so no file but the first raised the size: " + err.Error() + } + return "" +} + +// planParts says where two plans of one run part, or nothing when they are one +// plan: the same files under the same names, each planned to the same bytes +// with the same facts - or the same refusal, word for word. +func planParts(a []engine.PlannedFile, aErr error, b []engine.PlannedFile, bErr error) string { + if (aErr == nil) != (bErr == nil) || aErr != nil && aErr.Error() != bErr.Error() { + return fmt.Sprintf("refused with %v against %v", aErr, bErr) + } + if len(a) != len(b) { + return fmt.Sprintf("%d files against %d", len(a), len(b)) + } + for i := range a { + x, y := a[i], b[i] + if x.ID != y.ID || x.Name != y.Name || x.Index != y.Index || x.Seed != y.Seed { + return fmt.Sprintf("file %d is %s %s against %s %s", i+1, x.ID, x.Name, y.ID, y.Name) + } + if !reflect.DeepEqual(x.Plan, y.Plan) { + return fmt.Sprintf("the plan of %s is\n %+v\nagainst\n %+v", x.Name, x.Plan, y.Plan) + } + } + return "" +} + +// targetFiles is the loop that plans the files of a target, the one +// TestThePicturesPlannedAtOnceHoldNoMoreThanTheMemorySettingLeaves counts. +const targetFiles = "the files of a target" + +// plannerPaths are the three loops planned in stretches, each named by the +// function only a goroutine planning in it has on its stack. +var plannerPaths = map[string]string{ + targetFiles: "engine.(*planning).files", + "the draw of a range": "engine.drawOne", + "the walk of a refused batch": "engine.batchWalk.sizeEveryFileTakes", +} + +// plannersBeside runs do and answers, for each loop of plannerPaths, the most +// goroutines planning in it at one moment. +// +// A goroutine planning is one with engine.askInTurn on its stack - a +// goroutine of a stretch (beside, in parallel.go) - so a goroutine a format +// starts of its own, or one an earlier test left behind, is not counted. The +// count of every goroutine in the process was what this read until the review +// of #252, which named both ways that could be wrong. Read from the stacks +// rather than told, because the engine says nothing about how it plans, and +// being told would be a promise this test could only believe. A stretch of +// pictures plans for milliseconds, so a reading every 200 us sees it, and a +// name that stops matching after a rename reads as nothing planned at once. +func plannersBeside(do func()) map[string]int { + most := map[string]int{} + stop, counted := make(chan struct{}), make(chan struct{}) + go func() { + defer close(counted) + buf := make([]byte, 8<<20) + for { + now := map[string]int{} + for _, g := range strings.Split(string(buf[:runtime.Stack(buf, true)]), "\n\n") { + if !strings.Contains(g, "engine.askInTurn") { + continue + } + for path, frame := range plannerPaths { + if strings.Contains(g, frame) { + now[path]++ + } + } + } + for path, n := range now { + most[path] = max(most[path], n) + } + select { + case <-stop: + return + case <-time.After(200 * time.Microsecond): + } + } + }() + do() + close(stop) + <-counted + return most +} diff --git a/internal/guard/raceparts_test.go b/internal/guard/raceparts_test.go index 89e65b20..4bd7d22b 100644 --- a/internal/guard/raceparts_test.go +++ b/internal/guard/raceparts_test.go @@ -75,10 +75,14 @@ func guardTestNames(t *testing.T) []string { // raceJob reads what the race job states: its parts and its timeout in seconds. func raceJob(t *testing.T) (parts int, timeout float64) { t.Helper() - ci := readFile(t, filepath.Join(repoRoot(t), ".github", "workflows", "ci.yml")) + // The race job's block alone: the test job and coverage have parts too. + ci, ok := ciJobs(readFile(t, filepath.Join(repoRoot(t), ".github", "workflows", "ci.yml")))["race"] + if !ok { + t.Fatal("ci.yml has no job called race, so its parts cannot be read") + } matrix := regexp.MustCompile(`(?m)^\s+part: \[([0-9, ]+)\]$`).FindAllStringSubmatch(ci, -1) if len(matrix) != 1 { - t.Fatalf("ci.yml states the race job's parts %d times, and this reads exactly one strategy.matrix.part", len(matrix)) + t.Fatalf("the race job of ci.yml states its parts %d times, and this reads exactly one strategy.matrix.part", len(matrix)) } parts = len(strings.Split(matrix[0][1], ",")) limit := regexp.MustCompile(`\./internal/guard/ -count=1 -race -timeout ([0-9]+)m `).FindAllStringSubmatch(ci, -1) @@ -291,23 +295,32 @@ func TestTheRaceJobLaysItsPartsOutByTheWeights(t *testing.T) { t.Fatalf("ci.yml sets the race job's watched files %d times, and this reads exactly one", len(watched)) } files := strings.Fields(watched[0][1]) - for _, want := range []string{".github/race-weights", ".github/scripts/race_parts.py"} { + for _, want := range []string{".github/race-weights", ".github/scripts/race_parts.py", ".github/scripts/guard_part.sh", "internal/guard/guardpart_test.go"} { if !slices.Contains(files, want) { t.Errorf("the race job does not run when %s changes, so a change to how its parts are laid out merges unrun", want) } } - split := `python3 .github/scripts/race_parts.py split names.txt .github/race-weights "$PART" "$PARTS" > mine.txt` + // The split itself lives in guard_part.sh, which every job split into + // parts calls (O361), so it is asked for there, once. + script := readFile(t, filepath.Join(repoRoot(t), ".github", "scripts", "guard_part.sh")) + split := `.github/scripts/race_parts.py split names.txt .github/race-weights "$part" "$parts" | tr -d '\r' > mine.txt` + if n := strings.Count(script, split); n != 1 { + t.Errorf("guard_part.sh holds %d copies of\n %s\nand the parts need exactly one", n, split) + } + race := ciJobs(ci)["race"] + pick := `bash .github/scripts/guard_part.sh pick "$PART" "$PARTS" "$LISTED" -race` + ran := `bash .github/scripts/guard_part.sh ran part.log` unlisted := `python3 .github/scripts/race_parts.py unlisted .github/race-weights part.log` - for _, line := range []string{split, unlisted} { - if n := strings.Count(ci, line); n != 1 { - t.Errorf("ci.yml holds %d copies of\n %s\nand the race job needs exactly one", n, line) + for _, line := range []string{pick, ran, unlisted} { + if n := strings.Count(race, line); n != 1 { + t.Errorf("the race job holds %d copies of\n %s\nand needs exactly one", n, line) } } if strings.Contains(ci, "| cksum)") { t.Error("ci.yml still lays the race parts out by the checksum of each name alone") } - tee, after := strings.Index(ci, "| tee part.log"), strings.Index(ci, unlisted) + tee, after := strings.Index(race, "| tee part.log"), strings.Index(race, unlisted) if tee < 0 || after < tee { - t.Error("ci.yml asks about unlisted tests before the part's log is written, so it reads nothing") + t.Error("the race job asks about unlisted tests before the part's log is written, so it reads nothing") } } diff --git a/internal/guard/screenpixels_test.go b/internal/guard/screenpixels_test.go index b66d5ca1..83cf52b1 100644 --- a/internal/guard/screenpixels_test.go +++ b/internal/guard/screenpixels_test.go @@ -308,7 +308,7 @@ type screenScene struct { } func screenScenes() []screenScene { - return []screenScene{ + return append([]screenScene{ // The whole catalogue, every part in every state, as one picture. // This is the one scene where a change of a token shows on every // control at once, which is what makes it the before-and-after of @@ -520,18 +520,34 @@ func screenScenes() []screenScene { set: func(t *testing.T, s scene) { menuUnder(t, s.tab, text.FieldPreset()).SetSelected("upload-validation") }}, + }, recipeScenes()...) +} - // The recipe screen, which arrived on 2026-08-18. It has states neither - // of the others can be put into, and every one of them is here because a - // state with no picture is a state nobody has looked at - docs/UX.md - // section 7.0 gate 1. +// recipeScenes is the recipe screen, which arrived on 2026-08-18. It has +// states neither of the others can be put into, and every one of them is here +// because a state with no picture is a state nobody has looked at - +// docs/UX.md section 7.0 gate 1. A list of its own since 2026-11-18, when the +// whole list reached the length a person can follow. +func recipeScenes() []screenScene { + return []screenScene{ {name: "recipe", tab: text.TabRecipe()}, // A second batch. This is the state the whole screen exists for, and it // is also the one that proves the form does not fall apart when the // blocks repeat - two batches means two fields called Size, two called // Format, and a heading over each block saying which is which. + // + // Adding a batch folds the one above it since 2026-11-18 (foldAbove), + // so the first is opened again: this picture is of the two blocks one + // under the other. {name: "recipe-two-batches", tab: text.TabRecipe(), set: func(t *testing.T, s scene) { pressNamed(t, s.tab, text.ButtonAddBatch()) + openFold(t, s.tab, "", text.BatchHeading(1)) + }}, + // What a press of Add batch leaves since 2026-11-18: the batch above + // folded to its head, saying what it holds, and the new one open under + // it (foldAbove, O356). + {name: "recipe-batch-added", tab: text.TabRecipe(), set: func(t *testing.T, s scene) { + pressNamed(t, s.tab, text.ButtonAddBatch()) }}, // Everything wrong at once on an untouched screen: no group name and no // size. Both marks belong to the first batch and both have to appear, diff --git a/internal/guard/testdata/screens/recipe-batch-added.png b/internal/guard/testdata/screens/recipe-batch-added.png new file mode 100644 index 00000000..a4c9c7c8 Binary files /dev/null and b/internal/guard/testdata/screens/recipe-batch-added.png differ diff --git a/internal/guard/testdata/screens/recipe-batch-added.xml b/internal/guard/testdata/screens/recipe-batch-added.xml new file mode 100644 index 00000000..644ccfc5 --- /dev/null +++ b/internal/guard/testdata/screens/recipe-batch-added.xml @@ -0,0 +1,723 @@ + + + + + + + + + + + Single batch + + + + + Presets + + + + + Several batches + + + + + Tools + + + + + Preferences + + + + + About + + + + + + + + + + + + + + + + Several batches + + + + + + + Batches of different formats and sizes, generated together in one run. + + + + + + + + + + + + + + + + + + + + + + + Build on a preset + + + + + + + + + + + + + + With the box ticked, the chosen preset's files come first and the batches below are added after them. Without it, the batches below are + everything the run makes. + + + + + + + + + + + + + Start from a preset + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Batch 1 + + + + + files · avif · 10mb + + + + + + + + + + + + Duplicate + + + + + Remove + + + + + + + + + + + + + + + + + + + + + + + + Batch 2 + + + + + + + + + + Duplicate + + + + + Remove + + + + + + + + + Format + + + + + + + + + + + + + avif + + + + + + + + + + + + + + + How many files + + + + + + + + + + default: 1 + + + + + + + + + + + + + + + + How the size is given + + + + + + + + + + + + + + + One size + A range + Around a limit + Smallest + + + + + + + + Size + + * + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Batch name + + * + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + File names + + + + + + + + + + + + + + + files_0001 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Settings for avif + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Notes for the manifest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Output + + + + + + + + + + + + + + + Output directory + + * + + + + + + + + + + + + + + + + /tfg/out + + + + + + + + Choose... + + + + + + + + + + + + + + + + + + Add beside earlier runs + + + + + + + + + + + + + + + + Manifest file name + + + + + + + + + + + + + + + manifest.json + + + + + + + + + + + + + + + + Seed + + + + + + + + + + + + + + + default: 0 + + + + + + + + + + + + + + + + + + + + + + + Label in each file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Preview + + + + + Generate + + + + + + + + + Files will go to /tfg/out + + + + + + + + + + + + + + + Donate + + + + + GitHub + + + + + + + Add a batch + + + + + + + + + + + + + + + + diff --git a/internal/guard/workflowtimeouts_test.go b/internal/guard/workflowtimeouts_test.go index e35e3612..8f11c760 100644 --- a/internal/guard/workflowtimeouts_test.go +++ b/internal/guard/workflowtimeouts_test.go @@ -34,7 +34,9 @@ import ( // And the same branch swung from 479 s to past 600 s between two runs, so the // margin was smaller than the fleet's own variance. // -// Only whole tree runs are asked. A targeted -run walks a handful of tests and +// Whole tree runs are asked, and runs of the guard package without -run, which +// is how the parts of the test job, coverage and the race detector run theirs +// (O361). A targeted -run walks a handful of tests and // a fuzz step carries -fuzztime, which is its own budget - demanding a flag // there would be noise, and a guard that cries wolf gets skipped. func TestEveryWholeTreeTestRunStatesItsOwnTimeout(t *testing.T) { @@ -46,7 +48,12 @@ func TestEveryWholeTreeTestRunStatesItsOwnTimeout(t *testing.T) { asked := 0 for _, step := range steps { command := strings.Join(strings.Fields(step.run), " ") - if !strings.Contains(command, "go test ") || !strings.Contains(command, "./...") { + wholeTree := strings.Contains(command, "./...") + // A part of a job split into parts runs the guard package with its + // tests handed over in a file, not by -run (O361), and that is most of + // the tree's time. + aPart := strings.Contains(command, "./internal/guard/ ") && !strings.Contains(command, "-run ") + if !strings.Contains(command, "go test ") || !(wholeTree || aPart) { continue } asked++ @@ -64,7 +71,7 @@ func TestEveryWholeTreeTestRunStatesItsOwnTimeout(t *testing.T) { // reading nothing - the same failure it exists to catch. if asked < 3 { t.Errorf("only %d whole tree test runs were found across the workflows, and there are at least "+ - "three - the matrix, the coverage gate and the release. Either they moved or the way this "+ + "three - the parts of the test job, coverage and the release. Either they moved or the way this "+ "reads them stopped working", asked) } } diff --git a/internal/gui/parts/foldhead.go b/internal/gui/parts/foldhead.go index 2afae4f3..7bc64d54 100644 --- a/internal/gui/parts/foldhead.go +++ b/internal/gui/parts/foldhead.go @@ -196,7 +196,15 @@ func (r *foldHeadRenderer) MinSize() fyne.Size { return fyne.NewSize(0, 0) } // Refresh draws the state: a fill under the pointer, a ring for the keyboard, // and neither at rest. The ring is a line and not a fill, for the reason Ring // gives. +// +// It lays the two out again first, because folding changes how wide the +// words are - the summary shows while folded - and leaves the row the same +// size, so the toolkit does not lay it out. Until 2026-11-18 a batch folded +// and opened again kept a fill as wide as its title and its summary under +// the pointer (found in the stored screens when batches began to fold on +// their own, O356). func (r *foldHeadRenderer) Refresh() { + r.Layout(r.head.Size()) if r.head.hovered { r.back.FillColor = PaletteColour(theme.ColorNameHover, theme.VariantDark) } else { diff --git a/internal/gui/parts/grid.go b/internal/gui/parts/grid.go index 1eca8c44..dd1ba6c9 100644 --- a/internal/gui/parts/grid.go +++ b/internal/gui/parts/grid.go @@ -172,12 +172,13 @@ func isGridCell(o fyne.CanvasObject) bool { // width it was last laid out at - see MinSize. type formGrid struct{ width float32 } -// placed is one item of a grid: where it starts, how many columns it takes -// and which row it is in. +// placed is one item of a grid: where it starts, how many columns it takes, +// which row it is in and what it asked for (gridasks.go). type placed struct { o fyne.CanvasObject row, column int span int + asked asked } // columnWidth is the width of one of GridColumns columns in a grid this wide. @@ -189,13 +190,12 @@ func columnWidth(width float32) float32 { // fewest that hold what it needs, and all of them for anything that is not a // field or was marked Wide. Worked out from the item, never written down per // field - a translation that makes a name longer makes its field wider. -func spanOf(o fyne.CanvasObject, column float32) int { - if IsWide(o) || !isGridCell(o) { +func spanOf(p placed, column float32) int { + if IsWide(p.o) || !isGridCell(p.o) { return GridColumns } - need := cellWidthNeed(o) for span := 1; span < GridColumns; span++ { - if column*float32(span)+GapColumns*float32(span-1) >= need { + if column*float32(span)+GapColumns*float32(span-1) >= p.asked.across { return span } } @@ -203,20 +203,23 @@ func spanOf(o fyne.CanvasObject, column float32) int { } // pack lays the shown items into rows at one width, in the order given: an -// item that does not fit in what is left of a row starts the next one. -func pack(objects []fyne.CanvasObject, width float32) []placed { +// item that does not fit in what is left of a row starts the next one. It +// takes the items askAll gave and hands back the ones with a height, in the +// same slice. +func pack(shown []placed, width float32) []placed { column := columnWidth(width) - var out []placed + out := shown[:0] row, used := 0, 0 - for _, o := range objects { - if !o.Visible() || o.MinSize().Height == 0 { + for _, p := range shown { + if p.asked.whole.Height == 0 { continue } - span := spanOf(o, column) + span := spanOf(p, column) if used > 0 && used+span > GridColumns { row, used = row+1, 0 } - out = append(out, placed{o: o, row: row, column: used, span: span}) + p.row, p.column, p.span = row, used, span + out = append(out, p) used += span if used >= GridColumns { row, used = row+1, 0 @@ -238,11 +241,7 @@ func rowHeights(items []placed, width float32) []float32 { for len(heights) <= p.row { heights = append(heights, 0) } - body := p.o.MinSize().Height - if cell, _ := refusalOf(p.o); cell != nil { - body = p.o.(*fyne.Container).Objects[0].MinSize().Height - } - heights[p.row] = fyne.Max(heights[p.row], body) + heights[p.row] = fyne.Max(heights[p.row], p.asked.tall) } column := columnWidth(width) under := make([]float32, len(heights)) @@ -258,7 +257,7 @@ func rowHeights(items []placed, width float32) []float32 { cell.areaWidth = width cell.areaTop = heights[p.row] + GapTight + under[p.row] if area.Visible() { - under[p.row] += area.MinSize().Height + GapTight + under[p.row] += p.asked.refusal + GapTight } } for row := range heights { @@ -280,13 +279,12 @@ func (g *formGrid) MinSize(objects []fyne.CanvasObject) fyne.Size { if width <= 0 { width = ColumnWidth - Inset*2 } + shown := askAll(objects) var minWidth, height float32 - for _, o := range objects { - if o.Visible() { - minWidth = fyne.Max(minWidth, cellWidthNeed(o)) - } + for _, p := range shown { + minWidth = fyne.Max(minWidth, p.asked.across) } - items := pack(objects, width) + items := pack(shown, width) gaps := rowGaps(items) for i, h := range rowHeights(items, width) { height += gaps[i] + h @@ -297,7 +295,7 @@ func (g *formGrid) MinSize(objects []fyne.CanvasObject) fyne.Size { func (g *formGrid) Layout(objects []fyne.CanvasObject, size fyne.Size) { g.width = size.Width column := columnWidth(size.Width) - items := pack(objects, size.Width) + items := pack(askAll(objects), size.Width) heights := rowHeights(items, size.Width) gaps := rowGaps(items) tops := make([]float32, len(heights)) @@ -306,7 +304,7 @@ func (g *formGrid) Layout(objects []fyne.CanvasObject, size fyne.Size) { } for _, p := range items { width := column*float32(p.span) + GapColumns*float32(p.span-1) - height := p.o.MinSize().Height + height := p.asked.tall if cell, _ := refusalOf(p.o); cell != nil { height = heights[p.row] } @@ -359,15 +357,3 @@ func isGroup(o fyne.CanvasObject) bool { _, group := layoutOf(o).(groupCell) return group } - -// cellWidthNeed is how wide an item asks to be in a grid. A field asks with -// its body alone: its refusal is laid under the row, across it, so a long -// sentence or the button under it must not widen the field's column - -// measured on the prototype, the button offering the smallest size pushed the -// size box to two columns and the field after it to the next row. -func cellWidthNeed(o fyne.CanvasObject) float32 { - if cell, _ := refusalOf(o); cell != nil { - return o.(*fyne.Container).Objects[0].MinSize().Width - } - return o.MinSize().Width -} diff --git a/internal/gui/parts/gridasks.go b/internal/gui/parts/gridasks.go new file mode 100644 index 00000000..a0e5d1da --- /dev/null +++ b/internal/gui/parts/gridasks.go @@ -0,0 +1,96 @@ +package parts + +import "fyne.io/fyne/v2" + +// What a grid asks of its items: every part of every item, once a pass. +// +// The toolkit asks every shown object for its smallest size before each +// frame it draws after a change, and a notch of the wheel is a change. An +// object's answer asks every object inside it again, and nothing is +// remembered between the two (fyne v2.8.2, EnsureMinSize in +// internal/driver/common/canvas.go, read 2026-11-18). So whatever one +// layout asks of a child twice, every level above it pays twice as well. +// +// The grid asked a field for its size five times a pass - for the width, to +// see whether it had a height, for its columns, for its row and for its body +// - and a group of settings three times, and a batch is a grid holding +// groups holding grids. Measured on 2026-11-18 (O356, docs/PLAN-AND-WHEEL- +// 2026-11-18.md section 2): with forty batches on the screen a notch cost the +// window 19.5 ms, past the 16.7 ms of a frame at 60 Hz. +// +// So a grid asks each part of an item once and works the item's own size +// out from those answers by the item's own rule - stacked for the column a +// field is, toggleCell.over for a box to tick - rather than asking the item +// too. + +// asked is what one shown item of a grid needs. +type asked struct { + // whole is the item's own smallest size. An item with no height takes + // no row. + whole fyne.Size + // across is the width it needs in a column. A field asks with its body + // alone: its refusal is laid under the row, across it, so a long + // sentence or the button under it must not widen the field's column - + // measured on the prototype of 2026-09-23, the button offering the + // smallest size pushed the size box to two columns and the field after + // it to the next row. + across float32 + // tall is its height in its row: a field's body without its refusal, + // and a box to tick with the room its row gives it (levelToggles). + tall float32 + // refusal is the height of a field's refusal, while one is shown. + refusal float32 + // column is a box to tick's column before that room, which is what + // levelToggles adds it to once the packing says which row it is in. + column fyne.Size +} + +// askAll asks every shown item of a grid what it needs, in order. +func askAll(objects []fyne.CanvasObject) []placed { + shown := make([]placed, 0, len(objects)) + for _, o := range objects { + if o.Visible() { + shown = append(shown, placed{o: o, asked: ask(o)}) + } + } + return shown +} + +// ask is what one item needs. +func ask(o fyne.CanvasObject) asked { + if cell, _ := refusalOf(o); cell != nil { + return askField(cell.column, o.(*fyne.Container).Objects) + } + if t, toggle := layoutOf(o).(*toggleCell); toggle { + col := t.stack(o.(*fyne.Container).Objects) + whole := t.over(col) + return asked{whole: whole, across: whole.Width, tall: whole.Height, column: col} + } + whole := o.MinSize() + return asked{whole: whole, across: whole.Width, tall: whole.Height} +} + +// askField is what a field with a refusal under it needs: its body asked +// once whether it is shown or not, since its width and height are what the +// grid lays out by, the refusal and anything after it asked once while +// shown, and the field's own size stacked from those the way its column +// stacks them. +func askField(c column, objects []fyne.CanvasObject) asked { + body := objects[0].MinSize() + var s stacked + var refusal float32 + for i, o := range objects { + if !o.Visible() { + continue + } + size := body + if i > 0 { + size = o.MinSize() + } + if i == 1 { + refusal = size.Height + } + s.add(size) + } + return asked{whole: s.with(c.gap), across: body.Width, tall: body.Height, refusal: refusal} +} diff --git a/internal/gui/parts/parts.go b/internal/gui/parts/parts.go index ed68af58..cb370951 100644 --- a/internal/gui/parts/parts.go +++ b/internal/gui/parts/parts.go @@ -722,21 +722,37 @@ func Column(gap float32, children ...fyne.CanvasObject) *fyne.Container { type column struct{ gap float32 } func (c column) MinSize(objects []fyne.CanvasObject) fyne.Size { - size := fyne.NewSize(0, 0) - shown := 0 + var s stacked for _, o := range objects { - if !o.Visible() { - continue + if o.Visible() { + s.add(o.MinSize()) } - min := o.MinSize() - size.Width = fyne.Max(size.Width, min.Width) - size.Height += min.Height - shown++ } - if shown > 1 { - size.Height += c.gap * float32(shown-1) + return s.with(c.gap) +} + +// stacked is the size of things standing one under another, added one answer +// at a time: as wide as the widest, as tall as all of them and the gaps +// between. The rule of column.MinSize, in a type of its own so a grid that +// has asked a field's parts already stacks them by the same rule +// (gridasks.go). +type stacked struct { + size fyne.Size + shown int +} + +func (s *stacked) add(min fyne.Size) { + s.size.Width = fyne.Max(s.size.Width, min.Width) + s.size.Height += min.Height + s.shown++ +} + +// with is the stack with gap between every two things in it. +func (s stacked) with(gap float32) fyne.Size { + if s.shown > 1 { + s.size.Height += gap * float32(s.shown-1) } - return size + return s.size } func (c column) Layout(objects []fyne.CanvasObject, size fyne.Size) { diff --git a/internal/gui/parts/togglefield.go b/internal/gui/parts/togglefield.go index d0318c9f..22e31ec2 100644 --- a/internal/gui/parts/togglefield.go +++ b/internal/gui/parts/togglefield.go @@ -50,9 +50,21 @@ func (t *toggleCell) drop() float32 { } func (t *toggleCell) MinSize(objects []fyne.CanvasObject) fyne.Size { - size := column{gap: GapTight}.MinSize(objects) - size.Height += t.drop() - return size + return t.over(t.stack(objects)) +} + +// stack is the cell's column: the box with its name, and its refusal under +// it. +func (*toggleCell) stack(objects []fyne.CanvasObject) fyne.Size { + return column{gap: GapTight}.MinSize(objects) +} + +// over is the cell's size from the size of its column: the column, with the +// room its row gives it above. Apart from MinSize so a grid that has asked +// the column already can level the box without asking again (gridasks.go). +func (t *toggleCell) over(col fyne.Size) fyne.Size { + col.Height += t.drop() + return col } func (t *toggleCell) Layout(objects []fyne.CanvasObject, size fyne.Size) { @@ -69,7 +81,8 @@ func (t *toggleCell) Layout(objects []fyne.CanvasObject, size fyne.Size) { } // levelToggles tells every box to tick in a packing whether it shares its -// row with a named field. +// row with a named field, and works out the height that gives it from the +// column it was asked for while being packed. func levelToggles(items []placed) { named := map[int]bool{} for _, p := range items { @@ -77,9 +90,10 @@ func levelToggles(items []placed) { named[p.row] = true } } - for _, p := range items { + for i, p := range items { if t, toggle := layoutOf(p.o).(*toggleCell); toggle { t.level = named[p.row] + items[i].asked.tall = t.over(p.asked.column).Height } } } diff --git a/internal/gui/window/recipelist.go b/internal/gui/window/recipelist.go index 85fb0c08..6c05d57c 100644 --- a/internal/gui/window/recipelist.go +++ b/internal/gui/window/recipelist.go @@ -11,12 +11,34 @@ import ( // on 2026-11-03, when that file reached its ceiling - the screen builds the // batches, and this is the part that only changes how many there are. -// addBatch puts another batch at the end of the list. +// addBatch puts another batch at the end of the list, open under the ones +// before it, which fold - see foldAbove. func (r *Recipe) addBatch() { + foldAbove(r, len(r.batches)) newBatchAtTheEnd(r) afterAPress(r) } +// foldAbove folds every batch above the place a new one is about to stand, +// so the batch just added or copied is the one open, under heads that each +// say what their batch holds (the owner's choice of 2026-11-18, O356). +// +// What it is for, measured with docs/PLAN-AND-WHEEL-2026-11-18.md section 2: +// the window measures every shown field before each frame it draws after a +// notch of the wheel, so forty open batches cost it 11 ms a notch and forty +// folded ones too little to read. A batch was open from the moment it was +// added until somebody folded it, and a list built by pressing Add batch was +// a list of open batches. Batches below a copy keep whatever state they had: +// nothing a person did not touch moves under them. +// +// Folded is not out of reach: a press refused about a field in a folded batch +// opens that batch first (runner.unfold). +func foldAbove(r *Recipe, place int) { + for _, b := range r.batches[:place] { + b.folded = true + } +} + // newBatchAtTheEnd puts a batch after the last one, without saying what the // form comes to. Apart from addBatch for the one caller that is not a press: // the base switched off with no batch left brings one back, and the switch's @@ -60,6 +82,7 @@ func (r *Recipe) duplicateBatch(index int) { to.sizeWay.SetSelected(from.sizeWay.Selected) } + foldAbove(r, index+1) rest := append([]*batch{to}, r.batches[index+1:]...) r.batches = append(r.batches[:index+1], rest...) afterAPress(r)