diff --git a/CHANGELOG.md b/CHANGELOG.md index f56d84134e..075342f22c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,41 @@ or console deployment, feature activation, model promotion or hardware qualification. Sections marked historical retain the original candidate's qualification, opt-in and deployment limits rather than claiming activation. -## v0.10.12 — candidate (unpublished) +## v0.10.13 — candidate (unpublished) -Prepared on 2026-11-12; tagging and publication are separate steps. +Prepared on 2026-11-13; tagging and publication are separate steps. + +### Upgrade and rollout notes + +**Highlights** + +Plain-language summary of provider 0.10.13. The full technical changelog, the pull requests and the build's +verification details are on this page too. + +- Gemma 4 no longer gets stuck repeating a thought: when its reasoning starts to loop, it stops thinking and answers. +- When you set up a two-Mac pair, the second Mac no longer says "Stopped" while the first Mac downloads the model. + +- **A Gemma 4 thought that repeats itself verbatim now ends in an answer:** the loop guard closes the thought and the model answers in the same response (at most 8,192 tokens, within the request's budget), instead of ending as `length` with no answer. A loop in the answer still ends as `length`. Gemma 4 only; never with logprobs or on a pair; `DARKBLOOM_LOOP_EXIT_THINKING=0` turns it off (#2040). +- **Setting up a pair no longer says "Stopped" while the leading Mac downloads:** the joining Mac ends its screen only on a stop someone asked for, and such a stop now ends the leading Mac's start at once, also during the download or the load (#2042). +- **Rollout:** a patch release over 0.10.12 with only the fixes below; nothing else from `dev` rides. Pairs: both Macs must run the same version, and a pair on 0.10.12 updates itself. `darkbloom update --rollback` puts back 0.10.12. +- The registration keeps 0.10.12's fields and cluster runtime facts; `libs/mlx` (72dffa2d), `libs/mlx-swift` (b1c94d29) and the Xcode 27.2 toolchain are unchanged, so `mlx.metallib` is unchanged. +- The 2 entries below are the pending fragments rendered verbatim, except where the release notes reword one; CI-only entries change no provider behaviour. + +### A pair being set up is no longer called stopped while the leading Mac downloads + +- During `darkbloom cluster` setup, the Mac that joined ended its screen about 20 s into the leading Mac's download (or a long copy) of the chosen model with "Stopped (by `darkbloom cluster stop` on one of the Macs): the pair isn't starting any more", though nobody had stopped anything and the leading Mac's start went on (0.10.9 to 0.10.12). It took the leading Mac's status, which reads "Stopped" until both Macs' parts start, for a stop. The leading Mac now counts each stop someone asks for (`darkbloom cluster stop` on either Mac, and `darkbloom stop` or `darkbloom restart` once the pair runs) and its status carries the count; the Mac that joined ends only on a stop asked since the start began, and then at once instead of 20 s later. A leading Mac on an older build sends no count, so the Mac that joined follows its start to the end. +- On the leading Mac, such a stop now ends the start at once too: during the model's download or copy (what arrived stays, and the next start goes on from there; before, both Macs were started once it finished), while both Macs load the model (before, a ✗ with Retry after 15 minutes), and at the test (before, "✓ Serving" or "the test failed"). The registration no longer starts again a pair stopped during the test. The pair's own stops (the registration's restart, the cluster service's restart for a changed approval) no longer end the leading Mac's wait for the coordinator with that line. + +### A Gemma 4 thought that repeats itself verbatim now ends in an answer + +- When the loop guard stops a verbatim loop inside Gemma 4's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``), and the model writes its answer in the same response. The client sees the thought close and the answer start. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`, as in 0.10.12. +- The answer gets what is left of the request's output budget, at most 8,192 tokens. If it cannot start (under 256 tokens left, the stopped row not released within 5 s, a full Mac, a cancel), the request ends as `length`, as before; if it fails after its first token, the answer ends there as `length`. +- Gemma 4 only (`gemma4`, `gemma4_text`). Never with logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=0` turns it off. +- `DARKBLOOM_LOOP_EXIT_THINKING` and 0.10.12's `DARKBLOOM_LOOP_GUARD` now reach a provider started by `darkbloom start` (launchd). Before, both worked only in the foreground or with `--local`. + +## v0.10.12 + +Published 2026-11-12 ([release](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.12)). ### Upgrade and rollout notes diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a6cc4fb505..a88327753d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -450,7 +450,27 @@ over the cable and ends with the same ✓/✗ block, bounded like the leader's s rows. Plain output prints each whole line. - **How the wait ends.** A refusal ends the wait at once with the leader's ✗ (`followRefused`; different builds: `differentBuildsLines`). Running out of time ends it with a ✗ and next steps (`notStartedReason`, - `notStartedLines`). + `notStartedLines`). A stop someone asked for ends it at once with the leading Mac's line (`ClusterOnboardingStopped`): + `darkbloom cluster stop` on either Mac, and `darkbloom stop` or `restart` once the pair runs (before that, `darkbloom + stop` stops only what runs on its own Mac). The leading Mac runs each such stop (`OnboardingLive.stop`) and counts it + in its setup record, in the same write as the stopped intent (`ClusterSetupRecord.stopsAsked`, + `OnboardingLive.recordStop`); the start's own stops (a model change, the registration's restart) and the cluster + service's don't count. Its status reply carries the count (`ClusterControlReply.stopsAsked`, 0 before the first; nil + from an older build, which an older Mac ignores). The start begins at its first step on the leading Mac, the model's + transfer or the start itself (`ClusterOnboardingLeaderStep.startBegun`); that step carries the count read then + (`ClusterOnboardingLeaderStep.stopsBefore`), so both Macs compare with the same number. The Mac that joins ends once + it grew (`ClusterOnboardingFollowedStop`; a look that read no count tells nothing), and so does the leading Mac: in + the model's download or copy (what arrived stays, and the next start goes on from there), in its waits for the + parts and for the coordinator (`ClusterOnboardingDriver.endsOnStopAsked`, asked about once a second off the console's + thread, `ClusterOnboardingLooker`), at its test, and before both Macs start (`startBothMacs`, also when the same start + goes on after the single-Mac or version question). The leading Mac compares the count again under the command lock + its start takes (`OnboardingLive.localServe(unlessStoppedSince:)`, `ClusterControlRequest.stopsBefore`), so a stop + that took the lock first is never undone, and its registration neither registers nor starts again a pair stopped + since its start (`OnboardingLive.localRegister`). Retry after a ✗ is a new start. The status' words never tell + a stop: it reads "Stopped" until both parts start, so through a whole download or copy of the model, and again while + the registration restarts them. 0.10.9 to 0.10.12 took "Stopped" held 20 s for a stop on the Mac that joins (an + external pair's said it 20 s into a download, 2026-11-12), and the saved start turned off for one in the leading + Mac's coordinator wait, which the cluster service's own restarts turn off too. - **The leader's own Local Network wait** has a bound too (`ClusterOnboardingOperations.localNetworkWaitSeconds`, `localNetworkOffLines`). @@ -3216,9 +3236,10 @@ stops such a row early. engine's cancelled terminal into a `length` finish with the engine's usage: `finish_reason: "length"`, the tokens produced, no error frame, paid like any completion. It logs one line (category `engine_v2_loop_guard`: model, - `model_type`, period, span, tokens) and emits an `engine_v2_loop_guard` - engine-health event with the same fields. To the coordinator it is a - `length` finish below the request's bound. + `model_type`, period, span, tokens, and whether the stop ended a thought) + and emits an `engine_v2_loop_guard` engine-health event with the same fields + (`ends_thought`). To the coordinator it is a `length` finish below the + request's bound. - **Never on:** the first 4,096 tokens; a request with a token constraint, a forced tool call or a JSON `response_format`; the rest of a row once its text shows a tool-call frame (``, `<|tool_call>`, `` … ``; the prompt's tail seeds the state) and records + every token the row produces, the in-flight ones after its stop included. A + detection inside the thought stops the row as above; the scheduler + (`prepareCompletion`) then holds the row's `length` terminal, waits until the + row has released its serving slot (`EngineV2Bridge.waitForRowRelease`, as + model calibration waits: its pump's retirement cleanup and its whole-Mac + service charge; a row with a retirement handle, the coordinator's atomic + admission path, ends its stream before that; at most 5 s), and submits one + continuation on the same bridge: the prompt, every generated + token and ``, with `max_tokens` = the output the bridge resolved + for the row minus the tokens produced minus 1, at most 8,192; the same + sampling, stop strings and cache scope; and a loop guard without the exit, so + a loop in the answer still ends as `length`. The client's stream carries the + thought, a `` chunk and the answer, then one terminal: the original + prompt, completion = the row's tokens + 1 + the answer's, the continuation's + finish reason. The continuation is an ordinary row, so exact MTP drafting + stays on for it and its batch; a cancelled row donates no KV, so the + continuation prefills the thought again (its prompt part can hit the prefix + cache). When the continuation cannot start (under 256 tokens of budget left, + the row closed its thought itself, the row did not release its slot in time, + a refused submission, a failure before its first token, a cancel), the held + `length` terminal is + delivered as before; a failure after its first token ends the answer there, + as `length` (only the client's cancel keeps its error). Never with + logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`) + turns it off; a comma-separated list keeps it to the listed `model_type`s + that have a marker. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`, + to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended + thought gives the outcome. ### Collected and streaming reasoning state diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index be223a1fde..9b59a97310 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -1,6 +1,6 @@ # Release A Provider Version -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 Build, sign, notarize and publish an explicitly authorized provider artifact. The pipeline registers its exact official identity through the external platform @@ -27,89 +27,34 @@ runs the resolve, build, qualification, signing, R2 staging and publication chain for one environment. To find the newest dev release, read `https://api.dev.darkbloom.dev/v1/releases/latest`. -`ProviderCore.version` is prepared as `0.10.12`, a patch release over `v0.10.11`. -A running request that one Mac's memory refuses now ends alone in every pair -mode, and the pair keeps serving (#1932, #1934, #1935); a Gemma 4 pair's -pipeline serves the model's whole context again (#1933, with #1928's capacity -tests); Gemma 4 and GLM-5.3-Flash pairs in tensor parallel serve as many -requests at once as both Macs' memory holds (#1936, #1939, with #1940's -per-lane parity check), and a pair estimates each request's first token before -it takes it (#1936). A pair's API answers a typed 503 from the first request -(#1929), the words real-Mac tests found are fixed (#1931), media decode faults -carry their own reason (#1921), and the watchdog no longer counts a requested -restart as a failed start (#1948), restores a provider job launchd lost (#1945) -and lets a pair's leader back off while the other Mac is away (#1949). Selected -models come back by themselves (#1609); `status` reports fan control (#1942), -paid early ends (#1950) and older authorization reports (#1943); Gemma 4 -reasons with `tool_choice` `none` (#1941); the desktop app recommends models by -chip (#1610); GPT-OSS repack tooling is added (#1562). A GLM-5.3-Flash heartbeat -reports only the requests it holds (#1964), and Nemotron Super -serves JSON, tools and WebP/GIF/BMP with media (#1922, #1962); a verbatim-repeating -answer stops early as `length` (#2005); GLM answers a JSON format with media on one -Mac (#2009). A request no -longer waits forever behind the idle speed check (#1966), and a drain stops -waiting for requests the coordinator abandoned (#1968). Qwen 3.5/3.6 requests that -can't speculate save prefix checkpoints again (#1965), Lightning serves plain -decode (#1969), the checkpoint export batches its rows (#1971), and Gemma 4's -MTP upgrade no longer runs a forward on the serving model (#1985); a native MiMo step may run -120 s before the watchdog seals the engine (#1989); `status` lists early-ended -requests by cause, paid or unpaid (#1980), and `models catalog` names the models this -Mac could add (#1957); Gemma 4 QAT (#1974) and Qwen 3.8 27B on -single Macs (#1999) draft with exact MTP acceptance; Nemotron Super saves native-precision -prefix checkpoints, so its cached answers equal cold ones (#2002); tool calls under `tool_choice: auto` -return as generated, while strict, required and named tools stay checked (#2003). -`darkbloom start` serves Both without a question and `darkbloom local` serves only you -(#2008); `darkbloom cluster` sets a pair up without the serving question and picks -the mode itself (#2007). Also: a stopped pair keeps its last mode (#2013); a Gemma 4 pipeline checks its whole number of requests at load (#1937 via #2015); a refusal's error frame names its reason (#2016); `status` shows the answers in progress (#2017); a held local stream counts once at the fallback width (#2018); a media request a Mac can't hold is `media_memory_unavailable` (#2019); Super's text route gets the loop guard (#2020); the SDK fixes the drafting shared-event leak and keeps paged decode at one pass per layer (#2021: mlx-swift-lm #403, #404), and Qwen3.5-9B drops the default penalty with exact acceptance (#1961); a single Mac reads Bonsai 2 27B prompts batched again; pairs keep per-row arithmetic (#2022); a stale prefill estimate that keeps refusing gets one idle probe, never an unprojected request (#2024); `status` lists answers in progress on a Mac that serves only you (#2030); CI resumes the MiMo audio codec download (#2023, CI only); two Bonsai 2 27B requests decoding together on a single Mac run per-row again at full speed, while prompts and larger batches stay batched (#2028); a pair's cluster service restarts into the installed release after an update (#2033); a Super image arriving as the previous image finishes waits for its cleanup (#2029); a Super image stacked behind a streaming image waits up to 3 s within its budget (#2035). The SDK pin -moves once more, to `ad8a5860e5` (mlx-swift-lm #378, #398, #399, #402: Gemma 4 admits -deadline text beside an image row once its prompt is read). The SDK pin moves once to -`libs/mlx-swift-lm` `093563be11`: Gemma 4's row-mapped NAX prefill on by default -with compiled feed-forward graphs (#1608, #1611, #1614), Qwen 3.5 MTP prompts -projecting only their last position (SDK #302), nullable tool parameters -(#1944) and an opt-in early response before the checkpoint write (#1671, off). Both Macs of a pair must -run 0.10.12, and a pair on 0.10.11 updates itself -([updating Darkbloom on the pair](../provider/two-mac-cluster.md#updating-darkbloom-on-the-pair)). -See the [`v0.10.12` changelog entry](../../CHANGELOG.md) for the full scope. - -Before tagging `v0.10.12`: +`ProviderCore.version` is prepared as `0.10.13`, a patch release over `v0.10.12` +with only the fixes listed in the [`v0.10.13` changelog entry](../../CHANGELOG.md): a Gemma 4 thought the loop guard stops ends in an answer (#2040); a pair being set up is no longer called stopped during the leader's download (#2042). + +Before tagging `v0.10.13`: - Toolchain unchanged: `mise.toml` `swift = "6.4.2"`, `release-provider.yml` sets `DARKBLOOM_PROVIDER_TOOLCHAIN: release` and asserts - `build_sdk_version == '27.2'`; `scripts/check-date-comparisons.py` passes; the - release build runs `scripts/check-provider-weak-imports.py`. -- Pins: `libs/mlx` `72dffa2d` as v0.10.11 and `libs/mlx-swift` moves to `b1c94d29c5` (mlx-swift #70, #71: Swift sources only), so the tag - build's `metallib_hash` should equal v0.10.11's `5b97893c…70ac`; - `libs/mlx-swift-lm` moves to fork `main` `44ab17555f` (#403, #404 on top of `ad8a5860e5`) (Swift model code, no Metal kernels). Confirm against the final DevNet build's row first. + `build_sdk_version == '27.2'`; the release build runs + `scripts/check-provider-weak-imports.py`. +- Pins: `libs/mlx` `72dffa2d`, `libs/mlx-swift` `b1c94d29` and + `libs/mlx-swift-lm` `44ab1755` as v0.10.12, so the tag build's + `metallib_hash` should equal v0.10.12's `5b97893c…70ac`. - Cluster runtime facts: run the release's facts step read-only on the exact tag - tree. Expect the same models and grants as v0.10.11; Gemma 4's pipeline - qualification carries the whole context again (#1933). Parse the block with - the coordinator that ships with this release before tagging. -- Catalog room: v0.10.11 and v0.10.12 hold 24 approvals each; v0.10.10's 24 are - left out (72 > 64). Pairs still on 0.10.10 stop serving through Darkbloom + tree; expect the same models and grants as v0.10.12. +- Catalog room: v0.10.12 and v0.10.13 hold 24 approvals each; v0.10.11's 24 are + left out (72 > 64). Pairs still on 0.10.11 stop serving through Darkbloom until they update. - The tagged commit is on `master` and verified, holds `ProviderCore.version` - `0.10.12`, keeps the plain-build default `prod`, and its `changelog.d/` holds + `0.10.13`, keeps the plain-build default `prod`, and its `changelog.d/` holds only `README.md`. -Roll out in this order; each step is a separate approval: - -1. Production platform: deploy the coordinator that ships with 0.10.12 (its - provider contracts snapshot this preparation's commit) first. -2. Merge into `master`, each squash-merged after its approval: the `dev` to - `master` release branch, then this preparation. -3. Re-run the facts dry run on the tag tree and parse the block with the - deployed coordinator's parser. -4. Tag `v0.10.12` on this preparation's squash commit. After registration, check - `release/0.10.12//s<1|2>` approvals beside v0.10.11's. -5. Pairs on 0.10.11 update themselves; check that each serves, including a - Gemma 4 pair in the pipeline with a long prompt. +After publish: the coordinator snapshot PR (pin + `LatestProviderVersion` +0.10.13) rides the next coordinator update. +`v0.10.12` was [published on 2026-11-12](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.12) +from `dafd15c65850c0e4dfb7b7801d39b890bcc8f9cd`, `v0.10.11` was [published on 2026-11-09](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.11) -from `34c4a10d86aa72e823787cb9cccb5d6c850d540a`, -`v0.10.10` was [published on 2026-11-06](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.10) -from `102ba6f74b0e4d8620768b5f6f11a49c13d3c571`, -`v0.10.9` was [published on 2026-11-05](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.9) -from `95cc1ca37533aa860f1948bde0d6ec9c36a6bd4a`. Publication does not +from `34c4a10d86aa72e823787cb9cccb5d6c850d540a`. Publication does not establish that every optional feature or environment has been activated. ## Prerequisites diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index c904ab5fde..1b40191de5 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -673,8 +673,15 @@ many at once ([Gemma pipeline lanes](../architecture/inference.md#gemma-pipeline be paired by the coordinator by itself. Check with `darkbloom status`." A `darkbloom cluster stop` from any window or either Mac ends the wait at once with "Stopped (by `darkbloom cluster stop` on one of the Macs): the pair - isn't starting any more." The Mac that joined says the same once the leading - Mac's status has stayed stopped for 20 seconds. + isn't starting any more." So does one while the leading Mac downloads or + copies the model (what arrived stays, and the next start goes on from + there), while both Macs load it, and at the test (`darkbloom stop` and + `restart` count too once the pair runs; before that, `darkbloom stop` stops + only what runs on its own Mac). The Mac + that joined says the same at once: the leading Mac counts each stop someone + asks for, and its status carries the count. A status that reads "Stopped" is + no stop on its own: it reads so through a whole download or copy, until both + parts start (0.10.9 to 0.10.12 took it for one after 20 seconds). An approval ends at its `not_after`, which the operator sets; one derived from a release ends 90 days after that release registered diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index ebef44677f..38ad1cd38d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -126,6 +126,12 @@ public struct ClusterSetupRecord: Codable, Sendable, Equatable { public var lastTestFailure: String? = nil /// The approval set aside while the pair serves locally (`ApprovalSetAside`); nil otherwise. public var approvalSetAside: ApprovalSetAside? = nil + /// How many stops a person asked for while this Mac led (`darkbloom cluster stop` on either Mac, and `darkbloom stop` + /// or `restart` once the pair runs, which the leading Mac runs: `OnboardingLive.stop`). The leading Mac's status + /// carries it (`ClusterControlReply.stopsAsked`), so a screen that follows a start ends on a stop only when this grew + /// since the start began (`ClusterOnboardingFollowedStop`). The start's own stops (a model change, the registration's + /// restart) and the cluster service's never count. Nil before the first. + public var stopsAsked: Int? = nil /// The cluster approval both Macs saved their setups without, and why (`ClusterApprovalCheck`): the leader checks /// the coordinator every minute while it is set, and does not take an approval its parts kept failing with again diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift index b21181c23e..d34dce0123 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift @@ -825,10 +825,15 @@ public struct ClusterControlRequest: Codable, Sendable, Equatable { /// `adopt`: the mode family chosen on the forwarding Mac's screen (a `ClusterForcedMode` raw value); nil keeps the /// listed plan's, and from an older build. public var mode: String? - public init(op: Operation, index: Int? = nil, model: String? = nil, scope: ClusterServingScope? = nil, mode: String? = nil) { + /// `serve`: the stops counted when the forwarding Mac's start began; the leading Mac doesn't serve once one more was + /// asked (`OnboardingLive.localServe(unlessStoppedSince:)`). Nil serves as before, and an older leader ignores it. + public var stopsBefore: Int? + public init(op: Operation, index: Int? = nil, model: String? = nil, scope: ClusterServingScope? = nil, mode: String? = nil, + stopsBefore: Int? = nil) { self.op = op; self.index = index; self.model = model; self.localOnly = scope.map(\.isLocalOnly); self.bind = scope?.localAPIBind self.localAPI = scope?.addsLocalAPI == true ? true : nil self.mode = mode + self.stopsBefore = stopsBefore } /// `scope`'s value; nil when it names none or an address the local API does not take. @@ -861,6 +866,16 @@ public struct ClusterControlReply: Codable, Sendable, Equatable { /// `status`: how far the leading Mac's start is (`ClusterOnboardingStartProgress`); nil when no start runs, and from /// an older build. public var start: ClusterOnboardingStartProgress? = nil + /// `status`: how many stops a person asked for on the leading Mac (`ClusterSetupRecord.stopsAsked`, 0 before the + /// first); nil from an older build. An older Mac ignores it. + public var stopsAsked: Int? = nil +} + +extension ClusterOnboardingLeaderStatus { + /// The leading Mac's status as its reply carries it, on the Mac that forwarded the `status` (`OnboardingLive.leaderStatus`). + public init(reply: ClusterControlReply) { + self.init(lines: reply.lines, step: reply.step, start: reply.start, stopsAsked: reply.stopsAsked) + } } public enum ClusterControlRouting { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index e6161fca80..46ca90a7ab 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -1515,6 +1515,14 @@ public struct ClusterOnboardingOperations: Sendable { /// Publishes how far the start is (`ClusterOnboardingStartProgress`) in the leading Mac's status, so the Mac that /// joined shows the same step; nil clears it. Not in `init`: only the live operations set it. public var publishStart: @Sendable (ClusterOnboardingStartProgress?) -> Void = { _ in } + /// How many stops a person asked for (`darkbloom cluster stop`, and `darkbloom stop` or `restart` once the pair runs, + /// on either Mac), as the leading Mac counts them (`ClusterSetupRecord.stopsAsked`); nil when that can't be read, and + /// from an older build. Not in `init`: only the live operations set it. + public var stopsAsked: @Sendable () -> Int? = { nil } + /// `serve`, unless a stop was asked since the count was `stopsBefore` (checked on the leading Mac under the lock its + /// start takes, so a stop that took the lock first is never undone): then a failure marked `stopped`. Nil: `serve`. + /// Not in `init`: only the live operations set it. + public var serveUnlessStopped: (@Sendable (_ stopsBefore: Int?) -> Result<[String], ClusterOnboardingFailure>)? = nil /// The rank this Mac's part runs in the saved setup (each screen names its own part "This Mac"); nil when unknown. /// Not in `init`: only the live operations set it. public var thisRank: @Sendable () -> Int? = { nil } @@ -2841,7 +2849,7 @@ public enum ClusterOnboardingDriver { // A model a Mac has no room for on disk now, or that cannot be copied or downloaded here, is refused before // anything is asked or stopped, in `provision`'s one wording. if let offer = choice.provision, offer.blocker != nil { - _ = provision(offer, title: choice.title, index: chosen!, operations, console) + _ = provision(offer, title: choice.title, index: chosen!, stopsBefore: nil, operations, console) return 1 } // How both Macs split it, chosen for the person (`ClusterOnboardingMode.automaticIndex`; owner, 2026-11-11: "don't @@ -2890,11 +2898,20 @@ public enum ClusterOnboardingDriver { if privateImage, let line = choice.publicTraffic { console.say(" " + ClusterOnboardingMacName.sentence(line) + (line.hasSuffix(".") ? "" : ".")) } + // The start begins with the first of its steps the Mac that joined sees (`ClusterOnboardingLeaderStep.startBegun`), + // which carries the stops counted then: a stop someone asks for from then on is the start's, on both Macs, which + // compare with that same count (`ClusterOnboardingStopped`). + var stopsBefore: Int?, begun = false + func begin(_ step: ClusterOnboardingLeaderStep.Kind) { + if !begun { (stopsBefore, begun) = (operations.stopsAsked(), true) } + operations.publishStep(.init(step, stopsBefore: stopsBefore)) + } if let offer = choice.provision { - operations.publishStep(.init(.copy)) - switch provision(offer, title: choice.title, index: chosen!, operations, console) { - case .stopped: return 0 + begin(.copy) + switch provision(offer, title: choice.title, index: chosen!, stopsBefore: stopsBefore, operations, console) { + case .cancelled: return 0 case .failed: return 1 + case .stopAsked: return stoppedEnding(operations, console, transfer: true) case .done: // A model this Mac downloaded (or copied from the other Mac) is planned from its own files now. if offer.leaderDownloads { @@ -2911,9 +2928,10 @@ public enum ClusterOnboardingDriver { choice = again[index] chosen = index if let more = choice.provision { - switch provision(more, title: choice.title, index: index, operations, console) { - case .stopped: return 0 + switch provision(more, title: choice.title, index: index, stopsBefore: stopsBefore, operations, console) { + case .cancelled: return 0 case .failed: return 1 + case .stopAsked: return stoppedEnding(operations, console, transfer: true) case .done: break } } @@ -2937,7 +2955,7 @@ public enum ClusterOnboardingDriver { console.say("Nothing changed.") return 1 } - operations.publishStep(.init(.starting)) + begin(.starting) switch busy(console, "Sending the setup to the other Mac", { operations.adopt(index) }) { case .success: break case .failure(let failure): @@ -2961,13 +2979,38 @@ public enum ClusterOnboardingDriver { guard clearVersionSplit(operations.versionSplit(), operations, console) else { return 1 } // Single-Mac serving on either Mac never ends by itself: said once, before anything starts, never waited for. guard clearSoloServing(operations.soloServing(), operations, console) else { return 1 } - switch busy(console, "Starting both Macs", operations.serve) { - case .success: break + // A count that couldn't be read when the start began (the leading Mac didn't answer) is read now, so a stop from + // here on still ends the start. + if stopsBefore == nil { stopsBefore = operations.stopsAsked() } + if let ended = startBothMacs(since: stopsBefore, operations, console) { return ended } + return finishStart(title: choice.title, scope: scope, startOverRequest: startOverRequest, peer: peer, stopsBefore: stopsBefore, + operations, console) + } + + /// Starts both Macs for the start whose stops were counted `stopsBefore`, unless a stop was asked since (while the + /// model downloaded or copied, a login or a question was asked, say): the pair then stays stopped and the screen ends + /// as the Mac that joined does (`ClusterOnboardingFollowedStop`). The leading Mac checks again under the lock its start + /// takes (`serveUnlessStopped`), for a stop that lands just now. Nil once both Macs were asked to serve; else the end. + static func startBothMacs(since stopsBefore: Int?, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> Int32? { + if stopAsked(since: stopsBefore, operations) { return stoppedEnding(operations, console) } + switch busy(console, "Starting both Macs", { operations.serveUnlessStopped?(stopsBefore) ?? operations.serve() }) { + case .success: return nil + case .failure(let failure) where failure.stopped: return stoppedEnding(operations, console) case .failure(let failure): for line in failure.lines { console.say(" " + line) } return 1 } - return finishStart(title: choice.title, scope: scope, startOverRequest: startOverRequest, peer: peer, operations, console) + } + + /// The screen's end on a stop someone asked for (`ClusterOnboardingStopped`), with nothing of its start published any + /// more. `transfer`: it ended a download or copy, which the next start goes on with. + static func stoppedEnding(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, transfer: Bool = false) -> Int32 { + operations.publishStart(nil) + console.settle() + console.say(ClusterOnboardingCommand.named(ClusterOnboardingStopped.line)) + if transfer { console.say(" " + ClusterOnboardingStopped.transferKeptLine) } + return 1 } /// Serving through Darkbloom needs every Mac logged in: the coordinator pairs only Macs logged in to one account. @@ -3014,15 +3057,18 @@ public enum ClusterOnboardingDriver { /// `registers`: a pair on the leader's API is registered with the coordinator after its test (a start, and the /// switch to Darkbloom, which is one; not the switch to local only or the serving model's Retry). `startOverRequest`: as `chooseAndServe`'s, kept for /// Change model, so a Mac paired before this run keeps its choices when the other Mac stops answering. + /// `stopsBefore`: the stops counted when the start began (`chooseAndServe`); nil reads them now. One more ends the + /// start's waits at once (`endsOnStopAsked`). static func finishStart(title: String, scope: ClusterServingScope, registers: Bool = true, - startOverRequest: ClusterOnboardingRequest? = nil, peer: String? = nil, + startOverRequest: ClusterOnboardingRequest? = nil, peer: String? = nil, stopsBefore: Int? = nil, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Int32 { var mayRegister = registers + var stopsBefore = stopsBefore ?? operations.stopsAsked() // The screen's start marks itself until its test is answered (through Darkbloom, until the coordinator decides), // so the leading Mac publishes its outcome and the Mac that joined ends with the same. if registers { operations.markRegistrationPending() } while true { - let outcome = startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) + let outcome = startOutcome(title: title, scope: scope, stopsBefore: stopsBefore, mayRegister: &mayRegister, operations, console) // The start's steps are over (left: they go on by themselves, and the published figures age out). A pair that // doesn't serve publishes its ✗ in their place below, with no gap between them where the Mac that joined would // read no start and show the status' ✗ without its next step. @@ -3044,9 +3090,7 @@ public enum ClusterOnboardingDriver { console.waitForExit() return 1 case .stopped: - console.settle() - console.say(ClusterOnboardingCommand.named(ClusterOnboardingStopped.line)) - return 1 + return stoppedEnding(operations, console) case .leftPairWait: console.settle() console.say(ClusterOnboardingCommand.named(ClusterOnboardingStopped.leftPairWaitLine)) @@ -3054,17 +3098,12 @@ public enum ClusterOnboardingDriver { case .versionSplit(let split): guard clearVersionSplit(split, operations, console), clearSoloServing(operations.soloServing(), operations, console) else { return 1 } - if case .failure(let failure) = busy(console, "Starting both Macs", operations.serve) { - for line in failure.lines { console.say(" " + line) } - return 1 - } + // The same start goes on (the Mac that joined still follows it): a stop asked meanwhile stands. + if let ended = startBothMacs(since: stopsBefore, operations, console) { return ended } continue case .soloServing(let serving): guard clearSoloServing(serving, operations, console) else { return 1 } - if case .failure(let failure) = busy(console, "Starting both Macs", operations.serve) { - for line in failure.lines { console.say(" " + line) } - return 1 - } + if let ended = startBothMacs(since: stopsBefore, operations, console) { return ended } continue case .notServing(let lines): // The start's outcome, published so the Mac that joined ends with the same ✗ and points to Retry here. @@ -3074,15 +3113,16 @@ public enum ClusterOnboardingDriver { case .retry: // The versions first: a Retry of a pair split across versions would only end the same way. guard clearVersionSplit(operations.versionSplit(), operations, console) else { return 1 } + // Retry is a new start (the Mac that joined ended on the published ✗): a stop from here on is its own, and + // its step says the count it began with, for a joining Mac that follows it now. + stopsBefore = operations.stopsAsked() + operations.publishStep(.init(.starting, stopsBefore: stopsBefore)) // A pair stopped meanwhile (`cluster stop --service` on a Mac): Retry starts it again and says so, instead // of waiting for parts nothing would start (the pair-2 run, P2-4). if operations.status().first?.hasPrefix("Stopped") == true { guard clearSoloServing(operations.soloServing(), operations, console) else { return 1 } console.say(" The pair is stopped: starting both Macs again.") - if case .failure(let failure) = busy(console, "Starting both Macs", operations.serve) { - for line in failure.lines { console.say(" " + line) } - return 1 - } + if let ended = startBothMacs(since: stopsBefore, operations, console) { return ended } } // A start asks Darkbloom again for a pair that isn't offered (it may serve an approval now). mayRegister = registers @@ -3129,10 +3169,10 @@ public enum ClusterOnboardingDriver { /// Waits for the started parts; a pair offered for pairing then for the coordinator to pair both Macs and load the /// model there (registered is not serving); a pair on the leader's API is tested, then registered with the /// coordinator when it serves a cluster approval (once per start: both parts then start again and are awaited). - static func startOutcome(title: String, scope: ClusterServingScope, mayRegister: inout Bool, + static func startOutcome(title: String, scope: ClusterServingScope, stopsBefore: Int?, mayRegister: inout Bool, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> StartOutcome { let ready: ClusterOnboardingReady - switch waitForParts(title: title, operations, console) { + switch waitForParts(title: title, stopsBefore: stopsBefore, operations, console) { case .success(let value)?: ready = value case .failure(let failure)? where failure.stopped: return .stopped case .failure(let failure)? where failure.versionSplit != nil: return .versionSplit(failure.versionSplit!) @@ -3142,24 +3182,31 @@ public enum ClusterOnboardingDriver { } let tested: String? if ready.offered != nil { - switch awaitPairServing(title: title, operations, console) { + switch awaitPairServing(title: title, stopsBefore: stopsBefore, operations, console) { case .success(let test)?: tested = test case .failure(let failure)? where failure.stopped: return .stopped case .failure(let failure)?: return .notServing(failure.lines) case nil: return .leftPairWait } } else { - // The test's time is said in the outcome block; only a failure is said here. + // The test's time is said in the outcome block; only a failure is said here. A stop asked meanwhile is the + // outcome whatever the test said, as on the Mac that joined: the parts it tested are stopped. operations.publishStart(.init(.testing)) switch busy(console, "Sending a test request", operations.testRequest) { case .success(let lines): tested = lines.first.flatMap { $0.isEmpty ? nil : $0 } + case .failure where stopAsked(since: stopsBefore, operations): return .stopped case .failure(let failure): for line in failure.lines { console.say(" " + line) } return .testFailed } + if stopAsked(since: stopsBefore, operations) { return .stopped } if mayRegister, !scope.isLocalOnly { mayRegister = false - if register(title: title, operations, console) { return startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) } + if register(title: title, operations, console) { + return startOutcome(title: title, scope: scope, stopsBefore: stopsBefore, mayRegister: &mayRegister, operations, console) + } + // A pair stopped since its start is neither registered nor started again (`OnboardingLive.localRegister`). + if stopAsked(since: stopsBefore, operations) { return .stopped } } // Set to serve through Darkbloom, but not offered after the registration (the coordinator serves no approval // for it, or the check refused it): a pair on the leading Mac's API never earns, so this ends with ✗, never @@ -3266,12 +3313,28 @@ public enum ClusterOnboardingDriver { /// A pair offered for pairing: waits for the coordinator to pair both Macs and both to load the model, its progress /// live; the pair's first request's time ("in 0.84 s"), or why it does not serve. /// Nil when the person left it (q or Esc): the pair keeps trying by itself (DevNet, 2026-11-05: q did nothing here). - static func awaitPairServing(title: String, _ operations: ClusterOnboardingOperations, + static func awaitPairServing(title: String, stopsBefore: Int?, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Result? { - waitWithRows("Serving \(title) through Darkbloom", console, leaving: leaves, operations.pairServing)? + waitWithRows("Serving \(title) through Darkbloom", console, leaving: leaves, ending: endsOnStopAsked(since: stopsBefore, operations), + operations.pairServing)? .map { $0.first.flatMap { $0.isEmpty ? nil : $0 } } } + /// A stop someone asked for since the start's count was `stopsBefore`, as the leading Mac counts them now + /// (`ClusterOnboardingStopped.asked`). It may ask the other Mac over the cable. + static func stopAsked(since stopsBefore: Int?, _ operations: ClusterOnboardingOperations) -> Bool { + ClusterOnboardingStopped.asked(since: stopsBefore, now: operations.stopsAsked()) + } + + /// The start's waits end at once on a stop someone asked for since the start began (`stopsBefore`): the parts are + /// stopped and nothing starts them again. The pair's own stops aren't counted (the registration's, the cluster + /// service's), so a wait goes on through them. Nil without a count to compare with: nothing to ask. + static func endsOnStopAsked(since stopsBefore: Int?, _ operations: ClusterOnboardingOperations) + -> (@Sendable () -> Result?)? { + guard stopsBefore != nil else { return nil } + return { stopAsked(since: stopsBefore, operations) ? .failure(.stopped) : nil } + } + /// How the pair serves, at the end of the serving line: nothing for a pair offered for pairing (its own line says /// through Darkbloom once the coordinator has it), else local only. A pair on the serving Mac's API is never offered, /// whatever its scope, so it never earns through Darkbloom (DevNet, 2026-11-04: "earning through Darkbloom" followed @@ -3300,9 +3363,10 @@ public enum ClusterOnboardingDriver { /// Waits for the started cluster's parts with their progress as the live rows. /// Nil when the person left it (q, Esc or Ctrl-C): the parts go on starting by themselves (P2-4: q was ignored). - static func waitForParts(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) + static func waitForParts(title: String, stopsBefore: Int?, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Result? { - waitWithRows("Loading \(title) on both Macs", console, leaving: leaves, operations.waitReady) + waitWithRows("Loading \(title) on both Macs", console, leaving: leaves, ending: endsOnStopAsked(since: stopsBefore, operations), + operations.waitReady) } /// Said when the person leaves the start's wait. @@ -3317,8 +3381,11 @@ public enum ClusterOnboardingDriver { waitWithRows(title, console, leaving: { _ in false }, work)! } - /// The same, left (nil) at a key `leaving` takes; the work then goes on by itself. + /// The same, left (nil) at a key `leaving` takes; the work then goes on by itself. `ending`, asked about once a second + /// off the console's thread (it may ask the other Mac over the cable), ends the wait with the value it gives; the work + /// goes on by itself then too. static func waitWithRows(_ title: String, _ console: ClusterOnboardingConsole, leaving: (Character) -> Bool, + ending: (@Sendable () -> Value?)? = nil, _ work: @escaping @Sendable (_ progress: @escaping @Sendable (String) -> Void) -> Value) -> Value? { let progress = ClusterOnboardingMailbox() @@ -3328,6 +3395,7 @@ public enum ClusterOnboardingDriver { var clock = ClusterOnboardingLoadRows(started: Date()) // A plain window shows no live rows: each Mac's row is said once as it changes. var said = Set() + let ends = ending.map { ClusterOnboardingLooker($0) } while true { for line in progress.take() { latest = line @@ -3335,16 +3403,19 @@ public enum ClusterOnboardingDriver { for row in line.components(separatedBy: "\n").dropFirst() where !row.isEmpty && said.insert(row).inserted { console.say(" " + row) } } if let value = finished.take().first { console.settle(); return value } + if let end = ends?.poll().compactMap({ $0 }).first { console.settle(); return end } console.workingRows(clock.rows(title, report: latest, now: Date(), width: console.liveWidth)) if let key = console.key(milliseconds: 120), leaving(key) { console.settle(); return nil } } } - enum ProvisionOutcome { case done, stopped, failed } + /// `cancelled`: the person chose Cancel (nothing changed). `stopAsked`: a stop someone asked for since the start + /// began (`stopsBefore`) ended the transfer's screen. + enum ProvisionOutcome { case done, cancelled, failed, stopAsked } /// Asks once how the chosen model reaches the Mac that lacks it (the recommended way first, the list saying what - /// moves), and moves it with progress. - static func provision(_ offer: ClusterOnboardingProvisionOffer, title: String, index: Int, + /// moves), and moves it with progress. `stopsBefore`: the stops counted when the start began (`chooseAndServe`). + static func provision(_ offer: ClusterOnboardingProvisionOffer, title: String, index: Int, stopsBefore: Int?, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ProvisionOutcome { if let blocker = offer.blocker { console.say("Can't start \(title): \(blocker). Free space, then run `darkbloom cluster` again.") @@ -3357,9 +3428,9 @@ public enum ClusterOnboardingDriver { let options = [get] + (offer.downloadAlternative ? ["Download"] : []) + ["Cancel"] guard let answer = console.choose(options, selected: 0), answer != options.count - 1 else { console.say("Nothing changed.") - return .stopped + return .cancelled } - return move(index: index, download: offer.downloadAlternative && answer == 1, operations, console) + return move(index: index, download: offer.downloadAlternative && answer == 1, stopsBefore: stopsBefore, operations, console) } /// "about 3 s", "about 2 min" (as `ClusterModelProvisioning.duration`, which this file does not link). @@ -3368,8 +3439,10 @@ public enum ClusterOnboardingDriver { } /// Moves the chosen model until it is done or failed. Its progress is one live line where the console shows - /// one; a transcript keeps the lines and the logged reports. - static func move(index: Int, download: Bool, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ProvisionOutcome { + /// one; a transcript keeps the lines and the logged reports. A stop someone asks for ends it at once (`stopAsked`), as + /// on the Mac that joined: what arrived stays, and the next start goes on from there. + static func move(index: Int, download: Bool, stopsBefore: Int?, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> ProvisionOutcome { let progress = ClusterOnboardingMailbox() let finished = ClusterOnboardingMailbox>() let chosenDownload = download @@ -3389,9 +3462,11 @@ public enum ClusterOnboardingDriver { } } var result: Result<[String], ClusterOnboardingFailure>? + let stops = stopsBefore.map { _ in ClusterOnboardingLooker { stopAsked(since: stopsBefore, operations) } } while result == nil { show() if let value = finished.take().first { result = value; break } + if stops?.poll().contains(true) == true { console.settle(); return .stopAsked } // The petal keeps turning while a step reports nothing new (the check of every file after a download). if let live { console.progress(live, logged: false) } _ = console.key(milliseconds: 200) @@ -3440,3 +3515,25 @@ final class ClusterOnboardingMailbox: @unchecked Sendable { return items } } + +/// Asks `look` on a thread of its own, one look at a time and at most once a second, so a look that may ask the other +/// Mac over the cable (how many stops were asked, in the start's waits and its transfer: `endsOnStopAsked`, `move`) +/// never holds up the console. +final class ClusterOnboardingLooker: @unchecked Sendable { + private let answers = ClusterOnboardingMailbox() + private let look: @Sendable () -> Value + private var asking = false, asked = Date.distantPast + + init(_ look: @escaping @Sendable () -> Value) { self.look = look } + + /// The answers that came since the last call; asks again when it is due. Only the console's thread calls it. + func poll() -> [Value] { + let came = answers.take() + if !came.isEmpty { asking = false } + if !asking, Date().timeIntervalSince(asked) >= 1 { + (asking, asked) = (true, Date()) + Thread.detachNewThread { [answers, look] in answers.post(look()) } + } + return came + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFollow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFollow.swift index fa701ba1dd..38883844d1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFollow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFollow.swift @@ -51,10 +51,6 @@ extension ClusterOnboardingDriver { "If it still doesn't start, run `darkbloom --version` on both Macs; if they differ, run `darkbloom update` on the one that's behind."] } - /// How long the leading Mac's status must stay Stopped, once its start began, before the Mac that joined takes it - /// as a stop from anywhere. - static let stoppedHoldSeconds: Double = 20 - /// After the version split's ✗ on the Mac that joined. static func versionSplitAfterLine(_ leader: String?) -> String { ClusterOnboardingCommand.named("Once both Macs run the same version, run `darkbloom cluster` on \(ClusterOnboardingMacName.other(named: leader)) again; this Mac follows it by itself.") @@ -202,7 +198,10 @@ extension ClusterOnboardingDriver { // The two Macs' versions, read on the looks' cadence: a split never clears by itself, so the wait ends at once. let splits = ClusterOnboardingMailbox() var splitAsking = false, splitAsked = Date.distantPast - var stoppedSince: Date? + // A stop a person asked for since the start began, by the leading Mac's count, never by its status' words. The start + // began at its first step on the leading Mac (`ClusterOnboardingLeaderStep.startBegun`), as that Mac counts from + // there too, or at its first progress or started status. + var stops = ClusterOnboardingFollowedStop(), startBegan = false while true { if !splitAsking, Date().timeIntervalSince(splitAsked) >= timing.pollSeconds { (splitAsking, splitAsked) = (true, Date()) @@ -218,15 +217,6 @@ extension ClusterOnboardingDriver { return 1 } } - // A stop from anywhere once the start began ends the wait: the leading Mac's status stays Stopped (a start - // reads Stopped for a moment while it stops the old setup or restarts the parts to register, never this long). - let stoppedNow = (started != nil || start != nil) && start?.phase != .stopping && lastStatus?.hasPrefix("Stopped") == true - stoppedSince = stoppedNow ? stoppedSince ?? Date() : nil - if let since = stoppedSince, Date().timeIntervalSince(since) >= Self.stoppedHoldSeconds { - console.settle() - console.say(ClusterOnboardingCommand.named(ClusterOnboardingStopped.line)) - return 1 - } if !asking, Date().timeIntervalSince(asked) >= timing.pollSeconds { asking = true asked = Date() @@ -283,6 +273,15 @@ extension ClusterOnboardingDriver { } let seen = followed(status) if started == nil, seen != .notStarted { started = Date() } + // A stop from anywhere once the start began ends the wait at once, as on the leading Mac. Its status + // reading "Stopped" is none: it reads so through a download or copy of the model, until both parts start, + // and while the start stops them to register. + startBegan = startBegan || started != nil || start != nil || step?.startBegun == true + if stops.look(look.stopsAsked, begun: startBegan, startStops: step?.startBegun == true ? step?.stopsBefore : nil) { + console.settle() + console.say(ClusterOnboardingCommand.named(ClusterOnboardingStopped.line)) + return 1 + } // Each stage has the whole bound, as on the leading Mac (its load, its test and check, its restart). let next = followStage(status, after: stage) if started != nil, next > stage { stage = next; started = Date() } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLeaderStep.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLeaderStep.swift index 20b66bc68a..42040e6cab 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLeaderStep.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLeaderStep.swift @@ -36,9 +36,13 @@ public struct ClusterOnboardingLeaderStep: Codable, Sendable, Equatable { public var reason: String? /// The leading Mac's Darkbloom version, when it said it. public var version: String? + /// `copy`, `starting` (`startBegun`): the stops the leading Mac counted when its start began + /// (`ClusterSetupRecord.stopsAsked`), so the Mac that joined compares with the same count. Nil when it couldn't be + /// read, and from an older build. + public var stopsBefore: Int? - public init(_ kind: Kind, reason: String? = nil, version: String? = nil) { - self.kind = kind; self.reason = reason; self.version = version + public init(_ kind: Kind, reason: String? = nil, version: String? = nil, stopsBefore: Int? = nil) { + self.kind = kind; self.reason = reason; self.version = version; self.stopsBefore = stopsBefore } /// The planner's blocker when the two Macs' cluster workers differ (`ClusterSetupPlanning.differentBuilds`). @@ -47,6 +51,10 @@ public struct ClusterOnboardingLeaderStep: Codable, Sendable, Equatable { /// The refusal of every model because the two Macs run different builds. public var differentBuilds: Bool { kind == .refused && reason == Self.differentBuildsReason } + /// The leading Mac's start began at this step: a model was chosen, and its transfer (`copy`) or the start itself + /// (`starting`) is next. A stop someone asks for from then on is that start's, on both Macs (`ClusterOnboardingStopped`). + public var startBegun: Bool { kind == .copy || kind == .starting } + /// What the leading Mac is doing, after "the other Mac: "; nil when there is nothing to say. public var words: String? { switch kind { @@ -123,7 +131,10 @@ public struct ClusterOnboardingLeaderStatus: Sendable, Equatable { public var step: ClusterOnboardingLeaderStep? /// How far its start is (`ClusterOnboardingStartProgress`); nil before it starts, and from an older build. public var start: ClusterOnboardingStartProgress? - public init(lines: [String], step: ClusterOnboardingLeaderStep?, start: ClusterOnboardingStartProgress? = nil) { - self.lines = lines; self.step = step; self.start = start + /// How many stops a person asked for there (`ClusterSetupRecord.stopsAsked`, 0 before the first); nil when the status + /// couldn't be read, and from an older build. + public var stopsAsked: Int? + public init(lines: [String], step: ClusterOnboardingLeaderStep?, start: ClusterOnboardingStartProgress? = nil, stopsAsked: Int? = nil) { + self.lines = lines; self.step = step; self.start = start; self.stopsAsked = stopsAsked } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 91f30cad0d..07115f1606 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -74,6 +74,8 @@ extension ClusterOnboardingOperations { made.stopSoloServing = { live.stopSoloServing() } made.markSoloBlocked = { live.markSoloBlocked($0) } made.publishStart = { live.publishStart($0) } + made.stopsAsked = { live.stopsAsked() } + made.serveUnlessStopped = { live.serve(unlessStoppedSince: $0) } made.thisRank = { live.context.savedConfiguration().configuration?.localRank } made.servesThroughDarkbloom = { live.leadership?.scope.isLocalOnly != true } return made @@ -394,9 +396,16 @@ final class OnboardingLive: @unchecked Sendable { /// The leader's half: one forwarded command, run here as `darkbloom cluster` would run it on this Mac. func execute(_ request: ClusterControlRequest, leaderID: String) -> ClusterControlReply { - var reply = answeringForwarded { executeForwarded(request, leaderID: leaderID) } - // The status carries how far the start is, for the Mac that joined (an older Mac ignores it). - if request.op == .status { reply.start = currentStart() } + let reply = answeringForwarded { executeForwarded(request, leaderID: leaderID) } + return request.op == .status ? followerStatus(reply) : reply + } + + /// A status reply with what the Mac that joined follows a start by: how far the start is and how many stops a person + /// asked for (an older Mac ignores both). + func followerStatus(_ reply: ClusterControlReply) -> ClusterControlReply { + var reply = reply + reply.start = currentStart() + reply.stopsAsked = currentStopsAsked() return reply } @@ -452,8 +461,8 @@ final class OnboardingLive: @unchecked Sendable { case .adopt: return lines(localAdopt(request.index ?? -1, model: request.model, scope: request.scope, family: request.mode.flatMap(ClusterForcedMode.init(rawValue:)))) - case .serve: return lines(localServe()) - case .stop: return lines(localStop()) + case .serve: return lines(localServe(unlessStoppedSince: request.stopsBefore)) + case .stop: return lines(localStop(asked: true)) case .readiness: let once = readinessOnce() if once.ready == nil { publishStart(.init(.loading, parts: once.parts), every: 1) } @@ -1447,7 +1456,10 @@ final class OnboardingLive: @unchecked Sendable { /// and both parts start again as cluster members. func localRegister() -> Result<[String], ClusterOnboardingFailure> { defer { clearRegistrationPending() } - guard leadership?.scope.isLocalOnly != true else { return .success([]) } + // A pair stopped since it was started (a stop someone asked for during its test took the command lock first, or + // single-Mac serving took this Mac back) is neither registered nor started again: the stop stands. + let leadership = self.leadership + guard leadership?.scope.isLocalOnly != true, leadership?.serving == true else { return .success([]) } let providerConfiguration = settings.service.wizard.providerConfiguration guard let saved = try? ClusterApprovalAttachment.savedSetup(paths: context.paths, providerConfiguration: providerConfiguration), let fetched = ClusterApprovalFetch.fetchBlocking(providerConfiguration: providerConfiguration), @@ -1502,11 +1514,17 @@ final class OnboardingLive: @unchecked Sendable { body: try JSONEncoder().encode(command), seconds: seconds).reply } - func serve() -> Result<[String], ClusterOnboardingFailure> { + /// `stopsBefore`: the stops counted when the screen's start began (`ClusterOnboardingOperations.serveUnlessStopped`); + /// one asked since keeps the pair stopped, a failure marked `stopped`. Nil serves as before. + func serve(unlessStoppedSince stopsBefore: Int? = nil) -> Result<[String], ClusterOnboardingFailure> { // The person starts the pair from this Mac: a choice of single-Mac serving made here before no longer stands. ClusterSoloChoice.clear(in: store.paths.directory) markSoloBlocked(false) - return routed(.init(op: .serve), acting: true, local: { localServe() }) { $0.lines } + let served = routed(.init(op: .serve, stopsBefore: stopsBefore), acting: true, + local: { localServe(unlessStoppedSince: stopsBefore) }) { $0.lines } + // A forwarded start refused for that reason comes back as its line only. + if case .failure(let failure) = served, failure.lines == ClusterOnboardingFailure.stopped.lines { return .failure(.stopped) } + return served } /// The screen's start through Darkbloom, which asks the coordinator after its test whether to offer the pair @@ -1678,7 +1696,10 @@ final class OnboardingLive: @unchecked Sendable { return (try? JSONDecoder().decode(ClusterServiceStatus.self, from: command(.init(op: .status), seconds: 10)))?.child.starts } - func localServe() -> Result<[String], ClusterOnboardingFailure> { + /// `stopsBefore` (`serve(unlessStoppedSince:)`): a stop someone asked for since then keeps the pair stopped, never + /// undone here. Every stop takes the command lock this start holds, so one that took it first is seen. Nil: none. + func localServe(unlessStoppedSince stopsBefore: Int? = nil) -> Result<[String], ClusterOnboardingFailure> { + if ClusterOnboardingStopped.asked(since: stopsBefore, now: currentStopsAsked()) { return .failure(.stopped) } guard (try? store.readRecord().stopDrain) == nil else { return .failure(.init("\(Self.sentence(hereShort)) is still finishing a stop. Run `\(Self.cli) cluster stop` again before serving.")) } @@ -2214,14 +2235,14 @@ final class OnboardingLive: @unchecked Sendable { static let pairReasonSettleSeconds: Double = 90 /// A pair offered for pairing: waits until the coordinator paired both Macs, both loaded the model and the pair - /// answered its first request (rank 0's part says so), or a reason the Macs know held (`pairLook`). + /// answered its first request (rank 0's part says so), or a reason the Macs know held (`pairLook`). A stop someone + /// asks for ends the screen's wait at once (`ClusterOnboardingDriver.endsOnStopAsked`); the pair's own stops (the cluster + /// service's approval change) don't, so this wait goes on through them. func pairServing(_ progress: @escaping @Sendable (String) -> Void) -> Result<[String], ClusterOnboardingFailure> { var wait = ClusterOnboardingPairWait(started: Date().timeIntervalSince1970, bound: Self.pairServingSeconds, settle: Self.pairReasonSettleSeconds) var said: String? while true { - // A stop from anywhere (`cluster stop` in another window, or on the other Mac) ends the wait at once. - if pairStopped() { return .failure(.stopped) } let look = pairLook() if look.serving { return .success([look.test ?? ""]) } // A login missing, a model the coordinator's catalog does not list, or an owner-only pair holds until a person acts. @@ -2283,10 +2304,6 @@ final class OnboardingLive: @unchecked Sendable { return (false, nil, progress, nil) } - /// The pair was stopped while a screen waits for it: this Mac's saved start is off (`cluster stop` here, or the - /// leading Mac's stop that reached it). - func pairStopped() -> Bool { leadership.map { !$0.serving } ?? false } - /// The Macs without a Darkbloom login, as this screen names them. func missingLogins() -> [String] { missingLogins(peer: try? JSONDecoder().decode(ClusterServiceStatus.self, from: command(.init(op: .status), seconds: 10))) @@ -2357,8 +2374,9 @@ final class OnboardingLive: @unchecked Sendable { var forwarded = false var look: ClusterOnboardingLeaderStatus switch routed(.init(op: .status), seconds: 30, acting: false, forwarding: { forwarded = true }, - local: { .success(ClusterOnboardingLeaderStatus(lines: localStatus(), step: currentLeaderStep(), start: currentStart())) }, - remote: { ClusterOnboardingLeaderStatus(lines: $0.lines, step: $0.step, start: $0.start) }) { + local: { .success(ClusterOnboardingLeaderStatus(lines: localStatus(), step: currentLeaderStep(), start: currentStart(), + stopsAsked: currentStopsAsked())) }, + remote: { ClusterOnboardingLeaderStatus(reply: $0) }) { case .success(let value): look = value case .failure(let failure): look = ClusterOnboardingLeaderStatus(lines: failure.lines, step: nil) } @@ -2389,6 +2407,13 @@ final class OnboardingLive: @unchecked Sendable { (try? store.readRecord())?.onboardingStep?.current(now: Date().timeIntervalSince1970, started: Self.processStarted) } + /// How many stops a person asked for while this Mac led (0 before the first), as the status publishes it when this + /// Mac leads; nil when its record can't be read. + func currentStopsAsked() -> Int? { (try? store.readRecord()).map { $0.stopsAsked ?? 0 } } + + /// The same, from the leading Mac: this Mac's record when it leads, else the leading Mac's status over the cable. + func stopsAsked() -> Int? { forwards ? leaderStatus().stopsAsked : currentStopsAsked() } + /// A model id as the screens name it: its catalog name, when the last catalog this Mac read has one. func modelTitle(_ modelID: String) -> String { let catalog = (ClusterModelStore.readSmall(store.paths.directory.appendingPathComponent("catalog.json")) @@ -2514,9 +2539,11 @@ final class OnboardingLive: @unchecked Sendable { + (Self.endedClause(mac: thereShort, child: member?.child) ?? "") } + /// A stop a person asked for (`darkbloom cluster stop`, and `darkbloom stop` or `restart` once the pair runs), on + /// either Mac: the leading Mac runs it and counts it (`ClusterSetupRecord.stopsAsked`). func stop() -> Result<[String], ClusterOnboardingFailure> { markSoloBlocked(false) - return routed(.init(op: .stop), seconds: 330, acting: true, local: { localStop() }) { $0.lines } + return routed(.init(op: .stop), seconds: 330, acting: true, local: { localStop(asked: true) }) { $0.lines } } func verifyTeardown() -> Result<[String], ClusterOnboardingFailure> { @@ -2543,24 +2570,31 @@ final class OnboardingLive: @unchecked Sendable { return mac + line[colon.lowerBound...] } - func localStop() -> Result<[String], ClusterOnboardingFailure> { - localStop(seconds: 300) { _ = try command(.init(op: .stop)) } + /// `asked`: a person asked for this stop (`stop`), never the start's own (a model change, the registration's restart) + /// nor the cluster service's. + func localStop(asked: Bool = false) -> Result<[String], ClusterOnboardingFailure> { + localStop(seconds: 300, asked: asked) { _ = try command(.init(op: .stop)) } + } + + /// A stop's first write: its drain custody and the stopped intent, with no published test result. A stop a person + /// asked for is counted too (`ClusterSetupRecord.stopsAsked`), in the same write, so a screen that reads the count + /// reads the pair as stopped too. + static func recordStop(_ record: inout ClusterSetupRecord, id: UUID, asked: Bool) { + record.stopDrain = .init(id: id, keepPeerRunning: record.leadership?.serving == true || record.stopDrain?.keepPeerRunning == true) + record.leadership?.serving = false + record.registrationPending = nil + clearTestResults(&record) + if asked { record.stopsAsked = (record.stopsAsked ?? 0) + 1 } } /// The transport remains separate from local process custody so every /// caller (CLI, model switch, or update) uses the same retirement ordering. - func localStop(seconds: Double, stopPeer: () throws -> Void) -> Result<[String], ClusterOnboardingFailure> { + func localStop(seconds: Double, asked: Bool = false, stopPeer: () throws -> Void) -> Result<[String], ClusterOnboardingFailure> { let stopID = UUID() // Named for the screen that shows the lines (the other Mac's, when it forwarded the stop). let mac = Self.sentence(hereShort), other = thereShort do { - try store.updateRecord { record in - record.stopDrain = .init(id: stopID, - keepPeerRunning: record.leadership?.serving == true || record.stopDrain?.keepPeerRunning == true) - record.leadership?.serving = false - record.registrationPending = nil - Self.clearTestResults(&record) - } + try store.updateRecord { Self.recordStop(&$0, id: stopID, asked: asked) } lock.withLock { partsStoppedAt = Date() } } catch { return .failure(.init("\(mac) could not save the stop request: \((error as? ClusterSetupFailure)?.text ?? "\(error)")")) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift index 9a65640bc5..a7ec3707d4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift @@ -393,11 +393,52 @@ public struct ClusterOnboardingPairWait: Sendable { } /// A stop from anywhere (`darkbloom cluster stop` in another window, or on the other Mac) while a screen waits for the -/// pair: the wait ends at once with this, on both Macs. +/// pair: the wait ends at once with this, on both Macs. The leading Mac counts each stop a person asks for +/// (`ClusterSetupRecord.stopsAsked`) and its status carries the count (`ClusterOnboardingLeaderStatus.stopsAsked`), so a +/// screen knows such a stop from the start's own: a status that reads "Stopped" tells nothing of who stopped. public enum ClusterOnboardingStopped { public static let line = "Stopped (by `darkbloom cluster stop` on one of the Macs): the pair isn't starting any more. " + "Run `darkbloom cluster` on the leading Mac to start it again." /// What a screen that leaves the coordinator's wait says: what keeps going, and how to check. public static let leftPairWaitLine = "Left the wait: both Macs stay registered and the pair keeps trying to be paired by " + "the coordinator by itself. Check with `darkbloom status`." + /// Under `line` on the leading Mac when the stop ended its download or copy of the model. + public static let transferKeptLine = "What was downloaded or copied so far stays: the next start goes on from there." + + /// A stop a person asked for since the count was `before`. A count not known then or now (a status that couldn't be + /// read, a leader on an older build, which counts none) never tells one. + public static func asked(since before: Int?, now: Int?) -> Bool { + guard let before, let now else { return false } + return now > before + } +} + +/// The stop the Mac that joined ends its follow on (`ClusterOnboardingDriver.followStart`): one a person asked for since +/// the start began. The leading Mac's status reads "Stopped" until both parts start, so through a whole download or copy +/// of the model, and again while the start stops both parts to register them: none of that is a stop (an external pair +/// on 0.10.12, 2026-11-12: the joining Mac said "Stopped (by `darkbloom cluster stop` …)" 20 s into a download nobody +/// stopped). Each look before the start began takes the count as the one to compare with, so a stop then (the leading +/// Mac still at its model list, whose start goes on) is no stop of this start. +public struct ClusterOnboardingFollowedStop: Sendable { + private var before: Int? + /// The count the leading Mac read when its start began, as its step carries it (`ClusterOnboardingLeaderStep.stopsBefore`). + private var startStops: Int? + + public init() {} + + /// One look at the leading Mac's status: the stops it counts (nil: not read, or a leader on an older build), whether + /// the start had begun by then, and the count its start began with when its step says it. True when a stop asked + /// since the start began ends it: compared with the leading Mac's own count where it says it, so both Macs count the + /// same stops, else with this Mac's last look before the start began. A count lower than before (a record made + /// again) is the one to compare with from then on. + public mutating func look(_ stopsAsked: Int?, begun: Bool, startStops: Int? = nil) -> Bool { + if let startStops { self.startStops = startStops } + guard let stopsAsked else { return false } + if begun, let startStops = self.startStops { return ClusterOnboardingStopped.asked(since: startStops, now: stopsAsked) } + guard begun, let before, stopsAsked >= before else { + self.before = stopsAsked + return false + } + return stopsAsked > before + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService+RestartingStop.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService+RestartingStop.swift index 5a567e9804..c152e1adc4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService+RestartingStop.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService+RestartingStop.swift @@ -2,9 +2,10 @@ import Foundation /// The control leader's automatic steps that stop the pair only to start it again: the re-plan after a Darkbloom update /// (`checkForUpdate`) and a change of the pair's cluster approval (`checkApproval`). Both keep three invariants: -/// - A failed stop never loses the pair's saved start. Their stop is a person's stop (`OnboardingLive.localStop`): it -/// clears the saved start before it stops anything. Both steps act only while the start is saved, and nothing else -/// starts a pair again, so every failure from the stop on, including the stop's own, puts it back (`restoreStart`). +/// - A failed stop never loses the pair's saved start. Their stop is the one a person's stop runs +/// (`OnboardingLive.localStop`, never counted as asked for: `ClusterSetupRecord.stopsAsked`): it clears the saved start +/// before it stops anything. Both steps act only while the start is saved, and nothing else starts a pair again, so +/// every failure from the stop on, including the stop's own, puts it back (`restoreStart`). /// - A stop the owner made is never undone. Every stop of the pair holds the control command lock (a person's, typed /// here or forwarded by the other Mac, and `releaseForSingleMac`'s), and once a step holds it, it stops and starts the /// pair only while the start is still saved: the re-plan reads it again (`commandLockIfStillStarted`), and the diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift index aa2bd37988..50129e70d9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift @@ -151,9 +151,13 @@ extension EngineV2Bridge { if !text.isEmpty { continuation.yield(.chunk(text)) } - if loopStop == nil, let detection = loopGuard?.observe(text: text, tokens: tokens) { + // The guard sees every delta, the in-flight ones after its stop + // included (a thought it ends resumes after all of them). + if let detection = loopGuard?.observe(text: text, tokens: tokens), loopStop == nil { loopStop = detection - stopRepeatingRow(id: id, modelType: loopGuard?.modelType, detection: detection) + stopRepeatingRow( + id: id, modelType: loopGuard?.modelType, detection: detection, + endsThought: loopGuard?.endsThought == true) } case .finished(let engineReason, let usage): // The guard's own stop is a complete answer cut at its length, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+LoopGuard.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+LoopGuard.swift index cacc65ac4b..b3a436d5f5 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+LoopGuard.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+LoopGuard.swift @@ -16,20 +16,27 @@ extension EngineV2Bridge { /// Stop the row in the engine, as a cancel does, but not as the caller's /// cancel: the pump turns the engine's cancelled terminal into a `length` /// finish with the tokens produced, so no `tokens_after_cancel` is taken. - func stopRepeatingRow(id: String, modelType: String?, detection: GenerationLoopDetector.Detection) { + /// `endsThought`: the loop was inside the reasoning channel and the + /// scheduler continues the answer after the thought + /// (`LoopExitThinkingContinuation`); the row itself ends the same way. + func stopRepeatingRow( + id: String, modelType: String?, detection: GenerationLoopDetector.Detection, endsThought: Bool = false + ) { if let cbv2Id = idMap[id] { ownedEngine?.cancel(cbv2Id) } #if canImport(os) // One line per stop: the model, its type, the period, the span and the tokens so far. Self.loopGuardLogger.notice( - "loop guard stopped \(id, privacy: .public): \(self.modelId, privacy: .public) (\(modelType ?? "?", privacy: .public)) period \(detection.period) span \(detection.span) at \(detection.generatedTokens)") + "loop guard stopped \(id, privacy: .public): \(self.modelId, privacy: .public) (\(modelType ?? "?", privacy: .public)) period \(detection.period) span \(detection.span) at \(detection.generatedTokens)\(endsThought ? "; it asks to end the thought and continue the answer" : "", privacy: .public)") #endif var event = TelemetryEvent( source: .provider, severity: .info, kind: .engineHealth, - message: "engine_v2: loop guard ended a repeating answer as length" + message: endsThought + ? "engine_v2: loop guard stopped a repeating thought and asks to continue the answer" + : "engine_v2: loop guard ended a repeating answer as length" ).withFields([ "component": .string("engine"), "operation": .string("engine_v2_loop_guard"), @@ -39,8 +46,52 @@ extension EngineV2Bridge { "period_tokens": .int(detection.period), "span_tokens": .int(detection.span), "generated_tokens": .int(detection.generatedTokens), + "ends_thought": .bool(endsThought), ]) event.requestId = id emit(event) } + + /// Waits until the row `requestId` has released its serving slot: its pump + /// ran its retirement cleanup (service allowance, KV reservation) and the + /// whole-Mac budget no longer charges it, as model calibration waits + /// (`runModelCalibrationCell`). A row with a retirement handle (atomic + /// deadline admission, the coordinator's path) ends its client stream + /// before that, so a continuation submitted at once would still count the + /// stopped row and, on a full Mac, be refused + /// (`LoopExitThinkingContinuation`). False when `bound` passes first: a + /// wedged row may never retire. + func waitForRowRelease(requestId: String, within bound: Duration) async -> Bool { + let pump = pumpTasks[requestId] + let budget = serviceBudget + let ownerID = serviceOwnerPrefix + ":" + requestId + return await withCheckedContinuation { (continuation: CheckedContinuation) in + let once = ResumeOnce(continuation) + Task { + await pump?.value + await budget?.waitForRelease(ownerID: ownerID) + once.resume(true) + } + Task { + try? await Task.sleep(for: bound) + once.resume(false) + } + } + } +} + +/// Resumes a continuation with the first of several racing results. +private final class ResumeOnce: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + + init(_ continuation: CheckedContinuation) { self.continuation = continuation } + + func resume(_ value: Bool) { + let pending = lock.withLock { () -> CheckedContinuation? in + defer { continuation = nil } + return continuation + } + pending?.resume(returning: value) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/MiMo/MiMoV26NativeLoadTransaction.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/MiMo/MiMoV26NativeLoadTransaction.swift index 1b537317f7..5436f28581 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/MiMo/MiMoV26NativeLoadTransaction.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/MiMo/MiMoV26NativeLoadTransaction.swift @@ -296,6 +296,7 @@ final class MiMoV26NativeLoadTransaction: @unchecked Sendable { private var nativeConstruction: UUID? private var slotAssemblyClaimed = false private var usageReaderPreparationHookForTesting: (@Sendable () -> Void)? + private var mediaReservationRemovalHookForTesting: (@Sendable () -> Void)? private var cancelled = false private var published = false private var draining = false @@ -1095,11 +1096,17 @@ final class MiMoV26NativeLoadTransaction: @unchecked Sendable { } private func removeSettledMediaReservation(_ reservation: MiMoV26ManagedMediaReservation) { guard reservation.isFullyRetired else { return } - lock.withLock { - if mediaReservations[reservation.id] === reservation { - mediaReservations.removeValue(forKey:reservation.id) - } + let removalHook = lock.withLock { () -> (@Sendable () -> Void)? in + guard mediaReservations[reservation.id] === reservation else { return nil } + mediaReservations.removeValue(forKey:reservation.id) + return mediaReservationRemovalHookForTesting } + removalHook?() + } + /// Observation only: runs outside the lock after each settled reservation + /// leaves the map. Test-only. + func setMediaReservationRemovalHookForTesting(_ hook: (@Sendable () -> Void)?) { + lock.withLock { mediaReservationRemovalHookForTesting = hook } } func registerDecodedMediaConsumer(_ lease: NativeLocalConsumerLease, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift new file mode 100644 index 0000000000..3dcd68dcdb --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift @@ -0,0 +1,233 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import Logging + +/// Continues an answer whose thought the loop guard ended. +/// +/// The bridge stops a row whose thought repeats verbatim exactly as it stops +/// any repeating row: the engine cancels it and its stream ends with a +/// `length` terminal. When the guard asked to end the thought instead +/// (`GenerationLoopExitRecord.requested`), this holds that terminal back, waits +/// for the row's stream to finish, and submits one continuation (its `submit` +/// first waits for the row to release its serving slot: +/// `EngineV2Bridge.waitForRowRelease`): the same prompt, every token the row +/// produced, then the family's end-of-thinking marker, with the output budget +/// the row left (at most `GenerationLoopExitThinking.answerTokenLimit`). The +/// client sees one answer: the thought, the marker, then the continuation's +/// text, and one terminal whose usage is the original prompt and every token +/// produced (the row's, the marker, the continuation's). +/// +/// Anything that keeps the continuation from starting (under +/// `minimumAnswerBudget` tokens of budget left, a row that closed its thought +/// itself, a row that did not release its slot in time, a refused submission, +/// a continuation that fails before its first token, a cancel) ends the answer +/// exactly as before: the held `length` terminal. A continuation that fails +/// after its first token ends the answer there, as `length`; only the client's +/// cancel keeps its error. +enum LoopExitThinkingContinuation { + typealias Submit = @Sendable (_ promptTokens: [Int], _ maxTokens: Int) async throws + -> AsyncStream + + /// What happened to one request whose loop guard ended its thought. + enum Outcome: Sendable, Equatable, CustomStringConvertible { + /// The continuation produced the answer's end (its own terminal). + case continued(continuationTokens: Int, finishReason: String?) + /// It did not start: the request ended as `length`, as before. + case endedAsLength(reason: String) + /// It started and then was cancelled. + case failedAfterStart + /// It started and then failed: the answer ends there, as `length`. + case cutAfterStart(reason: String) + + var description: String { + switch self { + case .continued(let tokens, let reason): "continued: \(tokens) answer tokens, \(reason ?? "no reason")" + case .endedAsLength(let reason): "ended as length: \(reason)" + case .failedAfterStart: "cancelled after the answer started" + case .cutAfterStart(let reason): "cut after the answer started: \(reason)" + } + } + } + + static let logger = Logger(label: "darkbloom.loop-guard.exit-thinking") + + /// The stopped row did not release its serving slot in time + /// (`EngineV2Bridge.waitForRowRelease`). + struct RowNotReleased: Error {} + + /// Below this answer budget the re-prefill of the whole thought is not + /// worth it: the request ends as `length`, as before. + static let minimumAnswerBudget = 256 + + /// The spliced stream and its cancel, which stops whichever row is running. + static func splice( + first: AsyncStream, + cancelFirst: @escaping @Sendable () async -> Void, + exit: GenerationLoopExitThinking, + promptTokens: [Int], + outputBudget: Int, + submit: @escaping Submit, + cancelContinuation: @escaping @Sendable () async -> Void, + onOutcome: (@Sendable (Outcome) -> Void)? = nil + ) -> (events: AsyncStream, cancel: @Sendable () async -> Void) { + let (events, out) = AsyncStream.makeStream() + let control = Control() + let task = Task { + await run( + first: first, out: out, control: control, exit: exit, promptTokens: promptTokens, + outputBudget: outputBudget, submit: submit, cancelContinuation: cancelContinuation, + onOutcome: onOutcome) + } + let cancel: @Sendable () async -> Void = { + let continuationStarted = control.cancel() + await cancelFirst() + if continuationStarted { await cancelContinuation() } + } + out.onTermination = { termination in + guard case .cancelled = termination else { return } + task.cancel() + Task { await cancel() } + } + return (events, cancel) + } + + private static func run( + first: AsyncStream, + out: AsyncStream.Continuation, + control: Control, + exit: GenerationLoopExitThinking, + promptTokens: [Int], + outputBudget: Int, + submit: Submit, + cancelContinuation: @Sendable () async -> Void, + onOutcome: (@Sendable (Outcome) -> Void)? + ) async { + // The row's own events; only the guard's `length` terminal is held. + var held: (prompt: Int, completion: Int, tokensPerSecond: Double)? + for await event in first { + if case .info(let prompt, let completion, let tps, let reason) = event, + reason == "length", exit.record.requested != nil { + held = (prompt, completion, tps) + continue + } + out.yield(event) + } + guard let held else { + out.finish() + return + } + func endAsLength(_ reason: String) { + out.yield(.info( + promptTokens: held.prompt, completionTokens: held.completion, + tokensPerSecond: held.tokensPerSecond, finishReason: "length")) + out.finish() + onOutcome?(.endedAsLength(reason: reason)) + } + let generated = exit.record.generatedTokens + // A row that closed its thought itself, in the tokens it produced + // after the stop, has no thought left to end. + if let detection = exit.record.requested, + generated.dropFirst(detection.generatedTokens).contains(where: exit.exitTokens.contains) { + return endAsLength("the row closed its thought itself") + } + let budget = min(outputBudget - held.completion - exit.exitTokens.count, exit.answerTokenLimit) + guard budget >= minimumAnswerBudget else { return endAsLength("output budget left \(max(0, budget))") } + guard !control.isCancelled, !Task.isCancelled else { return endAsLength("cancelled") } + let continuation: AsyncStream + do { + continuation = try await submit(promptTokens + generated + exit.exitTokens, budget) + } catch { + return endAsLength("continuation refused: \(error)") + } + guard control.markStarted() else { + await cancelContinuation() + return endAsLength("cancelled") + } + // Tokens the client is billed for before the continuation's own. + let carried = held.completion + exit.exitTokens.count + var started = false + // The continuation's last reported completion, for a failure after it started. + var answerTokens = 0 + // A failure after the answer started ends it as a cut `length`, as the + // guard's own stop would have; only a cancel keeps its error framing. + func endCut(_ reason: String, completion: Int) { + out.yield(.info( + promptTokens: held.prompt, completionTokens: carried + completion, + tokensPerSecond: held.tokensPerSecond, finishReason: "length")) + out.finish() + onOutcome?(.cutAfterStart(reason: reason)) + } + func start() { + guard !started else { return } + started = true + out.yield(.chunk(exit.exitText)) + } + for await event in continuation { + switch event { + case .chunk(let text): + start() + out.yield(.chunk(text)) + case .logprobs(let entries): + start() + out.yield(.logprobs(entries)) + case .info(_, let completion, let tps, let reason): + // A cancelled continuation reports its usage with no reason, + // then its error: before its first token that is a failure. + guard reason != nil || started else { continue } + start() + answerTokens = completion + if reason == nil, !control.isCancelled { + // Usage ahead of an error that is not the client's cancel: + // held for the cut `length` below. + continue + } + out.yield(.info( + promptTokens: held.prompt, completionTokens: carried + completion, + tokensPerSecond: tps, finishReason: reason)) + if reason != nil { + onOutcome?(.continued(continuationTokens: completion, finishReason: reason)) + } + case .error(let message): + guard started else { return endAsLength("continuation failed: \(message)") } + guard control.isCancelled else { return endCut(message, completion: answerTokens) } + out.yield(.error(message)) + onOutcome?(.failedAfterStart) + case .terminal(let cause, _, _, let completion): + guard started else { return endAsLength("continuation ended: \(cause.rawValue)") } + return endCut(cause.rawValue, completion: completion) + } + } + if !started { + return endAsLength(control.isCancelled ? "cancelled" : "continuation ended before its first token") + } + out.finish() + } + + /// Orders a cancel against the continuation's start: a cancel that wins + /// keeps it from starting; one that loses also stops the continuation. + final class Control: @unchecked Sendable { + private let lock = NSLock() + private var cancelled = false + private var started = false + + var isCancelled: Bool { lock.withLock { cancelled } } + + /// Returns whether the continuation already started. + func cancel() -> Bool { + lock.withLock { + cancelled = true + return started + } + } + + /// Returns false when a cancel came first. + func markStarted() -> Bool { + lock.withLock { + guard !cancelled else { return false } + started = true + return true + } + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 3943f9e627..e7ea281696 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1021,8 +1021,18 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // reasoning must already be a separate channel: validation sees only // the answer. let jsonAnswer = tokenConstraint as? JSONAnswerConstraint + // A loop inside the thought ends the thought, not the answer, on a + // single Mac's text row without logprobs (`GenerationLoopExitThinkingPolicy`). + var exitThinking = GenerationLoopExitThinkingPolicy.resolve( + modelType: modelType, tokenizer: tokenizer.inner, promptTokens: promptTokens, + logprobs: engineV2Logprobs != nil) + if exitThinking != nil, await engineV2Bridge?.servesDistributedPair != false { exitThinking = nil } let loopGuard = GenerationLoopGuardPolicy.resolve( - modelType: modelType, request: request, prepared: prepared, tokenConstraint: tokenConstraint) + modelType: modelType, request: request, prepared: prepared, tokenConstraint: tokenConstraint, + exitThinking: exitThinking) + let stopStringScope = ReasoningStopScope.scope( + reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix, + parsesToolCalls: toolHandler != nil) let requestId = "req-\(UUID().uuidString.prefix(12))" @@ -1065,9 +1075,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { cacheEnabled: cacheEnabled, usageSignal: requestUsage, tokenConstraint: tokenConstraint, - stopStringScope: ReasoningStopScope.scope( - reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix, - parsesToolCalls: toolHandler != nil), + stopStringScope: stopStringScope, donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1097,10 +1105,72 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { throw MultiModelBatchSchedulerEngineError.generationFailed( "internal error: model '\(modelId)' has no serving engine (no v2 bridge)") } + var events = upstream + var cancelEvents = cancelUpstream + if let exitThinking, loopGuard != nil, let bridge = engineV2Bridge { + // The answer after a thought the guard ended: one more engine row on + // the same slot, with the row's own tokens and the end of thinking. + let base = request + let continuationId = requestId + "-exit" + let defaultMaxTokens = defaultMaxTokens + let sampling = engineV2Sampling + let measurementPurpose = measurementPurpose + let cacheScope = requestCacheScope + let cacheEnabled = cacheEnabled + let donationDemand = donationDemand + let spliced = LoopExitThinkingContinuation.splice( + first: upstream, + cancelFirst: cancelUpstream, + exit: exitThinking, + promptTokens: promptTokens, + // The output the bridge resolved for the row, as it sized the + // row's service allowance. + outputBudget: bridge.outputTokens(requested: base.maxTokens, promptTokens: promptTokens.count), + submit: { continuationPrompt, budget in + // The stopped row's stream can end before it releases its + // serving slot (a row with a retirement handle): until then + // it still counts against the Mac's width. + guard await bridge.waitForRowRelease(requestId: requestId, within: .seconds(5)) else { + throw LoopExitThinkingContinuation.RowNotReleased() + } + var next = base + next.maxTokens = budget + // As model calibration submits: the request's prompt progress + // has ended, and the owner's make-room hook is the row's. + return try await LocalPrefillProgress.$current.withValue(nil) { + try await MeFirstOwnerRequest.$makeRoom.withValue(nil) { + try await bridge.submitTokenized( + promptTokens: continuationPrompt, + request: Self.translate( + openAIRequest: next, defaultMaxTokens: defaultMaxTokens, + logitBias: sampling?.logitBias, seed: sampling?.seed, + engineStopStrings: modelType != "flint"), + requestId: continuationId, + cacheScope: cacheScope, + cacheEnabled: cacheEnabled, + stopStringScope: stopStringScope, + donationDemand: donationDemand, + firstContentDeadline: nil, + measurementPurpose: measurementPurpose, + // A loop in the answer still ends it as `length`. + loopGuard: GenerationLoopGuardPolicy.resolve( + modelType: modelType, request: next, prepared: prepared, tokenConstraint: nil)) + } + } + }, + cancelContinuation: { await bridge.cancel(requestId: continuationId) }, + onOutcome: { outcome in + LoopExitThinkingContinuation.logger.notice( + "loop guard ended a thought", metadata: [ + "request_id": .string(requestId), "outcome": .string(outcome.description)]) + }) + events = spliced.events + cancelEvents = spliced.cancel + } return try await makeDeadlineCheckedEventStream( - upstream: upstream, - cancelUpstream: cancelUpstream, + upstream: events, + cancelUpstream: cancelEvents, toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox, diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift new file mode 100644 index 0000000000..c49856b7c5 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift @@ -0,0 +1,138 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon + +/// The loop guard's way out of a repeating thought. +/// +/// When the guard (`GenerationLoopGuard`) finds a verbatim loop while the row +/// is inside its reasoning channel, the row is stopped as before, and the +/// request then continues from the same tokens with the family's +/// end-of-thinking marker appended, so the model writes its answer instead of +/// ending with an empty one (`LoopExitThinkingContinuation`). A loop outside +/// the reasoning channel still ends as `length`. +public struct GenerationLoopExitThinking: Sendable { + /// Text that opens the reasoning channel in the generated stream. + let openMarker: String + /// Text that closes it. + let closeMarker: String + /// The tokens appended to end the thought: the close marker's token. + let exitTokens: [Int] + /// Their text, as the client's stream shows them. + let exitText: String + /// The prompt itself left the reasoning channel open. + let startsInside: Bool + /// Shared with the continuation: the row's tokens and the guard's request. + let record: GenerationLoopExitRecord + /// The most the answer after the thought may take, within the request's own + /// budget: a model that wrote a loop may write a near-verbatim one next, + /// which the guard does not see. + var answerTokenLimit = GenerationLoopExitThinkingPolicy.answerTokenLimit +} + +/// One request's generated tokens and whether its loop guard asked to end +/// the thought. Written by the bridge's pump (through the guard) and read by +/// the scheduler's continuation once the row has ended. +public final class GenerationLoopExitRecord: @unchecked Sendable { + private let lock = NSLock() + private var tokens: [Int] = [] + private var detection: GenerationLoopDetector.Detection? + + func append(_ new: [Int]) { + guard !new.isEmpty else { return } + lock.withLock { tokens.append(contentsOf: new) } + } + + func requestExit(_ detection: GenerationLoopDetector.Detection) { + lock.withLock { if self.detection == nil { self.detection = detection } } + } + + /// The detection that ended the thought, or nil while none did. + var requested: GenerationLoopDetector.Detection? { lock.withLock { detection } } + + /// Every token the row produced, the in-flight ones after the stop included. + var generatedTokens: [Int] { lock.withLock { tokens } } +} + +/// Which requests may end a repeating thought instead of the whole answer. +/// +/// On by default for Gemma 4 only, whose thought closes with one special +/// token (``). The guard keeps ending every other loop as `length`: +/// a loop outside the thought, a family without a listed marker, a request +/// that asked for logprobs (the forced token has none), a pair's request. +/// +/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list; +/// `0` or `off` turns it off; any other value is the comma-separated list of +/// `model_type`s to allow, among those with a listed marker. +enum GenerationLoopExitThinkingPolicy { + static let environmentKey = "DARKBLOOM_LOOP_EXIT_THINKING" + + struct Markers: Sendable, Equatable { + let open: String + let close: String + } + + /// The families whose thought this can end, by `model_type`. + static let markersByModelType: [String: Markers] = [ + "gemma4": .init(open: "<|channel>", close: ""), + "gemma4_text": .init(open: "<|channel>", close: ""), + ] + + static let defaultModelTypes: Set = ["gemma4", "gemma4_text"] + + /// The answer's own cap. Gemma's GPQA answers after a thought are under + /// 1,000 tokens; a Tau2 reply or call is shorter. + static let answerTokenLimit = 8_192 + + enum Setting: Sendable, Equatable { + case off + case modelTypes(Set) + } + + static let current = setting(environment: ProcessInfo.processInfo.environment) + + static func setting(environment: [String: String]) -> Setting { + guard let raw = environment[environmentKey]?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty else { return .modelTypes(defaultModelTypes) } + switch raw.lowercased() { + case "1", "on", "true": return .modelTypes(defaultModelTypes) + case "0", "off", "false": return .off + default: + let types = Set(raw.lowercased().split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }) + return types.isEmpty ? .off : .modelTypes(types) + } + } + + /// The exit for one guarded text request, or nil when its loops must + /// keep ending as `length`. + static func resolve( + modelType: String?, + tokenizer: any MLXLMCommon.Tokenizer, + promptTokens: [Int], + logprobs: Bool, + setting: Setting = current + ) -> GenerationLoopExitThinking? { + guard case .modelTypes(let enabled) = setting, + let modelType = modelType?.lowercased(), enabled.contains(modelType), + let markers = markersByModelType[modelType], !logprobs, + let close = tokenizer.convertTokenToId(markers.close), + tokenizer.convertIdToToken(close) == markers.close + else { return nil } + let tail = tokenizer.decode( + tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)), + skipSpecialTokens: false) + return GenerationLoopExitThinking( + openMarker: markers.open, closeMarker: markers.close, + exitTokens: [close], exitText: markers.close, + startsInside: endsInside(tail, open: markers.open, close: markers.close), + record: GenerationLoopExitRecord()) + } + + /// Whether `text` leaves the channel open: its last marker opens it. + static func endsInside(_ text: String, open: String, close: String) -> Bool { + guard let opened = text.range(of: open, options: .backwards) else { return false } + guard let closed = text.range(of: close, options: .backwards) else { return true } + return opened.lowerBound > closed.lowerBound + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift index dabd6ca32b..e064ed9115 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift @@ -5,6 +5,11 @@ import Foundation /// One row's loop guard. The detector watches the row's generated tokens; the /// guard is off for the rest of the row once its text shows a tool-call frame, /// so a call's arguments (a file of repeated lines, say) are never cut. +/// +/// With `exitThinking`, the guard also follows the row's reasoning channel and +/// keeps every token the row produces: a loop it finds inside the thought asks +/// the scheduler to end the thought and continue the answer +/// (`LoopExitThinkingContinuation`) instead of ending the row as `length`. public struct GenerationLoopGuard: Sendable { /// The served model's `model_type`, for the log line and the metric. let modelType: String @@ -19,9 +24,21 @@ public struct GenerationLoopGuard: Sendable { private var carry = "" /// Set by a tool-call frame, or once the guard fired: it never fires again. private(set) var disarmed = false + /// The way out of a repeating thought, when this request may take it + /// (`GenerationLoopExitThinkingPolicy`); nil keeps every stop a `length`. + let exitThinking: GenerationLoopExitThinking? + /// Whether the row is inside its reasoning channel (followed with `exitThinking` only). + private(set) var insideThinking: Bool + /// The end of the previous delta's text for the channel markers. + private var channelCarry = "" + /// Set when the guard's stop ended the thought rather than the answer. + private(set) var endsThought = false + /// A tool-call frame turned the guard off: there is no thought to end. + private var sawToolCall = false init(modelType: String, toolCallMarkers: [String], - thresholds: GenerationLoopDetector.Thresholds = .init()) { + thresholds: GenerationLoopDetector.Thresholds = .init(), + exitThinking: GenerationLoopExitThinking? = nil) { self.modelType = modelType self.detector = GenerationLoopDetector(thresholds: thresholds) self.toolCallMarkers = toolCallMarkers.filter { !$0.isEmpty } @@ -30,11 +47,18 @@ public struct GenerationLoopGuard: Sendable { marker.utf8.contains { probe.contains($0) } } ? probe : [] self.carryLength = max(0, (self.toolCallMarkers.map(\.count).max() ?? 1) - 1) + self.exitThinking = exitThinking + self.insideThinking = exitThinking?.startsInside ?? false } /// One delta of the row: its text and the tokens behind it. Returns the /// detection that should stop the row, at most once. mutating func observe(text: String, tokens: [Int]) -> GenerationLoopDetector.Detection? { + // The continuation resumes after every token the row produced, the + // in-flight ones after a stop included, so they are all kept. + if let exitThinking, !sawToolCall { + exitThinking.record.append(tokens) + } guard !disarmed else { return nil } if !toolCallMarkers.isEmpty, !text.isEmpty { let scanned = carry + text @@ -42,12 +66,40 @@ public struct GenerationLoopGuard: Sendable { if bytes.isEmpty || scanned.utf8.contains(where: { bytes.contains($0) }), toolCallMarkers.contains(where: { scanned.contains($0) }) { disarmed = true + sawToolCall = true return nil } carry = String(scanned.suffix(carryLength)) } + if let exitThinking, !text.isEmpty { + followChannel(text, markers: exitThinking) + } guard let detection = detector.append(tokens) else { return nil } disarmed = true + if let exitThinking, insideThinking { + endsThought = true + exitThinking.record.requestExit(detection) + } return detection } + + /// The last channel marker seen decides whether the row is inside its + /// thought. A marker split across deltas is seen through `channelCarry`, + /// which is one character shorter than the longest marker, so a marker + /// is never counted from the carry alone. + private mutating func followChannel(_ text: String, markers: GenerationLoopExitThinking) { + let scanned = channelCarry + text + if scanned.utf8.contains(UInt8(ascii: "<")) { + let opened = scanned.range(of: markers.openMarker, options: .backwards) + let closed = scanned.range(of: markers.closeMarker, options: .backwards) + switch (opened, closed) { + case (nil, nil): break + case (.some, nil): insideThinking = true + case (nil, .some): insideThinking = false + case (.some(let open), .some(let close)): insideThinking = open.lowerBound > close.lowerBound + } + } + let keep = max(markers.openMarker.count, markers.closeMarker.count) - 1 + channelCarry = String(scanned.suffix(max(0, keep))) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift index 3c288b2211..a66d8020e0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift @@ -64,7 +64,8 @@ enum GenerationLoopGuardPolicy { prepared: ToolChoicePromptPolicy.Prepared, tokenConstraint: (any CBv2TokenConstraint)?, setting: Setting = current, - thresholds: GenerationLoopDetector.Thresholds = .init() + thresholds: GenerationLoopDetector.Thresholds = .init(), + exitThinking: GenerationLoopExitThinking? = nil ) -> GenerationLoopGuard? { guard case .modelTypes(let enabled) = setting, let modelType = modelType?.lowercased(), enabled.contains(modelType) else { return nil } @@ -82,6 +83,7 @@ enum GenerationLoopGuardPolicy { guard !parser.supportsBareJSON, !parser.supportsMarkerlessNamedJSON else { return nil } markers += [parser.startTag].compactMap { $0 } + parser.alternateStartTags } - return GenerationLoopGuard(modelType: modelType, toolCallMarkers: markers, thresholds: thresholds) + return GenerationLoopGuard( + modelType: modelType, toolCallMarkers: markers, thresholds: thresholds, exitThinking: exitThinking) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift index e51253ae1b..04baf50a0e 100644 --- a/provider-swift/Sources/ProviderCore/ProviderCore.swift +++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift @@ -5,5 +5,5 @@ public enum ProviderCore { /// Release identity consumed by CLI output, registration and packaging. /// scripts/check-release-version.sh verifies this provider-owned identity /// against the requested release tag and reported binary version. - public static let version = "0.10.12" + public static let version = "0.10.13" } diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index b53b7506f8..72f7edd7ff 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -418,6 +418,9 @@ public enum LaunchAgent: Sendable { /// on by default; exact `0` is each rollback. /// `DARKBLOOM_GEMMA4_NAX_ROW_MAP`: eligible Gemma expert prefill uses the /// row-mapped NAX route by default; exact `0` restores its original graph. + /// `DARKBLOOM_LOOP_GUARD` / `DARKBLOOM_LOOP_EXIT_THINKING`: the loop guard + /// and its exit from a repeating Gemma 4 thought are on by default; `0` + /// turns each off, a list of `model_type`s replaces its default list. static let inferencePassthroughEnvKeys = [ EngineV2Factory.maxPartialPrefillsKey, EngineV2Factory.prefillChunkKey, @@ -448,6 +451,8 @@ public enum LaunchAgent: Sendable { ToolStreamPreparation.streamToolCallsEnvironmentKey, ReasoningPromptProbe.plainTailContentSeedEnvironmentKey, "DARKBLOOM_GEMMA4_NAX_ROW_MAP", + GenerationLoopGuardPolicy.environmentKey, + GenerationLoopExitThinkingPolicy.environmentKey, ] + MiMoV26DecodeDefaults.environmentKeys + MiMoV26DecodeDefaults.verifyEnvironmentKeys static let passthroughEnvKeys = [ diff --git a/provider-swift/Tests/ClusterOnboardingChecks/WaitHonestChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/WaitHonestChecks.swift index 1d4166ac96..e37da31ef7 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/WaitHonestChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/WaitHonestChecks.swift @@ -13,6 +13,20 @@ extension OnboardingChecks { aStopFromAnywhereEndsTheLeadersWaitAtOnce() aStopFromAnywhereEndsTheJoiningMacsWait() theJoiningMacFollowsTheLeadersModelChange() + // An external pair on 0.10.12 (2026-11-12): the joining Mac said the stop line 20 s into a download nobody stopped. + aStatusThatReadsStoppedThroughADownloadIsNoStop() + aStopIsTheLeadersRecordNeverItsStatusWords() + aStopBeforeTheStartIsNoStopOfIt() + aStopDuringTheDownloadEndsTheJoiningMacsWaitAtOnce() + aStopDuringTheDownloadKeepsThePairStopped() + aStopFromAnywhereEndsTheLeadersLoadAtOnce() + thePairsOwnStopsNeverEndTheLeadersWait() + aStopDuringTheTestEndsTheLeadersScreen() + aStartRefusedForAStopEndsTheScreen() + aStopDuringTheSoloQuestionKeepsThePairStopped() + aStopDuringTheVersionQuestionKeepsThePairStopped() + retryIsANewStart() + theJoiningMacComparesWithTheLeadersCount() } static func theCoordinatorsWaitNamesOnlyWhatTheMacsReportNow() { @@ -74,13 +88,18 @@ extension OnboardingChecks { expect(!run.text.contains(notServingChoices), "coordinator q: no ✗ or Retry") } + /// A `darkbloom cluster stop` while the leading Mac waits for the coordinator: the count grows (`stopsAsked`), and the + /// screen ends at once, while the wait itself would go on for minutes. static func aStopFromAnywhereEndsTheLeadersWaitAtOnce() { - let recorder = Recorder() - let run = TerminalRun(coordinatorWait(recorder) { progress in + let recorder = Recorder(), waiting = Recorder() + var made = coordinatorWait(recorder) { progress in + waiting.note("pairServing") progress("waiting for the coordinator to pair both Macs\nThis Mac: registered; waiting for the coordinator") - usleep(300_000) - return .failure(.stopped) - }) + sleep(30) + return .failure(.init("not reached")) + } + made.stopsAsked = { waiting.all.isEmpty ? 4 : 5 } + let run = TerminalRun(made) expect(run.waitFor(prompt(2)), "leader stop: the list"); run.type("\r") expect(run.finish(seconds: 10) == 1, "leader stop: ended") expect(run.text.contains("Stopped (by `darkbloom cluster stop` on one of the Macs): the pair isn't starting any more."), @@ -88,15 +107,47 @@ extension OnboardingChecks { expect(!run.text.contains(notServingChoices) && !run.text.contains("registering"), "leader stop: no Retry, no rows back: \(run.text)") } + /// A real `darkbloom cluster stop` while the parts load: the leading Mac counts it (`stopsAsked`), and the joining Mac + /// ends at once with the leading Mac's line. Its record already counted two stops from an earlier day. static func aStopFromAnywhereEndsTheJoiningMacsWait() { - let recorder = Recorder() + typealias P = ClusterOnboardingStartProgress let loading = "Loading Qwen 3.8 27B: 1 of 2 parts ready." - let run = joining(recorder, statusSequence: [["Stopped."], [loading], [loading], ["Stopped; last model Qwen 3.8 27B."]]) + let parts = P(.loading, parts: [.init(rank: 0, state: .ready), .init(rank: 1, state: .loading)]) + let run = TerminalRun(followingWithStops([.init(["Stopped."], stops: 2), .init([loading], start: parts, stops: 2), + .init([loading], start: parts, stops: 2), + .init(["Stopped; last model Qwen 3.8 27B."], stops: 3)])) + defer { run.release() } expect(run.waitFor(codeQuestion), "joining stop: the code"); run.type("y") - expect(run.finish(seconds: 40) == 1, "joining stop: ended once Stopped held, not after the bound: \(run.text)") + let began = Date() + expect(run.finish(seconds: 40) == 1, "joining stop: ended, not after the bound: \(run.text)") + expect(Date().timeIntervalSince(began) < 10, "joining stop: at once, never after a hold: \(Date().timeIntervalSince(began)) s") expect(run.text.contains("Stopped (by `darkbloom cluster stop` on one of the Macs)"), "joining stop: the same line: \(run.text)") } + /// One look of the joining Mac at the leading Mac's status: its lines, its start's progress, how many stops a person + /// asked for there (nil: a look that read none) and the step its screen published. + struct FollowLook: Sendable { + var lines: [String] + var start: ClusterOnboardingStartProgress? + var stops: Int? + var step: ClusterOnboardingLeaderStep? + init(_ lines: [String], start: ClusterOnboardingStartProgress? = nil, stops: Int? = nil, step: ClusterOnboardingLeaderStep? = nil) { + self.lines = lines; self.start = start; self.stops = stops; self.step = step + } + } + + /// The Mac that joined a leader whose looks say each of `looks` in turn (the last one repeats). + static func followingWithStops(_ looks: [FollowLook]) -> ClusterOnboardingOperations { + var made = operations(Recorder(), pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: leaderName)) + let count = Recorder() + made.leaderStatus = { + count.note("look") + let look = looks[min(count.all.count, looks.count) - 1] + return .init(lines: look.lines, step: look.step, start: look.start, stopsAsked: look.stops) + } + return made + } + static func theJoiningMacFollowsTheLeadersModelChange() { var made = operations(Recorder(), resume: memberResume(), pairEvents: [], pairResult: .failed([])) let status = made.status @@ -110,4 +161,312 @@ extension OnboardingChecks { expect(run.finish(seconds: 5) == 0, "model change: q leaves the follow") expect(!run.text.contains(ClusterOnboardingDriver.memberRunsByItselfLine), "model change: not the idle member screen: \(run.text)") } + + /// Seconds since it was first read: a scripted leader's start runs from the joining Mac's first look. + final class FirstLook: @unchecked Sendable { + private let lock = NSLock() + private var began: Date? + var seconds: Double { + lock.withLock { + let now = Date() + if began == nil { began = now } + return now.timeIntervalSince(began!) + } + } + } + + /// The report (an external pair on 0.10.12, 2026-11-12 ~20:46Z): the leading Mac downloaded the chosen model and the + /// joining Mac's screen ended about 20 s later with "Stopped (by `darkbloom cluster stop` on one of the Macs) …", + /// though nobody ran it. Until both parts start, the leading Mac's status reads "Stopped." (`localStatus` says so while + /// `leadership.serving` is off, and only `localServe` turns it on): through the download and the copy, which publish + /// their bytes, and through what comes before the start with nothing published (here a login after the download). It + /// reads "Stopped; last model …" again while it stops both parts to register them. Each stretch lasts over 20 s, so no + /// rule that takes "Stopped" held a while for a stop passes, whichever phases it leaves out. None of it is a stop: the + /// joining Mac follows the start to the leading Mac's outcome. + static func aStatusThatReadsStoppedThroughADownloadIsNoStop() { + typealias P = ClusterOnboardingStartProgress + let served = "Serving Qwen 3.8 27B through Darkbloom on both Macs (pipeline)." + var made = operations(Recorder(), pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: leaderName)) + let clock = FirstLook() + made.leaderStatus = { + let seconds = clock.seconds + switch seconds { + case ..<21: + return .init(lines: ["Stopped."], step: .init(.copy), + start: P(.downloading, done: Int64(seconds / 21 * 16_300_000_000), total: 16_300_000_000)) + case ..<22: + return .init(lines: ["Stopped."], step: .init(.copy), start: P(.copying, done: 8_000_000_000, total: 16_300_000_000)) + case ..<43: + // After the copy and before the start (a login asked on the leading Mac's screen): no figures, "Stopped.". + return .init(lines: ["Stopped."], step: .init(.login), start: nil) + case ..<44: + return .init(lines: ["Starting Qwen 3.8 27B."], step: .init(.starting), + start: P(.loading, parts: [.init(rank: 0, state: .starting), .init(rank: 1, state: .starting)])) + case ..<45: + return .init(lines: ["Loading Qwen 3.8 27B: 1 of 2 parts ready."], step: .init(.starting), + start: P(.loading, parts: [.init(rank: 0, state: .ready), .init(rank: 1, state: .loading)])) + case ..<66: + // The registration stops both parts, saves the approval on each Mac and starts them again as members. + return .init(lines: ["Stopped; last model Qwen 3.8 27B."], step: .init(.starting), start: P(.registering)) + default: + return .init(lines: [served], step: .init(.starting), start: nil) + } + } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(codeQuestion), "download, no stop: the code"); run.type("y") + let code = run.finish(seconds: 90) + let text = run.text + expect(text.contains("4/4 Start"), "download, no stop: the joining Mac followed the start: \(text)") + expect(!text.contains("Stopped (by `darkbloom cluster stop`"), "download, no stop: no stop line nobody asked for: \(text)") + expect(code == 0 && text.hasSuffix(ending("Serving Qwen 3.8 27B on both Macs")), + "download, no stop: the leading Mac's outcome, ✓: \(String(describing: code)) \(text)") + transcript("member-download-no-stop", text, keys: run.keys) + } + + /// What tells a stop: the leading Mac's count of the stops a person asked for, compared with the count when the start + /// began; never the words of its status. The start begins at the leading Mac's first step of it. + static func aStopIsTheLeadersRecordNeverItsStatusWords() { + let asked = ClusterOnboardingStopped.asked + expect(!asked(nil, nil) && !asked(nil, 1) && !asked(1, nil) && !asked(1, 1) && !asked(2, 0), + "stop asked: a count not read (an older leader, a status that couldn't be read), the same count or a lower one is no stop") + expect(asked(0, 1) && asked(1, 3), "stop asked: a higher count is") + var stop = ClusterOnboardingFollowedStop() + expect(!stop.look(nil, begun: false) && !stop.look(0, begun: false) && !stop.look(1, begun: false), + "followed stop: before the start, the latest count is the one to compare with") + expect(!stop.look(1, begun: true) && !stop.look(nil, begun: true), "followed stop: the same count once begun, or none read, is no stop") + expect(stop.look(2, begun: true), "followed stop: a higher count once begun ends the follow") + var late = ClusterOnboardingFollowedStop() + expect(!late.look(nil, begun: true) && !late.look(4, begun: true), + "followed stop: a start already running when a count is first read compares with that count") + expect(late.look(5, begun: true), "followed stop: then a higher one ends it") + var remade = ClusterOnboardingFollowedStop() + expect(!remade.look(3, begun: false) && !remade.look(0, begun: true) && remade.look(1, begun: true), + "followed stop: a lower count (a record made again) is the one to compare with from then on") + // The leading Mac's own count where its start's step carries it: both Macs count the same stops. + var shared = ClusterOnboardingFollowedStop() + expect(!shared.look(3, begun: false) && shared.look(3, begun: true, startStops: 2), + "followed stop: a stop between the leading Mac's count and this Mac's last look is the start's on both Macs") + var sharedLater = ClusterOnboardingFollowedStop() + expect(!sharedLater.look(nil, begun: true, startStops: 5) && !sharedLater.look(5, begun: true) && sharedLater.look(6, begun: true), + "followed stop: the step's count is kept once seen, and a look that read none tells nothing") + let kinds: [ClusterOnboardingLeaderStep.Kind] = [.localNetwork, .reading, .tryAgain, .modelList, .copy, .login, .starting, .refused, .unknown] + let begun = kinds.filter { ClusterOnboardingLeaderStep($0).startBegun } + expect(begun == [.copy, .starting], "the start begins at the model's transfer or the start itself: \(begun)") + } + + /// Someone runs `darkbloom cluster stop` while the leading Mac is still at its model list (nothing runs to stop): the + /// start that follows is no stopped one. + static func aStopBeforeTheStartIsNoStopOfIt() { + typealias P = ClusterOnboardingStartProgress + let loading = P(.loading, parts: [.init(rank: 0, state: .ready), .init(rank: 1, state: .loading)]) + let list = ClusterOnboardingLeaderStep(.modelList) + let run = TerminalRun(followingWithStops([.init(["Stopped."], step: list), .init(["Stopped."], stops: 0, step: list), + .init(["Stopped."], stops: 1, step: list), .init(["Stopped."], stops: 1, step: .init(.starting)), + .init(["Starting Qwen 3.8 27B."], start: loading, stops: 1, step: .init(.starting)), + .init(["Loading Qwen 3.8 27B: 1 of 2 parts ready."], start: loading, stops: 1), + .init(["Serving Qwen 3.8 27B through Darkbloom on both Macs (pipeline)."], stops: 1)])) + defer { run.release() } + expect(run.waitFor(codeQuestion), "stop before the start: the code"); run.type("y") + expect(run.finish(seconds: 20) == 0, "stop before the start: the start's outcome, ✓: \(run.text)") + expect(!run.text.contains("Stopped (by `darkbloom cluster stop`") && run.text.hasSuffix(ending("Serving Qwen 3.8 27B on both Macs")), + "stop before the start: no stop line: \(run.text)") + } + + /// A real stop while the leading Mac downloads the model, or while its screen asks how to get it there (the start's + /// first step, before any figure): the joining Mac ends at once with the leading Mac's line, whose own screen keeps + /// the pair stopped (`aStopDuringTheDownloadKeepsThePairStopped`). + static func aStopDuringTheDownloadEndsTheJoiningMacsWaitAtOnce() { + typealias P = ClusterOnboardingStartProgress + let copy = ClusterOnboardingLeaderStep(.copy) + for (label, during) in [("stop in the download", P(.downloading, done: 3_000_000_000, total: 16_300_000_000)), ("stop at the copy question", nil)] { + let run = TerminalRun(followingWithStops([.init(["Stopped."], stops: 0, step: .init(.modelList)), + .init(["Stopped."], start: during, stops: 0, step: copy), .init(["Stopped."], start: during, stops: 0, step: copy), + .init(["Stopped."], start: during, stops: 1, step: copy)])) + defer { run.release() } + expect(run.waitFor(codeQuestion), "\(label): the code"); run.type("y") + let began = Date() + expect(run.finish(seconds: 20) == 1, "\(label): ended: \(run.text)") + expect(Date().timeIntervalSince(began) < 10, "\(label): at once: \(Date().timeIntervalSince(began)) s") + expect(run.text.contains("Stopped (by `darkbloom cluster stop` on one of the Macs)"), "\(label): the leading Mac's line: \(run.text)") + } + } + + /// The leading Mac's start began at a count of 2, and a stop came before this Mac's first look: its step's count is the + /// one both Macs compare with, so this Mac ends as the leading Mac does. + static func theJoiningMacComparesWithTheLeadersCount() { + let run = TerminalRun(followingWithStops([.init(["Stopped."], stops: 3, step: .init(.copy, stopsBefore: 2))])) + defer { run.release() } + expect(run.waitFor(codeQuestion), "the leader's count: the code"); run.type("y") + expect(run.finish(seconds: 10) == 1 && run.text.contains("Stopped (by `darkbloom cluster stop` on one of the Macs)"), + "the leader's count: the stop before this Mac's first look is the start's: \(run.text)") + } + + /// The leading Mac downloads a model no Mac has while someone runs `darkbloom cluster stop`, or asks how to get it + /// there when they do: its screen ends at once, as the joining Mac's does, and starts nothing (before, it started both + /// Macs once the download was done, as if nobody had stopped them). What arrived stays for the next start. + static func aStopDuringTheDownloadKeepsThePairStopped() { + let offer = ClusterOnboardingProvisionOffer(lines: ["This Mac: download from Darkbloom's catalog (16.3 GB)"], + downloadAlternative: false, leaderDownloads: true) + let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · not on these Macs: downloaded from Darkbloom's catalog first"], + blocker: nil, provision: offer)] + let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], + blocker: nil)] + for atTheQuestion in [false, true] { + let label = atTheQuestion ? "leader stop at the copy question" : "leader stop in the download" + let recorder = Recorder(), stopped = Recorder() + // A download of about 8 s. + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: before, replanned: after, provisionReports: Array(repeating: copyReports[0], count: 80), + provisionReportPause: 100_000) + // Two stops counted on earlier days; one more asked at the question or during the download. + made.stopsAsked = { !stopped.all.isEmpty || (!atTheQuestion && recorder.all.contains("provision 0 copy")) ? 3 : 2 } + let steps = Recorder() + made.publishStep = { step in steps.note("\(step?.kind.rawValue ?? "none") \(step?.stopsBefore.map(String.init) ?? "-")") } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(1)), "\(label): the list"); run.type("\r") + expect(run.waitFor(" 1) Download\n 2) Cancel\n"), "\(label): get it") + if atTheQuestion { stopped.note("stop") } + run.type("\r") + let began = Date() + expect(run.finish(seconds: 10) == 1, "\(label): ended, not served: \(run.text)") + expect(Date().timeIntervalSince(began) < 5, "\(label): at once, not after the download: \(Date().timeIntervalSince(began)) s") + expect(run.text.hasSuffix("Stopped (by `darkbloom cluster stop` on one of the Macs): the pair isn't starting any more. " + + "Run `darkbloom cluster` on the leading Mac to start it again.\n " + + ClusterOnboardingStopped.transferKeptLine + "\n"), "\(label): the line, and what stays: \(run.text)") + expect(recorder.all.contains("provision 0 copy") && recorder.all.filter({ $0 == "planModels" }).count == 1 && !recorder.all.contains("serve"), + "\(label): nothing planned or started after it: \(recorder.all)") + expect(steps.all.contains("copy 2"), "\(label): the start's step carries the count it began with: \(steps.all)") + } + } + + /// A stop that lands while the leading Mac tests the started pair: the stop is the outcome, never ✓ or "test failed", + /// and nothing registers or starts again. + static func aStopDuringTheTestEndsTheLeadersScreen() { + for testPasses in [true, false] { + let recorder = Recorder(), tested = Recorder() + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([])) + made.testRequest = { + tested.note("test") + return testPasses ? .success(["in 0.61 s"]) : .failure(.init("The test request did not reach this Mac: closed")) + } + made.stopsAsked = { tested.all.isEmpty ? 0 : 1 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "stop in the test: the list"); run.type("\r") + expect(run.finish(seconds: 10) == 1, "stop in the test (\(testPasses ? "passed" : "failed")): ended: \(run.text)") + expect(run.text.hasSuffix(ClusterOnboardingStopped.line + "\n") + && !run.text.contains("\u{2713} Serving") && !run.text.contains("the test failed") && !recorder.all.contains("register"), + "stop in the test (\(testPasses ? "passed" : "failed")): the stop, nothing else: \(run.text) \(recorder.all)") + } + } + + /// The leading Mac refuses its start under the lock (`serveUnlessStopped`): a stop took the lock first. The screen + /// ends with the stop line and waits for nothing. + static func aStartRefusedForAStopEndsTheScreen() { + let recorder = Recorder() + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([])) + made.serveUnlessStopped = { since in recorder.note("serveUnlessStopped \(since.map(String.init) ?? "-")"); return .failure(.stopped) } + made.stopsAsked = { 7 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "refused start: the list"); run.type("\r") + expect(run.finish(seconds: 10) == 1, "refused start: ended") + expect(run.text.hasSuffix(ClusterOnboardingStopped.line + "\n") && !run.text.contains(" " + ClusterOnboardingStopped.line) + && !recorder.all.contains("waitReady") && !recorder.all.contains("serve") && recorder.all.contains("serveUnlessStopped 7"), + "refused start: the stop's own ending, nothing waited for: \(run.text) \(recorder.all)") + } + + /// A stop asked while the leading Mac's screen asks to stop single-Mac serving (found while the parts loaded): the + /// same start goes on there, so the stop stands and nothing starts again (the joining Mac, which still follows, ends + /// on the same stop). + static func aStopDuringTheSoloQuestionKeepsThePairStopped() { + let recorder = Recorder(), stopped = Recorder() + let ready = ClusterOnboardingReady(servedBy: "this Mac", port: 8000, deployment: "Serving Gemma 4 26B across both Macs: tensor parallel", + split: "tensor parallel") + var made = soloOperations(recorder, serving: [], readyResults: [.failure(.soloServing([soloBoth[1]])), .success(ready)]) + made.stopsAsked = { stopped.all.isEmpty ? 0 : 1 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "stop at the solo question: the list"); run.type("\r") + expect(run.waitFor(" 2) Leave\n"), "stop at the solo question: the offer") + stopped.note("stop") + run.type("1") + expect(run.finish(seconds: 10) == 1, "stop at the solo question: ended: \(run.text)") + expect(run.text.hasSuffix(ClusterOnboardingStopped.line + "\n") && recorder.all.filter({ $0 == "serve" }).count == 1, + "stop at the solo question: the stop line, not started again: \(run.text) \(recorder.all)") + } + + /// The same while the leading Mac's screen asks to check the versions again (a split found while the parts loaded). + static func aStopDuringTheVersionQuestionKeepsThePairStopped() { + let recorder = Recorder(), stopped = Recorder() + let split = ClusterOnboardingVersionSplit(thisVersion: "0.10.13", otherVersion: "0.10.12", other: m5MaxNamed) + var made = operations(recorder, resume: .init(role: .leader, peerName: m5Max), pairEvents: [], pairResult: .failed([]), + readyResults: [.failure(split.failure), .success(offeredReady)]) + made.stopsAsked = { stopped.all.isEmpty ? 0 : 1 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "stop at the version question: the list"); run.type("\r") + expect(run.waitFor(" 2) Leave\n"), "stop at the version question: check again, or leave: \(run.text)") + stopped.note("stop") + run.type("1") + expect(run.finish(seconds: 10) == 1, "stop at the version question: ended: \(run.text)") + expect(run.text.hasSuffix(ClusterOnboardingStopped.line + "\n") && recorder.all.filter({ $0 == "serve" }).count == 1, + "stop at the version question: the stop line, not started again: \(run.text) \(recorder.all)") + } + + /// Retry after a ✗ is a new start (the joining Mac ended on that ✗): a stop asked before it is no stop of the new one, + /// and the new start's step says its own count, for a joining Mac that follows it now. + static func retryIsANewStart() { + let recorder = Recorder(), stopped = Recorder(), steps = Recorder() + // Each wait for the parts takes about 2.4 s: long enough for a count compared with the first start's to end it. + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), + readyResults: [.failure(.init("A part keeps ending the same way: boom")), .success(offeredReady)], + readyReportPause: 1_200_000) + made.stopsAsked = { stopped.all.isEmpty ? 0 : 1 } + made.publishStep = { step in steps.note("\(step?.kind.rawValue ?? "none") \(step?.stopsBefore.map(String.init) ?? "-")") } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "retry: the list"); run.type("\r") + expect(run.waitFor(notServingItemLines), "retry: the ✗ and its choices: \(run.text)") + stopped.note("stop") + run.type("1") + expect(run.finish(seconds: 20) == 0, "retry: served: \(run.text)") + expect(!run.text.contains("Stopped (by `darkbloom cluster stop`"), "retry: no stop line from before it: \(run.text)") + expect(steps.all.suffix(1) == ["starting 1"], "retry: its step carries the count it began with: \(steps.all)") + } + + /// A real stop while the parts load: the leading Mac's screen ends at once with the stop line (its parts are stopped + /// and nothing starts them again), never a ✗ after 15 minutes with Retry. The wait itself goes on by itself (here it + /// would answer only after 20 s). + static func aStopFromAnywhereEndsTheLeadersLoadAtOnce() { + let recorder = Recorder() + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), + readyReports: ["1 of 2 parts ready"], readyReportPause: 20_000_000) + made.stopsAsked = { recorder.all.contains("waitReady") ? 3 : 2 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "leader stop in the load: the list"); run.type("\r") + let began = Date() + expect(run.finish(seconds: 15) == 1, "leader stop in the load: ended") + expect(Date().timeIntervalSince(began) < 10, "leader stop in the load: at once, not when the wait answers: \(Date().timeIntervalSince(began)) s") + expect(run.text.contains("Stopped (by `darkbloom cluster stop` on one of the Macs): the pair isn't starting any more."), + "leader stop in the load: said plainly: \(run.text)") + expect(!run.text.contains(notServingChoices) && !recorder.all.contains("testRequest"), "leader stop in the load: no Retry, no test: \(run.text)") + } + + /// The leading Mac's own stops while the parts load (a part a model change or the registration stopped, the cluster + /// service's restart for an approval) count none: its wait goes on to the outcome. + static func thePairsOwnStopsNeverEndTheLeadersWait() { + let recorder = Recorder() + var made = operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), + readyReports: ["1 of 2 parts ready", "2 of 2 parts ready"], readyReportPause: 1_500_000) + made.stopsAsked = { 2 } + let run = TerminalRun(made) + defer { run.release() } + expect(run.waitFor(prompt(2)), "own stops: the list"); run.type("\r") + expect(run.finish(seconds: 20) == 0, "own stops: served: \(run.text)") + expect(!run.text.contains("Stopped (by `darkbloom cluster stop`") && recorder.all.contains("testRequest"), "own stops: no stop line: \(run.text)") + } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift index 19904c595b..f3ca23f8ec 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift @@ -307,3 +307,21 @@ final class ClusterApprovalRecorder: @unchecked Sendable { func append(_ value: Value) { lock.withLock { stored.append(value) } } var values: [Value] { lock.withLock { stored } } } + +extension ClusterApprovalMacs { + /// The leading Mac's cluster service for this pair, its pair started on the fixture's model. No loop runs: only what a + /// test calls acts on its record. `powerAssertionReason` keeps its power assertions apart from those of the other + /// services the test process runs. + func startedLeaderService(powerAssertionReason: String) throws -> ClusterService { + let wizard = ClusterSetupOperations.LiveSettings(providerConfiguration: leader.provider, + darkbloomExecutable: URL(fileURLWithPath: "/usr/bin/true"), sessionArguments: [], pair: nil, dryRun: true, + version: "fixture") + let service = ClusterService(settings: .init(wizard: wizard, leaderArguments: [], followerArguments: []), + paths: leader.paths, recoveryGraceSeconds: 0.2, supervisionIntervalSeconds: 0.1, powerAssertionReason: powerAssertionReason) + var leadership = ClusterOnboardingLeadership(role: "leader", leaderPin: leader.pin, peerPin: follower.pin, + peerName: "fixture peer", since: "fixture") + leadership.serving = true; leadership.modelName = Self.model + _ = try service.store.updateRecord { $0.leadership = leadership } + return service + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingStopsAskedTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingStopsAskedTests.swift new file mode 100644 index 0000000000..149ef34211 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingStopsAskedTests.swift @@ -0,0 +1,85 @@ +import Foundation +import Testing +@testable import ProviderCore + +/// An external pair on 0.10.12 (2026-11-12): the joining Mac took the leading Mac's "Stopped" status for a stop 20 s into +/// a download nobody stopped. The leading Mac now counts each stop a person asks for (`ClusterSetupRecord.stopsAsked`), +/// its status carries the count, and the screens end on a stop only once it grew. The leading Mac here is the +/// `ClusterApprovalMacs` fixture's, in its own home; nothing asks the other Mac (its answer is given). +@Suite("Cluster onboarding: the stops a person asked for", .serialized) +struct ClusterOnboardingStopsAskedTests { + /// A reply's shape as a build before the count decodes it. + struct OlderReply: Decodable { var lines: [String]; var failed: Bool; var leaderID: String? } + + /// The leading Mac of a pair the fixture saved, its pair started. Its cluster service runs no loop. + private static func leader() throws -> (ClusterApprovalMacs, ClusterService) { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + return (macs, try macs.startedLeaderService(powerAssertionReason: "Cluster stops asked test " + UUID().uuidString)) + } + + @Test func theStatusCarriesTheStopsAskedForAndAnOlderMacIgnoresThem() throws { + var reply = ClusterControlReply(lines: ["Stopped; last model Qwen 3.8 27B."], failed: false, leaderID: "a") + reply.stopsAsked = 3 + let data = try JSONEncoder().encode(reply) + #expect(try JSONDecoder().decode(ClusterControlReply.self, from: data) == reply, "round trip") + #expect(try JSONDecoder().decode(OlderReply.self, from: data).lines == reply.lines, "an older Mac reads the rest") + #expect(ClusterOnboardingLeaderStatus(reply: reply).stopsAsked == 3, "the Mac that forwarded the status reads the count") + let fromOlder = try JSONDecoder().decode(ClusterControlReply.self, from: Data(#"{"lines":["Stopped."],"failed":false}"#.utf8)) + #expect(fromOlder.stopsAsked == nil && !ClusterOnboardingStopped.asked(since: 0, now: ClusterOnboardingLeaderStatus(reply: fromOlder).stopsAsked), + "an older leader sends none: no stop") + let request = ClusterControlRequest(op: .serve, stopsBefore: 2) + #expect(try JSONDecoder().decode(ClusterControlRequest.self, from: JSONEncoder().encode(request)).stopsBefore == 2, "a start's count travels") + #expect(try JSONDecoder().decode(ClusterControlRequest.self, from: Data(#"{"op":"serve"}"#.utf8)).stopsBefore == nil, + "an older Mac's start carries none, and serves as before") + } + + /// Each stop's first write: only one a person asked for is counted; the start's own (a model change, the + /// registration's restart) and the cluster service's are not. Each stops the pair the same way. + @Test func onlyAStopAPersonAskedForIsCounted() throws { + var record = ClusterSetupRecord() + record.leadership = ClusterOnboardingLeadership(role: "leader", leaderPin: "a", peerPin: "b", peerName: "Apple M5 Max, 128 GB", + since: "2026-11-12T20:40:00Z") + record.leadership?.serving = true + let own = UUID() + OnboardingLive.recordStop(&record, id: own, asked: false) + #expect(record.leadership?.serving == false && record.stopDrain?.id == own && record.stopsAsked == nil, "the start's own stop") + OnboardingLive.recordStop(&record, id: UUID(), asked: true) + OnboardingLive.recordStop(&record, id: UUID(), asked: true) + #expect(record.leadership?.serving == false && record.stopsAsked == 2, "each stop a person asked for, counted") + #expect(try JSONDecoder().decode(ClusterSetupRecord.self, from: JSONEncoder().encode(record)).stopsAsked == 2, "kept") + let older = try JSONDecoder().decode(ClusterSetupRecord.self, from: Data( + #"{"schema":"darkbloom_cluster_setup_wizard_v1","confirmed":[],"sent":[],"checks":[]}"#.utf8)) + #expect(older.stopsAsked == nil, "an older record counts none") + } + + /// The real stop on the leading Mac's record, and the status reply the Mac that joined reads it from: 0 before the + /// first; a stop asked for counts, the pair's own doesn't. + @Test func theLeadingMacCountsAStopAskedForAndItsStatusCarriesIt() throws { + let (macs, service) = try Self.leader() + let live = service.controlLive + #expect(live.currentStopsAsked() == 0 && live.followerStatus(.init(lines: [], failed: false)).stopsAsked == 0, "none yet") + if case .failure(let failure) = live.localStop(seconds: 1, asked: true, stopPeer: {}) { Issue.record("stop: \(failure.lines)") } + let stopped = try service.store.readRecord() + #expect(live.currentStopsAsked() == 1 && stopped.leadership?.serving == false, "a stop asked for") + if case .failure(let failure) = live.localStop(seconds: 1, stopPeer: {}) { Issue.record("own stop: \(failure.lines)") } + #expect(live.currentStopsAsked() == 1, "the pair's own stop counts none") + #expect(live.followerStatus(.init(lines: ["Stopped; last model fixture/qwen."], failed: false)).stopsAsked == 1, + "the status the Mac that joined reads carries it") + withExtendedLifetime(macs) {} + } + + /// A start that took the command lock after a stop asked since it began never undoes that stop: it serves nothing. + @Test func aStartNeverUndoesAStopAskedSinceItBegan() throws { + let (macs, service) = try Self.leader() + let live = service.controlLive + if case .failure(let failure) = live.localStop(seconds: 1, asked: true, stopPeer: {}) { Issue.record("stop: \(failure.lines)") } + guard case .failure(let refused) = live.localServe(unlessStoppedSince: 0) else { + Issue.record("served after a stop asked since the start began") + return + } + #expect(refused.stopped && refused.lines == [ClusterOnboardingStopped.line], "the stop line, marked stopped") + let record = try service.store.readRecord() + #expect(record.leadership?.serving == false, "the pair stays stopped") + withExtendedLifetime(macs) {} + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRestartingStopTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRestartingStopTests.swift index eafb5aaafc..6a4ab47ce0 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRestartingStopTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRestartingStopTests.swift @@ -29,19 +29,7 @@ struct ClusterServiceRestartingStopTests { } private static func service(_ macs: ClusterApprovalMacs) throws -> ClusterService { - let leader = macs.leader - let wizard = ClusterSetupOperations.LiveSettings(providerConfiguration: leader.provider, - darkbloomExecutable: URL(fileURLWithPath: "/usr/bin/true"), sessionArguments: [], pair: nil, dryRun: true, - version: "fixture") - let service = ClusterService(settings: .init(wizard: wizard, leaderArguments: [], followerArguments: []), - paths: leader.paths, recoveryGraceSeconds: 0.2, supervisionIntervalSeconds: 0.1, - // Its power assertions apart from those of the other services this test process runs. - powerAssertionReason: "Cluster restarting stop test " + UUID().uuidString) - var leadership = ClusterOnboardingLeadership(role: "leader", leaderPin: leader.pin, peerPin: macs.follower.pin, - peerName: "fixture peer", since: "fixture") - leadership.serving = true; leadership.modelName = ClusterApprovalMacs.model - _ = try service.store.updateRecord { $0.leadership = leadership } - return service + try macs.startedLeaderService(powerAssertionReason: "Cluster restarting stop test " + UUID().uuidString) } /// The stop both steps make (`OnboardingLive.localStop`): this Mac's saved start cleared, its part retired, then the diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift new file mode 100644 index 0000000000..8d239293e9 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift @@ -0,0 +1,295 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import Testing + +@testable import ProviderCore + +@Suite("Continuing an answer after the loop guard ended its thought") +struct LoopExitThinkingContinuationTests { + private static let prompt = [1, 2, 3, 4, 5] + private static let close = GemmaThoughtTestTokenizer.channelClose + + /// What the continuation was asked for, and what was cancelled. + private final class Calls: @unchecked Sendable { + private let lock = NSLock() + private var submitted: [(prompt: [Int], maxTokens: Int)] = [] + private var firstCancels = 0 + private var continuationCancels = 0 + + func submit(_ prompt: [Int], _ maxTokens: Int) { lock.withLock { submitted.append((prompt, maxTokens)) } } + func cancelFirst() { lock.withLock { firstCancels += 1 } } + func cancelContinuation() { lock.withLock { continuationCancels += 1 } } + var submits: [(prompt: [Int], maxTokens: Int)] { lock.withLock { submitted } } + var cancels: (first: Int, continuation: Int) { lock.withLock { (firstCancels, continuationCancels) } } + } + + private struct Refused: Error {} + + private final class Seen: @unchecked Sendable { + private let lock = NSLock() + private var events = 0 + func add() { lock.withLock { events += 1 } } + var count: Int { lock.withLock { events } } + } + + private func stream(_ events: [GenerationEvent], finish: Bool = true) -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream() + events.forEach { continuation.yield($0) } + if finish { continuation.finish() } + return stream + } + + private func exit(requested: Bool, tokens: [Int]) -> GenerationLoopExitThinking { + let record = GenerationLoopExitRecord() + record.append(tokens) + if requested { record.requestExit(.init(period: 19, span: 2_048, generatedTokens: 4_096)) } + return GenerationLoopExitThinking( + openMarker: "<|channel>", closeMarker: "", exitTokens: [Self.close], + exitText: "", startsInside: false, record: record) + } + + private static func describe(_ event: GenerationEvent) -> String { + switch event { + case .chunk(let text): "chunk:\(text)" + case .logprobs: "logprobs" + case .info(let prompt, let completion, _, let reason): "info:\(prompt)/\(completion)/\(reason ?? "nil")" + case .error(let message): "error:\(message)" + case .terminal(let cause, _, let prompt, let completion): "terminal:\(cause.rawValue)/\(prompt)/\(completion)" + } + } + + private func drain(_ events: AsyncStream) async -> [String] { + var out: [String] = [] + for await event in events { out.append(Self.describe(event)) } + return out + } + + private func splice( + first: AsyncStream, exit: GenerationLoopExitThinking, outputBudget: Int = 8_192, + calls: Calls, continuation: @escaping @Sendable () throws -> AsyncStream + ) -> (events: AsyncStream, cancel: @Sendable () async -> Void) { + LoopExitThinkingContinuation.splice( + first: first, cancelFirst: { calls.cancelFirst() }, exit: exit, promptTokens: Self.prompt, + outputBudget: outputBudget, + submit: { prompt, maxTokens in + calls.submit(prompt, maxTokens) + return try continuation() + }, + cancelContinuation: { calls.cancelContinuation() }) + } + + private let thought = Array(repeating: 900, count: 4_200) + + @Test("no exit asked: the row's events pass through and nothing more is submitted") + func passThrough() async { + let calls = Calls() + let first = stream([.chunk("a"), .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: false, tokens: thought), calls: calls) { + self.stream([.chunk("never")]) + }.events) + #expect(out == ["chunk:a", "info:5/4200/length"]) + #expect(calls.submits.isEmpty) + } + + @Test("an ended thought continues: the marker, the answer, and one terminal with every token") + func continues() async throws { + let calls = Calls() + let first = stream([.chunk("think"), .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.chunk("Answer: B"), .info(promptTokens: 4_206, completionTokens: 9, tokensPerSecond: 20, + finishReason: "stop")]) + }.events) + #expect(out == ["chunk:think", "chunk:", "chunk:Answer: B", "info:5/4210/stop"]) + let submit = try #require(calls.submits.first) + #expect(calls.submits.count == 1) + #expect(submit.prompt == Self.prompt + thought + [Self.close]) + #expect(submit.maxTokens == 8_192 - 4_200 - 1) + } + + @Test("a refused continuation ends the answer as length, as before") + func refused() async { + let calls = Calls() + let first = stream([.chunk("think"), .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + throw Refused() + }.events) + #expect(out == ["chunk:think", "info:5/4200/length"]) + } + + @Test("a continuation that fails before its first token ends the answer as length") + func failsBeforeFirstToken() async { + let calls = Calls() + let first = stream([.chunk("think"), .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.info(promptTokens: 4_206, completionTokens: 0, tokensPerSecond: 0, finishReason: nil), + .error("request cancelled")]) + }.events) + #expect(out == ["chunk:think", "info:5/4200/length"]) + } + + @Test("the answer's budget is the request's remainder, at most the answer cap") + func answerCap() async throws { + let calls = Calls() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + let out = await drain(splice( + first: first, exit: exit(requested: true, tokens: thought), outputBudget: 131_072, calls: calls + ) { + self.stream([.chunk("B"), .info(promptTokens: 4_206, completionTokens: 1, tokensPerSecond: 20, + finishReason: "stop")]) + }.events) + #expect(out == ["chunk:", "chunk:B", "info:5/4202/stop"]) + let submit = try #require(calls.submits.first) + #expect(submit.maxTokens == GenerationLoopExitThinkingPolicy.answerTokenLimit) + } + + @Test("a row that closed its thought itself after the stop is not continued") + func closedInFlight() async { + let calls = Calls() + let tokens = Array(repeating: 900, count: 4_096) + [Self.close, 65, 66] + let first = stream([.chunk("thinkAB"), + .info(promptTokens: 5, completionTokens: 4_099, tokensPerSecond: 10, finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: tokens), calls: calls) { + self.stream([.chunk("never")]) + }.events) + #expect(out == ["chunk:thinkAB", "info:5/4099/length"]) + #expect(calls.submits.isEmpty) + } + + @Test("no output budget left: nothing is submitted") + func noBudget() async { + let calls = Calls() + let first = stream([.chunk("think"), .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")]) + let out = await drain(splice( + first: first, exit: exit(requested: true, tokens: thought), outputBudget: 4_201, calls: calls + ) { self.stream([.chunk("never")]) }.events) + #expect(out == ["chunk:think", "info:5/4200/length"]) + #expect(calls.submits.isEmpty) + } + + @Test("under 256 tokens of budget left, the thought is not prefilled again for an answer") + func smallBudget() async { + let calls = Calls() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + let out = await drain(splice( + first: first, exit: exit(requested: true, tokens: thought), outputBudget: 4_200 + 1 + 255, calls: calls + ) { self.stream([.chunk("never")]) }.events) + #expect(out == ["info:5/4200/length"]) + #expect(calls.submits.isEmpty) + } + + @Test("a client that leaves during the answer cancels the continuation") + func consumerLeaves() async throws { + let calls = Calls() + let (answer, answerContinuation) = AsyncStream.makeStream() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + let spliced = splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { answer } + answerContinuation.yield(.chunk("A")) + let seen = Seen() + // The client's task is cancelled while it waits for more of the answer. + let consumer = Task { for await _ in spliced.events { seen.add() } } + let limit = ContinuousClock.now + .seconds(2) + while seen.count < 2, ContinuousClock.now < limit { try await Task.sleep(for: .milliseconds(5)) } + #expect(seen.count == 2) + consumer.cancel() + while calls.cancels.continuation == 0, ContinuousClock.now < limit { + try await Task.sleep(for: .milliseconds(5)) + } + #expect(calls.cancels.continuation == 1) + answerContinuation.finish() + } + + @Test("a row that ended any other way is not continued") + func otherEndings() async { + for ending: GenerationEvent in [ + .info(promptTokens: 5, completionTokens: 100, tokensPerSecond: 1, finishReason: "stop"), + .error("request cancelled"), + ] { + let calls = Calls() + let first = stream([.chunk("think"), ending]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.chunk("never")]) + }.events) + #expect(out == ["chunk:think", Self.describe(ending)]) + #expect(calls.submits.isEmpty) + } + } + + @Test("an empty answer still closes the thought") + func emptyAnswer() async { + let calls = Calls() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.info(promptTokens: 4_206, completionTokens: 0, tokensPerSecond: 0, finishReason: "stop")]) + }.events) + #expect(out == ["chunk:", "info:5/4201/stop"]) + } + + @Test("a failure after the answer started ends it as a paid length, as the guard's stop would") + func failureAfterStart() async { + let calls = Calls() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + // Not the client's cancel (a teardown, a capacity error): the usage before the error is kept. + let out = await drain(splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.chunk("A"), .info(promptTokens: 4_206, completionTokens: 3, tokensPerSecond: 0, finishReason: nil), + .error("request cancelled")]) + }.events) + #expect(out == ["chunk:", "chunk:A", "info:5/4204/length"]) + + let capacity = await drain(splice(first: stream([.info(promptTokens: 5, completionTokens: 4_200, + tokensPerSecond: 10, finishReason: "length")]), exit: exit(requested: true, tokens: thought), calls: Calls()) { + self.stream([.chunk("A"), .error("token_budget_exhausted: KV capacity exhausted")]) + }.events) + #expect(capacity == ["chunk:", "chunk:A", "info:5/4201/length"]) + + let terminal = await drain(splice(first: stream([.info(promptTokens: 5, completionTokens: 4_200, + tokensPerSecond: 10, finishReason: "length")]), exit: exit(requested: true, tokens: thought), calls: Calls()) { + self.stream([.chunk("A"), .terminal(cause: .decodeStall, message: "stalled", promptTokens: 4_206, + completionTokens: 2)]) + }.events) + #expect(terminal == ["chunk:", "chunk:A", "info:5/4203/length"]) + } + + @Test("a cancel before the continuation starts keeps it from starting") + func cancelBeforeStart() async { + let calls = Calls() + let (first, firstContinuation) = AsyncStream.makeStream() + let spliced = splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { + self.stream([.chunk("never")]) + } + firstContinuation.yield(.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, + finishReason: "length")) + await spliced.cancel() + firstContinuation.finish() + let out = await drain(spliced.events) + #expect(out == ["info:5/4200/length"]) + #expect(calls.submits.isEmpty) + #expect(calls.cancels.first == 1) + #expect(calls.cancels.continuation == 0) + } + + @Test("a cancel during the continuation stops it") + func cancelDuringContinuation() async { + let calls = Calls() + let (answer, answerContinuation) = AsyncStream.makeStream() + let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")]) + let spliced = splice(first: first, exit: exit(requested: true, tokens: thought), calls: calls) { answer } + answerContinuation.yield(.chunk("A")) + var iterator = spliced.events.makeAsyncIterator() + #expect(await iterator.next().map(Self.describe) == "chunk:") + #expect(await iterator.next().map(Self.describe) == "chunk:A") + await spliced.cancel() + #expect(calls.cancels.continuation == 1) + answerContinuation.yield(.info(promptTokens: 4_206, completionTokens: 1, tokensPerSecond: 0, finishReason: nil)) + answerContinuation.yield(.error("request cancelled")) + answerContinuation.finish() + #expect(await iterator.next().map(Self.describe) == "info:5/4202/nil") + #expect(await iterator.next().map(Self.describe) == "error:request cancelled") + #expect(await iterator.next() == nil) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift new file mode 100644 index 0000000000..f3bc093458 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift @@ -0,0 +1,376 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// A Gemma 4 row that repeats one clause verbatim, inside its thought or in +/// its answer, one token per delta; the guard's cancel ends it `.cancelled` +/// (a row nobody cancels ends `.length` after a short wait). Any later +/// submission is the continuation: it answers "Answer: B" and stops. +private final class ThoughtLoopCBv2Engine: CBv2Engine, @unchecked Sendable { + private let lock = NSLock() + private var continuations: [AsyncStream.Continuation] = [] + private var submitted: [CBv2Request] = [] + private var produced: [[Int]] = [] + private var cancels = 0 + let loopInsideThought: Bool + let loopTokens: Int + + init(loopInsideThought: Bool, loopTokens: Int = 4_200) { + self.loopInsideThought = loopInsideThought + self.loopTokens = loopTokens + } + + var requests: [CBv2Request] { lock.withLock { submitted } } + var outputs: [[Int]] { lock.withLock { produced } } + var cancelCount: Int { lock.withLock { cancels } } + + func submit(_ request: CBv2Request) throws -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream() + let index = lock.withLock { + submitted.append(request) + continuations.append(continuation) + produced.append([]) + return submitted.count - 1 + } + func emit(_ text: String) { + let tokens = GemmaThoughtTestTokenizer.tokens(text) + lock.withLock { produced[index] += tokens } + continuation.yield(.delta(text: text, tokens: tokens, logprobs: nil)) + } + if index == 0 { + emit("<|channel>") + emit("thought\n") + if !loopInsideThought { + emit("ok") + emit("") + } + let clause = Array("Wait, the carbon count is 19. ") + for position in 0...makeStream().continuation } + return (continuations[index], submitted[index].promptTokens.count, produced[index].count) + } + continuation.yield(.finished( + reason: reason, usage: CBv2Usage(promptTokens: prompt, completionTokens: completion))) + continuation.finish() + } + + func cancel(_ id: CBv2RequestID) { + let index = lock.withLock { + cancels += 1 + return submitted.lastIndex { $0.id == id } + } + if let index { finish(index, .cancelled) } + } + + func capacity() -> CBv2CapacitySnapshot { + .init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0) + } + + func shutdown() async {} +} + +/// A retirement the engine holds until it releases it. +private final class RetirementGate: @unchecked Sendable { + private let lock = NSLock() + private var released = false + private var waiters: [CheckedContinuation] = [] + + var retirement: CBv2RequestRetirement { CBv2RequestRetirement { await self.wait() } } + + func wait() async { + await withCheckedContinuation { continuation in + let now = lock.withLock { () -> Bool in + if released { return true } + waiters.append(continuation) + return false + } + if now { continuation.resume() } + } + } + + func release() { + let pending = lock.withLock { () -> [CheckedContinuation] in + released = true + defer { waiters.removeAll() } + return waiters + } + pending.forEach { $0.resume() } + } +} + +/// The coordinator's path: the row is admitted atomically against its +/// first-content deadline, so its stream ends before its retirement, which this +/// engine holds 50 ms past the stop. The continuation (no deadline) is an +/// ordinary submission: it answers "Answer: B" and stops. +private final class AdmittedThoughtLoopEngine: CBv2Engine, @unchecked Sendable { + private let lock = NSLock() + private var submitted: [CBv2Request] = [] + private var continuations: [CBv2RequestID: AsyncStream.Continuation] = [:] + private var produced: [CBv2RequestID: Int] = [:] + private var gates: [CBv2RequestID: RetirementGate] = [:] + + var requests: [CBv2Request] { lock.withLock { submitted } } + + func submit( + _ request: CBv2Request, firstTokenDeadline: CBv2FirstTokenDeadlineAdmission + ) async throws -> CBv2FirstTokenDeadlineResult { + let gate = RetirementGate() + lock.withLock { gates[request.id] = gate } + return .admitted( + stream: start(request), + projectedWork: .bounded( + work: .init(prefillTokens: request.promptTokens.count, decodeTokens: 0, scheduledSteps: 1, mixedSteps: 0), + serviceDuration: .milliseconds(1)), + admittedAt: .now, retirement: gate.retirement) + } + + func submit(_ request: CBv2Request) throws -> AsyncStream { start(request) } + + private func start(_ request: CBv2Request) -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream() + let first = lock.withLock { + submitted.append(request) + continuations[request.id] = continuation + return submitted.count == 1 + } + func emit(_ text: String) { + let tokens = GemmaThoughtTestTokenizer.tokens(text) + lock.withLock { produced[request.id, default: 0] += tokens.count } + continuation.yield(.delta(text: text, tokens: tokens, logprobs: nil)) + } + if first { + emit("<|channel>") + emit("thought\n") + let clause = Array("Wait, the carbon count is 19. ") + for position in 0..<4_200 { emit(String(clause[position % clause.count])) } + } else { + for character in "Answer: B" { emit(String(character)) } + finish(request.id, .stop) + } + return stream + } + + private func finish(_ id: CBv2RequestID, _ reason: CBv2FinishReason) { + let (continuation, prompt, completion, gate) = lock.withLock { + defer { continuations[id] = nil } + return (continuations[id], submitted.first { $0.id == id }?.promptTokens.count ?? 0, produced[id] ?? 0, + gates[id]) + } + continuation?.yield(.finished( + reason: reason, usage: CBv2Usage(promptTokens: prompt, completionTokens: completion))) + continuation?.finish() + // The row's engine resources retire a little after its terminal. + Task { + try? await Task.sleep(for: .milliseconds(50)) + gate?.release() + } + } + + func cancel(_ id: CBv2RequestID) { finish(id, .cancelled) } + + func capacity() -> CBv2CapacitySnapshot { + .init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0) + } + + func shutdown() async {} +} + +@Suite("Loop guard: a repeating thought ends in an answer (scheduler text path)") +struct GenerationLoopExitThinkingServingTests { + private let modelID = "mlx-community/gemma-4-26B-A4B-it-qat-4bit" + private static let tokenizer = TokenizerHandle(GemmaThoughtTestTokenizer()) + + private struct Outcome { + var content = "" + var reasoning = "" + var info: ServerGenerationInfo? + var error: (any Error)? + /// The `ends_thought` field of each loop-guard telemetry event (nil: the field is missing). + var loopGuardStops: [Bool?] = [] + } + + private final class TelemetrySink: @unchecked Sendable { + private let lock = NSLock() + private var received: [TelemetryEvent] = [] + func add(_ event: TelemetryEvent) { lock.withLock { received.append(event) } } + var loopGuardStops: [Bool?] { + lock.withLock { + received.filter { $0.fields?["operation"]?.description == "engine_v2_loop_guard" } + .map { $0.fields?["ends_thought"]?.value as? Bool } + } + } + } + + private func serve( + _ engine: ThoughtLoopCBv2Engine, modelType: String = "gemma4", maxTokens: Int = 8_192 + ) async throws -> Outcome { + let telemetry = TelemetrySink() + let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: Self.tokenizer, + eosTokenIds: [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos], defaultMaxTokens: 64, + maxConcurrentRequests: 1, emitTelemetry: { telemetry.add($0) }) + let id = modelID + let tokenizer = Self.tokenizer + let scheduler = MultiModelBatchSchedulerEngine(registryProvider: { + [id: .init(tokenizer: tokenizer, modelType: modelType, engineV2Bridge: bridge)] + }) + var outcome = try await consume(scheduler, maxTokens: maxTokens) + await bridge.shutdown() + outcome.loopGuardStops = telemetry.loopGuardStops + return outcome + } + + private func consume(_ scheduler: MultiModelBatchSchedulerEngine, maxTokens: Int) async throws -> Outcome { + let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data(""" + {"model":"\(modelID)","messages":[{"role":"user","content":"hi"}],"reasoning_parser":"gemma4",\ + "max_tokens":\(maxTokens)} + """.utf8)) + var outcome = Outcome() + var parser = StreamingReasoningParser(format: .gemma4) + func apply(_ parsed: ParsedReasoning) { + outcome.content += parsed.content + outcome.reasoning += parsed.reasoningContent ?? "" + } + do { + for try await event in try await scheduler.streamChatCompletion(request: request) { + switch event { + case .content(let text): parser.parse(text).forEach(apply) + case .parsed(let parsed): apply(parsed) + case .info(let info): outcome.info = info + case .toolCall, .toolCallDelta, .logprobs: break + } + } + } catch { outcome.error = error } + parser.finish().forEach(apply) + return outcome + } + + @Test("a loop inside the thought ends the thought; the answer continues and the usage counts every token") + func thoughtLoopEndsInAnAnswer() async throws { + let engine = ThoughtLoopCBv2Engine(loopInsideThought: true) + let outcome = try await serve(engine) + #expect(outcome.error == nil) + #expect(engine.cancelCount == 1) + let requests = engine.requests + #expect(requests.count == 2) + let first = try #require(requests.first) + let continuation = try #require(requests.last) + let firstOutput = try #require(engine.outputs.first) + // The same prompt, every token the row produced (the in-flight ones + // after the stop included), then the end of thinking. + #expect(continuation.promptTokens + == first.promptTokens + firstOutput + [GemmaThoughtTestTokenizer.channelClose]) + #expect(continuation.maxTokens == first.maxTokens - firstOutput.count - 1) + #expect(outcome.reasoning.hasPrefix("Wait, the carbon count is 19.")) + #expect(outcome.content == "Answer: B") + #expect(outcome.info?.stopReason == "stop") + #expect(outcome.info?.promptTokens == first.promptTokens.count) + #expect(outcome.info?.completionTokens == firstOutput.count + 1 + 9) + #expect(outcome.loopGuardStops == [true]) + } + + @Test("a loop in the answer, after the thought, still ends as length with nothing more submitted") + func answerLoopEndsAsLength() async throws { + let engine = ThoughtLoopCBv2Engine(loopInsideThought: false) + let outcome = try await serve(engine) + #expect(outcome.error == nil) + #expect(engine.cancelCount == 1) + #expect(engine.requests.count == 1) + #expect(outcome.info?.stopReason == "length") + #expect(outcome.content.hasPrefix("Wait, the carbon count is 19.")) + #expect(outcome.loopGuardStops == [false]) + } + + @Test("a thought loop that used the whole budget ends as length, with nothing more submitted") + func noBudgetLeft() async throws { + let engine = ThoughtLoopCBv2Engine(loopInsideThought: true) + // The row produces 1 + 8 + 4,200 tokens; the marker would be the 4,210th. + let outcome = try await serve(engine, maxTokens: 4_210) + let firstOutput = try #require(engine.outputs.first) + #expect(firstOutput.count == 4_209) + #expect(engine.requests.count == 1) + #expect(outcome.error == nil) + #expect(outcome.info?.stopReason == "length") + #expect(outcome.info?.completionTokens == 4_209) + #expect(outcome.content.isEmpty) + #expect(outcome.loopGuardStops == [true]) + } + + @Test("the bridge reports a row's serving slot released only after its pump's cleanup") + func waitForRowRelease() async throws { + let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, loopTokens: 64) + let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: Self.tokenizer, + eosTokenIds: [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos], defaultMaxTokens: 64, + maxConcurrentRequests: 1) + let request = MultiModelBatchSchedulerEngine.translate( + openAIRequest: try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data(""" + {"model":"\(modelID)","messages":[{"role":"user","content":"hi"}],"max_tokens":256} + """.utf8)), defaultMaxTokens: 64) + let stream = await bridge.submitTokenized( + promptTokens: GemmaThoughtTestTokenizer.tokens("<|turn>user\nhi\n<|turn>model\n"), + request: request, requestId: "row-1") + // The row still runs: its slot is still held. + #expect(await bridge.waitForRowRelease(requestId: "row-1", within: .milliseconds(50)) == false) + await bridge.cancel(requestId: "row-1") + for await _ in stream {} + #expect(await bridge.waitForRowRelease(requestId: "row-1", within: .seconds(5))) + await bridge.shutdown() + } + + @Test("on a full Mac, a row admitted against its deadline still gets its continuation once it retires") + func fullMacAtomicAdmission() async throws { + let engine = AdmittedThoughtLoopEngine() + let budget = GlobalKVCacheBudget(capFraction: 0.9, activationReserveBytes: 0) { + .init(total: 8 << 30, active: 0, cache: 0, systemAvailable: 8 << 30) + } + // Every whole-Mac slot is busy but the one this request takes. + let width = ServingPerformanceProfiles.legacyWholeMacConcurrency + for slot in 0..<(width - 1) { + #expect(budget.serviceBudget.acquire(ownerID: "busy-\(slot)", concurrency: width)) + } + let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: Self.tokenizer, + eosTokenIds: [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos], defaultMaxTokens: 64, + maxConcurrentRequests: 1, prefillDeadlineMode: .enforce, kvBytesPerToken: 4_000, kvBudget: budget) + await bridge.setMeasurementActivity(EngineMeasurementActivity()) + await bridge.updatePrefillTpsEwma(2_000, isolated: true) + let id = modelID + let tokenizer = Self.tokenizer + let scheduler = MultiModelBatchSchedulerEngine( + registryProvider: { [id: .init(tokenizer: tokenizer, modelType: "gemma4", engineV2Bridge: bridge)] }, + firstContentDeadline: FirstContentDeadline(relativeBudgetMilliseconds: 60_000)) + let outcome = try await consume(scheduler, maxTokens: 8_192) + await bridge.shutdown() + #expect(outcome.error == nil) + #expect(engine.requests.count == 2) + #expect(outcome.info?.stopReason == "stop") + #expect(outcome.content == "Answer: B") + } + + @Test("a family without the exit keeps today's length") + func otherFamilyKeepsLength() async throws { + let engine = ThoughtLoopCBv2Engine(loopInsideThought: true) + let outcome = try await serve(engine, modelType: "qwen3_5") + #expect(engine.requests.count == 1) + #expect(outcome.info?.stopReason == "length") + #expect(outcome.loopGuardStops == [false]) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift new file mode 100644 index 0000000000..6c499059a0 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift @@ -0,0 +1,250 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// ASCII bytes plus Gemma 4's turn and thought markers, each one special token. +struct GemmaThoughtTestTokenizer: MLXLMCommon.Tokenizer { + static let channelOpen = 1000 + static let channelClose = 1001 + static let turnClose = 1002 + static let eos = 1003 + static let specials: [(String, Int)] = [ + ("<|channel>", 1000), ("", 1001), ("", 1002), ("", 1003), ("<|turn>", 1004), + ] + + var markers = Self.specials + + static func tokens(_ text: String, markers: [(String, Int)] = specials) -> [Int] { + let bytes = Array(text.utf8) + var ids: [Int] = [] + var index = 0 + while index < bytes.count { + if let marker = markers.first(where: { bytes[index...].starts(with: Array($0.0.utf8)) }) { + ids.append(marker.1) + index += marker.0.utf8.count + } else { + ids.append(Int(bytes[index])) + index += 1 + } + } + return ids + } + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { Self.tokens(text, markers: markers) } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.compactMap(convertIdToToken).joined() + } + func convertTokenToId(_ token: String) -> Int? { markers.first { $0.0 == token }?.1 } + func convertIdToToken(_ id: Int) -> String? { + if let marker = markers.first(where: { $0.1 == id }) { return marker.0 } + guard (0..<128).contains(id), let scalar = UnicodeScalar(id) else { return nil } + return String(Character(scalar)) + } + var bosToken: String? { nil } + var eosToken: String? { "" } + var unknownToken: String? { nil } + /// The served Gemma 4 template's shape with thinking on: the model turn + /// is open and the model opens its own thought. + func applyChatTemplate( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + Self.tokens("<|turn>user\nhi\n<|turn>model\n", markers: markers) + } +} + +@Suite("Loop guard: ending a repeating thought") +struct GenerationLoopExitThinkingTests { + private func gemmaExit(startsInside: Bool = false) -> GenerationLoopExitThinking { + GenerationLoopExitThinking( + openMarker: "<|channel>", closeMarker: "", exitTokens: [GemmaThoughtTestTokenizer.channelClose], + exitText: "", startsInside: startsInside, record: GenerationLoopExitRecord()) + } + + private func loopGuard(_ exit: GenerationLoopExitThinking?) -> GenerationLoopGuard { + GenerationLoopGuard( + modelType: "gemma4", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers, + exitThinking: exit) + } + + /// Window 7's Gemma q63: one 19-token clause, verbatim. + private func clause(_ count: Int) -> [(String, [Int])] { + let block = Array(900..<919) + return (0.. (GenerationLoopDetector.Detection?, [Int]) { + var fed: [Int] = [] + for (text, tokens) in deltas { + fed += tokens + if let detection = loopGuard.observe(text: text, tokens: tokens) { return (detection, fed) } + } + return (nil, fed) + } + + @Test("a loop inside the thought asks to end the thought, and every token is kept") + func loopInsideThought() { + let exit = gemmaExit() + var loopGuard = loopGuard(exit) + let opening: [(String, [Int])] = [("<|channel>", [1000]), ("thought\n", [116, 10])] + let (detection, fed) = run(opening + clause(8_000), into: &loopGuard) + #expect(detection != nil) + #expect(loopGuard.endsThought) + #expect(exit.record.requested == detection) + // The in-flight deltas after the stop are kept too: the answer resumes after them. + var all = fed + for (text, tokens) in clause(3) { + all += tokens + #expect(loopGuard.observe(text: text, tokens: tokens) == nil) + } + #expect(exit.record.generatedTokens == all) + } + + @Test("a loop in the answer, after the thought closed, still ends the row as before") + func loopInAnswer() { + let exit = gemmaExit() + var loopGuard = loopGuard(exit) + let thought: [(String, [Int])] = [("<|channel>", [1000]), ("thought\nok", [116, 10, 111]), ("", [1001])] + let (detection, _) = run(thought + clause(8_000), into: &loopGuard) + #expect(detection != nil) + #expect(!loopGuard.endsThought) + #expect(exit.record.requested == nil) + } + + @Test("markers split across deltas are followed") + func splitMarkers() { + let exit = gemmaExit() + var opened = loopGuard(exit) + let (inside, _) = run([("<|chan", [60, 124]), ("nel>thought\n", [99, 10])] + clause(8_000), into: &opened) + #expect(inside != nil) + #expect(opened.endsThought) + + var closed = loopGuard(gemmaExit()) + let split: [(String, [Int])] = [("<|channel>", [1000]), ("thought\n", [62])] + let (outside, _) = run(split + clause(8_000), into: &closed) + #expect(outside != nil) + #expect(!closed.endsThought) + } + + @Test("a prompt that opened the thought starts inside it") + func startsInside() { + let exit = gemmaExit(startsInside: true) + var loopGuard = loopGuard(exit) + let (detection, _) = run(clause(8_000), into: &loopGuard) + #expect(detection != nil) + #expect(loopGuard.endsThought) + #expect(exit.record.requested != nil) + } + + @Test("without the exit, the guard keeps ending the row") + func withoutExit() { + var loopGuard = loopGuard(nil) + let (detection, _) = run([("<|channel>", [1000])] + clause(8_000), into: &loopGuard) + #expect(detection != nil) + #expect(!loopGuard.endsThought) + } + + @Test("a tool call turns the guard off: no stop and no exit") + func toolCallDisarms() { + let exit = gemmaExit() + var loopGuard = loopGuard(exit) + let call: [(String, [Int])] = [("<|channel>", [1000]), ("<|tool_call>", [48])] + let (detection, _) = run(call + clause(8_000), into: &loopGuard) + #expect(detection == nil) + #expect(exit.record.requested == nil) + } + + // MARK: Policy + + private static let tokenizer = GemmaThoughtTestTokenizer() + private static let prompt = GemmaThoughtTestTokenizer.tokens("<|turn>user\nhi\n<|turn>model\n") + + private func resolve( + _ modelType: String?, tokenizer: GemmaThoughtTestTokenizer = Self.tokenizer, prompt: [Int] = Self.prompt, + logprobs: Bool = false, + setting: GenerationLoopExitThinkingPolicy.Setting = + .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes) + ) -> GenerationLoopExitThinking? { + GenerationLoopExitThinkingPolicy.resolve( + modelType: modelType, tokenizer: tokenizer, promptTokens: prompt, logprobs: logprobs, setting: setting) + } + + @Test("on by default for Gemma 4 only, with its close marker as the exit") + func defaultModelTypes() throws { + for modelType in ["gemma4", "gemma4_text", "GEMMA4"] { + let exit = try #require(resolve(modelType), "\(modelType)") + #expect(exit.exitTokens == [GemmaThoughtTestTokenizer.channelClose]) + #expect(exit.exitText == "") + #expect(!exit.startsInside) + } + for modelType in ["qwen3_5", "qwen3_5_moe", "qwen4_exp", "gpt_oss", "nemotron_h", "glm5_next", "mimo_v2", + "diffusion_gemma", "llama"] { + #expect(resolve(modelType) == nil, "\(modelType)") + } + #expect(resolve(nil) == nil) + } + + @Test("DARKBLOOM_LOOP_EXIT_THINKING turns it off or names the model types") + func environmentOverride() { + let key = GenerationLoopExitThinkingPolicy.environmentKey + let defaults = GenerationLoopExitThinkingPolicy.Setting.modelTypes( + GenerationLoopExitThinkingPolicy.defaultModelTypes) + #expect(GenerationLoopExitThinkingPolicy.setting(environment: [:]) == defaults) + #expect(GenerationLoopExitThinkingPolicy.setting(environment: [key: "on"]) == defaults) + #expect(GenerationLoopExitThinkingPolicy.setting(environment: [key: "0"]) == .off) + #expect(GenerationLoopExitThinkingPolicy.setting(environment: [key: "off"]) == .off) + let listed = GenerationLoopExitThinkingPolicy.setting(environment: [key: " gemma4_text , qwen3_5 "]) + #expect(listed == .modelTypes(["gemma4_text", "qwen3_5"])) + #expect(resolve("gemma4", setting: .off) == nil) + #expect(resolve("gemma4", setting: listed) == nil) + #expect(resolve("gemma4_text", setting: listed) != nil) + // A listed family without a known marker stays off. + #expect(resolve("qwen3_5", setting: listed) == nil) + } + + @Test("never with logprobs, and never without the marker token") + func logprobsAndMissingMarker() { + #expect(resolve("gemma4", logprobs: true) == nil) + var without = Self.tokenizer + without.markers.removeAll { $0.0 == "" } + #expect(resolve("gemma4", tokenizer: without) == nil) + } + + @Test("the prompt's tail decides whether output starts inside the thought") + func promptTail() { + // The probe reads the last 8 prompt tokens; this tokenizer spells text byte by byte. + let primed = GemmaThoughtTestTokenizer.tokens("<|turn>model\n<|channel>") + let closed = GemmaThoughtTestTokenizer.tokens("<|turn>model\n<|channel>") + #expect(resolve("gemma4", prompt: primed)?.startsInside == true) + #expect(resolve("gemma4", prompt: closed)?.startsInside == false) + #expect(resolve("gemma4", prompt: Self.prompt)?.startsInside == false) + } + + @Test("darkbloom start passes the loop guard's and the exit's switches to the launchd daemon") + func launchdPassthrough() { + for key in [GenerationLoopExitThinkingPolicy.environmentKey, GenerationLoopGuardPolicy.environmentKey] { + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key), "\(key)") + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0", "\(key)") + } + } + + @Test("the guard's policy carries the exit to the guard") + func guardPolicyCarriesTheExit() throws { + let request = OpenAIChatCompletionRequest( + model: "m", messages: [.init(role: .user, content: .text("hi"))], maxTokens: 131_072) + let exit = gemmaExit() + let loopGuard = try #require(GenerationLoopGuardPolicy.resolve( + modelType: "gemma4", request: request, + prepared: try ToolChoicePromptPolicy.prepare(request, modelType: "gemma4"), + tokenConstraint: nil, setting: .modelTypes(["gemma4"]), exitThinking: exit)) + #expect(loopGuard.exitThinking?.record === exit.record) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26EncodedMediaIngressTests.swift b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26EncodedMediaIngressTests.swift index fe2dcfa0b4..08c3be24bf 100644 --- a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26EncodedMediaIngressTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26EncodedMediaIngressTests.swift @@ -340,6 +340,11 @@ final class MiMoV26EncodedMediaIngressTests: XCTestCase { ]]] requests.append(("/v1/chat/completions", try JSONSerialization.data(withJSONObject:mixed))) let immutableRequests = requests + // Each request's media reservation settles on an engine-queue callback + // after its terminal event, so wait for that settlement, not the joins. + let removals = EventCounter() + value.transaction.setMediaReservationRemovalHookForTesting { removals.increment() } + let settled = removals.expectation(reaching: immutableRequests.count, "media reservations settled") try await app.test(.router) { client in for (index, request) in immutableRequests.enumerated() { try await client.execute(uri:request.path, method:.post, @@ -372,14 +377,7 @@ final class MiMoV26EncodedMediaIngressTests: XCTestCase { XCTAssertEqual(owners.acquisitions,5) XCTAssertEqual(actual.mtpMetricsSnapshot()?.draftedTokens,0,"media remains target-only") for lease in owners.all { await lease.joinFromOutside() } - // The bridge returns the terminal before the row's native retirement - // (`EngineV2Bridge+Events`), and the leases are host ownership only, so - // the media reservation settles on the engine queue just after. Wait - // for it; a leaked reservation still fails here. - let settled = ContinuousClock.now + .seconds(10) - while value.transaction.managedMediaReservationCountForTesting != 0, ContinuousClock.now < settled { - try await Task.sleep(for: .milliseconds(5)) - } + await fulfillment(of:[settled],timeout:10) XCTAssertEqual(value.transaction.managedMediaReservationCountForTesting,0) try await drain(value,bundle,actual) } diff --git a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift index 5eaa41e5bc..37df8a7910 100644 --- a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift @@ -239,6 +239,12 @@ final class MiMoV26ManagedAudioProviderTests: XCTestCase { },tokenizerProvider:{ _ in .init(tokenizer:value.tokenizer,modelType:"mimo_v2") }, availableModels:{ ["audio-fixture"] },mtpSlots:{ [] }, modelTypeProvider:{ _ in "mimo_v2" }) + // The engine delivers the stream's terminal event, then settles the + // request's one media reservation on a later engine-queue callback. + // The lease can join first, so wait for the settlement itself. + let removals = EventCounter() + value.transaction.setMediaReservationRemovalHookForTesting { removals.increment() } + let settled = removals.expectation(reaching:1,"media reservation settled") phase("sending authenticated media") try await app.test(.router) { client in try await client.execute(uri:"/v1/chat/completions",method:.post, @@ -265,16 +271,9 @@ final class MiMoV26ManagedAudioProviderTests: XCTestCase { } await lease.joinFromOutside() phase("owner joined") + await fulfillment(of:[settled],timeout:10) XCTAssertGreaterThan(actual.stepCount,before) XCTAssertEqual(lease.snapshot().phase,.completed) - // The bridge returns the terminal before the row's native retirement - // (`EngineV2Bridge+Events`), and the lease is host ownership only, so - // the media reservation settles on the engine queue just after. Wait - // for it; a leaked reservation still fails here. - let settled = ContinuousClock.now + .seconds(10) - while value.transaction.managedMediaReservationCountForTesting != 0, ContinuousClock.now < settled { - try await Task.sleep(for: .milliseconds(5)) - } XCTAssertEqual(value.transaction.managedMediaReservationCountForTesting,0) XCTAssertNil(actual.nativeCompletionFault) let receipt = try await retire(value) @@ -302,7 +301,12 @@ final class MiMoV26ManagedAudioProviderTests: XCTestCase { let waveBody = Array("WAVEfmt ".utf8) + u32(16) + fmt + Array("data".utf8) + u32(UInt32(pcm.count)) + pcm let wave = Data(Array("RIFF".utf8) + u32(UInt32(waveBody.count)) + waveBody) + // Each request's media reservation settles on an engine-queue callback + // after its terminal event, so wait for that settlement, not the join. + let removals = EventCounter() + value.transaction.setMediaReservationRemovalHookForTesting { removals.increment() } for responses in [false, true] { + let settled = removals.expectation(reaching: responses ? 2 : 1, "media reservation settled") let messages: [[String: Any]] = [["role": "user", "content": [ ["type": "input_audio", "input_audio": ["format": "wav", "data": wave.base64EncodedString()]], ["type": responses ? "input_text" : "text", "text": "describe"], @@ -339,6 +343,7 @@ final class MiMoV26ManagedAudioProviderTests: XCTestCase { } } await lease.joinFromOutside() + await fulfillment(of: [settled], timeout: 10) XCTAssertEqual(infos, 1) XCTAssertGreaterThan(actual.stepCount, before, "normal encoded-audio route must execute the real native engine") XCTAssertEqual(lease.snapshot().phase, .completed)