// EngineMainGroupTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // Tests for the persistent mainGroup added to SynthesisEngine at init. // MARK: - Helper: value-stamping synthesizer // Test-only Synthesizer; RT-thread mutation of evaluateCallCount is acceptable in test scope only. /// Synthesizer that writes a constant Float value to a control bus every block. /// Used to verify render order by reading bus values in sequence. private final class ControlBusStamper: Synthesizer { let busIndex: Int let value: Float var evaluateCallCount: Int = 0 init( bus: Int, value: Float ) { self.busIndex = bus self.value = value } func build() {} func evaluate(graph: SynthGraph, count: Int) { evaluateCallCount += 1 graph.engine.controlBuses[busIndex] = value } } // MARK: - @Suite("EngineMainGroup") struct EngineMainGroupTests { // MARK: - Structural invariants at init time @Test func mainGroupExistsAfterInit() { let engine: SynthesisEngine = makeTestEngine() // mainGroup is accessible immediately — no start() required. #expect(engine.mainGroup !== engine.rootGroup) } @Test func mainGroupIsDirectChildOfRootGroupAtInit() { let engine: SynthesisEngine = makeTestEngine() // rootGroup holds exactly mainGroup as its sole direct child. #expect(engine.rootGroup.count == 1) #expect(engine.rootGroup.head?.synth === engine.mainGroup) } @Test func mainGroupIsEmptyAtInit() { let engine: SynthesisEngine = makeTestEngine() #expect(engine.mainGroup.count == 0) #expect(engine.mainGroup.isEmpty) } @Test func rootGroupCountIsOneAfterInit() { let engine: SynthesisEngine = makeTestEngine() // rootGroup always has exactly 1 direct child (mainGroup) at init. #expect(engine.rootGroup.count == 1) } // MARK: - Default add target @Test func defaultAddLandsInMainGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.contains(synth)) } @Test func defaultAddDoesNotLandDirectlyInRootGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) // rootGroup only contains mainGroup as a direct child, not the synth. #expect(!engine.rootGroup.contains(synth)) } @Test func addTwoSynthsNewerAtHead() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let first: TrackingNode = TrackingNode() let second: TrackingNode = TrackingNode() try engine.add(first) engine.processBlock(inputSamples: []) try engine.add(second) engine.processBlock(inputSamples: []) // second was added last → lands at mainGroup.head (newest-first). #expect(engine.mainGroup.head?.synth === second) } @Test func addedSynthsEvaluateViaMainGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(synth.evaluateCallCount == 2) } // MARK: - Pre-main and post-main positioning @Test func addBeforeMainGroupInsertsIntoRootGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let preSynth: TrackingNode = TrackingNode() try engine.add(preSynth, position: .before(engine.mainGroup)) engine.processBlock(inputSamples: []) // preSynth sits in rootGroup immediately before mainGroup. #expect(engine.rootGroup.contains(preSynth)) #expect(!engine.mainGroup.contains(preSynth)) } @Test func addAfterMainGroupInsertsIntoRootGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let postSynth: TrackingNode = TrackingNode() try engine.add(postSynth, position: .after(engine.mainGroup)) engine.processBlock(inputSamples: []) #expect(engine.rootGroup.contains(postSynth)) #expect(!engine.mainGroup.contains(postSynth)) } @Test func secondPreMainInsertionPushesFirstAwayFromMainGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let pre1: TrackingNode = TrackingNode() let pre2: TrackingNode = TrackingNode() try engine.add(pre1, position: .before(engine.mainGroup)) engine.processBlock(inputSamples: []) try engine.add(pre2, position: .before(engine.mainGroup)) engine.processBlock(inputSamples: []) // Structure: [pre1] [pre2] [mainGroup] ... // pre2 is immediately before mainGroup; pre1 is before pre2. // Walk rootGroup to find mainGroup position: var node: PreparedNode? = engine.rootGroup.head var order: [ObjectIdentifier] = [] while let n: PreparedNode = node { order.append(ObjectIdentifier(n.synth)) node = n.next } let mainGroupID: ObjectIdentifier = ObjectIdentifier(engine.mainGroup) let pre1ID: ObjectIdentifier = ObjectIdentifier(pre1) let pre2ID: ObjectIdentifier = ObjectIdentifier(pre2) if let idxMain: Int = order.firstIndex(of: mainGroupID), let idxPre1: Int = order.firstIndex(of: pre1ID), let idxPre2: Int = order.firstIndex(of: pre2ID) { // pre1 < pre2 < mainGroup in render order #expect(idxPre1 < idxPre2) #expect(idxPre2 < idxMain) } else { Issue.record("pre1, pre2, or mainGroup not found in rootGroup walk") } } // MARK: - Render order @Test func renderOrderIsPreMainThenMainThenPostMain() throws { let engine: SynthesisEngine = makeTestEngine( blockSize: 8, numAudioBuses: 16, numControlBuses: 4096 ) try engine.start() // Each stamper overwrites control bus 0 with its tag value. // The last writer in evaluation order wins: reading bus 0 after processBlock // reveals which zone evaluated last. let probeControlBus: Int = 10 let preNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 1.0) let mainNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 2.0) let postNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 3.0) try engine.add(preNode, position: .before(engine.mainGroup)) try engine.add(mainNode) try engine.add(postNode, position: .after(engine.mainGroup)) engine.processBlock(inputSamples: []) // postNode evaluated last → its value (3.0) wins. #expect(engine.controlBuses[probeControlBus] == 3.0) } @Test func preMainEvaluatesBeforeMain() throws { let engine: SynthesisEngine = makeTestEngine( blockSize: 8, numAudioBuses: 16, numControlBuses: 4096 ) try engine.start() let probeControlBus: Int = 11 let preNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 10.0) let mainNode: ControlBusStamper = ControlBusStamper(bus: probeControlBus, value: 20.0) try engine.add(preNode, position: .before(engine.mainGroup)) try engine.add(mainNode) engine.processBlock(inputSamples: []) // mainNode evaluated after preNode → mainNode's value (20.0) wins. #expect(engine.controlBuses[probeControlBus] == 20.0) } // MARK: - groupFree on persistent groups is suppressed @Test func groupFreeOnMainGroupIsNoOp() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) // Directly calling free on mainGroup should be suppressed. engine.mainGroup.free(engine: engine) engine.processBlock(inputSamples: []) // mainGroup is still a direct child of rootGroup. #expect(engine.rootGroup.head?.synth === engine.mainGroup) // mainGroup still contains the synth (its children were NOT drained). #expect(engine.mainGroup.contains(synth)) } @Test func groupFreeOnRootGroupIsNoOp() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() engine.rootGroup.free(engine: engine) engine.processBlock(inputSamples: []) // rootGroup and mainGroup are both still in place. #expect(engine.rootGroup.head?.synth === engine.mainGroup) #expect(engine.rootGroup.count == 1) } @Test func groupFreeCountersUnchangedAfterPersistentFreeAttempt() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) let synthCountBefore: Int = engine.synthesizerCount engine.mainGroup.free(engine: engine) engine.processBlock(inputSamples: []) #expect(engine.synthesizerCount == synthCountBefore) } // MARK: - mainGroup.release cascade — persistent group survives @Test func mainGroupReleaseWithNoGateChildrenDrainsMainGroupButGroupPersists() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() // default release throws noGate → free immediately try engine.add(synth) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.contains(synth)) // release() cascades to the child; since it has no gate it gets freed via child.free(). engine.mainGroup.release(engine: engine) // child.free posts a remove event; synth should be gone after next processBlock. engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) // Child was removed, but mainGroup itself persists. #expect(engine.mainGroup.count == 0) #expect(engine.rootGroup.head?.synth === engine.mainGroup, "mainGroup must remain as rootGroup's direct child after release cascade") } @Test func canAddToMainGroupAfterReleaseCascadeDrains() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) engine.mainGroup.release(engine: engine) engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 0) // Re-add after drain — mainGroup must accept new children. let newSynth: TrackingNode = TrackingNode() try engine.add(newSynth) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.contains(newSynth)) } // MARK: - rootGroup remains as-is @Test func rootGroupCountIsAlwaysAtLeastOneWhileEngineAlive() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() // Advance several blocks. engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(engine.rootGroup.count == 1) } @Test func removeDoesNotRemoveMainGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() // engine.remove on a persistent group is silently ignored (language-side guard). engine.remove(engine.mainGroup) engine.processBlock(inputSamples: []) // mainGroup must still be the sole direct child of rootGroup after the ignored remove. #expect(engine.rootGroup.count == 1) #expect(engine.rootGroup.head?.synth === engine.mainGroup) } // MARK: - B1 regression: second release cascades new children /// Verify that a persistent group's _releaseStarted flag is reset after each release /// so a subsequent release() correctly cascades to any new children added in the interim. @Test func secondReleaseCascadesNewChildren() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() // Round 1: add 2 children, release, settle until empty. let firstA: TrackingNode = TrackingNode() let firstB: TrackingNode = TrackingNode() try engine.add(firstA) try engine.add(firstB) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 2) engine.mainGroup.release(engine: engine) engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 0, "First release: mainGroup should be empty after settling") // Round 2: add 2 new children, release again, settle until empty. let secondA: TrackingNode = TrackingNode() let secondB: TrackingNode = TrackingNode() try engine.add(secondA) try engine.add(secondB) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 2) // This call would be silently dropped before B1 was fixed — _releaseStarted was // stuck at true from the first release, so only round 2's children would persist. engine.mainGroup.release(engine: engine) engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 0, "Second release: mainGroup should be empty after settling") // mainGroup itself must remain attached to rootGroup throughout. #expect(engine.rootGroup.head?.synth === engine.mainGroup) } // MARK: - stop() drains all non-persistent nodes @Test func stopDrainsMainGroupChildren() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let synth: TrackingNode = TrackingNode() try engine.add(synth) engine.processBlock(inputSamples: []) #expect(engine.mainGroup.count == 1) engine.stop() #expect(engine.mainGroup.count == 0) #expect(engine.mainGroup.head == nil) #expect(engine.mainGroup.tail == nil) #expect(engine.synthesizerCount == 0) } @Test func stopDrainsPreAndPostMainNodes() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let pre: TrackingNode = TrackingNode() let post: TrackingNode = TrackingNode() try engine.add(pre, position: .before(engine.mainGroup)) try engine.add(post, position: .after(engine.mainGroup)) engine.processBlock(inputSamples: []) #expect(engine.rootGroup.count == 3) // pre + mainGroup + post engine.stop() // rootGroup is back to its initial shape: mainGroup is the sole child. #expect(engine.rootGroup.count == 1) #expect(engine.rootGroup.head?.synth === engine.mainGroup) #expect(engine.rootGroup.tail?.synth === engine.mainGroup) #expect(engine.synthesizerCount == 0) } @Test func stopPreservesPersistentRootAndMainGroup() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) let originalRoot: Group = engine.rootGroup let originalMain: Group = engine.mainGroup try engine.start() try engine.add(TrackingNode()) engine.processBlock(inputSamples: []) engine.stop() // Identity preserved — same `Group` instances. #expect(engine.rootGroup === originalRoot) #expect(engine.mainGroup === originalMain) #expect(engine.rootGroup.head?.synth === engine.mainGroup) } @Test func stopDrainsNestedUserGroups() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let nested: Group = Group() try engine.add(nested) try engine.add(TrackingNode(), position: .head(of: nested)) try engine.add(TrackingNode(), position: .tail(of: nested)) engine.processBlock(inputSamples: []) #expect(engine.groupCount == 1) #expect(engine.synthesizerCount == 2) engine.stop() #expect(engine.groupCount == 0) #expect(engine.synthesizerCount == 0) } @Test func restartAfterStopBeginsFromEmptyBaseline() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() try engine.add(TrackingNode()) try engine.add(TrackingNode()) engine.processBlock(inputSamples: []) #expect(engine.synthesizerCount == 2) engine.stop() try engine.start() defer { engine.stop() } #expect(engine.synthesizerCount == 0) #expect(engine.groupCount == 0) #expect(engine.mainGroup.count == 0) #expect(engine.rootGroup.count == 1) #expect(engine.rootGroup.head?.synth === engine.mainGroup) } @Test func stopDrainsCarryOverEvents() throws { // A future-dated `engine.remove(synth, at:)` parks in `carryOverEvents` // until its target time arrives. Without the carryOverEvents drain in // `_drainAllNonPersistentNodes`, the `Unmanaged.passRetained` ref inside // the `.remove` event would never balance after `stop()` — a synth ARC // leak. This test verifies the drain by asserting `carryOverEvents` // is empty (its capacity is preserved, so it returns to the same shape // as a freshly-started engine). let engine: SynthesisEngine = makeTestEngine(blockSize: 8) let synth: TrackingNode = TrackingNode() try engine.start() try engine.add(synth) engine.processBlock(inputSamples: []) // Future-dated remove — far enough out that the RT thread routes it // into `carryOverEvents` rather than firing this block. let farFuture: SampleTime = engine.currentTime + engine.seconds(60.0) _ = engine.remove(synth, at: farFuture) engine.processBlock(inputSamples: []) // The remove is now parked in carryOverEvents holding a retained ref. #expect(engine.carryOverEvents.contains { event in if case .remove = event { return true } return false }) engine.stop() // Drain emptied carryOverEvents; if its passRetained ref had not been // released, ARC would still hold the synth via the event existential. #expect(engine.carryOverEvents.isEmpty) #expect(engine.synthesizerCount == 0) #expect(engine.mainGroup.count == 0) } @Test func postStopGroupFreeDoesNotPushSynthCountNegative() throws { // Regression: a `Group.free(engine:)` call landing in `pendingQueue` // AFTER `engine.stop()` returned would, on the next `start()`, run // `applyEvent(.groupFree)`. The handler walked the group's still- // populated internal linked list and decremented `_synthesizerCount` // per descendant — but `stop()` already zeroed the counter via // `_drainAllNonPersistentNodes`. Result: counter wrapped negative. // // Triggers in practice: any caller that holds a `Group` strongly // across stop/restart and frees it after stop returns — // `LyrebirdProcess._teardown` (group.free via its watcher timer), // `LyrebirdEventList` cleanup, ad-hoc app teardown paths. let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() let nested: Group = Group() try engine.add(nested) try engine.add(TrackingNode(), position: .head(of: nested)) try engine.add(TrackingNode(), position: .tail(of: nested)) engine.processBlock(inputSamples: []) #expect(engine.synthesizerCount == 2) #expect(engine.groupCount == 1) engine.stop() #expect(engine.synthesizerCount == 0) #expect(engine.groupCount == 0) // Free the group AFTER stop — enqueues `.groupFree` to pendingQueue. // The pendingQueue drain in `_drainAllNonPersistentNodes` ran during // stop(), so this event will be applied by the next start(). nested.free(engine: engine) try engine.start() defer { engine.stop() } // Pump one block so the RT thread drains pendingQueue. engine.processBlock(inputSamples: []) #expect(engine.synthesizerCount == 0, "synthesizerCount must not go negative after post-stop groupFree") #expect(engine.groupCount == 0, "groupCount must not go negative after post-stop groupFree") } @Test func stopResetsNodeTreeMirror() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 8) try engine.start() try engine.add(TrackingNode()) try engine.add(TrackingNode()) engine.processBlock(inputSamples: []) // Before stop: rootGroup contains mainGroup, mainGroup contains 2 synths. let beforeRoot: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root let beforeMain: NodeTreeSnapshot.Node? = beforeRoot.children.first #expect(beforeMain?.children.count == 2) engine.stop() // After stop: rootGroup contains mainGroup, mainGroup is empty. let afterRoot: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root #expect(afterRoot.children.count == 1) let afterMain: NodeTreeSnapshot.Node? = afterRoot.children.first #expect(afterMain?.children.isEmpty == true) } }