* Make peer registry and local announce state lock-backed The main actor answered isPeerConnected/peerNickname/currentPeerSnapshots and flipped runtime capability bits by blocking on collectionsQueue behind whatever transport work was in flight. Peer state now lives in a lock-backed BLEPeerRegistryStore (every registry mutation is a single whole-transition method, so readers never observe a torn state), and the runtime capability bits move into BLELocalIdentityStateStore next to the identity they ride announces with. No transport entry point called from the main actor blocks on a transport queue for peer state anymore. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Move BLE link egress/ingress buffers to bleQueue ownership pendingPeripheralWrites, pendingNotifications, and pendingWriteBuffers were collectionsQueue-guarded, but every producer and drain already runs on bleQueue next to the CoreBluetooth objects they feed — each access paid a cross-queue barrier for state that never leaves the radio thread, and the notification drain even invoked peripheralManager.updateValue from the collections queue. They are now bleQueue-confined like the link state store: CB delegate callbacks and drains touch them directly, and the few engine-side entry points hop to bleQueue (the direction the transport's sync-edge order already allows). This clears most bleQueue-to-collectionsQueue sync edges ahead of merging the collections queue into the message queue. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Stop bleQueue maintenance and status paths from blocking on collectionsQueue The traffic-burst tracker becomes a lock-backed monitor (written by the receive pipeline, read by scan-duty adaptation and announce pacing on bleQueue), the status-log peer summary and topology refresh read the already lock-backed registry directly, and the stalled-fragment reap moves to an async collections hop with the gossip resync request inside it. bleQueue no longer sync-waits on the collections queue anywhere. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Unify the message and collections queues into one serial engine queue The old model ran a concurrent message queue over a second concurrent collections queue whose barrier flags served as the real mutual exclusion — every field carried an ownership comment, and correctness lived in per-site discipline. The message queue is now a single serial engine queue that owns all mesh protocol state; the collections queue, its 98 sync/async hops, and every barrier flag are gone. Cross-thread callers go through onEngine, which documents and (in debug) enforces the transport's sync-edge order: main and test threads may block on the engine, the engine may block on bleQueue and the crypto/identity queues, and nothing may block the other way. The debug trap caught two latent inversions the leaf-lock structure had been masking: the verified-announce rebind path re-resolved the ingress link through the engine from inside its bleQueue critical section (it now receives the already-resolved link), and the noise session-generation closures sync-re-entered the engine from the noise manager's queue while their own engine slot was blocked on it (they now touch engine state directly, which the held slot makes exclusive). BLE throughput is orders of magnitude below what one serial queue sustains; the full suite runs at identical speed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Wire gateway/bridge/panic features to capability ports, not BLEService App wiring discovered mesh-only features by casting the Transport to the concrete BLEService class in nine places. Those surfaces are now three capability protocols — BluetoothStateReporting, PanicResettingTransport, and MeshBridgingTransport — discovered with as? like any optional capability, so the bootstrapper, panic flow, and lifecycle coordinator no longer name the concrete transport at all. A future second mesh transport picks up gateway/bridge wiring and the panic lifecycle by conforming, and the remaining Transport god-protocol requirements can migrate to the same pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Extract mesh-ping diagnostics state into a pure engine-confined tracker First slice of the feature-module direction: BLEMeshPingTracker owns the outstanding-probe map and the per-link inbound response budget as pure state (register/resolve/expire/reset), so the security invariants — a pong only resolves against the probed peer, the budget keys on the ingress link because claimed senders are forgeable, panic reset drops probes and budget together — are now unit-tested without queues or radios. The transport keeps only packet I/O, timers, and main-actor delivery around it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Document the V3 transport architecture and remaining roadmap Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Resolve the pass-6 review findings and the proof-timeout drain defect Periphery: the registry store's unused forwarders are gone (the struct method stays — it has direct tests). F1: refreshPeerIdentity, deliverBridgedEnvelope, and the three panic fences route through onEngine, so every sync entry onto the engine now carries the bleQueue trap. F2: the registry-store ownership comments state the real writer set (engine plus the two bleQueue link-drop paths). F7: BLEQueueContractTests pins the contract — only onEngine may sync-enter the engine, transport code never sync-dispatches to main, and the collections queue stays deleted — with a queue-contract-ok waiver for the two sanctioned lines. The real defect behind the timeoutRestoredSession CI flake: a timeout-restore parks the outbound queues until the convergence retry, but the capability-proof watchdog armed at the original authentication kept draining them when it fired — encrypting the parked traffic under restored keys the counterpart may have discarded, the exact silent loss the defer path exists to prevent. Deferred peers are now tracked and the watchdog drain respects the same rule; the test fires the watchdog deterministically inside the deferred window instead of losing that race only on stalled runners. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Extract private-media session state into a lock-backed store The six generation-keyed maps plus the convergence-deferral set move out of BLEService into BLEPrivateMediaSessionStore, each transition one whole method under a leaf lock with direct unit tests (generation rotation rejects mismatched waiters, stale proofs cannot classify a replacement session, expiry requires the live deadline identity, clears rebase waiters onto a nil-generation deadline, peer-state sends are once per generation per kind). Being a leaf lock also simplifies two contracts: the send policy is now answered entirely from locks (the main actor no longer sync-enters the engine for it), and the noise-manager critical sections call ordinary store methods instead of relying on the held-engine-slot direct-access subtlety. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Split the mesh-only Transport surface into capability protocols Transport kept ~50 requirements that only the BLE mesh implements — files/private media, voice, courier, groups, board, diagnostics, verification, archive — held together by an extension of inert defaults, so every call site compiled against a surface most transports faked. Those are now eight capability protocols (MeshFileTransferring, MeshVoiceStreaming, MeshCourierTransporting, MeshGroupMessaging, MeshBoardBroadcasting, MeshDiagnosing, MeshVerifying, MeshPublicArchiving) discovered with as?, joining the bridging/panic ports from the previous pass. Consumers resolve the capability they need; where the old defaults encoded a safe floor the caller keeps it explicitly (private-media policy degrades to blockedDowngrade). The inert-defaults extension is deleted, along with the never-implemented acceptPendingFile/declinePendingFile pair. NostrTransport is untouched — it only ever implemented the core. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Update the V3 doc for the completed feature-peeling and Transport split Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Drop the dead three-argument sendFilePrivate overload Every production caller goes through the allowLegacyFallback variant; the short form only existed as a Transport-era forwarding default. Tests that used it on the concrete service now state the fallback decision explicitly, which is the point of the parameter. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Decide the link-auth boundary: bindings become engine-owned The atomicity that keeps link-auth on bleQueue exists to stop a binding from changing between a security check and its action; once every rebind is an engine operation, the engine's serial slot gives the same guarantee, the stolen-link residual is unchanged (directed payloads are Noise ciphertext), and the receive path lands in its sans-I/O shape — the link layer reports bytes-plus-linkID and the engine resolves the sender. Records the extraction order too: the binding-free radio half first (after #1521 lands — it collides in the scanPlan region), then bindings, then the delegates behind the port. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix two bleQueue-to-engine sync edges the queue merge created The collections-to-engine conversion turned two formerly leaf-lock sync calls into onEngine calls reachable from bleQueue, where the debug trap (correctly) aborts: flushDirectedSpool runs from bleQueue maintenance and now hops to the engine asynchronously, and ingress recording — which must answer the duplicate gate on bleQueue the moment a frame decodes — moves to a lock-backed BLEIngressLinkStore read by the engine's relay and routing decisions. Unit suites never hit either path (no CoreBluetooth managers means no maintenance timer and no live receive path); the iOS simulator job boots the real app as its test host, which is exactly where the maintenance trap fired. The ingress one would have trapped a real device on its first received packet — worth a device pass before release. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Route all deferred engine work through an injectable scheduler Relay jitter, announce delays, the ping and capability-proof deadlines, notification retry backoff, and fragment pacing all reached the engine through raw messageQueue.asyncAfter with product constants as deadlines — the hidden-elapsed-deadline flake class that the test-timing hygiene rules exist to contain, testable only by racing the wall clock. BLEEngineScheduling is now the transport's single source of engine delay: production is a thin veneer over the engine queue, tests inject a manually advanced clock whose advance() returns only after the released work has finished on the engine. The queue-contract test pins the seam (no raw messageQueue.asyncAfter), and the ping deadline gets the pattern's proof: the real 10s constant asserted in milliseconds — must not fire early, fires exactly once at the deadline, stays consumed after. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Assert the armed deadline count in the injected-clock ping test Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
9.3 KiB
BLE Transport Architecture V3
The plan of record for restructuring BLEService from an 8.3k-line god
object into a layered mesh stack. ARCHITECTURE_V2 rebuilt the app layer
above the transport and deliberately deferred the transport itself; this
document covers that remainder: what already landed, the target shape, and
the order for the rest.
Why the satellite strategy stalled
V2's transport approach was to peel pure policies and closure-driven
handlers out of BLEService while the class kept coordinating. The ~30
pure policy structs were a clear win. The five big handler extractions
were not: each needed an "environment" of 20–30 closures that weakly
capture the service and hop queues back into its state. Logic left, but
state ownership and synchronization never moved, so extraction paid a
plumbing tax that grew as fast as the logic shrank — the five
make*HandlerEnvironment() factories alone were ~1.5k lines. The file
held ~60 mutable fields across four concurrency domains whose ownership
lived in comments, and every new feature added Transport requirements,
state maps, and switch cases to the same class.
Two chronic costs came straight from that structure: queue-order deadlocks (the July 9 main↔bleQueue ABBA freeze), and timing-dependent tests (correctness only observable through real queues and real time).
Target shape
A packet-radio stack with one rule per layer about state and threads:
BLELinkLayer— the only CoreBluetooth import. Owns both managers, scanning/advertising, duty cycle, connection scheduling, MTU, write and notification backpressure buffers, state restoration. SpeaksLinkEventup (link up/down, bytes in, writable) andLinkCommanddown (send bytes on link, scan/advertise policy). Knows nothing about packets, peers, or Noise. bleQueue-confined. ASimulatedLinkLayerimplementing the same port gives multi-node tests real topologies with no radios and no wall-clock waits.- Mesh engine — one serial queue owning all protocol state: wire
codec, fragmentation, dedup, relay policy, peer registry, topology,
gossip sync, Noise orchestration. Synchronous single-writer logic; the
pure policy satellites slot in unchanged. Endgame: the engine core
becomes
handle(event, now) -> [Effect](sans-I/O), which makes the whole mesh property-testable and fuzzable in simulation. - Feature modules — courier, board, prekeys, private media, file transfer, voice, diagnostics, groups, verify/vouch each own their state and register for their message types. A new feature is a new module, not edits to the engine.
- App boundary — a small
Transportcore both transports genuinely implement, plus capability protocols discovered withas?(MeshBridgingTransportetc.), replacing the ~90-requirement god-protocol and its inert defaults.
Concurrency contract
State is owned one of three ways:
- Engine-confined — mutated only on the serial engine queue
(
mesh.message). Cross-thread callers useonEngine. - bleQueue-confined — link-layer state next to CoreBluetooth objects (link store, write/notification buffers, link-auth maps).
- Lock-backed store — state with legitimate cross-domain readers (peer registry, local identity/capabilities, traffic monitor). Writes still come from one domain; the lock exists so readers never block on a queue. Every mutation is a single whole-transition method, so readers never observe torn state.
Sync-edge order (deadlock freedom by construction, debug-enforced in
onEngine):
main / test threads ──sync──▶ engine ──sync──▶ bleQueue
└──sync──▶ noise / identity queues (leaves)
Nothing may sync-wait in the reverse direction: bleQueue and the crypto
queues reach the engine only via async, and nothing sync-dispatches to
main. Two subtleties worth knowing:
- A closure executed inside a noise-manager critical section entered from an engine slot may touch engine state directly (the blocked slot makes it exclusive) but must never sync-re-enter the engine — that is a self-deadlock.
- bleQueue critical sections (e.g. the verified-announce link rebind)
must receive engine-derived values as arguments rather than fetching
them through
onEngine.
What landed in this pass
- Lock-backed peer state (
BLEPeerRegistryStore): every main-actor Transport read (isPeerConnected, nicknames, snapshots, capability queries) reads a lock, not a queue. Runtime capability bits moved intoBLELocalIdentityStateStorebeside the identity they ride announces with. - bleQueue owns the link buffers:
pendingPeripheralWrites,pendingNotifications,pendingWriteBuffersare bleQueue-confined (their producers and drains already ran there); the notification drain no longer invokes CoreBluetooth from a transport queue. - One serial engine queue: the concurrent message queue and the
collections queue it guarded state with are one serial domain; every
barrier flag and per-field ownership comment deleted; ~98 cross-queue
hops removed.
onEnginedocuments and debug-enforces the sync-edge order — and its trap caught two latent inversions during migration (the announce-rebind path and the noise session-generation closures). - Capability ports: gateway/bridge/courier wiring, the panic
lifecycle, and radio-state reads go through
MeshBridgingTransport,PanicResettingTransport, andBluetoothStateReporting; no app code casts toBLEServiceanymore. - Feature-owned state:
BLEMeshPingTracker(the /ping probe map and per-link response budget) andBLEPrivateMediaSessionStore(the six generation-keyed private-media maps plus the convergence-deferral set, as whole-transition methods under a leaf lock), both with direct unit tests. The private-media store also took the last routine main-actor sync reads off the engine and turned the noise-critical-section transitions into ordinary leaf-lock calls. Remaining feature state (courier, board, prekeys) already lives in injected stores. - Transport split: the mesh-only surface left the god-protocol.
Transportis core only (lifecycle, identity, snapshots, basic messaging, noise wrappers); files/private media, voice, courier, groups, board, diagnostics, verification, and the public archive are eight capability protocols discovered withas?, alongside the bridging/panic/radio-state ports. The inert-defaults extension is gone; consumers that relied on a default keep its safe floor explicitly at the call site. - Contract pinning:
BLEQueueContractTestsgreps the transport sources — onlyonEnginemay sync-enter the engine, transport code never sync-dispatches to main, and the collections queue stays deleted (waivable per line withqueue-contract-ok:plus a reason).
Full suite green throughout (1,964 tests), identical wall-clock — BLE throughput is nowhere near what one serial queue sustains.
Remaining roadmap (in order)
-
Link-layer extraction. Move the CB delegates, scheduling, duty cycle, and buffers behind
LinkEvent/LinkCommandports.Link-auth boundary (decided): bindings become engine-owned. Today
noiseAuthenticatedLinkOwners, the rebind containment rules, and the peer↔link binding maps live on bleQueue so that "check binding + auth, then act" is one critical section (the rebind path and the authenticated-send commit point innotifyOrEnqueueIfAccepted). That atomicity exists to stop a binding from changing between a security check and its action — and the engine's serial slot provides exactly the same guarantee once every rebind is an engine operation. The residual stolen-link risk is unchanged: directed payloads are Noise ciphertext, useless on a link that changed hands after the decision. Making bindings engine state also puts the receive path in its sans-I/O shape: the link layer reportsreceived(bytes, linkID)and the engine resolves the sender binding, instead of the CB delegate resolving peers before handoff. The link layer keeps only physical link state (CB objects, connect/subscribe lifecycles, backpressure buffers) keyed by opaque link IDs.Extraction order: (a) the binding-free radio half — scanning, advertising, duty cycle, connection budget/scheduling — moves first (it makes no peer decisions); (b) bindings + link-auth migrate to the engine, converting
readLinkStatecallers; (c) the delegates shrink to event emission and move behind the port. -
Sans-I/O engine core + simulator. Make the engine formally
handle(event) -> [Effect], feed it from aSimulatedLinkLayer, and move the multi-node E2E suite onto deterministic simulation (nowaitUntil, no timing hygiene battles). Property tests become possible: relay-storm bounds, partition-heal convergence, dedup soundness under duplicate floods. The remaining feature code moves (courier, board, prekey, voice, file, group handlers out of the packet switch) ride this seam as handler-registered modules instead of getting closure-environment extractions now.
What this is not
No wire changes: packet formats, signing (padding is signed), the peerID identity binding, and courier tag construction are untouched — see the wire-landmines notes before assuming any of that is local.