Skip to content

Timeouts read an injectable clock, and the suite moves time instead of timing it - #274

Merged
Mpdreamz merged 1 commit into
mainfrom
fix/test-clock
Nov 16, 2026
Merged

Mpdreamz merged 1 commit into
mainfrom
fix/test-clock

Conversation

@Mpdreamz

Copy link
Copy Markdown
Contributor

Tests bounded wall-clock durations and failed on loaded runners (took < .milliseconds(800) at 1.06 s, the forty-asks < .seconds(3), and the like). This gives the code that owns those timeouts a clock and rewrites the tests to move time instead of measuring it.

The clock seam

  • PermissionHook.wait / exchange and Ledger.summarizeThenRemove take clock: any Clock<Duration> = ContinuousClock(). That is Swift's protocol, spelled _Concurrency.Clock in HeedCore because heed's own Clock enum (display time) shadows it. The enum is unchanged.
  • The hook blocks on sockets on a plain thread, so its deadlines are a new Deadline: an instant on any clock, which ControlClient reads before every poll (connect, write, each read, the backlog retry). On the continuous clock a poll waits for all the time left, as before. On any other clock a poll cannot see time pass, so it waits in 5 ms slices and reads the clock again. Moving a manual clock past the ceiling therefore ends the wait, with real sockets.
  • exchange(received:) hears each receipt as the hook takes it. Tests need it to move time only after the receipt; without it they race.
  • summarizeThenRemove keeps the dispatch timer from Ledger removal: dispatch-timer deadline, and a test that signals instead of timing #268 on the continuous clock and sleeps on any other clock. This replaces armTimer.
  • The pauses between reconnect attempts (Thread.sleep) stay real time. PermissionBroker already takes now:, and ControlServer has no timeout of its own besides its 1 s slow-reader write poll, which is untouched.

Behaviour with the default clock is the same: the same deadlines, and polls bounded by the time left.

Tests

  • ManualClock (tests only): time moves only on advance, sleep waits for it, and reads counts how often now was read. Hang guards waitUntil and finished give up after ten real seconds and record a failure.
  • PermissionRoundTripTests and ApprovalTests' aSlowAnswerTimesOut… run the hook on the manual clock. Each window closes because the test advanced past it, and the test asserts the outcome: .ceiling, .noReceipt, and that heed had not answered yet. Heed's own answer arrives only after ten real seconds, as a hang guard.
  • Forty asks are answered while time stands still, and the slow ask still waits. Then the test advances past its ceiling.
  • anAnswerIsNotHeldBackByABusyCooperativePool now asserts an order instead of took < 500 ms: heed's answer arrives before half of the queued medium-priority work has run.
  • The ledger removal test advances the manual clock past the timeout.
  • DomainTests' 200k-character branch name keeps its outcome check. Its < 5 s moves to BranchNameBench (mise run bench).
  • A grep for timeIntervalSince(, ContinuousClock.now - and took < in Tests finds no duration assertion left outside Bench. LLMRunnerTests.noMoreThanTheConcurrencyRunAtOnce asserts a lower bound (>= 2 s), which load cannot break, so I left it to the LLMRunner fake work.

Verification

  • mise run fmt and mise run lint are clean. A full mise run test passed: 2516 tests, on a machine at load average about 100–240.
  • I ran the affected suites (PermissionRoundTrip, Approval, Ledger, ManualClock) 15 times in a row: 0 failures.
  • Each mutation made the tests fail. None of them hung:
    • the hook ignores its ceiling: the trickle, slow-answer and forty-asks tests fail, the last two at the hang guard
    • the hook ignores its receipt window: noReceipt… fails
    • a receipt does not extend the wait to the ceiling: aReceiptKeeps… fails, 3 out of 3 runs
    • the reply task runs at .medium: the busy-pool test fails, with 1199 of 1200 tasks run before the answer
    • the removal ignores its timeout: the ledger test fails

Not tested

  • The 5 ms slice runs only under a non-continuous clock, so the real hook in production never runs it.
  • No test checks that the default-clock path keeps its exact poll timeouts.
  • The app-side wait_seconds fallback in AppModel+Approvals still uses Task.sleep. It is app layer and not under test.

🤖 Generated with Claude Code

…f timing it

The permission hook's ceiling, receipt window and rejoin window, the fallback
report's moment, and the ledger's removal wait now run out on a clock passed in
(`any Clock<Duration>`, Swift's protocol), `ContinuousClock()` by default. heed's
own `Clock` (display time) is unchanged.

The hook blocks on sockets on a plain thread, so its deadlines are a `Deadline`:
an instant on any clock, which `ControlClient` reads before every poll. On the
continuous clock a poll waits for all the time left, as before; on any other
clock it waits in 5 ms slices and reads the clock again, so moving a manual clock
past a deadline ends the wait. `exchange` takes a `received` callback that hears
each receipt as the hook takes it. `summarizeThenRemove` keeps its dispatch timer
on the continuous clock and sleeps on any other, replacing `armTimer`.

Tests:
- A test `ManualClock` (time moves only on `advance`) and hang guards
  (`waitUntil`, `finished`, ten real seconds) that fail rather than hang.
- PermissionRoundTripTests and ApprovalTests' ceiling test run the hook on the
  manual clock: a window closes because the test advanced past it, and the
  outcome is asserted (`.ceiling`, `.noReceipt`, heed had not answered yet).
  The forty asks are answered while time stands still, then the slow one's
  ceiling is reached. The busy-pool test asserts an order: heed's answer is in
  before half the queued work has run.
- The ledger removal test advances the manual clock past the timeout.
- The 200k-character branch name keeps its outcome check; its timing moves to
  `BranchNameBench`.

No test asserts a duration any more. Mutations, each caught without a hang:
the hook ignoring its ceiling, ignoring its receipt window, a receipt not
extending the wait, the reply task losing its high priority, the removal
ignoring its timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the bug Something isn't working label Nov 16, 2026
@Mpdreamz
Mpdreamz merged commit 933afb8 into main Nov 16, 2026
5 checks passed
@Mpdreamz
Mpdreamz deleted the fix/test-clock branch November 16, 2026 15:10
Mpdreamz added a commit that referenced this pull request Nov 16, 2026
…ner's tests answer in-process (#280)

Fixes `LLMRunnerTests.interactiveCallsGoFirst` failing in full-suite
runs and cuts the suite's wall time.

## Diagnosis (measured on this machine, load average 125–235 throughout)

- **Child processes are not the problem.** A count of the test helper's
children every 0.5 s during full runs peaked at 32 and stayed mostly
between 2 and 4. A cap would not help, so this PR adds none.
- **The pool is saturated at the start of a run.** A temporary probe
test timed a 10 ms `Task.sleep`. Its first sleep came back after **16.4
s**. After that, sleeps mostly overshot by 5–10 ms. Swift Testing starts
every test at once, so for about the first 16 s each continuation waits
behind the whole backlog. That is why nearly every test reports 16–17 s
in the xunit file. Every await costs seconds during that window.
`interactiveCallsGoFirst` needs a dozen or more of them before its
shell-script agent records the first call, which is how it ran past its
10 s deadline (failed 4 of 4 baseline runs here).
- **What held the pool threads.** `sample` during runs showed all 8
cooperative threads busy in CPU-bound synchronous tests. The largest was
TurnEnd's regex: one thread for 30–58 s. #272 fixed that, and the
baseline below already includes it. There were a few `waitUntilExit`
calls (TempRepo and others), about 1% of pool samples. No test was
sleeping or spinning on the pool.
- **ProcessRunner's poll after exit.** Counted with a temporary counter:
457 of 665 commands (69%) still had a pipe open when they exited.
ProcessRunner then slept in 50 ms steps until the pipe closed, which
added up to **55 s** in one run, plus a pool round trip per step. With
this change the same count is 428 of 565, waiting **10.5 s** in total.
- **Two more found on the way.**
`HostCallTests.theHostsHeedWritesItsCallAndPrintsTheAnswer` hung for
more than 10 minutes in `waitUntilExit` after the test resumed on
another thread, with no child process left (seen in a `--no-parallel`
run). In parallel runs it failed once when its script's 20 s timeout
fired first. `scannerFindsMainCheckoutsOnly` stats every entry of
`$TMPDIR`, which has 71,242 entries here: tests leak folders, 14,207 of
them from the LLM runner's FakeCLI.

## Changes

- `ProcessRunner`: each pipe buffer resumes a continuation when its pipe
ends. Collection gives up after the same 2 s, and returns at once when
the task is cancelled, as the old loop did. New tests cover both cases:
output written after the exit is kept, and a child that holds the pipes
is not waited for.
- `LLMRunner`: a new `execute: Execute` parameter, defaulting to
`LLMRunner.process`, runs detection checks and calls. It is built the
same way as the existing `resolve`. Production behaviour is unchanged.
- `LLMRunnerTests`: an in-process `FakeAgent` now answers 26 of the 30
tests. The queue tests hold calls on a continuation.
`noMoreThanTheConcurrencyRunAtOnce` counts the most calls running at
once instead of asserting that at least 2 s passed. Four tests keep the
shell-script FakeCLI to prove the process path: the login check, stderr
as the reason, the timeout, and the call log row.
- `HostCallTests`: the test awaits its process through
`terminationHandler`. It waits as long as the script allows, under a
2-minute time limit.
- `scannerFindsMainCheckoutsOnly`: the test scans a folder of its own.

## Timings (`swift test --skip-build`, full suite, 3 runs each)

| | wall (median) | test run (median) | interactiveCallsGoFirst |
|---|---|---|---|
| before (main abe9c0d incl. #272), load 157–165 | 88.8 s (88.8 / 89.3
/ 70.3) | 74.7 s | failed 3/3 |
| after, load 126–151 | 48.7 s (43.7 / 48.7 / 55.5) | 43.3 s | passed
3/3 |

The machine was less loaded during the after runs, so part of the drop
comes from that. The probe numbers above (time spent waiting for pipes,
process count) do not depend on load. Rebased onto #274/#275, the full
suite passed in 34.0 s.

Slowest tests, median, before → after. These times include the
start-of-run queue wait: RunGit aRunPushes… 34.7 → 20.2 s,
scannerFindsMainCheckoutsOnly 32.9 s → out of the top 12, ArchiveGit
removingSavesUncommitted… 32.7 → 18.3 s, OriginWorld everyRecordedCall…
31.5 → 18.1 s, ArchiveGit pushedWork… 31.5 → 17.2 s, pruningDrops… 31.5
→ 17.6 s, removingSavesUnpushed… 31.1 → 17.0 s, gitDiffScopes 28.7 →
15.5 s, everyLineReachesTheAgent… 28.1 s → out of the top 12, LedgerGit
readsAWorktree… 28.0 → 15.1 s.

## Tests of the tests

Each mutation was built and run against the changed tests:
- `ended()` returns at once: `outputAfterTheExitIsKept` fails, and so do
the FakeCLI process-path tests.
- The 2 s give-up never abandons: `aChildHoldingThePipesIsNotWaitedFor`
fails at its time limit.
- `release` ignores priority: `interactiveCallsGoFirst` fails for both
arguments.
- Concurrency + 1: `noMoreThanTheConcurrencyRunAtOnce` fails
(`mostAtOnce == 2`), and so does `interactiveCallsGoFirst`. Both fail
fast: the first version of these tests hung the run under this mutation,
so the waits now count calls answering plus calls queued, and each held
fake is released on the way out.

## Not done / untested

- The leaked temporary folders are left for chore/test-hygiene, which is
already changing these files. Expect a small conflict in
`LLMRunnerTests` (`Scratch.folder` for FakeCLI).
- The remaining synchronous `waitUntilExit` helpers (TempRepo,
RunIsolation, Telemetry, HookCommand) are unchanged. They run in sync
tests with no thread hop, and took about 1% of pool samples.
- `theSameCallAskedTwiceAtOnceRunsOnce` still cannot tell joining a
running call from a cache hit, as before this PR. Its mutation was not
run.
- The fast return on cancellation in `ProcessRunner` has no test.
Telling it apart from the 2 s give-up would mean asserting a duration.
- `outputAfterTheExitIsKept` relies on a 0.1 s background write landing
inside the 2 s window. That is the same window production uses.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant