v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass

- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
This commit is contained in:
2026-07-17 14:05:01 -07:00
parent 63d6e0746f
commit 560724d116
149 changed files with 5010 additions and 1029 deletions
+328
View File
@@ -10760,3 +10760,331 @@ parameter where more than one bridging mode is wanted.
Validated against the **1 kHz @ 40 dB SPL = 1 sone** definition anchor (all
models), +10 dB ≈ 2× (Stevens), monotonicity, silence→0, free≠diffuse. Design +
algorithm + tables: `docs/stdlib/analysis.md`. This completes the GC 1.2 group.
---
## Phase 230 — Configurable `maxEventsPerBlock` + drop telemetry ✓ *(merged to main)*
- **`SynthesisEngine.maxEventsPerBlock`** — the per-block scheduling budget (events
firing per block **and** future-event carry-over / look-ahead depth) was a hard-coded
`private static let = 256`; now an `init` parameter (default
`lyrebirdDefaultMaxEventsPerBlock = 256`, `> 0`, power-of-two **not** required) stored
as a `public let` and read on the RT thread as a plain immutable. Threaded through
`SynthesisEngineConfig` + `EngineHost`. Clarified that this cap — not
`eventQueueCapacity` — is the ceiling that governs whether a large batch of
pre-scheduled / carried-over events survives; the two are independent (carry-over
accumulates across blocks, so `maxEventsPerBlock` may exceed `eventQueueCapacity`,
e.g. under a JIT NRT feed).
- **Drop telemetry + console warning** — when the RT drain discards an event for
exceeding the cap it calls `_recordPerBlockEventDrop()`: a relaxed counter increment
+ a `.releasing` latch store (no allocation / lock / `print` — RT-safe). A non-RT
drain (`freeWorker` timer, `stop()`, and the end of `NRTDriver.start()` so a
fast-exiting NRT process still reports) does an `.acquiring` CAS on the latch and
prints a one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` at most once
per drain. Public `perBlockEventDropCount` / `resetPerBlockEventDropCount()` mirror
the existing `pendingQueueDroppedCount` surface. Docs: `docs/engine/scheduling.md`
(new "Per-Block Event Budget" section).
- Tests: `MaxEventsPerBlockTests` (6) — default-cap drops surplus look-ahead, raised
cap keeps all, exact drop-count arithmetic, counter stays zero within cap, configured
value exposed, default matches constant. Review fixes: latch store `.relaxed →
.releasing` for a correct release/acquire pair with the drain; dropped an over-strict
`maxEventsPerBlock <= eventQueueCapacity` precondition (staging arrays are independent
of ring size — it broke small-queue engines).
---
## Phase 231 — `ctx.onMain` + threading/isolation docs ✓ *(merged to main)*
- **`LyrebirdRoutineContext.onMain(_:)`** — runs a `@MainActor` closure, blocks the
routine/task body until it returns, and hands the (possibly non-`Sendable`) result back.
Lets a `@Sendable` body construct `@MainActor` synthesizers inline, so the *number* and
*parameters* of synths can depend on the body's own logic rather than being pre-allocated
outside and captured (the `BufferDemos` idiom). Built on the existing
`lyrebirdRunMainActorMutation` bridge — that helper returns `Void` because a non-`Sendable`
result cannot cross back through `DispatchQueue.sync`, so a private `_OnMainResultBox`
(`@unchecked Sendable`, safe by the sync hop's full barrier) carries the value out.
Deadlock-free: a body always runs off-main, so the internal `DispatchQueue.main.sync` cannot
re-enter its own thread. Synchronous cost is absorbed by `wait(seconds:)`'s existing drift
compensation. `rethrows`.
- **Threading documentation** — `ARCHITECTURE.md` §9.2 ("Working with the isolation from a
routine or task"): a table of what is main-bound and *why* (load-bearing vs ergonomic),
the pre-publication (`init`) vs post-publication (parameter write) distinction, `ctx.onMain`
for construction, and `ctx.set` + a main-captured `$param` for mutation (a lock-free atomic
write — *not* a main hop; the only cost is the capture). Linked from `GettingStarted.md`
(new "Threading" section), `Lyrebird.docc/RoutineTask.md`, and
`docs/tooling/routine-task.md` (§ Thread model → Actor isolation).
- **Recorded why `SynthesizerBase.init` cannot be made `nonisolated`** — it looks free (empty
base init, `build()` not called from it, fresh synth unshared) but under
`-default-isolation MainActor` a consumer subclass's *implicit* `@MainActor init()` would
override a `nonisolated` base init and fail isolation-mismatch, breaking every unannotated
consumer — the guarantee §9.1 documents. The main suite cannot catch this (it does not build
under that flag); only `RegressionFixtures/MainActorConsumer` does. `onMain` buys the same
ergonomics additively with no isolation change. Dropped the stale `(Phase 201)` tag from the
§9.1 heading per the no-phase-numbers-in-docs rule.
- Tests: `RoutineContextOnMainTests` (4) — result built on the main thread, synthesizer
constructed inside the body (3 dynamic synths all reach `build()`), thrown errors propagate,
non-`Sendable` reference type returned. Suite is intentionally not `@MainActor`: `run`
blocks the caller, so the body's hops need a free main thread.
---
## Phase 232 — Doc sweep + DocC warning ratchet ✓ *(merged to main)*
- **`scripts/check-docc.sh`** — guards against new DocC warnings (broken symbol links,
ambiguous refs, article/symbol collisions). DocC symbol links pin a symbol's **full
signature**, so adding one parameter silently breaks every link to it — and nothing in
`swift build` / `swift test` checks this, which is why ~84 warnings had accumulated
undetected (including one broken by the `maxEventsPerBlock` init parameter in the cycle it
shipped). A **ratchet**, not a zero-gate: fails only on warnings absent from the committed
`scripts/docc-warnings-baseline.txt` (62 entries), so it gates regressions today while the
Score-signature backlog is cleared incrementally. Baseline identity is `message :: file` —
line/col are dropped because they shift on unrelated edits. `--update-baseline` re-records
(may only shrink); `--strict` requires zero (goal state). Verified both directions: an
injected bogus link fails with exit 1; a removed baseline entry reports "now fixed" and
suggests tightening. Manual/CI only (~60s) — deliberately not in `pre-commit`, which is fast
by design. Documented in CLAUDE.md alongside the previously-undocumented
`check-swift6-consumer.sh`, and both added to the phase-completion checklist.
- **Doc corrections — actively wrong:** `SPSCQueue.init(capacity:)` was documented as
"capacity rounded up to next power of 2" in two files; it **preconditions** — a
non-power-of-two traps rather than rounding. `EnvelopeGen`'s usage example called
`engine.schedule(.remove(synth), at:)`, an overload that does not exist (→ `engine.remove`).
`Package.swift`'s own DocC command named `--target Lyrebird`; the target is `LyrebirdSynth`.
- **Doc corrections — stale since add/schedule became throwing:** 11 doc-comment examples
called `engine.add(...)` without `try` (SynthesisEngine, VoicePool, ParallelGroup,
NodePosition, ParameterNode, DiskOut) — none would compile.
- **SynthesisEngine:** `EngineSetup.md`'s init block was missing `controlBlockSize`,
`eventQueueCapacity`, and `maxEventsPerBlock`; added with a table distinguishing the two
scheduling ceilings. Class-doc thread-safety text claimed `add`/`remove`/`schedule` are all
"safe to call from the main thread" — imprecise: `add`/`schedule` are `@MainActor`-isolated
(SPSC single-producer), `remove` is `nonisolated`. `NRTGuide`'s "large scores" advice pinned
the pre-`maxEventsPerBlock` init signature and only mentioned `eventQueueCapacity` — the
carry-over cap is what actually drops a large pre-scheduled batch; now covers both knobs plus
the `TriggerListener` just-in-time alternative. Added a Per-Block Event Budget section to
docc `Scheduling.md`, and normalised ~15 MusicXML symbol links to the current full signature.
- Remaining backlog (baselined, not blocking): ~62 DocC warnings, almost all Score-system
signature links (`Note` / `Chord` / `Part` / `Score.init`), `fill(_:overlap:)` ambiguity, and
5 article/symbol name collisions.
---
## Phase 233 — DocC link repair (62 → 5) ✓ *(merged to main)*
- **Cleared the DocC backlog the ratchet was holding**: 62 baselined warnings → 5. Baseline
tightened accordingly (`scripts/docc-warnings-baseline.txt`); the gate stays green and now
guards a much smaller floor.
- **Root cause, uniformly**: DocC symbol links pin a symbol's **full** signature, and the Score
API grew parameters over the beat-timeline group — `Note`/`Chord` gained
`spanners:`/`display:`/`marks:`/`dynamicCurve:`, `Part` gained `meterMap:`/`offset:`/`id:`,
`Score.init` gained `measureBarlines:`/`timeSignature:`, `ScoreElement.tuplet` gained
`normalType:`, `ScoreElement.chord` gained `tie:`, `toMusicXMLString`/`Data` gained
`rehearsalMarksAsStaffText:`. Every older link silently broke. Links updated to the current
signatures.
- **Converted to plain code where a symbol link cannot ever resolve** (rather than pinning a
fragile signature): overloads that collapse to one DocC signature and are therefore
permanently ambiguous — `Chord(_:dur:…)` (`[Pitch]` vs `[(NoteName, Int)]`),
`ScoreTimeline.fill(_:overlap:)` (array-of-pairs vs dictionary), `dbToAmp(_:)` (scalar vs
array); symbols DocC never emits a page for because they are `internal` — `BeatTrackerCore`,
`Dynamic.midiMaxVelocity`, `Fraction.beatApproxDenominator`; and links to initializers that
do not exist (`Score(parts:)`, `init(parts:)`). Bare `` ``Part`` `` / `` ``Tuplet`` `` /
`` ``Voice`` `` prose mentions likewise became plain code — a DocC link to an overloaded DSL
builder renders as the full ugly signature and re-breaks on the next parameter addition.
- Fixed `` ``.rest(duration:)`` `` (a leading dot never resolves → `ScoreElement/rest(duration:)`)
and pointed `Klank` / `Klang`'s `setBuffer(_:engine:)` links at the nested `Audio` class that
actually declares them.
- **Remaining 5 (baselined, deliberate):** article/symbol filename collisions
(`SendTrigger`, `SpectralChain`, `StepSequencer`, `ValueComputable`,
`GeneratorInputProvider`) — an acknowledged DocC bug where a curated article shadows the
symbol's reference page. These are an information-architecture decision (rename the article
vs. convert it to a symbol extension), not stale links, and both options change published doc
URLs — deferred pending a maintainer call rather than restructured unilaterally.
---
## Phase 234 — DocC catalog to zero warnings ✓ *(merged to main)*
- **Converted the 5 colliding articles to documentation extensions** — `SendTrigger`,
`SpectralChain`, `StepSequencer`, `ValueComputable`, `GeneratorInputProvider`. Each was an
article whose *filename* matched a public symbol, so DocC (by its own acknowledged bug) let
the article shadow the symbol's reference page — the API reference for five public types was
unreachable. Changing each H1 from a plain title to a symbol link (`` # ``SendTrigger`` ``)
makes the file an extension, so DocC merges the guide **into** the symbol's page instead:
one canonical page carrying both the prose guide and the generated API reference.
`@Metadata { @PageKind(article) }` removed (invalid on an extension).
- Cost of the approach, accepted deliberately: the three custom titles are gone
("RT-to-Language Triggers", "Step Sequencer", "Value Sources for Non-RT Loops") — an
extension is titled by its symbol. Each page's abstract still carries the framing.
- `<doc:X>` references across the catalog (Scheduling, ParameterInputs, ProcessSystem,
RoutineTask, Generators/Triggers, Lyrebird.md) rewritten to the symbol-link form ``` ``X` ```.
`Lyrebird.md` curated both `<doc:StepSequencer>` **and** ``StepSequencer`` as separate
Topics bullets — the same page twice once merged — so the duplicates were removed
(same for `ValueComputable`).
- **The catalog is now at zero DocC warnings** (from ~84 at the start of the sweep). The
ratchet's baseline is empty, so `check-docc.sh` now fails on *any* new warning —
`--strict` passes and is equivalent while the baseline stays empty. CLAUDE.md and the
script header updated to describe the cleared state rather than a backlog.
---
## Phase 236 — Doc-example compile harness ✓ *(merged to main)*
- **`scripts/check-doc-snippets.sh`** + **`scripts/doc_snippets.py`** — typechecks the
```swift examples in the DocC catalog and the `///` doc comments against the real API.
Nothing else could: `swift build` never sees a code fence and `check-docc.sh` only
validates symbol links, which is why `engine.add` could become throwing while 11 examples
kept calling it without `try`, and why 75 references to the deleted `LyrebirdFloat`
survived. Both are type errors, so typechecking catches them.
- **Mechanism.** Each fence is generated into a throwaway `.swift` under `mktemp -d`
(nothing touches the working tree): imports hoisted to file scope — each replaced in
place by a blank line so line numbers stay exact — and the body wrapped in
`@MainActor func _fence_N()`. `@MainActor` because doc examples are language-side code
and a nonisolated wrapper would false-positive on every `engine.add`; everything inside
the function so two fences declaring the same helper can't collide at file scope.
`#sourceLocation` makes a failure point at the **original markdown file and line**.
Deliberately not a guard sub-package — that would re-resolve the dependency graph and
full-link a module already built, for a check that only needs `swiftc -typecheck`.
- **Classify, don't mark.** The checked set (`scripts/doc-snippets-manifest.txt`) is
produced by asking the compiler which fences compile, never by annotating ~1450 fences.
Fences that compile under no preamble self-exclude — iOS-only examples, `Package.swift`
snippets and pseudo-code drop out with no skip list. Result: **323 of 1457 checkable**
(304 under `none`, 19 more under `engine`); 1134 fragments unchecked. Classify ~35 s
(parallel), check ~32 s.
- **Soundness bug found and fixed during the build.** The first classify claimed 1455 of
1457 compiled. Batching is unsound: a parse error in one file (an invalid
`Package.swift` fence) aborts swiftc before later files are reached, so "no diagnostic"
does not mean "compiles" — ~1450 unreached fences were silently recorded as passing.
Classification is now one invocation per file, parallelised. Checks still batch, which
*is* sound when clean (no diagnostics at all means the whole set was processed).
- **Verified both directions, and an honest negative.** Renaming a parameter in a covered
example fails with the true source line (`Envelopes/Envelope.swift:143`). But
re-injecting the original historical rot — dropping `try` from
`GettingStarted.md`'s `try engine.add(MySynth())` — **passes**, because that fence needs
both an `engine` and a `MySynth` in scope and is therefore unclassifiable. The harness
does not cover the exact incident that motivated it. The fix is to make that example
self-contained (phase 237), not to grow the preamble table.
---
## Phase 237 — Doc-example fallout + golden values ✓ *(merged to main)*
- **Fixed the flagship example, which did not compile.** `GettingStarted.md`'s "Add a
synthesizer" — the first code a new user copies — set `doneAction = .freeEnclosing` inside
`build()`. `doneAction` is not a member of ``SynthesizerBase`` (it is a read-only
*Generator* property), and **`.freeEnclosing` does not exist at all** (the cases are
`.nothing` / `.freeNode` / `.loop`). Two errors in six lines. Replaced with a plain
continuous synth, plus a second example showing the real self-freeing idiom —
`EnvelopeGen(doneAction: .freeNode)`.
- **Made the entry examples self-contained**, which is better documentation *and* pulls them
into harness coverage: the wiring example is now a complete `main.swift` (engine + start +
add) rather than the bare fragment `try engine.add(MySynth())`. `GettingStarted` went from
**0 of 5** covered to 3.
- **Closed the coverage gap phase 236 reported.** Re-injecting the original historical rot —
dropping `try` from `GettingStarted`'s `engine.add` — now **fails** at the exact markdown
line. In phase 236 that same injection passed.
- **Two harness fixes found by chasing that gap:**
- The generated wrapper was not `throws`, so **every fence using `try` failed to
classify** — silently excluding the exact examples most worth checking. Making it
`throws` unlocked +53 fences (a missing `try` still errors, which is the point).
- Preambles are now tried narrowest-first (`none` → `synth` → `engine`), because a
preamble that declares a name the fence also declares makes the fence fail. Coverage:
**382 of 1458** (was 323).
- **Golden values — the rot a typecheck cannot see.** `DistributionKind`'s four documented
sequences passed `seed:` to ``TemporalTendency``, which has no such parameter (the seed
belongs to ``TemporalStream``), so none of them compiled. Worse, once run against the real
API, **three of the four documented sequences were wrong** — `.lpRand`, `.hpRand`,
`.meanRand` had drifted, while their prose descriptions stayed correct (actual `.lpRand` is
exactly `uniform²`, as described). Corrected the API and the values, and pinned them with
`DistributionKindGoldenValueTests`, which also asserts the *characterisations*
(`.lpRand == uniform²`, `.hpRand == 1 − uniform²`) so the prose is verified rather than
merely asserted.
- **Kept `_DocTheorySnippetCheckTests` rather than retiring it.** The plan assumed the
extractor would subsume it; the harness does now typecheck **17 of theory.md's 21** fences,
but that suite *is* value assertions (`#expect(Interval.majorThird.semitones == 4)`) —
precisely what a typecheck cannot do. Deleting it would have lost coverage. Its header now
states the division of labour, and CLAUDE.md records golden-value tests as the standing
companion to the compile guard.
---
## Phase 238 — Doc-rot gap pass ✓ *(merged to main)*
Swept what the guards could not see. Each item below was measured, not assumed.
- **`LyrebirdUI.docc` was entirely unguarded** — `check-docc.sh` only built the
`LyrebirdSynth` target, so a broken link in the public UI module's catalog produced no
signal anywhere. The gate now builds every consumer-facing catalog
(`TARGETS=("LyrebirdSynth" "LyrebirdUI")`). Its first-ever build came back at **0 warnings**,
so nothing needed fixing — but the coverage was the point. Verified in both directions: an
injected bogus link into `LyrebirdUI.docc` now fails with the correct file.
- **The LiveCompile catalog stays a deliberate gap.** `LiveCompile/` has no
`swift-docc-plugin` dependency, so `generate-documentation` cannot run there at all; its
catalog is one 86-line file with 2 fences. Adding a plugin dependency and a second gate
invocation to a dev-only sub-package is disproportionate. Recorded in `check-docc.sh`'s
header so the omission is a decision rather than an oversight.
- **Known-dead API forms: clean.** Grepped the whole corpus for every form this series
retired — `.freeEnclosing`, `doneAction` assignment on a synth, `LyrebirdFloat`,
`LyrebirdInt`, `seed:` on an algorithm — and found **zero** remaining outside the historical
planning archives (which legitimately record what was true at the time).
- **Implemented the fourth preamble, `member`.** Triage of the 1062 unchecked fences showed
the single biggest blocker was `output` (118 occurrences) — `output(bus:source:)` is a
`SynthesizerBase` member that exists in no other context, so those fences are `build()`
bodies lifted out of their class. `member` is structurally a *wrapper*, not a text prefix:
the body goes inside `final class DocSynth_N: SynthesizerBase { override func build() { … } }`.
Gain: **+30** (396 → **426**). Less than hoped, because most `output` fences *also*
reference a previous fence's locals — which brings us to:
- **The remaining 1032 are dominated by continuation fences and are not preamble-fixable.**
The undefined identifiers are `sig` (142), `osc` (62), `lfo` (32), `env` (18) — arbitrary
locals defined in a *preceding* fence. No preamble can supply those; only rewriting the doc
self-contained can, one example at a time (as phase 237 did for GettingStarted). All four
planned preambles (`none`/`synth`/`engine`/`member`) are now implemented, and per the plan
the table stops here.
- **Golden values: `DistributionKind` was the only gap.** A corpus scan for docs asserting
concrete numeric output found exactly two files. The other, `LyrebirdMusicMath`'s
`interpolateAt` examples, turned out to be **already pinned** — including both documented
clipping cases — by `MusicMathTests.interpolateAtFraction/ClipHigh/ClipLow`. Verified the
values against the real API anyway (all three correct). No new test needed.
- **Verified the guards compose.** Breaking a doc example fails the check via the content
hash; following the advice to `--classify` is then **REFUSED** by the shrink guard
("A doc example probably broke — fix it rather than un-recording it"). A broken example
cannot be silently un-recorded without an explicit `--allow-shrink`.
---
## Phase 239 — Doc checks in the review process ✓ *(merged to main)*
- **`scripts/check-doc-impact.sh` + `scripts/doc_impact.py`** — reports which docs a diff's
public-API changes may have invalidated. Doc rot is overwhelmingly *caused* by an API
change, and a review that reads only the diff **structurally cannot find it**: the stale
references live in files the diff never touches. Validated against the real commit that
caused the original incident (`f4b5be6`, which converted `engine.add` to `throws`) — the
tool names `SynthesisEngine.add` and lists the docs referencing it, which is exactly the
set that then rotted for months.
- **It reports and never fails.** It cannot distinguish "intentionally unaffected" from
"forgotten", and a check that cannot judge must not block. Every other guard in the repo
fails on violation; this one deliberately does not, which is why it is wired into
`/lyrebird_review` (step 2b) and pasted into the review agent's prompt rather than run as a
gate.
- **It composes with the existing guards instead of duplicating them.** References inside
fences that `check-doc-snippets.sh` already typechecks are **suppressed** — re-reporting
them would bury the references nobody is checking. Everything it lists is unverified by any
automation.
- **Two precision problems, both fixed by measurement rather than assumption:**
- Matching the bare declaration name returned **1329** hits for `add` — almost all English
prose ("must *add* the same two-line extension"). That is the same signal-to-noise failure
that sank phase 235b's corpus-wide identifier lint. References must be **code-shaped**
(a call, a symbol link, or a code span): 1329 → 278.
- The detector is name-based, so `add` also matched `group.add(` / `pool.add(`. Git's hunk
headers carry the enclosing declaration, giving the owning type for free — the report now
says `SynthesisEngine.add` vs `LyrebirdEventList.addPreMaster`, and states plainly that a
member name is matched across types so the reviewer qualifies by owner.
- Output is **grouped by file with counts**, not a flat sample: for a common member name a
flat list is hundreds of lines and a reviewer checks none of them.
- **New public API with no doc reference anywhere is called out explicitly** — the
`maxEventsPerBlock` case, which reached zero `.docc` files in the cycle it shipped.
- Wired into `/lyrebird_review` (new step 2b) and the review agent's documentation-accuracy
section, which now says to *work the list* rather than to remember to grep. Correctly
silent on docs-only diffs.
**Known limits, recorded honestly:** it is a text matcher, not a semantic one. It cannot see
rot that no API change caused (`theory.md`'s `.freeEnclosing` was already dead — that needed
the phase 238 sweep), and for short common member names the candidate list is long enough that
the reviewer must qualify by owning type. It narrows where to look; it does not decide.