Split the Swift package into one library per service

Merged
JE
1d ago
+4088-231

An app that imported the Swift SDK linked all 58 services, whatever it called. A one-call iOS app (Release, generic iOS, Xcode 27.2) was 4,380 KB, of which 4,120 KB was the Basecamp module.

Root cause, measured from the linker map: Swift marks every public symbol no_dead_strip, and the type and protocol-conformance records keep every model's Codable witnesses and every service's vtable alive. Dead stripping removed 12.5 KB of the module. Models were 2.95 MB of it (1.7 MB Codable), services 0.55 MB. -internalize-at-link only reached 3.88 MB, and it and -conditional-runtime-records both need unsafeFlags, which SwiftPM refuses for version-pinned dependencies. Inside a module nothing is strippable, so the module boundary is the lever.

What changes

  • Targets. BasecampCore holds the client, transport, errors, pagination, BaseService, and every model that two or more services (or none) reach. Each service gets a Basecamp<Service> target and product: the service, its options, its account.<service> accessor, and the models only it reaches. BasecampMentions and BasecampRecordingSummaries hold the composites that call several services. Basecamp is the umbrella and re-exports all of them, so import Basecamp code is unchanged apart from the renames.
  • Placement is generated. Files stay under swift/Sources/Basecamp. The generator places every file in exactly one target (swift/Sources/BasecampGenerator/TargetPlan.swift) and writes the table into a marked block in both Package.swift files. The manifests compute each target's excludes, so SwiftPM reports no unhandled files. check-swift-service-drift.sh now regenerates the manifest tables too.
  • Renames (Swift only). Calendar becomes BasecampCalendar and Notification becomes BasecampNotification. Both were ambiguous with Foundation's types in any file importing both. The old names are @available(*, unavailable, renamed:) aliases in the umbrella. A deprecated alias would still take part in lookup and keep the ambiguity. The unavailable alias breaks only code that meant Basecamp's type, and gives a fix-it. BasecampPublicAPIConsumer/NameCollisions.swift compiles bare Foundation Calendar/Notification and Basecamp.Ping against app-declared types.
  • BasecampDynamic is the umbrella as a dynamic framework, for apps whose extensions also use the SDK.
  • Size budget. make swift-size-check, run in the Swift CI job, builds swift/SizeBudget's one-call app for iOS. It fails when the app grows past its budget in swift/SizeBudget/budget.json. Budgets are kept per Xcode major, because the same sources link to different sizes under each toolchain: 734,624 bytes on Xcode 27.2 and 1,524,640 on CI's Xcode 16.4. Each budget is about 10% over the measurement. An Xcode major with no budget recorded fails and prints the measurement to record. A change that moves a service's models into core shows up as growth.
  • Hand-written code across targets. BasecampClient.campfireIndex moves out of core into a per-client ClientStorage, with an extension in CampfireIndex.swift. internal becomes package where another target needs a declaration: ZeroPerson, decodePeople*, BaseService.decoding/pathSegment, Metadata, queryString, goWhitespace. Tests import @testable BasecampCore plus the composite modules they exercise.
  • Scripts. sync-doc-constants.rb and check-service-inventory-parity read Swift's accessors from Generated/Accessors/ (one file per service) instead of AccountClient+Services.swift. Their self-tests are updated.

Measurements

Same harness before and after: Release, generic iOS, Xcode 27.2, linked executable size.

AppBeforeAfter
empty, no SDK67 KB67 KB
one call, import BasecampBookmarks4,380 KB735 KB
directory + to-dos + bookmarks (BasecampProjects, BasecampTodos, BasecampBookmarks)4,380 KB861 KB
one call via the umbrella / every service4,380 KB3,533 KB
one call via BasecampDynamicn/a69 KB executable + 3,912 KB framework

The one-call app, import BasecampBookmarks, on both toolchains:

