fixes for Swift 6 and threading concerns

This commit is contained in:
2026-06-02 12:09:44 -07:00
parent 2fa4bfd45e
commit 6d3a0930a1
327 changed files with 1596 additions and 199 deletions
+210
View File
@@ -226,6 +226,216 @@ Full details in `docs/01-completed-working-order.md`.
Phases ordered by dependency and value/effort. Each phase needs tests before moving on.
### Phase 201 — Swift 6 main-actor isolation for `Synthesizer` (zero-annotation consumer subclassing)
**Goal.** A consumer building under Xcode 26's default
`SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` must be able to subclass
`SynthesizerBase` with **no concurrency annotations**:
```swift
import LyrebirdSynth
final class ToneSynth: SynthesizerBase { // no nonisolated, no @preconcurrency
@UIParam var freq: Double = 440
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
```
This must hold for the **core package, Quartet (local-path reference), and Test
(remote gitea reference)** simultaneously — those three are the acceptance gate.
**Problem (reproduced).** Core compiles in Swift 5 language mode, so
`SynthesizerBase.build()` / `init()` are *nonisolated*. A consumer whose project
defaults to `@MainActor` makes its subclass's `build()`/`init()` main-actor
isolated → **"main actor-isolated method has different actor isolation from
nonisolated overridden declaration."** Today's only workarounds live on the
consumer (`nonisolated override func build()`, `@preconcurrency`,
`nonisolated override init()`) — exactly what we will not ship. Verified: no
core annotation that keeps `build` nonisolated fixes it (the consumer's own
default-isolation governs its own override declaration). The fix is to make the
*language-side* surface of `Synthesizer` **main-actor isolated** so the
consumer's MainActor default *matches* instead of conflicts, while the single
RT entry point (`evaluate`) stays `nonisolated`.
**Isolation split — the core design.** `Synthesizer` has exactly one RT-thread
entry point; everything else is language-side (main thread):
| Member | Thread | Phase 201 isolation |
|---|---|---|
| `build()` | main (called once at add) | `@MainActor` |
| `release(engine:)` | main only (doc-stated) | `@MainActor` |
| `free(engine:)` | main only (doc-stated) | `@MainActor` |
| `evaluate(graph:count:)` | **RT render thread** | **`nonisolated`** |
| `@LiveParam` / `@UIParam` setters | main / atomic store | inherit main; atomic store is already cross-thread-safe |
`evaluate()` reads only two members: `parameterTable` (immutable `let`) and
`outputGenerators` (`var`, written in `build()` on main, read on RT after the
add-event barrier). Both are touched cross-thread **safely today** via the
engine's existing scheduling contract (the add event is applied on the RT thread
only after `build()` has fully returned on main — a happens-before edge through
the SPSC `pendingQueue`). Phase 201 makes that contract explicit to the compiler
with `nonisolated(unsafe)` on exactly those two stored properties, with a
comment citing the barrier. No new runtime synchronisation is added — the safety
argument is the one already in `ARCHITECTURE.md` §2/§9.
**Plan of work.**
1. **Protocol (`Synthesizer.swift`).** Annotate the protocol so language-side
requirements are `@MainActor` and `evaluate` is `nonisolated`. Options to
evaluate during implementation (pick whichever the compiler accepts most
cleanly): `@MainActor protocol Synthesizer` with `nonisolated func
evaluate(...)`, vs. per-requirement isolation. Update the default-extension
implementations (`evaluate` no-op, `release` throws, `free`) to match.
2. **`SynthesizerBase.swift`.** Mark the class `@MainActor`. Mark
`evaluate(graph:count:)` `nonisolated final`. Mark `parameterTable` and
`outputGenerators` `nonisolated(unsafe)` (the only state `evaluate` reads),
each with a `// RT-read after add-barrier; see ARCHITECTURE.md §9` comment.
Confirm `@LiveParam`/`@UIParam` wrapper-backed properties still compile (the
earlier whole-class-`nonisolated` experiment failed *because* wrappers reject
`nonisolated`; `@MainActor` does not have that problem — verify).
3. **`Group` / `ParallelGroup` (`NodeTree/`).** Both conform to `Synthesizer`
and call `evaluate` on the RT thread. Apply the same split: `build`/`release`/
`free` main-actor, `evaluate` `nonisolated`. `ParallelGroup.evaluate` uses
`concurrentPerform` over children — confirm the child `evaluate` calls remain
`nonisolated` end-to-end (no hop).
4. **Engine call sites.** `SynthesisEngine.processBlock` → `rootGroup.evaluate`
runs on the RT thread and must reach `evaluate` with no actor hop. Verify the
whole RT call chain (`processBlock` → `Group.evaluate` →
`synth.evaluate` → `Generator.calculatedSamples`) is `nonisolated`. The
engine itself is not an actor; ensure nothing forces a `MainActor.assumeIsolated`
or `await` onto the RT path (that would be a correctness/perf regression — a
hard fail for this phase).
5. **Other in-core conformers.** Audit the conformers that implement
`Synthesizer` directly rather than via `SynthesizerBase` (e.g. `VoicePool`,
AUv3 `LyrebirdAudioUnit` / `LyrebirdAUVoicePoolBinding`, any others surfaced
by `grep ": Synthesizer"`). Each needs the same `evaluate`-nonisolated split.
AUv3 is the riskiest (its render block is already a separate isolation
domain) — give it explicit attention.
6. **Language-mode decision.** Determine whether the core `LyrebirdSynth` target
should move to `.swiftLanguageMode(.v6)` (so the isolation is baked into the
module's binary interface and propagates to consumers regardless of their
mode) or stay `.v5` with explicit annotations. Prefer keeping `.v5` if
explicit `@MainActor`/`nonisolated` annotations suffice — a full v6 migration
of the whole module is a much larger lift and out of scope unless required to
make the consumer experience clean. **Spike this first** — it determines the
size of the rest of the phase.
7. **`LyrebirdUI`.** Currently `.v5` to dodge SwiftUI/AppKit actor diagnostics.
`@UIParam` lives here. Confirm the isolation split doesn't force a `.v6`
migration of `LyrebirdUI`; if `@UIParam`-bearing synths need anything, capture
it.
**Acceptance criteria (all three must pass with NO consumer-side concurrency
annotations):**
- **Core:** `swift test --no-parallel` green; `(cd LiveCompile && swift test
--no-parallel)` 34/34. RT path verified to have no actor hop (inspect, and
confirm no perf regression on the core synthesis benchmark).
- **Quartet** (local-path ref): builds + runs; its `SynthesizerBase` subclasses
carry no `nonisolated`/`@preconcurrency`. Remove any such annotations Quartet
currently has and confirm it still builds.
- **Test** (remote gitea ref, Xcode-26 `MainActor` default): the plain
`final class ToneSynth: SynthesizerBase { override func build() {…} }` builds
and runs with zero annotations. Revert the `@preconcurrency` /
`nonisolated override init` / `nonisolated override func build` that
Claude-in-Xcode added.
- A **regression fixture**: an SPM consumer target built with
`-default-isolation MainActor` + `.swiftLanguageMode(.v6)` (the repro from
the Phase-201 investigation) compiles an unannotated `SynthesizerBase`
subclass. Keep this as a committed smoke test so the guarantee doesn't silently
regress.
**Risks / watch-items.**
- `nonisolated(unsafe)` is a promise to the compiler — the `/lyrebird_review`
RT-safety pass must explicitly bless the two properties it lands on, citing the
add-barrier. Do not broaden it beyond `parameterTable` + `outputGenerators`
without re-justifying.
- If the protocol-level `@MainActor` forces awaits onto any existing internal
call site that currently runs sync on a background queue (routines, NRT batch),
that's in-scope to fix — those are language-side and can be `@MainActor` or
explicitly hopped, but must not touch the RT path.
- Docs: once landed, update `GettingStarted.md` / `INSTALLATION_AND_USAGE.md` to
show the clean zero-annotation subclass as *the* pattern, and drop the
interim "use `nonisolated final class`" guidance if it was added.
**Branch:** `phase-201-mainactor-isolation` off `main`. Standard phase
checklist + `/lyrebird_review` before merge. After merge, re-snapshot to gitea
and re-tag (the gitea 1.0.0 is unreleased, so it can absorb this).
**Investigation notes (from the session that wrote this plan — don't re-run these).**
*Exact failure (reproduced).* Consumer error under Xcode 26 MainActor default:
```
error: main actor-isolated instance method 'build()' has different actor isolation
from nonisolated overridden declaration
error: main actor-isolated initializer 'init()' has different actor isolation
from nonisolated overridden declaration
```
Source: `SynthesizerBase.build()` / `init()` are nonisolated (core is Swift 5
mode); consumer's project default makes the *subclass's* override `@MainActor`;
override-vs-base isolation mismatch.
*Reproduction recipe (use verbatim as the Phase 201 regression fixture).* A
throwaway SPM consumer at `/tmp`, depending on the package via local path:
```swift
// Package.swift target settings that reproduce Xcode 26's new-project default:
swiftSettings: [
.swiftLanguageMode(.v6),
.unsafeFlags(["-default-isolation", "MainActor"]),
]
```
```swift
// Sources/App/main.swift — the unannotated subclass that MUST compile post-201:
import LyrebirdSynth
final class ToneSynth: SynthesizerBase {
override func build() { output(bus: 0, source: OscSin.Audio(freq: 440) * 0.2) }
}
let s = ToneSynth(); print("ok \(s)")
```
Note: `.defaultIsolation(MainActor.self)` in the manifest is **unavailable** in
this SwiftPM toolchain (`error: 'defaultIsolation' is unavailable`) — must use
the raw `-default-isolation MainActor` unsafeFlag as above.
*Approaches already tried and RULED OUT (don't repeat):*
1. `nonisolated` on base `init()` + `build()` — **fails.** Consumer's override
still gets `@MainActor` from its own project default; mismatch persists. (The
error even confirms the base is "nonisolated" — proving the problem is the
consumer side, not the base.)
2. `nonisolated` on the **class** declaration (`open nonisolated class
SynthesizerBase`) — **fails to compile core**: `'nonisolated' is not
supported on properties with property wrappers` (the `@LiveParam`/`@UIParam`
stored properties). Whole-class `nonisolated` is a dead end.
3. `nonisolated` on the **protocol requirement** (`Synthesizer.build`) + base —
**fails the same way** as (1).
4. `@MainActor` on the class + `nonisolated final func evaluate(...)` — **right
direction, but surfaced the real work**: 9 errors, all from `evaluate()`
reading `parameterTable` and `outputGenerators` from a nonisolated context
while the class is MainActor (`#ConformanceIsolation` + "main actor-isolated
property can not be referenced from a nonisolated context"). This is exactly
why the plan lands `nonisolated(unsafe)` on those **two** properties — they
are the entire RT-read surface of `evaluate()`. Nothing else in the class is
read on the RT thread.
*Verified-working interim (NOT what we ship, but proves the seam):* the consumer
single-annotation form `nonisolated final class ToneSynth: SynthesizerBase { … }`
compiles cleanly (`Build complete`). Confirms one annotation on the *type* is
enough — Phase 201's job is to move that necessity into the core so the consumer
needs zero.
*RT-read surface (confirmed by reading `evaluate()`):* `evaluate(graph:count:)`
references exactly `parameterTable` (immutable `let`) and `outputGenerators`
(`var`, written in `build()` on main, read on RT). No other stored property is
touched on the RT thread. The `nonisolated(unsafe)` blast radius is precisely
these two.
### Phase 104 — AUv3 Plugin Export
Ship a `SynthesizerBase` subclass as an AudioUnit v3 (.appex) plugin loadable
+76
View File
@@ -9852,3 +9852,79 @@ commits total; one session.
- `8fb88e0` Phase 198.8-198.10: drop dead .duplicateDevice case, add F11 TODO, delete POST_197_FIXES.md
- `216650a` Phase 198 review fix: Task.isCancelled guard for build-thrown CancellationError + regression test
- `84961ae` Phase 198 re-review nits: rethrow caught CancellationError, robust >= 1 result count, onTermination comment
---
## Phase 203 — `LiveCompile` UI to Swift 6 language mode
**Goal.** Flip the last two `.swiftLanguageMode(.v5)` pins in the repo —
`LyrebirdLiveCompileUI` and `LyrebirdLiveCompileUITests` in
`LiveCompile/Package.swift` — to Swift 6 language mode, so the entire codebase
(core + UI + CLI + LiveCompile + tests + the regression-fixture consumer) is
uniformly v6 and can track Swift 7/8+. This is the only target left on `.v5`
after Phase 202; unlike `LyrebirdUI`/`LyrebirdCLI` (pure caution, flipped with
zero changes in 202), this one has a real — but small — concurrency issue.
**The one real error (spiked + confirmed).** At v6 the only build error is:
```
LyrebirdScratchModel.swift:149:31: error: sending 'self.session' risks causing
data races [#SendingRisksDataRace]
```
`LyrebirdScratchModel` is `@MainActor` (an `ObservableObject`); its
`run(additive:)` calls `await session.compileAndRunAsync(...)`. `LiveSession` is
a plain non-`Sendable` `final class`, so passing it into the `nonisolated async`
method from the main actor (where it is also retained) is flagged as a send race.
**The fix (minimal, spiked → 0 errors).** Mark `LiveSession` `@unchecked
Sendable`. It is already thread-safe by construction:
- `engine` + all `-I`/`-L`/`-l`/`rpath` config are immutable `let`.
- The only mutable graph state (`trackedSynths`, `loadedSnippets`) is guarded by
`trackingLock: NSLock` at every access (`track`, `clearTracked`,
`trackedSynthCount`, `runEntry`).
- `reportedSampleRate` / `lastSnippetMessage` are test-only side channels written
from the single in-flight snippet entry (documented one-invocation-at-a-time
precondition).
Spike: `LiveSession: @unchecked Sendable` + flipping both UI targets to v6 →
`swift build --build-tests` reports **0 errors** for the `LiveCompile` sub-package.
**Plan of work.**
1. **`LiveSession.swift`** — add `: @unchecked Sendable` to the class with a doc
block justifying it (immutable config + lock-guarded mutable state). Tighten
the two test-only side-channel `var`s: either guard them under `trackingLock`
too, or mark them clearly single-writer/test-only so the `@unchecked` promise
is fully accurate (decide during implementation — guarding is cheap and
removes the only unprotected `var`s).
2. **`LiveCompile/Package.swift`** — remove `.swiftLanguageMode(.v5)` from
`LyrebirdLiveCompileUI` and `LyrebirdLiveCompileUITests` (drop the trailing
comma on the preceding `path:` line, as in the Phase 202 flips).
3. **Verify snippet runtime threading.** `compileAndRunAsync` is `nonisolated`:
it compiles off-main via `Task.detached`, then resumes on the generic
executor (NOT the caller's main actor) to call `runEntry` → the snippet's
`context.play(...)`. `SnippetContext.play` is `@MainActor` (Phase 201).
Confirm a live snippet still adds synths correctly post-flip — either the
snippet path already hops correctly, or `runEntry`/`play` needs the
`lyrebirdRunMainActorMutation` bridge treatment. **Check this at runtime, not
just at compile time** (the doc comment claims "snippet entry executes on the
caller's actor" — verify that claim holds, since a `nonisolated async` method
does not resume on the caller's actor).
4. **Docs.** `LiveCompile/.../LiveCoding.md` and any LiveCompile README — drop
`.v5` mentions if present (none found in a quick grep, but recheck).
**Acceptance.**
- `(cd LiveCompile && swift build)` and `(cd LiveCompile && swift test)` green at
v6 (current baseline: 36/36).
- A live-compiled snippet that calls `context.play(_:)` actually adds and renders
a synth (manual run of `LyrebirdScratchDemo`, or an integration test in
`LyrebirdLiveCompileTests` that drives `compileAndRunAsync` and asserts
`trackedSynthCount` increments).
- `grep -rn "swiftLanguageMode(.v5)"` across the repo (excl. `legacy/`,
`.build/`) returns **zero** hits.
**Effort.** Small — likely a single-commit phase (one `@unchecked Sendable` line +
optional lock tidy + 2 Package.swift edits + a runtime-verification test). The
only open risk is item 3 (snippet `@MainActor play` from the off-main resume),
which the runtime check resolves.
**Branch:** `phase-203-livecompile-swift6` off `main`. Standard checklist +
`/lyrebird_review` before merge.
+4 -4
View File
@@ -30,7 +30,7 @@ Optional GUI module. Import alongside `Lyrebird` when you need parameter control
import LyrebirdUI
```
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Uses Swift 5 language mode to avoid actor-isolation diagnostics in SwiftUI/AppKit interop.
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode (Phase 202).
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
@@ -49,7 +49,7 @@ lyrebird export MySynth # generate a SynthesizerBase template
lyrebird repl # start Swift REPL with Lyrebird importable
```
Provides an interactive `lyrebird>` shell (via LineNoise) with history and tab completion. Uses Swift 5 language mode — LineNoise predates Swift 6 concurrency annotations.
Provides an interactive `lyrebird>` shell (via LineNoise) with history and tab completion. Builds under Swift 6 language mode (Phase 202).
See [cli-guide.md](cli-guide.md) for a full walkthrough.
@@ -110,12 +110,12 @@ swift test
```
LyrebirdC
└── Lyrebird (links CoreAudio, AudioToolbox, Accelerate)
├── LyrebirdUI (SwiftUI + AppKit, Swift 5 mode)
├── LyrebirdUI (SwiftUI + AppKit)
├── LyrebirdDemo
├── LyrebirdBenchmark
└── LyrebirdUIDemo (also links LyrebirdUI)
LyrebirdCLI (links LineNoise, Swift 5 mode)
LyrebirdCLI (links LineNoise)
```
---
+4 -3
View File
@@ -294,9 +294,10 @@ Sources/
└── ParameterLabel.swift
```
`LyrebirdUI` uses `.swiftLanguageMode(.v5)` — the same rationale as `LyrebirdCLI` —
to avoid Swift 6 actor-isolation diagnostics in SwiftUI/AppKit interop until the
concurrency model for UI is fully audited.
`LyrebirdUI` builds under Swift 6 language mode (Phase 202) — cleanly, with no
actor-isolation diagnostics. The earlier `.swiftLanguageMode(.v5)` pin was removed once
the core `Synthesizer` isolation surface landed (Phase 201); the SwiftUI/AppKit interop
needed no special handling.
---