Merge branch 'mac-user-temp' into main
Merge mac-user-temp: srt checks may write the user's own T T is resolved with getconf, verified (under /private/var/folders, owned by the runner user, 0700) and held by handle; checks refuse to start otherwise. Attempts take one turn across processes; simulators shut down and T is cleaned of what each attempt added. C gets nothing: the plugin cache is warmed outside srt. Astra R2 fixes folded in. Hosted CI passed on 2248b3a.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+1,177
−13
.rastrillo/budgets.txt+1 −1docs/superpowers/specs/2026-11-07-equipo-mac-runners.md+9 −1internal/runner/mac/gate.go+99 −0internal/runner/mac/probe.go+17 −2internal/runner/mac/probe_test.go+1 −1internal/runner/mac/profile.go+12 −3internal/runner/mac/profile_test.go+13 −1internal/runner/mac/usertemp.go+441 −0internal/runner/mac/usertemp_test.go+366 −0internal/runner/thin/mac.go+121 −2internal/runner/thin/mac_test.go+97 −2
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index c2906171..c6446178 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 17046 8823 Engineering in an empty repository: the step starts from no base and tells Engineering so, the push names an unborn default, Review reads an initial commit against the empty tree (changeDiff), checks list its files, and a repository whose only branches are task branches stays empty (onlyTaskBranches; about 60 lines); their tests (the task-branch, review diff and prompt tests in index_empty_test.go, about 92 lines): measured 17046/8823. Mac checks wait for the sandbox: macChecks.Run refuses unproven without the dispatch's consent, the consent context, the worker's refusal report and the link's protocol 7 gate (about 38 lines), and their tests (sandbox_consent_test.go, about 131 lines); measured 16986/8731. Mac Xcode scratch: the Mac host test pins the gate's environment (the runner user's HOME kept, no scratch home; 6 lines); measured 16948/8600. Empty repositories merged onto main: measured 16948/8594. Empty repositories: the index lists a reachable repository with no commits as empty, DefaultBranch tells that from no access (lsRemote), reads of it say so, and the handshake hello keeps empty entries back until a protocol 6 welcome (about 52 lines); their tests (index_empty_test.go, the handshake hello at protocols 5 and 6, startLinkWith; about 183 lines). Token row facts merged onto main: measured 16896/8411. Token row facts read the check's rate limit and record it as a turn's (TokenCheck, the Verify wiring, about 40 lines); measured 16614. 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. Mac P2 diagnostics hand the probes' host runner.log's WARN (macHost.warn, 8 lines) and pin it with a test (12 lines): measured 16854/8411. 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. |
| +size internal/runner/thin 17165 8918 Mac pending cleanup: the warm waits while an attempt's cleanup is pending (5 lines, test 4); measured 17165/8918. Mac simulators before T: quietSimulators shuts every simulator down (bounded) before a T cleanup and logs what is left (about 43 lines), and its test with a hung simctl (about 45 lines); measured 17160/8914. Mac user temp: the Mac host resolves the user's T and refuses an untrusted one (macUserTemp, why in words), gives every gate one turn across the worker and the probe command, and warms Xcode's plugin cache once per Xcode outside the sandbox (warm, warmNow; about 71 lines); its tests pin T on the srt gates, a refused T and the warm's once, retry and turn (about 46 lines); measured 17117/8869. Engineering in an empty repository: the step starts from no base and tells Engineering so, the push names an unborn default, Review reads an initial commit against the empty tree (changeDiff), checks list its files, and a repository whose only branches are task branches stays empty (onlyTaskBranches; about 60 lines); their tests (the task-branch, review diff and prompt tests in index_empty_test.go, about 92 lines): measured 17046/8823. Mac checks wait for the sandbox: macChecks.Run refuses unproven without the dispatch's consent, the consent context, the worker's refusal report and the link's protocol 7 gate (about 38 lines), and their tests (sandbox_consent_test.go, about 131 lines); measured 16986/8731. Mac Xcode scratch: the Mac host test pins the gate's environment (the runner user's HOME kept, no scratch home; 6 lines); measured 16948/8600. Empty repositories merged onto main: measured 16948/8594. Empty repositories: the index lists a reachable repository with no commits as empty, DefaultBranch tells that from no access (lsRemote), reads of it say so, and the handshake hello keeps empty entries back until a protocol 6 welcome (about 52 lines); their tests (index_empty_test.go, the handshake hello at protocols 5 and 6, startLinkWith; about 183 lines). Token row facts merged onto main: measured 16896/8411. Token row facts read the check's rate limit and record it as a turn's (TokenCheck, the Verify wiring, about 40 lines); measured 16614. 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. Mac P2 diagnostics hand the probes' host runner.log's WARN (macHost.warn, 8 lines) and pin it with a test (12 lines): measured 16854/8411. 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/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md| index 8d91cb54..380d2b0a 100644 |
| --- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md |
| +++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md |
| @@ -446,7 +446,9 @@ designed there. |
| settings file and runs `srt --settings <file> -- /bin/bash -c <gate>` in |
| the checks tree (the exact SHA, with the one-commit `.git` as today). |
| `allowWrite`: the tree, the attempt's DerivedData and temp dirs under |
| -scratch, `~/Library/Developer/Xcode/DerivedData`, |
| +scratch, the runner user's `DARWIN_USER_TEMP_DIR` (resolved and checked |
| +at start; Xcode writes there whatever `TMPDIR` says), |
| +`~/Library/Developer/Xcode/DerivedData`, |
| `~/Library/Caches/org.swift.swiftpm`, `~/Library/org.swift.swiftpm`; |
| §4.2 denies; `network.allowedDomains` empty; `allowMachLookup` set to |
| exactly what P2 shows `xcodebuild test` needs. A network failure is |
| @@ -507,6 +509,12 @@ and `apiKeyHelper` run unsandboxed (Equipo disables hooks and pins MCP). |
| Violations show only in `log stream --predicate 'process == |
| "sandbox-exec"'`, which the runner tails and counts in the step log. |
| +The user's temp folder is shared between attempts. After each sandboxed |
| +attempt the runner shuts its simulators down and removes what appeared |
| +there, but a check can leave changes inside folders that existed before |
| +the attempt. The runner user is per person and holds no secrets, so v1 |
| +accepts this. The v2 path is a disposable Mac user per attempt. |
| + |
| ## 5. Termination on macOS |
| No namespace and no pidfd proof. Each attempt starts in its own session |
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go| index f72645ad..9107130a 100644 |
| --- a/internal/runner/mac/gate.go |
| +++ b/internal/runner/mac/gate.go |
| @@ -57,6 +57,19 @@ type Gate struct { |
| // build's fake worker; a Mac keeps the runner user's home, where |
| // Xcode's caches are). |
| ScratchHome bool |
| + // UserTemp is the runner user's DARWIN_USER_TEMP_DIR ("T", which a |
| + // checks profile lets the gate write): what appears in it and in |
| + // T/TemporaryItems while a run lasts is removed once the run's end |
| + // is proven. "" removes nothing. |
| + UserTemp string |
| + // QuietSimulators, when set, runs once a run with a UserTemp has |
| + // proven its end and before T is cleaned: on a Mac, every |
| + // simulator of the runner user shut down (bounded), and what is |
| + // left of them logged. |
| + QuietSimulators func(context.Context) |
| + // Turns, when set, lets one run at a time hold the Mac (shared by |
| + // every gate of the runner), so a cleanup of T sees only its own. |
| + Turns *Turns |
| // Watch sees each line of output as it comes (probe P6 waits for a |
| // test to start before it kills the group). |
| Watch func(string) |
| @@ -79,6 +92,16 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| if len(argv) == 0 || strings.ContainsAny(attempt, " \n\x00") { |
| return unavailable() |
| } |
| + if g.Turns != nil { |
| + if err := g.Turns.take(ctx); err != nil { |
| + if ctx.Err() == nil { |
| + return unavailable() |
| + } |
| + res.Reason, res.Terminated = "cancelled", true |
| + return res |
| + } |
| + defer g.Turns.give() |
| + } |
| scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-") |
| if err != nil { |
| return unavailable() |
| @@ -100,6 +123,48 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| defer os.Remove(settings) |
| cmdline = append([]string{g.SRT, "--settings", settings, "--"}, cmdline...) |
| } |
| + // What T holds before anything of the run starts, by handle: the |
| + // cleanup keeps exactly that. A cleanup an earlier attempt left is |
| + // finished first; a T that cannot be listed (or is no longer this |
| + // user's own folder) or cleaned runs nothing. |
| + var temp *tempState |
| + if g.UserTemp != "" { |
| + if err := g.finishPending(ctx); err != nil { |
| + return unavailable() |
| + } |
| + if temp, err = openTemp(g.UserTemp, nil); err != nil { |
| + return unavailable() |
| + } |
| + defer temp.close() |
| + // On record before anything starts: a runner killed from here |
| + // on leaves the cleanup to the next gate, not to nobody. |
| + if err := g.Turns.writePending(pendingRecord{Attempt: attempt, Before: temp.before}); err != nil { |
| + return unavailable() |
| + } |
| + } |
| + // Only once the run's end is proven: a process of it still alive |
| + // could be writing T as it is cleaned. Unproven, or not finished, |
| + // the cleanup is left for the next gate, which runs nothing until |
| + // it is done. |
| + cleanUp := func() { |
| + if temp == nil { |
| + return |
| + } |
| + if !res.Terminated { |
| + // The record stays: the next gate proves this attempt's |
| + // end before it cleans. |
| + return |
| + } |
| + // Simulator processes are CoreSimulator's, outside the group |
| + // and outside srt, and may still write T: they go first |
| + // (bounded by the hook; it never fails the run). |
| + if g.QuietSimulators != nil { |
| + g.QuietSimulators(context.WithoutCancel(ctx)) |
| + } |
| + if temp.clean() == nil { |
| + _ = g.Turns.dropPending() |
| + } |
| + } |
| if err := record(RecordID(0, attempt)); err != nil { |
| return unavailable() |
| } |
| @@ -139,12 +204,18 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| return unavailable() |
| } |
| pgid := cmd.Process.Pid |
| + if temp != nil { |
| + // With its group, so the next gate can prove that end too. Best |
| + // effort: the record before the start has the marker. |
| + _ = g.Turns.writePending(pendingRecord{Attempt: attempt, PGID: pgid, Before: temp.before}) |
| + } |
| exited := make(chan error, 1) |
| go func() { exited <- cmd.Wait() }() |
| if err := record(RecordID(pgid, attempt)); err != nil { |
| _ = syscall.Kill(-pgid, syscall.SIGKILL) |
| <-exited |
| res.Reason, res.Terminated, res.Output = "checks_unavailable", g.settle(pgid, attempt, true), out.String() |
| + cleanUp() |
| return res |
| } |
| if g.Caffeinate != "" { |
| @@ -197,10 +268,38 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| } |
| } |
| } |
| + cleanUp() |
| res.Output = out.String() |
| return res |
| } |
| +// finishPending finishes the T cleanup an earlier attempt (in this |
| +// process or another, perhaps killed) left: that attempt's end proven |
| +// first (its group and every process with its marker gone, killed if |
| +// need be, as Verify does), its simulators shut down, then T cleaned |
| +// against what it held before that attempt. Holding the turn. |
| +func (g *Gate) finishPending(ctx context.Context) error { |
| + r, ok, err := g.Turns.readPending() |
| + if err != nil || !ok { |
| + return err |
| + } |
| + if !g.settle(r.PGID, r.Attempt, false) { |
| + return errors.New("mac: an earlier attempt's end is not proven") |
| + } |
| + if g.QuietSimulators != nil { |
| + g.QuietSimulators(context.WithoutCancel(ctx)) |
| + } |
| + s, err := openTemp(g.UserTemp, r.Before) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.close() |
| + if err := s.clean(); err != nil { |
| + return err |
| + } |
| + return g.Turns.dropPending() |
| +} |
| + |
| // RecordID is the process record of an attempt: its group and marker. |
| func RecordID(pgid int, attempt string) string { return "pg:" + strconv.Itoa(pgid) + ":" + attempt } |
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go| index 78b4ab37..932471fc 100644 |
| --- a/internal/runner/mac/probe.go |
| +++ b/internal/runner/mac/probe.go |
| @@ -107,10 +107,20 @@ func (r Report) Probe(id string) wire.Probe { |
| // say so (seatbelt). |
| func (r Report) Sandboxed() bool { return r.Probe("P2").Verdict == wire.ProbeDenied } |
| +// digestInput is the checks profile over fixed paths that |
| +// ProfileDigest names (TestProfileDigest: ChecksSettings accepts it). |
| +func digestInput() ChecksInput { |
| + return ChecksInput{Paths: Paths{Home: "/Users/u", StateDir: "/Users/u/s", AccountsRoot: "/Users/u/a", SessionRoot: "/Users/u/n", InstallDir: "/Users/u/i", OtherHomes: []string{"/Users/o"}, UserTemp: UserTempPrefix + "/u/T"}, Tree: "/Users/u/t/tree", Attempt: "/Users/u/t/attempt", Mach: CheckMachServices} |
| +} |
| + |
| // ProfileDigest names the checks profile the probes judged: the |
| -// settings over fixed paths, the Mach list and the fixture. |
| +// settings over fixed paths, the Mach list and the fixture. A profile |
| +// that cannot be made is named so, never as no profile. |
| func ProfileDigest() string { |
| - raw, _ := ChecksSettings(ChecksInput{Paths: Paths{Home: "/Users/u", StateDir: "/Users/u/s", AccountsRoot: "/Users/u/a", SessionRoot: "/Users/u/n", InstallDir: "/Users/u/i", OtherHomes: []string{"/Users/o"}}, Tree: "/Users/u/t/tree", Attempt: "/Users/u/t/attempt", Mach: CheckMachServices}) |
| + raw, err := ChecksSettings(digestInput()) |
| + if err != nil { |
| + raw = []byte("unmade: " + err.Error()) |
| + } |
| h := sha256.New() |
| h.Write(raw) |
| _ = fs.WalkDir(fixtures, "fixtures", func(p string, d fs.DirEntry, err error) error { |
| @@ -414,6 +424,11 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| if h.Tools.SRT == "" { |
| return fail(wire.ProbeUnavailable, "srt is not installed") |
| } |
| + // No checks profile without the user's T (ChecksSettings refuses): |
| + // say why, and checks wait for the sandbox. |
| + if h.Paths.UserTemp == "" { |
| + return fail(wire.ProbeUnavailable, clean("user temp folder refused: "+firstNonEmpty(h.Paths.UserTempWhy, "not resolved"))) |
| + } |
| if caps.Xcode.Version == "" { |
| return fail(wire.ProbeUnavailable, clean(h.noXcode())) |
| } |
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go| index e7b56cd9..0424ebbe 100644 |
| --- a/internal/runner/mac/probe_test.go |
| +++ b/internal/runner/mac/probe_test.go |
| @@ -136,7 +136,7 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| } |
| base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")} |
| f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: xcrun, Node: "node", SRT: srt, RG: "rg"}, |
| - Paths: Paths{Home: root, StateDir: state, OtherHomes: []string{"/Users/Shared", "/Users/paul"}}, |
| + Paths: Paths{Home: root, StateDir: state, OtherHomes: []string{"/Users/Shared", "/Users/paul"}, UserTemp: "/private/var/folders/4m/abc123_def/T"}, |
| Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234", |
| Gate: func(sandboxed bool) *Gate { |
| g := &Gate{Env: append(append([]string{}, base...), env...), Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: wire.SandboxNone} |
diff --git a/internal/runner/mac/profile.go b/internal/runner/mac/profile.go| index 2377e71e..c2db6d55 100644 |
| --- a/internal/runner/mac/profile.go |
| +++ b/internal/runner/mac/profile.go |
| @@ -26,6 +26,11 @@ type Paths struct { |
| InstallDir string |
| // OtherHomes are every home under /Users but the runner user's. |
| OtherHomes []string |
| + // UserTemp is the runner user's DARWIN_USER_TEMP_DIR, resolved and |
| + // checked by UserTemp; "" when it was refused, and UserTempWhy says |
| + // why. No checks profile is made without it: Xcode writes there |
| + // whatever $TMPDIR says. |
| + UserTemp, UserTempWhy string |
| // HomesUnknown: /Users could not be listed. Every profile then denies |
| // all of /Users, the runner's own home too, so no checks profile can |
| // be made (checks cannot run) rather than one that misses a home. |
| @@ -103,12 +108,16 @@ type Filesystem struct { |
| } |
| // ChecksSettings is the per-attempt checks profile of §4.4: writes only |
| -// to the tree, the attempt's scratch and Xcode's and SwiftPM's caches; |
| +// to the tree, the attempt's scratch, the runner user's T and Xcode's |
| +// and SwiftPM's caches; |
| // the §4.2 denies for reads and writes, plus the install dir for |
| // writes; no network; the Mach services xcodebuild needs. |
| func ChecksSettings(in ChecksInput) ([]byte, error) { |
| deny := DenyList(in.Paths) |
| - write := []string{in.Tree, in.Attempt, |
| + if in.UserTemp == "" || in.UserTemp == UserTempPrefix || !within(UserTempPrefix, in.UserTemp) { |
| + return nil, ErrProfile |
| + } |
| + write := []string{in.Tree, in.Attempt, in.UserTemp, |
| filepath.Join(in.Home, "Library/Developer/Xcode/DerivedData"), |
| filepath.Join(in.Home, "Library/Caches/org.swift.swiftpm"), |
| filepath.Join(in.Home, "Library/org.swift.swiftpm")} |
| @@ -121,7 +130,7 @@ func ChecksSettings(in ChecksInput) ([]byte, error) { |
| // A writable place inside a denied one would not be writable (srt's |
| // denyWrite wins), and a tree inside the state dir would be the |
| // state dir: refuse rather than run a gate that cannot write. |
| - for _, w := range write[:2] { |
| + for _, w := range write[:3] { |
| for _, d := range denyWrite { |
| if within(d, w) || within(w, d) { |
| return nil, ErrProfile |
diff --git a/internal/runner/mac/profile_test.go b/internal/runner/mac/profile_test.go| index 1e691bca..44a107d1 100644 |
| --- a/internal/runner/mac/profile_test.go |
| +++ b/internal/runner/mac/profile_test.go |
| @@ -8,6 +8,12 @@ import ( |
| ) |
| func testPaths() Paths { |
| + p := homePaths() |
| + p.UserTemp = "/private/var/folders/4m/abc123_def/T" |
| + return p |
| +} |
| + |
| +func homePaths() Paths { |
| return Paths{Home: "/Users/equipo-paul", StateDir: "/Users/equipo-paul/.local/share/equipo-runner/state", |
| AccountsRoot: "/Users/equipo-paul/.local/share/equipo/accounts", SessionRoot: "/Users/equipo-paul/.local/share/equipo-runner/sessions", |
| InstallDir: "/Users/equipo-paul/.local/lib/equipo-runner", OtherHomes: []string{"/Users/paul", "/Users/Shared"}} |
| @@ -53,7 +59,9 @@ func TestChecksSettings(t *testing.T) { |
| if !slices.Contains(s.Filesystem.DenyWrite, in.InstallDir) || slices.Contains(s.Filesystem.DenyRead, in.InstallDir) { |
| t.Fatalf("install dir: writes denied, reads allowed (srt runs from it): %s", raw) |
| } |
| - want := []string{in.Tree, in.Attempt, "/Users/equipo-paul/Library/Developer/Xcode/DerivedData", "/Users/equipo-paul/Library/Caches/org.swift.swiftpm", "/Users/equipo-paul/Library/org.swift.swiftpm"} |
| + // The user's T is the one place added by the coordinator's ruling |
| + // (Xcode writes there whatever $TMPDIR says); nothing else widened. |
| + want := []string{in.Tree, in.Attempt, "/private/var/folders/4m/abc123_def/T", "/Users/equipo-paul/Library/Developer/Xcode/DerivedData", "/Users/equipo-paul/Library/Caches/org.swift.swiftpm", "/Users/equipo-paul/Library/org.swift.swiftpm"} |
| if !slices.Equal(s.Filesystem.AllowWrite, want) { |
| t.Fatalf("allowWrite %v, want %v", s.Filesystem.AllowWrite, want) |
| } |
| @@ -79,6 +87,10 @@ func TestChecksSettingsRefusals(t *testing.T) { |
| "glob home": func(in *ChecksInput) { in.OtherHomes = []string{"/Users/[ab]"} }, |
| "every mach service": func(in *ChecksInput) { in.Mach = []string{"*"} }, |
| "inner mach wildcard": func(in *ChecksInput) { in.Mach = []string{"com.*.dt"} }, |
| + "no user temp": func(in *ChecksInput) { in.UserTemp = "" }, |
| + "user temp elsewhere": func(in *ChecksInput) { in.UserTemp = "/Users/equipo-paul/tmp" }, |
| + "all users' temp": func(in *ChecksInput) { in.UserTemp = UserTempPrefix }, |
| + "glob user temp": func(in *ChecksInput) { in.UserTemp = UserTempPrefix + "/*/T" }, |
| } { |
| in := good |
| in.Paths.OtherHomes = slices.Clone(good.OtherHomes) |
diff --git a/internal/runner/mac/usertemp.go b/internal/runner/mac/usertemp.go| new file mode 100644 |
| index 00000000..f2bd0091 |
| --- /dev/null |
| +++ b/internal/runner/mac/usertemp.go |
| @@ -0,0 +1,441 @@ |
| +package mac |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "time" |
| +) |
| + |
| +// The runner user's DARWIN_USER_TEMP_DIR ("T"). Xcode writes there |
| +// whatever $TMPDIR says: Foundation's temporary directory under Seatbelt |
| +// (Swift Build's swbuild.tmp.*, swift-driver's TemporaryDirectory.*) and |
| +// NSItemReplacementDirectory's TemporaryItems/NSIRD_* (atomic saves of |
| +// logs and result bundles). The checks profile lets a gate write it |
| +// (the coordinator's ruling); this file finds it, refuses one it cannot |
| +// trust, and removes what an attempt left there. |
| + |
| +// UserTempPrefix is where macOS keeps every user's T. |
| +const UserTempPrefix = "/private/var/folders" |
| + |
| +// ErrUserTemp says T was not found or is not the runner user's own. |
| +var ErrUserTemp = errors.New("mac: user temp folder refused") |
| + |
| +// UserTemp resolves the runner user's T: `getconf DARWIN_USER_TEMP_DIR`, |
| +// its symlinks resolved (/var is /private/var), no trailing slash. It |
| +// must be a directory under prefix (UserTempPrefix), owned by uid, mode |
| +// 0700; otherwise the error says why and no checks profile can be made. |
| +func UserTemp(ctx context.Context, x Exec, uid int, prefix string) (string, error) { |
| + ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| + defer cancel() |
| + out, err := x(ctx, "/usr/bin/getconf", "DARWIN_USER_TEMP_DIR") |
| + raw := strings.TrimSpace(out) |
| + if err != nil || raw == "" || !filepath.IsAbs(raw) { |
| + return "", refuse("getconf did not name it") |
| + } |
| + path, err := filepath.EvalSymlinks(raw) |
| + if err != nil { |
| + return "", refuse("it does not exist") |
| + } |
| + path = filepath.Clean(path) |
| + if !within(prefix, path) || path == prefix || !literalPath(path) { |
| + return "", refuse("it is not under the system's user folders") |
| + } |
| + info, err := os.Lstat(path) |
| + if err != nil || !info.IsDir() { |
| + return "", refuse("it is not a directory") |
| + } |
| + st, ok := info.Sys().(*syscall.Stat_t) |
| + if !ok || int(st.Uid) != uid { |
| + return "", refuse("another user owns it") |
| + } |
| + if info.Mode().Perm() != 0700 { |
| + return "", refuse("its mode is not 0700") |
| + } |
| + return path, nil |
| +} |
| + |
| +// UserTempError is a refused T, with why in words (no path). |
| +type UserTempError struct{ Why string } |
| + |
| +func (e *UserTempError) Error() string { return ErrUserTemp.Error() + ": " + e.Why } |
| +func (e *UserTempError) Is(target error) bool { return target == ErrUserTemp } |
| + |
| +func refuse(why string) error { return &UserTempError{Why: why} } |
| + |
| +// tempItems is NSItemReplacementDirectory's folder in T. |
| +const tempItems = "TemporaryItems" |
| + |
| +// tempEntry is one name in T or T/TemporaryItems and the file it was. |
| +type tempEntry struct { |
| + Dev uint64 `json:"dev"` |
| + Ino uint64 `json:"ino"` |
| + Kind fs.FileMode `json:"kind"` |
| +} |
| + |
| +func entryOf(info fs.FileInfo) tempEntry { |
| + e := tempEntry{Kind: info.Mode().Type()} |
| + if st, ok := info.Sys().(*syscall.Stat_t); ok { |
| + e.Dev, e.Ino = uint64(st.Dev), uint64(st.Ino) |
| + } |
| + return e |
| +} |
| + |
| +// tempListing is what was in T (keys "name") and T/TemporaryItems (keys |
| +// "TemporaryItems/name") right before an attempt. |
| +type tempListing map[string]tempEntry |
| + |
| +// tempState is T held open for one attempt: the directory listed, by |
| +// handle (os.Root), so a T replaced meanwhile (by a symlink, say) is |
| +// never what the cleanup reads or removes in; and the same for |
| +// T/TemporaryItems, held only when it was a real directory. |
| +type tempState struct { |
| + root, items *os.Root |
| + before tempListing |
| +} |
| + |
| +// openTemp opens T for an attempt and lists it. T must still be a real |
| +// directory (not a symlink), this user's own, mode 0700, and the |
| +// directory opened must be the one at the path. |
| +func openTemp(dir string, before tempListing) (*tempState, error) { |
| + info, err := os.Lstat(dir) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if st, ok := info.Sys().(*syscall.Stat_t); !info.IsDir() || !ok || int(st.Uid) != os.Getuid() || info.Mode().Perm() != 0700 { |
| + return nil, ErrUserTemp |
| + } |
| + root, err := os.OpenRoot(dir) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s := &tempState{root: root, before: before} |
| + if self, err := root.Stat("."); err != nil || entryOf(self) != entryOf(info) { |
| + s.close() |
| + return nil, ErrUserTemp |
| + } |
| + now, err := list(root, "") |
| + if err != nil { |
| + s.close() |
| + return nil, err |
| + } |
| + // TemporaryItems by handle, and only the directory that was there |
| + // before (a fresh listing: the one there now). |
| + want, had := now[tempItems], true |
| + if before != nil { |
| + want, had = before[tempItems] |
| + } |
| + if items, ok := now[tempItems]; ok && had && items == want && items.Kind == fs.ModeDir { |
| + if s.items, err = root.OpenRoot(tempItems); err == nil { |
| + if self, err := s.items.Stat("."); err != nil || entryOf(self) != items { |
| + s.items.Close() |
| + s.items = nil |
| + } |
| + } else if !errors.Is(err, fs.ErrNotExist) { |
| + s.close() |
| + return nil, err |
| + } |
| + } |
| + if s.items != nil { |
| + in, err := list(s.items, tempItems+"/") |
| + if err != nil { |
| + s.close() |
| + return nil, err |
| + } |
| + for k, v := range in { |
| + now[k] = v |
| + } |
| + } |
| + if s.before == nil { |
| + s.before = now |
| + } |
| + return s, nil |
| +} |
| + |
| +func (s *tempState) close() { |
| + if s.items != nil { |
| + s.items.Close() |
| + } |
| + s.root.Close() |
| +} |
| + |
| +// list names what is in dir (by handle), keyed with prefix. A name gone |
| +// between the listing and the look is not there; any other error is. |
| +func list(dir *os.Root, prefix string) (tempListing, error) { |
| + f, err := dir.Open(".") |
| + if err != nil { |
| + return nil, err |
| + } |
| + names, err := f.Readdirnames(-1) |
| + f.Close() |
| + if err != nil { |
| + return nil, err |
| + } |
| + l := tempListing{} |
| + for _, n := range names { |
| + info, err := dir.Lstat(n) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + l[prefix+n] = entryOf(info) |
| + } |
| + return l, nil |
| +} |
| + |
| +// clean removes what appeared in T and T/TemporaryItems since before: |
| +// every name not listed then, or listed as another file (same name, |
| +// other device, file number or kind). Each name is removed by the handle of |
| +// its own directory, one path element, so no symlink is followed: a |
| +// symlink goes as itself. A folder the attempt made unreadable is made |
| +// the owner's again to be removed. What vanishes meanwhile is not an |
| +// error; anything else is. |
| +func (s *tempState) clean() error { |
| + var errs []error |
| + for _, d := range []struct { |
| + root *os.Root |
| + prefix string |
| + }{{s.root, ""}, {s.items, tempItems + "/"}} { |
| + if d.root == nil { |
| + continue |
| + } |
| + now, err := list(d.root, d.prefix) |
| + if err != nil { |
| + errs = append(errs, err) |
| + continue |
| + } |
| + for name, e := range now { |
| + if old, ok := s.before[name]; ok && old == e { |
| + continue |
| + } |
| + if err := remove(d.root, strings.TrimPrefix(name, d.prefix)); err != nil { |
| + errs = append(errs, err) |
| + } |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// remove removes name in dir and all below it, never through a symlink; |
| +// a folder that cannot be read or written is given back to its owner |
| +// (this user) first. |
| +func remove(dir *os.Root, name string) error { |
| + err := dir.RemoveAll(name) |
| + if err == nil || errors.Is(err, fs.ErrNotExist) { |
| + return nil |
| + } |
| + if info, lerr := dir.Lstat(name); lerr == nil && info.IsDir() { |
| + _ = unlock(dir, name, 0) |
| + } |
| + if err := dir.RemoveAll(name); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| +// unlock makes the folder name (and the folders below it) 0700 again, |
| +// opening each by handle so no symlink is followed. |
| +func unlock(dir *os.Root, name string, depth int) error { |
| + if depth > 64 { |
| + return errors.New("mac: too deep") |
| + } |
| + if err := dir.Chmod(name, 0700); err != nil { |
| + return err |
| + } |
| + sub, err := dir.OpenRoot(name) |
| + if err != nil { |
| + return err |
| + } |
| + defer sub.Close() |
| + in, err := list(sub, "") |
| + if err != nil { |
| + return err |
| + } |
| + for n, e := range in { |
| + if e.Kind == fs.ModeDir { |
| + _ = unlock(sub, n, depth+1) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// Turns lets one gate run at a time on a Mac, across the runner's |
| +// processes (the worker and the probe command): a channel within a |
| +// process and an flock on a file in the state dir, which no checks |
| +// profile lets a gate reach, between them. A sandboxed attempt's T |
| +// cleanup removes what appeared in T while it ran, so nothing else of |
| +// the runner's may run beside it. It also keeps a cleanup that did not |
| +// finish (lock + ".pending": what T held before, as JSON): until a later |
| +// one finishes it, no sandboxed gate runs. |
| +type Turns struct { |
| + ch chan struct{} |
| + lock string |
| + f *os.File |
| +} |
| + |
| +// NewTurns makes the runner's one turn; lock is its file in the state |
| +// dir ("" keeps the turn within this process). |
| +func NewTurns(lock string) *Turns { return &Turns{ch: make(chan struct{}, 1), lock: lock} } |
| + |
| +func (t *Turns) take(ctx context.Context) error { |
| + select { |
| + case t.ch <- struct{}{}: |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + if t.lock == "" { |
| + return nil |
| + } |
| + f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600) |
| + if err != nil { |
| + <-t.ch |
| + return err |
| + } |
| + for { |
| + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| + if err == nil { |
| + t.f = f |
| + return nil |
| + } |
| + if !errors.Is(err, syscall.EWOULDBLOCK) { |
| + f.Close() |
| + <-t.ch |
| + return err |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + f.Close() |
| + <-t.ch |
| + return ctx.Err() |
| + case <-time.After(250 * time.Millisecond): |
| + } |
| + } |
| +} |
| + |
| +// TryTake takes the turn only if it is free now (in this process and |
| +// the others); Give gives it back. |
| +func (t *Turns) TryTake() bool { |
| + select { |
| + case t.ch <- struct{}{}: |
| + default: |
| + return false |
| + } |
| + if t.lock == "" { |
| + return true |
| + } |
| + f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600) |
| + if err == nil { |
| + if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil { |
| + t.f = f |
| + return true |
| + } |
| + f.Close() |
| + } |
| + <-t.ch |
| + return false |
| +} |
| + |
| +// Give gives the turn back. |
| +func (t *Turns) Give() { t.give() } |
| + |
| +func (t *Turns) give() { |
| + if t.f != nil { |
| + _ = syscall.Flock(int(t.f.Fd()), syscall.LOCK_UN) |
| + t.f.Close() |
| + t.f = nil |
| + } |
| + <-t.ch |
| +} |
| + |
| +func (t *Turns) pending() string { |
| + if t == nil || t.lock == "" { |
| + return "" |
| + } |
| + return t.lock + ".pending" |
| +} |
| + |
| +// pendingRecord is a sandboxed attempt whose T cleanup is not done yet: |
| +// written before anything of the attempt starts (and again with its |
| +// group once there is one), removed only once its end is proven and T |
| +// is cleaned. A runner killed meanwhile leaves it for the next gate, |
| +// in any runner process. |
| +type pendingRecord struct { |
| + Attempt string `json:"attempt"` |
| + PGID int `json:"pgid"` |
| + Before tempListing `json:"before"` |
| +} |
| + |
| +// writePending records r durably (written beside, then renamed over). |
| +// Without a lock file (tests) there is nowhere to keep it. |
| +func (t *Turns) writePending(r pendingRecord) error { |
| + p := t.pending() |
| + if p == "" { |
| + return nil |
| + } |
| + raw, err := json.Marshal(r) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := os.OpenFile(p+".new", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = f.Write(raw) |
| + if serr := f.Sync(); err == nil { |
| + err = serr |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return os.Rename(p+".new", p) |
| +} |
| + |
| +// readPending is the record an earlier attempt left; ok is false when |
| +// there is none. One that cannot be read is an error: nothing runs |
| +// until a person looks. |
| +func (t *Turns) readPending() (r pendingRecord, ok bool, err error) { |
| + p := t.pending() |
| + if p == "" { |
| + return r, false, nil |
| + } |
| + raw, err := os.ReadFile(p) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return r, false, nil |
| + } |
| + if err != nil { |
| + return r, false, err |
| + } |
| + if err := json.Unmarshal(raw, &r); err != nil || r.Attempt == "" || r.Before == nil { |
| + return r, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err) |
| + } |
| + return r, true, nil |
| +} |
| + |
| +// dropPending removes the record once its cleanup is done. |
| +func (t *Turns) dropPending() error { |
| + p := t.pending() |
| + if p == "" { |
| + return nil |
| + } |
| + if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| +// Pending reports whether an attempt's cleanup is still to be done |
| +// (the warm waits for it: that attempt's end is not proven yet). |
| +func (t *Turns) Pending() bool { |
| + _, err := os.Lstat(t.pending()) |
| + return t.pending() != "" && err == nil |
| +} |
diff --git a/internal/runner/mac/usertemp_test.go b/internal/runner/mac/usertemp_test.go| new file mode 100644 |
| index 00000000..40117677 |
| --- /dev/null |
| +++ b/internal/runner/mac/usertemp_test.go |
| @@ -0,0 +1,366 @@ |
| +package mac |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// userTempFixture is a stand-in for /private/var/folders with one |
| +// user's T in it, 0700 and this test's own. |
| +func userTempFixture(t *testing.T) (prefix, temp string) { |
| + t.Helper() |
| + prefix, err := filepath.EvalSymlinks(t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + temp = filepath.Join(prefix, "4m", "abc123_def", "T") |
| + if err := os.MkdirAll(temp, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + return prefix, temp |
| +} |
| + |
| +func getconf(out string, err error) Exec { |
| + return func(_ context.Context, name string, args ...string) (string, error) { |
| + if name != "/usr/bin/getconf" || strings.Join(args, " ") != "DARWIN_USER_TEMP_DIR" { |
| + return "", errors.New("not getconf") |
| + } |
| + return out, err |
| + } |
| +} |
| + |
| +// T is getconf's answer with its symlinks resolved and no trailing |
| +// slash, and only when it is the runner user's own 0700 directory |
| +// under the system's user folders; otherwise why, in words. |
| +func TestUserTemp(t *testing.T) { |
| + prefix, temp := userTempFixture(t) |
| + uid := os.Getuid() |
| + // macOS names it through /var, a symlink to /private/var. |
| + link := filepath.Join(t.TempDir(), "var-T") |
| + if err := os.Symlink(temp, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, err := UserTemp(context.Background(), getconf(link+"/\n", nil), uid, prefix); err != nil || got != temp { |
| + t.Fatalf("resolved %q %v, want %q", got, err, temp) |
| + } |
| + refused := func(name, why string, x Exec, uid int) { |
| + t.Helper() |
| + got, err := UserTemp(context.Background(), x, uid, prefix) |
| + var e *UserTempError |
| + if got != "" || !errors.Is(err, ErrUserTemp) || !errors.As(err, &e) || e.Why != why || strings.Contains(e.Why, "/") { |
| + t.Fatalf("%s: %q %v", name, got, err) |
| + } |
| + } |
| + refused("another owner", "another user owns it", getconf(temp, nil), uid+1) |
| + refused("getconf failed", "getconf did not name it", getconf("", errors.New("exit 1")), uid) |
| + refused("relative", "getconf did not name it", getconf("T/", nil), uid) |
| + refused("missing", "it does not exist", getconf(temp+"-gone", nil), uid) |
| + refused("the prefix itself", "it is not under the system's user folders", getconf(prefix, nil), uid) |
| + elsewhere := t.TempDir() |
| + if err := os.Chmod(elsewhere, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused("outside the user folders", "it is not under the system's user folders", getconf(elsewhere, nil), uid) |
| + // A link inside the user folders that leads out of them. |
| + if err := os.Symlink(elsewhere, filepath.Join(prefix, "out")); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused("linked out", "it is not under the system's user folders", getconf(filepath.Join(prefix, "out"), nil), uid) |
| + file := filepath.Join(prefix, "file") |
| + if err := os.WriteFile(file, nil, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused("a file", "it is not a directory", getconf(file, nil), uid) |
| + if err := os.Chmod(temp, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused("readable by others", "its mode is not 0700", getconf(temp, nil), uid) |
| +} |
| + |
| +// tempTree writes what T holds before an attempt: a file, a folder, |
| +// TemporaryItems with one entry, and a folder outside T. |
| +func tempTree(t *testing.T, temp string) (outside string) { |
| + t.Helper() |
| + for _, d := range []string{"keepdir", "TemporaryItems/old", "shared"} { |
| + if err := os.MkdirAll(filepath.Join(temp, d), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, f := range []string{"keep", "shared/a"} { |
| + if err := os.WriteFile(filepath.Join(temp, f), []byte("before"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + outside = t.TempDir() |
| + if err := os.WriteFile(filepath.Join(outside, "precious"), []byte("x"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return outside |
| +} |
| + |
| +func exists(p string) bool { _, err := os.Lstat(p); return err == nil } |
| + |
| +// Once a sandboxed run is proven over, what appeared in T and in |
| +// T/TemporaryItems goes and what was there stays, even rewritten; a |
| +// symlink goes as itself, never what it leads to. |
| +func TestGateCleansUserTemp(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + outside := tempTree(t, temp) |
| + g.UserTemp = temp |
| + script := `T=` + quote(temp) + ` |
| +echo after > "$T/keep" |
| +mkdir -p "$T/new/deep" "$T/swbuild.tmp.1" "$T/TemporaryItems/NSIRD_xcodebuild_1" && touch "$T/new/deep/f" "$T/TemporaryDirectory.2" |
| +ln -s ` + quote(outside) + ` "$T/link" |
| +ln -s ` + quote(outside) + ` "$T/TemporaryItems/NSIRD_link"` |
| + if res, _ := run(g, dir, "checks-t-1", time.Minute, script); res.Code != 0 || !res.Terminated { |
| + t.Fatalf("%+v", res) |
| + } |
| + for _, kept := range []string{"keep", "keepdir", "shared/a", "TemporaryItems", "TemporaryItems/old"} { |
| + if !exists(filepath.Join(temp, kept)) { |
| + t.Fatalf("%s was there before and is gone", kept) |
| + } |
| + } |
| + for _, gone := range []string{"new", "swbuild.tmp.1", "TemporaryDirectory.2", "link", "TemporaryItems/NSIRD_xcodebuild_1", "TemporaryItems/NSIRD_link"} { |
| + if exists(filepath.Join(temp, gone)) { |
| + t.Fatalf("%s appeared during the run and is left", gone) |
| + } |
| + } |
| + if !exists(filepath.Join(outside, "precious")) { |
| + t.Fatal("the cleanup followed a symlink out of T") |
| + } |
| +} |
| + |
| +// TemporaryItems swapped for a symlink to a folder that was in T before: |
| +// the link goes, the folder and what it held stay. |
| +func TestGateCleanupKeepsASwappedTemporaryItemsTarget(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + tempTree(t, temp) |
| + g.UserTemp = temp |
| + // Relative, so it stays inside T, where os.Root would follow it. |
| + script := `T=` + quote(temp) + `; rm -rf "$T/TemporaryItems" && ln -s shared "$T/TemporaryItems"` |
| + if res, _ := run(g, dir, "checks-t-2", time.Minute, script); res.Code != 0 || !res.Terminated { |
| + t.Fatalf("%+v", res) |
| + } |
| + if exists(filepath.Join(temp, "TemporaryItems")) || !exists(filepath.Join(temp, "shared/a")) { |
| + t.Fatal("a swapped TemporaryItems was followed, or left") |
| + } |
| +} |
| + |
| +// A run whose end is not proven may still be writing T: nothing is |
| +// removed then. |
| +func TestGateCleanupWaitsForTheProvenEnd(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock")) |
| + g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil } |
| + quieted := 0 |
| + g.QuietSimulators = func(context.Context) { quieted++ } |
| + res, _ := run(g, dir, "checks-t-3", time.Minute, `touch `+quote(filepath.Join(temp, "late"))) |
| + if res.Terminated || !exists(filepath.Join(temp, "late")) || quieted != 0 { |
| + t.Fatalf("cleaned before the end was proven: %+v", res) |
| + } |
| + // The next gate finishes that cleanup before anything of its own runs. |
| + g.find = nil |
| + res, _ = run(g, dir, "checks-t-3b", time.Minute, `ls `+quote(temp)+`; touch `+quote(filepath.Join(temp, "next"))) |
| + if !res.Terminated || strings.Contains(res.Output, "late") || exists(filepath.Join(temp, "late")) || exists(filepath.Join(temp, "next")) || exists(g.Turns.pending()) { |
| + t.Fatalf("the left cleanup was not finished first: %+v", res) |
| + } |
| + // One that cannot be finished (T is no longer a folder of this |
| + // user's): nothing runs. |
| + g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil } |
| + run(g, dir, "checks-t-3c", time.Minute, `true`) |
| + g.find = nil |
| + if err := os.Chmod(temp, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if res, _ := run(g, dir, "checks-t-3d", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) { |
| + t.Fatalf("ran with a cleanup left that cannot be finished: %+v", res) |
| + } |
| + if err := os.Chmod(temp, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A T that cannot be listed: nothing runs. |
| + g.UserTemp = filepath.Join(temp, "gone") |
| + if res, _ := run(g, dir, "checks-t-4", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) { |
| + t.Fatalf("ran without a listing of T: %+v", res) |
| + } |
| +} |
| + |
| +// Gates sharing the Mac's turns never overlap, sandboxed or not, and one |
| +// waiting for its turn can be cancelled before anything of it runs. |
| +func TestGatesTakeTurns(t *testing.T) { |
| + // Two processes' turns over one lock file (the worker and |
| + // the probe command): as one. |
| + lock := filepath.Join(t.TempDir(), "lock") |
| + turns := NewTurns(lock) |
| + a, dirA := gateFixture(t, true) |
| + b, dirB := gateFixture(t, false) |
| + a.Turns, b.Turns = turns, NewTurns(lock) |
| + log := filepath.Join(t.TempDir(), "log") |
| + step := func(name string) string { |
| + return `echo ` + name + `-start >> ` + quote(log) + `; sleep 0.3; echo ` + name + `-end >> ` + quote(log) |
| + } |
| + var wg sync.WaitGroup |
| + for _, g := range []struct { |
| + g *Gate |
| + dir string |
| + name string |
| + }{{a, dirA, "a"}, {b, dirB, "b"}} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + if res, _ := run(g.g, g.dir, "checks-turn-"+g.name, time.Minute, step(g.name)); res.Code != 0 { |
| + t.Errorf("%s: %+v", g.name, res) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + raw, _ := os.ReadFile(log) |
| + lines := strings.Fields(string(raw)) |
| + if len(lines) != 4 || strings.TrimSuffix(lines[0], "-start") != strings.TrimSuffix(lines[1], "-end") { |
| + t.Fatalf("gates overlapped: %v", lines) |
| + } |
| + if err := turns.take(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b.Turns.TryTake() { |
| + t.Fatal("TryTake while another holds the turn") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + defer cancel() |
| + res := b.Run(ctx, "checks-turn-c", dirB, []string{"/bin/sh", "-c", "touch " + quote(log+".c")}, time.Minute, func(string) error { return nil }) |
| + turns.give() |
| + if res.Reason != "cancelled" || !res.Terminated || exists(log+".c") { |
| + t.Fatalf("ran without its turn: %+v", res) |
| + } |
| +} |
| + |
| +// P2 needs the user's T: refused, it says why (in words) and checks |
| +// wait for the sandbox. |
| +func TestP2NeedsTheUserTemp(t *testing.T) { |
| + f := newProbeFixture(t, allLines("denied")) |
| + f.h.Paths.UserTemp, f.h.Paths.UserTempWhy = "", "its mode is not 0700" |
| + p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if ran || p.Verdict != wire.ProbeUnavailable || p.Detail != "user temp folder refused: its mode is not 0700" { |
| + t.Fatalf("%+v", p) |
| + } |
| +} |
| + |
| +// What the attempt made unreadable is still removed; a T replaced by a |
| +// symlink during the run is cleaned by the folder it was (never where |
| +// the link leads), and the next gate runs nothing. |
| +func TestGateCleanupHoldsT(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + outside := tempTree(t, temp) |
| + g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock")) |
| + locked := `T=` + quote(temp) + `; mkdir -p "$T/left/deep" && touch "$T/left/deep/payload" && chmod 000 "$T/left/deep" "$T/left"` |
| + if res, _ := run(g, dir, "checks-t-5", time.Minute, locked); res.Code != 0 || exists(filepath.Join(temp, "left")) || exists(g.Turns.pending()) { |
| + t.Fatalf("a locked folder was left: %+v", res) |
| + } |
| + moved := filepath.Join(filepath.Dir(temp), "T-moved") |
| + swap := `T=` + quote(temp) + `; touch "$T/new" && mv "$T" ` + quote(moved) + ` && ln -s ` + quote(outside) + ` "$T"` |
| + if res, _ := run(g, dir, "checks-t-6", time.Minute, swap); res.Code != 0 || !res.Terminated { |
| + t.Fatalf("%+v", res) |
| + } |
| + if exists(filepath.Join(moved, "new")) || !exists(filepath.Join(moved, "keep")) || !exists(filepath.Join(outside, "precious")) { |
| + t.Fatal("the cleanup did not hold the T it listed") |
| + } |
| + if res, _ := run(g, dir, "checks-t-7", time.Minute, `touch `+quote(filepath.Join(outside, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(outside, "ran")) { |
| + t.Fatalf("ran with T a symlink: %+v", res) |
| + } |
| +} |
| + |
| +// The digest names a profile ChecksSettings makes, not a refusal. |
| +func TestProfileDigest(t *testing.T) { |
| + if _, err := ChecksSettings(digestInput()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Simulators are shut down once the end is proven and before T is |
| +// cleaned (CoreSimulator's processes may still be writing it); however |
| +// long that takes, the cleanup then runs and the run's result stands. |
| +func TestGateQuietsSimulatorsBeforeCleaning(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + g.UserTemp = temp |
| + var saw []bool |
| + g.QuietSimulators = func(context.Context) { |
| + saw = append(saw, exists(filepath.Join(temp, "new"))) |
| + time.Sleep(300 * time.Millisecond) |
| + } |
| + res, _ := run(g, dir, "checks-t-8", time.Minute, `touch `+quote(filepath.Join(temp, "new"))) |
| + if len(saw) != 1 || !saw[0] || exists(filepath.Join(temp, "new")) || res.Code != 0 || res.Reason != "" || !res.Terminated { |
| + t.Fatalf("quieted %v before cleaning, result %+v", saw, res) |
| + } |
| +} |
| + |
| +// The cleanup is on record before anything of an attempt starts: a |
| +// runner killed mid-run leaves it to the next gate (any process), which |
| +// first proves that attempt over, then cleans T, then runs. Not proven, |
| +// unreadable or unrecordable: nothing runs. |
| +func TestGatePendingCleanupSurvivesTheRunner(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + _, temp := userTempFixture(t) |
| + tempTree(t, temp) |
| + lock := filepath.Join(t.TempDir(), "lock") |
| + g.UserTemp, g.Turns, g.Settle = temp, NewTurns(lock), 500*time.Millisecond |
| + // The killed runner's attempt: its record, then what it left. |
| + s, err := openTemp(temp, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := g.Turns.writePending(pendingRecord{Attempt: "checks-dead", Before: s.before}); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.close() |
| + if err := os.WriteFile(filepath.Join(temp, "leftover"), nil, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Still running (a process with its marker): nothing runs, nothing goes. |
| + g.find = func(a string) ([]Proc, error) { |
| + if a == "checks-dead" { |
| + return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil |
| + } |
| + return nil, nil |
| + } |
| + ran := filepath.Join(t.TempDir(), "ran") |
| + if res, _ := run(g, dir, "checks-p-1", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !exists(filepath.Join(temp, "leftover")) { |
| + t.Fatalf("ran beside an unproven attempt: %+v", res) |
| + } |
| + // Over: its leftovers go before the next gate runs, and the record. |
| + g.find = func(string) ([]Proc, error) { return nil, nil } |
| + quieted := 0 |
| + g.QuietSimulators = func(context.Context) { quieted++ } |
| + res, _ := run(g, dir, "checks-p-2", time.Minute, `ls `+quote(temp)) |
| + if res.Code != 0 || strings.Contains(res.Output, "leftover") || exists(filepath.Join(temp, "leftover")) || exists(g.Turns.pending()) || quieted != 2 { |
| + t.Fatalf("pending cleanup not finished first (quieted %d): %+v", quieted, res) |
| + } |
| + // A record that cannot be read, or written: nothing runs. |
| + if err := os.WriteFile(g.Turns.pending(), []byte("{"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if res, _ := run(g, dir, "checks-p-3", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !g.Turns.Pending() { |
| + t.Fatalf("ran past an unreadable record: %+v", res) |
| + } |
| + if err := os.Remove(g.Turns.pending()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Mkdir(g.Turns.pending()+".new", 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if res, _ := run(g, dir, "checks-p-4", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) { |
| + t.Fatalf("ran without its cleanup on record: %+v", res) |
| + } |
| +} |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index a1e81c74..e7fcb547 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -13,6 +13,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "slices" |
| "strconv" |
| "strings" |
| "sync" |
| @@ -406,6 +407,12 @@ const srtPinned = "pinned" |
| // macUsers is where a Mac keeps its people's homes. |
| var macUsers = "/Users" |
| +// macUserTemp resolves the runner user's DARWIN_USER_TEMP_DIR (tests |
| +// stand in: a Linux host has none). |
| +var macUserTemp = func(ctx context.Context, x mac.Exec) (string, error) { |
| + return mac.UserTemp(ctx, x, os.Getuid(), mac.UserTempPrefix) |
| +} |
| + |
| // macHost is the Mac worker's setup: its tools, paths and gates. |
| type macHost struct { |
| // scratch is the runner's scratch root: the probes' fixture copies |
| @@ -422,6 +429,48 @@ type macHost struct { |
| // gathering (capsLogged) and of xcode-select at start. |
| log *slog.Logger |
| capsLogged atomic.Bool |
| + // turns lets one gate at a time run (mac.Turns). |
| + turns *mac.Turns |
| + // warmMu guards warmed, the Xcode (version and build) whose plugin |
| + // cache was last warmed. |
| + warmMu sync.Mutex |
| + warmed string |
| +} |
| + |
| +// warm builds Xcode's plugin cache (DARWIN_USER_CACHE_DIR/ |
| +// com.apple.DeveloperTools/<version>/Xcode/PlugInCache-xcodebuild. |
| +// xcplugincache) outside the sandbox, once per Xcode version and build: |
| +// a checks profile does not let a gate write it, so a sandboxed |
| +// xcodebuild must find it current. Bounded by QueryLimit. |
| +func (h *macHost) warm(ctx context.Context, x wire.Xcode) { |
| + key := x.Version + " " + x.Build |
| + if x.Version == "" || h.tools.Xcodebuild == "" { |
| + return |
| + } |
| + h.warmMu.Lock() |
| + defer h.warmMu.Unlock() |
| + // Not while a gate runs (its T cleanup could take what the warm |
| + // writes there): the next gathering tries again, as after a failure. |
| + if h.warmed == key || h.turns != nil && !h.turns.TryTake() { |
| + return |
| + } |
| + if h.turns != nil { |
| + defer h.turns.Give() |
| + // Nor while an earlier attempt's end is unproven (its cleanup |
| + // pending): the next gate settles that first. |
| + if h.turns.Pending() { |
| + return |
| + } |
| + } |
| + c, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| + defer cancel() |
| + if _, err := h.run(c, h.tools.Xcodebuild, "-showsdks"); err != nil { |
| + if h.log != nil { |
| + h.log.Info("xcode plugin cache not warmed", "xcode", key, "err", err) |
| + } |
| + return |
| + } |
| + h.warmed = key |
| } |
| // slowCommand is how long a command the Mac worker runs may take before |
| @@ -595,10 +644,27 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| h.paths = mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: accounts, SessionRoot: SessionRoot(c), InstallDir: filepath.Dir(c.Executable), OtherHomes: others, HomesUnknown: err != nil} |
| h.tools = macTools(h.paths.InstallDir, home, getenv) |
| h.env = []string{"HOME=" + home, "PATH=" + gatePath(h.tools), "CI=1", "LANG=en_US.UTF-8"} |
| + // One turn for every gate and the warm, across this user's runner |
| + // processes (the worker and the probe command). |
| + h.turns = mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock")) |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| if out, err := h.logged(slog.LevelInfo)(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) { |
| h.env = append(h.env, "DEVELOPER_DIR="+strings.TrimSpace(out)) |
| } |
| + // The user's T, which checks may write: refused, no checks profile |
| + // can be made, P2 says why and checks wait for the sandbox. |
| + if t, err := macUserTemp(ctx, h.logged(slog.LevelInfo)); err == nil { |
| + h.paths.UserTemp = t |
| + } else { |
| + h.paths.UserTempWhy = "not resolved" |
| + var why *mac.UserTempError |
| + if errors.As(err, &why) { |
| + h.paths.UserTempWhy = why.Why |
| + } |
| + if h.log != nil { |
| + h.log.Warn("user temp folder refused", "why", h.paths.UserTempWhy) |
| + } |
| + } |
| cancel() |
| settings := func(tree, attempt string) ([]byte, error) { |
| return mac.ChecksSettings(mac.ChecksInput{Paths: h.paths, Tree: tree, Attempt: attempt, Mach: mac.CheckMachServices}) |
| @@ -625,13 +691,14 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| _, _ = h.run(c, h.tools.Xcrun, "simctl", "shutdown", udid) |
| } |
| gate := func(srt, label string) *mac.Gate { |
| - g := &mac.Gate{SRT: srt, Env: h.env, Caffeinate: "/usr/bin/caffeinate", Booted: booted, Shutdown: shutdown, Lines: wire.MaxChecksLines, Sandbox: label} |
| + g := &mac.Gate{SRT: srt, Env: h.env, Caffeinate: "/usr/bin/caffeinate", Booted: booted, Shutdown: shutdown, Lines: wire.MaxChecksLines, Sandbox: label, Turns: h.turns} |
| if srt != "" { |
| - g.Settings = settings |
| + g.Settings, g.UserTemp, g.QuietSimulators = settings, h.paths.UserTemp, h.quietSimulators |
| } |
| return g |
| } |
| h.probes = newMacProbes(o.Version, ProbeRequest(c), func(ctx context.Context) mac.Report { |
| + h.warmNow(ctx) |
| return mac.RunProbes(ctx, h.probeHost(o.Version, gate)) |
| }, func() bool { return mac.VerifyTools(h.paths.InstallDir, h.tools) == nil }) |
| h.probes.log = o.Logger |
| @@ -645,7 +712,10 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| if h.capsLogged.CompareAndSwap(false, true) { |
| level = slog.LevelInfo |
| } |
| + // Outside the turn (the coordinator's ruling): a T cleanup may take |
| + // these queries' temp files, which costs availability only. |
| caps := mac.Capabilities(ctx, h.logged(level), h.tools) |
| + h.warm(ctx, caps.Xcode) |
| if probes := h.probes.report().Probes; len(probes) > 0 { |
| caps.Probes = probes |
| } |
| @@ -655,6 +725,55 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| return h, nil |
| } |
| +// simShutdownLimit bounds `simctl shutdown all` before a T cleanup. |
| +// It shuts every booted simulator down one after another, each taking |
| +// seconds to tens of seconds, so QueryLimit (30 s) would cut a Mac with |
| +// a few booted short; two minutes is the most an attempt's end waits. |
| +var simShutdownLimit = 2 * time.Minute |
| + |
| +// macPS lists this user's processes by name (tests stand in). |
| +var macPS = "/bin/ps" |
| + |
| +// quietSimulators shuts down every simulator of the runner user (a |
| +// dedicated user, so all are the runner's) before a sandboxed |
| +// attempt's T is cleaned: CoreSimulator's processes are outside the |
| +// attempt's group and outside srt, and may still write T. Bounded; it |
| +// never fails the attempt. What simulator processes are left is |
| +// logged at info, names only. |
| +func (h *macHost) quietSimulators(ctx context.Context) { |
| + c, cancel := context.WithTimeout(ctx, simShutdownLimit) |
| + _, err := h.run(c, h.tools.Xcrun, "simctl", "shutdown", "all") |
| + cancel() |
| + if h.log == nil { |
| + return |
| + } |
| + if err != nil { |
| + h.log.Info("simulators not all shut down", "err", err) |
| + } |
| + c, cancel = context.WithTimeout(ctx, mac.QueryLimit) |
| + out, _ := h.run(c, macPS, "-x", "-o", "comm=") |
| + cancel() |
| + var left []string |
| + for _, l := range strings.Split(out, "\n") { |
| + if n := filepath.Base(strings.TrimSpace(l)); strings.Contains(strings.ToLower(n), "sim") && !slices.Contains(left, n) { |
| + left = append(left, n) |
| + } |
| + } |
| + if len(left) > 0 { |
| + slices.Sort(left) |
| + h.log.Info("simulator processes still running", "names", strings.Join(left, " ")) |
| + } |
| +} |
| + |
| +// warmNow warms the plugin cache for the Xcode installed now (the |
| +// probes run before any capability gathering may have). |
| +func (h *macHost) warmNow(ctx context.Context) { |
| + c, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| + out, _ := h.run(c, h.tools.Xcodebuild, "-version") |
| + cancel() |
| + h.warm(ctx, mac.ParseXcode(out)) |
| +} |
| + |
| func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) mac.ProbeHost { |
| return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), UID: os.Getuid(), Version: version, |
| Gate: func(sandboxed bool) *mac.Gate { |
diff --git a/internal/runner/thin/mac_test.go b/internal/runner/thin/mac_test.go| index 8d808329..73f1a251 100644 |
| --- a/internal/runner/thin/mac_test.go |
| +++ b/internal/runner/thin/mac_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| + "log/slog" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -269,15 +270,23 @@ func TestMacHostPaths(t *testing.T) { |
| if err := os.MkdirAll(filepath.Join(users, "paul"), 0700); err != nil { |
| t.Fatal(err) |
| } |
| - was := macUsers |
| + was, wasTemp := macUsers, macUserTemp |
| macUsers = users |
| - defer func() { macUsers = was }() |
| + const temp = "/private/var/folders/4m/abc123_def/T" |
| + macUserTemp = func(context.Context, mac.Exec) (string, error) { return temp, nil } |
| + defer func() { macUsers, macUserTemp = was, wasTemp }() |
| // The tools come from the runner's own environment (its env file), |
| // not the process's. |
| h, err := newMacHost(c, OptionsFromEnv(func(k string) string { return tools[k] })) |
| if err != nil { |
| t.Fatal(err) |
| } |
| + // The user's T: written by sandboxed gates and cleaned after each; |
| + // every gate takes the one turn. |
| + k := h.checks |
| + if h.paths.UserTemp != temp || k.sandboxed.UserTemp != temp || k.unproven.UserTemp != temp || k.bare.UserTemp != "" || k.sandboxed.Turns == nil || k.sandboxed.Turns != k.bare.Turns || k.sandboxed.QuietSimulators == nil || k.bare.QuietSimulators != nil { |
| + t.Fatalf("user temp %+v", h.paths) |
| + } |
| if p := h.probeHost("v1", nil); p.Scratch != filepath.Join(c.ScratchRoot, "probes") || p.Paths.StateDir != c.StateDir || p.Paths.InstallDir != filepath.Join(root, "lib") { |
| t.Fatalf("%+v", p) |
| } |
| @@ -309,6 +318,48 @@ func TestMacHostPaths(t *testing.T) { |
| if want := []string{"HOME=" + home, h.env[1], "CI=1", "LANG=en_US.UTF-8"}; !slices.Equal(h.env[:min(4, len(h.env))], want) || len(h.env) > 4 && (len(h.env) > 5 || !strings.HasPrefix(h.env[4], "DEVELOPER_DIR=")) || h.checks.sandboxed.ScratchHome || h.checks.unproven.ScratchHome { |
| t.Fatalf("gate env %v", h.env) |
| } |
| + // A refused T: why, in words, and no checks profile. |
| + macUserTemp = func(context.Context, mac.Exec) (string, error) { |
| + return "", &mac.UserTempError{Why: "another user owns it"} |
| + } |
| + if h, err = newMacHost(c, OptionsFromEnv(func(k string) string { return tools[k] })); err != nil || h.paths.UserTemp != "" || h.paths.UserTempWhy != "another user owns it" { |
| + t.Fatalf("refused T: %+v %v", h.paths, err) |
| + } |
| + if _, err := h.checks.sandboxed.Settings(filepath.Join(key, "tree"), filepath.Join(key, "attempt-1")); err == nil { |
| + t.Fatal("a checks profile without the user's T") |
| + } |
| +} |
| + |
| +// Xcode's plugin cache is warmed outside the sandbox with -showsdks, |
| +// once per Xcode version and build: again after a failure, and not |
| +// while a gate holds the turn. |
| +func TestMacWarmsThePluginCacheOncePerXcode(t *testing.T) { |
| + dir := t.TempDir() |
| + xb, log, fail := filepath.Join(dir, "xcodebuild"), filepath.Join(dir, "log"), filepath.Join(dir, "fail") |
| + if err := os.WriteFile(xb, []byte("#!/bin/sh\necho \"$*\" >> "+log+"\n[ ! -e "+fail+" ]\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + h := &macHost{tools: mac.Tools{Xcodebuild: xb}, turns: mac.NewTurns(filepath.Join(dir, "lock"))} |
| + b52, b60 := wire.Xcode{Version: "27.2", Build: "27B52"}, wire.Xcode{Version: "27.2", Build: "27B60"} |
| + other := mac.NewTurns(filepath.Join(dir, "lock")) |
| + if !other.TryTake() { |
| + t.Fatal("turn") |
| + } |
| + h.warm(context.Background(), b52) |
| + other.Give() |
| + // Nor while an earlier attempt's cleanup is pending. |
| + _ = os.WriteFile(filepath.Join(dir, "lock.pending"), nil, 0600) |
| + h.warm(context.Background(), b52) |
| + _ = os.Remove(filepath.Join(dir, "lock.pending")) |
| + _ = os.WriteFile(fail, nil, 0600) |
| + h.warm(context.Background(), b52) |
| + _ = os.Remove(fail) |
| + for _, x := range []wire.Xcode{b52, b52, {}, b60, b60} { |
| + h.warm(context.Background(), x) |
| + } |
| + if raw, _ := os.ReadFile(log); string(raw) != strings.Repeat("-showsdks\n", 3) { |
| + t.Fatalf("warmed %q", raw) |
| + } |
| } |
| // A worker's attempt has its marker on record before it starts anything, |
| @@ -420,3 +471,47 @@ func TestMacTaintIsSticky(t *testing.T) { |
| t.Fatal("the instance's taint not taken") |
| } |
| } |
| + |
| +// Before a sandboxed attempt's T is cleaned, every simulator is shut |
| +// down (`simctl shutdown all`, bounded): a hung shutdown is cut off, |
| +// the cleanup still runs and the attempt keeps its result; simulator |
| +// processes left are logged by name. |
| +func TestMacQuietsSimulatorsBeforeCleaning(t *testing.T) { |
| + dir := t.TempDir() |
| + temp := filepath.Join(dir, "T") |
| + if err := os.Mkdir(temp, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + xcrun, ps, log := filepath.Join(dir, "xcrun"), filepath.Join(dir, "ps"), filepath.Join(dir, "log") |
| + // The shutdown notes that T still holds the attempt's file, then hangs. |
| + if err := os.WriteFile(xcrun, []byte("#!/bin/sh\n[ -e "+temp+"/new ] && echo \"$*\" >> "+log+"\nexec sleep 30\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(ps, []byte("#!/bin/sh\necho /usr/bin/zsh\necho /Library/Developer/launchd_sim\necho SimMetalHost\necho SimMetalHost\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + limit, wasPS := simShutdownLimit, macPS |
| + simShutdownLimit, macPS = 300*time.Millisecond, ps |
| + defer func() { simShutdownLimit, macPS = limit, wasPS }() |
| + var out strings.Builder |
| + h := &macHost{tools: mac.Tools{Xcrun: xcrun}, log: slog.New(slog.NewTextHandler(&out, nil))} |
| + tree := filepath.Join(dir, "tree") |
| + if err := os.Mkdir(tree, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, UserTemp: temp, QuietSimulators: h.quietSimulators, Grace: time.Second, Settle: 5 * time.Second, Lines: 50} |
| + start := time.Now() |
| + res := g.Run(context.Background(), "checks-sim-1", tree, []string{"/bin/sh", "-c", "touch " + temp + "/new"}, time.Minute, func(string) error { return nil }) |
| + if took := time.Since(start); took > 15*time.Second || res.Code != 0 || res.Reason != "" || !res.Terminated { |
| + t.Fatalf("after %s: %+v", took, res) |
| + } |
| + if raw, _ := os.ReadFile(log); string(raw) != "simctl shutdown all\n" { |
| + t.Fatalf("shutdown before the cleanup: %q", raw) |
| + } |
| + if _, err := os.Lstat(filepath.Join(temp, "new")); err == nil { |
| + t.Fatal("T not cleaned after a hung shutdown") |
| + } |
| + if !strings.Contains(out.String(), `names="SimMetalHost launchd_sim"`) { |
| + t.Fatalf("log %s", out.String()) |
| + } |
| +} |