Repository navigation
Share build artifacts with Xcode, prefer its bundled build service on 27+ - #18
Open
silentswordfish wants to merge 8 commits into
Open
silentswordfish wants to merge 8 commits into
silentswordfish wants to merge 8 commits into
Conversation
FileHandle.bytes suspends once per byte, so a ~90KB payload (the size of an xcodebuild -showBuildSettings -json dump) took minutes instead of milliseconds. availableData also signals read errors by raising an uncatchable NSFileHandleOperationException instead of a Swift error, so a read failure crashed the process rather than surfacing. Switch to read(upToCount:) on a background queue: chunked reads (verified 90KB in ~0.01s vs >150s before), and read failures now surface as RunError.outputReadFailed instead of either crashing or silently returning truncated output.
sourcekit-xcode-bsp previously always built into a project-local .build/derived-data, duplicating whatever Xcode's own GUI had already built for the same workspace. XcodeDerivedDataResolver asks xcodebuild directly for the DerivedData root (via -list and -showBuildSettings, both -json) rather than reconstructing Xcode's undocumented <Name>-<hash> folder naming, which would silently break on any Xcode change to that scheme. This also means it automatically follows a user's Settings > Locations > Derived Data override, verified live. Not every scheme reports usable build settings -- schemes backed by SPM package products (common with a local Modules/ directory) exit 0 with empty settings -- so candidates are ranked by how likely they are to answer (container-name match, then target-backed, then prefix, then listing order) and probed until one does, bounded by an overall deadline rather than a fixed attempt count. Verified against NetNewsWire (27 schemes, 17 local SPM modules): resolves correctly in ~3s in the common case, and in the worst real case (no exact-match scheme) still resolves well inside the 60s deadline. Critically, the SWBArenaInfo passed to swift-build now writes into the index arena (Index.noindex/Build/...) and only references the regular one (Build/...), matching Xcode's own background indexer. Proved by reconstructing the prior (collapsed-arena) behavior and diffing: it wrote into Xcode's regular-arena build.db under a real build/prepare request (3,231,744 -> 3,493,888 bytes), i.e. shared an llbuild database with the user's own Cmd-B builds. The fix leaves that database byte-identical. Resolution failures (no scheme answers, non-DerivedData build location, timeout) fall back to .build/derived-data as before; the server now logs which of the three sources (buildServer.json config, Xcode's DerivedData, or the fallback) actually won, since the prior silent fallback made a fully broken resolution indistinguishable from a working one.
On Xcode 27+, BuildServiceProviderFactory now points SWBBUILDSERVICE_PATH at the SWBBuildService bundled inside the selected Xcode rather than the SWBBuildServiceBundle pinned to this project's swift-build revision and co-located with the binary. Below Xcode 27, or if Xcode's own build service can't be located, it falls back to the co-located bundle as before. An explicit serviceBundlePath in buildServer.json still wins outright, same as before. Verified end-to-end on Xcode 27.1: a full (not description-only) build succeeds via Xcode's bundled SWBBuildService -- including dependency-target sequencing, Swift/Clang compilation, and linking -- and produces an identical compile error to the pinned bundle on the same fixture, confirming the IPC protocol version between this project's pinned swift-build client and Xcode 27's bundled service is compatible for that path. This keeps the server current with whatever SDKs/toolchains ship in the user's selected Xcode without re-vendoring swift-build on every Xcode release, at the cost of depending on an Apple-internal binary with no compatibility guarantee across Xcode point releases -- serviceBundlePath remains the escape hatch if that ever breaks.
XcodeDerivedDataResolver was previously invoked once per `serve` process launch (not, as originally assumed, on every workspace reload -- that path only re-runs loadWorkspace). Still, paying ~3-6s of xcodebuild subprocess cost on every launch is worth avoiding, and buildServer.json's other fields (workspace, platform, serviceBundlePath) already follow a generate-once, regenerate-if-it- changes model -- live re-resolution for just buildRoot was the inconsistent one. `init` now resolves the DerivedData root once and shows it as the prompt default, so the baked value is visible and overridable rather than invisible. If Xcode's DerivedData location later changes (a different selected Xcode, a custom Derived Data preference, or the project moving), re-running `init` refreshes it -- same as any other field in the file. serve's existing fallback resolution (when buildRoot is absent from the config) is unchanged, covering hand-written or pre-existing configs. Verified on NetNewsWire: server startup with a baked buildRoot dropped from ~9-10s to ~4s, confirmed via the existing "Build root from buildServer.json" log line that the resolver isn't invoked at all in that path.
Previously, resolving Xcode's DerivedData root (an xcodebuild subprocess chain costing ~3-6s) only started after both the workspace and platform prompts returned, even though the workspace path is already known -- via auto-detection -- before either prompt is shown. init now kicks off resolution against the detected default immediately, overlapping its subprocess cost with the time a human spends reading and answering those prompts. If the user types a workspace other than the detected default, the speculative result is discarded and resolution reruns for the corrected path -- no worse than not speculating. Verified with paced input simulating ~4s of human response time: 6.1s -> 4.0s end-to-end on NetNewsWire, with the override path producing the correct (different) DerivedData root. This surfaced a real side effect: cancelling the speculative task mid-flight propagates as SIGTERM to the xcodebuild subprocess, which previously logged a misleading "xcodebuild -list failed" line even though nothing had actually failed. XcodeDerivedDataResolver now suppresses that log specifically when the task was cancelled, while still logging genuine -list failures.
Checked the actual cost first: XcodePathsService.resolve() measures ~3-6ms, nothing like the multi-second DerivedData resolution -- moving it alone saves nothing perceptible. But investigating surfaced a real, independent inefficiency: configureEnvironment() called xcodePaths.resolve() unconditionally, even when an explicit serviceBundlePath was already set and the resolved value would be discarded outright (environmentAssignments' explicit-path branch wins regardless). Fixed that for every caller, not just init-generated configs. For the init-time move itself: buildServer.json's serviceBundlePath field already exists and is already authoritative, so `init` now resolves once whether to prefer Xcode's own bundled build service (same decision BuildServiceProviderFactory makes at every launch) and bakes the result into that field when applicable, mirroring buildRoot. preferredXcodeBundledServiceBundlePath and minimumXcodeVersionForBundledService are now public so this logic lives in one place rather than being duplicated between the factory and InitCommand. This one carries a sharper staleness risk than buildRoot: a stale buildRoot just quietly stops sharing with Xcode, but a baked serviceBundlePath pointing at a since-moved/removed Xcode install can fail the build service outright. Documented in both the doc comments and the README; re-running `init` after switching or reinstalling Xcode is the expected fix, consistent with how the other fields in this file already work. Verified end-to-end on NetNewsWire (Xcode 27): init correctly bakes the bundled SWBBuildService path, and serve launches that exact process (confirmed via ps) using the baked value with no re-resolution.
configureEnvironment() still called xcodePaths.resolve() whenever serviceBundlePath was absent from config -- which is exactly the case for every config predating the previous commit, every hand-written one, and any init generated while on Xcode <27. Those configs would re-derive the same decision on every single serve launch, which is the dynamic-resolution-on-every-startup pattern this whole effort has been removing, just hiding in the fallback branch. Removed it outright: BuildServiceProviderFactory no longer depends on XcodePathsService at all. configureEnvironment() is synchronous now and always passes xcodeBundledServiceBundlePath: nil to environmentAssignments -- InitCommand is the only place that decision gets made, baked into serviceBundlePath when it applies. This does change behavior for the absent-field case: a config without serviceBundlePath baked now always gets the co-located pinned bundle, even on Xcode 27+, until init is re-run. Consistent with the regenerate-when-something-changes model already established for buildRoot, but worth calling out since (unlike buildRoot's fallback, which stayed purely static) this one previously still re-checked Xcode's version dynamically every launch. Verified both outcomes live: a config without serviceBundlePath now spawns the co-located SWBBuildServiceBundle (confirmed via ps) even on this Xcode 27 machine; a config with it baked still spawns Xcode's own bundled service exactly as before.
The previous commit fixed this exact pattern for serviceBundlePath but left it in resolveBuildRoot: whenever buildRoot was absent from config, serve still called XcodeDerivedDataResolver.resolve() on every launch -- the full xcodebuild -list/-showBuildSettings subprocess chain (~3-6s), not even the cheap one. Any config predating this feature, hand-written, or where init's resolution failed would pay that cost on every single startup. Removed it: resolveBuildRoot no longer takes a workspacePath or resolver, isn't async, and never calls XcodeDerivedDataResolver. Absent buildRoot now means .build/derived-data, full stop, same as serviceBundlePath's absent-field behavior. init (XcodeDerivedDataResolver, via InitCommand) is the only place this gets resolved live. Same tradeoff as the serviceBundlePath change: a config without buildRoot baked now always gets the project-local fallback, even if Xcode's DerivedData location would otherwise resolve fine, until init is re-run. Unlike serviceBundlePath's failure mode (hard crash on a stale path), a stale/absent buildRoot here just quietly stops sharing with Xcode -- the softer case, consistent with how this field was already described. Verified live: a config without buildRoot now skips the resolver entirely (confirmed via the existing log line and no behavior regression versus the already-baked case), landing on the same ~4-6s session/workspace-load floor every run hits regardless.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Three related changes, found and verified by testing against a real OSS project (NetNewsWire: 27 schemes, 17 local SPM modules, 89 configured targets), not just the test fixture:
SWBBuildServiceon Xcode 27+ instead of the pinned, co-located bundle. Verified end-to-end: a full (not description-only) build succeeds via Xcode 27.1's bundled service -- compilation, dependency-target sequencing, linking -- and produces an identical compile error to the pinned bundle on the same fixture.serviceBundlePathremains the escape hatch.buildRootwith Xcode's own DerivedData.XcodeDerivedDataResolverasksxcodebuild -list/-showBuildSettings(-json) directly rather than reconstructing Xcode's undocumented<Name>-<hash>folder naming -- verified that approach would've broken under a custom DerivedData location (tested live: it followedSettings > Locations > Derived Dataautomatically). Not every scheme reports usable settings (SPM-package-backed schemes exit 0 with empty settings), so candidates are ranked by likelihood rather than filtered, since target-backing turned out to be sufficient but not necessary for a scheme to work.SWBArenaInfopreviously wrote into Xcode's regular build arena. Proved it with a byte-level diff -- the old code'spreparerequest grew Xcode's realbuild.dbby 262KB under a concurrent request. The fix writes intoIndex.noindex/Build/...(matching Xcode's own background indexer) and leaves the regular arena'sbuild.dbbyte-identical.inittime, rather than on everyservelaunch.buildServer.json's other fields (workspace,platform,serviceBundlePath) already follow a generate-once/regenerate-if-it-changes model; live re-resolution for justbuildRootwas the inconsistent one.initnow resolves once and shows the result as the prompt default, so the baked value is visible rather than invisible. Verified on NetNewsWire: startup with a bakedbuildRootdropped from ~9-10s to ~4s.Along the way, found and fixed a real bug in
ProcessRunner: it drained subprocess pipes one byte at a time, which made the ~90KB payloads from-showBuildSettings -jsontake minutes instead of milliseconds (silently blowing timeouts), and used an API that raises an uncatchable ObjC exception on a read error instead of throwing a Swift one.Start that resolution speculatively as
initbegins, rather than after the workspace/platform prompts return. The workspace path is already known via auto-detection before either prompt shows, so resolution now overlaps its ~3-6s subprocess cost with the time a human spends answering them. Verified with paced input simulating ~4s of human response time: 6.1s -> 4.0s end-to-end on NetNewsWire. Also fixed a misleading log line this surfaced: cancelling the speculative result (when the user types a different workspace) propagates as SIGTERM to the subprocess, which previously logged a false '-list failed' line.Resolve the preferred build service path at init time too. Measured first:
XcodePathsService.resolve()is ~3-6ms, not worth moving for perf alone. But it surfaced a real, independent fix --configureEnvironment()was resolving Xcode's version/path even when an explicitserviceBundlePathalready made that result moot -- fixed for every caller.initnow bakes the resolved bundled-service path intoserviceBundlePathwhen applicable, same mechanism asbuildRoot. Flagged clearly: this one has a sharper staleness risk thanbuildRoot-- a stale baked path can fail the build service outright if Xcode moves/is removed, not just degrade quietly. Verified end-to-end on NetNewsWire:initbakes the bundled path,servelaunches that exact process (confirmed viaps).Removed the remaining dynamic fallback entirely. The previous commit only skipped Xcode version/path resolution when
serviceBundlePathwas already set -- it still re-derived the same decision on everyservelaunch whenever that field was absent (any config predating this feature, hand-written, or generated on Xcode <27).BuildServiceProviderFactoryno longer depends onXcodePathsServiceat all; an absentserviceBundlePathnow always means the co-located pinned bundle, full stop, untilinitis re-run. Verified both outcomes live viaps: a config without the field spawns the co-located bundle even on this Xcode 27 machine; a config with it baked still spawns Xcode's own service exactly as before.Same fix, applied to
resolveBuildRoot. It had the identical pattern, just with the expensive resolver: absentbuildRootstill calledXcodeDerivedDataResolveron everyservelaunch. Removed entirely --resolveBuildRootis synchronous now, takes no workspace/resolver parameters, and an absentbuildRootalways means.build/derived-data, full stop.initis the only place this gets resolved live. Verified: a config withoutbuildRootnow lands on the same ~4-6s session/workspace-load floor every run hits regardless, with zeroxcodebuildsubprocess calls for this specifically.Known limitation (not resolved in this PR)
The index arena is now shared with Xcode's own background indexer, not just with Cmd-B builds. Concurrency testing here was two BSP processes with sub-second
preparecalls -- real but weak evidence. I could not drive Xcode.app's indexer headlessly to soak-test this against a real open Xcode session.Test plan
swift build+swiftlint lintclean on all touched filesprepare(build) succeedsbuild.dbdiff under concurrent access)IDECustomDerivedDataLocation) followed automatically, verified live and restored afterinit-bakedbuildRootverified end-to-end: correct resolved path written,serveskips resolution and reads it directly