Files
Lyrebird/Tests/LyrebirdTests/Parameters/ParameterNodeSourceSlotTests.swift
T
2026-06-01 18:27:40 -07:00

480 lines
22 KiB
Swift

// ParameterNodeSourceSlotTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Helper generators for source-slot tests
/// Simple constant-output audio-rate generator used as a source in tests.
/// Produces a flat block at `outputValue`. Single channel.
private final class ConstantSource: GeneratorBase, AudioGenerator {
let outputValue: Double
init(_ value: Double) {
outputValue = value
super.init()
}
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count)
for i: Int in 0..<count { _result[0][i] = outputValue }
return _result
}
func floatValue(graph: SynthGraph) -> Double { outputValue }
}
/// Mutable bool flag used as a deinit sentinel. A class wrapper so it can be observed
/// after the generator that holds a reference to it is dealloc'd.
private final class DeinitFlag {
var fired: Bool = false
}
/// Source generator whose deinit writes `true` to an external `DeinitFlag`.
/// Used to verify ARC release fires off the RT thread.
private final class SentinelSource: GeneratorBase, AudioGenerator {
let outputValue: Double
// External flag written from deinit — must outlive the SentinelSource instance.
private let _deinitFlag: DeinitFlag
init(_ value: Double, deinitFlag: DeinitFlag) {
outputValue = value
_deinitFlag = deinitFlag
super.init()
}
deinit {
_deinitFlag.fired = true
}
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count)
for i: Int in 0..<count { _result[0][i] = outputValue }
return _result
}
func floatValue(graph: SynthGraph) -> Double { outputValue }
}
// MARK: - Test suite
@Suite("ParameterNode source slot")
struct ParameterNodeSourceSlotTests {
// MARK: - 1. Scalar path unchanged when no source is set
@Test func scalarPathUnchangedWhenNoSourceSet() {
// Baseline: a ParameterNode with no source set should produce the same ramping
// scalar output as pre-Stage-2. Ramp from 0 → 1 over 8 samples.
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
let graph: SynthGraph = makeSynthGraph(engine: engine)
let node: ParameterNode = ParameterNode(0.0)
node.value = 1.0
let samples: [Double] = node.calculatedSamples(graph: graph, count: 8)[0]
// Expected ramp: step = 1.0/8 = 0.125; samples = [0.125, 0.25, ..., 1.0]
let expected: [Double] = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]
for (i, (s, e)) in zip(samples.prefix(8), expected).enumerated() {
#expect(abs(s - e) < 1e-12, "Sample \(i): expected \(e), got \(s)")
}
// Verify _sourceSlot is nil — no swap was performed
#expect(node._sourceSlot == nil)
}
// MARK: - 2. Source swap is observable in the next block
@Test func sourceSwapIsObservable() {
// Enqueue a ConstantSource(42.0) via _sourceQueue, render one block,
// verify all output samples are 42.0.
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
// Block 1: no source. Advance serial first so we get a fresh evaluation.
advanceBlock(engine)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: graph1, count: blockSize)
#expect(node._sourceSlot == nil)
// Enqueue a source for block 2.
let src: ConstantSource = ConstantSource(42.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src))
// Block 2: drain happens inside calculatedSamples — source is installed.
advanceBlock(engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
let samples: [Double] = node.calculatedSamples(graph: graph2, count: blockSize)[0]
// All samples should be 42.0 (constant source).
for (i, s) in samples.prefix(blockSize).enumerated() {
#expect(abs(s - 42.0) < 1e-12, "Block 2 sample \(i): expected 42.0, got \(s)")
}
#expect(node._sourceSlot != nil, "Source slot should be non-nil after swap")
// Clean up: drain kill queue to release any retained pointers.
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - 3. Revert to scalar works
@Test func revertToScalarWorks() {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(10.0)
// Block 1: install source (constant 99.0).
let src: ConstantSource = ConstantSource(99.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src))
advanceBlock(engine)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let block1: [Double] = node.calculatedSamples(graph: g1, count: blockSize)[0]
// Should be 99.0 from the source.
#expect(abs(block1[blockSize - 1] - 99.0) < 1e-12)
#expect(node._sourceSlot != nil)
// Block 2: enqueue revert-to-scalar.
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let block2: [Double] = node.calculatedSamples(graph: g2, count: blockSize)[0]
// After revert, scalar target is still 10.0.
// previousOutputValue was updated to 99.0 in block 1 (last sample of source).
// So block 2 ramps from 99.0 → 10.0 over 8 samples.
let step: Double = (10.0 - 99.0) / Double(blockSize)
for (i, s) in block2.prefix(blockSize).enumerated() {
let expected: Double = 99.0 + step * Double(i + 1)
#expect(abs(s - expected) < 1e-12, "Revert block sample \(i): expected \(expected), got \(s)")
}
#expect(node._sourceSlot == nil, "Source slot should be nil after revert")
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - 4. Old source is enqueued on kill queue when swapped out
@Test func oldSourceEnqueuedOnKillQueueWhenSwappedOut() {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
// Block 1: install first source.
let src1: ConstantSource = ConstantSource(1.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src1))
advanceBlock(engine)
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g1, count: blockSize)
// Block 2: install second source — src1 should be pushed to kill queue.
let src2: ConstantSource = ConstantSource(2.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src2))
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g2, count: blockSize)
// Kill queue should have exactly one entry (the old src1).
let drainCount: Int = engine.drainParameterSourceKillQueue()
#expect(drainCount == 1, "Expected 1 item in kill queue (old src1), got \(drainCount)")
// Clean up src2 when it eventually gets displaced.
// (It's still live in _sourceSlot — no more displacement happened.)
// Force displacement via revert-to-scalar.
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g3: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g3, count: blockSize)
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - 5. Kill-queue drain releases (no leak)
@Test func killQueueDrainReleasesGenerator() {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
let deinitFlag: DeinitFlag = DeinitFlag()
do {
// Scope: create sentinel, install it, then displace it.
let sentinel: SentinelSource = SentinelSource(77.0, deinitFlag: deinitFlag)
// Block 1: install sentinel.
node._sourceQueue.enqueue(SourcePacket.handoff(sentinel))
advanceBlock(engine)
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g1, count: blockSize)
// sentinel is now in _sourceSlot (1 RT ref) + local `sentinel` (1 local ref) = 2
// Block 2: displace sentinel with revert-to-scalar.
// RT thread will passRetained(sentinel) → kill queue, then _sourceSlot = nil.
// Kill queue holds 1 ref; local `sentinel` still holds 1 ref. Total = 2.
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g2, count: blockSize)
// Now kill queue holds 1 ref, local `sentinel` holds 1 ref.
// Sentinel falls out of scope here → local ref drops → kill queue holds last ref.
}
// sentinel's local reference is dropped. Kill queue holds the final retain.
#expect(!deinitFlag.fired, "Sentinel deinit must not fire before drain")
let drainCount: Int = engine.drainParameterSourceKillQueue()
#expect(drainCount == 1, "Expected 1 item drained, got \(drainCount)")
#expect(deinitFlag.fired, "Sentinel deinit must fire after drain")
}
// MARK: - 6. Multiple rapid swaps — only latest is live, older on kill queue
@Test func multipleRapidSwapsOnlyLatestIsLive() {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
// Block 1: install initial source so _sourceSlot is occupied.
let src0: ConstantSource = ConstantSource(0.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src0))
advanceBlock(engine)
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g1, count: blockSize)
// Enqueue 3 more source packets in rapid succession (before next block render).
// The drain in block 2 will pick the LAST one as live and drop the first two.
let src1: ConstantSource = ConstantSource(10.0)
let src2: ConstantSource = ConstantSource(20.0)
let src3: ConstantSource = ConstantSource(30.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src1))
node._sourceQueue.enqueue(SourcePacket.handoff(src2))
node._sourceQueue.enqueue(SourcePacket.handoff(src3))
// Block 2: drain picks src3 as live; src1 and src2 are in droppedPayloads → kill queue.
// The old _sourceSlot (src0) is also pushed to kill queue.
// Kill queue should get: src0 (old slot) + src1 (dropped) + src2 (dropped) = 3 entries.
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let block2: [Double] = node.calculatedSamples(graph: g2, count: blockSize)[0]
// Output should be 30.0 (src3 — the latest).
#expect(abs(block2[0] - 30.0) < 1e-12, "Expected 30.0 from src3, got \(block2[0])")
let drainCount: Int = engine.drainParameterSourceKillQueue()
// 3 items: src0 (displaced slot) + src1 (dropped) + src2 (dropped)
#expect(drainCount == 3, "Expected 3 kill-queue items from rapid swaps, got \(drainCount)")
// Clean up src3 (still live in slot).
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g3: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g3, count: blockSize)
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - 7. Kill-queue overflow doesn't crash
@Test func killQueueOverflowDoesNotCrash() {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
// Directly fill the kill queue to capacity without draining.
// `parameterSourceKillQueueCapacity` is 256 (internal constant).
// We enqueue 256 dummy retained pointers directly onto parameterSourceKillQueue.
// Use a trivial object for each entry.
let dummySources: [ConstantSource] = (0..<257).map { ConstantSource(Double($0)) }
var overflowed: Bool = false
for source: ConstantSource in dummySources {
let ptr: UnsafeMutableRawPointer = Unmanaged.passRetained(source as AnyObject).toOpaque()
if !engine.parameterSourceKillQueue.enqueue(ptr) {
// Queue full — balance the retain we just added and note the overflow.
Unmanaged<AnyObject>.fromOpaque(ptr).release()
overflowed = true
}
}
// The 257th enqueue should have failed (queue capacity = 256).
#expect(overflowed, "Kill queue should overflow at capacity + 1")
// Engine must still be usable — render a block.
let node: ParameterNode = ParameterNode(1.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let samples: [Double] = node.calculatedSamples(graph: g, count: 8)[0]
#expect(abs(samples[7] - 1.0) < 1e-12, "Engine must render correctly after kill-queue overflow")
// Drain to release the 256 retained objects we successfully enqueued.
let drained: Int = engine.drainParameterSourceKillQueue()
#expect(drained == 256, "Should drain exactly 256 items (capacity), got \(drained)")
}
// MARK: - Kill-queue overflow flag via ParameterNode._pushToKillQueue path
@Test func killQueueOverflowFlagIsSetWhenFull() {
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
// Fill the kill queue to capacity via direct enqueue (bypass ParameterNode machinery).
let holdSources: [ConstantSource] = (0..<256).map { ConstantSource(Double($0)) }
for source: ConstantSource in holdSources {
let ptr: UnsafeMutableRawPointer = Unmanaged.passRetained(source as AnyObject).toOpaque()
_ = engine.parameterSourceKillQueue.enqueue(ptr)
}
// Queue is now full (256/256 slots occupied).
// Overflow flag starts false.
let overflowedBeforeSwap: Bool = engine._killQueueOverflowed.load(ordering: .relaxed)
#expect(!overflowedBeforeSwap)
// Install and then displace a source — ParameterNode will try to push old slot to
// the (full) kill queue, triggering the overflow flag.
let src1: ConstantSource = ConstantSource(1.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src1))
advanceBlock(engine)
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g1, count: blockSize)
let src2: ConstantSource = ConstantSource(2.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src2))
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g2, count: blockSize)
// The kill queue was full when the RT thread tried to push src1, so the flag is set.
let overflowedAfterSwap: Bool = engine._killQueueOverflowed.load(ordering: .relaxed)
#expect(overflowedAfterSwap, "Overflow flag must be set when kill queue is full")
// Drain the filled queue (256 pre-filled + not src1 since it leaked + src2 displaced next).
_ = engine.drainParameterSourceKillQueue()
// After drain, the overflow flag should be cleared (drain checks and clears it).
let overflowedAfterDrain: Bool = engine._killQueueOverflowed.load(ordering: .relaxed)
#expect(!overflowedAfterDrain, "Overflow flag must be cleared after drain")
// Displace src2 (still in slot).
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g3: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g3, count: blockSize)
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - 8. No allocation path: 1000 block renders with active swaps (indirect)
@Test func noAllocationDuringSwaps() {
// Indirect test: 1000 blocks with alternating source swaps. Verifies:
// - Engine renders without crashing or hanging.
// - Kill queue never permanently overflows (overflow flag stays clear across drains).
// - Output is deterministic (no silent NaN injection from bad pointer dereference).
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(1.0)
let srcA: ConstantSource = ConstantSource(10.0)
let srcB: ConstantSource = ConstantSource(20.0)
var totalDrained: Int = 0
for i: Int in 0..<1000 {
// Alternate between srcA and srcB every 5 blocks.
if i % 10 < 5 {
node._sourceQueue.enqueue(SourcePacket.handoff(srcA))
} else {
node._sourceQueue.enqueue(SourcePacket.handoff(srcB))
}
advanceBlock(engine)
let g: SynthGraph = makeSynthGraph(engine: engine)
let samples: [Double] = node.calculatedSamples(graph: g, count: blockSize)[0]
// All samples must be finite — a bad pointer dereference would produce garbage.
for s: Double in samples.prefix(blockSize) {
#expect(s.isFinite, "Sample must be finite during sustained swaps")
}
// Drain frequently to prevent overflow.
if i % 5 == 0 {
totalDrained += engine.drainParameterSourceKillQueue()
}
}
// Final drain.
totalDrained += engine.drainParameterSourceKillQueue()
// Overflow flag must be clear — no unrecovered overflows.
let overflowedAfterSustainedSwaps: Bool = engine._killQueueOverflowed.load(ordering: .relaxed)
#expect(!overflowedAfterSustainedSwaps,
"Kill queue must not have overflowed during sustained swaps")
// Displace whichever source is live in the slot.
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g, count: blockSize)
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - Fan-out cache: same ParameterNode with active source feeds multiple consumers
@Test func fanOutCacheWithSourceSlot() {
// Two consumers evaluate the same ParameterNode in the same segment.
// The second call must return the cached result (same serial).
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
let src: ConstantSource = ConstantSource(55.0)
node._sourceQueue.enqueue(SourcePacket.handoff(src))
advanceBlock(engine)
let graph: SynthGraph = makeSynthGraph(engine: engine)
// First consumer — triggers _computeSamples via source slot.
let result1: [Double] = node.calculatedSamples(graph: graph, count: blockSize)[0]
// Second consumer — must be served from cache.
let result2: [Double] = node.calculatedSamples(graph: graph, count: blockSize)[0]
// Both results must be identical objects (cache hit).
#expect(result1.first == result2.first, "Fan-out cache must return same result for second consumer")
#expect(abs(result1[0] - 55.0) < 1e-12, "First consumer: expected 55.0 from source")
#expect(abs(result2[0] - 55.0) < 1e-12, "Second consumer: expected 55.0 from cache")
_ = engine.drainParameterSourceKillQueue()
}
// MARK: - Dropped payloads from rapid enqueue go to kill queue
@Test func droppedPayloadsFromRapidEnqueueGoToKillQueue() {
// Enqueue 3 packets before any block renders.
// After drain: the 2 superseded ones should be in droppedPayloads → kill queue.
// The 3rd (latest) should be live in _sourceSlot.
let blockSize: Int = 8
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
let node: ParameterNode = ParameterNode(0.0)
let s1: ConstantSource = ConstantSource(1.0)
let s2: ConstantSource = ConstantSource(2.0)
let s3: ConstantSource = ConstantSource(3.0)
node._sourceQueue.enqueue(SourcePacket.handoff(s1))
node._sourceQueue.enqueue(SourcePacket.handoff(s2))
node._sourceQueue.enqueue(SourcePacket.handoff(s3))
advanceBlock(engine)
let g: SynthGraph = makeSynthGraph(engine: engine)
let samples: [Double] = node.calculatedSamples(graph: g, count: blockSize)[0]
// Output should be 3.0 — the last/latest packet.
#expect(abs(samples[0] - 3.0) < 1e-12, "Latest source (3.0) must be live, got \(samples[0])")
// Kill queue should have s1 and s2 (the two dropped packets).
let drainCount: Int = engine.drainParameterSourceKillQueue()
#expect(drainCount == 2, "Expected 2 dropped payloads in kill queue, got \(drainCount)")
// Clean up s3.
node._sourceQueue.enqueue(SourcePacket.revertToScalar())
advanceBlock(engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = node.calculatedSamples(graph: g2, count: blockSize)
_ = engine.drainParameterSourceKillQueue()
}
}