ToolchainBefore (one Basecamp module)AfterBudget
Xcode 27.2 (measured here)4,380 KB735 KB (734,624 B), 17% of before820,000 B
Xcode 16.4 (CI's macos-15)not measured: no Xcode 16 here, and CI only builds the split package1,525 KB (1,524,640 B), 35% of the 27.2 baseline1,680,000 B

Xcode 16.4 links the same sources to about twice the size 27.2 does, so its row is not a like-for-like before/after. The comparison with the 4,380 KB baseline holds on 27.2.

Lane M's 6.18 MB figure was measured against a merge of several in-flight branches, so it isn't comparable to the main-based numbers above.

Not done here

  • Placing shared models in an owner target instead of core (option B) would take roughly another 250 KB off the smallest apps. Core is 650 KB of the 735, 347 KB of it models. Deferred.
  • Composite dependencies are over-approximated. They come from a token scan of class names and .accessor uses, so they may include a service a composite doesn't call. That costs size only for apps that use summarize.
  • One stale prose mention. spec/doc-constants.json still names AccountClient+Services.swift in its rationale. It is left alone because a spec/ change triggers a release.
  • CI's toolchain is older than the one I measured on. The Swift job runs Xcode 16.4 on macos-15; I probed and measured on Xcode 27.2. On 16.4 the build and tests pass, which covers the shared-path targets and the unavailable-alias lookup in NameCollisions.swift. Sizes for both toolchains are in the table above.

Outside review (dual-model, on a42ac9a9)

Fixed, each with a test that failed first where one could:

  • The placement scan stripped comments before strings. So "https://…" hid the rest of its line, and a string interpolation hid the model it named. It is now one left-to-right pass that keeps code inside interpolations (codeOnly in TargetPlan.swift); TargetPlanTests has three new cases. The committed placement did not change.
  • Composite dependency discovery saw .accessor tokens inside strings and block comments. It now uses the same pass.
  • Two services claiming one hand-written file trapped. That case now throws. A composite listing BasecampCore explicitly no longer duplicates the dependency.
  • BasecampMentions and BasecampRecordingSummaries did not re-export BasecampCore or the service they extend, so a file importing only one of them could not name BasecampClient or Person. They now re-export both. The new non-test target BasecampCompositeConsumer compiles against each module alone.
  • A non-integer budget made the size gate's -gt error out, and the gate passed. Every budget must now be a positive integer.
  • The core-closure test passed even with the closure pass removed. It now pins a model to core through a core source, so only the closure pass moves the model it names.
  • A new test covers the Campfire index across forAccount wrappers (shared) and across clients (separate).
  • Smaller fixes:
    • the MIGRATING and Umbrella.swift text on when the fix-it appears;
    • a README note not to mix BasecampDynamic with static products;
    • swift/SizeBudget build output added to .gitignore;
    • Dir.children instead of Dir.glob in sync-doc-constants.rb;
    • swiftTypeName in ServiceEmitter's last fallback. That fallback is unreachable with today's spec, so it has no test.

Declined:

  • A generator run with only --output pointing at a scratch directory fails. That refusal is intended: placing files needs the hand-written sources. The error says to pass --sources, and the Makefile and the drift check both pass it.
  • Multi-file fixtures for the accessor self-tests of sync-doc-constants.rb and the parity check. Both gates run on every PR against the real 58-file Generated/Accessors/, which already exercises the multi-file case.
  • Composite discovery ignores *Options and *Result types. A missed dependency fails swift build, so the gap cannot ship silently.

Outside review, second pass (on b950d4d6)

Fixed, each with a test that failed first:

  • The scanner misread a one-line raw string like #"""# as a multi-line string, which hid the rest of the file. """ now opens a multi-line string only when nothing but whitespace follows it on its line.
  • A generator run with only --output set took the parent of --output as the source root, so a scratch output under /tmp walked all of /tmp. --sources now defaults to Sources/Basecamp, matching --output's own default. The walk also skips an output directory that sits inside the root. This answers the first pass's --output-only finding too: a scratch run from swift/ now succeeds and leaves both manifests byte-identical.
  • The composite consumer imported BasecampMentions only through BasecampRecordingSummaries. It is now two targets. BasecampMentionsConsumer depends only on BasecampMentions and also calls createWithMentions. BasecampRecordingSummariesConsumer depends only on BasecampRecordingSummaries. PublicInitCoverageTests holds three things for both: plain imports of the one module, a plain .target, and that single dependency.

Declined:

  • "Recording summaries depend on BasecampMentions only for goWhitespace." Not so: summarize calls Mentions.personIds(in:) to fill mentionedPersonIds (RecordingsServiceExtensions.swift, the chat-line and projection paths). Moving goWhitespace into core would not remove the dependency. Putting the mention parser in its own target would let summaries drop BasecampPeople and the comment composites; it already depends on BasecampComments. That is a small size change for summarize-only apps, so I left it for later.
  • The size gate passes if OneOperation stops calling the SDK. That takes a deliberate edit to the harness, and the edit is reviewed like any other diff. The gate guards against placement drift, not against harness edits.
  • No check catches deleting the root BasecampDynamic product. That deletion is a visible diff in a hand-written manifest.
  • Some helpers widened to package have no caller outside core. package is invisible outside this package, so nothing public changes. Narrowing them is churn for no consumer.
  • Composite discovery matches any .accessor token, whatever its receiver. This over-approximation is already documented above. It can only add a dependency, which costs size for summarize users and never breaks the build.

Outside review, third pass (on 9eab459b)

No high-severity findings. Fixed in the last push, each with a test that failed first:

  • Two schemas emitting one Swift name are now refused. If a BasecampCalendar schema were added beside Calendar, the generator used to keep only the later model and write one file, silently. It now stops before deleting or writing anything and names both schemas. ModelRegistry compares names, and compares paths case-insensitively. This retracts my second-pass decline, which wrongly assumed swift build would catch it.
  • SPEC §18 rule 5 and Appendix F's Swift row now name the Swift composite targets. The text said "same-module extension"; it now names the targets TargetPlan.swift declares (BasecampMentions, BasecampRecordingSummaries). TargetPlanTests checks that rule 5 names every declared composite.
  • handWrittenSources now resolves symlinks before comparing the root and output paths, so /tmp vs /private/tmp no longer matters.
  • The composite-consumer import guard now sees access-modified and attributed imports, such as internal import X and @preconcurrency public import X.
  • The size check's judging half is scripts/swift-size-verdict.rb. It reads the size with Ruby's File.size rather than stat -f and refuses an empty binary. scripts/test-swift-size-verdict.rb tests it with no Xcode needed: a float or string budget, a missing major, an empty binary, over budget, and a GNU stat first on PATH. make swift-size-check runs that self-test first.

Declined:

  • The size gate measures only the executable, so a dynamically linked BasecampBookmarks would shrink it. Making that product dynamic is a visible edit to a hand-written manifest.
  • The planner does not scan generated accessor bodies or generated core files. Accessors name only their own service class, and Metadata and QueryString name no models. A core file naming a service's model fails swift build.
  • Products removed from the root manifest, and multi-file fixtures for the accessor self-tests. Both re-raise declines from the earlier passes, with nothing new.

The full dual review was not re-run after this push. Its findings fell each pass, and this pass had no high-severity ones. Anything that surfaces later becomes a follow-up, not another push on this PR.

#1151 (service protocols) is compatible: each protocol and its conformance land in the service's own target. The budget gets re-measured once #1151 lands.