mac: bound every probe command and stop the updater waiting on probes
Paul's Studio (runner 577e24c) hung in its first probe run: the probes' `simctl list -j devices booted` (Gate.Booted, called by P6's gate) had no deadline, so macProbes.ready never closed, a checks step sat in Ready holding worker.mu, and the self-updater's hold() never got it. Fix 1, every probe command bounded: - mac.QueryLimit (30 s) bounds each query: the capability report, ComputerName, security add/delete, the DNS check, launchctl, pmset, ps, the tools' --version, and the booted list in newMacHost (all through macHost.run with its group kill and WaitDelay). srt's own run of /usr/bin/true gets a minute; shutdown keeps its minute; the gates keep their own limits (P2 20 min, P6 8 min). - A query that times out is noted; P1, P2 and P6 then say "simulator unavailable: simctl did not answer in 30s" (or "Xcode unavailable") and move on. P6 no longer waits out 8 minutes on a stuck CoreSimulator: xcodebuild asks it for destinations even for macOS. - RunProbes has an overall limit, mac.ProbeLimit = 30 min. It is above the gates' own bounds so it never cuts a slow but healthy cold build (a cut P2 would leave checks unsandboxed for good); it is the backstop for a wait nothing else bounds. At the limit the run ends with what it has, the rest "not proven" and listed in Report.Unfinished, ready closes and the worker logs WARN. Fix 2, option (a): Worker.Exec now waits for Ready before taking mu, and checks its context once it has mu. hold() (now Worker.hold) waits only for a step that really runs. Smaller and safer than (b): a three-line move in one function, no new placement rules, and no step ever runs before the probes are ready. The probe goroutine never held worker.mu; only Ready-inside-mu did. Tests (linux, through the Tools seam and newMacHost): - TestMacProbesFinishWhenSimctlHangs: a fake xcrun whose simctl sleeps with a child holding stdout, hanging every simctl or only the booted list. The run finishes in about 1 s at QueryLimit 300ms, ready closes, the verdicts say why, no fake process is left. - TestRunProbesLimit: a command that ignores its context; the run ends at its 300ms limit with P4-P7 not proven. - TestMacUpdateWhileProbesStall: probes stalled forever, the update swaps the binary and stops with ErrUpdated at once, the waiting step ends cancelled; with a gate really running it waits until it ends. Mutations, each restored: - booted without its timeout: SimctlHangs fails (ready never closed). - capability queries without their timeout: SimctlHangs fails. - Ready back inside mu: UpdateWhileProbesStall fails (update waited). - RunProbes waiting on done only: TestRunProbesLimit fails. Self-review: - At the limit the probe goroutine is left to finish on a cancelled context (up to a gate's grace and settle, about 40 s); its late results are dropped and its fixture copies are its own temp dirs. - A real gate's booted list is now bounded too: a simctl slower than 30 s makes the gate see none booted before it, so it may shut down a simulator it did not boot. Before, that gate hung for good. - Ready outside mu lets several steps wait for the probes at once; they still run one at a time under mu. - Paul suggested a 10 min overall limit; 30 min is chosen for the reason above. Steps on a Mac whose probes hit an unforeseen hang wait up to that long; the updater no longer does. - thin size budget raised to the measured 16846/8399.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+506
−28
.rastrillo/budgets.txt+1 −1internal/runner/mac/caps.go+1 −2internal/runner/mac/probe.go+169 −20internal/runner/mac/probe_test.go+37 −0internal/runner/thin/mac.go+9 −2internal/runner/thin/mac_stall_test.go+269 −0internal/runner/thin/worker.go+20 −3
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 6408f8dd..e2f52c20 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -34,7 +34,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| -size internal/runner/thin 16822 8130 Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| +size internal/runner/thin 16846 8399 Mac probe deadlines bound the booted simctl list, move the worker's wait for the probes out of its lock (hold) and warn when a probe run reaches its limit (about 24 lines); their tests (mac_stall_test.go: a fake xcrun that never answers, probes stalled while an update applies, about 270 lines) beside the Mac host they drive: measured 16846/8399. Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
diff --git a/internal/runner/mac/caps.go b/internal/runner/mac/caps.go| index a73ac20a..8e589263 100644 |
| --- a/internal/runner/mac/caps.go |
| +++ b/internal/runner/mac/caps.go |
| @@ -7,7 +7,6 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| - "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -28,7 +27,7 @@ func Capabilities(ctx context.Context, x Exec, t Tools) wire.Capabilities { |
| if name == "" { |
| return "" |
| } |
| - c, cancel := context.WithTimeout(ctx, 30*time.Second) |
| + c, cancel := context.WithTimeout(ctx, QueryLimit) |
| defer cancel() |
| out, err := x(c, name, args...) |
| if err != nil { |
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go| index 0b71c3c5..b49a1e58 100644 |
| --- a/internal/runner/mac/probe.go |
| +++ b/internal/runner/mac/probe.go |
| @@ -7,6 +7,7 @@ import ( |
| "embed" |
| "encoding/hex" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "io/fs" |
| "net" |
| @@ -52,8 +53,25 @@ type ProbeHost struct { |
| Listen func() (net.Listener, error) |
| // Wait bounds P6's wait for its test to start (8 minutes). |
| Wait time.Duration |
| + // Limit bounds the whole run (ProbeLimit). |
| + Limit time.Duration |
| + // late notes the queries that did not answer in time (RunProbes). |
| + late *queries |
| } |
| +// QueryLimit bounds each query the probes and the capability report |
| +// make (simctl list, xcodebuild -version, launchctl, pmset, a tool's |
| +// version): a command that has not answered by then is killed and taken |
| +// as unavailable. Only the gates the probes run (a real build and test) |
| +// and srt's own start take longer, each with a bound of its own. |
| +var QueryLimit = 30 * time.Second |
| + |
| +// ProbeLimit bounds a whole probe run, whatever hangs inside it. It is |
| +// above the bounds of the probes' own gates (P2's 20 minutes, P6's 8), |
| +// so it never cuts a slow but healthy first build short: it is the |
| +// backstop for a wait nothing else bounds. |
| +const ProbeLimit = 30 * time.Minute |
| + |
| // Report is what the probes found, kept in the state dir and sent in the |
| // capability report. |
| type Report struct { |
| @@ -67,6 +85,9 @@ type Report struct { |
| // SRT fingerprints the srt, Node and ripgrep the probes ran with |
| // (set by the worker that made the report). |
| SRT string `json:"srt"` |
| + // Unfinished are the probes the run's limit cut short: each says |
| + // not proven. |
| + Unfinished []string `json:"unfinished,omitempty"` |
| } |
| // Probe is the result of one probe ("" verdict when it did not run). |
| @@ -101,22 +122,131 @@ func ProfileDigest() string { |
| } |
| // RunProbes runs P1 to P7 (spec §6) and reports each. None needs a |
| -// person: P3 and P5 say what they could not do and why. |
| +// person: P3 and P5 say what they could not do and why. Every command |
| +// is bounded (QueryLimit, or a gate's own limit) and so is the run |
| +// (h.Limit): when that passes the run ends with what it has, the |
| +// probes it did not finish not proven and listed in Unfinished. |
| func RunProbes(ctx context.Context, h ProbeHost) Report { |
| + limit := h.Limit |
| + if limit <= 0 { |
| + limit = ProbeLimit |
| + } |
| + run, cancel := context.WithTimeout(ctx, limit) |
| + defer cancel() |
| r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()} |
| - caps := Capabilities(ctx, h.Exec, h.Tools) |
| - r.Probes = append(r.Probes, probeP1(ctx, h, caps)) |
| - p2, srtRan, keychain := probeP2(ctx, h, caps) |
| + h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}} |
| + h.Exec = h.late.do |
| + var mu sync.Mutex |
| + got := map[string]wire.Probe{} |
| + srtRan := false |
| + // A result that comes once the run's limit has passed is left out: |
| + // the cancellation, not the Mac, may have decided it. |
| + put := func(p wire.Probe, ran ...bool) { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if run.Err() == nil { |
| + got[p.ID] = p |
| + if len(ran) > 0 { |
| + srtRan = ran[0] |
| + } |
| + } |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + caps := Capabilities(run, h.Exec, h.Tools) |
| + put(probeP1(run, h, caps)) |
| + p2, ran, keychain := probeP2(run, h, caps) |
| + put(p2, ran) |
| + put(wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: clean("sign-in needs a person (slice F); Keychain from the sandbox: " + keychain)}) |
| + put(probeP4(run, h)) |
| + put(wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: "Codex on the Mac is parked (slice G)"}) |
| + put(probeP6(run, h, caps, ran)) |
| + put(probeP7(run, h)) |
| + }() |
| + select { |
| + case <-done: |
| + case <-run.Done(): |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| r.SRTRanXcode = srtRan |
| - r.Probes = append(r.Probes, p2) |
| - r.Probes = append(r.Probes, wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: clean("sign-in needs a person (slice F); Keychain from the sandbox: " + keychain)}) |
| - r.Probes = append(r.Probes, probeP4(ctx, h)) |
| - r.Probes = append(r.Probes, wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: "Codex on the Mac is parked (slice G)"}) |
| - r.Probes = append(r.Probes, probeP6(ctx, h, caps, srtRan)) |
| - r.Probes = append(r.Probes, probeP7(ctx, h)) |
| + for _, id := range wire.ProbeIDs { |
| + p, ok := got[id] |
| + if !ok { |
| + p = wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: clean("not proven: the probe run reached its limit of " + limit.String())} |
| + r.Unfinished = append(r.Unfinished, id) |
| + } |
| + r.Probes = append(r.Probes, p) |
| + } |
| return r |
| } |
| +// queries runs the probes' commands and notes each that did not answer |
| +// in time: its own deadline passed while the run's had not. |
| +type queries struct { |
| + run context.Context |
| + exec Exec |
| + mu sync.Mutex |
| + late map[string]bool |
| +} |
| + |
| +func (q *queries) do(ctx context.Context, name string, args ...string) (string, error) { |
| + out, err := q.exec(ctx, name, args...) |
| + if errors.Is(ctx.Err(), context.DeadlineExceeded) && q.run.Err() == nil { |
| + q.mu.Lock() |
| + q.late[queryKey(name, args)] = true |
| + q.mu.Unlock() |
| + } |
| + return out, err |
| +} |
| + |
| +// queryKey names a command by its program, or xcrun's by its tool |
| +// ("simctl"). |
| +func queryKey(name string, args []string) string { |
| + if path.Base(name) == "xcrun" && len(args) > 0 { |
| + return args[0] |
| + } |
| + return path.Base(name) |
| +} |
| + |
| +// said is why a tool cannot be relied on when a query to it did not |
| +// answer ("simctl did not answer in 30s"), else "". |
| +func (h ProbeHost) said(tool string) string { |
| + if h.late == nil { |
| + return "" |
| + } |
| + h.late.mu.Lock() |
| + defer h.late.mu.Unlock() |
| + if h.late.late[tool] { |
| + return tool + " did not answer in " + QueryLimit.String() |
| + } |
| + return "" |
| +} |
| + |
| +// noXcode and noSimulator say why a probe that needs Xcode or a |
| +// simulator cannot run: a query that did not answer, or none found. |
| +func (h ProbeHost) noXcode() string { |
| + if why := h.said("xcodebuild"); why != "" { |
| + return "Xcode unavailable: " + why |
| + } |
| + return "no Xcode" |
| +} |
| + |
| +func (h ProbeHost) noSimulator() string { |
| + if why := h.said("simctl"); why != "" { |
| + return "simulator unavailable: " + why |
| + } |
| + return "" |
| +} |
| + |
| +// query runs one probe command bounded by limit. |
| +func (h ProbeHost) query(ctx context.Context, limit time.Duration, name string, args ...string) (string, error) { |
| + c, cancel := context.WithTimeout(ctx, limit) |
| + defer cancel() |
| + return h.Exec(c, name, args...) |
| +} |
| + |
| func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Probe { |
| name := ComputerName(ctx, h.Exec) |
| ios := 0 |
| @@ -126,9 +256,12 @@ func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Prob |
| } |
| } |
| if caps.Xcode.Version == "" { |
| - return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean("no Xcode; " + name)} |
| + return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean(h.noXcode() + "; " + name)} |
| } |
| detail := fmt.Sprintf("Xcode %s (%s); %d iOS simulators; %s", caps.Xcode.Version, caps.Xcode.Build, ios, name) |
| + if why := h.noSimulator(); why != "" { |
| + detail = fmt.Sprintf("Xcode %s (%s); %s; %s", caps.Xcode.Version, caps.Xcode.Build, why, name) |
| + } |
| if ios == 0 { |
| return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean(detail)} |
| } |
| @@ -137,6 +270,8 @@ func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Prob |
| // ComputerName is the Mac's name as people see it ("Tito Studio"). |
| func ComputerName(ctx context.Context, x Exec) string { |
| + ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| + defer cancel() |
| out, err := x(ctx, "/usr/sbin/scutil", "--get", "ComputerName") |
| if err != nil { |
| return "" |
| @@ -237,7 +372,10 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| return fail(wire.ProbeUnavailable, "srt is not installed") |
| } |
| if caps.Xcode.Version == "" { |
| - return fail(wire.ProbeUnavailable, "no Xcode") |
| + return fail(wire.ProbeUnavailable, clean(h.noXcode())) |
| + } |
| + if why := h.noSimulator(); why != "" { |
| + return fail(wire.ProbeUnavailable, clean(why)) |
| } |
| // The hostile test runs where production checks run: on an iOS |
| // simulator, through CoreSimulator and the test services. |
| @@ -285,13 +423,15 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| }(place, l) |
| targets = append(targets, "port_"+place+"="+strconv.Itoa(l.Addr().(*net.TCPAddr).Port)) |
| } |
| - facts.DNS = h.Resolve(ctx, "example.com") |
| + resolve, cancel := context.WithTimeout(ctx, QueryLimit) |
| + facts.DNS = h.Resolve(resolve, "example.com") |
| + cancel() |
| targets = append(targets, "dns=example.com") |
| service := "io.amadan.equipo.probe." + secret[:12] |
| - if _, err := h.Exec(ctx, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { |
| + if _, err := h.query(ctx, QueryLimit, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { |
| facts.Keychain = true |
| defer func() { |
| - _, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) |
| + _, _ = h.query(context.WithoutCancel(ctx), QueryLimit, "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) |
| }() |
| } |
| // On a simulator the Keychain API is the simulator's own: the test |
| @@ -351,9 +491,9 @@ func probeP4(ctx context.Context, h ProbeHost) wire.Probe { |
| for _, home := range ExposedHomes(h.Paths.OtherHomes, h.Exposed) { |
| readable = append(readable, path.Base(home)) |
| } |
| - _, err := h.Exec(ctx, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) |
| + _, err := h.query(ctx, QueryLimit, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) |
| loaded := err == nil |
| - pm, _ := h.Exec(ctx, "/usr/bin/pmset", "-g", "custom") |
| + pm, _ := h.query(ctx, QueryLimit, "/usr/bin/pmset", "-g", "custom") |
| sleep, known := ACSleep(pm) |
| var parts []string |
| switch { |
| @@ -404,7 +544,13 @@ func ACSleep(out string) (int, bool) { |
| // the end takes to prove, what is left, and whether the tree goes. |
| func probeP6(ctx context.Context, h ProbeHost, caps wire.Capabilities, srtRan bool) wire.Probe { |
| if caps.Xcode.Version == "" { |
| - return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: "no Xcode"} |
| + return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: clean(h.noXcode())} |
| + } |
| + // A simctl that does not answer means CoreSimulator is stuck, and |
| + // xcodebuild test asks it for destinations even for macOS: the probe |
| + // would only wait out its whole limit. |
| + if why := h.noSimulator(); why != "" { |
| + return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: clean(why)} |
| } |
| root, err := copyFixture(h.Scratch) |
| if err != nil { |
| @@ -477,6 +623,8 @@ exec ` + xb + ` test -scheme "$s" -destination ` + quote(destination) + ` -only- |
| // processNames are this user's processes by name (basename), counted. |
| func processNames(ctx context.Context, x Exec) map[string]int { |
| + ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| + defer cancel() |
| out, err := x(ctx, "/bin/ps", "-x", "-o", "comm=") |
| names := map[string]int{} |
| if err != nil { |
| @@ -509,7 +657,7 @@ func probeP7(ctx context.Context, h ProbeHost) wire.Probe { |
| if tool == "" { |
| return "" |
| } |
| - out, err := h.Exec(ctx, tool, args...) |
| + out, err := h.query(ctx, QueryLimit, tool, args...) |
| if err != nil { |
| return "" |
| } |
| @@ -538,7 +686,8 @@ func probeP7(ctx context.Context, h ProbeHost) wire.Probe { |
| ok = false |
| } else { |
| defer os.Remove(file) |
| - if _, err := h.Exec(ctx, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { |
| + // srt starts its own runtime before the command: a minute, not a query's 30 s. |
| + if _, err := h.query(ctx, time.Minute, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { |
| parts, ok = append(parts, "srt could not run a command"), false |
| } |
| } |
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go| index 2c7e8294..5643f07d 100644 |
| --- a/internal/runner/mac/probe_test.go |
| +++ b/internal/runner/mac/probe_test.go |
| @@ -328,3 +328,40 @@ func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) { |
| t.Fatalf("no simulator: %+v", p) |
| } |
| } |
| + |
| +// A wait nothing else bounds (a command that ignores its context) ends |
| +// at the run's limit: the report has every probe, the ones not finished |
| +// not proven and listed, and stays a valid capability report. |
| +func TestRunProbesLimit(t *testing.T) { |
| + stuck := make(chan struct{}) |
| + t.Cleanup(func() { close(stuck) }) |
| + h := ProbeHost{Version: "abc1234", UID: 501, Paths: Paths{HomesUnknown: true}, Exposed: func(string) bool { return false }, Limit: 300 * time.Millisecond, |
| + Exec: func(ctx context.Context, name string, args ...string) (string, error) { |
| + if name == "/bin/launchctl" { |
| + <-stuck |
| + } |
| + return "", errors.New("not recorded") |
| + }} |
| + got := make(chan Report, 1) |
| + go func() { got <- RunProbes(context.Background(), h) }() |
| + var r Report |
| + select { |
| + case r = <-got: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the probe run outlived its limit") |
| + } |
| + if !slices.Equal(r.Unfinished, []string{"P4", "P5", "P6", "P7"}) { |
| + t.Fatalf("unfinished %v %+v", r.Unfinished, r.Probes) |
| + } |
| + for _, id := range r.Unfinished { |
| + if p := r.Probe(id); p.Verdict != wire.ProbeUnavailable || p.Detail != "not proven: the probe run reached its limit of 300ms" { |
| + t.Fatalf("%s %+v", id, p) |
| + } |
| + } |
| + if p := r.Probe("P1"); p.Verdict != wire.ProbeFailed { |
| + t.Fatalf("P1 finished before the limit: %+v", p) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| + t.Fatalf("report outside the capability rules: %v", err) |
| + } |
| +} |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index 4e6cf78a..c324c295 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -290,6 +290,9 @@ func (p *macProbes) start(ctx context.Context, refresh func()) { |
| p.log.Log(ctx, level, "probes finished", "took", took(start), "verdicts", v) |
| said = v |
| } |
| + if len(r.Unfinished) > 0 && p.log != nil { |
| + p.log.Warn("probe run reached its limit; unfinished probes are not proven", "unfinished", strings.Join(r.Unfinished, " ")) |
| + } |
| if before && p.verified() { |
| r.SRT = srtPinned |
| } |
| @@ -572,8 +575,12 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| settings := func(tree, attempt string) ([]byte, error) { |
| return mac.ChecksSettings(mac.ChecksInput{Paths: h.paths, Tree: tree, Attempt: attempt, Mach: mac.CheckMachServices}) |
| } |
| + // Both bounded: a simctl that never answers (CoreSimulator stuck) |
| + // must not hold a gate or a probe run. |
| booted := func(ctx context.Context) []string { |
| - out, err := h.run(ctx, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted") |
| + c, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| + defer cancel() |
| + out, err := h.run(c, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted") |
| var udids []string |
| if err == nil { |
| for _, s := range mac.ParseSimulators([]byte(out)) { |
| @@ -680,7 +687,7 @@ func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error |
| if w.Tainted { |
| h.taint.Set() |
| } |
| - up.offer(w, func() func() { worker.mu.Lock(); return worker.mu.Unlock }, func() { stop(ErrUpdated) }, o.Logger) |
| + up.offer(w, worker.hold, func() { stop(ErrUpdated) }, o.Logger) |
| }}) |
| } |
diff --git a/internal/runner/thin/mac_stall_test.go b/internal/runner/thin/mac_stall_test.go| new file mode 100644 |
| index 00000000..6c7a4014 |
| --- /dev/null |
| +++ b/internal/runner/thin/mac_stall_test.go |
| @@ -0,0 +1,269 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// stallXcrun plays an xcrun whose simctl never answers: the hanging |
| +// call leaves a child (sleep) holding its output, as a stuck |
| +// CoreSimulator client would. Every pid goes in PIDS so the test can |
| +// prove them gone and kill any left, by pid. |
| +const stallXcrun = `#!/bin/sh |
| +echo $$ >> PIDS |
| +case "$*" in |
| +*"devices available"*) [ -z "HANG_AVAILABLE" ] && { cat SIMS; exit 0; } ;; |
| +esac |
| +sleep 600 & |
| +echo $! >> PIDS |
| +wait |
| +` |
| + |
| +const stallXcodebuild = `#!/bin/sh |
| +case "$*" in |
| +-version) echo "Xcode 16.2"; echo "Build version 16C5032a"; exit 0 ;; |
| +esac |
| +exit 64 |
| +` |
| + |
| +// stallHost is a Mac host on Linux whose xcrun hangs: on every simctl |
| +// call (all) or only on the booted list the probes' gates ask (P6). |
| +func stallHost(t *testing.T, all bool) (*macHost, string) { |
| + t.Helper() |
| + root := t.TempDir() |
| + pids := filepath.Join(root, "pids") |
| + sims, err := filepath.Abs("../mac/testdata/simctl-devices.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hang := "" |
| + if all { |
| + hang = "1" |
| + } |
| + xcrun := strings.NewReplacer("PIDS", pids, "SIMS", sims, `"HANG_AVAILABLE"`, `"`+hang+`"`).Replace(stallXcrun) |
| + tools := mac.Tools{Xcrun: filepath.Join(root, "xcrun"), Xcodebuild: filepath.Join(root, "xcodebuild")} |
| + for p, body := range map[string]string{tools.Xcrun: xcrun, tools.Xcodebuild: stallXcodebuild} { |
| + if err := os.WriteFile(p, []byte(body), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + t.Cleanup(func() { |
| + raw, _ := os.ReadFile(pids) |
| + for _, f := range strings.Fields(string(raw)) { |
| + if pid, err := strconv.Atoi(f); err == nil && pid > 1 { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + } |
| + }) |
| + was, users := mac.QueryLimit, macUsers |
| + mac.QueryLimit, macUsers = 300*time.Millisecond, filepath.Join(root, "Users") |
| + t.Cleanup(func() { mac.QueryLimit, macUsers = was, users }) |
| + c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "runner")} |
| + for _, d := range []string{c.StateDir, c.ScratchRoot} { |
| + if err := os.MkdirAll(d, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" })) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.tools = tools |
| + return h, pids |
| +} |
| + |
| +// alive lists the recorded pids still running after a short settle. |
| +func alive(pids string) []string { |
| + deadline := time.Now().Add(3 * time.Second) |
| + for { |
| + raw, _ := os.ReadFile(pids) |
| + var left []string |
| + for _, f := range strings.Fields(string(raw)) { |
| + if pid, err := strconv.Atoi(f); err == nil && syscall.Kill(pid, 0) == nil { |
| + if stat, _ := os.ReadFile("/proc/" + f + "/stat"); !strings.Contains(string(stat), ") Z ") { |
| + left = append(left, f) |
| + } |
| + } |
| + } |
| + if len(left) == 0 || time.Now().After(deadline) { |
| + return left |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
| + |
| +// A simctl that never answers no longer holds the probes: each query is |
| +// killed at QueryLimit with what it started, the run finishes, ready |
| +// closes, and the report says why the simulator probes could not run. |
| +// The booted list the probes' gates ask (Paul's Studio, 15:44) is |
| +// bounded as well as the capability list. |
| +func TestMacProbesFinishWhenSimctlHangs(t *testing.T) { |
| + for _, all := range []bool{true, false} { |
| + t.Run(map[bool]string{true: "every simctl", false: "the booted list"}[all], func(t *testing.T) { |
| + h, pids := stallHost(t, all) |
| + start := time.Now() |
| + h.probes.start(t.Context(), func() {}) |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + if err := h.probes.wait(ctx); err != nil { |
| + t.Fatalf("the probe run did not finish (ready never closed): %v", err) |
| + } |
| + if took := time.Since(start); took > 15*time.Second { |
| + t.Fatalf("the probe run took %s", took) |
| + } |
| + r := h.probes.report() |
| + if len(r.Probes) != len(wire.ProbeIDs) || len(r.Unfinished) != 0 { |
| + t.Fatalf("report %+v", r) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| + t.Fatalf("report outside the capability rules: %v", err) |
| + } |
| + p1, p6 := r.Probe("P1"), r.Probe("P6") |
| + if all { |
| + why := "simulator unavailable: simctl did not answer in 300ms" |
| + if p1.Verdict != wire.ProbeFailed || !strings.Contains(p1.Detail, why) || p6.Verdict != wire.ProbeUnavailable || p6.Detail != why { |
| + t.Fatalf("P1 %+v P6 %+v", p1, p6) |
| + } |
| + } else if p6.Verdict != wire.ProbeFailed || !strings.Contains(p6.Detail, "did not start") { |
| + // The fake xcodebuild runs no test: P6 ran its gate (which |
| + // asked the booted list twice) and says so. |
| + t.Fatalf("P6 %+v", p6) |
| + } |
| + if left := alive(pids); len(left) != 0 { |
| + t.Fatalf("hung simctl processes left: %v", left) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// updateServer serves release bbb2222 with a runner whose digest its |
| +// manifest names. |
| +func updateServer(t *testing.T) (string, []byte) { |
| + newBin := []byte("#!new runner\n") |
| + sum := sha256.Sum256(newBin) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case r.URL.Path == "/releases/bbb2222/install-manifest.json": |
| + _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: hex.EncodeToString(sum[:])}}}) |
| + case strings.HasPrefix(r.URL.Path, "/releases/bbb2222/"+release.DarwinDir+"/"): |
| + _, _ = w.Write(newBin) |
| + default: |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv.URL, newBin |
| +} |
| + |
| +// heldGate runs only once the test lets it. |
| +type heldGate struct { |
| + *stubGate |
| + started, release chan struct{} |
| +} |
| + |
| +func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| + close(g.started) |
| + <-g.release |
| + return g.stubGate.Run(ctx, a, dir, argv, l, record) |
| +} |
| + |
| +// The updater does not wait for the probes: with the probes stalled for |
| +// good and a step waiting on them, a new release is swapped in and the |
| +// worker stopped with ErrUpdated at once. A step that really runs still |
| +// holds the swap until it ends. |
| +func TestMacUpdateWhileProbesStall(t *testing.T) { |
| + origin, newBin := updateServer(t) |
| + update := func(t *testing.T, w *Worker, stop func()) (string, *macUpdater) { |
| + binary := filepath.Join(t.TempDir(), "runner") |
| + if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + u := &macUpdater{origin: origin, version: "aaa1111", binary: binary, fetch: fetchLimited} |
| + u.offer(wire.Welcome{Release: "bbb2222"}, w.hold, stop, nil) |
| + return binary, u |
| + } |
| + swapped := func(binary string) bool { raw, _ := os.ReadFile(binary); return string(raw) == string(newBin) } |
| + |
| + t.Run("probes stalled", func(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + waiting := make(chan struct{}) |
| + x.w.Ready = func(ctx context.Context) error { |
| + close(waiting) |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + ctx, stop := context.WithCancelCause(context.Background()) |
| + defer stop(nil) |
| + reps := make(chan wire.StepReport, 1) |
| + go func() { reps <- x.w.Exec(ctx, x.r, func(wire.StepReport) {}) }() |
| + <-waiting |
| + binary, u := update(t, x.w, func() { stop(ErrUpdated) }) |
| + select { |
| + case err := <-u.done: |
| + if err != nil || !swapped(binary) || !errors.Is(context.Cause(ctx), ErrUpdated) { |
| + t.Fatalf("update: %v swapped=%v cause=%v", err, swapped(binary), context.Cause(ctx)) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the update waited for probes that never finish") |
| + } |
| + select { |
| + case rep := <-reps: |
| + if rep.State != wire.StepCancelled || len(x.gate.ran) != 0 { |
| + t.Fatalf("waiting step %+v ran %v", rep, x.gate.ran) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the waiting step did not end with the worker") |
| + } |
| + }) |
| + |
| + t.Run("step running", func(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + g := heldGate{stubGate: x.gate, started: make(chan struct{}), release: make(chan struct{})} |
| + x.w.Gate = g |
| + reps := make(chan wire.StepReport, 1) |
| + go func() { reps <- x.run() }() |
| + <-g.started |
| + stopped := make(chan struct{}) |
| + binary, u := update(t, x.w, func() { close(stopped) }) |
| + select { |
| + case <-u.done: |
| + t.Fatal("the update did not wait for the running step") |
| + case <-time.After(500 * time.Millisecond): |
| + } |
| + if swapped(binary) { |
| + t.Fatal("binary swapped while a step ran") |
| + } |
| + close(g.release) |
| + if rep := <-reps; rep.State != wire.StepDone { |
| + t.Fatalf("step %+v", rep) |
| + } |
| + select { |
| + case err := <-u.done: |
| + if err != nil || !swapped(binary) { |
| + t.Fatalf("update after the step: %v", err) |
| + } |
| + <-stopped |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the update never applied after the step") |
| + } |
| + }) |
| +} |
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go| index f26752ef..0d0e1ce1 100644 |
| --- a/internal/runner/thin/worker.go |
| +++ b/internal/runner/thin/worker.go |
| @@ -70,11 +70,21 @@ type Worker struct { |
| Ready func(context.Context) error |
| // mu is held while an attempt runs, so an update swaps the binary |
| - // only between steps; marker is that attempt's EQUIPO_ATTEMPT. |
| + // only between steps; marker is that attempt's EQUIPO_ATTEMPT. An |
| + // attempt waiting for Ready does not hold it. |
| mu sync.Mutex |
| marker string |
| } |
| +// hold waits until no attempt runs and keeps the next one from starting |
| +// until the returned release (the Mac updater swaps the binary there). |
| +// It never waits for Ready: probes that never finish must not keep the |
| +// runner on an old release. |
| +func (w *Worker) hold() func() { |
| + w.mu.Lock() |
| + return w.mu.Unlock |
| +} |
| + |
| func (w *Worker) root() string { return filepath.Join(w.Engine.O.Runner.StateDir, "worker") } |
| func (w *Worker) stepsDir() string { |
| @@ -110,13 +120,20 @@ func (w *Worker) Exec(ctx context.Context, r stepRow, progress func(wire.StepRep |
| // Only checks are placed on workers until slice F. |
| return end(wire.StepFailed, "placement_refused") |
| } |
| - w.mu.Lock() |
| - defer w.mu.Unlock() |
| + // Ready first, outside mu: a step waiting for the probes is not a |
| + // step running, and the updater's hold must not wait for it. |
| if w.Ready != nil { |
| if err := w.Ready(ctx); err != nil { |
| return end(wire.StepCancelled, "cancelled") |
| } |
| } |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + // An update may have swapped the binary and stopped the worker while |
| + // this step waited for mu. |
| + if ctx.Err() != nil { |
| + return end(wire.StepCancelled, "cancelled") |
| + } |
| // The attempt's marker is on record before anything of it runs: every |
| // process it starts (git here, the gate later) carries it, so a |
| // restarted runner can find them even if no group was recorded. |