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

353 lines
13 KiB
Swift

// ParameterSourceQueueTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Minimal test generator
/// Minimal `AudioGenerator` conformer for SourcePacket / ParameterSourceQueue tests.
/// Pre-allocates a single constant-zero output buffer — no signal-path behaviour needed.
private final class MinimalGen: GeneratorBase, AudioGenerator {
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
return _result
}
}
// MARK: - SourcePacket Tests
@Suite("SourcePacket")
struct SourcePacketTests {
// MARK: revertToScalar
@Test func revertToScalarProducesNilPtr() {
let packet: SourcePacket = SourcePacket.revertToScalar()
#expect(packet.sourcePtr == nil)
#expect(packet.crossfadeBlocks == 0)
}
@Test func revertToScalarRoundTripsTakeRetainedSource() {
let packet: SourcePacket = SourcePacket.revertToScalar()
#expect(packet.takeRetainedBox()?.generator == nil)
}
@Test func revertToScalarWithCrossfade() {
let packet: SourcePacket = SourcePacket.revertToScalar(crossfadeBlocks: 8)
#expect(packet.crossfadeBlocks == 8)
#expect(packet.sourcePtr == nil)
}
// MARK: handoff / takeRetainedBox
@Test func handoffRoundTripReturnsSameInstance() {
let gen: MinimalGen = MinimalGen()
let packet: SourcePacket = SourcePacket.handoff(gen)
// takeRetainedBox balances the passRetained in handoff — no leak.
let recovered: (any Generator)? = packet.takeRetainedBox()?.generator
// Identity check: the recovered object must be the same instance.
#expect(recovered as AnyObject === gen)
}
@Test func handoffPreservesNonNilPtr() {
let gen: MinimalGen = MinimalGen()
let packet: SourcePacket = SourcePacket.handoff(gen)
#expect(packet.sourcePtr != nil)
// Balance the retain.
packet.releaseUnconsumed()
}
@Test func handoffCrossfadeBlocksRoundTrips() {
let gen: MinimalGen = MinimalGen()
let packet: SourcePacket = SourcePacket.handoff(gen, crossfadeBlocks: 12)
#expect(packet.crossfadeBlocks == 12)
// Balance the retain.
packet.releaseUnconsumed()
}
@Test func releaseUnconsumedBalancesRetain() {
// Enqueue several packets and release without dequeue — verifies that
// releaseUnconsumed() does not crash and does not double-free.
let releaseCount: Int = 100
for _ in 0..<releaseCount {
let gen: MinimalGen = MinimalGen()
let packet: SourcePacket = SourcePacket.handoff(gen)
packet.releaseUnconsumed()
}
// If we reach here without a crash or ASAN error, the test passes.
}
@Test func releaseUnconsumedOnRevertPacketIsNoOp() {
// releaseUnconsumed on a nil-ptr packet must be a safe no-op.
let packet: SourcePacket = SourcePacket.revertToScalar()
packet.releaseUnconsumed() // must not crash
}
// MARK: Sendable compile-test
@Test func sourcePacketIsSendable() {
// If SourcePacket were not Sendable this would fail to compile.
let packet: SourcePacket = SourcePacket.revertToScalar()
let _: @Sendable () -> Void = {
let _capturedPacket: SourcePacket = packet
_ = _capturedPacket.sourcePtr
}
}
}
// MARK: - ParameterSourceQueue Tests
@Suite("ParameterSourceQueue")
struct ParameterSourceQueueTests {
// MARK: Empty drain
@Test func emptyDrainReturnsNil() {
let queue: ParameterSourceQueue = ParameterSourceQueue()
let result: SourcePacket? = queue.drain()
#expect(result == nil)
#expect(queue.droppedCount == 0)
#expect(queue.droppedPayloads.isEmpty)
}
// MARK: Single revert-to-scalar round-trip
@Test func revertToScalarRoundTrip() {
let queue: ParameterSourceQueue = ParameterSourceQueue()
queue.enqueue(.revertToScalar())
guard let packet: SourcePacket = queue.drain() else {
Issue.record("Expected a non-nil packet")
return
}
#expect(packet.sourcePtr == nil)
#expect(packet.takeRetainedBox()?.generator == nil)
#expect(queue.droppedCount == 0)
}
// MARK: Single handoff round-trip
@Test func handoffRoundTrip() {
let gen: MinimalGen = MinimalGen()
let queue: ParameterSourceQueue = ParameterSourceQueue()
queue.enqueue(.handoff(gen))
guard let packet: SourcePacket = queue.drain() else {
Issue.record("Expected a non-nil packet")
return
}
#expect(queue.droppedCount == 0)
let recovered: (any Generator)? = packet.takeRetainedBox()?.generator
#expect(recovered as AnyObject === gen)
}
// MARK: crossfadeBlocks field round-trips
@Test func crossfadeBlocksRoundTrips() {
let gen: MinimalGen = MinimalGen()
let queue: ParameterSourceQueue = ParameterSourceQueue()
queue.enqueue(.handoff(gen, crossfadeBlocks: 7))
guard let packet: SourcePacket = queue.drain() else {
Issue.record("Expected a non-nil packet")
return
}
#expect(packet.crossfadeBlocks == 7)
// Balance the retain.
packet.releaseUnconsumed()
}
// MARK: Latest-wins on rapid enqueue
@Test func latestWinsOnRapidEnqueue() {
// Enqueue 3 packets without intervening drain — drain must return
// the most recent and report 2 dropped payloads.
let gen1: MinimalGen = MinimalGen()
let gen2: MinimalGen = MinimalGen()
let gen3: MinimalGen = MinimalGen()
let queue: ParameterSourceQueue = ParameterSourceQueue()
queue.enqueue(.handoff(gen1))
queue.enqueue(.handoff(gen2))
queue.enqueue(.handoff(gen3))
guard let packet: SourcePacket = queue.drain() else {
Issue.record("Expected a non-nil packet")
return
}
// Latest packet carries gen3.
let latest: (any Generator)? = packet.takeRetainedBox()?.generator
#expect(latest as AnyObject === gen3)
// Two older packets were superseded.
#expect(queue.droppedCount == 2)
// Release the two dropped payloads to balance their passRetained.
// In production these go onto the engine kill queue instead.
for ptr: UnsafeRawPointer in queue.droppedPayloads {
Unmanaged<GeneratorBox>.fromOpaque(ptr).release()
}
}
@Test func latestWinsWithMixedPackets() {
// Revert-to-scalar packets carry no retained ptr — they should appear
// in droppedCount only if they occupy the "prev" slot when superseded.
let gen1: MinimalGen = MinimalGen()
let queue: ParameterSourceQueue = ParameterSourceQueue()
// Packet 1: revert (no retained ptr)
// Packet 2: handoff gen1 (retained ptr)
// Packet 3: revert again (no retained ptr) — this is latest
queue.enqueue(.revertToScalar())
queue.enqueue(.handoff(gen1))
queue.enqueue(.revertToScalar())
guard let packet: SourcePacket = queue.drain() else {
Issue.record("Expected a non-nil packet")
return
}
// Latest is the final revert-to-scalar.
#expect(packet.sourcePtr == nil)
// droppedCount should be 1: the handoff(gen1) packet had a non-nil
// ptr and was superseded. The first revert-to-scalar had nil ptr so
// it doesn't add to droppedCount.
#expect(queue.droppedCount == 1)
// Release the one dropped payload.
for ptr: UnsafeRawPointer in queue.droppedPayloads {
Unmanaged<GeneratorBox>.fromOpaque(ptr).release()
}
}
// MARK: Full capacity then drain then re-enqueue
@Test func fillDrainRefill() {
let queue: ParameterSourceQueue = ParameterSourceQueue()
// Fill to capacity (4 slots).
for _ in 0..<parameterSourceQueueCapacity {
queue.enqueue(.revertToScalar())
}
// Drain — returns the last one, drops the first 3 (all nil-ptr, so
// droppedCount stays 0).
let result: SourcePacket? = queue.drain()
#expect(result != nil)
#expect(queue.droppedCount == 0)
// After draining, queue is empty and can accept new enqueues.
queue.enqueue(.revertToScalar())
let result2: SourcePacket? = queue.drain()
#expect(result2 != nil)
}
// MARK: Queue-full overflow trap
@Test func queueFullOverflowTraps() {
// Enqueueing more than parameterSourceQueueCapacity packets without
// draining is a programmer error and traps via precondition. Swift
// Testing cannot catch precondition traps in-process; we verify the
// capacity constant and document the expected behaviour.
//
// To observe the trap: enqueue 5 packets to a capacity-4 queue in a
// separate process / manual test. Here we verify the queue accepts
// exactly parameterSourceQueueCapacity items before the backing
// SPSCQueue returns false (which triggers the precondition).
#expect(parameterSourceQueueCapacity == 4)
// We exercise the boundary safely: enqueue exactly capacity items —
// all succeed. A 5th would trap, but we do not enqueue it here.
let queue: ParameterSourceQueue = ParameterSourceQueue()
for _ in 0..<parameterSourceQueueCapacity {
queue.enqueue(.revertToScalar())
}
// Drain to reset.
_ = queue.drain()
}
// MARK: Repeated drain/enqueue cycles (retain correctness under tight loop)
@Test func retainBalanceUnderTightLoop() {
// Enqueue and drain 500 handoff packets in sequence.
// If retains are not balanced the process will crash with BAD_ACCESS or
// a Swift runtime over-release assertion.
let iterationCount: Int = 500
let queue: ParameterSourceQueue = ParameterSourceQueue()
for _ in 0..<iterationCount {
let gen: MinimalGen = MinimalGen()
queue.enqueue(.handoff(gen))
guard let packet: SourcePacket = queue.drain() else {
Issue.record("drain returned nil unexpectedly")
return
}
let recovered: (any Generator)? = packet.takeRetainedBox()?.generator
// Consume the reference so ARC releases it after this block.
_ = recovered
}
}
@Test func latestWinsRetainBalanceUnderTightLoop() {
// Enqueue 3 packets, drain (2 dropped), release dropped — 200 times.
let iterationCount: Int = 200
let queue: ParameterSourceQueue = ParameterSourceQueue()
for _ in 0..<iterationCount {
let g1: MinimalGen = MinimalGen()
let g2: MinimalGen = MinimalGen()
let g3: MinimalGen = MinimalGen()
queue.enqueue(.handoff(g1))
queue.enqueue(.handoff(g2))
queue.enqueue(.handoff(g3))
guard let packet: SourcePacket = queue.drain() else {
Issue.record("drain returned nil unexpectedly")
return
}
// Take ownership of latest.
_ = packet.takeRetainedBox()?.generator
// Release dropped payloads.
for ptr: UnsafeRawPointer in queue.droppedPayloads {
Unmanaged<GeneratorBox>.fromOpaque(ptr).release()
}
}
}
// MARK: droppedPayloads slice is valid until next drain
@Test func droppedPayloadsSliceIsValidBeforeNextDrain() {
let gen1: MinimalGen = MinimalGen()
let gen2: MinimalGen = MinimalGen()
let queue: ParameterSourceQueue = ParameterSourceQueue()
queue.enqueue(.handoff(gen1))
queue.enqueue(.handoff(gen2))
_ = queue.drain()
// Access droppedPayloads before next drain — must be valid.
let count: Int = queue.droppedCount
#expect(count == 1)
let slice: ArraySlice<UnsafeRawPointer> = queue.droppedPayloads
#expect(slice.count == 1)
// Release the single dropped payload.
for ptr: UnsafeRawPointer in slice {
Unmanaged<GeneratorBox>.fromOpaque(ptr).release()
}
// After a second drain (empty queue), droppedCount resets.
_ = queue.drain()
#expect(queue.droppedCount == 0)
}
// MARK: Capacity constant sanity
@Test func capacityConstantIsPowerOfTwo() {
let c: Int = parameterSourceQueueCapacity
#expect(c > 0)
#expect(c & (c - 1) == 0)
}
}