Repository navigation
test: guard against new timing patterns in test code, and migrate the next tests to testutil - #1182
Conversation
…aitFor copies Part 3 of the flaky-test plan. internal/timingguard fails when a test file gains time.Sleep, a deadline poll loop, or a time.After select timeout. A checked-in baseline per file and kind only shrinks. //timing:ok <reason> excuses a real case. Local waitFor copies in proxy, dash, keepalive and internal/modelinfo now call testutil.WaitFor or WaitForState. TestHandlerKeysRowsAndKeepAliveByThread waits for the keeper hand-off instead of reading it right after the last row. Test-only. No behavior change. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…dKeepAliveByThread Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…to the guard message Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (bob, user of @amiddavid) | IBM Bob Shell 1.0.3 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 9573dab57f48 |
approve |
Verdict: approve
Findings
None. The PR is a pure test infrastructure improvement with no production code changes.
Non-blocking
- The timing guard is a valuable addition. It prevents flaky tests on slow CI runners by enforcing the use of
testutil.WaitForhelpers instead of fixed sleeps and polling loops. - The ratchet mechanism (baseline only shrinks) is the right design. It prevents new timing patterns while allowing gradual cleanup of existing ones.
- The escape hatch (
//timing:ok <reason>) with mandatory reason is well-designed. It allows legitimate cases (injected delays, testing timing behavior) while preventing abuse.
What I checked
-
New package
internal/timingguard: Implements a static analysis tool that scans test files for three timing patterns:sleep(time.Sleep or bare <-time.After),poll(for loops with time.Now().Add deadlines), andafter(select cases on time.After). The scanner handles aliased imports, deadline variables, and distinguishes select cases from bare receives. The baseline file lists existing patterns per file and kind. The test enforces that counts only go down, never up. -
Baseline file accuracy: The baseline.txt file lists 73 test files with timing patterns. The format is correct (file path, then kind=count pairs). The guard's own tests verify the baseline round-trips and the ratchet mechanism works.
-
Test refactorings in 4 files:
keepalive/keeper_test.go: Three polling loops replaced withtestutil.WaitForState. Each provides a descriptive message and a state function that shows current values. The logic is equivalent: wait for a condition with a long safety bound instead of a fixed 2-second deadline.proxy/feedback_test.go: One polling loop replaced withtestutil.WaitForState. The mail sink is polled until it contains the expected text. Equivalent behavior.proxy/thread_test.go: AddedwaitForRowscalls between sends to wait for the async row recording to complete. The comment explains this prevents a test-only race where two rows could take IDs in the wrong order. This is a test fix, not a behavior change. Also added a wait for the keeper to hold entries before asserting the count. Both changes make the test more robust.proxy/dash_test.go: One polling loop replaced withtestutil.WaitForState. The recorder's written count is polled. Equivalent behavior with better diagnostics.
-
Guard test coverage: The guard has 11 test cases covering: each pattern kind, the escape hatch (line above and same line), rejection of empty reasons, exemption of non-test files and internal/testutil, aliased imports, the ratchet mechanism (fails on increase and decrease), and baseline round-trip. Coverage is thorough.
-
Exemption of internal/testutil: Correct. The helpers themselves must sleep and poll to implement the wait logic. The exemptPrefixes list includes "internal/testutil/".
-
No production code changes: Verified. All changes are in test files or the new guard package. No changes to components, apply, proxy (non-test), or any other production package.
-
Follows repo rules: The PR adds test infrastructure only. It does not change behavior, add data dependence, or touch the fail-open path. The guard itself is a build-time check, not runtime code. The ASD-STE100 style is followed in comments and error messages.
-
DCO and commit format: Not checked (cannot run git log in this worktree). The PR description should confirm DCO sign-off and conventional commit format.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (bob, user of @amiddavid) | IBM Bob Shell 1.0.3 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 9573dab57f48 |
approve |
Verdict: approve
Findings
None. The PR adds a timing guard to prevent flaky tests on slow CI runners and fixes several existing timing patterns. The implementation is correct.
Non-blocking
-
internal/timingguard/timingguard_test.go:137 — The
deadlineNamesfunction walks the entire function body to find deadline variables. For deeply nested code, this could be slow. Not a defect, but consider adding a depth limit if performance becomes an issue. -
keepalive/keeper_test.go:735 — The
waitRefreshedfunction acquiresk.muinside the condition function that WaitForState calls repeatedly. This works correctly but creates lock contention during the poll loop. The alternative (snapshot outside the loop) would race with concurrent updates. The current approach is correct for this use case.
What I checked
-
Guard logic: The AST scanner correctly identifies all three timing patterns (sleep, poll, after). It handles aliased imports, escape hatches, and exempts the testutil package itself.
-
Baseline accuracy: The baseline file lists 75 test files with remaining timing patterns. This is expected — the PR adds the guard and fixes some patterns, but not all at once. The ratchet mechanism (counts only shrink) prevents new patterns from entering.
-
Test changes: Reviewed all modified test files. Each change replaces a fixed timeout or poll loop with
testutil.WaitForortestutil.WaitForState. The replacements are correct:waitForRowsinproxy/dash_test.gonow uses WaitForState with a descriptive state functionwaitPings,waitSkipped,waitRefreshedinkeepalive/keeper_test.gofollow the same patternwaitForSinkinproxy/feedback_test.gocaptures the sink content in the state function- The thread test in
proxy/thread_test.goadds a wait after each send to prevent row ID ordering issues
-
Escape hatch: The
//timing:ok <reason>marker works on the same line or the line above. Empty reasons are rejected. The guard tests verify this behavior. -
Fail-open: Not applicable. This is test infrastructure, not production code. The guard itself fails the test build when new patterns appear, which is the intended behavior.
-
Security: No security implications. The guard operates on test files only and does not affect production code or runtime behavior.
-
Data dependence: Not applicable. This is build-time tooling.
-
Conventions: The package follows Go conventions. The baseline file format is simple and human-readable. The error messages guide developers to the fix.
Main removed the local waitFor helper in #1182. dash/currency_test.go still called it, so go vet failed in CI (build-test, record). Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ount (#1190) The accountant now prices a thinking block that comes back at the thinking tokens of the response that made it (#1187). Measured on Opus 5.5 (accountant#77), a sent-back block bills its thinking_tokens plus 0 to 4 tokens; the old fixed price was 19 to 87 times too low. New library package thinkcount: a bounded table from a signature hash to a count (20,000 blocks, oldest out first, saved as JSON), FromBody for a JSON response or a whole stream, and a Collector that reads an SSE stream as the bytes go by, with limits. The proxy feeds a Collector on the Anthropic chat routes and records the count for a 2xx response with usage; the accountant state file gets an optional thinking field. github.com/rossoctl/accountant moves from v0.1.2 to v0.2.0. Behavior change, 3 parts (no switch; pinning the accountant back to v0.1.2 turns off all 3): 1. Users whose responses carry thinking blocks, when a component drops or shortens one. Old: the saving was the signature at 1 token per 250 bytes (about 12 tokens for a 3,000-byte signature). New: the block's own thinking_tokens (about 1,000). The text ratio of a request with thinking blocks falls by up to about 5%. Models that strip thinking are out of scope by the owner's decision. 2. accountant#79: a model change that no operation reports. Old: a charged break with no ChangeID (one Sonnet-to-Opus switch showed -$0.205). New: the break is in the baseline (model_changed). 3. accountant#82: a router's model setting ends on the request that ended it, so a later client switch goes to the baseline. Owner's yes, 2026-11-17, in the integrator session: "1190 yes". Data dependence: metadata only, no change in level. A new table holds a 64-bit hash of each thinking signature and a token count, no signature and no text. The Accountant savings row is updated. Reviews: 3 offload review rounds: both approve at b2e3828. After it: be15cd5 changes only comment lines (approval-still-valid: COMMENTS ONLY). The new tests use no poll loop that the #1182 timing guard counts. Signed-off-by: DAVID BOAZ <[email protected]> Assisted-By: Claude (Anthropic AI) <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.327 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 2 of 2 | 9573dab57f48 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Round 1, reviewer 1: approved, no findings. Nothing to track.
- Round 1, reviewer 2 (mine): approved, no findings. Both non-blocking notes stand; the author did not reply, and no commit followed, so nothing changed.
Non-blocking
- dash/reprice_test.go:223 — This
time.Sleep(60 * time.Millisecond)has no//timing:okmarker. Two identical negative waits in the same file (lines 74 and 256) carry one. The baseline holds this third one assleep=1, so the guard passes. Mark it the same way and regenerate the baseline, for consistency.
What I checked
- Last review: round 1, 9573dab, 2026-11-16T20:30:47Z.
- New commits read: 0.
git log --stat 9573dab57f48052d7724ce7ae2fcf16cd593f96d..HEADprinted nothing. The head is the same as round 1. - Read in full: 2 reviews, 0 comments, 0 inline comments (from the three files).
- New items since my last review: none. My round-1 review is the newest item in the PR. The comments and inline lists are empty.
- Re-read the full diff (
git diff ea73ea7d..HEAD, 1173 lines) with fresh context, and checked:internal/testutil.WaitForandWaitForStateexist (internal/testutil/testutil.go:38,45) with signatures that match every call site.- Every edited file still compiles by inspection:
fmtandtimeimports are present where the new code uses them (proxy/thread_test.go,proxy/feedback_test.go,keepalive/keeper_test.go,dash/grace_test.go,dash/reprice_test.go), andtimeis dropped only where no use remains (proxy/feedback_test.go). - The guard's AST logic: select-case
<-time.Aftercounts once asafterand not again assleep(theinSelectmap suppresses the second visit); the escape hatch matches the same line or the line above; the alias and dot-import handling is correct; the walk skips.dirs,vendor,testdata,node_modules. - The ratchet: counts up fail, counts down fail until regen, a file that leaves the tree fails, equal counts pass. The guard's own tests cover each case.
- The baseline matches the tree: the one unmarked sleep in
dash/reprice_test.gois the baseline'ssleep=1entry. All marked sleeps are marked on the same line. - Test-behaviour changes are sound:
waitForRowsuses>=so the per-send wait inproxy/thread_test.gocannot under-wait; the keeper wait pollsStats().Liveon the test goroutine;waitRefreshedreadsgotonly from the same goroutine that wrote it. - Repo rules: no production code changes (all edits are
*_test.go,CONTRIBUTING.md, and the new test-only guard package), no data dependence, no behavior change, fail-open not touched.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.327 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 2 of 2 | 9573dab57f48 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Reviewer 1, round 1: no findings. Still true. I re-read the full diff with fresh eyes.
- Reviewer 2, round 1: no findings, two non-blocking notes. I checked both myself:
deadlineNameswalks the whole function body. Correct as written. Performance is not a concern: the guard parses test files once per test run.waitRefreshedlocksk.muinside the condition function. Correct. A snapshot outside the loop would race. I agree with the author's shape.
Non-blocking
- internal/timingguard/timingguard_test.go (scanSource, walkFunc) — the guard does not count an assign-receive of
time.Afteroutside a select.x := <-time.After(d)blocks like a sleep, but no case inwalkFunchandles an*ast.AssignStmtat statement level.isAfterRecvsupports it, yet onlyCommClauseandExprStmtcall it. A new flaky wait in that form would pass the guard. The doc comment only promises the bare form, so this is a gap, not a wrong count. - internal/timingguard/timingguard_test.go (okMarker check) —
strings.HasPrefix(c.Text, okMarker)also matches//timing:okay …. The text after the prefix ("ay …") counts as the reason. A dot-import oftimealso evades the scanner (Sleep(…)with notime.qualifier). Both are contrived. Note them for a later tightening. - dash/reprice_test.go:223 — one
time.Sleep(60ms)keeps a plain comment while its two twins carry//timing:ok. The baseline listssleep=1for this file, so the ratchet covers it. Marking all three would be more consistent.
What I checked
- Last review: round 1, 9573dab, 2026-11-16T20:30:07Z
- New commits read: 0.
git log --stat 9573dab5..HEADprinted nothing; HEAD is still 9573dab, as the round-2 brief said to expect. - Read in full: 2 reviews, 0 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt) - New items since my last review: reviewer 2's round-1 review (posted 40 s after mine). I checked its two non-blocking notes myself; both hold and neither is a defect.
- Re-read the whole diff
ea73ea7d..HEAD(11 files, +775/−109) and the code around each hunk. internal/timingguard/timingguard_test.go: read all 595 lines. The scanner handles aliased imports,_/.imports (skips), deadline variables in init, cond and body, select cases vs bare receives, and the same-line/line-above escape hatch with a non-empty reason.comparefails both directions, so the baseline only shrinks. The-run TestTestTimingprefix in the documented regenerate command matchesTestTestTimingBaseline.- Baseline vs tree, without running Go (live tests are not approved): for
sleepandafterI listed every*_test.gofile withtime.Sleep/<-time.Afterand compared it with the baseline entries. Only differences:internal/testutil/(exempt by prefix) andinternal/timingguard/timingguard_test.go(pattern strings inside string literals, not AST calls). Spot counts match onproxy/keepalive_inflight_test.go(sleep 18, after 2),keepalive/substitute_test.go(sleep 9),dash/sse_test.go(sleep 3, after 4),modes/modes_test.go(sleep 2, after 3),dash/reprice_test.go(sleep 1 unmarked of 3). testutil.WaitFor/WaitForStateexist at the base commit with a long safety bound andt.Fatalfon timeout, cut to the test deadline minus 5 s. The migrations keep the old conditions and add state strings.- Migrations in
dash/grace_test.go,dash/reprice_test.go,internal/modelinfo/builtin_test.go,internal/modelinfo/litellm/decode_test.go,keepalive/keeper_test.go,proxy/dash_test.go,proxy/feedback_test.go: each replaces a fixed deadline loop withWaitFor/WaitForStateon the same condition.waitForSinkreturns the capturedgot, which holds the read that satisfied the condition. Imports check out (fmtpresent where new code uses it,timedropped only where no longer used). proxy/thread_test.go:sendnow waits forsentrows before the next request, and the test waits for the keeper to hold 2 entries. Both close real races (deferred row recording and deferred keeper hand-off after the response is on the wire). Test-only; no behavior change.- No production code changes: only
*_test.gofiles,CONTRIBUTING.md, and the newinternal/timingguardpackage. No data dependence, no fail-open path touched. - Commits: conventional titles, DCO
Signed-off-byon all three,Assisted-By:attribution.
Summary
Part 3 of the flaky-test plan. Test-only, no behavior change.
internal/testutil,testutil/testdb).docs/data-dependence.mdneeds no change.The rule for test authors
The guard is
internal/timingguard. It runs ingo test ./..., somake testand CI run it with no new tool. It reads the code withgo/astand checks*_test.gofiles only. It skipsinternal/testutil.It flags three kinds:
time.Sleep, or a bare<-time.After(...).forloop whose limit is atime.Now().Add(...)deadline ortime.After(...).selectcase on<-time.After(...), used as a test timeout.How to fix:
testutil.WaitFor(t, what, cond)ortestutil.WaitForState.testutil.NewUpstream(...).WaitForCall(...).//timing:ok <reason>. Use it for an injected fake delay, or a sleep that is the thing under test. The reason must not be empty. An empty reason fails the guard.The baseline
internal/timingguard/baseline.txtholds the existing cases, per test file and kind. No line numbers.go test ./internal/timingguard -run TestTestTiming -updateWhy a new package and not
internal/boundary:boundaryenforces one rule, the dispatch split, on production code. This rule covers test files. A separate package keeps each rule and allow-list apart.What changed
New:
internal/timingguard(guard, its tests, baseline).Migrated to
testutil.WaitFor/WaitForState. The polling loops are gone:proxy/dash_test.gowaitForRows(about 100 callers keep the name)proxy/feedback_test.gowaitForSink, and themailed_atloopdash/grace_test.gowaitForRowCountdash/reprice_test.gowaitFor(copy deleted, callers usetestutil.WaitFor)keepalive/keeper_test.gowaitPings,waitSkipped,waitRefreshed, the expiry wait, and the kill-switch waitinternal/modelinfo/litellm/decode_test.go,internal/modelinfo/builtin_test.godash/reprice_test.gonow carry//timing:ok.Not migrated:
modes/modes_test.gowaitForandproxy/modes_test.goawaitSnapshot. Open PR feat(proxy): async mode — cache-safe deferred compaction (HELD: benefit unmeasured since #34) #35 changes both files.Fixed
TestHandlerKeysRowsAndKeepAliveByThread. It had two causes, both in the test:WaitForStateon the count.waitForRowsis now the shared helper.Production code is not at fault.
Open PR feat(offload): extract_llm_ride, a batched triage that rides the session's prompt cache #475 also edits
proxy/thread_test.go, in other hunks (lines near 300 and 341). No overlap.How it was tested
//timing:ok reasonis accepted;//timing:okwith no reason is rejected;internal/testutilare ignored;-race.TestHandlerKeysRowsAndKeepAliveByThreadat-count=100under load, before and after;-count=20under load.The owner plans one full Part A over every PR merged during the outage. This PR will be part of it.
Follow-ups
Remaining work (the baseline): sleep 169, poll 72, after 52, across 87 test files. Each PR that migrates a file lowers the baseline with
-update.