Skip to content

bloom-audiod: the playback daemon skeleton — socket, devices, transport - #12

Merged
ninjudd merged 3 commits into
mainfrom
feat/audiod
Aug 5, 2026
Merged

ninjudd merged 3 commits into
mainfrom
feat/audiod

Conversation

@ninjudd

@ninjudd ninjudd commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Chunk 1 of playback.md §4, implementing the decisions recorded in §3 (daemon-lite, per-project socket, NDJSON, local device state, resample-with-notice, CMake+JUCE). The docs commit also closes out mix-assembly's status lines.

What this adds

  • native/audiod/ — the first C++ in the repo: a JUCE console daemon (~500 lines) built by ~40 lines of CMake (FetchContent, pinned JUCE 8.0.4; AGPL quarantined here by design). pnpm build:native, never postinstall.
  • The control socket — versioned NDJSON over .bloom/audiod.sock: hello (protocol handshake), devices, device.select, load, play/pause/stop/locate (samples), status, quit, plus broadcast events (state transitions, 4 Hz position). Zod schemas are the TS-side source of truth. Socket paths bind relative to the project root — sun_path is 104 bytes and project paths aren't.
  • Daemon-lite lifecycle — the client spawns the daemon on demand (stderr → .bloom/audiod.log), polls the socket, and the daemon idle-exits. Second connection reuses the running daemon (verified live: bloom devices twice = one process).
  • Sample-accurate transport — JUCE AudioTransportSource; on load the daemon tries to run the device at the file's rate, else resamples and reports resampling: true in status (§3.5).
  • --null-output — a clock thread pulls the transport at real-time pace with no device, so CI runs the entire protocol against the real daemon: spawn, handshake, load, transport, locate bounds, position/state events, end-of-stream, multi-client. CI caches the JUCE build on the CMakeLists hash.
  • bloom devices — the first consumer.

Bugs the pre-review soak caught

A 60-round loop of the multi-client scenario surfaced two classic native traps before review did:

  1. std::terminate on client disconnect — the reader thread's Connection (owning a joinable std::thread) could be destroyed on its own thread. Readers now mark themselves closed; the message thread joins and reaps them (single fd closer, no double-close on reused descriptors).
  2. SIGPIPE on writes to vanished clients — a position broadcast racing a ctrl-c killed the process. SIG_IGN + SO_NOSIGPIPE.

Plus client-side: in-flight requests reject when the connection drops — a daemon death is an error, never a hang.

