// LyrebirdProcessTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation import Synchronization @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // MARK: - Test fixtures /// Minimal synthesizer that writes silence to bus 0. /// /// `@unchecked Sendable` is test-scope only: lets `SilentSynth` be captured by `@Sendable` /// closures (body, onRelease) while preserving the synth's identity for `===` assertions. /// `SynthesizerBase` itself is not Sendable; production code should not adopt this pattern. private final class SilentSynth: SynthesizerBase, @unchecked Sendable { override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.0)) } } /// Short fixed envelope — no releaseNode. Total duration ~40 ms. private func shortAutoEnvelope() -> Envelope { Envelope( levels: [0.0, 1.0, 0.0], durations: [0.02, 0.02], curves: [.lin, .lin] ) } /// Sustained envelope with a releaseNode — holds until gate drops. /// Attack 20 ms, release tail 50 ms. private func sustainedEnvelope() -> Envelope { Envelope( levels: [0.0, 1.0, 0.0], durations: [0.02, 0.05], curves: [.lin, .lin], releaseNode: 2 ) } /// Build a test engine backed by OfflineDriver (no real-time audio). private func makeProcessTestEngine() -> SynthesisEngine { SynthesisEngine( blockSize: 64, sampleRate: 44100, numOutputChannels: 2, numInputChannels: 0, numAudioBuses: 128, numControlBuses: 64, driver: OfflineDriver() ) } // MARK: - Engine block driver /// Drives `engine.processBlock` at ~1 ms intervals on a background thread while /// `isRunning` returns `true`. This is required for `EnvelopeGen.needsFree` to /// be set — without block rendering the watcher never triggers. /// /// The `OfflineDriver` does not generate its own render callbacks, so tests that /// rely on envelope completion must drive the engine themselves. private final class TestBlockDriver: @unchecked Sendable { private let _running: Atomic = Atomic(false) private let _done: DispatchSemaphore = DispatchSemaphore(value: 0) private let _engine: SynthesisEngine // 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime. // Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire // before engine-time advances past envelope releases / process completions. private static let blocksPerBurst: Int = 32 private static let wallSleepSeconds: TimeInterval = 0.001 init(engine: SynthesisEngine) { _engine = engine } func start() { _running.store(true, ordering: .relaxed) let thread: Thread = Thread { [self] in while self._running.load(ordering: .relaxed) { for _ in 0.. = Box(false) let process: LyrebirdProcess = LyrebirdProcess( id: "release-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in // Body waits "forever" — released externally. await ctx.wait(30.0) }, onRelease: { _ in releaseBeforeFinished.mutate { $0 = !finishedFired.isFulfilled } releaseFired.fulfill() }, onFinished: { finishedFired.fulfill() } ) process.play(engine: engine) #expect(process.isRunning) // Let the attack segment complete (~20 ms + margin). try await Task.sleep(nanoseconds: 60_000_000) process.release() #expect(process.isReleasing) let releaseOK: Bool = await releaseFired.waitForFulfillment(timeout: 5.0) #expect(releaseOK, "onRelease should fire when release() is called") let finishedOK: Bool = await finishedFired.waitForFulfillment(timeout: 10.0) #expect(finishedOK, "onFinished should fire after envelope tail completes") #expect(releaseBeforeFinished.get(), "onRelease must fire before onFinished") #expect(!process.isRunning, "isRunning should be false after completion") } // MARK: - Test 3: release() on env without releaseNode — ignored @Test("release() on env-without-releaseNode → ignored, envelope runs to natural end") func testReleaseIgnoredNoReleaseNode() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let finishedFired: AsyncExpectation = AsyncExpectation() let process: LyrebirdProcess = LyrebirdProcess( id: "no-release-node", envelope: shortAutoEnvelope(), numChannels: 1, body: { ctx in await ctx.wait(0.01) }, onFinished: { finishedFired.fulfill() } ) process.play(engine: engine) // Call release() — should be ignored (no releaseNode). process.release() // isReleasing should remain false since the call was ignored and reverted. #expect(!process.isReleasing, "isReleasing should stay false when release() is ignored") // The envelope still runs to completion. let finished: Bool = await finishedFired.waitForFulfillment(timeout: 10.0) #expect(finished, "onFinished should fire from natural envelope end") } // MARK: - Test 4: kill() mid-run → immediate free @Test("kill() mid-run → group freed immediately, onFinished fires") func testKill() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } // No block driver needed — kill() does not depend on envelope completion. let finishedFired: AsyncExpectation = AsyncExpectation() let process: LyrebirdProcess = LyrebirdProcess( id: "kill-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in await ctx.wait(30.0) }, onFinished: { finishedFired.fulfill() } ) process.play(engine: engine) #expect(process.isRunning) // Small pause so the body Task actually starts. try await Task.sleep(nanoseconds: 20_000_000) process.kill() let finished: Bool = await finishedFired.waitForFulfillment(timeout: 1.0) #expect(finished, "onFinished should fire after kill()") #expect(!process.isRunning, "isRunning should be false after kill()") } // MARK: - Test 5: amp setter @Test("amp setter → ParameterNode value updated on route synth") func testAmpSetter() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let process: LyrebirdProcess = LyrebirdProcess( id: "amp-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in await ctx.wait(30.0) } ) process.play(engine: engine) #expect(process.isRunning) // Brief pause to allow body Task to start (so routeSynth is set). try await Task.sleep(nanoseconds: 20_000_000) // Write a new amplitude. process.amp = 0.5 // Verify the route synth's @LiveParam amp ParameterNode received the write. let routeSynth: ProcessRouteSynth = try #require(process._routeSynth, "Route synth should exist while running") let nodeValue: Double = routeSynth.$amp.value #expect( abs(nodeValue - 0.5) < 0.001, "amp ParameterNode value should be 0.5 after write; got \(nodeValue)" ) process.kill() } // MARK: - Test 6: ctx.wait() elapsed-compensation @Test("ctx.wait(t): if work exceeds t, next resume is immediate (elapsed compensation)") func testWaitElapsedCompensation() async throws { let secondWaitStart: Box = Box(Date()) let secondWaitEnd: Box = Box(Date()) let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let done: AsyncExpectation = AsyncExpectation() let process: LyrebirdProcess = LyrebirdProcess( id: "elapsed-comp-test", // Long non-auto-releasing envelope so the watcher never fires. envelope: Envelope( levels: [1.0, 1.0], durations: [30.0], curves: [.lin] ), numChannels: 1, body: { ctx in // First wait: 50 ms. await ctx.wait(0.05) // "Work" that exceeds the next interval (120 ms > 50 ms). try? await Task.sleep(nanoseconds: 120_000_000) // Second wait: should be immediately because the deadline // (_nextWakeDate after first wait + 50 ms) is already in the past. secondWaitStart.mutate { $0 = Date() } await ctx.wait(0.05) secondWaitEnd.mutate { $0 = Date() } done.fulfill() // Body stays alive until process is killed externally. await ctx.wait(30.0) }, onFinished: nil ) process.play(engine: engine) let ok: Bool = await done.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should complete the elapsed-comp test within the timeout") // The second wait should be near-instant (< 20 ms) because work consumed the budget. let elapsed: TimeInterval = secondWaitEnd.get().timeIntervalSince(secondWaitStart.get()) #expect(elapsed < 0.020, "Elapsed-compensated wait should be immediate when work exceeded t; got \(elapsed) s") process.kill() } // MARK: - Test 7: ctx.add default position targets head of private group @Test("ctx.add(synth) default position targets head of process's private group") func testCtxAddDefaultTargetsHead() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let synthAdded: AsyncExpectation = AsyncExpectation() let s1: SilentSynth = SilentSynth() let s2: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "default-pos-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in // Add s1 first at default (.head), then s2 at .head. // After both adds, s2 should be at the head (added last to head), // s1 should be second. ctx.add(s1) // lands at head ctx.add(s2) // lands at head — now s2 is before s1 try? await Task.sleep(nanoseconds: 100_000_000) synthAdded.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await synthAdded.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have added synths within timeout") // Allow block processing to apply the pending add events. try await Task.sleep(nanoseconds: 50_000_000) let group: Group = try #require(process._group, "Group should exist while running") // The group should contain at least the route synth + 2 user synths. #expect(group.count >= 3, "Group should contain route synth + 2 user synths; got \(group.count)") // Both synths should be present. #expect(group.contains(s1), "s1 should be in process group") #expect(group.contains(s2), "s2 should be in process group") // Pin head-first semantics: s2 was added last to .head, so it must come before s1. // Walk head → tail and assert s2 appears before s1. var indexOfS1: Int = -1 var indexOfS2: Int = -1 var idx: Int = 0 var node: PreparedNode? = group.head while let n: PreparedNode = node { if n.synth === s1 { indexOfS1 = idx } if n.synth === s2 { indexOfS2 = idx } idx += 1 node = n.next } #expect(indexOfS2 >= 0 && indexOfS1 >= 0, "both synths must be found in group") #expect(indexOfS2 < indexOfS1, "s2 added last to head must appear before s1 (got s2@\(indexOfS2), s1@\(indexOfS1))") process.kill() } // MARK: - Test 8 (old Test 7): ctx.add at explicit head and tail @Test("ctx.add([synth], at: .head) and .tail place synths into process group") func testCtxAddHeadTail() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } // Drive processBlock so engine events (add group, add synths) are applied. let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let synthsAdded: AsyncExpectation = AsyncExpectation() let process: LyrebirdProcess = LyrebirdProcess( id: "add-pos-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in let (s1, s2): (SilentSynth, SilentSynth) = await MainActor.run { (SilentSynth(), SilentSynth()) } ctx.add(s1, at: .head) ctx.add(s2, at: .tail) // Allow main-thread dispatches from ctx.add to land and the engine // to process those add events in subsequent processBlock calls. try? await Task.sleep(nanoseconds: 100_000_000) synthsAdded.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await synthsAdded.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have added synths within timeout") // Allow additional processBlock cycles to apply the pending add events. try await Task.sleep(nanoseconds: 50_000_000) // The group should contain the route synth + 2 user synths. // group.count is only incremented by the RT thread in processBlock. let group: Group = try #require(process._group, "Group should exist while running") #expect( group.count >= 3, "Group should contain route synth + 2 user synths; got \(group.count)" ) process.kill() } // MARK: - Test 9: before/after placement for sibling processes @Test(".before(other) and .after(other) placement — standalone siblings") func testBeforeAfterPlacement() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let bodyAStarted: AsyncExpectation = AsyncExpectation() // Process A — baseline. let processA: LyrebirdProcess = LyrebirdProcess( id: "sibling-A", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in bodyAStarted.fulfill() await ctx.wait(30.0) } ) processA.play(engine: engine) // Wait for A's body to start and its group to be registered. let aStarted: Bool = await bodyAStarted.waitForFulfillment(timeout: 2.0) #expect(aStarted, "Process A body should start") // Give main-thread dispatches (try engine.add(group)) time to process. try await Task.sleep(nanoseconds: 60_000_000) // Process B — before A. let processB: LyrebirdProcess = LyrebirdProcess( id: "sibling-B", envelope: sustainedEnvelope(), numChannels: 1, target: .before(processA), body: { ctx in await ctx.wait(30.0) } ) processB.play(engine: engine) // Process C — after A. let processC: LyrebirdProcess = LyrebirdProcess( id: "sibling-C", envelope: sustainedEnvelope(), numChannels: 1, target: .after(processA), body: { ctx in await ctx.wait(30.0) } ) processC.play(engine: engine) // Allow engine add events to process. try await Task.sleep(nanoseconds: 100_000_000) #expect(processA.isRunning) #expect(processB.isRunning) #expect(processC.isRunning) processA.kill() processB.kill() processC.kill() } // MARK: - Test 10: Cross-EventList target trap // This test covers the happy path: standalone processes (no parent // EventList) all have `_eventListID == nil`, so the cross-list trap in // `LyrebirdProcess.play()` compares equal and does not fire — wiring one // standalone as `.before` of another is legal. // // The negative path — two distinct EventLists with cross-wired // `.before`/`.after` targets — is exercised by the LyrebirdEventList // integration tests, which can mint owned processes with non-nil // `_eventListID` values. @Test("cross-EventList target trap: standalone processes have nil eventListID") func testCrossEventListTargetStubbed() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let bodyAStarted: AsyncExpectation = AsyncExpectation() let processA: LyrebirdProcess = LyrebirdProcess( id: "trap-A", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in bodyAStarted.fulfill() await ctx.wait(30.0) } ) processA.play(engine: engine) _ = await bodyAStarted.waitForFulfillment(timeout: 2.0) // Standalone process has nil eventListID. #expect(processA._eventListID == nil, "Standalone process should have nil _eventListID") // processB targeting .before(processA) — both nil IDs → no trap. let processB: LyrebirdProcess = LyrebirdProcess( id: "trap-B", envelope: sustainedEnvelope(), numChannels: 1, target: .before(processA), body: { ctx in await ctx.wait(30.0) } ) processB.play(engine: engine) #expect(processB.isRunning, "Standalone .before(standalone) should not trap") processA.kill() processB.kill() } // MARK: - Test 11: throwaway group freed after onFinished @Test("throwaway group freed and bus returned to allocator after onFinished") func testThrowawayGroupFreed() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let finished: AsyncExpectation = AsyncExpectation() let capturedBusIndex: Box = Box(-1) let groupExistedDuringBody: Box = Box(false) let process: LyrebirdProcess = LyrebirdProcess( id: "group-free-test", envelope: shortAutoEnvelope(), numChannels: 1, body: { ctx in capturedBusIndex.mutate { $0 = ctx.routeBus.index } groupExistedDuringBody.mutate { $0 = true } await ctx.wait(0.01) }, onFinished: { finished.fulfill() } ) process.play(engine: engine) let ok: Bool = await finished.waitForFulfillment(timeout: 10.0) #expect(ok, "onFinished should fire after envelope auto-ends") #expect(groupExistedDuringBody.get(), "Group should have existed during body") #expect(capturedBusIndex.get() >= 0, "A valid bus index should have been allocated") // After teardown the group reference should be nil. #expect(process._group == nil, "Group should be nil after teardown") #expect(!process.isRunning, "Process should not be running after completion") // Re-allocating the same bus proves it was returned to the allocator. let busIdx: Int = capturedBusIndex.get() let realloc: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) #expect( realloc.index == busIdx, "Freed bus \(busIdx) should be first available for the next allocator caller; got \(realloc.index)" ) engine.busAllocator.releaseAudioBus(realloc) // Engine-level node counts must settle to zero after the process's private // group is freed. Direct synth + nested group hierarchies (`proc._group` // containing `_routeSynth`) need the recursive subtree-decrement path in // `applyEvent(.groupFree)` — without it the routeSynth phantom remains // counted and the status panel reports a non-zero `synthesizerCount` after // every kill cycle. let countSettleDeadlineNs: UInt64 = 1_000_000_000 let pollIntervalNs: UInt64 = 5_000_000 let countSettleStart: UInt64 = DispatchTime.now().uptimeNanoseconds while engine.synthesizerCount != 0 || engine.groupCount != 0 { if DispatchTime.now().uptimeNanoseconds - countSettleStart > countSettleDeadlineNs { break } try? await Task.sleep(nanoseconds: pollIntervalNs) } #expect(engine.synthesizerCount == 0, "synthesizerCount should be 0 after process teardown; got \(engine.synthesizerCount)") #expect(engine.groupCount == 0, "groupCount should be 0 after process teardown; got \(engine.groupCount)") } // MARK: - Test 12 (N6 regression): amp setter before play() updates initial amplitude @Test("N6 regression: amp setter before play() updates initial amplitude, not silently dropped") func testAmpSetterBeforePlay() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let targetAmp: Double = 0.6 let process: LyrebirdProcess = LyrebirdProcess( id: "pre-play-amp", envelope: Envelope( levels: [0.0, 1.0, 0.0], durations: [0.5, 0.5], curves: [.lin, .lin], releaseNode: 2 ), amp: 1.0, numChannels: 1, body: { ctx in await ctx.wait(30.0) } ) // Set amp BEFORE play() — should update _initialAmp, not be silently dropped. process.amp = targetAmp // Verify the getter reflects the pre-play value. #expect( abs(process.amp - targetAmp) < 0.001, "amp getter should return \(targetAmp) before play(); got \(process.amp)" ) process.play(engine: engine) // Give the route synth a moment to be assigned. try await Task.sleep(nanoseconds: 30_000_000) // After play(), the ParameterNode should have been initialised to the pre-set value. let routeSynth: ProcessRouteSynth = try #require(process._routeSynth, "Route synth should exist while running") let nodeValue: Double = routeSynth.$amp.value #expect( abs(nodeValue - targetAmp) < 0.001, "Route synth amp ParameterNode should be \(targetAmp) after pre-play set; got \(nodeValue)" ) process.kill() } // MARK: - Test 13: add to mainHead places synth in mainGroup @Test("addToMainHead places synth into engine mainGroup") func testAddToMainHeadPlacesSynthIntoMainGroup() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let s: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "main-head-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(s, at: .mainHead) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have dispatched the add within timeout") // Allow processBlock to apply the pending add event. try await Task.sleep(nanoseconds: 50_000_000) #expect(engine.mainGroup.contains(s), "Synth should be in mainGroup after .mainHead add") process.kill() // s is in mainGroup (outside the process group) — free it directly. Test-scope // only: no other producer is enqueueing to pendingQueue concurrently. s.free(engine: engine) try await Task.sleep(nanoseconds: 50_000_000) } // MARK: - Test 13b: add to mainTail places synth in mainGroup at the tail @Test("addToMainTail places synth into engine mainGroup at tail") func testAddToMainTailPlacesSynthIntoMainGroupTail() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let sHead: SilentSynth = SilentSynth() let sTail: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "main-tail-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(sHead, at: .mainHead) ctx.add(sTail, at: .mainTail) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have dispatched the adds within timeout") try await Task.sleep(nanoseconds: 50_000_000) #expect(engine.mainGroup.contains(sHead), "sHead should be in mainGroup") #expect(engine.mainGroup.contains(sTail), "sTail should be in mainGroup") // Walk mainGroup head → tail and confirm sHead appears before sTail. var indexOfHead: Int = -1 var indexOfTail: Int = -1 var idx: Int = 0 var node: PreparedNode? = engine.mainGroup.head while let n: PreparedNode = node { if n.synth === sHead { indexOfHead = idx } if n.synth === sTail { indexOfTail = idx } idx += 1 node = n.next } #expect(indexOfHead >= 0 && indexOfTail >= 0, "both synths must be found in mainGroup") #expect(indexOfHead < indexOfTail, "sHead must appear before sTail (got head@\(indexOfHead), tail@\(indexOfTail))") process.kill() sHead.free(engine: engine) sTail.free(engine: engine) try await Task.sleep(nanoseconds: 50_000_000) } // MARK: - Test 14: add to beforeMain places synth in rootGroup before mainGroup @Test("addToBeforeMain places synth in rootGroup before mainGroup") func testAddToBeforeMainPlacesSynthInRootGroupBeforeMainGroup() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let s: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "before-main-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(s, at: .beforeMain) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have dispatched the add within timeout") try await Task.sleep(nanoseconds: 50_000_000) // s should be a direct child of rootGroup (not mainGroup). #expect(engine.rootGroup.contains(s), "Synth should be a child of rootGroup after .beforeMain add") #expect(!engine.mainGroup.contains(s), "Synth should NOT be inside mainGroup") // Verify ordering: s appears before mainGroup in rootGroup's child list. var foundSFirst: Bool = false var node: PreparedNode? = engine.rootGroup.head while let n: PreparedNode = node { if n.synth === s { foundSFirst = true break } if n.synth === engine.mainGroup { break } node = n.next } #expect(foundSFirst, "Synth (beforeMain) should appear before mainGroup in rootGroup child list") process.kill() s.free(engine: engine) try await Task.sleep(nanoseconds: 50_000_000) } // MARK: - Test 15: add to afterMain places synth in rootGroup after mainGroup @Test("addToAfterMain places synth in rootGroup after mainGroup") func testAddToAfterMainPlacesSynthInRootGroupAfterMainGroup() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let s: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "after-main-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(s, at: .afterMain) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) } ) process.play(engine: engine) let ok: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(ok, "Body should have dispatched the add within timeout") try await Task.sleep(nanoseconds: 50_000_000) // s should be a direct child of rootGroup (not mainGroup). #expect(engine.rootGroup.contains(s), "Synth should be a child of rootGroup after .afterMain add") #expect(!engine.mainGroup.contains(s), "Synth should NOT be inside mainGroup") // Verify ordering: mainGroup appears before s in rootGroup's child list. var foundMainFirst: Bool = false var node: PreparedNode? = engine.rootGroup.head while let n: PreparedNode = node { if n.synth === engine.mainGroup { foundMainFirst = true break } if n.synth === s { break } node = n.next } #expect(foundMainFirst, "mainGroup should appear before synth (afterMain) in rootGroup child list") process.kill() s.free(engine: engine) try await Task.sleep(nanoseconds: 50_000_000) } // MARK: - Test 16: ctx.release removes synth from mainGroup (with fallback to free) @Test("ctx.release removes synth from mainGroup; falls back to free when no gate") func testCtxReleaseRemovesSynthFromMainGroup() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let released: AsyncExpectation = AsyncExpectation() let s: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "ctx-release-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(s, at: .mainHead) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) }, onRelease: { ctx in // SilentSynth has no gate — release() throws, free() is the fallback. ctx.release(s) released.fulfill() } ) process.play(engine: engine) let addOK: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(addOK, "Synth should have been added within timeout") try await Task.sleep(nanoseconds: 50_000_000) #expect(engine.mainGroup.contains(s), "Synth should be in mainGroup before release") // Trigger the process release — fires onRelease which calls ctx.release(s). process.release() let releaseOK: Bool = await released.waitForFulfillment(timeout: 5.0) #expect(releaseOK, "onRelease should have fired and called ctx.release") // Allow the free dispatch to land. try await Task.sleep(nanoseconds: 100_000_000) #expect(!engine.mainGroup.contains(s), "Synth should be removed from mainGroup after ctx.release") } // MARK: - Test 17: ctx.free immediately removes synth from mainGroup @Test("ctx.free immediately removes synth from mainGroup") func testCtxFreeImmediatelyRemovesSynthFromMainGroup() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let added: AsyncExpectation = AsyncExpectation() let freed: AsyncExpectation = AsyncExpectation() let s: SilentSynth = SilentSynth() let process: LyrebirdProcess = LyrebirdProcess( id: "ctx-free-test", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctx.add(s, at: .mainHead) try? await Task.sleep(nanoseconds: 100_000_000) added.fulfill() await ctx.wait(30.0) }, onRelease: { ctx in ctx.free(s) freed.fulfill() } ) process.play(engine: engine) let addOK: Bool = await added.waitForFulfillment(timeout: 10.0) #expect(addOK, "Synth should have been added within timeout") try await Task.sleep(nanoseconds: 50_000_000) #expect(engine.mainGroup.contains(s), "Synth should be in mainGroup before free") process.release() let freeOK: Bool = await freed.waitForFulfillment(timeout: 5.0) #expect(freeOK, "onRelease should have fired and called ctx.free") try await Task.sleep(nanoseconds: 100_000_000) #expect(!engine.mainGroup.contains(s), "Synth should be removed from mainGroup after ctx.free") } // MARK: - Test 17: ctx.isRunning / ctx.isReleasing reflect process state @Test("ctx.isRunning starts true, flips false on kill(); body loop using ctx.isRunning exits cleanly") func testCtxIsRunningGatesBodyLoop() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } let bodyEntered: AsyncExpectation = AsyncExpectation() let bodyExited: AsyncExpectation = AsyncExpectation() let observedRunningWhileAlive: Box = Box(false) let loopIterationsAfterKill: Box = Box(0) let observedRunningAfterKill: Box = Box(true) let process: LyrebirdProcess = LyrebirdProcess( id: "ctx-isrunning", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in bodyEntered.fulfill() observedRunningWhileAlive.mutate { $0 = ctx.isRunning } while ctx.isRunning { await ctx.wait(0.005) } observedRunningAfterKill.mutate { $0 = ctx.isRunning } // Demonstrate the loop did exit naturally — bump a counter on // each iteration after the loop body to prove this code ran. loopIterationsAfterKill.mutate { $0 += 1 } bodyExited.fulfill() } ) process.play(engine: engine) let entered: Bool = await bodyEntered.waitForFulfillment(timeout: 5.0) #expect(entered, "Body should have entered") #expect(observedRunningWhileAlive.get(), "ctx.isRunning should be true while body is running") process.kill() let exited: Bool = await bodyExited.waitForFulfillment(timeout: 5.0) #expect(exited, "Body loop should exit after kill() flips ctx.isRunning false") #expect(!observedRunningAfterKill.get(), "ctx.isRunning should be false after kill()") #expect(loopIterationsAfterKill.get() == 1, "Body should run past the while-loop exactly once") } @Test("ctx.isReleasing flips true after release() and stays true through the release tail") func testCtxIsReleasingFlag() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } // Capture ctx into a box from inside the body so the test thread can // query ctx.isReleasing directly — avoids body-Task scheduling flake. let ctxBox: Box = Box(nil) let bodyEntered: AsyncExpectation = AsyncExpectation() let finished: AsyncExpectation = AsyncExpectation() let process: LyrebirdProcess = LyrebirdProcess( id: "ctx-isreleasing", envelope: sustainedEnvelope(), numChannels: 1, body: { ctx in ctxBox.mutate { $0 = ctx } bodyEntered.fulfill() while ctx.isRunning { await ctx.wait(0.01) } }, onFinished: { finished.fulfill() } ) process.play(engine: engine) let entered: Bool = await bodyEntered.waitForFulfillment(timeout: 5.0) #expect(entered) guard let ctx: LyrebirdProcessContext = ctxBox.get() else { Issue.record("ctx was not captured by body") return } #expect(!ctx.isReleasing, "ctx.isReleasing should be false before release()") try await Task.sleep(nanoseconds: 60_000_000) // let attack settle process.release() // Read on the test thread immediately after release() — state transition is synchronous. #expect(ctx.isReleasing, "ctx.isReleasing should be true after release()") let done: Bool = await finished.waitForFulfillment(timeout: 10.0) #expect(done) } // MARK: - Test 18: deinit safety-net returns the route bus when the process // is deallocated before _teardown runs. @Test("LyrebirdProcess deinit returns the allocated route bus to the allocator if dropped while running") func testDeinitReleasesRouteBus() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } // No TestBlockDriver — the process never reaches envelope completion, // so `_teardown` cannot run via the watcher path. We simulate a "dropped // while alive" leak by allocating a process, calling play() to allocate // the route bus, then dropping the strong reference without calling // kill(). let baselineBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let baselineIndex: Int = baselineBus.index engine.busAllocator.releaseAudioBus(baselineBus) do { let process: LyrebirdProcess = LyrebirdProcess( id: "dropped-without-kill", envelope: sustainedEnvelope(), numChannels: 1, body: { _ in // Body never returns — process would normally run forever. try? await Task.sleep(nanoseconds: 60_000_000_000) } ) process.play(engine: engine) // Drop the strong ref by leaving this scope. } // Give the deinit a moment to run on whichever thread released the // process — the body Task captures the context strongly, so deinit // happens once that Task is also released (sustainedEnvelope holds the // process alive only via the route synth which is now orphaned). try await Task.sleep(nanoseconds: 200_000_000) // If the deinit released the bus, allocating a fresh single-channel // bus returns the same index. let realloc: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) #expect( realloc.index == baselineIndex, "Deinit should have returned the route bus to the allocator; got \(realloc.index), baseline \(baselineIndex)" ) engine.busAllocator.releaseAudioBus(realloc) } // MARK: - Test 22: procOut accepts AudioBus directly @Test("init(procOut: AudioBus) stores bus.index in _procOut and threads it into ProcessRouteSynth") func testProcOutAcceptsAudioBus() async throws { let engine: SynthesisEngine = makeProcessTestEngine() try engine.start() defer { engine.stop() } let driver: TestBlockDriver = TestBlockDriver(engine: engine) driver.start() defer { driver.stop() } // Allocate a real AudioBus and pass it directly to LyrebirdProcess.init // via the new `procOut: any ValidBus` API. The process should route to // `targetBus.index` even though the caller never extracted `.index`. let targetBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let targetIndex: Int = targetBus.index engine.busAllocator.releaseAudioBus(targetBus) let finished: AsyncExpectation = AsyncExpectation() let observedProcOut: Box = Box(-1) let process: LyrebirdProcess = LyrebirdProcess( id: "audiobus-procout", envelope: shortAutoEnvelope(), numChannels: 1, procOut: AudioBus(index: targetIndex, channelCount: 1), body: { ctx in await ctx.wait(0.01) }, onFinished: { finished.fulfill() } ) process.play(engine: engine) // Capture the routed-output index from the live route synth before the // envelope auto-frees the process. if let routeSynth: ProcessRouteSynth = process._routeSynth { observedProcOut.mutate { $0 = routeSynth.procOut } } let ok: Bool = await finished.waitForFulfillment(timeout: 10.0) #expect(ok, "onFinished should fire after envelope auto-ends") #expect( observedProcOut.get() == targetIndex, "ProcessRouteSynth.procOut should equal AudioBus.index (\(targetIndex)); got \(observedProcOut.get())" ) } } // MARK: - AsyncExpectation helper /// Minimal async-compatible one-shot fulfillment token for use with Swift Testing. /// /// Uses a polling approach (5 ms interval) to avoid continuation-reuse issues. /// `XCTestExpectation` is not available in Swift Testing. private final class AsyncExpectation: @unchecked Sendable { private let _lock: NSLock = NSLock() private var _fulfilled: Bool = false var isFulfilled: Bool { _lock.withLock { _fulfilled } } func fulfill() { _lock.withLock { _fulfilled = true } } /// Poll until fulfilled or `timeout` seconds elapse. Returns `true` if fulfilled. func waitForFulfillment(timeout: Double) async -> Bool { let pollNs: UInt64 = 5_000_000 // 5 ms poll let deadlineNs: UInt64 = DispatchTime.now().uptimeNanoseconds + UInt64(timeout * 1_000_000_000) while true { if isFulfilled { return true } let nowNs: UInt64 = DispatchTime.now().uptimeNanoseconds if nowNs >= deadlineNs { return isFulfilled } try? await Task.sleep(nanoseconds: pollNs) } } } // MARK: - Box helper /// Thread-safe mutable value box for use in closures captured across threads. private final class Box: @unchecked Sendable { private let _lock: NSLock = NSLock() private var _value: T init(_ value: T) { _value = value } func get() -> T { _lock.withLock { _value } } func mutate(_ transform: (inout T) -> Void) { _lock.withLock { transform(&_value) } } }