Files
Lyrebird/docs/diagnostics-guide.md

13 KiB

Diagnostics Guide

Two complementary diagnostic surfaces live in Sources/Lyrebird/Diagnostics/ and Sources/Lyrebird/NodeTree/:

Subsystem Type What it surfaces
Messages LyrebirdMessageCenter Curated user-visible text (info / warning / error)
Node tree mirror NodeTreeMirror Live snapshot of the engine's signal-graph node tree

Both are language-side, main-thread facilities. The RT thread does not call into either, and there is no SPSC bridge from RT to main. If you need to react to RT events from the UI, the existing SynthesisEngineListener lifecycle hook is the only fan-out the engine exposes today.

This guide covers user-visible runtime surfaces. For developer-side inspection — breakpointing a specific voice on the RT thread, reading a generator's live output and inner state — see the DocC article <doc:Debugging> (Sources/Lyrebird/Lyrebird.docc/Debugging.md).


Part 1 — LyrebirdMessage

What it is

A bounded ring of user-facing diagnostic messages, observed by SwiftUI through the @Observable macro and rendered by LyrebirdMessageView / LyrebirdMessageBanner.

public enum LyrebirdMessageTier: Sendable, Equatable, CaseIterable {
    case info, warning, error
}

public struct LyrebirdMessage: Identifiable, Sendable, Equatable {
    public let id: UUID
    public let timestamp: Date
    public let tier: LyrebirdMessageTier
    public let text: String
    public let source: String?
}

@Observable
@MainActor
public final class LyrebirdMessageCenter {
    public static let shared: LyrebirdMessageCenter

    public private(set) var messages: [LyrebirdMessage]
    public var capacity: Int   // default 200; prunes immediately when lowered

    public func post(_ tier: LyrebirdMessageTier, _ text: String, source: String? = nil)
    public func info(_ text: String, source: String? = nil)
    public func warning(_ text: String, source: String? = nil)
    public func error(_ text: String, source: String? = nil)
    public func clear()
}

print() vs post() — two channels, by design

Two distinct streams. Library authors choose which one each diagnostic goes to:

Channel Audience When to use
print("[Lyrebird ...] ...") Developer / Xcode console Engine internals, dev diagnostics, anything that should not surface to the end user. The existing engine / LyrebirdEventList / LyrebirdProcess / OSCServer sites all use this.
LyrebirdMessageCenter.shared.post(...) End user / library consumer Curated text the user is meant to see: "recording started", "buffer not found", "OSC port already in use", "voice pool full".

Existing print sites stay as-is. New diagnostic sites pick one channel — and one only — based on who needs to see the line.

Posting

import LyrebirdSynth

// At a save site:
LyrebirdMessageCenter.shared.info(
    "Recording started at \(directory.path)",
    source: "LyrebirdEventList '\(id)'"
)

// At a non-fatal anomaly:
LyrebirdMessageCenter.shared.warning(
    "Sample rate changed mid-session — buffers may glitch.",
    source: "SynthesisEngine"
)

// At a user-actionable failure:
LyrebirdMessageCenter.shared.error(
    "OSC port \(port) is already in use; OSCServer not started.",
    source: "OSCServer"
)

The source parameter is optional but encouraged — the UI shows it as a small caption above the message body, and it's the only way the user distinguishes two messages with identical text from different sources.

Threading

The center is @MainActor. Callers off the main thread must hop:

Task { @MainActor in
    LyrebirdMessageCenter.shared.warning("Bus pool nearly full.")
}

No RT-thread access. Generators (RT thread) have no API for posting. If a future RT path genuinely needs to emit a message, the intended bridge is a dedicated SPSCQueue<MessageRecord> drained at 10 Hz by the center — out of scope for now.

Capacity

Default capacity is 200. Exceeding it drops the oldest entries (FIFO ring). Lowering capacity prunes immediately to the new bound.

LyrebirdMessageCenter.shared.capacity = 50   // keep only the most recent 50

View hosting

Two SwiftUI surfaces:

import LyrebirdUI

