// EventConductorTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import Synchronization import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // MARK: - Shared fixture /// A fresh voice per event, counting `build()` calls so a test can observe when (and whether) the /// conductor has started a pattern. private final class CondVoice: SynthesizerBase { @LiveParam var freq: Double = 0.0 nonisolated static let buildCount: Atomic = Atomic(0) override func build() { CondVoice.buildCount.wrappingAdd(1, ordering: .releasing) output(bus: 0, source: $freq) } } /// Builds a two-event finite pattern at `tempo`. @MainActor private func makeFinitePattern(tempo: Double) -> EventPattern { EventPattern(make: { CondVoice() }) .bind(\.freq, .sequence([440.0, 550.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(tempo) } /// Builds a never-ending fast pattern at `tempo` — its build counter keeps climbing until stopped, /// so a test can detect a child the conductor failed to halt. @MainActor private func makeInfinitePattern(tempo: Double) -> EventPattern { EventPattern(make: { CondVoice() }) .bind(\.freq, .uniformRandom(low: 100.0, high: 200.0)) .dur(.sequence([0.05])) .tempo(tempo) } // MARK: - Conductor playback /// `EventConductor` live, clock-driven playback. Serialized because the fixture shares a static /// build counter. @Suite("EventConductor", .serialized) struct EventConductorTests { @Test func quantiseDelaysEntryThenPlays() async { CondVoice.buildCount.store(0, ordering: .releasing) // afterBeats(2) at 120 BPM = a 1.0 s lead-in before the first voice is built. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) c.add(makeFinitePattern(tempo: 120.0), quantize: .afterBeats(2.0)) return c } // Well inside the lead-in: nothing built yet, but the conductor clock is running. try? await Task.sleep(for: .milliseconds(300)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) #expect(conductor.isRunning) // After the boundary the pattern runs to completion: both events fire. let deadline: Date = Date().addingTimeInterval(2.0) while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(CondVoice.buildCount.load(ordering: .acquiring) == 2) conductor.stop() } @Test func nextMultipleEntersOnGrid() async { CondVoice.buildCount.store(0, ordering: .releasing) // nextMultiple(ofBeats: 2) at 120 BPM: the next bar line is at beat 2 = 1.0 s out. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) c.add(makeFinitePattern(tempo: 120.0), quantize: .nextMultiple(ofBeats: 2.0)) return c } try? await Task.sleep(for: .milliseconds(300)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) let deadline: Date = Date().addingTimeInterval(2.5) while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(CondVoice.buildCount.load(ordering: .acquiring) == 2) conductor.stop() } @Test func liveAddAfterStartPlaysAndIdles() async { CondVoice.buildCount.store(0, ordering: .releasing) // Start the conductor empty, as a running engine would sit waiting for input. The pattern // is built on the main actor (its `\.freq` key path is main-actor-isolated) but not yet // handed over; the conductor supplies the engine later. let (conductor, pattern): (EventConductor, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) let p: EventPattern = EventPattern(make: { CondVoice() }) .bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(240.0) return (c, p) } // Add it AFTER start, from off the main thread — standing in for a UI / OSC / MIDI callback. conductor.add(pattern, quantize: .nextBeat) // waitUntilIdle (off main here) blocks until the pattern has entered and finished. conductor.waitUntilIdle() #expect(CondVoice.buildCount.load(ordering: .acquiring) == 3) #expect(!conductor.hasActiveChildren) conductor.stop() } @Test func addBeforeStartIsServicedAfterStart() async { CondVoice.buildCount.store(0, ordering: .releasing) // Queue a pattern, THEN start — the conductor must service the pre-start inbox on its first // poll relative to beat 0. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.add(makeFinitePattern(tempo: 240.0), quantize: .now) // before start c.start(on: engine) return c } conductor.waitUntilIdle() #expect(CondVoice.buildCount.load(ordering: .acquiring) == 2) #expect(!conductor.hasActiveChildren) conductor.stop() } @Test func multipleAddsInOnePollAllPlay() async { CondVoice.buildCount.store(0, ordering: .releasing) // Three finite patterns added before the first poll — all must enter and finish. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.add(makeFinitePattern(tempo: 240.0), quantize: .now) c.add(makeFinitePattern(tempo: 240.0), quantize: .now) c.add(makeFinitePattern(tempo: 240.0), quantize: .now) c.start(on: engine) return c } conductor.waitUntilIdle() #expect(CondVoice.buildCount.load(ordering: .acquiring) == 6) // 3 patterns × 2 events #expect(!conductor.hasActiveChildren) conductor.stop() } @Test func polytempoEntryAlignsToConductorClock() async { CondVoice.buildCount.store(0, ordering: .releasing) // Conductor at 120, pattern at 60 (half tempo). Entry must align to the CONDUCTOR'S grid — // the bar at conductor beat 2 (1.0 s) — not be stretched by the pattern's slow tempo. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) let slow: EventPattern = EventPattern(make: { CondVoice() }) .bind(\.freq, .sequence([440.0, 550.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(60.0) c.add(slow, quantize: .nextMultiple(ofBeats: 2.0)) return c } // Still inside the 1.0 s conductor lead-in: nothing built. try? await Task.sleep(for: .milliseconds(300)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) // Enters on the conductor's bar line and runs to completion. let deadline: Date = Date().addingTimeInterval(2.5) while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(CondVoice.buildCount.load(ordering: .acquiring) == 2) conductor.stop() } @Test func currentBeatAdvancesWhileRunning() async { let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) return c } #expect(conductor.currentBeat >= 0.0) try? await Task.sleep(for: .milliseconds(500)) // 500 ms at 120 BPM ≈ 1.0 beat; assert a generous lower bound to avoid CI-load flake. #expect(conductor.currentBeat > 0.3) conductor.stop() } @Test func stopDuringStartHaltsEverything() async { // Race stop() against the inbox service across many iterations with a randomised sub-poll // delay, so some iterations land stop() mid-hop (the post-hop `.stopped` branch) rather than // before the first 10 ms poll. After each iteration nothing may keep playing. for iteration: Int in 0..<24 { CondVoice.buildCount.store(0, ordering: .releasing) let (conductor, patterns): (EventConductor, [EventPattern]) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) let ps: [EventPattern] = (0..<4).map { _ in makeInfinitePattern(tempo: 240.0) } return (c, ps) } for pattern: EventPattern in patterns { conductor.add(pattern, quantize: .now) } // 0–15 ms: sometimes before the first poll, sometimes mid-service. let delayMs: Int = (iteration * 7) % 16 if delayMs > 0 { try? await Task.sleep(for: .milliseconds(delayMs)) } conductor.stop() // Let any in-flight start land and any missed child reveal itself by climbing the counter. try? await Task.sleep(for: .milliseconds(120)) let countA: Int = CondVoice.buildCount.load(ordering: .acquiring) try? await Task.sleep(for: .milliseconds(120)) let countB: Int = CondVoice.buildCount.load(ordering: .acquiring) #expect(countA == countB, "iteration \(iteration): a child kept building after stop()") #expect(!conductor.hasActiveChildren, "iteration \(iteration): active child survived stop()") #expect(!conductor.isRunning) } } @Test func stopHaltsConductorAndChildren() async { CondVoice.buildCount.store(0, ordering: .releasing) // An infinite pattern, started immediately. let conductor: EventConductor = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) c.add(makeInfinitePattern(tempo: 120.0), quantize: .now) return c } try? await Task.sleep(for: .milliseconds(200)) #expect(conductor.hasActiveChildren) conductor.stop() let deadline: Date = Date().addingTimeInterval(2.0) while conductor.hasActiveChildren, Date() < deadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(!conductor.hasActiveChildren) #expect(!conductor.isRunning) // A stopped conductor ignores further adds. let countAfterStop: Int = CondVoice.buildCount.load(ordering: .acquiring) await MainActor.run { conductor.add(makeFinitePattern(tempo: 120.0), quantize: .now) } try? await Task.sleep(for: .milliseconds(150)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == countAfterStop) } @Test func concurrentAddsFromManyThreadsAllPlay() async { CondVoice.buildCount.store(0, ordering: .releasing) let patternCount: Int = 8 let (conductor, patterns): (EventConductor, [EventPattern]) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) let ps: [EventPattern] = (0..) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) return (c, makeFinitePattern(tempo: 240.0)) } let handle: EventConductorHandle = conductor.add(pattern, quantize: .now) #expect(handle.isPlaying) // pending → reports playing before it even enters conductor.waitUntilIdle() #expect(!handle.isPlaying) // finite pattern finished #expect(CondVoice.buildCount.load(ordering: .acquiring) == 2) conductor.stop() } @Test func perPartStopLeavesOtherPartsPlaying() async { CondVoice.buildCount.store(0, ordering: .releasing) let (conductor, patternA, patternB): (EventConductor, EventPattern, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) return (c, makeInfinitePattern(tempo: 240.0), makeInfinitePattern(tempo: 240.0)) } let handleA: EventConductorHandle = conductor.add(patternA, quantize: .now) let handleB: EventConductorHandle = conductor.add(patternB, quantize: .now) // Wait until both have entered and are building voices. let entryDeadline: Date = Date().addingTimeInterval(1.0) while !conductor.hasActiveChildren, Date() < entryDeadline { try? await Task.sleep(for: .milliseconds(20)) } try? await Task.sleep(for: .milliseconds(150)) #expect(handleA.isPlaying) #expect(handleB.isPlaying) // Stop ONE part. Its pattern tears down (an infinite pattern's teardown is not instant), so // poll its handle with a deadline rather than assuming a fixed delay. handleA.stop() let aStopDeadline: Date = Date().addingTimeInterval(2.0) while handleA.isPlaying, Date() < aStopDeadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(!handleA.isPlaying) // the stopped part is gone // The other part must keep playing and keep building voices. let countAfterStopA: Int = CondVoice.buildCount.load(ordering: .acquiring) try? await Task.sleep(for: .milliseconds(250)) let countLater: Int = CondVoice.buildCount.load(ordering: .acquiring) #expect(handleB.isPlaying) // the other part survives #expect(conductor.hasActiveChildren) #expect(countLater > countAfterStopA) // part B kept building conductor.stop() let stopDeadline: Date = Date().addingTimeInterval(2.0) while handleB.isPlaying, Date() < stopDeadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(!handleB.isPlaying) #expect(!conductor.hasActiveChildren) } @Test func handleStopBeforeEntryNeverBuilds() async { CondVoice.buildCount.store(0, ordering: .releasing) // afterBeats(1) at 240 BPM = a 0.25 s lead-in, so the entry falls WELL INSIDE the wait // window below: were the pre-entry cancel skip removed, the pattern would enter and build. // The immediate stop() must prevent that. let (conductor, pattern): (EventConductor, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) return (c, makeInfinitePattern(tempo: 240.0)) } let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(1.0)) handle.stop() // cancel while still pending // waitUntilIdle must return (covers `_starting` decrement on the skip path); the entry // window (0.25 s) elapses well within the wait. conductor.waitUntilIdle() try? await Task.sleep(for: .milliseconds(350)) #expect(!handle.isPlaying) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) // never entered #expect(!conductor.hasActiveChildren) conductor.stop() } @Test func addAfterStopReturnsStoppedHandle() async { CondVoice.buildCount.store(0, ordering: .releasing) let (conductor, pattern): (EventConductor, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) return (c, makeInfinitePattern(tempo: 240.0)) } conductor.stop() // Adding to a stopped conductor returns an already-cancelled handle and never builds. let handle: EventConductorHandle = conductor.add(pattern, quantize: .now) #expect(!handle.isPlaying) try? await Task.sleep(for: .milliseconds(150)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) } @Test func conductorStopCancelsPendingHandle() async { CondVoice.buildCount.store(0, ordering: .releasing) // A part queued far out, then the whole conductor stopped before it enters: its handle must // report not-playing and it must never build a voice. let (conductor, pattern): (EventConductor, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 120.0) c.start(on: engine) return (c, makeInfinitePattern(tempo: 120.0)) } let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(8.0)) // 4 s out try? await Task.sleep(for: .milliseconds(100)) // let it resolve into _pending conductor.stop() try? await Task.sleep(for: .milliseconds(150)) #expect(!handle.isPlaying) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) } @Test func handleAddedBeforeStartCanBeStopped() async { CondVoice.buildCount.store(0, ordering: .releasing) // Add BEFORE start (the _inbox path), stop the handle, THEN start. It must never enter. let (conductor, handle): (EventConductor, EventConductorHandle) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) let h: EventConductorHandle = c.add(makeInfinitePattern(tempo: 240.0), quantize: .now) h.stop() c.start(on: engine) return (c, h) } try? await Task.sleep(for: .milliseconds(200)) #expect(!handle.isPlaying) #expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) #expect(!conductor.hasActiveChildren) conductor.stop() } @Test func handleStopRacingEntryNeverLeaksAChild() async { // Stress the per-part stop against the entry hop: add one infinite part `.now`, stop its // handle after a randomised sub-poll delay, and confirm nothing keeps playing. Exercises the // pre-hop skip and the attach-after-cancel path. for iteration: Int in 0..<24 { CondVoice.buildCount.store(0, ordering: .releasing) let (conductor, pattern): (EventConductor, EventPattern) = await MainActor.run { let engine: SynthesisEngine = makeTestEngine() let c: EventConductor = EventConductor(tempo: 240.0) c.start(on: engine) return (c, makeInfinitePattern(tempo: 240.0)) } let handle: EventConductorHandle = conductor.add(pattern, quantize: .now) let delayMs: Int = (iteration * 7) % 16 if delayMs > 0 { try? await Task.sleep(for: .milliseconds(delayMs)) } handle.stop() let deadline: Date = Date().addingTimeInterval(2.0) while handle.isPlaying, Date() < deadline { try? await Task.sleep(for: .milliseconds(20)) } #expect(!handle.isPlaying, "iteration \(iteration): part kept playing after handle.stop()") // Counter must stabilise — no orphaned child building on. let countA: Int = CondVoice.buildCount.load(ordering: .acquiring) try? await Task.sleep(for: .milliseconds(120)) #expect(CondVoice.buildCount.load(ordering: .acquiring) == countA, "iteration \(iteration): a child kept building after handle.stop()") conductor.stop() } } } /// Carries the main-built patterns into the `concurrentPerform` closure without tripping Sendable /// checking — the array is read-only after construction and each index is touched once. private final class PatternBox: @unchecked Sendable { private let patterns: [EventPattern] init(_ patterns: [EventPattern]) { self.patterns = patterns } func add(into conductor: EventConductor, index: Int) { conductor.add(patterns[index], quantize: .now) } }