Repository navigation
Use export session states to observe video progress - #26090
crazytonyli wants to merge 4 commits into
Conversation
|
| App Name | Jetpack | |
| Configuration | Release-Alpha | |
| Build Number | 35043 | |
| Version | PR #26090 | |
| Bundle ID | com.jetpack.alpha | |
| Commit | 578f9b8 | |
| Installation URL | 2urtoop05qeb8 |
|
| App Name | WordPress | |
| Configuration | Release-Alpha | |
| Build Number | 35043 | |
| Version | PR #26090 | |
| Bundle ID | org.wordpress.alpha | |
| Commit | 578f9b8 | |
| Installation URL | 3kuvajvttoc1g |
ecd613c to
a679cf9
Compare
a679cf9 to
578f9b8
Compare
|
Before this lands, check that |
578f9b8 to
d29bb4c
Compare
d29bb4c to
3246be3
Compare
jkmassel
left a comment
There was a problem hiding this comment.
From Claude: cancelling a video export can crash the app on this branch. The cause is session.states(updateInterval:). Trunk doesn't call it, and the suggestion replaces it.
What happens: Apple's iterator checks the session status twice while it builds its first .exporting value. If the status changes between those checks, it traps. A cancel at the wrong moment does exactly that.
Who is affected: anyone who cancels a video upload just as the export starts, for example with Aztec's Stop Upload. The gap is very short, so this is rare for each cancel.
What they see: the app crashes (EXC_BREAKPOINT). Neither onCompletion nor onError runs.
Suggested fix: keep the task group, but poll session.progress in the child task. session.progress is deprecated from iOS 27, which doesn't warn at the iOS 18 minimum.
How this was checked: the real MediaVideoExporter in the WordPress test host, on an iOS 27.0 simulator, at 3246be3fb3.
| Test | This PR | Trunk | With the suggestion |
|---|---|---|---|
| Cancel aimed at export start (the test below, 3 runs) | crashed 3 of 3 | passed 3 of 3 | passed 3 of 3 |
Random cancel, 0-20 ms, through MediaVideoExporter(url:), 3 runs of 2,000 exports |
crashed 2 of 3 | 0 crashes | 0 crashes |
| Callback lost in those random cancels | 0 of 2,000 (only finished run) | 168 of 6,000 | 25 of 6,000 |
- Every crash report has the same top frame,
AVAssetExportSession.ProgressStates.Iterator.StateInternal.init(forSnapshotOf:previousInternalState:). - The suggestion ran without the two-line comment, which is the only difference from the code posted here.
- The lost callback is the existing problem from #26041, a cancel at export start. The suggestion is better than trunk there, but this PR's one finished run had none.
- The same crash appeared on iOS 18.6 and 26.5 in standalone test programs. The test host was not run on those versions.
- Not tested: a physical device, or the full app UI.
Earlier question on this PR: states(updateInterval:) does stop when the group is cancelled. It stopped within 5 ms on iOS 18.6, 26.5 and 27.0, and on macOS 27.2. Apple doesn't document that, and the suggestion no longer depends on it.
Non-blocking: every video export test is currently skipped, so CI doesn't run this code. The test below needs init(session:), which has no other callers, so please keep that initializer. The comment at UploadSourceMaterializer.swift:327 still says the iOS 17 minimum rules out states. That reason is gone, and the comment now invites the same crash.
Test that crashes on this branch
Tests/KeystoneTests/Tests/Features/Media/MediaVideoExporterCancellationTests.swift
import AVFoundation
import Foundation
import Testing
@testable import WordPress
struct MediaVideoExporterCancellationTests {
/// Cancels each export at the moment its session enters `.exporting`.
///
/// `AVAssetExportSession.states(updateInterval:)` traps if the session leaves
/// `.exporting` while the iterator builds its first `.exporting` value, so
/// observing progress with it crashes the test host here.
@Test func cancellingAsExportStartsReportsCancellation() async throws {
let url = try #require(
Bundle(for: MediaURLExporterTests.self).url(forResource: "test-video-device-gps", withExtension: "m4v")
)
for _ in 0..<300 {
let asset = AVURLAsset(url: url)
let session = try #require(AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset640x480))
let error = await exportAndCancelAtStart(session)
// A cancel at export start can lose the callback, so `nil` is tolerated.
if let error {
#expect(error as? MediaVideoExporter.VideoExportError == .videoExportSessionCancelled)
}
}
}
/// Returns the error reported by the export, or `nil` if no callback arrived in time.
private func exportAndCancelAtStart(_ session: AVAssetExportSession) async -> MediaExportError? {
nonisolated(unsafe) let session = session
let exporter = MediaVideoExporter(session: session)
exporter.mediaDirectoryType = .temporary
return await withCheckedContinuation { continuation in
let result = OneShot(continuation)
let progress = exporter.export(
onCompletion: { export in
try? FileManager.default.removeItem(at: export.url)
Issue.record("The export should have been cancelled")
result.resume(with: nil)
},
onError: { result.resume(with: $0) }
)
nonisolated(unsafe) let cancellable = progress
DispatchQueue.global(qos: .userInteractive)
.async {
let deadline = Date.now.addingTimeInterval(3)
while session.status != .exporting, Date.now < deadline {}
cancellable.cancel()
}
DispatchQueue.global()
.asyncAfter(deadline: .now() + 3) {
result.resume(with: nil)
}
}
}
}
private final class OneShot: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<MediaExportError?, Never>?
init(_ continuation: CheckedContinuation<MediaExportError?, Never>) {
self.continuation = continuation
}
func resume(with error: MediaExportError?) {
lock.withLock {
continuation?.resume(returning: error)
continuation = nil
}
}
}| for await state in session.states(updateInterval: 0.1) { | ||
| if case .exporting(let exportProgress) = state { | ||
| progress.completedUnitCount = Int64( | ||
| Double(MediaExportProgressUnits.done) * exportProgress.fractionCompleted | ||
| ) | ||
| } | ||
| } |
There was a problem hiding this comment.
From Claude: this loop can crash the app when a video export is cancelled. Polling session.progress avoids the crash and keeps the task group, so no progress write can land after the callback. See the review summary for the evidence.
| for await state in session.states(updateInterval: 0.1) { | |
| if case .exporting(let exportProgress) = state { | |
| progress.completedUnitCount = Int64( | |
| Double(MediaExportProgressUnits.done) * exportProgress.fractionCompleted | |
| ) | |
| } | |
| } | |
| // Poll rather than use `states(updateInterval:)`. Its iterator crashes the | |
| // app if the session leaves `.exporting` while it reads the first progress. | |
| while !Task.isCancelled { | |
| progress.completedUnitCount = Int64( | |
| Double(MediaExportProgressUnits.done) * Double(session.progress) | |
| ) | |
| try? await Task.sleep(for: .milliseconds(100)) | |
| } |
There was a problem hiding this comment.
I'm a bit conflicted about this issue. This code here uses the new states(updateInterval:) API and follows the usage pattern in Apple's sample code. progress is deprecated and does not crash. The new API is the recommended replacement, but may crash.
Considering the crash may happen in that tiny window after export starts, I'm leaning towards using the new API, even though it technically may crash. What do you think?
There was a problem hiding this comment.
From Claude: I think we can keep states(updateInterval:). The crash only happens when the session is cancelled in the first microseconds of the export, so #26338 holds the cancel until the states loop has seen .exporting.
- No crashes in 5,500 cancels, including 900 aimed at the start. This branch crashed 3 of 3 runs on the same aimed test.
- It also fixes the lost callback from Load AVAsset properties asynchronously #26041: 0 in 4,000 random cancels, against 6 in 4,000 with polling.
- A cancel still takes effect in about 15–20 ms.
It's based on this branch, so you can merge it in, cherry-pick it, or close it. The numbers are in its description.
* Hold a video export cancel until the session is exporting `states(updateInterval:)` traps if the session leaves `.exporting` while the iterator builds its first `.exporting` value, so a cancel at the start of an export crashed the app. A cancel at the same moment could also leave the export stuck with no callback. `export(to:as:)` now runs in an unstructured task, so cancelling the caller doesn't cancel the session straight away. `ExportCancelGate` sends `cancelExport()` once the cancel is requested and the `states` loop has seen `.exporting`. * Cancel the export task instead of calling cancelExport() `cancelExport()` is deprecated from iOS 27 in favour of task cancellation. Cancelling the task that runs `export(to:as:)` cancels the session, and the gate still decides when that happens.
🤖 Build Failure AnalysisThis build has failures. Claude has analyzed them - check the build annotations for details. |
|
Version |


No description provided.