Skip to content

[CP-stable][Tool] Fix SwiftPM race condition during parallel Xcode builds - #191120

Merged
auto-submit[bot] merged 1 commit into
flutter:flutter-3.47-candidate.0from
flutteractionsbot:cp-stable-2cb26f7500f7a17e87f00d0f3077f1eccad3ed91
Aug 18, 2026
Merged

auto-submit[bot] merged 1 commit into
flutter:flutter-3.47-candidate.0from
flutteractionsbot:cp-stable-2cb26f7500f7a17e87f00d0f3077f1eccad3ed91

Conversation

@flutteractionsbot

@flutteractionsbot flutteractionsbot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is created by automatic cherry pick workflow
Please fill in the form below, and a flutter domain expert will evaluate this cherry pick request.

Issue Link:

What is the link to the issue this cherry-pick is addressing?

#188446

Impact Description:

What is the impact (ex. visual jank on Samsung phones, app crash, cannot ship an iOS app)?
Does it impact development (ex. flutter doctor crashes when Android Studio is installed),
or the shipping of production apps (the app crashes on launch).
This information is for domain experts and release engineers to understand the consequences of saying yes or no to the cherry pick.

The Flutter tool experiences a race condition when preparing the Swift Packages directory during parallel Xcode builds, leading to FileSystemException (OS Error: Directory not empty, errno = 66) or PathExistsException. This is one of the top crashers identified in the Flutter 3.44.3 stable release. It impacts development when building multi-target iOS/macOS applications in parallel.

Changelog Description:

Explain this cherry pick:

  • In one line that is accessible to most Flutter developers.
  • That describes the state prior to the fix.
  • That includes which platforms are impacted.
    See best practices for examples.

[flutter/188446] When building multi-target applications in parallel on iOS and macOS, a race condition in SwiftPM integration causes FileSystemException.

Workaround:

Is there a workaround for this issue?

Run Xcode builds sequentially (disable parallel target builds) or build targets one by one.

Risk:

What is the risk level of this cherry-pick?

  • Low
  • Medium
  • High

Test Coverage:

Are you confident that your fix is well-tested by automated tests?

  • Yes
  • No

Validation Steps:

What are the steps to validate that this fix works?

  1. Enable Swift PM in a Flutter project.
  2. Add multiple targets (e.g. App and Share Extension) that use Swift PM plugins.
  3. Build the project in Xcode with parallel builds enabled.
  4. Verify the build succeeds without FileSystemException or PathExistsException in ephemeral/Packages.

…er#188451)

Xcode builds multi-target applications in parallel, invoking the Flutter
build pipeline concurrently. This leads to a destructive race condition
in `generatePluginsSwiftPackage` where one process deletes the ephemeral
packages directory while another is writing to it, causing
`FileSystemException` or `PathExistsException`.

This change implements:

1. Process-safe file locking (`.swift_pm.lock`) with retry loops to
serialize directory preparation across parallel builds.

2. Non-destructive, incremental cleanup of obsolete symlinks rather than
deleting the entire directory.

3. Content-aware write skipping for `Package.swift` and placeholder
source files to avoid redundant writes and prevent unnecessary Xcode
project re-indexing.

Fixes flutter#188446
@flutteractionsbot flutteractionsbot added the cp: review Cherry-picks in the review queue label Aug 14, 2026
@flutteractionsbot
flutteractionsbot requested review from a team as code owners August 14, 2026 16:32
@flutteractionsbot

Copy link
Copy Markdown
Contributor Author

@bkonyi please fill out the PR description above, afterwards the release team will review this request.

@flutter-dashboard flutter-dashboard Bot added the CICD Run CI/CD label Aug 14, 2026
@flutter-dashboard

Copy link
Copy Markdown

This pull request was opened from and to a release candidate branch. This should only be done as part of the official Flutter release process. If you are attempting to make a regular contribution to the Flutter project, please close this PR and follow the instructions at Tree Hygiene for detailed instructions on contributing to Flutter.

Reviewers: Use caution before merging pull requests to release branches. Ensure the proper procedure has been followed.

@github-actions github-actions Bot added tool Affects the "flutter" command-line tool. See also t: labels. platform-macos Building on or for macOS specifically a: desktop Running on desktop team-ios Owned by iOS platform team team-macos Owned by the macOS platform team labels Aug 14, 2026

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces file-based locking when generating Swift Packages for Flutter plugins to prevent concurrent modifications, along with optimizations to clean up stale symlinks and avoid redundant writes to Package.swift and placeholder source files. Feedback highlights potential issues with the locking mechanism, including infinite loops on persistent exceptions and synchronous thread blocking on macOS/Linux, as well as missing documentation on public members.

Comment on lines +295 to +331
var printed = false;
RandomAccessFile? openedFile;
while (true) {
try {
lockFile.parent.createSync(recursive: true);
openedFile = lockFile.openSync(mode: FileMode.write);
openedFile.lockSync();
break;
} on UnimplementedError {
logger?.printTrace(traceMessage ?? 'Locking not supported (UnimplementedError).');
break;
} on UnsupportedError {
logger?.printTrace(traceMessage ?? 'Locking not supported (UnsupportedError).');
break;
} on FileSystemException catch (e) {
final lockFailed = openedFile != null;
if (openedFile != null) {
try {
openedFile.closeSync();
} on FileSystemException catch (_) {}
openedFile = null;
}
if (!printed) {
final details = lockFailed ? '' : ' (Error: $e)';
logger?.printTrace(
traceMessage ?? 'Waiting to obtain lock of directory: ${lockFile.path}$details',
);
logger?.printWarning(
warningMessage ?? 'Waiting for another flutter command to release the lock...',
color: TerminalColor.grey,
fatal: false,
);
printed = true;
}
await Future<void>.delayed(const Duration(milliseconds: 50));
}
}

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.

