Skip to content

provider: local router, this Mac first then my Macs (L3, stacked on #1870) - #1876

Merged
jonathan308 merged 19 commits into
devfrom
local-first/l3-local-router
Nov 7, 2026
Merged

jonathan308 merged 19 commits into
devfrom
local-first/l3-local-router

Conversation

@jonathan308

@jonathan308 jonathan308 commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The local router (PR L3 of the local-first stack for provider 0.10.11): the local API of start --local, --local-endpoint and a pair's leader now routes the owner's requests like the iPhone app. This Mac answers first. When it can't take a request, the request goes on to the owner's other Macs with X-Darkbloom-Route: self ([local] route = "my-macs", free). With "my-macs-first" it goes on with prefer (the owner's Macs first, then the network, billed), and after any 402 from it (no balance, or the key's spend cap) once more with self, which never spends. Nothing leaves the Mac without a saved account key, with route = "this-mac", or with --no-auth. darkbloom route key [--stdin|--remove] keeps the account API key in the Keychain; a running local API reads it once, and again when route key changes it.

Stacked on #1870 (L0, local-first/l0-config, head f7c398b9f2, merged here). The base is dev as asked, so until #1870 merges this diff also shows L0's commits. L3's own commits:

  • first version: 34d05abbfd (red), 796ff312e9 (green), a00c0ddfc9 (an opt-in end-to-end suite);
  • refactor pass: 1a4c9b8955 (merges L0 2a2987cd5c), 0ea283557b;
  • the independent review's fixes: f1f3e03239 (merges L0 f7c398b9f2), c69eb99da9 (red), c9b5fcd008 (green), ff8b731f23 (end to end: my-macs-first through prefer), 853345f070 (docs: when a client that leaves is noticed);
  • the re-review's nits: 651f2e9251 (red), 22ebd6a822 (green);
  • the focused confirm: d76eb6177a (red), 2a424575d7 (green), b79a3c528f (connections per host, pinned by a live test).

Draft. Do not merge. No dev merges until the owner says so: a dev merge publishes a DevNet build.

Linked issue

None. This is part of the local-first goal (GOAL.md, D1 DESIGN-LOCAL-FIRST.md §3 and §6 L3, V0 SPIKE-V0.md findings F1–F4).

Test plan

This round, the focused confirm (review-L3.md, "Round 3": one small change needed). Xcode 27.2, DARKBLOOM_RELEASE_ENVIRONMENT=prod, nice -n 19, inside sandbox-exec with a profile that denies ~/.darkbloom*.

  • CPU only: every suite run here uses stub engines or stand-ins and loads no Metal kernel. The three Nemotron Super suites, which do, were skipped.
  • Isolation:
    • Key stores are in memory or a fake Keychain; no test touches the real Keychain.
    • The router tests' change notifications have names of their own (io.darkbloom.test.route-key-changed.<UUID>), never an install's.
    • Coordinators are stubs, or stand-ins on 127.0.0.1 with kernel-chosen ports.
  • Not done: no darkbloom CLI ran, no real Keychain item was touched, and no port 8000 or 47420–47423 was bound.

Results:

  • Red at d76eb6177a (the tests plus an unwired skeleton), swift test --skip-build --filter 'LocalRouter|RouteKey': 6 tests fail with 12 issues:

    • a signed build's read touching the switch, and the login-keychain read's switch (off for that read only);
    • a switch that can't be turned off stopping the data-protection read too;
    • the key read once (five passed-on requests and a model list read it 6 times at red, once at green), and again after the change notification;
    • a failed read tried again on the next request, and a kept key still used when the keychain locks later;
    • saving or removing announcing the change.

    Three checks pass on both sides by design: a switch already off is left off, saving and removing at a terminal may still ask, and --no-auth reads no key.

  • Green at 2a424575d7 (60 tests in 6 suites and 13 in 2), and at b79a3c528f with the two connection tests: 62 tests in 6 suites and 13 in 2 suites. All pass except 8 opt-in ones, which skip: 7 end-to-end and the Keychain round trip. The two new router tests and the store suite passed 5 runs in a row: the notification arrives within milliseconds, and the tests wait up to 2 s.

  • Live disconnect (code unchanged): cut 0.20 s after a client left mid-stream, and 0.21 ms after a reset while nothing flowed.

  • Connections per host (b79a3c528f, the first review's nit 6):

    • The live test: ten concurrent streamed requests go through the product's URLSession client to a plain-HTTP (HTTP/1.1) stand-in on loopback, whose every stream stays open until all ten have arrived. All ten are answered, in about 30 ms, and the test passed 5 runs in a row.
    • The configuration test: at least 32 connections per host, and nothing kept (cookies, cache, credentials).
    • Mutation check (not committed): with the setting removed, so URLSession's default of 6 applies, both tests fail. The live one fails with Darkbloom did not answer the connection in time after its 3 s connect watchdog, as the review described.
  • Regressions: 195 tests in 28 core suites and 70 in 13 CLI suites pass (197 + 70 at b79a3c528f), with the last round's filter and --skip NemotronSuper. CLIDispatchTests was left out: it runs this build's darkbloom binary.

  • Checks at 2a424575d7 and b79a3c528f: changelog.py check (21 fragments), docs-check.sh (208 files), docs-impact-check.py against origin/dev (37 files) and f7c398b9f2 (32 files), and git diff --check pass.

  • Overhead benchmark (LocalRouterOverheadTests), owner requirement "does not add much overhead". This Mac's path is unchanged.

    • Setup: the same streamed chat through the same stub engine, once through the endpoint without a router and once through the endpoint with one (a key saved, so the router is fully on). Interleaved, 50 warm-up rounds, n=3000, at a load average of about 23. The bench also asserts that this Mac's path reads the key store zero times.
    Path Metric p50 without → with (added) p99 without → with (added)
    in process (the router's own cost) first byte 90.9 → 92.5 µs (+1.6 µs) 126.8 → 128.2 µs (+1.4 µs)
    in process response head 72.8 → 75.7 µs (+2.9 µs) 116.5 → 119.5 µs (+3.0 µs)
    in process whole response 114.8 → 116.7 µs (+1.9 µs) 153.2 → 152.9 µs (−0.2 µs)
    loopback socket (what a client sees) first byte 430.6 → 431.5 µs (+0.8 µs) 683.9 → 692.4 µs (+8.5 µs)
    loopback socket response head 419.2 → 428.1 µs (+8.9 µs) 673.5 → 679.8 µs (+6.3 µs)
    loopback socket whole response 584.0 → 589.4 µs (+5.4 µs) 864.6 → 876.2 µs (+11.6 µs)
    • What I count as negligible: under 0.5 ms added at p50 to the first byte. The test asserts that bound in process, and 1 ms over loopback.
    • On the fallback path (new): after the first, a passed-on request or a model list no longer reads the Keychain, which the review measured at 1–3 ms of XPC. A signed build never touches the switch or its lock.
  • End to end against a real coordinator on loopback (LocalRouterCoordinatorE2ETests): run at 03:59Z against a copy of the V0 harness (darkbloom-platform 90ee29fc0d, development mode, memory store) on 127.0.0.1:<ephemeral>, with the last round's seeding and capped keys. 7 of 7 pass, the same as the last round. Every harness process was then stopped. Its secrets, binaries and Privy stand-in key were deleted: a first rm missed the secrets (a zsh glob without matches aborted it), and they were deleted a minute later.

  • Keychain round trip (DARKBLOOM_TEST_KEYCHAIN=1): still V1/V2 (a Terminal in a GUI session). New for V1/V2:

    • with a local API running, darkbloom route key (a save, or --remove) should make its next passed-on request read the key again;
    • after replacing the ad-hoc build, a pass-on should show no dialog, log one line and keep requests on this Mac;
    • a signed build should never touch the switch.
  • CI on b79a3c528f: every provider and cluster job passes on the first run, the three non-blocking GPU shards included. The two Vercel failures (d-inference, d-inference-console-ui-dev) also fail on dev. At 2a424575d7, Provider Unit Tests shard 1 had failed in an XCTest that L3 doesn't touch: MiMoV26EncodedAudiovisualIngressTests.testAFailedAudioReaderPassIsReadAgainAndReported reported video_reader_failed where audio_reader_failed was expected. It passed here.

  • Dev-identity build.

Earlier rounds:

  • The re-review's nits (651f2e9251, 22ebd6a822): red 7 tests fail with 22 issues, green 57 + 13, regressions 190 + 70, end to end 7 of 7 (two capped keys added), overhead +2.2 µs p50 to the first byte in process. CI was green on the first run.
  • The review's fixes (f1f3e03239 to 853345f070): red at c69eb99da9 (15 tests fail with 57 issues), green 47 + 10, regressions 181 + 52, end to end 5 of 5, overhead +1.2 µs p50 to the first byte in process. CI was green at 853345f070 after one re-run (a hung artifact download).
  • First version: red at 34d05abbfd (34 tests fail with 213 issues), green at 796ff312e9 (31 tests in 4 suites and 9 in 1), end to end 4 of 4 at a00c0ddfc9. That round's regression run included the three Nemotron Super suites, which need Metal kernels, so it was most likely not CPU-only (the refactor pass's note 3).
  • Refactor pass at 0ea283557b: see "Refactor Pass".

Components touched

  • provider-swift (Swift CLI)
  • native runtime / MLX
  • landing (Next.js)
  • enclave (Swift)
  • CI / provider release
  • docs

Protocol / interface changes

  • No protocol/interface changes

  • Yes, all on the provider's own local HTTP API and CLI; no coordinator, WebSocket or release change:

    • new response headers X-Darkbloom-Served-By and X-Darkbloom-Route-Used;
    • the local /v1/models gains owned_by: this-mac|my-macs|darkbloom, max_output_length and upstream entries, each model once;
    • a new CLI command, darkbloom route key;
    • a new Keychain item, <keychainServicePrefix>.route / account-api-key.

    The router only calls coordinator routes that already exist: POST /v1/chat/completions|completions|responses, GET /v1/models, GET /v1/models/{id} and GET /v1/models/catalog.

Documentation impact

  • Canonical documentation updated:
    • docs/provider/direct-mode.md:
      • the section "When this Mac can't take a request: the local router". The review round added my-macs-first's order and why it doesn't wait on a busy Mac, --no-auth, aliases, a client that leaves, all of the router's own answers, [local] route read at start, and the ws:// note. The re-review round added the 402 wording by error.type, when my-macs-first does queue, and that reading the key never asks. This round adds that the key is read once and read again when route key changes it, and that only the login-keychain read touches the switch;
      • the --no-auth row, the routes table and the stack;
    • docs/reference/configuration.md: [local] route;
    • docs/provider/cli-reference.md: darkbloom route and route key, including what it says under --no-auth, ^C at the hidden prompt, and the change notification it posts;
    • docs/provider/self-route.md: "From a Mac that runs Darkbloom", with both 402 types.
  • No documentation needed. Reason:

Changelog

  • Added changelog.d/local-router.md (updated: my-macs-first with the spend cap, --no-auth, aliases, a client that disconnects, reading the key once and without a dialog, ^C at the hidden prompt, and owned_by: "local" → "this-mac") and ran make changelog-check (scripts/changelog.py check).
  • No user-visible change, or an explicitly authorized release/history change.

Notes for reviewers

Router API for L4 and the integrations (D2a/D2b)

These names are unchanged:

  • LocalRouterConfig.host(local:coordinatorURL:takesCoordinatorWork:), effectiveRoute() and LocalInferenceHTTPConfig(router:);
  • KeychainLocalRouterAccountKeyStore and RouteKeyFlow (save/remove/routeLines);
  • the owned_by values and the headers.

What the last three rounds added or changed is marked new or changed.

Need API
Turn the router on in a host LocalInferenceHTTPConfig(host:port:authToken:router:) with router: LocalRouterConfig.host(local: config.local, coordinatorURL:, takesCoordinatorWork:). Wired already: --local (takesCoordinatorWork: false), --local-endpoint (true), --distributed (!noCoordinator). With router: nil the endpoint behaves exactly as before.
Upstream URL LocalRouterPolicy.upstreamBaseURL(coordinatorURL:): ws://h:8080/ws/provider → http://h:8080, wss → https, the build's coordinator otherwise
Route in effect LocalRouterConfig.effectiveRoute(). It is [local] route via L0's resolvedRoute(accountKeySaved:), except that nothing leaves the Mac without a saved key, or (new) without a local key. New: LocalRouterConfig.localKeyRequired (default true); makeLocalInferenceApplication turns it off when authToken is nil or empty. Changed: the key is read once and kept in memory, and read again after route key changes it (a Darwin notification), so route key still needs no restart. [local] route is read at start.
Hops (changed) LocalRouterPolicy.hops(for:): none for this-mac, [.mine] for my-macs, [.prefer] for my-macs-first (was [.mine, .prefer]). New: asksYourMacs(afterNetworkStatus:) (402) and yourMacsCouldNotTakeIt(status:) (409, 429, 503). They replace triesNextHop(after:), which nothing outside L3 used. New, internal: networkRefusalPrefix(errorType:), the words for a 402 that stands.
Account key LocalRouterAccountKeyStore (load/save/remove): KeychainLocalRouterAccountKeyStore (service <prefix>.route, account account-api-key) and InMemoryLocalRouterAccountKeyStore for tests. Internal: KeychainItemCalls, the four SecItem calls and (new) the legacy keychain's interaction switch, behind init(service:account:calls:), so tests can use a fake. Changed: load() never asks the user (Decisions), wherever it is called. L4's Start.accountKeySaved() then answers false for a key this build may not read yet. New: KeychainLocalRouterAccountKeyStore.changeNotification (<prefix>.route-key-changed). save and remove post it wherever they are called, L4's start-screen key prompt included. LocalRouterAccountKeyFormat.refusal(_:) holds the rules route key checks. L4's start-screen key prompt can call RouteKeyFlow (save/remove/routeLines) in darkbloom.
Status strings RouteKeyFlow.routeLines(savedRoute:keySaved:), in the iPhone app's words, with no speeds. New: RouteKeyFlow.liveEndpointHasNoLocalKey. route key sets it from LocalEndpoint.readLiveInfo(), and then says that the running API keeps every request on this Mac.
Upstream transport (changed) New: LocalRouterUpstreamResponse.cancel, an init parameter with default {}. The relay calls it when the client leaves. The URLSession transport cancels its task there; a custom LocalRouterTransport should stop its request. Internal: URLSessionLocalRouterTransport.sessionConfiguration(), the session's configuration (64 connections per host), which a test reads.
Integration contract GET <base>/v1/models with the local key. Each entry has id, object, created, owned_by (this-mac | my-macs | darkbloom), and when known name, context_length (also as max_model_len) and max_output_length. Order: this Mac, your Macs, the network. Changed: each model once. An upstream entry that is a public alias of a build this Mac lists is dropped, and a request naming that alias is answered by this Mac under the build's id. Upstream ids are the coordinator's alias ids, passed through unchanged. Limits come from this Mac's engine (resident slots; a pair's profile), else the Darkbloom catalog (by id, or the alias's desired build). Changed: the upstream lists wait at most 3 s (was 5 s), inside D2a's 5 s fetch. Tools send one URL and the local key; any X-Darkbloom-Route they send is dropped.
Timing (new) LocalRouter.Timing.ownedCountTTL (5 s): how long the coordinator's count of the owner's Macs serving a model is reused. A failed read isn't kept.
Hidden prompt (changed) RouteKeyFlow.readHidden(prompt:) is unchanged for callers. It now gives the terminal its echo back on ^C, ^\, a hang-up or kill, then ends as the signal would (HiddenReadSignals). Internal: readHidden(prompt:terminal:onSignal:).
max_tokens Every local API reads a chat request's max_completion_tokens as max_tokens when max_tokens is absent (LocalChatRequest). OpenCode's compatibility.maxTokensField is then optional; passed-on bodies go unchanged.
Response headers X-Darkbloom-Served-By: this-mac or darkbloom; X-Darkbloom-Route-Used: self or prefer on upstream answers. New: the router's own 413 says Served-By: this-mac, and its 502s say Route-Used. No Mac's identity: the coordinator's X-Provider-Id is not relayed.

Merging this head into L4.

  • L4 (fa673b9082) and D2b (1d78fa7474) have merged 853345f070.
  • A trial git merge-tree of b79a3c528f into each shows no conflict. Nothing in L4 names LocalRouterKeyReads, which this round renamed LocalRouterKeyCache (internal).
  • One behaviour to know there: Start.accountKeySaved() now answers false for a key this build may not read without asking (above).

Decisions to check

  • The focused confirm (review-L3.md, "Round 3", of 22ebd6a822) asked for one change and recommended a second. Both are here:

    1. The switch, and its lock, only around the login-keychain read:
      • Before: every read flipped the process-wide SecKeychainSetUserInteractionAllowed switch under a process-wide lock, in every build.
      • Now: only the login-keychain attempt (the ad-hoc fallback after errSecMissingEntitlement) runs with the switch off.
      • Signed builds read the data-protection Keychain only, with the LAContext that may not ask. They never read or set the switch, or take its lock.
    2. The key is read once and kept in memory (LocalRouterKeyCache), so a passed-on request or a model list no longer reads the Keychain each time:
      • When it is read again: KeychainLocalRouterAccountKeyStore.save and remove post a Darwin notification scoped to the identity (changeNotification, <keychain prefix>.route-key-changed, with notify_post), so darkbloom route key announces every change. At its first read the router registers for it with notify_register_dispatch, and drops its copy when it arrives. The next request reads the key again. A read that a change overtook isn't kept.
      • A failed read isn't kept: the next request tries again, and a run of failures is still said once. A key read and kept stays in use when the keychain locks later, until it changes.
      • Only while watched: a copy is kept only while the notification is registered. A store that posts none (an in-memory one), or a registration that fails, reads on every request, as before.
      • What it costs: one Keychain read per router life, plus one after each change. On ad-hoc builds, the switch is flipped only then.
    3. Asked for alongside: the first review's nit 6, pinned. The session has allowed 64 connections per host since c9b5fcd008, but nothing tested it. A configuration test and a live HTTP/1.1 test with ten concurrent streams now do (Test plan). HTTP/2 to the real coordinator multiplexes anyway.
  • The re-review (review-L3.md, "Re-review", of 853345f070) approved with nits. This round takes all five, and the optional sixth:

    1. The 402 wording:
      • The retry stays on every 402 from prefer. self never spends: it skips both the reservation and the key's spend cap (admission.go), so the retry helps with a cap too.
      • The words follow the coordinator's error.type:
        • insufficient_funds keeps No balance for the network fallback: none of your Macs could take this request, and the Darkbloom network needs a positive balance. Darkbloom said: …;
        • any other type (the key's spend cap, insufficient_quota; a promotion's limit) reads Network fallback refused: none of your Macs could take this request, and Darkbloom would not send it to the network. Darkbloom said: …, followed by Darkbloom's own reason.
      • Also changed: the router's log line names the reason, and the comments and docs follow.
    2. When my-macs-first waits, said plainly: it doesn't wait on a busy Mac of yours while another Mac, yours or the network's, can take the request now. When none can, the coordinator queues prefer too: up to 120 s, then 429 machine_busy, and kept while you have a Mac serving the model (registry/queue.go:506-545 at 90ee).
    3. A Keychain read never waits on a dialog:
      • Data-protection items: the query carries an LAContext with interactionNotAllowed, the current form of kSecUseAuthenticationUIFail (which is deprecated).
      • Legacy items (the login keychain, where unsigned and ad-hoc builds keep the key): they ignore the query's UI keys (SecItem.h: "Legacy keychain items will still activate UI if needed"; Apple's SecItemCopyMatching_osx never reads them). So the login-keychain read turns the process-wide SecKeychainSetUserInteractionAllowed switch off and puts it back after (narrowed in the focused confirm: signed builds never touch it). The switch is deprecated (two compiler warnings), but no other API covers these items.
      • How: one login-keychain read at a time, under a lock. A switch that can't be read or turned off means no login-keychain read.
      • Saving and removing (route key, at a terminal) may still ask: approving a new build there is how it reads the key again.
      • When the key can't be read: effectiveRoute() no longer swallows the error. It logs one line per run of failures, with the OSStatus and the fix and never the key, then serves this Mac only.
    4. ^C at route key's hidden prompt (also ^\, a hang-up or kill) gives the terminal its echo back first, then ends the command as the signal would. The signals are ignored and watched with dispatch sources, as DistributedStartSignals does, and put back exactly. A signal the command already ignores stays ignored.
    5. The --no-auth test asserts zero key-store reads.
    6. Optional, taken: the coordinator's count of your Macs serving a model is reused for 5 s, so a burst of passed-on requests reads it once. A failed read isn't kept, so the fail-closed answer lasts one request.

    Left out, as asked: a pair's takesCoordinatorWork following its decided serving scope goes to cluster: Both, me first for a pair in darkbloom cluster (local-first L5b-cli) #1884 (the pair screens).

  • The independent review (review-L3.md, of 0ea283557b) asked for changes: three findings and a design question. This round takes all four.

    1. A client that leaves stops the upstream request (finding 1):
      • The cause: UpstreamTaskHandler kept its own copy of the body stream, so the stream never ended when the relay stopped reading it.
      • The fix: the handler hands the stream out once and keeps only the continuation, so the relay letting go of the stream cancels the request. In the reviewer's probe, this alone cut the upstream 0.21 s after the consumer left, where it had run 6.25 s to the end.
      • Even while no chunk flows: relay() also registers the answer's cancel with the request's disconnect scope, as this Mac's own streams do. It calls cancel when the body didn't end normally.
      • Limit: Hummingbird allows input half-close, so a client's normal close (a FIN) is noticed only when a chunk can't be delivered. Mid-stream, that is within a chunk or two (0.20 s in the live test); during a long prompt, at its first token. A reset is noticed at once. This Mac's own streams have the same limit.
    2. No upstream hop without local auth (finding 2):
      • The rule: without a local key (--no-auth), the router serves this Mac only. It never reads the account key and never dials the coordinator, and /v1/models lists this Mac only.
      • Where it is said: the router logs at start, on every host, pairs included: local router: no local key (--no-auth): requests stay on this Mac, and the account key is never used. The --local and --local-endpoint banners, darkbloom local, route key and the docs say it too.
      • There is no opt-in to lend the key without local auth.
    3. Aliases (finding 3). A public alias of a build this Mac lists counts as that build:
      • /v1/models lists the model once, as this-mac. Upstream my-macs or darkbloom entries for the alias are dropped (the catalog's aliasBuilds).
      • A request naming the alias gets this Mac's 404 first. With a route that dials out, the router then asks this Mac once more under the build's id (the body's model rewritten), before anything is passed on.
      • If this Mac still can't take it, the original request is passed on, and a self hop for it still never comes back here.
    4. my-macs-first sends prefer first (the design question):
      • Why: the coordinator orders the owner's Macs first, then the network, among the Macs that can take the request now. A busy Mac of the owner's doesn't hold the request while another Mac can take it (when none can, see the re-review's point 2).
      • The 402 retry: prefer reserves the price up front even when an owned Mac answers (F1; it charges nothing then), so its 402 asks self, once, free. The re-review widened the words to every 402 (above).
      • What comes back: if self then answers 409, 429 or 503, prefer's 402 stands. Any other self answer is relayed, with Route-Used: self. Any other prefer answer is relayed, as for my-macs.
      • A self-route-only key: the coordinator treats prefer as self, waits included. routeLines already says that such a key answers only from the owner's Macs.
    • Nits taken:

      • a fake behind the SecItem calls (2);
      • a counting key store in the bench (5);
      • 64 connections per host, for an HTTP/1.1 coordinator (6), pinned by tests in the focused-confirm round;
      • a 3 s deadline for the upstream lists (7);
      • Served-By and Route-Used on the router's own errors (9);
      • the docs gaps: --no-auth, the my-macs-first wait, 502 darkbloom_error_unreadable and the router's own 413, [local] route read at start, owned_by: "local" → "this-mac", and the ws:// note.

      L0's comment on Route.myMacsFirst follows the new order.

    • Nits not taken then:

      • kSecUseAuthenticationUIFail and a log line for an unreadable key (1), a short cache for the self-view count (3), and restoring the terminal on ^C at the hidden prompt (8): all taken in the re-review round (above);
      • a pair's takesCoordinatorWork following the decided scope (4): goes to cluster: Both, me first for a pair in darkbloom cluster (local-first L5b-cli) #1884;
      • the refactor's notes on the connect watchdog (10): agreed benign.
  • The four V0 findings:

    • F1, prefer 402s at a zero balance: my-macs-first asks self after any 402 from prefer (above). When that 402 stands, it keeps its status, type, code and Retry-After. Its message starts with No balance for the network fallback: … for insufficient_funds, and with Network fallback refused: … for any other type, followed by Darkbloom's own message. This is the one rewritten body. Every other refusal is verbatim.
    • F2, the self list has no limits: filled from this Mac's engine or the catalog (above).
    • F3, a self request to this Mac while it's paused waits 120 s:
      • The limit: the coordinator API can't leave one Mac out of a self request.
      • The check: on a Mac that takes coordinator work (--local-endpoint, or a pair through Darkbloom) and serves the requested model (or a build of the alias it names, from the catalog), the router reads the coordinator's self view of that one model (GET /v1/models/<id>, which still counts a paused Mac).
      • With fewer than 2 owned Macs serving it: my-macs returns this Mac's status with code this_mac_only and a plain message. my-macs-first answers prefer's 402 without the self retry. A failed check counts as 0 (fail closed).
      • No check needed: --local and cluster local never take coordinator work, so a self request can't reach them.
      • Waits that remain: with my-macs, self to other busy Macs keeps the coordinator's own 120 s queue and 429 machine_busy. The router allows 10 s to put a request on the wire (watchdog on bytes sent), then 5 minutes without a byte, and no cap on a stream.
    • F4, max_completion_tokens: above.
  • Placement: the router sits after the local key check (a bad local key never reaches it) and outside CORS (this Mac's engine errors arrive as statuses).

    • What passes a request on: only this Mac's 404, 429 or 503, before any byte.
    • What never does: 400, 401, 413, 422, 499, other 5xx, and anything after the first byte.
  • Low overhead (owner criterion 8):

    • This Mac's path: in process. The body is collected once and handed down as the same buffer (the engine collects it anyway), and the router never parses it. Nothing is read from the Keychain (now asserted in the bench), and the engine's Response (SSE or JSON) is returned as it is, with one header set. No body re-wrapping, copy or buffering.
    • The upstream client: one ephemeral URLSession, made by the first request that needs the coordinator.
    • /v1/models: the upstream lists are cached 30 s, the catalog 5 min and failures 10 s, with one read in flight per key. With this-mac or without a local key, the list never leaves the Mac.
  • Upstream 401/403: these become 502 account_key_refused ("Save a new one with darkbloom route key"), so a tool never mistakes them for its own local key being wrong. An unreachable coordinator is 502 darkbloom_unreachable, with a plain reason and no URL.

  • Account key secrecy:

    • It is never in argv: hidden prompt or --stdin.
    • It is never in output, logs, provider.toml, local.json or a response. Upstream error bodies are redacted, and tests scan responses, headers, log lines and files.
    • Redirects are never followed, so the key reaches only the configured coordinator.
  • Key storage:

    • Signed builds: the data-protection Keychain (app access group), so the CLI and the LaunchAgent share it without a prompt.
    • Builds without the entitlement (local, ad-hoc): the login keychain, as the App Attest shadow key does. Only errSecMissingEntitlement falls back (now tested with the fake).
    • A daemon that can't read it (a locked keychain, or a new build the item doesn't trust yet): no dialog, one log line, this Mac only.
  • route key checks the key once, with GET /v1/models + self:

    • 401/403 saves nothing and exits 1;
    • an unreachable coordinator saves it with a note;
    • its own local key (dk-local-…) and malformed input are refused before any check.
  • Behaviour change on every host that configures a router (all three production paths): /v1/models entries say owned_by: "this-mac" instead of "local", and a chat request's max_completion_tokens is now honoured.

Limitations

  • Not run on real Macs here, by the rules for Mac A: no darkbloom CLI and no real Keychain. V1/V2 on pair-2 with a staging build cover:
    • route key and the LaunchAgent's Keychain read;
    • real self and prefer hops;
    • a client leaving mid-stream, and --no-auth with a saved key;
    • /v1/models on a Mac serving a catalog model that has an alias (the V0 stub model has none).
  • A client's normal close is noticed at the next chunk, not at once (Decisions: the independent review, 1).
  • Aliases are resolved only with a route that dials out, because the catalog is a coordinator read. With this-mac or without a key, a request naming an alias gets this Mac's 404, as before, and /v1/models lists no alias then.
  • The alias retry's body is re-serialized with JSONSerialization, so key order and number formatting may change. That happens only on that retry, never on this Mac's path or a pass-on.
  • A pair's takesCoordinatorWork is fixed at start (!noCoordinator, review nit 4). When the coordinator refuses the member role and the pair serves locally only, the router still reads the self view. With exactly one other Mac serving the model, it can then answer a false this_mac_only; it fails closed. This goes to cluster: Both, me first for a pair in darkbloom cluster (local-first L5b-cli) #1884 (the pair screens).
  • The legacy keychain's switch is process-wide (unsigned and ad-hoc builds only):
    • for the moment of a login-keychain read, another legacy-keychain read in the same process (the App Attest shadow key, for one) would fail instead of asking;
    • that read happens once per router life, after each change, and, after a failed read, on the next request;
    • the switch is put back right after, and those reads are serialized.
  • The kept key changes only through route key. A key changed or deleted another way (Keychain Access, security) is noticed after the next route key, or a restart. A request that arrives within milliseconds of route key can still use the old key.
  • The count of your Macs is reused for 5 s. For up to 5 s after another Mac of yours goes offline, a self hop can still be sent, and may wait at the coordinator. A Mac that comes online can be missed for up to 5 s (this_mac_only).
  • The F3 check is per model: a Mac whose model isn't listed in the catalog's aliases is matched by exact id only.
  • Routed paths: chat completions, completions and responses. /v1/messages, embeddings, batches and stored responses stay this Mac's.

Before And After

flowchart LR
  subgraph Before
    C1[tool: local URL + local key] --> A1[auth] --> E1[CORS → engine]
    E1 -->|model not here / busy| X1[404 / 429 / 503 to the tool]
    M1["GET /v1/models"] --> L1["engine list: owned_by local, context only for Qwen4"]
  end
  subgraph After
    C2[tool: local URL + local key] --> A2[auth] --> R2{local router}
    R2 -->|in process, response as is| E2[CORS → engine]
    E2 -->|200 or client error| T2["to the tool + Served-By: this-mac"]
    E2 -->|404 / 429 / 503 before any byte| H2{"route, account key (read once without a dialog; again after route key), local key"}
    H2 -->|"this-mac, no account key, or no local key"| T2
    H2 -->|"404 for an alias of a build here: again, under the build's id"| E2
    H2 -->|my-macs| S2["coordinator, X-Darkbloom-Route: self"]
    H2 -->|my-macs-first| P2["coordinator, X-Darkbloom-Route: prefer"]
    P2 -->|"402: no balance or a spend cap (once)"| S2
    S2 -->|answer| U2["streamed through + Served-By: darkbloom, Route-Used"]
    P2 -->|answer| U2
    U2 -->|client leaves| K2[upstream request cancelled]
    M2["GET /v1/models"] --> L2["this-mac ∪ my-macs (∪ darkbloom), each model once, limits from engine or catalog; cached"]
  end
Loading
flowchart TD
  subgraph "Pass-on decision (LocalRouter.route / passOn)"
    a[POST chat / completions / responses] --> b[collect body once; same buffer handed down]
    b --> c[inner.respond: this Mac's engine]
    c -->|status not 404/429/503| d[return engine response as is + 1 header]
    c -->|404/429/503| e["effectiveRoute: local key required, route, account key (kept copy, else one Keychain read)"]
    e -->|"no local key, no readable account key, or this-mac"| d
    e -->|404| al{"alias of a build this Mac serves? (catalog)"}
    al -->|yes| c2["inner.respond again, model = build id"]
    c2 -->|status not 404/429/503| d
    c2 -->|404/429/503| r{route}
    al -->|no| r
    e -->|429/503| r
    r -->|my-macs| f{"self hop could land on this Mac? takesCoordinatorWork ∧ serves model or alias build"}
    f -->|yes| g["GET /v1/models/id with self: provider_count (reused 5 s)"]
    g -->|< 2| h["this_mac_only (this Mac's status)"]
    g -->|≥ 2| i[POST self]
    f -->|no| i
    r -->|my-macs-first| p[POST prefer]
    p -->|402| f2{"same check: could self only land here?"}
    f2 -->|yes| n["prefer's 402, prefixed by its error.type: no balance, or Darkbloom's own reason"]
    f2 -->|no| i2["POST self, once"]
    i2 -->|409/429/503| n
    i -->|2xx| j["relay chunk by chunk; client leaves → cancel upstream"]
    p -->|2xx| j
    i2 -->|2xx| j
    i -->|non-2xx| l["relay verbatim (key redacted; 401/403 → 502)"]
    p -->|other non-2xx| l
    i2 -->|other non-2xx| l
  end
Loading

Refactor Pass

Done at 0ea283557b, by a separate refactor pass before the independent review (refactor-L3.md). It made one behaviour-preserving commit (8 files, +95/−103):

  • this Mac's answer is labelled once;
  • one builder for the coordinator's model reads (modelsRequest);
  • the three owned_by values are named together (LocalRouterPolicy.myMacs);
  • LocalRouterRequestBody is folded into the router;
  • RouteKeyFlow.save switches once;
  • comments state the four invariants;
  • the tests share one endpoint builder.

Its evidence: the same passing test lines before and after (41 router, 233 regression), end to end 4 of 4, and overhead equal within noise.

The three rounds since: the independent review's fixes, the re-review's nits and the focused confirm's change came after the pass and keep its structure. No separate refactor pass ran on them; the orchestrator owns that gate.

jonathan308 and others added 5 commits November 6, 2026 14:12
Tests first for the local-first settings section, with a skeleton that
compiles but is not wired: [local] is never decoded or validated and the
writer changes nothing.

- an absent [local] keeps today's mode, port, bind and route;
- every key round-trips with the documented spelling;
- invalid values are refused with one plain line naming the key;
- the [local] edit keeps unknown keys and every other value, is a no-op
  when the file already says it, and refuses before writing.

Red (prod, CPU-only, sandboxed): 11 of 15 core tests and both CLI tests
fail (49 issues).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
LocalSettings {mode, meFirst, meFirstIdleMinutes, route, port, bind} in
provider.toml's new [local] section:

- Parse: every key optional; ProviderConfig.local is nil while the
  section is absent, so other writers never add it.
- Validate: enums, me_first_idle_minutes 1-120, port 1-65535, bind as
  `cluster local` takes it. A refusal is one plain line naming the key,
  what it takes and what the file has (LocalSettingsError), never a
  decoder dump. Integers are narrowed here: TOMLKit traps on its own.
- Defaults when absent: the launch flags decide the mode as today; port is
  the build's defaultLocalPort, bind 127.0.0.1, route this-mac (my-macs
  once an account key is saved), me first on only for mode both, and the
  owner's 2-minute idle before Darkbloom traffic resumes.
- Write: ConfigManager.updateLocal / setLocalSettings edit the raw TOML
  table under the config lock, like the cluster pointer and model
  selection writers, so unknown keys keep their values. Shaped like
  setIdleUnloadMinutes: refuse before writing, no-op when the file holds
  the change, pin explicit defaults.

Green (prod, CPU-only, sandboxed): LocalSettingsTests 15/15,
LocalSettingsMutationTests 2/2; config regression suites 128 + 33 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per test case

Same behaviour. The public API is unchanged: LocalSettings, its fields and
enums, the resolvers, validate(), LocalSettingsError, ConfigManager.updateLocal
and setLocalSettings.

- ConfigManager.updatingLocal says why the section edit is safe:
  - `local` is a section or absent, because parseValidating refused anything
    else and the encoder writes one;
  - an existing section is edited in place, because TOMLKit hands out the
    table's own node;
  - a new section always gets a key, because `after` differs from an empty
    `before`.
- LocalSettings.CodingKeys drops CaseIterable. Nothing iterates the keys, and
  [local] takes unknown keys on purpose. Elsewhere in Config/, CaseIterable
  CodingKeys feed key checks (exact fields, retired keys).
- LocalSettingsTests.validateMatchesDecoding calls validate() once per case
  and checks the words on the refusal that #expect(throws:) returns. Before,
  a second call in a do/catch checked the words only when something was
  thrown. A mutant validate() (no port check; bind found unquoted) fails the
  test on the same two cases, before and after.

Checks, all CPU only (empty kernel libraries in the test build, no command
buffer submitted), on Xcode 27.2 at nice 19 with ~/.darkbloom* denied:
- LocalSettingsTests 15/15 and LocalSettingsMutationTests 2/2: dev identity
  before and after, and prod identity after.
- The PR's config regression filter: prod 128 + 33 pass. Dev 128 + 33, with
  the same 3 issues before and after, all in ClusterPrefixCacheSettingsTests,
  which hard-codes prod's cache paths. They are pre-existing, and CI tests
  prod only.
- docs-check, docs-impact-check --base origin/dev and changelog check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests first for the local router, with an unwired skeleton: the router
types, the account key store, `darkbloom route key` and the host wiring
compile, but the responder passes every request through, the policy
returns nothing, the key store and the CLI flow do nothing, and the
upstream client throws.

- each fallback trigger (this Mac's 404, 429, 503) makes exactly one
  upstream call with `X-Darkbloom-Route: self`, to the coordinator URL
  derived from `[coordinator] url`;
- 400, 401, an engine failure and anything after the first byte never go
  upstream; `this-mac` and a missing key never dial out;
- the coordinator's 503/409/429/402 bodies and Retry-After come back
  verbatim; the client's route header and key are dropped; the account
  key is in no response and no log line;
- `my-macs-first` tries `self` before `prefer`; a 402 on the network hop
  says the network fallback needs a balance;
- a `self` hop is skipped when this Mac is the only one of the owner's
  Macs serving the model; a chat request's `max_completion_tokens` is
  read as `max_tokens`; `/v1/models` merges with limits and survives an
  unreachable coordinator;
- SSE passes through chunk by chunk; the URLSession client streams,
  follows no redirect and fails plainly;
- a CPU benchmark of this Mac's path with and without the router.

Red (prod, CPU-only, sandboxed): 34 tests fail with 213 issues; the 7 that
pass are the key-store and flag-parsing checks, the 2 MiB refusal the
engine already makes, and the two overhead benchmarks (a pass-through
router costs nothing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The local API (standalone, unified and a pair's) now routes like the
iPhone app: this Mac first, then the coordinator with
`X-Darkbloom-Route: self` (`[local] route = "my-macs"`), and with
"my-macs-first" `self` then `prefer`. `darkbloom route key` keeps the
account API key in the Keychain.

- This Mac's path stays in process: the body is collected once (the
  engine collects it anyway) and never parsed by the router, nothing is
  read from the Keychain, and the engine's response is returned as it is
  with `X-Darkbloom-Served-By: this-mac`. The upstream client is made by
  the first request that needs the coordinator.
- Only this Mac's 404, 429 or 503 before any byte pass a request on. The
  original body goes upstream with the account key and the saved route;
  the client's key and route header never do. 2xx answers stream through
  chunk by chunk; refusals come back with their status, body and
  Retry-After, plus `X-Darkbloom-Route-Used`.
- `self` comes before `prefer` because `prefer` needs a funded account
  even when an owned Mac answers. A 402 on the network hop starts with
  "No balance for the network fallback"; a refused account key is a 502
  `account_key_refused`, an unreachable coordinator a 502.
- A `self` hop never comes back to this Mac: on a Mac that takes
  coordinator work and serves the model (or a build of the alias), the
  router asks the coordinator's `self` view of that model first and skips
  `self` when no other owned Mac serves it (`this_mac_only`, or straight
  to `prefer`).
- `/v1/models` merges this Mac's models (`this-mac`), the owner's
  (`my-macs`) and, with my-macs-first, the public list (`darkbloom`), with
  `context_length` and `max_output_length` from the engine or the
  catalog. Lists are cached 30 s, the catalog 5 min, failures 10 s.
- A chat request's `max_completion_tokens` is read as `max_tokens` on
  every local API (`LocalChatRequest`).
- The account key is never printed, logged, written to a file or put in
  a response; upstream error bodies are redacted.

Green (prod, CPU-only, sandboxed): the 40 router and `route key` tests
pass; 174 core and 53 CLI tests across the local API, distributed HTTP,
cluster API parity and start suites pass. Overhead on this Mac's path,
n=3000, in process: +1.2 us p50 / +5.2 us p99 to the first byte;
over loopback: +3.9 us p50, p99 within noise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Error Error Nov 7, 2026 4:24am UTC
d-inference-console-ui-dev Error Error Nov 7, 2026 4:24am UTC
d-inference-landing Ready Ready Preview Nov 7, 2026 4:24am UTC
darkbloom-status Ready Ready Preview Nov 7, 2026 4:24am UTC
eigen-homepages-darkbloom Ready Ready Preview Nov 7, 2026 4:24am UTC

Request Review

An opt-in end-to-end suite (DARKBLOOM_ROUTER_E2E_BASE and _KEYS) that
runs the router, with the stub engine as this Mac and the real URLSession
client, against the V0 harness: darkbloom-platform 90ee29fc0d in
development mode on 127.0.0.1:<ephemeral>, seeded through its own
routes, with the owner's other Mac as a stub provider.

Run once on Mac A, 23:17Z, then every harness process was stopped:
- /v1/models lists the owner's v0/stub-small-model as my-macs with
  context 32768 and output 8192 from the catalog (the self view has none);
- a chat this Mac doesn't serve goes through `self`, 200 from the
  owner's other Mac, Served-By darkbloom, Route-Used self;
- a consumer without a Mac gets the coordinator's 409 no_linked_machine
  verbatim;
- a zero-balance owner whose Mac is offline, with my-macs-first: `self`
  refused, `prefer` 402, which starts with "No balance for the network
  fallback";
- the real GET /v1/models/<id with a slash> self view counts one Mac,
  so a Mac that takes coordinator work answers this_mac_only, and one
  that doesn't passes the request on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 and others added 3 commits November 6, 2026 15:21
#1870's head moved 00f5afa -> 2a2987c: a comment on the [local]
section edit in ConfigManager.updatingLocal, the internal
LocalSettings.CodingKeys without CaseIterable, and one validate() per
case in LocalSettingsTests.validateMatchesDecoding. No public name or
signature changed and no router file is touched, so the merge is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the independent review of #1870; the public API is unchanged.

- Bug: clearing the last key of a file that holds only [local] threw a
  false "did not serialize" error, because the round-trip guard refused
  an empty text. An empty table now serializes to an empty file, which
  loads as defaults. Red first: clearingTheOnlySection failed with that
  error; it now passes.
- Route.myMacsFirst's comment: the coordinator with
  X-Darkbloom-Route: self first, then prefer, as the router does.
- Docs and comments say exactly what the writer keeps: every value,
  unknown keys included. Like every config writer, it drops comments and
  re-sorts sections and keys. Other writers drop unknown keys.

Tests (prod, CPU-only, sandboxed): LocalSettingsTests 16/16,
LocalSettingsMutationTests 2/2, config/idle/beta/model-switch suites
130 + 35 pass; changelog, docs and docs-impact checks pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the model reads

Behaviour-preserving cleanup of the local router (L3). No public name,
signature, header, owned_by value, status, message or test assertion
changes; LocalRouterPolicy.myMacs is the one addition.

- LocalRouter.route labels this Mac's answer (X-Darkbloom-Served-By:
  this-mac) once, then returns it unless it passes the request on; the
  two label-and-return branches go. passOn's unreachable tail returns
  this Mac's answer instead of a this_mac_only refusal for "this model".
- The coordinator's model reads (the owner's and the public lists, the
  keyless catalog, one model's self view) build their GET in one place,
  modelsRequest. /v1/models reads its two lists with two async lets
  instead of an indexed task group.
- LocalRouterPolicy.myMacs joins thisMac and darkbloom, so the three
  owned_by values of the integration contract are named together.
- LocalRouterRequestBody, one two-line function in its own file, moves
  next to its only caller as LocalRouter.model(in:).
- RouteKeyFlow.save switches once on the check, without the dead
  .refused branch; its unused `cli` property goes. The Keychain store
  passes its operation name as a string; StandaloneServerConfig sets
  `router` in declaration order.
- Comments state the invariants: the account key leaves its store only
  as the Authorization header to the configured coordinator (no
  redirects); this Mac's path collects the body once, within the
  engine's own ceilings, hands the same buffer down and reads no key; a
  `self` hop that could only come back to this Mac is not sent, and a
  count the coordinator can't give fails closed.
- Tests: RouterFixture.makeApp(router:engine:localModels:...) builds the
  endpoint for the fixture and the opt-in E2E suite alike.

CPU-only (empty kernel libraries), prod identity, sandboxed, before and
after on the merged head: the router and route key suites 35 + 9 pass,
the regression suites 175 + 61 pass, with identical test names. The
overhead benchmark (n=3000), this Mac's path, first byte: +1.2 us p50
in process and +1.6 us over loopback (before: +1.1 and +1.8), under
the asserted 0.5 ms and 1 ms. The opt-in suite against the V0
coordinator on 127.0.0.1:<ephemeral> passes 4 of 4, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 and others added 4 commits November 6, 2026 16:55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests first for the four fixes the independent review of #1876 asked
for, and for a fake behind the Keychain calls. The skeleton adds only
the names the tests use: an upstream answer's cancel, the config's
localKeyRequired, the my-macs-first retry rule, KeychainItemCalls and
RouteKeyFlow.liveEndpointHasNoLocalKey. None is wired yet.

- A client that leaves a passed-on stream ends it at the coordinator:
  live, with real sockets on 127.0.0.1 (the client, the local API over
  the product's URLSession client, a coordinator stand-in that notes
  when its connection closes), while events flow and while nothing
  flows.
- Without a local key (--no-auth) nothing is passed on: no Authorization
  and a foreign Origin get this Mac's answers, /v1/models lists this
  Mac only, the coordinator is never dialled, and the router and
  `route key` say so.
- An alias of a build this Mac serves is served here, listed once (as
  this-mac, not again as my-macs or darkbloom), and a self hop for it
  still never comes back here.
- my-macs-first asks prefer first: a busy Mac of the owner's never holds
  it in self's 120 s queue (one prefer call); only a 402 asks self, once.
- The Keychain store, behind a fake: the data-protection Keychain first,
  the login keychain only on errSecMissingEntitlement, the new item's
  attributes, update in place, an empty item reads as no key.

Red (prod, CPU-only, sandboxed): 15 tests fail with 57 issues, both live
ones included (the coordinator stand-in streamed to its end after the
client left). Two new ones pass on both sides: the empty-item read, and
no `self` that could only come back here after a 402.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The four fixes the independent review of #1876 asked for, a fake behind
the Keychain calls, and five of its nits.

- A client that leaves a passed-on stream stops it at the coordinator.
  The URLSession client hands its stream out once and keeps only the
  continuation, so letting go of it cancels the request; the relay also
  cancels when a chunk can't be written, and registers with the
  request's disconnect scope, so a closed connection cancels it even
  while nothing flows. The answer carries its own `cancel`. (A client
  that only half-closes is noticed at the next chunk, as for this Mac's
  own streams: the server allows half-close.) Live, on real sockets:
  cut 0.20 s after the client left mid-stream (5 of 60 events), and
  0.25 ms after a reset while nothing flowed; before, the stand-in
  streamed to its end.
- No upstream hop without the local key. makeLocalInferenceApplication
  sets LocalRouterConfig.localKeyRequired from the endpoint's own key;
  without one (--no-auth) effectiveRoute() is this Mac only and never
  reads the Keychain. The router logs it at start, and the start banner,
  `darkbloom local` and `route key` say so.
- A public alias of a build this Mac serves is that build: listed once,
  as this-mac (an upstream my-macs or darkbloom entry for the alias is
  dropped), and a 404 for the alias is answered here under the build's
  id before anything is passed on. A `self` hop for it still never comes
  back here.
- my-macs-first sends `prefer` first: the coordinator orders the owner's
  Macs, then the network, among the Macs that can take the request now,
  so a busy owned Mac never holds it in `self`'s 120 s queue. Only a 402
  (no balance) asks `self`, once; if the owner's Macs can't take it
  either (409, 429, 503), the 402 stands, saying the network fallback
  needs a balance. my-macs is unchanged.
- KeychainItemCalls puts the four SecItem calls behind a seam; CI covers
  the data-protection-then-login rule (only errSecMissingEntitlement
  falls back), the new item's attributes, update in place and the empty
  item.
- Nits: the model-list deadline is 3 s (an integration's own read is
  5 s); 64 connections per host for an HTTP/1.1 test coordinator; the
  router's own 413 and 502s say Served-By or Route-Used; the overhead
  bench asserts this Mac's path reads no key; L0's comment on
  `my-macs-first` and the docs follow the new order.
- Docs: --no-auth, the alias rule, the client that leaves, the
  my-macs-first order and wait, the router's own answers (413,
  darkbloom_error_unreadable), `[local] route` read at start, a ws://
  coordinator sends the key without TLS, owned_by local -> this-mac.

The live disconnect stand-in now answers the router's catalog read
with a 404 and streams only the chat request.

Green (prod, CPU-only, sandboxed): the router, disconnect, account-key
and route key suites pass (46 tests in 6 suites, 10 in 1); 181 core and
52 CLI regression tests pass. Overhead on this Mac's path, n=3000:
+1.2 us p50 / +5.5 us p99 to the first byte in process, +1.3 us p50
over loopback (p99 noise).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… (L3)

One more case in the opt-in suite against the V0 coordinator: the owner's
funded account with my-macs-first is served through `prefer` by its
other Mac (200, Route-Used prefer).

Run once on Mac A, 01:19Z, against darkbloom-platform 90ee29fc0d in
development mode on 127.0.0.1:<ephemeral>, then every harness process
was stopped and its secrets deleted: 5 of 5 pass (self 200 with limits
from the catalog; my-macs-first 200 through prefer; 409
no_linked_machine verbatim; a zero-balance owner whose Mac is offline
gets prefer's 402, after the self retry, saying the network fallback
needs a balance; the self view's count keeps a self hop off this Mac).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…uest (L3)

Comments and docs only; no code changes.

The server allows input half-close, as for this Mac's own streams, so a
client's normal close (a FIN) is noticed only when a chunk can't be
delivered: mid-stream within a chunk or two, during a long prompt at its
first token. A reset is noticed at once, even while nothing flows. The
docs said "when its connection closes, even while nothing flows", which
holds only for a reset, and the changelog said "a client that stops
reading", which a client that keeps its connection open doesn't do.

Checked: swiftc -parse on both Swift files, docs-check 208 OK,
changelog 21 valid, docs-impact OK against origin/dev, git diff --check
clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 7, 2026
…w fixes

L3's head moved 0ea2835 -> 853345f: the router's review fixes
(no upstream hop without the local key: a `--no-auth` endpoint keeps
every request on this Mac and never reads the account key;
`my-macs-first` asks `prefer` first and `self` once on a 402; a client
that leaves stops a passed-on request), their tests and docs, and L0's
f7c398b, already here.

Two conflicts:
- StartCommand+Modes.swift: L3 changed one line of the --local-endpoint
  block that L4 moved into Start.unifiedLocalEndpoint. That line now
  says "(auth disabled: requests stay on this Mac)" there. L3's other
  line, "Requests: this Mac only. ...", merged into the --no-auth
  branch of runLocalStandalone's banner by itself.
- docs/reference/configuration.md, the [local] table: L4's rows for
  mode, me_first, me_first_idle_minutes and port, L3's row for route.

The start, status and local lines that name where requests go follow
L3's rule in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 and others added 2 commits November 6, 2026 18:58
Tests first for the re-review of #1876 (approve with nits). The skeleton
adds only the names the tests use, unwired: the legacy keychain's
interaction switch on KeychainItemCalls, the 402 wording function
(always the balance words for now) and readHidden(prompt:terminal:
onSignal:) without signal handling. No test touches the real Keychain:
the store's tests run against FakeKeychain, the router's against an
in-memory store.

- The 402 wording: a key's spend cap (error.type insufficient_quota) on
  prefer still asks self once (it never spends), and the 402 that
  stands is passed on in Darkbloom's own words, not as "no balance";
  only insufficient_funds is called no balance.
- A Keychain read never waits on a dialog: a login-keychain item this
  build may not read without approval (an ad-hoc rebuild) fails at once
  with the legacy keychain's interaction switch off, which is put back
  after; the data-protection query carries an LAContext that may not
  ask; a switch that can't be turned off means no read; saving and
  removing (route key, at a terminal) may still ask.
- A key that can't be read is said once per run of failures, in a line
  without the key, and requests stay on this Mac meanwhile.
- ^C at route key's hidden prompt gives the terminal its echo back
  first; in a child process on a pseudo-terminal.
- --no-auth reads the key store zero times.
- The coordinator's count of your Macs serving a model is read once for
  a burst of passed-on requests; a failed read isn't kept.

Red (prod, CPU-only, sandboxed), `--filter 'LocalRouter|RouteKey'`: 7
tests fail with 22 issues. Six new or changed checks pass on both
sides by design: a typed line comes back with the echo on; ^C still
ends the command as SIGINT; saving and removing may still ask; a switch
already off is left off; --no-auth reads no key; and my-macs-first's
no-balance 402 with this Mac the only one serving its model (its stub
now sends error.type, as the coordinator does).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The re-review of #1876 approved with nits; all five are here, and the
optional sixth. Public names are unchanged; Timing.ownedCountTTL is new.

- The 402 wording. my-macs-first still asks self once on every 402 from
  prefer: self never spends, so it helps with a key's spend cap too.
  But only error.type insufficient_funds is called "no balance" now.
  Any other 402 that stands (a spend cap, a promotion's limit) starts
  "Network fallback refused:" and passes on Darkbloom's own reason
  (LocalRouterPolicy.networkRefusalPrefix). The log lines, comments,
  docs and changelog follow.
- The docs say plainly that my-macs-first doesn't wait on a busy Mac of
  yours only while another Mac, yours or the network's, can take the
  request. When none can, the coordinator queues prefer too, up to
  120 s, and keeps it while you have a Mac serving the model
  (registry/queue.go at 90ee).
- A Keychain read never waits on a dialog. The data-protection query
  carries an LAContext with interactionNotAllowed (the current form of
  kSecUseAuthenticationUIFail). Legacy (login keychain) items ignore
  the query's UI keys (SecItem.h; Apple's SecItemCopyMatching_osx never
  reads them), so the read turns the process-wide
  SecKeychainSetUserInteractionAllowed switch off, one read at a time,
  and puts it back. A switch that can't be turned off means no read.
  Saving and removing (route key, at a terminal) may still ask. The
  switch is deprecated, hence two warnings. effectiveRoute() no longer
  swallows the error: it logs one line per run of failures (the
  OSStatus, never the key, and how to fix it), then serves this Mac.
- ^C, ^\, a hang-up or kill at route key's hidden prompt gives the
  terminal its echo back first, then ends the command as the signal
  would (HiddenReadSignals: ignored and watched with dispatch sources,
  as DistributedStartSignals does, and put back exactly). A signal
  already ignored stays ignored.
- The --no-auth test asserts zero key-store reads.
- Optional: the coordinator's count of your Macs serving a model is
  reused for 5 s (Timing.ownedCountTTL), so a burst of passed-on
  requests reads it once; a failed read isn't kept.
- The opt-in E2E gains two cases with capped keys (limit_usd 0.00001):
  the owner's capped key is answered through self by its other Mac;
  owner3's capped key, its Mac offline, hears Darkbloom's spend-limit
  reason, not "no balance".
- A test warning from the last round (a weak self captured as a var)
  is gone.

Green (prod, CPU-only, sandboxed), `--filter 'LocalRouter|RouteKey'`:
57 tests in 6 suites and 13 in 2 pass (8 opt-in skips). Regressions:
190 core tests in 28 suites and 70 CLI tests in 13 pass, the signal
suites included. E2E against the V0 coordinator (90ee29fc0d, loopback,
ephemeral ports), 03:08Z: 7 of 7; the harness was stopped and its
secrets deleted. Live disconnect: cut 0.20 s mid-stream, 0.23 ms on a
reset. Overhead n=3000: +2.2 us p50 to the first byte in process,
+5.9 us over loopback (load 9-14).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 and others added 2 commits November 6, 2026 19:53
… the login keychain only (L3)

Tests first for the focused confirm of #1876. The skeleton adds only the
names the tests use, unwired: KeychainLocalRouterAccountKeyStore's
changeNotification, KeychainItemCalls.announceChange (notify_post),
LocalRouterConfig.keyChangeNotification, and LocalRouterKeyCache (the
renamed LocalRouterKeyReads, which keeps no copy yet). No test touches
the real Keychain: the store's tests run against FakeKeychain, the
router's against an in-memory store, and the router's change
notifications have names of their own.

- The process-wide SecKeychainSetUserInteractionAllowed switch, and its
  lock, only around the login-keychain read: a signed build's
  data-protection read never reads or sets it (it reads the key even
  when the switch can't be set); the login read runs with it off, and
  it is put back; a switch that can't be turned off stops the login
  read only, after the data-protection one.
- The key is read once and kept: five passed-on requests and a model
  list read it once; after the change notification, the next request
  reads it again. A failed read isn't kept: each request tries again,
  said once per run of failures; a key read and kept stays in use when
  the keychain locks later, until it changes.
- Saving or removing the key posts the identity's change notification,
  <keychain prefix>.route-key-changed; a refused save or remove posts
  nothing; a read posts nothing.

Red (prod, CPU-only, sandboxed), `--filter 'LocalRouter|RouteKey'`: 6
tests fail with 12 issues. Three pass on both sides by design: a switch
already off is left off (now on the login path), saving and removing
at a terminal may still ask, and --no-auth reads no key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ly for the login keychain (L3)

The focused confirm of #1876 found the account key read, and the
process-wide SecKeychainSetUserInteractionAllowed switch flipped under a
process-wide lock, on every passed-on request and every model list, in
every build, signed ones included, where the switch governs nothing.

- The switch, and its lock, only around the login-keychain read: the
  ad-hoc fallback after errSecMissingEntitlement. A signed build reads
  the data-protection Keychain only, with its LAContext that may not
  ask, and never reads or sets the switch.
- The key is read once and kept in memory (LocalRouterKeyCache, which
  takes over LocalRouterKeyReads' log-once state). Saving or removing
  it posts a Darwin notification scoped to the identity,
  KeychainLocalRouterAccountKeyStore.changeNotification
  (<keychain prefix>.route-key-changed, notify_post), so `route key`
  announces every change; the router drops its copy on it
  (notify_register_dispatch), and the next request reads the key again.
  A read that a change overtook isn't kept. A copy is kept only while
  the notification is watched: a store that posts none (in memory), or
  a registration that fails, reads on every request as before.
- A failed read isn't kept: the next request tries again, and a run of
  failures is still said once. A key read and kept stays in use when
  the keychain locks later, until it changes.
- Docs: the key is read once and refreshed when route key changes it;
  only the login-keychain read touches the switch. Changelog too.

Public names are unchanged; KeychainLocalRouterAccountKeyStore gains
changeNotification.

Green (prod, CPU-only, sandboxed), `--filter 'LocalRouter|RouteKey'`:
60 tests in 6 suites and 13 in 2 pass (8 opt-in skips); the two new
router tests and the store suite passed 5 runs in a row. Regressions:
195 core tests in 28 suites and 70 CLI tests in 13 pass. E2E against
the V0 coordinator (90ee29fc0d, loopback, ephemeral ports), 03:59Z:
7 of 7; the harness was stopped and its secrets deleted. Overhead
n=3000: +1.6 us p50 to the first byte in process, +0.8 us over
loopback (load ~23). Disconnect: cut 0.20 s mid-stream, 0.21 ms on a
reset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…HTTP/1.1 test (L3)

The first review's nit 6: over a plain-HTTP coordinator (HTTP/1.1, the
V0 harness through a tunnel, as tomorrow's real-Mac check uses), one
request takes one connection, so URLSession's default of 6 per host
would hold a 7th concurrent pass-on until the 10 s connect watchdog
failed it as darkbloom_unreachable. The session has allowed 64 since
c9b5fcd; nothing tested it.

- URLSessionLocalRouterTransport.sessionConfiguration() (internal)
  builds the session's configuration, unchanged, so a test can read it.
- A test asserts at least 32 connections per host, and that the
  session keeps no cookies, cache or credentials and doesn't wait for
  connectivity.
- A live test sends ten concurrent streamed requests through the
  product's URLSession client to a plain-HTTP stand-in on loopback
  (kernel-chosen port), whose every stream stays open until all ten
  have arrived: all ten are answered, in about 30 ms.

Mutation check, not committed: with the line removed (the default of
6), both tests fail, the live one with "Darkbloom did not answer the
connection in time" after its 3 s connect watchdog.

Tests (prod, CPU-only, sandboxed): `--filter 'LocalRouter|RouteKey'`
62 tests in 6 suites and 13 in 2 pass (8 opt-in skips); the live test
passed 5 runs in a row; regressions 197 core and 70 CLI tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

2 failed and 3 active deployments
Preview – eigen-homepages-darkbloom — b79a3c52 Deployed Nov 7, 2026 by vercel[bot]
Preview – d-inference-landing — b79a3c52 Deployed Nov 7, 2026 by vercel[bot]
Preview – darkbloom-status — b79a3c52 Deployed Nov 7, 2026 by vercel[bot]
Preview – d-inference — b79a3c52 Deployed Nov 7, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — b79a3c52 Deployed Nov 7, 2026 by vercel[bot]
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