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..8e830da87f --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022252475157-a-test-judges-how-long-something-took.md @@ -0,0 +1,8 @@ +--- +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. + +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/.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..3065d8cb67 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022337510454-iss-2612022218392055-is-resolved-without.md @@ -0,0 +1,10 @@ +--- +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. + +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 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/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 56% 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..86ca93a37c 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 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 --- 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/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 5611258ccc..95f5cf5980 100644 --- a/internal/README.md +++ b/internal/README.md @@ -487,6 +487,16 @@ 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; `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/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/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/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)) diff --git a/internal/core/autonomy/promptlog_reap_test.go b/internal/core/autonomy/promptlog_reap_test.go index 67edc288c3..6543531ba3 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 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 +// 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,27 @@ 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). 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{} 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 +74,65 @@ 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) + } + 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) + } +} + +// 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) 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 f0a97a4efc..0dff366e9a 100644 --- a/internal/core/github/scheduled_test.go +++ b/internal/core/github/scheduled_test.go @@ -9,6 +9,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 @@ -226,21 +228,28 @@ 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/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/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)) + } +} 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/implement/loop/widen_paths_test.go b/internal/core/implement/loop/widen_paths_test.go index c80a59a130..1b027f4d9d 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,31 @@ 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. 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: 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: 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/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/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/lint/wallclock_audit_test.go b/internal/core/lint/wallclock_audit_test.go new file mode 100644 index 0000000000..e3310cd7c7 --- /dev/null +++ b/internal/core/lint/wallclock_audit_test.go @@ -0,0 +1,520 @@ +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 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 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 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; +// - 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 +// 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/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. +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. +// +// The package's constants count, and so does each package variable declared +// 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 { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + var files, tests []*ast.File + var names []string + own, ownInTests := "", "" + 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) + } + 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) + } + } + } + // 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 + } + } + } + } + } + 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 +} + +// 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). +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 { + 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 + } + } + } + } + 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 +} + +// 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, 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 +// 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 { + all[k] = true + } + declared, varied := map[string]bool{}, map[string]bool{} + assign := func(e ast.Expr, rhs ast.Expr) { + name := valueName(e) + if name == "" || name == "_" { + return + } + if rhs != nil && isConstDuration(rhs, all) { + all[name] = true + } else { + 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 { + 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) == 0: + all[name.Name] = 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 { + switch { + case (s.Tok == token.DEFINE || s.Tok == token.ASSIGN) && len(s.Lhs) == len(s.Rhs): + assign(l, s.Rhs[i]) + 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: + 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 +} + +// 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: + 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 { + 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 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 := 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 + } + 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 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 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) { + got := wallClockBounds(t, wallClockFixtureDir(t), "x") + if fmt.Sprint(got) != fmt.Sprint(wallClockFixtureWant) { + t.Fatalf("the scan found %v, want %v", got, wallClockFixtureWant) + } +} + +// 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 ")) + } +} diff --git a/internal/core/lint/wallclock_shapes_test.go b/internal/core/lint/wallclock_shapes_test.go new file mode 100644 index 0000000000..91699bbd75 --- /dev/null +++ b/internal/core/lint/wallclock_shapes_test.go @@ -0,0 +1,193 @@ +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": 4, + "x/x_test.go TestFlaggedStepped": 3, + "x/x_test.go TestFlaggedLater": 1, + "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() + +// 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 + +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) { + } + 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) { + 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 { + } + 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 + +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 { + } +} +`, +} 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/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/core/runner/gatewait_test.go b/internal/core/runner/gatewait_test.go index 92a5e5ac6e..68853b875a 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,34 @@ 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 (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) { - 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, 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)) } 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..9c440bc027 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,25 @@ 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 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 == "" { + 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: 1500 * time.Millisecond}).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/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/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 dad5b2ee93..6eb254954c 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") { diff --git a/internal/testtiming/testtiming.go b/internal/testtiming/testtiming.go new file mode 100644 index 0000000000..d12b06bd8e --- /dev/null +++ b/internal/testtiming/testtiming.go @@ -0,0 +1,129 @@ +// 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: 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" +) + +// 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 +} + +// 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 +// 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..56096ea4d6 --- /dev/null +++ b/internal/testtiming/testtiming_test.go @@ -0,0 +1,120 @@ +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) + } + } +} + +// 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 +// (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 +}