Skip to content

studio: reap durable chat generation runs that stop making progress - #9997

Merged
danielhanchen merged 39 commits into
mainfrom
studio/reap-wedged-durable-generation-runs
Aug 31, 2026
Merged

danielhanchen merged 39 commits into
mainfrom
studio/reap-wedged-durable-generation-runs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

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=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.

The consequences chain from there:

  1. The stuck run keeps thread.isRunning true, so isRunActive stays 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.
  2. thread.isRunning unmounts the Send button entirely and substitutes "Queue message", so anything typed is queued client side and never submitted. That is why llama.cpp requests_deferred stayed 0 for the whole of both captures.
  3. On reload, toThreadMessage re-promoted the message to running from stale persisted metadata and history.load re-stamped generationSettled: false. The user reloaded the whole app twice and it changed nothing.
  4. The escape hatch was dead too. stopChatThread early returned because its registries are module state wiped by any reload, while isRunning is 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

  • Two additive columns on the run row, progress_at and progress_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_runs is generalised into reconcile_runs(error, stale_after_ms). The old entry point keeps its signature and return type.
  • ChatGenerationLeaseSweeper settles expired runs and cancels their producers. Its stop event is recreated on start, not cleared: asyncio.Event binds 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 that asyncio.wait reports 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 from ChatGenerationSupervisor.stop() before it settles runs, so the sweeper cannot mark a run stalled while shutdown is already marking it interrupted. Shutdown follows the existing asyncio.wait idiom, so a sweep parked in the database cannot make shutdown itself unbounded.
  • Default timeout 1200s, deliberately equal to _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.

  • The lifecycle gate. A run waiting on the process-wide gate is still queued and ages from created_at with 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.
  • Model preparation. Automatic switching, idle reload and auto-download all run between mark_running and 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 waits. A run queued behind another generation waits inside the streamed response, and that wait emits : admission-wait comments which _SSEDecoder drops. 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.
  • The client's own view of all three. The event stream stays open throughout and sends only keep-alive comments, which streamChatGenerationEvents used 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_progress also moves updated_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)

  • LlamaServerStatsLogger reports a held slot that is not calling llama_decode(). In both user logs this was 135 and 154 consecutive samples of running=1 waiting=0 gen_tok_s=0.0 prompt_tok_s=0.0, logged at info level and otherwise completely silent.
  • Liveness is n_decode_total, which increments on every llama_decode() call. It is deliberately not the token counters: tokens_predicted_total is written from callback_on_reset, so it only moves when the slot is released at the end of a generation, and prompt_tokens_total only 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.
  • The watchdog does not cancel anything. /metrics counters 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.py is byte identical to main.
  • A build that does not export n_decode_total is indistinguishable from a wedge, so that case reports engine_progress_unmeasurable once and says nothing further.

