// 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: @unchecked Sendable { let value: T init(_ value: T) { self.value = value } } // MARK: - SPSC queue concurrency @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 = SPSCQueue(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.. = SPSCQueue(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...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.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...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.SubSequence = engine.audioBuses[0].prefix(8) #expect(block.allSatisfy { abs($0 - Float(persistedLevel)) < exactValueTolerance }) } } } // MARK: - Graph modification queue semantics @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.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.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...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...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 @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 = UncheckedSendable(engine) let sRef: UncheckedSendable = 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...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 = 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..