From ce9f52937ec9f706d1ed5f755abf8c249233d868 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 24 Aug 2026 00:58:07 +0200 Subject: [PATCH 01/16] ci: add renovate with the MSRV floor scoped to 1.88 Dependency updates were manual. Renovate now proposes them weekly, grouped into one PR for cargo patch updates and one for GitHub Actions, with 0.x minor bumps left on their own because in cargo they are breaking. The floor is scoped twice over. constraints.rust pins the toolchain Renovate runs cargo update with, and a crate-datasource rule carries the same floor as ~1.88 so release filtering actually holds: the comparison runs under cargo versioning, where a bare 1.88 reads as ^1.88 and a crate declaring rust-version = "1.90.0" satisfies it. Verified against a 1.87 floor, where ratatui 0.30.2 and image 0.25.10 drop out as they should. Renovate also reads its own config and offered to move that floor to 1.98, which is why the rust tool constraint and the msrv job's pinned toolchain are both disabled. The floor moves by hand or not at all. --- .github/renovate.json5 | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 .github/renovate.json5 diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 0000000..40c88f4 --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,82 @@ +{ + $schema: "https://docs.renovatebot.com/renovate-schema.json", + + extends: ["config:recommended"], + + timezone: "Europe/Berlin", + schedule: ["before 7am on monday"], + labels: ["dependencies"], + prConcurrentLimit: 3, + // A crates.io release cannot be unpublished, but it can be yanked. Waiting three + // days means a bad release is usually already yanked before a PR opens for it. + minimumReleaseAge: "3 days", + separateMinorPatch: true, + + // Installs the toolchain Renovate runs `cargo update` with, and is the baseline for + // constraintsFiltering. "1.88" is a range in rust-release-channel versioning, so the + // tool resolver picks the newest 1.88.x rather than failing to parse a single version. + constraints: { + rust: "1.88", + }, + constraintsFiltering: "strict", + + packageRules: [ + { + // The MSRV gate, in the only shape that works. Release filtering compares under + // cargo versioning, where a bare "1.88" means ^1.88, and a crate spelling its MSRV + // with three components ("1.90.0", which is what ratatui and image do) is then a + // valid semver version that satisfies ^1.88, so it slips through. "~1.88" is + // >=1.88.0 <1.89.0, which makes subset() the deciding check: [1.88, 1.89) sits + // inside ^1.85 so a crate needing 1.85 stays eligible, and does not sit inside + // ^1.90 so that one is dropped. + // + // The config validator warns that "~1.88" is not a valid rust-release-channel + // version. That is expected: it validates every constraints.rust against the + // toolchain versioning even when the rule is scoped to the crate datasource. The + // warning is the price of the filter working on three-component MSRVs. Reverting + // to "1.88" silences it and reopens the hole. + // + // Crates that declare no rust-version at all are never filtered, so the msrv job + // in ci.yml stays the hard gate; this only keeps doomed PRs from being opened. + matchDatasources: ["crate"], + constraints: { + rust: "~1.88", + }, + }, + { + // Both of these are the 1.88 floor itself, not dependencies to keep current. + // Renovate reads its own config with the renovate-config manager and offered to + // move constraints.rust to 1.98; the msrv job's toolchain is the same trap from + // the other side. The floor moves by hand, together with rust-version in + // Cargo.toml, or not at all. + matchManagers: ["renovate-config", "github-actions"], + matchPackageNames: ["rust", "dtolnay/rust-toolchain"], + enabled: false, + }, + { + // Cargo.toml carries loose ranges, so patch updates land in Cargo.lock alone and + // there is nothing to review one crate at a time. + matchManagers: ["cargo"], + matchUpdateTypes: ["patch"], + groupName: "cargo patch updates", + }, + { + matchManagers: ["github-actions"], + groupName: "github actions", + }, + { + // ratatui and crossterm are 0.x, so a minor bump is a breaking one, and it moves + // the pinned floor in Cargo.toml rather than only the lockfile. + matchManagers: ["cargo"], + matchUpdateTypes: ["minor", "major"], + groupName: null, + labels: ["dependencies", "needs-review"], + }, + ], + + // Refreshes transitive dependencies that no direct requirement pulls forward. + lockFileMaintenance: { + enabled: true, + schedule: ["before 7am on the first day of the month"], + }, +} From 508d060ccd25a8b805215e0043a2e797e37096bb Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 24 Aug 2026 21:08:29 +0200 Subject: [PATCH 02/16] ci: install zizmor through install-action, lint shell and workflows locally The zizmor job was the only step in CI installing its tool a different way: pipx pulled a Python toolchain into the runner to execute a Rust binary, while nextest, cargo-deny and cargo-codspeed all came from taiki-e/install-action. install-action carries a zizmor manifest with 1.28.0 as an exact key, so the swap keeps the pin and strengthens it, since the manifest verifies the artifact digest rather than trusting the name and version PyPI resolves at run time. shellcheck and actionlint run at pre-commit rather than in CI. install.sh is the gap they close: 334 lines of POSIX sh served over curl | sh, shipped to users, and read by nothing else in the gate. actionlint does not overlap zizmor, which audits for security while actionlint audits for correctness, and a workflow can be perfectly safe and still never run. Neither goes in CI: install-action has no actionlint manifest and it is a Go binary, so the cargo-binstall fallback cannot build it either, and adding it would mean a new third-party action or a curl | bash for a linter that only matters at authoring time. --- .github/workflows/ci.yml | 5 ++++- prek.toml | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff9ef3b..180b883 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,6 +72,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - run: pipx run zizmor==1.28.0 --min-severity high .github/workflows/ + - uses: taiki-e/install-action@v2 + with: + tool: zizmor@1.28.0 + - run: zizmor --min-severity high .github/workflows/ env: GH_TOKEN: ${{ github.token }} diff --git a/prek.toml b/prek.toml index 607074f..9e5522b 100644 --- a/prek.toml +++ b/prek.toml @@ -20,3 +20,19 @@ entry = "just ci" always_run = true pass_filenames = false stages = ["pre-push"] + +[[repos.hooks]] +id = "shellcheck" +name = "shellcheck (shell scripts)" +language = "system" +entry = "shellcheck" +files = '\.sh$' +stages = ["pre-commit"] + +[[repos.hooks]] +id = "actionlint" +name = "actionlint (workflow correctness)" +language = "system" +entry = "actionlint" +files = '^\.github/workflows/.*\.ya?ml$' +stages = ["pre-commit"] From a9bf7953ba6bde31537902e43ad739f06bb79730 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 16:52:59 +0200 Subject: [PATCH 03/16] ci: test on macOS and Windows, and stop CI resolving off the lockfile Two binaries ship every release that CI had never compiled. The release matrix builds aarch64-apple-darwin and x86_64-pc-windows-msvc; ci.yml ran on ubuntu-latest alone. There is not one cfg(windows) or cfg(unix) in src/, which is exactly why a break there would be invisible: every bit of platform divergence arrives through crossterm and ratatui, in raw-mode entry and restore and the non-TTY --frame and --plain paths, and none of it was exercised off Linux. tests/launch.rs spawns the real binary, so it is the test most likely to catch such a break and the one that never ran where breaks happen. The new platforms go in a separate `cross` job rather than as a matrix axis on the existing one. The repository ruleset requires a status check named exactly "fmt + clippy + test"; matrixing that job renames its checks to "fmt + clippy + test (ubuntu-latest)" and the required context would never report again, blocking every PR. Keeping the name intact also means a red macOS or Windows leg does not block merging until those contexts are added to the ruleset deliberately. Only the msrv job passed --locked, so clippy, nextest and the bench smoke were free to resolve newer dependencies than Cargo.lock describes and CI could pass against a dependency set nothing else had seen. They now all pass it, which is what makes the lockfile mean something. Tests also never ran without the png feature: clippy covered the default build, nextest did not. That path is the shipped binary. It now has a nextest line of its own, and 168 tests pass there today. cargo doc moves in from `just check`. The justfile explains it sat locally because nothing in CI built the docs, so build.warnings = "deny" gated only whoever ran the hook. That argues for adding it here rather than leaving it out, since --no-verify and any bot commit bypass the hook entirely, and it costs about twenty seconds. The push trigger was unfiltered while pull_request already covered PRs, so every branch push ran the whole gate twice. It is scoped to main now, with a concurrency group so a superseded push stops instead of running to completion, and a timeout on every job. persist-credentials: false on each checkout closes the deferred zizmor artipacked finding for this workflow. Nothing here needs to push. --- .github/workflows/ci.yml | 73 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 180b883..dd0fce3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,19 +2,27 @@ name: CI on: push: + branches: [main] pull_request: branches: [main] permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: test: name: fmt + clippy + test runs-on: ubuntu-latest + timeout-minutes: 30 steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: @@ -26,32 +34,77 @@ jobs: run: cargo fmt --check - name: clippy (default features) - run: cargo clippy --all-targets -- -D warnings + run: cargo clippy --locked --all-targets -- -D warnings - name: clippy (png feature) - run: cargo clippy --all-targets --features png -- -D warnings + run: cargo clippy --locked --all-targets --features png -- -D warnings - name: clippy (celsius-lab) - run: cargo clippy -p celsius-lab --all-targets -- -D warnings + run: cargo clippy --locked -p celsius-lab --all-targets -- -D warnings + + - name: doc + run: cargo doc --locked --no-deps --features png - uses: taiki-e/install-action@v2 with: tool: nextest - - name: test - run: cargo nextest run --features png + - name: test (default features) + run: cargo nextest run --locked + + - name: test (png feature) + run: cargo nextest run --locked --features png - name: test (celsius-lab) - run: cargo nextest run -p celsius-lab + run: cargo nextest run --locked -p celsius-lab - name: bench (compile + smoke) - run: cargo bench --bench render -- --test + run: cargo bench --locked --bench render -- --test + + cross: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - uses: Swatinem/rust-cache@v2 + + - name: clippy (png feature) + run: cargo clippy --locked --all-targets --features png -- -D warnings + + - uses: taiki-e/install-action@v2 + with: + tool: nextest + + - name: test (default features) + run: cargo nextest run --locked + + - name: test (png feature) + run: cargo nextest run --locked --features png + + - name: test (celsius-lab) + run: cargo nextest run --locked -p celsius-lab msrv: name: msrv (1.88.0) runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@1.88.0 - uses: Swatinem/rust-cache@v2 - run: cargo check --locked @@ -60,8 +113,11 @@ jobs: deny: name: cargo deny (advisories + licences + sources + bans) runs-on: ubuntu-latest + timeout-minutes: 15 steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: taiki-e/install-action@v2 with: tool: cargo-deny @@ -70,8 +126,11 @@ jobs: zizmor: name: zizmor (Actions security) runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: taiki-e/install-action@v2 with: tool: zizmor@1.28.0 From e602a8e964fea37ef86805409da24b05c46143fe Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 16:54:46 +0200 Subject: [PATCH 04/16] ci: build release binaries from the lockfile and attest their provenance upload-rust-binary-action defaults locked to false, so every binary we have shipped was built against a fresh dependency resolution rather than the Cargo.lock the oracle, the goldens and CI all ran against. For a crate whose whole premise is that one seed produces one set of pixels, letting the shipped artifact resolve its own dependency set is the wrong default. install.sh downloads the .sha256 sibling and refuses to install on a mismatch, which proves the archive survived the network intact. It cannot prove where the archive came from, because the digest is published by the same job that publishes the archive: anyone who could replace one could replace the other. actions/attest signs a SLSA provenance statement with the workflow's own OIDC identity, so `gh attestation verify -R lmarkmann/celsius` answers the question the checksum cannot. It binds through subject-checksums rather than subject-path because the action already writes the digest file in sha256sum format and exposes its name as an output. That attests the digest we actually published, instead of re-deriving one from a path and hoping the two agree. persist-credentials: false on the two checkouts that only read closes the deferred zizmor artipacked finding for these workflows. The tap checkout in the homebrew job says true explicitly, because it pushes the rendered formula and .github carries no comments to say so otherwise. --- .github/workflows/codspeed.yml | 2 ++ .github/workflows/release.yml | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 7859c81..934b9db 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -17,6 +17,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a3b31c..ef5316a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,8 @@ jobs: name: upload ${{ matrix.target }} permissions: contents: write + id-token: write + attestations: write strategy: fail-fast: false matrix: @@ -25,13 +27,20 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: taiki-e/upload-rust-binary-action@v1 + id: upload with: bin: celsius target: ${{ matrix.target }} archive: $bin-$tag-$target checksum: sha256 + locked: true token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/attest@v4 + with: + subject-checksums: ${{ steps.upload.outputs.sha256 }} homebrew: name: bump homebrew formula @@ -42,6 +51,7 @@ jobs: with: repository: lmarkmann/homebrew-tap token: ${{ secrets.HOMEBREW_TAP_TOKEN }} + persist-credentials: true path: tap - name: render formula From c314923a2602b4fd7310f3b5d047c59f0142d6ff Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 17:23:16 +0200 Subject: [PATCH 05/16] test: give mutation testing a home instead of a gitignored directory rules/determinism.md argues that a golden hash proves the render did not change by accident rather than that it is right, and that survivors in a well-covered file are coverage theatre. The tool that enforces that argument ran by hand, occasionally, and left its findings in mutants.out/, which .gitignore drops. The only surviving record was a run against v0.4.7 from 2026-07-27, and nothing in the repository could say whether it still described the code. It did not. Re-running src/moon.rs against 0.6.0 returns the same five survivors as that July run, at the same two lines: the disc_sample radius comparison and its squared-distance term, and the phase_lit bound. src/gradient.rs returns the blend comparison too, at line 93 rather than the old 74 because the code moved around it. .claude/CLAUDE.md records all of these as killed. They are not, and the point of committing the config is that the next such claim can be checked rather than believed. The config pins the three things that decide whether a run is reproducible. --features png, because the oracle, the analytic properties and the lightning overlay are the tests that assert on rendered output and none of them compile without it, so mutants would otherwise only have to survive the unit tests. nextest, so the runner matches `just test` and CI. A 60s floor, because the suite runs in under a second and the stock 20s minimum would let a mutant that merely makes the renderer slow read as a timeout instead of a kill. src/pigs.rs is excluded. It is gated to a 42-minute window over one district, so nothing can reach it and all 166 of its mutants would survive and bury the files that are genuinely under test. CI runs --in-diff on pull requests only: the full crate is ~3600 mutants and hours of wall clock, while a diff is minutes. It is continue-on-error for now, because the survivors above mean main does not currently pass a run of its own and a gate that is red on arrival gets ignored rather than fixed. .cargo/ joins the exclude list. Cargo packages every root file it is not told to drop and makes no exception for it, so without that line every edit to a mutation-testing knob would cut a patch release. --- .cargo/mutants.toml | 20 ++++++++++++ .github/workflows/mutants.yml | 59 +++++++++++++++++++++++++++++++++++ Cargo.toml | 4 +++ justfile | 19 ++++++++--- 4 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 .cargo/mutants.toml create mode 100644 .github/workflows/mutants.yml diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 0000000..192b868 --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1,20 @@ +# The oracle, the analytic properties and the lightning overlay all live behind +# `png`, and they are the tests that actually assert on rendered output. Without +# this a mutant only has to survive the unit tests, which is the coverage theatre +# `.claude/rules/determinism.md` warns about. +additional_cargo_test_args = ["--features", "png"] + +# Same runner as `just test` and CI, so a survivor here is reproducible there. +test_tool = "nextest" + +# A golden render is ~0.5s and the suite is ~0.6s, so the default 20s floor would +# let a mutant that merely makes the renderer slow read as a timeout rather than a +# caught mutant. 60s is well clear of a real run and still catches an infinite loop. +minimum_test_timeout = 60 + +exclude_globs = [ + # Location-gated easter egg. Nothing can reach it without pinning the clock to + # a 42-minute window over one Hong Kong district, so every mutant in it would + # survive and bury the signal from code that is genuinely under test. + "src/pigs.rs", +] diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml new file mode 100644 index 0000000..fbd1c10 --- /dev/null +++ b/.github/workflows/mutants.yml @@ -0,0 +1,59 @@ +name: mutants + +on: + pull_request: + branches: [main] + paths: + - "src/**" + - "tests/**" + - "Cargo.toml" + - "Cargo.lock" + - ".cargo/mutants.toml" + - ".github/workflows/mutants.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: mutants-${{ github.ref }} + cancel-in-progress: true + +jobs: + in-diff: + name: surviving mutants in the diff + runs-on: ubuntu-latest + timeout-minutes: 45 + continue-on-error: true + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: dtolnay/rust-toolchain@stable + + - uses: Swatinem/rust-cache@v2 + + - uses: taiki-e/install-action@v2 + with: + tool: cargo-mutants,nextest + + - name: diff against the merge base + env: + BASE_REF: ${{ github.base_ref }} + run: | + set -euo pipefail + git fetch --no-tags origin "$BASE_REF" + git diff "$(git merge-base HEAD "origin/$BASE_REF")" HEAD -- src tests > mutants.diff + wc -l < mutants.diff + + - name: mutants + run: cargo mutants --no-shuffle --in-place -vV --in-diff mutants.diff + + - uses: actions/upload-artifact@v7 + if: always() + with: + name: mutants-in-diff + path: mutants.out + if-no-files-found: ignore diff --git a/Cargo.toml b/Cargo.toml index 37be531..24d3a8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,10 @@ exclude = [ "deny.toml", "release-plz.toml", ".rumdl.toml", + # cargo-mutants config. Not excluded by default: cargo packages every root file it + # is not told to drop, and .cargo/ is no exception, so without this line every edit + # to a mutation-testing knob would cut a patch release. + ".cargo/", ] [workspace] diff --git a/justfile b/justfile index 7de94f2..801262b 100644 --- a/justfile +++ b/justfile @@ -98,7 +98,18 @@ lock: bench: cargo bench --bench render -# Build and run the benches under cargo-codspeed. Reports no timings off Linux; real numbers come from the CodSpeed job on the PR. -codspeed: - cargo codspeed build -m simulation -m memory - cargo codspeed run +# Config lives in .cargo/mutants.toml. The whole crate is ~3600 mutants and hours of +# wall clock, so reach for `mutants-file` or `mutants-diff` unless you mean it. +# Every mutant the suite fails to kill: code a test runs but nothing asserts on. +mutants: + cargo mutants --no-shuffle --in-place + +# One module's mutants, which is the shape worth running by hand. +mutants-file file: + cargo mutants --no-shuffle --in-place --file {{file}} + +# What the mutants CI job runs: only the code this branch changed. +mutants-diff: + git diff $(git merge-base HEAD main) HEAD -- src tests > /tmp/celsius-mutants.diff + cargo mutants --no-shuffle --in-place --in-diff /tmp/celsius-mutants.diff + From bb0977f3237f1ea2eea087b345bb7cbee6a36bdd Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 17:23:42 +0200 Subject: [PATCH 06/16] ci: enforce the spelling policy, and check for dependencies nothing imports .rumdl.toml disables MD044 and MD061 with a comment saying typos owns every spelling question. typos was wired into neither prek nor CI, so nothing owned it. It does now, at pre-commit, where it costs milliseconds. _typos.toml exists because all five findings on the current tree are false positives and every one of them is a real identifier: the ratatui crate read as a misspelling of ratatouille, image's from_numer_denom_ms, the pixel index iy that is always paired with ix, and PN falling out of the word PNGs in prose about the golden renders. Recording them once is the difference between a check that stays on and one that gets bypassed. cargo-shear over cargo-machete for unused dependencies: it parses with rust-analyzer's parser instead of text-matching, which matters here because the only optional dependency is image behind the png feature and a text scan is exactly the approach that gets that case wrong. cargo-udeps is out; it needs nightly and a full build. It reports clean today, which is the point of adding it before it does not. Both hooks are local rather than CI. Neither can break a build, and CI is already five jobs. just cov and cov-lcov are the coverage numbers .claude/CLAUDE.md quotes, which until now were measured once by hand and could only rot. Wiring the upload to an external service needs an account decision, so that half is deliberately not here. _typos.toml joins the exclude list for the same reason as .cargo/: it is a root file, Cargo packages those by default, and a tooling config that ships is a tooling config whose every edit cuts a patch release. --- Cargo.toml | 1 + _typos.toml | 15 +++++++++++++++ justfile | 15 +++++++++++++++ prek.toml | 18 ++++++++++++++++++ 4 files changed, 49 insertions(+) create mode 100644 _typos.toml diff --git a/Cargo.toml b/Cargo.toml index 24d3a8a..5cc374d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ exclude = [ "deny.toml", "release-plz.toml", ".rumdl.toml", + "_typos.toml", # cargo-mutants config. Not excluded by default: cargo packages every root file it # is not told to drop, and .cargo/ is no exception, so without this line every edit # to a mutation-testing knob would cut a patch release. diff --git a/_typos.toml b/_typos.toml new file mode 100644 index 0000000..a4618f2 --- /dev/null +++ b/_typos.toml @@ -0,0 +1,15 @@ +# .rumdl.toml turns MD044 and MD061 off so that spelling lives in exactly one place. +# This is that place. Everything below is a real identifier, not a typo we tolerate. + +[default.extend-identifiers] +# The TUI framework. The dictionary reads it as a misspelling of ratatouille. +ratatui = "ratatui" +Ratatui = "Ratatui" +# image::Delay::from_numer_denom_ms, an upstream API name we do not get to spell. +from_numer_denom_ms = "from_numer_denom_ms" + +[default.extend-words] +# Pixel loop index, always paired with ix. The dictionary reads it as "it". +iy = "iy" +# Falls out of splitting "PNGs", which appears in prose about the golden renders. +PN = "PN" diff --git a/justfile b/justfile index 801262b..9f01eaa 100644 --- a/justfile +++ b/justfile @@ -113,3 +113,18 @@ mutants-diff: git diff $(git merge-base HEAD main) HEAD -- src tests > /tmp/celsius-mutants.diff cargo mutants --no-shuffle --in-place --in-diff /tmp/celsius-mutants.diff +# --all-features so the png-gated sinks and the oracle count as covered code +# rather than reading as dead. High coverage here still means the goldens executed +# the line, not that anything checked the result; `mutants` is what checks that. +# Line coverage, which is where the percentages quoted in the docs come from. +cov: + cargo llvm-cov --locked --all-features --summary-only + +# Coverage as lcov, for an editor gutter or CI upload. +cov-lcov: + cargo llvm-cov --locked --all-features --lcov --output-path lcov.info + +# Build and run the benches under cargo-codspeed. Reports no timings off Linux; real numbers come from the CodSpeed job on the PR. +codspeed: + cargo codspeed build -m simulation -m memory + cargo codspeed run diff --git a/prek.toml b/prek.toml index 9e5522b..ce9e1bf 100644 --- a/prek.toml +++ b/prek.toml @@ -36,3 +36,21 @@ language = "system" entry = "actionlint" files = '^\.github/workflows/.*\.ya?ml$' stages = ["pre-commit"] + +[[repos.hooks]] +id = "typos" +name = "typos (spelling, config in _typos.toml)" +language = "system" +entry = "typos" +always_run = true +pass_filenames = false +stages = ["pre-commit"] + +[[repos.hooks]] +id = "cargo-shear" +name = "cargo shear (unused and misplaced dependencies)" +language = "system" +entry = "cargo shear" +always_run = true +pass_filenames = false +stages = ["pre-commit"] From 2be061667a8206502bf5ba020ad3ad7ba7953678 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 17:24:36 +0200 Subject: [PATCH 07/16] ci: publish to crates.io over OIDC instead of a stored registry token DO NOT MERGE THIS COMMIT until the trusted publisher exists on crates.io. It is last in the branch so it can be held back or dropped on its own. CARGO_REGISTRY_TOKEN is a long-lived crates.io credential sitting in repository secrets, and it is the one secret here that can publish a version that can never be unpublished. Trusted Publishing replaces it with a token minted per run over OIDC and valid for thirty minutes. release-plz performs the exchange itself, so this needs no crates-io-auth-action step and no token at all: id-token: write on the release job, and the secret comes out of the workflow entirely, which is what the release-plz docs require rather than merely suggest. The crates.io side is manual and must be configured first, under Settings -> Trusted Publishing on the celsius crate: owner lmarkmann, repository celsius, workflow release-plz.yml, environment blank. If an environment is set there it has to be named here too, or the exchange is refused. celsius-lab is publish = false and needs nothing. Leave the repository secret in place but unused until one publish succeeds, so a rollback is reverting this commit rather than minting a new token. The single job also becomes the two documented ones. It ran release-pr before release, so on the very push that merged a release PR the proposer evaluated the pre-publish state and could re-propose the version the publisher was mid-flight on, which is release-plz#1542. Six releases have not hit it, and the ordering is free to fix. `needs` keeps the two serialised in the right order, and `!cancelled()` stops a failed publish from skipping the PR job, since the release PR is how a broken release gets fixed and skipping it would deadlock the very first run. persist-credentials: false closes the last artipacked finding; zizmor now reports nothing across all five workflows at low severity. --- .github/workflows/release-plz.yml | 42 +++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/.github/workflows/release-plz.yml b/.github/workflows/release-plz.yml index ca3a87c..66a07c9 100644 --- a/.github/workflows/release-plz.yml +++ b/.github/workflows/release-plz.yml @@ -5,33 +5,53 @@ on: branches: [main] permissions: - contents: write - pull-requests: write + contents: read jobs: - release-plz: - name: release-plz + release-plz-release: + name: release-plz release runs-on: ubuntu-latest - concurrency: - group: release-plz-${{ github.ref }} - cancel-in-progress: false + timeout-minutes: 30 + permissions: + contents: write + pull-requests: read + id-token: write steps: - uses: actions/checkout@v7 with: fetch-depth: 0 + persist-credentials: false - uses: dtolnay/rust-toolchain@stable - uses: release-plz/action@v0.5 with: - command: release-pr + command: release env: GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }} - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + + release-plz-pr: + name: release-plz PR + runs-on: ubuntu-latest + timeout-minutes: 30 + needs: release-plz-release + if: ${{ !cancelled() }} + permissions: + contents: write + pull-requests: write + concurrency: + group: release-plz-${{ github.ref }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: dtolnay/rust-toolchain@stable - uses: release-plz/action@v0.5 with: - command: release + command: release-pr env: GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }} - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} From d1884f8d7e03aaeaad0ea91d7614c44203196139 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:27:53 +0200 Subject: [PATCH 08/16] perf: cut the shipped binary by a third 3.574 MiB to 2.288 MiB for the artifact a user actually downloads, a 36% cut, with every golden byte-identical and no feature removed. Two source changes account for 85 KiB of it. src/tui/app.rs:705 was the only Layout call site in the crate, and it was the only path to kasuari, the Cassowary constraint solver, which existed to compute height - 2. too_small() has already returned for anything under MIN_ROWS by that line, so the arithmetic needs no guard that the solver was providing. kasuari stays a declared dependency of ratatui-core but is now dead-stripped: cargo bloat had it at 20.8 KiB before and does not list it after, and ratatui_core itself halves from 32.1 to 16.4 KiB. layout-cache comes off ratatui's features with it, since it cached Layout::split results and nothing splits any more; that also drops critical-section from the dependency graph. The three strftime calls in weather/state.rs built a format-string interpreter to print two numbers. %H:%M is {:02}:{:02} over Timelike, and the out-of-range fallback adds Datelike, which format_label already used. cargo bloat confirms StrftimeItems as Display is gone. Honest accounting: chrono's total only fell 32.9 to 31.3 KiB rather than the 13.5 KiB hoped for, because parse_from_str still backs --at and keeps the parsing half alive. Hand-rolling date parsing to chase that is the brittleness this pass exists to avoid. The rest is [profile.dist]: fat LTO, one codegen unit, dependencies at opt-level "z". That is worth about a fifth of the binary and roughly seven seconds of link time, which is the right trade once per release and the wrong one on every `just ci`, so [profile.release] is untouched and the test gate keeps its fast rebuild. ratatui-core is pinned back to opt-level 3 because it is the one dependency drawn every tick; rustls, ring, clap, basic_toml and chrono run at startup, on a network call or on a keypress and never inside a frame. hyperfine over 441 and 475 runs of --frame puts dist at 1.02 +- 0.09 times the speed of release, which is to say indistinguishable. This introduces a gap and closes it in the same commit. Until now the shipped binary used the profile the tests ran under; it no longer does, so `just dist-check` runs the oracle against [profile.dist]. All 171 pass there with every golden unmoved, which is expected since Rust enables neither FP contraction nor reassociation at any opt-level, but expected is not verified. cargo install and the formula's source fallback still build [profile.release] and still get 3.49 MiB, because cargo cannot be told about a custom profile. The prebuilt archives cover every real install path: binstall resolves them and the formula installs them on arm64 macOS and x86_64 Linux. Criterion could not referee this. Re-running just bench against the identical binary with no rebuild in between reported 10 regressions and 8 improvements spanning -22.98% to +210.01%, so run-to-run noise on this machine exceeds the effect. CodSpeed's simulation instrument counts instructions instead of timing them, so the PR gets the deterministic answer a laptop cannot give. Numbers in .claude/docs/logs/BENCH.md. --- .github/workflows/release.yml | 1 + Cargo.lock | 7 ------- Cargo.toml | 27 ++++++++++++++++++++++++++- justfile | 12 ++++++++++++ src/tui/app.rs | 22 +++++++++++++++------- src/weather/state.rs | 15 +++++++++++---- 6 files changed, 65 insertions(+), 19 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ef5316a..a3136f1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,6 +37,7 @@ jobs: archive: $bin-$tag-$target checksum: sha256 locked: true + profile: dist token: ${{ secrets.GITHUB_TOKEN }} - uses: actions/attest@v4 with: diff --git a/Cargo.lock b/Cargo.lock index 545bbfb..959bbb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -513,12 +513,6 @@ dependencies = [ "itertools 0.10.5", ] -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - [[package]] name = "crossbeam-deque" version = "0.8.6" @@ -1540,7 +1534,6 @@ checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" dependencies = [ "bitflags", "compact_str", - "critical-section", "hashbrown 0.17.0", "itertools 0.14.0", "kasuari", diff --git a/Cargo.toml b/Cargo.toml index 5cc374d..a7c3da2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,7 +74,7 @@ dirs = "6" clap = { version = "4", features = ["derive"] } crossterm = "0.29" image = { version = "0.25", default-features = false, features = ["png"], optional = true } -ratatui = { version = "0.30.1", default-features = false, features = ["crossterm_0_29", "layout-cache"] } +ratatui = { version = "0.30.1", default-features = false, features = ["crossterm_0_29"] } serde = { version = "1", features = ["derive"] } thiserror = "2" basic-toml = "0.1" @@ -100,3 +100,28 @@ harness = false opt-level = 3 lto = "thin" strip = "symbols" + +# The profile the released artifacts are built with. Fat LTO plus a single codegen +# unit is worth about a fifth of the binary and roughly seven seconds of link time, +# which is the right trade once per release and the wrong one on every `just ci`, so +# [profile.release] stays as it is and the test gate keeps its fast rebuild. +[profile.dist] +inherits = "release" +lto = "fat" +codegen-units = 1 + +# rustls, ring, clap, basic_toml and chrono run at startup, on a network call, or on +# a keypress, never inside a frame, so trading their speed for size costs nothing a +# user can perceive. celsius itself is not covered by this glob and stays at 3. +[profile.dist.package."*"] +opt-level = "z" + +# Drawn every tick, so it is the one dependency actually on the frame path. +[profile.dist.package.ratatui-core] +opt-level = 3 + +# Dependencies change rarely and are painfully slow unoptimized, so pay for them once +# and keep our own crate at 0 for fast rebuilds and live debug assertions. Note this +# does not speed up debug rendering: the renderer is ours, and ours stays at 0. +[profile.dev.package."*"] +opt-level = 3 diff --git a/justfile b/justfile index 9f01eaa..81f89d7 100644 --- a/justfile +++ b/justfile @@ -46,6 +46,18 @@ build: build-oracle: cargo build --release --features png +# Fat LTO, one codegen unit, dependencies at opt-level "z". About a third smaller than +# `just build` and much slower to link, which is why it is not [profile.release]. +# The profile release.yml ships, so this is what a user actually downloads. +dist: + cargo build --profile dist + +# [profile.release] is what the test gate runs, so nothing otherwise proves fat LTO and +# opt-level "z" leave the render bit-identical. They do; this keeps it that way. +# The goldens against the profile we actually ship. +dist-check: + cargo nextest run --cargo-profile dist --features png + # Release tests incl. the golden oracle (the deterministic scene-lock path). test: cargo nextest run --release --features png diff --git a/src/tui/app.rs b/src/tui/app.rs index a29e854..6515877 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -16,7 +16,7 @@ use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifier use crossterm::execute; use crossterm::terminal::{BeginSynchronizedUpdate, EndSynchronizedUpdate}; use ratatui::buffer::Buffer; -use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::layout::Rect; use ratatui::style::{Color, Modifier, Style}; use ratatui::widgets::Widget; use ratatui::{DefaultTerminal, Frame}; @@ -702,12 +702,20 @@ fn draw_sky(buf: &mut Buffer, area: Rect, app: &mut App) { draw_too_small(buf, area); return; } - let [header, sky_area, footer] = Layout::vertical([ - Constraint::Length(1), - Constraint::Fill(1), - Constraint::Length(1), - ]) - .areas(area); + // A one-row header and footer around a filled middle, which a general constraint + // solver used to compute. too_small() has already returned for anything under + // MIN_ROWS, so height is at least 25 here and the subtraction cannot underflow. + let header = Rect { height: 1, ..area }; + let sky_area = Rect { + y: area.y + 1, + height: area.height - 2, + ..area + }; + let footer = Rect { + y: area.y + area.height - 1, + height: 1, + ..area + }; draw_chrome_bar( buf, diff --git a/src/weather/state.rs b/src/weather/state.rs index 7468064..fb1c7c3 100644 --- a/src/weather/state.rs +++ b/src/weather/state.rs @@ -6,7 +6,7 @@ //! //! Times are UTC everywhere inside. Open-Meteo returns local strings under `timezone=auto`, so they are converted in at the boundary and back out only for display. -use chrono::{Datelike, NaiveDateTime, TimeZone, Utc}; +use chrono::{Datelike, NaiveDateTime, TimeZone, Timelike, Utc}; use crate::analytic_sky::AnalyticSky; use crate::astro::{self, AltAz}; @@ -421,7 +421,7 @@ fn daily_high_low(daily: &DailyArrays, date_iso: &str) -> Option<(f64, f64)> { fn local_hhmm(unix_utc: i64, offset: i64) -> String { Utc.timestamp_opt(unix_utc + offset, 0) .single() - .map(|dt| dt.format("%H:%M").to_string()) + .map(|dt| format!("{:02}:{:02}", dt.hour(), dt.minute())) .unwrap_or_default() } @@ -739,7 +739,14 @@ fn format_label(unix_utc: i64, now_unix: i64, offset: i64) -> String { None => { // The offset pushed the timestamp out of range, so fall back to bare UTC. If that is out of range too there is no date to format, and the raw epoch beats a panic in the branch whose whole job is not failing. return match Utc.timestamp_opt(unix_utc, 0).single() { - Some(dt) => dt.format("%Y-%m-%d %H:%M").to_string(), + Some(dt) => format!( + "{:04}-{:02}-{:02} {:02}:{:02}", + dt.year(), + dt.month(), + dt.day(), + dt.hour(), + dt.minute() + ), None => format!("t={unix_utc}"), }; } @@ -749,7 +756,7 @@ fn format_label(unix_utc: i64, now_unix: i64, offset: i64) -> String { .single() .unwrap_or(target); let day_diff = (target.date_naive() - now.date_naive()).num_days(); - let hhmm = target.format("%H:%M").to_string(); + let hhmm = format!("{:02}:{:02}", target.hour(), target.minute()); match day_diff { 0 => format!("today {hhmm}"), 1 => format!("tomorrow {hhmm}"), From 312b95eacb0115856bd31f332709a455f051dc12 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:31:17 +0200 Subject: [PATCH 09/16] docs: rework the README badge row Adds the Built With Ratatui badge and gives the crates.io badge the rust logo, and pins the CI badge to main. The legacy /workflows/CI/badge.svg route resolves a workflow by display name and shows the newest run on any ref, so a failing Renovate branch push painted the badge red while main was green; the per-file route with an explicit branch and event reports what a reader wants to know, and the link opens the same filtered view. That pin was sitting unmerged on fix/ci-badge-url and lands here instead, so that branch is now redundant. Drops the CodSpeed badge. Its shields endpoint pointed at a bare codspeed.io/badge.json with no repository in the URL, so it rendered the same image for every project and told a reader nothing about this one. Order is source, then version, then health, then licence. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4c16356..dda090a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # celsius -[![CI](https://github.com/lmarkmann/celsius/workflows/CI/badge.svg)](https://github.com/lmarkmann/celsius/actions) -[![CodSpeed](https://img.shields.io/endpoint?url=https://codspeed.io/badge.json)](https://app.codspeed.io/lmarkmann/celsius?utm_source=badge) -[![Crates.io](https://img.shields.io/crates/v/celsius)](https://crates.io/crates/celsius) +[![Built With Ratatui](https://ratatui.rs/built-with-ratatui/badge.svg)](https://ratatui.rs/) +[![Crates.io](https://img.shields.io/crates/v/celsius?logo=rust)](https://crates.io/crates/celsius) +[![CI](https://github.com/lmarkmann/celsius/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/lmarkmann/celsius/actions/workflows/ci.yml?query=branch%3Amain) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) celsius demo From cc412c6c084be3e7de837057b74e7fba83ec91c7 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:41:17 +0200 Subject: [PATCH 10/16] ci: publish the binary size as a badge the release updates itself A hand-written size in the README goes stale the moment the binary moves, and the only thing that notices is a reader being told the wrong number. So the release publishes it. shields has no badge for release-asset size. Its github/size badge reads a file in the repository, not a release asset, and the dynamic JSON badge cannot help either: it has no byte formatting, so it renders 2062104 rather than 2.3 MB, and its JSONPath name filter returns invalid, leaving only a positional $.assets[5]. With a three-target matrix at fail-fast: false the upload order is not fixed, so that index can land on a .sha256 and the badge would proudly announce 109 bytes. The ecosystem answer is Schneegans/dynamic-badges-action writing a gist that shields reads back. Same idea here without the gist, because that action needs a personal access token carrying the gist scope stored as a repository secret, and this is the same release path that just stopped storing a crates.io token. The JSON goes to an orphan badges branch instead, pushed with the built-in GITHUB_TOKEN the job already has. No new secret, no third party, and shields fetches raw.githubusercontent.com perfectly well. The number is the uncompressed musl binary, untarred from the archive that was just published, so it is the size that lands on disk rather than the gzipped download, and it is measured from the shipped artifact rather than recomputed from a build that might differ. Reporting one target is a deliberate simplification: macOS and Windows are within a few percent, and three numbers in a badge row is worse than one honest one. The branch does not exist yet, so the badge is broken until it is seeded and the first release runs. --- .github/workflows/release.yml | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a3136f1..4f76ef4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,6 +43,39 @@ jobs: with: subject-checksums: ${{ steps.upload.outputs.sha256 }} + size-badge: + name: publish the binary size badge + needs: upload-binaries + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + with: + ref: badges + persist-credentials: true + path: badges + + - name: measure and publish + working-directory: badges + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ github.ref_name }} + run: | + set -euo pipefail + archive="celsius-$TAG-x86_64-unknown-linux-musl.tar.gz" + gh release download "$TAG" --repo lmarkmann/celsius -p "$archive" -D dl + tar -xzf "dl/$archive" -C dl + bytes=$(stat -c%s dl/celsius) + mib=$(awk -v b="$bytes" 'BEGIN { printf "%.1f", b / 1048576 }') + rm -rf dl + printf '{"schemaVersion":1,"label":"binary","message":"%s MB","color":"blue"}\n' "$mib" > size.json + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add size.json + git diff --cached --quiet || git commit -m "celsius $TAG: ${mib} MB" + git push + homebrew: name: bump homebrew formula needs: upload-binaries diff --git a/README.md b/README.md index dda090a..e669304 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![Built With Ratatui](https://ratatui.rs/built-with-ratatui/badge.svg)](https://ratatui.rs/) [![Crates.io](https://img.shields.io/crates/v/celsius?logo=rust)](https://crates.io/crates/celsius) [![CI](https://github.com/lmarkmann/celsius/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/lmarkmann/celsius/actions/workflows/ci.yml?query=branch%3Amain) +[![Binary size](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/lmarkmann/celsius/badges/size.json)](https://github.com/lmarkmann/celsius/releases/latest) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) celsius demo From 4f7f286b1270c49d9300c6804c4efff9ce7f6a59 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 17:03:14 +0200 Subject: [PATCH 11/16] test: make the CodSpeed benches measure what they claim Four micros reported the single-iteration harness rather than the function under it. warped_fbm measured 2.6us under simulation against 35ns locally, a 74x gap where the render benches hold between seven and thirteen; analytic_sample, sun_position and moon_state were the same shape. Each now runs a real unit of work per iteration, the way oklab_to_rgb_5200 already did: a frame's worth for the two per-pixel calls, a week for the two per-compose ones. Renamed rather than fixed in place, because the old series is not comparable to the new one and a silent continuation would read as a catastrophic regression. alloc_floor_104x50 is retired with its answer recorded where it stood. It existed to ask whether a render_into writing through a reused buffer would buy anything, and it answered: 18.6us against a 5.9ms stormy render, so 0.3% and no. A settled question left on the dashboard reads like an open one. Three gaps filled. render_supersampled had no benchmark at all despite being the heaviest path in the crate, and 104x50_stormy_aa comes out at 10.3ms locally, a third of the 33ms tick budget at the reference size and scaling with terminal area. drift_cadence measures a second of a drifting sky rather than a single tick, which is 22.2ms of CPU per second of wall clock spent advancing clouds about a tenth of a pixel. timeline_168h bounds everything startup computes before the first sky at 1.03ms, which is what establishes that the two Open-Meteo round trips are the load time and this is not. benches/ is excluded from the crate tarball, so this cuts no release. --- benches/render.rs | 92 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 78 insertions(+), 14 deletions(-) diff --git a/benches/render.rs b/benches/render.rs index 3d1e627..66b0063 100644 --- a/benches/render.rs +++ b/benches/render.rs @@ -16,7 +16,7 @@ use celsius::tui::{App, Timeline, draw_frame, write_frame}; use celsius::weather::forecast::Forecast; use celsius::weather::location::GeoResult; use celsius::weather::{ComposeOpts, compose, compose_at}; -use celsius::{PixelBuffer, Rgb, SkyState, load_scene, render}; +use celsius::{SkyState, load_scene, render, render_supersampled}; /// One TUI tick, matching `TICK` in the event loop. const TICK: Duration = Duration::from_millis(33); @@ -56,6 +56,15 @@ fn bench_render(c: &mut Criterion) { b.iter(|| render(black_box(&state), 320, 100)) }); + // The supersampled tiers. `raster::sample_factor` returns 2 for `--aa` on half blocks or for plain `--glyphs quad`, and 4 for both together, so factor 4 draws sixteen times the pixels of the default and is the heaviest frame the crate can be asked for. Until now the only measurement either had was a number typed by hand into a commit message. + g.bench_function("104x50_stormy_quad", |b| { + b.iter(|| render_supersampled(black_box(&state), 104, 50, 2)) + }); + + g.bench_function("104x50_stormy_aa", |b| { + b.iter(|| render_supersampled(black_box(&state), 104, 50, 4)) + }); + // Clear sky (no clouds, no precipitation) for comparison let clear = load_scene(scene_path("high_noon_clear")).unwrap(); g.bench_function("104x50_clear", |b| { @@ -131,6 +140,19 @@ fn bench_frame(c: &mut Criterion) { }); }); + // A second of a sky nobody is touching: thirty ticks, each followed by a draw. Every one of those ticks re-renders the whole buffer, though at 28 km/h with `scale_x = 3` the clouds advance about a three-hundredth of a pixel per tick, so a few hundred consecutive frames are the same picture. `dirty_rerender` measures a single tick and cannot see that; this measures the cadence, which is where a change to when drift invalidates the cache would show up. `scrub_hour` is what keeps guarding the render itself, since a scrub always dirties. + const TICKS_PER_SECOND: u32 = 30; + g.bench_function("drift_cadence", |b| { + let timeline = Timeline::single(stormy.clone()); + let mut app = App::new(&timeline); + b.iter(|| { + for _ in 0..TICKS_PER_SECOND { + app.tick(TICK); + draw_frame(&mut buf, FRAME_AREA, &mut app); + } + }); + }); + // Thunderstorm: the cached base survives, but every frame clones it and runs the flash overlay on the copy. g.bench_function("lightning_frame", |b| { let mut lit = stormy.clone(); @@ -356,6 +378,15 @@ fn bench_compose(c: &mut Criterion) { b.iter(|| compose_at(black_box(&forecast), &geo, target, t00, opts).unwrap()) }); + // Everything startup computes before the first sky appears: `build_timeline` composes every hour of the week eagerly. Worth stating plainly, because no benchmark can show it: real startup is dominated by two sequential Open-Meteo round trips, so a fast number here does not mean a fast start. What this pins is that the CPU share stays negligible against them. + g.bench_function("timeline_168h", |b| { + b.iter(|| { + for h in 0..WEEK_HOURS { + black_box(compose(black_box(&forecast), &geo, h, t00, opts).unwrap()); + } + }) + }); + g.finish(); } @@ -367,8 +398,24 @@ fn bench_noise(c: &mut Criterion) { b.iter(|| Noise::new(black_box(0xC0FFEE_u64))) }); - g.bench_function("warped_fbm", |b| { - b.iter(|| noise.warped_fbm(black_box(1.23), black_box(4.56))) + // A frame's worth, at the coordinates a 104x50 cloud layer actually walks (`nx = fx * scale_x + offset_x`, with the scene defaults). A lone call is far too short to survive the single-iteration harness the CodSpeed runner uses: it reported 2.6 us under simulation against 35 ns locally, a ratio the render benches hold between seven and thirteen, so what it measured was the harness rather than the fbm chain. Renamed rather than fixed in place, because the old series is not comparable to this one. + let coords: Vec<(f64, f64)> = (0..50) + .flat_map(|py| { + (0..104).map(move |px| { + ( + f64::from(px) / 104.0 * 3.0 + 0.4, + f64::from(py) / 50.0 * 2.2 + 1.3, + ) + }) + }) + .collect(); + + g.bench_function("warped_fbm_5200", |b| { + b.iter(|| { + for &(x, y) in &coords { + black_box(noise.warped_fbm(x, y)); + } + }) }); g.finish(); @@ -385,17 +432,37 @@ fn bench_micro(c: &mut Criterion) { turbidity: 2.0, blend: 1.0, }); - g.bench_function("analytic_sample", |b| { - b.iter(|| prepared.sample(black_box(0.37), black_box(0.62))) + // A frame's worth of Perez evaluations, which is what a daytime render pays: `sample` runs once per pixel and roughly triples a clear 104x50 frame. Batched for the same reason as `warped_fbm_5200`, a single call being short enough that the reported number was the harness. + let fracs: Vec<(f64, f64)> = (0..50) + .flat_map(|py| (0..104).map(move |px| (f64::from(px) / 103.0, f64::from(py) / 49.0))) + .collect(); + + g.bench_function("analytic_sample_5200", |b| { + b.iter(|| { + for &(x, y) in &fracs { + black_box(prepared.sample(x, y)); + } + }) }); - // Both run once per compose; Meeus' lunar series is the heavier of the two. + // Both run once per compose, and startup composes every hour of the week, so a week is the honest batch rather than an arbitrary multiple. Meeus' lunar series is the heavier of the two. let t = 1_775_865_600; - g.bench_function("sun_position", |b| { - b.iter(|| astro::sun_position(black_box(53.55), black_box(9.99), t)) + let week: Vec = (0..WEEK_HOURS as i64).map(|h| t + h * 3_600).collect(); + + g.bench_function("sun_position_168", |b| { + b.iter(|| { + for &at in &week { + black_box(astro::sun_position(black_box(53.55), black_box(9.99), at)); + } + }) }); - g.bench_function("moon_state", |b| { - b.iter(|| astro::moon_state(black_box(53.55), black_box(9.99), t)) + + g.bench_function("moon_state_168", |b| { + b.iter(|| { + for &at in &week { + black_box(astro::moon_state(black_box(53.55), black_box(9.99), at)); + } + }) }); // Real pixels rather than synthetic ones, so the value distribution matches what the write path actually sees. @@ -423,10 +490,7 @@ fn bench_micro(c: &mut Criterion) { }) }); - // What share of a 104x50 render is the allocator. Settles whether a render_into that writes through a reused buffer would buy anything. - g.bench_function("alloc_floor_104x50", |b| { - b.iter(|| PixelBuffer::filled(black_box(104), black_box(50), Rgb::BLACK)) - }); + // `alloc_floor_104x50` used to sit here, asking what share of a 104x50 render is the allocator and therefore whether a `render_into` writing through a reused buffer would buy anything. It answered: 18.6 us against a 5.9 ms stormy render, with the whole render allocating 15.4 KB, so 0.3% and no. Retired rather than kept, because a settled question on the dashboard reads like an open one. // The star field is rebuilt inside every render, and placing stars on the sky rather than on the screen made each candidate cost a projection and a rejection draw. This is what says whether that rebuild is worth caching or is already noise against the pixel loop. let dark = load_scene(scene_path("moonless_darksky")).unwrap(); From 69b11bd8c73a2157b43f16a2306cad0b23cb885e Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:25:23 +0200 Subject: [PATCH 12/16] perf: stop sampling a Preetham sky that is weighted to zero build_sky attaches an analytic sky whenever the sun is above the horizon, but weights it by (sun_alt / 8) * (1 - total_cover). A fully overcast daytime hour therefore asked for a Perez radiance sample at every pixel and then lerped all of it away, and Open-Meteo reports cloud cover as an integer percentage, so 100% is a value it actually returns rather than a limiting case. Dropping it is bit-identical rather than close: lerp_oklab(a, b, 0.0) is a + (b - a) * 0.0, which is exactly a for the finite radiance tests/analytic.rs already pins, so the discarded term could never have been anything but zero. Filtering before prepare also skips its 5x5 adapted_exposure survey. Done in render.rs rather than in weather/state.rs so it covers every caller including celsius-lab, and because that is where the cost was. render/104x50_clear_overcast is new and exists because nothing else would ever notice a regression here: with the sample gone this path is indistinguishable from a plain gradient sky, and only a benchmark that knows a Perez sky is attached can tell the difference between doing it right and doing it again. It now measures 175.0us against 174.3us for 104x50_clear, down from the 588us that 104x50_clear_analytic still costs at full weight. Goldens unmoved; the analytic and crossfade benches are unchanged, which is what says only the zero-weight case was touched. --- benches/render.rs | 6 ++++++ src/render.rs | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/benches/render.rs b/benches/render.rs index 66b0063..df24c0c 100644 --- a/benches/render.rs +++ b/benches/render.rs @@ -95,6 +95,12 @@ fn bench_render(c: &mut Criterion) { b.iter(|| render(black_box(&sky), 104, 50)) }); + // The overcast daytime sky. `build_sky` attaches a Perez sky whenever the sun is up, then weights it by `(1 - total_cover)`, so full cover asks for one and discards it whole. This should now cost what `104x50_clear` costs, and it is the only thing that would notice if the per-pixel sample came back. + g.bench_function("104x50_clear_overcast", |b| { + let sky = with_analytic(&clear, 0.0); + b.iter(|| render(black_box(&sky), 104, 50)) + }); + g.finish(); } diff --git a/src/render.rs b/src/render.rs index baf7fd2..225f21f 100644 --- a/src/render.rs +++ b/src/render.rs @@ -217,7 +217,13 @@ pub fn render_supersampled(state: &SkyState, width: u32, height: u32, factor: u3 let sun_disc = sun_disc_color(); // Prototype: when an analytic sky is attached, its Preetham radiance field replaces the vertical gradient as the background. Prepared once here; the per-pixel cost is one Perez ratio plus a color conversion. - let analytic = state.analytic.as_ref().map(crate::analytic_sky::prepare); + // + // Skipped outright at zero blend. `build_sky` attaches a sky whenever the sun is above the horizon but weights it by `(sun_alt / 8) * (1 - total_cover)`, so a fully overcast daytime hour asked for a Perez sample at every pixel and then lerped every bit of it away. Dropping it is bit-identical rather than merely close: `lerp_oklab(a, b, 0.0)` is `a + (b - a) * 0.0`, and `tests/analytic.rs` pins the radiance finite, so the discarded term could never have been anything but zero. + let analytic = state + .analytic + .as_ref() + .filter(|a| a.blend > 0.0) + .map(crate::analytic_sky::prepare); // Row-invariant cloud terms: the altitude gaussian and the noise row coordinate change per row and per layer, never per pixel. let mut row_clouds: Vec<(f64, f64)> = vec![(0.0, 0.0); cloud_layers.len()]; From 0b38b70979d34f6f5a32abb9cdaeb09c84217571 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:23:27 +0200 Subject: [PATCH 13/16] perf: redraw a drifting sky when it changes, not thirty times a second Drift advances offset_x by wind_speed_kmh * elapsed * 0.0001 and dirtied the cache whenever that was non-zero. At 28 km/h against the stormy scene's finest scale_x that is about 0.002 pixels per tick, so a cloud needs roughly ten seconds to cross one pixel, and the sky was re-rendered thirty times a second to discover that nothing had moved. Measured on the frame: one tick changes about thirty of a 104x50 frame's pixels, every one of them by exactly one level. offset_x keeps accumulating exactly, so a frame that does render is identical to the one the old code would have drawn. What is coarsened is only the decision of when to redraw. The debt is tracked in frame fractions and compared against a threshold in pixels of the buffer last rendered, because the on-screen shift is delta / scale_x * width and a threshold fixed in offset_x units would repaint a wide terminal a third as often as intended. That is the density-versus-absolute trap in rules/reference-size.md, and it would have looked like a rendering fault rather than a units one. 0.05 pixels is the largest shift measured to move no channel by more than one level, at 104x50 and at 320x150 alike; a quarter pixel reaches five levels and can shimmer. Going finer buys almost nothing, because thirty cached draws already cost more than the renders it would save. frame/drift_cadence, a second of a drifting sky, goes 18.9ms to 1.80ms, down 90.3%, and the real event loop does better still: tick now returns false on a gated frame, so the draw is skipped rather than served from cache. frame/scrub_hour is unmoved (p = 0.70), which is what says the render path still has a guard, and every golden holds. Note that frame/dirty_rerender falls 96% here and no longer means what its name says: with the gate in place a single tick is mostly a cache hit. It is left in place for its history; scrub_hour is the benchmark that guarantees a render. --- src/tui/app.rs | 80 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/src/tui/app.rs b/src/tui/app.rs index 6515877..7aea6f3 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -36,6 +36,15 @@ const TICK: Duration = Duration::from_millis(33); const MIN_COLS: u16 = 60; const MIN_ROWS: u16 = 25; +/// How far clouds must travel before the sky is worth redrawing, in pixels of the buffer last rendered. +/// +/// Drift advances `offset_x` by `wind_speed_kmh * elapsed * 0.0001`, which at 28 km/h against the stormy scene's finest `scale_x` is about 0.002 pixels per tick. A single tick therefore changes roughly thirty of a 104x50 frame's pixels by exactly one level each, and the sky was being re-rendered thirty times a second to produce that. Cloud motion is continuous, but the output is quantised to eight bits, and below this distance the two disagree. +/// +/// Measured in pixels rather than in `offset_x`, because the on-screen shift is `delta / scale_x * width`: this is a density, not an absolute. Reaching the same 0.05 pixels takes an `offset_x` step of 0.00216 at 104 wide but 0.00070 at 320, so a threshold fixed in `offset_x` would repaint a wide terminal a third as often as intended, which is the units fault `rules/reference-size.md` exists for. +/// +/// The value is the largest shift measured to move no channel by more than one level, at both 104x50 and 320x150. A quarter pixel reaches five levels and can shimmer; going finer than this buys little, because thirty cached draws already cost more than the renders it would save. +const DRIFT_REPAINT_PX: f64 = 0.05; + #[derive(Debug, PartialEq)] pub enum RunOutcome { Quit, @@ -130,6 +139,8 @@ pub struct App<'a> { index: usize, display: SkyState, drift_paused: bool, + /// Cloud motion accumulated since the last repaint, as a fraction of the frame. Compared against `DRIFT_REPAINT_PX` once scaled by the rendered width. + drift_debt: f64, overlay: Overlay, overlay_elapsed: Duration, egg_frame: u64, @@ -160,6 +171,7 @@ impl<'a> App<'a> { index, display, drift_paused: false, + drift_debt: 0.0, overlay: Overlay::None, overlay_elapsed: Duration::ZERO, egg_frame: 0, @@ -197,8 +209,29 @@ impl<'a> App<'a> { for layer in &mut self.display.clouds { layer.offset_x += delta; } - self.sky_dirty = true; - changed = true; + // `offset_x` keeps accumulating exactly, so a frame that does re-render is identical to the one this would have drawn every tick. Only the decision of *when* to redraw is coarsened. + // + // The layer with the smallest `scale_x` travels furthest on screen for the same `offset_x` step, so it is the one that decides whether the frame is stale yet. + let finest = self + .display + .clouds + .iter() + .map(|l| l.scale_x) + .filter(|s| *s > 0.0) + .fold(f64::INFINITY, f64::min); + self.drift_debt += if finest.is_finite() { + delta / finest + } else { + delta + }; + // Width of the buffer last actually rendered. Before the first draw there is no cache and no width to scale by, so the frame is simply stale. + let width = self.sky_cache.as_ref().map_or(0, |c| c.width); + if width == 0 || self.drift_debt * f64::from(width) >= DRIFT_REPAINT_PX { + // Reset rather than subtract the threshold: subtracting keeps the cadence marginally more even but carries stale units across a resize, and the two differ by at most one tick. + self.drift_debt = 0.0; + self.sky_dirty = true; + changed = true; + } } self.overlay_elapsed += elapsed; self.egg_frame = self.egg_frame.wrapping_add(1); @@ -1434,6 +1467,49 @@ mod tests { assert!(app.tick(Duration::from_millis(100))); } + /// The two tests above never draw, so they exercise the no-cache path, where there is no width to scale by and the frame is simply stale. This is the gated path, which needs a cache to exist first. + #[test] + fn slow_drift_delays_the_repaint_without_slowing_the_clouds() { + let tl = timeline(); + let mut app = App::new(&tl); + let mut term = Terminal::new(TestBackend::new(80, 40)).unwrap(); + term.draw(|f| { + let area = f.area(); + draw_sky(f.buffer_mut(), area, &mut app); + }) + .unwrap(); + assert!(!app.sky_dirty, "the first draw fills the cache"); + + // Pinned rather than taken from the fixture, so the arithmetic below does not move when a scene is retuned. At 28 km/h these advance about 0.0025 pixels per tick against an 80-pixel buffer, so the threshold is a little over twenty ticks away. + for layer in &mut app.display.clouds { + layer.scale_x = 3.0; + } + app.display.wind_speed_kmh = 28.0; + + app.tick(TICK); + assert!( + !app.sky_dirty, + "one tick of ordinary drift cannot change the frame by more than a rounding step, so it must not throw the cache away" + ); + + // The gate delays a repaint, it does not cancel one. + for _ in 0..40 { + app.tick(TICK); + } + assert!( + app.sky_dirty, + "accumulated drift must eventually invalidate the cache" + ); + + // And the clouds keep moving the whole time: only the decision of when to redraw is coarsened, never the drift itself. + let before = app.display.clouds[0].offset_x; + app.tick(TICK); + assert!( + app.display.clouds[0].offset_x > before, + "drift must continue between repaints" + ); + } + #[test] fn scrub_marks_sky_dirty() { let tl = timeline(); From ffc067a06b8099f5ef4ec2e00822a976e3e18809 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Wed, 26 Aug 2026 18:38:07 +0200 Subject: [PATCH 14/16] perf: take the integer divisions out of the value-noise inner loop Noise::value is 54% of a stormy frame under simulation, and it ran four integer divisions per call: rem_euclid twice, which is specified as two divisions each, then `% self.width` and `% self.height` for the neighbouring cell. width and height are runtime struct fields, so the compiler cannot fold any of them into a multiply, and integer division does not pipeline. warped_fbm_oct calls value ten times per pixel per cloud layer. Both rewrites are exact rather than close. rem_euclid becomes its own definition with the second division written as the conditional add it exists to perform. The neighbour wrap becomes a comparison, because wrap already guarantees the index is below the bound, so the modulo could only ever have been a no-op or a wrap to zero. Measured against the previous commit, the win lands precisely where noise is used and nowhere else, which is the evidence it does only what it claims: warped_fbm_5200 -13.5%, 104x50_stormy -7.5%, 200x50_stormy -8.2%, 320x100_stormy -7.2%, 104x50_stormy_quad -8.5%, 104x50_stormy_aa -8.3%, scrub_hour -7.3%, while clear, night, moonlit and the three analytic skies are all flat at p > 0.05. Every golden holds and value is pinned against the expression it replaced across 14400 coordinates including negatives and coordinates past the grid wrap. The third rewrite was reverted and is documented where it was going to go. f64::floor is 14% of a stormy frame under simulation because baseline x86-64 has no SSE4.1 roundsd and lowers it to a software bit-manipulation sequence, so replacing it with truncate-and-correct looks like free speed and is exactly as correct. It measured 32% slower: aarch64 lowers floor to a single frintm, and the replacement trades that for a seven-instruction dependency chain. warped_fbm_5200 runs 154us with floor against 203us by hand, on a 185us baseline, so the hand-written version was a regression that the division work was quietly paying for. The x86 cost is modelled and the aarch64 cost is measured. If the x86 floor is ever worth addressing it is a target-cpu question for the musl artifact rather than a code one. --- src/noise.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 86 insertions(+), 10 deletions(-) diff --git a/src/noise.rs b/src/noise.rs index 7e1d9c8..a6582c3 100644 --- a/src/noise.rs +++ b/src/noise.rs @@ -46,16 +46,15 @@ impl Noise { } pub fn value(&self, x: f64, y: f64) -> f64 { - let w = self.width as i64; - let h = self.height as i64; - let xi = x.floor(); - let yi = y.floor(); - let x0 = ((xi as i64).rem_euclid(w)) as usize; - let y0 = ((yi as i64).rem_euclid(h)) as usize; - let x1 = (x0 + 1) % self.width; - let y1 = (y0 + 1) % self.height; - let fx = smoothstep(x - xi); - let fy = smoothstep(y - yi); + let (xi, x_frac) = split_floor(x); + let (yi, y_frac) = split_floor(y); + let x0 = wrap(xi, self.width); + let y0 = wrap(yi, self.height); + // `wrap` already guarantees `x0 < width`, so the neighbour is a comparison rather than the division `% self.width` compiles to. `width` and `height` are runtime fields, so the compiler cannot fold either modulo into a multiply, and this ran four divisions per call on the hottest path in the renderer. + let x1 = if x0 + 1 == self.width { 0 } else { x0 + 1 }; + let y1 = if y0 + 1 == self.height { 0 } else { y0 + 1 }; + let fx = smoothstep(x_frac); + let fy = smoothstep(y_frac); let v00 = self.at(x0, y0); let v10 = self.at(x1, y0); let v01 = self.at(x0, y1); @@ -93,6 +92,29 @@ pub(crate) fn smoothstep(x: f64) -> f64 { x * x * (3.0 - 2.0 * x) } +/// The integer floor of `v`, paired with `v` minus it. +/// +/// A trap worth leaving marked, because the tempting rewrite here is a large regression. Under simulation `f64::floor` is 14% of a stormy frame: baseline x86-64 has no SSE4.1 `roundsd`, so it lowers to a software sequence of bit manipulations. Replacing it with truncate-and-correct (`v as i64`, minus one where truncation overshot a negative) removes that sequence and is exactly as correct, which makes it look like free speed. +/// +/// It measured 32% slower. aarch64 lowers `floor` to a single `frintm`, so the rewrite swaps one instruction for a seven-instruction dependency chain: `warped_fbm_5200` runs 154us this way against 203us by hand, on a 185us baseline. The x86 cost is modelled and the aarch64 cost is measured, and the measured one decides. +/// +/// If the x86 `floor` is ever worth addressing it is a `target-cpu` question for the musl artifact, not a code one. Writing it out by hand makes the primary platform pay for the secondary one. +#[inline] +fn split_floor(v: f64) -> (i64, f64) { + let floor = v.floor(); + (floor as i64, v - floor) +} + +/// `i` reduced into `0..n`, the value `i64::rem_euclid(n)` returns. +/// +/// `rem_euclid` is specified as `let r = self % rhs; if r < 0 { r + rhs.abs() } else { r }`, which is two divisions; for a positive `n` this is that definition with the second division written as the conditional add it exists to perform. Integer division is not pipelined, and `value` is called ten times per pixel per cloud layer, which put `rem_euclid` at 10% of a stormy frame under simulation. +#[inline] +fn wrap(i: i64, n: usize) -> usize { + let n = n as i64; + let r = i % n; + (if r < 0 { r + n } else { r }) as usize +} + // MT19937 seeded via init_by_array, matching Python's random.Random(seed). genrand_res53 matches Python's random.random() output exactly. const MT_N: usize = 624; const MT_M: usize = 397; @@ -296,4 +318,58 @@ mod tests { assert!((got - exp).abs() < 1e-15, "got {got} expected {exp}"); } } + + /// `value` avoids `f64::floor` and all four of the integer divisions it used to run per call. Each rewrite is meant to be exact rather than close, because a golden hash only objects once someone chooses to relock, at which point the new hash quietly becomes the truth. These pin the pieces against the expressions they replaced. + #[test] + fn split_floor_matches_f64_floor() { + let mut cases: Vec = (-400..400).map(|i| f64::from(i) * 0.37).collect(); + // Exact integers, zero, and negatives are the cases truncate-and-correct can get wrong. + cases.extend([-96.5, -3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 96.0, 383.0]); + for v in cases { + let (floor, frac) = split_floor(v); + assert_eq!(floor, v.floor() as i64, "floor of {v}"); + assert_eq!(frac, v - v.floor(), "fract of {v}"); + } + } + + #[test] + fn wrap_matches_rem_euclid() { + for i in -500i64..500 { + for n in [NOISE_WIDTH, NOISE_HEIGHT, 1, 7] { + assert_eq!(wrap(i, n), i.rem_euclid(n as i64) as usize, "{i} mod {n}"); + } + } + } + + /// The whole function against the body it replaced, including coordinates past the grid wrap and negative ones the cloud path never produces. Equality, not a tolerance: anything less would let a golden move. + #[test] + fn value_matches_the_expression_it_replaced() { + let noise = Noise::new(101); + let previous = |x: f64, y: f64| { + let w = noise.width as i64; + let h = noise.height as i64; + let xi = x.floor(); + let yi = y.floor(); + let x0 = ((xi as i64).rem_euclid(w)) as usize; + let y0 = ((yi as i64).rem_euclid(h)) as usize; + let x1 = (x0 + 1) % noise.width; + let y1 = (y0 + 1) % noise.height; + let fx = smoothstep(x - xi); + let fy = smoothstep(y - yi); + let v00 = noise.at(x0, y0); + let v10 = noise.at(x1, y0); + let v01 = noise.at(x0, y1); + let v11 = noise.at(x1, y1); + let a = v00 * (1.0 - fx) + v10 * fx; + let b = v01 * (1.0 - fx) + v11 * fx; + a * (1.0 - fy) + b * fy + }; + for iy in -60..60 { + for ix in -60..60 { + let x = f64::from(ix) * 3.3; + let y = f64::from(iy) * 1.7; + assert_eq!(noise.value(x, y), previous(x, y), "at ({x}, {y})"); + } + } + } } From eadae2e4f82b31b070131a511ebb1d962ae43f56 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 17:00:16 +0200 Subject: [PATCH 15/16] fix: pin the working tree to LF so the oracle holds on Windows The cross job found this on its first run, which is the case for having added it. tests/oracle.rs hashes scenes/*.toml byte for byte to prove the scene a golden was rendered from has not changed. Windows checks text files out as CRLF by default, so every scene file on a Windows clone carries different bytes and blue_hour_calm fails scene_sha256 immediately. It is worth being precise about what this was and was not. Only the scene hash failed; png_sha256 passed everywhere, so nothing about the render differed and no shipped binary was affected. basic_toml parses CRLF happily and line endings never reach a pixel. What broke is the claim the oracle makes about file identity, and it broke for any Windows contributor running just test, not only for CI. text=auto leaves tests/goldens/*.png alone, since git detects them as binary. The file joins .gitignore in the tarball rather than the exclude list: it is version-control metadata rather than development tooling, and it will not change again. --- .gitattributes | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b4454da --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# tests/oracle.rs hashes scenes/*.toml byte for byte, and Windows checks text files +# out as CRLF by default, so a Windows clone changes those bytes and fails +# scene_sha256 while rendering pixel-identical output. Pinning the working tree to LF +# everywhere keeps one hash true on every platform. The goldens under tests/goldens/ +# are detected as binary by text=auto and are left alone. +* text=auto eol=lf From dcc38cadb25932bf1e155ce96078b675478a238a Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 20:20:31 +0200 Subject: [PATCH 16/16] test: assert the layout split the solver used to guarantee The mutants job on this PR earned its place: it showed the suite would not notice `area.height - 2` becoming `area.height / 2` in draw_sky. At forty rows that is a sky of twenty-five rows instead of thirty-eight, half the frame left unpainted, and every test still green. Dropping Layout for arithmetic removed the only thing that had been checking the geometry, because a constraint solver at least asserts its own constraints, and the goldens never reach draw_sky to notice. The test draws at three sizes, including one row above MIN_ROWS, and pins what the split promises: row 0 and the last row carry chrome, and the sky reaches the row directly above the footer. That last assertion is the one that kills the mutant. Two survivors here are equivalent and stay. Deleting `height` from the header or footer Rect changes nothing, because draw_chrome_bar writes only `area.y` and never reads the height; the field documents what the row is rather than feeding anything. That is recorded next to the test so the next person does not spend an afternoon on it. --- src/tui/app.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/tui/app.rs b/src/tui/app.rs index 7aea6f3..b19a08c 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -1424,6 +1424,49 @@ mod tests { ); } + // The three-row split used to be a Cassowary solve, which at least had the solver + // asserting its own constraints. It is arithmetic now, and cargo-mutants showed the + // suite would not notice `area.height - 2` becoming `area.height / 2`: the goldens + // never reach draw_sky, so nothing downstream of it was checking the geometry. + // + // Two mutants here stay alive and are meant to: deleting `height` from the header + // or footer Rect is equivalent, because draw_chrome_bar writes only `area.y` and + // never reads the height. The field says what the row is, not what the code needs. + #[test] + fn draw_sky_splits_into_a_header_a_filled_middle_and_a_footer() { + let tl = timeline(); + let mut app = App::new(&tl); + + for (w, h) in [(80_u16, 40_u16), (60, 25), (200, 61)] { + let mut term = Terminal::new(TestBackend::new(w, h)).unwrap(); + term.draw(|f| { + let area = f.area(); + draw_sky(f.buffer_mut(), area, &mut app); + }) + .unwrap(); + + let buf = term.backend().buffer(); + let header_blank = (0..w).all(|x| buf[(x, 0)].symbol() == " "); + let footer_blank = (0..w).all(|x| buf[(x, h - 1)].symbol() == " "); + assert!(!header_blank, "{w}x{h}: row 0 must carry the header chrome"); + assert!( + !footer_blank, + "{w}x{h}: the last row must carry the footer chrome" + ); + + // The sky owns everything between them, so the row just inside each edge is + // painted sky rather than chrome or an untouched cell. A `/` in place of the + // `-` leaves the lower half of the frame blank and fails here. + let last_sky_row = h - 2; + let bottom_of_sky_painted = + (0..w).any(|x| buf[(x, last_sky_row)].bg != ratatui::style::Color::Reset); + assert!( + bottom_of_sky_painted, + "{w}x{h}: the sky must reach row {last_sky_row}, one above the footer" + ); + } + } + #[test] fn tick_marks_sky_dirty_only_when_clouds_move() { let tl = timeline();