From 3436e16b4e5c06b48d7d3164358e5f763cb96188 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:57:46 +0000 Subject: [PATCH 01/11] test: give a test's timing judgement one home in internal/testtiming No shared way to judge how long something took existed. The ratio of a reference with a floor lived inside lint's scalesLinearly, and the process CPU clock was copied three times, in core/reading, surface/cli and implement/loop. A fix for each slow-runner flake would otherwise add a fourth copy, which one-canonical-primitive forbids. internal/testtiming is a standard-library leaf imported only by tests: Bound holds a measured run to Ratio times a reference measured in the same run and never under Floor; CutShort is the Bound for a run that a context or a kill ends, judged against the work it ended; CPU is the process's CPU clock. scalesLinearly takes its bound from Bound.Limit, and the three clock copies are now testtiming.CPU. The reading package's test of the clock moves to testtiming with it. The package map names the package, and the choice is recorded as a decision. Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...7-a-test-judges-how-long-something-took.md | 6 ++ internal/README.md | 6 ++ internal/core/implement/loop/findings_test.go | 20 ++--- internal/core/lint/personquote_test.go | 3 +- internal/core/reading/cpuclock_test.go | 58 +++----------- internal/surface/cli/cpuclock_test.go | 28 +++---- internal/testtiming/testtiming.go | 78 +++++++++++++++++++ internal/testtiming/testtiming_test.go | 73 +++++++++++++++++ 8 files changed, 191 insertions(+), 81 deletions(-) create mode 100644 .abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md create mode 100644 internal/testtiming/testtiming.go create mode 100644 internal/testtiming/testtiming_test.go diff --git a/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md b/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md new file mode 100644 index 0000000000..63f5f1cdaf --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022252475157 +slug: a-test-judges-how-long-something-took +date: 2026-12-02 +--- +2026-12-02 — A test judges how long something took through internal/testtiming, a new standard-library leaf imported only by tests: a Bound holds a measured run to a ratio of a reference measured in the same run and never under a floor, CutShort judges a run a context or kill ends against the work it ended, and CPU is the one process CPU clock. Grounds (iss-2612022218392055): no shared helper existed; the ratio-and-floor judgement lived inside lint's scalesLinearly, and the CPU clock was copied three times (core/reading, surface/cli, implement/loop), so one-canonical-primitive forbids a further copy and gittest, the other shared test package, is git's. Those copies now call it. To reverse: inline Bound.Limit back into scalesLinearly and the processCPU and cpuTime copies, and delete the package; nothing outside tests imports it. diff --git a/internal/README.md b/internal/README.md index 5611258ccc..93a98b0dd4 100644 --- a/internal/README.md +++ b/internal/README.md @@ -487,6 +487,12 @@ plugin surface, and a future MCP server share one engine. terminal I/O. It sits outside `core/` and `term/` so the banner and the core's question row estimate measure text the same way without the core importing raw-mode terminal code. +- **`testtiming/`** — the one way a test judges how long something took + (iss-2612022218392055): a `Bound` holds a measured run to a ratio of a + reference measured in the same run, never under a floor, so a slow or + loaded runner slows both alike; `CutShort` judges a run a context or a kill + ends against the work it ended; `CPU` is the process's CPU clock a cost is + read off. Imported only by tests; a standard-library leaf. - **`surface/cli/`** — the default front door: a Cobra command tree that calls `core` and formats results as text or `--json`. Holds no business logic. - **`surface/cli/ask/`** — the drawing of a question in a plain Terminal diff --git a/internal/core/implement/loop/findings_test.go b/internal/core/implement/loop/findings_test.go index 5ef4b089ba..caf75c4631 100644 --- a/internal/core/implement/loop/findings_test.go +++ b/internal/core/implement/loop/findings_test.go @@ -9,11 +9,11 @@ import ( "runtime" "slices" "strings" - "syscall" "testing" "time" "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // The per-reviewer findings record (itd-2610240922461281, @@ -329,18 +329,12 @@ var timeRead = func(read func()) time.Duration { // part of what it reads. const readFloor = 10 * time.Millisecond -// cpuTime is the user and system CPU time the process has used. It is the -// whole process's clock, the collector's work in it, on every platform: Linux -// reads one thread's time without the slice it is running, so a read shorter -// than a scheduler tick could read as nothing, while the process's time takes -// that slice in. The coarse-clock test replaces it. -var cpuTime = func() time.Duration { - var ru syscall.Rusage - if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { - panic(err) - } - return time.Duration(ru.Utime.Nano() + ru.Stime.Nano()) -} +// cpuTime is the user and system CPU time the process has used, testtiming.CPU. +// It is the whole process's clock, the collector's work in it, on every +// platform: Linux reads one thread's time without the slice it is running, so +// a read shorter than a scheduler tick could read as nothing, while the +// process's time takes that slice in. The coarse-clock test replaces it. +var cpuTime = testtiming.CPU // TestAReadIsNotChargedTheTimeItIsNotRunning: the clock a read is timed by // counts the work done, not the time the process waits. A sleep stands in diff --git a/internal/core/lint/personquote_test.go b/internal/core/lint/personquote_test.go index 41599b9eb6..f20a61fb90 100644 --- a/internal/core/lint/personquote_test.go +++ b/internal/core/lint/personquote_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // TestPersonQuotesOnALine is the pattern's table (iss-2611291032489366): a line @@ -322,7 +323,7 @@ func scalesLinearly(clock linearClock, what string, slack float64, floor time.Du } } smallTime = max(smallTime, time.Microsecond) - bound := max(time.Duration(slack*sizes*float64(smallTime)), floor) + bound := testtiming.Bound{Ratio: slack * sizes, Floor: floor}.Limit(smallTime) bigTime, ended := clock.tookWithin(func() { judge(big) }, time.Duration(linearStraggle)*bound) if !ended { return "", fmt.Errorf("%s: %d bytes took %v, and %d bytes, %.0f times the length, ran on past %d times its bound of %v (%g times as long again, and never under %v) on attempt %d%s: the cost is not linear", diff --git a/internal/core/reading/cpuclock_test.go b/internal/core/reading/cpuclock_test.go index 3b55e54cd5..24c3be1f5d 100644 --- a/internal/core/reading/cpuclock_test.go +++ b/internal/core/reading/cpuclock_test.go @@ -1,50 +1,12 @@ package reading -import ( - "syscall" - "testing" - "time" -) - -// processCPU is the CPU time this test process has consumed, user and system, -// across every thread. The linearity guards bound it rather than the wall clock -// because it is the cost that tells a linear scan from a quadratic one and the -// one machine load cannot inflate: time spent waiting for a core is not -// charged, so a gate run on a busy machine reads the same figure as an idle one -// (iss-2609240046582859). No test in this package runs in parallel, so the -// figure is the guarded call's, plus the runtime's own collector. getrusage is -// the macOS and Linux call the gates run on. -func processCPU() time.Duration { - var ru syscall.Rusage - if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { - panic("getrusage: " + err.Error()) - } - return time.Duration(ru.Utime.Nano() + ru.Stime.Nano()) -} - -// TestTheLinearityClockDoesNotChargeWaiting: the clock the linearity guards -// read charges work, not waiting. A wall-clock ceiling charged the time a -// loaded machine kept the scan off a core, so a gate run could fail on linear -// code with nothing wrong (iss-2609240046582859); a sleep stands in for that -// wait here, and the clock must not see it. -func TestTheLinearityClockDoesNotChargeWaiting(t *testing.T) { - start := processCPU() - time.Sleep(300 * time.Millisecond) - if spent := processCPU() - start; spent > 100*time.Millisecond { - t.Fatalf("the clock charged %s across a 300ms wait; it counts time off the core, which load inflates", spent) - } - - // And it charges work, or every ceiling read off it would pass a quadratic scan. - start = processCPU() - deadline := time.Now().Add(30 * time.Second) - sink := 0 - for processCPU()-start < 50*time.Millisecond { - if time.Now().After(deadline) { - t.Fatalf("30s of spinning charged %s; the clock does not count work", processCPU()-start) - } - for i := range 100000 { - sink += i - } - } - _ = sink -} +import "github.com/intentdriven/abcd/internal/testtiming" + +// processCPU is the clock the linearity guards read: testtiming.CPU, the CPU +// time this test process has consumed. It is the cost that tells a linear scan +// from a quadratic one and the one machine load cannot inflate: time spent +// waiting for a core is not charged, so a gate run on a busy machine reads the +// same figure as an idle one (iss-2609240046582859); testtiming's own test +// holds that. No test in this package runs in parallel, so the figure is the +// guarded call's, plus the runtime's own collector. +var processCPU = testtiming.CPU diff --git a/internal/surface/cli/cpuclock_test.go b/internal/surface/cli/cpuclock_test.go index 0ee17c24df..1c40b9b735 100644 --- a/internal/surface/cli/cpuclock_test.go +++ b/internal/surface/cli/cpuclock_test.go @@ -1,22 +1,12 @@ package cli -import ( - "syscall" - "time" -) +import "github.com/intentdriven/abcd/internal/testtiming" -// processCPU is the CPU time this test process has consumed, user and system, -// across every thread — internal/core/reading's linearity clock, kept here for -// this package's own guards. Its one caller, scanGrowth, compares two of its -// readings in one run, a read of an input and of one four times larger, rather -// than bounding either: time spent waiting for a core is not charged, but a -// slower core is, and it slows both readings alike (iss-2609240046582859, -// iss-2611121820123919). No test in this package runs in parallel, so the -// figure is the measured call's, plus the runtime's own collector. -func processCPU() time.Duration { - var ru syscall.Rusage - if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { - panic("getrusage: " + err.Error()) - } - return time.Duration(ru.Utime.Nano() + ru.Stime.Nano()) -} +// processCPU is the CPU time this test process has consumed, testtiming.CPU. +// Its one caller, scanGrowth, compares two of its readings in one run, a read +// of an input and of one four times larger, rather than bounding either: time +// spent waiting for a core is not charged, but a slower core is, and it slows +// both readings alike (iss-2609240046582859, iss-2611121820123919). No test in +// this package runs in parallel, so the figure is the measured call's, plus the +// runtime's own collector. +var processCPU = testtiming.CPU diff --git a/internal/testtiming/testtiming.go b/internal/testtiming/testtiming.go new file mode 100644 index 0000000000..cabb9de321 --- /dev/null +++ b/internal/testtiming/testtiming.go @@ -0,0 +1,78 @@ +// Package testtiming is the one way a test judges how long something took +// (iss-2612022218392055). A hosted runner can be several times slower than the +// machine a bound was written on, and slower again under the race detector, so +// a test that holds a run to a fixed time fails there on code with nothing +// wrong: over sixty days of CI, half the failing runs were a wall-clock bound +// or a fixed budget running out. A test judges time by a Bound instead, in one +// of two ways: +// +// - against a reference measured in the same run, on the same machine at the +// same moment, so a slow runner slows both alike: a cost against the cost +// of a smaller input, by the ratio of the sizes, or a refusal that must come +// at once against one pass over its input; +// - against the alternative a run must cut short (CutShort): a call that a +// context or a kill ends comes back well inside the time the work it ended +// would have taken, so the test makes that work long and judges the call by +// a fraction of it, never by a constant just above the context. +// +// A Bound is never under its Floor, so a scheduler or collector pause cannot +// fail a run whose reference was a few milliseconds. CPU is the clock for a +// cost: it does not charge the time a loaded machine keeps the process off a +// core. A test that waits for another goroutine or process to reach a point +// waits for a sign that it did, never for a fixed sleep, and a fake clock is +// the only clock a fixture built on it reads. +package testtiming + +import ( + "fmt" + "syscall" + "time" +) + +// Bound is the most a measured run may take: Ratio times a reference measured +// in the same run, and never less than Floor. +type Bound struct { + // Ratio is how many times the reference the run may take. + Ratio float64 + // Floor is the least the bound is, whatever the reference. + Floor time.Duration +} + +// CutShort judges a run that must cut short an alternative, the work a +// context, a deadline or a kill ends: it comes back in under half the time +// the alternative takes. A slow runner adds to the run what it adds to +// starting and stopping a process, seconds at most, so the alternative is made +// long enough that half of it is far past that, and the run is still told from +// one that waited the alternative out. +var CutShort = Bound{Ratio: 0.5} + +// Limit is the most a run judged against reference may take. +func (b Bound) Limit(reference time.Duration) time.Duration { + return max(time.Duration(b.Ratio*float64(reference)), b.Floor) +} + +// Check is nil when took is within b's limit for reference, and otherwise an +// error naming what was measured, the reference, the ratio and the floor. +func (b Bound) Check(what string, took, reference time.Duration) error { + if limit := b.Limit(reference); took > limit { + return fmt.Errorf("%s took %v, over its bound of %v (%g times the reference of %v, and never under %v)", + what, took, limit, b.Ratio, reference, b.Floor) + } + return nil +} + +// CPU is the CPU time this process has used, user and system, across every +// thread, the collector's work included. It counts the work a run does and not +// the time it waits for a core, so a cost read off it on a loaded machine reads +// as on an idle one (iss-2609240046582859); a slower core still slows it, which +// is why a cost is judged against a reference rather than a constant. It is +// the process's clock, not one thread's: Linux reads a thread's time without +// the slice it is running, so a run shorter than a scheduler tick could read as +// nothing. getrusage is the call on the macOS and Linux the tests run on. +func CPU() time.Duration { + var ru syscall.Rusage + if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { + panic("getrusage: " + err.Error()) + } + return time.Duration(ru.Utime.Nano() + ru.Stime.Nano()) +} diff --git a/internal/testtiming/testtiming_test.go b/internal/testtiming/testtiming_test.go new file mode 100644 index 0000000000..a38d43b15c --- /dev/null +++ b/internal/testtiming/testtiming_test.go @@ -0,0 +1,73 @@ +package testtiming + +import ( + "strings" + "testing" + "time" +) + +// TestALimitIsTheRatioOfTheReferenceAndNeverUnderTheFloor: the limit follows +// the reference by the ratio, so a runner that slows the reference slows the +// limit alike, and a reference of a few microseconds still leaves the floor. +func TestALimitIsTheRatioOfTheReferenceAndNeverUnderTheFloor(t *testing.T) { + b := Bound{Ratio: 20, Floor: 500 * time.Millisecond} + for _, c := range []struct{ reference, want time.Duration }{ + {time.Microsecond, 500 * time.Millisecond}, + {25 * time.Millisecond, 500 * time.Millisecond}, + {100 * time.Millisecond, 2 * time.Second}, + {3 * time.Second, time.Minute}, + } { + if got := b.Limit(c.reference); got != c.want { + t.Errorf("the limit for a reference of %v is %v, want %v", c.reference, got, c.want) + } + } + if got := CutShort.Limit(time.Minute); got != 30*time.Second { + t.Errorf("a run cutting a minute's work short may take %v, want half of it", got) + } +} + +// TestACheckPassesWithinTheLimitAndNamesEveryFigureOverIt: a run at its limit +// passes; one over it is refused with what it took, the limit, the ratio, the +// reference and the floor, so a failure on a slow runner says how slow. +func TestACheckPassesWithinTheLimitAndNamesEveryFigureOverIt(t *testing.T) { + b := Bound{Ratio: 4, Floor: time.Second} + if err := b.Check("the scan", 2*time.Second, 500*time.Millisecond); err != nil { + t.Errorf("a run at its limit: %v", err) + } + err := b.Check("the scan", 3*time.Second, 500*time.Millisecond) + if err == nil { + t.Fatal("a run over its limit passed") + } + for _, want := range []string{"the scan took 3s", "bound of 2s", "4 times the reference of 500ms", "never under 1s"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("the refusal %q does not say %q", err, want) + } + } +} + +// TestCPUDoesNotChargeWaiting: the clock a cost is read off charges work, not +// waiting. A wall-clock ceiling charged the time a loaded machine kept a scan +// off a core, so a gate run could fail on linear code with nothing wrong +// (iss-2609240046582859); a sleep stands in for that wait here, and the clock +// must not see it. +func TestCPUDoesNotChargeWaiting(t *testing.T) { + start := CPU() + time.Sleep(300 * time.Millisecond) + if spent := CPU() - start; spent > 100*time.Millisecond { + t.Fatalf("the clock charged %s across a 300ms wait; it counts time off the core, which load inflates", spent) + } + + // And it charges work, or every bound read off it would pass a quadratic scan. + start = CPU() + deadline := time.Now().Add(30 * time.Second) + sink := 0 + for CPU()-start < 50*time.Millisecond { + if time.Now().After(deadline) { + t.Fatalf("30s of spinning charged %s; the clock does not count work", CPU()-start) + } + for i := range 100000 { + sink += i + } + } + _ = sink +} From f3187b4a04c2dbdbb564507be496fcf3b927b1fa Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:58:33 +0000 Subject: [PATCH 02/11] test: age a kept fixture world from its build, and bound Live.Since by its read The loop flake fixed on loopflake-1202 (4dd8a7e7d) was a stand-in clock that moved with the real one. The census of iss-2612022218392055 names two sibling sites of that shape, and each is fixed here. fixtureworld_test.go:254 set a kept world's clock in keep(), after its build had run, and line 97 reuses the world while time.Since of that clock is under keptWorldAge. Every time a world's files hold is written during the build, on the real clock, so a build a slow runner took minutes over was aged from its end and reused for those minutes past keptWorldAge, its run's clock that much older than the age read. The clock now starts before the world's first walk, the earliest moment any of its files can hold; line 97 needs nothing more once the clock is right. TestAKeptWorldIsAgedFromWhenItsBuildBegan holds it. livework_test.go:129 held Live.Since within three seconds of the process's start. The reader dates the table from just before it asks and the table ages the process to the moment it is read, so the start it gives is early by up to the reading's own length: a table read that a loaded runner kept for over three seconds failed. The bound is now that reading's measured length (testtiming.Bound, ratio 1, floor 1s), and a late start still fails. Line 88 (Age: time.Since(p.start)) cannot misfire: p.start is fixed, and the age is taken at the read, inside the window the bound already allows for. Red before green, through the narrow load gate, with throwaway copies of the new test bodies on a copy of the tree before this change: the kept world test failed on the old fixture ("the world is aged from ..., 21.549167ms after its build began"); with a process table a loaded runner kept for 3.5s, the old Live.Since bound failed ("Live.Since = 23:25:58.497966, want about 23:26:02") and the new one passed. Green, through the narrow load gate: TestAKeptWorldIsAgedFromWhenItsBuildBegan, TestASecondWorldInOneTestIsBuiltApart and TestLiveWholeRunMarksTheItem pass, and so does the new Live.Since bound against the 3.5s table read. Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- internal/core/autonomy/livework_test.go | 13 +++++-- .../core/implement/loop/fixtureworld_test.go | 34 +++++++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/internal/core/autonomy/livework_test.go b/internal/core/autonomy/livework_test.go index 220553b198..6ce5b45a95 100644 --- a/internal/core/autonomy/livework_test.go +++ b/internal/core/autonomy/livework_test.go @@ -14,6 +14,7 @@ import ( "github.com/intentdriven/abcd/internal/abcdhome" "github.com/intentdriven/abcd/internal/core/implement" "github.com/intentdriven/abcd/internal/core/machineload" + "github.com/intentdriven/abcd/internal/testtiming" ) // livework_test.go: the owed reading marks a capped item with the live work @@ -118,7 +119,9 @@ func TestLiveWholeRunMarksTheItem(t *testing.T) { start := time.Now().Add(-30 * time.Minute).Truncate(time.Second) f.plantMarker(livePID, start, f.root) tb := &table{procs: map[int]tableProc{livePID: {me(), "abcd", start}}} + before := time.Now() it := liveItem(t, f.readLive(tb)) + reading := time.Since(before) if it.Live == nil { t.Fatal("a whole run live for the item's head did not mark it") } @@ -126,8 +129,14 @@ func TestLiveWholeRunMarksTheItem(t *testing.T) { !strings.Contains(it.Live.What, "commit its stages test is not known") { t.Errorf("Live.What = %q, want the process and the commit it was queued or started at named, and the stages' commit said unknown", it.Live.What) } - if d := it.Live.Since.Sub(start); d < -3*time.Second || d > 3*time.Second { - t.Errorf("Live.Since = %s, want about %s, the process's start", it.Live.Since, start) + // The table ages the process to the moment it is read, inside the + // reading, while the reader dates the table from just before it asked: + // the start it gives is early by the time between the two, which the + // reading's own length bounds however slow the runner, and never late. A + // second either way is the wall clock's own adjustments. + early := it.Live.Since.Sub(start) + if err := (testtiming.Bound{Ratio: 1, Floor: time.Second}).Check("how early Live.Since is", -early, reading); err != nil || early > time.Second { + t.Errorf("Live.Since = %s, want %s, the process's start, or earlier by at most the reading's %s: %v", it.Live.Since, start, reading, err) } if tb.reads != 1 { t.Errorf("the process table was read %d times, want once", tb.reads) diff --git a/internal/core/implement/loop/fixtureworld_test.go b/internal/core/implement/loop/fixtureworld_test.go index fec39569cb..e137f2d1f9 100644 --- a/internal/core/implement/loop/fixtureworld_test.go +++ b/internal/core/implement/loop/fixtureworld_test.go @@ -103,6 +103,14 @@ func walkedOnce[T any](t *testing.T, w *fixtureWorld, name string, walk func() T outer := fw.building fw.building = w defer func() { fw.building = outer }() + if w.made.IsZero() { + // The world's clock starts with its first walk, which writes the + // first time any file in it holds, so its age is counted from + // before that walk and never from when the walk ended: a walk a + // slow runner took minutes over would be that much older than its + // age read, and kept past keptWorldAge. + w.made = time.Now() + } v := walk() if w.at != "" { w.keep(t, key, v) @@ -250,9 +258,6 @@ func (w *fixtureWorld) keep(t *testing.T, key string, value any) { if fw.kept == nil { fw.kept = map[string]*keptWorld{} } - if w.made.IsZero() { - w.made = time.Now() - } fw.kept[key] = &keptWorld{dir: dir, value: value, made: w.made, generation: fw.made} w.lineage = worldKey(key, strconv.Itoa(fw.made)) } @@ -439,3 +444,26 @@ func TestASecondWorldInOneTestIsBuiltApart(t *testing.T) { t.Fatal("the first world's repository is gone") } } + +// TestAKeptWorldIsAgedFromWhenItsBuildBegan: a kept world's age is counted +// from before its build ran, the earliest moment any file in it can hold, and +// not from when the build ended. A world's run is started on the real clock +// inside the build, so a build a slow runner took minutes over, aged from its +// end, would be copied for minutes past keptWorldAge with its run's clock that +// much older than the age read: the shape of a stand-in clock that moves with +// the real one (iss-2612022218392055). +func TestAKeptWorldIsAgedFromWhenItsBuildBegan(t *testing.T) { + key := fmt.Sprintf("%s-%d", t.Name(), time.Now().UnixNano()) + var began time.Time + _, w := builtOnce(t, key, func(w *fixtureWorld) bool { + began = time.Now() + time.Sleep(20 * time.Millisecond) // the build's own time, which the age must not leave out + return true + }) + if began.IsZero() { + t.Fatal("premise: the world was built, not copied") + } + if w.made.After(began) { + t.Fatalf("the world is aged from %s, %s after its build began", w.made.Format(time.RFC3339Nano), w.made.Sub(began)) + } +} From 9ac3822b25d0f4d084638a55eafa613637411a17 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:58:36 +0000 Subject: [PATCH 03/11] test: wait for a sign, not a fixed budget, in the census's flaky tests The census of iss-2612022218392055 confirms seven flaky tests. Their causes, read from each failing run's log and the commits since: - TestHostAndGuestOverTheWire: the guest joined before the host's update was logged, a race in the test; fixed by 632b07f87, after the failing 336cb674e. - TestARejoinDuringASlowReplayStaysBounded: a closed connection lived about 5s past its close grace, a production defect; fixed by 556a7c914, after the failing 49dd579aa. - TestAFourthRemovalAtOneHeadIsHandedBackAfterThreeArmings: a check for "1111" matched inside a commit hash (31111f...); fixed by 926eeb265. - TestVulncheckInterruptedLeavesNoCopyBehind: the signal raced the stub's fork (fixed by 2eab9c2b6), then a second HUP during cleanup, a production defect (fixed by 157741d77 and 758cd72b0); no failure since. - TestAGarbledClockNeverCostsTheReceipt: a real-clock hourAgo mixed with fixture times; fixed by 28c952a42. - TestALeaderStopsItsGroupWhenTheRunnerGoes: the pid file existed before the pid was in it, so a stop in that gap read pid 0; bb468eda3 made the test wait for the pid. Its sibling TestTheWholeRunsVerdictEndsTheAudits has the same gap and was still open to it. - TestAReservationRenewsDuringAPreflight: still open. It waited 5s of wall time for a renewal pass that fetches and pushes; on a loaded runner the pass took longer. TestAReservationRenewsDuringACall gave the same pass a call 1s long. Both production defects were fixed and recorded before this change; none of the seven needs a new capture. The five already fixed are fixed on this head and were not rerun. The fixes here: - testtiming.Patience is how long a test waits for work elsewhere: three quarters of the time the test binary has left, not a constant, and testtiming.Await asks for a sign for that long. AwaitWithin is the same wait for at most a limit, for a sign a fault would also give later: a process killed with its group is gone, but so is one that escaped once its own minute runs out, so that wait is bounded by half that minute, not by a Patience that could outlast it. interview's budget(t) is now Patience, the copy it held. - terminal_renew_test.go: the preflight test waits for the renewal to be recorded (Await) inside the preflight, and the call test's agent takes a new turn, untilrenewed, that stays in its call until the test marks the renewal recorded and says it saw it, at most 15s inside the runner's 20s bound, so the call lasts as long as the renewal takes rather than a second. The renewal is made only while a call runs, so the wait has to be the agent's, not the stage's before it calls. - precheck-audits: sh writes the pid beside the file and renames it on, so the file exists only with the whole pid in it, which closes the gap for every test that uses sh; waitForFile, waitForPid and the interrupt's wait use Await; the leader test's last wait uses AwaitWithin half the run's minute. Red before green, with each old body and its new one in throwaway tests run through the narrow load gate on a copy of the tree before this change: with every renewal slowed by 6s, as a fetch and a push on a loaded runner, the old preflight test failed ("the reservation was not renewed while the preflight ran"); the old call test's poll, about five seconds of reads, happened to outlast that 6s here and passed, so its change rests on the same shape, not on a reproduction. With half a second between the pid file's creation and its pid, the old way sh wrote it failed the whole run's verdict test (strconv.Atoi: parsing "") and the new way passed. Green, through the narrow load gate: both renewal tests pass (6.9s and 7.9s), and so do the same tests with every renewal slowed by 6s (12.5s and 13.3s); testtiming's tests and interview's two budget tests pass. cmd/precheck-audits, the leader and verdict tests among it, passes whole under make precheck. Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- cmd/precheck-audits/main_test.go | 60 ++++++-------- internal/README.md | 6 +- .../implement/loop/terminal_renew_test.go | 83 +++++++++++-------- internal/core/implement/loop/terminal_test.go | 14 ++++ internal/core/interview/budget_test.go | 14 +--- internal/testtiming/testtiming.go | 55 +++++++++++- internal/testtiming/testtiming_test.go | 47 +++++++++++ 7 files changed, 197 insertions(+), 82 deletions(-) diff --git a/cmd/precheck-audits/main_test.go b/cmd/precheck-audits/main_test.go index 6e5c7dbbec..33303ffdbd 100644 --- a/cmd/precheck-audits/main_test.go +++ b/cmd/precheck-audits/main_test.go @@ -18,6 +18,7 @@ import ( "github.com/intentdriven/abcd/internal/core/machineload" "github.com/intentdriven/abcd/internal/procgroup" + "github.com/intentdriven/abcd/internal/testtiming" ) // TestMain lets the test binary lead a run's group as the command's binary @@ -402,10 +403,15 @@ func (m *markOnLine) Write(p []byte) (int, error) { } // sh is a command running script in sh, after writing its pid to pidFile when -// one is named, so a test can prove it was stopped. +// one is named, so a test can prove it was stopped. The pid is written beside +// pidFile and renamed onto it, so pidFile exists only once it holds the whole +// pid: a shell creates a file before it writes to it, and a group stopped in +// that gap, by a command that went ahead on the file's being there, left an +// empty file that read as pid 0 (TestALeaderStopsItsGroupWhenTheRunnerGoes's +// failure, which TestTheWholeRunsVerdictEndsTheAudits shared). func sh(script, pidFile string) []string { if pidFile != "" { - script = "echo $$ > '" + pidFile + "'; " + script + script = "echo $$ > '" + pidFile + ".part' && mv '" + pidFile + ".part' '" + pidFile + "'; " + script } return []string{"sh", "-c", script} } @@ -435,24 +441,17 @@ func gone(t *testing.T, pidFile string) { // waitForFile waits until path exists, so a stop is tested on a started process. func waitForFile(t *testing.T, path string) { t.Helper() - for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { - if _, err := os.Stat(path); err == nil { - return - } + if !testtiming.Await(t, 20*time.Millisecond, func() bool { _, err := os.Stat(path); return err == nil }) { + t.Fatalf("%s was never written", path) } - t.Fatalf("%s was never written", path) } -// waitForPid waits for pidFile to hold a whole pid, which sh writes after it -// creates the file. +// waitForPid waits for pidFile to hold a whole pid. func waitForPid(t *testing.T, pidFile string) { t.Helper() - for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { - if wrotePid(pidFile) { - return - } + if !testtiming.Await(t, 20*time.Millisecond, func() bool { return wrotePid(pidFile) }) { + t.Fatalf("no pid was written to %s", pidFile) } - t.Fatalf("no pid was written to %s", pidFile) } func noGoFlags([]string) (string, error) { return "", nil } @@ -554,14 +553,9 @@ func TestAnInterruptStopsEverything(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) go func() { defer cancel() - // The shell creates each file before it writes the pid into it, so - // the interrupt waits for the pid itself: one sent between the two - // left gone an empty file to read. - for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { - if wrotePid(commandPid) && wrotePid(auditPid) { - return - } - } + // The interrupt waits for both pids: one sent before them left gone + // nothing to read. + testtiming.Await(t, 20*time.Millisecond, func() bool { return wrotePid(commandPid) && wrotePid(auditPid) }) }() var out lockedBuffer code := beside(ctx, []auditRun{{packages: []string{"./a"}}}, sh("exec sleep 60", commandPid), &out, &out, @@ -608,18 +602,16 @@ func TestALeaderStopsItsGroupWhenTheRunnerGoes(t *testing.T) { procgroup.Kill(cmd) t.Fatal("the leader outlived its runner") } - for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) { - raw, _ := os.ReadFile(pidFile) - pid, _ := strconv.Atoi(strings.TrimSpace(string(raw))) - if pid <= 0 { - t.Fatalf("%s holds no pid: %q", pidFile, raw) - } - if err := syscall.Kill(pid, 0); errors.Is(err, syscall.ESRCH) { - return - } - if time.Now().After(deadline) { - t.Fatalf("the run (pid %d) outlived its leader", pid) - } + raw, _ := os.ReadFile(pidFile) + pid, _ := strconv.Atoi(strings.TrimSpace(string(raw))) + if pid <= 0 { + t.Fatalf("%s holds no pid: %q", pidFile, raw) + } + // Killed with its group, the run is gone once whoever adopted it reaps it; + // one the leader left lives its whole minute, so it is given half that. + ended := func() bool { return errors.Is(syscall.Kill(pid, 0), syscall.ESRCH) } + if !testtiming.AwaitWithin(testtiming.CutShort.Limit(time.Minute), 20*time.Millisecond, ended) { + t.Fatalf("the run (pid %d) outlived its leader", pid) } } diff --git a/internal/README.md b/internal/README.md index 93a98b0dd4..95f5cf5980 100644 --- a/internal/README.md +++ b/internal/README.md @@ -492,7 +492,11 @@ plugin surface, and a future MCP server share one engine. reference measured in the same run, never under a floor, so a slow or loaded runner slows both alike; `CutShort` judges a run a context or a kill ends against the work it ended; `CPU` is the process's CPU clock a cost is - read off. Imported only by tests; a standard-library leaf. + read off; `Await` waits for a sign that work elsewhere reached a point, for + as long as `Patience` allows, a share of the time the test binary has left, + never a fixed sleep, and `AwaitWithin` for a sign a fault would also give + later, within a share of that fault's time. Imported only by tests; a + standard-library leaf. - **`surface/cli/`** — the default front door: a Cobra command tree that calls `core` and formats results as text or `--json`. Holds no business logic. - **`surface/cli/ask/`** — the drawing of a question in a plain Terminal diff --git a/internal/core/implement/loop/terminal_renew_test.go b/internal/core/implement/loop/terminal_renew_test.go index 6d5fc8d892..9f033e515b 100644 --- a/internal/core/implement/loop/terminal_renew_test.go +++ b/internal/core/implement/loop/terminal_renew_test.go @@ -4,10 +4,13 @@ package loop import ( "context" + "os" "strings" "sync/atomic" "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // TestAReservationRenewsDuringACall: an agent's call outlasting half the lease @@ -16,7 +19,15 @@ func TestAReservationRenewsDuringACall(t *testing.T) { was := terminalRenewTick terminalRenewTick = 20 * time.Millisecond t.Cleanup(func() { terminalRenewTick = was }) - w := newTerminalWorld(t, "shape", "slow") + // The agent stays in its call until the run records a renewal (the + // untilrenewed turn), so the renewal is made while it is there however + // long a fetch and a push take on the runner, where a call of a fixed + // second could end first on a slow one, the shape that failed the + // preflight test below (iss-2612022218392055). + w := newTerminalWorld(t, "shape", "untilrenewed") + renewed := os.Getenv(terminalScriptEnv) + ".renewed" + stop := make(chan struct{}) + t.Cleanup(func() { close(stop) }) var at atomic.Int64 at.Store(time.Now().UTC().UnixNano()) o := w.options(t) @@ -27,40 +38,46 @@ func TestAReservationRenewsDuringACall(t *testing.T) { run := w.stages[i].Run w.stages[i].Run = func(c Context, l *Lane) (Outcome, error) { at.Add(int64(90 * time.Minute)) - return run(c, l) - } - } - } - during := make(chan bool, 1) - go func() { - for range 1000 { - st, _, err := readDrain(w.repo.Root()) - if err == nil && len(st.Lanes) > 0 { - if run, err := ReadState(w.repo.Root(), st.Lanes[0].RunID); err == nil { - for _, e := range run.Record { - if e.Stage == StageReservationRenewed { - during <- len(run.Lanes[0].Receipts) == 0 - return + go func() { + seen := testtiming.Await(t, 5*time.Millisecond, func() bool { + select { + case <-stop: + return true + default: + return renewalRecorded(c.RepoRoot, c.State.RunID) } + }) + if seen { + _ = os.WriteFile(renewed, nil, 0o600) } - if len(run.Lanes[0].Receipts) > 0 { - during <- false - return - } - } + }() + return run(c, l) } - time.Sleep(5 * time.Millisecond) } - during <- false - }() + } if _, err := RunTerminal(context.Background(), w.repo.Root(), o); err != nil { t.Fatalf("%v\n%s", err, strings.Join(w.lines, "\n")) } - if !<-during { - t.Fatal("the reservation was not renewed while the agent was in its call") + if _, err := os.Stat(renewed + ".seen"); err != nil { + t.Fatalf("the reservation was not renewed while the agent was in its call:\n%s", strings.Join(w.lines, "\n")) } } +// renewalRecorded reports whether runID's record holds a renewal of what its +// lanes hold. +func renewalRecorded(root, runID string) bool { + run, err := ReadState(root, runID) + if err != nil { + return false + } + for _, e := range run.Record { + if e.Stage == StageReservationRenewed { + return true + } + } + return false +} + // TestAReservationRenewsDuringAPreflight: a preflight queued or running past half // the lease renews what the lane holds too. func TestAReservationRenewsDuringAPreflight(t *testing.T) { @@ -83,21 +100,17 @@ func TestAReservationRenewsDuringAPreflight(t *testing.T) { t.Errorf("no drain: %v", err) return inner(ctx, wt, head) } - for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline) && !renewed; time.Sleep(20 * time.Millisecond) { - run, err := ReadState(w.repo.Root(), st.Lanes[0].RunID) - if err != nil { - continue - } - for _, e := range run.Record { - renewed = renewed || e.Stage == StageReservationRenewed - } - } + // A renewal is a fetch and a push, which a loaded runner once took + // past a five-second wait to make while this stand-in waited + // (iss-2612022218392055): it waits for the run's record of one as + // long as the test can. + renewed = testtiming.Await(t, 20*time.Millisecond, func() bool { return renewalRecorded(w.repo.Root(), st.Lanes[0].RunID) }) return inner(ctx, wt, head) } if _, err := RunTerminal(context.Background(), w.repo.Root(), o); err != nil { t.Fatalf("%v\n%s", err, strings.Join(w.lines, "\n")) } if !renewed { - t.Fatal("the reservation was not renewed while the preflight ran") + t.Fatalf("the reservation was not renewed while the preflight ran:\n%s", strings.Join(w.lines, "\n")) } } diff --git a/internal/core/implement/loop/terminal_test.go b/internal/core/implement/loop/terminal_test.go index cc67bd4fbf..08d5ef2742 100644 --- a/internal/core/implement/loop/terminal_test.go +++ b/internal/core/implement/loop/terminal_test.go @@ -101,6 +101,20 @@ func terminalFakeTurn(role string) string { return "leaveopen" case "slow": time.Sleep(time.Second) + case "untilrenewed": + // The agent stays in its call until the test marks a renewal of + // what the lane holds, and says it saw one: a call of a fixed + // second could end before a renewal's fetch and push on a slow + // runner (iss-2612022218392055). It waits at most 15s, inside the + // runner's 20s bound, so a renewal that never comes ends the call + // unseen rather than killed. + mark := os.Getenv(terminalScriptEnv) + ".renewed" + for until := time.Now().Add(15 * time.Second); time.Now().Before(until); time.Sleep(10 * time.Millisecond) { + if _, err := os.Stat(mark); err == nil { + _ = os.WriteFile(mark+".seen", nil, 0o600) + break + } + } case "incall": // The agent in its call, as a check beside it could see. mark := os.Getenv(terminalScriptEnv) + ".in-call" diff --git a/internal/core/interview/budget_test.go b/internal/core/interview/budget_test.go index 18ceb9ed4c..d575bc076c 100644 --- a/internal/core/interview/budget_test.go +++ b/internal/core/interview/budget_test.go @@ -3,6 +3,8 @@ package interview import ( "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // budget is how long a test of this package waits for work an idle machine @@ -13,20 +15,12 @@ import ( // it, and a wait that runs out still fails the test with its own message // before the binary's timeout panic, with a quarter left to report and clean // up (iss-2610102020447522). A fixed budget was overrun at load averages of -// 31 to 57 on 16 cores. With no deadline (-timeout 0) it is noDeadlineBudget. +// 31 to 57 on 16 cores. It is testtiming.Patience, the one such wait. func budget(t *testing.T) time.Duration { t.Helper() - dl, ok := t.Deadline() - if !ok { - return noDeadlineBudget - } - return time.Until(dl) * 3 / 4 + return testtiming.Patience(t) } -// noDeadlineBudget is budget for a run given no deadline: long enough for any -// loaded runner, and a bound on a hang all the same. -const noDeadlineBudget = 10 * time.Minute - // TestEveryWaitEndsBeforeTheTestDeadline: no wait waits names runs past the // deadline the test binary was given, so a wait that does run out fails the // test with its own message rather than the binary's timeout panic. diff --git a/internal/testtiming/testtiming.go b/internal/testtiming/testtiming.go index cabb9de321..d12b06bd8e 100644 --- a/internal/testtiming/testtiming.go +++ b/internal/testtiming/testtiming.go @@ -19,13 +19,16 @@ // fail a run whose reference was a few milliseconds. CPU is the clock for a // cost: it does not charge the time a loaded machine keeps the process off a // core. A test that waits for another goroutine or process to reach a point -// waits for a sign that it did, never for a fixed sleep, and a fake clock is -// the only clock a fixture built on it reads. +// waits for a sign that it did, never for a fixed sleep: Await asks for the +// sign for as long as Patience allows, a share of the time the test binary has +// left rather than a constant. A fake clock is the only clock a fixture built +// on it reads. package testtiming import ( "fmt" "syscall" + "testing" "time" ) @@ -61,6 +64,54 @@ func (b Bound) Check(what string, took, reference time.Duration) error { return nil } +// Patience is how long a test waits for something an idle machine does in a +// second or two, another goroutine's or process's work it has no sign of but +// what that work leaves behind: three quarters of the time the test binary has +// left (t.Deadline), so a loaded runner, given the longer deadline a slow run +// is given, slows the test without failing it, and a wait that runs out still +// fails the test with its own message before the binary's timeout panic, with +// a quarter left to report and clean up (iss-2610102020447522). A fixed wait of +// five seconds ran out on a hosted runner while the work it waited for was +// still going (iss-2612022218392055). With no deadline (-timeout 0) it is +// NoDeadlinePatience. +func Patience(t *testing.T) time.Duration { + t.Helper() + dl, ok := t.Deadline() + if !ok { + return NoDeadlinePatience + } + return time.Until(dl) * 3 / 4 +} + +// NoDeadlinePatience is Patience for a run given no deadline: long enough for +// any loaded runner, and a bound on a hang all the same. +const NoDeadlinePatience = 10 * time.Minute + +// Await asks done every poll until it reports true, for at most Patience, and +// reports whether it did. It is the wait for a sign that work elsewhere has +// reached a point, never a sleep the work is assumed to finish within; the +// caller fails with what it was waiting for. +func Await(t *testing.T, poll time.Duration, done func() bool) bool { + t.Helper() + return AwaitWithin(Patience(t), poll, done) +} + +// AwaitWithin is Await for at most limit, for a sign that the work it waits +// for would also give, later, were it wrong: a process killed with its group +// is gone, as one that escaped the kill is once its own minute runs out. Such +// a wait is bounded by the alternative (CutShort.Limit of it), never by +// Patience, which could outlast it and pass the escape. +func AwaitWithin(limit, poll time.Duration, done func() bool) bool { + for deadline := time.Now().Add(limit); ; time.Sleep(poll) { + if done() { + return true + } + if time.Now().After(deadline) { + return false + } + } +} + // CPU is the CPU time this process has used, user and system, across every // thread, the collector's work included. It counts the work a run does and not // the time it waits for a core, so a cost read off it on a loaded machine reads diff --git a/internal/testtiming/testtiming_test.go b/internal/testtiming/testtiming_test.go index a38d43b15c..56096ea4d6 100644 --- a/internal/testtiming/testtiming_test.go +++ b/internal/testtiming/testtiming_test.go @@ -45,6 +45,53 @@ func TestACheckPassesWithinTheLimitAndNamesEveryFigureOverIt(t *testing.T) { } } +// TestPatienceEndsBeforeTheDeadlineAndGrowsWithIt: a wait ends before the +// binary's own deadline, so it fails with its own message, and is at least +// half the time left, so a slow run's longer deadline lengthens it. +func TestPatienceEndsBeforeTheDeadlineAndGrowsWithIt(t *testing.T) { + dl, ok := t.Deadline() + if !ok { + if got := Patience(t); got != NoDeadlinePatience { + t.Fatalf("with no deadline the wait is %v, want %v", got, NoDeadlinePatience) + } + return + } + got := Patience(t) + if end := time.Now().Add(got); !end.Before(dl) { + t.Errorf("a wait of %v ends %v past the deadline", got, end.Sub(dl)) + } + if left := time.Until(dl); got < left/2 { + t.Errorf("a wait of %v with %v left; want at least half", got, left) + } +} + +// TestAwaitReturnsOnTheSignAndAsksUntilIt: Await returns as soon as the sign +// shows, however many asks that takes, and asks no more after it. +func TestAwaitReturnsOnTheSignAndAsksUntilIt(t *testing.T) { + asks := 0 + if !Await(t, time.Millisecond, func() bool { asks++; return asks == 3 }) { + t.Fatal("Await gave up on a sign that showed") + } + if asks != 3 { + t.Errorf("Await asked %d times, want 3: it stops at the sign", asks) + } +} + +// TestAwaitWithinGivesUpAtItsLimit: a sign that never shows is given up on +// once the limit has passed, and not before, so a wait bounded by the +// alternative a fault would also end in fails rather than outlasting it. +func TestAwaitWithinGivesUpAtItsLimit(t *testing.T) { + const limit = 50 * time.Millisecond + start := time.Now() + if AwaitWithin(limit, time.Millisecond, func() bool { return false }) { + t.Fatal("AwaitWithin reported a sign that never showed") + } + // A lower bound: a slow runner only lengthens the wait. + if took := time.Since(start); took < limit { + t.Errorf("AwaitWithin gave up after %v, before its limit of %v", took, limit) + } +} + // TestCPUDoesNotChargeWaiting: the clock a cost is read off charges work, not // waiting. A wall-clock ceiling charged the time a loaded machine kept a scan // off a core, so a gate run could fail on linear code with nothing wrong From 024ddffdadd7f1a0d4f0ecd3181087021230c7f0 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:58:39 +0000 Subject: [PATCH 04/11] test: judge the census's ten worst timing bounds by what they cut short The flake census of iss-2612022218392055 ranks the tests most likely to fail on a slow runner. Each of its top ten is moved onto testtiming here, so a slow or loaded runner slows the test without failing it, and a fault still fails it: 1 testreuse run_test.go: the seven 1500ms sleeps before releasing a lock the second check must already be waiting on now wait for the check's own "waiting for another check" line (the shape clock_test.go took in 3076812c6), for as long as testtiming.Patience allows. 2 runner gatewait_test.go: the gate now waits past the run's bound (4s against 3s), so a run charged for its wait is killed however fast the runner, and the work ends once the gate opens (a file a timer writes at the opening, since the run stops asking the gate once its credit is spent), with two seconds of bound and credit left, instead of sleeping 0.7s against a 1s bound with 0.3s to spare; the gate credit is judged against a reference run's kill time, by the ratio LongestRun allows, not against a constant. 3 loop widen_paths_test.go: the refusal of 200,000 paths is judged against a pass over a tenth of them, and so is the dedup, measured in the same run, not against 2s and 4s. 4 claim: status_test.go's origin hangs a minute and the prompt is judged by CutShort of that; generated_match_test.go and generated_test.go read their slack bounds off the process CPU clock, which load does not inflate. 5 github scheduled_test.go: the origin is made before the 200ms context starts, and the hung stub runs a minute, judged by CutShort. 6 sessionname register_test.go: naming under a held lock is judged against a clean start timed in the same run (ratio 2, floor 1s). 7 gitutil: every hung stub git runs a minute (gitHang) and each read a context ends is judged by CutShort of it, not 2 to 3s; the 300ms sleep before asking whether prepare-commit-msg's program survived the stop is a wait for it to go, for half that program's minute (AwaitWithin). 8 cli: the stuck augmenter, the stalled stdin, the git that does not answer and the stuck renewal each end after a minute, and each hook or waiter is judged by CutShort of that, where 5 to 10s left a slow runner a few seconds to start and end the command in. 9 gitleaks augmenter_context_test.go: the context ends once the run has started (the runner closes a channel on entry), not on a 100ms timer a slow runner could spend before the run began; 9a5bfd431's fix for the scanner's own test. 10 matrix: the 4s bound under a 5s deadline is CutShort of a 20s deadline; the leader and FIFO runs are judged by CutShort of their deadlines; the compliance checks' FIFO is answered after a minute and judged by CutShort of that, not 20 and 30s. gittest.AnswerPipeAfter gives a FIFO git configuration that finite alternative: it opens the pipe for writing, without blocking, after the given time, so a git still reading it goes on, and a git the bound stopped leaves nothing to answer. Every change turns a bound a slow runner could fail into one only a fault fails. No reproduction was possible: none of the old bounds fails on demand, and a starved run long enough to try each would have added to a machine already at three to five times its cores' load, so none was run. The audit in the next commit, run on a copy of the tree before the census's fixes (3436e16b4), names exactly the 22 bounds this commit and the two before it moved. Green, through the narrow load gate, each changed test by name: cli (5), testreuse (5), runner (3), matrix (5), gitutil (7), claim (3), github (2), gitleaks (1), sessionname (1), gittest (1) and loop's widening (1) pass. The gate wait test's first version failed there at 6s: it opened the gate only when next asked, which a run whose credit was spent no longer does, so a timer now opens it (4.01s). Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- .../gitleaks/augmenter_context_test.go | 31 ++++++-- internal/core/claim/generated_match_test.go | 9 ++- internal/core/claim/generated_test.go | 10 ++- internal/core/claim/status_test.go | 44 +++++++---- internal/core/github/scheduled_test.go | 17 ++++- .../core/implement/loop/widen_paths_test.go | 28 +++++-- internal/core/matrix/compliance_unix_test.go | 17 ++++- internal/core/matrix/hiddenrun_signal_test.go | 12 ++- internal/core/matrix/hiddenrun_unix_test.go | 10 ++- internal/core/runner/gatewait_test.go | 54 ++++++++++++-- internal/core/sessionname/register_test.go | 19 ++++- internal/gittest/answerpipe_unix.go | 28 +++++++ internal/gittest/answerpipe_unix_test.go | 32 ++++++++ internal/gitutil/bounded_unix_test.go | 14 +++- internal/gitutil/context_test.go | 25 +++++-- internal/gitutil/stored_context_test.go | 13 ++-- internal/gitutil/stored_each_test.go | 7 +- .../hook_permission_request_budget_test.go | 10 ++- .../surface/cli/hook_subagent_start_test.go | 23 ++++-- .../surface/cli/implement_load_renew_test.go | 24 ++++-- internal/testreuse/run_test.go | 74 +++++++++++++------ 21 files changed, 387 insertions(+), 114 deletions(-) create mode 100644 internal/gittest/answerpipe_unix.go create mode 100644 internal/gittest/answerpipe_unix_test.go diff --git a/internal/adapter/gitleaks/augmenter_context_test.go b/internal/adapter/gitleaks/augmenter_context_test.go index a61007b26b..8031213278 100644 --- a/internal/adapter/gitleaks/augmenter_context_test.go +++ b/internal/adapter/gitleaks/augmenter_context_test.go @@ -10,19 +10,30 @@ import ( "time" "github.com/intentdriven/abcd/internal/adapter/scanner" + "github.com/intentdriven/abcd/internal/testtiming" ) // stalledRunner is a gitleaks run that does not finish until its context -// ends, and then fails with the context's error, as exec.CommandContext's -// killed process does. -type stalledRunner struct{ sawStop bool } +// ends, or for stalledFor, and then fails with the context's error, as +// exec.CommandContext's killed process does. It closes started on entry, so a +// test can end the context once the run has begun rather than on a timer a +// slow runner can spend before the run starts, as the scanner's own test of +// its run context once did (9a5bfd431, iss-2612022218392055). +type stalledRunner struct { + sawStop bool + started chan struct{} +} + +// stalledFor is how long a stalled run lasts if its context never ends. +const stalledFor = time.Minute func (r *stalledRunner) Run(ctx context.Context, _, _ string) ([]byte, error) { + close(r.started) select { case <-ctx.Done(): r.sawStop = true return nil, ctx.Err() - case <-time.After(10 * time.Second): + case <-time.After(stalledFor): return []byte("[]"), nil } } @@ -33,20 +44,24 @@ func (r *stalledRunner) Run(ctx context.Context, _, _ string) ([]byte, error) { func TestAugmenterScanContextStopsTheRun(t *testing.T) { repo := t.TempDir() writeConfig(t, repo, `{"schema_version":1,"enabled":true}`) - r := &stalledRunner{} + r := &stalledRunner{started: make(chan struct{})} a := &Adapter{LookPath: foundLookPath(t), Runner: r} aug, ok := a.AugmenterFor(repo).(scanner.ContextAugmenter) if !ok { t.Fatal("the gitleaks augmenter cannot be told to stop") } - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() + go func() { + <-r.started + cancel() + }() start := time.Now() if got := aug.ScanContext(ctx, "text", "doc.md"); got != nil { t.Fatalf("a stopped run returned findings: %v", got) } - if took := time.Since(start); took > 5*time.Second { - t.Fatalf("ScanContext took %s; its context ended after 100ms", took) + if err := testtiming.CutShort.Check("ScanContext, its context ended as the run started,", time.Since(start), stalledFor); err != nil { + t.Fatal(err) } if !r.sawStop { t.Error("the run was not handed the context") diff --git a/internal/core/claim/generated_match_test.go b/internal/core/claim/generated_match_test.go index c22dc2d03c..36766d267a 100644 --- a/internal/core/claim/generated_match_test.go +++ b/internal/core/claim/generated_match_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // The generated-file matcher (spc-2610161044461448 step 11; @@ -226,15 +227,17 @@ func TestAPatternPastTheStepBudgetIsNotGenerated(t *testing.T) { attrs := "*y linguist-generated\n*x linguist-generated\n" + strings.Repeat("**/", 300) + "q/*/x -linguist-generated\n" deep := strings.Repeat("a/", 60) + "x" done := make(chan bool, 1) - start := time.Now() + // The cost is read off the CPU clock, which does not charge the time a + // loaded runner keeps the match off a core (iss-2612022218392055). + start := testtiming.CPU() go func() { done <- parseAttributes(attrs).generated(deep) }() select { case got := <-done: if got { t.Fatalf("a path past the step budget is generated") } - if took := time.Since(start); !raceEnabled && took > slack(2*time.Second) { - t.Fatalf("matching one path took %s; want it bounded", took) + if took := testtiming.CPU() - start; !raceEnabled && took > slack(2*time.Second) { + t.Fatalf("matching one path took %s of CPU; want it bounded", took) } case <-time.After(slack(30 * time.Second)): t.Fatal("matching one path did not finish") diff --git a/internal/core/claim/generated_test.go b/internal/core/claim/generated_test.go index 4bc386c25d..d8a2636f9b 100644 --- a/internal/core/claim/generated_test.go +++ b/internal/core/claim/generated_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // Generated files are shared, and one person's own overlapping reserve warns @@ -338,7 +340,9 @@ func TestAVeryDeepPathIsJudgedQuickly(t *testing.T) { entries = append(entries, blobEntry(fmt.Sprintf("%sf%d", deep, i))) } done := make(chan int, 1) - start := time.Now() + // The cost is read off the CPU clock, which does not charge the time a + // loaded runner keeps the lookup off a core (iss-2612022218392055). + start := testtiming.CPU() go func() { got, _ := candidatesOf(entries) done <- len(got) @@ -348,8 +352,8 @@ func TestAVeryDeepPathIsJudgedQuickly(t *testing.T) { if n != 500 { t.Fatalf("candidates = %d; want the 500 deep files", n) } - if took := time.Since(start); !raceEnabled && took > slack(2*time.Second) { - t.Fatalf("500 paths 2,049 directories deep took %s; want well under a second", took) + if took := testtiming.CPU() - start; !raceEnabled && took > slack(2*time.Second) { + t.Fatalf("500 paths 2,049 directories deep took %s of CPU; want well under a second", took) } case <-time.After(slack(30 * time.Second)): t.Fatal("500 paths 2,049 directories deep did not finish") diff --git a/internal/core/claim/status_test.go b/internal/core/claim/status_test.go index 2cd93a18bf..4566329392 100644 --- a/internal/core/claim/status_test.go +++ b/internal/core/claim/status_test.go @@ -14,6 +14,7 @@ import ( "github.com/intentdriven/abcd/internal/core/lease" "github.com/intentdriven/abcd/internal/fsutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // Reading the announcements (itd-2609151838312703, spc-2610150728396006 step @@ -446,16 +447,18 @@ func TestThePromptNeverWaitsOnTheNetwork(t *testing.T) { pat.git("config", "protocol.ext.allow", "always") // "% " is git-remote-ext's literal space; a backslash would hand sleep // no argument, and the origin would fail at once instead of hanging. - pat.git("remote", "set-url", "origin", "ext::sh -c sleep% 30") + const originHang = time.Minute + pat.git("remote", "set-url", "origin", "ext::sh -c sleep% 60") log := traced(t) start := time.Now() got := pat.notes() - // The origin would hang for 30 s; the block reads disk alone, well inside - // it. The bound is slack's (wallClockSlack), not the hook's second: a - // network wait runs the read out of its budget, which notes fails on, - // and the trace below names it. - if took := time.Since(start); took > slack(time.Second) { - t.Fatalf("the block took %s; want it never to wait on the network", took) + // The origin would hang for a minute; the block reads disk alone, well + // inside it, so it is judged against the hang it must never wait out + // (testtiming.CutShort), not a constant a slow runner can pass: a network + // wait runs the read out of its budget, which notes fails on, and the + // trace below names it. + if err := testtiming.CutShort.Check("the block, which never waits on the network,", time.Since(start), originHang); err != nil { + t.Fatal(err) } if !strings.Contains(got, "merging #1012") { t.Fatalf("the block:\n%s\nwant the announcement from the last fetch", got) @@ -482,13 +485,26 @@ func TestThePromptNeverWaitsOnTheNetwork(t *testing.T) { }) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - start = time.Now() - n, err := PromptNotes(ctx, pat.dir, w.clock(), pat.opts()) - // The read is held until the test ends, so any finite bound shows the - // prompt returned at its deadline, a second, and not at the read's end; - // the bound is slack's, as above. - if took := time.Since(start); took > slack(time.Second) { - t.Fatalf("a slow read held the prompt for %s", took) + type notes struct { + n Notes + err error + } + returned := make(chan notes, 1) + go func() { + n, err := PromptNotes(ctx, pat.dir, w.clock(), pat.opts()) + returned <- notes{n, err} + }() + // The read is held until the test ends, so the prompt returning at all + // shows it returned at its deadline and not at the read's end; the wait + // for it is a bound on a hang, not on how long a second takes a slow + // runner. + var n Notes + var err error + select { + case r := <-returned: + n, err = r.n, r.err + case <-time.After(testtiming.Patience(t)): + t.Fatal("a slow read held the prompt") } if !errors.Is(err, ErrStatusUnavailable) || !strings.Contains(n.Text, "status unavailable: reading it here took longer than this prompt allows") { t.Fatalf("a slow read = %q, %v; want the status unavailable", n.Text, err) diff --git a/internal/core/github/scheduled_test.go b/internal/core/github/scheduled_test.go index 47b4e6a082..b74743ae33 100644 --- a/internal/core/github/scheduled_test.go +++ b/internal/core/github/scheduled_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // scheduledAnswer is the forge's list of a workflow's runs as GitHub answers it @@ -187,20 +189,27 @@ func TestAnOriginLookupPastItsDeadlineIsATimeout(t *testing.T) { // TestScheduledRunsEndsAtItsCallersDeadline: a forge that does not answer // holds the caller no longer than the deadline it set. +// +// The checkout is made before the deadline is set, so the deadline is spent +// on the call and not on the test's own git (iss-2612022218392055), and the +// call is judged against the forge's silence it must cut short +// (testtiming.CutShort), not a constant. func TestScheduledRunsEndsAtItsCallersDeadline(t *testing.T) { + const silence = time.Minute dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, "gh"), []byte("#!/bin/sh\nexec sleep 30\n"), 0o755); err != nil { + if err := os.WriteFile(filepath.Join(dir, "gh"), []byte("#!/bin/sh\nexec sleep 60\n"), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + cwd := originAt(t, "https://github.com/example-org/example-app.git") ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() start := time.Now() - _, err := ScheduledRuns(ctx, originAt(t, "https://github.com/example-org/example-app.git"), "nightly.yaml", "main") + _, err := ScheduledRuns(ctx, cwd, "nightly.yaml", "main") if !errors.Is(err, ErrTimeout) { t.Fatalf("ScheduledRuns = %v; want ErrTimeout", err) } - if d := time.Since(start); d > 20*time.Second { - t.Fatalf("the call took %s against a 200ms deadline", d) + if err := testtiming.CutShort.Check("the call against a 200ms deadline", time.Since(start), silence); err != nil { + t.Fatal(err) } } diff --git a/internal/core/implement/loop/widen_paths_test.go b/internal/core/implement/loop/widen_paths_test.go index c80a59a130..854fb24d25 100644 --- a/internal/core/implement/loop/widen_paths_test.go +++ b/internal/core/implement/loop/widen_paths_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/intentdriven/abcd/internal/core/claim" + "github.com/intentdriven/abcd/internal/testtiming" ) // TestPathsTooManyForAReservationAreAGapNamingTheCap: the walled implementer @@ -52,14 +53,29 @@ func TestAWideningOfVeryManyPathsIsRefusedAtOnce(t *testing.T) { if len(w.added) != 0 || w.footprint != nil { t.Fatalf("nothing is added or held: %+v", w) } - if took > 2*time.Second { - t.Fatalf("the refusal comes at once, not after comparing every path: %s", took) - } - if paths, err := widenPaths("lane-1", want); err != nil || len(paths) != len(want) { + pass := time.Now() + paths, err := widenPaths("lane-1", want) + onePass := time.Since(pass) + if err != nil || len(paths) != len(want) { t.Fatalf("the paths are deduplicated in one pass: %d, %v", len(paths), err) } - if took := time.Since(start); took > 4*time.Second { - t.Fatalf("checking and deduplicating the paths takes no more than a pass over them: %s", took) + // Both are judged against a pass over a tenth of the paths, timed beside + // them, so the race detector and a loaded runner slow the reference as + // they slow what is judged; bounds of two and four seconds were set for + // one machine and flaked on slower ones (iss-2612022218392055). The + // refusal compares no more than maxWidenPaths of the paths, under a tenth + // of them; deduplicating all of them is ten such passes and the sort's + // share, where comparing each path with every other is ten thousand. + tenth := time.Now() + if _, err := widenPaths("lane-1", want[:len(want)/10]); err != nil { + t.Fatal(err) + } + reference := time.Since(tenth) + if err := (testtiming.Bound{Ratio: 1, Floor: time.Second}).Check("the refusal, which comes at once rather than after comparing every path,", took, reference); err != nil { + t.Fatal(err) + } + if err := (testtiming.Bound{Ratio: 30, Floor: time.Second}).Check("deduplicating the paths, no more than a pass over them,", onePass, reference); err != nil { + t.Fatal(err) } } diff --git a/internal/core/matrix/compliance_unix_test.go b/internal/core/matrix/compliance_unix_test.go index 47d00e8484..8b8fb7d765 100644 --- a/internal/core/matrix/compliance_unix_test.go +++ b/internal/core/matrix/compliance_unix_test.go @@ -9,6 +9,9 @@ import ( "syscall" "testing" "time" + + "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // A copy controls its clone's git directory, so the tests-kept check reads @@ -129,13 +132,17 @@ func TestAGitThatWaitsIsStoppedAtItsBound(t *testing.T) { if err := syscall.Mkfifo(fifo, 0o600); err != nil { t.Fatal(err) } + // git is answered after gitStall, so the call is judged against waiting + // that out (testtiming.CutShort), not a constant (iss-2612022218392055). + const gitStall = time.Minute + gittest.AnswerPipeAfter(t, fifo, gitStall) start := time.Now() _, err := gitRawWithin(500*time.Millisecond, "config", "--file", fifo, "--get", "core.eol") if err == nil || !strings.Contains(err.Error(), "did not finish within 500ms") { t.Fatalf("a git that waits: %v; want it stopped at its bound", err) } - if took := time.Since(start); took > 20*time.Second { - t.Fatalf("a git that waits took %s to stop; want about its bound", took) + if err := testtiming.CutShort.Check("a git that waits, stopped at its 500ms bound,", time.Since(start), gitStall); err != nil { + t.Fatal(err) } } @@ -155,13 +162,15 @@ func TestTheComplianceCheckStopsAtItsOverallDeadline(t *testing.T) { t.Fatal(err) } c.in.Within = 2 * time.Second + const gitStall = time.Minute + gittest.AnswerPipeAfter(t, config, gitStall) start := time.Now() got, err := checkCompliance(c.in) if err != nil { t.Fatal(err) } - if took := time.Since(start); took > 30*time.Second { - t.Fatalf("the check took %s; want it stopped at its deadline of %s", took, c.in.Within) + if err := testtiming.CutShort.Check("the check, stopped at its deadline of 2s,", time.Since(start), gitStall); err != nil { + t.Fatal(err) } if err := got.validate(); err != nil { t.Fatalf("the stopped check's result is refused by its own record: %v", err) diff --git a/internal/core/matrix/hiddenrun_signal_test.go b/internal/core/matrix/hiddenrun_signal_test.go index 9f1fb6ea8a..bee4f873db 100644 --- a/internal/core/matrix/hiddenrun_signal_test.go +++ b/internal/core/matrix/hiddenrun_signal_test.go @@ -13,6 +13,8 @@ import ( "syscall" "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // A hidden-test run never outlives abcd's stop: a signal abcd catches kills the @@ -212,14 +214,18 @@ func TestAStopSignalStatusIsTheCopysFailureNotAStall(t *testing.T) { for _, code := range []string{"145", "146", "147", "149", "150", "200"} { hr := newHiddenRun(t, nil) hr.in.Command = sh(`exit ` + code) - hr.in.Deadline = 5 * time.Second + // Judged against the deadline a stall would run to + // (testtiming.CutShort), twenty seconds, so a slow runner has ten + // to start and end a shell in, where four seconds of a five-second + // deadline left it one (iss-2612022218392055). + hr.in.Deadline = 20 * time.Second start := time.Now() out, err := runHiddenTests(context.Background(), hr.in) if err != nil { t.Fatal(err) } - if took := time.Since(start); took > 4*time.Second { - t.Errorf("exit %s returned after %s, stalled toward its deadline", code, took) + if err := testtiming.CutShort.Check("exit "+code+", which returns at once and never stalls toward its deadline,", time.Since(start), hr.in.Deadline); err != nil { + t.Error(err) } if out.Status != StatusFailed || !strings.Contains(out.Reason, "exited "+code) || strings.Contains(out.Output, "kill") { t.Errorf("exit %s gave %+v; want failed, naming the status, with nothing of the supervisor's output", code, out) diff --git a/internal/core/matrix/hiddenrun_unix_test.go b/internal/core/matrix/hiddenrun_unix_test.go index f129cc5555..c5840c96cb 100644 --- a/internal/core/matrix/hiddenrun_unix_test.go +++ b/internal/core/matrix/hiddenrun_unix_test.go @@ -14,6 +14,8 @@ import ( "syscall" "testing" "time" + + "github.com/intentdriven/abcd/internal/testtiming" ) // pidGone waits up to 10s for pid to be no process at all, reaped. @@ -116,8 +118,8 @@ func TestALeaderThatExitsWhileItsChildHoldsItsOutputIsJudgedAtOnce(t *testing.T) if err != nil || out.Status != StatusPassed || out.Score == nil || out.Score.Passed != 1 || out.Score.Total != 1 { t.Fatalf("outcome %+v, %v; want passed 1 of 1", out, err) } - if took > 10*time.Second { - t.Errorf("returned after %s; the leader exited at once", took) + if err := testtiming.CutShort.Check("the run, whose leader exited at once,", took, hr.in.Deadline); err != nil { + t.Error(err) } if !strings.Contains(out.Output, "before") { t.Errorf("the output was not drained: %q", out.Output) @@ -183,8 +185,8 @@ func TestACopyHoldingAFIFOIsUnexaminedAndNeverWaitedOn(t *testing.T) { if err != nil || out.Status != StatusUnexamined || !strings.Contains(out.Reason, "pipe") { t.Fatalf("outcome %+v, %v; want unexamined naming the FIFO", out, err) } - if took := time.Since(start); took > 15*time.Second { - t.Errorf("the export waited %s on the FIFO", took) + if err := testtiming.CutShort.Check("the export, which never waits on the FIFO,", time.Since(start), hr.in.Deadline); err != nil { + t.Error(err) } } diff --git a/internal/core/runner/gatewait_test.go b/internal/core/runner/gatewait_test.go index 92a5e5ac6e..ef49585fbe 100644 --- a/internal/core/runner/gatewait_test.go +++ b/internal/core/runner/gatewait_test.go @@ -3,13 +3,16 @@ package runner import ( "context" "errors" + "os" "os/exec" + "path/filepath" "strings" "sync/atomic" "testing" "time" "github.com/intentdriven/abcd/internal/core/machineload" + "github.com/intentdriven/abcd/internal/testtiming" ) // sleepLauncher is a launcher that runs the system's sleep, asking gate @@ -29,11 +32,31 @@ func sleepLauncher(t *testing.T, gate func(int) bool) (launcher, string) { // the load gate for longer than its bound leaves the gate with its clock // stopped, and finishes its work rather than being killed at the bound // (iss-2611021751406429). +// +// The run's work ends once the gate has opened, not after a fixed time: a +// sleep of 1.5s behind a 0.8s wait left 0.3s of a 1s bound for starting the +// process and asking the gate, which a slow runner can spend +// (iss-2612022218392055). Now the gate waits past the bound, so a run charged +// for its wait is killed whatever the runner's speed, and once it opens, what +// is left of the bound and its credit (gateCredit, the bound again), two +// seconds, is for a shell loop to see one file and exit. func TestARunWaitingAtTheLoadGateIsNotKilledForIt(t *testing.T) { + const bound, wait = 3 * time.Second, 4 * time.Second + shell, err := exec.LookPath("sh") + if err != nil { + t.Skip("no sh on PATH") + } + // The gate opens on its own clock, not when it is next asked: the run + // stops asking once its credit is spent, which comes before the gate + // opens. + opened := filepath.Join(t.TempDir(), "opened") start := time.Now() - l, bin := sleepLauncher(t, func(int) bool { return time.Since(start) < 800*time.Millisecond }) - if _, err := l.run(context.Background(), Claude, bin, []string{"1.5"}, nil, t.TempDir(), time.Second); err != nil { - t.Fatalf("a run that waited 0.8s at the load gate, then worked 0.7s of its 1s bound, failed: %v", err) + open := time.AfterFunc(wait, func() { _ = os.WriteFile(opened, nil, 0o600) }) + t.Cleanup(func() { open.Stop() }) + l, _ := sleepLauncher(t, func(int) bool { return time.Since(start) < wait }) + work := "while [ ! -e '" + opened + "' ]; do sleep 0.02; done" + if _, err := l.run(context.Background(), Claude, shell, []string{"-c", work}, nil, t.TempDir(), bound); err != nil { + t.Fatalf("a run that waited %s at the load gate, past its %s bound, then ended, failed: %v", wait, bound, err) } } @@ -54,16 +77,33 @@ func TestARunNotWaitingAtTheGateIsKilledAtItsBound(t *testing.T) { // TestTheGateCreditIsBounded: a waiter that never opens holds a run open for // at most gateCredit past its bound, and the kill says how long it waited. +// +// The run is judged against the same run with no wait, killed at its bound, +// timed beside it: what a slow runner adds to starting and killing the process +// it adds to both, where a fixed two seconds of slack was a guess at it +// (iss-2612022218392055). The waited run lasts LongestRun, the bound and the +// credit, so it may take that many times the reference and half the reference +// again for the gate's polls; a credit never ended runs the sleep's whole +// minute, far over it. func TestTheGateCreditIsBounded(t *testing.T) { - l, bin := sleepLauncher(t, func(int) bool { return true }) + const bound = 500 * time.Millisecond + l, bin := sleepLauncher(t, func(int) bool { return false }) + began := time.Now() + if _, err := l.run(context.Background(), Claude, bin, []string{"60"}, nil, t.TempDir(), bound); !errors.Is(err, ErrKilled) { + t.Fatalf("premise: the run with no wait is killed at its bound: %v", err) + } + reference := time.Since(began) + + l, bin = sleepLauncher(t, func(int) bool { return true }) start := time.Now() - _, err := l.run(context.Background(), Claude, bin, []string{"10"}, nil, t.TempDir(), 500*time.Millisecond) + _, err := l.run(context.Background(), Claude, bin, []string{"60"}, nil, t.TempDir(), bound) took := time.Since(start) if !errors.Is(err, ErrKilled) { t.Fatalf("err = %v, want a kill", err) } - if took > LongestRun(500*time.Millisecond)+2*time.Second { - t.Errorf("the run lasted %s, past its longest (%s)", took, LongestRun(500*time.Millisecond)) + longest := testtiming.Bound{Ratio: float64(LongestRun(bound))/float64(bound) + 0.5} + if err := longest.Check("the run held at the gate", took, reference); err != nil { + t.Errorf("%v: past its longest (%s)", err, LongestRun(bound)) } if !strings.Contains(err.Error(), "load gate") { t.Errorf("the kill does not say the run waited at the load gate: %v", err) diff --git a/internal/core/sessionname/register_test.go b/internal/core/sessionname/register_test.go index f106cee8ac..9a671a1e03 100644 --- a/internal/core/sessionname/register_test.go +++ b/internal/core/sessionname/register_test.go @@ -17,6 +17,7 @@ import ( "github.com/intentdriven/abcd/internal/abcdhome" "github.com/intentdriven/abcd/internal/core/machineload" "github.com/intentdriven/abcd/internal/fsutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // machine is a fixture computer: a temporary home and a process table the @@ -686,12 +687,24 @@ func TestNamingNeverFailsASession(t *testing.T) { }, "lock"}, } { t.Run(name, func(t *testing.T) { + // Each failure is judged against a start that names a session, + // timed beside it, not against a constant a slow runner can + // pass (iss-2612022218392055): it may take twice as long, and + // never less than a second, so the held lock's case waiting + // out the default two seconds in place of its own tenth of one + // is still over it wherever a clean start takes under a second. + clean := newMachine(t) + began := time.Now() + if out := clean.start(100, t.TempDir(), "a"); out.Name == "" { + t.Fatalf("premise: a start on a clean machine names its session: %+v", out) + } + reference := time.Since(began) m := newMachine(t) c.arrange(t, m) - began := time.Now() + began = time.Now() out := m.start(100, t.TempDir(), "a") - if took := time.Since(began); took > 1500*time.Millisecond { - t.Fatalf("naming took %s", took) + if err := (testtiming.Bound{Ratio: 2, Floor: time.Second}).Check("naming", time.Since(began), reference); err != nil { + t.Fatal(err) } if out.Name != "" || len(out.Notes) != 1 { t.Fatalf("Start = %+v, want unnamed with one note", out) diff --git a/internal/gittest/answerpipe_unix.go b/internal/gittest/answerpipe_unix.go new file mode 100644 index 0000000000..8125d8a728 --- /dev/null +++ b/internal/gittest/answerpipe_unix.go @@ -0,0 +1,28 @@ +//go:build unix + +package gittest + +import ( + "os" + "syscall" + "testing" + "time" +) + +// AnswerPipeAfter ends, after d, the wait of a git still reading pipe, a named +// pipe a fixture put where git reads its configuration: it opens the pipe for +// writing, without blocking, and closes it, so a reader waiting there reads an +// empty file and goes on. A wait that was stopped, as it should be, leaves no +// reader, and the open finds none. It turns a git that would wait forever into +// one that waits d, the finite alternative a test judges a stopped call +// against (testtiming.CutShort, iss-2612022218392055), rather than a constant +// a slow runner's process start can pass. +func AnswerPipeAfter(t *testing.T, pipe string, d time.Duration) { + t.Helper() + answer := time.AfterFunc(d, func() { + if f, err := os.OpenFile(pipe, os.O_WRONLY|syscall.O_NONBLOCK, 0); err == nil { + _ = f.Close() + } + }) + t.Cleanup(func() { answer.Stop() }) +} diff --git a/internal/gittest/answerpipe_unix_test.go b/internal/gittest/answerpipe_unix_test.go new file mode 100644 index 0000000000..e59d803eb2 --- /dev/null +++ b/internal/gittest/answerpipe_unix_test.go @@ -0,0 +1,32 @@ +//go:build unix + +package gittest + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +// TestAnswerPipeAfterEndsAWaitingRead: a read waiting on the pipe, as a git +// reading its configuration there does, reads an empty file once the answer +// comes, and not before. +func TestAnswerPipeAfterEndsAWaitingRead(t *testing.T) { + pipe := filepath.Join(t.TempDir(), "config") + if err := syscall.Mkfifo(pipe, 0o600); err != nil { + t.Skipf("no named pipe here: %v", err) + } + const after = 200 * time.Millisecond + AnswerPipeAfter(t, pipe, after) + start := time.Now() + data, err := os.ReadFile(pipe) + if err != nil || len(data) != 0 { + t.Fatalf("the read got %q, %v; want an empty file", data, err) + } + // A lower bound: a slow runner only lengthens the read. + if took := time.Since(start); took < after/2 { + t.Errorf("the read ended after %v, before the answer at %v", took, after) + } +} diff --git a/internal/gitutil/bounded_unix_test.go b/internal/gitutil/bounded_unix_test.go index 07a60fabee..12869e5154 100644 --- a/internal/gitutil/bounded_unix_test.go +++ b/internal/gitutil/bounded_unix_test.go @@ -16,6 +16,7 @@ import ( "github.com/intentdriven/abcd/internal/gittest" "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot is the reproduced @@ -39,8 +40,17 @@ func TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot(t *testing.T) { if !errors.Is(err, stalled) { t.Fatalf("the stopped commit was not refused as stalled: %v", err) } - time.Sleep(300 * time.Millisecond) - if pid, ok := lateChildAlive(t, pidFile); ok { + // The program, killed with the stop, may take a moment to go on a loaded + // runner; one the stop missed lives its whole minute, so it is given half + // of that (testtiming.CutShort) rather than a fixed 300ms + // (iss-2612022218392055). + var pid int + gone := func() bool { + var alive bool + pid, alive = lateChildAlive(t, pidFile) + return !alive + } + if !testtiming.AwaitWithin(testtiming.CutShort.Limit(time.Minute), 20*time.Millisecond, gone) { t.Errorf("prepare-commit-msg's program (pid %d) is still running after the stop", pid) } if took >= gitutil.StopGrace { diff --git a/internal/gitutil/context_test.go b/internal/gitutil/context_test.go index ba0ea3a91e..3839474101 100644 --- a/internal/gitutil/context_test.go +++ b/internal/gitutil/context_test.go @@ -14,10 +14,19 @@ import ( "github.com/intentdriven/abcd/internal/gittest" "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // hangingGit puts a `git` first on PATH that records its pid in the returned // file and then sleeps far past any deadline a test sets. +// gitHang is how long a stand-in git that hangs takes to end on its own. A +// read bounded by a deadline under a second is judged against it +// (testtiming.CutShort): it comes back in under half of it, which a read that +// waited the git out cannot, while a slow runner's seconds of starting and +// killing processes cannot fail it as a constant of two or three seconds +// could (iss-2612022218392055). +const gitHang = time.Minute + func hangingGit(t *testing.T) (pidFile string) { t.Helper() if _, err := exec.LookPath("sh"); err != nil { @@ -25,7 +34,7 @@ func hangingGit(t *testing.T) (pidFile string) { } bin := t.TempDir() pidFile = filepath.Join(t.TempDir(), "pid") - body := "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 10\n" + body := "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 60\n" if err := os.WriteFile(filepath.Join(bin, "git"), []byte(body), 0o755); err != nil { t.Fatal(err) } @@ -58,8 +67,8 @@ func TestRootCommitContextKillsGitAtTheDeadline(t *testing.T) { if sha != "" || !errors.Is(err, context.DeadlineExceeded) { t.Errorf("RootCommitContext = %q, %v; want \"\" and context.DeadlineExceeded", sha, err) } - if took > 3*time.Second { - t.Errorf("returned after %s; the deadline was 500ms", took) + if err := testtiming.CutShort.Check("the lookup against a 500ms deadline", took, gitHang); err != nil { + t.Error(err) } raw, rerr := os.ReadFile(pidFile) if os.IsNotExist(rerr) { @@ -131,8 +140,8 @@ func TestAContextBoundReadEndsAtItsDeadlineWhileTheVersionProbeHangs(t *testing. if sha != "" || !errors.Is(err, context.DeadlineExceeded) { t.Errorf("RootCommitContext = %q, %v; want \"\" and context.DeadlineExceeded", sha, err) } - if took > 3*time.Second { - t.Errorf("returned after %s while git's version probe hung; the deadline was 500ms", took) + if err := testtiming.CutShort.Check("the lookup against a 500ms deadline, while git's version probe hung,", took, gitHang); err != nil { + t.Error(err) } raw, rerr := os.ReadFile(pidFile) if os.IsNotExist(rerr) { @@ -167,7 +176,7 @@ func TestAContextBoundReadEndsAtItsDeadlineWhileTheConfigReadHangs(t *testing.T) t.Fatal(err) } bin := t.TempDir() - body := "#!/bin/sh\nif [ \"$1\" = version ]; then echo 'git version 2.30.0'; exit 0; fi\nexec sleep 10\n" + body := "#!/bin/sh\nif [ \"$1\" = version ]; then echo 'git version 2.30.0'; exit 0; fi\nexec sleep 60\n" if err := os.WriteFile(filepath.Join(bin, "git"), []byte(body), 0o755); err != nil { t.Fatal(err) } @@ -185,8 +194,8 @@ func TestAContextBoundReadEndsAtItsDeadlineWhileTheConfigReadHangs(t *testing.T) if sha != "" || !errors.Is(err, context.DeadlineExceeded) { t.Errorf("RootCommitContext = %q, %v; want \"\" and context.DeadlineExceeded", sha, err) } - if took > 3*time.Second { - t.Errorf("returned after %s while git's config read hung; the deadline was 500ms", took) + if err := testtiming.CutShort.Check("the lookup against a 500ms deadline, while git's config read hung,", took, gitHang); err != nil { + t.Error(err) } } diff --git a/internal/gitutil/stored_context_test.go b/internal/gitutil/stored_context_test.go index 4b16378139..0640fc858b 100644 --- a/internal/gitutil/stored_context_test.go +++ b/internal/gitutil/stored_context_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // The deadline-bound stored read the status reader's walk and batch reads @@ -47,13 +48,13 @@ func stubGit(t *testing.T, act string) (runs string) { // TestTheStoredReadKillsAGitThatHangs: a git that sleeps past the deadline // is killed when it ends, and the read answers the context's own error. func TestTheStoredReadKillsAGitThatHangs(t *testing.T) { - stubGit(t, "exec sleep 10") + stubGit(t, "exec sleep 60") ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) defer cancel() start := time.Now() out, err := gitutil.RunCappedBytesAsStoredContext(ctx, t.TempDir(), "", 1024, "for-each-ref") - if took := time.Since(start); took > 2*time.Second { - t.Fatalf("returned after %s; the deadline was 300ms", took) + if err := testtiming.CutShort.Check("the read against a 300ms deadline", time.Since(start), gitHang); err != nil { + t.Fatal(err) } if out != nil || !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("read = %q, %v; want nothing and context.DeadlineExceeded", out, err) @@ -97,13 +98,13 @@ func TestTheStoredReadReadsAnAnswerWhoseOutputClosesLate(t *testing.T) { // left holding its output cannot hold the read past its deadline, and what // was read before it is never answered as git's. func TestTheStoredReadEndsAtItsDeadlineWhileTheOutputStaysOpen(t *testing.T) { - stubGit(t, "sleep 5 &\necho answer") + stubGit(t, "sleep 60 &\necho answer") ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) defer cancel() start := time.Now() out, err := gitutil.RunCappedBytesAsStoredContext(ctx, t.TempDir(), "", 1024, "for-each-ref") - if took := time.Since(start); took > 3*time.Second { - t.Fatalf("returned after %s; the deadline was 300ms", took) + if err := testtiming.CutShort.Check("the read against a 300ms deadline, with its output held open,", time.Since(start), gitHang); err != nil { + t.Fatal(err) } if out != nil || !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("read = %q, %v; want nothing and context.DeadlineExceeded", out, err) diff --git a/internal/gitutil/stored_each_test.go b/internal/gitutil/stored_each_test.go index 5ba6035b5f..008f3d3174 100644 --- a/internal/gitutil/stored_each_test.go +++ b/internal/gitutil/stored_each_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/testtiming" ) // TestTheStoredLineReadHandsOnEveryLine: a stored read line by line hands on @@ -35,13 +36,13 @@ func TestTheStoredLineReadHandsOnEveryLine(t *testing.T) { // the context ends, and the read answers the context's own error; one whose // context has already ended runs no git. func TestTheStoredLineReadEndsWithItsContext(t *testing.T) { - runs := stubGit(t, "echo first; exec sleep 10") + runs := stubGit(t, "echo first; exec sleep 60") ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) defer cancel() start := time.Now() err := gitutil.EachAsStoredContext(ctx, t.TempDir(), 64, func(string) {}, "for-each-ref") - if took := time.Since(start); took > 3*time.Second { - t.Fatalf("a hanging git held the read %s", took) + if err := testtiming.CutShort.Check("the read of a hanging git against a 300ms deadline", time.Since(start), gitHang); err != nil { + t.Fatal(err) } if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("err = %v; want the deadline", err) diff --git a/internal/surface/cli/hook_permission_request_budget_test.go b/internal/surface/cli/hook_permission_request_budget_test.go index 0a920d3e06..aadbb3e207 100644 --- a/internal/surface/cli/hook_permission_request_budget_test.go +++ b/internal/surface/cli/hook_permission_request_budget_test.go @@ -10,6 +10,7 @@ import ( "github.com/intentdriven/abcd/internal/adapter/scanner" "github.com/intentdriven/abcd/internal/adapter/scanner/augmenttest" "github.com/intentdriven/abcd/internal/termsafe" + "github.com/intentdriven/abcd/internal/testtiming" ) // stuckAugmenter is a repository's augmenter whose run does not finish: it @@ -47,7 +48,8 @@ func (a *stuckAugmenter) ScanContext(ctx context.Context, text, file string) []s // stderr says so, and the hook still exits 0 with its decision unchanged. func TestPermissionRequestRecordKeepsToItsBudget(t *testing.T) { root := managedCheckout(t) - stuck := newStuckAugmenter(10 * time.Second) + const stuckFor = time.Minute + stuck := newStuckAugmenter(stuckFor) augmenttest.Install(t, stuck) prev := permissionRecordBudget permissionRecordBudget = 300 * time.Millisecond @@ -60,8 +62,10 @@ func TestPermissionRequestRecordKeepsToItsBudget(t *testing.T) { if code != 0 || stdout != "" { t.Fatalf("nobody away: exit %d stdout %q (stderr %q); want exit 0 and no decision", code, stdout, stderr) } - if took > 5*time.Second { - t.Fatalf("the hook took %s with a stuck augmenter; the record's budget is %s", took, permissionRecordBudget) + // Judged against the scan it must not wait out (testtiming.CutShort), not a + // constant a slow runner's process start can pass (iss-2612022218392055). + if err := testtiming.CutShort.Check("the hook with a stuck augmenter and a 300ms record budget", took, stuckFor); err != nil { + t.Fatal(err) } recs := promptRecord(t, root) if len(recs) != 1 { diff --git a/internal/surface/cli/hook_subagent_start_test.go b/internal/surface/cli/hook_subagent_start_test.go index 4915ed20ea..4084649c49 100644 --- a/internal/surface/cli/hook_subagent_start_test.go +++ b/internal/surface/cli/hook_subagent_start_test.go @@ -18,6 +18,7 @@ import ( "github.com/intentdriven/abcd/internal/core/history" "github.com/intentdriven/abcd/internal/core/rules" "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // subagentCheckWord stands in a fixture's conventions file and must reach @@ -646,16 +647,21 @@ func TestSubagentStartStopsAtItsOwnBound(t *testing.T) { t.Fatal(err) } setBound(t, &subagentStartBound, 300*time.Millisecond) + // The stdin ends after stdinStall, so the hook is judged against waiting + // that out (testtiming.CutShort), not a constant a slow runner's start + // can pass (iss-2612022218392055). + const stdinStall = time.Minute never := func() io.Reader { r, w := io.Pipe() - t.Cleanup(func() { _ = w.Close() }) + end := time.AfterFunc(stdinStall, func() { _ = w.Close() }) + t.Cleanup(func() { end.Stop(); _ = w.Close() }) return r } t.Chdir(repo.Root()) start := time.Now() failedStart(t, "a stdin that never ends", never()) - if took := time.Since(start); took > 5*time.Second { - t.Errorf("the hook answered after %s", took) + if err := testtiming.CutShort.Check("the hook with a stalled stdin and a 300ms bound", time.Since(start), stdinStall); err != nil { + t.Error(err) } // Silent where the checkout does not look managed. t.Chdir(realPath(t, t.TempDir())) @@ -699,13 +705,18 @@ func TestSubagentStartNotesOnlyASubagentItAnswersFor(t *testing.T) { // TestSubagentStartStopsWhenGitDoesNotAnswer: git waiting on a configuration // it cannot finish reading spends the bound, and the failure is the hook's. func TestSubagentStartStopsWhenGitDoesNotAnswer(t *testing.T) { - repo, _ := pipeIncludedRepo(t) + repo, pipe := pipeIncludedRepo(t) writeUnder(t, repo, "AGENTS.md", "x\n") setBound(t, &subagentStartBound, 500*time.Millisecond) + // git is answered after gitStall, so the hook is judged against waiting + // that out (testtiming.CutShort), not a constant a slow runner's start + // can pass (iss-2612022218392055). + const gitStall = time.Minute + gittest.AnswerPipeAfter(t, pipe, gitStall) start := time.Now() failedStart(t, "git not answering", strings.NewReader(startHookPayload(t, "s1", repo, "a1", "t"))) - if took := time.Since(start); took > 10*time.Second { - t.Errorf("the hook answered after %s", took) + if err := testtiming.CutShort.Check("the hook with git not answering and a 500ms bound", time.Since(start), gitStall); err != nil { + t.Error(err) } if files := factFiles(t); len(files) != 0 { t.Errorf("a sub-agent that was not told left %v", files) diff --git a/internal/surface/cli/implement_load_renew_test.go b/internal/surface/cli/implement_load_renew_test.go index 19a458a0ee..5cb8733638 100644 --- a/internal/surface/cli/implement_load_renew_test.go +++ b/internal/surface/cli/implement_load_renew_test.go @@ -11,6 +11,7 @@ import ( "github.com/intentdriven/abcd/internal/core/claim" "github.com/intentdriven/abcd/internal/core/implement" "github.com/intentdriven/abcd/internal/core/machineload" + "github.com/intentdriven/abcd/internal/testtiming" ) // renewFixture swaps the waiter's renewal for renew, run every millisecond, @@ -131,12 +132,19 @@ func TestImplementLoadWaitNeverWaitsOnARenewal(t *testing.T) { t.Cleanup(func() { loadRenewStopWait = prevStopWait }) stuck := make(chan struct{}) started := make(chan struct{}, 1) + // The renewal comes back after renewalStall, so the open is judged against + // waiting that out (testtiming.CutShort), not a constant a slow runner's + // start can pass (iss-2612022218392055). + const renewalStall = time.Minute renewFixture(t, func(string) ([]claim.Renewal, error) { select { case started <- struct{}{}: default: } - <-stuck + select { + case <-stuck: + case <-time.After(renewalStall): + } return []claim.Renewal{{Record: "iss-5", Until: time.Now()}}, nil }) defer close(stuck) @@ -145,8 +153,8 @@ func TestImplementLoadWaitNeverWaitsOnARenewal(t *testing.T) { if code != 0 { t.Fatalf("exit %d\n%s%s", code, out, errOut) } - if took := time.Since(begin); took > 5*time.Second { - t.Fatalf("the gate opened after %s with a renewal stuck; want it not to wait on one", took) + if err := testtiming.CutShort.Check("the gate's open with a renewal stuck", time.Since(begin), renewalStall); err != nil { + t.Fatal(err) } if strings.Contains(errOut, "renew") { t.Errorf("a renewal is said on standard error:\n%s", errOut) @@ -167,10 +175,14 @@ func TestImplementLoadWaitExitsSoonAfterItsCommandThoughARoundIsInFlight(t *test } release := make(chan struct{}) t.Cleanup(func() { close(release) }) + // The round comes back after roundStall, so the exit is judged against + // waiting that out (testtiming.CutShort): twenty seconds left a slow + // runner ten to start and end the waiter in (iss-2612022218392055). + const roundStall = time.Minute renewFixture(t, func(string) ([]claim.Renewal, error) { select { case <-release: - case <-time.After(20 * time.Second): + case <-time.After(roundStall): } return []claim.Renewal{{Record: "iss-5", Until: time.Now()}}, nil }) @@ -180,8 +192,8 @@ func TestImplementLoadWaitExitsSoonAfterItsCommandThoughARoundIsInFlight(t *test if code != 0 { t.Fatalf("exit %d\n%s%s", code, out, errOut) } - if took > 10*time.Second { - t.Fatalf("the waiter exited %s after its command, a renewal round in flight; want a few seconds at most", took.Round(time.Second)) + if err := testtiming.CutShort.Check("the waiter's exit after its command, a renewal round in flight,", took, roundStall); err != nil { + t.Fatal(err) } if strings.Contains(errOut, "renewed your reservation") { t.Errorf("the renewal finished past the bound is said:\n%s", errOut) diff --git a/internal/testreuse/run_test.go b/internal/testreuse/run_test.go index ba8355450a..0e17f7b7ef 100644 --- a/internal/testreuse/run_test.go +++ b/internal/testreuse/run_test.go @@ -17,6 +17,7 @@ import ( "github.com/intentdriven/abcd/internal/abcdhome" "github.com/intentdriven/abcd/internal/fsutil" "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/testtiming" ) // world is one repository with an origin, its fixture packages, and the home @@ -498,9 +499,7 @@ func TestASecondCheckWaitsOrRefuses(t *testing.T) { t.Errorf("a refused check ran tests:\n%s", refused) } - got := make(chan result) - go func() { got <- w.stage(w.repo, nil, allPackages...) }() - time.Sleep(1500 * time.Millisecond) + got := w.stageWaiting(t, nil, allPackages...) close(release) if err := <-done; err != nil { t.Fatal(err) @@ -685,11 +684,21 @@ func TestCancellingEndsTheWait(t *testing.T) { }() ctx, cancel := context.WithCancel(context.Background()) var out, errb bytes.Buffer - ended := make(chan int) + waiting := make(chan struct{}) + ended := make(chan int, 1) go func() { - ended <- Run(ctx, Config{Stage: "unit", Args: allPackages, Worktree: w.repo, Home: w.home, Stdout: &out, Stderr: &errb, LockWait: time.Hour, Uid: os.Geteuid()}) + ended <- Run(ctx, Config{Stage: "unit", Args: allPackages, Worktree: w.repo, Home: w.home, + Stdout: &onLine{w: &out, line: waitingLine, seen: waiting}, Stderr: &errb, LockWait: time.Hour, Uid: os.Geteuid()}) }() - time.Sleep(1500 * time.Millisecond) + // The cancel comes once the check is waiting, not after a fixed time it + // may still be making its git calls in. + select { + case <-waiting: + case code := <-ended: + t.Fatalf("the check never waited for the held lock: exit %d\n%s%s", code, out.String(), errb.String()) + case <-time.After(testtiming.Patience(t)): + t.Fatal("the check never reached the held lock") + } cancel() select { case code := <-ended: @@ -724,6 +733,39 @@ func holdLock(t *testing.T, lock string) (release func()) { } } +// waitingLine is what a stage says once it finds the check directory's lock held. +const waitingLine = "check-tests: waiting for another check" + +// stageWaiting starts a stage of the world with mod, while a test holds the +// lock, and returns once the stage says it is waiting for it, with the channel +// its result comes on. A test then releases the lock knowing the stage waited: +// a fixed sleep of a second and a half before the release left a stage still +// making its git calls on a slow runner to find the lock free, wait for +// nothing and fail what the test asked of a wait, as clock_test.go's lock test +// did before it waited for this line (iss-2612022218392055). +func (w *world) stageWaiting(t *testing.T, mod func(*Config), args ...string) <-chan result { + t.Helper() + waiting := make(chan struct{}) + got := make(chan result, 1) + go func() { + got <- w.stage(w.repo, func(c *Config) { + if mod != nil { + mod(c) + } + c.Stdout = &onLine{w: c.Stdout, line: waitingLine, seen: waiting} + }, args...) + }() + select { + case <-waiting: + return got + case r := <-got: + t.Fatalf("the stage never waited for the held lock: %s", r) + case <-time.After(testtiming.Patience(t)): + t.Fatal("the stage never reached the held lock") + } + return nil +} + // TestAWaitTakesTheBudgetAgain: -p and -timeout are derived before a wait that can // last hours, so what follows one takes them afresh. No wait, no hook. func TestAWaitTakesTheBudgetAgain(t *testing.T) { @@ -748,9 +790,7 @@ func TestAWaitTakesTheBudgetAgain(t *testing.T) { } lock := filepath.Join(dir, lockName) release := holdLock(t, lock) - got := make(chan result) - go func() { got <- w.stage(w.repo, hook, allPackages...) }() - time.Sleep(1500 * time.Millisecond) + got := w.stageWaiting(t, hook, allPackages...) release() if r := <-got; r.code != 0 { t.Fatalf("the check failed: %s", r) @@ -764,9 +804,7 @@ func TestAWaitTakesTheBudgetAgain(t *testing.T) { refusing := func(c *Config) { c.AfterWait = func() (string, string, error) { return "", "", errors.New("no budget") } } - got = make(chan result) - go func() { got <- w.stage(w.repo, refusing, allPackages...) }() - time.Sleep(1500 * time.Millisecond) + got = w.stageWaiting(t, refusing, allPackages...) release() r := <-got if r.code == 0 || !strings.Contains(r.String(), "no budget") || strings.Contains(r.out, "ok \t") { @@ -808,9 +846,7 @@ func TestARaceStageThatWaitedGoesBackThroughItsGateWithoutTheLock(t *testing.T) } release := holdLock(t, lock) - got := make(chan result) - go func() { got <- w.stage(w.repo, hook, race...) }() - time.Sleep(1500 * time.Millisecond) + got := w.stageWaiting(t, hook, race...) release() if r := <-got; r.code != 0 { t.Fatalf("the check failed: %s", r) @@ -824,9 +860,7 @@ func TestARaceStageThatWaitedGoesBackThroughItsGateWithoutTheLock(t *testing.T) calls = 0 release = holdLock(t, lock) - got = make(chan result) - go func() { got <- w.stage(w.repo, func(c *Config) { hook(c); c.Stage = "unit" }, allPackages...) }() - time.Sleep(1500 * time.Millisecond) + got = w.stageWaiting(t, func(c *Config) { hook(c); c.Stage = "unit" }, allPackages...) release() if r := <-got; r.code != 0 { t.Fatalf("the check failed: %s", r) @@ -837,12 +871,10 @@ func TestARaceStageThatWaitedGoesBackThroughItsGateWithoutTheLock(t *testing.T) // A gate that refuses stops the stage, having run nothing. release = holdLock(t, lock) - got = make(chan result) refusing := func(c *Config) { c.RaceGate = func() error { return errors.New("the gate stayed shut") } } - go func() { got <- w.stage(w.repo, refusing, race...) }() - time.Sleep(1500 * time.Millisecond) + got = w.stageWaiting(t, refusing, race...) release() r := <-got if r.code == 0 || !strings.Contains(r.String(), "the gate stayed shut") || strings.Contains(r.out, "ok \t") { From 58c84da10a251d281e1741b7e4d50f31df61a3eb Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:58:42 +0000 Subject: [PATCH 05/11] test: refuse a new wall-clock bound outside internal/testtiming The last part of iss-2612022218392055's remedy that fits this change: an audit that flags a test holding a measured wall-clock time to a constant, so the census's pattern cannot come back one test at a time. TestNoNewWallClockBound (internal/core/lint, which precheck and both CI legs run whole) reads every test file under internal/ and cmd/ and finds each upper bound on an elapsed wall-clock time (time.Since, time.Now() .Sub, or a name assigned from one) that is a constant duration (unit literals, the package's constants, time.Duration conversions). A lower bound is passed: a slow runner only lengthens what it measures. The 48 bounds left after the census's ten worst were moved are listed by file and function in wallClockBaseline; one more in any function fails, and a listed one fixed fails until the list drops it, so the list only shrinks. internal/testtiming itself is exempt. TestTheWallClockAuditReadsEachShape holds the scan to each shape it flags and each it passes. Red before green: with an empty baseline it named 50 functions on this tree; with lower bounds still counted it named the two lower bounds it now passes, as entries to drop; and on a copy of the tree at 3436e16b4, before the previous three commits, it named exactly the 22 bounds those commits moved onto testtiming, in 21 functions. It sees neither a constant passed through a helper (claim's slack(d)), nor a fixed sleep used as a hand-off, nor a fake clock that reads time.Now; those stay a reviewer's. The last and the remedy's starved lane are deferred by dcn-2612022337510454, with their grounds. The issue is resolved here: the timing helper (3436e16b4), the census's two sibling stand-in clocks, the seven confirmed flaky tests' causes and the one still open, the census's ten worst bounds, and this audit. make precheck passes on this tree (exit 0), internal/core/lint and cmd/precheck-audits whole among it. Resolves: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...ss-2612022218392055-is-resolved-without.md | 6 + ...55-flaky-tests-share-one-pattern-a-test.md | 2 + internal/core/lint/wallclock_audit_test.go | 350 ++++++++++++++++++ 3 files changed, 358 insertions(+) create mode 100644 .abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md rename .abcd/work/issues/{open => resolved}/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md (65%) create mode 100644 internal/core/lint/wallclock_audit_test.go diff --git a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md new file mode 100644 index 0000000000..4c4e7e4a1e --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022337510454 +slug: iss-2612022218392055-is-resolved-without +date: 2026-12-02 +--- +2026-12-02 — iss-2612022218392055 is resolved without two parts of its remedy, each deferred: the starved lane (go test -race under GOMAXPROCS=3 over the packages the flake census names) and the audit's second half, which would flag a fake clock that reads time.Now. What is done: internal/testtiming, the fixes of the census's ten worst bounds, of its two sibling stand-in clocks and of the one confirmed flake still open, and the audit TestNoNewWallClockBound in internal/core/lint, which lists the 48 wall-clock bounds left by function, so none can be added and each one fixed must be struck off; the census rows 11 to 18 that are bounds are among them, and its fixed sleeps and short contexts (rows 11, 17 and 18) the audit cannot see. Grounds: the lane adds hosted-runner time to every CI run, a cost for the person to approve, and its shape should follow the macOS shard split still in flight; a fake that reads the real clock cannot be told by its syntax from a fixture that rightly dates a file, so that check needs a declared list of fakes, more than the hour step 5 allowed, and the two live cases the census found (fixtureworld, livework) are fixed. To reverse: capture either part as its own issue, or add the lane to ci.yml as a job running go test -race with GOMAXPROCS=3 over the census's packages. diff --git a/.abcd/work/issues/open/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md similarity index 65% rename from .abcd/work/issues/open/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md rename to .abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md index b4651019e9..4d982d2d96 100644 --- a/.abcd/work/issues/open/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md +++ b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/implement/loop" remedy: "a test audit that flags a wall-clock assertion (an elapsed time compared with a constant, a fake that reads time.Now) outside one shared helper that judges a ratio against a floor; a flake census of the last 60 days of CI failures, each remaining case fixed or recorded; and a starved lane (GOMAXPROCS=3 with -race, the hosted macOS runner's shape) for the packages the census names" +resolution: "A test judges how long something took through internal/testtiming (Bound, CutShort, CPU, Await, AwaitWithin, Patience); the census's two sibling stand-in clocks, its one confirmed flaky test still open (TestAReservationRenewsDuringAPreflight) and its ten worst wall-clock bounds are fixed on it, the causes of all seven confirmed flakes are named, and TestNoNewWallClockBound in internal/core/lint refuses a new wall-clock bound outside testtiming, the 48 left listed so the list only shrinks; the starved lane and the fake-clock half of the audit are deferred by dcn-2612022337510454" +impact: internal --- Flaky tests share one pattern: a test asserts a wall-clock bound, a fixed budget, or mixes a fake clock with real time, and fails when the runner is slow or loaded. At least twenty commits since 30 Oct fix one (linear-timing bounds, growth reads, push and pusher budgets, a fake process table aging with real time, the scanner context test); two of them failed the v0.18.0 release run, each costing a merge-queue round and a macOS round. Each is fixed one at a time after it fails in CI. diff --git a/internal/core/lint/wallclock_audit_test.go b/internal/core/lint/wallclock_audit_test.go new file mode 100644 index 0000000000..88d2e4ffc3 --- /dev/null +++ b/internal/core/lint/wallclock_audit_test.go @@ -0,0 +1,350 @@ +package lint_test + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +// A test that holds a measured wall-clock time to a constant fails on a runner +// slower than the machine the constant was written on: over sixty days of CI, +// half the failing runs were a wall-clock bound or a fixed budget running out +// (iss-2612022218392055). internal/testtiming is the one way a test judges how +// long something took, against a reference measured in the same run or the +// work a run must cut short. This audit holds every other test to it: it reads +// each test file under internal/ and cmd/ and finds every upper bound on an +// elapsed wall-clock time (time.Since, time.Now().Sub, or a variable assigned +// from one) that is a constant duration (unit literals, constants and +// time.Duration conversions of them). The bounds written before the audit are +// wallClockBaseline, by file and function; a new one, or one more in a listed +// function, fails here, and a listed one fixed fails here until the baseline +// drops it, so the list only shrinks. +// +// It does not see a constant passed through a helper (a `slack(d)`), a bound +// read off the CPU clock, which load does not inflate, or a fixed sleep used as +// a hand-off; those stay a reviewer's to catch. + +// wallClockBaseline is how many wall-clock bounds each function held when the +// audit came in, after the census's ten worst were moved to testtiming. Each +// is a candidate for testtiming too, most of them a generous bound on a call a +// short context ends; none may be added. +var wallClockBaseline = map[string]int{ + "cmd/precheck-audits/main_test.go TestAFailingAuditRunStopsTheWholeRun": 1, + "internal/adapter/openaiapi/client_test.go TestATimeoutIsRefused": 1, + "internal/adapter/openaiapi/local_test.go TestTheProbeIsBounded": 1, + "internal/adapter/openaiapi/models_test.go TestListModelsBoundsTimeAndSize": 1, + "internal/adapter/openaiapi/routing_test.go TestTheGenerationRecordIsWaitedForWithinItsBound": 1, + "internal/core/ahoy/readme_derive_test.go TestHeadingTextStaysLinear": 1, + "internal/core/autonomy/owedread_test.go TestBehindInMergeQueueRepository": 1, + "internal/core/autonomy/owedread_test.go TestForgeListingDeadline": 1, + "internal/core/autonomy/owedread_test.go TestReadOwedHonoursDeadline": 1, + "internal/core/autonomy/session_tracked_test.go TestACreatedBranchStoreTheDeadlineEndsIsMarkedCutShort": 1, + "internal/core/autonomy/session_tracked_test.go TestAReservationsReadTheDeadlineEndsIsMarkedCutShort": 1, + "internal/core/cite/fetch_test.go TestCheckTimesOutAsAnOutcome": 1, + "internal/core/claim/generatedcache_test.go TestAKeptReadWithNoContextIsBounded": 1, + "internal/core/claim/status_pushers_test.go TestEachForgeLookupEndsAtTheBudget": 1, + "internal/core/claim/viewctx_test.go TestABoundTipReadOnItsOwnStopsAHungGit": 1, + "internal/core/claim/viewctx_test.go TestATipReadItsDeadlineEndsIsNoObjectTooBig": 1, + "internal/core/claim/viewctx_test.go TestViewContextStopsAHungGitOnEveryRoute": 1, + "internal/core/dogfood/dogfood_routes_test.go TestResolveNeverReadsTheNetwork": 1, + "internal/core/findings/list_test.go TestACancelledCallDoesNotWaitForTheLock": 1, + "internal/core/findings/list_test.go TestAPutWaitsNoLongerThanItsCaller": 1, + "internal/core/findings/list_test.go TestTheLockWaitIsBounded": 1, + "internal/core/github/activity_test.go TestPushersEndsAtItsCallersDeadline": 1, + "internal/core/guard/landing_test.go TestAGitAliasReadThatDoesNotAnswerIsRefusedWithinItsBudget": 1, + "internal/core/implement/loop/lanehooks_test.go TestALaneCheckoutHasItsOwnBound": 1, + "internal/core/implement/loop/pickgit_deadline_test.go TestALaneResetStoppedAtItsBoundIsNamedAsAReset": 1, + "internal/core/implement/loop/pickgit_deadline_test.go assertStopped": 1, + "internal/core/implement/loop/sync_stall_test.go TestASyncMergeStoppedAtItsDeadlineIsUndone": 1, + "internal/core/landing/gate_test.go TestAPreflightPastItsBoundIsKilledWithItsGroup": 1, + "internal/core/machineload/read_context_darwin_test.go TestReadContextEndingStopsPS": 1, + "internal/core/matrix/hiddenrun_test.go TestATestRunPastItsDeadlineIsUnexaminedNeverFailed": 1, + "internal/core/matrix/scrub_test.go TestTheScrubIsLinearOnAdversarialText": 1, + "internal/core/runner/exec_test.go TestExecNamesTheStageThatFailed": 1, + "internal/core/runner/proc_held_test.go TestAStageThatLeavesAProcessHoldingItsOutputIsMarked": 1, + "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosed": 1, + "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosedOnAChildHoldingItsOutput": 1, + "internal/core/tools/runargv_regroup_test.go TestRunArgvBoundHoldsAgainstAReGroupedDescendant": 1, + "internal/core/tools/tools_test.go TestRunArgvKillsItsOwnGroupOnTimeout": 1, + "internal/gitutil/net_ssh_test.go TestTheSSHCommandsReadEndsWithItsContext": 1, + "internal/gitutil/waitdelay_test.go TestRootCommitContextEndsAtItsDeadlineWhileTheOutputStaysOpen": 1, + "internal/procgroup/run_test.go TestRunToEOFDrainsAndReportsAWriterThatFails": 1, + "internal/procgroup/run_test.go TestRunToEOFEndsAtTheContextWhileAPipeIsHeld": 1, + "internal/procgroup/run_test.go TestRunToEOFStopsACommandThatHangs": 1, + "internal/surface/cli/ahoy_worktree_test.go TestAhoyWorktreeAddStopsACheckoutPastItsBound": 1, + "internal/surface/cli/drain_drive_update_test.go TestTheRehearsalRunsTheCandidateReadOnlyWithABound": 1, + "internal/surface/cli/hook_stop_test.go TestHookStopBudgetFailsOpen": 1, + "internal/surface/cli/status_hook_test.go TestThePromptHookReturnsInsideItsSecond": 1, + "internal/surface/session/server_bounds_test.go TestAClosedConnectionStopsItsReplay": 1, + "internal/surface/session/server_bounds_test.go TestAReplayHasATimeBound": 1, +} + +// timeUnits are the time package's duration constants. +var timeUnits = map[string]bool{"Nanosecond": true, "Microsecond": true, "Millisecond": true, "Second": true, "Minute": true, "Hour": true} + +// wallClockBounds returns the wall-clock bounds in the test files of the +// package directory dir, as "/ " keys with their counts. +func wallClockBounds(t *testing.T, dir, rel string) map[string]int { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + consts := map[string]bool{} + var tests []*ast.File + var names []string + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") { + continue + } + f, err := parser.ParseFile(fset, filepath.Join(dir, e.Name()), nil, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range f.Decls { + if g, ok := d.(*ast.GenDecl); ok && g.Tok == token.CONST { + for _, s := range g.Specs { + for _, n := range s.(*ast.ValueSpec).Names { + consts[n.Name] = true + } + } + } + } + if strings.HasSuffix(e.Name(), "_test.go") { + tests, names = append(tests, f), append(names, e.Name()) + } + } + hits := map[string]int{} + for i, f := range tests { + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + if n := len(boundsIn(fn.Body, consts)); n > 0 { + hits[rel+"/"+names[i]+" "+fn.Name.Name] += n + } + } + } + return hits +} + +// boundsIn returns each comparison in body of an elapsed wall-clock time with a +// constant duration. +func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { + elapsed := map[string]bool{} + ast.Inspect(body, func(n ast.Node) bool { + if a, ok := n.(*ast.AssignStmt); ok && len(a.Lhs) == len(a.Rhs) { + for i, r := range a.Rhs { + if id, ok := a.Lhs[i].(*ast.Ident); ok && isElapsed(r, nil) { + elapsed[id.Name] = true + } + } + } + return true + }) + // Only an upper bound: a slow runner lengthens what is measured, so a + // lower one (`took < d`) it can never fail. + var out []*ast.BinaryExpr + ast.Inspect(body, func(n ast.Node) bool { + b, ok := n.(*ast.BinaryExpr) + if !ok { + return true + } + over := (b.Op == token.GTR || b.Op == token.GEQ) && isElapsed(b.X, elapsed) && isConstDuration(b.Y, consts) + under := (b.Op == token.LSS || b.Op == token.LEQ) && isElapsed(b.Y, elapsed) && isConstDuration(b.X, consts) + if over || under { + out = append(out, b) + } + return true + }) + return out +} + +// isElapsed reports whether e is a wall-clock time since a moment: a call of +// time.Since, time.Now().Sub, or a name in vars assigned from one. +func isElapsed(e ast.Expr, vars map[string]bool) bool { + switch x := e.(type) { + case *ast.ParenExpr: + return isElapsed(x.X, vars) + case *ast.Ident: + return vars[x.Name] + case *ast.CallExpr: + sel, ok := x.Fun.(*ast.SelectorExpr) + if !ok { + return false + } + if isPkgSel(sel, "time", "Since") { + return true + } + if now, ok := sel.X.(*ast.CallExpr); ok && sel.Sel.Name == "Sub" { + if s, ok := now.Fun.(*ast.SelectorExpr); ok && isPkgSel(s, "time", "Now") { + return true + } + } + } + return false +} + +// isConstDuration reports whether e is a constant duration: built of numeric +// literals, the time package's units, the package's own constants and +// time.Duration conversions, with at least one unit or constant in it. +func isConstDuration(e ast.Expr, consts map[string]bool) bool { + ok, named := true, false + ast.Inspect(e, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + if isPkgSel(x, "time", "") && timeUnits[x.Sel.Name] { + named = true + } else if !isPkgSel(x, "time", "Duration") { + ok = false + } + return false + case *ast.CallExpr: + if s, isSel := x.Fun.(*ast.SelectorExpr); !isSel || !isPkgSel(s, "time", "Duration") { + ok = false + return false + } + case *ast.Ident: + if !consts[x.Name] { + ok = false + } + named = true + } + return ok + }) + return ok && named +} + +// isPkgSel reports whether sel is pkg.name, or pkg.anything when name is "". +func isPkgSel(sel *ast.SelectorExpr, pkg, name string) bool { + id, ok := sel.X.(*ast.Ident) + return ok && id.Name == pkg && (name == "" || sel.Sel.Name == name) +} + +// TestTheWallClockAuditReadsEachShape: the scan finds an upper bound on +// time.Since itself, on a variable taken from it and on time.Now().Sub, +// against a unit literal, a constant and a conversion, written either way +// round; and it passes a bound held through a helper, one read off another +// clock, one against a measured value and a lower bound. +func TestTheWallClockAuditReadsEachShape(t *testing.T) { + dir := t.TempDir() + src := `package x + +import ( + "testing" + "time" +) + +const budget = 2 * time.Second + +func TestFlagged(t *testing.T) { + start := time.Now() + if time.Since(start) > 5*time.Second { + } + took := time.Since(start) + if took > budget { + } + if time.Now().Sub(start) >= time.Duration(3)*time.Second { + } + if 300*time.Millisecond < took { + } +} + +func TestPassed(t *testing.T) { + start := time.Now() + took := time.Since(start) + reference := time.Since(start) + if took > 2*reference { + } + cpu := clock() - 0 + if cpu > 5*time.Second { + } + if took > limit(reference) { + } + if took < 5*time.Second { + } + if 300*time.Millisecond > time.Since(start) { + } +} + +func clock() time.Duration { return 0 } +func limit(d time.Duration) time.Duration { return d } +` + if err := os.WriteFile(filepath.Join(dir, "x_test.go"), []byte(src), 0o600); err != nil { + t.Fatal(err) + } + got := wallClockBounds(t, dir, "x") + want := map[string]int{"x/x_test.go TestFlagged": 4} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("the scan found %v, want %v", got, want) + } +} + +// TestNoNewWallClockBound: no test outside internal/testtiming holds a +// wall-clock time to a constant beyond the bounds wallClockBaseline lists, and +// each listed one is still there. +func TestNoNewWallClockBound(t *testing.T) { + root := filepath.Join("..", "..", "..") + got := map[string]int{} + for _, top := range []string{"internal", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if !d.IsDir() { + return nil + } + if name := d.Name(); name == "testdata" || strings.HasPrefix(name, ".") { + return filepath.SkipDir + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + if rel == "internal/testtiming" { + return filepath.SkipDir + } + for k, n := range wallClockBounds(t, path, rel) { + got[k] = n + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + keys := map[string]bool{} + for k := range got { + keys[k] = true + } + for k := range wallClockBaseline { + keys[k] = true + } + var added, dropped []string + for k := range keys { + switch n, was := got[k], wallClockBaseline[k]; { + case n > was: + added = append(added, fmt.Sprintf("%s: %d wall-clock bound(s), %d listed", k, n, was)) + case n < was: + dropped = append(dropped, fmt.Sprintf("%q: %d,", k, n)) + } + } + sort.Strings(added) + sort.Strings(dropped) + if len(added) > 0 { + t.Errorf("a test holds a wall-clock time to a constant, which a slow runner fails (iss-2612022218392055); "+ + "judge it through internal/testtiming (a Bound on a reference measured beside it, CutShort against the work it ends, "+ + "Await for a sign rather than a sleep):\n %s", strings.Join(added, "\n ")) + } + if len(dropped) > 0 { + t.Errorf("wallClockBaseline lists more bounds than these functions hold; set each to what is left (0 removes it):\n %s", + strings.Join(dropped, "\n ")) + } +} From a980eae1afdedbaa1dcdbd7e343af4ac7247933e Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:37:56 +0000 Subject: [PATCH 06/11] test: count a bound held to a function-local constant in the wall-clock audit The correctness review of 58c84da10 found the audit blind to a bound held to a constant the test function declares itself: consts was filled only from file-level declarations, so `const budget = time.Second` inside a test and `took >= budget` passed, and moving a listed constant into its function took the bound off the list with the bound still there. Three such bounds were in the tree and unlisted. boundsIn now reads the function's own constants as it reads the package's (withLocalConsts): each name a const declaration in the body declares, and each variable whose every assignment, `:=`, `=` or `var`, is a constant duration, in the order written, so one built from another counts; a variable also given anything else, stepped or ranged over is not constant. TestTheWallClockAuditReadsEachShape gains a function with each of the three shapes and a passed variable also given a measured value. The baseline grows once, here, from 48 bounds to 52 in 51 functions: landing's TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs (10s) and a second bound in cli's TestThePromptHookReturnsInsideItsSecond (5s), which the review named, and two it did not: claim's TestPushHonoursCallerContext (a second and 6s of grace and margin) and spotcheck's writeCutOff (a local sum of package constants). promptlog_reap_test.go held the record to its own one-second deadline, which left a loaded runner the half second after the scan's stop to clean up, write and return in. The scan now keeps the deadline it was given, and the test reads it, not times it: it must be before the record's. The scan ends on its own after a minute, and the record is judged by CutShort of that minute, so a record that stops nothing still fails. No reproduction was possible: the old bound does not fail on demand, and a starved run was not made on a machine already at three to five times its cores' load. The audit's blind spot for a fixed budget waited out, a select on time.After() or a time.Now().Add() poll loop, which the security review named, is recorded in dcn-2612022337510454 rather than taught here: 378 such calls in 191 test files, most fixture dates or deadlines far past the work, which syntax does not tell from a budget. The audit's header names it. Red before green, through the narrow load gate: the new shapes run through a throwaway copy of the audit as 58c84da10 had it found TestFlagged's 4 and none of TestFlaggedLocally's 3, and failed; the new audit found both and passed. On the tree, the new audit named exactly the four bounds above, and nothing else, until they were listed. TestPermissionPromptRecordWaitsForAStoppedScan passes (0.62s). Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...ss-2612022218392055-is-resolved-without.md | 2 + internal/core/autonomy/promptlog_reap_test.go | 47 ++++-- internal/core/lint/wallclock_audit_test.go | 145 +++++++++++++++--- 3 files changed, 163 insertions(+), 31 deletions(-) diff --git a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md index 4c4e7e4a1e..24dcaffbb7 100644 --- a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md +++ b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md @@ -4,3 +4,5 @@ slug: iss-2612022218392055-is-resolved-without date: 2026-12-02 --- 2026-12-02 — iss-2612022218392055 is resolved without two parts of its remedy, each deferred: the starved lane (go test -race under GOMAXPROCS=3 over the packages the flake census names) and the audit's second half, which would flag a fake clock that reads time.Now. What is done: internal/testtiming, the fixes of the census's ten worst bounds, of its two sibling stand-in clocks and of the one confirmed flake still open, and the audit TestNoNewWallClockBound in internal/core/lint, which lists the 48 wall-clock bounds left by function, so none can be added and each one fixed must be struck off; the census rows 11 to 18 that are bounds are among them, and its fixed sleeps and short contexts (rows 11, 17 and 18) the audit cannot see. Grounds: the lane adds hosted-runner time to every CI run, a cost for the person to approve, and its shape should follow the macOS shard split still in flight; a fake that reads the real clock cannot be told by its syntax from a fixture that rightly dates a file, so that check needs a declared list of fakes, more than the hour step 5 allowed, and the two live cases the census found (fixtureworld, livework) are fixed. To reverse: capture either part as its own issue, or add the lane to ci.yml as a job running go test -race with GOMAXPROCS=3 over the census's packages. + +Amended after the review of 58c84da10: the audit now also counts a bound held to a constant the function declares itself, or to a variable only ever given a constant duration, so moving a listed constant into its function no longer takes it off the list; the baseline grew once, at that change, from 48 bounds to 52 in 51 functions (claim's TestPushHonoursCallerContext, landing's TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs, spotcheck's writeCutOff and a second bound in cli's TestThePromptHookReturnsInsideItsSecond), and promptlog_reap's one-second bound equal to its own deadline was fixed through testtiming instead of listed. A third part stays deferred: the audit does not see a fixed budget a test waits out rather than measures, a select on time.After() or a poll loop until time.Now().Add(), three of which this change itself leaves (terminal_test.go's 15s turn, precheck-audits' 20s leader wait, testreuse's 30s). Grounds: there are 121 time.After and 257 time.Now().Add calls in 191 test files, most a fixture's date or a failure deadline far past the work, and syntax does not tell a budget from either, so teaching the audit them is a data-flow change and a baseline several times this one's, not the small change this round allows. To reverse: capture it as its own issue, and teach boundsIn a time.After or time.Now().Add whose argument isConstDuration and which ends a wait the test fails on. diff --git a/internal/core/autonomy/promptlog_reap_test.go b/internal/core/autonomy/promptlog_reap_test.go index 67edc288c3..ec88d76a1d 100644 --- a/internal/core/autonomy/promptlog_reap_test.go +++ b/internal/core/autonomy/promptlog_reap_test.go @@ -10,12 +10,20 @@ import ( "github.com/intentdriven/abcd/internal/adapter/scanner" "github.com/intentdriven/abcd/internal/adapter/scanner/augmenttest" "github.com/intentdriven/abcd/internal/termsafe" + "github.com/intentdriven/abcd/internal/testtiming" ) -// cleaningAug is a secret scan that never finishes on its own and, once told -// to stop, takes a moment to clean up after itself before it returns, as the -// gitleaks run removes its scratch directory after its process is killed. -type cleaningAug struct{ cleaned atomic.Bool } +// scanStall is how long cleaningAug's scan runs when nothing tells it to stop. +const scanStall = time.Minute + +// cleaningAug is a secret scan that does not finish on its own for a minute +// and, once told to stop, takes a moment to clean up after itself before it +// returns, as the gitleaks run removes its scratch directory after its process +// is killed. It keeps the deadline it was given. +type cleaningAug struct { + cleaned atomic.Bool + stopBy atomic.Int64 // the scan's deadline in Unix nanoseconds, 0 for none +} func (a *cleaningAug) Available() error { return nil } @@ -24,7 +32,13 @@ func (a *cleaningAug) Scan(text, file string) []scanner.Finding { } func (a *cleaningAug) ScanContext(ctx context.Context, text, file string) []scanner.Finding { - <-ctx.Done() + if d, ok := ctx.Deadline(); ok { + a.stopBy.Store(d.UnixNano()) + } + select { + case <-ctx.Done(): + case <-time.After(scanStall): + } time.Sleep(50 * time.Millisecond) a.cleaned.Store(true) return nil @@ -32,15 +46,23 @@ func (a *cleaningAug) ScanContext(ctx context.Context, text, file string) []scan // TestPermissionPromptRecordWaitsForAStoppedScan: the scan is told to stop // before the record's own deadline, and the record waits for it to return, -// cleaned up, before it writes the line, still within the deadline. The -// command is recorded by its length. +// cleaned up, before it writes the line. The command is recorded by its +// length. +// +// The deadline the scan was given is read, not timed, and the record is judged +// against the minute a scan nothing stopped would run (testtiming.CutShort): a +// bound of the one-second deadline itself left a loaded runner the half second +// after the scan's stop to clean up, write and return in +// (iss-2612022218392055). That the record ends by its deadline is its context's +// to keep; what this test holds is that it stops the scan in time to wait for +// it. func TestPermissionPromptRecordWaitsForAStoppedScan(t *testing.T) { root, _ := managedCopy(t) a := &cleaningAug{} augmenttest.Install(t, a) - const budget = time.Second - ctx, cancel := context.WithTimeout(context.Background(), budget) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() + deadline, _ := ctx.Deadline() const command = "echo a command the scan does not finish" start := time.Now() err := RecordPermissionPrompt(ctx, root, PermissionPrompt{Decision: PermissionDecisionNone, Command: command}, time.Now()) @@ -48,8 +70,11 @@ func TestPermissionPromptRecordWaitsForAStoppedScan(t *testing.T) { if !a.cleaned.Load() { t.Error("the record returned before the stopped scan had cleaned up") } - if took >= budget { - t.Errorf("the record took %s, past its %s deadline", took, budget) + if by := a.stopBy.Load(); by == 0 || !time.Unix(0, by).Before(deadline) { + t.Errorf("the scan was told to stop at %s, not before the record's deadline %s", time.Unix(0, by).Format(time.StampMilli), deadline.Format(time.StampMilli)) + } + if err := testtiming.CutShort.Check("the record with a scan nothing stopped", took, scanStall); err != nil { + t.Error(err) } if !errors.Is(err, ErrRedactionBudget) { t.Errorf("err = %v, want ErrRedactionBudget", err) diff --git a/internal/core/lint/wallclock_audit_test.go b/internal/core/lint/wallclock_audit_test.go index 88d2e4ffc3..da10bd24b0 100644 --- a/internal/core/lint/wallclock_audit_test.go +++ b/internal/core/lint/wallclock_audit_test.go @@ -22,14 +22,18 @@ import ( // each test file under internal/ and cmd/ and finds every upper bound on an // elapsed wall-clock time (time.Since, time.Now().Sub, or a variable assigned // from one) that is a constant duration (unit literals, constants and -// time.Duration conversions of them). The bounds written before the audit are -// wallClockBaseline, by file and function; a new one, or one more in a listed -// function, fails here, and a listed one fixed fails here until the baseline -// drops it, so the list only shrinks. +// time.Duration conversions of them, the constants and constant-valued +// variables declared inside the function included). The bounds written before +// the audit are wallClockBaseline, by file and function; a new one, or one more +// in a listed function, fails here, and a listed one fixed fails here until the +// baseline drops it, so the list only shrinks. // // It does not see a constant passed through a helper (a `slack(d)`), a bound -// read off the CPU clock, which load does not inflate, or a fixed sleep used as -// a hand-off; those stay a reviewer's to catch. +// read off the CPU clock, which load does not inflate, a fixed sleep used as a +// hand-off, or a fixed budget a test waits out rather than measures: a select +// on time.After(), or a poll loop until time.Now().Add(). +// Those stay a reviewer's to catch (dcn-2612022337510454 says why the last two +// are not audited). // wallClockBaseline is how many wall-clock bounds each function held when the // audit came in, after the census's ten worst were moved to testtiming. Each @@ -49,6 +53,7 @@ var wallClockBaseline = map[string]int{ "internal/core/autonomy/session_tracked_test.go TestAReservationsReadTheDeadlineEndsIsMarkedCutShort": 1, "internal/core/cite/fetch_test.go TestCheckTimesOutAsAnOutcome": 1, "internal/core/claim/generatedcache_test.go TestAKeptReadWithNoContextIsBounded": 1, + "internal/core/claim/spotcheck_push_test.go TestPushHonoursCallerContext": 1, "internal/core/claim/status_pushers_test.go TestEachForgeLookupEndsAtTheBudget": 1, "internal/core/claim/viewctx_test.go TestABoundTipReadOnItsOwnStopsAHungGit": 1, "internal/core/claim/viewctx_test.go TestATipReadItsDeadlineEndsIsNoObjectTooBig": 1, @@ -64,11 +69,13 @@ var wallClockBaseline = map[string]int{ "internal/core/implement/loop/pickgit_deadline_test.go assertStopped": 1, "internal/core/implement/loop/sync_stall_test.go TestASyncMergeStoppedAtItsDeadlineIsUndone": 1, "internal/core/landing/gate_test.go TestAPreflightPastItsBoundIsKilledWithItsGroup": 1, + "internal/core/landing/receipt_context_test.go TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs": 1, "internal/core/machineload/read_context_darwin_test.go TestReadContextEndingStopsPS": 1, "internal/core/matrix/hiddenrun_test.go TestATestRunPastItsDeadlineIsUnexaminedNeverFailed": 1, "internal/core/matrix/scrub_test.go TestTheScrubIsLinearOnAdversarialText": 1, "internal/core/runner/exec_test.go TestExecNamesTheStageThatFailed": 1, "internal/core/runner/proc_held_test.go TestAStageThatLeavesAProcessHoldingItsOutputIsMarked": 1, + "internal/core/spotcheck/store_test.go writeCutOff": 1, "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosed": 1, "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosedOnAChildHoldingItsOutput": 1, "internal/core/tools/runargv_regroup_test.go TestRunArgvBoundHoldsAgainstAReGroupedDescendant": 1, @@ -81,7 +88,7 @@ var wallClockBaseline = map[string]int{ "internal/surface/cli/ahoy_worktree_test.go TestAhoyWorktreeAddStopsACheckoutPastItsBound": 1, "internal/surface/cli/drain_drive_update_test.go TestTheRehearsalRunsTheCandidateReadOnlyWithABound": 1, "internal/surface/cli/hook_stop_test.go TestHookStopBudgetFailsOpen": 1, - "internal/surface/cli/status_hook_test.go TestThePromptHookReturnsInsideItsSecond": 1, + "internal/surface/cli/status_hook_test.go TestThePromptHookReturnsInsideItsSecond": 2, "internal/surface/session/server_bounds_test.go TestAClosedConnectionStopsItsReplay": 1, "internal/surface/session/server_bounds_test.go TestAReplayHasATimeBound": 1, } @@ -138,8 +145,10 @@ func wallClockBounds(t *testing.T, dir, rel string) map[string]int { } // boundsIn returns each comparison in body of an elapsed wall-clock time with a -// constant duration. +// constant duration, the constants body declares for itself among them +// (withLocalConsts). func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { + consts = withLocalConsts(body, consts) elapsed := map[string]bool{} ast.Inspect(body, func(n ast.Node) bool { if a, ok := n.(*ast.AssignStmt); ok && len(a.Lhs) == len(a.Rhs) { @@ -169,6 +178,77 @@ func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { return out } +// withLocalConsts is consts and the names body holds constant itself: each name +// a const declaration in it declares, and each variable whose every assignment +// in it, `:=`, `=` or `var`, is a constant duration, read in the order they are +// written so that one built from another counts. A bound held to a constant +// declared inside its function is the same bound as one declared beside it, and +// moving the constant in must not take it off the baseline. A variable also +// assigned anything else, stepped, or ranged over is not constant. +func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]bool { + all := make(map[string]bool, len(consts)) + for k := range consts { + all[k] = true + } + declared, varied := map[string]bool{}, map[string]bool{} + assign := func(e ast.Expr, rhs ast.Expr) { + id, ok := e.(*ast.Ident) + if !ok || id.Name == "_" { + return + } + if rhs != nil && isConstDuration(rhs, all) { + all[id.Name] = true + } else { + varied[id.Name] = true + } + } + ast.Inspect(body, func(n ast.Node) bool { + switch s := n.(type) { + case *ast.GenDecl: + for _, spec := range s.Specs { + v, ok := spec.(*ast.ValueSpec) + if !ok { + continue + } + for i, name := range v.Names { + switch { + case s.Tok == token.CONST: + all[name.Name], declared[name.Name] = true, true + case len(v.Values) == len(v.Names): + assign(name, v.Values[i]) + default: + assign(name, nil) + } + } + } + case *ast.AssignStmt: + for i, l := range s.Lhs { + if (s.Tok == token.DEFINE || s.Tok == token.ASSIGN) && len(s.Lhs) == len(s.Rhs) { + assign(l, s.Rhs[i]) + } else { + assign(l, nil) + } + } + case *ast.IncDecStmt: + assign(s.X, nil) + case *ast.RangeStmt: + if s.Key != nil { + assign(s.Key, nil) + } + if s.Value != nil { + assign(s.Value, nil) + } + } + return true + }) + for name := range varied { + if !declared[name] { + delete(all, name) + } + } + return all +} + // isElapsed reports whether e is a wall-clock time since a moment: a call of // time.Since, time.Now().Sub, or a name in vars assigned from one. func isElapsed(e ast.Expr, vars map[string]bool) bool { @@ -233,11 +313,25 @@ func isPkgSel(sel *ast.SelectorExpr, pkg, name string) bool { // TestTheWallClockAuditReadsEachShape: the scan finds an upper bound on // time.Since itself, on a variable taken from it and on time.Now().Sub, // against a unit literal, a constant and a conversion, written either way -// round; and it passes a bound held through a helper, one read off another -// clock, one against a measured value and a lower bound. +// round, and against a constant or a constant-valued variable the function +// declares itself; and it passes a bound held through a helper, one read off +// another clock, one against a measured value, one against a variable that +// is also given a measured value, and a lower bound. func TestTheWallClockAuditReadsEachShape(t *testing.T) { dir := t.TempDir() - src := `package x + if err := os.WriteFile(filepath.Join(dir, "x_test.go"), []byte(wallClockShapes), 0o600); err != nil { + t.Fatal(err) + } + got := wallClockBounds(t, dir, "x") + want := map[string]int{"x/x_test.go TestFlagged": 4, "x/x_test.go TestFlaggedLocally": 3} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("the scan found %v, want %v", got, want) + } +} + +// wallClockShapes is TestTheWallClockAuditReadsEachShape's package: each shape +// the audit flags, and each it passes. +const wallClockShapes = `package x import ( "testing" @@ -259,6 +353,20 @@ func TestFlagged(t *testing.T) { } } +func TestFlaggedLocally(t *testing.T) { + const ceiling = time.Second + twice := 2 * ceiling + var stall = time.Minute + start := time.Now() + took := time.Since(start) + if took >= ceiling { + } + if took > twice { + } + if stall/2 < time.Since(start) { + } +} + func TestPassed(t *testing.T) { start := time.Now() took := time.Since(start) @@ -274,20 +382,17 @@ func TestPassed(t *testing.T) { } if 300*time.Millisecond > time.Since(start) { } + allowed := 2 * time.Second + if reference > allowed { + allowed = 2 * reference + } + if took > allowed { + } } func clock() time.Duration { return 0 } func limit(d time.Duration) time.Duration { return d } ` - if err := os.WriteFile(filepath.Join(dir, "x_test.go"), []byte(src), 0o600); err != nil { - t.Fatal(err) - } - got := wallClockBounds(t, dir, "x") - want := map[string]int{"x/x_test.go TestFlagged": 4} - if fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("the scan found %v, want %v", got, want) - } -} // TestNoNewWallClockBound: no test outside internal/testtiming holds a // wall-clock time to a constant beyond the bounds wallClockBaseline lists, and From 6fefbcfa2642ba550ea8a3b1a96c2d2e045a2ae9 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:38:02 +0000 Subject: [PATCH 07/11] test: keep the old limits as floors where a ratio alone was tighter The correctness review of 58c84da10 found three rewrites that judged a run by a ratio of a reference with a floor under the bound they replaced, so a stall a loaded runner puts in one call could fail correct code the old bound passed: - runner gatewait_test.go, TestTheGateCreditIsBounded: the held run at 2.5 times a no-wait run allowed about 1.3s where LongestRun and 2s allowed 3s, and one start or kill held up 0.3s longer than the other failed it. The floor is now LongestRun(bound) + 2s; a credit never ended still runs the sleep's minute. - sessionname register_test.go: naming under each failure keeps the 1.5s it was allowed before as its floor, in place of 1s. - loop widen_paths_test.go: the refusal keeps 2s and the dedup 4s as floors, in place of 1s each. Each regression these tests exist for is still far over its floor: a gate credit never ended (a minute), a held lock waited out at its two second default, a refusal or dedup that compares every path with every other (ten thousand passes). dcn-2612022252475157 names the cost the security review left as designed: an "ends at its deadline" test judged by CutShort of a minute no longer catches a slip of up to about 29s. No reproduction was possible: a stall in one call does not come on demand, and a starved run was not made on a machine already at two to four times its cores' load. Through the narrow load gate, TestTheGateCreditIsBounded passes (1.52s). Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...2475157-a-test-judges-how-long-something-took.md | 2 ++ internal/core/implement/loop/widen_paths_test.go | 8 +++++--- internal/core/runner/gatewait_test.go | 13 +++++++------ internal/core/sessionname/register_test.go | 9 +++++---- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md b/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md index 63f5f1cdaf..8e830da87f 100644 --- a/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md +++ b/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md @@ -4,3 +4,5 @@ slug: a-test-judges-how-long-something-took date: 2026-12-02 --- 2026-12-02 — A test judges how long something took through internal/testtiming, a new standard-library leaf imported only by tests: a Bound holds a measured run to a ratio of a reference measured in the same run and never under a floor, CutShort judges a run a context or kill ends against the work it ended, and CPU is the one process CPU clock. Grounds (iss-2612022218392055): no shared helper existed; the ratio-and-floor judgement lived inside lint's scalesLinearly, and the CPU clock was copied three times (core/reading, surface/cli, implement/loop), so one-canonical-primitive forbids a further copy and gittest, the other shared test package, is git's. Those copies now call it. To reverse: inline Bound.Limit back into scalesLinearly and the processCPU and cpuTime copies, and delete the package; nothing outside tests imports it. + +Accepted cost (security review of 58c84da10): CutShort is half the work it judges a run against, and every such work in the census's conversions is a minute, so each test that held a run to ending at its deadline within 2 to 20s now passes any return under 30s; a kill, deadline or grace that slips late by up to about 29s is no longer caught there, only one that waits the work out, and a wait that runs out (Await) takes three quarters of the binary's remaining time before it fails. diff --git a/internal/core/implement/loop/widen_paths_test.go b/internal/core/implement/loop/widen_paths_test.go index 854fb24d25..1b027f4d9d 100644 --- a/internal/core/implement/loop/widen_paths_test.go +++ b/internal/core/implement/loop/widen_paths_test.go @@ -65,16 +65,18 @@ func TestAWideningOfVeryManyPathsIsRefusedAtOnce(t *testing.T) { // one machine and flaked on slower ones (iss-2612022218392055). The // refusal compares no more than maxWidenPaths of the paths, under a tenth // of them; deduplicating all of them is ten such passes and the sort's - // share, where comparing each path with every other is ten thousand. + // share, where comparing each path with every other is ten thousand. Each + // keeps the bound it had before as its floor, two seconds and four, so a + // stall a loaded runner puts in one call is not taken for the fault. tenth := time.Now() if _, err := widenPaths("lane-1", want[:len(want)/10]); err != nil { t.Fatal(err) } reference := time.Since(tenth) - if err := (testtiming.Bound{Ratio: 1, Floor: time.Second}).Check("the refusal, which comes at once rather than after comparing every path,", took, reference); err != nil { + if err := (testtiming.Bound{Ratio: 1, Floor: 2 * time.Second}).Check("the refusal, which comes at once rather than after comparing every path,", took, reference); err != nil { t.Fatal(err) } - if err := (testtiming.Bound{Ratio: 30, Floor: time.Second}).Check("deduplicating the paths, no more than a pass over them,", onePass, reference); err != nil { + if err := (testtiming.Bound{Ratio: 30, Floor: 4 * time.Second}).Check("deduplicating the paths, no more than a pass over them,", onePass, reference); err != nil { t.Fatal(err) } } diff --git a/internal/core/runner/gatewait_test.go b/internal/core/runner/gatewait_test.go index ef49585fbe..68853b875a 100644 --- a/internal/core/runner/gatewait_test.go +++ b/internal/core/runner/gatewait_test.go @@ -80,11 +80,12 @@ func TestARunNotWaitingAtTheGateIsKilledAtItsBound(t *testing.T) { // // The run is judged against the same run with no wait, killed at its bound, // timed beside it: what a slow runner adds to starting and killing the process -// it adds to both, where a fixed two seconds of slack was a guess at it -// (iss-2612022218392055). The waited run lasts LongestRun, the bound and the -// credit, so it may take that many times the reference and half the reference -// again for the gate's polls; a credit never ended runs the sleep's whole -// minute, far over it. +// it adds to both (iss-2612022218392055). The waited run lasts LongestRun, the +// bound and the credit, so it may take that many times the reference and half +// the reference again for the gate's polls, and never less than LongestRun and +// the two seconds the test allowed before: one start or kill a loaded runner +// holds up a few hundred milliseconds longer than the other must not fail it. +// A credit never ended runs the sleep's whole minute, far over either. func TestTheGateCreditIsBounded(t *testing.T) { const bound = 500 * time.Millisecond l, bin := sleepLauncher(t, func(int) bool { return false }) @@ -101,7 +102,7 @@ func TestTheGateCreditIsBounded(t *testing.T) { if !errors.Is(err, ErrKilled) { t.Fatalf("err = %v, want a kill", err) } - longest := testtiming.Bound{Ratio: float64(LongestRun(bound))/float64(bound) + 0.5} + longest := testtiming.Bound{Ratio: float64(LongestRun(bound))/float64(bound) + 0.5, Floor: LongestRun(bound) + 2*time.Second} if err := longest.Check("the run held at the gate", took, reference); err != nil { t.Errorf("%v: past its longest (%s)", err, LongestRun(bound)) } diff --git a/internal/core/sessionname/register_test.go b/internal/core/sessionname/register_test.go index 9a671a1e03..9c440bc027 100644 --- a/internal/core/sessionname/register_test.go +++ b/internal/core/sessionname/register_test.go @@ -690,9 +690,10 @@ func TestNamingNeverFailsASession(t *testing.T) { // Each failure is judged against a start that names a session, // timed beside it, not against a constant a slow runner can // pass (iss-2612022218392055): it may take twice as long, and - // never less than a second, so the held lock's case waiting - // out the default two seconds in place of its own tenth of one - // is still over it wherever a clean start takes under a second. + // never less than the second and a half it was allowed before, + // so the held lock's case waiting out the default two seconds + // in place of its own tenth of one is still over it wherever a + // clean start takes under a second. clean := newMachine(t) began := time.Now() if out := clean.start(100, t.TempDir(), "a"); out.Name == "" { @@ -703,7 +704,7 @@ func TestNamingNeverFailsASession(t *testing.T) { c.arrange(t, m) began = time.Now() out := m.start(100, t.TempDir(), "a") - if err := (testtiming.Bound{Ratio: 2, Floor: time.Second}).Check("naming", time.Since(began), reference); err != nil { + if err := (testtiming.Bound{Ratio: 2, Floor: 1500 * time.Millisecond}).Check("naming", time.Since(began), reference); err != nil { t.Fatal(err) } if out.Name != "" || len(out.Notes) != 1 { From 148bbc095b7d2fdbf2b3af166118b4bc5963a685 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:36:29 +0000 Subject: [PATCH 08/11] test: count the package's own constants and variables in the wall-clock audit, however read Both reviews of 6fefbcfa2 found the audit's header claiming constants without limit where isConstDuration read only the package's own, bare: `took >= gitutil.StopGrace` in an external test package (bounded_unix_test.go, 5s, as long as the delay it detects) and `took > spotcheckNetTimeout+grace+margin` (claim remote_test.go), a package variable the test sets and puts back, were neither counted nor named. The audit now counts: - the package's constants and its variables declared with a constant duration, read bare or, from an external test package, through the package's name, its export_test files included; - a variable, the function's or the package's, whose every assignment in the function keeps it constant: a constant duration, a `var` with no value, a step by a constant (`limit *= 5`, `n++`), or a value put back from a copy taken while it was constant; - an elapsed time given by `var took = time.Since(...)`. A variable also given anything else, a value put back through a function's parameter included, is not constant. What the audit still does not read is listed in its header and in dcn-2612022337510454, shape by shape: another package's constant or variable (none in the tree is held as a bound), a struct field, parameter or call's result, a variable given anything but a constant, an elapsed time taken any other way (end.Sub(start) of two readings, which syntax does not tell from a fake clock's), the CPU clock by design, a fixed sleep as a hand-off, and a budget waited out on time.After or time.Now().Add. The fixture is now a package with an external test package beside it (wallclock_shapes_test.go), so a scratch copy can run it through an older audit. The baseline grows once, here, from 52 bounds to 55 in 54 functions: claim's TestTheSpotcheckFetchEndsAtItsBound (a package variable set and put back), loop's TestTheWaiterPassesOverARunWhoseLockIsHeld (ten times the package variable lockTimeout and 5s) and gitutil's TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot (gitutil.StopGrace from the external test package). No other selector form is held as a bound in the tree: a grep of every test file that takes time.Since or time.Now().Sub for a comparison with a package-qualified name found only gitutil.StopGrace. Red before green, through the narrow load gate: on a scratch copy at 6fefbcfa2, the new fixture through the audit as that head has it found TestFlagged's 4 and TestFlaggedLocally's 3, none of TestFlaggedStepped's 3 or TestFlaggedOutside's 2, and failed; on this tree it found all four and passed, and the scan of the tree named exactly the three functions above until they were listed. The resolved issue's resolution is brought in line: the count left and the three deferrals. Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...ss-2612022218392055-is-resolved-without.md | 2 + ...55-flaky-tests-share-one-pattern-a-test.md | 2 +- internal/core/lint/wallclock_audit_test.go | 294 ++++++++++-------- internal/core/lint/wallclock_shapes_test.go | 165 ++++++++++ 4 files changed, 340 insertions(+), 123 deletions(-) create mode 100644 internal/core/lint/wallclock_shapes_test.go diff --git a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md index 24dcaffbb7..8c24d5b1aa 100644 --- a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md +++ b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md @@ -6,3 +6,5 @@ date: 2026-12-02 2026-12-02 — iss-2612022218392055 is resolved without two parts of its remedy, each deferred: the starved lane (go test -race under GOMAXPROCS=3 over the packages the flake census names) and the audit's second half, which would flag a fake clock that reads time.Now. What is done: internal/testtiming, the fixes of the census's ten worst bounds, of its two sibling stand-in clocks and of the one confirmed flake still open, and the audit TestNoNewWallClockBound in internal/core/lint, which lists the 48 wall-clock bounds left by function, so none can be added and each one fixed must be struck off; the census rows 11 to 18 that are bounds are among them, and its fixed sleeps and short contexts (rows 11, 17 and 18) the audit cannot see. Grounds: the lane adds hosted-runner time to every CI run, a cost for the person to approve, and its shape should follow the macOS shard split still in flight; a fake that reads the real clock cannot be told by its syntax from a fixture that rightly dates a file, so that check needs a declared list of fakes, more than the hour step 5 allowed, and the two live cases the census found (fixtureworld, livework) are fixed. To reverse: capture either part as its own issue, or add the lane to ci.yml as a job running go test -race with GOMAXPROCS=3 over the census's packages. Amended after the review of 58c84da10: the audit now also counts a bound held to a constant the function declares itself, or to a variable only ever given a constant duration, so moving a listed constant into its function no longer takes it off the list; the baseline grew once, at that change, from 48 bounds to 52 in 51 functions (claim's TestPushHonoursCallerContext, landing's TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs, spotcheck's writeCutOff and a second bound in cli's TestThePromptHookReturnsInsideItsSecond), and promptlog_reap's one-second bound equal to its own deadline was fixed through testtiming instead of listed. A third part stays deferred: the audit does not see a fixed budget a test waits out rather than measures, a select on time.After() or a poll loop until time.Now().Add(), three of which this change itself leaves (terminal_test.go's 15s turn, precheck-audits' 20s leader wait, testreuse's 30s). Grounds: there are 121 time.After and 257 time.Now().Add calls in 191 test files, most a fixture's date or a failure deadline far past the work, and syntax does not tell a budget from either, so teaching the audit them is a data-flow change and a baseline several times this one's, not the small change this round allows. To reverse: capture it as its own issue, and teach boundsIn a time.After or time.Now().Add whose argument isConstDuration and which ends a wait the test fails on. + +Amended after the reviews of 6fefbcfa2: the audit also counts the package's own constants and its variables declared with a constant duration (which a test may set to another and put back), read bare or, from an external test package, through the package's name; a variable stepped by a constant or declared with no value and then given constants; and an elapsed time given by `var`. The baseline grew once more, at that change, from 52 bounds to 55 in 54 functions (claim's TestTheSpotcheckFetchEndsAtItsBound, loop's TestTheWaiterPassesOverARunWhoseLockIsHeld and gitutil's TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot). What the audit still does not read, each a reviewer's to catch and each deferred on the grounds above (syntax does not settle it without type or data-flow information, or no live case asks for it): a constant or variable of another package, none of which the tree holds as a bound; a bound held to a struct field, a parameter or a function's result, such as claim's slack(d); a variable the function also gives anything but a constant duration, a value put back through a function's parameter included, or a package variable declared with anything else; an elapsed time taken any other way, such as end.Sub(start) of two readings, which syntax does not tell from a fake clock's difference; a bound read off the CPU clock, by design; a fixed sleep used as a hand-off; and a fixed budget waited out on time.After or time.Now().Add, the third deferral above. The audit's header lists the same shapes. diff --git a/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md index 4d982d2d96..9092b70aa1 100644 --- a/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md +++ b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md @@ -10,7 +10,7 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/implement/loop" remedy: "a test audit that flags a wall-clock assertion (an elapsed time compared with a constant, a fake that reads time.Now) outside one shared helper that judges a ratio against a floor; a flake census of the last 60 days of CI failures, each remaining case fixed or recorded; and a starved lane (GOMAXPROCS=3 with -race, the hosted macOS runner's shape) for the packages the census names" -resolution: "A test judges how long something took through internal/testtiming (Bound, CutShort, CPU, Await, AwaitWithin, Patience); the census's two sibling stand-in clocks, its one confirmed flaky test still open (TestAReservationRenewsDuringAPreflight) and its ten worst wall-clock bounds are fixed on it, the causes of all seven confirmed flakes are named, and TestNoNewWallClockBound in internal/core/lint refuses a new wall-clock bound outside testtiming, the 48 left listed so the list only shrinks; the starved lane and the fake-clock half of the audit are deferred by dcn-2612022337510454" +resolution: "A test judges how long something took through internal/testtiming (Bound, CutShort, CPU, Await, AwaitWithin, Patience); the census's two sibling stand-in clocks, its one confirmed flaky test still open (TestAReservationRenewsDuringAPreflight) and its ten worst wall-clock bounds are fixed on it, the causes of all seven confirmed flakes are named, and TestNoNewWallClockBound in internal/core/lint refuses a new wall-clock bound outside testtiming held to a constant duration it can read (the package's constants and constant-valued variables, bare or through the package's name, and a function's own), the 55 left listed by function so the list only shrinks; the starved lane, the fake-clock half of the audit and the fixed budgets a test waits out (time.After and time.Now().Add) are deferred, and the shapes the audit does not read are named, by dcn-2612022337510454" impact: internal --- diff --git a/internal/core/lint/wallclock_audit_test.go b/internal/core/lint/wallclock_audit_test.go index da10bd24b0..355c6ea314 100644 --- a/internal/core/lint/wallclock_audit_test.go +++ b/internal/core/lint/wallclock_audit_test.go @@ -20,20 +20,30 @@ import ( // long something took, against a reference measured in the same run or the // work a run must cut short. This audit holds every other test to it: it reads // each test file under internal/ and cmd/ and finds every upper bound on an -// elapsed wall-clock time (time.Since, time.Now().Sub, or a variable assigned -// from one) that is a constant duration (unit literals, constants and -// time.Duration conversions of them, the constants and constant-valued -// variables declared inside the function included). The bounds written before -// the audit are wallClockBaseline, by file and function; a new one, or one more -// in a listed function, fails here, and a listed one fixed fails here until the +// elapsed wall-clock time (time.Since or time.Now().Sub, or a variable given +// one by `:=`, `=` or `var`) against a constant duration: one built of unit +// literals, time.Duration conversions, the package's own constants and its +// variables declared with a constant duration (which a test may set to another +// and put back), either of them read bare or, from an external test package, +// through the package's name, and the constants and constant-only variables +// the function declares itself (withLocalConsts). The bounds written before the +// audit are wallClockBaseline, by file and function; a new one, or one more in +// a listed function, fails here, and a listed one fixed fails here until the // baseline drops it, so the list only shrinks. // -// It does not see a constant passed through a helper (a `slack(d)`), a bound -// read off the CPU clock, which load does not inflate, a fixed sleep used as a -// hand-off, or a fixed budget a test waits out rather than measures: a select -// on time.After(), or a poll loop until time.Now().Add(). -// Those stay a reviewer's to catch (dcn-2612022337510454 says why the last two -// are not audited). +// It does not read, and a reviewer must catch (dcn-2612022337510454): +// - a constant or variable of another package (`took > other.Grace`); +// - a bound held to a struct field, a parameter or a function's result +// (a `slack(d)`); +// - a variable the function also gives anything but a constant duration, a +// value put back through a function's parameter included, or a package +// variable declared with anything else; +// - an elapsed time taken any other way, such as end.Sub(start) of two +// readings, which syntax does not tell from a fake clock's difference; +// - a bound read off the CPU clock, which load does not inflate, by design; +// - a fixed sleep used as a hand-off; +// - a fixed budget a test waits out rather than measures: a select on +// time.After(), or a poll loop until time.Now().Add(). // wallClockBaseline is how many wall-clock bounds each function held when the // audit came in, after the census's ten worst were moved to testtiming. Each @@ -53,6 +63,7 @@ var wallClockBaseline = map[string]int{ "internal/core/autonomy/session_tracked_test.go TestAReservationsReadTheDeadlineEndsIsMarkedCutShort": 1, "internal/core/cite/fetch_test.go TestCheckTimesOutAsAnOutcome": 1, "internal/core/claim/generatedcache_test.go TestAKeptReadWithNoContextIsBounded": 1, + "internal/core/claim/remote_test.go TestTheSpotcheckFetchEndsAtItsBound": 1, "internal/core/claim/spotcheck_push_test.go TestPushHonoursCallerContext": 1, "internal/core/claim/status_pushers_test.go TestEachForgeLookupEndsAtTheBudget": 1, "internal/core/claim/viewctx_test.go TestABoundTipReadOnItsOwnStopsAHungGit": 1, @@ -67,6 +78,7 @@ var wallClockBaseline = map[string]int{ "internal/core/implement/loop/lanehooks_test.go TestALaneCheckoutHasItsOwnBound": 1, "internal/core/implement/loop/pickgit_deadline_test.go TestALaneResetStoppedAtItsBoundIsNamedAsAReset": 1, "internal/core/implement/loop/pickgit_deadline_test.go assertStopped": 1, + "internal/core/implement/loop/renewruns_test.go TestTheWaiterPassesOverARunWhoseLockIsHeld": 1, "internal/core/implement/loop/sync_stall_test.go TestASyncMergeStoppedAtItsDeadlineIsUndone": 1, "internal/core/landing/gate_test.go TestAPreflightPastItsBoundIsKilledWithItsGroup": 1, "internal/core/landing/receipt_context_test.go TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs": 1, @@ -80,6 +92,7 @@ var wallClockBaseline = map[string]int{ "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosedOnAChildHoldingItsOutput": 1, "internal/core/tools/runargv_regroup_test.go TestRunArgvBoundHoldsAgainstAReGroupedDescendant": 1, "internal/core/tools/tools_test.go TestRunArgvKillsItsOwnGroupOnTimeout": 1, + "internal/gitutil/bounded_unix_test.go TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot": 1, "internal/gitutil/net_ssh_test.go TestTheSSHCommandsReadEndsWithItsContext": 1, "internal/gitutil/waitdelay_test.go TestRootCommitContextEndsAtItsDeadlineWhileTheOutputStaysOpen": 1, "internal/procgroup/run_test.go TestRunToEOFDrainsAndReportsAWriterThatFails": 1, @@ -98,6 +111,13 @@ var timeUnits = map[string]bool{"Nanosecond": true, "Microsecond": true, "Millis // wallClockBounds returns the wall-clock bounds in the test files of the // package directory dir, as "/ " keys with their counts. +// +// The package's constants count, and so does each package variable declared +// with a constant duration, which a test function may set to another and put +// back (withLocalConsts drops it from a function that gives it anything +// else). An external test package reads both through the package's name, so +// `.` counts for each of them declared in the package itself, +// its export_test files included. func wallClockBounds(t *testing.T, dir, rel string) map[string]int { t.Helper() entries, err := os.ReadDir(dir) @@ -105,9 +125,9 @@ func wallClockBounds(t *testing.T, dir, rel string) map[string]int { t.Fatal(err) } fset := token.NewFileSet() - consts := map[string]bool{} - var tests []*ast.File + var files, tests []*ast.File var names []string + own, ownInTests := "", "" for _, e := range entries { if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") { continue @@ -116,19 +136,43 @@ func wallClockBounds(t *testing.T, dir, rel string) map[string]int { if err != nil { t.Fatal(err) } - for _, d := range f.Decls { - if g, ok := d.(*ast.GenDecl); ok && g.Tok == token.CONST { - for _, s := range g.Specs { - for _, n := range s.(*ast.ValueSpec).Names { - consts[n.Name] = true - } - } - } + files = append(files, f) + switch pkg := f.Name.Name; { + case !strings.HasSuffix(e.Name(), "_test.go"): + own = pkg + case !strings.HasSuffix(pkg, "_test"): + ownInTests = pkg } if strings.HasSuffix(e.Name(), "_test.go") { tests, names = append(tests, f), append(names, e.Name()) } } + if own == "" { + own = ownInTests + } + consts := map[string]bool{} + declare := func(f *ast.File, name string) { + consts[name] = true + if f.Name.Name == own { + consts[own+"."+name] = true + } + } + for _, f := range files { + for _, s := range topSpecs(f, token.CONST) { + for _, n := range s.Names { + declare(f, n.Name) + } + } + } + for _, f := range files { + for _, s := range topSpecs(f, token.VAR) { + for i, n := range s.Names { + if len(s.Values) == len(s.Names) && isConstDuration(s.Values[i], consts) { + declare(f, n.Name) + } + } + } + } hits := map[string]int{} for i, f := range tests { for _, d := range f.Decls { @@ -144,6 +188,19 @@ func wallClockBounds(t *testing.T, dir, rel string) map[string]int { return hits } +// topSpecs returns f's top-level declarations made with tok, const or var. +func topSpecs(f *ast.File, tok token.Token) []*ast.ValueSpec { + var out []*ast.ValueSpec + for _, d := range f.Decls { + if g, ok := d.(*ast.GenDecl); ok && g.Tok == tok { + for _, s := range g.Specs { + out = append(out, s.(*ast.ValueSpec)) + } + } + } + return out +} + // boundsIn returns each comparison in body of an elapsed wall-clock time with a // constant duration, the constants body declares for itself among them // (withLocalConsts). @@ -151,10 +208,21 @@ func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { consts = withLocalConsts(body, consts) elapsed := map[string]bool{} ast.Inspect(body, func(n ast.Node) bool { - if a, ok := n.(*ast.AssignStmt); ok && len(a.Lhs) == len(a.Rhs) { - for i, r := range a.Rhs { - if id, ok := a.Lhs[i].(*ast.Ident); ok && isElapsed(r, nil) { - elapsed[id.Name] = true + switch s := n.(type) { + case *ast.AssignStmt: + if len(s.Lhs) == len(s.Rhs) { + for i, r := range s.Rhs { + if id, ok := s.Lhs[i].(*ast.Ident); ok && isElapsed(r, nil) { + elapsed[id.Name] = true + } + } + } + case *ast.ValueSpec: + if len(s.Names) == len(s.Values) { + for i, r := range s.Values { + if isElapsed(r, nil) { + elapsed[s.Names[i].Name] = true + } } } } @@ -179,12 +247,16 @@ func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { } // withLocalConsts is consts and the names body holds constant itself: each name -// a const declaration in it declares, and each variable whose every assignment -// in it, `:=`, `=` or `var`, is a constant duration, read in the order they are -// written so that one built from another counts. A bound held to a constant -// declared inside its function is the same bound as one declared beside it, and -// moving the constant in must not take it off the baseline. A variable also -// assigned anything else, stepped, or ranged over is not constant. +// a const declaration in it declares, and each variable, its own or the +// package's, whose every assignment in it keeps it a constant duration, read in +// the order they are written so that one built from another counts. A `:=`, +// `=` or `var` of a constant duration keeps it so, as does a `var` with no +// value (the zero duration) and a step by a constant (`limit *= 5`, `n++`); +// so does putting back a value saved from it while it was constant. A bound +// held to a constant declared inside its function is the same bound as one +// declared beside it, and moving the constant in must not take it off the +// baseline. A variable also given anything else, a value put back through a +// function's parameter included, or ranged over, is not constant. func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]bool { all := make(map[string]bool, len(consts)) for k := range consts { @@ -192,14 +264,19 @@ func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]boo } declared, varied := map[string]bool{}, map[string]bool{} assign := func(e ast.Expr, rhs ast.Expr) { - id, ok := e.(*ast.Ident) - if !ok || id.Name == "_" { + name := valueName(e) + if name == "" || name == "_" { return } if rhs != nil && isConstDuration(rhs, all) { - all[id.Name] = true + all[name] = true } else { - varied[id.Name] = true + varied[name] = true + } + } + step := func(e ast.Expr, by ast.Expr) { + if name := valueName(e); name != "" && (by == nil || !isConstExpr(by, all)) { + varied[name] = true } } ast.Inspect(body, func(n ast.Node) bool { @@ -214,6 +291,8 @@ func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]boo switch { case s.Tok == token.CONST: all[name.Name], declared[name.Name] = true, true + case len(v.Values) == 0: + all[name.Name] = true case len(v.Values) == len(v.Names): assign(name, v.Values[i]) default: @@ -223,14 +302,16 @@ func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]boo } case *ast.AssignStmt: for i, l := range s.Lhs { - if (s.Tok == token.DEFINE || s.Tok == token.ASSIGN) && len(s.Lhs) == len(s.Rhs) { + switch { + case (s.Tok == token.DEFINE || s.Tok == token.ASSIGN) && len(s.Lhs) == len(s.Rhs): assign(l, s.Rhs[i]) - } else { + case s.Tok != token.DEFINE && s.Tok != token.ASSIGN && len(s.Rhs) == 1: + step(l, s.Rhs[0]) + default: assign(l, nil) } } case *ast.IncDecStmt: - assign(s.X, nil) case *ast.RangeStmt: if s.Key != nil { assign(s.Key, nil) @@ -249,6 +330,21 @@ func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]boo return all } +// valueName is the name an assignment to e sets: an identifier, or +// `.` for a value an external test package sets through the +// package's name; "" for anything else. +func valueName(e ast.Expr) string { + switch x := e.(type) { + case *ast.Ident: + return x.Name + case *ast.SelectorExpr: + if id, ok := x.X.(*ast.Ident); ok { + return id.Name + "." + x.Sel.Name + } + } + return "" +} + // isElapsed reports whether e is a wall-clock time since a moment: a call of // time.Since, time.Now().Sub, or a name in vars assigned from one. func isElapsed(e ast.Expr, vars map[string]bool) bool { @@ -275,15 +371,33 @@ func isElapsed(e ast.Expr, vars map[string]bool) bool { } // isConstDuration reports whether e is a constant duration: built of numeric -// literals, the time package's units, the package's own constants and -// time.Duration conversions, with at least one unit or constant in it. +// literals, the time package's units, the names in consts (the package's own +// constants and constant-valued variables, bare or through the package's +// name, and the function's) and time.Duration conversions, with at least one +// unit or name in it. func isConstDuration(e ast.Expr, consts map[string]bool) bool { - ok, named := true, false + ok, named := constParts(e, consts) + return ok && named +} + +// isConstExpr reports whether e is constant as isConstDuration reads it, a +// bare number included, as a step (`*= 5`) may be. +func isConstExpr(e ast.Expr, consts map[string]bool) bool { + ok, _ := constParts(e, consts) + return ok +} + +// constParts reports whether e is built only of what isConstDuration accepts, +// and whether a unit or a name is among it. +func constParts(e ast.Expr, consts map[string]bool) (ok, named bool) { + ok = true ast.Inspect(e, func(n ast.Node) bool { switch x := n.(type) { case *ast.SelectorExpr: if isPkgSel(x, "time", "") && timeUnits[x.Sel.Name] { named = true + } else if consts[valueName(x)] { + named = true } else if !isPkgSel(x, "time", "Duration") { ok = false } @@ -301,7 +415,7 @@ func isConstDuration(e ast.Expr, consts map[string]bool) bool { } return ok }) - return ok && named + return ok, named } // isPkgSel reports whether sel is pkg.name, or pkg.anything when name is "". @@ -311,89 +425,25 @@ func isPkgSel(sel *ast.SelectorExpr, pkg, name string) bool { } // TestTheWallClockAuditReadsEachShape: the scan finds an upper bound on -// time.Since itself, on a variable taken from it and on time.Now().Sub, -// against a unit literal, a constant and a conversion, written either way -// round, and against a constant or a constant-valued variable the function -// declares itself; and it passes a bound held through a helper, one read off -// another clock, one against a measured value, one against a variable that -// is also given a measured value, and a lower bound. +// time.Since itself, on a variable taken from it by `:=` or `var` and on +// time.Now().Sub, written either way round, against a unit literal, a +// constant and a conversion; against a constant the function declares, a +// variable it gives only constant durations, stepped by a constant or +// declared with no value first; against a package variable declared with a +// constant duration, set to another and put back; and, from an external test +// package, against the package's constant or such a variable through the +// package's name. It passes a bound held through a helper, one read off +// another clock, one against a measured value, a variable also given a +// measured value or put back through a parameter, a package variable no +// syntax shows constant, another package's constant, and a lower bound +// (wallClockFixture). func TestTheWallClockAuditReadsEachShape(t *testing.T) { - dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, "x_test.go"), []byte(wallClockShapes), 0o600); err != nil { - t.Fatal(err) - } - got := wallClockBounds(t, dir, "x") - want := map[string]int{"x/x_test.go TestFlagged": 4, "x/x_test.go TestFlaggedLocally": 3} - if fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("the scan found %v, want %v", got, want) - } -} - -// wallClockShapes is TestTheWallClockAuditReadsEachShape's package: each shape -// the audit flags, and each it passes. -const wallClockShapes = `package x - -import ( - "testing" - "time" -) - -const budget = 2 * time.Second - -func TestFlagged(t *testing.T) { - start := time.Now() - if time.Since(start) > 5*time.Second { - } - took := time.Since(start) - if took > budget { - } - if time.Now().Sub(start) >= time.Duration(3)*time.Second { - } - if 300*time.Millisecond < took { - } -} - -func TestFlaggedLocally(t *testing.T) { - const ceiling = time.Second - twice := 2 * ceiling - var stall = time.Minute - start := time.Now() - took := time.Since(start) - if took >= ceiling { - } - if took > twice { - } - if stall/2 < time.Since(start) { - } -} - -func TestPassed(t *testing.T) { - start := time.Now() - took := time.Since(start) - reference := time.Since(start) - if took > 2*reference { - } - cpu := clock() - 0 - if cpu > 5*time.Second { - } - if took > limit(reference) { - } - if took < 5*time.Second { - } - if 300*time.Millisecond > time.Since(start) { - } - allowed := 2 * time.Second - if reference > allowed { - allowed = 2 * reference - } - if took > allowed { + got := wallClockBounds(t, wallClockFixtureDir(t), "x") + if fmt.Sprint(got) != fmt.Sprint(wallClockFixtureWant) { + t.Fatalf("the scan found %v, want %v", got, wallClockFixtureWant) } } -func clock() time.Duration { return 0 } -func limit(d time.Duration) time.Duration { return d } -` - // TestNoNewWallClockBound: no test outside internal/testtiming holds a // wall-clock time to a constant beyond the bounds wallClockBaseline lists, and // each listed one is still there. diff --git a/internal/core/lint/wallclock_shapes_test.go b/internal/core/lint/wallclock_shapes_test.go new file mode 100644 index 0000000000..95eb3c3589 --- /dev/null +++ b/internal/core/lint/wallclock_shapes_test.go @@ -0,0 +1,165 @@ +package lint_test + +import ( + "os" + "path/filepath" + "testing" +) + +// wallClockFixtureDir writes wallClockFixture into a directory of its own, one +// package with an external test package beside it, and returns the directory. +func wallClockFixtureDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + for name, src := range wallClockFixture { + if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o600); err != nil { + t.Fatal(err) + } + } + return dir +} + +// wallClockFixtureWant is what the audit finds in wallClockFixture: each +// TestFlagged function's bounds, and nothing in a TestPassed one. +var wallClockFixtureWant = map[string]int{ + "x/x_test.go TestFlagged": 4, + "x/x_test.go TestFlaggedLocally": 3, + "x/x_test.go TestFlaggedStepped": 3, + "x/x_ext_test.go TestFlaggedOutside": 2, +} + +// wallClockFixture is TestTheWallClockAuditReadsEachShape's package, by file: +// each shape the audit flags, and each it passes. +var wallClockFixture = map[string]string{ + "x.go": `package x + +import "time" + +// Grace is a constant an external test reads through the package's name. +const Grace = 5 * time.Second + +// Wait is a variable declared with a constant duration, which a test may set +// to another and put back. +var Wait = 2 * time.Second + +// Measured is a variable whose value no syntax shows constant. +var Measured = measure() + +func measure() time.Duration { return 0 } +`, + "x_test.go": `package x + +import ( + "testing" + "time" +) + +const budget = 2 * time.Second + +func TestFlagged(t *testing.T) { + start := time.Now() + if time.Since(start) > 5*time.Second { + } + took := time.Since(start) + if took > budget { + } + if time.Now().Sub(start) >= time.Duration(3)*time.Second { + } + if 300*time.Millisecond < took { + } +} + +func TestFlaggedLocally(t *testing.T) { + const ceiling = time.Second + twice := 2 * ceiling + var stall = time.Minute + start := time.Now() + took := time.Since(start) + if took >= ceiling { + } + if took > twice { + } + if stall/2 < time.Since(start) { + } +} + +func TestFlaggedStepped(t *testing.T) { + limit := time.Second + limit *= 5 + var later time.Duration + later = 3 * time.Second + saved := Wait + t.Cleanup(func() { Wait = saved }) + Wait = time.Second + start := time.Now() + var took = time.Since(start) + if took > limit { + } + if took > later { + } + if took > Wait { + } +} + +func TestPassed(t *testing.T) { + start := time.Now() + took := time.Since(start) + reference := time.Since(start) + if took > 2*reference { + } + cpu := clock() - 0 + if cpu > 5*time.Second { + } + if took > limit(reference) { + } + if took < 5*time.Second { + } + if 300*time.Millisecond > time.Since(start) { + } + allowed := 2 * time.Second + if reference > allowed { + allowed = 2 * reference + } + if took > allowed { + } + defer func(d time.Duration) { Wait = d }(Wait) + Wait = time.Second + if took > Wait { + } + if took > Measured { + } +} + +func clock() time.Duration { return 0 } +func limit(d time.Duration) time.Duration { return d } +`, + "x_ext_test.go": `package x_test + +import ( + "testing" + "time" + + "example.com/other" + "example.com/x" +) + +func TestFlaggedOutside(t *testing.T) { + start := time.Now() + if time.Since(start) >= x.Grace { + } + if 2*x.Wait < time.Since(start) { + } +} + +func TestPassedOutside(t *testing.T) { + start := time.Now() + x.Wait = time.Since(start) + if time.Since(start) > x.Wait { + } + if time.Since(start) > x.Measured { + } + if time.Since(start) > other.Grace { + } +} +`, +} From d7b3a9806360cd1c4150ada2b408f3034b27f76d Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:36:33 +0000 Subject: [PATCH 09/11] test: hold the prompt record to its context with a scan that ignores it The security review of 6fefbcfa2 found that no test held the record to its context's end: both fake scans honour their context, so deleting redactWithin's `case <-ctx.Done()` (promptlog.go) left every test green, at this head and at the branch's base alike. Pre-existing, and fixed here. TestPermissionPromptRecordEndsWithItsContext gives the record a scan that ignores its context and returns only after a minute (or when the test ends). The record must return, the command recorded by its length, within CutShort of that minute; a record that waits for the scan takes the whole minute. Its context is five seconds, so the scanner has time to start the scan before it is told to stop, and the test fails on the premise if the scan never started. TestPermissionPromptRecordWaitsForAStoppedScan no longer holds the record inside its own second, and that is kept so: the deadline is now held in two halves, that test's read of the scan's deadline (told to stop before the record's) and this test's (the record does not wait past its context). A record that stopped the scan late and waited for it past its deadline fails both. What neither holds is a slow write after the scan, which is the flake the second-long bound was, or a slip of under half a minute, the cost dcn-2612022252475157 records. Red before green, through the narrow load gate: on a scratch copy at 6fefbcfa2 with that case deleted, the new test failed ("took 1m0.0116605s, over its bound of 30s"); on this tree it passes (5.05s), and so does TestPermissionPromptRecordWaitsForAStoppedScan (0.64s). Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- internal/core/autonomy/promptlog_reap_test.go | 66 +++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/internal/core/autonomy/promptlog_reap_test.go b/internal/core/autonomy/promptlog_reap_test.go index ec88d76a1d..6543531ba3 100644 --- a/internal/core/autonomy/promptlog_reap_test.go +++ b/internal/core/autonomy/promptlog_reap_test.go @@ -13,7 +13,7 @@ import ( "github.com/intentdriven/abcd/internal/testtiming" ) -// scanStall is how long cleaningAug's scan runs when nothing tells it to stop. +// scanStall is how long a fake scan here runs when nothing ends it. const scanStall = time.Minute // cleaningAug is a secret scan that does not finish on its own for a minute @@ -53,9 +53,13 @@ func (a *cleaningAug) ScanContext(ctx context.Context, text, file string) []scan // against the minute a scan nothing stopped would run (testtiming.CutShort): a // bound of the one-second deadline itself left a loaded runner the half second // after the scan's stop to clean up, write and return in -// (iss-2612022218392055). That the record ends by its deadline is its context's -// to keep; what this test holds is that it stops the scan in time to wait for -// it. +// (iss-2612022218392055). The record ending by its deadline is held in two +// halves instead: this test holds that the scan is told to stop before it, and +// TestPermissionPromptRecordEndsWithItsContext that the record does not wait +// for a scan past it. A record that stopped the scan late and waited for it +// fails both; what neither holds is a write after the scan that a loaded runner +// takes long over, which is the flake, or a slip of under half the scan's +// minute (dcn-2612022252475157). func TestPermissionPromptRecordWaitsForAStoppedScan(t *testing.T) { root, _ := managedCopy(t) a := &cleaningAug{} @@ -84,3 +88,57 @@ func TestPermissionPromptRecordWaitsForAStoppedScan(t *testing.T) { t.Errorf("record = %+v, want one line with the command's length description", got) } } + +// ignoringAug is a secret scan that ignores its context: once started it +// returns only after scanStall, or when its test ends. +type ignoringAug struct { + started atomic.Bool + end chan struct{} +} + +func (a *ignoringAug) Available() error { return nil } + +func (a *ignoringAug) Scan(text, file string) []scanner.Finding { + return a.ScanContext(context.Background(), text, file) +} + +func (a *ignoringAug) ScanContext(context.Context, string, string) []scanner.Finding { + a.started.Store(true) + select { + case <-a.end: + case <-time.After(scanStall): + } + return nil +} + +// TestPermissionPromptRecordEndsWithItsContext: a scan that does not stop when +// told does not hold the record past its context. The record returns when its +// context ends, the command recorded by its length, and leaves the scan to +// finish unread (redactWithin). It is judged against the minute the scan runs +// (testtiming.CutShort), so a record that waits for the scan fails on any +// runner. The context's five seconds give the scanner time to start the scan +// before it is told to stop, so the test holds the wait, not the start. +func TestPermissionPromptRecordEndsWithItsContext(t *testing.T) { + root, _ := managedCopy(t) + a := &ignoringAug{end: make(chan struct{})} + augmenttest.Install(t, a) + t.Cleanup(func() { close(a.end) }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + const command = "echo a command the scan does not let go of" + start := time.Now() + err := RecordPermissionPrompt(ctx, root, PermissionPrompt{Decision: PermissionDecisionNone, Command: command}, time.Now()) + if judged := testtiming.CutShort.Check("the record with a scan that ignores its context", time.Since(start), scanStall); judged != nil { + t.Error(judged) + } + if !a.started.Load() { + t.Error("premise: the scan was never started, so nothing held the record") + } + if !errors.Is(err, ErrRedactionBudget) { + t.Errorf("err = %v, want ErrRedactionBudget", err) + } + got := readPermissionPrompts(t, root) + if len(got) != 1 || got[0].Command != termsafe.DescribeRefused(command) { + t.Errorf("record = %+v, want one line with the command's length description", got) + } +} From 557ff3d9980199d1d3cbe47b494c384c2484612b Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:06:04 +0000 Subject: [PATCH 10/11] test: read package variables to a fixed point in the wall-clock audit The correctness review of d7b3a9806 found that the audit read the package's variables in one pass, in file-name order, so a variable declared from one a later file declares was never constant to it: in package loop, gitenvs.go's `var heldReadTimeout = originAskTimeout` comes before lane.go's `var originAskTimeout = time.Minute`, and `took >= heldReadTimeout/2` in remoteid_bounded_test.go's TestAComparisonSlowOnEveryReadEndsAtItsOverallBound (five minutes once the test sets the variable to ten) was off the list. Renaming lane.go to sort first would have failed the audit on a change that adds no bound. The variable pass now repeats until it declares nothing new, so what the audit finds does not hang on the order of the file names. The function is listed; the baseline is 56 bounds in 55 functions, and dcn-2612022337510454 and the resolved issue say so. The security review of the same head noted the header said a bound held to a struct field is not read, where a field the function itself sets only to constant durations (`cfg.Timeout = 2 * time.Second`) is counted. The header, the decision and the doc comments now say exactly that: a field the function sets is read, one set elsewhere (a helper, a fixture's constructor) is not. The fixture gains a variable declared from one in a file that sorts after it (TestFlaggedLater), a field set in the function (TestFlaggedLocally) and one set by a constructor (TestPassed). Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- ...ss-2612022218392055-is-resolved-without.md | 2 +- ...55-flaky-tests-share-one-pattern-a-test.md | 2 +- internal/core/lint/wallclock_audit_test.go | 187 ++++++++++-------- internal/core/lint/wallclock_shapes_test.go | 30 ++- 4 files changed, 132 insertions(+), 89 deletions(-) diff --git a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md index 8c24d5b1aa..3065d8cb67 100644 --- a/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md +++ b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md @@ -7,4 +7,4 @@ date: 2026-12-02 Amended after the review of 58c84da10: the audit now also counts a bound held to a constant the function declares itself, or to a variable only ever given a constant duration, so moving a listed constant into its function no longer takes it off the list; the baseline grew once, at that change, from 48 bounds to 52 in 51 functions (claim's TestPushHonoursCallerContext, landing's TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs, spotcheck's writeCutOff and a second bound in cli's TestThePromptHookReturnsInsideItsSecond), and promptlog_reap's one-second bound equal to its own deadline was fixed through testtiming instead of listed. A third part stays deferred: the audit does not see a fixed budget a test waits out rather than measures, a select on time.After() or a poll loop until time.Now().Add(), three of which this change itself leaves (terminal_test.go's 15s turn, precheck-audits' 20s leader wait, testreuse's 30s). Grounds: there are 121 time.After and 257 time.Now().Add calls in 191 test files, most a fixture's date or a failure deadline far past the work, and syntax does not tell a budget from either, so teaching the audit them is a data-flow change and a baseline several times this one's, not the small change this round allows. To reverse: capture it as its own issue, and teach boundsIn a time.After or time.Now().Add whose argument isConstDuration and which ends a wait the test fails on. -Amended after the reviews of 6fefbcfa2: the audit also counts the package's own constants and its variables declared with a constant duration (which a test may set to another and put back), read bare or, from an external test package, through the package's name; a variable stepped by a constant or declared with no value and then given constants; and an elapsed time given by `var`. The baseline grew once more, at that change, from 52 bounds to 55 in 54 functions (claim's TestTheSpotcheckFetchEndsAtItsBound, loop's TestTheWaiterPassesOverARunWhoseLockIsHeld and gitutil's TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot). What the audit still does not read, each a reviewer's to catch and each deferred on the grounds above (syntax does not settle it without type or data-flow information, or no live case asks for it): a constant or variable of another package, none of which the tree holds as a bound; a bound held to a struct field, a parameter or a function's result, such as claim's slack(d); a variable the function also gives anything but a constant duration, a value put back through a function's parameter included, or a package variable declared with anything else; an elapsed time taken any other way, such as end.Sub(start) of two readings, which syntax does not tell from a fake clock's difference; a bound read off the CPU clock, by design; a fixed sleep used as a hand-off; and a fixed budget waited out on time.After or time.Now().Add, the third deferral above. The audit's header lists the same shapes. +Amended after the reviews of 6fefbcfa2 and d7b3a9806: the audit also counts the package's own constants and its variables declared with a constant duration or from another such variable, whichever file declares it (which a test may set to another and put back), read bare or, from an external test package, through the package's name; a variable or a struct field the function sets only to constant durations, stepped by a constant or declared with no value first; and an elapsed time given by `var`. The baseline grew once more, at that change, from 52 bounds to 56 in 55 functions (claim's TestTheSpotcheckFetchEndsAtItsBound, loop's TestTheWaiterPassesOverARunWhoseLockIsHeld and TestAComparisonSlowOnEveryReadEndsAtItsOverallBound, and gitutil's TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot). What the audit still does not read, each a reviewer's to catch and each deferred on the grounds above (syntax does not settle it without type or data-flow information, or no live case asks for it): a constant or variable of another package, none of which the tree holds as a bound; a bound held to a parameter, a function's result such as claim's slack(d), or a struct field the function does not set itself (one set in a helper or a fixture's constructor); a variable or field the function also gives anything but a constant duration, a value put back through a function's parameter included, or a package variable declared with anything else; an elapsed time taken any other way, such as end.Sub(start) of two readings, which syntax does not tell from a fake clock's difference; a bound read off the CPU clock, by design; a fixed sleep used as a hand-off; and a fixed budget waited out on time.After or time.Now().Add, the third deferral above. The audit's header lists the same shapes. diff --git a/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md index 9092b70aa1..86ca93a37c 100644 --- a/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md +++ b/.abcd/work/issues/resolved/iss-2612022218392055-flaky-tests-share-one-pattern-a-test.md @@ -10,7 +10,7 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/implement/loop" remedy: "a test audit that flags a wall-clock assertion (an elapsed time compared with a constant, a fake that reads time.Now) outside one shared helper that judges a ratio against a floor; a flake census of the last 60 days of CI failures, each remaining case fixed or recorded; and a starved lane (GOMAXPROCS=3 with -race, the hosted macOS runner's shape) for the packages the census names" -resolution: "A test judges how long something took through internal/testtiming (Bound, CutShort, CPU, Await, AwaitWithin, Patience); the census's two sibling stand-in clocks, its one confirmed flaky test still open (TestAReservationRenewsDuringAPreflight) and its ten worst wall-clock bounds are fixed on it, the causes of all seven confirmed flakes are named, and TestNoNewWallClockBound in internal/core/lint refuses a new wall-clock bound outside testtiming held to a constant duration it can read (the package's constants and constant-valued variables, bare or through the package's name, and a function's own), the 55 left listed by function so the list only shrinks; the starved lane, the fake-clock half of the audit and the fixed budgets a test waits out (time.After and time.Now().Add) are deferred, and the shapes the audit does not read are named, by dcn-2612022337510454" +resolution: "A test judges how long something took through internal/testtiming (Bound, CutShort, CPU, Await, AwaitWithin, Patience); the census's two sibling stand-in clocks, its one confirmed flaky test still open (TestAReservationRenewsDuringAPreflight) and its ten worst wall-clock bounds are fixed on it, the causes of all seven confirmed flakes are named, and TestNoNewWallClockBound in internal/core/lint refuses a new wall-clock bound outside testtiming held to a constant duration it can read (the package's constants and constant-valued variables, bare or through the package's name, and a function's own), the 56 left listed by function so the list only shrinks; the starved lane, the fake-clock half of the audit and the fixed budgets a test waits out (time.After and time.Now().Add) are deferred, and the shapes the audit does not read are named, by dcn-2612022337510454" impact: internal --- diff --git a/internal/core/lint/wallclock_audit_test.go b/internal/core/lint/wallclock_audit_test.go index 355c6ea314..e3310cd7c7 100644 --- a/internal/core/lint/wallclock_audit_test.go +++ b/internal/core/lint/wallclock_audit_test.go @@ -23,21 +23,24 @@ import ( // elapsed wall-clock time (time.Since or time.Now().Sub, or a variable given // one by `:=`, `=` or `var`) against a constant duration: one built of unit // literals, time.Duration conversions, the package's own constants and its -// variables declared with a constant duration (which a test may set to another -// and put back), either of them read bare or, from an external test package, -// through the package's name, and the constants and constant-only variables -// the function declares itself (withLocalConsts). The bounds written before the -// audit are wallClockBaseline, by file and function; a new one, or one more in -// a listed function, fails here, and a listed one fixed fails here until the -// baseline drops it, so the list only shrinks. +// variables declared with a constant duration or from another such variable, +// whichever file declares it (which a test may set to another and put back), +// either of them read bare or, from an external test package, through the +// package's name; and the constants the function declares itself, and the +// variables and struct fields it sets only to constant durations +// (`cfg.Timeout = 2 * time.Second`), read in withLocalConsts. The bounds +// written before the audit are wallClockBaseline, by file and function; a new +// one, or one more in a listed function, fails here, and a listed one fixed +// fails here until the baseline drops it, so the list only shrinks. // // It does not read, and a reviewer must catch (dcn-2612022337510454): // - a constant or variable of another package (`took > other.Grace`); -// - a bound held to a struct field, a parameter or a function's result -// (a `slack(d)`); -// - a variable the function also gives anything but a constant duration, a -// value put back through a function's parameter included, or a package -// variable declared with anything else; +// - a bound held to a parameter, a function's result (a `slack(d)`), or a +// struct field the function does not set itself (one set elsewhere, in a +// helper or a fixture's constructor); +// - a variable or field the function also gives anything but a constant +// duration, a value put back through a function's parameter included, or +// a package variable declared with anything else; // - an elapsed time taken any other way, such as end.Sub(start) of two // readings, which syntax does not tell from a fake clock's difference; // - a bound read off the CPU clock, which load does not inflate, by design; @@ -50,60 +53,61 @@ import ( // is a candidate for testtiming too, most of them a generous bound on a call a // short context ends; none may be added. var wallClockBaseline = map[string]int{ - "cmd/precheck-audits/main_test.go TestAFailingAuditRunStopsTheWholeRun": 1, - "internal/adapter/openaiapi/client_test.go TestATimeoutIsRefused": 1, - "internal/adapter/openaiapi/local_test.go TestTheProbeIsBounded": 1, - "internal/adapter/openaiapi/models_test.go TestListModelsBoundsTimeAndSize": 1, - "internal/adapter/openaiapi/routing_test.go TestTheGenerationRecordIsWaitedForWithinItsBound": 1, - "internal/core/ahoy/readme_derive_test.go TestHeadingTextStaysLinear": 1, - "internal/core/autonomy/owedread_test.go TestBehindInMergeQueueRepository": 1, - "internal/core/autonomy/owedread_test.go TestForgeListingDeadline": 1, - "internal/core/autonomy/owedread_test.go TestReadOwedHonoursDeadline": 1, - "internal/core/autonomy/session_tracked_test.go TestACreatedBranchStoreTheDeadlineEndsIsMarkedCutShort": 1, - "internal/core/autonomy/session_tracked_test.go TestAReservationsReadTheDeadlineEndsIsMarkedCutShort": 1, - "internal/core/cite/fetch_test.go TestCheckTimesOutAsAnOutcome": 1, - "internal/core/claim/generatedcache_test.go TestAKeptReadWithNoContextIsBounded": 1, - "internal/core/claim/remote_test.go TestTheSpotcheckFetchEndsAtItsBound": 1, - "internal/core/claim/spotcheck_push_test.go TestPushHonoursCallerContext": 1, - "internal/core/claim/status_pushers_test.go TestEachForgeLookupEndsAtTheBudget": 1, - "internal/core/claim/viewctx_test.go TestABoundTipReadOnItsOwnStopsAHungGit": 1, - "internal/core/claim/viewctx_test.go TestATipReadItsDeadlineEndsIsNoObjectTooBig": 1, - "internal/core/claim/viewctx_test.go TestViewContextStopsAHungGitOnEveryRoute": 1, - "internal/core/dogfood/dogfood_routes_test.go TestResolveNeverReadsTheNetwork": 1, - "internal/core/findings/list_test.go TestACancelledCallDoesNotWaitForTheLock": 1, - "internal/core/findings/list_test.go TestAPutWaitsNoLongerThanItsCaller": 1, - "internal/core/findings/list_test.go TestTheLockWaitIsBounded": 1, - "internal/core/github/activity_test.go TestPushersEndsAtItsCallersDeadline": 1, - "internal/core/guard/landing_test.go TestAGitAliasReadThatDoesNotAnswerIsRefusedWithinItsBudget": 1, - "internal/core/implement/loop/lanehooks_test.go TestALaneCheckoutHasItsOwnBound": 1, - "internal/core/implement/loop/pickgit_deadline_test.go TestALaneResetStoppedAtItsBoundIsNamedAsAReset": 1, - "internal/core/implement/loop/pickgit_deadline_test.go assertStopped": 1, - "internal/core/implement/loop/renewruns_test.go TestTheWaiterPassesOverARunWhoseLockIsHeld": 1, - "internal/core/implement/loop/sync_stall_test.go TestASyncMergeStoppedAtItsDeadlineIsUndone": 1, - "internal/core/landing/gate_test.go TestAPreflightPastItsBoundIsKilledWithItsGroup": 1, - "internal/core/landing/receipt_context_test.go TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs": 1, - "internal/core/machineload/read_context_darwin_test.go TestReadContextEndingStopsPS": 1, - "internal/core/matrix/hiddenrun_test.go TestATestRunPastItsDeadlineIsUnexaminedNeverFailed": 1, - "internal/core/matrix/scrub_test.go TestTheScrubIsLinearOnAdversarialText": 1, - "internal/core/runner/exec_test.go TestExecNamesTheStageThatFailed": 1, - "internal/core/runner/proc_held_test.go TestAStageThatLeavesAProcessHoldingItsOutputIsMarked": 1, - "internal/core/spotcheck/store_test.go writeCutOff": 1, - "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosed": 1, - "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosedOnAChildHoldingItsOutput": 1, - "internal/core/tools/runargv_regroup_test.go TestRunArgvBoundHoldsAgainstAReGroupedDescendant": 1, - "internal/core/tools/tools_test.go TestRunArgvKillsItsOwnGroupOnTimeout": 1, - "internal/gitutil/bounded_unix_test.go TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot": 1, - "internal/gitutil/net_ssh_test.go TestTheSSHCommandsReadEndsWithItsContext": 1, - "internal/gitutil/waitdelay_test.go TestRootCommitContextEndsAtItsDeadlineWhileTheOutputStaysOpen": 1, - "internal/procgroup/run_test.go TestRunToEOFDrainsAndReportsAWriterThatFails": 1, - "internal/procgroup/run_test.go TestRunToEOFEndsAtTheContextWhileAPipeIsHeld": 1, - "internal/procgroup/run_test.go TestRunToEOFStopsACommandThatHangs": 1, - "internal/surface/cli/ahoy_worktree_test.go TestAhoyWorktreeAddStopsACheckoutPastItsBound": 1, - "internal/surface/cli/drain_drive_update_test.go TestTheRehearsalRunsTheCandidateReadOnlyWithABound": 1, - "internal/surface/cli/hook_stop_test.go TestHookStopBudgetFailsOpen": 1, - "internal/surface/cli/status_hook_test.go TestThePromptHookReturnsInsideItsSecond": 2, - "internal/surface/session/server_bounds_test.go TestAClosedConnectionStopsItsReplay": 1, - "internal/surface/session/server_bounds_test.go TestAReplayHasATimeBound": 1, + "cmd/precheck-audits/main_test.go TestAFailingAuditRunStopsTheWholeRun": 1, + "internal/adapter/openaiapi/client_test.go TestATimeoutIsRefused": 1, + "internal/adapter/openaiapi/local_test.go TestTheProbeIsBounded": 1, + "internal/adapter/openaiapi/models_test.go TestListModelsBoundsTimeAndSize": 1, + "internal/adapter/openaiapi/routing_test.go TestTheGenerationRecordIsWaitedForWithinItsBound": 1, + "internal/core/ahoy/readme_derive_test.go TestHeadingTextStaysLinear": 1, + "internal/core/autonomy/owedread_test.go TestBehindInMergeQueueRepository": 1, + "internal/core/autonomy/owedread_test.go TestForgeListingDeadline": 1, + "internal/core/autonomy/owedread_test.go TestReadOwedHonoursDeadline": 1, + "internal/core/autonomy/session_tracked_test.go TestACreatedBranchStoreTheDeadlineEndsIsMarkedCutShort": 1, + "internal/core/autonomy/session_tracked_test.go TestAReservationsReadTheDeadlineEndsIsMarkedCutShort": 1, + "internal/core/cite/fetch_test.go TestCheckTimesOutAsAnOutcome": 1, + "internal/core/claim/generatedcache_test.go TestAKeptReadWithNoContextIsBounded": 1, + "internal/core/claim/remote_test.go TestTheSpotcheckFetchEndsAtItsBound": 1, + "internal/core/claim/spotcheck_push_test.go TestPushHonoursCallerContext": 1, + "internal/core/claim/status_pushers_test.go TestEachForgeLookupEndsAtTheBudget": 1, + "internal/core/claim/viewctx_test.go TestABoundTipReadOnItsOwnStopsAHungGit": 1, + "internal/core/claim/viewctx_test.go TestATipReadItsDeadlineEndsIsNoObjectTooBig": 1, + "internal/core/claim/viewctx_test.go TestViewContextStopsAHungGitOnEveryRoute": 1, + "internal/core/dogfood/dogfood_routes_test.go TestResolveNeverReadsTheNetwork": 1, + "internal/core/findings/list_test.go TestACancelledCallDoesNotWaitForTheLock": 1, + "internal/core/findings/list_test.go TestAPutWaitsNoLongerThanItsCaller": 1, + "internal/core/findings/list_test.go TestTheLockWaitIsBounded": 1, + "internal/core/github/activity_test.go TestPushersEndsAtItsCallersDeadline": 1, + "internal/core/guard/landing_test.go TestAGitAliasReadThatDoesNotAnswerIsRefusedWithinItsBudget": 1, + "internal/core/implement/loop/lanehooks_test.go TestALaneCheckoutHasItsOwnBound": 1, + "internal/core/implement/loop/pickgit_deadline_test.go TestALaneResetStoppedAtItsBoundIsNamedAsAReset": 1, + "internal/core/implement/loop/pickgit_deadline_test.go assertStopped": 1, + "internal/core/implement/loop/remoteid_bounded_test.go TestAComparisonSlowOnEveryReadEndsAtItsOverallBound": 1, + "internal/core/implement/loop/renewruns_test.go TestTheWaiterPassesOverARunWhoseLockIsHeld": 1, + "internal/core/implement/loop/sync_stall_test.go TestASyncMergeStoppedAtItsDeadlineIsUndone": 1, + "internal/core/landing/gate_test.go TestAPreflightPastItsBoundIsKilledWithItsGroup": 1, + "internal/core/landing/receipt_context_test.go TestTheReceiptReadEndsAtItsDeadlineWhileGitHangs": 1, + "internal/core/machineload/read_context_darwin_test.go TestReadContextEndingStopsPS": 1, + "internal/core/matrix/hiddenrun_test.go TestATestRunPastItsDeadlineIsUnexaminedNeverFailed": 1, + "internal/core/matrix/scrub_test.go TestTheScrubIsLinearOnAdversarialText": 1, + "internal/core/runner/exec_test.go TestExecNamesTheStageThatFailed": 1, + "internal/core/runner/proc_held_test.go TestAStageThatLeavesAProcessHoldingItsOutputIsMarked": 1, + "internal/core/spotcheck/store_test.go writeCutOff": 1, + "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosed": 1, + "internal/core/sweep/liveness_test.go TestTheLsofProbeFailsClosedOnAChildHoldingItsOutput": 1, + "internal/core/tools/runargv_regroup_test.go TestRunArgvBoundHoldsAgainstAReGroupedDescendant": 1, + "internal/core/tools/tools_test.go TestRunArgvKillsItsOwnGroupOnTimeout": 1, + "internal/gitutil/bounded_unix_test.go TestAStoppedCommitLeavesNoChildGitStartsAfterTheSnapshot": 1, + "internal/gitutil/net_ssh_test.go TestTheSSHCommandsReadEndsWithItsContext": 1, + "internal/gitutil/waitdelay_test.go TestRootCommitContextEndsAtItsDeadlineWhileTheOutputStaysOpen": 1, + "internal/procgroup/run_test.go TestRunToEOFDrainsAndReportsAWriterThatFails": 1, + "internal/procgroup/run_test.go TestRunToEOFEndsAtTheContextWhileAPipeIsHeld": 1, + "internal/procgroup/run_test.go TestRunToEOFStopsACommandThatHangs": 1, + "internal/surface/cli/ahoy_worktree_test.go TestAhoyWorktreeAddStopsACheckoutPastItsBound": 1, + "internal/surface/cli/drain_drive_update_test.go TestTheRehearsalRunsTheCandidateReadOnlyWithABound": 1, + "internal/surface/cli/hook_stop_test.go TestHookStopBudgetFailsOpen": 1, + "internal/surface/cli/status_hook_test.go TestThePromptHookReturnsInsideItsSecond": 2, + "internal/surface/session/server_bounds_test.go TestAClosedConnectionStopsItsReplay": 1, + "internal/surface/session/server_bounds_test.go TestAReplayHasATimeBound": 1, } // timeUnits are the time package's duration constants. @@ -113,9 +117,10 @@ var timeUnits = map[string]bool{"Nanosecond": true, "Microsecond": true, "Millis // package directory dir, as "/ " keys with their counts. // // The package's constants count, and so does each package variable declared -// with a constant duration, which a test function may set to another and put -// back (withLocalConsts drops it from a function that gives it anything -// else). An external test package reads both through the package's name, so +// with a constant duration or from another such variable, in whichever file, +// which a test function may set to another and put back (withLocalConsts drops +// it from a function that gives it anything else). An external test package +// reads both through the package's name, so // `.` counts for each of them declared in the package itself, // its export_test files included. func wallClockBounds(t *testing.T, dir, rel string) map[string]int { @@ -164,11 +169,18 @@ func wallClockBounds(t *testing.T, dir, rel string) map[string]int { } } } - for _, f := range files { - for _, s := range topSpecs(f, token.VAR) { - for i, n := range s.Names { - if len(s.Values) == len(s.Names) && isConstDuration(s.Values[i], consts) { - declare(f, n.Name) + // A variable may be declared from one a later file declares, so the pass + // repeats until it declares nothing new: what it finds does not hang on + // the order of the file names. + for grew := true; grew; { + grew = false + for _, f := range files { + for _, s := range topSpecs(f, token.VAR) { + for i, n := range s.Names { + if !consts[n.Name] && len(s.Values) == len(s.Names) && isConstDuration(s.Values[i], consts) { + declare(f, n.Name) + grew = true + } } } } @@ -248,8 +260,9 @@ func boundsIn(body *ast.BlockStmt, consts map[string]bool) []*ast.BinaryExpr { // withLocalConsts is consts and the names body holds constant itself: each name // a const declaration in it declares, and each variable, its own or the -// package's, whose every assignment in it keeps it a constant duration, read in -// the order they are written so that one built from another counts. A `:=`, +// package's, and each struct field it sets (`cfg.Timeout`), whose every +// assignment in it keeps it a constant duration, read in the order they are +// written so that one built from another counts. A `:=`, // `=` or `var` of a constant duration keeps it so, as does a `var` with no // value (the zero duration) and a step by a constant (`limit *= 5`, `n++`); // so does putting back a value saved from it while it was constant. A bound @@ -330,9 +343,10 @@ func withLocalConsts(body *ast.BlockStmt, consts map[string]bool) map[string]boo return all } -// valueName is the name an assignment to e sets: an identifier, or -// `.` for a value an external test package sets through the -// package's name; "" for anything else. +// valueName is the name an assignment to e sets: an identifier, or `.` +// for a selector on one, a value an external test package sets through the +// package's name or a field of a local struct (`cfg.Timeout`); "" for anything +// else. func valueName(e ast.Expr) string { switch x := e.(type) { case *ast.Ident: @@ -428,13 +442,14 @@ func isPkgSel(sel *ast.SelectorExpr, pkg, name string) bool { // time.Since itself, on a variable taken from it by `:=` or `var` and on // time.Now().Sub, written either way round, against a unit literal, a // constant and a conversion; against a constant the function declares, a -// variable it gives only constant durations, stepped by a constant or -// declared with no value first; against a package variable declared with a -// constant duration, set to another and put back; and, from an external test -// package, against the package's constant or such a variable through the -// package's name. It passes a bound held through a helper, one read off -// another clock, one against a measured value, a variable also given a -// measured value or put back through a parameter, a package variable no +// variable or a struct field it gives only constant durations, stepped by a +// constant or declared with no value first; against a package variable +// declared with a constant duration, set to another and put back, or declared +// from one a later file declares; and, from an external test package, against +// the package's constant or such a variable through the package's name. It +// passes a bound held through a helper, one read off another clock, one +// against a measured value, a variable also given a measured value or put +// back through a parameter, a field set elsewhere, a package variable no // syntax shows constant, another package's constant, and a lower bound // (wallClockFixture). func TestTheWallClockAuditReadsEachShape(t *testing.T) { diff --git a/internal/core/lint/wallclock_shapes_test.go b/internal/core/lint/wallclock_shapes_test.go index 95eb3c3589..91699bbd75 100644 --- a/internal/core/lint/wallclock_shapes_test.go +++ b/internal/core/lint/wallclock_shapes_test.go @@ -23,8 +23,9 @@ func wallClockFixtureDir(t *testing.T) string { // TestFlagged function's bounds, and nothing in a TestPassed one. var wallClockFixtureWant = map[string]int{ "x/x_test.go TestFlagged": 4, - "x/x_test.go TestFlaggedLocally": 3, + "x/x_test.go TestFlaggedLocally": 4, "x/x_test.go TestFlaggedStepped": 3, + "x/x_test.go TestFlaggedLater": 1, "x/x_ext_test.go TestFlaggedOutside": 2, } @@ -45,7 +46,17 @@ var Wait = 2 * time.Second // Measured is a variable whose value no syntax shows constant. var Measured = measure() +// Held is declared from a variable a file that sorts after this one declares. +var Held = Ask + func measure() time.Duration { return 0 } +`, + "y.go": `package x + +import "time" + +// Ask is a variable declared with a constant duration, after Held's file. +var Ask = time.Minute `, "x_test.go": `package x @@ -81,6 +92,17 @@ func TestFlaggedLocally(t *testing.T) { } if stall/2 < time.Since(start) { } + var cfg struct{ Timeout time.Duration } + cfg.Timeout = 2 * time.Second + if took > cfg.Timeout { + } +} + +func TestFlaggedLater(t *testing.T) { + start := time.Now() + took := time.Since(start) + if took >= Held/2 { + } } func TestFlaggedStepped(t *testing.T) { @@ -128,10 +150,16 @@ func TestPassed(t *testing.T) { } if took > Measured { } + c := config() + if took > c.Timeout { + } } func clock() time.Duration { return 0 } func limit(d time.Duration) time.Duration { return d } +func config() struct{ Timeout time.Duration } { + return struct{ Timeout time.Duration }{2 * time.Second} +} `, "x_ext_test.go": `package x_test From 4e4e89805cfcb5f5cde8324072e7b248bd337b1f Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:05:09 +0000 Subject: [PATCH 11/11] test: judge the release-hold read's deadline through testtiming The release-hold test that reached main beside this branch held the judgement a deadline ends to half the hung git's stall with its own comparison. The wall-clock audit refuses a bound written that way; the check is now testtiming.CutShort against the same stall, the bound it already meant. Refs: iss-2612022218392055 Assisted-by: Claude:claude-opus-5-5 --- internal/core/autonomy/owedread_releasehold_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/core/autonomy/owedread_releasehold_test.go b/internal/core/autonomy/owedread_releasehold_test.go index fde4d1d0ca..977d608ce8 100644 --- a/internal/core/autonomy/owedread_releasehold_test.go +++ b/internal/core/autonomy/owedread_releasehold_test.go @@ -18,6 +18,7 @@ import ( "github.com/intentdriven/abcd/internal/core/claim" "github.com/intentdriven/abcd/internal/fsutil" "github.com/intentdriven/abcd/internal/localtier" + "github.com/intentdriven/abcd/internal/testtiming" ) // The release the fixtures cut, and the no-reply addresses that name the @@ -563,8 +564,8 @@ func TestTheStopCheckJudgesTheReleaseHoldBounded(t *testing.T) { if err != nil { t.Fatal(err) } - if took > holdStall/2 { - t.Errorf("the judgement ran %s past a deadline that ended while git hung; it stops with it", took) + if err := testtiming.CutShort.Check("the judgement a deadline ended while git hung", took, holdStall); err != nil { + t.Errorf("%v; it stops with the deadline", err) } if !owed.Incomplete { t.Errorf("a judgement the deadline ended marks the reading cut short: %s", describe(owed))