Files

409 lines
17 KiB
Swift

// ThreadSafetyTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Sendable wrapper
//
// SynthesisEngine and SynthesizerBase are not declared Sendable because their
// mutable state is intentionally mediated by SPSC queues (pendingQueue / paramQueue).
// These queues ARE the thread-safety mechanism under test. The wrapper below is the
// standard Swift-6-compatible way to cross an isolation boundary in tests that
// deliberately exercise this lock-free design.
private struct UncheckedSendable<T>: @unchecked Sendable {
let value: T
init(_ value: T) { self.value = value }
}
// MARK: - SPSC queue concurrency
@MainActor
@Suite("SPSC queue concurrency")
struct SPSCQueueConcurrencyTests {
// Use a small queue capacity relative to the total item count so the producer
// must wait for the consumer to drain before it can enqueue more — this forces
// real interleaving between producer and consumer threads.
private let queueCapacity: Int = 64
private let itemCount: Int = 2000
/// Single producer on a background thread, single consumer on the calling thread.
/// Every enqueued integer must be received by the consumer in FIFO order.
@Test func concurrentProducerConsumerDeliversAllItemsInOrder() {
let q: SPSCQueue<Int> = SPSCQueue<Int>(capacity: queueCapacity) // @unchecked Sendable — safe to share
let producerDone: DispatchSemaphore = DispatchSemaphore(value: 0)
let totalItems: Int = itemCount
// Background thread: producer
DispatchQueue.global(qos: .userInteractive).async {
var sent: Int = 0
while sent < totalItems {
if q.enqueue(sent) { sent += 1 }
}
producerDone.signal()
}
// Calling thread: consumer
var received: [Int] = []
received.reserveCapacity(totalItems)
while received.count < totalItems {
if let v: Int = q.dequeue() { received.append(v) }
}
producerDone.wait() // producer must also be finished
#expect(received.count == totalItems)
// FIFO: item at position i must equal i
for i: Int in 0..<totalItems {
#expect(received[i] == i, "FIFO violation at index \(i): got \(received[i])")
}
}
/// Multiple fill-drain cycles on separate producer / consumer threads must not lose
/// or duplicate items. The queue is reused across cycles to catch state bugs that
/// only appear after wrap-around of the internal ring-buffer indices.
@Test func concurrentFillDrainCyclesAreConsistent() {
let q: SPSCQueue<Int> = SPSCQueue<Int>(capacity: queueCapacity)
let cycleCount: Int = 10
let perCycle: Int = queueCapacity // fill queue completely each cycle
let allExpected: Int = cycleCount * perCycle
var totalReceived: Int = 0
let allDone: DispatchSemaphore = DispatchSemaphore(value: 0)
DispatchQueue.global(qos: .userInteractive).async {
for cycle: Int in 0..<cycleCount {
let base: Int = cycle * perCycle
var sent: Int = 0
while sent < perCycle {
if q.enqueue(base + sent) { sent += 1 }
}
}
allDone.signal()
}
// Consumer: drain all items (in order, given FIFO guarantee)
var expected: Int = 0
while totalReceived < allExpected {
if let v: Int = q.dequeue() {
#expect(v == expected, "Out-of-order item: expected \(expected), got \(v)")
expected += 1
totalReceived += 1
}
}
allDone.wait()
#expect(totalReceived == allExpected)
}
}
// MARK: - Parameter queue semantics
@MainActor
@Suite("Parameter queue semantics")
struct ParameterQueueSemanticsTests {
// These tests are intentionally single-threaded: they verify the ordering and
// block-boundary semantics of the parameter update queue without needing real
// concurrency. Real concurrency is exercised by SPSCQueueConcurrencyTests above.
/// Tolerance for comparing constant-parameter sample values against an exact target.
private let exactValueTolerance: Float = 1e-6
/// A parameter update must be applied by the RT thread before the *next*
/// processBlock invocation begins, not mid-block.
///
/// `@LiveParam` ramps over one block from prev → target. The last sample of the post-update
/// block must reach the new target — proving the atomic write was visible at block start.
@Test func parameterUpdateAppliedAtBlockBoundary() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let synth: ConstantParamSynthFixture = ConstantParamSynthFixture(defaultValue: 0.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: []) // block 1: flat at 0.0
try synth.updateParameter("level", value: 1.0)
engine.processBlock(inputSamples: []) // block 2: ramp 0 → 1; last sample == 1.0
let block2: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
let lastSample: Float = block2[block2.endIndex - 1]
#expect(abs(lastSample - 1.0) < exactValueTolerance,
"Parameter update must reach target at last sample of block 2")
}
/// `@LiveParam` is backed by an atomic store — multiple writes before the next block
/// collapse to the last value (releasing-store ordering, last-wins).
@Test func lastUpdateWins() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let synth: ConstantParamSynthFixture = ConstantParamSynthFixture(defaultValue: 0.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
try synth.updateParameter("level", value: 0.5)
try synth.updateParameter("level", value: 0.75)
try synth.updateParameter("level", value: 1.0) // last write — must win
engine.processBlock(inputSamples: []) // ramp 0 → 1 (target picked from atomic)
let block: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
let lastSample: Float = block[block.endIndex - 1]
#expect(abs(lastSample - 1.0) < exactValueTolerance,
"Last atomic write must be the target reached at end of block")
}
/// `@LiveParam` is atomic — there is no queue, so issuing arbitrarily many updates
/// from the main thread cannot overflow or lose data structurally; only the latest
/// value persists. This replaces the legacy queue-capacity test.
@Test func rapidUpdatesDoNotCrash() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let synth: ConstantParamSynthFixture = ConstantParamSynthFixture(defaultValue: 0.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
let updateCount: Int = 1000
for i: Int in 0..<updateCount {
try? synth.updateParameter("level", value: Double(i))
}
engine.processBlock(inputSamples: [])
let block: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
#expect(block.allSatisfy { $0.isFinite })
}
/// Once written, the atomic value persists across blocks — `previousOutputValue`
/// equals `target` after the first ramp, so subsequent blocks are flat at the target.
@Test func parameterValuePersistsAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let synth: ConstantParamSynthFixture = ConstantParamSynthFixture(defaultValue: 0.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
let persistedLevel: Double = 0.6
try synth.updateParameter("level", value: persistedLevel)
engine.processBlock(inputSamples: []) // ramp 0 → persistedLevel
// After the ramp completes, all subsequent blocks are flat at persistedLevel.
for _ in 0..<5 {
engine.processBlock(inputSamples: [])
let block: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
#expect(block.allSatisfy { abs($0 - Float(persistedLevel)) < exactValueTolerance })
}
}
}
// MARK: - Graph modification queue semantics
@MainActor
@Suite("Graph modification queue semantics")
struct GraphModificationQueueSemanticsTests {
/// Tolerance for exact constant-value bus comparisons.
private let exactValueTolerance: Float = 1e-6
/// Tolerance for bus comparisons where multiple floating-point additions may accumulate.
private let accumulationTolerance: Float = 1e-5
/// try engine.add() enqueues via pendingQueue; the synth appears in the tree on the next
/// processBlock (or the same block if the scheduled time is in the current window).
@Test func addSynthTakesEffectAtNextProcessBlock() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
engine.processBlock(inputSamples: []) // establish clean state
let synth: ConstantSynth = ConstantSynth(value: 1.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
#expect(bus.allSatisfy { abs($0 - 1.0) < exactValueTolerance },
"Synth added before processBlock must be active by the time the block runs")
}
/// engine.remove() must remove the synth before the next processBlock begins,
/// leaving the bus at zero.
@Test func removeSynthTakesEffectAtNextProcessBlock() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let synth: ConstantSynth = ConstantSynth(value: 1.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: []) // synth active
engine.remove(synth)
engine.processBlock(inputSamples: []) // synth removed
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
#expect(bus.allSatisfy { $0 == 0.0 })
}
/// Rapidly adding and removing a synth many times must not leak memory or crash.
@Test func rapidAddRemoveCyclesDoNotCrash() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
try engine.start()
let cycleCount: Int = 50
for _ in 0..<cycleCount {
let synth: ConstantSynth = ConstantSynth(value: 0.5, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
engine.remove(synth)
engine.processBlock(inputSamples: [])
}
// Final state: bus must be zero (last synth removed).
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(8)
#expect(bus.allSatisfy { $0 == 0.0 })
}
/// Multiple synths added in sequence must all be present simultaneously.
@Test func multipleSynthsAddedSequentiallyAreAllActive() throws {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, numAudioBuses: 16)
try engine.start()
let synthCount: Int = 5
let valuePerSynth: Double = 0.1
for _ in 0..<synthCount {
try engine.add(ConstantSynth(value: valuePerSynth, outputBus: 0))
}
engine.processBlock(inputSamples: [])
let expected: Double = valuePerSynth * Double(synthCount)
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(blockSize)
#expect(bus.allSatisfy { abs($0 - Float(expected)) < accumulationTolerance },
"All \(synthCount) synths must contribute to the mixed bus output")
}
}
// MARK: - Concurrent parameter updates with processBlock
@MainActor
@Suite("Concurrent parameter updates")
struct ConcurrentParameterUpdateTests {
/// Updating a parameter from a background thread while processBlock loops on the
/// calling thread must not crash or produce non-finite output.
/// This is the primary concurrency invariant of the per-synth paramQueue.
@Test func updateParameterConcurrentWithProcessBlockIsStable() throws {
let engine: SynthesisEngine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 8,
numControlBuses: 64
)
try engine.start()
let synth: ConstantParamSynthFixture = ConstantParamSynthFixture(defaultValue: 0.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: []) // establish synth in tree
// Box engine and synth in @unchecked Sendable wrappers so they can cross the
// isolation boundary into the background DispatchQueue closure.
let eRef: UncheckedSendable<SynthesisEngine> = UncheckedSendable(engine)
let sRef: UncheckedSendable<ConstantParamSynthFixture> = UncheckedSendable(synth)
let processBlockCount: Int = 200
let processDone: DispatchSemaphore = DispatchSemaphore(value: 0)
// Background thread: run processBlock continuously
DispatchQueue.global(qos: .userInteractive).async {
let e: SynthesisEngine = eRef.value
for _ in 0..<processBlockCount {
e.processBlock(inputSamples: [])
}
processDone.signal()
}
// Calling thread: flood parameter updates concurrently
let updateCount: Int = 500
for i: Int in 0..<updateCount {
// Alternate between values to maximize queue pressure.
let v: Double = Double(i % 2 == 0 ? 0.0 : 1.0)
try? sRef.value.updateParameter("level", value: v)
}
processDone.wait()
// Engine must still be stable: run a few more blocks and verify finite output.
for _ in 0..<5 { engine.processBlock(inputSamples: []) }
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(64)
#expect(bus.allSatisfy { $0.isFinite }, "Output must remain finite after concurrent updates")
}
/// Adding and removing synths from the calling thread while processBlock runs on a
/// background thread must not crash — pendingQueue mediates the mutation safely.
@Test func addRemoveSynthConcurrentWithProcessBlockIsStable() throws {
let engine: SynthesisEngine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 8,
numControlBuses: 64
)
try engine.start()
let eRef: UncheckedSendable<SynthesisEngine> = UncheckedSendable(engine)
let processBlockCount: Int = 200
let processDone: DispatchSemaphore = DispatchSemaphore(value: 0)
// Background thread: continuous processBlock loop
DispatchQueue.global(qos: .userInteractive).async {
let e: SynthesisEngine = eRef.value
for _ in 0..<processBlockCount {
e.processBlock(inputSamples: [])
}
processDone.signal()
}
// Calling thread: add/remove synths rapidly
let mutationCount: Int = 50
for _ in 0..<mutationCount {
let synth: ConstantSynth = ConstantSynth(value: 0.5, outputBus: 0)
try engine.add(synth)
engine.remove(synth)
}
processDone.wait()
// No crash = success; verify engine is still operational.
engine.processBlock(inputSamples: [])
#expect(engine.isRunning)
}
}
// MARK: - Local test fixture
/// A `@LiveParam`-backed synth whose `level` can be updated at runtime.
/// Placed in this file because it is only used by the thread-safety suites above.
///
/// Note: the parameter value is delivered via a `ParameterNode` (`ControlGenerator`), which
/// linearly ramps from the previous block's end value to the new atomic target. With
/// initial `prev == target`, the very first block is flat at `defaultValue`. After
/// `updateParameter("level", value: X)`, the next block ramps from old → X (reaching X
/// at the last sample), and subsequent blocks remain flat at X.
private final class ConstantParamSynthFixture: SynthesizerBase {
@LiveParam var level: Double = 0.0
let outputBus: Int
init(defaultValue: Double, outputBus: Int) {
self.outputBus = outputBus
super.init()
// prime() resets both atomic and ramp origin so the first block is flat at defaultValue.
$level.prime(defaultValue)
}
override func build() {
addOutputGenerator(Out.Audio(bus: outputBus, source: $level))
}
}