Skip to content

Commit 36fdeb1

Browse files
denikIsaac
andauthored
Collect per-test coverage in the Linux test cells for the CI dashboard (#7694)
## Changes Collect coverage in the existing Linux cells of `task test` and upload it as a small artifact, `coverage-linux-<cell>`. It is for the CI dashboard, which will show coverage by package and file (unit, acceptance and combined) and which acceptance tests cover each line. - When: on every push to main, and on a PR whose head commit message contains `with-coverage` (for testing changes to this). Windows, macOS and the merge queue do not collect it. - Unit tests: when `CLI_GOCOVERDIR_UNIT` is set, `test-unit-root` runs with `-cover -coverpkg=./...` into that coverage directory. It is a directory rather than `-coverprofile` because `--rerun-fails` runs `go test` again with the same flags, which would overwrite the profile with the coverage of the rerun alone. - Acceptance tests: each per-test coverage directory gets a `name` file with `t.Name()`. The directory name ends in a variant index that does not say which variant ran. - `tools/coverpack` (new, Go) packs both into one zstd file. It reads Go's binary `covmeta`/`covcounters` files directly instead of running `go tool covdata` per test: each distinct meta-data file is parsed once, and a test costs one pass over its counter files. The format is documented at the top of `format.go`. In short: the block layout of each file once, then the distinct per-file bitmaps (one bit per Go block) once, then per test, which bitmap it has for each file it covered. `go run ./coverpack -dump FILE` prints it back as Go cover profile text. - The metadata records the commit that was checked out. For a PR that is GitHub's merge commit, which is what the block positions belong to. ## Why Each per-test coverage directory holds its own ~900 KB copy of the CLI's coverage meta-data, so the raw directories come to several GB per cell. Most tests cover a file the same way as many other tests (mostly the CLI's startup): 2,259 tests have about 3M (test, file) pairs but only 12k distinct bitmaps. | `direct` cell | without coverage (mean of 5 main runs) | this PR | |---|---|---| | Run tests | 6m19s | 8m56s | | Pack coverage | – | 1s (0.7s for 10,846 counter files) | | Whole job | 7m20s | 10m24s | | Artifact | – | 339 KB (2.9 MB uncompressed) | The `directdms` cell gives 307 KB. The overhead is running the tests with `-cover`; packing is negligible. ## Tests - `tools/coverpack/main_test.go` builds a small program with `-cover`, runs it as two "tests" and one unit run, and checks that the packed and dumped profiles equal `go tool covdata textfmt`, including a line with two blocks and a function that never runs. A second test checks that every truncation of a file is rejected. - On 358 local acceptance tests, the dump matches the per-test `covdata textfmt` output in all 360 sections. - This PR's own runs (its commit messages contain `with-coverage`) exercise the CI path end to end; see the `coverage-linux-*` artifacts of its latest run. This pull request and its description were written by Isaac. --------- Co-authored-by: Isaac <no-reply@databricks.com>
1 parent d1d4c9c commit 36fdeb1

10 files changed

Lines changed: 1221 additions & 3 deletions

File tree

‎.github/actions/setup-build-environment/action.yml‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ inputs:
55
cache-key:
66
description: 'Cache key identifier for Go cache'
77
required: true
8+
save-cache:
9+
description: 'Whether a run on main saves the Go cache; off for builds whose objects other runs cannot reuse'
10+
required: false
11+
default: 'true'
812

913
runs:
1014
using: 'composite'
@@ -40,7 +44,7 @@ runs:
4044
# unified action's post-step (which fires at the calling job's
4145
# end, even when invoked from a composite).
4246
- name: Restore and save Go cache (main)
43-
if: github.ref == 'refs/heads/main'
47+
if: github.ref == 'refs/heads/main' && inputs.save-cache == 'true'
4448
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
4549
with:
4650
path: |
@@ -55,7 +59,7 @@ runs:
5559
# main still restore main's most recent cache and rebuild only
5660
# the delta.
5761
- name: Restore Go cache (non-main)
58-
if: github.ref != 'refs/heads/main'
62+
if: github.ref != 'refs/heads/main' || inputs.save-cache != 'true'
5963
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
6064
with:
6165
path: |

‎.github/workflows/push.yml‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ jobs:
141141
uses: ./.github/actions/setup-build-environment
142142
with:
143143
cache-key: test-${{ matrix.deployment.name }}
144+
# Coverage runs (below) build with -cover, so a cache they saved would lack the
145+
# plain objects every other Linux run needs; the nightly run saves it instead.
146+
save-cache: ${{ !(matrix.os.name == 'linux' && github.event_name == 'push') }}
144147

145148
# Make origin/main available with enough history for `git diff --merge-base
146149
# origin/main`, which the acceptance subset selector uses to always run the
@@ -157,8 +160,25 @@ jobs:
157160
git fetch --no-tags --unshallow origin
158161
fi
159162
163+
# Coverage for the CI dashboard: on Linux, for every push to main, and for a PR
164+
# whose head commit message has "with-coverage" (to try a change to it). The
165+
# directories are outside the checkout, so that the check for new files below
166+
# does not see them. The PR's head commit is there after the fetch above.
167+
- name: Decide whether to collect coverage
168+
id: cover
169+
if: ${{ matrix.os.name == 'linux' && (github.event_name == 'push' || github.event_name == 'pull_request') }}
170+
env:
171+
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
172+
run: |
173+
if [ "$GITHUB_EVENT_NAME" = "push" ] || git log -1 --format=%B "$HEAD_SHA" | grep -q 'with-coverage'; then
174+
echo "unit=$RUNNER_TEMP/cover-unit" >> "$GITHUB_OUTPUT"
175+
echo "acc=$RUNNER_TEMP/cover-acc" >> "$GITHUB_OUTPUT"
176+
fi
177+
160178
- name: Run tests
161179
env:
180+
CLI_GOCOVERDIR_UNIT: ${{ steps.cover.outputs.unit }}
181+
CLI_GOCOVERDIR: ${{ steps.cover.outputs.acc }}
162182
ENVFILTER: ${{ matrix.deployment.envfilter }}
163183
# On pull requests, run only a subset of acceptance subtests on the slower
164184
# windows/macOS cells so neither lands on the critical path to merge. An
@@ -184,6 +204,36 @@ jobs:
184204
if-no-files-found: warn
185205
retention-days: 7
186206

207+
# Failed tests count too: their coverage is as real as that of the ones that passed.
208+
- name: Pack coverage
209+
if: ${{ always() && steps.cover.outputs.acc != '' }}
210+
# Coverage is for the dashboard; failing to collect it must not fail the tests.
211+
continue-on-error: true
212+
env:
213+
SHA: ${{ github.event.pull_request.head.sha || github.sha }}
214+
PR_NUMBER: ${{ github.event.pull_request.number }}
215+
OS: ${{ matrix.os.name }}
216+
CELL: ${{ matrix.deployment.name }}
217+
UNIT_DIR: ${{ steps.cover.outputs.unit }}
218+
ACC_DIR: ${{ steps.cover.outputs.acc }}
219+
run: |
220+
go -C tools run ./coverpack -root "$GITHUB_WORKSPACE" -unit "$UNIT_DIR" -acc "$ACC_DIR" \
221+
-o "$RUNNER_TEMP/coverage.bin.zst" \
222+
-meta "{\"sha\": \"$SHA\", \"os\": \"$OS\", \"cell\": \"$CELL\", \"pr\": ${PR_NUMBER:-null}}"
223+
224+
- name: Upload coverage
225+
if: ${{ always() && steps.cover.outputs.acc != '' }}
226+
# Coverage is for the dashboard; failing to collect it must not fail the tests.
227+
continue-on-error: true
228+
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
229+
with:
230+
name: coverage-${{ matrix.os.name }}-${{ matrix.deployment.name }}
231+
path: ${{ runner.temp }}/coverage.bin.zst
232+
if-no-files-found: warn
233+
retention-days: 7
234+
# Already compressed.
235+
compression-level: 0
236+
187237
# `task test` prints a lot of output that GitHub is slow to render, so
188238
# surface just the failed test names on the job summary page (and in this
189239
# step's log) for a quick read of what broke.

‎Taskfile.yml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,14 +482,21 @@ tasks:
482482
# The slowest unit package observed across Linux/macOS/Windows is ~83s, so 10m is
483483
# ample headroom while a hung package (e.g. a wedged goroutine) fails in minutes
484484
# instead of burning the full hour. LOCAL_TIMEOUT still overrides when needed.
485+
#
486+
# CLI_GOCOVERDIR_UNIT (an absolute path) turns on coverage of every package by
487+
# every test (tools/coverpack reads it). It is a coverage directory, not
488+
# -coverprofile, because --rerun-fails runs go test again with the same flags and
489+
# that would overwrite the profile with the coverage of the rerun alone.
490+
- '[ -z "$CLI_GOCOVERDIR_UNIT" ] || mkdir -p "$CLI_GOCOVERDIR_UNIT"'
485491
- |
486492
{{.GO_TOOL}} gotestsum \
487493
--format ${GOTESTSUM_FORMAT:-pkgname-and-test-fails} \
488494
--no-summary=skipped \
489495
--jsonfile test-output-unit-root.json \
490496
--rerun-fails \
491497
--packages "{{.TEST_PACKAGES}}" \
492-
-- -timeout=${LOCAL_TIMEOUT:-10m}
498+
-- ${CLI_GOCOVERDIR_UNIT:+-cover -coverpkg=./...} -timeout=${LOCAL_TIMEOUT:-10m} \
499+
${CLI_GOCOVERDIR_UNIT:+-args -test.gocoverdir=$CLI_GOCOVERDIR_UNIT}
493500
494501
test-unit-tools:
495502
desc: Run unit tests in tools/ module

‎acceptance/acceptance_test.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,6 +1036,8 @@ func runTest(t *testing.T,
10361036
}
10371037
err := os.MkdirAll(coverDir, os.ModePerm)
10381038
require.NoError(t, err)
1039+
// The directory name does not say which variant it is; tools/coverpack reads the test name from here.
1040+
testutil.WriteFile(t, filepath.Join(coverDir, "name"), t.Name())
10391041
cmd.Env = append(cmd.Env, "GOCOVERDIR="+coverDir)
10401042
}
10411043

