Skip to content

Use export session states to observe video progress - #26090

Open
crazytonyli wants to merge 4 commits into
trunkfrom
task/ios-18-export-progress
Open

crazytonyli wants to merge 4 commits into
trunkfrom
task/ios-18-export-progress

Conversation

@crazytonyli

Copy link
Copy Markdown
Contributor

No description provided.

@wpmobilebot

wpmobilebot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
App Icon📲 You can test the changes from this Pull Request in Jetpack by scanning the QR code below to install the corresponding build.
App NameJetpack
ConfigurationRelease-Alpha
Build Number35043
VersionPR #26090
Bundle IDcom.jetpack.alpha
Commit578f9b8
Installation URL2urtoop05qeb8
Automatticians: You can use our internal self-serve MC tool to give yourself access to those builds if needed.

@wpmobilebot

wpmobilebot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
App Icon📲 You can test the changes from this Pull Request in WordPress by scanning the QR code below to install the corresponding build.
App NameWordPress
ConfigurationRelease-Alpha
Build Number35043
VersionPR #26090
Bundle IDorg.wordpress.alpha
Commit578f9b8
Installation URL3kuvajvttoc1g
Automatticians: You can use our internal self-serve MC tool to give yourself access to those builds if needed.

@crazytonyli
crazytonyli added this pull request to stack #26152 October 18, 2026 20:13
@crazytonyli
crazytonyli removed this pull request from stack #26152 October 18, 2026 21:33
@crazytonyli
crazytonyli changed the base branch from task/zero-warnings-avasset-async to task/raise-min-ios-18 October 18, 2026 21:33
@crazytonyli
crazytonyli force-pushed the task/ios-18-export-progress branch from ecd613c to a679cf9 Compare October 18, 2026 21:33
@crazytonyli
crazytonyli added this pull request to stack #26155 October 18, 2026 21:34
@crazytonyli crazytonyli changed the title Raise minimum iOS to 18 and modernize video export progress Use export session states to observe video progress Oct 18, 2026
@crazytonyli
crazytonyli force-pushed the task/ios-18-export-progress branch from a679cf9 to 578f9b8 Compare October 19, 2026 00:21
@jkmassel

Copy link
Copy Markdown
Contributor

Before this lands, check that states(updateInterval:) stops when the group is cancelled. withThrowingTaskGroup waits for the progress task, so if the sequence keeps going after cancelAll(), the export never returns.

@crazytonyli
crazytonyli force-pushed the task/ios-18-export-progress branch from 578f9b8 to d29bb4c Compare November 1, 2026 21:47
@crazytonyli
crazytonyli marked this pull request as ready for review November 1, 2026 21:49
@crazytonyli
crazytonyli requested a review from jkmassel November 1, 2026 21:50
@crazytonyli crazytonyli added this to the 27.5 milestone Nov 1, 2026
Base automatically changed from task/raise-min-ios-18 to trunk November 2, 2026 19:48
@crazytonyli
crazytonyli force-pushed the task/ios-18-export-progress branch from d29bb4c to 3246be3 Compare November 2, 2026 19:48

@jkmassel jkmassel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
        }
    }
}

Comment on lines +220 to +226
for await state in session.states(updateInterval: 0.1) {
if case .exporting(let exportProgress) = state {
progress.completedUnitCount = Int64(
Double(MediaExportProgressUnits.done) * exportProgress.fractionCompleted
)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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))
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@crazytonyli
crazytonyli enabled stacked auto-merge November 5, 2026 04:21
@wpmobilebot

Copy link
Copy Markdown
Contributor

🤖 Build Failure Analysis

This build has failures. Claude has analyzed them - check the build annotations for details.

@wpmobilebot wpmobilebot modified the milestones: 27.5, 27.6 Nov 20, 2026
@wpmobilebot

Copy link
Copy Markdown
Contributor

Version 27.5 has now entered code-freeze, so the milestone of this PR has been updated to 27.6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants