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/.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 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"], + }, +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff9ef3b..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,14 @@ jobs: zizmor: name: zizmor (Actions security) runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@v7 - - run: pipx run zizmor==1.28.0 --min-severity high .github/workflows/ + with: + persist-credentials: false + - 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/.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/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/.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 }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a3b31c..4f76ef4 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,54 @@ 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 + profile: dist token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/attest@v4 + 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 @@ -42,6 +85,7 @@ jobs: with: repository: lmarkmann/homebrew-tap token: ${{ secrets.HOMEBREW_TAP_TOKEN }} + persist-credentials: true path: tap - name: render formula 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 37be531..a7c3da2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,11 @@ 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. + ".cargo/", ] [workspace] @@ -69,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" @@ -95,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/README.md b/README.md index 4c16356..e669304 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ # 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) +[![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 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/benches/render.rs b/benches/render.rs index 3d1e627..df24c0c 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| { @@ -86,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(); } @@ -131,6 +146,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 +384,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 +404,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 +438,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 +496,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(); diff --git a/justfile b/justfile index 7de94f2..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 @@ -98,6 +110,32 @@ lock: bench: cargo bench --bench render +# 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 + +# --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 diff --git a/prek.toml b/prek.toml index 607074f..ce9e1bf 100644 --- a/prek.toml +++ b/prek.toml @@ -20,3 +20,37 @@ 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"] + +[[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"] 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})"); + } + } + } } 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()]; diff --git a/src/tui/app.rs b/src/tui/app.rs index a29e854..b19a08c 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}; @@ -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); @@ -702,12 +735,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, @@ -1383,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(); @@ -1426,6 +1510,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(); 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}"),