// EngineLifecycleCoordinator.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation /// Process-wide registry of live `SynthesisEngine` instances, keyed by /// `SynthesisEngine.identifier`. Module-internal singleton. /// /// Purpose /// ======= /// 1. **Engine lookup by identifier** — `EngineAddError.boundToOtherEngine` /// carries `current` and `prior` UUIDs; the registry lets diagnostics and /// the multi-engine host (`EngineHost`) resolve a UUID /// back to the actual `SynthesisEngine` instance. /// 2. **Cross-engine lifecycle serialisation** — `withLifecycleLock(_:)` is /// intended to wrap `engine.start()` / `engine.stop()` so concurrent /// start/stop calls across two `SynthesisEngine` instances cannot /// interleave in the `freeWorker.sync` teardown drain (suspected behind /// the deferred parallel-`swift test` crash; see /// `memory/project_parallel_test_crash.md`). Lock is held only across /// main-thread lifecycle calls — RT thread never touches it. /// 3. **Diagnostics** — `count` and `engines` let tests + the host facade /// detect "more than one engine in process" cases that should go through /// `EngineHost`. /// /// Thread safety /// ============= /// All public methods acquire `_lock` (an `NSLock`). Holds are short — dict /// mutation only — except `withLifecycleLock(_:)`, which is called by /// engine start/stop on the main thread and is expected to hold across the /// full lifecycle transition. No method is callable from the RT audio /// thread; the coordinator is a non-RT-safe construct. /// /// Memory model /// ============ /// Registry stores `WeakEngineRef` so the coordinator never keeps engines /// alive past their natural reference-counted lifetime. Engines call /// `unregister(_:)` in their `deinit` to evict the dictionary slot /// proactively — without this, slot stays in the dict with a nil weak /// payload until the next `prune()` call. `unregister(_:)` is therefore an /// optimisation, not a correctness requirement. internal final class EngineLifecycleCoordinator: @unchecked Sendable { /// Process-wide singleton. The registry is intentionally global — /// engine identity is a process-level concern. Tests must accept that /// instances created in one test case are visible from another until /// they deinit; engine `deinit` evicts the slot. Real tests using the /// coordinator (regression test, host tests) /// should not rely on a globally empty starting state. internal static let shared: EngineLifecycleCoordinator = EngineLifecycleCoordinator() /// Internal lock protecting `_engines` mutation and held by /// `withLifecycleLock(_:)` for the duration of engine start/stop. /// `NSLock` is recursion-unsafe; do not nest `withLifecycleLock`. private let _lock: NSLock = NSLock() /// Weak references to live engines, keyed by `SynthesisEngine.identifier`. /// Slots whose `engine` property has gone `nil` are pruned lazily on the /// next `register` / `unregister` / `prune` call. private var _engines: [UUID: WeakEngineRef] = [:] /// Private to enforce singleton access via ``shared``. private init() {} // MARK: - Registration /// Add `engine` to the registry. Called from `SynthesisEngine.init` /// after the `identifier` property is assigned. Idempotent on the same /// UUID — re-registering with the same key replaces the weak slot. /// /// - Parameter engine: The engine to register. Held weakly. internal func register(_ engine: SynthesisEngine) { _lock.lock() defer { _lock.unlock() } _engines[engine.identifier] = WeakEngineRef(engine: engine) } /// Remove the registry slot for `identifier`. Called from /// `SynthesisEngine.deinit`. Safe to call on a UUID that is not present /// (no-op). /// /// - Parameter identifier: The engine identifier to evict. internal func unregister(_ identifier: UUID) { _lock.lock() defer { _lock.unlock() } _engines.removeValue(forKey: identifier) } /// Resolve `identifier` to its live engine, or `nil` if no live engine /// is registered under that key. Used by `EngineAddError` diagnostics /// to print engine details by UUID. /// /// - Parameter identifier: The engine identifier to look up. /// - Returns: The live `SynthesisEngine`, or `nil` if absent / deinited. internal func engine(for identifier: UUID) -> SynthesisEngine? { _lock.lock() defer { _lock.unlock() } return _engines[identifier]?.engine } /// Number of live engines currently registered. Counts only slots whose /// weak reference is still resolvable. Used by tests and the /// host facade for "multi-engine detected" diagnostics. internal var count: Int { _lock.lock() defer { _lock.unlock() } return _engines.values.reduce(0) { $0 + ($1.engine == nil ? 0 : 1) } } /// Snapshot of all live engines. Returned as a fresh array to avoid /// holding the lock across caller iteration. Dead weak slots are /// skipped (not returned). internal var engines: [SynthesisEngine] { _lock.lock() defer { _lock.unlock() } return _engines.values.compactMap { $0.engine } } /// Evict registry slots whose weak engine has deinited. Normally /// unnecessary because `SynthesisEngine.deinit` calls `unregister`, but /// kept as a safety valve for unit tests that drop engines on a thread /// that races with the registry lock. Not called automatically. internal func prune() { _lock.lock() defer { _lock.unlock() } // Collect dead keys first, then remove. Mutating a Dictionary // while iterating it via `for ... in` is undefined behaviour in // Swift — the iterator is not guaranteed stable under // concurrent modification of the underlying storage. let deadKeys: [UUID] = _engines.compactMap { (key, ref) in ref.engine == nil ? key : nil } for key: UUID in deadKeys { _engines.removeValue(forKey: key) } } // MARK: - Lifecycle lock /// Acquire the lifecycle lock for the duration of `body`. Intended to /// wrap `SynthesisEngine.start()` and `SynthesisEngine.stop()` so that /// concurrent start/stop calls across engines serialise their /// teardown drains (`freeWorker.sync` + `parameterSourceKillQueue` + /// `bufferSwapKillQueue`). Caller must run on the main thread; the RT /// audio thread must never call into the coordinator. /// /// `NSLock` is non-reentrant — `withLifecycleLock` calls must not nest. /// If start() ever needs to call stop() on another engine (or /// vice-versa), the engine API must release the outer lock first. /// /// **Transitive re-entry warning.** `_lock` also guards /// `register(_:)` and `unregister(_:)`. If `body` triggers any code /// path that constructs or destroys a `SynthesisEngine` (e.g. a /// closure that creates a temporary engine, or releases the last /// strong reference to one), the resulting `register` / `unregister` /// call will deadlock on the same NSLock. /// `EngineHost` enforces the no-engine-lifecycle-inside-body /// contract by owning all engine ctors/dtors itself. /// /// - Parameter body: Closure executed under the lifecycle lock. /// - Returns: The return value of `body`. /// - Throws: Re-throws whatever `body` throws. internal func withLifecycleLock(_ body: () throws -> T) rethrows -> T { _lock.lock() defer { _lock.unlock() } return try body() } } /// Weak reference wrapper for the engine registry. Keeps the engine /// dictionary value-type at the cost of one indirection. Cannot be a /// `weak var` directly because dictionaries require their values to be /// stable types, and Swift's `weak` modifier only applies to property /// declarations. internal struct WeakEngineRef { weak var engine: SynthesisEngine? }