critical

If lockFile.parent.createSync or lockFile.openSync throws a persistent FileSystemException (such as a permission denied error), the loop will retry indefinitely every 50ms, causing the Flutter tool to hang forever.

Additionally, on certain filesystems (like network shares, NFS, SMB, or VM shared folders), lockSync can fail persistently with a FileSystemException (e.g., 'Operation not supported' or 'No locks available'). Because openedFile is not null in this case, lockFailed is set to true, which sets details to '', completely hiding the actual error message $e from the trace logs.

To prevent infinite hangs and improve diagnostics, implement a maximum retry limit or timeout, and ensure the actual exception $e is always included in the trace log even when lockFailed is true.

    var printed = false;
    RandomAccessFile? openedFile;
    var retries = 0;
    const int maxRetries = 600; // 30 seconds
    while (true) {
      try {
        lockFile.parent.createSync(recursive: true);
        openedFile = lockFile.openSync(mode: FileMode.write);
        openedFile.lockSync();
        break;
      } on UnimplementedError {
        logger?.printTrace(traceMessage ?? 'Locking not supported (UnimplementedError).');
        break;
      } on UnsupportedError {
        logger?.printTrace(traceMessage ?? 'Locking not supported (UnsupportedError).');
        break;
      } on FileSystemException catch (e) {
        retries++;
        if (retries >= maxRetries) {
          if (openedFile != null) {
            try {
              openedFile.closeSync();
            } on FileSystemException catch (_) {}
          }
          rethrow;
        }
        final lockFailed = openedFile != null;
        if (openedFile != null) {
          try {
            openedFile.closeSync();
          } on FileSystemException catch (_) {}
          openedFile = null;
        }
        if (!printed) {
          logger?.printTrace(
            traceMessage ?? 'Waiting to obtain lock of directory: ${lockFile.path} (Error: $e)',
          );
          logger?.printWarning(
            warningMessage ?? 'Waiting for another flutter command to release the lock...',
            color: TerminalColor.grey,
            fatal: false,
          );
          printed = true;
        }
        await Future<void>.delayed(const Duration(milliseconds: 50));
      }
    }

try {
lockFile.parent.createSync(recursive: true);
openedFile = lockFile.openSync(mode: FileMode.write);
openedFile.lockSync();

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.

medium

On macOS and Linux, RandomAccessFile.lockSync() blocks the thread synchronously until the lock is acquired. It does not throw a FileSystemException on lock contention.

Consequently, the catch (FileSystemException) block is never entered for lock contention on macOS/Linux, meaning:

  1. The warning message 'Waiting for another flutter command to release the lock...' will never be printed on macOS (which is the primary platform for this SwiftPM fix).
  2. The entire Flutter tool main thread is blocked synchronously, preventing any other asynchronous tasks or signal handlers from running while waiting for the lock.

Consider using the asynchronous lock() method instead of lockSync() to avoid blocking the main thread, or document this synchronous blocking behavior and the fact that the warning message won't be printed on macOS/Linux.

Directory get superSystemTempDirectory => super.systemTempDirectory;
}

extension FileSystemLocking on FileSystem {

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.

medium

The public extension FileSystemLocking is missing a documentation comment. According to the repository style guide, all public members should have documentation.

Suggested change
extension FileSystemLocking on FileSystem {
/// Extension on [FileSystem] to support file-based locking.
extension FileSystemLocking on FileSystem {
References
  1. All public members should have documentation. (link)

/// Creates a Swift Package called 'FlutterGeneratedPluginSwiftPackage' that
/// has dependencies on Flutter plugins that are compatible with Swift
/// Package Manager.
Future<void> generatePluginsSwiftPackage(

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.

medium

The documentation comment for the public method generatePluginsSwiftPackage was removed. According to the repository style guide, all public members should have documentation. Please restore the documentation comment.

Suggested change
Future<void> generatePluginsSwiftPackage(
/// Creates a Swift Package called 'FlutterGeneratedPluginSwiftPackage' that
/// has dependencies on Flutter plugins that are compatible with Swift
/// Package Manager.
Future<void> generatePluginsSwiftPackage(
References
  1. All public members should have documentation. (link)

@eyebrowsoffire eyebrowsoffire added the autosubmit Merge PR when tree becomes green via auto submit App label Aug 18, 2026
@auto-submit
auto-submit Bot merged commit e5b61cd into flutter:flutter-3.47-candidate.0 Aug 18, 2026
10 checks passed
@flutteractionsbot
flutteractionsbot deleted the cp-stable-2cb26f7500f7a17e87f00d0f3077f1eccad3ed91 branch August 18, 2026 19:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

a: desktop Running on desktop autosubmit Merge PR when tree becomes green via auto submit App CICD Run CI/CD cp: review Cherry-picks in the review queue platform-macos Building on or for macOS specifically team-ios Owned by iOS platform team team-macos Owned by the macOS platform team tool Affects the "flutter" command-line tool. See also t: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants