diff --git a/.abcd/development/intents/drafts/itd-2610071208598233-the-context-probe-measures-whether-a-model-accepts-and.md b/.abcd/development/intents/drafts/itd-2610071208598233-the-context-probe-measures-whether-a-model-accepts-and.md new file mode 100644 index 00000000..4e42b87e --- /dev/null +++ b/.abcd/development/intents/drafts/itd-2610071208598233-the-context-probe-measures-whether-a-model-accepts-and.md @@ -0,0 +1,43 @@ +--- +id: itd-2610071208598233 +slug: the-context-probe-measures-whether-a-model-accepts-and +spec_id: null +kind: null +suggested_kind: null +reclassification_history: [] +builds_on: [] +severity: minor +related_issues: [iss-2610041945033770] +origin: extracted-from-record +production_mode: hand-written +--- + +# The context probe measures whether a model accepts and answers a prompt of a given size, not whether it can use that much context. Its measured window says a prompt that long loaded, prefilled and got an answer before a bound stopped the probe. It does not show that the model retrieves or reasons over content near the start of that window. Published long-context evaluations show the two differ widely. RULER (arXiv:2404.06654) found models that score near-perfectly on vanilla needle-in-a-haystack retrieval yet degrade sharply as context grows, with few holding up at 32K despite claiming more. HELMET (2024, updated 2025) reaches the same conclusion with broader tasks. A served window set from the probe can therefore advertise context a model cannot actually use. + +## Press Release + +> _Seeded by promotion from iss-2610041945033770. Expand into the full press-release narrative before planning._ + +## Why This Matters + +Graduated from `iss-2610041945033770`: The context probe measures whether a model accepts and answers a prompt of a given size, not whether it can use that much context. Its measured window says a prompt that long loaded, prefilled and got an answer before a bound stopped the probe. It does not show that the model retrieves or reasons over content near the start of that window. Published long-context evaluations show the two differ widely. RULER (arXiv:2404.06654) found models that score near-perfectly on vanilla needle-in-a-haystack retrieval yet degrade sharply as context grows, with few holding up at 32K despite claiming more. HELMET (2024, updated 2025) reaches the same conclusion with broader tasks. A served window set from the probe can therefore advertise context a model cannot actually use.. Read that issue record for the source observation. + +## Mechanism + +> _Prompted (the claim-recording gradient): why the authors expect this to work, as a falsifiable "we expect X because Y" — not the outcome restated. Replace this line with the claim, or with the exact token `None stated.` alone on its line to record the claim as considered and declined._ + +## Scope Conditions + +> _Required (the claim-recording gradient): the population, platform, scale, or assumptions this claim holds under, one per top-level bullet — `abcd intent plan` stamps each with a persistent identity. Replace this line with those bullets, or with the exact token `None stated.` alone on its line._ + +## Acceptance Criteria + +> _Required (the itd-1 discipline): add at least one Given-When-Then bullet describing the verifiable bar for "shipped" before this draft can be planned._ + +## Open Questions + +_None recorded yet._ + +## Audit Notes + +_Empty. Populated by intent-auditor when intent moves to shipped/._ diff --git a/.abcd/development/intents/shipped/itd-2610030857275099-dessau-tells-alice-when-a-model-she-downloaded-has-a-newer.md b/.abcd/development/intents/shipped/itd-2610030857275099-dessau-tells-alice-when-a-model-she-downloaded-has-a-newer.md index 1a656a05..56116083 100644 --- a/.abcd/development/intents/shipped/itd-2610030857275099-dessau-tells-alice-when-a-model-she-downloaded-has-a-newer.md +++ b/.abcd/development/intents/shipped/itd-2610030857275099-dessau-tells-alice-when-a-model-she-downloaded-has-a-newer.md @@ -251,6 +251,15 @@ Scope-condition dispositions: evidence: cmd/dessau/main.go:338 — "a, err := app.New(app.Options{Paths: paths, Config: cfg, Log: log, Bind: plan, LogLevel: appLog.Level})" +2026-10-07 — Criterion 9's mark is withdrawn by the maintainer's decision of +2026-10-07 (iss-2610042101436891): the press release stands, and a decision +model is never marked. The update check records a decision model's newer +version that no Dessau release has reviewed as nothing to offer, which the +panel shows with no mark and no Update; the `awaiting_review` status is gone +from the check, the registry and the panel. A reviewed version is still the +only one a decision model is offered or fetched at. iss-2610042101435880 is +moot (wontfix). The criterion's text above is left as shipped. + ## Grounds - pursued: fixes to chat templates, settings and quantisations land on HuggingFace silently, so Alice serves stale builds without knowing; shown wrong if, over a month of daily checks, no model she uses changes in a file Dessau reads. And the only way to update today, downloading again, can leave a half-old, half-new model, which a safe one-click update fixes; shown wrong if no one ever re-downloads a changed model. diff --git a/.abcd/work/DECISIONS.md b/.abcd/work/DECISIONS.md index 24fc7217..ab4362da 100644 --- a/.abcd/work/DECISIONS.md +++ b/.abcd/work/DECISIONS.md @@ -456,3 +456,18 @@ - 2026-10-07 — **The update check reads an LFS `config.json` from the content CDN, and a version whose config it cannot hold to the listed hash is `cannot_check`, never offered** (iss-2610042101439623; branch `fix/update-check-lfs-config`; `impact: fix`). The check treated the Hub's hand-off of an LFS `config.json` to its CDN (`ErrCrossOrigin`) as "offer it", so a newer version that names a `model_file` was marked `available`. `SmallFileAt` now takes the listed `File`: a git file still goes through `do` and its origin rule unchanged; a file the listing keeps in LFS with a 64-hex sha256 goes through `doContent`, which follows the CDN hop as the download does — the 2026-09-19 exception, extended to this one read and only where a sha256 anchors the bytes — drops the token from any hop off the Hub's origin, refuses a listed size past the 1 MiB bound before asking, and holds the body to the sha256 (`ErrContentMismatch`). Off-origin with no sha256, a mismatch, or past the bound records the new `cannot_check` status (card "newer version not checked", Update refused in Go and on the panel); a CDN or Hub that does not answer stays "unreachable" as before. Chosen over a status alone because reading the file is what names a version that ships code, which is the mark the card exists to show. What would show this wrong: a CDN that needs the token, which would turn every gated repository's LFS config into `cannot_check`. - 2026-10-07 — **The idle clock counts client requests at the gateway, beside the pool's per-model figures** (iss-2610041945030758; branch `fix/idle-clock-counts-unreachable`; `impact: fix`). The idle check read only `Pool.Residency()`: each resident entry's `InFlight` and `lastUsed`. An entry that leaves the pool (unloaded, stopped by the health watch, crashed, evicted, reaped) takes its last use with it, and a request the pool never admitted (still uploading, refused, failed before a model was chosen) never touched one; so an unreachable request on a wedged model that was then taken out left no trace, and the remaining models' 17:34 last use was over the hour by 18:45. The pool was left alone: a pool-wide clock there would still miss requests that never reach `Acquire` and would put the change inside `internal/runtime`. Instead `selftest.Clients` counts every request to the completion routes and every `Ask` from the handler's start to its return, the gateway holds it through `Options.Clients` (wired in `cmd/dessau` from `App.Clients`), and `selftest.Activity` carries `Requests` and `LastRequest` to `heldBy`. The context probe drives its model through the gateway, so a last request no later than the loop's own latest release (`touched`) is discounted, as the pool's stamp of that release already is; the cost is that a client request that never reached the pool and ended entirely inside a run is discounted too. What would show this wrong: an idle job starting within the threshold of a client request that ended unreachable, or one held for the threshold after the probe's own run. - 2026-10-07 — **The decision-model over-charge is folded into the decision-model spec, with no stopgap** (iss-2610041945038826; spc-2610030846273729 steps 2 and 4). Diagnosis showed that the charge is the automatic served window filling the budget, which applies to every model, not a decision-model KV reservation. The maintainer chose the spec over a joint-head stopgap with a guessed figure, and over reopening the 2026-09-20 window derivation for all models. +- 2026-10-07 — **The self-test skips models that cannot chat** (iss-2610041945034263; maintainer, interview). Already the behaviour since a0264236, now stated in docs/self-test.md. A short decision-model test is seeded for after itd-2610030656210408 (iss-2610071209008023). +- 2026-10-07 — **Decision models are never marked 'awaiting review'** (iss-2610042101436891; maintainer, interview). The press release of itd-2610030857275099 stands over its criterion 9 and the mark is removed, so iss-2610042101435880 is moot (wontfix). +- 2026-10-07 — **Admit what is charged** (iss-2610071035138788; maintainer, interview). Each model's semaphore is sized to decode_concurrency, not twice it, so at the default a second request to one model waits. +- 2026-10-07 — **The prompt cache is bounded within the existing charge** (iss-2610071035130302; maintainer, interview). The bound is one served window's uninflated KV per model, and the charge is not raised. +- 2026-10-07 — **The update card lists the changed files and tests their rendering** (iss-2610042101436222; maintainer, interview), rather than dropping the file-name half of criterion 11. +- 2026-10-07 — **The context probe's usability check becomes an intent** (iss-2610041945033770 promoted to itd-2610071208598233; maintainer, interview). +- 2026-10-07 — **Connections are capped per client address plus a global cap per listener** (iss-2609190254516275; maintainer, interview). +- 2026-10-07 — **Two open issues were not asked because the record already settles them**: `logit_bias` stays refused (the 2026-10-03 decision on iss-2610031811486498), and released unloads belong in the Statistics tab under the AGENTS.md panel-gap rule (iss-2610042100405045). +- 2026-10-07 — **The gateway refuses a request body that is not valid UTF-8 with a 400** (iss-2610042036094209; branch `fix/gateway-invalid-utf8`; `impact: fix`). A check of the body's encoding reads no field, and is the same kind of check as the JSON syntax check, so it is not the "further reading of prompt content" adr-2610042021365934 reserves for a new decision. It replaces the 2026-09-06 line's relaying of invalid UTF-8 system content: on the network path such a body is now refused before any merge. The merge also declines content carrying a lone surrogate escape, which it would otherwise rewrite to U+FFFD. +- 2026-10-07 — **A bridged request asks for half the model's served window as `max_tokens`, and an answer the gateway reports as stopped on length says so** (iss-2610041945020793; branch `fix/bridge-answer-length`; `impact: fix`). `buildRequest` reserved `min(1024, window/2)` for the answer; the fixed 1,024 is dropped and the `window/2` it already fell back to becomes the rule, so the history keeps the other half and the two still fit the window the gateway judges. Taken over giving the answer whatever the history leaves (unchanged history, but the answer shrinks back towards 1,024 as a channel grows) as the split `buildRequest` already used. `deltaText` now also reads `finish_reason`; a stream ending on `length` with an answer posts "The answer reached its length limit and stops there." as a message of its own (not kept in the history), and with no answer written says the model reached its length limit before it wrote one instead of "answered with nothing". Not decided here: a ceiling on long reasoning runs, which the 2026-10-03 long-answers note leaves as a product decision. +- 2026-10-07 — **The idle threshold reaches 24 hours** (iss-2610041948272032; branch `feat/self-test-idle-threshold`; `impact: additive`). The maintainer confirmed 24 hours as the cap on 2026-10-07: `MaxIdleThresholdSec` is 86400, and the config validation, the panel's Idle threshold field (`max="86400"`) and docs/context-probe.md move together, the field held to exactly the server's bounds by `TestTheIdleThresholdFieldSpansTheServersBounds` beside the three-surfaces narrower-than-Validate check. The minimum (60 s) and the default (300 s) are unchanged. What would show this wrong: an operator wanting a quiet spell longer than a day, or a threshold near the cap that leaves an idle job never running on a Mac that is used daily. +- 2026-10-07 — **The self-test waits for an idle threshold of its own, `self_test_idle_threshold_sec`, 4 hours unless set** (iss-2610041956214381; branch `feat/self-test-idle-threshold`; `impact: breaking`, on the 2026-09-20 `decode_concurrency` precedent that a changed default is breaking). The maintainer asked for the two idle jobs to be separated, the self-test waiting four hours by default while the context probe keeps `idle_threshold_sec`. The loop keeps one idea of what counts as use (`heldBy`, with the gateway's client count from iss-2610041945030758) and takes the quiet period per run: `selftest.Options.SelfTestQuiet` for the self-test's set, `Quiet` for a job; `App.applyIdleJobs` puts both in force at start and after every save, and a test's fixed `IdleOptions.Quiet` fixes both. The bounds are the idle threshold's (60–86,400 s); an unusable stored value is repaired on load, never refused at a save. No migration: an operator who had raised `idle_threshold_sec` to hold the self-test back sets the new key. What would show this wrong: a self-test run starting within its own threshold of a client request, or the probe held for the self-test's. +- 2026-10-07 — **The connection caps are 32 open connections per client address and 512 per listener, constants, loopback held to the 512 only** (iss-2609190254516275; agent, under the maintainer's decision above). 32 is several times any one machine's normal parallelism (URLSession and browsers hold six per host; the Discord bridge asks in-process and holds none) and half one model's 64-request queue, while sixteen addresses are needed to fill a listener; 512 is eight models' whole queues, more than this Mac holds loaded at once, at a cost of tens of megabytes. IPv6 is keyed by the full address, not the /64, so the 512 is the ceiling a peer that mints addresses meets. Loopback is exempt from the per-address cap because every account on this Mac is one address and the cap would let one local client lock the panel out. Wrong if a debug log shows refusals for one legitimate machine or a NAT'd network in normal use (raise or key differently), if the 512 is reached with no hostile peer, or if descriptors run out before it. +- 2026-10-07 — **Loopback gets its own connection budget, not a share of the remote total** (iss-2609190254516275; security review of `fix/listener-connection-caps`). With a bind to `::`, the panel's `localhost` reaches the dual-stack wildcard listener as `::1`. If loopback shared the 512 with remote peers, a LAN machine filling it would lock the operator out of the panel. Loopback now counts against a 512 of its own, and remote peers against theirs. The 32-per-address cap is a guard against accidents, not a security boundary, on a LAN where addresses are free. Shown wrong if the panel is refused while remote peers hold the listener full. +- 2026-10-07 — **The prompt cache's bound is a stored real figure, and a model with none keeps no prompt cache** (iss-2610071035130302; branch `fix/runtime-budget-bounds`; `impact: fix`). Maintainer's follow-up: the uninflated per-token figure is stored as `kv_bytes_per_token` beside `kv_charge_per_token` (`KVShape.BytesPerToken`, from the same scan, held to the charge's bound and never above the charge) rather than derived at launch by dividing the charge. The launcher passes `--dessau-prompt-cache-bytes` (that figure times the served window) and `--prompt-cache-size 10`; `serve.py` hands the bound to `LRUPromptCache(max_bytes=)` and refuses a launch whose bound is missing, negative or not a whole number. A model whose figure or window is unknown follows the flat-charge precedent of `capability.LoadCostOf` (a documented fallback, not a refusal): the flat charge reserves no cache, so its bound is 0 and its server keeps nothing between requests. Upstream's own `--prompt-cache-bytes` is not passed: 0.32.0 applies it only as a trim on the batched path and never to the constructor. What would show this wrong: a real-Mac footprint sample of a model holding several long conversations above its charge, which is still owed. diff --git a/.abcd/work/issues/open/iss-2610041945033770-the-context-probe-measures-whether-a-model-accepts-and.md b/.abcd/work/issues/open/iss-2610041945033770-the-context-probe-measures-whether-a-model-accepts-and.md index 03a5af47..a9fe8fa2 100644 --- a/.abcd/work/issues/open/iss-2610041945033770-the-context-probe-measures-whether-a-model-accepts-and.md +++ b/.abcd/work/issues/open/iss-2610041945033770-the-context-probe-measures-whether-a-model-accepts-and.md @@ -10,6 +10,7 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/app/contextprobe.go" remedy: "Extend the context probe, rather than adding a new tool, with a usability check at its measured size: RULER-style multi-needle retrieval at several depths (arXiv:2404.06654), scored and recorded beside measured_context, so the window Dessau publishes is one the model retrieves from correctly, not only one it accepts." +related_intents: [itd-2610071208598233] --- The context probe measures whether a model accepts and answers a prompt of a given size, not whether it can use that much context. Its measured window says a prompt that long loaded, prefilled and got an answer before a bound stopped the probe. It does not show that the model retrieves or reasons over content near the start of that window. Published long-context evaluations show the two differ widely. RULER (arXiv:2404.06654) found models that score near-perfectly on vanilla needle-in-a-haystack retrieval yet degrade sharply as context grows, with few holding up at 32K despite claiming more. HELMET (2024, updated 2025) reaches the same conclusion with broader tasks. A served window set from the probe can therefore advertise context a model cannot actually use. diff --git a/.abcd/work/issues/open/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md b/.abcd/work/issues/open/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md deleted file mode 100644 index 6c4ee791..00000000 --- a/.abcd/work/issues/open/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -schema_version: 1 -id: "iss-2610071035130302" -slug: "the-model-server-s-prompt-cache-has-no-byte-limit-so-cached" -severity: "minor" -category: "bug" -source: "agent-finding" -found_during: "SOTA research on MLX serving performance, 2026-10-07" -origin: researcher-authored -production_mode: hand-written -found_at: "internal/runtime/serve.py" -remedy: "Pass max_bytes to LRUPromptCache in serve.py, derived from the model's charged KV allowance (and pass --prompt-cache-size explicitly), with a test that the bound reaches the constructor; verify on a Mac with the launcher's footprint sampling that peak memory stays within the charge." ---- - -The model server's prompt cache has no byte limit, so cached prompts grow outside the memory budget. internal/runtime/serve.py builds server.LRUPromptCache(cli.prompt_cache_size) with the entry count only, so mlx-lm 0.32.0's default of 10 entries and 2^63 bytes applies; upstream's --prompt-cache-bytes flag is parsed but not applied (ml-explore/mlx-lm PR 1392, open, which reports Metal running out of memory on long-running servers). docs/memory-budget-explained.md already says caches stack across requests. Each cached entry can hold a whole served window's KV, so a model serving several long conversations can hold several windows' worth of cache that the charge (one window per sequence) does not count. diff --git a/.abcd/work/issues/open/iss-2610071209008023-the-self-test-skips-every-model-that-cannot-chat-so-a.md b/.abcd/work/issues/open/iss-2610071209008023-the-self-test-skips-every-model-that-cannot-chat-so-a.md new file mode 100644 index 00000000..72b6c481 --- /dev/null +++ b/.abcd/work/issues/open/iss-2610071209008023-the-self-test-skips-every-model-that-cannot-chat-so-a.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2610071209008023" +slug: "the-self-test-skips-every-model-that-cannot-chat-so-a" +severity: "minor" +category: "future-work-seed" +source: "user-observation" +found_during: "maintainer interview on unsettled issues, 2026-10-07" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/app/selftest.go" +remedy: "After itd-2610030656210408 ships, add a short decision-model test to the self-test through the decision route, recorded beside the chat figures; until then the skip stands." +--- + +The self-test skips every model that cannot chat, so a decision model is never measured at all. Once itd-2610030656210408 lands, a decision model answers typed questions through its own route, and a short self-test there (latency for one typed question and its odds) would give Alice the same kind of figure chat models get, without a chat benchmark's cold load. diff --git a/.abcd/work/issues/open/iss-2610071214551838-a-pin-saved-in-the-settings-reaches-the-pool-a-moment-after.md b/.abcd/work/issues/open/iss-2610071214551838-a-pin-saved-in-the-settings-reaches-the-pool-a-moment-after.md new file mode 100644 index 00000000..824dea2a --- /dev/null +++ b/.abcd/work/issues/open/iss-2610071214551838-a-pin-saved-in-the-settings-reaches-the-pool-a-moment-after.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2610071214551838" +slug: "a-pin-saved-in-the-settings-reaches-the-pool-a-moment-after" +severity: "minor" +category: "bug" +source: "review-followup" +found_during: "security review of the idle-unload pin race fix (iss-2610042033419572), 2026-10-07" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/app/app.go" +remedy: "Call Pool.SetPinned before releasing cfgMu on every settings write that changes pins, after confirming that no path holding p.mu ever takes cfgMu (the pool's callbacks into the app, such as the served-window and budget reads), with a test that holds the lock order; if that order cannot be guaranteed, say so and leave the window documented." +--- + +A pin saved in the settings reaches the pool a moment after the configuration says it is pinned. The settings writers (internal/app/app.go, the save and the spelling adoption around line 1188) write the per-model settings under cfgMu, release it, then call Pool.SetPinned, which takes p.mu. An idle job's unload in that gap reads the pool's pin set, which does not yet hold the new pin, and stops a model the operator has just pinned. The window is microseconds wide; iss-2610042033419572 closed the larger window between the idle job's own check and its stop, and the security review of that fix named this remaining one. diff --git a/.abcd/work/issues/open/iss-2610071228050036-testsavingthesamesettingsrestartsabridgediscordstopped.md b/.abcd/work/issues/open/iss-2610071228050036-testsavingthesamesettingsrestartsabridgediscordstopped.md new file mode 100644 index 00000000..7fee8d54 --- /dev/null +++ b/.abcd/work/issues/open/iss-2610071228050036-testsavingthesamesettingsrestartsabridgediscordstopped.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2610071228050036" +slug: "testsavingthesamesettingsrestartsabridgediscordstopped" +severity: "minor" +category: "bug" +source: "agent-observation" +found_during: "full test runs of the 2026-10-07 fix lanes" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/bridge/discord" +remedy: "Run it with -race -count=200 beside a CPU-bound load until it fails, keep the message, and root-cause it; a failing test is not a flake until shown to be one." +--- + +TestSavingTheSameSettingsRestartsABridgeDiscordStopped (internal/bridge/discord) failed once during a full make test run on 2026-10-07 and passed on its own with -count=5 and on the full re-run. It was seen on a base without any of that day's bridge changes, so it predates them. The failure message was not kept. diff --git a/.abcd/work/issues/open/iss-2610071231371995-request-bodies-can-hold-a-large-share-of-this-mac-s-memory.md b/.abcd/work/issues/open/iss-2610071231371995-request-bodies-can-hold-a-large-share-of-this-mac-s-memory.md new file mode 100644 index 00000000..f37faf3f --- /dev/null +++ b/.abcd/work/issues/open/iss-2610071231371995-request-bodies-can-hold-a-large-share-of-this-mac-s-memory.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2610071231371995" +slug: "request-bodies-can-hold-a-large-share-of-this-mac-s-memory" +severity: "minor" +category: "security" +source: "review-followup" +found_during: "security review of the connection caps (iss-2609190254516275), 2026-10-07" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/gateway/gateway.go" +remedy: "Trace whether a queued request's body is retained while it waits; then bound the gateway's total in-flight body bytes (a byte budget taken before the read and released after forwarding) or lower maxRequestBody to what the largest served window can need, with a test that a flood of large bodies is refused before memory grows." +--- + +Request bodies can hold a large share of this Mac's memory at once when no API key is set. The gateway reads each body whole, io.ReadAll over http.MaxBytesReader at maxRequestBody (32 MiB, internal/gateway/gateway.go), after withAuth, which lets every client through on a keyless install. With the listener's 512-connection cap, partial bodies are bounded by bandwidth (about 30 s of throughput in flight, some 3.75 GB on gigabit, plus ReadAll's growth), and a complete body waiting in a model's queue may stay in memory for its wait; whether it does was not traced. Assessed by the security review of the connection caps, which bound it where nothing did before; the exposure itself predates that change. diff --git a/.abcd/work/issues/open/iss-2610071256503188-a-model-s-config-json-can-lower-its-own-memory-charge-by.md b/.abcd/work/issues/open/iss-2610071256503188-a-model-s-config-json-can-lower-its-own-memory-charge-by.md new file mode 100644 index 00000000..c8cd6cdd --- /dev/null +++ b/.abcd/work/issues/open/iss-2610071256503188-a-model-s-config-json-can-lower-its-own-memory-charge-by.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2610071256503188" +slug: "a-model-s-config-json-can-lower-its-own-memory-charge-by" +severity: "minor" +category: "security" +source: "review-followup" +found_during: "security review of the prompt-cache bound (iss-2610071035130302), 2026-10-07" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/registry/registry.go" +remedy: "Decide the latent cache type from more than one config key (the architecture's model_type among the latent families mlx-lm implements, with the rank and rope dimensions present and plausible), and charge the key-value figure whenever the evidence disagrees, with a registry test for a config that claims latent attention falsely." +--- + +A model's config.json can lower its own memory charge by claiming a compressed-latent cache it does not have. The registry reads the cache type from the config (a kv_lora_rank key marks latent attention) and charges a latent model's smaller per-token figure, so an ordinary key-value model whose config adds that key is under-charged against the memory budget, and the pool may load it beside models it does not fit with. The prompt-cache bound is not made worse by it, since mlx-lm measures cache entries by their real size. Found by the security review of the prompt-cache bound; it predates that change. diff --git a/.abcd/work/issues/open/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md b/.abcd/work/issues/resolved/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md similarity index 54% rename from .abcd/work/issues/open/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md rename to .abcd/work/issues/resolved/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md index a0da1e44..50776277 100644 --- a/.abcd/work/issues/open/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md +++ b/.abcd/work/issues/resolved/iss-2609190254516275-neither-listener-has-a-connection-or-concurrency-ceiling-bou.md @@ -9,6 +9,9 @@ found_during: "adversarial security review of the listener read-bound change" origin: researcher-authored production_mode: hand-written found_at: "cmd/dessau/listeners.go" +remedy: "Maintainer's decision 2026-10-07: cap per client address plus a global cap on each listener. Wrap both listeners so one remote address may hold at most a fixed number of open connections and the listener at most a fixed total; refuse (close) a connection over either cap before any read, with tests for both caps and for a loopback client; record the figures chosen and why." +resolution: "Every listener (plain and TLS, loopback and the bound address) is wrapped in one connCap in cmd/dessau/listeners.go: 32 open connections per client address (full address, loopback exempt) and 512 per listener, a connection over either closed on accept before any read, its slot freed once on close." +impact: fix --- Neither listener has a connection or concurrency ceiling. Bounding the request read converts 'one unauthenticated connection held forever' into 'held about fifteen seconds of headers plus thirty of body, then reconnect', which is a real improvement but is not the end of goroutine and connection exhaustion on /pair: a peer that reconnects in a loop still costs a goroutine and a socket per attempt, and nothing caps how many it may hold at once. iss-2609190226050845 should not be read as closing that. diff --git a/.abcd/work/issues/open/iss-2610032216257762-transcript-page-mixes-types.md b/.abcd/work/issues/resolved/iss-2610032216257762-transcript-page-mixes-types.md similarity index 77% rename from .abcd/work/issues/open/iss-2610032216257762-transcript-page-mixes-types.md rename to .abcd/work/issues/resolved/iss-2610032216257762-transcript-page-mixes-types.md index 830edea8..723e26b1 100644 --- a/.abcd/work/issues/open/iss-2610032216257762-transcript-page-mixes-types.md +++ b/.abcd/work/issues/resolved/iss-2610032216257762-transcript-page-mixes-types.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "docs/transcript.md" remedy: "Keep the how-to and the bridge and debug-logging rules on the page; move the recording field and the icons to the models-list reference, linking back." +resolution: "The recording field and the icons moved to the models-list reference (Recording); docs/transcript.md keeps the how-to with the bridge and debug-logging rules and links there" +impact: internal --- docs/transcript.md mixes Diátaxis types: a how-to (Mark a model), reference (the recording field and the icons) and explanation (the bridge and what the mark does not cover). It did before this change too. diff --git a/.abcd/work/issues/open/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md b/.abcd/work/issues/resolved/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md similarity index 85% rename from .abcd/work/issues/open/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md rename to .abcd/work/issues/resolved/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md index 5b3b0ff8..de86c809 100644 --- a/.abcd/work/issues/open/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md +++ b/.abcd/work/issues/resolved/iss-2610032231045098-a-tool-call-probe-requeue-can-be-lost-between-errgone-and-dequeue.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/toolprobe/probe.go" remedy: "Keep a requeue-requested flag (or a generation counter) on the queue head so an Enqueue that lands while the head is being served survives the dequeue." +resolution: "the queue head keeps an again flag that an Enqueue after the head's last look sets, so dequeue moves it to the back instead of dropping it" +impact: fix --- A tool-call probe re-queue can be lost: after a resident-only Acquire returns ErrGone, the other caller's load can finish and modelLoaded can call Enqueue before drain reaches dequeue; Enqueue skips the model because it is still queued, and dequeue then removes it, so the model goes unprobed until its next load. The window is microseconds against a load of seconds and the worst outcome is a missed probe, never a wrong verdict. diff --git a/.abcd/work/issues/open/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md b/.abcd/work/issues/resolved/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md similarity index 86% rename from .abcd/work/issues/open/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md rename to .abcd/work/issues/resolved/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md index 8ef4608d..d6381673 100644 --- a/.abcd/work/issues/open/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md +++ b/.abcd/work/issues/resolved/iss-2610041945020793-discord-bridge-answers-stop-silently-at-a-fixed-1-024-token.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/bridge/discord/conversation.go" remedy: "Size the bridge's max_tokens from the model's served window, as conversation.go already does for the history, instead of a fixed 1024; when an answer still stops on length, say so in the reply rather than ending silently or reporting that the model answered with nothing." +resolution: "The bridge asks for half the served window as max_tokens, the history keeping the other half, and a stream the gateway ends with finish_reason length is followed by a notice saying so" +impact: fix --- Discord bridge answers stop silently at a fixed 1,024-token cap. Every bridged request asks for max_tokens = answerTokens (1024, internal/bridge/discord/conversation.go, the same on main), whatever the model's served window. When the model reaches it the reply simply ends: mid-sentence, sometimes with markdown left open (an unclosed **). With a reasoning model the hidden reasoning spends the budget first. Nemotron-3.5-Lightning used 404 tokens to say a one-line hello, and one reply was 'The model answered with nothing.' (1,024 tokens, all reasoning). Seen 2026-10-04: three Nemotron answers and one Qwen3-Coder-Next answer each stopped at exactly 1,024 tokens. diff --git a/.abcd/work/issues/open/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md b/.abcd/work/issues/resolved/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md similarity index 88% rename from .abcd/work/issues/open/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md rename to .abcd/work/issues/resolved/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md index a295a315..1d889db8 100644 --- a/.abcd/work/issues/open/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md +++ b/.abcd/work/issues/resolved/iss-2610041945030524-the-discord-bridge-ignores-edited-messages-and-the-docs-do.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "docs/discord-bridge.md" remedy: "State in docs/discord-bridge.md that the bot reads a message only when it is sent, never an edit, so a mention or question added by editing is not answered and must be sent again as a new message." +resolution: "docs/discord-bridge.md's Limits now say the bot reads a message only when it is sent, never an edit" +impact: internal --- The Discord bridge ignores edited messages, and the docs do not say so. A message that gains its mention of the bot by an edit, or whose question is changed after sending, is never answered: the bridge reads a message only when it is created. That is a reasonable design, but docs/discord-bridge.md is silent on it, so to a user it looks like the bot has stopped working. Seen 2026-10-04 with an edited '@Dessau tell me more about epoché'. diff --git a/.abcd/work/issues/open/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md b/.abcd/work/issues/resolved/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md similarity index 86% rename from .abcd/work/issues/open/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md rename to .abcd/work/issues/resolved/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md index 69fb1e95..5cf12932 100644 --- a/.abcd/work/issues/open/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md +++ b/.abcd/work/issues/resolved/iss-2610041945034263-the-idle-time-self-test-runs-chat-benchmarks-on-non-chat.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/selftest/selftest.go" remedy: "The maintainer decides whether non-chat models are self-tested at all: either skip every model that cannot chat, as Load now does (iss-2610031010371709), or give decision models their own short test through /v1/systemone once itd-2610030656210408 lands; record the choice in docs/self-test.md." +resolution: "The self-test skips models that cannot chat (since a0264236); docs/self-test.md now says so, and a decision-model test is seeded as iss-2610071209008023" +impact: internal --- The idle-time self-test runs chat benchmarks on non-chat models. At 18:45 on 2026-10-04 it loaded mlx-community/clef-4bit, a decision model that cannot chat, to run pp512, tg128 and tg128xN through chat completions. Its previous self-test record for that model reads 'yielded'. A chat benchmark says nothing useful about a model that answers typed decisions, and it costs a cold load of a large model. Nothing records whether non-chat models (decision models, OCR models) should be self-tested at all. diff --git a/.abcd/work/issues/open/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md b/.abcd/work/issues/resolved/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md similarity index 77% rename from .abcd/work/issues/open/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md rename to .abcd/work/issues/resolved/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md index 71ccf47e..607cd70c 100644 --- a/.abcd/work/issues/open/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md +++ b/.abcd/work/issues/resolved/iss-2610041948272032-the-idle-threshold-cannot-be-set-above-one-hour-the-context.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/config/config.go" remedy: "Raise MaxIdleThresholdSec to 86400 (24 hours), changing the config validation, the panel's Idle threshold field and docs/context-probe.md together, with the three-surfaces test covering the new upper bound." +resolution: "MaxIdleThresholdSec is 86400 (24 hours): config validation, the panel's Idle threshold field (max=86400) and docs/context-probe.md moved together, the field held to the server's bounds by a test beside the three-surfaces check; confirmed by the maintainer on 2026-10-07." +impact: additive --- The idle threshold cannot be set above one hour. The context probe and the self-test share idle_threshold_sec, which is held to 60–3600 seconds (MaxIdleThresholdSec in internal/config/config.go, and max="3600" on the panel's Idle threshold field). The maintainer wants these jobs to run only after a long quiet spell, up to 24 hours, so they never load models during an ordinary break in use. Their threshold is already at the 3600 cap. diff --git a/.abcd/work/issues/open/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md b/.abcd/work/issues/resolved/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md similarity index 80% rename from .abcd/work/issues/open/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md rename to .abcd/work/issues/resolved/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md index 36a8cd3b..8238a77b 100644 --- a/.abcd/work/issues/open/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md +++ b/.abcd/work/issues/resolved/iss-2610041956214381-the-self-test-has-no-idle-threshold-of-its-own-and-the.md @@ -11,6 +11,8 @@ production_mode: hand-written found_at: "internal/config/config.go" remedy: "Give the self-test its own idle threshold (a self_test_idle_threshold_sec setting beside idle_threshold_sec, which stays the context probe's), defaulting to 14400 seconds (4 hours), across config, the panel's Self-test box and docs/self-test.md together; it needs the raised cap from iss-2610041948272032." blocked_by: [iss-2610041948272032] +resolution: "The self-test waits for self_test_idle_threshold_sec (default 14400 s, bounds 60-86400 s) across config, the panel's Self-test box and docs/self-test.md and the reference; idle_threshold_sec stays the context probe's, and the idle check still counts every admitted client request." +impact: breaking --- The self-test has no idle threshold of its own, and the shared default is too short for it. It waits for the same idle_threshold_sec as the context probe, whose default is 300 seconds (DefaultIdleThresholdSec in internal/config/config.go). So, out of the box, it loads and benchmarks a model five minutes after the last request: an ordinary pause in use. On 2026-10-04 it started loading models straight after a peer's run. The maintainer wants the two jobs separated, with the self-test waiting four hours by default, while the context probe keeps its own threshold. diff --git a/.abcd/work/issues/open/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md b/.abcd/work/issues/resolved/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md similarity index 85% rename from .abcd/work/issues/open/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md rename to .abcd/work/issues/resolved/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md index 4ed63f85..d1ad1472 100644 --- a/.abcd/work/issues/open/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md +++ b/.abcd/work/issues/resolved/iss-2610042033419572-the-self-test-s-and-the-context-probe-s-unloadunpinned.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/app/contextprobe.go" remedy: "Add a pool-level UnloadUnpinned in internal/runtime that checks the pin under the same hold of p.mu as the stop and refuses a pinned model with a sentinel the idle jobs map to their own ErrPinned; route unloadUnpinned through it. internal/runtime is a trust boundary, so the change needs an adversarial security review." +resolution: "Pool.UnloadUnpinned reads the pin under the same hold of p.mu as the stop; both idle jobs route through it and map runtime.ErrPinned to their own ErrPinned" +impact: fix --- The self-test's and the context probe's unloadUnpinned (internal/app/contextprobe.go) checks the pin with isPinned and then stops the model with Pool.Unload; each takes the pool's lock separately, so a pin saved in the instant between the check and the stop is lost: the idle job unloads a model a person has just pinned, leaving it pinned and not loaded. diff --git a/.abcd/work/issues/open/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md b/.abcd/work/issues/resolved/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md similarity index 85% rename from .abcd/work/issues/open/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md rename to .abcd/work/issues/resolved/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md index 4bc1aed8..44eacf1a 100644 --- a/.abcd/work/issues/open/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md +++ b/.abcd/work/issues/resolved/iss-2610042036094209-a-request-body-carrying-invalid-utf-8-inside-a-json-string.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/gateway/gateway.go" remedy: "Refuse a request body that is not valid UTF-8 with a 400 at the gateway (utf8.Valid on the bytes it already holds), confirming under the prompt-reading ADRs that a validity check reads no content." +resolution: "A body that is not valid UTF-8 is refused with a 400 at the gateway before it is parsed or forwarded; the check reads the body's encoding, names no field and keeps nothing." +impact: fix --- A request body carrying invalid UTF-8 inside a JSON string reaches the model server and fails on its handler thread with a 502. Go's json.Unmarshal into RawMessage does not validate UTF-8 inside strings, and json.Marshal forwards those bytes unchanged. mlx-lm 0.32.0's request handler then calls raw_body.decode(), which raises UnicodeDecodeError, and its except clause catches only json.JSONDecodeError. The handler thread errors, the connection closes, and the client gets a 502 rather than a clear 400. The generation thread is not affected, so other clients are unharmed. Found by the security review of the non-string prompt refusal; predates it. diff --git a/.abcd/work/issues/open/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md b/.abcd/work/issues/resolved/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md similarity index 83% rename from .abcd/work/issues/open/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md rename to .abcd/work/issues/resolved/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md index db748e44..ce886223 100644 --- a/.abcd/work/issues/open/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md +++ b/.abcd/work/issues/resolved/iss-2610042100405045-the-control-panel-does-not-show-a-program-s-unload-when-a.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/ui/static/app.js" remedy: "Show released unloads in the panel's Statistics tab beside evictions, with the caller kind, held by a UI test against the field Go publishes." +resolution: "The stats counters count released unloads by caller kind (ModelCounters.released); the Statistics tab shows them beside evictions, held by a UI test over the marshalled Go struct" +impact: additive --- The control panel does not show a program's unload. When a client unloads a model through /api/models/unload, the statistics store records the reason released and the kind of caller (itd-2610031024247803, criterion 10), and the log line says so. But the panel's Statistics tab counts evictions only and never shows a released unload (internal/ui/static/app.js, around line 2430). An operator using the panel cannot see that a program unloaded a model, though Go records it. AGENTS.md treats a Go capability with no panel equivalent as a gap. diff --git a/.abcd/work/issues/open/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md b/.abcd/work/issues/resolved/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md similarity index 86% rename from .abcd/work/issues/open/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md rename to .abcd/work/issues/resolved/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md index 1c614beb..6db009fa 100644 --- a/.abcd/work/issues/open/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md +++ b/.abcd/work/issues/resolved/iss-2610042100409263-the-rule-that-saving-an-unrelated-setting-is-never-refused.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/ui/apiunload_test.go" remedy: "Add api_unload_off to the untouched-save test's form body (uneditedFormBody) and a save test that changes another setting while api_unload_off carries an unusual stored value, so the three-surfaces promise is held by a test." +resolution: "The untouched-save test's form body now carries api_unload_off, with a row for the route turned off and a save of another setting that keeps it off" +impact: internal --- The rule that saving an unrelated setting is never refused over api_unload_off is not held by a test. The fidelity review of itd-2610031024247803 (criterion 8) found that it holds only because the field has no validation rule. No save test names the field, and the save test's form helper uneditedFormBody leaves it out, so a future validation rule on api_unload_off could refuse saves of other settings without any test failing. AGENTS.md requires each cross-surface promise to be armed by a test. The panel side is checked only by a source pattern-match (internal/ui/apiunload_test.go). diff --git a/.abcd/work/issues/open/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md b/.abcd/work/issues/resolved/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md similarity index 60% rename from .abcd/work/issues/open/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md rename to .abcd/work/issues/resolved/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md index fe8b9ee1..7ce66beb 100644 --- a/.abcd/work/issues/open/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md +++ b/.abcd/work/issues/resolved/iss-2610042101436222-the-test-that-model-and-file-names-are-shown-safely-in-the.md @@ -9,7 +9,9 @@ found_during: "fidelity review rcp-c60839654fc3 of itd-2610030857275099, 2026-10 origin: researcher-authored production_mode: hand-written found_at: "internal/ui" -remedy: "Add a UI test that renders an update card for a repository name containing markup and asserts it appears as text; drop the file-name half from the criterion or show file names and test them." +remedy: "Maintainer's decision 2026-10-07: show and test file names. The update card lists the files a newer version changes, rendered as text, and a UI test renders a card whose repository name and file names carry markup and asserts both appear as text." +resolution: "The check records the files a newer version changes (first 10 by name plus the count); the card lists them through escapeHtml, held by a rendered UI test with markup in the repository and file names" +impact: additive --- The test that model and file names are shown safely in the update panel does not render a name with markup. internal/ui's test only searches the panel source for escapeHtml calls, while the spec planned a UI test with markup in a repository name and a file name. The card also shows no file names, so the file-name half of criterion 11 of itd-2610030857275099 is never exercised. diff --git a/.abcd/work/issues/open/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md b/.abcd/work/issues/resolved/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md similarity index 56% rename from .abcd/work/issues/open/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md rename to .abcd/work/issues/resolved/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md index b8f3b1e4..5cd49392 100644 --- a/.abcd/work/issues/open/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md +++ b/.abcd/work/issues/resolved/iss-2610042101436891-itd-2610030857275099-s-press-release-says-a-decision-model.md @@ -9,7 +9,9 @@ found_during: "fidelity review rcp-c60839654fc3 of itd-2610030857275099, 2026-10 origin: researcher-authored production_mode: hand-written found_at: ".abcd/development/intents/shipped" -remedy: "Record which promise stands: if decision models are marked 'awaiting review', say so in a successor record or the intent's audit notes (a shipped intent's text is not rewritten), so the press release is not read as the behaviour." +remedy: "Maintainer's decision 2026-10-07: the press release stands, so decision models are never marked. Remove the 'awaiting review' mark for decision models from the update check and the panel, with a test that a decision model shows no mark and offers no Update, and note in the intent's audit notes that criterion 9's mark is withdrawn." +resolution: "Decision models are never marked: an unreviewed newer version is recorded as current (no mark, no Update), awaiting_review removed from the check, registry and panel; audit note on itd-2610030857275099" +impact: fix --- itd-2610030857275099's press release says a decision model is never marked, but its acceptance criteria give one an 'awaiting review' mark, and the panel code shows it (internal/ui/static/app.js, around line 596). The fidelity review listed this as a promise delivered differently. A shipped intent's press release now contradicts its own criteria. diff --git a/.abcd/work/issues/resolved/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md b/.abcd/work/issues/resolved/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md new file mode 100644 index 00000000..dc65e47b --- /dev/null +++ b/.abcd/work/issues/resolved/iss-2610071035130302-the-model-server-s-prompt-cache-has-no-byte-limit-so-cached.md @@ -0,0 +1,19 @@ +--- +schema_version: 1 +id: "iss-2610071035130302" +slug: "the-model-server-s-prompt-cache-has-no-byte-limit-so-cached" +severity: "minor" +category: "bug" +source: "agent-finding" +found_during: "SOTA research on MLX serving performance, 2026-10-07" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/runtime/serve.py" +remedy: "Maintainer's decision 2026-10-07: bound the cache within the existing charge. Pass max_bytes to LRUPromptCache in serve.py equal to one served window's KV for one sequence (the uninflated per-token KV size times the served window), passed by the launcher, and pass --prompt-cache-size explicitly; the charge is not raised. Test that the bound reaches the constructor; verify peak memory on a Mac with footprint sampling." +resolution: "Bounded the model server's prompt cache to one served window of real KV (kv_bytes_per_token, stored beside the charge) via --dessau-prompt-cache-bytes and an explicit --prompt-cache-size 10; serve.py passes max_bytes and refuses a bad bound; a model with no real figure keeps no prompt cache. A real-Mac footprint check (launcher footprint sampling) is still owed." +impact: fix +--- + +The model server's prompt cache has no byte limit, so cached prompts grow outside the memory budget. internal/runtime/serve.py builds server.LRUPromptCache(cli.prompt_cache_size) with the entry count only, so mlx-lm 0.32.0's default of 10 entries and 2^63 bytes applies; upstream's --prompt-cache-bytes flag never reaches the LRUPromptCache constructor (ml-explore/mlx-lm PR 1392, open, which reports Metal running out of memory on long-running servers). docs/memory-budget-explained.md already says caches stack across requests. Each cached entry can hold a whole served window's KV, so a model serving several long conversations can hold several windows' worth of cache that the charge (one window per sequence) does not count. + +Correction (2026-10-07, on fixing): the flag is not entirely unused, as first written. In 0.32.0 it drives a trim on the batched path (server.py around line 761: `self.prompt_cache.trim_to(n_bytes=total - active)` after a request joins the batch), but it is never passed to the constructor, so the cache's own max_bytes stays 2^63 and nothing bounds it on the other paths. diff --git a/.abcd/work/issues/open/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md b/.abcd/work/issues/resolved/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md similarity index 61% rename from .abcd/work/issues/open/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md rename to .abcd/work/issues/resolved/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md index e09ac7fa..2a70070b 100644 --- a/.abcd/work/issues/open/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md +++ b/.abcd/work/issues/resolved/iss-2610071035138788-the-pool-admits-twice-as-many-requests-per-model-as-it.md @@ -9,7 +9,9 @@ found_during: "SOTA research on MLX serving performance, 2026-10-07" origin: researcher-authored production_mode: hand-written found_at: "internal/runtime/pool.go" -remedy: "Make the charge and the admission agree: either size the semaphore to DecodeConcurrency or charge 2 x DecodeConcurrency sequences, choosing by measurement of what the batching gains; add a test that the charge covers every request the semaphore admits." +remedy: "Maintainer's decision 2026-10-07: admit what is charged. Size each model's semaphore to DecodeConcurrency, not twice it, so the budget's charge covers every request admitted; at the default of 1 a second request to the same model waits. Add a test that the charge covers every request the semaphore admits." +resolution: "Each model's semaphore is sized to decode_concurrency, so the pool admits only the requests the KV charge covers; held by TestTheChargeCoversEveryRequestThePoolAdmits." +impact: breaking --- The pool admits twice as many requests per model as it charges memory for. chargeLocked in internal/runtime/pool.go charges KV for DecodeConcurrency sequences, but each loaded model's semaphore admits 2 x DecodeConcurrency requests at once (the sem in startLocked), and at the default of 1 mlx-lm is launched without --decode-concurrency, so its own batch limit (32) lets both admitted requests decode together. Two long requests on one model can therefore use about twice the KV the budget reserved. diff --git a/.abcd/work/issues/open/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md b/.abcd/work/issues/resolved/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md similarity index 87% rename from .abcd/work/issues/open/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md rename to .abcd/work/issues/resolved/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md index 0d79104e..0955a9c2 100644 --- a/.abcd/work/issues/open/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md +++ b/.abcd/work/issues/resolved/iss-2610071200183905-a-403-from-the-content-cdn-during-the-update-check-s-config.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/hub/hub.go" remedy: "Word SmallFileAt's non-200 error by which host answered: name the content CDN and drop the token advice when the refusal came from off the Hub's origin." +resolution: "SmallFileAt names the content CDN and drops the token advice when an off-origin host refused the file" +impact: fix --- A 403 from the content CDN during the update check's config fetch is worded as Hugging Face refusing access with the access token in Settings, though the CDN was never sent the token. The update check counts it as unreachable and never shows or logs the text, so no one sees it today; it would mislead anyone who surfaced it. diff --git a/.abcd/work/issues/open/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md b/.abcd/work/issues/resolved/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md similarity index 91% rename from .abcd/work/issues/open/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md rename to .abcd/work/issues/resolved/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md index 402a96ea..2fa4d938 100644 --- a/.abcd/work/issues/open/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md +++ b/.abcd/work/issues/resolved/iss-2610071200187548-the-update-check-s-content-fetch-docontent-in-internal-hub.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/hub/hub.go" remedy: "In doContent's CheckRedirect, drop Authorization for the rest of the chain once any hop in via is off-origin, and refuse a non-https hop when the base URL is https; add hub tests for leave-then-return and for an https-to-http redirect." +resolution: "doContent's redirect rule drops the token for the rest of the chain once any hop is off-origin and refuses https-to-http" +impact: fix --- The update check's content fetch (doContent in internal/hub/hub.go) strips the access token only on the hop that leaves the Hub's origin, so a redirect chain that leaves and then returns sends the token to the Hub again. A CDN on a host net/http treats as the same domain, or the same host on another port, can redirect back to the Hub origin, and the next request is rebuilt from the original headers. The reviewer's probe showed the CDN hop receiving no token and the hop back receiving the bearer token. The token only reaches its own audience and the bytes are still checked against the listed sha256, but a hostile CDN can choose one authenticated Hub GET, which refuseOffOrigin exists to prevent. The same fetch also follows an https-to-http hop: integrity holds through the hash and the token is dropped, but a gated repo's config.json crosses the network unencrypted. diff --git a/.abcd/work/issues/open/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md b/.abcd/work/issues/resolved/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md similarity index 87% rename from .abcd/work/issues/open/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md rename to .abcd/work/issues/resolved/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md index 50724b71..ce3ecba3 100644 --- a/.abcd/work/issues/open/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md +++ b/.abcd/work/issues/resolved/iss-2610071200187920-the-model-download-path-sets-no-checkredirect-of-its-own-so.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/hub/download.go" remedy: "Give the download client the same redirect policy as doContent, one shared primitive rather than a second copy: strip Authorization off-origin and keep the 10-hop limit, with a download test using a same-host, other-port CDN." +resolution: "downloads now fetch through doContent, sharing its one redirect rule: token stays on the Hub's origin, https-to-http refused, 10 hops" +impact: fix --- The model download path sets no CheckRedirect of its own, so it relies on net/http's default header stripping, which keeps Authorization on a redirect to a subdomain of the Hub's host. The update check's newer content fetch (doContent) drops the token on any hop that leaves the Hub's origin, so the path that moves gigabytes is the less strict of the two. Today's CDN hosts are on another domain, so net/http drops the token anyway; the gap opens only if the Hub redirects to one of its own subdomains. diff --git a/.abcd/work/issues/open/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md b/.abcd/work/issues/wontfix/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md similarity index 76% rename from .abcd/work/issues/open/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md rename to .abcd/work/issues/wontfix/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md index 2c94a07a..44ef6b01 100644 --- a/.abcd/work/issues/open/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md +++ b/.abcd/work/issues/wontfix/iss-2610042101435880-in-the-shipped-binary-no-decision-model-is-ever-marked.md @@ -10,6 +10,11 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/app/app.go" remedy: "Wire the reviewed-build manifest from itd-2610030656210408 step 2 into app.New in cmd/dessau, so decision models are marked 'awaiting review' with no Update until a release ships their reviewed build; add a test on the binary's own wiring." +wontfix_reason: "Moot after the maintainer's decision of 2026-10-07 on iss-2610042101436891: decision models are never marked 'awaiting review', so there is no mark to wire the reviewed-build manifest into." --- In the shipped binary no decision model is ever marked 'awaiting review': criterion 9 of itd-2610030857275099 is not met. The update check has a hook for decision models (internal/app/app.go around line 242: 'Nil means no model is a decision model'), but cmd/dessau/main.go builds the app without a list of reviewed builds, and none ships. So a decision model with a newer version is marked 'available', with Update offered, and no Dessau release can make Update appear by shipping a reviewed version. The waiting behaviour exists only in tests that supply the list by hand. It depends on itd-2610030656210408 step 2 (the embedded reviewed-build manifest). Today decision models are not served as decision models, so updating one changes no served behaviour. + +## Grounds + +- declined: Moot after the maintainer's decision of 2026-10-07 on iss-2610042101436891: decision models are never marked 'awaiting review', so there is no mark to wire the reviewed-build manifest into. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a876562..b5a8dfb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,95 @@ GitHub release notes. ## [Unreleased] +### Added + +- **A model's card names the files a newer version changes.** + `impact: additive`. When a check finds a newer version, the card under + **My Models** now lists the files it changes, adds or removes — up to ten, + then how many more — so Alice can tell a fixed chat template from a new + set of weights before she clicks **Update**. The names are shown as plain + text whatever HuggingFace calls them + ([model updates](docs/model-updates.md#what-the-marks-mean); + iss-2610042101436222). +- **The Statistics tab shows when a program unloaded a model.** + `impact: additive`. Dessau recorded each unload a program asked for + through the model API, with the kind of caller that asked, but the + control panel counted evictions only, so Alice could not see from the + panel that Bob's script had unloaded a model. Each model's card now says + how many times a program unloaded it, beside its evictions and by kind of + caller — on this Mac, with the API key, or a paired client + ([request statistics](docs/request-statistics.md#what-is-recorded); + iss-2610042100405045). +### Changed + +- **The idle threshold can be set up to 24 hours.** `impact: additive`. The + threshold the context probe waits for, `idle_threshold_sec`, stopped at one + hour, so Alice could not keep idle work to a long quiet spell such as the + night. It now takes anything from 60 seconds to 86,400 seconds (24 hours), + in `config.json` and in the **Idle threshold** field under **Settings → + Context probe** alike; the default is unchanged + ([context probe](docs/context-probe.md); iss-2610041948272032). +- **The self-test waits for an idle threshold of its own, four hours unless + set.** `impact: breaking`. The self-test shared `idle_threshold_sec` with + the context probe, so out of the box it loaded and benchmarked a model five + minutes after the last request — an ordinary pause in Bob's use of the + server. It now waits for `self_test_idle_threshold_sec`, 4 hours unless + set, from 60 seconds to 86,400 (24 hours), in `config.json` and in + **Self-test idle threshold** under **Settings → Self-test** alike; the + panel's self-test lines name that threshold. `idle_threshold_sec` is the + context probe's alone and keeps its five-minute default. A Mac that had + set `idle_threshold_sec` to hold the self-test back should set the new + setting too: nothing is carried across + ([self-test](docs/self-test.md); iss-2610041956214381). + +### Fixed + +- **A client's request no longer waits behind the tool-call check.** `impact: fix`. + When Bob's request arrives on a model while Dessau is asking it whether it + can call tools, the check stops and lets the model go at once, and asks + again once the model is quiet, so Bob is answered without waiting for the + check's own answer (iss-2610071035138788). + +- **A Discord answer is no longer cut short at a fixed 1,024 tokens, and one + that reaches its limit says so.** `impact: fix`. The bridge asked every + model for at most 1,024 tokens whatever window it was served at, so a long + answer stopped mid-sentence without a word, and a reasoning model could + spend all of it thinking and be reported as having answered with nothing. + An answer may now take half the model's served window, the conversation + sent with it keeping the other half. When the model still stops on length, + the bot says so in a message of its own after the answer, or, when nothing + of the answer was written, says that the model reached its length limit + before it wrote one ([Discord bridge](docs/discord-bridge.md); + iss-2610041945020793). +### Changed + +- **A model runs no more requests at once than its memory is charged for.** + `impact: breaking`. Each model is charged one served window of attention + cache per batched request, but its server was handed twice that many + requests at once, so two long conversations on one model could build twice + the cache the memory budget had set aside. A model now runs as many + requests at once as **Settings → Batched requests** says, and the next + waits its turn: at the default of one, when Alice and Bob ask the same + model together, Bob's answer starts when Alice's ends. Raise **Batched + requests** on a Mac that serves several clients at once + ([getting started](docs/getting-started.md); + [why there is a memory budget](docs/memory-budget-explained.md); + iss-2610071035138788). + ### Fixed +- **The conversations a model remembers between requests no longer grow + past its memory charge.** `impact: fix`. A model's server keeps the + caches of recent prompts so that the next turn of a conversation is not + read again, and it kept up to ten of them with no limit on their size: a + model serving Alice's, Bob's and Carol's long conversations could hold + several windows of cache that the memory budget never counted. What it + keeps is now held, all together, to one served window of the cache's own + size. A model whose configuration does not say what its cache costs keeps + none between requests. Dessau works out the new figure when it starts, so + a model downloaded earlier gains it at the next start + ([why there is a memory budget](docs/memory-budget-explained.md); + iss-2610071035130302). - **An update that will not load no longer leaves a model without a version to serve.** `impact: fix`. Dessau removed the old version of a model as soon as the new one passed the checks it makes before starting a @@ -35,6 +122,22 @@ GitHub release notes. **newer version not run**. One whose `config.json` cannot be held to that hash is marked **newer version not checked**, and is not offered either ([model updates](docs/model-updates.md); iss-2610042101439623). +- **The access token goes to no host but HuggingFace's own, on any redirect + a download or the update check follows.** `impact: fix`. The update check + dropped the token on the hop that left HuggingFace's origin but sent it + again on a hop that came back, so a host along the way could choose a + request made with Alice's token; a download relied on Go's own rule, which + keeps the token on a redirect to HuggingFace's host at another port or to a + subdomain of it. Both now go through one redirect rule: once a redirect + leaves HuggingFace's origin, no later hop carries the token, and a redirect + from https to plain http is refused rather than followed + (iss-2610071200187548, iss-2610071200187920). +- **A refusal from HuggingFace's content CDN is no longer worded as + HuggingFace refusing the access token.** `impact: fix`. When the update + check read a `config.json` from the content CDN and the CDN refused it, the + error advised about the access token in Settings, which the CDN is never + sent. It now names the content CDN that answered and gives no token advice + (iss-2610071200183905). - **The self-test and the context probe no longer start while a client is still sending requests that fail.** `impact: fix`. The idle check read each loaded model's last request, so a request that never reached a model, or @@ -44,6 +147,53 @@ GitHub release notes. threshold was an hour, and load models while he was still trying. Every client request now counts from the moment it arrives until it ends, however it ends ([self-test](docs/self-test.md); iss-2610041945030758). +- **A model loaded just as its tool-call probe found it gone is now asked.** + `impact: fix`. When Alice's request loaded a model at the moment Dessau's + tool-call probe found that model not yet held, the probe dropped the model + and the new load's report with it, so the card read **Tool calls: not + measured** until the model was next loaded. Dessau now asks the model once + its turn comes round again + ([context probe](docs/context-probe.md#whether-the-model-calls-tools); + iss-2610032231045098). +- **A request whose body is not valid UTF-8 is refused with a 400 instead of + failing with a 502.** `impact: fix`. Dessau passed such a body on to the + model server unchanged, which failed to decode it and dropped the + connection, so Carol's client was told only that the gateway had a bad + answer from upstream. The body is now checked to be valid UTF-8 before + anything else is asked of it, and refused with + `request body is not valid UTF-8`; text in any script, emoji included, is + passed on as before. The check reads the body's encoding, not what any field + says, and keeps nothing + ([request fields](docs/request-fields.md#a-body-that-is-not-valid-utf-8); + iss-2610042036094209). +- **A model you pin just as the self-test or the context probe unloads it + now stays loaded.** `impact: fix`. Both checked the pin and then stopped + the model as two separate steps, so a pin saved in the instant between them + was overridden: the model was unloaded and left pinned but not in memory. + The pin is now checked in the same step as the stop, so a pin saved before + the stop always keeps the model loaded + ([self-test](docs/self-test.md); iss-2610042033419572). +- **A decision model is never marked "newer version awaiting review".** + `impact: fix`. The update check marked a decision model's newer version + that no Dessau release had reviewed as awaiting review, although the + update check was announced as never marking a decision model. Such a + version now carries no mark and no **Update**, as a model with nothing + newer does; a decision model is still offered, and fetched at, only a + version a Dessau release has reviewed. A record left over with the old + mark is dropped when Dessau starts, and the next check writes it again + (iss-2610042101436891). +- **A machine on the network can no longer hold an unlimited number of + connections open.** `impact: fix`. Neither port Dessau answers on, nor the + pairing call, limited how many connections a peer could keep open at once, + so a machine that reconnected in a loop could hold a socket and a goroutine + per attempt for as long as it kept trying. Each address and port Dessau + listens on now holds at most 512 open connections, and at most 32 from any + one client address; a connection over + either limit is closed as it arrives, before anything is read from it. + Connections from this Mac count towards the 512 only, so the control panel + is never locked out by a busy local client + ([bind address](docs/bind-address.md#how-many-connections-each-address-may-hold); + iss-2609190254516275). ## [0.10.0] - 2026-10-04 diff --git a/cmd/dessau/conncap_test.go b/cmd/dessau/conncap_test.go new file mode 100644 index 00000000..4e66f5e1 --- /dev/null +++ b/cmd/dessau/conncap_test.go @@ -0,0 +1,478 @@ +package main + +import ( + "crypto/tls" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/intentdriven/Dessau/internal/bind" + "github.com/intentdriven/Dessau/internal/config" +) + +// The connection caps (iss-2609190254516275). A read bound turns "one +// connection held forever" into "held for the bound, then reconnect"; nothing +// before these capped how many a peer could hold at once, and /pair asks for no +// credential. + +// fakeAddr is a remote address a test can choose, so the per-address cap can +// be exercised with addresses no test machine holds. +type fakeAddr string + +func (a fakeAddr) Network() string { return "tcp" } +func (a fakeAddr) String() string { return string(a) } + +// fakeConn records whether anything read from it and when it was closed. The +// embedded net.Conn is nil: a method the wrapper calls that is not defined +// here panics, which is the test saying the wrapper did more than it should. +type fakeConn struct { + net.Conn + remote net.Addr + + mu sync.Mutex + reads int + closes int + closed chan struct{} +} + +func newFakeConn(remote string) *fakeConn { + return &fakeConn{remote: fakeAddr(remote), closed: make(chan struct{})} +} + +func (c *fakeConn) Read([]byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.reads++ + return 0, io.EOF +} + +func (c *fakeConn) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + c.closes++ + if c.closes == 1 { + close(c.closed) + } + return nil +} + +func (c *fakeConn) RemoteAddr() net.Addr { return c.remote } +func (c *fakeConn) LocalAddr() net.Addr { return fakeAddr("198.51.100.10:11535") } + +func (c *fakeConn) counts() (reads, closes int) { + c.mu.Lock() + defer c.mu.Unlock() + return c.reads, c.closes +} + +// fakeListener hands out the connections a test pushes into it. +type fakeListener struct { + conns chan net.Conn + done chan struct{} + once sync.Once +} + +func (l *fakeListener) Accept() (net.Conn, error) { + select { + case c := <-l.conns: + return c, nil + case <-l.done: + return nil, net.ErrClosed + } +} + +func (l *fakeListener) Close() error { + l.once.Do(func() { close(l.done) }) + return nil +} + +func (l *fakeListener) Addr() net.Addr { return fakeAddr("198.51.100.10:11535") } + +// capHarness drives a capped fake listener: one goroutine accepts, as an +// http.Server's Serve loop does, and each dial says whether the connection was +// handed on or closed. +type capHarness struct { + t *testing.T + fake *fakeListener + ln *connCap + accepted chan net.Conn + logs *syncBuffer +} + +func newCapHarness(t *testing.T, perAddr, total int) *capHarness { + t.Helper() + h := &capHarness{ + t: t, + fake: &fakeListener{conns: make(chan net.Conn), done: make(chan struct{})}, + accepted: make(chan net.Conn, 1), + logs: &syncBuffer{}, + } + log := slog.New(slog.NewTextHandler(h.logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + h.ln = newConnCap(h.fake, perAddr, total, log) + go func() { + for { + c, err := h.ln.Accept() + if err != nil { + return + } + h.accepted <- c + } + }() + t.Cleanup(func() { h.ln.Close() }) + return h +} + +// dial offers one connection from remote and reports what became of it: the +// connection the server was handed, or nil and the fake it closed. +func (h *capHarness) dial(remote string) (net.Conn, *fakeConn) { + h.t.Helper() + fc := newFakeConn(remote) + h.fake.conns <- fc + select { + case c := <-h.accepted: + return c, fc + case <-fc.closed: + return nil, fc + case <-time.After(5 * time.Second): + h.t.Fatalf("a connection from %s was neither handed on nor closed", remote) + return nil, nil + } +} + +func (h *capHarness) admit(remote string) net.Conn { + h.t.Helper() + c, _ := h.dial(remote) + if c == nil { + h.t.Fatalf("a connection from %s was refused under its caps", remote) + } + return c +} + +func (h *capHarness) refuse(remote, why string) { + h.t.Helper() + c, fc := h.dial(remote) + if c != nil { + h.t.Fatalf("a connection from %s was handed on, want it closed: %s", remote, why) + } + if reads, _ := fc.counts(); reads != 0 { + h.t.Errorf("a connection from %s was read %d times before it was refused; it is closed before any read", remote, reads) + } +} + +// One address at its cap is refused; another address still connects. +func TestAnAddressAtItsCapIsRefusedWhileAnotherStillConnects(t *testing.T) { + h := newCapHarness(t, 2, 100) + h.admit("192.0.2.1:50001") + h.admit("192.0.2.1:50002") + h.refuse("192.0.2.1:50003", "192.0.2.1 already holds its two connections") + h.admit("192.0.2.2:50001") + if got := h.ln.Refused(); got != 1 { + t.Errorf("the listener counted %d refusals, want 1", got) + } + // Counted and logged, and the log line describes the listener and never + // the peer (docs/logging.md: no client address is ever written). + logs := h.logs.String() + if !strings.Contains(logs, "level=DEBUG") { + t.Errorf("the refusal was not logged at debug: %q", logs) + } + if strings.Contains(logs, "192.0.2.1") || strings.Contains(logs, "50003") { + t.Errorf("the refusal's log line names the peer: %q", logs) + } +} + +// An IPv6 peer is counted by its full address: two addresses in one /64 are +// two peers. An IPv4 peer that reaches a dual-stack socket as a mapped address +// is the same peer as when it arrives as itself. +func TestPeersAreCountedByTheirFullAddress(t *testing.T) { + h := newCapHarness(t, 2, 100) + h.admit("[2001:db8::1]:50001") + h.admit("[2001:db8::1]:50002") + h.refuse("[2001:db8::1]:50003", "2001:db8::1 already holds its two connections") + h.admit("[2001:db8::2]:50001") + + h.admit("192.0.2.7:50001") + h.admit("[::ffff:192.0.2.7]:50002") + h.refuse("192.0.2.7:50003", "192.0.2.7 holds two connections, one of them as a mapped address") +} + +// A listener at its total is refused, whoever is asking. +func TestAListenerAtItsTotalIsRefused(t *testing.T) { + h := newCapHarness(t, 10, 3) + h.admit("192.0.2.1:50001") + h.admit("192.0.2.2:50001") + h.admit("[2001:db8::1]:50001") + h.refuse("192.0.2.3:50001", "the listener already holds its three connections") +} + +// Loopback has a budget of its own on a listener remote peers also reach. +// Bound to ::, the wildcard listener is dual-stack and the panel's localhost +// arrives on it as ::1, so if loopback shared the remote total, a machine on +// the network that filled it would lock the operator out of the panel. +// Remote peers filling the total do not touch loopback's budget, and loopback +// filling its own does not touch theirs. +func TestLoopbackKeepsItsOwnBudgetWhenRemotePeersFillTheListener(t *testing.T) { + h := newCapHarness(t, 10, 2) + h.admit("192.0.2.1:50001") + h.admit("[2001:db8::1]:50001") + h.refuse("192.0.2.2:50001", "remote peers already hold the listener's two connections") + h.admit("[::1]:50001") + h.admit("127.0.0.1:50002") + h.refuse("[::1]:50003", "loopback already holds its own two connections") + h.refuse("192.0.2.3:50001", "remote peers are still at their total") +} + +// A closed connection frees its slot, on both caps. +func TestAClosedConnectionFreesItsSlot(t *testing.T) { + h := newCapHarness(t, 2, 2) + a := h.admit("192.0.2.1:50001") + h.admit("192.0.2.1:50002") + h.refuse("192.0.2.1:50003", "the address and the listener are both full") + if err := a.Close(); err != nil { + t.Fatal(err) + } + h.admit("192.0.2.1:50004") + h.refuse("192.0.2.1:50005", "the slot the close freed has been taken again") +} + +// Closing a connection twice frees one slot, not two — net/http can close a +// connection on more than one path, and a TLS connection closes its own. +func TestClosingTwiceFreesOnce(t *testing.T) { + h := newCapHarness(t, 2, 100) + a := h.admit("192.0.2.1:50001") + h.admit("192.0.2.1:50002") + a.Close() + a.Close() + h.admit("192.0.2.1:50003") + h.refuse("192.0.2.1:50004", "a double close freed two slots for one connection") +} + +// This Mac is never locked out of its own panel by the per-address cap. Every +// account on this Mac arrives as the one loopback address, so a per-address +// cap there would be a cap on the whole Mac, shared by the panel and every +// local client. Held here at the production figures, with the panel's load +// at more than the per-address cap — far more than any panel opens. +func TestALoopbackClientIsNotStarvedByThePanelsParallelLoad(t *testing.T) { + raw, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + // Closed last, after the server's side: the side that closes first keeps + // the TIME_WAIT, and kept on these clients' ephemeral ports it collides + // with the bind tests' free ports. + var clients []net.Conn + t.Cleanup(func() { closeConns(clients) }) + release := make(chan struct{}) + var entered sync.WaitGroup + entered.Add(connsPerAddr) + srv := listenerServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/events" { + entered.Done() + <-release + } + io.WriteString(w, "ok") + }), requestReadTimeout) + ln := capConns(raw, testLogger(t)) + go srv.Serve(ln) + t.Cleanup(func() { close(release); srv.Close() }) + + addr := raw.Addr().String() + for i := 0; i < connsPerAddr; i++ { + c, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + clients = append(clients, c) + if _, err := fmt.Fprint(c, "GET /api/events HTTP/1.1\r\nHost: localhost\r\n\r\n"); err != nil { + t.Fatal(err) + } + } + waited := make(chan struct{}) + go func() { entered.Wait(); close(waited) }() + select { + case <-waited: + case <-time.After(10 * time.Second): + t.Fatalf("the panel's %d parallel streams were not all admitted from loopback", connsPerAddr) + } + + client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}, Timeout: 10 * time.Second} + resp, err := client.Get("http://" + addr + "/health") + if err != nil { + t.Fatalf("a loopback client was refused while the panel held %d connections: %v", connsPerAddr, err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Errorf("a loopback client got %d, want 200", resp.StatusCode) + } +} + +// The TLS listeners — the paired clients' port — are capped beneath the TLS +// layer, so a connection over the cap is closed before a handshake byte is +// read. Held through acquireTLSBind at the production total, from loopback, +// which the per-address cap leaves alone and the total does not. +func TestTheTLSListenersAreCappedBeneathTheHandshake(t *testing.T) { + probe, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := probe.Addr().(*net.TCPAddr).Port + probe.Close() + + // Closed last, for the reason the loopback test gives. + var clients []net.Conn + t.Cleanup(func() { closeConns(clients) }) + cfg := config.Default() + cfg.TLSPort = port + id, reg := testIdentity(t) + lns := acquireTLSBind(bind.ForHost("127.0.0.1"), cfg, id, reg, testLogger(t)) + if len(lns) != 1 { + t.Fatalf("the TLS bind took %d listeners, want 1", len(lns)) + } + ln := lns[0] + t.Cleanup(func() { ln.Close() }) + + var mu sync.Mutex + var held []net.Conn + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + if _, ok := c.(*tls.Conn); !ok { + t.Errorf("the TLS listener handed on a %T; net/http needs the *tls.Conn itself", c) + } + mu.Lock() + held = append(held, c) + mu.Unlock() + } + }() + t.Cleanup(func() { + mu.Lock() + defer mu.Unlock() + for _, c := range held { + c.Close() + } + }) + + addr := ln.Addr().String() + for i := 0; i < connsPerListener; i++ { + c, err := net.Dial("tcp", addr) + if err != nil { + t.Fatalf("dial %d: %v", i, err) + } + clients = append(clients, c) + } + deadline := time.Now().Add(10 * time.Second) + for { + mu.Lock() + n := len(held) + mu.Unlock() + if n == connsPerListener { + break + } + if time.Now().After(deadline) { + t.Fatalf("only %d of %d connections were handed on under the cap", n, connsPerListener) + } + time.Sleep(10 * time.Millisecond) + } + + over, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer over.Close() + over.SetReadDeadline(time.Now().Add(5 * time.Second)) + _, err = over.Read(make([]byte, 1)) + if err == nil || errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("a connection over the TLS listener's total of %d was held open (read: %v), want it closed", + connsPerListener, err) + } +} + +// The wrapped connection keeps the half-close net/http uses to flush an answer +// before it closes, so capping a plain listener does not turn a graceful close +// into a reset. +func TestACappedConnectionKeepsItsHalfClose(t *testing.T) { + raw, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + ln := capConns(raw, testLogger(t)) + defer ln.Close() + go func() { + if c, err := net.Dial("tcp", raw.Addr().String()); err == nil { + defer c.Close() + io.Copy(io.Discard, c) + } + }() + c, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + defer c.Close() + cw, ok := c.(interface{ CloseWrite() error }) + if !ok { + t.Fatalf("a capped TCP connection (%T) has no CloseWrite", c) + } + if err := cw.CloseWrite(); err != nil { + t.Errorf("CloseWrite on a capped TCP connection: %v", err) + } +} + +// The plain listeners are capped in runServer before they serve, in the shape +// the other wiring tests here hold: capConns is a function a test can call +// with any listener it likes, which makes every test above true of a socket +// this process might never cap. +func TestThePlainListenersAreCappedBeforeTheyServe(t *testing.T) { + src, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + body := string(src) + wrap := strings.Index(body, "lns[i] = capConns(ln, log)") + serve := strings.Index(body, "serveAll(srv, lns,") + if wrap < 0 { + t.Fatal("runServer no longer caps the plain listeners") + } + if serve < 0 || serve < wrap { + t.Error("the plain listeners are served before they are capped") + } + tlsSrc, err := os.ReadFile("tlsbind.go") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(tlsSrc), "tls.NewListener(capConns(ln, log), tlsCfg)") { + t.Error("the TLS listeners are no longer capped beneath the TLS layer") + } +} + +// The figures, and the page that states them. +func TestTheConnectionCapsAreTheRecordedFigures(t *testing.T) { + if connsPerAddr != 32 || connsPerListener != 512 { + t.Errorf("the caps are %d per address and %d per listener, want the 32 and 512 recorded in "+ + ".abcd/work/DECISIONS.md", connsPerAddr, connsPerListener) + } + page, err := os.ReadFile("../../docs/bind-address.md") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{fmt.Sprint(connsPerAddr), fmt.Sprint(connsPerListener)} { + if !strings.Contains(string(page), want) { + t.Errorf("docs/bind-address.md does not state the figure %s", want) + } + } +} + +func closeConns(cs []net.Conn) { + for _, c := range cs { + c.Close() + } +} diff --git a/cmd/dessau/listeners.go b/cmd/dessau/listeners.go index 674d900a..ac1a5317 100644 --- a/cmd/dessau/listeners.go +++ b/cmd/dessau/listeners.go @@ -1,7 +1,13 @@ package main import ( + "errors" + "log/slog" + "net" "net/http" + "net/netip" + "sync" + "sync/atomic" "time" "github.com/intentdriven/Dessau/internal/gateway" @@ -68,3 +74,201 @@ func listenerServer(h http.Handler, read time.Duration) *http.Server { IdleTimeout: idleTimeout, } } + +// The connection caps every listener this process opens is wrapped in +// (iss-2609190254516275): one remote address may hold at most connsPerAddr +// open connections, and one listener at most connsPerListener. The read +// bounds above turn "one connection held forever" into "held for the bound, +// then reconnect"; these are what stop a peer reconnecting in a loop from +// holding an unbounded number of sockets and goroutines at once. /pair is the +// sharp case again, because it asks for no credential. +// +// The figures are recorded, with what would show them wrong, in +// .abcd/work/DECISIONS.md (2026-10-07). In short: a model queues at most 64 +// requests beyond its batch and refuses the rest itself, and the clients this +// server is built for open a handful of connections each (URLSession and a +// browser hold six per host; the Discord bridge asks in-process and holds +// none), so 32 is several times any one machine's normal parallelism while +// still taking sixteen addresses to fill a listener. 512 is eight models' +// whole queues — more than this Mac holds loaded at once — and costs a few +// tens of megabytes of goroutines and buffers at most, far inside the +// descriptor limit. +// +// Constants rather than settings: the record asks for none, and a ceiling an +// operator can lift is one more thing the panel has to explain. +const ( + connsPerAddr = 32 + connsPerListener = 512 +) + +// capConns wraps a listener in the connection caps. It is the one primitive +// both servers' sockets go through: runServer wraps the plain listeners before +// they serve, and acquireTLSBind wraps each raw socket BENEATH the TLS layer, +// so a connection over a cap is closed before a handshake byte is read and +// net/http is still handed the *tls.Conn it looks for. +func capConns(ln net.Listener, log *slog.Logger) net.Listener { + return newConnCap(ln, connsPerAddr, connsPerListener, log) +} + +// connCap is a listener whose Accept closes a connection over either cap the +// moment it is accepted, before anything reads from it, and goes on to the +// next one. It never returns the refusal as an error: an error from Accept is +// net/http's signal to back off or to stop serving, and a peer at its cap is +// neither. +// +// The per-address cap is keyed by the peer's full address — an IPv6 peer is +// not collapsed to its /64. That leaves a peer that can mint addresses (an +// IPv6 host on the same link can, freely) able to sidestep the per-address +// cap, which is what the listener's total is for: it is the ceiling that holds +// whatever the addresses are. Collapsing to a /64 would instead put every +// client behind one router's prefix into a single bucket. +// +// Loopback peers are not held to the per-address cap. Every account on this +// Mac arrives as the one loopback address, so a per-address cap there is a cap +// on the whole Mac, shared between the operator's own panel and every local +// client — one busy local client would lock the operator out of the panel. The +// pool says the same of its own per-source cap: an address is not a client. +// +// Nor do they share the remote peers' total: loopback has a budget of its own, +// of the same size. Bound to ::, the wildcard listener is dual-stack and the +// panel's localhost reaches it as ::1, so a total shared with the network +// would let a machine on the LAN that fills it lock the operator out of the +// panel. Each side filling its own budget leaves the other's alone. +type connCap struct { + net.Listener + perAddr, total int + log *slog.Logger + + mu sync.Mutex + open int // remote connections, held to total + loopback int // loopback connections, held to a total of their own + byAddr map[string]int + + refused atomic.Uint64 + lastLog atomic.Int64 // unix nanoseconds of the last refusal logged +} + +func newConnCap(ln net.Listener, perAddr, total int, log *slog.Logger) *connCap { + return &connCap{Listener: ln, perAddr: perAddr, total: total, log: log, byAddr: map[string]int{}} +} + +// Refused is how many connections this listener has closed over a cap. +func (l *connCap) Refused() uint64 { return l.refused.Load() } + +func (l *connCap) Accept() (net.Conn, error) { + for { + c, err := l.Listener.Accept() + if err != nil { + return nil, err + } + key, exempt := peerKey(c.RemoteAddr()) + if over := l.admit(key, exempt); over != "" { + // Counted before the close, so a refusal the peer has seen is + // one the count already holds. + l.logRefusal(over) + c.Close() + continue + } + return &cappedConn{Conn: c, release: func() { l.release(key, exempt) }}, nil + } +} + +// admit takes a slot for a connection from key, or names the cap it is over. +func (l *connCap) admit(key string, exempt bool) string { + l.mu.Lock() + defer l.mu.Unlock() + if exempt { + if l.loopback >= l.total { + return "loopback" + } + l.loopback++ + return "" + } + if l.open >= l.total { + return "listener" + } + if l.byAddr[key] >= l.perAddr { + return "per-address" + } + l.open++ + l.byAddr[key]++ + return "" +} + +func (l *connCap) release(key string, exempt bool) { + l.mu.Lock() + defer l.mu.Unlock() + if exempt { + l.loopback-- + return + } + l.open-- + if l.byAddr[key]--; l.byAddr[key] <= 0 { + delete(l.byAddr, key) + } +} + +// logRefusal counts a refusal and logs it at debug, at most once a second: a +// peer reconnecting in a loop causes one per accept, and a debug level left +// on must not let it write to this Mac's disk as fast as it can connect. The +// line carries the running count, so the refusals in between are not lost. It +// names this listener and never the peer — no client address is written to +// the log (docs/logging.md). +func (l *connCap) logRefusal(over string) { + n := l.refused.Add(1) + now := time.Now().UnixNano() + last := l.lastLog.Load() + if last != 0 && now-last < int64(time.Second) { + return + } + if !l.lastLog.CompareAndSwap(last, now) { + return + } + l.log.Debug("refused a connection over the "+over+" connection cap", + "listener", l.Addr().String(), "per_address_cap", l.perAddr, + "listener_cap", l.total, "refused_total", n) +} + +// peerKey is the per-address cap's key for a remote address, and whether that +// address is loopback. The key is the full address without its port. An IPv4 +// peer that a dual-stack socket presents as IPv4-mapped IPv6 is unmapped, +// which is the same address spelled the other way rather than a collapse. An +// address that does not parse is keyed by its whole string: counted, and +// never exempt. +func peerKey(a net.Addr) (string, bool) { + if a == nil { + return "", false + } + ap, err := netip.ParseAddrPort(a.String()) + if err != nil { + return a.String(), false + } + ip := ap.Addr().Unmap() + return ip.String(), ip.IsLoopback() +} + +// cappedConn gives its slot back when it is closed, exactly once however many +// times it is closed: net/http can close a connection on more than one path, +// and a TLS connection closes the one beneath it. +type cappedConn struct { + net.Conn + once sync.Once + release func() +} + +func (c *cappedConn) Close() error { + err := c.Conn.Close() + c.once.Do(c.release) + return err +} + +// CloseWrite passes the half-close through. net/http half-closes a plain +// connection to flush an answer before closing it, and finds the method by +// asking the connection it was handed, so a wrapper without it would turn +// that graceful close into a possible reset. +func (c *cappedConn) CloseWrite() error { + if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok { + return cw.CloseWrite() + } + return errors.ErrUnsupported +} diff --git a/cmd/dessau/main.go b/cmd/dessau/main.go index 18a48e40..1182f50d 100644 --- a/cmd/dessau/main.go +++ b/cmd/dessau/main.go @@ -418,6 +418,13 @@ func runServer(lns []net.Listener, plan bind.Plan, paths config.Paths, cfg confi srv := listenerServer(withLogging(mux, log), requestReadTimeout) + // Every plain listener is capped before it serves, the loopback one + // included: one address may hold so many connections and the listener so + // many in all (iss-2609190254516275). The TLS listeners were capped + // beneath their TLS layer in acquireTLSBind. + for i, ln := range lns { + lns[i] = capConns(ln, log) + } for _, ln := range lns { log.Info("serving", "addr", ln.Addr().String(), "ui", panelURL(cfg)) } diff --git a/cmd/dessau/tlsbind.go b/cmd/dessau/tlsbind.go index f54ff07d..4a311ee5 100644 --- a/cmd/dessau/tlsbind.go +++ b/cmd/dessau/tlsbind.go @@ -44,7 +44,9 @@ func acquireTLSBind(plan bind.Plan, cfg config.Config, id *pairing.Identity, reg log.Error("could not listen for paired clients", "addr", addr, "err", err) continue } - out = append(out, tls.NewListener(ln, tlsCfg)) + // Capped beneath the TLS layer, so a connection over a cap is closed + // before a handshake byte is read (iss-2609190254516275). + out = append(out, tls.NewListener(capConns(ln, log), tlsCfg)) } return out } diff --git a/docs/bind-address.md b/docs/bind-address.md index 55d76f4d..fb3b3fe2 100644 --- a/docs/bind-address.md +++ b/docs/bind-address.md @@ -36,6 +36,39 @@ accounts on this one out. The control panel is loopback-only under every choice, so what a machine elsewhere reaches is the model API and not the panel. +## How many connections each address may hold + +Every address and port Dessau listens on — the ordinary port and the port +paired clients use, on loopback and on the address the bind adds — holds at +most 512 open connections, and at most 32 from any one client address. A +connection over either limit is closed as soon as it arrives, before Dessau +reads anything from it; the client sees the connection close, not an HTTP +error. The limits are fixed, not settings. + +| Limit | Figure | Applies to | +|---|---|---| +| Per client address | 32 open connections | each address another machine connects from | +| Per listening address | 512 open connections | everything another machine opens to that address and port | +| Loopback, per listening address | 512 open connections | everything this Mac opens to that address and port | + +A client address is counted whole: two IPv6 addresses in the same network +prefix are two addresses. Connections from this Mac over loopback have a 512 of +their own and no per-address limit. Every account on this Mac arrives from the +same loopback address, so a per-address limit would be shared between the +control panel and every local client, and one busy client could lock the panel +out. And because a bind to `::` also takes this Mac's own `localhost` +connections, other machines filling their 512 never take loopback's. + +The per-address limit guards against a client that opens too many connections +by mistake. It does not stop a machine on the network that can use many +addresses, which IPv6 makes free; the 512 is what holds then. + +A client that opens more than 32 connections at once from one address, or +several clients sharing one address behind a router, have the extra connections +closed. A closed connection frees its place straight away. Refusals are counted +in the log at the debug level, at most one line a second, and the line never +names the address that was refused. + ## The private-network choice Dessau reads this Mac's own interfaces and selects the address that sits on a diff --git a/docs/context-probe.md b/docs/context-probe.md index f56c6a3e..0721fa46 100644 --- a/docs/context-probe.md +++ b/docs/context-probe.md @@ -49,7 +49,10 @@ minutes unless you change it, in the same section) and nothing is downloading, Dessau measures the first model that has no current measurement, one model at a time. A model you download later is measured the next time the Mac is idle. In `config.json` the switch is -`"context_probe": true` and the threshold `"idle_threshold_sec"`. +`"context_probe": true` and the threshold `idle_threshold_sec`, in seconds: +anything from 60 (1 minute) to 86,400 (24 hours), or leave it out for the +default. The threshold is the context probe's alone: the +[self-test](self-test.md) waits for one of its own. ## Which models it measures @@ -180,4 +183,4 @@ card says the probe was incomplete. Press **Measure now** to run it again. - [The memory budget, explained](memory-budget-explained.md) — what a served window costs, and why adopting a measurement is a separate act. - [Test your models while the Mac is idle](self-test.md) — the other idle - job, which shares the idle threshold. + job, which waits for an idle threshold of its own. diff --git a/docs/discord-bridge.md b/docs/discord-bridge.md index cdea9055..1b7bdacf 100644 --- a/docs/discord-bridge.md +++ b/docs/discord-bridge.md @@ -112,6 +112,15 @@ field. left out of the history sent with the next one. A single message too long for the window on its own is sent cut down to its end, so the latest part of it is what the model sees. +- An answer may take up to half the model's served window; the conversation + sent with it keeps the other half. An answer that reaches that limit stops + there, and the bot says so in a message of its own after it. A reasoning + model can spend the whole limit thinking, and then the bot says that the + model reached its length limit before it wrote an answer, rather than that + it answered with nothing. +- The bot reads a message once, when it is sent, and never reads an edit. A + mention of the bot or a question added to a message by editing it is not + answered; send it again as a new message. - The bridge holds a limited number of conversations and answers a small number of requests at once. It keeps up to 64 conversations of 32 turns, a turn up to 16 KiB — every message Discord delivers fits whole — and 8 MiB of diff --git a/docs/getting-started.md b/docs/getting-started.md index b3c14fdb..349d58ad 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -98,7 +98,8 @@ and nothing is unloaded to fit a lowered figure. See does and does not account for. **Settings → Batched requests** is how many requests one model server answers -at once: one by default. Each batched request holds its own attention cache, and +at once: one by default. A request beyond that waits for one in progress to +finish. Each batched request holds its own attention cache, and a model with no served context of its own is served at the largest window the budget has room for per request, so one is the setting that gives each model its widest window. Raise it on a Mac that serves several clients at once, and diff --git a/docs/memory-budget-explained.md b/docs/memory-budget-explained.md index 286e1e3e..9cd0ba39 100644 --- a/docs/memory-budget-explained.md +++ b/docs/memory-budget-explained.md @@ -36,16 +36,22 @@ any figure you type at its word. A loaded model is charged three things: its weights, a fifth of them again for the working set a running model needs whatever the prompt is, and the attention cache the window it is served at costs — once for every sequence its server may -decode at once. +decode at once. No more requests run on a model at once than it is charged +for; the next waits for one in progress to finish. The cache is the term that decides which models can share this Mac. It grows with the prompt, and what it costs per token is a property of the architecture rather than of the model's size: measured on a 128 GB Mac, four models between 18 GB and 45 GB of weights ranged from 12 KB to 353 KB per token, a thirtyfold -spread, and the largest of them was not the most expensive. The model server -also keeps a prompt's cache after the answer is sent, and caches stack across -requests, so the charge is what the model may come to hold rather than what it -holds the moment it loads. +spread, and the largest of them was not the most expensive. The charge is what +the model may come to hold rather than what it holds the moment it loads. + +The model server also keeps prompts' caches after their answers are sent, so +that the next turn of a conversation is not read again from the start. Those +kept caches do not stack beyond one window per model: Dessau holds them, all +together, to one served window of cache at the configuration's own figure, +before the multiplier described below. They are counted inside the charge +rather than added to it, on the strength of that multiplier's margin. The figure per token is read from the model's own configuration: how many of its layers attend over the whole prompt, and what one layer's entry costs. That @@ -54,7 +60,8 @@ than it, because a server keeps more than the raw cache — so Dessau multiplies it: five times for a model that caches keys and values per head, seven for one that caches a compressed latent, each the top of what its own kind was measured holding. A model whose configuration cannot be read is charged the flat figure -instead: its weights plus a fifth. +instead: its weights plus a fifth. That figure sets nothing aside for a cache, +so such a model's server keeps no prompt's cache once the answer is sent. ## The window is the operator's, and it is the same window twice diff --git a/docs/model-updates.md b/docs/model-updates.md index da6a352c..5743bd07 100644 --- a/docs/model-updates.md +++ b/docs/model-updates.md @@ -69,6 +69,15 @@ Each model's card under **My Models** says what the last check found: | Version unknown | Dessau did not record which version it downloaded, so it cannot tell whether a newer one exists. | Offered: it fetches the current version and records it | | Nothing | The last check found nothing newer, or checks are off. | Not offered | +Beside any of the three marks, the card names the files the newer version +changes — files it changes, adds or removes, never its documentation — up to +ten of them sorted by name, and says how many more there are: **Files it +changes: config.json, tokenizer.json and 12 more.** The names are shown as +plain text; a name made of anything but letters, digits and `._+-/` is counted +in the figure but not shown. A model whose download recorded its version +without each file's hash has no files named, since there is nothing to compare +them with. + Click **Update** to fetch the newer version. The card shows how far it has come, and **Cancel update** stops it; the model keeps answering requests meanwhile. diff --git a/docs/models-list.md b/docs/models-list.md index c50488d9..be97fd3e 100644 --- a/docs/models-list.md +++ b/docs/models-list.md @@ -193,6 +193,22 @@ same answer. relayed to the model exactly as sent and answered as the model answers it; nothing on the completions path reads the field. +## Recording + +`recording` says whether a conversation with the model is written to a +transcript on the Mac that runs the server. Dessau keeps no transcript, so it +is `false` for every model. It is on every entry, to every client — with or +without an API key, on the LAN as on this Mac — so the fact reaches everyone +before a model is chosen. A model [marked as keeping no +transcript](transcript.md) carries the same value; the mark governs the +Discord bridge and debug logging, not this field. + +| Where | What it shows | +|---|---| +| Dessau Chat's model picker | An icon beside each model, struck through while a conversation with it is not written down, labelled in words for a screen reader. | +| The control panel's model cards | The same icon. | +| Any other OpenAI-compatible client | Nothing: it reads a model's name and was not written to show this field, which is published for every client to read. | + ## The context figure `context_length` and `max_model_len` always carry the same number, as a JSON diff --git a/docs/posture-reference.md b/docs/posture-reference.md index 6be3ba14..089ec660 100644 --- a/docs/posture-reference.md +++ b/docs/posture-reference.md @@ -29,7 +29,7 @@ stored configuration, which a save changes before a restart applies it. | **The request log** | That each request to the API is written to the server log as method, path, status and duration, with no client address, prompt, answer or key; the level the log is at, and that it is kept in the logs folder of this account's data folder in a file created for this account alone. | The `log_level` setting, which is applied live. | | **Request statistics** | Whether request statistics are being recorded; what a record holds and what it never holds; that the same store also records when a model was loaded or evicted and the settings in force; for how many months and within how much room records are kept, and where; how far back the records on disk reach and how much room they take, or that the store could not be opened; and that every account on this Mac can read them. When recording is off, that no request is recorded. | The statistics switch, the two retention settings, and the store's status. | | **Debug logging** | Present while a model is armed for debug logging or running at it. Which models are armed, to be logged from their next start, and which are on, their model server having been started with it; that while it is on the model server's own log holds every request sent to it and every answer it produced — the prompts and the completions, whoever sent them — and the requests Dessau's own probes and self-test send; that it ends when that model server next starts, which memory pressure or another client's request can cause; that the file is in this account's logs folder, created for this account alone, stops at 64 MB, and that the previous run's file is kept beside it; that nothing is sent anywhere and clients are not told. Absent when no model is armed or at debug. | The armed set, and each resident model's running level. | -| **Self-test** | Whether the self-test is on: that while the Mac is idle Dessau loads one of its models at a time where it fits beside what is loaded, measures it with a fixed set of prompts and unloads what it loaded; that any request ends the run; and that the figures go to a file in this account's data folder and hold no prompt and no answer. When it is off, that Dessau loads no model on its own. | The `self_test` setting, which is applied live. | +| **Self-test** | Whether the self-test is on: that once the Mac has been idle for the self-test's own idle threshold, named in the line, Dessau loads one of its models at a time where it fits beside what is loaded, measures it with a fixed set of prompts and unloads what it loaded; that any request ends the run; and that the figures go to a file in this account's data folder and hold no prompt and no answer. When it is off, that Dessau loads no model on its own. | The `self_test` setting and the self-test's idle threshold, `self_test_idle_threshold_sec` (its default when unset), both applied live. | ## The two key lines diff --git a/docs/request-fields.md b/docs/request-fields.md index 939ead34..16e5b4fd 100644 --- a/docs/request-fields.md +++ b/docs/request-fields.md @@ -4,8 +4,9 @@ to the model server, changing only the fields listed under [What Dessau changes in a request it passes on](#what-dessau-changes-in-a-request-it-passes-on). Two fields are refused instead, and a request carrying either goes no further; -so is a request with nothing to answer, a `prompt` that is not a string, one -that asks for an empty answer, or one whose `stop` is not text. +so is a request whose body is not valid UTF-8, one with nothing to answer, a +`prompt` that is not a string, one that asks for an empty answer, or one whose +`stop` is not text. ## The refused fields @@ -51,6 +52,24 @@ is evicted for it, the model server never receives it, and the answer carries none of the [response headers](response-headers.md). Every client receives the same message, with or without the API key. +## A body that is not valid UTF-8 + +A request body must be valid UTF-8 text, as JSON sent between systems is. A +body holding any byte sequence that is not — a stray byte, a character cut +short, an over-long or surrogate encoding — anywhere in it, inside a message +or a key alike, is refused with **400** and the message +`request body is not valid UTF-8`. The model server takes such a body and +then fails to decode it, dropping the connection without an answer. Text in +any script, accents, CJK and emoji included, is valid UTF-8 and is passed on +as usual; so is a character written as a JSON escape (`\u00e9`). The check is +of the bytes, so an escape for half of a surrogate pair (`\ud800`) is plain +ASCII to it and is passed on as written, except where a field's own rule +refuses it (`stop`, below). + +The check is of the body's encoding as a whole: it reads no field, and the +message carries none of the body. Like the refusals above, it comes before a +model is chosen, so nothing is loaded or evicted for the request. + ## Nothing to answer A request with nothing to generate from is refused with **400**: diff --git a/docs/request-statistics.md b/docs/request-statistics.md index 3c5b7fec..0b304599 100644 --- a/docs/request-statistics.md +++ b/docs/request-statistics.md @@ -40,9 +40,16 @@ of it, field by field, in Alongside those, Dessau counts per model how many requests each outcome accounted for, how many tokens went in and came out altogether, how many times the model loaded and how many times it failed to, how long the last -load took, how many times it was evicted to make room for another, and the -last request's own timings. It also keeps a per-minute total of requests and -tokens for the last day. +load took, how many times it was evicted to make room for another, how many +times a program unloaded it through the [model API](unload-reference.md) and +which kind of caller asked, and the last request's own timings. It also keeps +a per-minute total of requests and tokens for the last day. + +Each model's card on the Statistics tab shows an unload a program asked for +beside its evictions, not among them, since it made no room for anything: +**evicted 2× · unloaded by a program 3× (2 on this Mac, 1 by a paired +client)**. The kinds are a program on this Mac, a program elsewhere with the +API key, and a paired client — never the key itself, and never which client. The Statistics tab shows the most recent thousand requests one by one, and the totals for the last hour and the last day, which reach back further than a diff --git a/docs/self-test-reference.md b/docs/self-test-reference.md index 5b5924d7..43cd42e1 100644 --- a/docs/self-test-reference.md +++ b/docs/self-test-reference.md @@ -91,7 +91,8 @@ for the same model, which times the prompt alone. | | | | --- | --- | | The idle check | once a minute | -| Idle means | no request in flight, none waiting for a load, no download running, and the last request older than the idle threshold (`idle_threshold_sec`, five minutes unless set; shared with the context probe) | +| Idle means | no request in flight, none waiting for a load, no download running, and the last request older than the self-test's idle threshold | +| The self-test's idle threshold | `self_test_idle_threshold_sec`, 4 hours unless set, from 60 seconds to 86,400 (24 hours); the context probe waits for its own, `idle_threshold_sec` | | A request counts when | it is a client's request for an answer that the server admits, however it ends — answered, failed or refused by the model's server — and whether or not its model is still loaded; a request turned away for a missing or wrong key, or from an unpaired client, does not count | | A model is loaded only when | it fits beside what is in memory; the self-test never evicts | | A run in progress ends when | a request is in flight on any model, a load is waiting for room, a load has been refused room since the run began, or a client's load needs the memory the run is holding | diff --git a/docs/self-test.md b/docs/self-test.md index 0017bf61..2c671422 100644 --- a/docs/self-test.md +++ b/docs/self-test.md @@ -31,13 +31,21 @@ are. Once a minute Dessau asks whether the Mac is idle: no request in flight, no request waiting for a model to load, no download running, and the last -request older than the idle threshold. Every client request the server -admits counts, however it ends — one that failed, or whose model has since -been unloaded, counts the same as one that was answered. A request turned -away for a missing or wrong key, or from an unpaired client, does not count. The threshold is five minutes unless you -change it under **Settings → Context probe**, `idle_threshold_sec` in -`config.json`; the self-test and the [context probe](context-probe.md) share -it. When the Mac is idle, Dessau picks the +request older than the self-test's idle threshold. Every client request the +server admits counts, however it ends — one that failed, or whose model has +since been unloaded, counts the same as one that was answered. A request +turned away for a missing or wrong key, or from an unpaired client, does not +count. + +The self-test's idle threshold is its own: 4 hours unless you change it in +**Self-test idle threshold** under **Settings → Self-test**, or as +`self_test_idle_threshold_sec` in `config.json`, in seconds — anything from +60 (1 minute) to 86,400 (24 hours). Loading and measuring a model is work a +short pause in use should not set off, so it waits for a long quiet spell. +The [context probe](context-probe.md) waits for a threshold of its own, +`idle_threshold_sec`, and changing one leaves the other as it is. + +When the Mac is idle, Dessau picks the model measured longest ago — a model never measured comes first, and a model measured within the last day is left alone — and runs it through the same short set every model gets: @@ -55,6 +63,10 @@ short set every model gets: The names are [llama-bench](https://github.com/ggml-org/llama.cpp/tree/master/tools/llama-bench)'s, so a figure here can be set beside a published one. +The set is a chat benchmark, so the self-test measures only models that can +chat. A model that cannot, such as a decision model or an OCR model, is +passed over and never loaded for it (see [chat models](chat-models.md)). + When the set is done Dessau writes one line to the results file and, if the self-test was what loaded the model, unloads it again; a model that was already in memory is left there. The self-test never unloads a diff --git a/docs/transcript.md b/docs/transcript.md index 7a16262f..9129bd20 100644 --- a/docs/transcript.md +++ b/docs/transcript.md @@ -27,21 +27,10 @@ first request the model ever serves after it is downloaded; the panel draws a row for it, marked *not on this Mac*, so it can be cleared from the form that shows it. -## What a client is told - -Every client that asks the server for its models is told, for each one, -whether a conversation with it is recorded: the `recording` field on every -entry of the [models list](models-list.md), present with or without an API -key, on the LAN as on this Mac. Dessau keeps no transcript, so it is `false` -for every model. Dessau Chat reads it and shows an icon beside each model in -its picker, struck through while a conversation with the model is not written -down, labelled in words for a screen reader, so the state is visible before -the model is chosen. The control panel's model cards carry the same icon. - -An ordinary OpenAI-compatible client reads a model's name and displays none of -this. Dessau cannot make software show something it was not written to show; -what it can do is publish the fact where every client can read it, and show it -in its own client and panel. +Every client is told whether a conversation with a model is recorded, +through the models list's `recording` field and the icon Dessau Chat and the +control panel draw from it; [the models list](models-list.md#recording) +describes both. ## Over the Discord bridge diff --git a/docs/unload-reference.md b/docs/unload-reference.md index 59bfea34..33e23a0e 100644 --- a/docs/unload-reference.md +++ b/docs/unload-reference.md @@ -79,7 +79,10 @@ are on, as a removal with the reason `released` and the kind of caller that asked: a program on this Mac (whether or not it sent the API key), a program elsewhere that sent the API key, or a paired client. The statistics record the kind only, never the key and never which client -([statistics reference](statistics-store-reference.md)). The server log's +([statistics reference](statistics-store-reference.md)). The control panel's +Statistics tab shows the count on the model's card, beside its evictions and +by kind of caller ([request statistics](request-statistics.md#what-is-recorded)). +The server log's `model unloaded` line says the same, and names a paired client by the name it was paired under and the short fingerprint of its key. diff --git a/internal/app/app.go b/internal/app/app.go index c37c10c1..51f49ab6 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -62,7 +62,8 @@ type App struct { ToolProbe *toolprobe.Probe Log *slog.Logger // idleQuiet is Options.Idle.Quiet: a cadence a test fixed, which a save - // must not replace with the configured threshold. + // must not replace with the configured thresholds — the context probe's + // or the self-test's. idleQuiet time.Duration // logLevel is Options.LogLevel: the variable Log's handler reads. Held so @@ -255,6 +256,8 @@ type Options struct { // IdleOptions is the cadence the idle loop and the context probe run at; see // Options.Idle. Zero means the default for each. type IdleOptions struct { + // Quiet, when set, fixes both idle thresholds — the context probe's and + // the self-test's — for a test, in place of the configured ones. Tick, Poll, Quiet time.Duration // StepTimeout bounds one of the probe's requests, given the body's size. StepTimeout func(bodyBytes int) time.Duration @@ -422,6 +425,9 @@ func New(opts Options) (*App, error) { Tick: opts.Idle.Tick, Poll: opts.Idle.Poll, Quiet: opts.Idle.Quiet, + // A test's fixed cadence fixes the self-test's threshold as well; + // otherwise applyIdleJobs puts the configured one in force below. + SelfTestQuiet: opts.Idle.Quiet, }) // Staleness is a stored fact: judged now, against what this start put in // force, before anything reads a measurement. @@ -1517,6 +1523,7 @@ func (s modelSource) Resolve(repoID string) (runtime.ResolvedModel, error) { Bytes: m.Bytes, ServedContext: window, KVChargePerToken: m.KVChargePerToken, + KVBytesPerToken: m.KVBytesPerToken, }, nil } @@ -1753,6 +1760,7 @@ func (a *App) startDownload(repoID, commit string) error { Bytes: bytes, ContextLength: facts.ContextLength, KVChargePerToken: facts.KVChargePerToken, + KVBytesPerToken: facts.KVBytesPerToken, ChatTemplate: facts.ChatTemplate, QuantizationBits: facts.QuantizationBits, PipelineTag: pipelineTag, diff --git a/internal/app/app_test.go b/internal/app/app_test.go index cc8dbe1b..c0779430 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -25,9 +25,15 @@ import ( // fakeHub serves a minimal model repo. func fakeHub(t *testing.T) *httptest.Server { + t.Helper() + return fakeHubWithConfig(t, `{"model_type":"qwen3","max_position_embeddings":40960}`) +} + +// fakeHubWithConfig is fakeHub serving the model configuration given. +func fakeHubWithConfig(t *testing.T, modelConfig string) *httptest.Server { t.Helper() files := map[string][]byte{ - "config.json": []byte(`{"model_type":"qwen3","max_position_embeddings":40960}`), + "config.json": []byte(modelConfig), "model.safetensors": make([]byte, 2048), "tokenizer.json": []byte(`{}`), } diff --git a/internal/app/contextprobe.go b/internal/app/contextprobe.go index a65e6cde..85cac21c 100644 --- a/internal/app/contextprobe.go +++ b/internal/app/contextprobe.go @@ -89,23 +89,30 @@ func (s probeSources) Available() int64 { } // Unload stops a model server for the probe, and never a pinned one -// (iss-2609211754251373); see unloadUnpinned. A pin saved between the check -// and the stop is met at the next step's unload. +// (iss-2609211754251373); see unloadUnpinned. func (s probeSources) Unload(repoID string) error { return s.a.unloadUnpinned(repoID, contextprobe.ErrPinned) } -// unloadUnpinned is the idle jobs' unload: the pool's Unload, refused with -// refusal — the job's own ErrPinned — when the model is pinned. The pool's -// Unload is the operator's and stops whatever it is given, so a pin is each -// idle job's to honour, and this is the one place they honour it. +// unloadUnpinned is the idle jobs' unload: the pool's UnloadUnpinned, its +// pin refusal answered with refusal — the job's own ErrPinned. The pool's +// Unload is the operator's and stops whatever it is given; UnloadUnpinned +// reads the pin under the same hold of the pool's lock as the stop, so a pin +// saved while the job is deciding is never overridden (iss-2610042033419572). func (a *App) unloadUnpinned(repoID string, refusal error) error { - if a.isPinned(repoID) { + beforeIdleUnload(repoID) + err := a.Pool.UnloadUnpinned(repoID) + if errors.Is(err, runtime.ErrPinned) { return fmt.Errorf("%s: %w", repoID, refusal) } - return a.Pool.Unload(repoID) + return err } +// beforeIdleUnload runs as an idle job's unload is about to reach the pool, +// outside every lock. It does nothing; it is the seam a test saves a pin +// through at the last instant a person's save could land before the stop. +var beforeIdleUnload = func(string) {} + // isPinned reports whether the pool holds the model pinned, whichever way // either spelling folds. func (a *App) isPinned(repoID string) bool { @@ -147,10 +154,12 @@ func (s probeSources) Endpoint() (string, string) { // applyIdleJobs puts the idle loop's switches into force: the loop runs when // either idle job is switched on or a probe is queued, the self-test's own -// set follows its switch alone, and the idle threshold applies to both. +// set follows its switch alone, the context probe waits for the idle +// threshold and the self-test for its own (iss-2610041956214381). func (a *App) applyIdleJobs(c config.Config) { if a.idleQuiet == 0 { a.SelfTest.SetQuiet(c.EffectiveIdleThreshold()) + a.SelfTest.SetSelfTestQuiet(c.EffectiveSelfTestIdleThreshold()) } a.SelfTest.SetEnabled(c.SelfTest || c.ContextProbe || len(a.Probe.Queued()) > 0) } diff --git a/internal/app/idle_unload_pin_race_test.go b/internal/app/idle_unload_pin_race_test.go new file mode 100644 index 00000000..9d282704 --- /dev/null +++ b/internal/app/idle_unload_pin_race_test.go @@ -0,0 +1,51 @@ +package app + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/intentdriven/Dessau/internal/contextprobe" + "github.com/intentdriven/Dessau/internal/selftest" +) + +// A pin saved in the instant before an idle job's unload reaches the pool is +// honoured: the model stays loaded and pinned, and the job is refused with its +// own ErrPinned. The pin check and the stop are one hold of the pool's lock, +// so no save can land between them (iss-2610042033419572). +func TestAnIdleJobsUnloadHonoursAPinSavedJustBeforeTheStop(t *testing.T) { + for _, tc := range []struct { + name string + unload func(*App, string) error + want error + }{ + {"self-test", func(a *App, id string) error { return selfTestServer{a}.Unload(id) }, selftest.ErrPinned}, + {"context probe", func(a *App, id string) error { return probeSources{a}.Unload(id) }, contextprobe.ErrPinned}, + } { + t.Run(tc.name, func(t *testing.T) { + a := newSelfTestPinApp(t, "org/m") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, release, err := a.Pool.Acquire(ctx, "org/m") + if err != nil { + t.Fatal(err) + } + release() + + previous := beforeIdleUnload + beforeIdleUnload = func(string) { pin(t, a, "ORG/M") } + t.Cleanup(func() { beforeIdleUnload = previous }) + + if err := tc.unload(a, "org/m"); !errors.Is(err, tc.want) { + t.Errorf("the unload of a model pinned just before the stop = %v, want %v", err, tc.want) + } + if !a.isPinned("org/m") { + t.Error("the model is no longer pinned") + } + if !residentIn(a, "org/m") { + t.Error("the idle job unloaded a model pinned just before the stop") + } + }) + } +} diff --git a/internal/app/promptcache_test.go b/internal/app/promptcache_test.go new file mode 100644 index 00000000..2e5a5de5 --- /dev/null +++ b/internal/app/promptcache_test.go @@ -0,0 +1,74 @@ +package app + +import ( + "testing" + "time" + + "github.com/intentdriven/Dessau/internal/registry" +) + +// shapedConfig declares a cache: 2 layers of 2 key-value heads of 128, which +// is 2,048 bytes a token of real cache and 10,240 charged. +const shapedConfig = `{"model_type":"qwen3","max_position_embeddings":40960, + "num_hidden_layers":2,"num_key_value_heads":2,"head_dim":128}` + +const shapedRealPerToken = 2 * 2 * 128 * 2 * 2 + +// The pool is handed the real cache a token costs beside its charge, so the +// launcher can bound the model server's prompt cache to one served window of +// it (iss-2610071035130302). +func TestTheResolvedModelCarriesTheRealCacheFigure(t *testing.T) { + a := newBudgetApp(t, 128*gb, captureConfig()) + m := captureModel("org/long") + m.KVBytesPerToken = 327680 / 5 + putModel(t, a, m) + resolved, err := modelSource{a}.Resolve("org/long") + if err != nil { + t.Fatal(err) + } + if resolved.KVBytesPerToken != 327680/5 { + t.Errorf("the pool resolves %d real bytes a token, want %d", resolved.KVBytesPerToken, 327680/5) + } +} + +// A model carries the figure the moment its download completes, as it +// carries the charge, not only after the next startup rescan. +func TestADownloadRecordsTheRealCacheFigure(t *testing.T) { + a := newTestApp(t) + a.Hub.BaseURL = fakeHubWithConfig(t, shapedConfig).URL + if err := a.Download("org/repo"); err != nil { + t.Fatalf("Download: %v", err) + } + waitFor(t, "the model to become ready", func() bool { + m, err := a.Registry.Get("org/repo") + return err == nil && m.Ready() + }) + m, _ := a.Registry.Get("org/repo") + if m.KVChargePerToken != shapedRealPerToken*5 { + t.Errorf("KVChargePerToken = %d, want %d", m.KVChargePerToken, shapedRealPerToken*5) + } + if m.KVBytesPerToken != shapedRealPerToken { + t.Errorf("KVBytesPerToken = %d, want %d", m.KVBytesPerToken, shapedRealPerToken) + } +} + +// And an update records the new version's figure with the rest of its facts. +func TestAnUpdateRecordsTheRealCacheFigure(t *testing.T) { + a, h := newStagedApp(t) + h.set(func(h *versionedHub) { + h.versions[commitV2]["config.json"] = []byte(shapedConfig) + h.current = commitV2 + }) + a.Registry.SetUpdate("org/repo", commitV1, registry.UpdateCheck{Status: registry.UpdateAvailable, Commit: commitV2, CheckedAt: time.Now()}) + if err := a.Update("org/repo"); err != nil { + t.Fatalf("Update: %v", err) + } + waitSettled(t, a) + m, _ := a.Registry.Get("org/repo") + if !m.Ready() || m.Commit != commitV2 { + t.Fatalf("after the update: state %s, commit %s", m.State, m.Commit) + } + if m.KVBytesPerToken != shapedRealPerToken { + t.Errorf("KVBytesPerToken = %d, want %d", m.KVBytesPerToken, shapedRealPerToken) + } +} diff --git a/internal/app/selftest.go b/internal/app/selftest.go index 1d0e0cf6..07ca7f40 100644 --- a/internal/app/selftest.go +++ b/internal/app/selftest.go @@ -84,8 +84,9 @@ func (s selfTestServer) Unload(repoID string) error { return s.a.unloadUnpinned(repoID, selftest.ErrPinned) } -// Pinned is the pool's pin, the one the context probe's candidates and both -// idle jobs' unloads read (isPinned). +// Pinned is the pool's pin, the one the context probe's candidates read +// (isPinned) and both idle jobs' unloads read under the pool's lock +// (Pool.UnloadUnpinned). func (s selfTestServer) Pinned(repoID string) bool { return s.a.isPinned(repoID) } func (s selfTestServer) Concurrency() int { return s.a.Pool.DecodeConcurrency() } diff --git a/internal/app/selftest_pins_test.go b/internal/app/selftest_pins_test.go index 12a9873d..e6569f6c 100644 --- a/internal/app/selftest_pins_test.go +++ b/internal/app/selftest_pins_test.go @@ -92,7 +92,7 @@ func runOnce(t *testing.T, srv selftest.Server) selftest.Run { path := filepath.Join(t.TempDir(), selftest.FileName) r := selftest.New(selftest.Options{ Server: srv, Path: path, - Tick: 10 * time.Millisecond, Poll: 5 * time.Millisecond, Quiet: time.Millisecond, + Tick: 10 * time.Millisecond, Poll: 5 * time.Millisecond, Quiet: time.Millisecond, SelfTestQuiet: time.Millisecond, }) r.SetEnabled(true) var runs []selftest.Run @@ -230,7 +230,7 @@ func TestTheSelfTestDoesNotLoadAModelPinnedAndNotLoaded(t *testing.T) { path := filepath.Join(t.TempDir(), selftest.FileName) r := selftest.New(selftest.Options{ Server: srv, Path: path, - Tick: 10 * time.Millisecond, Poll: 5 * time.Millisecond, Quiet: time.Millisecond, + Tick: 10 * time.Millisecond, Poll: 5 * time.Millisecond, Quiet: time.Millisecond, SelfTestQuiet: time.Millisecond, }) r.SetEnabled(true) waitFor(t, "the self-test to measure the unpinned model", func() bool { diff --git a/internal/app/selftest_threshold_test.go b/internal/app/selftest_threshold_test.go new file mode 100644 index 00000000..715b0481 --- /dev/null +++ b/internal/app/selftest_threshold_test.go @@ -0,0 +1,52 @@ +package app + +import ( + "testing" + "time" + + "github.com/intentdriven/Dessau/internal/config" +) + +// The idle loop is handed two thresholds, one per setting +// (iss-2610041956214381): the self-test's own, self_test_idle_threshold_sec, +// four hours unless set, and the context probe's, idle_threshold_sec. Both are +// in force from the start and follow every save; a save that names neither +// moves neither. +func TestTheSelfTestAndTheProbeWaitForTheirOwnThresholds(t *testing.T) { + a := newTestApp(t) + job, self := a.SelfTest.Thresholds() + if job != config.DefaultIdleThresholdSec*time.Second || self != config.DefaultSelfTestIdleThresholdSec*time.Second { + t.Errorf("at defaults the loop waits %v for the probe and %v for the self-test; want %ds and %ds", + job, self, config.DefaultIdleThresholdSec, config.DefaultSelfTestIdleThresholdSec) + } + + c := config.Default() + c.IdleThresholdSec = 120 + c.SelfTestIdleThresholdSec = 7200 + if err := a.SetConfig(c); err != nil { + t.Fatal(err) + } + if job, self := a.SelfTest.Thresholds(); job != 120*time.Second || self != 7200*time.Second { + t.Errorf("after a save the loop waits %v for the probe and %v for the self-test; want 2m0s and 2h0m0s", job, self) + } + + c = a.Config() + c.LogLevel = config.LogLevelDetailed + if err := a.SetConfig(c); err != nil { + t.Fatal(err) + } + if got := a.Config(); got.IdleThresholdSec != 120 || got.SelfTestIdleThresholdSec != 7200 { + t.Errorf("a save of the log level moved the thresholds: probe %d, self-test %d", + got.IdleThresholdSec, got.SelfTestIdleThresholdSec) + } +} + +// A file carrying the self-test's threshold puts it in force at construction. +func TestASavedSelfTestThresholdIsInForceFromTheStart(t *testing.T) { + c := config.Default() + c.SelfTestIdleThresholdSec = config.MaxIdleThresholdSec + a, _ := statsApp(t, c) + if _, self := a.SelfTest.Thresholds(); self != config.MaxIdleThresholdSec*time.Second { + t.Errorf("the self-test waits %v, want the saved %ds", self, config.MaxIdleThresholdSec) + } +} diff --git a/internal/app/staged.go b/internal/app/staged.go index e8295cd8..a82a0cfc 100644 --- a/internal/app/staged.go +++ b/internal/app/staged.go @@ -264,7 +264,7 @@ func (a *App) Update(repoID string) error { switch u.Status { case registry.UpdateAvailable: commit = u.Commit - case registry.UpdateRunsOwnCode, registry.UpdateAwaitingReview, registry.UpdateCannotCheck: + case registry.UpdateRunsOwnCode, registry.UpdateCannotCheck: return fmt.Errorf("%s: %w", m.RepoID, ErrUpdateNotOffered) } } @@ -727,6 +727,7 @@ func (a *App) restoreFallback(repoID string) bool { Bytes: bytes, ContextLength: facts.ContextLength, KVChargePerToken: facts.KVChargePerToken, + KVBytesPerToken: facts.KVBytesPerToken, ChatTemplate: facts.ChatTemplate, QuantizationBits: facts.QuantizationBits, PipelineTag: m.PipelineTag, diff --git a/internal/app/staged_fallback_test.go b/internal/app/staged_fallback_test.go index 9b821300..0b46ab9d 100644 --- a/internal/app/staged_fallback_test.go +++ b/internal/app/staged_fallback_test.go @@ -139,12 +139,15 @@ func TestANewVersionThatFailsItsFirstLoadPutsTheOldOneBack(t *testing.T) { if err := servable(a); err != nil { t.Errorf("the old version put back is not served: %v", err) } + // The failed version is removed just after the record is written, so + // wait for the staging folder to empty rather than look once. + waitFor(t, "the staging folder to empty after the old version went back", func() bool { + entries, _ := os.ReadDir(filepath.Join(a.stagingRoot(), "org")) + return len(entries) == 0 + }) if got := asidesOf(a); len(got) != 0 { t.Errorf("left aside after the old version went back: %v", got) } - if entries, _ := os.ReadDir(filepath.Join(a.stagingRoot(), "org")); len(entries) != 0 { - t.Errorf("the failed new version was left in the staging folder: %d entries", len(entries)) - } } // The old copy is held aside until the new version has loaded and answered @@ -256,9 +259,9 @@ func TestASecondUpdateBeforeAnyLoadKeepsTheVersionThatServed(t *testing.T) { if m, _ := a.Registry.Get("org/repo"); m.Commit != commitV3 { t.Fatalf("the second update was not swapped in: commit %s", m.Commit) } - if got := asidesOf(a); len(got) != 1 { - t.Fatalf("held aside after two updates: %v, want one copy", got) - } + // The second update's own aside copy is removed just after the download + // mark is cleared, outside the lock, so wait for it rather than look once. + waitFor(t, "one copy to be held after two updates", func() bool { return len(asidesOf(a)) == 1 }) if err := servable(a); err == nil { t.Fatal("the broken newest version loaded") diff --git a/internal/app/staged_test.go b/internal/app/staged_test.go index c86d2095..21ae810c 100644 --- a/internal/app/staged_test.go +++ b/internal/app/staged_test.go @@ -398,11 +398,11 @@ func TestAnUpdateClearsFileFactsAndKeepsSettings(t *testing.T) { } } -// Update offers nothing for a version Dessau would not run, one waiting for -// review, or one whose code a check could not tell. +// Update offers nothing for a version Dessau would not run, or one whose code +// a check could not tell. func TestUpdateIsRefusedWhereNoneIsOffered(t *testing.T) { a, _ := newStagedApp(t) - for _, status := range []string{registry.UpdateRunsOwnCode, registry.UpdateAwaitingReview, registry.UpdateCannotCheck} { + for _, status := range []string{registry.UpdateRunsOwnCode, registry.UpdateCannotCheck} { a.Registry.SetUpdate("org/repo", commitV1, registry.UpdateCheck{Status: status, Commit: commitV2, CheckedAt: time.Now()}) if err := a.Update("org/repo"); !errors.Is(err, ErrUpdateNotOffered) { t.Errorf("%s: err = %v, want ErrUpdateNotOffered", status, err) diff --git a/internal/app/updatecheck.go b/internal/app/updatecheck.go index 829b6c08..b4a49ccf 100644 --- a/internal/app/updatecheck.go +++ b/internal/app/updatecheck.go @@ -8,6 +8,7 @@ import ( "os" "path" "path/filepath" + "slices" "strings" "time" @@ -39,8 +40,9 @@ var errChecksOff = errors.New("update checks were turned off") // ReviewedBuilds says whether a model is a decision model, and which upstream // commits of it a Dessau release has reviewed. A decision model is offered an -// update only to a reviewed commit (itd-2610030656210408). Nil means no model -// is a decision model. +// update only to a reviewed commit (itd-2610030656210408), and a newer one +// that is not reviewed is never marked (iss-2610042101436891). Nil means no +// model is a decision model. type ReviewedBuilds func(repoID string) (decision bool, reviewed []string) // UpdateRound is what one round of update checks did. @@ -225,10 +227,14 @@ func (a *App) checkOne(ctx context.Context, m registry.Model) (registry.UpdateCh if err != nil { return registry.UpdateCheck{}, err } - changed, configChanged := a.compareVersions(m, hub.WantedFiles(files)) + changed, configChanged, paths := a.compareVersions(m, hub.WantedFiles(files)) if !changed { return registry.UpdateCheck{Status: registry.UpdateCurrent}, nil } + // What a newer version is found to be, naming the files it changes. + found := func(status string) (registry.UpdateCheck, error) { + return newerVersion(status, up.Commit, paths), nil + } if configChanged { if !a.Config().UpdateCheck { return registry.UpdateCheck{}, errChecksOff @@ -248,7 +254,7 @@ func (a *App) checkOne(ctx context.Context, m registry.Model) (registry.UpdateCh // sha256 to check, not the listed bytes, or past the bound — // so whether the newer version names a model_file is unknown, // and it is not offered (iss-2610042101439623). - return registry.UpdateCheck{Status: registry.UpdateCannotCheck, Commit: up.Commit}, nil + return found(registry.UpdateCannotCheck) case err != nil: return registry.UpdateCheck{}, err default: @@ -257,7 +263,7 @@ func (a *App) checkOne(ctx context.Context, m registry.Model) (registry.UpdateCh return registry.UpdateCheck{}, err } if names { - return registry.UpdateCheck{Status: registry.UpdateRunsOwnCode, Commit: up.Commit}, nil + return found(registry.UpdateRunsOwnCode) } } } @@ -265,28 +271,45 @@ func (a *App) checkOne(ctx context.Context, m registry.Model) (registry.UpdateCh if decision, reviewed := a.reviewed(m.RepoID); decision { for _, c := range reviewed { if c == up.Commit { - return registry.UpdateCheck{Status: registry.UpdateAvailable, Commit: up.Commit}, nil + return found(registry.UpdateAvailable) } } - return registry.UpdateCheck{Status: registry.UpdateAwaitingReview, Commit: up.Commit}, nil + // Nothing to offer, and a decision model is never marked: the + // 'awaiting review' mark is withdrawn (iss-2610042101436891), so + // the check records what it records for a version with nothing + // newer, which carries no mark and no Update. + return registry.UpdateCheck{Status: registry.UpdateCurrent}, nil } } - return registry.UpdateCheck{Status: registry.UpdateAvailable, Commit: up.Commit}, nil + return found(registry.UpdateAvailable) +} + +// newerVersion is what a check records for a newer version: its status, its +// commit, and the files it changes, the first registry.MaxUpdateFiles of them +// in order with the count of all (iss-2610042101436222). +func newerVersion(status, commit string, paths []string) registry.UpdateCheck { + slices.Sort(paths) + u := registry.UpdateCheck{Status: status, Commit: commit, FilesChanged: len(paths)} + if len(paths) > 0 { + u.Files = slices.Clone(paths[:min(len(paths), registry.MaxUpdateFiles)]) + } + return u } // compareVersions says whether the files Dessau uses differ between the -// version on disk and the listing at the newer commit, and whether -// config.json is among them. +// version on disk and the listing at the newer commit, whether config.json is +// among them, and which they are: a file changed, removed or added. // // Documentation is not compared: a README, a licence, any Markdown. A file // the record holds a hash for differs when the listing gives another or // lists it no more. A file the record has no hash for is unknown, not // changed (iss-2610031239271873): it counts as added only when it is not on // disk, which is what an added file is. A version recorded as its commit -// alone has no hashes to compare, so any move of the commit is a change. -func (a *App) compareVersions(m registry.Model, files []hub.File) (changed, configChanged bool) { +// alone has no hashes to compare, so any move of the commit is a change, and +// which files it changes is not known: no path is named. +func (a *App) compareVersions(m registry.Model, files []hub.File) (changed, configChanged bool, paths []string) { if m.FileHashes == nil { - return true, true + return true, true, nil } // A config.json the record has no hash for is read whenever anything // changed: whether the newer one names a model_file cannot otherwise be @@ -310,6 +333,7 @@ func (a *App) compareVersions(m registry.Model, files []hub.File) (changed, conf } mark := func(p string) { changed = true + paths = append(paths, p) if p == "config.json" { configChanged = true } @@ -333,7 +357,7 @@ func (a *App) compareVersions(m registry.Model, files []hub.File) (changed, conf mark(p) } } - return changed, configChanged + return changed, configChanged, paths } // isDocumentation reports whether a repository file is one no model server diff --git a/internal/app/updatecheck_test.go b/internal/app/updatecheck_test.go index 5d1152f5..7d853ff9 100644 --- a/internal/app/updatecheck_test.go +++ b/internal/app/updatecheck_test.go @@ -12,6 +12,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "reflect" "strings" "sync" "testing" @@ -261,6 +262,51 @@ func TestAChangedWeightMarksTheModel(t *testing.T) { } } +// A check records which files the newer version changes — changed, added and +// removed alike, documentation never — so the card can name them +// (iss-2610042101436222). +func TestACheckRecordsTheFilesTheNewerVersionChanges(t *testing.T) { + recorded := recordedFiles() + recorded["old.json"] = hConfig + files := recordedFiles() + files["config.json"] = hConfig2 + files["model.safetensors"] = hWeight2 + files["README.md"] = hReadme2 + files["tokenizer.json"] = hConfig2 + h := newCheckFakeHub(t, map[string]upstreamRepo{"org/m": {commit: newer, files: files, config: `{"model_type":"qwen3"}`}}) + a, _ := newCheckApp(t, h, true, map[string]map[string]string{"org/m": recorded}) + a.CheckForUpdates(context.Background(), a.updateCheckDue(time.Now())) + u := update(t, a, "org/m") + want := []string{"config.json", "model.safetensors", "old.json", "tokenizer.json"} + if u == nil || u.Status != registry.UpdateAvailable || strings.Join(u.Files, ",") != strings.Join(want, ",") || u.FilesChanged != len(want) { + t.Errorf("Update = %+v, want available naming %v of %d", u, want, len(want)) + } +} + +// The list a check records is bounded: past MaxUpdateFiles names it keeps the +// first in order and counts the rest, so a repository that changes a thousand +// shards costs the index a dozen names. +func TestTheChangedFilesAreBoundedAndCounted(t *testing.T) { + recorded := recordedFiles() + files := recordedFiles() + n := registry.MaxUpdateFiles + 12 + for i := 0; i < n; i++ { + p := fmt.Sprintf("model-%05d.safetensors", i) + recorded[p] = hWeights + files[p] = hWeight2 + } + h := newCheckFakeHub(t, map[string]upstreamRepo{"org/m": {commit: newer, files: files}}) + a, _ := newCheckApp(t, h, true, map[string]map[string]string{"org/m": recorded}) + a.CheckForUpdates(context.Background(), a.updateCheckDue(time.Now())) + u := update(t, a, "org/m") + if u == nil || len(u.Files) != registry.MaxUpdateFiles || u.FilesChanged != n { + t.Fatalf("Update = %+v, want %d names of %d", u, registry.MaxUpdateFiles, n) + } + if u.Files[0] != "model-00000.safetensors" || u.Files[registry.MaxUpdateFiles-1] != fmt.Sprintf("model-%05d.safetensors", registry.MaxUpdateFiles-1) { + t.Errorf("the names kept are not the first in order: %v", u.Files) + } +} + // A newer version whose config.json names its own code is marked as one // Dessau will not run (criterion 8); one that does not is offered. func TestANewerVersionThatShipsCodeIsMarkedAsOneDessauWillNotRun(t *testing.T) { @@ -306,12 +352,12 @@ func TestAnUnrecordedFileIsAddedOnlyWhenItIsNotOnDisk(t *testing.T) { func TestAnUnreachableHubLeavesMarksAsTheyWere(t *testing.T) { h := newCheckFakeHub(t, nil) a, logs := newCheckApp(t, h, true, map[string]map[string]string{"org/a": recordedFiles(), "org/b": recordedFiles()}) - mark := registry.UpdateCheck{Status: registry.UpdateAvailable, Commit: newer, CheckedAt: time.Now().Add(-48 * time.Hour)} + mark := registry.UpdateCheck{Status: registry.UpdateAvailable, Commit: newer, Files: []string{"model.safetensors"}, FilesChanged: 1, CheckedAt: time.Now().Add(-48 * time.Hour)} a.Registry.SetUpdate("org/a", onDisk, mark) h.srv.Close() a.updateCheckTickAt(context.Background(), time.Now()) - if u := update(t, a, "org/a"); u == nil || *u != mark { + if u := update(t, a, "org/a"); u == nil || !reflect.DeepEqual(*u, mark) { t.Errorf("the mark changed: %+v", u) } if u := update(t, a, "org/b"); u != nil { @@ -383,23 +429,29 @@ func TestARoundStopsWhenTheHubsBudgetRunsLow(t *testing.T) { } } -// A decision model's newer version is marked as one that will be offered once -// reviewed, and offered once a Dessau release has reviewed it (criterion 9). -func TestADecisionModelWaitsForAReviewedVersion(t *testing.T) { +// A decision model is never marked (iss-2610042101436891, the maintainer's +// decision of 2026-10-07 withdrawing criterion 9's mark): a newer version no +// Dessau release has reviewed is recorded as nothing to offer, which carries no +// mark and no Update, while a reviewed one is offered as any newer version is. +func TestADecisionModelIsNeverMarkedAwaitingReview(t *testing.T) { files := recordedFiles() files["model.safetensors"] = hWeight2 - for reviewed, want := range map[string]string{ - "": registry.UpdateAwaitingReview, - newer: registry.UpdateAvailable, + for reviewed, want := range map[string]registry.UpdateCheck{ + "": {Status: registry.UpdateCurrent}, + newer: {Status: registry.UpdateAvailable, Commit: newer}, } { h := newCheckFakeHub(t, map[string]upstreamRepo{"org/decide": {commit: newer, files: files}}) a, _ := newCheckApp(t, h, true, map[string]map[string]string{"org/decide": recordedFiles()}) a.reviewed = func(id string) (bool, []string) { return id == "org/decide", []string{onDisk, reviewed} } - a.CheckForUpdates(context.Background(), a.updateCheckDue(time.Now())) - if u := update(t, a, "org/decide"); u == nil || u.Status != want || u.Commit != newer { - t.Errorf("reviewed %q: Update = %+v, want %s", reviewed, u, want) + round := a.CheckForUpdates(context.Background(), a.updateCheckDue(time.Now())) + u := update(t, a, "org/decide") + if u == nil || u.Status != want.Status || u.Commit != want.Commit { + t.Errorf("reviewed %q: Update = %+v, want status %q commit %q", reviewed, u, want.Status, want.Commit) + } + if marked := want.Status != registry.UpdateCurrent; (round.Marked == 1) != marked { + t.Errorf("reviewed %q: the round marked %d models, want marked = %v", reviewed, round.Marked, marked) } } } diff --git a/internal/archtest/idle_threshold_docs_test.go b/internal/archtest/idle_threshold_docs_test.go new file mode 100644 index 00000000..ad1865d9 --- /dev/null +++ b/internal/archtest/idle_threshold_docs_test.go @@ -0,0 +1,55 @@ +package archtest_test + +import ( + "fmt" + "testing" + + "github.com/intentdriven/Dessau/internal/config" +) + +// The context probe's page states the idle threshold's range from the +// server's own bounds, so raising the cap without the page — or the page +// without the cap — is a failure rather than a figure an operator types and +// sees refused (iss-2610041948272032). +func TestTheContextProbePageStatesTheIdleThresholdsRange(t *testing.T) { + page := readDoc(t, "context-probe.md") + for _, want := range []string{ + "`idle_threshold_sec`", + fmt.Sprintf("%d minute", config.MinIdleThresholdSec/60), + fmt.Sprintf("%d hours", config.MaxIdleThresholdSec/3600), + } { + if !containsAll(page, want) { + t.Errorf("docs/context-probe.md does not say %q, so the idle threshold's range is not "+ + "the one the server enforces", want) + } + } +} + +// The self-test's pages name its own threshold, its default and its range +// from the server's constants, and no page still says the self-test and the +// context probe share one (iss-2610041956214381). +func TestTheSelfTestPagesStateItsOwnThreshold(t *testing.T) { + def := fmt.Sprintf("%d hours", config.DefaultSelfTestIdleThresholdSec/3600) + for page, wants := range map[string][]string{ + "self-test.md": { + "`self_test_idle_threshold_sec`", "Settings → Self-test", def, + fmt.Sprintf("%d hours", config.MaxIdleThresholdSec/3600), + }, + "self-test-reference.md": {"`self_test_idle_threshold_sec`", def}, + } { + body := readDoc(t, page) + for _, want := range wants { + if !containsAll(body, want) { + t.Errorf("docs/%s does not say %q", page, want) + } + } + } + for _, page := range []string{"self-test.md", "self-test-reference.md", "context-probe.md"} { + body := readDoc(t, page) + for _, stale := range []string{"shared with the context probe", "shares the idle threshold", "share it"} { + if containsAll(body, stale) { + t.Errorf("docs/%s still says %q, and the self-test has a threshold of its own", page, stale) + } + } + } +} diff --git a/internal/bridge/discord/answer.go b/internal/bridge/discord/answer.go index c60bdd90..6ff9cf57 100644 --- a/internal/bridge/discord/answer.go +++ b/internal/bridge/discord/answer.go @@ -197,13 +197,16 @@ func (s *session) answer(ctx context.Context, conv *conversation, msg incoming, ed := newEditor(s.rest, msg.ChannelID, msg.ID, s.bridge.now) started := time.Now() - var answer string + var answer, finish string askErr := s.bridge.opts.Ask(ctx, gateway.AskRequest{ Model: model, Body: body, Source: stats.SourceBridge, OnEvent: func(payload []byte) { - delta := deltaText(payload) + delta, reason := deltaText(payload) + if reason != "" { + finish = reason + } if delta == "" { return } @@ -239,8 +242,18 @@ func (s *session) answer(ctx context.Context, conv *conversation, msg incoming, s.bridge.log.Debug("could not finish a bridged answer", "bridge", bridgeName, "channel", numericID(msg.ChannelID), "err", err) } + // What the gateway said, not a guess at it (iss-2610041945020793): only a + // stream whose finish_reason is "length" is reported as cut, so an answer + // the model ended itself is never followed by a notice. The notice is not + // kept in the history; it is the bridge talking, not the model. + stoppedLong := askErr == nil && finish == finishLength if answer != "" { conv.append(turn{Role: roleAssistant, Content: answer}) + if stoppedLong && ed.wrote() { + s.say(ctx, msg.ChannelID, msg.ID, stoppedOnLength) + } + } else if stoppedLong { + s.say(ctx, msg.ChannelID, msg.ID, stoppedBeforeAnswering) } else if askErr == nil { s.say(ctx, msg.ChannelID, msg.ID, "The model answered with nothing.") } @@ -267,6 +280,18 @@ const genericProblem = "Something went wrong answering that." // into a channel whose answer is still being written. const stillAnswering = "I am still answering your last message here." +// stoppedOnLength is posted after an answer the gateway reported as stopped +// on length (iss-2610041945020793), so a reply cut mid-sentence is not taken +// for the whole of it. It is a message of its own rather than text added to +// the answer, so an answer that stopped inside a code block or an unclosed +// emphasis does not swallow it. +const stoppedOnLength = "The answer reached its length limit and stops there." + +// stoppedBeforeAnswering is said instead of "the model answered with nothing" +// when the length ran out before any of the answer was written — a reasoning +// model can spend the whole of it thinking. +const stoppedBeforeAnswering = "The model reached its length limit before it wrote an answer." + // publicRefusal is what may be repeated to whoever asked. func publicRefusal(err error) string { var askErr *gateway.AskError @@ -296,28 +321,36 @@ func (s *session) say(ctx context.Context, channelID, replyTo, text string) { } } -// deltaText reads the generated text out of one streamed event. +// finishLength is the finish_reason of an answer that stopped because it +// reached the max_tokens it was asked for. +const finishLength = "length" + +// deltaText reads the generated text out of one streamed event, and the +// reason the model stopped when the event carries one. // // This is the other half of what the bridge is admitted to read: the answer it // is posting. It reads the delta's text and the non-streamed field beside it // (some servers send the whole piece rather than a delta on the first event), -// and nothing else in the event. -func deltaText(payload []byte) string { +// and the choice's finish_reason — not content, but the gateway's word on why +// the answer ended — and nothing else in the event. +func deltaText(payload []byte) (text, finish string) { var ev struct { Choices []struct { Delta struct { Content string `json:"content"` } `json:"delta"` - Text string `json:"text"` + Text string `json:"text"` + FinishReason string `json:"finish_reason"` } `json:"choices"` } if json.Unmarshal(payload, &ev) != nil || len(ev.Choices) == 0 { - return "" + return "", "" } - if c := ev.Choices[0].Delta.Content; c != "" { - return c + c := ev.Choices[0] + if c.Delta.Content != "" { + return c.Delta.Content, c.FinishReason } - return ev.Choices[0].Text + return c.Text, c.FinishReason } // defaultModel is the model a channel starts on: the first the server offers diff --git a/internal/bridge/discord/answer_test.go b/internal/bridge/discord/answer_test.go index 9b073d51..07d0b09e 100644 --- a/internal/bridge/discord/answer_test.go +++ b/internal/bridge/discord/answer_test.go @@ -600,3 +600,122 @@ func TestASlashCommandIsAnsweredWhileTheChannelIsBusy(t *testing.T) { } close(hold) } + +// finishing is recording with the stream's last event carrying a +// finish_reason, as the gateway relays it: an empty delta and the reason the +// model stopped. +func finishing(t *testing.T, f *fakeDiscord, reason string, pieces ...string) (*Bridge, func() []request) { + t.Helper() + var mu sync.Mutex + var asked []request + opts := f.options(time.Now) + opts.Ask = func(ctx context.Context, req gateway.AskRequest) error { + var body request + if err := json.Unmarshal(req.Body, &body); err != nil { + return err + } + mu.Lock() + asked = append(asked, body) + mu.Unlock() + for _, p := range pieces { + payload, _ := json.Marshal(map[string]any{ + "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": p}, "finish_reason": nil}}, + }) + req.OnEvent(payload) + } + payload, _ := json.Marshal(map[string]any{ + "choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": reason}}, + }) + req.OnEvent(payload) + return nil + } + b := New(opts) + t.Cleanup(func() { _ = b.Close() }) + return b, func() []request { + mu.Lock() + defer mu.Unlock() + return append([]request(nil), asked...) + } +} + +// postedWithin collects every message the bot posted into the channel within +// a quiet moment. +func postedWithin(f *fakeDiscord) []string { + var texts []string + deadline := time.After(quiet) + for { + select { + case c := <-f.calls: + if c.Method == http.MethodPost && strings.HasSuffix(c.Path, "/channels/"+channelID+"/messages") { + text, _ := c.Body["content"].(string) + texts = append(texts, text) + } + case <-deadline: + return texts + } + } +} + +// An answer the gateway reports as stopped on length says so, in a message +// of its own after the answer, so Alice does not take a reply cut +// mid-sentence for the whole of it (iss-2610041945020793). The notice is the +// bridge's, not the model's: it is not kept in the history the next message +// sends. +func TestAnAnswerThatStopsOnLengthSaysSo(t *testing.T) { + f := newFakeDiscord(t) + b, asked := finishing(t, f, "length", "the answer was going to say **that") + connected(t, f, b) + + f.message("tell me everything", false, false) + first := answered(t, f, b) + if got, _ := first.Body["content"].(string); !strings.Contains(got, "the answer was going") { + t.Fatalf("the bot posted %q first, want the model's answer", got) + } + posted := postedWithin(f) + if len(posted) != 1 || posted[0] != stoppedOnLength { + t.Fatalf("after an answer that stopped on length the bot posted %q, want the one notice %q", + posted, stoppedOnLength) + } + + f.message("go on", false, false) + answered(t, f, b) + got := asked() + if len(got) != 2 { + t.Fatalf("the gateway was asked %d times, want twice", len(got)) + } + for _, m := range got[1].Messages { + if strings.Contains(m.Content, stoppedOnLength) { + t.Errorf("the notice was sent to the model as part of the history: %q", m.Content) + } + } +} + +// An answer whose length ran out before any of it was written — a reasoning +// model can spend the whole of it thinking — says that, rather than that the +// model answered with nothing. +func TestAnAnswerAllReasoningSaysItStoppedOnLength(t *testing.T) { + f := newFakeDiscord(t) + b, _ := finishing(t, f, "length") + connected(t, f, b) + + f.message("hello", false, false) + call := answered(t, f, b) + if got, _ := call.Body["content"].(string); got != stoppedBeforeAnswering { + t.Errorf("an answer that ran out of length before it began was reported as %q, want %q", + got, stoppedBeforeAnswering) + } +} + +// The notice comes from the finish_reason the gateway returns, not from a +// guess: an answer the model ended itself carries none, however it ends. +func TestAnAnswerThatStopsOnItsOwnCarriesNoNotice(t *testing.T) { + f := newFakeDiscord(t) + b, _ := finishing(t, f, "stop", "an answer that ends with **that") + connected(t, f, b) + + f.message("hello", false, false) + answered(t, f, b) + if posted := postedWithin(f); len(posted) != 0 { + t.Errorf("after an answer the model ended itself the bot also posted %q", posted) + } +} diff --git a/internal/bridge/discord/conversation.go b/internal/bridge/discord/conversation.go index e4dc309d..a08cdd55 100644 --- a/internal/bridge/discord/conversation.go +++ b/internal/bridge/discord/conversation.go @@ -310,10 +310,18 @@ type request struct { Stream bool `json:"stream"` } -// answerTokens is how much of a window is left for the answer. It is also the -// max_tokens the request asks for, so the figure the gateway judges the -// request by is the figure this bridge reserved. -const answerTokens = 1024 +// answerDivisor is what the window is divided by for the answer: half of it +// is kept for the answer, the other half being the history's. The answer's +// half is also the max_tokens the request asks for, so the figure the gateway +// judges the request by is the figure this bridge reserved. +// +// SIZED FROM THE WINDOW, NOT FIXED (iss-2610041945020793). A fixed 1,024 +// stopped every long answer at the same place whatever the model was served +// at, and a reasoning model could spend all of it thinking and write nothing. +// Half is the split this function already fell back to for a window too small +// for the fixed figure; it gives the answer room in proportion to the window +// and never squeezes the history below what the answer takes. +const answerDivisor = 2 // defaultWindow is the window assumed for a model this Mac cannot report one // for. Deliberately small: the cost of assuming too little is a shorter @@ -357,10 +365,7 @@ func buildRequest(model string, turns []turn, served int64) ([]byte, error) { if window <= 0 { window = defaultWindow } - answer := answerTokens - if int64(answer) > window/2 { - answer = int(window / 2) - } + answer := int(window / answerDivisor) budget := (window - int64(answer)) * bytesPerToken for start := 0; start < len(turns); start++ { diff --git a/internal/bridge/discord/conversation_test.go b/internal/bridge/discord/conversation_test.go index 797ec067..ddcddb18 100644 --- a/internal/bridge/discord/conversation_test.go +++ b/internal/bridge/discord/conversation_test.go @@ -55,6 +55,38 @@ func TestAConversationIsTrimmedToTheServedWindow(t *testing.T) { } } +// The answer is sized from the model's served window, as the history is, +// rather than held to a fixed figure (iss-2610041945020793): a reasoning +// model spent a fixed 1,024 tokens thinking and every answer stopped there, +// whatever the window. The history keeps its share all the same — the answer +// never takes more than half — and the two together are still a request the +// gateway admits. +func TestTheAnswerIsSizedFromTheServedWindow(t *testing.T) { + const fixedCap = 1024 + turns := []turn{{Role: roleUser, Content: "hello"}} + for _, served := range []int64{32_768, 65_536, 262_144} { + body, err := buildRequest("a-model", turns, served) + if err != nil { + t.Fatal(err) + } + var req request + if err := json.Unmarshal(body, &req); err != nil { + t.Fatal(err) + } + if req.MaxTokens <= fixedCap { + t.Errorf("a model served at %d tokens is asked for an answer of %d, no more than the "+ + "fixed %d the bridge used to ask for whatever the window", served, req.MaxTokens, fixedCap) + } + if int64(req.MaxTokens) > served/2 { + t.Errorf("a model served at %d tokens is asked for an answer of %d, more than half the "+ + "window, which would leave the history less than the answer", served, req.MaxTokens) + } + if judged := int64(len(body)/bytesPerToken) + int64(req.MaxTokens); judged > served { + t.Errorf("the request would be judged at %d tokens against a window of %d", judged, served) + } + } +} + // A single message too large for the window on its own is truncated rather // than refused: refusing would leave that person unable to say anything at all // in that channel. diff --git a/internal/config/config.go b/internal/config/config.go index e44a4204..ef25407e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -413,11 +413,19 @@ type Config struct { ContextProbe bool `json:"context_probe,omitempty"` // IdleThresholdSec is how long the last request must be in the past - // before the Mac counts as idle for the self-test and the context probe - // — one idea of idle for both. Zero means the default; read it through - // EffectiveIdleThresholdSec. + // before the Mac counts as idle for the context probe. Zero means the + // default; read it through EffectiveIdleThresholdSec. IdleThresholdSec int `json:"idle_threshold_sec,omitempty"` + // SelfTestIdleThresholdSec is the self-test's own idle threshold: how + // long the last request must be in the past before the self-test loads + // and measures a model. It is longer than the context probe's by + // default, because a benchmark five minutes after the last request + // lands in an ordinary pause in use (iss-2610041956214381). Zero means + // the default; read it through EffectiveSelfTestIdleThresholdSec. The + // bounds are the idle threshold's. + SelfTestIdleThresholdSec int `json:"self_test_idle_threshold_sec,omitempty"` + // APIUnloadOff turns off POST /v1/dessau/unload, the model API's request // for a program to unload a model it has finished with // (adr-2610031153127219). Absent means on: the route is open only to the @@ -1179,12 +1187,13 @@ func (c *Config) sanitizeLogLevel() []string { } // The idle threshold's bounds: a minute is the shortest quiet a loop that -// ticks once a minute can tell from noise, and an hour is past the point where -// an idle job would never run on a Mac that is used at all. +// ticks once a minute can tell from noise, and a day is the longest quiet an +// operator may ask for, so an idle job can be kept to the night on a Mac that +// is used all day (iss-2610041948272032). const ( DefaultIdleThresholdSec = 300 MinIdleThresholdSec = 60 - MaxIdleThresholdSec = 3600 + MaxIdleThresholdSec = 86400 ) // EffectiveIdleThresholdSec is the idle threshold in force: the setting, or @@ -1201,18 +1210,44 @@ func (c Config) EffectiveIdleThreshold() time.Duration { return time.Duration(c.EffectiveIdleThresholdSec()) * time.Second } +// DefaultSelfTestIdleThresholdSec is the self-test's own idle threshold +// when none is set: four hours, so a benchmark waits for a long quiet spell +// rather than an ordinary pause (iss-2610041956214381). Its bounds are +// MinIdleThresholdSec and MaxIdleThresholdSec. +const DefaultSelfTestIdleThresholdSec = 14400 + +// EffectiveSelfTestIdleThresholdSec is the self-test's idle threshold in +// force: the setting, or the default when none is set. +func (c Config) EffectiveSelfTestIdleThresholdSec() int { + if c.SelfTestIdleThresholdSec == 0 { + return DefaultSelfTestIdleThresholdSec + } + return c.SelfTestIdleThresholdSec +} + +// EffectiveSelfTestIdleThreshold is EffectiveSelfTestIdleThresholdSec as a +// duration. +func (c Config) EffectiveSelfTestIdleThreshold() time.Duration { + return time.Duration(c.EffectiveSelfTestIdleThresholdSec()) * time.Second +} + func usableIdleThreshold(sec int) bool { return sec == 0 || (sec >= MinIdleThresholdSec && sec <= MaxIdleThresholdSec) } -// sanitizeIdleThreshold repairs a threshold this build cannot use and returns -// what it repaired, for the reason sanitizeStats gives. +// sanitizeIdleThreshold repairs a threshold this build cannot use — the +// context probe's or the self-test's — and returns what it repaired, for the +// reason sanitizeStats gives. func (c *Config) sanitizeIdleThreshold() []string { - if usableIdleThreshold(c.IdleThresholdSec) { - return nil + var repaired []string + if !usableIdleThreshold(c.IdleThresholdSec) { + repaired = append(repaired, "idle_threshold_sec="+strconv.Itoa(c.IdleThresholdSec)) + c.IdleThresholdSec = 0 + } + if !usableIdleThreshold(c.SelfTestIdleThresholdSec) { + repaired = append(repaired, "self_test_idle_threshold_sec="+strconv.Itoa(c.SelfTestIdleThresholdSec)) + c.SelfTestIdleThresholdSec = 0 } - repaired := []string{"idle_threshold_sec=" + strconv.Itoa(c.IdleThresholdSec)} - c.IdleThresholdSec = 0 return repaired } @@ -1307,6 +1342,10 @@ func (c Config) Validate() error { return fmt.Errorf("idle_threshold_sec must be between %d and %d, or 0 for the default, got %d", MinIdleThresholdSec, MaxIdleThresholdSec, c.IdleThresholdSec) } + if !usableIdleThreshold(c.SelfTestIdleThresholdSec) { + return fmt.Errorf("self_test_idle_threshold_sec must be between %d and %d, or 0 for the default, got %d", + MinIdleThresholdSec, MaxIdleThresholdSec, c.SelfTestIdleThresholdSec) + } if !usableUpdateCheckInterval(c.UpdateCheckIntervalHours) { return fmt.Errorf("update_check_interval_hours must be between %d and %d, or 0 for daily, got %d", MinUpdateCheckIntervalHours, MaxUpdateCheckIntervalHours, c.UpdateCheckIntervalHours) diff --git a/internal/config/contextprobe_test.go b/internal/config/contextprobe_test.go index 0bf9f611..f0d2188b 100644 --- a/internal/config/contextprobe_test.go +++ b/internal/config/contextprobe_test.go @@ -72,3 +72,34 @@ func TestAnUnusableIdleThresholdIsRepairedOnLoad(t *testing.T) { t.Errorf("the repair was not reported: %v", notices.Repaired) } } + +// The idle threshold reaches a whole day (iss-2610041948272032): an operator +// who wants the context probe to run only after a long quiet spell can say +// so, up to 24 hours, and not a second past it. A file carrying the day loads +// as it is, with nothing repaired. +func TestTheIdleThresholdReachesADay(t *testing.T) { + if MaxIdleThresholdSec != 86400 { + t.Fatalf("MaxIdleThresholdSec = %d, want 86400 (24 hours)", MaxIdleThresholdSec) + } + c := Default() + c.IdleThresholdSec = 86400 + if err := c.Validate(); err != nil { + t.Errorf("idle_threshold_sec=86400 was refused: %v", err) + } + c.IdleThresholdSec = 86401 + if err := c.Validate(); err == nil { + t.Error("idle_threshold_sec=86401 was accepted") + } + + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(`{"host":"127.0.0.1","port":8080,"idle_threshold_sec":86400}`), 0o600); err != nil { + t.Fatal(err) + } + loaded, notices, err := Load(path) + if err != nil { + t.Fatal(err) + } + if loaded.IdleThresholdSec != 86400 || len(notices.Repaired) != 0 { + t.Errorf("a day loaded as %d with repairs %v, want it kept as it is", loaded.IdleThresholdSec, notices.Repaired) + } +} diff --git a/internal/config/selftestidle_test.go b/internal/config/selftestidle_test.go new file mode 100644 index 00000000..3393f884 --- /dev/null +++ b/internal/config/selftestidle_test.go @@ -0,0 +1,102 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// The self-test has an idle threshold of its own (iss-2610041956214381): +// four hours unless set, held to the same bounds as the context probe's, and +// carried in config.json under its own key. Setting one threshold moves +// nothing about the other. +func TestTheSelfTestHasAnIdleThresholdOfItsOwn(t *testing.T) { + if DefaultSelfTestIdleThresholdSec != 14400 { + t.Fatalf("DefaultSelfTestIdleThresholdSec = %d, want 14400 (4 hours)", DefaultSelfTestIdleThresholdSec) + } + d := Default() + if d.SelfTestIdleThresholdSec != 0 || d.EffectiveSelfTestIdleThresholdSec() != DefaultSelfTestIdleThresholdSec { + t.Fatalf("a fresh install's self-test threshold: stored %d, effective %d, want 0 and %d", + d.SelfTestIdleThresholdSec, d.EffectiveSelfTestIdleThresholdSec(), DefaultSelfTestIdleThresholdSec) + } + if got := d.EffectiveSelfTestIdleThreshold().Hours(); got != 4 { + t.Errorf("a fresh install's self-test threshold is %v hours, want 4", got) + } + + // Independent of the context probe's, both ways. + c := Default() + c.IdleThresholdSec = 120 + if c.EffectiveSelfTestIdleThresholdSec() != DefaultSelfTestIdleThresholdSec { + t.Errorf("setting idle_threshold_sec moved the self-test's threshold to %d", c.EffectiveSelfTestIdleThresholdSec()) + } + c = Default() + c.SelfTestIdleThresholdSec = 7200 + if c.EffectiveIdleThresholdSec() != DefaultIdleThresholdSec { + t.Errorf("setting self_test_idle_threshold_sec moved the context probe's threshold to %d", c.EffectiveIdleThresholdSec()) + } + + path := filepath.Join(t.TempDir(), "config.json") + if err := Save(path, c); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(path) + if !strings.Contains(string(raw), `"self_test_idle_threshold_sec": 7200`) { + t.Errorf("the file does not carry the self-test's threshold under its key:\n%s", raw) + } + again, notices, err := Load(path) + if err != nil { + t.Fatal(err) + } + if again.SelfTestIdleThresholdSec != 7200 || len(notices.Repaired) != 0 { + t.Errorf("read back %d with repairs %v", again.SelfTestIdleThresholdSec, notices.Repaired) + } + + // The same bounds as the context probe's, and zero for the default. + for _, sec := range []int{0, MinIdleThresholdSec, 14400, MaxIdleThresholdSec} { + c := Default() + c.SelfTestIdleThresholdSec = sec + if err := c.Validate(); err != nil { + t.Errorf("self_test_idle_threshold_sec=%d was refused: %v", sec, err) + } + } + for _, sec := range []int{-1, MinIdleThresholdSec - 1, MaxIdleThresholdSec + 1} { + c := Default() + c.SelfTestIdleThresholdSec = sec + err := c.Validate() + if err == nil { + t.Errorf("self_test_idle_threshold_sec=%d was accepted", sec) + continue + } + if !strings.Contains(err.Error(), "self_test_idle_threshold_sec") { + t.Errorf("self_test_idle_threshold_sec=%d was refused in words that do not name it: %v", sec, err) + } + } +} + +// A file carrying a self-test threshold this build cannot use loads with the +// default and says so, rather than refusing to start or leaving a value a +// later save would be refused over. +func TestAnUnusableSelfTestIdleThresholdIsRepairedOnLoad(t *testing.T) { + for _, stored := range []string{"7", "86401"} { + path := filepath.Join(t.TempDir(), "config.json") + body := `{"host":"127.0.0.1","port":8080,"self_test_idle_threshold_sec":` + stored + `}` + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + c, notices, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.SelfTestIdleThresholdSec != 0 || c.EffectiveSelfTestIdleThresholdSec() != DefaultSelfTestIdleThresholdSec { + t.Errorf("loaded %s as %d (effective %d), want the default", stored, + c.SelfTestIdleThresholdSec, c.EffectiveSelfTestIdleThresholdSec()) + } + if !strings.Contains(strings.Join(notices.Repaired, ","), "self_test_idle_threshold_sec="+stored) { + t.Errorf("the repair of %s was not reported: %v", stored, notices.Repaired) + } + if err := c.Validate(); err != nil { + t.Errorf("the repaired configuration is refused: %v", err) + } + } +} diff --git a/internal/gateway/ask.go b/internal/gateway/ask.go index 7b6ca2eb..849bcda1 100644 --- a/internal/gateway/ask.go +++ b/internal/gateway/ask.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "time" + "unicode/utf8" "github.com/intentdriven/Dessau/internal/runtime" "github.com/intentdriven/Dessau/internal/stats" @@ -58,6 +59,13 @@ func (g *Gateway) Ask(ctx context.Context, req AskRequest) error { obs.failed(stats.ClassClientError) return &AskError{detail: "the request is larger than this server will read", public: genericRefusal} } + // The same encoding check the network route makes. The bridge marshals + // Go strings and so never builds an invalid body, but Ask holds itself + // to everything a network request is held to. + if !utf8.Valid(req.Body) { + obs.failed(stats.ClassGatewayError) + return &AskError{detail: invalidUTF8Refusal, public: genericRefusal} + } var payload map[string]json.RawMessage if err := json.Unmarshal(req.Body, &payload); err != nil { obs.failed(stats.ClassGatewayError) diff --git a/internal/gateway/control.go b/internal/gateway/control.go index b5e1dca2..eaf249eb 100644 --- a/internal/gateway/control.go +++ b/internal/gateway/control.go @@ -511,6 +511,11 @@ type Defaults struct { // (iss-2609190146152463). IdleThresholdSec int `json:"idle_threshold_sec"` + // SelfTestIdleThresholdSec is the self-test's own idle threshold for a + // panel whose field is blank, stated on the field, beside it and in the + // self-test's status prose (iss-2610041956214381). + SelfTestIdleThresholdSec int `json:"self_test_idle_threshold_sec"` + // UpdateCheckIntervalHours is how often the update check runs for a // panel whose interval field is blank: daily. UpdateCheckIntervalHours int `json:"update_check_interval_hours"` @@ -556,6 +561,8 @@ func (c *Control) snapshot() State { EvictionMaxWaitSec: config.DefaultEvictionMaxWaitSec, IdleThresholdSec: config.DefaultIdleThresholdSec, + SelfTestIdleThresholdSec: config.DefaultSelfTestIdleThresholdSec, + UpdateCheckIntervalHours: config.DefaultUpdateCheckIntervalHours, }, Pinned: c.App.Pool.Pinned(), diff --git a/internal/gateway/control_probe_test.go b/internal/gateway/control_probe_test.go index fd682777..5daa3f78 100644 --- a/internal/gateway/control_probe_test.go +++ b/internal/gateway/control_probe_test.go @@ -137,3 +137,34 @@ func TestStateCarriesTheFigureAnUnsetIdleThresholdResolvesTo(t *testing.T) { got, config.DefaultIdleThresholdSec) } } + +// The self-test's own threshold is served the same way, for the same reason: +// its field is blank for the default, and the panel names the figure that +// stands for from the server rather than from a copy (iss-2610041956214381). +func TestStateCarriesTheFigureAnUnsetSelfTestThresholdResolvesTo(t *testing.T) { + _, srv := newBudgetControl(t, config.Default(), 128*gb, nil) + + if got := stateOf(t, srv).Defaults.SelfTestIdleThresholdSec; got != config.DefaultSelfTestIdleThresholdSec { + t.Errorf("defaults.self_test_idle_threshold_sec = %d, want the server's own default %d", + got, config.DefaultSelfTestIdleThresholdSec) + } +} + +// A save that does not name the self-test's threshold leaves it alone. +func TestASaveThatDoesNotNameTheSelfTestThresholdLeavesItAlone(t *testing.T) { + c := config.Default() + c.SelfTestIdleThresholdSec = 7200 + srv, a := newTestControlApp(t, c) + resp, err := http.Post(srv.URL+"/api/settings", "application/json", bytes.NewReader([]byte(`{"idle_threshold_sec":600}`))) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("save = %d", resp.StatusCode) + } + if got := a.Config(); got.SelfTestIdleThresholdSec != 7200 || got.IdleThresholdSec != 600 { + t.Errorf("after a save of the probe's threshold: self-test %d, probe %d; want 7200 and 600", + got.SelfTestIdleThresholdSec, got.IdleThresholdSec) + } +} diff --git a/internal/gateway/control_untouched_test.go b/internal/gateway/control_untouched_test.go index a98528b7..8c3ef933 100644 --- a/internal/gateway/control_untouched_test.go +++ b/internal/gateway/control_untouched_test.go @@ -218,6 +218,28 @@ func TestASaveOfAnUneditedFormIsAccepted(t *testing.T) { name: "a memory budget of the operator's own", stored: func(c config.Config) config.Config { c.MaxResidentBytes = 12 << 30; return c }, }, + { + // The top of the idle threshold's range, a day + // (iss-2610041948272032). + name: "an idle threshold of a day", + stored: func(c config.Config) config.Config { c.IdleThresholdSec = 86400; return c }, + }, + { + // The self-test's own threshold at both ends of its range, beside + // a probe threshold of the operator's own (iss-2610041956214381). + name: "a self-test threshold of a day", + stored: func(c config.Config) config.Config { + c.SelfTestIdleThresholdSec, c.IdleThresholdSec = 86400, 600 + return c + }, + }, + { + name: "a self-test threshold of a minute", + stored: func(c config.Config) config.Config { + c.SelfTestIdleThresholdSec = config.MinIdleThresholdSec + return c + }, + }, { // A figure the panel refused to post until its own ceiling was // removed, and the server always accepted. @@ -234,6 +256,13 @@ func TestASaveOfAnUneditedFormIsAccepted(t *testing.T) { return c }, }, + { + // The model API's unload route turned off: a switch with no + // validation rule today, which a later rule must not turn into + // a refusal of every other save (iss-2610042100409263). + name: "the model API's unload route turned off", + stored: func(c config.Config) config.Config { c.APIUnloadOff = true; return c }, + }, { name: "per-model settings on a model this Mac has not downloaded", stored: func(c config.Config) config.Config { @@ -277,6 +306,40 @@ func TestASaveOfAnUneditedFormIsAccepted(t *testing.T) { } } +// Changing another setting is accepted while the model API's unload route is +// turned off, and the save keeps it off: the switch is never a reason to +// refuse a save that did not touch it (iss-2610042100409263). +func TestASaveOfAnotherSettingKeepsTheUnloadRouteOff(t *testing.T) { + stored := config.Default() + stored.APIUnloadOff = true + if err := stored.Validate(); err != nil { + t.Fatalf("the premise: a configuration the load path accepts: %v", err) + } + srv, a := newTestControlApp(t, stored) + + var body map[string]any + if err := json.Unmarshal([]byte(uneditedFormBody(t, stored)), &body); err != nil { + t.Fatal(err) + } + body["idle_timeout_sec"] = stored.IdleTimeoutSec + 60 + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + resp := postJSON(t, srv, "/api/settings", string(b)) + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("a save of another setting was refused with %d: %s", resp.StatusCode, refusalText(t, resp)) + } + got := a.Config() + if !got.APIUnloadOff { + t.Error("the save turned the model API's unload route back on") + } + if got.IdleTimeoutSec != stored.IdleTimeoutSec+60 { + t.Errorf("idle_timeout_sec = %d, want the posted %d", got.IdleTimeoutSec, stored.IdleTimeoutSec+60) + } +} + // A setting the form does not own survives any save it makes. // // The two exempted settings have no control by decision, so the ONLY thing @@ -347,8 +410,12 @@ func uneditedFormBody(t *testing.T, stored config.Config) string { "eviction_grace_sec": shown.EvictionGraceSec, "eviction_max_wait_sec": shown.EvictionMaxWaitSec, "chat_rule": shown.ChatRule, - "statistics": shown.Statistics, - "stats_months": shown.StatsMonths, + // A blank field posts zero, which is what an unset threshold is. + "idle_threshold_sec": shown.IdleThresholdSec, + "self_test_idle_threshold_sec": shown.SelfTestIdleThresholdSec, + "statistics": shown.Statistics, + "stats_months": shown.StatsMonths, + "api_unload_off": shown.APIUnloadOff, // Typed in megabytes and stored in bytes, so a figure that is not a // whole number of megabytes comes back rounded — which is itself a // value the save has to accept. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 250a9510..909d095a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -20,6 +20,7 @@ import ( "strings" "sync/atomic" "time" + "unicode/utf8" "github.com/intentdriven/Dessau/internal/capability" "github.com/intentdriven/Dessau/internal/config" @@ -686,6 +687,10 @@ const maxStreamLine = maxResponseBody // headers took, never more. const BodyReadTimeout = 30 * time.Second +// invalidUTF8Refusal is the refusal of a body that is not valid UTF-8. It +// names the encoding and nothing of what the body carried. +const invalidUTF8Refusal = "request body is not valid UTF-8" + // handleChatCompletions is handleCompletions for the chat route, which holds // a conversation: the route itself says so, rather than a comparison of the // path a later alias route could slip past (iss-2610031010371709). @@ -733,6 +738,20 @@ func (g *Gateway) completions(w http.ResponseWriter, r *http.Request, chat bool) // Body is in hand; the multi-minute generation phase must not be bounded. _ = rc.SetReadDeadline(time.Time{}) + // JSON exchanged between systems is UTF-8 (RFC 8259, section 8.1), and + // Go's decoder does not hold a RawMessage to it: invalid bytes inside a + // string are kept as they came and json.Marshal forwards them, so the + // model server fails to decode the body on its handler thread and the + // client sees a 502 (iss-2610042036094209). This is a check of the + // body's encoding as a whole, like the syntax check below it: it names + // no field, reads no prompt for what it says, and keeps nothing, and the + // refusal carries none of the body. + if !utf8.Valid(raw) { + obs.failed(stats.ClassClientError) + writeError(w, http.StatusBadRequest, invalidUTF8Refusal) + return + } + // Decode into raw messages, not a fully-materialized map: the gateway only // rewrites the "model" field, so parsing the entire prompt (the messages array // can be hundreds of KB) into Go values and re-serializing it is wasted CPU and diff --git a/internal/gateway/invalidutf8_test.go b/internal/gateway/invalidutf8_test.go new file mode 100644 index 00000000..4822ffdd --- /dev/null +++ b/internal/gateway/invalidutf8_test.go @@ -0,0 +1,104 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/intentdriven/Dessau/internal/config" +) + +// The refusal a body that is not valid UTF-8 gets, word for word: it names +// the encoding and nothing of what the body carried. +const wantInvalidUTF8Refusal = "request body is not valid UTF-8" + +// A body whose bytes are not valid UTF-8 is refused before anything is +// resolved or loaded (iss-2610042036094209). Go's decoder keeps such bytes as +// they came inside a RawMessage, and json.Marshal forwards them, so before +// this check they reached the model server, whose request handler fails to +// decode them on its handler thread and drops the connection: the client saw +// a 502 rather than a refusal it could act on. Valid multi-byte UTF-8 — +// accented Latin, CJK, emoji — is relayed as it always was. +func TestABodyThatIsNotValidUTF8IsRefused(t *testing.T) { + const model = `"model":"mlx-community/Qwen3-8B-4bit"` + const text = "/v1/completions" + chat := func(content string) string { + return `{` + model + `,"messages":[{"role":"user","content":"` + content + `"}]}` + } + completion := func(prompt string) string { + return `{` + model + `,"prompt":"` + prompt + `"}` + } + for _, c := range []struct { + name, path, body string + refused bool + }{ + {"a lone 0xff in a chat message", chatCompletionsPath, chat("hi \xff there"), true}, + {"a truncated sequence in a chat message", chatCompletionsPath, chat("\xe4\xb8"), true}, + {"an overlong encoding in a chat message", chatCompletionsPath, chat("\xc0\xaf"), true}, + {"an encoded surrogate in a chat message", chatCompletionsPath, chat("\xed\xa0\x80"), true}, + {"a lone 0xff in a completions prompt", text, completion("The capital of France is \xff"), true}, + {"a lone 0xff in a key", text, `{` + model + `,"prompt":"hi","x` + "\xff" + `":1}`, true}, + {"accented Latin in a chat message", chatCompletionsPath, chat("Bonjour, ça va ?"), false}, + {"CJK in a chat message", chatCompletionsPath, chat("你好,世界"), false}, + {"emoji in a chat message", chatCompletionsPath, chat("hello 👋🏽 world"), false}, + {"CJK and emoji in a completions prompt", text, completion("東京は 🗼"), false}, + } { + t.Run(c.name, func(t *testing.T) { + srv, pool, fake := newTestGateway(t, config.Default()) + req, _ := http.NewRequest(http.MethodPost, srv.URL+c.path, strings.NewReader(c.body)) + req.Header.Set("Content-Type", "application/json") + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + got, _ := io.ReadAll(resp.Body) + resp.Body.Close() + pool.mu.Lock() + acquired := len(pool.acquired) + pool.mu.Unlock() + if !c.refused { + if resp.StatusCode != http.StatusOK { + t.Errorf("status %d, %s; want valid UTF-8 relayed", resp.StatusCode, got) + } + if fake.LastBody() == nil { + t.Error("a valid UTF-8 body did not reach the model server") + } + return + } + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("status %d, %s; want a 400", resp.StatusCode, got) + } + if acquired != 0 || fake.LastBody() != nil { + t.Error("a body that is not valid UTF-8 reached the pool or the model server") + } + var e struct { + Error struct { + Message string `json:"message"` + Type string `json:"type"` + Code int `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal(got, &e); err != nil { + t.Fatalf("the refusal is not the usual error shape: %v: %s", err, got) + } + if e.Error.Message != wantInvalidUTF8Refusal || e.Error.Type != "invalid_request_error" || e.Error.Code != http.StatusBadRequest { + t.Errorf("refusal %+v; want %q, invalid_request_error, 400", e.Error, wantInvalidUTF8Refusal) + } + }) + } +} + +// The reference page states the refusal word for word. +func TestTheRequestFieldsReferenceStatesTheUTF8Refusal(t *testing.T) { + page, err := os.ReadFile(filepath.Join("..", "..", "docs", "request-fields.md")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(page), "`"+wantInvalidUTF8Refusal+"`") { + t.Errorf("docs/request-fields.md does not state the refusal %q", wantInvalidUTF8Refusal) + } +} diff --git a/internal/gateway/systemmerge.go b/internal/gateway/systemmerge.go index 3e5a1eda..9c7e1a07 100644 --- a/internal/gateway/systemmerge.go +++ b/internal/gateway/systemmerge.go @@ -221,7 +221,10 @@ func instructionText(fields map[string]json.RawMessage) (string, bool) { if !ok { return "", false } - if !utf8.Valid(raw) { + // Invalid bytes, or an escape that decodes to no character (a lone + // surrogate), would come back from the decode as U+FFFD: content the + // client never sent. + if !utf8.Valid(raw) || loneSurrogateEscape(raw) { return "", false } // A pointer tells JSON null apart from an empty string: null is the diff --git a/internal/gateway/systemmerge_test.go b/internal/gateway/systemmerge_test.go index fe7cd0d2..5d9826f4 100644 --- a/internal/gateway/systemmerge_test.go +++ b/internal/gateway/systemmerge_test.go @@ -2,7 +2,6 @@ package gateway import ( "bufio" - "bytes" "context" "encoding/json" "fmt" @@ -782,9 +781,12 @@ func TestPlainCompletionsAreNeverMerged(t *testing.T) { // Go repairs an invalid UTF-8 byte sequence into U+FFFD when it decodes a JSON // string, and re-encodes it as valid UTF-8. Merging such a message would hand -// the model characters the client never sent, while relaying it passes the -// same bytes through untouched — so it is relayed. Only raw bytes can show -// this: every JSON decoder between here and the assertion would repair them. +// the model characters the client never sent. On the network path the body is +// now refused before merging is reached, because the model server cannot +// decode such bytes either (iss-2610042036094209); so neither a merged nor a +// relayed copy reaches it. The merge's own refusal of such content is held by +// TestMergeSystemMessagesRefusesShapesItCannotRebuild, for the bridge's path, +// which merges a body it did not read from the network. func TestMergingRefusesInvalidUTF8InSystemContent(t *testing.T) { srv, upstream := newRecordingGateway(t, mergingOn, false) @@ -800,16 +802,11 @@ func TestMergingRefusesInvalidUTF8InSystemContent(t *testing.T) { t.Fatal(err) } defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("status = %d, want 200", resp.StatusCode) - } - - raw := upstream.rawBody() - if !bytes.Contains(raw, []byte{0xff, 0xfe}) { - t.Errorf("the model server received %q; the invalid bytes were repaired rather than relayed through", raw) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", resp.StatusCode) } - if bytes.Contains(raw, []byte(`a\ufffd`)) || bytes.Contains(raw, []byte(`\n\nAnswer briefly.`)) { - t.Errorf("the request was merged despite content merging cannot re-encode: %q", raw) + if raw := upstream.rawBody(); raw != nil { + t.Errorf("the model server received %q; a body that is not valid UTF-8 must not reach it, merged or not", raw) } } @@ -829,6 +826,10 @@ func TestMergeSystemMessagesRefusesShapesItCannotRebuild(t *testing.T) { {"a system message after the first carrying another field", `[{"role":"user","content":"hi"},{"role":"system","content":"a"},{"role":"system","content":"b","name":"house-rules"}]`}, {"a system message after the first with a case-variant of content", `[{"role":"system","content":"a"},{"role":"user","content":"hi"},{"role":"system","content":"b","Content":"c"}]`}, {"the first system message's content is not a string", `[{"role":"system","content":[{"type":"text","text":"a"}],"name":"x"},{"role":"system","content":"b"}]`}, + {"system content that is not valid UTF-8", `[{"role":"system","content":"a` + "\xff\xfe" + `b"},{"role":"user","content":"hi"},{"role":"system","content":"Answer briefly."}]`}, + // Valid UTF-8 bytes, but the escape decodes to no character: merging + // would rewrite it to U+FFFD, a character the client never sent. + {"system content carrying a lone surrogate escape", `[{"role":"system","content":"a\ud800"},{"role":"user","content":"hi"},{"role":"system","content":"b"}]`}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/internal/hub/check_test.go b/internal/hub/check_test.go index fbb200bf..e1195ee4 100644 --- a/internal/hub/check_test.go +++ b/internal/hub/check_test.go @@ -11,6 +11,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" ) @@ -329,3 +330,114 @@ func TestAnUpstreamNeverFormatsItsToken(t *testing.T) { } } } + +// Once a content fetch's redirect chain has left the Hub's origin, the token +// stays off every later hop, including one that returns to the Hub: a host +// off the origin chooses the next hop, and must not be able to pick an +// authenticated Hub request (iss-2610071200187548). +func TestAContentFetchSendsNoTokenBackToTheHubAfterLeavingIt(t *testing.T) { + const body = `{"model_type":"qwen3"}` + var mu sync.Mutex + var cdnAuth, returnAuth []string + var hubURL string + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + cdnAuth = append(cdnAuth, r.Header.Get("Authorization")) + mu.Unlock() + http.Redirect(w, r, hubURL+"/returned", http.StatusFound) + })) + t.Cleanup(cdn.Close) + hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/org/repo/resolve/" + testCommit + "/config.json": + http.Redirect(w, r, cdn.URL+"/blob", http.StatusFound) + case "/returned": + mu.Lock() + returnAuth = append(returnAuth, r.Header.Get("Authorization")) + mu.Unlock() + fmt.Fprint(w, body) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(hub.Close) + hubURL = hub.URL + c := &Client{BaseURL: hub.URL, HTTP: hub.Client()} + up := Upstream{RepoID: "org/repo", Commit: testCommit, Authed: true, token: "hf_secret"} + if _, err := c.SmallFileAt(context.Background(), up, lfsFile("config.json", body, int64(len(body))), 1<<20); err != nil { + t.Fatalf("SmallFileAt: %v", err) + } + mu.Lock() + defer mu.Unlock() + if len(cdnAuth) != 1 || len(returnAuth) != 1 { + t.Fatalf("hops made: CDN %d, back to the Hub %d; want 1 each", len(cdnAuth), len(returnAuth)) + } + if cdnAuth[0] != "" { + t.Errorf("the content CDN was sent Authorization %q", cdnAuth[0]) + } + if returnAuth[0] != "" { + t.Errorf("the hop back to the Hub after leaving it was sent Authorization %q", returnAuth[0]) + } +} + +// A content fetch from an https Hub refuses a hop to plain http rather than +// carry a gated repository's file unencrypted (iss-2610071200187548). +func TestAContentFetchRefusesARedirectFromHTTPSToHTTP(t *testing.T) { + const body = `{"model_type":"qwen3"}` + var plainHits atomic.Int32 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + plainHits.Add(1) + fmt.Fprint(w, body) + })) + t.Cleanup(plain.Close) + hub := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+"/blob", http.StatusFound) + })) + t.Cleanup(hub.Close) + c := &Client{BaseURL: hub.URL, HTTP: hub.Client()} + up := Upstream{RepoID: "org/repo", Commit: testCommit} + if _, err := c.SmallFileAt(context.Background(), up, lfsFile("config.json", body, int64(len(body))), 1<<20); err == nil { + t.Error("SmallFileAt followed a redirect from https to http") + } + if n := plainHits.Load(); n != 0 { + t.Errorf("the plain-http host was asked %d times", n) + } +} + +// A refusal from the content CDN names the CDN and gives no advice about the +// access token, which the CDN was never sent; one from the Hub's own origin +// keeps it (iss-2610071200183905). +func TestACDNRefusalIsNotWordedAsTheHubRefusingTheToken(t *testing.T) { + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "denied", http.StatusForbidden) + })) + t.Cleanup(cdn.Close) + hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/org/repo/resolve/"+testCommit+"/config.json" { + http.Redirect(w, r, cdn.URL+"/blob", http.StatusFound) + return + } + http.Error(w, "denied", http.StatusForbidden) + })) + t.Cleanup(hub.Close) + c := &Client{BaseURL: hub.URL, HTTP: hub.Client()} + up := Upstream{RepoID: "org/repo", Commit: testCommit, Authed: true, token: "hf_secret"} + + _, err := c.SmallFileAt(context.Background(), up, lfsFile("config.json", "{}", 2), 1<<20) + if err == nil { + t.Fatal("a 403 from the content CDN was read as a file") + } + msg := err.Error() + if strings.Contains(msg, "token") { + t.Errorf("a CDN refusal gives token advice: %s", msg) + } + cdnHost := strings.TrimPrefix(cdn.URL, "http://") + if !strings.Contains(msg, "content CDN") || !strings.Contains(msg, cdnHost) { + t.Errorf("a CDN refusal does not name the CDN at %s: %s", cdnHost, msg) + } + + _, err = c.SmallFileAt(context.Background(), up, File{Path: "other.json"}, 1<<20) + if err == nil || !strings.Contains(err.Error(), "access token") { + t.Errorf("a refusal from the Hub's origin lost its token advice: %v", err) + } +} diff --git a/internal/hub/download.go b/internal/hub/download.go index b7fedc4d..3344ad06 100644 --- a/internal/hub/download.go +++ b/internal/hub/download.go @@ -435,8 +435,10 @@ func (c *Client) downloadFile(ctx context.Context, req DownloadRequest, token st // the listing gives no usable hash for is checked on length alone, so for // those this hole is wider than the reason it exists — iss-2609190151179403. // TestDownloadFollowsTheHubsRedirectToItsContentCDN holds the hole open for - // the case that needs it. - resp, err := c.httpClient().Do(httpReq) + // the case that needs it. doContent is the content fetch's redirect policy, + // shared with the update check: the token goes nowhere but the Hub's origin + // and an https Hub is never left for plain http. + resp, err := c.doContent(httpReq) if err != nil { return false, fmt.Errorf("download %s: %w", f.Path, err) } @@ -469,7 +471,7 @@ func (c *Client) downloadFile(ctx context.Context, req DownloadRequest, token st // that sent a Range can mean that: a 416 to a plain GET is a server // error, and retrying it would recurse forever. if resumeAt == 0 { - return false, apiError(resp, u) + return false, c.contentError(resp, u) } if err := root.Remove(part); err != nil && !os.IsNotExist(err) { return false, err @@ -477,7 +479,7 @@ func (c *Client) downloadFile(ctx context.Context, req DownloadRequest, token st tr.addCompleted(-resumeAt) return c.downloadFile(ctx, req, token, root, f, tr) default: - return false, apiError(resp, u) + return false, c.contentError(resp, u) } // O_NOFOLLOW: refuse to write through a symlink planted at the .part path, diff --git a/internal/hub/download_test.go b/internal/hub/download_test.go index 85f84604..b749af8b 100644 --- a/internal/hub/download_test.go +++ b/internal/hub/download_test.go @@ -673,6 +673,136 @@ func TestDownloadFollowsTheHubsRedirectToItsContentCDN(t *testing.T) { } } +// cdnRedirectingHub serves repo the way the Hub does, handing its one LFS +// file, model.safetensors, to wherever cdnURL names when it is asked for it; +// newServer starts the Hub (plain or TLS). +func cdnRedirectingHub(t *testing.T, repo map[string][]byte, newServer func(http.Handler) *httptest.Server, cdnURL func(name string) string) *httptest.Server { + t.Helper() + const lfsFile = "model.safetensors" + mux := http.NewServeMux() + mux.HandleFunc("/api/models/org/repo/tree/main", func(w http.ResponseWriter, r *http.Request) { + var entries []File + for p, b := range repo { + e := File{Path: p, Size: int64(len(b)), OID: gitBlobID(b)} + if p == lfsFile { + e.LFS = &struct { + OID string `json:"oid"` + Size int64 `json:"size"` + }{OID: sha256Hex(b), Size: int64(len(b))} + } + entries = append(entries, e) + } + json.NewEncoder(w).Encode(entries) + }) + mux.HandleFunc("/org/repo/resolve/main/", func(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/org/repo/resolve/main/") + body, ok := repo[name] + if !ok { + http.Error(w, "no such file", http.StatusNotFound) + return + } + if name == lfsFile { + http.Redirect(w, r, cdnURL(name), http.StatusFound) + return + } + w.Write(body) + }) + mux.HandleFunc("/returned/", func(w http.ResponseWriter, r *http.Request) { + if a := r.Header.Get("Authorization"); a != "" { + t.Errorf("the hop back to the Hub after leaving it was sent Authorization %q", a) + } + w.Write(repo[strings.TrimPrefix(r.URL.Path, "/returned/")]) + }) + srv := newServer(atCommit(mux)) + t.Cleanup(srv.Close) + return srv +} + +// A download sends the access token to no host but the Hub's origin. A CDN on +// the Hub's own host at another port is a different origin, which net/http's +// own stripping lets the token through to, and once the chain has left the +// origin the token stays off the hop that returns to it +// (iss-2610071200187920). +func TestADownloadSendsTheTokenNowhereButTheHubsOrigin(t *testing.T) { + repo := standardRepo() + var hubURL string + var cdnHits atomic.Int32 + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cdnHits.Add(1) + if a := r.Header.Get("Authorization"); a != "" { + t.Errorf("the content CDN on the Hub's host at another port was sent Authorization %q", a) + } + http.Redirect(w, r, hubURL+"/returned/"+strings.TrimPrefix(r.URL.Path, "/cdn/"), http.StatusFound) + })) + defer cdn.Close() + srv := cdnRedirectingHub(t, repo, httptest.NewServer, func(name string) string { return cdn.URL + "/cdn/" + name }) + hubURL = srv.URL + + c := &Client{BaseURL: srv.URL, HTTP: srv.Client()} + c.SetToken("hf_secret") + dest := t.TempDir() + if _, err := c.Download(context.Background(), DownloadRequest{RepoID: "org/repo", Dest: dest}); err != nil { + t.Fatalf("Download: %v", err) + } + if n := cdnHits.Load(); n != 1 { + t.Fatalf("the CDN was asked %d times, want 1", n) + } + got, err := os.ReadFile(filepath.Join(dest, "model.safetensors")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, repo["model.safetensors"]) { + t.Error("the weights did not land intact") + } +} + +// A download from an https Hub refuses a hop to plain http, as the update +// check's content fetch does (iss-2610071200187920). +func TestADownloadRefusesARedirectFromHTTPSToHTTP(t *testing.T) { + repo := standardRepo() + var plainHits atomic.Int32 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + plainHits.Add(1) + w.Write(repo[strings.TrimPrefix(r.URL.Path, "/cdn/")]) + })) + defer plain.Close() + srv := cdnRedirectingHub(t, repo, httptest.NewTLSServer, func(name string) string { return plain.URL + "/cdn/" + name }) + + c := &Client{BaseURL: srv.URL, HTTP: srv.Client()} + if _, err := c.Download(context.Background(), DownloadRequest{RepoID: "org/repo", Dest: t.TempDir()}); err == nil { + t.Error("Download followed a redirect from https to http") + } + if n := plainHits.Load(); n != 0 { + t.Errorf("the plain-http host was asked %d times", n) + } +} + +// A download the content CDN refuses names the CDN and gives no token +// advice, as the update check's read does: the CDN was never sent the token +// (iss-2610071200183905). +func TestADownloadTheCDNRefusesIsNotWordedAsATokenProblem(t *testing.T) { + repo := standardRepo() + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "denied", http.StatusForbidden) + })) + defer cdn.Close() + srv := cdnRedirectingHub(t, repo, httptest.NewServer, func(name string) string { return cdn.URL + "/cdn/" + name }) + + c := &Client{BaseURL: srv.URL, HTTP: srv.Client()} + c.SetToken("hf_secret") + _, err := c.Download(context.Background(), DownloadRequest{RepoID: "org/repo", Dest: t.TempDir()}) + if err == nil { + t.Fatal("a download the CDN refused succeeded") + } + msg := err.Error() + if strings.Contains(msg, "token") { + t.Errorf("a CDN refusal gives token advice: %s", msg) + } + if host := strings.TrimPrefix(cdn.URL, "http://"); !strings.Contains(msg, "content CDN") || !strings.Contains(msg, host) { + t.Errorf("a CDN refusal does not name the CDN at %s: %s", host, msg) + } +} + // A download is bounded by what the Hub said the file is. A tree entry that // declares ten bytes against a body that streams tens of megabytes must be // refused at the boundary, before the surplus is written: peak disk during a diff --git a/internal/hub/hub.go b/internal/hub/hub.go index 0e646528..ce81e257 100644 --- a/internal/hub/hub.go +++ b/internal/hub/hub.go @@ -216,7 +216,7 @@ func (c *Client) newTokenRequest(ctx context.Context, method, u, token string) ( return req, nil } -// maxRedirects is the hop limit refuseOffOrigin re-imposes. Setting +// maxRedirects is the hop limit refuseOffOrigin and followContent re-impose. Setting // CheckRedirect replaces net/http's own default of 10, so it is spelled here // rather than inherited. const maxRedirects = 10 @@ -415,7 +415,7 @@ func (c *Client) SmallFileAt(ctx context.Context, up Upstream, f File, max int64 } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, apiError(resp, u) + return nil, c.contentError(resp, u) } b, err := io.ReadAll(io.LimitReader(resp.Body, max+1)) if err != nil { @@ -433,24 +433,52 @@ func (c *Client) SmallFileAt(ctx context.Context, up Upstream, f File, max int64 return b, nil } -// doContent issues a request for an LFS object's content, which the Hub -// answers with a redirect to its content CDN. Unlike do it follows that hop -// off the Hub's origin — the caller holds what arrives to the sha256 the -// listing gave — but it drops the access token from any hop that leaves the -// origin, which a pre-signed CDN URL does not need, and keeps the hop limit. -// It runs on a shallow copy of the client, as do does. +// doContent issues a request for a file's content, which the Hub answers for +// an LFS object with a redirect to its content CDN. It is the one way this +// package fetches content — a download's every file, and SmallFileAt's read +// of a file the listing keeps in LFS — and it runs under followContent rather +// than refuseOffOrigin: it follows the hop off the Hub's origin, because the +// caller holds what arrives to a hash the listing gave. It runs on a shallow +// copy of the client, as do does. func (c *Client) doContent(req *http.Request) (*http.Response, error) { hc := *c.httpClient() - hc.CheckRedirect = func(next *http.Request, via []*http.Request) error { - if len(via) >= maxRedirects { - return fmt.Errorf("stopped after %d redirects", maxRedirects) + hc.CheckRedirect = c.followContent + return hc.Do(req) +} + +// followContent is the redirect policy of doContent. It keeps the hop limit, +// refuses a hop to anything but https when the Hub's base URL is https, and +// drops the access token from every hop once any hop of the chain is off the +// Hub's origin, which a pre-signed CDN URL does not need. +// +// net/http's own stripping is not enough on either count. It keeps the token +// on a hop to the Hub's host at another port or to a subdomain of it, which +// are other origins. And each hop's headers are copied afresh from the first +// request, so a token deleted on the hop that leaves the origin comes back on +// a hop that returns to it — a host off the origin would choose which +// authenticated Hub request is made — unless it is deleted on every hop after +// (iss-2610071200187548, iss-2610071200187920). +func (c *Client) followContent(next *http.Request, via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + base := c.baseURL() + if b, err := url.Parse(base); err != nil || strings.EqualFold(b.Scheme, "https") { + if !strings.EqualFold(next.URL.Scheme, "https") { + return fmt.Errorf("redirected from https to %s://%s — refusing to follow it", next.URL.Scheme, next.URL.Host) } - if !sameOrigin(c.baseURL(), next.URL.String()) { - next.Header.Del("Authorization") + } + left := !sameOrigin(base, next.URL.String()) + for _, r := range via { + if left { + break } - return nil + left = !sameOrigin(base, r.URL.String()) } - return hc.Do(req) + if left { + next.Header.Del("Authorization") + } + return nil } // APIError is a non-2xx response from the Hub. @@ -463,9 +491,20 @@ type APIError struct { // 401, exactly as it answers one for a gated repository, so what a 401 // means depends on it (iss-2610030913177383). TokenSent bool + // ContentHost is the host that answered when it is off the Hub's origin: + // the content CDN a file was handed to, which is never sent the token, so + // its refusal says nothing about the token (iss-2610071200183905). + ContentHost string } func (e *APIError) Error() string { + if e.ContentHost != "" { + switch e.StatusCode { + case http.StatusUnauthorized, http.StatusForbidden: + return fmt.Sprintf("huggingface's content CDN at %s refused %s (HTTP %d)", e.ContentHost, e.URL, e.StatusCode) + } + return fmt.Sprintf("huggingface's content CDN at %s returned HTTP %d for %s: %s", e.ContentHost, e.StatusCode, e.URL, e.Body) + } switch e.StatusCode { case http.StatusUnauthorized, http.StatusForbidden: if e.TokenSent { @@ -1096,6 +1135,18 @@ func HasWeights(files []File) bool { return false } +// contentError is apiError for a content fetch, which may have been answered +// off the Hub's origin: a refusal from the content CDN names the CDN, so it +// is not worded as the Hub refusing a token the CDN was never sent. +func (c *Client) contentError(resp *http.Response, u string) error { + err := apiError(resp, u) + var ae *APIError + if final := resp.Request; final != nil && final.URL != nil && !sameOrigin(c.baseURL(), final.URL.String()) && errors.As(err, &ae) { + ae.ContentHost = final.URL.Host + } + return err +} + func apiError(resp *http.Response, u string) error { // Read, not a single resp.Body.Read call: io.Reader may legitimately // return fewer bytes than the buffer even mid-body (chunked framing, TLS diff --git a/internal/lifecycle/testdata/config_show.json b/internal/lifecycle/testdata/config_show.json index 2e63aab7..2a373114 100644 --- a/internal/lifecycle/testdata/config_show.json +++ b/internal/lifecycle/testdata/config_show.json @@ -43,6 +43,7 @@ "sampling.top_k": null, "sampling.top_p": null, "self_test": false, + "self_test_idle_threshold_sec": 0, "statistics": false, "stats_max_bytes": 209715200, "stats_months": 6, diff --git a/internal/registry/kvbytes_test.go b/internal/registry/kvbytes_test.go new file mode 100644 index 00000000..f19609c6 --- /dev/null +++ b/internal/registry/kvbytes_test.go @@ -0,0 +1,102 @@ +package registry + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +// hybridConfig is Qwen3-Coder-Next's shape: 12 full-attention layers of 48, +// 24,576 bytes a token of real cache, charged five times that. +const hybridConfig = `{"model_type":"qwen3_next","max_position_embeddings":262144,"num_hidden_layers":48, + "full_attention_interval":4,"num_key_value_heads":2,"head_dim":256}` + +// The real cache a token costs is recorded beside what it is charged, from +// the same scan, so the launcher can bound the model server's prompt cache +// by it (iss-2610071035130302). A model the index already lists gains it at +// the next rescan, as it gains every other figure the scan re-derives. +func TestRescanRecordsTheRealCacheFigure(t *testing.T) { + r, dir := newTestRegistry(t) + if err := r.Put(Model{RepoID: "org/hybrid", State: StateReady, KVChargePerToken: 24576 * 5}); err != nil { + t.Fatal(err) + } + writeModelDirWithConfig(t, dir, "org", "hybrid", hybridConfig, 1024) + if err := r.Rescan(dir); err != nil { + t.Fatalf("Rescan: %v", err) + } + m, err := r.Get("org/hybrid") + if err != nil { + t.Fatalf("Get: %v", err) + } + if m.KVBytesPerToken != 24576 { + t.Errorf("KVBytesPerToken = %d, want 24576", m.KVBytesPerToken) + } + if m.KVChargePerToken != 24576*5 { + t.Errorf("KVChargePerToken = %d, want %d", m.KVChargePerToken, 24576*5) + } +} + +// A configuration whose charge is past the plausible ceiling records no real +// figure either: a model charged the flat figure has no cache in its charge +// for the prompt cache to be bounded within. +func TestAnImplausibleConfigurationRecordsNoRealCacheFigure(t *testing.T) { + // 64 layers of 64 heads of 1,024: 16 MiB a token of real cache, under + // the ceiling on its own and five times past it once charged. + const hostile = `{"model_type":"test","num_hidden_layers":64,"num_key_value_heads":64,"head_dim":1024}` + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(hostile), 0o644); err != nil { + t.Fatal(err) + } + facts := ReadModelFacts(dir) + if facts.KVChargePerToken != 0 { + t.Fatalf("KVChargePerToken = %d, want 0 for a charge past the ceiling", facts.KVChargePerToken) + } + if facts.KVBytesPerToken != 0 { + t.Errorf("KVBytesPerToken = %d for a model charged no cache, want 0", facts.KVBytesPerToken) + } +} + +// The figure is persisted, and it is what the model server's prompt cache is +// allowed to hold, so it survives a reopen as written and is held, when read +// back, to the bound the charge beside it is held to — and to the charge +// itself, which a real figure is never above. +func TestTheRealCacheFigureRoundTripsAndIsBoundedOnRead(t *testing.T) { + path := filepath.Join(t.TempDir(), "registry.json") + r, err := Open(path) + if err != nil { + t.Fatal(err) + } + if err := r.Put(Model{RepoID: "org/kept", State: StateReady, KVChargePerToken: 24576 * 5, KVBytesPerToken: 24576}); err != nil { + t.Fatal(err) + } + r, err = Open(path) + if err != nil { + t.Fatal(err) + } + if m, _ := r.Get("org/kept"); m.KVBytesPerToken != 24576 { + t.Errorf("after a reopen KVBytesPerToken = %d, want 24576", m.KVBytesPerToken) + } + + planted := fmt.Sprintf(`[ + {"repo_id":"org/huge","state":"ready","kv_charge_per_token":%d,"kv_bytes_per_token":%d}, + {"repo_id":"org/negative","state":"ready","kv_charge_per_token":100,"kv_bytes_per_token":-1}, + {"repo_id":"org/above","state":"ready","kv_charge_per_token":100,"kv_bytes_per_token":101}, + {"repo_id":"org/uncharged","state":"ready","kv_bytes_per_token":20}, + {"repo_id":"org/fine","state":"ready","kv_charge_per_token":100,"kv_bytes_per_token":20}]`, + int64(MaxKVChargePerToken), int64(MaxKVChargePerToken)+1) + if err := os.WriteFile(path, []byte(planted), 0o600); err != nil { + t.Fatal(err) + } + r, err = Open(path) + if err != nil { + t.Fatal(err) + } + for id, want := range map[string]int64{ + "org/huge": 0, "org/negative": 0, "org/above": 0, "org/uncharged": 0, "org/fine": 20, + } { + if m, _ := r.Get(id); m.KVBytesPerToken != want { + t.Errorf("%s: KVBytesPerToken = %d, want %d", id, m.KVBytesPerToken, want) + } + } +} diff --git a/internal/registry/kvshape_test.go b/internal/registry/kvshape_test.go index 1c5b5615..1c6f93de 100644 --- a/internal/registry/kvshape_test.go +++ b/internal/registry/kvshape_test.go @@ -116,10 +116,16 @@ func TestKVBytesPerTokenReadsTheConfigurationsShape(t *testing.T) { if c.latent { factor = 7 } - if got, want := ReadModelFacts(dir).KVChargePerToken, c.want*factor; got != want { + facts := ReadModelFacts(dir) + if got, want := facts.KVChargePerToken, c.want*factor; got != want { t.Errorf("KVChargePerToken = %d, want %d (%d from the configuration, times %d)", got, want, c.want, factor) } + // And the arithmetic itself, uncharged, beside it: what the + // model server's prompt cache is bounded by. + if got := facts.KVBytesPerToken; got != c.want { + t.Errorf("KVBytesPerToken = %d, want %d, the configuration's own figure", got, c.want) + } }) } } diff --git a/internal/registry/registry.go b/internal/registry/registry.go index a81bbe96..6669b300 100644 --- a/internal/registry/registry.go +++ b/internal/registry/registry.go @@ -72,6 +72,14 @@ type Model struct { // does not say enough to work it out, and such a model is charged the flat // figure instead. KVChargePerToken int64 `json:"kv_charge_per_token,omitempty"` + // KVBytesPerToken is the same configuration's arithmetic without the + // safety factor (capability.KVShape.BytesPerToken): the real cache one + // token costs. The model server's prompt cache is bounded by one served + // window of it (iss-2610071035130302). Zero means the figure is not + // known — the configuration does not say, or the charge beside it is + // zero — and such a model's server keeps no prompt cache. Never above + // the charge. + KVBytesPerToken int64 `json:"kv_bytes_per_token,omitempty"` // PipelineTag and Tags are what HuggingFace says this model is: the repo's // pipeline tag ("text-generation", "automatic-speech-recognition") and its // tags, recorded from the Hub when the model was downloaded. @@ -156,6 +164,14 @@ type UpdateCheck struct { // Commit is the newer upstream commit the check found; empty when the // version on disk is current. Commit string `json:"commit,omitempty"` + // Files names the files the newer version changes — changed, added or + // removed, documentation never — in order, at most MaxUpdateFiles of + // them; FilesChanged is how many it changes in all, so the card can say + // how many more there are (iss-2610042101436222). Both are empty when + // the version on disk is current, or when the record holds no hashes to + // compare against and which files changed is not known. + Files []string `json:"files,omitempty"` + FilesChanged int `json:"files_changed,omitempty"` // CheckedAt is when the Hub answered. Wall-clock time, compared with the // clock when the next check is due, so a Mac that slept is not skewed. CheckedAt time.Time `json:"checked_at"` @@ -164,16 +180,15 @@ type UpdateCheck struct { // What an update check can find. Every value but UpdateCurrent is a mark on // the model's card; only UpdateAvailable offers Update. const ( - // UpdateCurrent: no file Dessau uses differs from the version on disk. + // UpdateCurrent: no file Dessau uses differs from the version on disk, + // or the only newer version is a decision model's that no Dessau release + // has reviewed, which is never marked (iss-2610042101436891). UpdateCurrent = "current" // UpdateAvailable: a newer version changes a file Dessau uses. UpdateAvailable = "available" // UpdateRunsOwnCode: the newer version's config.json names a model_file, // which Dessau will not run. UpdateRunsOwnCode = "runs_own_code" - // UpdateAwaitingReview: a decision model's newer version has not been - // reviewed by a Dessau release, so it is not offered until one has. - UpdateAwaitingReview = "awaiting_review" // UpdateCannotCheck: the Hub handed out the newer version's config.json // in a form the check could not hold to the hash it lists for it, so // whether that version ships its own code is unknown and it is not @@ -181,6 +196,11 @@ const ( UpdateCannotCheck = "cannot_check" ) +// MaxUpdateFiles bounds the files a check names: a card has room for a +// handful, and a repository that changes a thousand shards should cost the +// index no more than one that changes a dozen. +const MaxUpdateFiles = 10 + // ErrVersionMoved is SetUpdate's refusal when the model on disk is no longer // the version the check compared. var ErrVersionMoved = errors.New("the model's version changed while it was being checked") @@ -203,7 +223,7 @@ func sanitizeUpdate(m Model) Model { switch u.Status { case UpdateCurrent: ok = ok && u.Commit == "" - case UpdateAvailable, UpdateRunsOwnCode, UpdateAwaitingReview, UpdateCannotCheck: + case UpdateAvailable, UpdateRunsOwnCode, UpdateCannotCheck: ok = ok && validCommit(u.Commit) && u.Commit != m.Commit default: ok = false @@ -216,10 +236,38 @@ func sanitizeUpdate(m Model) Model { if cp.CheckedAt.After(time.Now().Add(24 * time.Hour)) { cp.CheckedAt = time.Time{} } + cp.Files, cp.FilesChanged = sanitizeUpdateFiles(cp.Status, cp.Files, cp.FilesChanged) m.Update = &cp return m } +// sanitizeUpdateFiles holds the files a check names to what a check writes: +// none on a version with nothing newer; otherwise plain names only (the rule +// a recorded version's paths are held to), at most MaxUpdateFiles of them, +// and a count no smaller than the names it was given. A name dropped here +// still counts among the files changed; it is only not named. The list +// returned is a fresh slice, so what the registry holds is never the +// caller's. +func sanitizeUpdateFiles(status string, files []string, changed int) ([]string, int) { + if status == UpdateCurrent { + return nil, 0 + } + changed = max(changed, len(files)) + var out []string + for _, p := range files { + if len(out) == MaxUpdateFiles { + break + } + if plainRelPath(p) { + out = append(out, p) + } + } + if len(out) == 0 { + out = nil + } + return out, changed +} + // SetUpdate records what a check found, provided the model on disk is still // the version the check compared (onDisk is that version's commit): a model // downloaded again while its check was in flight is not described by it. @@ -584,6 +632,12 @@ func Open(path string) (*Registry, error) { if !plausibleKVChargePerToken(m.KVChargePerToken) { m.KVChargePerToken = 0 } + // And the real figure beside it, which bounds the prompt cache the + // model server keeps: held to the same bound, and to the charge it + // is never above, checked after the charge itself was. + if !plausibleKVBytesPerToken(m.KVBytesPerToken, m.KVChargePerToken) { + m.KVBytesPerToken = 0 + } // The category is persisted too, so a hand-edited or planted index can // carry an unbounded tag list straight to the LAN with no download in // between. Bound words read back exactly as words from the Hub are. @@ -1008,6 +1062,7 @@ func (r *Registry) Rescan(modelsDir string) error { Bytes: size, ContextLength: facts.ContextLength, KVChargePerToken: facts.KVChargePerToken, + KVBytesPerToken: facts.KVBytesPerToken, ChatTemplate: facts.ChatTemplate, QuantizationBits: facts.QuantizationBits, State: StateReady, @@ -1032,6 +1087,7 @@ func (r *Registry) Rescan(modelsDir string) error { // next startup rescan rather than only on a re-download. existing.ContextLength = m.ContextLength existing.KVChargePerToken = m.KVChargePerToken + existing.KVBytesPerToken = m.KVBytesPerToken existing.ChatTemplate = m.ChatTemplate existing.QuantizationBits = m.QuantizationBits // The category is deliberately NOT re-derived. It is the Hub's @@ -1173,6 +1229,7 @@ func ModelDirComplete(dir string) bool { type ModelFacts struct { ContextLength int64 KVChargePerToken int64 + KVBytesPerToken int64 ChatTemplate bool QuantizationBits int } @@ -1196,6 +1253,7 @@ func factsFrom(dir string, cfg map[string]any) ModelFacts { return ModelFacts{ ContextLength: contextLengthFrom(cfg), KVChargePerToken: kvChargePerTokenFrom(cfg), + KVBytesPerToken: kvBytesPerTokenFrom(cfg), ChatTemplate: hasChatTemplate(dir), QuantizationBits: quantizationBitsFrom(cfg), } @@ -1454,6 +1512,20 @@ func kvChargePerTokenFrom(cfg map[string]any) int64 { return n } +// kvBytesPerTokenFrom is the real cache one token costs, from the same shape +// as the charge and without its safety factor: what bounds the model +// server's prompt cache (iss-2610071035130302). A configuration whose charge +// is not believed yields nothing here either, because such a model is +// charged the flat figure, which reserves no cache for the prompt cache to +// be bounded within. +func kvBytesPerTokenFrom(cfg map[string]any) int64 { + n := kvShapeFrom(cfg).BytesPerToken() + if !plausibleKVBytesPerToken(n, kvChargePerTokenFrom(cfg)) { + return 0 + } + return n +} + // kvShapeFrom reads the shape itself, leaving the arithmetic and its own // bounds to capability. func kvShapeFrom(cfg map[string]any) capability.KVShape { @@ -1570,6 +1642,14 @@ func plausibleKVChargePerToken(n int64) bool { return n >= 0 && n <= MaxKVChargePerToken } +// plausibleKVBytesPerToken is the bound applied wherever a real cache figure +// enters the registry: the charge's own bound, and the charge itself, which +// is that figure times a safety factor and so never below it. A figure with +// no charge beside it is not believed either. +func plausibleKVBytesPerToken(n, charge int64) bool { + return plausibleKVChargePerToken(n) && (n == 0 || n <= charge) +} + // CheckShards reports an error unless every weight shard named by // model.safetensors.index.json exists in dir as a regular file. Single-file // models have no index, which counts as complete. A present-but-unreadable diff --git a/internal/registry/version_test.go b/internal/registry/version_test.go index 3c86160f..c825a53e 100644 --- a/internal/registry/version_test.go +++ b/internal/registry/version_test.go @@ -276,7 +276,8 @@ func TestAPlantedCheckIsHeldToWhatACheckWrites(t *testing.T) { {"repo_id":"org/a","state":"ready","commit":"` + aCommit + `","update":{"status":"new","commit":"` + aCommit + `","checked_at":"2026-10-03T12:00:00Z"}}, {"repo_id":"org/b","state":"ready","commit":"` + aCommit + `","update":{"status":"available","commit":"main","checked_at":"2026-10-03T12:00:00Z"}}, {"repo_id":"org/c","state":"ready","commit":"` + aCommit + `","update":{"status":"current","checked_at":"2999-01-01T00:00:00Z"}}, - {"repo_id":"org/d","state":"ready","update":{"status":"current","checked_at":"2026-10-03T12:00:00Z"}} + {"repo_id":"org/d","state":"ready","update":{"status":"current","checked_at":"2026-10-03T12:00:00Z"}}, + {"repo_id":"org/e","state":"ready","commit":"` + aCommit + `","update":{"status":"awaiting_review","commit":"fedcba9876543210fedcba9876543210fedcba98","checked_at":"2026-10-03T12:00:00Z"}} ]` if err := os.WriteFile(path, []byte(planted), 0o600); err != nil { t.Fatal(err) @@ -285,7 +286,9 @@ func TestAPlantedCheckIsHeldToWhatACheckWrites(t *testing.T) { if err != nil { t.Fatal(err) } - for _, id := range []string{"org/a", "org/b", "org/d"} { + // org/e is the mark a decision model once carried, which no check writes + // any more (iss-2610042101436891). + for _, id := range []string{"org/a", "org/b", "org/d", "org/e"} { if m, _ := r.Get(id); m.Update != nil { t.Errorf("%s: a planted check was kept: %+v", id, m.Update) } @@ -295,6 +298,39 @@ func TestAPlantedCheckIsHeldToWhatACheckWrites(t *testing.T) { } } +// The files a check names are held to what a check writes: plain names only, +// at most MaxUpdateFiles of them, a count no smaller than the list, and none +// on a version with nothing newer (iss-2610042101436222). +func TestAPlantedFileListIsHeldToWhatACheckWrites(t *testing.T) { + path := filepath.Join(t.TempDir(), "registry.json") + const newer = "fedcba9876543210fedcba9876543210fedcba98" + var many []string + for i := 0; i < MaxUpdateFiles+5; i++ { + many = append(many, fmt.Sprintf("%q", fmt.Sprintf("shard-%02d.safetensors", i))) + } + planted := `[ + {"repo_id":"org/a","state":"ready","commit":"` + aCommit + `","update":{"status":"available","commit":"` + newer + `","files":["config.json",".json","../up.json"],"files_changed":1,"checked_at":"2026-10-03T12:00:00Z"}}, + {"repo_id":"org/b","state":"ready","commit":"` + aCommit + `","update":{"status":"available","commit":"` + newer + `","files":[` + strings.Join(many, ",") + `],"files_changed":-4,"checked_at":"2026-10-03T12:00:00Z"}}, + {"repo_id":"org/c","state":"ready","commit":"` + aCommit + `","update":{"status":"current","files":["config.json"],"files_changed":1,"checked_at":"2026-10-03T12:00:00Z"}} + ]` + if err := os.WriteFile(path, []byte(planted), 0o600); err != nil { + t.Fatal(err) + } + r, err := Open(path) + if err != nil { + t.Fatal(err) + } + if m, _ := r.Get("org/a"); m.Update == nil || strings.Join(m.Update.Files, ",") != "config.json" || m.Update.FilesChanged != 3 { + t.Errorf("org/a: Update = %+v, want config.json alone named of 3", m.Update) + } + if m, _ := r.Get("org/b"); m.Update == nil || len(m.Update.Files) != MaxUpdateFiles || m.Update.FilesChanged != MaxUpdateFiles+5 { + t.Errorf("org/b: Update = %+v, want %d names of %d", m.Update, MaxUpdateFiles, MaxUpdateFiles+5) + } + if m, _ := r.Get("org/c"); m.Update == nil || m.Update.Files != nil || m.Update.FilesChanged != 0 { + t.Errorf("org/c: a current version names files: %+v", m.Update) + } +} + // The rule the model server loads code by, applied to the bytes of a // config.json a check fetched rather than to a file on disk. func TestAConfigThatNamesModelCodeIsRecognisedFromItsBytes(t *testing.T) { diff --git a/internal/runtime/kvcharge_test.go b/internal/runtime/kvcharge_test.go index c3c754da..194c42e5 100644 --- a/internal/runtime/kvcharge_test.go +++ b/internal/runtime/kvcharge_test.go @@ -2,8 +2,11 @@ package runtime import ( "context" + "errors" + "fmt" "strings" "testing" + "time" "github.com/intentdriven/Dessau/internal/capability" ) @@ -246,3 +249,90 @@ func TestTheSameModelLoadsAtAWindowThatFits(t *testing.T) { t.Errorf("Resident() = %+v, want the model charged its weights and two windows", got) } } + +// The charge covers every request the pool admits to a model at once. A model +// is charged one served window of cache per batched request, so the pool must +// let no more requests run against it than it charged for: two long requests +// admitted on a one-sequence charge can build twice the cache the budget +// reserved (iss-2610071035138788). The request past the charge waits for a +// running one to finish rather than running beside it. +func TestTheChargeCoversEveryRequestThePoolAdmits(t *testing.T) { + for _, sequences := range []int{1, 2, 3} { + t.Run(fmt.Sprintf("%d batched requests", sequences), func(t *testing.T) { + const size, kv, window = 100, 1, 100 + l := newFakeLauncher() + src := &fakeSource{ + models: map[string]int64{"org/m": size}, + facts: map[string]ResolvedModel{ + "org/m": {Bytes: size, ServedContext: window, KVChargePerToken: kv}, + }, + } + p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 30, DecodeConcurrency: sequences}) + + // Take every request the pool admits at once; the first one it + // will not admit before its deadline marks the limit. + var releases []func() + defer func() { + for _, release := range releases { + release() + } + }() + for len(releases) <= 4*sequences { + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + _, release, err := p.Acquire(ctx, "org/m") + cancel() + if err != nil { + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Acquire: %v", err) + } + break + } + releases = append(releases, release) + } + admitted := len(releases) + if admitted == 0 { + t.Fatal("the pool admitted no request at all") + } + + got := p.Resident() + if len(got) != 1 { + t.Fatalf("Resident() = %+v, want the one model", got) + } + covered := capability.LoadCostOf(capability.Load{ + DiskBytes: size, KVChargePerToken: kv, Window: window, Sequences: int64(admitted), + }) + if got[0].Charge < covered { + t.Errorf("%d requests ran at once on a charge of %d, but their caches need %d: the charge covers %d", + admitted, got[0].Charge, covered, sequences) + } + if admitted != sequences { + t.Errorf("%d requests ran at once, want the %d the charge covers", admitted, sequences) + } + + // The next request waits for a running one, and runs once it ends. + done := make(chan error, 1) + go func() { + _, release, err := p.Acquire(context.Background(), "org/m") + if err == nil { + release() + } + done <- err + }() + select { + case err := <-done: + t.Fatalf("a request past the charge ran beside the others (err %v)", err) + case <-time.After(100 * time.Millisecond): + } + releases[0]() + releases = releases[1:] + select { + case err := <-done: + if err != nil { + t.Fatalf("the waiting request, once a slot freed: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("the waiting request did not run after a running one ended") + } + }) + } +} diff --git a/internal/runtime/launcher.go b/internal/runtime/launcher.go index 43b4f3be..06c9deaa 100644 --- a/internal/runtime/launcher.go +++ b/internal/runtime/launcher.go @@ -14,6 +14,7 @@ import ( "syscall" "time" + "github.com/intentdriven/Dessau/internal/capability" "github.com/intentdriven/Dessau/internal/config" "github.com/intentdriven/Dessau/internal/registry" ) @@ -49,8 +50,22 @@ type Spec struct { // carries it, so the launch after this one is back at INFO with nothing to // remember (adr-2609201008477513). DebugLog bool + // KVBytesPerToken and ServedContext bound the prompt cache the server + // keeps between requests: their product, one served window of real + // cache for one sequence, is what the cache may hold + // (promptCacheBytes). They are the pool's resolved figures + // (ResolvedModel), and either being zero or less means the bound is not + // known, which keeps no prompt cache at all. + KVBytesPerToken int64 + ServedContext int64 } +// promptCacheBytesFlag is Dessau's own flag, read and removed by serve.py +// before the server's argument parser sees the rest. It is not the pinned +// server's --prompt-cache-bytes, which 0.32.0 applies only as a trim on its +// batched path and never hands to the prompt cache's constructor. +const promptCacheBytesFlag = "--dessau-prompt-cache-bytes" + // DebugLogMaxBytes bounds what one armed run of a model server writes to its // log. At DEBUG the server writes every request body and every response, so // the bytes in the file are chosen by whoever is sending requests; the bound @@ -422,6 +437,31 @@ func refuseModelCode(spec Spec, owner int) error { } } +// promptCacheEntries is how many prompts' caches the model server keeps +// between requests: the pinned server's own default, passed explicitly. +const promptCacheEntries = 10 + +// promptCacheBytes is the most the model server's prompt cache may hold: one +// served window of real cache for one sequence (iss-2610071035130302). +// +// The charge already reserves a window of charged cache — the real figure +// times a safety factor — for every sequence the server may decode, so a +// prompt cache held to one real window is counted inside what the model is +// charged, on the margin that factor leaves, and the charge is not raised. +// Without a bound the pinned server keeps ten entries of any size, and each +// can be a whole window: several long conversations held several windows the +// charge does not count. +// +// A model whose real figure or window is not known is charged the flat +// figure, which reserves no cache at all (capability.LoadCostOf). Its prompt +// cache is bounded within that charge too — at nothing, so its server keeps +// no cache between requests rather than one without a limit. That costs +// such a model the reuse of a conversation's earlier turns; a guess at a +// figure would be worse, as it would be for the charge. +func promptCacheBytes(spec Spec) int64 { + return capability.MulSaturating(spec.KVBytesPerToken, spec.ServedContext) +} + // launchArgs is the model server's whole command line, spec by spec. // // It is a function of the Spec alone, and the one thing the Spec says about @@ -445,11 +485,17 @@ func launchArgs(spec Spec) []string { // main(), handler and argument parser, served on Spec.Socket instead of a // TCP port. Only the Go gateway faces the network, so it alone enforces // auth and rewrites requests; the launcher's own refusals sit behind it. + // + // The prompt-cache bound follows the socket, where serve.py takes it by + // position, and the entry count is spelled out rather than left to the + // server's default, so a release that moved it would not move the cache. args := []string{ "-I", "-u", "-c", serveScript, "--dessau-socket", spec.Socket, + promptCacheBytesFlag, strconv.FormatInt(promptCacheBytes(spec), 10), "--model", spec.ModelPath, "--log-level", level, + "--prompt-cache-size", strconv.Itoa(promptCacheEntries), } args = append(args, samplingArgs(spec.Sampling)...) if spec.DecodeConcurrency > 1 { diff --git a/internal/runtime/observer_test.go b/internal/runtime/observer_test.go index b1b2535f..90ff8bc4 100644 --- a/internal/runtime/observer_test.go +++ b/internal/runtime/observer_test.go @@ -312,7 +312,7 @@ func TestAcquireSeparatesTheLoadWaitFromTheQueueWait(t *testing.T) { l.loadDelay = 80 * time.Millisecond src := &fakeSource{models: map[string]int64{"org/m": 1 << 20}} p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 30, DecodeConcurrency: 1}) - // cap(sem) = 2 * DecodeConcurrency = 2. + // cap(sem) = DecodeConcurrency = 1. up, rel1, err := p.Acquire(context.Background(), "org/m") if err != nil { @@ -325,12 +325,7 @@ func TestAcquireSeparatesTheLoadWaitFromTheQueueWait(t *testing.T) { t.Errorf("the first request is reported as queueing for %v; nothing was ahead of it", up.Waits.QueueWait) } - _, rel2, err := p.Acquire(context.Background(), "org/m") - if err != nil { - t.Fatal(err) - } - - // Both slots are taken; the third request queues until one frees. + // The one slot is taken; the second request queues until it frees. type result struct { up *Upstream rel func() @@ -341,7 +336,7 @@ func TestAcquireSeparatesTheLoadWaitFromTheQueueWait(t *testing.T) { u, rel, err := p.Acquire(context.Background(), "org/m") done <- result{u, rel, err} }() - waitInFlight(t, p, "org/m", 3) + waitInFlight(t, p, "org/m", 2) time.Sleep(60 * time.Millisecond) rel1() @@ -350,7 +345,6 @@ func TestAcquireSeparatesTheLoadWaitFromTheQueueWait(t *testing.T) { t.Fatal(got.err) } defer got.rel() - defer rel2() if got.up.Waits.QueueWait < 50*time.Millisecond { t.Errorf("the queued request is reported as waiting %v for a slot, want at least the 60ms it waited", got.up.Waits.QueueWait) diff --git a/internal/runtime/pool.go b/internal/runtime/pool.go index 2a810864..3a3a4042 100644 --- a/internal/runtime/pool.go +++ b/internal/runtime/pool.go @@ -49,6 +49,11 @@ type ResolvedModel struct { // KVChargePerToken is what one token of that window is charged against the // budget (registry.Model.KVChargePerToken). KVChargePerToken int64 + // KVBytesPerToken is what one token of that window really costs, without + // the charge's safety factor (registry.Model.KVBytesPerToken). It is not + // charged: it bounds the prompt cache the model server keeps between + // requests (Spec.KVBytesPerToken). Zero means it is not known. + KVBytesPerToken int64 } // Upstream is a ready model server the gateway can proxy to. @@ -373,11 +378,13 @@ type entry struct { debugLog bool // sem bounds how many requests run against this one model server at once. Its - // capacity is a small multiple of the server's --decode-concurrency: mlx-lm - // batches only that many decodes, and each extra in-flight sequence holds its - // own KV cache. On a unified-memory Mac an unbounded burst is a direct path to - // a GPU-memory blowup that crashes the server and every request with it, so - // excess requests queue on this channel instead. + // capacity is the server's decode concurrency, which is exactly how many + // sequences the budget charges this model's cache for (chargeLocked): each + // in-flight sequence holds its own KV cache, so admitting more than were + // charged lets the model grow past what the budget reserved. On a + // unified-memory Mac that is a direct path to a GPU-memory blowup that + // crashes the server and every request with it, so excess requests queue on + // this channel instead. sem chan struct{} // soft are the preemptible holds on this model: the id release uses to @@ -1369,9 +1376,10 @@ func (p *Pool) startLocked(repoID string, waited time.Duration, adm admission, c loadedAt: p.opts.now(), lastUsed: p.opts.now(), ready: make(chan struct{}), - // Allow twice the decode batch size in flight: enough to keep mlx-lm's - // batching full without letting an unbounded burst exhaust GPU memory. - sem: make(chan struct{}, 2*p.opts.DecodeConcurrency), + // Admit what is charged: chargeLocked reserves one served window of + // cache per decode slot, so no more requests than that run at once + // (iss-2610071035138788). The rest wait on the queue. + sem: make(chan struct{}, p.opts.DecodeConcurrency), } var sampling config.Sampling @@ -1396,6 +1404,8 @@ func (p *Pool) startLocked(repoID string, waited time.Duration, adm admission, c DecodeConcurrency: p.opts.DecodeConcurrency, Sampling: sampling, DebugLog: debugLog, + KVBytesPerToken: m.KVBytesPerToken, + ServedContext: m.ServedContext, }) if err != nil { return nil, p.launchFailedLocked(repoID, err) @@ -2476,6 +2486,21 @@ func (p *Pool) Unload(repoID string) error { return p.unloadLocked(repoID) } +// UnloadUnpinned is Unload for the idle jobs, which never stop a pinned +// model: a pinned one is refused with ErrPinned and nothing changes, and +// otherwise Unload's rule holds. The pin is read under the same hold of p.mu +// as the stop, so a pin saved through SetPinned lands either before the check +// and is honoured, or after the stop (iss-2610042033419572). The operator's +// Unload keeps its own rule. +func (p *Pool) UnloadUnpinned(repoID string) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.isPinnedLocked(repoID) { + return fmt.Errorf("%s is pinned: %w", repoID, ErrPinned) + } + return p.unloadLocked(repoID) +} + // Remove is Unload for a model that is being deleted. It stops the server // under Unload's rule — a busy model is refused and nothing changes — and // drops what the pool holds about the model beyond its process: the @@ -2530,7 +2555,7 @@ func (p *Pool) Release(repoID string, by Caller) error { return nil } -// The refusals Release adds to Unload's. +// The refusals Release adds to Unload's. UnloadUnpinned adds ErrPinned alone. var ( ErrPinned = errors.New("the model is pinned") ErrLoading = errors.New("the model is still loading") diff --git a/internal/runtime/pool_test.go b/internal/runtime/pool_test.go index 00d27355..2637c8c1 100644 --- a/internal/runtime/pool_test.go +++ b/internal/runtime/pool_test.go @@ -39,7 +39,7 @@ func (s *fakeSource) Resolve(repoID string) (ResolvedModel, error) { m := ResolvedModel{Path: "/models/" + id, Bytes: size} for factID, f := range s.facts { if strings.EqualFold(factID, repoID) { - m.ServedContext, m.KVChargePerToken = f.ServedContext, f.KVChargePerToken + m.ServedContext, m.KVChargePerToken, m.KVBytesPerToken = f.ServedContext, f.KVChargePerToken, f.KVBytesPerToken } } return m, nil @@ -291,14 +291,14 @@ func TestAcquireLaunchesAndReturnsReadyUpstream(t *testing.T) { } } -// The per-model semaphore bounds in-flight requests to 2x DecodeConcurrency, so a +// The per-model semaphore bounds in-flight requests to DecodeConcurrency, so a // burst cannot swamp one mlx-lm server's memory. Past the cap, Acquire blocks // until a slot frees rather than admitting the request. func TestAcquireBoundsPerModelConcurrency(t *testing.T) { l := newFakeLauncher() src := &fakeSource{models: map[string]int64{"org/m": 1 << 20}} - p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 30, DecodeConcurrency: 1}) - // cap = 2 * DecodeConcurrency = 2. + p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 30, DecodeConcurrency: 2}) + // cap = DecodeConcurrency = 2. r1, rel1, err := p.Acquire(context.Background(), "org/m") if err != nil { @@ -340,9 +340,9 @@ func TestAcquireBoundsPerModelConcurrency(t *testing.T) { func TestAcquireRejectsBeyondQueueDepth(t *testing.T) { l := newFakeLauncher() src := &fakeSource{models: map[string]int64{"org/m": 1 << 20}} - // cap(sem) = 2*DecodeConcurrency = 2; MaxQueueDepth = 2; so maxInFlight = 4. + // cap(sem) = DecodeConcurrency = 2; MaxQueueDepth = 2; so maxInFlight = 4. p := newTestPool(t, l, src, PoolOptions{ - MaxResidentBytes: 1 << 30, DecodeConcurrency: 1, MaxQueueDepth: 2, + MaxResidentBytes: 1 << 30, DecodeConcurrency: 2, MaxQueueDepth: 2, }) // Two active slots, held for the duration. diff --git a/internal/runtime/promptcache_test.go b/internal/runtime/promptcache_test.go new file mode 100644 index 00000000..46311ac6 --- /dev/null +++ b/internal/runtime/promptcache_test.go @@ -0,0 +1,113 @@ +package runtime + +import ( + "context" + "strconv" + "testing" +) + +// The model server keeps prompts' caches after their answers are sent, and +// left to its own defaults it keeps ten of them with no limit on their size, +// so a model serving several long conversations held several windows of cache +// its charge does not count (iss-2610071035130302). The maintainer's bound is +// one served window of real, uncharged cache for one sequence: the charge +// already reserves a charged window per sequence, so the kept caches sit +// inside it and the charge is not raised. +// +// The pool hands the launcher both figures, and the launcher passes the +// product as Dessau's own flag — which serve.py reads and hands to the +// prompt cache's constructor — with the entry count spelled out rather than +// left to the server's default. +func TestThePromptCacheIsBoundedToOneServedWindowOfRealCache(t *testing.T) { + const ( + window = 32768 + perToken = 24576 // real bytes a token; the charge is five times this + ) + l := newFakeLauncher() + src := &fakeSource{ + models: map[string]int64{"org/a": 1 << 20}, + facts: map[string]ResolvedModel{"org/a": { + ServedContext: window, KVChargePerToken: perToken * 5, KVBytesPerToken: perToken, + }}, + } + p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 40}) + _, release, err := p.Acquire(context.Background(), "org/a") + if err != nil { + t.Fatalf("Acquire: %v", err) + } + release() + + spec := l.specFor("org/a") + if spec.KVBytesPerToken != perToken || spec.ServedContext != window { + t.Fatalf("the launch carries %d bytes a token at a window of %d, want %d at %d", + spec.KVBytesPerToken, spec.ServedContext, perToken, window) + } + argv := launchArgs(spec) + if got, ok := flagValue(argv, promptCacheBytesFlag); !ok || got != strconv.Itoa(perToken*window) { + t.Errorf("%s = %q (present=%v), want %d — one served window of real cache; argv %v", + promptCacheBytesFlag, got, ok, perToken*window, argv) + } + if got, ok := flagValue(argv, "--prompt-cache-size"); !ok || got != "10" { + t.Errorf("--prompt-cache-size = %q (present=%v), want an explicit 10; argv %v", got, ok, argv) + } +} + +// serve.py takes its own flags by position, before anything it hands the +// server's argument parser, so the bound is always where it looks for it — +// and it is always there: a launch with no bound is one it refuses. +func TestThePromptCacheBoundFollowsTheSocketInEveryLaunch(t *testing.T) { + for name, spec := range map[string]Spec{ + "known": {ModelPath: "/models/org/a", Socket: "/s/m1", KVBytesPerToken: 10, ServedContext: 20}, + "no real figure": {ModelPath: "/models/org/a", Socket: "/s/m1", ServedContext: 20}, + "no window": {ModelPath: "/models/org/a", Socket: "/s/m1", KVBytesPerToken: 10}, + "neither": {ModelPath: "/models/org/a", Socket: "/s/m1"}, + } { + argv := launchArgs(spec) + i := indexOf(argv, "--dessau-socket") + if i < 0 || i+3 >= len(argv) || argv[i+2] != promptCacheBytesFlag { + t.Errorf("%s: %s does not follow the socket: %v", name, promptCacheBytesFlag, argv) + } + if n := countArg(argv, promptCacheBytesFlag); n != 1 { + t.Errorf("%s: %s appears %d times, want once: %v", name, promptCacheBytesFlag, n, argv) + } + } +} + +// A model whose real figure is not known — its configuration says nothing +// about its cache, or the window it is served at is not known — is charged +// the flat figure, which reserves nothing for a cache. Its prompt cache is +// bounded within that charge too: at nothing, so the server keeps no prompt +// cache between requests rather than one with no limit. A guess would be +// worse, as it is for the charge (capability.LoadCostOf). +func TestAModelWithNoRealCacheFigureKeepsNoPromptCache(t *testing.T) { + for name, m := range map[string]ResolvedModel{ + "no real figure": {ServedContext: 32768, KVChargePerToken: 100}, + "no window": {KVChargePerToken: 100, KVBytesPerToken: 20}, + "nothing known": {}, + "negative figures": {ServedContext: -1, KVBytesPerToken: -5}, + } { + t.Run(name, func(t *testing.T) { + l := newFakeLauncher() + src := &fakeSource{models: map[string]int64{"org/a": 1 << 20}, facts: map[string]ResolvedModel{"org/a": m}} + p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 40}) + _, release, err := p.Acquire(context.Background(), "org/a") + if err != nil { + t.Fatalf("Acquire: %v", err) + } + release() + argv := launchArgs(l.specFor("org/a")) + if got, ok := flagValue(argv, promptCacheBytesFlag); !ok || got != "0" { + t.Errorf("%s = %q (present=%v), want 0; argv %v", promptCacheBytesFlag, got, ok, argv) + } + }) + } +} + +func indexOf(argv []string, s string) int { + for i, a := range argv { + if a == s { + return i + } + } + return -1 +} diff --git a/internal/runtime/serve.py b/internal/runtime/serve.py index 3bf21d08..d3972cd5 100644 --- a/internal/runtime/serve.py +++ b/internal/runtime/serve.py @@ -11,7 +11,8 @@ module from the working directory, the model directory or a PYTHONPATH is imported in its place or in mlx_lm's. -Usage: python -I -u -c --dessau-socket PATH [mlx_lm.server flags...] +Usage: python -I -u -c --dessau-socket PATH --dessau-prompt-cache-bytes N + [mlx_lm.server flags...] What it adds to the server, as defence behind the gateway's own checks: @@ -22,7 +23,9 @@ server hands to load() -- is refused, by the key's presence whatever its value, as the gateway refuses them; * a launch naming a draft model, an adapter or remote tokenizer code is - refused, and no origin is allowed cross-origin access. + refused, and no origin is allowed cross-origin access; + * the prompt cache kept between requests holds no more than N bytes, and a + launch with no N, or one that is not a whole number, is refused. """ import io @@ -34,6 +37,9 @@ import sys SOCKET_FLAG = "--dessau-socket" +PROMPT_CACHE_BYTES_FLAG = "--dessau-prompt-cache-bytes" +# The largest bound the Go side can pass (an int64). +MAX_PROMPT_CACHE_BYTES = (1 << 63) - 1 # The fields the pinned server reads as an instruction to load something the # request names. Kept in step with internal/gateway's loadFields. @@ -55,6 +61,25 @@ def _take_socket(argv): return argv[1], argv[2:] +def _take_prompt_cache_bytes(argv): + """The most the prompt cache may hold, in bytes: a whole number from 0. + + Without it the pinned server builds its prompt cache with no byte limit + (2**63), so a missing or malformed value refuses the launch rather than + serving unbounded (iss-2610071035130302). + """ + if len(argv) < 2 or argv[0] != PROMPT_CACHE_BYTES_FLAG: + _fail("the prompt cache has no bound: the second argument must be " + PROMPT_CACHE_BYTES_FLAG + " N") + value = argv[1] + if not (value.isascii() and value.isdigit()): + _fail("the prompt cache bound is not a whole number of bytes") + # The length first: int() refuses a string of more than a few thousand + # digits with its own error rather than this launcher's. + if len(value) > len(str(MAX_PROMPT_CACHE_BYTES)) or int(value) > MAX_PROMPT_CACHE_BYTES: + _fail("the prompt cache bound is out of range") + return int(value), argv[2:] + + def _check_private_dir(path): """Refuse a socket whose directory is not this account's alone.""" directory = os.path.dirname(path) @@ -139,7 +164,7 @@ def do_POST(self): return Handler -def _serve(server, path, model_provider): +def _serve(server, path, prompt_cache_bytes, model_provider): cli = model_provider.cli_args if getattr(cli, "draft_model", None) is not None: _fail("a draft model is not loaded") @@ -151,7 +176,10 @@ def _serve(server, path, model_provider): _fail("no model to serve") cli.allowed_origins = [] - prompt_cache = server.LRUPromptCache(cli.prompt_cache_size) + # Bounded in bytes as well as entries: the pinned server's own run() + # passes the entry count alone, and its --prompt-cache-bytes never + # reaches this constructor. + prompt_cache = server.LRUPromptCache(cli.prompt_cache_size, max_bytes=prompt_cache_bytes) generator = server.ResponseGenerator(model_provider, prompt_cache) handler = _handler_class(server.APIHandler, cli.model) fingerprint = server.get_system_fingerprint() @@ -178,6 +206,7 @@ def _serve(server, path, model_provider): def main(): path, rest = _take_socket(sys.argv[1:]) + prompt_cache_bytes, rest = _take_prompt_cache_bytes(rest) _check_private_dir(path) from mlx_lm import server @@ -185,7 +214,7 @@ def main(): def run(host, port, model_provider, server_class=None, handler_class=None): # The server's main() parses its flags and builds its model provider, # then calls this in place of its own run(), which would bind TCP. - _serve(server, path, model_provider) + _serve(server, path, prompt_cache_bytes, model_provider) server.run = run sys.argv = ["mlx_lm.server"] + rest diff --git a/internal/runtime/serve_test.go b/internal/runtime/serve_test.go index e2087886..0a1de26e 100644 --- a/internal/runtime/serve_test.go +++ b/internal/runtime/serve_test.go @@ -27,7 +27,8 @@ import ( // APIHandler takes the response generator first and reads allowed_origins // off its cli_args). Its own run() is the TCP server the launcher must never // reach, so it leaves a marker and exits. Its handler answers a POST with the -// model and the keys it was given, so a test can see what reached it. +// model and the keys it was given, and a GET with the bounds its prompt +// cache was built with, so a test can see what reached it. const standInServer = ` import argparse, json, os, sys from http.server import BaseHTTPRequestHandler @@ -36,8 +37,9 @@ def get_system_fingerprint(): return "stand-in" class LRUPromptCache: - def __init__(self, size): - self.size = size + def __init__(self, max_size=10, max_bytes=1 << 63): + self.max_size = max_size + self.max_bytes = max_bytes class ModelProvider: def __init__(self, cli_args): @@ -46,6 +48,7 @@ class ModelProvider: class ResponseGenerator: def __init__(self, model_provider, prompt_cache): self.model_provider = model_provider + self.prompt_cache = prompt_cache @property def cli_args(self): return self.model_provider.cli_args @@ -72,7 +75,9 @@ class APIHandler(BaseHTTPRequestHandler): self.wfile.write(body) def do_GET(self): - self._reply(200, {"status": "ok"}) + cache = self.response_generator.prompt_cache + self._reply(200, {"status": "ok", + "prompt_cache": {"max_size": cache.max_size, "max_bytes": cache.max_bytes}}) def do_POST(self): n = int(self.headers.get("Content-Length")) @@ -411,3 +416,106 @@ func TestTheLauncherRefusesAFileInItsSocketsPlace(t *testing.T) { t.Errorf("the file in the socket's place was not left as it was: %q, %v", b, err) } } + +// The bound the launcher is handed reaches the prompt cache's constructor as +// its max_bytes, with the entry count the launch spells out +// (iss-2610071035130302). Without it the pinned server builds the cache with +// its default of 2^63 bytes, which is no bound at all. +func TestTheLauncherBoundsThePromptCache(t *testing.T) { + paths := standInRuntime(t) + t.Setenv("STANDIN_TCP_MARKER", filepath.Join(t.TempDir(), "tcp")) + sock := privateSocket(t) + l := &ExecLauncher{Paths: paths, LogDir: paths.Logs} + p, err := l.Launch(context.Background(), Spec{ + RepoID: "org/name", ModelPath: plainModelDir(t), Socket: sock, + KVBytesPerToken: 1000, ServedContext: 4096, + }) + if err != nil { + t.Fatalf("Launch: %v", err) + } + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), stopBound) + defer cancel() + _ = p.Stop(ctx) + }() + + c := &http.Client{Transport: childTransport(sock), Timeout: 5 * time.Second} + var got struct { + PromptCache struct { + MaxSize int64 `json:"max_size"` + // Unsigned: the server's own default is 2^63, one past int64. + MaxBytes uint64 `json:"max_bytes"` + } `json:"prompt_cache"` + } + deadline := time.Now().Add(20 * time.Second) + for { + resp, err := c.Get(childBaseURL + "/health") + if err == nil { + ok := resp.StatusCode == http.StatusOK && json.NewDecoder(resp.Body).Decode(&got) == nil + resp.Body.Close() + if ok { + break + } + } + select { + case <-p.Done(): + b, _ := os.ReadFile(filepath.Join(paths.Logs, logFileName("org/name"))) + t.Fatalf("the launcher exited before it answered (%v); its log:\n%s", p.Err(), b) + default: + } + if time.Now().After(deadline) { + t.Fatal("the launcher never answered on its socket") + } + time.Sleep(50 * time.Millisecond) + } + if got.PromptCache.MaxBytes != 1000*4096 { + t.Errorf("the prompt cache was built with max_bytes %d, want %d", got.PromptCache.MaxBytes, 1000*4096) + } + if got.PromptCache.MaxSize != 10 { + t.Errorf("the prompt cache was built with max_size %d, want 10", got.PromptCache.MaxSize) + } +} + +// A launch whose bound is missing or is not a whole number of bytes is +// refused before the launcher binds, rather than served with the pinned +// server's unbounded default: the Go side always passes one, and the +// launcher is the last thing between a bad one and the constructor. +func TestTheLauncherRefusesAMissingOrMalformedPromptCacheBound(t *testing.T) { + paths := standInRuntime(t) + t.Setenv("STANDIN_TCP_MARKER", filepath.Join(t.TempDir(), "tcp")) + for name, value := range map[string]string{ + "missing": "", + "negative": "-1", + "not a number": "lots", + "fractional": "1.5", + "signed": "+5", + "non-ASCII": "١٢", + "empty": "", + "past 2^63": "9223372036854775808", + "far past it": strings.Repeat("9", 5000), + } { + t.Run(name, func(t *testing.T) { + sock := privateSocket(t) + argv := launchArgs(Spec{ModelPath: plainModelDir(t), Socket: sock, KVBytesPerToken: 10, ServedContext: 10}) + i := indexOf(argv, promptCacheBytesFlag) + if i < 0 { + t.Fatalf("no %s to tamper with: %v", promptCacheBytesFlag, argv) + } + switch value { + case "": + argv = append(argv[:i:i], argv[i+2:]...) + case "": + argv[i+1] = "" + default: + argv[i+1] = value + } + out := runLauncherExpectingRefusal(t, paths, argv) + if !strings.Contains(out, "prompt cache") { + t.Errorf("the refusal does not say why:\n%s", out) + } + if _, err := os.Lstat(sock); !errors.Is(err, os.ErrNotExist) { + t.Errorf("a socket was bound for a refused launch: %v", err) + } + }) + } +} diff --git a/internal/runtime/softhold_test.go b/internal/runtime/softhold_test.go index 2812aca0..76ca2fec 100644 --- a/internal/runtime/softhold_test.go +++ b/internal/runtime/softhold_test.go @@ -196,12 +196,14 @@ func TestAResidentOnlyAcquireNeverLoads(t *testing.T) { if n := len(l.launched); n != 0 { t.Errorf("a resident-only acquire launched %d model server(s)", n) } - // Held ordinarily, the model is there to be acquired resident-only. + // Loaded ordinarily, the model is there to be acquired resident-only. The + // loading request is served first, as the probe's always is: at one + // decode slot a second request waits for the first to finish. _, release, err := p.Acquire(context.Background(), "org/a") if err != nil { t.Fatal(err) } - defer release() + release() _, release2, err := p.Acquire(WithResidentOnly(context.Background()), "org/a") if err != nil { t.Fatalf("a resident-only acquire of a resident model was refused: %v", err) diff --git a/internal/runtime/unload_unpinned_test.go b/internal/runtime/unload_unpinned_test.go new file mode 100644 index 00000000..244e6b05 --- /dev/null +++ b/internal/runtime/unload_unpinned_test.go @@ -0,0 +1,58 @@ +package runtime + +import ( + "context" + "errors" + "testing" +) + +// UnloadUnpinned is Unload for the idle jobs: it refuses a pinned model with +// ErrPinned, whichever way the pin spells the id, and otherwise keeps +// Unload's rule — a model not loaded is ErrNotLoaded, a busy one ErrBusy +// (iss-2610042033419572). +func TestUnloadUnpinnedRefusesAPinnedModelAndOtherwiseUnloads(t *testing.T) { + l := newFakeLauncher() + src := &fakeSource{models: map[string]int64{"org/m": 1 << 20}} + p := newTestPool(t, l, src, PoolOptions{MaxResidentBytes: 1 << 30}) + + if err := p.UnloadUnpinned("org/m"); !errors.Is(err, ErrNotLoaded) { + t.Errorf("a model not loaded: err = %v, want ErrNotLoaded", err) + } + + _, release, err := p.Acquire(context.Background(), "org/m") + if err != nil { + t.Fatal(err) + } + if err := p.UnloadUnpinned("org/m"); !errors.Is(err, ErrBusy) { + t.Errorf("a model serving a request: err = %v, want ErrBusy", err) + } + release() + + p.SetPinned([]string{"ORG/M"}) + if err := p.UnloadUnpinned("Org/M"); !errors.Is(err, ErrPinned) { + t.Errorf("a pinned model: err = %v, want ErrPinned", err) + } + if len(p.Resident()) != 1 { + t.Fatal("a refused unload changed what is loaded") + } + + // The operator's Unload still stops a pinned model. + if err := p.Unload("org/m"); err != nil { + t.Fatalf("the operator's unload of a pinned model: %v", err) + } + if len(p.Resident()) != 0 { + t.Fatal("the operator's unload left a pinned model resident") + } + + p.SetPinned(nil) + if _, release, err = p.Acquire(context.Background(), "org/m"); err != nil { + t.Fatal(err) + } + release() + if err := p.UnloadUnpinned("org/m"); err != nil { + t.Fatalf("an idle, unpinned model: %v", err) + } + if len(p.Resident()) != 0 { + t.Error("the model is still resident after UnloadUnpinned") + } +} diff --git a/internal/selftest/selftest.go b/internal/selftest/selftest.go index 1c2bfda7..936a30d2 100644 --- a/internal/selftest/selftest.go +++ b/internal/selftest/selftest.go @@ -4,7 +4,9 @@ // once a minute and asks whether the Mac is idle: no client request in flight // anywhere, nobody waiting for a load, no download running, and the last // client request — whatever it ended as, and whether or not its model is still -// loaded (Clients) — older than a quiet period. When it is, the loop picks the +// loaded (Clients) — older than a quiet period: the self-test's own +// (SelfTestQuiet, four hours unless set), apart from the one the other jobs +// wait for (Quiet). When it is, the loop picks the // ready model that was tested longest ago — never one tested within the last // day — acquires it through the pool's ordinary path, runs the same short set // of tests against it, appends one line of figures to a file, and unloads the @@ -216,8 +218,13 @@ const ( // DefaultTick is how often the loop asks whether the Mac is idle. DefaultTick = time.Minute // DefaultQuiet is how long the last request must be in the past before - // the Mac counts as idle. + // the Mac counts as idle for a job (the context probe's threshold). DefaultQuiet = 5 * time.Minute + // DefaultSelfTestQuiet is how long it must be in the past before the + // self-test's own set runs: longer, because loading and benchmarking a + // model five minutes after the last request lands in an ordinary pause + // in use (iss-2610041956214381). + DefaultSelfTestQuiet = 4 * time.Hour // DefaultRetest is how long a model's result stands before it is measured // again. DefaultRetest = 24 * time.Hour @@ -239,6 +246,9 @@ type Options struct { Log *slog.Logger Tick, Quiet, Retest, Poll, RequestTimeout time.Duration + // SelfTestQuiet is the quiet period the self-test's own set waits for; + // Quiet is the one every job waits for. Zero means DefaultSelfTestQuiet. + SelfTestQuiet time.Duration // MaxBytes is the results file's cap; zero means DefaultMaxBytes. MaxBytes int64 // Jobs are the other kinds of run the loop schedules, asked in order at @@ -303,6 +313,9 @@ func New(opts Options) *Runner { if opts.Quiet <= 0 { opts.Quiet = DefaultQuiet } + if opts.SelfTestQuiet <= 0 { + opts.SelfTestQuiet = DefaultSelfTestQuiet + } if opts.Retest <= 0 { opts.Retest = DefaultRetest } @@ -376,8 +389,8 @@ func (r *Runner) Close() { r.file.close() } -// SetQuiet changes the idle threshold in force, so a saved setting applies -// to the next tick rather than the next start. +// SetQuiet changes the idle threshold the jobs wait for, so a saved setting +// applies to the next tick rather than the next start. func (r *Runner) SetQuiet(d time.Duration) { if d <= 0 { return @@ -387,6 +400,25 @@ func (r *Runner) SetQuiet(d time.Duration) { r.mu.Unlock() } +// SetSelfTestQuiet changes the idle threshold the self-test's own set waits +// for, the way SetQuiet does the jobs'. +func (r *Runner) SetSelfTestQuiet(d time.Duration) { + if d <= 0 { + return + } + r.mu.Lock() + r.opts.SelfTestQuiet = d + r.mu.Unlock() +} + +// Thresholds reports the idle thresholds in force: the one the jobs wait +// for, and the self-test's own. +func (r *Runner) Thresholds() (job, selfTest time.Duration) { + r.mu.Lock() + defer r.mu.Unlock() + return r.opts.Quiet, r.opts.SelfTestQuiet +} + // Status reports what the loop is doing. func (r *Runner) Status() Status { r.mu.Lock() @@ -516,7 +548,9 @@ func (r *Runner) tick(ctx context.Context) { return } r.roomFound(model) - if held := r.heldBy(act, now); held != "" { + // The self-test's own set waits for its own threshold, a job for the + // jobs' (iss-2610041956214381). + if held := r.heldBy(act, now, job == nil); held != "" { r.setStatus(func(st *Status) { st.HeldBy, st.Due = held, model }) return } @@ -568,8 +602,11 @@ func (r *Runner) roomFound(model string) { } // heldBy names what keeps a due run from starting, or "" when the Mac is -// idle. It is quiet's answer with its reason. -func (r *Runner) heldBy(act Activity, now time.Time) string { +// idle. It is quiet's answer with its reason. The quiet period is the +// self-test's own (SelfTestQuiet) for the self-test's set, and the jobs' +// (Quiet) for a job: one idea of what counts as use, two thresholds for how +// long ago it must have been. +func (r *Runner) heldBy(act Activity, now time.Time, selfTest bool) string { if act.Waiting > 0 { return HeldByWaiting } @@ -587,14 +624,18 @@ func (r *Runner) heldBy(act Activity, now time.Time) string { } r.mu.Lock() defer r.mu.Unlock() - if r.clientRecentLocked(act.LastRequest, now) { + wait := r.opts.Quiet + if selfTest { + wait = r.opts.SelfTestQuiet + } + if r.clientRecentLocked(act.LastRequest, now, wait) { return HeldByRecent } for _, m := range act.Models { if m.InFlight > 0 { return HeldByInFlight } - if m.LastUsed.IsZero() || now.Sub(m.LastUsed) >= r.opts.Quiet { + if m.LastUsed.IsZero() || now.Sub(m.LastUsed) >= wait { continue } if own, ok := r.touched[config.FoldRepoID(m.RepoID)]; ok && !m.LastUsed.After(own) { @@ -606,12 +647,12 @@ func (r *Runner) heldBy(act Activity, now time.Time) string { } // clientRecentLocked reports whether the gateway's last client request is -// within the quiet period. A last request no later than the loop's own most +// within the quiet period wait. A last request no later than the loop's own most // recent release is the loop's own — the context probe drives its model // through the gateway — and is discounted the way the pool's stamp of that // release is (touched). Callers hold r.mu. -func (r *Runner) clientRecentLocked(last, now time.Time) bool { - if last.IsZero() || now.Sub(last) >= r.opts.Quiet { +func (r *Runner) clientRecentLocked(last, now time.Time, wait time.Duration) bool { + if last.IsZero() || now.Sub(last) >= wait { return false } for _, own := range r.touched { @@ -626,8 +667,12 @@ func (r *Runner) clientRecentLocked(last, now time.Time) bool { // flight, nothing waiting, nothing downloading, and the last request older // than the quiet period — the last on any resident model and the last client // request the gateway counted, wherever it went. A model never used counts as -// long idle, and a last use that is the loop's own is not a request. -func (r *Runner) quiet(act Activity, now time.Time) bool { return r.heldBy(act, now) == "" } +// long idle, and a last use that is the loop's own is not a request. The +// quiet period is the self-test's own when selfTest is set, the jobs' +// otherwise. +func (r *Runner) quiet(act Activity, now time.Time, selfTest bool) bool { + return r.heldBy(act, now, selfTest) == "" +} // hold is what the loop itself has taken from the pool right now: the model, // how many acquisitions it holds on it (one for the single tests, the decode diff --git a/internal/selftest/selftest_test.go b/internal/selftest/selftest_test.go index 0f170cf8..aefea31b 100644 --- a/internal/selftest/selftest_test.go +++ b/internal/selftest/selftest_test.go @@ -223,7 +223,7 @@ func fastRunner(t *testing.T, srv Server, dir string) *Runner { Path: filepath.Join(dir, FileName), Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, - Quiet: time.Nanosecond, + Quiet: time.Nanosecond, SelfTestQuiet: time.Nanosecond, }) t.Cleanup(r.Close) return r @@ -312,7 +312,7 @@ func TestAQueuedJobWhoseModelDoesNotFitIsHeldRatherThanDropped(t *testing.T) { lines := &recordingHandler{} r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, SelfTestQuiet: time.Nanosecond, Jobs: []Job{job}, SelfTest: func() bool { return false }, Log: slog.New(lines), }) @@ -353,7 +353,7 @@ func TestAQueuedJobWithNoRoomIsReportedWhileAnotherModelIsMeasured(t *testing.T) lines := &recordingHandler{} r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, SelfTestQuiet: time.Nanosecond, // Measured again at once, so there is a run to go ahead on every tick. Retest: time.Millisecond, Jobs: []Job{job}, @@ -598,7 +598,7 @@ func TestNothingRunsWhileTheMacIsBusy(t *testing.T) { srv.mu.Unlock() r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, SelfTestQuiet: time.Hour, }) t.Cleanup(r.Close) r.SetEnabled(true) @@ -629,7 +629,7 @@ func TestAResultStandsForADayAndTheStalestModelGoesFirst(t *testing.T) { srv := newFakeServer(t, "org/a", "org/b", "org/c") r := New(Options{ Server: srv, Path: filepath.Join(dir, FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, SelfTestQuiet: time.Nanosecond, Retest: 24 * time.Hour, Now: func() time.Time { return now }, }) t.Cleanup(r.Close) @@ -961,7 +961,7 @@ func TestTheSelfTestsOwnRunDoesNotCountAsARecentRequest(t *testing.T) { srv.mu.Unlock() r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, SelfTestQuiet: time.Hour, }) t.Cleanup(r.Close) r.SetEnabled(true) @@ -994,7 +994,7 @@ func TestAJobsOwnGatewayRequestsDoNotCountAsARecentRequest(t *testing.T) { job := &gatewayJob{srv: srv} r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, SelfTestQuiet: time.Hour, Jobs: []Job{job}, SelfTest: func() bool { return false }, }) t.Cleanup(r.Close) @@ -1009,7 +1009,7 @@ func TestAClientRequestAfterARunHoldsTheNextTick(t *testing.T) { job := &gatewayJob{srv: srv} r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Hour, SelfTestQuiet: time.Hour, Jobs: []Job{job}, SelfTest: func() bool { return false }, }) t.Cleanup(r.Close) @@ -1237,7 +1237,7 @@ func TestInterruptEndsTheRunOnThatModelAsAYield(t *testing.T) { job := &blockingJob{due: "org/a", started: make(chan struct{}), ended: make(chan struct{})} r := New(Options{ Server: srv, Path: filepath.Join(t.TempDir(), FileName), - Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, Quiet: time.Nanosecond, SelfTestQuiet: time.Nanosecond, Jobs: []Job{job}, SelfTest: func() bool { return false }, Log: slog.New(slog.DiscardHandler), }) diff --git a/internal/selftest/threshold_test.go b/internal/selftest/threshold_test.go new file mode 100644 index 00000000..b1b8548e --- /dev/null +++ b/internal/selftest/threshold_test.go @@ -0,0 +1,94 @@ +package selftest + +import ( + "path/filepath" + "testing" + "time" +) + +// The self-test and the jobs wait for thresholds of their own +// (iss-2610041956214381). The self-test loads and benchmarks a model, which an +// ordinary pause in use should not set off, so it waits for SelfTestQuiet — +// four hours unless set — while a job such as the context probe keeps Quiet, +// the context probe's idle_threshold_sec. + +// tenMinutesQuiet is a server whose last client request ended ten minutes +// ago: past a five-minute threshold, well short of an hour's. +func tenMinutesQuiet(t *testing.T) *fakeServer { + t.Helper() + srv := newFakeServer(t, "org/a") + srv.mu.Lock() + srv.lastRequest = time.Now().Add(-10 * time.Minute) + srv.mu.Unlock() + return srv +} + +func TestTheSelfTestWaitsForItsOwnThreshold(t *testing.T) { + srv := tenMinutesQuiet(t) + r := New(Options{ + Server: srv, Path: filepath.Join(t.TempDir(), FileName), + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, + Quiet: 5 * time.Minute, SelfTestQuiet: time.Hour, + }) + t.Cleanup(r.Close) + r.SetEnabled(true) + waitFor(t, "the self-test to be held by the request ten minutes ago", func() bool { + return r.Status().HeldBy == HeldByRecent + }) + if acquired, _, _ := srv.snapshot(); len(acquired) != 0 { + t.Errorf("the self-test loaded %v ten minutes after a request, with its own threshold an hour", acquired) + } + + // Its own threshold moved, live, and the next tick runs. + r.SetSelfTestQuiet(time.Minute) + waitFor(t, "the self-test to run once its own threshold is a minute", func() bool { return len(runsIn(t, r)) == 1 }) +} + +func TestAJobWaitsForItsThresholdNotTheSelfTests(t *testing.T) { + srv := tenMinutesQuiet(t) + job := &gatewayJob{srv: srv} + r := New(Options{ + Server: srv, Path: filepath.Join(t.TempDir(), FileName), + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, + Quiet: 5 * time.Minute, SelfTestQuiet: time.Hour, + Jobs: []Job{job}, SelfTest: func() bool { return false }, + }) + t.Cleanup(r.Close) + r.SetEnabled(true) + waitFor(t, "the job to run on its own five-minute threshold despite the self-test's hour", func() bool { + return job.runs.Load() >= 1 + }) +} + +func TestTheSelfTestRunsOnItsOwnThresholdWhenTheJobsIsLonger(t *testing.T) { + srv := tenMinutesQuiet(t) + r := New(Options{ + Server: srv, Path: filepath.Join(t.TempDir(), FileName), + Tick: 5 * time.Millisecond, Poll: 2 * time.Millisecond, + Quiet: time.Hour, SelfTestQuiet: 5 * time.Minute, + }) + t.Cleanup(r.Close) + r.SetEnabled(true) + waitFor(t, "the self-test to run on its own five-minute threshold despite the jobs' hour", func() bool { + return len(runsIn(t, r)) == 1 + }) +} + +// Left unset, the self-test waits four hours and a job five minutes: the +// figures config.DefaultSelfTestIdleThresholdSec and +// config.DefaultIdleThresholdSec stand for. +func TestTheThresholdsDefaultToFourHoursAndFiveMinutes(t *testing.T) { + if DefaultSelfTestQuiet != 4*time.Hour { + t.Errorf("DefaultSelfTestQuiet = %v, want 4h", DefaultSelfTestQuiet) + } + r := New(Options{Server: newFakeServer(t), Path: filepath.Join(t.TempDir(), FileName)}) + job, self := r.Thresholds() + if job != DefaultQuiet || self != DefaultSelfTestQuiet { + t.Errorf("thresholds = %v for jobs, %v for the self-test; want %v and %v", job, self, DefaultQuiet, DefaultSelfTestQuiet) + } + r.SetQuiet(2 * time.Minute) + r.SetSelfTestQuiet(3 * time.Hour) + if job, self := r.Thresholds(); job != 2*time.Minute || self != 3*time.Hour { + t.Errorf("after setting each: %v for jobs, %v for the self-test; want 2m and 3h", job, self) + } +} diff --git a/internal/stats/released_test.go b/internal/stats/released_test.go index d0d2afd9..a62a4c03 100644 --- a/internal/stats/released_test.go +++ b/internal/stats/released_test.go @@ -36,3 +36,37 @@ func TestAReleaseRecordsTheKindOfCaller(t *testing.T) { t.Errorf("a release counted as %d evictions: only making room for another model is one", got) } } + +// The per-model counters the Statistics tab draws count each release by the +// kind of caller that asked, beside the evictions and apart from them, so the +// panel can show what Go records (iss-2610042100405045). +func TestTheCountersCountReleasesByKindOfCaller(t *testing.T) { + r := New(Options{}) + r.SetEnabled(true) + + r.Released("org/a", CallerThisMac) + r.Released("org/a", CallerThisMac) + r.Released("org/a", CallerPairedClient) + r.Released("org/a", "sk-a-key-in-the-wrong-place") + r.Removed("org/a", ReasonEvicted) + r.Removed("org/a", ReasonUnloaded) + + got := r.Summary()[0] + want := map[string]int{CallerThisMac: 2, CallerPairedClient: 1, "": 1} + if len(got.Released) != len(want) { + t.Fatalf("Released = %v, want %v", got.Released, want) + } + for k, n := range want { + if got.Released[k] != n { + t.Errorf("Released[%q] = %d, want %d", k, got.Released[k], n) + } + } + if got.Evictions != 1 { + t.Errorf("Evictions = %d, want the one eviction alone", got.Evictions) + } + // What Summary hands out is a copy: the caller cannot reach the counts. + got.Released[CallerThisMac] = 99 + if again := r.Summary()[0].Released[CallerThisMac]; again != 2 { + t.Errorf("a caller's write reached the recorder's counts: %d", again) + } +} diff --git a/internal/stats/stats.go b/internal/stats/stats.go index 78156083..2b7b593e 100644 --- a/internal/stats/stats.go +++ b/internal/stats/stats.go @@ -14,6 +14,7 @@ package stats import ( + "maps" "slices" "sync" "time" @@ -320,6 +321,12 @@ type ModelCounters struct { // out to make room for another. An idle reap, an operator's unload and a // crash are removals, not evictions. Evictions int `json:"evictions"` + // Released counts the times a program unloaded the model through the + // model API, by the kind of caller that asked: one of the Caller kinds, + // or "" for a kind this package does not know. A release is a removal, + // not an eviction, and is counted apart from Evictions so the Statistics + // tab can show both (iss-2610042100405045). + Released map[string]int `json:"released,omitempty"` // The last request's figures, which is what a reader comparing two // quantisations looks at first. LastFirstTokenMS int64 `json:"last_first_token_ms"` @@ -673,8 +680,7 @@ func (r *Recorder) Released(model, by string) { } func (r *Recorder) removed(ev Event) { - model, reason := ev.Model, ev.Reason - if !r.removedLocked(model, reason) { + if !r.removedLocked(ev.Model, ev.Reason, ev.By) { return } if r.store != nil { @@ -682,16 +688,21 @@ func (r *Recorder) removed(ev Event) { } } -func (r *Recorder) removedLocked(model, reason string) bool { +func (r *Recorder) removedLocked(model, reason, by string) bool { r.mu.Lock() defer r.mu.Unlock() if !r.enabled { return false } - if reason == ReasonEvicted { - r.modelLocked(model).Evictions++ - } else { - r.modelLocked(model) + m := r.modelLocked(model) + switch reason { + case ReasonEvicted: + m.Evictions++ + case ReasonReleased: + if m.Released == nil { + m.Released = map[string]int{} + } + m.Released[by]++ } return true } @@ -752,6 +763,7 @@ func (r *Recorder) summaryLocked() []ModelCounters { for k, v := range m.ByClass { c.ByClass[k] = v } + c.Released = maps.Clone(m.Released) out = append(out, c) } sortModels(out) diff --git a/internal/toolprobe/probe.go b/internal/toolprobe/probe.go index ed98d146..a32221a8 100644 --- a/internal/toolprobe/probe.go +++ b/internal/toolprobe/probe.go @@ -38,6 +38,7 @@ import ( "log/slog" "net/http" "sync" + "sync/atomic" "time" "github.com/intentdriven/Dessau/internal/config" @@ -133,6 +134,11 @@ type Options struct { // never loads one. var ErrGone = errors.New("the model is not loaded") +// ErrYielded is returned by Run when a client's request arrived on the model +// while the probe held it: the probe abandoned its request and let the model +// go rather than keep the client waiting, and recorded nothing. +var ErrYielded = errors.New("a client's request arrived on the model, so the probe let it go") + // Probe is the job and its queue. type Probe struct { opts Options @@ -146,6 +152,13 @@ type Probe struct { queue []string // running says the drain goroutine is up. running bool + // again says the model at the head was queued again after the last + // look its probe's outcome rests on (iss-2610032231045098): a load that + // finished while the attempt was under way, which that attempt cannot + // have seen. Enqueue sets it, serve clears it before each look at the + // model, and dequeue reads it, moving the head to the back rather than + // dropping it. One flag is enough because only the head is ever served. + again bool } // New builds a Probe. It starts nothing until the first Enqueue. @@ -175,8 +188,11 @@ func New(opts Options) *Probe { } // Enqueue queues one probe of the model and reports whether it was added: a -// model already queued, or in progress, is not queued again. The queue is -// drained one model at a time on the probe's own goroutine. +// model already queued, or in progress, is not queued again. A model in +// progress is still asked again once its probe is done, when the probe was +// already past its last look at the model: that probe cannot have seen the +// load being reported. The queue is drained one model at a time on the +// probe's own goroutine. func (p *Probe) Enqueue(repoID string) bool { p.mu.Lock() defer p.mu.Unlock() @@ -184,8 +200,11 @@ func (p *Probe) Enqueue(repoID string) bool { return false } key := config.FoldRepoID(repoID) - for _, q := range p.queue { + for i, q := range p.queue { if config.FoldRepoID(q) == key { + if i == 0 { + p.again = true + } return false } } @@ -246,6 +265,11 @@ func (p *Probe) drain() { func (p *Probe) serve(model string) (finished bool) { deadline := time.Now().Add(p.opts.MaxQuietWait) for { + // A load reported before this look is one the look sees: it asks + // for nothing more than the probe already under way. + p.mu.Lock() + p.again = false + p.mu.Unlock() loaded, inFlight := p.opts.Sources.Resident(model) if !loaded { p.opts.Log.Debug("tool-call probe dropped: the model is no longer loaded; it is queued again at its next serve", "model", model) @@ -269,6 +293,11 @@ func (p *Probe) serve(model string) (finished bool) { case err == nil, p.ctx.Err() != nil: case errors.Is(err, ErrGone): p.opts.Log.Debug("tool-call probe dropped: the model is no longer loaded; it is queued again at its next serve", "model", model) + case errors.Is(err, ErrYielded): + // A client wanted the model: the probe is asked again once the model + // falls quiet, after the models behind it have had their turn. + p.opts.Log.Debug("tool-call probe gave way to a client; it is tried again when the model falls quiet", "model", model) + return false default: // The server did not answer, or a client's load took the model // from under the probe: no evidence either way, and the model is @@ -283,6 +312,7 @@ func (p *Probe) serve(model string) (finished bool) { func (p *Probe) requeue(model string) { p.mu.Lock() defer p.mu.Unlock() + p.again = false key := config.FoldRepoID(model) for i, q := range p.queue { if config.FoldRepoID(q) == key { @@ -292,13 +322,22 @@ func (p *Probe) requeue(model string) { } } +// dequeue removes the finished model from the queue, unless it was queued +// again while its probe was past its last look (again): then it goes to the +// back, where that Enqueue would have put it. func (p *Probe) dequeue(model string) { p.mu.Lock() defer p.mu.Unlock() + again := p.again + p.again = false key := config.FoldRepoID(model) for i, q := range p.queue { if config.FoldRepoID(q) == key { - p.queue = append(p.queue[:i], p.queue[i+1:]...) + if again { + p.queue = append(append(p.queue[:i:i], p.queue[i+1:]...), q) + } else { + p.queue = append(p.queue[:i], p.queue[i+1:]...) + } return } } @@ -324,7 +363,38 @@ func (p *Probe) Run(ctx context.Context, model string) (*registry.ToolCalling, e return nil, err } defer release() + // A client's request on the model gets in ahead of the probe: the pool + // admits as many requests per model as it charges for, one by default, + // so a client arriving now would otherwise wait for the probe's whole + // answer. The pool counts a request in flight before it waits for a + // place, so anything beyond the probe's own hold is a client's, and the + // probe abandons its request and lets the model go, as the self-test's + // run does. + var yielded atomic.Bool + watching := make(chan struct{}) + defer close(watching) + go func() { + tick := time.NewTicker(p.opts.Poll) + defer tick.Stop() + for { + select { + case <-watching: + return + case <-runCtx.Done(): + return + case <-tick.C: + if _, inFlight := p.opts.Sources.Resident(model); inFlight > 1 { + yielded.Store(true) + preempt() + return + } + } + } + }() can, err := p.request(runCtx, up) + if yielded.Load() { + return nil, ErrYielded + } if err != nil { return nil, err } diff --git a/internal/toolprobe/probe_test.go b/internal/toolprobe/probe_test.go index d48ad747..20f1d9fd 100644 --- a/internal/toolprobe/probe_test.go +++ b/internal/toolprobe/probe_test.go @@ -37,6 +37,9 @@ type fakeSources struct { // lastYield is the yield the last acquisition carried, as the app's // adapter would hand it to the pool. lastYield func() + // beforeAcquire, when set, runs at the start of each Acquire, outside + // the lock; an error it returns is Acquire's answer. + beforeAcquire func(repoID string) error } func newSources(srv *mlxtest.Server) *fakeSources { @@ -53,6 +56,11 @@ func (s *fakeSources) Resident(repoID string) (bool, int) { } func (s *fakeSources) Acquire(ctx context.Context, repoID string) (Upstream, func(), error) { + if s.beforeAcquire != nil { + if err := s.beforeAcquire(repoID); err != nil { + return Upstream{}, nil, err + } + } s.mu.Lock() defer s.mu.Unlock() if !s.loaded { @@ -451,3 +459,81 @@ func TestAFailedSaveIsLoggedAsHeldForTheSession(t *testing.T) { t.Errorf("the log says the verdict was not recorded, which is not what happened:\n%s", out) } } + +// A load that lands while the head of the queue is being served is not lost +// (iss-2610032231045098). The pool refuses the probe's resident-only hold +// because another caller's load has the model; that load finishes and the +// observer queues the model again before the queue is done with its head. +// The Enqueue finds the model still queued, but the probe it asks for comes +// after the attempt that failed, so the model is probed again rather than +// dropped with the failed attempt. +func TestALoadDuringTheHeadsGoneProbeIsProbedAgain(t *testing.T) { + srv := mlxtest.Start(mlxtest.Options{ModelArg: "/models/org/m", ToolCall: true}) + t.Cleanup(srv.Close) + src := newSources(srv) + p := newProbe(t, src) + var once sync.Once + src.beforeAcquire = func(repoID string) error { + var err error + once.Do(func() { + // The other caller's load finishes and modelLoaded queues the + // model, before the pool's refusal reaches the queue. + p.Enqueue(repoID) + err = ErrGone + }) + return err + } + p.Enqueue("org/m") + waitFor(t, "the queue to drain", func() bool { return len(p.Queued()) == 0 }) + if src.verdict("org/m") == nil { + t.Fatal("the model was queued again while its gone probe was in progress, and was never probed") + } + if srv.Completions() != 1 { + t.Errorf("the probe sent %d requests, want exactly one", srv.Completions()) + } + if acquired, held := src.counts(); acquired != 1 || held != 0 { + t.Errorf("acquired %d times, holding %d; want one acquisition, released", acquired, held) + } +} + +// A client that arrives on the model while the probe holds it is not kept +// waiting behind the probe's request: the pool admits as many requests per +// model as it charges for, one by default, so the probe would otherwise make +// the client wait for its whole answer. The probe sees a request in flight +// beside its own hold, abandons its request and lets the model go, and the +// model stays queued to be asked again once it falls quiet. +func TestAClientArrivingDuringTheProbeIsNotKeptWaiting(t *testing.T) { + srv := mlxtest.Start(mlxtest.Options{ModelArg: "/models/org/m", ToolCall: true, ResponseDelay: 3 * time.Second}) + t.Cleanup(srv.Close) + src := newSources(srv) + p := newProbe(t, src) + + done := make(chan error, 1) + start := time.Now() + go func() { + _, err := p.Run(context.Background(), "org/m") + done <- err + }() + waitFor(t, "the probe to hold the model", func() bool { _, held := src.counts(); return held == 1 }) + src.mu.Lock() + src.inFlight = 2 // the probe's own hold and a client's request + src.mu.Unlock() + + select { + case err := <-done: + if !errors.Is(err, ErrYielded) { + t.Errorf("Run = %v, want ErrYielded", err) + } + if waited := time.Since(start); waited > 2*time.Second { + t.Errorf("the probe let the model go after %v; a client waited for its whole answer", waited) + } + case <-time.After(5 * time.Second): + t.Fatal("the probe never let the model go while a client waited") + } + if _, held := src.counts(); held != 0 { + t.Error("still holding the model after yielding to a client") + } + if saved := src.verdict("org/m"); saved != nil { + t.Errorf("a probe that yielded recorded %+v", saved) + } +} diff --git a/internal/ui/contextprobe_test.go b/internal/ui/contextprobe_test.go index 37174a68..ef441884 100644 --- a/internal/ui/contextprobe_test.go +++ b/internal/ui/contextprobe_test.go @@ -124,55 +124,80 @@ func TestTheIdleThresholdDefaultIsFilledFromTheServer(t *testing.T) { // told the operator five minutes anyway (iss-2609190201317726). // // All three now read the threshold in force — the setting where one is set and -// the default otherwise, which is config.EffectiveIdleThresholdSec on the Go -// side — and a panel that has not been told it names no figure at all. +// the default otherwise — and a panel that has not been told it names no +// figure at all. The self-test has a threshold of its own +// (iss-2610041956214381), so all three are prose about that one, +// config.EffectiveSelfTestIdleThresholdSec on the Go side, and none of them +// reads the context probe's idle_threshold_sec. func TestTheIdleThresholdInStatusProseIsFilledFromTheServer(t *testing.T) { page, err := assets.ReadFile("static/index.html") if err != nil { t.Fatal(err) } - literal := regexp.MustCompile(`\b` + strconv.Itoa(config.DefaultIdleThresholdSec) + `\b`) - for name, body := range map[string]string{"index.html": string(page), "app.js": readPanelSource(t)} { - if strings.Contains(body, "five minutes") { - t.Errorf("%s still spells the idle threshold out as \"five minutes\"; the figure is the "+ - "server's, off the snapshot, and a Mac serving another one must say so", name) + for _, def := range []struct { + name string + sec int + }{ + {"config.DefaultIdleThresholdSec", config.DefaultIdleThresholdSec}, + {"config.DefaultSelfTestIdleThresholdSec", config.DefaultSelfTestIdleThresholdSec}, + } { + literal := regexp.MustCompile(`\b` + strconv.Itoa(def.sec) + `\b`) + for name, body := range map[string]string{"index.html": string(page), "app.js": readPanelSource(t)} { + if loc := literal.FindStringIndex(body); loc != nil { + t.Errorf("%s writes %s out as a literal at byte %d; "+ + "the panel is told the figure and never holds a copy of it", name, def.name, loc[0]) + } } - if loc := literal.FindStringIndex(body); loc != nil { - t.Errorf("%s writes config.DefaultIdleThresholdSec out as a literal at byte %d; "+ - "the panel is told the figure and never holds a copy of it", name, loc[0]) + } + for name, body := range map[string]string{"index.html": string(page), "app.js": readPanelSource(t)} { + for _, spelled := range []string{"five minutes", "four hours"} { + if strings.Contains(body, spelled) { + t.Errorf("%s still spells an idle threshold out as %q; the figure is the "+ + "server's, off the snapshot, and a Mac serving another one must say so", name, spelled) + } } } - // The words the prose is written in: minutes for a whole number of them, - // seconds otherwise, and nothing at all for a figure nobody sent. + // The words the prose is written in: hours for a whole number of them, + // minutes for a whole number of those, seconds otherwise, and nothing at + // all for a figure nobody sent. words := func(expr string) string { v := evalPanelValue(t, "({text: "+expr+"})", "intervalWords") s, _ := v["text"].(string) return s } for expr, want := range map[string]string{ - "intervalWords(300)": "5 minutes", - "intervalWords(60)": "1 minute", - "intervalWords(90)": "90 seconds", - "intervalWords(0)": "", + "intervalWords(300)": "5 minutes", + "intervalWords(60)": "1 minute", + "intervalWords(90)": "90 seconds", + "intervalWords(5400)": "90 minutes", + "intervalWords(3600)": "1 hour", + "intervalWords(14400)": "4 hours", + "intervalWords(0)": "", } { if got := words(expr); got != want { t.Errorf("%s = %q, want %q", expr, got, want) } } - // The threshold in force: the setting where one is set, the default where - // it is not, and a phrase naming no figure where the panel knows neither. + // The self-test's threshold in force: its own setting where one is set, + // its own default where it is not, and a phrase naming no figure where the + // panel knows neither. The context probe's threshold is in every snapshot + // below, and none of the self-test's prose may read it. said := func(snapshot string) string { - v := evalPanelValue(t, "({text: idleThresholdWords("+snapshot+")})", "intervalWords", "idleThresholdWords") + v := evalPanelValue(t, "({text: selfTestIdleWords("+snapshot+")})", "intervalWords", "selfTestIdleWords") s, _ := v["text"].(string) return s } - if got := said(`{"config":{},"defaults":{"idle_threshold_sec":300}}`); got != "5 minutes" { - t.Errorf("with only a default served the prose says %q, want the default in words", got) + if got := said(`{"config":{"idle_threshold_sec":600},"defaults":{"idle_threshold_sec":300,"self_test_idle_threshold_sec":14400}}`); got != "4 hours" { + t.Errorf("with only the self-test's default served the prose says %q, want that default in words", got) + } + if got := said(`{"config":{"idle_threshold_sec":600,"self_test_idle_threshold_sec":7200},` + + `"defaults":{"idle_threshold_sec":300,"self_test_idle_threshold_sec":14400}}`); got != "2 hours" { + t.Errorf("with the self-test's threshold set the prose says %q, want the setting and not the default", got) } - if got := said(`{"config":{"idle_threshold_sec":600},"defaults":{"idle_threshold_sec":300}}`); got != "10 minutes" { - t.Errorf("with a threshold set the prose says %q, want the setting and not the default", got) + if got := said(`{"config":{"idle_threshold_sec":600},"defaults":{"idle_threshold_sec":300}}`); got == "" || strings.ContainsAny(got, "0123456789") { + t.Errorf("told only the probe's threshold the prose says %q, want a phrase carrying no figure", got) } if got := said(`{}`); got == "" || strings.ContainsAny(got, "0123456789") { t.Errorf("told no threshold the prose says %q, want a phrase carrying no figure", got) @@ -180,21 +205,32 @@ func TestTheIdleThresholdInStatusProseIsFilledFromTheServer(t *testing.T) { // The Self-test hint in the markup: a span the panel fills, not a figure // written into the page. - doc := evalPanelDOM(t, `renderIdleProse({"config":{"idle_threshold_sec":600},"defaults":{"idle_threshold_sec":300}});`, - "intervalWords", "idleThresholdWords", "renderIdleProse") - if got, _ := doc["selfTestIdleFigure"]["textContent"].(string); got != "10 minutes" { - t.Errorf("the Self-test hint's figure reads %q, want the threshold in force", got) + doc := evalPanelDOM(t, `renderIdleProse({"config":{"idle_threshold_sec":600,"self_test_idle_threshold_sec":7200},`+ + `"defaults":{"idle_threshold_sec":300,"self_test_idle_threshold_sec":14400}});`, + "intervalWords", "selfTestIdleWords", "renderIdleProse") + if got, _ := doc["selfTestIdleFigure"]["textContent"].(string); got != "2 hours" { + t.Errorf("the Self-test hint's figure reads %q, want the self-test's threshold in force", got) } if !strings.Contains(string(page), `id="selfTestIdleFigure"`) { t.Error("the Self-test hint carries no span for the threshold, so nothing can fill it from the snapshot") } // The posture page's self-test line. - line := evalPanelValue(t, `(postureLines({"config":{"self_test":true,"idle_threshold_sec":600},`+ - `"defaults":{"idle_threshold_sec":300},"bind":{},"endpoints":[]}).find((l) => l.id === "selftest"))`, - append(postureFunctions, "intervalWords")...) - if text, _ := line["text"].(string); !strings.Contains(text, "10 minutes") { - t.Errorf("the posture page's self-test line reads %q, want the threshold in force in it", text) + line := evalPanelValue(t, `(postureLines({"config":{"self_test":true,"idle_threshold_sec":600,"self_test_idle_threshold_sec":7200},`+ + `"defaults":{"idle_threshold_sec":300,"self_test_idle_threshold_sec":14400},"bind":{},"endpoints":[]}).find((l) => l.id === "selftest"))`, + postureFunctions...) + if text, _ := line["text"].(string); !strings.Contains(text, "2 hours") { + t.Errorf("the posture page's self-test line reads %q, want the self-test's threshold in force in it", text) + } + reads, _ := line["reads"].([]any) + for _, want := range []string{"config.self_test_idle_threshold_sec", "defaults.self_test_idle_threshold_sec"} { + found := false + for _, r := range reads { + found = found || r == want + } + if !found { + t.Errorf("the posture page's self-test line does not say it reads %s: %v", want, reads) + } } // The Self-test view's own hint, on and off. @@ -213,3 +249,20 @@ func TestTheIdleThresholdInStatusProseIsFilledFromTheServer(t *testing.T) { t.Errorf("the Self-test hint with the test off reads %q, and a test that is off runs at no interval", got) } } + +// The Idle threshold field spans exactly the server's bounds, a minute to a +// day (iss-2610041948272032). Narrower would wedge a stored value the panel +// cannot post back (TestNoSettingsControlIsNarrowerThanValidate); wider would +// offer a figure the save then refuses. +func TestTheIdleThresholdFieldSpansTheServersBounds(t *testing.T) { + tag := fieldTag(t, settingsPane(t, readPanelMarkup(t)), "setIdleThreshold") + if got, want := attr(tag, "min"), strconv.Itoa(config.MinIdleThresholdSec); got != want { + t.Errorf("setIdleThreshold has min=%q, want the server's %s", got, want) + } + if got, want := attr(tag, "max"), strconv.Itoa(config.MaxIdleThresholdSec); got != want { + t.Errorf("setIdleThreshold has max=%q, want the server's %s", got, want) + } + if got := attr(tag, "max"); got != "86400" { + t.Errorf("setIdleThreshold has max=%q, want 86400 (24 hours)", got) + } +} diff --git a/internal/ui/controls_test.go b/internal/ui/controls_test.go index ea495c9a..79339ed1 100644 --- a/internal/ui/controls_test.go +++ b/internal/ui/controls_test.go @@ -135,6 +135,7 @@ func numericSettingsControls() []settingsControl { {"setStatsMonths", true, func(c *config.Config, v float64) { c.StatsMonths = int(v) }}, {"setStatsMB", true, func(c *config.Config, v float64) { c.StatsMaxBytes = int64(v) * (1 << 20) }}, {"setIdleThreshold", true, func(c *config.Config, v float64) { c.IdleThresholdSec = int(v) }}, + {"setSelfTestIdleThreshold", true, func(c *config.Config, v float64) { c.SelfTestIdleThresholdSec = int(v) }}, {"setUpdateCheckInterval", true, func(c *config.Config, v float64) { c.UpdateCheckIntervalHours = int(v) }}, {"setTemp", false, func(c *config.Config, v float64) { c.Sampling.Temperature = &v }}, diff --git a/internal/ui/posture_test.go b/internal/ui/posture_test.go index c5afda00..92774979 100644 --- a/internal/ui/posture_test.go +++ b/internal/ui/posture_test.go @@ -44,7 +44,7 @@ const loopbackOnlyEdits = `{ "bind": {"mode":"","candidates":[],"mode_in_force":"","wildcard":false,"reaches_other_machines":false, "port":11535,"advertising":false}}` -var postureFunctions = []string{"endpointOf", "bytes", "advertising", "intervalWords", "postureLines"} +var postureFunctions = []string{"endpointOf", "bytes", "advertising", "intervalWords", "selfTestIdleWords", "postureLines"} // privateAddr is an address in the RFC 6598 shared range, which is the shape // the classifier marks as a private network; the snapshots below write PRIV diff --git a/internal/ui/selftest_test.go b/internal/ui/selftest_test.go index 0aa8f32d..cfb3f31c 100644 --- a/internal/ui/selftest_test.go +++ b/internal/ui/selftest_test.go @@ -1,8 +1,13 @@ package ui import ( + "fmt" "regexp" + "strconv" + "strings" "testing" + + "github.com/intentdriven/Dessau/internal/config" ) // The self-test switch is one setting on three surfaces — config.json, the @@ -22,6 +27,80 @@ func TestThePaneIsWiredToTheSelfTestSwitch(t *testing.T) { } } +// The self-test's own idle threshold is one setting on three surfaces too +// (iss-2610041956214381): config.json's self_test_idle_threshold_sec, the +// loop's SelfTestQuiet, and a field in the Self-test box — filled from the +// key, posted back under it, a blank field posting zero for the default, and +// an edit marking the form touched so the next snapshot does not overwrite it. +func TestThePaneIsWiredToTheSelfTestThreshold(t *testing.T) { + src := readPanelSource(t) + for _, want := range []*regexp.Regexp{ + regexp.MustCompile(`self_test_idle_threshold_sec:\s*parseInt\(\$\('setSelfTestIdleThreshold'\)\.value, 10\) \|\| 0`), + regexp.MustCompile(`\$\('setSelfTestIdleThreshold'\)\.value\s*=\s*c\.self_test_idle_threshold_sec \|\| ''`), + regexp.MustCompile(`\$\('setSelfTestIdleThreshold'\)\.addEventListener\('input', \(\) => \{ settingsTouched = true; \}\)`), + } { + if !want.MatchString(src) { + t.Errorf("the control panel no longer matches %s — that behavior is then asserted by nothing", want) + } + } +} + +// The field sits in the Self-test box, not beside the context probe's, and +// spans exactly the server's bounds — the same as the probe's threshold. +func TestTheSelfTestThresholdFieldIsInTheSelfTestBoxWithTheServersBounds(t *testing.T) { + pane := settingsPane(t, readPanelMarkup(t)) + start := strings.Index(pane, "Self-test") + if start < 0 { + t.Fatal("the Settings pane has no Self-test box") + } + box := pane[start:] + if end := strings.Index(box, ""); end >= 0 { + box = box[:end] + } + if !strings.Contains(box, `id="setSelfTestIdleThreshold"`) { + t.Fatal("the Self-test box carries no setSelfTestIdleThreshold field") + } + tag := fieldTag(t, box, "setSelfTestIdleThreshold") + if got := attr(tag, "type"); got != "number" { + t.Errorf("setSelfTestIdleThreshold is type=%q, want number", got) + } + if got, want := attr(tag, "min"), strconv.Itoa(config.MinIdleThresholdSec); got != want { + t.Errorf("setSelfTestIdleThreshold has min=%q, want the server's %s", got, want) + } + if got, want := attr(tag, "max"), strconv.Itoa(config.MaxIdleThresholdSec); got != want { + t.Errorf("setSelfTestIdleThreshold has max=%q, want the server's %s", got, want) + } + if !strings.Contains(box, `id="selfTestIdleThresholdDefault"`) { + t.Error("the Self-test box carries no span saying what a blank threshold is") + } +} + +// A blank field is the self-test's default, and the field and the sentence +// beside it say which figure that is from the snapshot, never from a copy. +func TestTheSelfTestThresholdDefaultIsFilledFromTheServer(t *testing.T) { + doc := evalPanelDOM(t, fmt.Sprintf(`renderDefaults({"idle_threshold_sec":%d,"self_test_idle_threshold_sec":%d});`, + config.DefaultIdleThresholdSec, config.DefaultSelfTestIdleThresholdSec), + "renderDefaults", "blankIsSentence", "intervalWords") + if got, _ := doc["setSelfTestIdleThreshold"]["placeholder"].(string); got != strconv.Itoa(config.DefaultSelfTestIdleThresholdSec) { + t.Errorf("setSelfTestIdleThreshold's placeholder is %q, want the server's default %d", + got, config.DefaultSelfTestIdleThresholdSec) + } + if said, _ := doc["selfTestIdleThresholdDefault"]["textContent"].(string); !strings.Contains(said, "Blank is 4 hours") { + t.Errorf("the prose beside the self-test's field reads %q, want it to name the server's default", said) + } + if got, _ := doc["setIdleThreshold"]["placeholder"].(string); got != strconv.Itoa(config.DefaultIdleThresholdSec) { + t.Errorf("setIdleThreshold's placeholder is %q, want the probe's own default %d", got, config.DefaultIdleThresholdSec) + } + + blank := evalPanelDOM(t, `renderDefaults({});`, "renderDefaults", "blankIsSentence", "intervalWords") + if got, _ := blank["setSelfTestIdleThreshold"]["placeholder"].(string); got != "" { + t.Errorf("setSelfTestIdleThreshold's placeholder is %q for a snapshot carrying no defaults, want it blank", got) + } + if got, _ := blank["selfTestIdleThresholdDefault"]["textContent"].(string); got != "" { + t.Errorf("the prose beside the self-test's field reads %q for a snapshot carrying no defaults, want nothing", got) + } +} + // The results reach the tab on the tab's own cadence, from the endpoint that // serves them, and every figure in a row is drawn from the run it names. func TestTheStatisticsTabShowsTheSelfTestResults(t *testing.T) { diff --git a/internal/ui/static/app.js b/internal/ui/static/app.js index 3cbdc811..6915688e 100644 --- a/internal/ui/static/app.js +++ b/internal/ui/static/app.js @@ -341,14 +341,19 @@ function graceWaitHint(graceValue, maxWaitValue, defaults) { + 'protection. Raise the maximum to at least the protection.'; } -// intervalWords puts an interval into words, in minutes where the figure is a -// whole number of them and in seconds otherwise — rounding 90 seconds to -// "1.5 minutes" would state a figure the server does not hold. Empty for an -// interval the panel was not told, so whatever is written from it says nothing -// rather than naming a figure nobody sent. +// intervalWords puts an interval into words, in hours where the figure is a +// whole number of them, in minutes where it is a whole number of those, and +// in seconds otherwise — rounding 90 seconds to "1.5 minutes" would state a +// figure the server does not hold. Empty for an interval the panel was not +// told, so whatever is written from it says nothing rather than naming a +// figure nobody sent. function intervalWords(sec) { if (!sec) return ''; if (sec % 60 !== 0) return `${sec} second${sec === 1 ? '' : 's'}`; + if (sec % 3600 === 0) { + const hours = sec / 3600; + return `${hours} hour${hours === 1 ? '' : 's'}`; + } const minutes = sec / 60; return `${minutes} minute${minutes === 1 ? '' : 's'}`; } @@ -361,25 +366,28 @@ function blankIsSentence(sec) { return words ? ` Blank is ${words}.` : ''; } -// idleThresholdWords is how long this Mac must have gone unasked before it -// counts as idle, in the words the status prose reads it in. It is the -// threshold in force — the setting where one is set, the server's default -// where it is not, which is config.EffectiveIdleThresholdSec on the Go side — -// and never a figure the panel holds a copy of (iss-2609190201317726). Told -// neither, it names the setting instead of a number: the sentences this goes -// into run on either side of it, so it cannot simply vanish the way the -// sentence beside the field does. -function idleThresholdWords(state) { +// selfTestIdleWords is how long this Mac must have gone unasked before the +// self-test counts it as idle, in the words the status prose reads it in. It +// is the self-test's own threshold in force — its setting where one is set, +// the server's default for it where it is not, which is +// config.EffectiveSelfTestIdleThresholdSec on the Go side — and never the +// context probe's, nor a figure the panel holds a copy of +// (iss-2609190201317726, iss-2610041956214381). Told neither, it names the +// setting instead of a number: the sentences this goes into run on either +// side of it, so it cannot simply vanish the way the sentence beside the +// field does. +function selfTestIdleWords(state) { const s = state || {}; const c = s.config || {}; const d = s.defaults || {}; - return intervalWords(c.idle_threshold_sec || d.idle_threshold_sec) || 'the idle threshold'; + return intervalWords(c.self_test_idle_threshold_sec || d.self_test_idle_threshold_sec) + || 'the self-test idle threshold'; } // renderIdleProse fills the figure in the Self-test hint, which is prose about // the threshold in force rather than a hint about what a blank field means. function renderIdleProse(state) { - $('selfTestIdleFigure').textContent = idleThresholdWords(state); + $('selfTestIdleFigure').textContent = selfTestIdleWords(state); } // renderDefaults says, on the settings fields themselves, what leaving one @@ -396,6 +404,9 @@ function renderDefaults(defaults) { $('setGraceWait').placeholder = d.eviction_max_wait_sec ? String(d.eviction_max_wait_sec) : ''; $('setIdleThreshold').placeholder = d.idle_threshold_sec ? String(d.idle_threshold_sec) : ''; $('idleThresholdDefault').textContent = blankIsSentence(d.idle_threshold_sec); + $('setSelfTestIdleThreshold').placeholder = d.self_test_idle_threshold_sec + ? String(d.self_test_idle_threshold_sec) : ''; + $('selfTestIdleThresholdDefault').textContent = blankIsSentence(d.self_test_idle_threshold_sec); $('setUpdateCheckInterval').placeholder = d.update_check_interval_hours ? String(d.update_check_interval_hours) : ''; // In hours, which is how the field is typed; blankIsSentence speaks in // seconds and minutes. @@ -471,6 +482,7 @@ function renderModels() { const tools = m.state === 'ready' ? toolCallText(m) : ''; const failed = m.state === 'ready' ? loadFailureText(m) : ''; const update = updateText(m); + const updateFiles = updateFilesText(m); const mark = updateMark(m); if (mark) pill += `${escapeHtml(mark)}`; @@ -482,6 +494,7 @@ function renderModels() { ${measured ? `
${escapeHtml(measured)}
` : ''} ${tools ? `
${escapeHtml(tools)}
` : ''} ${update ? `
${escapeHtml(update)}
` : ''} + ${updateFiles ? `
${escapeHtml(updateFiles)}
` : ''} ${m.updating != null ? `
` : ''} ${m.state === 'downloading' @@ -581,7 +594,6 @@ function updateText(m) { switch (u.status) { case 'available': return `A newer version is available (${short}).`; case 'runs_own_code': return `A newer version (${short}) ships its own code, which Dessau will not run, so it is not offered.`; - case 'awaiting_review': return `A newer version (${short}) exists and will be offered once a Dessau release has reviewed it.`; case 'cannot_check': return `A newer version (${short}) exists, but HuggingFace did not hand over its configuration in a form Dessau could verify, so Dessau could not tell whether it ships its own code and it is not offered.`; default: return ''; } @@ -595,12 +607,25 @@ function updateMark(m) { switch ((m.update || {}).status) { case 'available': return 'newer version'; case 'runs_own_code': return 'newer version not run'; - case 'awaiting_review': return 'newer version awaiting review'; case 'cannot_check': return 'newer version not checked'; default: return ''; } } +// updateFilesText names the files the newer version a check found changes, +// beside the line that says it exists: the names the check recorded, and how +// many more it changes. The names are HuggingFace's, so the card escapes the +// line like every other (iss-2610042101436222). Empty where no newer version +// is shown, or where the check could not tell which files changed. +function updateFilesText(m) { + if (updateMark(m) === '') return ''; + const u = m.update || {}; + const files = Array.isArray(u.files) ? u.files.map(String) : []; + if (files.length === 0) return ''; + const more = Math.max(0, Math.floor(Number(u.files_changed) || 0) - files.length); + return `Files it changes: ${files.join(', ')}${more ? ` and ${more} more` : ''}.`; +} + // updateOffered says whether the card carries Update: a ready model not // already updating, whose version was never recorded or that a check found a // newer version of that Dessau would run. @@ -1176,11 +1201,11 @@ function postureLines(state) { // The self-test loads models on its own while the Mac is idle, which is a // thing that can be on; the page says so from the setting, which applies - // the moment it is saved. The interval it names is the threshold in force, - // off the snapshot: the setting where one is set, the served default where - // it is not, and never a figure written into this page (iss-2609190201317726). - const idleFor = intervalWords(c.idle_threshold_sec || (state.defaults || {}).idle_threshold_sec) - || 'the idle threshold'; + // the moment it is saved. The interval it names is the self-test's own + // threshold in force, off the snapshot: its setting where one is set, the + // served default where it is not, and never a figure written into this page + // (iss-2609190201317726, iss-2610041956214381). + const idleFor = selfTestIdleWords(state); const selfTest = c.self_test ? `The self-test is on: while nothing has asked this Mac for a model for ${idleFor} and ` + 'nothing is downloading, Dessau loads one of its models at a time where it fits beside ' + @@ -1189,7 +1214,7 @@ function postureLines(state) { 'hold no prompt and no answer.' : 'The self-test is off: Dessau loads no model on its own.'; lines.push({ id: 'selftest', heading: 'Self-test', text: selfTest, - reads: ['config.self_test', 'config.idle_threshold_sec', 'defaults.idle_threshold_sec'] }); + reads: ['config.self_test', 'config.self_test_idle_threshold_sec', 'defaults.self_test_idle_threshold_sec'] }); return lines; } @@ -1461,6 +1486,7 @@ function renderSettings() { $('setUpdateCheck').checked = !!c.update_check_enabled; $('setUpdateCheckInterval').value = c.update_check_interval_hours || ''; $('setSelfTest').checked = !!c.self_test; + $('setSelfTestIdleThreshold').value = c.self_test_idle_threshold_sec || ''; $('setStats').checked = !!c.statistics; $('setStatsMonths').value = c.stats_months; // Typed in megabytes and stored in bytes, which is how every other size in @@ -2057,6 +2083,7 @@ $('setUpdateCheck').addEventListener('change', () => { settingsTouched = true; } $('setUpdateCheckInterval').addEventListener('input', () => { settingsTouched = true; }); $('setIdleThreshold').addEventListener('input', () => { settingsTouched = true; }); $('setSelfTest').addEventListener('change', () => { settingsTouched = true; }); +$('setSelfTestIdleThreshold').addEventListener('input', () => { settingsTouched = true; }); $('setStats').addEventListener('change', () => { settingsTouched = true; }); $('setGrace').addEventListener('change', () => { settingsTouched = true; }); $('setAdvertise').addEventListener('change', () => { settingsTouched = true; }); @@ -2191,6 +2218,8 @@ $('settingsForm').addEventListener('submit', async (e) => { // Blank posts zero, which the server reads as daily. update_check_interval_hours: parseInt($('setUpdateCheckInterval').value, 10) || 0, self_test: $('setSelfTest').checked, + // Blank posts zero, which the server reads as the self-test's default. + self_test_idle_threshold_sec: parseInt($('setSelfTestIdleThreshold').value, 10) || 0, statistics: $('setStats').checked, stats_months: parseInt($('setStatsMonths').value, 10) || 6, stats_max_bytes: (parseInt($('setStatsMB').value, 10) || 200) * 1024 * 1024, @@ -2309,7 +2338,7 @@ function selfTestHint(on, measured, idleFor) { function renderSelfTest(view) { const on = !!(view && view.enabled); const latest = (view && view.latest) || []; - $('selftestHint').textContent = selfTestHint(on, latest.length > 0, idleThresholdWords(state)); + $('selftestHint').textContent = selfTestHint(on, latest.length > 0, selfTestIdleWords(state)); $('selftestBody').hidden = latest.length === 0; const rows = $('selftestRows'); rows.replaceChildren(); @@ -2431,12 +2460,40 @@ function modelStatsCard(m) { m.loads ? `loaded ${m.loads}×` : null, m.failed_loads ? `${m.failed_loads} failed to load` : null, m.evictions ? `evicted ${m.evictions}×` : null, + releasedText(m.released) || null, m.last_load_ms ? `last load ${millis(m.last_load_ms)}` : null, ].filter(Boolean).join(' · '); return `
${escapeHtml(m.model || '—')}
` + `
${figures}
`; } +// releasedText says how many times programs unloaded a model through the model +// API, and which kinds of caller asked, from the counts Go keeps by kind +// (iss-2610042100405045). A release is a removal and not an eviction, so it +// stands beside the evictions rather than in them. The kinds are the +// recorder's fixed words, put in the panel's own; one it does not know is +// shown as that and never by its name. Empty when no program unloaded it. +function releasedText(released) { + const words = { + this_mac: 'on this Mac', + api_key: 'with the API key', + paired_client: 'by a paired client', + }; + const counts = new Map(); + let total = 0; + for (const [kind, raw] of Object.entries(released || {})) { + const n = Math.floor(Number(raw) || 0); + if (n <= 0) continue; + const said = Object.hasOwn(words, kind) ? words[kind] : 'by a caller of no recorded kind'; + counts.set(said, (counts.get(said) || 0) + n); + total += n; + } + if (total === 0) return ''; + const order = [...Object.values(words), 'by a caller of no recorded kind']; + const parts = order.filter((said) => counts.has(said)).map((said) => `${counts.get(said)} ${said}`); + return `unloaded by a program ${total}× (${parts.join(', ')})`; +} + // requestRow is the whole of one row of the request table: a pure function of // one record, so what a reader sees can be asserted without a DOM (see // stats_test.go). Every cell is a figure, a fixed outcome word, or the id of a diff --git a/internal/ui/static/index.html b/internal/ui/static/index.html index 442b1c6a..890ec3cb 100644 --- a/internal/ui/static/index.html +++ b/internal/ui/static/index.html @@ -521,10 +521,11 @@

Where this server stands

probe page says what the figure means and what it costs.

-

How long the last request must be in the past before the Mac counts as idle, - for the context probe and the self-test alike.

+

How long the last request must be in the past before the context probe + counts the Mac as idle: from 60 seconds to 86,400 seconds (24 hours). The self-test + has a threshold of its own, under Self-test.

@@ -546,6 +547,14 @@

Where this server stands

answer, and nothing in it leaves this Mac. The self-test page says what it costs and where the file is.

+ +

How long the last request must be in the past before the self-test counts + the Mac as idle: from 60 seconds to 86,400 seconds (24 hours). It is the self-test’s + own, apart from the context probe’s, so a model is measured only after a long quiet + spell rather than in an ordinary pause.

diff --git a/internal/ui/stats_test.go b/internal/ui/stats_test.go index b6e1fd9e..07ccbbfc 100644 --- a/internal/ui/stats_test.go +++ b/internal/ui/stats_test.go @@ -1,14 +1,57 @@ package ui import ( + "encoding/json" "fmt" "os" "reflect" "regexp" "strings" "testing" + + "github.com/intentdriven/Dessau/internal/stats" ) +// A model a program unloaded through the model API is shown on its card in the +// Statistics tab beside its evictions, with the kind of caller that asked, from +// the counters Go publishes (iss-2610042100405045). The card is drawn from +// stats.ModelCounters as the server marshals it, so a renamed field fails +// here rather than leaving the panel reading nothing. +func TestTheStatisticsCardShowsReleasesBesideEvictions(t *testing.T) { + card := func(m stats.ModelCounters) string { + t.Helper() + b, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + return evalPanel(t, "modelStatsCard("+string(b)+")", + "modelStatsCard", "releasedText", "generationRate", "millis") + } + got := card(stats.ModelCounters{ + Model: "org/a", Evictions: 2, + Released: map[string]int{stats.CallerThisMac: 2, stats.CallerAPIKey: 1, stats.CallerPairedClient: 1, "": 1}, + }) + want := "evicted 2× · unloaded by a program 5× (2 on this Mac, 1 with the API key, 1 by a paired client, 1 by a caller of no recorded kind)" + if !strings.Contains(got, want) { + t.Errorf("the card reads %q, want it to say %q", got, want) + } + if got := card(stats.ModelCounters{Model: "org/a", Evictions: 1}); strings.Contains(got, "unloaded by a program") { + t.Errorf("a model no program unloaded says one did: %q", got) + } + // Every kind of caller Go may record has words of its own on the card. + for _, kind := range stats.CallerKinds() { + got := card(stats.ModelCounters{Model: "org/a", Released: map[string]int{kind: 1}}) + if !strings.Contains(got, "unloaded by a program 1×") || strings.Contains(got, "no recorded kind") { + t.Errorf("the caller kind %q has no words on the card: %q", kind, got) + } + } + // A kind the panel does not know is shown as one, never by its name. + got = card(stats.ModelCounters{Model: "org/a", Released: map[string]int{"x": 1}}) + if strings.Contains(got, "") || !strings.Contains(got, "1 by a caller of no recorded kind") { + t.Errorf("an unknown caller kind reads %q", got) + } +} + // The request table's one piece of real logic is what each cell says, so it // lives in a pure function a test can lift out of app.js and evaluate. What is // asserted here is the row a reader actually sees. @@ -172,7 +215,7 @@ func TestEveryRecordedFigureReachesThePanel(t *testing.T) { for _, field := range []string{ "prompt_tokens", "completion_tokens", "first_token_ms", "duration_ms", "queue_wait_ms", "load_wait_ms", "streamed", "model", "class", "at", - "loads", "failed_loads", "evictions", "last_load_ms", + "loads", "failed_loads", "evictions", "released", "last_load_ms", "last_first_token_ms", "last_duration_ms", "last_completion_tokens", "by_class", "requests", "rollups", } { diff --git a/internal/ui/update_test.go b/internal/ui/update_test.go index e50b5e5d..efda49b4 100644 --- a/internal/ui/update_test.go +++ b/internal/ui/update_test.go @@ -1,15 +1,21 @@ package ui import ( + "encoding/json" "regexp" "strings" "testing" + + "github.com/intentdriven/Dessau/internal/registry" ) // The card says what the last check found, in words: a newer version, one -// Dessau will not run, one waiting for review, a version never recorded, and -// an update under way; and Update appears exactly where there is something -// Dessau would run to update to (itd-2610030857275099 criteria 4, 7, 8, 9). +// Dessau will not run, a version never recorded, and an update under way; and +// Update appears exactly where there is something Dessau would run to update +// to (itd-2610030857275099 criteria 4, 7, 8). A decision model is never +// marked: the 'awaiting review' mark criterion 9 gave one is withdrawn +// (iss-2610042101436891), so a record still carrying it shows nothing and +// offers no Update. func TestTheCardSaysWhatACheckFound(t *testing.T) { const c = `"commit":"1111111111111111111111111111111111111111"` cases := []struct { @@ -23,7 +29,7 @@ func TestTheCardSaysWhatACheckFound(t *testing.T) { {`{"state":"ready",` + c + `,"update":{"status":"runs_own_code","commit":"2222222222222222222222222222222222222222"}}`, `ships its own code, which Dessau will not run`, `newer version not run`, false}, {`{"state":"ready",` + c + `,"update":{"status":"awaiting_review","commit":"2222222222222222222222222222222222222222"}}`, - `will be offered once a Dessau release has reviewed it`, `newer version awaiting review`, false}, + ``, ``, false}, {`{"state":"ready",` + c + `,"update":{"status":"cannot_check","commit":"2222222222222222222222222222222222222222"}}`, `could not tell whether it ships its own code`, `newer version not checked`, false}, {`{"state":"ready"}`, `Version unknown`, ``, true}, @@ -56,6 +62,7 @@ func TestTheVersionLinesAreEscaped(t *testing.T) { for _, want := range []*regexp.Regexp{ regexp.MustCompile(`escapeHtml\(m\.repo_id\)`), regexp.MustCompile(`escapeHtml\(update\)`), + regexp.MustCompile(`escapeHtml\(updateFiles\)`), regexp.MustCompile(`escapeHtml\(mark\)`), regexp.MustCompile(`postModel\('/api/models/update', m\.repo_id\)`), regexp.MustCompile(`m\.updating != null\) \{\s*actions\.append\(btn\('Cancel update', 'ghost', \(\) =>\s*postModel\('/api/models/cancel', m\.repo_id\)`), @@ -107,3 +114,134 @@ func TestTheCardSaysWhyTheLastUpdateFailed(t *testing.T) { } } } + +// renderModelCard runs the panel's own renderModels over one model and +// returns the card's markup as a browser would parse it. escapeHtml is the +// panel's own, run against a node that escapes on the way out of innerHTML as +// a browser does once textContent was assigned; everything renderModels draws +// that is not about the model's version is stubbed to nothing, so a renderer +// that gains a helper fails here by name rather than passing unread. +func renderModelCard(t *testing.T, modelJSON string) string { + t.Helper() + src := readPanelSource(t) + var b strings.Builder + b.WriteString(` +const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +function node(tag) { + const n = { + tag, kids: [], _text: '', _raw: null, className: '', title: '', hidden: false, + append(...cs) { for (const c of cs) n.kids.push(c); }, + appendChild(c) { n.kids.push(c); return c; }, + addEventListener() {}, + querySelector() { if (!n._q) n._q = node('div'); return n._q; }, + get textContent() { return n._text; }, + set textContent(v) { n._text = String(v); n._raw = null; }, + get innerHTML() { return n._raw !== null ? n._raw : esc(n._text); }, + set innerHTML(v) { n._raw = v; n.kids = []; }, + }; + return n; +} +const doc = {}; +function $(id) { if (!doc[id]) doc[id] = node('div'); return doc[id]; } +const document = { createElement: node }; +const resourcesSummary = () => ({ text: '' }); +const waitingLine = () => ''; +const residencyLabel = () => ''; +const pinLabel = () => ''; +const debugArmedFor = () => false; +const transcriptPill = () => ''; +const sequencesInForce = () => 1; +const modelInfoLine = () => ''; +const measurementText = () => ''; +const toolCallText = () => ''; +const loadFailureText = () => ''; +const btn = (label) => { const b = node('button'); b.textContent = label; return b; }; +const confirmBtn = btn; +const postModel = () => ({ catch() {} }); +const postDebugLog = postModel; +const alertErr = () => {}; +`) + b.WriteString("const state = { models: [" + modelJSON + "] };\n") + for _, name := range []string{"escapeHtml", "renderModels", "updateText", "updateMark", "updateOffered", "updateFilesText"} { + b.WriteString(extractFunction(t, src, name)) + b.WriteString("\n") + } + b.WriteString(`renderModels(); +const card = doc['modelList'].kids[0]; +process.stdout.write(JSON.stringify({markup: card.innerHTML}));`) + var out struct { + Markup string `json:"markup"` + } + if err := json.Unmarshal([]byte(evalJS(t, b.String())), &out); err != nil { + t.Fatalf("the panel did not render a card: %v", err) + } + return out.Markup +} + +// The card names the files a newer version changes, and every name on it +// that came from HuggingFace — the repository and each file — appears as +// text, never as markup, however it is spelled (itd-2610030857275099 +// criterion 11; iss-2610042101436222). The registry admits plain names only, +// so this is the panel's own half of the guarantee, rendered rather than +// searched for. +func TestTheCardShowsHuggingFaceNamesAsText(t *testing.T) { + const evil = `` + // The model as Go publishes it, so the fields the card reads are the + // registry's own and not a spelling this test made up. + model, err := json.Marshal(registry.Model{ + RepoID: "org/" + evil, + State: registry.StateReady, + Commit: "1111111111111111111111111111111111111111", + Update: ®istry.UpdateCheck{ + Status: registry.UpdateAvailable, + Commit: "2222222222222222222222222222222222222222", + Files: []string{"config.json", evil + ".safetensors"}, + FilesChanged: 14, + }, + }) + if err != nil { + t.Fatal(err) + } + markup := renderModelCard(t, string(model)) + if strings.Contains(markup, "