Repository navigation
studio: reap durable chat generation runs that stop making progress - #9997
Conversation
A durable chat generation run that never reaches a terminal status leaves Studio permanently wedged: the thread stays "generating", the Send button is unmounted in favour of "Queue message", and nothing further is ever submitted to the engine. Reloading the browser does not clear it, because the stuck state lives in the run row and is re-projected into a running status on every load. Durable runs set cancel_on_disconnect=False on purpose, so a closed browser cannot kill a long generation. Nothing else bounded them: _produce had no wall clock, no heartbeat and no lease, and reconcile_orphaned_runs only ran once at process boot, so a run that wedged while Studio kept running was never repaired. Reaping is keyed on progress, never on connectedness. That keeps the durable behaviour (survive a dropped connection) and removes the failure mode (survive forever producing nothing). Backend: - Add a progress lease to the run row (progress_at, progress_tokens), renewed from the producer's existing token path. Monotonic, so a wall clock that steps backwards cannot age a live run into the sweep. - Generalise reconcile_orphaned_runs into reconcile_runs(error, stale_after_ms); the old entry point keeps its signature and return type. - Add ChatGenerationLeaseSweeper, which settles expired runs and cancels their producers. Settling the row alone would leave a producer parked in the engine still holding its slot. Shutdown follows the ChatGenerationSupervisor.stop() idiom, so a sweep parked in the database cannot make shutdown unbounded. - Default lease timeout 1200s, matching _DEFAULT_FIRST_TOKEN_TIMEOUT_S: the request path already refuses to wait longer than that for a first token, so an older lease cannot be legitimate prefill. Slow decode is safe at any speed. Engine stall watchdog: - LlamaServerStatsLogger now reports a held slot whose cumulative counters never advance, and cancels the generation holding it. Progress is measured on the counters, never on the rate gauges, because llama-server can keep reporting a stale nonzero predicted_tokens_seconds while decode is wedged. Prefill counts as progress, so a long prompt is never mistaken for a stall. - Only the oldest in-flight generation is cancelled, never cancel_all(): the counters are engine wide, so a freeze proves nothing is decoding, but Studio can also hold generations merely queued behind the wedge. - If /metrics does not expose the token counters, progress is unmeasurable and indistinguishable from a wedge, so the watchdog reports once and never reaps. Frontend: - A running status now requires corroboration from the server active run list. An uncorroborated run renders as interrupted with its partial text preserved. - Distinguish a failed active-run read from an empty one. - Bound the follow loop and the checkpoint scheduler, both of which could previously spin forever against a run that never terminalises. - stopChatThread falls back to the server when its module registries are empty, which is the state after any page reload. Env: UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S, UNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_S, UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S. Setting a timeout to 0 disables it.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Simulating the watchdog against llama.cpp's actual metric semantics showed the previous version would cancel healthy generations, so this replaces both the signal and the response. llama-server does not update the token counters while a generation is running: - tokens_predicted_total is added in one lump by metrics_on_prediction, called from callback_on_reset when the slot is released at the END of a generation. - prompt_tokens_total is only flushed by metrics_post_decode when a decode produced output, so it stays still for the whole of a multi-batch prefill. Both counters are therefore static throughout a healthy long prefill and a healthy long decode, which is exactly the signature the watchdog treated as a wedge. At the 5-6 tok/s the reporting user gets from DeepSeek-V4 on ROCm, any answer over roughly a thousand tokens would have been cancelled mid-flight. Changes: - Measure progress with n_decode_total, which metrics_post_decode increments on every llama_decode() call and is the thing that actually stops when the engine is wedged. Its help text excludes speculative and multimodal decoding, so a long image or audio encode can still look static. - Report only. Cancelling a generation on a scrape that cannot prove the engine will not resume, and cannot see which of several in-flight generations owns the slot, is not safe. Studio reaps a run that stops making progress from its own per-token event stream instead, where the signal is unambiguous. The reaper and its wiring are removed, so llama_cpp.py is unchanged from main again. - Raise the default threshold to 600s and rename the event to engine_no_decode_progress, whose message states that a wedge and a long multimodal encode look the same here. Frontend deadlines, same class of bug: - The follow deadline was 15 minutes while the backend allows 1200s for a first token and the lease sweeper needs another interval to settle a dead run. A prefill emits no events at all, so the client would have reported "interrupted" over a generation the server was still working on, on exactly the slow hardware that needs the long budget. Both it and the checkpoint cap are now 30 minutes, which keeps the server authoritative and still bounds the loop. - Treat "the server has not answered yet" as unknown rather than as "nothing is running". On a first load where the active-run read failed there is no previous answer to leave standing, and an empty map would have marked a live reply interrupted for anyone whose backend was briefly unreachable at page load. Tests: - test_llama_stats_platform_matrix.py walks [Windows, Linux, WSL, macOS] x [NVIDIA, ROCm, Vulkan, CPU] as metric payloads and asserts a healthy generation is never flagged and a real wedge always is, plus scrape robustness for CRLF bodies, labelled and scientific-notation samples, malformed values, non-UTF-8 bytes, and a /metrics that disappears during a model swap. - test_chat_generation_lease_compat.py covers upgrading over a database written by an older build, a rolled-back build inserting without the new columns, NULL progress_at falling back to started_at, a missing table, eight threads racing the migration, a lost ALTER, and clocks stepping both ways.
|
Simulating this against llama.cpp's actual metric semantics found a serious bug in the version I first pushed, so the watchdog half of this PR has changed shape. Flagging it here because the original description no longer describes what it does. What was wrongThe watchdog treated "a slot is held and the token counters are not moving" as a wedge. That premise is false. Reading
Both counters are therefore static throughout a healthy long prefill and a healthy long decode. That is exactly the signature the watchdog was cancelling on. At the 5-6 tok/s this reporter gets from DeepSeek-V4 on ROCm, any answer over roughly a thousand tokens would have been cancelled mid-flight, and the 180s default made it worse. This also softens one claim in the original description. The 135 and 154 samples of What it does now
The reaping is still done, correctly, by the progress lease, which reads Studio's own per-token event stream rather than an aggregate engine gauge. Same class of bug on the frontendThe follow deadline was 15 minutes while the backend allows 1200s for a first token and the lease sweeper needs another interval to settle a dead run. A prefill emits no events at all, so the client would have reported "interrupted" over a generation the server was still working on, on exactly the slow hardware that needs the long budget. Both that deadline and the checkpoint cap are now 30 minutes, which keeps the server authoritative and still bounds the loop. Separately, "the server has not answered yet" is now treated as unknown rather than as "nothing is running". On a first load where the active-run read failed there was no previous answer to leave standing, and an empty map would have marked a live reply interrupted for anyone whose backend was briefly unreachable at page load. Simulation coverage added
CompatibilityOld installs upgrade in place: two additive columns via No new browser baseline. The changed frontend files use No GPU or hardware path is touched, and Backend suites for every touched area pass, and the frontend is 5990 passing with |
Backend: - ChatGenerationLeaseSweeper.start() now clears the stop event. A second lifespan reuses the instance parked on app.state, and stop() left the event set, so the new task's first wait returned immediately and the sweeper was silently dead for that whole lifespan. Frontend: - followChatGenerationRun now surfaces a ChatGenerationStalledError instead of resolving as if the run had finished, so the caller can distinguish "the run ended" from "we stopped waiting for it". - The checkpoint scheduler's max-duration cap only applies to threads that actually carry a durable generation run. Plain runs are unbounded as before. - Recovery tracks which threads the server answered for, per thread, instead of a single global flag. One thread's answer no longer decides another's. - runtime-provider re-reads the active-run list when a loaded message names a run the first read missed, closing the gap between the two snapshots. Tests updated and extended for each of the above.
Frontend: - The corroboration gate now applies to unfinished runs only. list_active filters to queued/running/cancelling, so a completed-but-unsettled run could never be corroborated and its unreplayed tail was being dropped. Recovering it is safe: the run is terminal, so the follow returns on the first snapshot. - The recovery follower catches ChatGenerationStalledError and falls through to the same settlement it used to reach by returning. Without this the throw landed in the outer no-op handler and the message stayed marked running. - A failed second active-run read no longer records the stale first list as an answer. `missed` is exactly the proof that list predates the run. Backend: - The lease paths degrade when contention has blocked the progress-lease migration. _connect deliberately lets a call through so a history read cannot fail, which left every lease statement able to meet a table without the columns and abort a generation with `no such column` once the writer let go. _touch_progress_locked becomes a no-op, get_progress and reconcile_runs fall back to COALESCE(started_at, created_at), which is strictly more conservative than the lease. The match is on the column names, so an unrelated `no such column` still surfaces. Tests updated and extended for each of the above.
Backend: - Add touch_progress(run_id), which renews the lease without recording output, and call it once produce_openai_chat_completions returns. Automatic switching, idle reload and auto-download all run between mark_running and the first token, and llama.cpp's own first-token budget only starts after them, so ageing the run from mark_running could reap a legitimate load followed by a legitimate prefill. Frontend: - A follower that gives up locally stamps generationLocallyInterrupted, and both generationNeedsRecovery and generationIsCorroboratedLive refuse that run the benefit of the doubt. Without it the next online, pageshow or visibility trigger started another follower that republished the message as running. history.load clears the marker when /chat-runs/active still names the run, so the server keeps the last word. - A failed active-run refresh retracts this thread's earlier answer instead of leaving it standing, since another tab may have started a run since. - A run that reaches a terminal status leaves the server-active map, in both the recovery follower and the adapter. It used to linger until the next successful sync, which kept the thread reading as durable and capped a later subscriber-owned stream whose only persistence is those checkpoints. - The legacy-fallback branch releases the pre-admission claim itself rather than waiting for the outer finally, for the same reason. Tests updated and extended for each of the above.
|
The The assertion is in What I checked before saying so:
So the check is unstable on the merge base itself and happens to pass on main some of the time. Turn 1 is byte identical across both runs, which says the same model and quant is serving, so this is llama-server prompt cache reuse across the two passes rather than anything in either branch. Worth fixing separately: as written the check cannot distinguish a real determinism regression from this, which is the more expensive problem. I will raise that on its own rather than touch it here. |
Backend: - Renew the lease WHILE the model is being prepared, not only once preparation returns. A single preparation phase can outlast the lease on its own, a large GGUF over a slow link being the obvious case, and the sweeper would settle valid work mid-download. The heartbeat is cancelled the moment preparation returns, so it never overlaps streaming, and it is bounded: a preparation that never returns still ages out rather than being held alive forever, which is the failure this file exists to end. Frontend: - generationLocallyInterrupted applies only while the stored status is non-terminal. A run the backend went on to finish is stored completed and unsettled and still needs a replay to import its event tail, and /chat-runs/active excludes completed runs so it could never clear the marker for one. Honouring it there left the reply running forever with its tail never imported. - A failed INITIAL active-run read retracts this thread's earlier answer, not just a failed retry. Otherwise a stale answer stayed authoritative and a run another tab had started was restored as interrupted. Tests updated and extended for each of the above.
…ounded Two follow-ups from review. Leaving the admission queue is a transition, not a keep-alive, and the wait renewals are rate limited, so a run admitted just after one could enter its first-token window with a lease most of an interval old. The default lease equals the default first-token timeout deliberately, which leaves that difference as negative margin: a sweep landing in it settles a run whose prefill is still inside the engine's own budget. The admission-done comment now renews unconditionally, once per run. The pre-admission claim is taken before the create POST so a recovery trigger during that await cannot start a second follower. It also made the thread bounded, which is a different question: until the POST lands there is no server-side run, so the thread's checkpoints are still its only persistence. createChatGenerationRun retries transient failures until aborted, so that await can outlast the 30 minute cap, and a capped thread is dropped from the schedule for good, leaving a legacy fallback stream with no periodic persistence at all. The claim is now provisional and only the post-admission claim marks the thread bounded. generation-recovery-own-run.test.ts pinned the claim as a single-line literal, which the options object breaks. Its matcher is updated rather than its intent, and it now also pins that the pre-admission claim is provisional.
…dence Two more overflow paths, both measured on this platform rather than assumed. I had said the stats settings needed no clamp because nothing converts them to integer milliseconds. That was wrong: threading.Event .wait() turns its timeout into an absolute deadline, and 1e10 seconds raises OverflowError, timestamp out of range for platform time_t, the moment the wait is entered. That kills the poll thread and takes the engine stats and the stall report with it. A century still waits and 1e10 does not, so the cap is a year, well below the boundary. The lease floor reads the admission keep-alive cadence from a parser that is not ours and only checks the value is positive, so inf reached it intact and made the applied lease infinite. The sweeper then raised on int(timeout * 1000) every pass and reaped nothing. An oversized finite cadence stretched the lease past any horizon instead. Both now fall back to the shipped default with a warning, while a merely slow cadence still raises the floor as before.
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Trims the explanatory comments this branch added back toward the density of the surrounding code, which the review rounds had pushed well past. Comments only: the three Python files are AST-identical and the TypeScript diff contains no non-comment lines. Kept the rationale that is not recoverable from the code, in particular why the sweeper's stop event is recreated rather than cleared, why the watchdog keys on n_decode_total and not the token counters, and why the migration fallback to started_at is the aggressive choice rather than the conservative one.
Found by running the shutdown path rather than reasoning about it. A sweep parked on SQLite's writer lock made stop() spend its whole ten second grace and then left the interpreter alive: asyncio.to_thread runs on non-daemon executor threads that an atexit hook joins, so abandoning the asyncio task does not abandon the work. Measured: stop() returned after 10.01s and the process then had to be killed (exit 124). Studio Desktop allows five seconds for a graceful backend exit before force-killing, and stops the backend this way before it updates, so this was a user-visible hang on the update path. The sweep now runs on a daemon thread the sweeper owns, and its shutdown budget is 0.5s rather than the producers' ten: letting a sweep finish at shutdown buys nothing, because the boot reconcile settles every active run anyway. Same measurement after: 0.50s and a clean exit. The regression test asserts the PROCESS exits, in a subprocess, because a stop() that returns proves nothing here.
The Windows CI leg caught this: a one year cap waits fine on Linux, whose threading.TIMEOUT_MAX is about 9.2e9 seconds, and raises OverflowError on Windows, where the timeout becomes a DWORD of milliseconds and the ceiling is 49.7 days. The clamp meant to stop an oversized interval killing the poll thread was itself oversized there. The cap is now a week bounded by threading.TIMEOUT_MAX, so it is correct by construction rather than by a constant I picked. The test asserts the Windows ceiling on every platform as well as waiting on the value, so Linux can no longer pass a cap Windows would reject.
…epalives The frontend deadline was unreachable in the one case it exists for. The events route emits a keep-alive every 15s for as long as there are no events, and the follower rearmed on any byte, so a wedged producer with a healthy socket rearmed it forever. With the sweeper disabled, failed to start, or unable to reach the database, nothing would have settled that run. The keep-alive now carries the run's progress stamp, which the lease renewals move, and the follower rearms only when it changes. A long model preparation still holds the follow open, because its heartbeat is what moves the stamp; a wedge no longer does. Comment framing is unchanged, so _SSEDecoder still drops it and no client that parses events is affected. The existing test asserted the old rule with BARE keep-alives. Its intent was right and is kept, now with an advancing stamp, and the missing half is added: a frozen stamp must NOT hold the follower open. That one pumps keep-alives continuously while waiting, because stopping them lets the deadline fire on its own and the first version of the test passed against the unfixed code.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4eb80548e1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const reader = response.body.getReader(); | ||
| const decoder = new TextDecoder(); | ||
| let buffer = ""; | ||
| let lastKeepAliveStamp: string | null = null; |
There was a problem hiding this comment.
Preserve the keepalive stamp across SSE reconnects
When a proxy or unstable LAN reconnects this SSE stream, streamChatGenerationEvents is invoked again and resets lastKeepAliveStamp to null, so the first keepalive on every new connection calls onActivity even if its progress stamp is unchanged. If reconnects occur more frequently than the 30-minute deadline—especially when the backend sweeper is disabled or unavailable—a genuinely wedged run can therefore rearm the follower indefinitely. Keep the last observed stamp in followChatGenerationRun so it survives stream reconnections.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and it is the same defect one level up from the one I just fixed. Fixed in 10e73cd.
lastKeepAliveStamp was a local in streamChatGenerationEvents, which followChatGenerationRun re-invokes on every reconnect, so the memory reset each time and the first keep-alive of every connection counted as progress.
The stream now reports the stamp rather than judging it, onActivity?.(stamp), and the follower holds the last value and decides, because the follower is the only thing that spans reconnects. Events still call it with no argument and are unconditional progress.
New test drives the real path: each connection sends one keep-alive with the same frozen stamp and then EOF, so the follower goes round the reconnect loop repeatedly inside a single 2.5s deadline, and it asserts more than one connection actually happened. Against the unfixed code it hangs until its 20s bound rather than settling.
| if (followStalled || generationNeedsRecovery(currentMetadata)) { | ||
| // The follow returned with the run still non-terminal, so its no-progress | ||
| // deadline expired. Settle the reply here rather than leaving a message that | ||
| // says "running" until the next reload, which is what keeps Send unmounted. | ||
| // Everything replayed so far is kept, and the Continue bar can resume it. | ||
| await commit( |
There was a problem hiding this comment.
Do not expose Continue while the server run remains active
When the client deadline is the only mechanism that fires—for example with UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S=0 or an unavailable sweeper—this marks the reply interrupted and restores the composer without terminalizing or fencing the server run. The old row remains in an active status, so pressing Continue or sending another message reaches create_run and gets the thread's active-generation conflict; a cooperative cancel alone may also remain stuck in cancelling if the producer is wedged. The stalled path needs a server operation that settles/fences the run, or it must not present the reply as resumable until the server reports a terminal state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 10e73cd. I checked the conflict rather than assuming it: create_run runs SELECT 1 FROM chat_generation_runs WHERE thread_id=? AND status IN ('queued','running','cancelling') and raises This thread already has an active generation, so settling only in this tab really would have left Continue and the next message both 409ing against a reply the UI had just declared finished.
The run is now fenced with serverCancel() before the reply is presented as resumable, and the test pins the ordering rather than merely the presence of the call.
I want to be explicit about the residual, because your last sentence is right and the fix does not fully close it: a cooperative cancel moves the row to cancelling, which is still an active status, and a producer wedged inside the engine will sit there. Settling that is exactly what the server-side sweeper does, and this whole path is reachable mainly when the sweeper is disabled or cannot reach the database. So the client can no longer contradict itself in the common case, and the genuinely wedged case still needs the server. I did not want to overstate it as fully solved.
…ed run Two consequences of the previous commit. The stamp lived in the per-connection generator, which is re-invoked on every reconnect, so the first keep-alive after each one counted as progress even when the stamp had not moved. Behind a proxy that reconnects more often than the deadline, a wedged run rearmed the follower forever. The stream now reports the stamp and the follower decides, because only the follower spans reconnects. Settling a stalled reply in this tab left the row queued, running or cancelling, and create_run refuses a thread that already has an active generation, so Continue and the next message both 409 against a reply the UI had just declared finished. The run is now fenced before the reply is presented as resumable. Best effort, and not sufficient alone: a producer wedged inside the engine stays in cancelling, which is still active, and settling that is what the server-side sweeper is for. The reconnect test drives several real reconnections inside one deadline; against the unfixed code it hangs until its 20s bound.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
test_event_batch_flushes_while_upstream_is_idle slept 0.2s and then asserted the two chunks were durable. The flush it waits on costs _EVENT_BATCH_SECONDS plus a thread hop and a SQLite write, which measures 0.104s to 0.128s over twelve runs on a completely idle machine, so the assertion had under 2x headroom before it ever reached a loaded runner. It lost that race on a Backend tests lane where the other 35,482 tests passed. Neither of the two commits that shaped this loop is at fault. #9187 wrote the test with the margin it has, and the producer loop #9997 later touched only adds work on admission markers, which this stream never emits. So the production behaviour is right and the test was measuring it wrongly. It now polls until the events land, in the same idiom the sibling replay test already uses, bounded by the midpoint between the batch and single-event flush intervals and reading both from the module so the bound tracks the code. That raises the margin from under 2x to roughly 5x while staying strictly below the single-event timer, so the test still fails if these two events ever fall onto that slower path. Confirmed by mutation: raising _EVENT_BATCH_MIN_SIZE to 3, which drops the pair onto the 1.0s timer, and deleting the idle flush outright both still fail. The file passes 24/24, and the test passes 40/40 pinned to one CPU shared with six busy loops. Co-authored-by: danielhanchen <[email protected]>
Summary
A user reported the Studio UI freezing, and separately that it "kept disconnecting over LAN". Two server logs, 23 and 26 minutes long, show the same failure. Neither contains a single error level line and every request returns HTTP 200, which is why nothing looked wrong.
The freeze is a durable chat generation run that never reaches a terminal status.
Durable runs set
cancel_on_disconnect=Falseon purpose, so a closed browser cannot kill a long generation. Nothing else bounded them._producehad no wall clock, no heartbeat and no lease, andreconcile_orphaned_runsonly ran once at process boot, so a run that wedged while Studio kept running was never repaired.The consequences chain from there:
thread.isRunningtrue, soisRunActivestays true, so the 8s checkpoint scheduler reschedules forever. That is the 160 and 188 identical four request cycles in the two logs, at the 8-9s period its trailing reschedule produces.thread.isRunningunmounts the Send button entirely and substitutes "Queue message", so anything typed is queued client side and never submitted. That is why llama.cpprequests_deferredstayed 0 for the whole of both captures.toThreadMessagere-promoted the message to running from stale persisted metadata andhistory.loadre-stampedgenerationSettled: false. The user reloaded the whole app twice and it changed nothing.stopChatThreadearly returned because its registries are module state wiped by any reload, whileisRunningis rebuilt from persisted metadata. The UI said "running" and the stop path said "nothing to stop".Reaping is keyed on progress, never on connectedness. That keeps the durable behaviour (survive a dropped connection) and removes the failure mode (survive forever producing nothing).
Changes
Progress lease on durable runs
progress_atandprogress_tokens, renewed from the producer's existing token path. Monotonic in both fields, so a wall clock that steps backwards cannot age a live run into the sweep.reconcile_orphaned_runsis generalised intoreconcile_runs(error, stale_after_ms). The old entry point keeps its signature and return type.ChatGenerationLeaseSweepersettles expired runs and cancels their producers. Its stop event is recreated on start, not cleared:asyncio.Eventbinds to the loop that first awaits it, and a second lifespan can be a second loop, which would otherwise leave the new task's wait raising "bound to a different event loop". That failure is silent, because the error lands on an inner waiter thatasyncio.waitreports merely as done. Settling the row alone would leave a producer parked in the engine still holding its slot and activity reservation. Started from the lifespan, stopped fromChatGenerationSupervisor.stop()before it settles runs, so the sweeper cannot mark a run stalled while shutdown is already marking it interrupted. Shutdown follows the existingasyncio.waitidiom, so a sweep parked in the database cannot make shutdown itself unbounded._DEFAULT_FIRST_TOKEN_TIMEOUT_S. Slow decode is safe at any speed: at 5 tok/s the lease renews about once a second.Shutdown
The sweep runs on a daemon thread this module owns rather than through
asyncio.to_thread, whose executor threads are not daemons and are joined by an atexit hook: abandoning the asyncio task did not abandon the work, so a sweep parked on SQLite's writer lock kept the interpreter alive after shutdown had given up on it. Measured on the real classes,stop()returned after 10.01s and the process then had to be killed; it now returns in 0.50s and the process exits. Studio Desktop allows five seconds for a graceful backend exit before force-killing, and stops the backend this way before it updates, so that hang was reachable from the update path.The sweeper's own shutdown budget is 0.5s rather than the producers' ten. Letting a sweep finish at shutdown buys nothing, because the boot reconcile settles every active run regardless. The regression test runs a subprocess and asserts the process exits: a
stop()that returns proves nothing here.Work the lease cannot see
Three phases produce no streamed output and would otherwise age a healthy run out.
queuedand ages fromcreated_atwith nothing renewing it, and a preview swap on the other side can hold it for a long time. The heartbeat is an async context manager opened before the gate wait, so an early return between the gate and the produce call cancels it as reliably as the normal path.mark_runningand the first token, and the engine's own first-token budget only starts after them. The same heartbeat covers this, and is cancelled the moment preparation returns so it never overlaps streaming. Bounded by total time, because an unbounded heartbeat would keep a load that never returns alive forever, which is the failure this PR exists to end.: admission-waitcomments which_SSEDecoderdrops. Bytes on the wire now renew the lease. Leaving the queue renews too, and unconditionally: the wait renewals are rate limited, and the default lease equals the default first-token timeout, so a lease carried into the prefill window most of an interval old is negative margin.streamChatGenerationEventsused to drop without yielding, so the follower's loop never advanced and the snapshot poll after it never ran. Those comments now carry the run's progress stamp, which the lease renewals move, and the follower rearms only when it changes. The last stamp is held by the follower rather than the stream, because the stream is re-invoked on every reconnect and a per-connection memory would treat the first keep-alive after each reconnect as progress. Bytes alone are deliberately not progress: the route emits a keep-alive every wait timeout for as long as the socket holds, so rearming on arrival would leave the follower's deadline unreachable on a wedged run, which is the one case it exists for.touch_progressalso movesupdated_at, which the snapshot poll compares, but that is the weaker of the two signals: it is only reachable once the stream closes, and a stream that stays open is exactly the case needing cover.Renewal cadence derives from the configured lease rather than a constant. Both are configurable, and a fixed interval longer than a lease set below it means the first renewal arrives after the sweep has already settled the run. Every renewal that is not streamed output goes through one tolerant path, so a history transaction holding SQLite's writer lock past the busy timeout costs one interval rather than the generation.
Engine stall watchdog (reports only)
LlamaServerStatsLoggerreports a held slot that is not callingllama_decode(). In both user logs this was 135 and 154 consecutive samples ofrunning=1 waiting=0 gen_tok_s=0.0 prompt_tok_s=0.0, logged at info level and otherwise completely silent.n_decode_total, which increments on everyllama_decode()call. It is deliberately not the token counters:tokens_predicted_totalis written fromcallback_on_reset, so it only moves when the slot is released at the end of a generation, andprompt_tokens_totalonly flushes on a decode that produced output. Both are static through healthy prefill and healthy decode, so keying on them would have killed any answer over roughly a thousand tokens at the reporter's 5-6 tok/s./metricscounters are process wide, so they cannot name the run holding the slot, and a static counter does not prove the work will not resume.llama_cpp.pyis byte identical tomain.n_decode_totalis indistinguishable from a wedge, so that case reportsengine_progress_unmeasurableonce and says nothing further.Frontend
create_runrefuses a thread that already has an active generation, so Continue and the next message would both conflict with a reply the UI had just declared finished. Best effort, and not sufficient alone: a producer wedged inside the engine stays incancelling, which is still active, and settling that is what the sweeper is for.ChatGenerationStalledErrorrather than resolving as if the run had finished, and both callers catch it and settle the reply: the recovery follower and the adapter's own follower for the first stream of a turn. Both persist the interruption marker, since metadata that still reads running and unsettled would have the next reload attach another follower and block the composer for another full deadline, and both set the interrupted incomplete reason, without which the final yield writes noincompleteat all and a partial reply reads as finished until a reload rebuilds the reason. A locally interrupted run is marked so it cannot be revived on the next visibility trigger, and only the server naming it live clears that.history.loaddoes not overlay an active-run row onto a message whose stored status is already terminal. A run that finished between the runs read and the messages read is still listed as running while the message snapshot has its terminal status, so the overlay pushed a completed reply back to running and blocked the composer.stopChatThreadfalls back to the server when its module registries are empty, which is the state after any page reload.Compatibility
The two columns are additive with a nullable
progress_atand a defaultedprogress_tokens, so a rolled-back Studio can still insert. Rows written before the migration readNULLand fall back toCOALESCE(started_at, created_at)rather than being treated as infinitely old or infinitely fresh.If contention blocks the migration entirely, the lease paths degrade instead of failing a generation with
no such column, and the match is on the column names so an unrelatedno such columnstill surfaces. Live reaping is deferred until the migration lands. Sweeping onstarted_at/created_atis not a conservative substitute for the lease, it is the opposite: those stamps are older by the whole life of the run, so a run that streamed a chunk moments ago would be reaped once its total age passed the timeout. Boot reconcile is unaffected, since it passes nostale_after_msand every active run is orphaned by definition at process start.Known limitations
Stated because the lease is a wall-clock mechanism and these follow from that, not from a defect.
test_chat_generation_lease_compat.pypins this as a known limitation rather than leaving it implicit.studio.dbare not lease-compatible. An older writer advancesupdated_atbut cannot advanceprogress_at, so a newer process's sweep falls back tostarted_at/created_atand ages the run by its whole life. Single-process installs are unaffected.Configuration
UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_SUNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_SAll three are parsed the same way. A value that is not a finite number falls back to its default with one warning, and a finite value too large to convert to integer milliseconds is clamped to a century with one warning.
float()acceptsinfandnan, and each disabled reaping in its own quiet way:infonly failed atint(timeout * 1000)inside the sweep, once per pass, whilenanlost every comparison, somax(0.0, nan)returned0.0and the sweeper reported itself disabled.|
UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S| 600 | Held slot with nollama_decode()call before the watchdog logs. 0 disables. |The engine stats settings are parsed the same way and reject non-finite values for the same reason:
nanloses every comparison so the stall line never arms. Oversized finite values are clamped there too, for a different reason than the lease:threading.Event.wait()turns its timeout into an absolute deadline, and one far enough out raisestimestamp out of range for platform time_tas soon as the wait is entered, killing the poll thread. The admission keep-alive cadence is validated before the lease floor is derived from it, since that value is parsed elsewhere by a check that only requires it to be positive, and infinity is positive.Testing
Backend, new:
test_chat_generation_run_lease.py(30),test_chat_generation_lease_compat.py(47),test_llama_stats_stall.py(24),test_llama_stats_platform_matrix.py(52, the[Windows, Linux, WSL, Mac] x [NVIDIA, AMD, CPU]product plus scrape robustness).These cover lease renewal, the backwards clock case, partial output preserved through a reap, a slow but progressing run surviving 30 minutes of sweeps, a run wedged before its first token, long prefill not being mistaken for a stall, unmeasurable counters silencing the watchdog rather than reaping, a preparation twice the lease surviving, a bounded heartbeat still ageing out a load that never returns, one contended write not costing a run its lease, upgrade and downgrade across the migration, and a migration blocked by a writer degrading rather than failing, and a non-finite lease setting falling back rather than leaving runs unreaped, an oversized finite one being clamped rather than overflowing every sweep, and the renewal cadence pacing off the lease actually in force rather than the raw setting.
Frontend: 6012 pass,
tsc -bandtsc -p tsconfig.test.jsonclean.stuck-generation-run.test.tsis new (34).tests/chat-run-checkpoint-lifecycle.test.tspreviously asserted that indefinite checkpointing was intentional. That justification was circular:isActivereportsisRunning, and a run that never terminalises is exactly what holdsisRunningtrue, so the probe and the scheduler agreed forever. The test is rewritten deliberately, keeping its original body as the first half so an absent probe still cannot end a live run early.Cross-platform CI was run on owned staging repos rather than the org queue: ubuntu-latest, macos-15 and windows-latest all pass, plus a Playwright leg.
The
multi_turn_chat.pydeterminism check fails on this branch. It also fails on the merge base with zero changes, on two unrelated PRs, and on both Linux and macOS while Windows passes. Tracked separately in #10004; it is not caused by this PR.