Skip to content

Commit 8e398d9

Browse files
authored
fix(macos): prevent app-owned child processes surviving shutdown (#123538)
* fix(macos): reap app-owned child process groups macOS-owned SSH, Codex, and node-host descendants no longer survive terminal shutdown. Codex retains EOF-first graceful exit before bounded process-group termination and reaping. * fix(macos): correct managed cleanup wake binding * fix(macos): preserve Codex shutdown escalation Keep the app-owned EOF grace window while allowing abortive requests to interrupt it before process-group TERM and KILL.
1 parent d8a1ebb commit 8e398d9

9 files changed

Lines changed: 788 additions & 627 deletions
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
import Darwin
2+
import Foundation
3+
import Subprocess
4+
5+
final class ManagedProcess: @unchecked Sendable {
6+
private enum WakeReason: Sendable {
7+
case exited
8+
case terminate(gracefully: Bool)
9+
}
10+
11+
private struct StartFailure: LocalizedError, Sendable {
12+
let message: String
13+
var errorDescription: String? {
14+
self.message
15+
}
16+
}
17+
18+
private final class State: @unchecked Sendable {
19+
private let lock = NSLock()
20+
private var childHandles: [FileHandle]
21+
private var abortiveTerminationRequested = false
22+
private var finished = false
23+
private var status: TerminationStatus?
24+
25+
init(childHandles: [FileHandle]) {
26+
self.childHandles = childHandles
27+
}
28+
29+
var isRunning: Bool {
30+
self.lock.withLock { !self.finished }
31+
}
32+
33+
var terminationStatus: TerminationStatus? {
34+
self.lock.withLock { self.status }
35+
}
36+
37+
var shouldAbortGracefulTermination: Bool {
38+
self.lock.withLock { self.abortiveTerminationRequested }
39+
}
40+
41+
func requestAbortiveTermination() {
42+
self.lock.withLock { self.abortiveTerminationRequested = true }
43+
}
44+
45+
func closeChildHandles() {
46+
let handles = self.lock.withLock {
47+
defer { self.childHandles.removeAll() }
48+
return self.childHandles
49+
}
50+
handles.forEach { try? $0.close() }
51+
}
52+
53+
func finish(status: TerminationStatus?) {
54+
self.lock.withLock { (self.finished, self.status) = (true, status) }
55+
}
56+
57+
static func hasExited(_ processIdentifier: pid_t) -> Bool {
58+
var info = siginfo_t()
59+
return waitid(P_PID, id_t(processIdentifier), &info, WEXITED | WNOHANG | WNOWAIT) == 0 &&
60+
info.si_pid != 0
61+
}
62+
}
63+
64+
private let state: State
65+
private let startEvents: AsyncStream<Result<pid_t, StartFailure>>
66+
private let wakeContinuation: AsyncStream<WakeReason>.Continuation
67+
let completionTask: Task<TerminationStatus?, Never>
68+
69+
var isRunning: Bool {
70+
self.state.isRunning
71+
}
72+
73+
var terminationStatus: TerminationStatus? {
74+
self.state.terminationStatus
75+
}
76+
77+
private init(
78+
state: State,
79+
startEvents: AsyncStream<Result<pid_t, StartFailure>>,
80+
wakeContinuation: AsyncStream<WakeReason>.Continuation,
81+
completionTask: Task<TerminationStatus?, Never>)
82+
{
83+
self.state = state
84+
self.startEvents = startEvents
85+
self.wakeContinuation = wakeContinuation
86+
self.completionTask = completionTask
87+
}
88+
89+
static func launch(
90+
configuration: Subprocess.Configuration,
91+
input: some InputProtocol,
92+
output: some OutputProtocol,
93+
error: some ErrorOutputProtocol,
94+
closeAfterSpawn childHandles: [FileHandle] = [],
95+
closeStdinForGracefulShutdown stdinHandle: FileHandle? = nil,
96+
gracefulShutdownTimeout: Duration = .zero) -> ManagedProcess
97+
{
98+
var configuration = configuration
99+
configuration.platformOptions.createSession = true
100+
configuration.platformOptions.teardownSequence = [
101+
.send(signal: .terminate, toProcessGroup: true, allowedDurationToNextStep: .milliseconds(250)),
102+
]
103+
let state = State(childHandles: childHandles)
104+
let (startEvents, startContinuation) = AsyncStream.makeStream(of: Result<pid_t, StartFailure>.self)
105+
let (wakeEvents, wakeContinuation) = AsyncStream.makeStream(
106+
of: WakeReason.self,
107+
bufferingPolicy: .bufferingNewest(1))
108+
let task = Task.detached(priority: .userInitiated) { () -> TerminationStatus? in
109+
do {
110+
let result = try await Subprocess.run(
111+
configuration,
112+
input: input,
113+
output: output,
114+
error: error)
115+
{ execution in
116+
let pid = pid_t(execution.processIdentifier.value)
117+
state.closeChildHandles()
118+
startContinuation.yield(.success(pid))
119+
120+
let exitSource = DispatchSource.makeProcessSource(
121+
identifier: pid,
122+
eventMask: .exit,
123+
queue: .global(qos: .userInitiated))
124+
exitSource.setEventHandler { wakeContinuation.yield(.exited) }
125+
exitSource.resume()
126+
if State.hasExited(pid) { wakeContinuation.yield(.exited) }
127+
var wakeIterator = wakeEvents.makeAsyncIterator()
128+
let wakeReason = await wakeIterator.next() ?? .terminate(gracefully: true)
129+
exitSource.cancel()
130+
131+
func killGroup() async {
132+
try? execution.send(signal: .kill, toProcessGroup: true)
133+
try? await Task.sleep(for: .milliseconds(50))
134+
}
135+
136+
guard !State.hasExited(pid),
137+
case let .terminate(gracefully: graceful) = wakeReason
138+
else {
139+
// The unreaped leader pins the group identity while descendants are killed.
140+
await killGroup()
141+
return
142+
}
143+
if graceful, let stdinHandle {
144+
try? stdinHandle.close()
145+
if await self.waitForExit(
146+
pid,
147+
timeout: gracefulShutdownTimeout,
148+
interruptWhenAbortive: state)
149+
{
150+
await killGroup()
151+
return
152+
}
153+
}
154+
try? await Task.sleep(for: .milliseconds(10))
155+
try? execution.send(signal: .terminate, toProcessGroup: true)
156+
_ = await self.waitForExit(pid, timeout: .milliseconds(250))
157+
await killGroup()
158+
}
159+
state.finish(status: result.terminationStatus)
160+
return result.terminationStatus
161+
} catch {
162+
state.closeChildHandles()
163+
let message = (error as? SubprocessError)?.description ?? error.localizedDescription
164+
startContinuation.yield(.failure(StartFailure(message: message)))
165+
state.finish(status: nil)
166+
return nil
167+
}
168+
}
169+
return ManagedProcess(
170+
state: state,
171+
startEvents: startEvents,
172+
wakeContinuation: wakeContinuation,
173+
completionTask: task)
174+
}
175+
176+
static func launch(
177+
configuration: Subprocess.Configuration,
178+
stdin: FileHandle,
179+
stdout: FileHandle,
180+
stderr: FileHandle,
181+
closeStdinForGracefulShutdown stdinWriter: FileHandle? = nil,
182+
gracefulShutdownTimeout: Duration = .zero) -> ManagedProcess
183+
{
184+
self.launch(
185+
configuration: configuration,
186+
input: .fileDescriptor(.init(rawValue: stdin.fileDescriptor), closeAfterSpawningProcess: false),
187+
output: .fileDescriptor(.init(rawValue: stdout.fileDescriptor), closeAfterSpawningProcess: false),
188+
error: .fileDescriptor(.init(rawValue: stderr.fileDescriptor), closeAfterSpawningProcess: false),
189+
closeAfterSpawn: [stdin, stdout, stderr],
190+
closeStdinForGracefulShutdown: stdinWriter,
191+
gracefulShutdownTimeout: gracefulShutdownTimeout)
192+
}
193+
194+
static func environment(from values: [String: String]) -> Environment {
195+
.custom(values.reduce(into: [:]) { result, element in
196+
if let key = Environment.Key(rawValue: element.key) { result[key] = element.value }
197+
})
198+
}
199+
200+
func waitUntilStarted() async throws -> pid_t {
201+
var iterator = self.startEvents.makeAsyncIterator()
202+
return try await iterator.next()!.get()
203+
}
204+
205+
func requestTermination(gracefully: Bool = true) {
206+
if !gracefully {
207+
self.state.requestAbortiveTermination()
208+
}
209+
self.wakeContinuation.yield(.terminate(gracefully: gracefully))
210+
}
211+
212+
func wait() async {
213+
_ = await self.completionTask.value
214+
}
215+
216+
func terminate(gracefully: Bool = true) async {
217+
self.requestTermination(gracefully: gracefully)
218+
await self.wait()
219+
}
220+
221+
deinit {
222+
self.requestTermination()
223+
}
224+
225+
private static func waitForExit(
226+
_ processIdentifier: pid_t,
227+
timeout: Duration,
228+
interruptWhenAbortive state: State? = nil) async -> Bool
229+
{
230+
let deadline = ContinuousClock.now.advanced(by: timeout)
231+
while ContinuousClock.now < deadline {
232+
if State.hasExited(processIdentifier) { return true }
233+
if state?.shouldAbortGracefulTermination == true { return false }
234+
do {
235+
try await Task.sleep(for: .milliseconds(10))
236+
} catch {
237+
return false
238+
}
239+
}
240+
return State.hasExited(processIdentifier)
241+
}
242+
}

0 commit comments

Comments
 (0)