diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a64708..1329d46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -127,6 +127,27 @@ jobs: awk -v t="$cov" 'BEGIN { exit !(t+0 >= 100.0) }' || { echo "::error::coverage ${cov}% < 100%"; exit 1; } + # tools/covgate is the coverage gate of the vector lane below, a module of its + # own (cobra), and it gates itself. + covgate: + name: tools/covgate (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + defaults: + run: + working-directory: tools/covgate + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7 + with: + go-version: '1.27.4' + - run: go vet ./... + - name: Test + 100% coverage gate + run: go test -race -coverprofile=cover.out ./... && go run . cover.out + # The media module on 32-bit. A job of its own on Linux, not a step guarded by # `if: runner.os` in the matrix above: buildscan reads that step as a 32-bit # build on every OS of the matrix, including darwin/386, which does not exist. @@ -187,13 +208,16 @@ jobs: - run: go test ./... # The vector EASU/RCAS kernels (upscale/easu_simd.go) exist only under the # experiment, so the 100% gate of the scalar lanes never sees them. + # The permute gather (easu_perm_amd64.go) runs only with AVX-512, which a + # hosted amd64 runner has or lacks from one job to the next: a plain + # "total = 100%" was green on #149 and red on its merge commit (94.4%). + # covgate requires every block, and excuses that one file only on a CPU + # without avx512f, with a warning that counts what was not measured; with + # avx512f it says that the file is held like the rest. - name: upscale coverage gate, vector lane run: | go test -coverprofile=cover-simd.out ./upscale - cov=$(go tool cover -func=cover-simd.out | tail -1 | awk '{print $3}' | tr -d '%') - echo "coverage: ${cov}%" - awk -v t="$cov" 'BEGIN { exit !(t+0 >= 100.0) }' || { - echo "::error::upscale coverage ${cov}% < 100% under GOEXPERIMENT=simd"; exit 1; } + go -C tools/covgate run . --needs-cpu avx512f=upscale/easu_perm_amd64.go ../../cover-simd.out # The one 32-bit target. 386 runs natively on the amd64 runner, without qemu, # and it is where int and uint are 32 bits wide: a length converted to int diff --git a/README.md b/README.md index 2743197..2109be2 100644 --- a/README.md +++ b/README.md @@ -1453,14 +1453,21 @@ comparison favours ffmpeg: | Threads | `upscale` FSR EASU+RCAS | ffmpeg lanczos | |---------|-------------------------|----------------| -| 1 | 26.2 (core 9) | 2.8 (core 9) | -| 2 | 13.2 | | -| 4 | 6.9 | | -| 8 | 4.3 to 4.6 | 0.20 | -| 16 | 3.5 to 3.6 | 0.20 | +| 1 | 28.7 to 29.3 (core 9) | 2.8 (core 9) | +| 2 | 14.5 | | +| 4 | 7.5 | | +| 8 | 5.4 | 0.20 | +| 16 | 3.6 | 0.20 | The `upscale` column is elapsed time per frame throughout (`go test -bench`, -25.8 with one worker when not pinned). For ffmpeg, one thread is user CPU time +28.7 with one worker when not pinned; with several workers, the best two of +three runs, the third having been disturbed by another load). These are +measured at the merged code. A first version of this table said 26.2 on one +core: that was measured before the position of an output pixel was computed in +integers, a correction which costs 10 % on the same core for a reason we have +not established, the per-pixel code being unchanged. With several workers +`-benchmem` reports 0 allocs/op and between 1 and 522 B/op, that is an +allocation every few frames, whose origin has not been traced either. For ffmpeg, one thread is user CPU time on a pinned core; several threads are elapsed time (`-threads 0 -filter_threads N` and swscale `threads=N`), a difference of two runs of about 0.1 s over 300 frames, so 0.20 is an order of magnitude, not a precise figure. Runs on several @@ -1470,15 +1477,15 @@ agrees with the vector one within `ErrorBound`, was 242 at v0.24.0. This release resolves the taps once per output row, factors the rotation out of the twelve tap offsets and vectorises the luma and the last pixels of an RCAS row. -FSR remains 9.4 times slower than ffmpeg's lanczos on one core and about 17 +FSR remains 10.4 times slower than ffmpeg's lanczos on one core and about 18 times on sixteen threads. We do not expect that gap to close on a CPU: a separable filter applies fixed taps along each axis, where EASU computes for every output pixel an edge direction from twelve taps, then twelve rotated, anisotropic weights and a division. A 16-bit integer or half-float path was considered and not built: by our reasoning, not by measurement, it cannot hold `ErrorBound` = 2e-4, a 16-bit half-float carrying 11 significant bits. With 16 -workers a 1080p frame takes 3.5 ms, which fits a 60 Hz frame (16.7 ms); on one -core it does not. Scaling is 7.4 times at 16 workers and 6 times at 8; where the +workers a 1080p frame takes 3.6 ms, which fits a 60 Hz frame (16.7 ms); on one +core it does not. Scaling is 8 times at 16 workers and 5.3 times at 8; where the rest goes has not been profiled. Reproduce both tables with `tools/fsrbench` (its own module; needs `ffmpeg` on the diff --git a/tools/covgate/go.mod b/tools/covgate/go.mod new file mode 100644 index 0000000..17678c1 --- /dev/null +++ b/tools/covgate/go.mod @@ -0,0 +1,10 @@ +module github.com/go-avkit/avkit/tools/covgate + +go 1.27.4 + +require github.com/spf13/cobra v1.10.2 + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/tools/covgate/go.sum b/tools/covgate/go.sum new file mode 100644 index 0000000..a6ee3e0 --- /dev/null +++ b/tools/covgate/go.sum @@ -0,0 +1,10 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/tools/covgate/main.go b/tools/covgate/main.go new file mode 100644 index 0000000..dc42f08 --- /dev/null +++ b/tools/covgate/main.go @@ -0,0 +1,191 @@ +// Command covgate is the 100 % coverage gate of a lane whose runner may lack +// the CPU a kernel needs. +// +// covgate [--needs-cpu FLAG=FILE]... [--cpuinfo /proc/cpuinfo] cover.out +// +// It fails when a block of the profile was never entered. A block in a file +// named by --needs-cpu is excused only when the CPU of this machine lacks +// FLAG, and each excuse is printed as a warning with its statement count: the +// kernel was not measured here, which is not the same as covered. +// +// Why it exists: upscale/easu_perm_amd64.go runs only with AVX-512, and the +// hosted amd64 runners have it or not from one job to the next. A plain +// "total = 100 %" gate was green on the pull request and red on the merge +// commit of the same tree (go-avkit/avkit#149, run 46292291989: 94.4 %). +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" + + "github.com/spf13/cobra" +) + +var osExit = os.Exit + +func main() { + if err := RootCmd().Execute(); err != nil { + osExit(1) + } +} + +// RootCmd builds the command. +func RootCmd() *cobra.Command { + var ( + needs []string + cpuinfo string + ) + cmd := &cobra.Command{ + Use: "covgate [flags] profile", + Short: "Fail unless every block of a Go coverage profile ran, excusing only what this CPU cannot run", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + return run(cmd.OutOrStdout(), args[0], cpuinfo, needs) + }, + } + cmd.Flags().StringArrayVar(&needs, "needs-cpu", nil, + "FLAG=FILE: blocks of FILE (a path suffix) are excused when the CPU lacks FLAG") + cmd.Flags().StringVar(&cpuinfo, "cpuinfo", "/proc/cpuinfo", "where the CPU flags are read") + return cmd +} + +// block is one line of a coverage profile. +type block struct { + file, pos string + stmts int + hit bool +} + +// parseProfile reads a Go coverage profile, merging the lines that repeat a +// block (one per test binary). +func parseProfile(r io.Reader) ([]block, error) { + sc := bufio.NewScanner(r) + if !sc.Scan() || !strings.HasPrefix(sc.Text(), "mode: ") { + return nil, fmt.Errorf("not a coverage profile: no mode line") + } + var out []block + at := map[string]int{} + for n := 2; sc.Scan(); n++ { + line := sc.Text() + if line == "" { + continue + } + // "file:pos stmts count". The fields are padded so that one guard + // holds the whole shape and nothing below it can index out of range. + i := max(strings.LastIndexByte(line, ':'), 0) + file, fields := line[:i], strings.Fields(line[i:]) + f := append(fields, "", "", "")[:3] + stmts, err1 := strconv.Atoi(f[1]) + count, err2 := strconv.ParseUint(f[2], 10, 64) + if file == "" || len(fields) != 3 || err1 != nil || err2 != nil || stmts < 0 { + return nil, fmt.Errorf("line %d: not a block: %q", n, line) + } + pos := strings.TrimPrefix(f[0], ":") + key := file + ":" + pos + k, seen := at[key] + if !seen { + k = len(out) + at[key] = k + out = append(out, block{file: file, pos: pos, stmts: stmts}) + } + out[k].hit = out[k].hit || count > 0 + } + return out, sc.Err() +} + +// cpuFlags reads the feature names of the first CPU of a Linux cpuinfo file +// ("flags" on x86, "Features" on arm64). +func cpuFlags(path string) (map[string]bool, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("CPU flags unread: %w", err) + } + for _, line := range strings.Split(string(b), "\n") { + k, v, ok := strings.Cut(line, ":") + if k = strings.TrimSpace(k); !ok || (k != "flags" && k != "Features") { + continue + } + flags := map[string]bool{} + for _, f := range strings.Fields(v) { + flags[f] = true + } + return flags, nil + } + return nil, fmt.Errorf("CPU flags unread: no flags line in %s", path) +} + +func run(w io.Writer, profile, cpuinfo string, needs []string) error { + f, err := os.Open(profile) + if err != nil { + return err + } + defer f.Close() + blocks, err := parseProfile(f) + if err != nil { + return err + } + // excuse: file suffix -> the flag this CPU lacks. + excuse := map[string]string{} + if len(needs) > 0 { + flags, err := cpuFlags(cpuinfo) + if err != nil { + return err + } + for _, n := range needs { + flag, file, ok := strings.Cut(n, "=") + if !ok || flag == "" || file == "" { + return fmt.Errorf("--needs-cpu %q: want FLAG=FILE", n) + } + if !flags[flag] { + excuse[file] = flag + continue + } + fmt.Fprintf(w, "covgate: this CPU has %s: %s is held like the rest\n", flag, file) + } + } + var total, hit, red int + excused := map[string]int{} + for _, b := range blocks { + total += b.stmts + if b.hit { + hit += b.stmts + continue + } + if s := suffixOf(excuse, b.file); s != "" { + excused[s] += b.stmts + continue + } + red += b.stmts + fmt.Fprintf(w, "not covered: %s:%s (%d statement(s))\n", b.file, b.pos, b.stmts) + } + fmt.Fprintf(w, "covgate: %d of %d statements ran\n", hit, total) + for _, n := range needs { + _, file, _ := strings.Cut(n, "=") + if c := excused[file]; c > 0 { + fmt.Fprintf(w, "::warning::%d statement(s) of %s were NOT measured: this CPU has no %s\n", c, file, excuse[file]) + delete(excused, file) + } + } + if total == 0 { + return fmt.Errorf("the profile holds no statement: nothing was measured") + } + if red > 0 { + return fmt.Errorf("%d statement(s) never ran", red) + } + return nil +} + +// suffixOf returns the key of m that file ends with, or "". +func suffixOf(m map[string]string, file string) string { + for s := range m { + if strings.HasSuffix(file, s) { + return s + } + } + return "" +} diff --git a/tools/covgate/main_test.go b/tools/covgate/main_test.go new file mode 100644 index 0000000..f0f487f --- /dev/null +++ b/tools/covgate/main_test.go @@ -0,0 +1,147 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +const ( + x86With = "processor\t: 0\nflags\t\t: fpu avx2 avx512f avx512bw\n" + x86Without = "processor\t: 0\nflags\t\t: fpu avx2\n" + arm = "processor\t: 0\nFeatures\t: fp asimd\n" + + full = "mode: set\n" + + "m/upscale/a.go:1.1,2.2 3 1\n" + + "m/upscale/easu_perm_amd64.go:5.1,9.2 4 1\n" + // The permute kernel never entered, a.go entered by the second binary only. + noPerm = "mode: set\n" + + "m/upscale/a.go:1.1,2.2 3 0\n" + + "m/upscale/easu_perm_amd64.go:5.1,9.2 4 0\n" + + "\n" + + "m/upscale/a.go:1.1,2.2 3 7\n" + hole = "mode: set\n" + + "m/upscale/a.go:1.1,2.2 3 0\n" + + "m/upscale/easu_perm_amd64.go:5.1,9.2 4 0\n" +) + +func write(t *testing.T, s string) string { + t.Helper() + p := filepath.Join(t.TempDir(), "f") + if err := os.WriteFile(p, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func gate(t *testing.T, args ...string) (string, error) { + t.Helper() + var out bytes.Buffer + cmd := RootCmd() + cmd.SetArgs(args) + cmd.SetOut(&out) + cmd.SetErr(&out) + err := cmd.Execute() + return out.String(), err +} + +func TestGate(t *testing.T) { + need := "avx512f=upscale/easu_perm_amd64.go" + for _, c := range []struct { + name, profile, cpu string + needs []string + ok bool + want string + }{ + {"full, no excuse asked", full, "", nil, true, "7 of 7 statements ran"}, + {"full, AVX-512 present", full, x86With, []string{need}, true, + "this CPU has avx512f: upscale/easu_perm_amd64.go is held like the rest"}, + {"kernel unmeasured, CPU lacks it", noPerm, x86Without, []string{need}, true, + "::warning::4 statement(s) of upscale/easu_perm_amd64.go were NOT measured: this CPU has no avx512f"}, + {"kernel unmeasured on arm64", noPerm, arm, []string{need}, true, "::warning::4"}, + {"kernel unmeasured, CPU HAS it", noPerm, x86With, []string{need}, false, "easu_perm_amd64.go:5.1,9.2"}, + {"kernel unmeasured, no excuse asked", noPerm, "", nil, false, "4 statement(s) never ran"}, + {"another file unmeasured is never excused", hole, x86Without, []string{need}, false, "not covered: m/upscale/a.go:1.1,2.2"}, + {"an excuse that excuses nothing prints nothing", full, x86Without, []string{need}, true, "7 of 7"}, + {"empty profile is not a pass", "mode: set\n", "", nil, false, "nothing was measured"}, + {"no mode line", "m/a.go:1.1,2.2 3 1\n", "", nil, false, "no mode line"}, + {"no colon", "mode: set\nnonsense\n", "", nil, false, "line 2"}, + {"two fields", "mode: set\nm/a.go:1.1,2.2 3\n", "", nil, false, "line 2"}, + {"count not a number", "mode: set\nm/a.go:1.1,2.2 3 x\n", "", nil, false, "line 2"}, + {"negative statements", "mode: set\nm/a.go:1.1,2.2 -3 1\n", "", nil, false, "line 2"}, + {"cpuinfo without flags", full, "processor: 0\nnoflags\n", []string{need}, false, "no flags line"}, + {"malformed need", full, x86With, []string{"avx512f"}, false, "want FLAG=FILE"}, + {"need without file", full, x86With, []string{"avx512f="}, false, "want FLAG=FILE"}, + } { + args := []string{"--cpuinfo", write(t, c.cpu)} + for _, n := range c.needs { + args = append(args, "--needs-cpu", n) + } + out, err := gate(t, append(args, write(t, c.profile))...) + if (err == nil) != c.ok { + t.Errorf("%s: err = %v, want ok = %v\n%s", c.name, err, c.ok, out) + } + if !strings.Contains(out, c.want) { + t.Errorf("%s: output lacks %q:\n%s", c.name, c.want, out) + } + if c.ok && strings.Contains(out, "not covered") { + t.Errorf("%s: a pass that lists an uncovered block:\n%s", c.name, out) + } + } +} + +// A warning is the only trace of an excuse: a pass with no excuse has none. +func TestNoWarningWithoutExcuse(t *testing.T) { + out, err := gate(t, "--cpuinfo", write(t, x86Without), "--needs-cpu", "avx512f=upscale/easu_perm_amd64.go", write(t, full)) + if err != nil || strings.Contains(out, "::warning::") { + t.Fatalf("err %v, output:\n%s", err, out) + } +} + +func TestUnreadFiles(t *testing.T) { + missing := filepath.Join(t.TempDir(), "absent") + // A file that cannot be opened is said to be so, not parsed as an empty one. + out, err := gate(t, missing) + if err == nil || strings.Contains(out, "not a coverage profile") { + t.Errorf("missing profile: err %v\n%s", err, out) + } + out, err = gate(t, "--cpuinfo", missing, "--needs-cpu", "avx512f=x.go", write(t, full)) + if err == nil || !strings.Contains(out, "CPU flags unread") || strings.Contains(out, "no flags line") { + t.Errorf("unreadable cpuinfo: err %v\n%s", err, out) + } +} + +func TestMainExit(t *testing.T) { + defer func(a []string, e func(int)) { os.Args, osExit = a, e }(os.Args, osExit) + code := -1 + osExit = func(c int) { code = c } + os.Args = []string{"covgate", write(t, full)} + main() + if code != -1 { + t.Fatalf("a full profile exited %d", code) + } + os.Args = []string{"covgate", write(t, hole)} + main() + if code != 1 { + t.Fatalf("a profile with a hole exited %d", code) + } +} + +func FuzzParseProfile(f *testing.F) { + for _, s := range []string{full, noPerm, hole, "", "mode: set\n:\n", "mode: set\na: b 1 1\n", "mode: set\nm/a.go:1.1,2.2 99999999999999999999 1\n"} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, s string) { + blocks, err := parseProfile(strings.NewReader(s)) + if err != nil { + return + } + for _, b := range blocks { + if b.stmts < 0 || b.file == "" { + t.Fatalf("accepted block %+v from %q", b, s) + } + } + }) +}