Skip to content

test: guard against new timing patterns in test code, and migrate the next tests to testutil - #1182

Merged
amiddavid merged 3 commits into
mainfrom
test/lint-guard
Nov 17, 2026
Merged

amiddavid merged 3 commits into
mainfrom
test/lint-guard

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

Part 3 of the flaky-test plan. Test-only, no behavior change.

  • Over 30 days, 35 of 1,390 CI runs (2.5%) ran again only because of a flaky test.
  • The cause is a few timing patterns in test code. Parts 1 and 2 added the shared helpers (internal/testutil, testutil/testdb).
  • This PR adds a guard so new tests cannot add the patterns. It also moves the next group of tests onto the helpers.
  • Data dependence: none. No stored customer data is read or changed. docs/data-dependence.md needs no change.

The rule for test authors

The guard is internal/timingguard. It runs in go test ./..., so make test and CI run it with no new tool. It reads the code with go/ast and checks *_test.go files only. It skips internal/testutil.

It flags three kinds:

  • sleep: a call to time.Sleep, or a bare <-time.After(...).
  • poll: a for loop whose limit is a time.Now().Add(...) deadline or time.After(...).
  • after: a select case on <-time.After(...), used as a test timeout.

How to fix:

  • Wait for a condition: testutil.WaitFor(t, what, cond) or testutil.WaitForState.
  • Wait for a request to a fake upstream: testutil.NewUpstream(...).WaitForCall(...).
  • If the case is real, add a line comment on the same line or the line above: //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.txt holds the existing cases, per test file and kind. No line numbers.

  • A count that goes up fails. The message names the file, the kind, both counts and the fix.
  • A count that goes down also fails, with "lower the baseline". The baseline only shrinks.
  • A new test file may have 0.
  • Regenerate the baseline: go test ./internal/timingguard -run TestTestTiming -update

Why a new package and not internal/boundary: boundary enforces 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.go waitForRows (about 100 callers keep the name)
    • proxy/feedback_test.go waitForSink, and the mailed_at loop
    • dash/grace_test.go waitForRowCount
    • dash/reprice_test.go waitFor (copy deleted, callers use testutil.WaitFor)
    • keepalive/keeper_test.go waitPings, waitSkipped, waitRefreshed, the expiry wait, and the kill-switch wait
    • internal/modelinfo/litellm/decode_test.go, internal/modelinfo/builtin_test.go
    • Three negative waits in dash/reprice_test.go now carry //timing:ok.
  • Not migrated: modes/modes_test.go waitFor and proxy/modes_test.go awaitSnapshot. 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:

    1. The handler records the row and hands the request to the keeper in a deferred func. The client can get the response first. The test then sent the next request before the row existed. Two rows took their IDs in the wrong order, and the sort by ID mixed up the threads. Fix: wait for each row before the next send.
    2. The test read the keeper entry count with no sync point. Fix: WaitForState on the count.
    3. The fixed 2 s limit in waitForRows is 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

  • Guard tests feed small source strings. They check that:
    • each kind is caught;
    • //timing:ok reason is accepted;
    • //timing:ok with no reason is rejected;
    • non-test files and internal/testutil are ignored;
    • the ratchet fails both up and down.
  • CI runs the guard on the whole tree, and runs every migrated test, with -race.
  • Not run: load proofs. The eval box went down during this work, and its hostname does not resolve. These are pending:
    • TestHandlerKeysRowsAndKeepAliveByThread at -count=100 under load, before and after;
    • each migrated test at -count=20 under 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.

…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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.WaitFor helpers 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), and after (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 with testutil.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 with testutil.WaitForState. The mail sink is polled until it contains the expected text. Equivalent behavior.
    • proxy/thread_test.go: Added waitForRows calls 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 with testutil.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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 deadlineNames function 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 waitRefreshed function acquires k.mu inside 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.WaitFor or testutil.WaitForState. The replacements are correct:

    • waitForRows in proxy/dash_test.go now uses WaitForState with a descriptive state function
    • waitPings, waitSkipped, waitRefreshed in keepalive/keeper_test.go follow the same pattern
    • waitForSink in proxy/feedback_test.go captures the sink content in the state function
    • The thread test in proxy/thread_test.go adds 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.

@amiddavid
amiddavid merged commit f324e5e into main Nov 17, 2026
8 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 17, 2026
amiddavid added a commit that referenced this pull request Nov 17, 2026
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]>
amiddavid pushed a commit that referenced this pull request Nov 17, 2026
…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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:ok marker. Two identical negative waits in the same file (lines 74 and 256) carry one. The baseline holds this third one as sleep=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..HEAD printed 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.WaitFor and WaitForState exist (internal/testutil/testutil.go:38,45) with signatures that match every call site.
    • Every edited file still compiles by inspection: fmt and time imports 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), and time is dropped only where no use remains (proxy/feedback_test.go).
    • The guard's AST logic: select-case <-time.After counts once as after and not again as sleep (the inSelect map 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.go is the baseline's sleep=1 entry. All marked sleeps are marked on the same line.
    • Test-behaviour changes are sound: waitForRows uses >= so the per-send wait in proxy/thread_test.go cannot under-wait; the keeper wait polls Stats().Live on the test goroutine; waitRefreshed reads got only 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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:
    • deadlineNames walks the whole function body. Correct as written. Performance is not a concern: the guard parses test files once per test run.
    • waitRefreshed locks k.mu inside 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.After outside a select. x := <-time.After(d) blocks like a sleep, but no case in walkFunc handles an *ast.AssignStmt at statement level. isAfterRecv supports it, yet only CommClause and ExprStmt call 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 of time also evades the scanner (Sleep(…) with no time. 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 lists sleep=1 for 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..HEAD printed 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. compare fails both directions, so the baseline only shrinks. The -run TestTestTiming prefix in the documented regenerate command matches TestTestTimingBaseline.
  • Baseline vs tree, without running Go (live tests are not approved): for sleep and after I listed every *_test.go file with time.Sleep / <-time.After and compared it with the baseline entries. Only differences: internal/testutil/ (exempt by prefix) and internal/timingguard/timingguard_test.go (pattern strings inside string literals, not AST calls). Spot counts match on proxy/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 / WaitForState exist at the base commit with a long safety bound and t.Fatalf on 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 with WaitFor/WaitForState on the same condition. waitForSink returns the captured got, which holds the read that satisfied the condition. Imports check out (fmt present where new code uses it, time dropped only where no longer used).
  • proxy/thread_test.go: send now waits for sent rows 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.go files, CONTRIBUTING.md, and the new internal/timingguard package. No data dependence, no fail-open path touched.
  • Commits: conventional titles, DCO Signed-off-by on all three, Assisted-By: attribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant