bugfixes, better MusicXML support and 1.1.0
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
// ActorIsolationGuardTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
/// Main-actor isolation guards.
|
||||
///
|
||||
/// These tests protect the main-actor isolation model against silent regression:
|
||||
///
|
||||
/// 1. **Off-main bridge** — `lyrebirdRunMainActorMutation` must run a `@MainActor`
|
||||
/// mutation correctly when invoked from a background thread (synchronous hop to
|
||||
/// main), without trapping. This path is exercised in production by the NRT inline
|
||||
/// dispatcher (`LyrebirdMessageContext(nrtEngine:)`) and by AUv3 off-main hosts. The
|
||||
/// rest of the suite runs `@MainActor` (node-tree mutation is a main-thread API), so
|
||||
/// these specific tests are deliberately **nonisolated** to drive the off-main path.
|
||||
///
|
||||
/// 2. **RT-layer purity** — Generator hot-path sources must never reference actor-hop
|
||||
/// machinery (`MainActor`, `assumeIsolated`, `DispatchQueue`, `Task {`). Under the
|
||||
/// Swift 6 language mode such a call would compile silently but violate the
|
||||
/// `nonisolated` RT render contract. This is a source-text lint.
|
||||
@Suite("Actor isolation guards")
|
||||
struct ActorIsolationGuardTests {
|
||||
|
||||
// MARK: - Guard A: off-main bridge
|
||||
|
||||
/// The bridge runs inline when already on the main thread.
|
||||
@Test @MainActor func bridgeRunsInlineOnMain() {
|
||||
var ran: Bool = false
|
||||
lyrebirdRunMainActorMutation { ran = true }
|
||||
#expect(ran)
|
||||
}
|
||||
|
||||
/// The bridge hops synchronously to main when called off-main — it must NOT trap
|
||||
/// (the regression that bare `MainActor.assumeIsolated` would have caused on the
|
||||
/// NRT inline / off-main AU-host paths).
|
||||
@Test func bridgeHopsFromBackgroundThreadWithoutTrapping() async {
|
||||
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
let ran: LockedBool = LockedBool()
|
||||
// Dispatch onto a background queue so the bridge takes its `main.sync` branch.
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
#expect(!Thread.isMainThread)
|
||||
lyrebirdRunMainActorMutation {
|
||||
// Body runs on the main actor.
|
||||
#expect(Thread.isMainThread)
|
||||
ran.set(true)
|
||||
}
|
||||
done.signal()
|
||||
}
|
||||
// Wait off the main thread (this test is nonisolated) so main is free to service
|
||||
// the bridge's synchronous hop.
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
DispatchQueue.global().async {
|
||||
_ = done.wait(timeout: .now() + 5)
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
#expect(ran.get())
|
||||
}
|
||||
|
||||
/// End-to-end: the NRT inline `LyrebirdMessageContext` dispatcher invoked from a
|
||||
/// background thread routes `ctx.add` through the bridge and the synth's `build()`
|
||||
/// runs (on main) — proving the off-main NRT add path does not trap.
|
||||
@Test func nrtInlineContextAddFromBackgroundThreadBuildsSynth() async {
|
||||
// No `engine.start()` here on purpose: `build()` runs at add time (in `prepareNode`),
|
||||
// before any render. Starting an NRT render would mark this pooled thread RT via
|
||||
// `RTThreadIdentity`; that marker persists and could false-trip
|
||||
// `_lyrebirdAssertNotOnRTThread` in a later `.compute()` test reusing the thread.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
|
||||
let builtCount: LockedInt = LockedInt()
|
||||
final class ProbeSynth: SynthesizerBase, @unchecked Sendable {
|
||||
let onBuild: @Sendable () -> Void
|
||||
init(onBuild: @escaping @Sendable () -> Void) { self.onBuild = onBuild; super.init() }
|
||||
override func build() { onBuild() }
|
||||
}
|
||||
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(nrtEngine: engine)
|
||||
// Synth construction is `@MainActor`; build it on main, then add from
|
||||
// a background thread to exercise the off-main bridge hop.
|
||||
let synth: ProbeSynth = await MainActor.run { ProbeSynth { builtCount.increment() } }
|
||||
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
ctx.add(synth) // inline dispatcher → lyrebirdRunMainActorMutation off-main → main hop
|
||||
done.signal()
|
||||
}
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
DispatchQueue.global().async {
|
||||
_ = done.wait(timeout: .now() + 5)
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
#expect(builtCount.get() == 1)
|
||||
}
|
||||
|
||||
// MARK: - Guard B: RT-layer source purity
|
||||
|
||||
/// RT-DSP sources must not reference actor-isolation machinery. Under Swift 6 language
|
||||
/// mode an `@MainActor` / `assumeIsolated` call inside an RT-path source compiles
|
||||
/// silently but breaks the `nonisolated` RT render contract — this lint fails the build
|
||||
/// before that can ship.
|
||||
///
|
||||
/// Scope: the pure RT-DSP directories — `Generators/` (concrete units), `GeneratorCore/`
|
||||
/// (the Generator protocol layer + `MulAdd` + hot-loop helpers), `Oversampling/`,
|
||||
/// `Spectral/`, and `Math/`. `Engine/` and `NodeTree/` are intentionally NOT scanned:
|
||||
/// they legitimately host the language-side `@MainActor` surface (`SynthesizerBase`,
|
||||
/// the `MainActorMutationBridge`) whose `evaluate`/render entry points are separately
|
||||
/// `nonisolated`.
|
||||
///
|
||||
/// Only `MainActor` / `assumeIsolated` are banned — pure actor-isolation hooks with no
|
||||
/// legitimate place in an RT-DSP unit. `DispatchQueue` / `Task` are intentionally NOT
|
||||
/// banned: buffer generators (`DiskIn` / `DiskOut`) use a background queue for off-RT
|
||||
/// disk I/O (the RT side only touches a lock-free ring buffer).
|
||||
@Test func generatorSourcesContainNoActorHopMachinery() throws {
|
||||
let rtDspDirs: [String] = [
|
||||
"Sources/Lyrebird/Generators",
|
||||
"Sources/Lyrebird/GeneratorCore",
|
||||
"Sources/Lyrebird/Oversampling",
|
||||
"Sources/Lyrebird/Spectral",
|
||||
"Sources/Lyrebird/Math",
|
||||
]
|
||||
let forbidden: [String] = [
|
||||
"MainActor",
|
||||
"assumeIsolated",
|
||||
]
|
||||
let fm: FileManager = FileManager.default
|
||||
var violations: [String] = []
|
||||
for dir: String in rtDspDirs {
|
||||
let root: URL = Self.repoRoot.appendingPathComponent(dir, isDirectory: true)
|
||||
guard let enumerator: FileManager.DirectoryEnumerator =
|
||||
fm.enumerator(at: root, includingPropertiesForKeys: nil) else {
|
||||
Issue.record("Could not enumerate \(root.path)")
|
||||
continue
|
||||
}
|
||||
for case let url as URL in enumerator where url.pathExtension == "swift" {
|
||||
let text: String = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
|
||||
for token: String in forbidden where text.contains(token) {
|
||||
violations.append("\(dir)/\(url.lastPathComponent): contains '\(token)'")
|
||||
}
|
||||
}
|
||||
}
|
||||
#expect(
|
||||
violations.isEmpty,
|
||||
"RT-DSP sources must not use actor-hop machinery (breaks the nonisolated RT contract): \(violations)"
|
||||
)
|
||||
}
|
||||
|
||||
/// Repo root, derived from this file's path:
|
||||
/// `<root>/Tests/LyrebirdTests/Concurrency/ActorIsolationGuardTests.swift`.
|
||||
private static var repoRoot: URL {
|
||||
URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // Concurrency/
|
||||
.deletingLastPathComponent() // LyrebirdTests/
|
||||
.deletingLastPathComponent() // Tests/
|
||||
.deletingLastPathComponent() // <root>
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Tiny thread-safe test helpers
|
||||
|
||||
private final class LockedBool: @unchecked Sendable {
|
||||
private let lock: NSLock = NSLock()
|
||||
private var value: Bool = false
|
||||
func set(_ v: Bool) { lock.lock(); value = v; lock.unlock() }
|
||||
func get() -> Bool { lock.lock(); defer { lock.unlock() }; return value }
|
||||
}
|
||||
|
||||
private final class LockedInt: @unchecked Sendable {
|
||||
private let lock: NSLock = NSLock()
|
||||
private var value: Int = 0
|
||||
func increment() { lock.lock(); value += 1; lock.unlock() }
|
||||
func get() -> Int { lock.lock(); defer { lock.unlock() }; return value }
|
||||
}
|
||||
Reference in New Issue
Block a user