Repository navigation
[CP-stable][Tool] Fix SwiftPM race condition during parallel Xcode builds - #191120
Conversation
…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
|
@bkonyi please fill out the PR description above, afterwards the release team will review this request. |
|
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. |
There was a problem hiding this comment.
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.
| 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)); | ||
| } | ||
| } |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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:
- 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).
- 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 { |
There was a problem hiding this comment.
The public extension FileSystemLocking is missing a documentation comment. According to the repository style guide, all public members should have documentation.
| extension FileSystemLocking on FileSystem { | |
| /// Extension on [FileSystem] to support file-based locking. | |
| extension FileSystemLocking on FileSystem { |
References
- 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( |
There was a problem hiding this comment.
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.
| 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
- All public members should have documentation. (link)
e5b61cd
into
flutter:flutter-3.47-candidate.0
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) orPathExistsException. 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:
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?
Test Coverage:
Are you confident that your fix is well-tested by automated tests?
Validation Steps:
What are the steps to validate that this fix works?
FileSystemExceptionorPathExistsExceptioninephemeral/Packages.