Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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(<constant>) or a poll loop until time.Now().Add(<constant>), 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.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
60 changes: 26 additions & 34 deletions cmd/precheck-audits/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
}
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
}

Expand Down
10 changes: 10 additions & 0 deletions internal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 23 additions & 8 deletions internal/adapter/gitleaks/augmenter_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand All @@ -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")
Expand Down
13 changes: 11 additions & 2 deletions internal/core/autonomy/livework_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -118,16 +119,24 @@ 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")
}
if !strings.Contains(it.Live.What, "abcd process 4242") || !strings.Contains(it.Live.What, "queued or started at "+shortHead(f.head("feat/live"))) ||
!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)
Expand Down
5 changes: 3 additions & 2 deletions internal/core/autonomy/owedread_releasehold_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down
Loading
Loading