// Full scrollable list with per-tier filter chips, count badges, Clear.
LyrebirdMessageView()

// Compact 3-line ticker. Tap → invokes the optional onOpenFull callback.
LyrebirdMessageBanner(onOpenFull: { /* open full view */ })

LyrebirdEngineStatusView already hosts a collapsible Messages section between the CPU metrics divider and the configuration section. Expanded, it inlines the full view; collapsed, it shows the banner. macOS additionally offers an "Open Window" button.

Open standalone (macOS):

LyrebirdMessageView.presentInWindow()                    // shared center
LyrebirdMessageView.presentInWindow(center: myCenter)    // custom center

Custom centers

Most apps use the shared singleton. If you need an isolated channel (e.g. a sub-component that wants its own message log), construct your own:

let myCenter: LyrebirdMessageCenter = LyrebirdMessageCenter(capacity: 50)
myCenter.warning("Recording buffer almost full.")
LyrebirdMessageView(center: myCenter)

The shared center is unaffected by writes to a custom one.


Part 2 — NodeTreeMirror

What it is

A main-thread mirror of the engine's signal-graph node tree, kept up to date by every language-side mutation and published as an immutable NodeTreeSnapshot for SwiftUI to observe.

public struct NodeTreeSnapshot: Sendable, Equatable {
    public struct Node: Identifiable, Sendable, Equatable {
        public enum Kind: Sendable, Equatable {
            case synth(className: String)
            case group
            case parallelGroup
        }
        public let id: ObjectIdentifier
        public let kind: Kind
        public let displayName: String
        public let children: [Node]
    }
    public let root: Node
}

@Observable
public final class NodeTreeMirror {
    public private(set) var snapshot: NodeTreeSnapshot
    // didAdd / didRemove / didFreeGroup are internal — driven by the engine.
}

Access via the engine:

let mirror: NodeTreeMirror = engine.nodeTreeMirror
let root: NodeTreeSnapshot.Node = mirror.snapshot.root

Why a mirror

The RT thread mutates Group.head / PreparedNode.next when it drains pendingQueue. A direct main-thread walk during playback is a data race. The mirror sidesteps the race by maintaining its own value-type tree updated from the language-side mutation API — never from the RT side.

When the mirror updates

Engine call Mirror update
engine.add(_:) head of mainGroup
engine.add(_:position:) at the specified NodePosition
engine.schedule(_:at:) / schedule(_:after:) head of mainGroup (immediately — UI shows the synth before its RT-side fire time)
engine.remove(_:) / remove(_:at:) drops the synth
Group.free(engine:) drops the group + entire subtree

Updates fire after pendingQueue.enqueue returns true. If the queue is full and the event is dropped, the mirror skips the update so its view stays consistent with the RT thread's view ("synth never appeared" — not "phantom node").

What does NOT update the mirror

Path Why
Natural envelope completion drained via freeQueue The RT thread frees the synth; there is no main-thread hook unless the owner (LyrebirdProcess._teardown, user code) calls engine.remove(synth). Raw synths added via engine.add that self-terminate without an explicit remove will linger in the mirror.
Group.release(engine:) cascading to children Release is envelope-driven; the actual removal only fires once each child completes its release tail and the owning code calls engine.remove. The mirror reflects the eventual removes, not the intermediate releasing state.
RT-side Group.addToHead / addToTail / addBefore / addAfter These are RT-internal — the language side already drove the mirror update on the corresponding engine.add call.

Reading the snapshot

import LyrebirdSynth

let root: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root
// root.children[0] is mainGroup by construction.

for node: NodeTreeSnapshot.Node in root.children {
    switch node.kind {
    case .synth(let className):
        print("synth: \(className)")
    case .group:
        print("group with \(node.children.count) children")
    case .parallelGroup:
        print("parallel group with \(node.children.count) children")
    }
}

Identity is stable: node.id == ObjectIdentifier(synthInstance) from the moment of add until the matching remove / free.

View hosting

import LyrebirdUI

LyrebirdNodeTreeView(engine: engine)

Or bind directly to the mirror:

LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror)

LyrebirdEngineStatusView already hosts a collapsible Node Tree section above the Messages section. macOS adds an "Open Window" button that opens a detached LyrebirdWindow:

LyrebirdNodeTreeView.presentInWindow(engine: engine)

Persistent groups (rootGroup + mainGroup)

rootGroup and mainGroup are created at SynthesisEngine.init, are flagged _persistent = true, and are never freed. They are visible in the mirror snapshot from the moment the engine exists: the snapshot root is rootGroup, and mainGroup is its sole initial child.

The engine's engine.groupCount excludes them by design — it tracks user-added containers only, which makes per-test reasoning easier (start at 0, increment on every engine.add(group, ...), decrement on every engine.remove / Group.free). The LyrebirdEngineStatusView "Groups" tile, however, displays groupCount + 2 with an incl. rootGroup, mainGroup caption so the UI surfaces the persistent baseline. After LyrebirdEventList.killAll(), the tile reads 2 (matching the tree view) rather than 0.

The Node Tree section in LyrebirdEngineStatusView additionally renders an always-visible "persistent-groups strip" — rootGroup (N) ▸ mainGroup (N) with live child counts pulled from the snapshot. The strip stays on screen even when the full tree is collapsed, so the user always has a confirmation that the two persistent containers are alive.

Reading order

Rows render top-to-bottom in head→tail order — the same order the RT thread evaluates them in. This matters when reasoning about signal flow:

  • A pre-processing limiter installed via .before(engine.mainGroup) appears above mainGroup (it runs first).
  • A master reverb installed via .after(engine.mainGroup) appears below mainGroup (it runs last).
  • Inside mainGroup, the newest-added synth (from engine.add(_:), which inserts at head) appears at the top.

Row affordances

Each row shows:

  • Glyph: chevron for groups (clickable expand / collapse) or dot for leaf synths.
  • Display name: the Swift runtime class name (e.g. MyVoice) for synths, or Group / ParallelGroup for containers.
  • Child-count badge for containers: (3) etc.
  • 4-hex identity suffix: #a12c. Derived deterministically from ObjectIdentifier.hashValue so two MyVoice instances in the tree can be told apart.

ParallelGroup children are populated by the main-thread add(_:) calls before the engine adds the parent group. The mirror walks that fixed list at parent-add time and never re-walks it; if you mutate the children list after the parent is added, the mirror won't notice.

Drift

The mirror drifts from the RT-thread tree only when:

  • A self-terminating synth was added via engine.add and is never explicitly removed (see "What does NOT update the mirror" above).
  • The owning code keeps a reference to a freed group via something other than the engine API.

Neither is fatal — drift surfaces as a stale node in the UI. Restarting the view (or the engine) clears it.


Choosing between the two

Need Use
Tell the user something happened LyrebirdMessageCenter.shared.{info,warning,error}
Show the user what's running right now Embed LyrebirdNodeTreeView or open via presentInWindow
Debug "is my synth actually in the graph?" Read engine.nodeTreeMirror.snapshot programmatically
Surface engine startup / shutdown lifecycle SynthesisEngineListener (pre-existing)

The Messages + Node Tree pair gives composers a live read on both what the engine is doing (node tree) and what the engine wants them to know (messages). The engine status view bundles all three (plus CPU metrics) into a single panel that drops cleanly into any demo.


See also

  • Sources/Lyrebird/Diagnostics/ — message model + center
  • Sources/Lyrebird/NodeTree/NodeTreeSnapshot.swift, NodeTreeMirror.swift — tree mirror
  • Sources/LyrebirdUI/LyrebirdMessageView.swift, LyrebirdMessageBanner.swift, LyrebirdMessageHelpers.swift — message UI
  • Sources/LyrebirdUI/LyrebirdNodeTreeView.swift — tree UI
  • Sources/LyrebirdUI/LyrebirdEngineStatusView.swift — bundled engine status panel hosting both
  • docs/ui/gui-system.md — @LiveParam / @UIParam parameter binding
  • docs/01-completed-working-order.md — diagnostics + message-center writeups