‎tools/coverpack/format.go‎

Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
package main
2+
3+
// The packed file, zstd-compressed. Inside, a uvarint is unsigned LEB128 (encoding/binary's
4+
// uvarint):
5+
//
6+
// "CLICOV1\n"
7+
// uvarint n, n bytes meta, JSON: the -meta object plus "go", "module" and "commit" (the commit that was
8+
// checked out and tested; for a PR, GitHub's merge of it into the base branch)
9+
// uvarint L layouts, sorted by path:
10+
// uvarint n, n bytes path relative to the module ("bundle/deploy/x.go")
11+
// 20 bytes git blob sha of the file as read (zeros if it was not found)
12+
// uvarint line count
13+
// uvarint B blocks, sorted by start, then end; per block:
14+
// uvarint sl - previous sl, uvarint sc, uvarint el - sl, uvarint ec, uvarint statements
15+
// (as in a Go cover profile: lines and byte columns 1-based, the end exclusive)
16+
// L times the distinct bitmaps of each layout, in layout order:
17+
// uvarint P, then P bitmaps of ceil(B / 8) bytes: block i is bit i % 8 of byte i / 8
18+
// uvarint N profiles:
19+
// 1 byte kind 0: all acceptance tests merged, 1: unit tests merged, 2: one acceptance test
20+
// uvarint n, n bytes test name (t.Name()), empty for kinds 0 and 1
21+
// uvarint F files, by layout; per file: uvarint layout - previous layout, uvarint bitmap index
22+
//
23+
// Kinds 0 and 1 list every file of their build, covered or not: they are its inventory. A file
24+
// that a test (kind 2) does not list was not covered by it if the build has the file, else it is
25+
// unknown.
26+
27+
import (
28+
"encoding/binary"
29+
"errors"
30+
"fmt"
31+
"io"
32+
)
33+
34+
const magic = "CLICOV1\n"
35+
36+
const (
37+
kindAll = 0
38+
kindUnit = 1
39+
kindTest = 2
40+
)
41+
42+
type layout struct {
43+
path string // relative to the module
44+
sha [20]byte
45+
lines int
46+
blocks []block
47+
first int // catalog id of blocks[0]; the ids of a layout are consecutive
48+
}
49+
50+
type profile struct {
51+
kind byte
52+
name string
53+
files []int // layouts, ascending
54+
bits bitset
55+
}
56+
57+
type bitset []uint64
58+
59+
func newBitset(n int) bitset { return make(bitset, (n+63)/64) }
60+
61+
func (b bitset) set(i int32) { b[i>>6] |= 1 << (i & 63) }
62+
func (b bitset) has(i int) bool { return b[i>>6]>>(i&63)&1 != 0 }
63+
64+
func (b bitset) or(o bitset) {
65+
for i := range b {
66+
b[i] |= o[i]
67+
}
68+
}
69+
70+
// bitmap is the bits of a layout, in the order of the file.
71+
func (b bitset) bitmap(l *layout) []byte {
72+
out := make([]byte, (len(l.blocks)+7)/8)
73+
for i := range l.blocks {
74+
if b.has(l.first + i) {
75+
out[i/8] |= 1 << (i % 8)
76+
}
77+
}
78+
return out
79+
}
80+
81+
// encode returns the uncompressed file and the number of distinct bitmaps in it.
82+
func encode(meta []byte, layouts []*layout, profiles []profile) ([]byte, int) {
83+
distinct := make([]map[string]int, len(layouts))
84+
order := make([][][]byte, len(layouts))
85+
index := make([][]int, len(profiles))
86+
for p, prof := range profiles {
87+
for _, l := range prof.files {
88+
bm := prof.bits.bitmap(layouts[l])
89+
if distinct[l] == nil {
90+
distinct[l] = map[string]int{}
91+
}
92+
i, ok := distinct[l][string(bm)]
93+
if !ok {
94+
i = len(order[l])
95+
distinct[l][string(bm)] = i
96+
order[l] = append(order[l], bm)
97+
}
98+
index[p] = append(index[p], i)
99+
}
100+
}
101+
102+
out := []byte(magic)
103+
put := func(v int) { out = binary.AppendUvarint(out, uint64(v)) }
104+
putBytes := func(b []byte) { put(len(b)); out = append(out, b...) }
105+
106+
putBytes(meta)
107+
put(len(layouts))
108+
for _, l := range layouts {
109+
putBytes([]byte(l.path))
110+
out = append(out, l.sha[:]...)
111+
put(l.lines)
112+
put(len(l.blocks))
113+
prev := uint32(0)
114+
for _, b := range l.blocks {
115+
put(int(b.sl - prev))
116+
put(int(b.sc))
117+
put(int(b.el - b.sl))
118+
put(int(b.ec))
119+
put(int(b.stmts))
120+
prev = b.sl
121+
}
122+
}
123+
total := 0
124+
for l := range layouts {
125+
put(len(order[l]))
126+
for _, bm := range order[l] {
127+
out = append(out, bm...)
128+
}
129+
total += len(order[l])
130+
}
131+
put(len(profiles))
132+
for p, prof := range profiles {
133+
out = append(out, prof.kind)
134+
putBytes([]byte(prof.name))
135+
put(len(prof.files))
136+
prev := 0
137+
for i, l := range prof.files {
138+
put(l - prev)
139+
put(index[p][i])
140+
prev = l
141+
}
142+
}
143+
return out, total
144+
}
145+
146+
// decoded is a packed file read back.
147+
type decoded struct {
148+
meta []byte
149+
layouts []*layout
150+
bitmaps [][][]byte // per layout
151+
profiles []decodedProfile
152+
}
153+
154+
type decodedProfile struct {
155+
kind byte
156+
name string
157+
files []int // layouts, ascending
158+
index []int // bitmap of each file
159+
}
160+
161+
func decode(data []byte) (*decoded, error) {
162+
c := &cursor{b: data}
163+
if string(c.take(len(magic))) != magic {
164+
return nil, errors.New("not a coverpack file")
165+
}
166+
str := func() []byte { return c.take(c.count()) }
167+
d := &decoded{meta: str()}
168+
d.layouts = make([]*layout, c.count())
169+
for i := range d.layouts {
170+
l := &layout{path: string(str())}
171+
copy(l.sha[:], c.take(20))
172+
l.lines = int(c.uleb128())
173+
l.blocks = make([]block, c.count())
174+
sl := uint32(0)
175+
for j := range l.blocks {
176+
sl += uint32(c.uleb128())
177+
b := block{file: l.path, sl: sl, sc: uint32(c.uleb128())}
178+
b.el = sl + uint32(c.uleb128())
179+
b.ec = uint32(c.uleb128())
180+
b.stmts = uint32(c.uleb128())
181+
l.blocks[j] = b
182+
}
183+
d.layouts[i] = l
184+
}
185+
d.bitmaps = make([][][]byte, len(d.layouts))
186+
for i, l := range d.layouts {
187+
d.bitmaps[i] = make([][]byte, c.count())
188+
for j := range d.bitmaps[i] {
189+
d.bitmaps[i][j] = c.take((len(l.blocks) + 7) / 8)
190+
}
191+
}
192+
d.profiles = make([]decodedProfile, c.count())
193+
for i := range d.profiles {
194+
p := decodedProfile{kind: c.u8(), name: string(str())}
195+
n, l := c.count(), 0
196+
for range n {
197+
l += int(c.uleb128())
198+
p.files = append(p.files, l)
199+
p.index = append(p.index, int(c.uleb128()))
200+
}
201+
d.profiles[i] = p
202+
}
203+
if c.err != nil {
204+
return nil, c.err
205+
}
206+
for _, p := range d.profiles {
207+
for i, l := range p.files {
208+
if l < 0 || l >= len(d.layouts) || p.index[i] < 0 || p.index[i] >= len(d.bitmaps[l]) {
209+
return nil, errMalformed
210+
}
211+
}
212+
}
213+
return d, nil
214+
}
215+
216+
// dumpText writes the profiles as Go cover profile text, each after a "# all", "# unit" or
217+
// "# test NAME" line. A test lists its covered blocks only.
218+
func dumpText(w io.Writer, d *decoded, module string) error {
219+
if _, err := fmt.Fprintf(w, "# coverage %s\n", d.meta); err != nil {
220+
return err
221+
}
222+
for _, p := range d.profiles {
223+
header := []string{"# all", "# unit"}
224+
h := "# test " + p.name
225+
if int(p.kind) < len(header) {
226+
h = header[p.kind]
227+
}
228+
if _, err := fmt.Fprintln(w, h); err != nil {
229+
return err
230+
}
231+
for i, l := range p.files {
232+
bm := d.bitmaps[l][p.index[i]]
233+
for j, b := range d.layouts[l].blocks {
234+
covered := bm[j/8] >> (j % 8) & 1
235+
if covered == 0 && p.kind == kindTest {
236+
continue
237+
}
238+
if _, err := fmt.Fprintf(w, "%s/%s:%d.%d,%d.%d %d %d\n", module, b.file, b.sl, b.sc, b.el, b.ec, b.stmts, covered); err != nil {
239+
return err
240+
}
241+
}
242+
}
243+
}
244+
return nil
245+
}

0 commit comments

Comments
 (0)