Repository navigation
fix(snapshot): finish queued writes without blocking quit (CC-196) #344
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b252228
fix(snapshot): drain async writes without blocking termination (CC-196)
swu-echo[bot] 578c90a
fix(snapshot): close termination queue and reply on repeated quit
swu-echo[bot] 97f8835
fix(snapshot): reset drain lifecycle when sampling resumes
swu-echo[bot] 5c86684
fix(snapshot): model one terminal quit lifecycle
swu-echo[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import Foundation | ||
|
|
||
| /// A deadline bounds how long termination waits, not the underlying disk write. | ||
| /// Unstructured waiters intentionally do not join the possibly stuck task on timeout. | ||
| @MainActor | ||
| enum SnapshotWriteDrain { | ||
| private final class ResultGate { | ||
| var continuation: CheckedContinuation<Bool, Never>? | ||
| var timeoutTask: Task<Void, Never>? | ||
|
|
||
| func finish(_ drained: Bool) { | ||
| guard let continuation else { return } | ||
| self.continuation = nil | ||
| timeoutTask?.cancel() | ||
| timeoutTask = nil | ||
| continuation.resume(returning: drained) | ||
| } | ||
| } | ||
|
|
||
| static func wait(for chain: Task<Void, Never>?, timeout: Duration) async -> Bool { | ||
| guard let chain else { return true } | ||
| return await withCheckedContinuation { continuation in | ||
| let gate = ResultGate() | ||
| gate.continuation = continuation | ||
| Task { @MainActor in | ||
| await chain.value | ||
| gate.finish(true) | ||
| } | ||
| gate.timeoutTask = Task { @MainActor in | ||
| do { try await Task.sleep(for: timeout) } | ||
| catch { return } | ||
| gate.finish(false) | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import Foundation | ||
| import XCTest | ||
| @testable import CodeCaps | ||
|
|
||
| @MainActor | ||
| final class SnapshotWriteDrainTests: XCTestCase { | ||
| func testEmptyQueueDoesNotWait() async { | ||
| let drained = await SnapshotWriteDrain.wait(for: nil, timeout: .seconds(2)) | ||
| XCTAssertTrue(drained) | ||
| } | ||
|
|
||
| func testMainActorCompletionRunsBeforeDrainReturns() async { | ||
| var completed = false | ||
| let chain = Task { @MainActor in | ||
| await Task.yield() | ||
| completed = true | ||
| } | ||
| let drained = await SnapshotWriteDrain.wait(for: chain, timeout: .seconds(2)) | ||
| XCTAssertTrue(drained) | ||
| XCTAssertTrue(completed) | ||
| } | ||
|
|
||
| func testStopAndFlushWaitForRealQueuedFileAndMainActorCompletion() async throws { | ||
| let name = "cc196-snapshot-tests-" + UUID().uuidString | ||
| let defaults = try XCTUnwrap(UserDefaults(suiteName: name)) | ||
| defaults.set(false, forKey: "localEnabled") | ||
| defer { defaults.removePersistentDomain(forName: name) } | ||
| let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) | ||
| try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) | ||
| defer { try? FileManager.default.removeItem(at: directory) } | ||
| let file = directory.appendingPathComponent("snapshot.txt") | ||
| let model = MonitorModel(defaults: defaults) | ||
| model.skipsSnapshotIOForTesting = true | ||
| var completion = false | ||
| model.enqueueSnapshotWrite({ try Data("ordered snapshot".utf8).write(to: file) }, | ||
| completion: { succeeded in completion = succeeded }) | ||
| model.stop() | ||
| let drained = await model.flushSnapshotWrites() | ||
| XCTAssertTrue(drained) | ||
| XCTAssertTrue(completion) | ||
| XCTAssertEqual(try String(contentsOf: file), "ordered snapshot") | ||
| } | ||
|
|
||
| func testFlushClosesQueueBeforeSuspendingAndPreservesPriorOrdering() async throws { | ||
| let name = "cc196-closed-queue-" + UUID().uuidString | ||
| let defaults = try XCTUnwrap(UserDefaults(suiteName: name)) | ||
| defaults.set(false, forKey: "localEnabled") | ||
| defer { defaults.removePersistentDomain(forName: name) } | ||
| let model = MonitorModel(defaults: defaults) | ||
| model.skipsSnapshotIOForTesting = true | ||
| var firstCompleted = false | ||
| var lateCompleted = false | ||
| model.enqueueSnapshotWrite({}, completion: { _ in firstCompleted = true }) | ||
| let drain = Task { @MainActor in await model.flushSnapshotWrites() } | ||
| while !model.snapshotWritesClosedForTermination { await Task.yield() } | ||
| model.enqueueSnapshotWrite({}, completion: { _ in lateCompleted = true }) | ||
| let drained = await drain.value | ||
| XCTAssertTrue(drained) | ||
| XCTAssertTrue(firstCompleted) | ||
| XCTAssertFalse(lateCompleted) | ||
| } | ||
|
|
||
| func testDeadlineDoesNotJoinStuckWriteAndLateCompletionIsSafe() async { | ||
| var release: CheckedContinuation<Void, Never>? | ||
| var completed = false | ||
| let chain = Task { @MainActor in | ||
| await withCheckedContinuation { release = $0 } | ||
| completed = true | ||
| } | ||
| while release == nil { await Task.yield() } | ||
| let clock = ContinuousClock() | ||
| let start = clock.now | ||
| let drained = await SnapshotWriteDrain.wait(for: chain, timeout: .milliseconds(20)) | ||
| XCTAssertFalse(drained) | ||
| XCTAssertLessThan(start.duration(to: clock.now), .seconds(1)) | ||
| XCTAssertFalse(completed) | ||
| release?.resume() | ||
| await chain.value | ||
| XCTAssertTrue(completed) | ||
| } | ||
| } | ||
|
|
||
| final class SnapshotTerminationIntegrationTests: XCTestCase { | ||
| private func source(_ file: String) throws -> String { | ||
| let root = URL(fileURLWithPath: #filePath) | ||
| .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() | ||
| return try String(contentsOf: root.appendingPathComponent("Sources/CodeCaps/" + file)) | ||
| } | ||
|
|
||
| func testTerminationDefersReplyUntilAsyncFlushWithoutBlockingMainActor() throws { | ||
| let delegate = try source("AppDelegate.swift") | ||
| XCTAssertTrue(delegate.contains("func applicationShouldTerminate(")) | ||
| XCTAssertTrue(delegate.contains("snapshotFlushTask = Task { @MainActor in await model.flushSnapshotWrites() }")) | ||
| XCTAssertTrue(delegate.contains("_ = await flush?.value")) | ||
| XCTAssertFalse(delegate.contains("guard !snapshotTerminationPending")) | ||
| XCTAssertTrue(delegate.contains("sender.reply(toApplicationShouldTerminate: true)")) | ||
| XCTAssertTrue(delegate.contains("return .terminateLater")) | ||
| let model = try source("MonitorModel.swift") | ||
| XCTAssertTrue(model.contains("timeout: Duration = .seconds(2)")) | ||
| XCTAssertTrue(model.contains("await SnapshotWriteDrain.wait(for: chain, timeout: timeout)")) | ||
| XCTAssertFalse(model.contains("group.wait(")) | ||
| XCTAssertFalse(model.contains("sem.wait(")) | ||
| } | ||
|
|
||
| func testDisableQueuesRemovalAndWidgetUsesCompletionTimeOrder() throws { | ||
| let model = try source("MonitorModel.swift") | ||
| let disable = try XCTUnwrap(model.range(of: "func setLocalEnabled(")) | ||
| let next = try XCTUnwrap(model.range(of: "func setProviderChecksEnabled(")) | ||
| let block = String(model[disable.lowerBound..<next.lowerBound]) | ||
| XCTAssertTrue(block.contains("enqueueHandoffWrite(windows: nil)")) | ||
| XCTAssertTrue(model.contains(".set(self.platformOrder, forKey: \"platformOrder\")")) | ||
| XCTAssertFalse(model.contains("let order = platformOrder")) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.