Skip to content

Share build artifacts with Xcode, prefer its bundled build service on 27+ - #18

Open
silentswordfish wants to merge 8 commits into
mainfrom
xcode27-derived-data-sharing
Open

silentswordfish wants to merge 8 commits into
mainfrom
xcode27-derived-data-sharing

Conversation

@silentswordfish

@silentswordfish silentswordfish commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Prefer Xcode's own bundled SWBBuildService on 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. serviceBundlePath remains the escape hatch.
  • Share buildRoot with Xcode's own DerivedData. XcodeDerivedDataResolver asks xcodebuild -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 followed Settings > Locations > Derived Data automatically). 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.
  • Fixed a real arena collision found via this testing: the SWBArenaInfo previously wrote into Xcode's regular build arena. Proved it with a byte-level diff -- the old code's prepare request grew Xcode's real build.db by 262KB under a concurrent request. The fix writes into Index.noindex/Build/... (matching Xcode's own background indexer) and leaves the regular arena's build.db byte-identical.
  • Resolve the DerivedData root once, at init time, rather than on every serve launch. 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 once and shows the result as the prompt default, so the baked value is visible rather than invisible. Verified on NetNewsWire: startup with a baked buildRoot dropped 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 -json take 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 init begins, 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 explicit serviceBundlePath already made that result moot -- fixed for every caller. init now bakes the resolved bundled-service path into serviceBundlePath when applicable, same mechanism as buildRoot. Flagged clearly: this one has a sharper staleness risk than buildRoot -- 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: init bakes the bundled path, serve launches that exact process (confirmed via ps).

  • Removed the remaining dynamic fallback entirely. The previous commit only skipped Xcode version/path resolution when serviceBundlePath was already set -- it still re-derived the same decision on every serve launch whenever that field was absent (any config predating this feature, hand-written, or generated on Xcode <27). BuildServiceProviderFactory no longer depends on XcodePathsService at all; an absent serviceBundlePath now always means the co-located pinned bundle, full stop, until init is re-run. Verified both outcomes live via ps: 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: absent buildRoot still called XcodeDerivedDataResolver on every serve launch. Removed entirely -- resolveBuildRoot is synchronous now, takes no workspace/resolver parameters, and an absent buildRoot always means .build/derived-data, full stop. init is the only place this gets resolved live. Verified: a config without buildRoot now lands on the same ~4-6s session/workspace-load floor every run hits regardless, with zero xcodebuild subprocess 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 prepare calls -- 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

  • 76 unit tests (14 suites), including new coverage for candidate ranking, arena paths, and chunked/failing pipe reads
  • swift build + swiftlint lint clean on all touched files
  • End-to-end on NetNewsWire: correct DerivedData root, 89 targets, full build graph generation, real prepare (build) succeeds
  • Byte-level proof of the arena fix (before/after build.db diff under concurrent access)
  • Custom DerivedData location (IDECustomDerivedDataLocation) followed automatically, verified live and restored after
  • init-baked buildRoot verified end-to-end: correct resolved path written, serve skips resolution and reads it directly
  • Real soak test with Xcode.app open and indexing concurrently (not done -- see limitation above)

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant