Skip to content

Commit 651c1ec

Browse files
authored
fix(macos): isolate native test process resources (#132251)
* fix(macos): isolate native test process resources * test(macos): include native launcher in workflow routing contract * fix(scripts): finalize strict child ownership before output closure * test(macos): isolate signing failure resources * test(ci): own checkout fixture processes and retained artifacts * ci(macos): capture bounded native test diagnostics * fix(macos): provision disposable native test keychains Complete the pre-bundle resource owner with an unlocked private Keychain and verified cleanup. Cover setup, shutdown, output drainage, migration, and failure retention without changing production preview behavior. Remove temporary native diagnostics before exact-head CI proof. * test(macos): honor Foundation path contracts Normalize both home-path operands with Foundation and verify inherited TMPDIR separately from Darwin's per-user temporary directory. Preserve actual fixture containment, cleanup, and Keychain acceptance; correct the matching docs and socket-fixture guidance. * test: preserve fixture cleanup failures Join the existing child-close promise within the cleanup budget, retain body and teardown errors through the shared fixture owner, and keep independent test-case dimensions explicit. Resolve fixture lint without weakening assertions or process cleanup.
1 parent c203fc3 commit 651c1ec

22 files changed

Lines changed: 2013 additions & 481 deletions

‎.github/workflows/ci.yml‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3938,6 +3938,14 @@ jobs:
39383938
steps:
39393939
- *platform_checkout_step
39403940

3941+
- name: Setup Node.js for native test tooling
3942+
env:
3943+
REQUESTED_NODE_VERSION: ${{ env.NODE_VERSION }}
3944+
run: |
3945+
set -euo pipefail
3946+
source .ci-harness/.github/actions/setup-pnpm-store-cache/ensure-node.sh
3947+
openclaw_ensure_node "$REQUESTED_NODE_VERSION"
3948+
39413949
- name: Install XcodeGen / SwiftLint / SwiftFormat
39423950
run: |
39433951
if [[ -x ./scripts/install-xcodegen.sh && -x ./scripts/install-swift-tools.sh ]]; then
@@ -4137,7 +4145,17 @@ jobs:
41374145
else
41384146
swift_test_args+=(--no-parallel)
41394147
fi
4140-
swift test "${swift_test_args[@]}"
4148+
if [[ -f scripts/test-macos-native.mts ]]; then
4149+
node scripts/test-macos-native.mts default "${swift_test_args[@]}" --skip AppStateIsolationTests
4150+
node scripts/test-macos-native.mts named "${swift_test_args[@]}" --filter AppStateIsolationTests
4151+
elif [[ "$HISTORICAL_TARGET" == "true" ]]; then
4152+
# Frozen release targets predate the resource-owner script and its tests.
4153+
# Their original suite still runs only on this disposable macOS worker.
4154+
swift test "${swift_test_args[@]}"
4155+
else
4156+
echo "Current CI targets must provide scripts/test-macos-native.mts." >&2
4157+
exit 1
4158+
fi
41414159
41424160
- name: Render isolated macOS health fixtures
41434161
id: health-render

‎apps/macos/README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,24 @@ preferences and Keychain use system services, and AppKit/WebKit tests can open
6262
windows and helper processes. Local subsets need a verified OS sandbox as well
6363
as test-owned resources. See [native test safety](https://docs.openclaw.ai/platforms/mac/dev-setup#run-native-tests-safely).
6464

65+
The `macos-swift` CI job builds tests once, then runs them through
66+
`scripts/test-macos-native.mts`. The full suite retains default-profile behavior;
67+
named-profile AppState isolation tests run separately. Each process gets private
68+
home, config/state paths, and a short `TMPDIR` for tools that honor it before the
69+
test bundle loads. Foundation uses Darwin's per-user temp directory instead;
70+
`TestIsolation` fixtures own and clean unique directories there, and the
71+
disposable OS worker owns and discards the surrounding directory. The launcher
72+
also creates an unlocked, disposable Keychain in that home
73+
and selects it as the user-domain default and search list, so catalog migration
74+
can save without prompting to create a login Keychain. It disables automatic
75+
locking only for that test resource and deletes it after the test process group
76+
and output pipes close. Failed or unverified cleanup retains resources and fails
77+
the launch.
78+
The disposable runner owns default preferences and system-service state; a named
79+
profile gets a fresh preferences domain. The launcher itself is not a sandbox.
80+
Local `scripts/prepush-ci.sh` keeps Swift lint/build checks but reports native
81+
test proof as incomplete and requires the exact commit's `macos-swift` CI result.
82+
6583
## Packaging flows
6684

6785
Development bundle (signed but not notarized):
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import Foundation
2+
import Security
3+
import Testing
4+
@testable import OpenClaw
5+
6+
@MainActor
7+
struct AppStateIsolationTests {
8+
@Test
9+
func `preview constructor uses launch namespace and owned config`() async throws {
10+
// Fail before touching defaults when the bundle was launched without its resource owner.
11+
let profile = try #require(AppProfile.current.name)
12+
try #require(profile.hasPrefix("test-"))
13+
let suiteName = try #require(AppProfile.current.defaultsSuiteName)
14+
let fm = FileManager()
15+
let home = try #require(OpenClawEnv.path("HOME"))
16+
// Check the platform's actual default before any fixture or catalog writes.
17+
// A profile name alone cannot keep Security away from an operator's Keychain.
18+
var defaultKeychain: SecKeychain?
19+
try #require(SecKeychainCopyDefault(&defaultKeychain) == errSecSuccess)
20+
let keychain = try #require(defaultKeychain)
21+
var pathBytes = [CChar](repeating: 0, count: 4096)
22+
var pathLength = UInt32(pathBytes.count)
23+
try #require(SecKeychainGetPath(keychain, &pathLength, &pathBytes) == errSecSuccess)
24+
let keychainPath = try #require(String(
25+
bytes: pathBytes.prefix(Int(pathLength)).map { UInt8(bitPattern: $0) },
26+
encoding: .utf8))
27+
let keychainURL = URL(fileURLWithPath: keychainPath).resolvingSymlinksInPath()
28+
try #require(keychainURL.deletingLastPathComponent().path ==
29+
URL(fileURLWithPath: home).appendingPathComponent("Library/Keychains").resolvingSymlinksInPath().path)
30+
let fixture = fm.temporaryDirectory.appendingPathComponent("app-state-\(UUID().uuidString)")
31+
try fm.createDirectory(at: fixture, withIntermediateDirectories: true)
32+
defer { try? fm.removeItem(at: fixture) }
33+
let configURL = fixture.appendingPathComponent("openclaw.json")
34+
let seededKeys = [
35+
iconAnimationsEnabledKey,
36+
showDockIconKey,
37+
talkPhaseSoundsEnabledKey,
38+
talkShiftToStopEnabledKey,
39+
heartbeatsEnabledKey,
40+
iconOverrideKey,
41+
]
42+
var defaults = Dictionary(uniqueKeysWithValues: seededKeys.map { ($0, nil as Any?) })
43+
defaults[swabbleEnabledKey] = false
44+
defaults[talkEnabledKey] = false
45+
defaults[talkRealtimeRelayEnabledKey] = true
46+
47+
let launchState = try await TestIsolation.withEnvValues([:]) {
48+
let home = try #require(OpenClawEnv.path("HOME"))
49+
#expect(OpenClawEnv.path("CFFIXED_USER_HOME") == home)
50+
let root = URL(fileURLWithPath: home).deletingLastPathComponent()
51+
#expect(fm.homeDirectoryForCurrentUser.resolvingSymlinksInPath().path ==
52+
URL(fileURLWithPath: home).resolvingSymlinksInPath().path)
53+
// Foundation uses Darwin's per-user temp directory independently of TMPDIR.
54+
// Fixtures there remain test-owned on the disposable worker.
55+
let tmp = try #require(OpenClawEnv.path("TMPDIR"))
56+
#expect(URL(fileURLWithPath: tmp).resolvingSymlinksInPath().path ==
57+
root.appendingPathComponent("tmp").resolvingSymlinksInPath().path)
58+
#expect(OpenClawPaths.stateDirURL == root.appendingPathComponent("state", isDirectory: true))
59+
#expect(OpenClawPaths.configURL == OpenClawPaths.stateDirURL.appendingPathComponent("openclaw.json"))
60+
return OpenClawPaths.stateDirURL
61+
}
62+
63+
let fixtureState = try await TestIsolation.withIsolatedState(
64+
env: ["OPENCLAW_CONFIG_PATH": configURL.path],
65+
defaults: defaults)
66+
{
67+
let preferences = try #require(UserDefaults(suiteName: suiteName))
68+
// Other tests may already have constructed AppState. Remove only these keys
69+
// under the cooperative lock instead of assuming this test runs first.
70+
for key in seededKeys {
71+
#expect(preferences.object(forKey: key) == nil)
72+
}
73+
#expect(!fm.fileExists(atPath: configURL.path))
74+
let absent = AppState(preview: true)
75+
#expect(absent.iconAnimationsEnabled)
76+
#expect(absent.showDockIcon)
77+
#expect(absent.talkPhaseSoundsEnabled)
78+
#expect(absent.talkShiftToStopEnabled)
79+
#expect(absent.heartbeatsEnabled)
80+
#expect(absent.iconOverride == .system)
81+
#expect(absent.talkRealtimeRelayEnabled)
82+
for key in seededKeys.dropLast() {
83+
#expect(preferences.object(forKey: key) as? Bool == true)
84+
}
85+
#expect(preferences.string(forKey: iconOverrideKey) == IconOverrideSelection.system.rawValue)
86+
#expect(!fm.fileExists(atPath: configURL.path))
87+
88+
let stateDirectory = OpenClawPaths.stateDirURL
89+
#expect(stateDirectory != launchState)
90+
#expect(stateDirectory.path.hasPrefix(fm.temporaryDirectory.path))
91+
#expect(OpenClawConfigFile.saveDict([
92+
"gateway": [
93+
"mode": "remote",
94+
"remote": [
95+
"transport": "direct",
96+
"url": "wss://fixture.example.invalid:9443",
97+
],
98+
],
99+
]))
100+
preferences.set(false, forKey: showDockIconKey)
101+
let configured = AppState(preview: true)
102+
#expect(!configured.showDockIcon)
103+
#expect(configured.connectionMode == .remote)
104+
#expect(configured.remoteTransport == .direct)
105+
#expect(configured.remoteUrl == "wss://fixture.example.invalid:9443")
106+
#expect(AppProfile.current.name == profile)
107+
108+
// Catalog reads commit legacy migration through SecItemAdd on a fresh Keychain.
109+
let catalog = try await MacGatewayProfileStore().catalogProfiles()
110+
#expect(catalog.count == 1)
111+
let migrated = try #require(catalog.first)
112+
#expect(migrated.profile.url.absoluteString == "wss://fixture.example.invalid:9443/")
113+
#expect(!migrated.canPromote)
114+
// A fresh store must read the committed registry, not the first actor's cache.
115+
#expect(try await MacGatewayProfileStore().catalogProfiles() == catalog)
116+
117+
// Preview still reads config; malformed input must keep its snapshot and audit in owned paths.
118+
try Data("{ invalid fixture".utf8).write(to: configURL)
119+
_ = AppState(preview: true)
120+
let auditURL = stateDirectory.appendingPathComponent("logs/config-audit.jsonl")
121+
let audit = try String(contentsOf: auditURL, encoding: .utf8)
122+
#expect(audit.contains("config.write"))
123+
#expect(audit.contains("config.observe"))
124+
#expect(try fm.contentsOfDirectory(atPath: fixture.path).contains {
125+
$0.hasPrefix("openclaw.json.clobbered.")
126+
})
127+
return stateDirectory
128+
}
129+
#expect(!fm.fileExists(atPath: fixtureState.path))
130+
await TestIsolation.withEnvValues([:]) {
131+
#expect(OpenClawPaths.stateDirURL == launchState)
132+
#expect(fm.fileExists(atPath: launchState.path))
133+
}
134+
}
135+
136+
@Test
137+
func `config fixture cleans audit after throwing body`() async throws {
138+
enum FixtureError: Error {
139+
case expected
140+
}
141+
let fm = FileManager()
142+
let configPath = TestIsolation.tempConfigPath()
143+
defer { try? fm.removeItem(atPath: configPath) }
144+
var fixtureState: URL?
145+
do {
146+
try await TestIsolation.withEnvValues(["OPENCLAW_CONFIG_PATH": configPath]) {
147+
fixtureState = OpenClawPaths.stateDirURL
148+
#expect(OpenClawConfigFile.saveDict(["gateway": ["mode": "local"]]))
149+
await Task.yield()
150+
#expect(fm.fileExists(atPath: OpenClawPaths.stateDirURL
151+
.appendingPathComponent("logs/config-audit.jsonl").path))
152+
throw FixtureError.expected
153+
}
154+
} catch FixtureError.expected {}
155+
let removed = try #require(fixtureState)
156+
#expect(!fm.fileExists(atPath: removed.path))
157+
}
158+
}

‎apps/macos/Tests/OpenClawIPCTests/ExecApprovalsSocketTestSupport.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ enum ExecApprovalsSocketTestSupport {
1212
guard longestSocketPath.utf8.count < MemoryLayout.size(ofValue: sockaddr_un().sun_path) else {
1313
throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENAMETOOLONG), userInfo: [
1414
NSLocalizedDescriptionKey:
15-
"Native socket fixtures need a shorter test-owned TMPDIR in the disposable runner.",
15+
"Native socket fixtures need a shorter per-user temporary directory in the disposable runner.",
1616
])
1717
}
1818
var bytes = Array(template.utf8CString)

‎apps/macos/Tests/OpenClawIPCTests/GatewayConnectionControlTests.swift‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,6 @@ private func assertConfigLookupCannotRecreateRoute(
10881088
defer { try? FileManager.default.removeItem(at: isolatedState) }
10891089

10901090
return try await TestIsolation.withEnvValues([
1091-
"OPENCLAW_PROFILE": "autoqa-185-tests",
10921091
"OPENCLAW_CONFIG_PATH": configURL.path,
10931092
"OPENCLAW_STATE_DIR": isolatedState.path,
10941093
]) {

‎apps/macos/Tests/OpenClawIPCTests/TestIsolation.swift‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,14 @@ enum TestIsolation {
3737
defaults: [String: Any?] = [:],
3838
_ body: () async throws -> T) async rethrows -> T
3939
{
40-
func restoreUserDefaults(_ values: [String: Any?], userDefaults: UserDefaults) {
40+
precondition(!env.keys.contains("OPENCLAW_PROFILE"), "Select the app profile before launching the test process")
41+
42+
func restoreUserDefaults(_ values: [String: Any?]) {
4143
for (key, value) in values {
4244
if let value {
43-
userDefaults.set(value, forKey: key)
45+
AppDefaults.standard.set(value, forKey: key)
4446
} else {
45-
userDefaults.removeObject(forKey: key)
47+
AppDefaults.standard.removeObject(forKey: key)
4648
}
4749
}
4850
}
@@ -58,35 +60,54 @@ enum TestIsolation {
5860
}
5961

6062
await TestIsolationLock.shared.acquire()
63+
var env = env
64+
// Config reads and writes also persist health/audit state. A config-only
65+
// fixture must not send those writes to the process-wide state directory.
66+
let ownedStateDirectory: URL? = if let configPath = env["OPENCLAW_CONFIG_PATH"] ?? nil,
67+
!configPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
68+
!env.keys.contains("OPENCLAW_STATE_DIR")
69+
{
70+
FileManager().temporaryDirectory
71+
.appendingPathComponent("openclaw-config-state-\(UUID().uuidString)", isDirectory: true)
72+
} else {
73+
nil
74+
}
75+
if let ownedStateDirectory {
76+
env["OPENCLAW_STATE_DIR"] = ownedStateDirectory.path
77+
}
78+
defer {
79+
if let ownedStateDirectory {
80+
try? FileManager().removeItem(at: ownedStateDirectory)
81+
}
82+
}
6183
var previousEnv: [String: String?] = [:]
6284
for (key, value) in env {
63-
previousEnv[key] = getenv(key).map { String(cString: $0) }
85+
previousEnv.updateValue(getenv(key).map { String(cString: $0) }, forKey: key)
6486
if let value {
6587
setenv(key, value, 1)
6688
} else {
6789
unsetenv(key)
6890
}
6991
}
7092

71-
let userDefaults = AppDefaults.standard
7293
var previousDefaults: [String: Any?] = [:]
7394
for (key, value) in defaults {
74-
previousDefaults[key] = userDefaults.object(forKey: key)
95+
previousDefaults.updateValue(AppDefaults.standard.object(forKey: key), forKey: key)
7596
if let value {
76-
userDefaults.set(value, forKey: key)
97+
AppDefaults.standard.set(value, forKey: key)
7798
} else {
78-
userDefaults.removeObject(forKey: key)
99+
AppDefaults.standard.removeObject(forKey: key)
79100
}
80101
}
81102

82103
do {
83104
let result = try await body()
84-
restoreUserDefaults(previousDefaults, userDefaults: userDefaults)
105+
restoreUserDefaults(previousDefaults)
85106
restoreEnv(previousEnv)
86107
await TestIsolationLock.shared.release()
87108
return result
88109
} catch {
89-
restoreUserDefaults(previousDefaults, userDefaults: userDefaults)
110+
restoreUserDefaults(previousDefaults)
90111
restoreEnv(previousEnv)
91112
await TestIsolationLock.shared.release()
92113
throw error

‎docs/ci.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ Runner choice follows contributor trust, not whether a pull request came from a
349349

350350
### Runner backend modes
351351

352-
The `macos-swift` lane runs Swift tests once per job. Automatic first attempts use parallel execution; manual dispatches and rerun attempts use serial execution. A failing test fails the job without an in-job retry.
352+
The `macos-swift` lane builds Swift tests once and runs each test once per job. The ordinary suite retains default-profile behavior; AppState isolation tests run in a separate named-profile process through the same resource-owning launcher. Each launch owns a private home and disposable, unlocked default Keychain until the test process group and output pipes close. HOME and profile markers do not isolate macOS services; both partitions run only on the disposable credentialless macOS worker. Automatic first attempts use parallel execution; manual dispatches and rerun attempts use serial execution. A failing test fails the job without an in-job retry. See [native test safety](/platforms/mac/dev-setup#run-native-tests-safely).
353353

354354
The repository variable `OPENCLAW_CI_RUNNER_BACKEND` controls the runner backend for `ci.yml`:
355355

0 commit comments

Comments
 (0)