Files
Lyrebird/docs/engine/multi-engine-host.md

319 lines
17 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# EngineHost — Multi-Engine Facade
Creation-owning facade for processes that need **two or more** `SynthesisEngine` instances.
Single-engine code does **not** use the host. Direct `SynthesisEngine()` construction remains the supported path for N = 1. The host adds nothing for the single-engine case that the `EngineLifecycleCoordinator` registry does not already provide.
---
## When to use the host
- **NRT batch render** — render N audio files in parallel, one engine per file. Use `renderConcurrent(jobs:)`.
- **Multi-device RT output** — drive two separate audio devices (e.g. headphone + main + sub) from one process, one engine per AUHAL device.
- **Auxiliary engines** — analysis-only side engines, decoder side-chains, scope taps that should be lifecycle-managed with the rest of the process.
- **Test fixtures** — wrap a small set of engines for unified start/stop in integration tests.
If your process uses one engine throughout, do not introduce the host. The direct constructor + binding APIs cover the single-engine case.
---
## Role-based registration
Every engine the host manages carries a `EngineHostRole`:
```swift
public enum EngineHostRole: Hashable, Sendable {
case nrtRender(slot: Int)
case rtOutput(deviceID: UInt32)
case auxiliary(name: String)
case custom(String)
}
```
| Case | Purpose | Uniqueness enforcement |
|---|---|---|
| `.nrtRender(slot:)` | NRT batch render slot | Role-identity (slot index) |
| `.rtOutput(deviceID:)` | Realtime AUHAL output | Role-identity + per-device |
| `.auxiliary(name:)` | Non-output engine | Role-identity (name string) |
| `.custom(String)` | Escape hatch | Role-identity (string) |
The host throws `EngineHostError.duplicateRole(role)` on any second registration under the same role. For `.rtOutput(deviceID:)`, same deviceID implies the same role (deviceID is part of the role's `Hashable` key), so duplicate device registration surfaces as `.duplicateRole`. AUHAL grants exclusive ownership per output device on macOS — the host's role-keyed registry enforces this at the API. (There is no separate `.duplicateDevice` enum case — it would be unreachable given the role-keyed design; re-add one only if a future role shape ever cross-cuts deviceID under a different surrounding case.)
**`.rtOutput.deviceID` semantics.** On macOS the `UInt32` is the raw bit pattern of `CoreAudio.AudioDeviceID`. On iOS the type carries no native meaning (RemoteIO does not address individual hardware devices — `AVAudioSession` routes are chosen at the session layer). Pass `0` for the default iOS route, or any caller-defined unique value if you want host-level uniqueness checks against other RT engines.
---
## Creation: `makeEngine(role:config:)`
```swift
let host = EngineHost()
let cfg = SynthesisEngineConfig(
blockSize: 256,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let engine = try host.makeEngine(role: .rtOutput(deviceID: 0), config: cfg)
```
`SynthesisEngineConfig` mirrors `SynthesisEngine.init` one-for-one with the same defaults. It is a value-typed carrier so callers don't thread eight parameters through every `makeEngine` call.
The returned engine is held strongly by the host. Caller may keep its own reference but the host's strong reference is the primary owner.
---
## Lookup
```swift
let engine: SynthesisEngine? = host.engine(for: .nrtRender(slot: 0))
let role: EngineHostRole? = host.role(for: someEngine)
let all: [SynthesisEngine] = host.engines // snapshot, unordered
let allRoles: [EngineHostRole] = host.roles
let n: Int = host.engineCount
```
All accessors hold the host's internal `NSLock` briefly; snapshots return arrays so callers can iterate without holding any lock.
---
## Lifecycle: `startAll()` / `stopAll()`
```swift
try host.startAll()
defer { host.stopAll() }
```
`startAll()` walks the registered engines from a snapshot taken under the host's lock, then calls `engine.start()` on each **outside the lock**. Concurrent host accessors (`engine(for:)`, `engineCount`, other `makeEngine` / `adopt` callers) are not blocked during the start sequence. Iteration order over the role dictionary is not stable; if your scenario requires a specific start ordering, register engines and start them explicitly via `engine(for:)`.
**Snapshot race window.** A `makeEngine` / `adopt` that commits between the snapshot and the loop end will leave its engine unstarted by this `startAll` call. Call `startAll()` once after all registrations complete, or serialise registration and startup on the caller side.
**Rollback on failure.** If one engine throws during start, every previously-started engine is rolled back with `engine.stop()` before the host throws `EngineHostError.startFailed(engine:underlying:)`. Partial start states are not exposed to the caller.
`stopAll()` is the reverse — `engine.stop()` is idempotent so calling `stopAll()` on a never-started or partially-started host is safe.
---
## Adoption: `adopt(existing:role:)`
Escape hatch for **migration** scenarios (existing direct-ctor code wanting to opt into host lifecycle without re-construction) and **test fixtures** (an engine constructed by a test helper that needs host registration after the fact):
```swift
let engine = SynthesisEngine(blockSize: 256, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: someDriver)
try host.adopt(existing: engine, role: .custom("imported"))
```
The host verifies the engine is visible in `EngineLifecycleCoordinator.shared.engines` before accepting — guards against passing a deinit-in-progress engine or one constructed via an unsupported path. Throws `EngineHostError.adoptRejected(engine:reason:)` if the verification fails.
After adoption the engine is indistinguishable from a `makeEngine`-constructed engine: same role-keyed lookup, same `startAll`/`stopAll` participation.
---
## NRT batch render: `renderConcurrent(jobs:maxConcurrent:)`
The blessed entry point for "render N audio files in parallel."
```swift
let host = EngineHost()
let jobs: [NRTJob] = mixes.enumerated().map { i, mix in
NRTJob(
outputURL: outDir.appendingPathComponent("mix_\(i).caf"),
duration: 4.0,
format: .cafFloat32, // default; use .wavFloat32 / .aiffFloat32 / .wavInt16 / .wavInt24 for interchange
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2
) { engine in
try engine.add(mix.makeRouteSynth())
}
}
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: 4) {
print("rendered \(result.outputURL.lastPathComponent) in \(result.elapsed) s")
}
```
### Job descriptors
`NRTJob` is a `Sendable` value carrying everything needed to spin up one engine and render one file:
| Field | Purpose |
|---|---|
| `outputURL: URL` | Destination CAF file |
| `duration: Double` | Render duration in seconds |
| `blockSize: Int` | Engine block size (defaults to `lyrebirdDefaultResultBufferSize = 512`) |
| `sampleRate: Double` | Engine sample rate |
| `numOutputChannels: Int` | 2 / 4 / 8 channel render |
| `inputURL: URL?` | Optional source file for processing jobs |
| `inputStartOffset: Double` | Seconds to skip into `inputURL` |
| `build: @Sendable (SynthesisEngine) throws -> Void` | Closure adding synths before render |
The `build` closure runs on the background `Task` executing the job — it must be `@Sendable` (no captures of non-Sendable state, no mutation of shared mutable references). Engine binding enforces that synthesizers added to one job's engine cannot leak into another job's engine.
### Completion records
`NRTResult` is yielded per successful render:
```swift
public struct NRTResult: Sendable {
public let outputURL: URL
public let jobIndex: Int // correlation back to input array
public let elapsed: Double // wall-clock seconds
}
```
**Results stream in completion order, not input order.** Use `jobIndex` to correlate results back to the original job list.
### Concurrency
`maxConcurrent` defaults to `ProcessInfo.processInfo.activeProcessorCount` and is clamped to `[1, jobs.count]`. The host drives a `withThrowingTaskGroup` with a seed-and-refill pattern: initial `maxConcurrent` jobs spawn; each completion triggers spawn of the next queued job until the input is exhausted.
### Failure semantics
If any job throws (from its `build` closure, from `engine.start()`, or from the `NRTDriver`), the throw propagates via the `AsyncThrowingStream`'s throw path. Iterate with `for try await`:
```swift
do {
for try await result in host.renderConcurrent(jobs: jobs) { … }
} catch let error as DeliberateBuildFailure {
// handle
}
```
Behaviour on throw:
- The throwing job's error propagates through the AsyncThrowingStream.
- `withThrowingTaskGroup` cancels the remaining child tasks when the body's `for try await` rethrows, and the refill loop's `addTaskUnlessCancelled` no longer spawns queued jobs.
- Cancellation propagates only as a flag — child tasks check `Task.isCancelled` cooperatively. `_executeJob` calls `engine.start()` which renders synchronously without cancellation checks, so any in-flight render runs to completion regardless of cancellation. Their results are discarded (the stream is finished by the time they return).
The stream is single-shot — once it finishes (clean end or throw), no further results arrive.
### Pool engines are not host-registered
NRT pool jobs spin up their engines **inline** — they are not registered in the host's role map. The engine lives for the duration of one render and deinits when the executing function returns. `EngineLifecycleCoordinator`'s auto register/unregister still applies.
This means:
- `host.engines` does **not** include pool jobs (the host's role map and the pool are independent facilities).
- Cancelling the stream cancels the underlying Task; in-flight engines stop naturally as their `engine.start()` returns.
---
## Drawbacks (acknowledged)
1. **New top-level public type.** API-stability commitment. If the role enum gains new cases (e.g. `.scope`, `.midiClock`) in a future phase, those additions are non-breaking — but renaming/removing cases is a major version bump.
2. **God-object risk.** The host is deliberately scoped to lifecycle + ownership registry + NRT pool. Routing stays in the bus system; scheduling stays per-engine; MIDI / OSC stay unchanged. Avoid expanding the host's responsibilities.
3. **Adoption optional.** Multi-engine bug reports without a host present require triage of "do you have an `EngineHost`?" as the first question.
---
## Drawbacks of NOT using the host
If you spin up two engines manually (direct `SynthesisEngine()` × 2) without a host, you lose:
- Role-keyed uniqueness check — nothing prevents two engines from binding to the same AUHAL device until the second one's `start()` fails at the driver layer.
- `startAll` / `stopAll` rollback semantics — you must hand-roll the partial-start cleanup.
- The `renderConcurrent` NRT pool API.
The `EngineLifecycleCoordinator` still tracks the engines, and binding errors still surface — but the convenience layer is missing.
---
## Caveats and footguns
Non-blocking findings that affect users of the host.
### NRT pool memory cost on high-core systems
`renderConcurrent`'s default `maxConcurrent: ProcessInfo.processInfo.activeProcessorCount` × per-engine working set can be large.
Per-engine memory at a glance (steady state):
| Component | Size |
|---|---|
| `audioBuses` | `numAudioBuses × blockSize × sizeof(Float)` |
| `controlBuses` | `numControlBuses × sizeof(Float)` |
| `_busAccumulateScratch` | `blockSize × sizeof(Float)` |
| `ScratchBuses` (per `ParallelGroup` child) | `numChildren × numAudioBuses × blockSize × sizeof(Float)` |
| Generator output buffers (per generator) | `lyrebirdDefaultResultBufferSize × numChannels × sizeof(Double)` |
On an M3 Max (16 cores) running stereo 48kHz with `numAudioBuses = 128`, `blockSize = 512`, the bus alone is ~2.5 MB × 16 ≈ 40 MB before any synth graph. iOS / memory-constrained Mac can OOM under the default cap.
**Mitigation.** Cap `maxConcurrent` to `min(4, activeProcessorCount)` on mobile / shared-memory targets, or size the cap to your render-time budget × per-render working set on desktop. Set explicitly:
```swift
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: cap) { … }
```
### In-flight NRT jobs continue writing to disk after stream cancellation
`engine.start()` renders synchronously without cooperative-cancellation checks. Caller break → in-flight renders run to completion → CAF files land on disk → results are discarded by the closed `for try await` loop. Users expect "cancellation = no files left behind."
**Mitigation.** Track the expected output URLs on the caller side; on cancellation, walk the set and delete any URLs that did not receive a corresponding `NRTResult`:
```swift
var pending: Set<URL> = Set(jobs.map(\.outputURL))
do {
for try await result in host.renderConcurrent(jobs: jobs) {
pending.remove(result.outputURL)
if shouldCancel { break }
}
} catch { … }
// `pending` now contains URLs for jobs that either never ran, or ran
// and landed on disk after the loop broke. Either case is cleanup.
for url in pending {
try? FileManager.default.removeItem(at: url)
}
```
### Cross-job synth-instance sharing trips engine binding
If you share a `Synthesizer` instance across `NRTJob.build` closures (captured by a job-list-building loop without re-construction), the first job binds the synth to its engine via the `_engineBinding` CAS. Subsequent jobs then throw `EngineAddError.boundToOtherEngine` — surprising because the first engine is "gone" from the caller's perspective.
The binding atomic survives the first engine's `deinit`. Either:
- An explicit `engine.remove(synth)` on the bound engine clears the binding (but pool engines deinit when `_executeJob` returns — there is no opportunity for a caller-side `remove`).
- A subsequent `_bind` on a different engine triggers the stale-pointer recovery path. The recovery is bounded by a documented address-reuse known limit — if Swift's allocator places the new engine at the freed engine's exact address, the new bind misclassifies as `.doubleAdd`. See `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::bindRecoversFromStaleEnginePointer` for the test that exercises this.
**Mitigation.** Construct fresh synth instances **inside** the `build` closure, not in the outer job-list-building scope:
```swift
// WRONG — synth is captured once and bound to job 0's engine.
let synth = MySynth()
let jobs = (0..<4).map { i in
NRTJob(...) { engine in try engine.add(synth) }
}
// RIGHT — each build closure constructs its own synth.
let jobs = (0..<4).map { i in
NRTJob(...) { engine in try engine.add(MySynth()) }
}
```
### Cooperative thread pool starvation on long renders
`_executeJob` runs a synchronous NRT render on a regular `Task` → occupies one cooperative-pool slot for the full render duration. With `maxConcurrent` = `activeProcessorCount`, the entire Swift global executor is parked for the render. Other async work in the same process stalls until at least one render completes and frees a slot.
**Mitigation (user-side).** Cap `maxConcurrent` below `activeProcessorCount` to leave headroom:
```swift
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
```
**Mitigation (future host change, deferred).** Dispatch `_executeJob` onto a dedicated `DispatchQueue.global(qos: .userInitiated)` and bridge to the `Task` via continuation. Decouples renders from the cooperative pool entirely. Tracked as a future change.
### `adopt(existing:role:)` TOCTOU is benign
`adopt` verifies the engine is live via `EngineLifecycleCoordinator.shared.engines` outside the host lock, then commits the registration under the host lock. The engine could deinit between the two — but Swift ARC guarantees the engine stays alive once the host's strong reference is acquired at commit time. The original strong-ref holder racing `deinit` either had a strong ref the whole time (no deinit) or already lost the ref by the time the coordinator's weak ref was non-nil at check time (engine cannot have started `deinit` while a strong ref existed).
**No user mitigation required** — the race is benign by ARC semantics. Surfaced here so users do not assume `adopt` needs external locking.
## See also
- `docs/engine/synthesis-engine.md` § Engine Identity, Ownership Binding
- `docs/engine/multi-core.md` § Multiple Engine Instances, Object ownership rules
- `Tests/LyrebirdTests/EngineHostTests.swift` — 14 host-coverage tests
- `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::twoEnginesViaHostUniformityContract` — host-variant of the two-engine concurrent regression test, proves the host-driven path produces the same observable behaviour as direct-ctor