Files
Lyrebird/Tests/LyrebirdTests/MultiEngineRegressionTests.swift
T

407 lines
16 KiB
Swift

// MultiEngineRegressionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Multi-engine regression coverage.
///
/// Validates the ownership-binding + lifecycle-coordinator
/// machinery against the two scenarios that motivated it:
///
/// 1. **Two engines, two threads, disjoint Synth graphs** — drives both
/// engines for ≥ 1000 segments each in parallel. Acts as a
/// deterministic repro target for the deferred parallel-`swift test`
/// crash (`_ContiguousArrayStorage retain count 2` at xctest teardown);
/// if RetainQueue / coordinator wiring is correct, this passes
/// cleanly under `--no-parallel` (single test process, two threads
/// inside).
///
/// 2. **Binding precondition coverage** — `engine.add` throws
/// `.boundToOtherEngine` for cross-engine sharing, `.doubleAdd` for
/// same-engine re-add without intervening `remove`, and accepts
/// re-add after `remove` clears the binding.
@MainActor
@Suite("Multi-engine regression")
struct MultiEngineRegressionTests {
// MARK: - Two-engine, two-thread driver
/// Drives two engines concurrently on dedicated threads, each with
/// its own disjoint Synth graph, for `segmentCount` processBlock
/// iterations. Joins both threads, stops both engines, and asserts
/// neither crashed nor produced obvious miscount.
///
/// `segmentCount = 1000` matches the plan exit criterion.
/// Adjust upward for stress runs; downward to keep CI fast.
@Test func twoEnginesTwoThreadsDisjointGraphs() throws {
let segmentCount: Int = 1000
let engineA: SynthesisEngine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
eventQueueCapacity: 64
)
let engineB: SynthesisEngine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
eventQueueCapacity: 64
)
// Distinct UUIDs — confirms identifier-per-instance contract.
#expect(engineA.identifier != engineB.identifier)
// Both engines must be visible in the lifecycle registry.
// Note: other tests in the same process may have left engines
// registered; only assert both A and B appear.
let registered: [SynthesisEngine] = EngineLifecycleCoordinator.shared.engines
#expect(registered.contains { $0 === engineA })
#expect(registered.contains { $0 === engineB })
try engineA.start()
try engineB.start()
// Disjoint Synth graphs — each engine gets its own synth instance.
// Distinct bus indices keep the language-side bus assignment unambiguous.
let synthA: ConstantSynth = ConstantSynth(value: 0.5, outputBus: 0)
let synthB: ConstantSynth = ConstantSynth(value: 0.25, outputBus: 0)
try engineA.add(synthA)
try engineB.add(synthB)
let group: DispatchGroup = DispatchGroup()
let queueA: DispatchQueue = DispatchQueue(label: "lyrebird.test.engineA")
let queueB: DispatchQueue = DispatchQueue(label: "lyrebird.test.engineB")
// Run both processBlock loops on dedicated background queues so
// the segments interleave on two distinct OS threads. Capture
// engines by reference inside the closures.
let engineARef: SynthesisEngine = engineA
let engineBRef: SynthesisEngine = engineB
queueA.async(group: group) {
for _ in 0..<segmentCount {
engineARef.processBlock(inputSamples: [])
}
}
queueB.async(group: group) {
for _ in 0..<segmentCount {
engineBRef.processBlock(inputSamples: [])
}
}
// Bounded wait — if either thread stalls past 30 s, fail loudly
// rather than hanging the test suite.
let result: DispatchTimeoutResult = group.wait(timeout: .now() + .seconds(30))
#expect(result == .success, "Two-engine processBlock loop timed out (deadlock?)")
// Both engines advanced their sample clocks by `segmentCount` blocks.
let blockSizeA: SampleTime = SampleTime(engineA.blockSize)
let blockSizeB: SampleTime = SampleTime(engineB.blockSize)
#expect(engineA.currentTime == SampleTime(segmentCount) * blockSizeA)
#expect(engineB.currentTime == SampleTime(segmentCount) * blockSizeB)
engineA.stop()
engineB.stop()
}
/// Uniformity-contract regression — same two-engine
/// two-thread workload as `twoEnginesTwoThreadsDisjointGraphs`, but
/// engines are constructed via `EngineHost.makeEngine` +
/// `host.startAll()` instead of direct-ctor. Verifies that the
/// host wrapping does not change observable engine behaviour: same
/// identifier-per-instance, same registry visibility, same sample-
/// clock advancement, same concurrent processBlock safety.
@Test func twoEnginesViaHostUniformityContract() throws {
let segmentCount: Int = 1000
let host: EngineHost = EngineHost()
let cfg: SynthesisEngineConfig = SynthesisEngineConfig(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: 64,
driver: OfflineDriver()
)
let engineA: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 0), config: cfg)
// Each call needs its own driver — same config but fresh.
let cfgB: SynthesisEngineConfig = SynthesisEngineConfig(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: 64,
driver: OfflineDriver()
)
let engineB: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 1), config: cfgB)
// Uniformity assertions: distinct UUIDs, host registry sees both.
#expect(engineA.identifier != engineB.identifier)
#expect(host.engineCount == 2)
#expect(host.engine(for: .nrtRender(slot: 0)) === engineA)
#expect(host.engine(for: .nrtRender(slot: 1)) === engineB)
// Lifecycle via host.startAll — same effect as engine.start() per engine.
try host.startAll()
#expect(engineA.isRunning)
#expect(engineB.isRunning)
let synthA: ConstantSynth = ConstantSynth(value: 0.5, outputBus: 0)
let synthB: ConstantSynth = ConstantSynth(value: 0.25, outputBus: 0)
try engineA.add(synthA)
try engineB.add(synthB)
let group: DispatchGroup = DispatchGroup()
let queueA: DispatchQueue = DispatchQueue(label: "lyrebird.test.host.engineA")
let queueB: DispatchQueue = DispatchQueue(label: "lyrebird.test.host.engineB")
let engineARef: SynthesisEngine = engineA
let engineBRef: SynthesisEngine = engineB
queueA.async(group: group) {
for _ in 0..<segmentCount { engineARef.processBlock(inputSamples: []) }
}
queueB.async(group: group) {
for _ in 0..<segmentCount { engineBRef.processBlock(inputSamples: []) }
}
let result: DispatchTimeoutResult = group.wait(timeout: .now() + .seconds(30))
#expect(result == .success, "Host-driven two-engine processBlock loop timed out (deadlock?)")
let blockSizeA: SampleTime = SampleTime(engineA.blockSize)
let blockSizeB: SampleTime = SampleTime(engineB.blockSize)
#expect(engineA.currentTime == SampleTime(segmentCount) * blockSizeA)
#expect(engineB.currentTime == SampleTime(segmentCount) * blockSizeB)
host.stopAll()
#expect(!engineA.isRunning)
#expect(!engineB.isRunning)
}
// MARK: - Binding precondition tests
/// `engine.add` throws `.boundToOtherEngine` when the same synth is
/// added to a second engine without an intervening `remove`.
@Test func crossEngineAddThrowsBoundToOther() throws {
let engineA: SynthesisEngine = makeTestEngine()
let engineB: SynthesisEngine = makeTestEngine()
try engineA.start()
try engineB.start()
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
try engineA.add(synth)
var caught: EngineAddError? = nil
do {
try engineB.add(synth)
} catch let error as EngineAddError {
caught = error
}
#expect(caught != nil, "Expected EngineAddError, got success")
if case .boundToOtherEngine(let current, let prior) = caught {
#expect(current == engineB.identifier)
#expect(prior == engineA.identifier,
"prior should resolve to engineA via lifecycle registry")
} else {
Issue.record("Expected .boundToOtherEngine, got \(String(describing: caught))")
}
engineA.stop()
engineB.stop()
}
/// `engine.add` throws `.doubleAdd` when the same synth is added
/// twice to the same engine without an intervening `remove`.
@Test func doubleAddSameEngineThrowsDoubleAdd() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
try engine.add(synth)
var caught: EngineAddError? = nil
do {
try engine.add(synth)
} catch let error as EngineAddError {
caught = error
}
#expect(caught != nil)
if case .doubleAdd(let id) = caught {
#expect(id == engine.identifier)
} else {
Issue.record("Expected .doubleAdd, got \(String(describing: caught))")
}
engine.stop()
}
/// `remove` clears the binding so a subsequent `add` succeeds.
/// (Documented constraint: caller must allow one processBlock between
/// remove and re-add; the test honours that by calling processBlock
/// between the two API calls.)
@Test func removeClearsBindingAndAllowsReAdd() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
_ = engine.remove(synth)
engine.processBlock(inputSamples: [])
// Re-add should succeed — binding cleared by remove + drained
// by processBlock.
#expect(throws: Never.self) {
try engine.add(synth)
}
engine.stop()
}
// MARK: - LyrebirdBuffer read-only sharing
/// `bindReadOnly` allows the same buffer to be shared across multiple
/// engines concurrently. Opt-in API.
@Test func bufferReadOnlyShareAcrossEngines() throws {
let engineA: SynthesisEngine = makeTestEngine()
let engineB: SynthesisEngine = makeTestEngine()
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 256)
buf.fillSine()
try buf.bindReadOnly(to: engineA)
try buf.bindReadOnly(to: engineB)
// Exclusive bind must fail while any read-only holder is active.
var caught: EngineAddError? = nil
do {
try buf.bindExclusive(to: engineA)
} catch let error as EngineAddError {
caught = error
}
#expect(caught != nil, "Expected EngineAddError on exclusive bind with read-only holders")
buf.unbindReadOnly(from: engineA)
buf.unbindReadOnly(from: engineB)
}
/// Stale-pointer recovery in `_bind`.
///
/// If an engine deinits without unbinding a synth it owns, the raw
/// pointer in `_engineBinding` is dangling. The recovery path in
/// `SynthesizerBase._bind` validates the stored pointer against the
/// lifecycle registry; if no live engine matches, the binding is
/// force-cleared and the CAS retries.
///
/// Test allocates an engine, binds a synth, leaks the binding, then
/// frees the engine. Then asserts that the synth's `_engineBinding`
/// atomic state is recoverable — either bound (re-add succeeded) or
/// the synth could not be re-bound because the new engine happens to
/// alias the freed engine's address (a known limit of pointer-only
/// binding storage; see comment below). The address-reuse path is
/// not exercised by this test, but is acknowledged as a deferred
/// concern.
///
/// **Known limit:** if Swift's allocator places the new engine at the
/// exact address freed from the prior engine, `original == target`
/// in the CAS and the recovery path classifies it as `.doubleAdd`
/// rather than stale-pointer recovery. Fixing this requires
/// replacing the raw-pointer-in-atomic with a coordinator-issued
/// monotonic UInt64 registration token (or stamping a generation
/// counter alongside the pointer). Tracked as a future improvement.
@Test func bindRecoversFromStaleEnginePointer() throws {
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
// Bind to engineA, leak binding, drop engineA.
weak var engineARef: SynthesisEngine?
do {
let engineA: SynthesisEngine = makeTestEngine()
engineARef = engineA
try engineA.add(synth)
engineA.stop()
}
// Confirm engineA was actually deallocated (Swift sometimes
// delays deinit; if so, the test premise is invalid).
guard engineARef == nil else {
// engineA still alive — recovery path cannot be exercised.
// Skip without failing; this is a Swift runtime behaviour
// outside the unit under test.
return
}
// Re-bind to engineB. Success = recovery cleared the dangling
// pointer. `.doubleAdd` failure = address-reuse pathology (the
// known limit documented above) — treat as a non-failure since
// this test cannot control Swift's allocator placement.
let engineB: SynthesisEngine = makeTestEngine()
try engineB.start()
do {
try engineB.add(synth)
// Recovery succeeded as designed.
} catch let error as EngineAddError {
if case .doubleAdd = error {
// Address-reuse case — engineB was allocated at the
// exact address freed from engineA. Documented known
// limit; not a regression. Print for observability,
// do not fail.
print("[Test note] address-reuse pathology exercised: \(error). Not a failure; see test doc.")
} else {
Issue.record("Unexpected EngineAddError on stale-pointer recovery: \(error)")
}
}
engineB.stop()
}
/// `unbindReadOnly` saturates at zero rather
/// than wrapping to `Int.max` under unbalanced misuse. Without
/// saturation, an unbalanced unbind would permanently block any
/// subsequent `bindExclusive` because the refcount check in
/// `bindExclusive` would see a huge positive count.
@Test func bufferUnbindReadOnlySaturatesAtZero() throws {
let engine: SynthesisEngine = makeTestEngine()
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 256)
// No matching bindReadOnly — unbind should be a no-op, not
// underflow.
buf.unbindReadOnly(from: engine)
buf.unbindReadOnly(from: engine)
buf.unbindReadOnly(from: engine)
// `bindExclusive` must still succeed; the refcount stayed at
// zero through the unbalanced unbinds.
try buf.bindExclusive(to: engine)
buf.unbindExclusive(from: engine)
}
/// `bindExclusive` blocks a second engine from claiming the same buffer.
@Test func bufferExclusiveBindBlocksCrossEngine() throws {
let engineA: SynthesisEngine = makeTestEngine()
let engineB: SynthesisEngine = makeTestEngine()
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 256)
try buf.bindExclusive(to: engineA)
var caught: EngineAddError? = nil
do {
try buf.bindExclusive(to: engineB)
} catch let error as EngineAddError {
caught = error
}
#expect(caught != nil, "Expected EngineAddError on cross-engine exclusive bind")
buf.unbindExclusive(from: engineA)
}
}