Skip to content

Commit b0a0916

Browse files
authored
fix(macos): prevent app stalls from stuck subprocess probes (#115938)
* refactor(macos): pin subprocess groups through cleanup * refactor(macos): keep bounded process probes async * test(macos): cover async process probe limits * fix(macos): preserve local gateway version fallback * test(macos): cover gateway version probe fallback * fix(macos): handle subprocesses that exit before monitoring * test(macos): stress instant bounded process exits * fix(macos): close bounded process exit registration race * fix(macos): preserve bounded probe output ordering * fix(macos): propagate bounded process cancellation * fix(macos): recover missed subprocess exit events * chore(macos): refresh native i18n inventory * fix(macos): reject invalid process argument bytes
1 parent 25d3c39 commit b0a0916

19 files changed

Lines changed: 622 additions & 173 deletions

‎apps/.i18n/native-source.json‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30291,47 +30291,47 @@
3029130291
},
3029230292
{
3029330293
"kind": "ui-localized-call",
30294-
"line": 421,
30294+
"line": 419,
3029530295
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3029630296
"source": "Repairing the OpenClaw Gateway update…",
3029730297
"surface": "apple",
3029830298
"id": "native.apple.86e7c86924ad0c70"
3029930299
},
3030030300
{
3030130301
"kind": "ui-localized-call",
30302-
"line": 422,
30302+
"line": 420,
3030330303
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3030430304
"source": "Updating the OpenClaw Gateway to \\(targetVersion)…",
3030530305
"surface": "apple",
3030630306
"id": "native.apple.b59713e1e3e7ee65"
3030730307
},
3030830308
{
3030930309
"kind": "ui-localized-call",
30310-
"line": 443,
30310+
"line": 441,
3031130311
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3031230312
"source": "Gateway update needs attention.",
3031330313
"surface": "apple",
3031430314
"id": "native.apple.7772913c171b78ac"
3031530315
},
3031630316
{
3031730317
"kind": "ui-localized-call",
30318-
"line": 445,
30318+
"line": 443,
3031930319
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3032030320
"source": "Gateway update failed.",
3032130321
"surface": "apple",
3032230322
"id": "native.apple.e831aa3b0ced39d4"
3032330323
},
3032430324
{
3032530325
"kind": "ui-localized-call",
30326-
"line": 460,
30326+
"line": 458,
3032730327
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3032830328
"source": "Gateway update finished, but verification failed.",
3032930329
"surface": "apple",
3033030330
"id": "native.apple.681e41736dc87c67"
3033130331
},
3033230332
{
3033330333
"kind": "ui-localized-call",
30334-
"line": 467,
30334+
"line": 465,
3033530335
"path": "apps/macos/Sources/OpenClaw/CLIInstaller.swift",
3033630336
"source": "OpenClaw Gateway \\(installedVersion) is installed.",
3033730337
"surface": "apple",
@@ -32795,15 +32795,15 @@
3279532795
},
3279632796
{
3279732797
"kind": "conditional-branch",
32798-
"line": 194,
32798+
"line": 195,
3279932799
"path": "apps/macos/Sources/OpenClaw/GatewayEnvironment.swift",
3280032800
"source": " (local: \\(projectEntrypoint ?? \"unknown\"))",
3280132801
"surface": "apple",
3280232802
"id": "native.apple.110f6e64e25dcd2e"
3280332803
},
3280432804
{
3280532805
"kind": "conditional-branch",
32806-
"line": 198,
32806+
"line": 199,
3280732807
"path": "apps/macos/Sources/OpenClaw/GatewayEnvironment.swift",
3280832808
"source": "(\\(gatewayLabel))",
3280932809
"surface": "apple",
@@ -32835,15 +32835,15 @@
3283532835
},
3283632836
{
3283732837
"kind": "conditional-branch",
32838-
"line": 571,
32838+
"line": 569,
3283932839
"path": "apps/macos/Sources/OpenClaw/GatewayProcessManager.swift",
3284032840
"source": "not linked",
3284132841
"surface": "apple",
3284232842
"id": "native.apple.151e5b5ab7d08a2a"
3284332843
},
3284432844
{
3284532845
"kind": "conditional-branch",
32846-
"line": 584,
32846+
"line": 582,
3284732847
"path": "apps/macos/Sources/OpenClaw/GatewayProcessManager.swift",
3284832848
"source": "unknown error",
3284932849
"surface": "apple",
@@ -33795,15 +33795,15 @@
3379533795
},
3379633796
{
3379733797
"kind": "ui-call",
33798-
"line": 832,
33798+
"line": 830,
3379933799
"path": "apps/macos/Sources/OpenClaw/GeneralSettings.swift",
3380033800
"source": "Retry now",
3380133801
"surface": "apple",
3380233802
"id": "native.apple.7a4bfb585fed2598"
3380333803
},
3380433804
{
3380533805
"kind": "ui-call",
33806-
"line": 837,
33806+
"line": 835,
3380733807
"path": "apps/macos/Sources/OpenClaw/GeneralSettings.swift",
3380833808
"source": "Open logs",
3380933809
"surface": "apple",
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
import Darwin
2+
import Dispatch
3+
import Foundation
4+
import Subprocess
5+
6+
enum BoundedProcessError: Error {
7+
case timedOut
8+
}
9+
10+
struct BoundedProcessResult: Sendable {
11+
var output: Data
12+
var terminationStatus: Int32
13+
}
14+
15+
enum BoundedProcess {
16+
private static let outputLimit = 64 * 1024
17+
18+
private enum DeadlineOutcome: Sendable {
19+
case exited
20+
case timedOut
21+
}
22+
23+
private final class ProcessExitSignal: @unchecked Sendable {
24+
private let lock = NSLock()
25+
private let processIdentifier: pid_t
26+
private let source: DispatchSourceProcess?
27+
private var continuation: CheckedContinuation<Void, Never>?
28+
private var finished = false
29+
30+
init(processIdentifier: pid_t) {
31+
self.processIdentifier = processIdentifier
32+
if Self.hasExited(processIdentifier) {
33+
self.source = nil
34+
self.finished = true
35+
return
36+
}
37+
let source = DispatchSource.makeProcessSource(
38+
identifier: processIdentifier,
39+
eventMask: .exit,
40+
queue: .global(qos: .utility))
41+
self.source = source
42+
source.setEventHandler { [weak self] in
43+
self?.finish()
44+
}
45+
source.resume()
46+
// The child can exit between the initial waitid probe and kqueue
47+
// registration. Recheck after resume so that race cannot consume
48+
// the full timeout when no NOTE_EXIT event is delivered.
49+
if Self.hasExited(processIdentifier) {
50+
self.finish()
51+
}
52+
}
53+
54+
func wait() async {
55+
await withTaskCancellationHandler {
56+
await withCheckedContinuation { continuation in
57+
self.lock.lock()
58+
guard !self.finished else {
59+
self.lock.unlock()
60+
continuation.resume()
61+
return
62+
}
63+
self.continuation = continuation
64+
self.lock.unlock()
65+
}
66+
} onCancel: {
67+
self.finish()
68+
}
69+
}
70+
71+
func pollUntilExit() async {
72+
while !Task.isCancelled {
73+
do {
74+
try await Task.sleep(for: .milliseconds(50))
75+
} catch {
76+
return
77+
}
78+
if Self.hasExited(self.processIdentifier) {
79+
self.finish()
80+
return
81+
}
82+
}
83+
}
84+
85+
func hasExited() -> Bool {
86+
Self.hasExited(self.processIdentifier)
87+
}
88+
89+
private func finish() {
90+
self.lock.lock()
91+
guard !self.finished else {
92+
self.lock.unlock()
93+
return
94+
}
95+
self.finished = true
96+
let continuation = self.continuation
97+
self.continuation = nil
98+
self.lock.unlock()
99+
self.source?.cancel()
100+
continuation?.resume()
101+
}
102+
103+
private static func hasExited(_ processIdentifier: pid_t) -> Bool {
104+
while true {
105+
var info = siginfo_t()
106+
if waitid(P_PID, id_t(processIdentifier), &info, WEXITED | WNOHANG | WNOWAIT) == 0 {
107+
return info.si_pid != 0 || info.si_signo != 0
108+
}
109+
guard errno == EINTR else { return false }
110+
}
111+
}
112+
}
113+
114+
static func run(
115+
path: String,
116+
arguments: [String],
117+
environment: [String: String]? = nil,
118+
workingDirectory: String? = nil,
119+
timeout: TimeInterval) async throws -> BoundedProcessResult
120+
{
121+
precondition(timeout > 0)
122+
var platformOptions = PlatformOptions()
123+
platformOptions.qualityOfService = .utility
124+
platformOptions.createSession = true
125+
platformOptions.teardownSequence = [
126+
.send(
127+
signal: .kill,
128+
toProcessGroup: true,
129+
allowedDurationToNextStep: .zero),
130+
]
131+
let configuration = Configuration(
132+
.path(.init(path)),
133+
arguments: Arguments(arguments),
134+
environment: environment.map(self.environment(from:)) ?? .inherit,
135+
workingDirectory: workingDirectory.map { .init($0) },
136+
platformOptions: platformOptions)
137+
let executionResult = try await Subprocess.run(
138+
configuration,
139+
input: .none,
140+
output: .bytes(limit: self.outputLimit),
141+
error: .combinedWithOutput)
142+
{ execution in
143+
let exitSignal = ProcessExitSignal(
144+
processIdentifier: pid_t(execution.processIdentifier.value))
145+
let deadline = await withTaskGroup(of: DeadlineOutcome.self) { group in
146+
group.addTask {
147+
await exitSignal.wait()
148+
return .exited
149+
}
150+
// Keep normal exits event-driven, but recover promptly if
151+
// kqueue misses NOTE_EXIT under heavy concurrent spawning.
152+
group.addTask {
153+
await exitSignal.pollUntilExit()
154+
return .exited
155+
}
156+
group.addTask {
157+
do {
158+
try await Task.sleep(for: .seconds(timeout))
159+
return .timedOut
160+
} catch {
161+
return .exited
162+
}
163+
}
164+
defer { group.cancelAll() }
165+
return await group.next() ?? .exited
166+
}
167+
try Task.checkCancellation()
168+
169+
switch deadline {
170+
case .exited:
171+
// The body runs before swift-subprocess reaps the group leader.
172+
// Kill inherited descendants while the pid cannot be recycled.
173+
try? execution.send(signal: .kill, toProcessGroup: true)
174+
return false
175+
case .timedOut:
176+
if exitSignal.hasExited() {
177+
try? execution.send(signal: .kill, toProcessGroup: true)
178+
return false
179+
}
180+
try? execution.send(signal: .terminate, toProcessGroup: true)
181+
try? await Task.sleep(for: .milliseconds(100))
182+
try? execution.send(signal: .kill, toProcessGroup: true)
183+
return true
184+
}
185+
}
186+
187+
if executionResult.closureOutput {
188+
throw BoundedProcessError.timedOut
189+
}
190+
let data = Data(executionResult.standardOutput)
191+
let terminationStatus = switch executionResult.terminationStatus {
192+
case let .exited(code), let .signaled(code):
193+
Int32(code)
194+
}
195+
return BoundedProcessResult(output: data, terminationStatus: terminationStatus)
196+
}
197+
198+
private static func environment(from values: [String: String]) -> Environment {
199+
var converted: [Environment.Key: String] = [:]
200+
converted.reserveCapacity(values.count)
201+
for (key, value) in values {
202+
guard let environmentKey = Environment.Key(rawValue: key) else { continue }
203+
converted[environmentKey] = value
204+
}
205+
return .custom(converted)
206+
}
207+
}

‎apps/macos/Sources/OpenClaw/CLIInstaller.swift‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -264,12 +264,10 @@ enum CLIInstaller {
264264

265265
private static func runtimeIsCompatible(environment: [String: String]) async -> Bool {
266266
let paths = environment["PATH"]?.split(separator: ":").map(String.init) ?? []
267-
return await Task.detached(priority: .utility) {
268-
if case .success = RuntimeLocator.resolve(searchPaths: paths) {
269-
return true
270-
}
271-
return false
272-
}.value
267+
if case .success = await RuntimeLocator.resolve(searchPaths: paths) {
268+
return true
269+
}
270+
return false
273271
}
274272

275273
static func classifyVersion(

‎apps/macos/Sources/OpenClaw/CommandResolver.swift‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ enum CommandResolver {
1414
return nil
1515
}
1616

17-
static func runtimeResolution(searchPaths: [String]?) -> Result<RuntimeResolution, RuntimeResolutionError> {
18-
RuntimeLocator.resolve(searchPaths: searchPaths ?? self.preferredPaths())
17+
static func runtimeResolution(searchPaths: [String]?) async -> Result<RuntimeResolution, RuntimeResolutionError> {
18+
await RuntimeLocator.resolve(searchPaths: searchPaths ?? self.preferredPaths())
1919
}
2020

2121
static func makeRuntimeCommand(
@@ -260,7 +260,7 @@ enum CommandResolver {
260260
defaults: UserDefaults = .standard,
261261
configRoot: [String: Any]? = nil,
262262
searchPaths: [String]? = nil,
263-
projectRoot: URL? = nil) -> [String]
263+
projectRoot: URL? = nil) async -> [String]
264264
{
265265
let settings = self.connectionSettings(defaults: defaults, configRoot: configRoot)
266266
if settings.mode == .remote, settings.transport == .ssh {
@@ -282,7 +282,7 @@ enum CommandResolver {
282282
return [openclawPath, subcommand] + extraArgs
283283
}
284284

285-
let runtimeResult = self.runtimeResolution(searchPaths: searchPaths)
285+
let runtimeResult = await self.runtimeResolution(searchPaths: searchPaths)
286286
switch runtimeResult {
287287
case let .success(runtime):
288288
if let entry = gatewayEntrypoint(in: root) {
@@ -318,9 +318,9 @@ enum CommandResolver {
318318
defaults: UserDefaults = .standard,
319319
configRoot: [String: Any]? = nil,
320320
searchPaths: [String]? = nil,
321-
projectRoot: URL? = nil) -> [String]
321+
projectRoot: URL? = nil) async -> [String]
322322
{
323-
self.openclawNodeCommand(
323+
await self.openclawNodeCommand(
324324
subcommand: subcommand,
325325
extraArgs: extraArgs,
326326
defaults: defaults,

0 commit comments

Comments
 (0)