Frontend

  • A running status requires corroboration from the server active-run list, except for a completed-but-unsettled run, which is terminal and so never appears in that list but still owns an unreplayed tail. An uncorroborated run renders as interrupted with its partial text preserved.
  • A failed active-run read is unknown, not empty, per thread and per read. A failure retracts any earlier answer for that thread and drops its run mappings, since a stale mapping would restore the message as running while recovery refused to start a follower.
  • A stalled follower fences the run server-side before presenting the reply as resumable. Settling only in the tab leaves the row active, and create_run refuses 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 in cancelling, which is still active, and settling that is what the sweeper is for.
  • The follower surfaces its no-progress deadline as ChatGenerationStalledError rather 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 no incomplete at 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.
  • The checkpoint cap applies only to threads carrying an ADMITTED durable run. The claim taken before the create POST owns recovery, so a trigger inside that round trip cannot start a second follower, but it is provisional: admission retries transient failures until aborted, so it can outlast the cap, and a capped thread is dropped from the schedule for good. A subscriber-owned stream persists ONLY through those checkpoints, so capping one would lose whatever it streamed after the cap.
  • history.load does 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.
  • stopChatThread falls 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_at and a defaulted progress_tokens, so a rolled-back Studio can still insert. Rows written before the migration read NULL and fall back to COALESCE(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 unrelated no such column still surfaces. Live reaping is deferred until the migration lands. Sweeping on started_at/created_at is 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 no stale_after_ms and 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.

  • A large forward clock jump can reap a healthy run. Progress stamps are wall clock, because they outlive the process and a monotonic clock does not. Stepping BACKWARDS cannot age a run into the sweep, since both fields are monotonic, but a forward jump larger than the lease can. test_chat_generation_lease_compat.py pins this as a known limitation rather than leaving it implicit.
  • A preparation longer than the heartbeat bound is reaped. The bound is two hours, so a still-healthy load of roughly 2h20m can be declared interrupted. An unbounded heartbeat would keep a load that never returns alive forever, which is the failure this PR exists to end, so the bound is the point rather than an oversight.
  • A lease configured below the engine's own first-token budget will reap a legitimate prefill. The floor is the admission cadence, not the 20 minute first-token timeout, so a 60 second lease can settle a prefill the inference layer would still be waiting on. Opt-in only; the default is deliberately equal to that budget.
  • Two Studio processes of different versions sharing one studio.db are not lease-compatible. An older writer advances updated_at but cannot advance progress_at, so a newer process's sweep falls back to started_at/created_at and ages the run by its whole life. Single-process installs are unaffected.

Configuration

Variable Default Effect
UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S 1200 Idle time before a durable run is settled. 0 disables.
UNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_S 60 Sweep interval.

All 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() accepts inf and nan, and each disabled reaping in its own quiet way: inf only failed at int(timeout * 1000) inside the sweep, once per pass, while nan lost every comparison, so max(0.0, nan) returned 0.0 and the sweeper reported itself disabled.
| UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S | 600 | Held slot with no llama_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: nan loses 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 raises timestamp out of range for platform time_t as 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 -b and tsc -p tsconfig.test.json clean. stuck-generation-run.test.ts is new (34).

tests/chat-run-checkpoint-lifecycle.test.ts previously asserted that indefinite checkpointing was intentional. That justification was circular: isActive reports isRunning, and a run that never terminalises is exactly what holds isRunning true, 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.py determinism 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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-30T22:10:17.522862Z 10e73cd Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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 wrong

The watchdog treated "a slot is held and the token counters are not moving" as a wedge. That premise is false. Reading tools/server/server-context.cpp on master:

  • tokens_predicted_total is added in one lump by metrics_on_prediction, which is 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. 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 gen_tok_s=0.0 in the two user logs do not by themselves prove nothing was decoding. The wedge conclusion still holds, but it rests on the other evidence: no completion request ever finished, the checkpoint loop ran for the entire capture, requests_deferred stayed 0, and the PUT service time stayed flat, so the assistant message was not accumulating text.

What it does now

  • The signal is n_decode_total, which metrics_post_decode increments on every llama_decode() call. That is the thing that actually stops when the engine is wedged.
  • It only reports. Cancelling 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 at any threshold. The reaper and its wiring are gone, so llama_cpp.py is byte-identical to main again.
  • Threshold raised to 600s, event renamed to engine_no_decode_progress, and the message says plainly that a wedge and a long multimodal encode look the same here (the counter's own help text excludes speculative and multimodal decoding).

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 frontend

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 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

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, on every cell. Plus scrape robustness: CRLF bodies, labelled and scientific-notation samples, malformed values, non-UTF-8 bytes, a /metrics that disappears during a model swap, and clamping of bad env values.

test_chat_generation_lease_compat.py covers the upgrade and downgrade paths, since this adds columns to a table that already exists in the wild: 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, a run progressing for two simulated hours never being reaped, and clocks stepping both ways.

Compatibility

Old installs upgrade in place: two additive columns via ALTER TABLE, progress_tokens with a default and progress_at nullable, so a downgraded build that inserts without them still works. A missing table degrades to "migrate on a later call" rather than failing a history read.

No new browser baseline. The changed frontend files use AbortController, addEventListener with {once}, signal.reason and .at(), and the app already targets ES2022 with signal.reason in 4 other files and .at() in 26. Chrome, Firefox, Safari and Edge are unaffected, as are the Tauri webviews.

No GPU or hardware path is touched, and llama_cpp.py is now unchanged from main.

Backend suites for every touched area pass, and the frontend is 5990 passing with tsc -b clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 30, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

The GGUF inference smoke (API, tools, vision) failure on this PR is not caused by it.

The assertion is in .github/scripts/studio_smoke/multi_turn_chat.py: the four-turn conversation is run twice at temperature=0.0 with a fixed seed and the two runs must match. Turn 2 diverges:

run1: 'I am doing not have the ability to ask questions before.'
run2: 'I am doing not understand.'

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 30, 2026
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 30, 2026 15:15
…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 7370fa23b5

ℹ️ 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".

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.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 30, 2026
danielhanchen and others added 3 commits August 30, 2026 21:30
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.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 30, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1049 to +1054
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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 10e73cd8e9

ℹ️ 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".

@danielhanchen
danielhanchen merged commit c57e5fb into main Aug 31, 2026
57 of 59 checks passed
@danielhanchen
danielhanchen deleted the studio/reap-wedged-durable-generation-runs branch August 31, 2026 01:25
danielhanchen added a commit that referenced this pull request Aug 31, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant