@@ -59,6 +59,59 @@ enum ApplicationRelocator {
5959 case relaunch
6060 }
6161
62+ enum ReplacementHandoffFailureAction : Equatable , Sendable {
63+ case retry ( after : Duration )
64+ case stopMonitoring
65+ case terminateForSupervisor
66+
67+ var isTerminal : Bool {
68+ switch self {
69+ case . retry :
70+ false
71+ case . stopMonitoring , . terminateForSupervisor :
72+ true
73+ }
74+ }
75+ }
76+
77+ struct ReplacementHandoffPolicy : Equatable , Sendable {
78+ let maximumAttempts : Int
79+ let initialBackoffSeconds : Int
80+ let maximumBackoffSeconds : Int
81+ let baseTimeoutMilliseconds : Int32
82+ let maximumTimeoutMilliseconds : Int32
83+
84+ func failureAction (
85+ failedAttempt : Int ,
86+ hasKeepAliveSupervisor : Bool ) -> ReplacementHandoffFailureAction
87+ {
88+ guard failedAttempt < self . maximumAttempts else {
89+ return hasKeepAliveSupervisor ? . terminateForSupervisor : . stopMonitoring
90+ }
91+ let exponent = max ( 0 , failedAttempt - 1 )
92+ let backoff = min (
93+ self . maximumBackoffSeconds ,
94+ self . initialBackoffSeconds * ( 1 << exponent ) )
95+ return . retry ( after : . seconds ( backoff ) )
96+ }
97+
98+ func timeoutMilliseconds (
99+ loadAverage : Double ? ,
100+ activeProcessorCount : Int ) -> Int32
101+ {
102+ guard let loadAverage ,
103+ loadAverage . isFinite ,
104+ loadAverage > 0 ,
105+ activeProcessorCount > 0
106+ else { return self . baseTimeoutMilliseconds }
107+ let loadPerProcessor = loadAverage / Double ( activeProcessorCount )
108+ let multiplier = min ( 4 , max ( 1 , loadPerProcessor ) )
109+ let scaled = Double ( self . baseTimeoutMilliseconds ) * multiplier
110+ let rounded = ceil ( scaled / 5000 ) * 5000
111+ return min ( self . maximumTimeoutMilliseconds , Int32 ( rounded ) )
112+ }
113+ }
114+
62115 enum RelaunchStrategy : Equatable , Sendable {
63116 case openAfterTermination
64117 case externalSupervisor
@@ -99,15 +152,28 @@ enum ApplicationRelocator {
99152 let launchCodeDirectoryHash : Data ?
100153 }
101154
155+ private enum ReplacementScheduleResult {
156+ case scheduled
157+ case failed ( supervisor : KeepAliveSupervisor ? )
158+ }
159+
102160 private static let logger = Logger ( subsystem : " ai.openclaw " , category : " app-relocation " )
103161 private static var bundleReplacementSnapshot : BundleReplacementSnapshot ?
104162 private static var bundleReplacementSource : DispatchSourceFileSystemObject ?
105163 private static var bundleReplacementRecoveryTask : Task < Void , Never > ?
106164 private static var bundleReplacementCheckPending = false
107165 private static var bundleReplacementHandoffInProgress = false
166+ private static var bundleReplacementHandoffAttempt = 0
167+ private static var bundleReplacementHandoffTargetHash : Data ?
108168 private static var inheritedReplacementSupervisor : KeepAliveSupervisor ?
109169 private static var supervisorRestorationWatcher : Process ?
110170 private static var authenticatedReplacementSourceBundleURL : URL ?
171+ nonisolated static let replacementHandoffPolicy = ReplacementHandoffPolicy (
172+ maximumAttempts : 3 ,
173+ initialBackoffSeconds : 2 ,
174+ maximumBackoffSeconds : 8 ,
175+ baseTimeoutMilliseconds : 15000 ,
176+ maximumTimeoutMilliseconds : 60000 )
111177 private nonisolated static let replacementSourceBundleEnvironmentKey = " OPENCLAW_REPLACEMENT_SOURCE_BUNDLE "
112178 private nonisolated static let replacementParentPIDEnvironmentKey = " OPENCLAW_REPLACEMENT_PARENT_PID "
113179 private nonisolated static let replacementCodeHashEnvironmentKey = " OPENCLAW_REPLACEMENT_CODE_HASH "
@@ -543,6 +609,8 @@ extension ApplicationRelocator {
543609 self . bundleReplacementSnapshot = nil
544610 self . bundleReplacementCheckPending = false
545611 self . bundleReplacementHandoffInProgress = false
612+ self . bundleReplacementHandoffAttempt = 0
613+ self . bundleReplacementHandoffTargetHash = nil
546614
547615 let bundleURL = monitoredBundleURL . standardizedFileURL
548616 guard bundleURL . pathExtension == " app " ,
@@ -614,6 +682,8 @@ extension ApplicationRelocator {
614682 } . value
615683 switch evaluation . action {
616684 case . unchanged :
685+ self . bundleReplacementHandoffAttempt = 0
686+ self . bundleReplacementHandoffTargetHash = nil
617687 if self . bundleReplacementCheckPending {
618688 continue
619689 }
@@ -634,18 +704,31 @@ extension ApplicationRelocator {
634704 try? await Task . sleep ( for : . milliseconds ( 250 ) )
635705 continue
636706 }
707+ if self . bundleReplacementHandoffTargetHash != launchCodeDirectoryHash {
708+ self . bundleReplacementHandoffTargetHash = launchCodeDirectoryHash
709+ self . bundleReplacementHandoffAttempt = 0
710+ }
711+ self . bundleReplacementHandoffAttempt += 1
712+ let handoffAttempt = self . bundleReplacementHandoffAttempt
713+ let maximumAttempts = self . replacementHandoffPolicy . maximumAttempts
637714 self . bundleReplacementCheckPending = false
638- self . logger . notice ( " Installed app changed; relaunching trusted replacement " )
715+ self . logger . notice (
716+ " Relaunching trusted replacement (attempt \( handoffAttempt ) / \( maximumAttempts ) ) " )
639717 self . bundleReplacementHandoffInProgress = true
640- let scheduled = self . scheduleReplacementRelaunch (
718+ let scheduleResult = self . scheduleReplacementRelaunch (
641719 at : snapshot . bundleURL ,
642720 launchReference : launchReference ,
643- codeDirectoryHash : launchCodeDirectoryHash )
644- if ! scheduled {
645- self . bundleReplacementHandoffInProgress = false
646- try? await Task . sleep ( for : . seconds ( 1 ) )
647- continue
721+ codeDirectoryHash : launchCodeDirectoryHash ,
722+ attempt : handoffAttempt )
723+ if case let . failed ( supervisor ) = scheduleResult {
724+ await self . handleReplacementHandoffFailure (
725+ attempt : handoffAttempt ,
726+ targetCodeDirectoryHash : launchCodeDirectoryHash ,
727+ supervisor : supervisor ,
728+ reason : " Could not spawn the trusted replacement " )
648729 }
730+ // The task defer clears recovery ownership before draining the
731+ // retry check queued by the failure handler.
649732 return
650733 }
651734 }
@@ -979,7 +1062,8 @@ extension ApplicationRelocator {
9791062 private static func scheduleReplacementRelaunch (
9801063 at destination : URL ,
9811064 launchReference : BundleFileReference ,
982- codeDirectoryHash : Data ) -> Bool
1065+ codeDirectoryHash : Data ,
1066+ attempt : Int ) -> ReplacementScheduleResult
9831067 {
9841068 let processInfo = ProcessInfo . processInfo
9851069 let activeSupervisor = self . verifiedKeepAliveSupervisor (
@@ -1000,32 +1084,133 @@ extension ApplicationRelocator {
10001084 bootoutTarget : bootoutTarget ,
10011085 forwardedArguments : forwardedArguments )
10021086 else {
1003- self . logger . error ( " Could not spawn the trusted replacement " )
1004- return false
1087+ return . failed ( supervisor : supervisor )
10051088 }
10061089
1090+ let timeoutMilliseconds = self . replacementHandoffPolicy . timeoutMilliseconds (
1091+ loadAverage : self . currentSystemLoadAverage ( ) ,
1092+ activeProcessorCount : processInfo . activeProcessorCount )
10071093 Task { @MainActor in
10081094 let handoffStatus = await Task . detached ( priority : . utility ) {
1009- self . awaitReplacementHandoff ( on : spawned . readyDescriptor )
1095+ self . awaitReplacementHandoff (
1096+ on : spawned . readyDescriptor ,
1097+ timeoutMilliseconds : timeoutMilliseconds )
10101098 } . value
10111099 Darwin . close ( spawned . readyDescriptor )
10121100 guard handoffStatus == " READY " else {
10131101 Darwin . kill ( spawned . processIdentifier , SIGKILL )
10141102 await Task . detached ( priority : . utility ) {
10151103 self . reapProcess ( spawned . processIdentifier )
10161104 } . value
1017- self . logger . error ( " Trusted replacement did not complete its authenticated handoff " )
1018- self . bundleReplacementHandoffInProgress = false
1019- self . bundleReplacementCheckPending = true
1020- try ? await Task . sleep ( for : . seconds ( 1 ) )
1021- self . bundleDirectoryDidChange ( )
1105+ await self . handleReplacementHandoffFailure (
1106+ attempt : attempt ,
1107+ targetCodeDirectoryHash : codeDirectoryHash ,
1108+ supervisor : supervisor ,
1109+ reason : " Trusted replacement handoff timed out after \( timeoutMilliseconds ) ms " )
10221110 return
10231111 }
10241112 self . cancelSupervisorRestorationWatcher ( )
10251113 TerminationSignalWatcher . scheduleExitFailsafe ( )
10261114 NSApp . terminate ( nil )
10271115 }
1028- return true
1116+ return . scheduled
1117+ }
1118+
1119+ private static func handleReplacementHandoffFailure (
1120+ attempt : Int ,
1121+ targetCodeDirectoryHash : Data ,
1122+ supervisor : KeepAliveSupervisor ? ,
1123+ reason : String ) async
1124+ {
1125+ let action = self . replacementHandoffPolicy . failureAction (
1126+ failedAttempt : attempt ,
1127+ hasKeepAliveSupervisor : supervisor != nil )
1128+ if action . isTerminal ,
1129+ await self . shouldContinueReplacementRecovery ( afterFailedTarget : targetCodeDirectoryHash )
1130+ {
1131+ self . bundleReplacementHandoffInProgress = false
1132+ self . bundleReplacementCheckPending = true
1133+ self . bundleDirectoryDidChange ( )
1134+ return
1135+ }
1136+ switch action {
1137+ case let . retry ( delay ) :
1138+ self . bundleReplacementCheckPending = true
1139+ let maximumAttempts = self . replacementHandoffPolicy . maximumAttempts
1140+ self . logger . error (
1141+ " Replacement handoff failed: \( reason , privacy : . public ) ; attempt \( attempt ) / \( maximumAttempts ) " )
1142+ do {
1143+ try await Task . sleep ( for : delay )
1144+ } catch {
1145+ return
1146+ }
1147+ guard self . bundleReplacementSnapshot != nil else { return }
1148+ self . bundleReplacementHandoffInProgress = false
1149+ self . bundleDirectoryDidChange ( )
1150+ case . stopMonitoring :
1151+ self . disableBundleReplacementMonitoring ( )
1152+ self . logger . critical (
1153+ """
1154+ \( reason , privacy : . public ) ; stopped app replacement monitoring after \( attempt ) attempts. \
1155+ Quit and reopen OpenClaw to load the installed replacement.
1156+ """ )
1157+ case . terminateForSupervisor :
1158+ guard let supervisor , self . startSupervisorRestorationWatcher ( supervisor ) else {
1159+ self . disableBundleReplacementMonitoring ( )
1160+ self . logger . critical (
1161+ """
1162+ \( reason , privacy : . public ) ; could not schedule verified KeepAlive recovery. \
1163+ Stopped app replacement monitoring after \( attempt ) attempts.
1164+ """ )
1165+ return
1166+ }
1167+ self . disableBundleReplacementMonitoring ( )
1168+ self . logger . critical (
1169+ """
1170+ \( reason , privacy : . public ) ; exiting after \( attempt ) attempts so verified KeepAlive supervisor \
1171+ \( supervisor . label , privacy : . public ) can restart the installed app.
1172+ """ )
1173+ TerminationSignalWatcher . scheduleExitFailsafe ( )
1174+ NSApp . terminate ( nil )
1175+ }
1176+ }
1177+
1178+ private static func shouldContinueReplacementRecovery ( afterFailedTarget failedTargetHash : Data ) async -> Bool {
1179+ guard let snapshot = self . bundleReplacementSnapshot else { return false }
1180+ // The coalescing bit can be cleared after an event arrives during the
1181+ // earlier async evaluation. Terminal actions always revalidate the disk.
1182+ self . bundleReplacementCheckPending = false
1183+ let evaluation = await Task . detached ( priority : . utility ) {
1184+ self . replacementEvaluationOnDisk ( for : snapshot )
1185+ } . value
1186+ if self . bundleReplacementCheckPending { return true }
1187+ return self . shouldContinueReplacementRecovery (
1188+ afterFailedTarget : failedTargetHash ,
1189+ latestAction : evaluation . action ,
1190+ latestTargetHash : evaluation . launchCodeDirectoryHash )
1191+ }
1192+
1193+ nonisolated static func shouldContinueReplacementRecovery (
1194+ afterFailedTarget failedTargetHash : Data ,
1195+ latestAction : ReplacementAction ,
1196+ latestTargetHash : Data ? ) -> Bool
1197+ {
1198+ switch latestAction {
1199+ case . unchanged , . waitForTrustedReplacement :
1200+ true
1201+ case . relaunch :
1202+ latestTargetHash != failedTargetHash
1203+ }
1204+ }
1205+
1206+ private static func disableBundleReplacementMonitoring ( ) {
1207+ self . bundleReplacementSource ? . cancel ( )
1208+ self . bundleReplacementSource = nil
1209+ self . bundleReplacementSnapshot = nil
1210+ self . bundleReplacementCheckPending = false
1211+ self . bundleReplacementHandoffInProgress = false
1212+ self . bundleReplacementHandoffAttempt = 0
1213+ self . bundleReplacementHandoffTargetHash = nil
10291214 }
10301215
10311216 private static func spawnReplacement (
@@ -1137,9 +1322,17 @@ extension ApplicationRelocator {
11371322 return ( processIdentifier , readDescriptor )
11381323 }
11391324
1140- private nonisolated static func awaitReplacementHandoff ( on descriptor : Int32 ) -> String ? {
1325+ private nonisolated static func currentSystemLoadAverage ( ) -> Double ? {
1326+ var loadAverage = 0.0
1327+ return getloadavg ( & loadAverage , 1 ) == 1 ? loadAverage : nil
1328+ }
1329+
1330+ private nonisolated static func awaitReplacementHandoff (
1331+ on descriptor : Int32 ,
1332+ timeoutMilliseconds : Int32 ) -> String ?
1333+ {
11411334 var event = pollfd ( fd : descriptor , events : Int16 ( POLLIN | POLLHUP ) , revents : 0 )
1142- guard poll ( & event , 1 , 10000 ) > 0 else { return nil }
1335+ guard poll ( & event , 1 , timeoutMilliseconds ) > 0 else { return nil }
11431336 var bytes = [ UInt8 ] ( repeating : 0 , count : 16 )
11441337 let count = bytes . withUnsafeMutableBytes { buffer in
11451338 Darwin . read ( descriptor , buffer . baseAddress , buffer . count )
0 commit comments