Repository navigation
provider: local router, this Mac first then my Macs (L3, stacked on #1870) - #1876
Merged
Merged
Conversation
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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
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>
#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>
7 of 9 tasks
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>
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>
… 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The local router (PR L3 of the local-first stack for provider 0.10.11): the local API of
start --local,--local-endpointand 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 withX-Darkbloom-Route: self([local] route = "my-macs", free). With"my-macs-first"it goes on withprefer(the owner's Macs first, then the network, billed), and after any402from it (no balance, or the key's spend cap) once more withself, which never spends. Nothing leaves the Mac without a saved account key, withroute = "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 whenroute keychanges it.Stacked on #1870 (L0,
local-first/l0-config, headf7c398b9f2, merged here). The base isdevas asked, so until #1870 merges this diff also shows L0's commits. L3's own commits:34d05abbfd(red),796ff312e9(green),a00c0ddfc9(an opt-in end-to-end suite);1a4c9b8955(merges L02a2987cd5c),0ea283557b;f1f3e03239(merges L0f7c398b9f2),c69eb99da9(red),c9b5fcd008(green),ff8b731f23(end to end:my-macs-firstthroughprefer),853345f070(docs: when a client that leaves is noticed);651f2e9251(red),22ebd6a822(green);d76eb6177a(red),2a424575d7(green),b79a3c528f(connections per host, pinned by a live test).Draft. Do not merge. No
devmerges until the owner says so: adevmerge publishes a DevNet build.Linked issue
None. This is part of the local-first goal (
GOAL.md, D1DESIGN-LOCAL-FIRST.md§3 and §6 L3, V0SPIKE-V0.mdfindings 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, insidesandbox-execwith a profile that denies~/.darkbloom*.io.darkbloom.test.route-key-changed.<UUID>), never an install's.127.0.0.1with kernel-chosen ports.darkbloomCLI 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: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-authreads no key.Green at
2a424575d7(60 tests in 6 suites and 13 in 2), and atb79a3c528fwith 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):URLSessionclient 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.Darkbloom did not answer the connection in timeafter 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.CLIDispatchTestswas left out: it runs this build'sdarkbloombinary.Checks at
2a424575d7andb79a3c528f:changelog.py check(21 fragments),docs-check.sh(208 files),docs-impact-check.pyagainstorigin/dev(37 files) andf7c398b9f2(32 files), andgit diff --checkpass.Overhead benchmark (
LocalRouterOverheadTests), owner requirement "does not add much overhead". This Mac's path is unchanged.n=3000, at a load average of about 23. The bench also asserts that this Mac's path reads the key store zero times.End to end against a real coordinator on loopback (
LocalRouterCoordinatorE2ETests): run at 03:59Z against a copy of the V0 harness (darkbloom-platform90ee29fc0d, development mode, memory store) on127.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 firstrmmissed 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:darkbloom route key(a save, or--remove) should make its next passed-on request read the key again;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 ondev. At2a424575d7, Provider Unit Tests shard 1 had failed in an XCTest that L3 doesn't touch:MiMoV26EncodedAudiovisualIngressTests.testAFailedAudioReaderPassIsReadAgainAndReportedreportedvideo_reader_failedwhereaudio_reader_failedwas expected. It passed here.Dev-identity build.
Earlier rounds:
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.f1f3e03239to853345f070): red atc69eb99da9(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 at853345f070after one re-run (a hung artifact download).34d05abbfd(34 tests fail with 213 issues), green at796ff312e9(31 tests in 4 suites and 9 in 1), end to end 4 of 4 ata00c0ddfc9. 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).0ea283557b: see "Refactor Pass".Components touched
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:
X-Darkbloom-Served-ByandX-Darkbloom-Route-Used;/v1/modelsgainsowned_by: this-mac|my-macs|darkbloom,max_output_lengthand upstream entries, each model once;darkbloom route key;<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}andGET /v1/models/catalog.Documentation impact
docs/provider/direct-mode.md: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] routeread at start, and thews://note. The re-review round added the402wording byerror.type, whenmy-macs-firstdoes queue, and that reading the key never asks. This round adds that the key is read once and read again whenroute keychanges it, and that only the login-keychain read touches the switch;--no-authrow, the routes table and the stack;docs/reference/configuration.md:[local] route;docs/provider/cli-reference.md:darkbloom routeandroute 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 both402types.Changelog
changelog.d/local-router.md(updated:my-macs-firstwith the spend cap,--no-auth, aliases, a client that disconnects, reading the key once and without a dialog, ^C at the hidden prompt, andowned_by: "local"→"this-mac") and ranmake changelog-check(scripts/changelog.py check).Notes for reviewers
Router API for L4 and the integrations (D2a/D2b)
These names are unchanged:
LocalRouterConfig.host(local:coordinatorURL:takesCoordinatorWork:),effectiveRoute()andLocalInferenceHTTPConfig(router:);KeychainLocalRouterAccountKeyStoreandRouteKeyFlow(save/remove/routeLines);owned_byvalues and the headers.What the last three rounds added or changed is marked new or changed.
LocalInferenceHTTPConfig(host:port:authToken:router:)withrouter: LocalRouterConfig.host(local: config.local, coordinatorURL:, takesCoordinatorWork:). Wired already:--local(takesCoordinatorWork: false),--local-endpoint(true),--distributed(!noCoordinator). Withrouter: nilthe endpoint behaves exactly as before.LocalRouterPolicy.upstreamBaseURL(coordinatorURL:):ws://h:8080/ws/provider→http://h:8080,wss→https, the build's coordinator otherwiseLocalRouterConfig.effectiveRoute(). It is[local] routevia L0'sresolvedRoute(accountKeySaved:), except that nothing leaves the Mac without a saved key, or (new) without a local key. New:LocalRouterConfig.localKeyRequired(defaulttrue);makeLocalInferenceApplicationturns it off whenauthTokenis nil or empty. Changed: the key is read once and kept in memory, and read again afterroute keychanges it (a Darwin notification), soroute keystill needs no restart.[local] routeis read at start.LocalRouterPolicy.hops(for:): none forthis-mac,[.mine]formy-macs,[.prefer]formy-macs-first(was[.mine, .prefer]). New:asksYourMacs(afterNetworkStatus:)(402) andyourMacsCouldNotTakeIt(status:)(409,429,503). They replacetriesNextHop(after:), which nothing outside L3 used. New, internal:networkRefusalPrefix(errorType:), the words for a402that stands.LocalRouterAccountKeyStore(load/save/remove):KeychainLocalRouterAccountKeyStore(service<prefix>.route, accountaccount-api-key) andInMemoryLocalRouterAccountKeyStorefor tests. Internal:KeychainItemCalls, the fourSecItemcalls and (new) the legacy keychain's interaction switch, behindinit(service:account:calls:), so tests can use a fake. Changed:load()never asks the user (Decisions), wherever it is called. L4'sStart.accountKeySaved()then answersfalsefor a key this build may not read yet. New:KeychainLocalRouterAccountKeyStore.changeNotification(<prefix>.route-key-changed).saveandremovepost it wherever they are called, L4's start-screen key prompt included.LocalRouterAccountKeyFormat.refusal(_:)holds the rulesroute keychecks. L4's start-screen key prompt can callRouteKeyFlow(save/remove/routeLines) indarkbloom.RouteKeyFlow.routeLines(savedRoute:keySaved:), in the iPhone app's words, with no speeds. New:RouteKeyFlow.liveEndpointHasNoLocalKey.route keysets it fromLocalEndpoint.readLiveInfo(), and then says that the running API keeps every request on this Mac.LocalRouterUpstreamResponse.cancel, an init parameter with default{}. The relay calls it when the client leaves. The URLSession transport cancels its task there; a customLocalRouterTransportshould stop its request. Internal:URLSessionLocalRouterTransport.sessionConfiguration(), the session's configuration (64 connections per host), which a test reads.GET <base>/v1/modelswith the local key. Each entry hasid,object,created,owned_by(this-mac|my-macs|darkbloom), and when knownname,context_length(also asmax_model_len) andmax_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; anyX-Darkbloom-Routethey send is dropped.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.RouteKeyFlow.readHidden(prompt:)is unchanged for callers. It now gives the terminal its echo back on ^C,^\, a hang-up orkill, then ends as the signal would (HiddenReadSignals). Internal:readHidden(prompt:terminal:onSignal:).max_tokensmax_completion_tokensasmax_tokenswhenmax_tokensis absent (LocalChatRequest). OpenCode'scompatibility.maxTokensFieldis then optional; passed-on bodies go unchanged.X-Darkbloom-Served-By: this-macordarkbloom;X-Darkbloom-Route-Used: selforpreferon upstream answers. New: the router's own413saysServed-By: this-mac, and its502s sayRoute-Used. No Mac's identity: the coordinator'sX-Provider-Idis not relayed.Merging this head into L4.
fa673b9082) and D2b (1d78fa7474) have merged853345f070.git merge-treeofb79a3c528finto each shows no conflict. Nothing in L4 namesLocalRouterKeyReads, which this round renamedLocalRouterKeyCache(internal).Start.accountKeySaved()now answersfalsefor a key this build may not read without asking (above).Decisions to check
The focused confirm (
review-L3.md, "Round 3", of22ebd6a822) asked for one change and recommended a second. Both are here:SecKeychainSetUserInteractionAllowedswitch under a process-wide lock, in every build.errSecMissingEntitlement) runs with the switch off.LAContextthat may not ask. They never read or set the switch, or take its lock.LocalRouterKeyCache), so a passed-on request or a model list no longer reads the Keychain each time:KeychainLocalRouterAccountKeyStore.saveandremovepost a Darwin notification scoped to the identity (changeNotification,<keychain prefix>.route-key-changed, withnotify_post), sodarkbloom route keyannounces every change. At its first read the router registers for it withnotify_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.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", of853345f070) approved with nits. This round takes all five, and the optional sixth:402wording:402fromprefer.selfnever spends: it skips both the reservation and the key's spend cap (admission.go), so the retry helps with a cap too.error.type:insufficient_fundskeepsNo balance for the network fallback: none of your Macs could take this request, and the Darkbloom network needs a positive balance. Darkbloom said: …;insufficient_quota; a promotion's limit) readsNetwork 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.my-macs-firstwaits, 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 queuesprefertoo: up to 120 s, then429 machine_busy, and kept while you have a Mac serving the model (registry/queue.go:506-545at90ee).LAContextwithinteractionNotAllowed, the current form ofkSecUseAuthenticationUIFail(which is deprecated).SecItem.h: "Legacy keychain items will still activate UI if needed"; Apple'sSecItemCopyMatching_osxnever reads them). So the login-keychain read turns the process-wideSecKeychainSetUserInteractionAllowedswitch 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.route key, at a terminal) may still ask: approving a new build there is how it reads the key again.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.route key's hidden prompt (also^\, a hang-up orkill) gives the terminal its echo back first, then ends the command as the signal would. The signals are ignored and watched with dispatch sources, asDistributedStartSignalsdoes, and put back exactly. A signal the command already ignores stays ignored.--no-authtest asserts zero key-store reads.Left out, as asked: a pair's
takesCoordinatorWorkfollowing its decided serving scope goes to cluster: Both, me first for a pair indarkbloom cluster(local-first L5b-cli) #1884 (the pair screens).The independent review (
review-L3.md, of0ea283557b) asked for changes: three findings and a design question. This round takes all four.UpstreamTaskHandlerkept its own copy of the body stream, so the stream never ended when the relay stopped reading it.relay()also registers the answer'scancelwith the request's disconnect scope, as this Mac's own streams do. It callscancelwhen the body didn't end normally.--no-auth), the router serves this Mac only. It never reads the account key and never dials the coordinator, and/v1/modelslists this Mac only.local router: no local key (--no-auth): requests stay on this Mac, and the account key is never used. The--localand--local-endpointbanners,darkbloom local,route keyand the docs say it too./v1/modelslists the model once, asthis-mac. Upstreammy-macsordarkbloomentries for the alias are dropped (the catalog'saliasBuilds).404first. With a route that dials out, the router then asks this Mac once more under the build's id (the body'smodelrewritten), before anything is passed on.selfhop for it still never comes back here.my-macs-firstsendspreferfirst (the design question):402retry:preferreserves the price up front even when an owned Mac answers (F1; it charges nothing then), so its402asksself, once, free. The re-review widened the words to every402(above).selfthen answers409,429or503,prefer's402stands. Any otherselfanswer is relayed, withRoute-Used: self. Any otherpreferanswer is relayed, as formy-macs.preferasself, waits included.routeLinesalready says that such a key answers only from the owner's Macs.Nits taken:
SecItemcalls (2);Served-ByandRoute-Usedon the router's own errors (9);--no-auth, themy-macs-firstwait,502 darkbloom_error_unreadableand the router's own413,[local] routeread at start,owned_by: "local"→"this-mac", and thews://note.L0's comment on
Route.myMacsFirstfollows the new order.Nits not taken then:
kSecUseAuthenticationUIFailand a log line for an unreadable key (1), a short cache for theself-view count (3), and restoring the terminal on ^C at the hidden prompt (8): all taken in the re-review round (above);takesCoordinatorWorkfollowing the decided scope (4): goes to cluster: Both, me first for a pair indarkbloom cluster(local-first L5b-cli) #1884;The four V0 findings:
prefer402s at a zero balance:my-macs-firstasksselfafter any402fromprefer(above). When that402stands, it keeps its status,type,codeandRetry-After. Its message starts withNo balance for the network fallback: …forinsufficient_funds, and withNetwork fallback refused: …for any other type, followed by Darkbloom's own message. This is the one rewritten body. Every other refusal is verbatim.selflist has no limits: filled from this Mac's engine or the catalog (above).selfrequest to this Mac while it's paused waits 120 s:selfrequest.--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'sselfview of that one model (GET /v1/models/<id>, which still counts a paused Mac).my-macsreturns this Mac's status with codethis_mac_onlyand a plain message.my-macs-firstanswersprefer's402without theselfretry. A failed check counts as 0 (fail closed).--localandcluster localnever take coordinator work, so aselfrequest can't reach them.my-macs,selfto other busy Macs keeps the coordinator's own 120 s queue and429 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.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).
Low overhead (owner criterion 8):
Response(SSE or JSON) is returned as it is, with one header set. No body re-wrapping, copy or buffering.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. Withthis-macor without a local key, the list never leaves the Mac.Upstream 401/403: these become
502 account_key_refused("Save a new one withdarkbloom route key"), so a tool never mistakes them for its own local key being wrong. An unreachable coordinator is502 darkbloom_unreachable, with a plain reason and no URL.Account key secrecy:
--stdin.provider.toml,local.jsonor a response. Upstream error bodies are redacted, and tests scan responses, headers, log lines and files.Key storage:
errSecMissingEntitlementfalls back (now tested with the fake).route keychecks the key once, withGET /v1/models+self:dk-local-…) and malformed input are refused before any check.Behaviour change on every host that configures a router (all three production paths):
/v1/modelsentries sayowned_by: "this-mac"instead of"local", and a chat request'smax_completion_tokensis now honoured.Limitations
darkbloomCLI and no real Keychain. V1/V2 on pair-2 with a staging build cover:route keyand the LaunchAgent's Keychain read;selfandpreferhops;--no-authwith a saved key;/v1/modelson a Mac serving a catalog model that has an alias (the V0 stub model has none).this-macor without a key, a request naming an alias gets this Mac's404, as before, and/v1/modelslists no alias then.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.takesCoordinatorWorkis fixed at start (!noCoordinator, review nit 4). When the coordinator refuses the member role and the pair serves locally only, the router still reads theselfview. With exactly one other Mac serving the model, it can then answer a falsethis_mac_only; it fails closed. This goes to cluster: Both, me first for a pair indarkbloom cluster(local-first L5b-cli) #1884 (the pair screens).route key. A key changed or deleted another way (Keychain Access,security) is noticed after the nextroute key, or a restart. A request that arrives within milliseconds ofroute keycan still use the old key.selfhop 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)./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"] endflowchart 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 endRefactor 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):modelsRequest);owned_byvalues are named together (LocalRouterPolicy.myMacs);LocalRouterRequestBodyis folded into the router;RouteKeyFlow.saveswitches once;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.