Verified

  • 124 tests pass (5 new protocol tests, skipped where the binary isn't built), full suite green 3× consecutively, standalone soak 60/60.
  • Live on real hardware: bloom devices lists Core Audio devices (Volt 476, speakers), spawn + reuse confirmed.

Next PR (§4.2): bloom play through the daemon — blocking with position streaming, --from <bar.beat.tick>, the bloom transport family, afplay demoted to fallback.


Note

Medium Risk
New native process boundary, unix socket IPC, and multi-threaded connection handling (SIGPIPE/std::terminate fixes are in-tree). CI now depends on macOS native builds; user-facing playback path unchanged until the play handoff.

Overview
Introduces playback chunk 1: the first native bloom-audiod daemon (native/audiod/, CMake + JUCE 8.0.4 via FetchContent), built with pnpm build:native and wired into CI with a cached JUCE build.

The daemon serves versioned NDJSON on .bloom/audiod.sock: transport (load, play/pause/stop/locate), device enumeration/selection, status, and broadcast state/position events. Daemon-lite behavior: CLI spawns on demand, idle timeout exits when no clients and transport stopped. --null-output runs a real-time clock thread so CI can exercise the full protocol without hardware.

TypeScript adds Zod protocol schemas, AudiodClient (spawn, handshake, request/response, events), protocol tests against the real binary, and bloom devices as the first consumer. bloom play still uses afplay; handoff is planned next.

Docs: mix-assembly marked shipped; playback moved to now; project tracking updated. vitest.config.ts limits tests to src/**/*.test.ts so fetched JUCE sources are ignored.

Reviewed by Cursor Bugbot for commit 5075968. Configure here.

The first native code (playback.md, decisions in section 3). A C++/JUCE
daemon (CMake + FetchContent, pinned JUCE 8.0.4, AGPL quarantined here)
serving a versioned NDJSON protocol over .bloom/audiod.sock: hello,
devices, device.select, load, play/pause/stop/locate (samples), status,
events (state transitions, 4 Hz position), quit. Daemon-lite lifecycle:
the CLI spawns it on demand (stderr to .bloom/audiod.log), it idle-exits;
one daemon per project, socket paths bound relative to the project root
to stay inside sun_path. Sample-accurate transport via JUCE's
AudioTransportSource; on load the daemon tries to run the device at the
file's rate and otherwise resamples and says so in status.

A --null-output mode pulls the transport at real-time pace with no
device, so CI exercises the entire protocol - spawn, handshake, load,
transport, position events, end-of-stream, multi-client - against the
real daemon. Two bugs the soak loop caught before review: destroying a
joinable std::thread on client disconnect (std::terminate mid-service;
readers now mark themselves closed and the message thread reaps them)
and writes to vanished clients raising SIGPIPE (ignored + SO_NOSIGPIPE).
The TS client rejects in-flight requests when the connection drops, so a
daemon death is an error, never a hang. bloom devices is the first
consumer; bloom play moves onto the daemon next PR.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5075968. Configure here.

Comment thread native/audiod/src/server.cpp Resolved

@ninjudd ninjudd left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head 5075968 (local checkout matches). I built the daemon from scratch here (pnpm build:native, JUCE 8.0.4 fetch + compile clean), ran the full suite — 124/124, with all 5 protocol tests executing against the real binary, not skipped — and smoke-tested on real hardware: bloom devices lists the Volt 476 and speakers, and two invocations share one daemon process. CI green (test + Bugbot).

Two findings, both verified by execution. The second is a one-liner; the first is the real one.

  1. P2 — daemon shutdown deadlocks when a request races the exit; the client hangs forever with it. Inline on server.cpp. My probe (client A hammering status while client B sends quit) deadlocked on round 1 of 15, and a thread sample of the stuck process shows the exact mechanism. This isn't only a quit race — the idle-exit path can hit the same window against a freshly connecting client, which is precisely the daemon-lite spawn scenario.
  2. P3 — bloom devices fails with ENOENT: … .bloom/audiod.log on any project that has never run a build. Inline on client.ts. .bloom/ is created lazily by the build cache, and the client opens the log without creating the directory — so the PR's headline command fails on exactly the first thing a fresh clone would try. The protocol test masks it by mkdirSync-ing .bloom itself.

Verified clean:

  • Both pre-review soak fixes hold up under reading: the sweep is the single closer (readers only mark open = false; joins happen on the message thread; a reused fd can't be closed twice), and SIG_IGN + SO_NOSIGPIPE is belt-and-suspenders as described. The multi-client test exercises the disconnect path the soak was for.
  • Client lifecycle: in-flight requests reject on connection close (never a silent hang — for a dead socket; finding 1 is the case where the socket stays alive), spawn-race between two CLIs self-heals (loser daemon sees "already owns" and exits), stale sockets are probed-then-replaced, and the BLOOM_AUDIOD override hard-errors on a missing path — the same contract as BLOOM_SCLANG after #7.
  • The §3 decision record is exactly the AGENTS.md shape — each decision with its rejected alternatives — and the §3.2 sun_path constraint is handled consistently on both sides (daemon binds cwd-relative, client connects cwd-relative when shorter).
  • CMake stays the promised ~40 write-once lines; AGPL quarantine holds (JUCE linked only into the daemon binary, nothing in the TS package); build:native is explicit, never postinstall; the CI cache key on the CMakeLists hash is right (source edits still rebuild incrementally inside the cached build dir).
  • vitest.config.ts correctly stops vitest from discovering JUCE's own test files once native/audiod/build exists — without it the suite breaks after the first native build.

One hardening note, not a thread: client.ts onData calls JSON.parse on each line with no try/catch — a daemon that ever emits a malformed line crashes the CLI with an uncaught exception, despite the neighboring comment's promise that a raw error must not crash the CLI. Unlikely today (the per-connection write mutex prevents interleaved lines), but a try { … } catch { this.socket.destroy(); } would make the promise true. Fine to fold into the next PR.

Merging is Justin's checkpoint; with finding 2 fixed and finding 1 addressed (or consciously deferred with the risk understood), this is a solid foundation for the §4.2 handoff.

Comment thread native/audiod/src/server.cpp Resolved
Comment thread src/audiod/client.ts Resolved
ninjudd added 2 commits August 5, 2026 12:56
…arse guard

P2: a request landing in the shutdown window parked its reader on a
MessageManagerLock nothing would ever grant - main had left the dispatch
loop, so ~Server's join deadlocked and the daemon zombied with its client.
Shutdown is now two-phase: beginShutdown() stops accepting and half-closes
read sides while the loop still dispatches, then main keeps dispatching
until every reader drains (progress guaranteed: each pass grants pending
locks), and only then does destruction join. The same-instant accept race
gets its half-close in the accept loop. Reviewer's probe carried as a
regression test (status hammer vs quit), green 8 consecutive runs.

P3: the client now creates .bloom/ before opening the daemon log - a
project that has never built can spawn the daemon; the protocol tests no
longer pre-create the directory, so they prove it.

Hardening: a malformed daemon line is skipped, not a CLI crash.
Two daemons spawned in the same instant could each fail the connect
probe and unlink the other's freshly bound socket, orphaning one until
idle timeout. The probe is gone: Server::start takes an exclusive flock
on .bloom/audiod.lock, held for the daemon's life and released by the OS
on any death, so it cannot go stale; with the lock won, any existing
socket file is by definition a dead daemon's leftover. The lock file is
never unlinked - removing it would reopen the race for the next pair.
Regression test: six concurrent first connections on a fresh project all
end up served by the one surviving daemon.

@ninjudd ninjudd left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fresh review of the fix range 81640e8..da1d56f at head da1d56f, requested because the P2 fix restructured the daemon's shutdown path — verified by execution, not just reading. Rebuilt the daemon from these sources; typecheck clean; all 126 tests pass; CI test job green on this head.

Shutdown restructure (P2 fix) — verified two ways:

  • My original probe scenario, 15/15 clean. A standalone probe spawning the daemon directly (real pid, no client library): one raw socket hammering status at 1 ms intervals, a second sending quit mid-hammer, then requiring the process to exit within 10 s. Pre-fix this deadlocked on round 1; post-fix, 15/15 rounds exited cleanly.
  • The idle-exit window too, 30/30 hang-free. The race I flagged as worse than quit — a client connecting in the instant idle-exit fires — probed with per-round jitter scanning 950–1385 ms across a --idle 1 daemon's exit window. Outcome spread confirms the scan actually crossed the window (10 rounds served, 20 refused, 0 closed-mid-handshake); every connect was served or refused within the watchdog, never hung, and the daemon exited every round. No leaked processes after either probe.

The design is right by reading as well: beginShutdown() runs while the loop still dispatches, so a reader parked on the MessageManagerLock is always eventually granted, finishes its request (write side deliberately left up — nice touch), hits EOF from SHUT_RD, and marks itself closed; the drain loop's connectionCount() > 0 condition is monotone because nothing new can arrive past the listen-socket shutdown. The same-instant accept race is genuinely closed: running = false is stored before beginShutdown takes the connections mutex, so a connection appended after its sweep necessarily observes !running in the accept loop and gets its half-close there. Destruction joins nothing live.

Bugbot's flock fix — correct, and better than the probe it replaced. The connect-probe TOCTOU was real (two same-instant spawns could each unlink the other's freshly bound socket), and an exclusive flock held for the daemon's life is the canonical fix: kernel-released on any death so it can't go stale, and never unlinking the lock file is the right call — deleting it would reopen the race for the next pair. The 6-way stampede test pins it.

P3 + hardening: mkdirSync sits correctly in the spawn path (covering the daemon's own socket bind), and un-pre-creating .bloom/ in the tests turns the old mask into permanent regression coverage — exactly the right move. The JSON.parse guard's skip-the-line choice is fine (arguably better than my suggested destroy).

Nothing new to raise. Ready for Justin's merge.

@ninjudd
ninjudd merged commit 08575a6 into main Aug 5, 2026
1 check passed
@ninjudd
ninjudd deleted the feat/audiod branch September 28, 2026 04:10
ninjudd added a commit that referenced this pull request Oct 11, 2026
…-portability.md chunk 1) (#157)

Chunk 1 of the [Windows portability
plan](../blob/windows/gitattributes/docs/projects/windows-portability/readme.md),
and the diff that moves the plan from `status: draft` to `status:
in-progress` at `priority: now`.

## Why

field hashes file content as it sits on disk: `.scd` programs are
action-key inputs, `field check`'s canonical-formatting comparison is
byte-wise, asset pins are the sha256 of committed bytes, and
`toPluginWire` refuses a state blob that stops hashing to its filename.
Git for Windows defaults `core.autocrlf=true`, so a fresh Windows clone
rewrote every text file to CRLF on the way to disk and changed all four
answers while `git status` stayed clean — git compares normalized
content; field reads the working tree.

§1.1's original measurement, on
`examples/bloom/shared/instruments/creek-kit.scd`:

```text
on-disk size: 2323 bytes, CR bytes present: 71
sha256 on disk : 197c273b…  (what a Windows clone hashed)
sha256 as LF   : 49f970a7…  (what everyone else hashed)
```

## What

One committed file: `* text=auto eol=lf`, with `binary` overrides for
the seven audio extensions and `*.state` — captured plugin state is
named by its own sha256 and `plugins.ts` refuses a blob that stops
hashing to its filename, so it must never ride the binary heuristic
(minjudd's finding on #154). Neither file type is in the tree today; the
rules exist so the first one arrives safely.

`git add --renormalize .` stages nothing: every blob in history is
already LF, so the attribute changes no committed content.

## Proof, per §1.1's amended definition

A fresh clone on a real Windows machine with `core.autocrlf=true`
inherited from global config:

```text
fresh clone, autocrlf=true:
  size: 2252 bytes, CR bytes: 0
  sha256: 49f970a7db30fc972b8ef060e55e3ae2991107137fbf9dd1a6ebb88e59dcea61
  match with the LF form named in the plan: True
  CR bytes across all text files in the clone: 0
```

2252 = 2323 − 71: the file now checks out byte-identical to its
committed form.

## The plan goes in-progress in the same diff

Chunk 1 is where implementation begins, and the flip answers §2's
decisions per the convention that the readiness claim answers for what
is open:

- **§2.1 named pipes** over loopback TCP for the transport —
`FILE_FLAG_FIRST_PIPE_INSTANCE` carries the single-owner guarantee
`flock` provides today; a port file reopens the staleness race #12
review closed.
- **§2.2 no non-daemon fallback** for `field play` on Windows — since
realtime.md, `field play` *is* live evaluation; without the daemon it
fails with "build the daemon".
- **§2.3 `socketPathFor` grows a platform branch** in the same function
— named pipes have no `sun_path` limit and are not filesystem paths.
- **§2.4 the "V1 platform scope" amendment rides this diff**, because
the plan's own rule tied the `in-progress` flip to it: Windows and Linux
move out of the out-of-scope list into a paragraph naming them
build-and-test targets, reusing linux-portability.md decision 5's
framing. The product ships on macOS.

§6's four open questions each carry a disposition: two deferred to chunk
4 with their tests named, one answered by the hasher grep, and the
104-byte question answered by §2.1 and §2.3. The plan's frontmatter
carries the move to `priority: now`, so `project list` shows it under
"now" with no separate list file to edit.

## Testing

Run these from the root of a checkout of `windows/gitattributes`. They
need no build and change nothing in the tree.

```sh
git check-attr text eol -- examples/bloom/shared/instruments/creek-kit.scd song.wav plugin.state
git ls-files --eol | grep -c 'i/crlf'
shasum -a 256 examples/bloom/shared/instruments/creek-kit.scd
wc -c < examples/bloom/shared/instruments/creek-kit.scd
project check
pnpm typecheck && pnpm test
```

You should see `text: auto` and `eol: lf` for `creek-kit.scd`, and
`text: unset` for the `.wav` and `.state` paths, which shows the binary
overrides win. The `grep -c` prints `0`, because no committed blob
carries CRLF. The hash is
`49f970a7db30fc972b8ef060e55e3ae2991107137fbf9dd1a6ebb88e59dcea61` and
the size is `2252`, the LF form §1.1 records. `project check` prints
`Project plans are valid.`, and the suite passes. The change is wrong if
`.wav` or `.state` reads `text: auto` or `text: set`, if any blob counts
as `i/crlf`, or if the hash is `197c273b…`, the CRLF form.

The Windows half of the proof needs a Windows machine: clone with `git
-c core.autocrlf=true clone`, then run the same `shasum` and size checks
there. Expect the same hash and `2252` bytes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- projector-summary v=1 sha=6d63b2b5b971c28f0a906985c59fb8054f9bf18f
-->
📽️ **Projector summary** of 6d63b2b: https://field.amnes.ac/reviews/157

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Justin Balthrop <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant