@@ -12,7 +12,9 @@ import XCTest
1212extension RunnerTests {
1313 /// Tracks one main-queue dispatch so the watchdog and the dispatched block can agree, under
1414 /// `mainThreadWorkLock`, on exactly one of: finished in time, or abandoned.
15- private final class MainThreadWorkState {
15+ private final class MainThreadWorkState < T > {
16+ let completed = DispatchSemaphore ( value : 0 )
17+ var result : Result < T , Error > ?
1618 var finished = false
1719 var abandoned = false
1820 }
@@ -62,24 +64,69 @@ extension RunnerTests {
6264 if Thread . isMainThread {
6365 return try work ( )
6466 }
65- var result : Result < T , Error > ?
66- let semaphore = DispatchSemaphore ( value : 0 )
67- let workState = MainThreadWorkState ( )
67+ mainThreadWorkLock . lock ( )
68+ let state = enqueueMainThreadWorkLocked ( operation , work )
69+ mainThreadWorkLock . unlock ( )
70+ return try awaitMainThreadWork (
71+ state ,
72+ operation : operation ,
73+ timeout : timeout ,
74+ timeoutError : timeoutError ,
75+ onAbandoned : onAbandoned
76+ )
77+ }
78+
79+ /// Runs optional `work` like `runMainThreadWork`, but only while no other dispatched main-thread
80+ /// work is in flight or abandoned; otherwise it returns `nil` without dispatching. The check and
81+ /// the enqueue happen under one hold of `mainThreadWorkLock`, the same lock every dispatch enqueues
82+ /// under, so admitted work never waits in the main queue behind a command's hop.
83+ func runMainThreadWorkIfIdle < T > (
84+ _ operation : String ,
85+ timeout : TimeInterval ,
86+ timeoutError : @escaping ( ) -> Error ,
87+ _ work : @escaping ( ) throws -> T
88+ ) throws -> T ? {
89+ if Thread . isMainThread {
90+ return nil
91+ }
92+ mainThreadWorkLock . lock ( )
93+ guard mainThreadWorkInFlightCount == 0 , abandonedMainThreadWorkCount == 0 else {
94+ mainThreadWorkLock . unlock ( )
95+ return nil
96+ }
97+ let state = enqueueMainThreadWorkLocked ( operation , work )
98+ mainThreadWorkLock . unlock ( )
99+ return try awaitMainThreadWork (
100+ state ,
101+ operation : operation ,
102+ timeout : timeout ,
103+ timeoutError : timeoutError ,
104+ onAbandoned : nil
105+ )
106+ }
107+
108+ private func enqueueMainThreadWorkLocked < T > (
109+ _ operation : String ,
110+ _ work : @escaping ( ) throws -> T
111+ ) -> MainThreadWorkState < T > {
112+ let state = MainThreadWorkState < T > ( )
113+ mainThreadWorkInFlightCount += 1
68114 DispatchQueue . main . async {
69115 do {
70- result = . success ( try work ( ) )
116+ state . result = . success ( try work ( ) )
71117 } catch {
72- result = . failure ( error )
118+ state . result = . failure ( error )
73119 }
74120 self . mainThreadWorkLock . lock ( )
75- let abandoned = workState . abandoned
121+ self . mainThreadWorkInFlightCount -= 1
122+ let abandoned = state . abandoned
76123 if abandoned {
77124 self . abandonedMainThreadWorkCount -= 1
78125 if self . abandonedMainThreadWorkCount == 0 {
79126 self . abandonedMainThreadWorkSince = nil
80127 }
81128 } else {
82- workState . finished = true
129+ state . finished = true
83130 }
84131 let allDrained = abandoned && self . abandonedMainThreadWorkCount == 0
85132 self . mainThreadWorkLock . unlock ( )
@@ -89,19 +136,29 @@ extension RunnerTests {
89136 NSLog ( " AGENT_DEVICE_RUNNER_ABANDONED_WORK_DRAINED " )
90137 }
91138 }
92- semaphore . signal ( )
139+ state . completed . signal ( )
93140 }
94- let waitResult = semaphore . wait ( timeout : . now ( ) + timeout )
141+ return state
142+ }
143+
144+ private func awaitMainThreadWork < T > (
145+ _ state : MainThreadWorkState < T > ,
146+ operation : String ,
147+ timeout : TimeInterval ,
148+ timeoutError : @escaping ( ) -> Error ,
149+ onAbandoned : ( ( ) -> Void ) ?
150+ ) throws -> T {
151+ let waitResult = state . completed . wait ( timeout : . now ( ) + timeout )
95152 if waitResult == . timedOut {
96153 #if AGENT_DEVICE_RUNNER_UNIT_TESTS
97154 mainThreadWorkTimedOutForTesting ? ( )
98155 #endif
99156 // Work that finished before the lock was taken already stored its result: it is answered
100157 // like work that finished in time, so an action that happened is never reported as a timeout.
101158 mainThreadWorkLock . lock ( )
102- let abandoned = ! workState . finished
159+ let abandoned = ! state . finished
103160 if abandoned {
104- workState . abandoned = true
161+ state . abandoned = true
105162 abandonedMainThreadWorkCount += 1
106163 if abandonedMainThreadWorkSince == nil {
107164 abandonedMainThreadWorkSince = Date ( )
@@ -118,7 +175,7 @@ extension RunnerTests {
118175 throw timeoutError ( )
119176 }
120177 }
121- switch result {
178+ switch state . result {
122179 case . success ( let value ) :
123180 return value
124181 case . failure ( let error ) :
@@ -252,6 +309,76 @@ extension RunnerTests {
252309 XCTAssertEqual ( outcome . onAbandonedCalls , 0 )
253310 }
254311
312+ func testRunMainThreadWorkIfIdleDeclinesWhileOtherWorkIsInFlight ( ) {
313+ final class Outcome {
314+ var offeredWhileInFlight = false
315+ var whileInFlight : Bool ?
316+ var ranWhileInFlight = false
317+ var whenIdle : Bool ?
318+ var error : Error ?
319+ }
320+ let outcome = Outcome ( )
321+ let releaseCommand = DispatchSemaphore ( value : 0 )
322+ let commandEntered = DispatchSemaphore ( value : 0 )
323+ let finished = expectation ( description : " optional work was offered during and after the command " )
324+
325+ DispatchQueue ( label : " agent-device.runner.tests.in-flight-command " ) . async {
326+ _ = try? self . runMainThreadWork (
327+ " command_execution " ,
328+ timeout : 5 ,
329+ timeoutError : self . mainThreadExecutionTimeoutError
330+ ) {
331+ commandEntered . signal ( )
332+ _ = releaseCommand . wait ( timeout : . now ( ) + 3 )
333+ }
334+ }
335+ DispatchQueue ( label : " agent-device.runner.tests.optional-work " ) . async {
336+ defer { finished . fulfill ( ) }
337+ guard commandEntered . wait ( timeout : . now ( ) + 3 ) == . success else { return }
338+ do {
339+ outcome . whileInFlight = try self . runMainThreadWorkIfIdle (
340+ " recording_frame " ,
341+ timeout : 5 ,
342+ timeoutError : self . mainThreadExecutionTimeoutError
343+ ) { ( ) -> Bool in
344+ outcome . ranWhileInFlight = true
345+ return true
346+ }
347+ outcome . offeredWhileInFlight = true
348+ } catch {
349+ outcome . error = error
350+ }
351+ releaseCommand . signal ( )
352+ let idleDeadline = Date ( ) . addingTimeInterval ( 3 )
353+ while Date ( ) < idleDeadline {
354+ self . mainThreadWorkLock . lock ( )
355+ let inFlight = self . mainThreadWorkInFlightCount
356+ self . mainThreadWorkLock . unlock ( )
357+ if inFlight == 0 { break }
358+ usleep ( 2_000 )
359+ }
360+ do {
361+ outcome . whenIdle = try self . runMainThreadWorkIfIdle (
362+ " recording_frame " ,
363+ timeout : 5 ,
364+ timeoutError : self . mainThreadExecutionTimeoutError
365+ ) {
366+ Thread . isMainThread
367+ }
368+ } catch {
369+ outcome . error = error
370+ }
371+ }
372+
373+ wait ( for : [ finished ] , timeout : 10 )
374+ XCTAssertNil ( outcome . error )
375+ XCTAssertTrue ( outcome . offeredWhileInFlight )
376+ XCTAssertNil ( outcome . whileInFlight , " optional work declines while a hop is in flight " )
377+ XCTAssertFalse ( outcome . ranWhileInFlight , " declined work is never dispatched " )
378+ XCTAssertEqual ( outcome . whenIdle , true , " optional work runs on main once main is idle " )
379+ XCTAssertFalse ( hasAbandonedMainThreadWork ( ) )
380+ }
381+
255382 private final class BoundaryOutcome {
256383 var value : Int ?
257384 var error : Error ?
0 commit comments