Skip to content

Studio: force-terminate a stuck training stop after a grace period - #7099

Merged
danielhanchen merged 11 commits into
mainfrom
fix/studio-training-stop-watchdog
Jul 15, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix/studio-training-stop-watchdog

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Stopping a training run with save could hang forever. A Stop-with-save only sends
a stop signal to the training subprocess and then waits for the subprocess to save
the model and exit on its own. The only force-kill path, force_terminate(), was
reachable exclusively from /reset and only when the user chose Cancel (save=False,
_cancel_requested=True). A normal Stop-with-save therefore had no force-kill
fallback.

On Windows + AMD ROCm this surfaces as a stuck run: the subprocess saves the
adapter files successfully but then wedges during post-save GPU/HIP context
teardown in the driver and never exits (unkillable even by taskkill /F until the
driver times out). The run is stuck in "Stopping..." indefinitely, is_training
stays true, and the user cannot recover because /reset returns HTTP 409 for a
non-cancel active run.

Changes

  • Add a stop watchdog (daemon thread) started when a stop is requested. It
    guarantees the run finalizes in bounded time by escalating to force_terminate()
    if the subprocess does not exit on its own, without ever killing a legitimate
    in-progress save prematurely.
    • Primary trigger: once the worker sends complete (which happens after
      trainer.save_model finishes), the save is done, so the watchdog
      force-terminates after a short grace period if the subprocess is still alive.
    • Absolute cap is a last-resort backstop only. For a save=True stop it is long,
      so a slow save (large model, network disk) is never killed mid-write; a
      not-yet-complete save is not treated as a hang before that long window. For a
      cancel (save=False) there is nothing to save, so the backstop is shorter. When
      the backstop fires with no completion signal it logs a clear warning.
  • After escalation the parent state is finalized regardless of whether the OS
    actually reaped the wedged process: is_training=False and status
    "Training stopped.", so the UI leaves "Stopping..." and the user can start a new
    run. Finalization runs even if force_terminate() raises on a wedged child
    (try/except/finally), and the saved output_dir is preserved so run history still
    records the checkpoint path. The wedged handle is dropped; it is a daemon bound to
    the parent lifetime.
  • The watchdog tracks the worker it watches: a new run always gets its own watcher,
    termination targets only the captured handle, and a superseded worker is never
    touched, so a stale watchdog can never kill a fresh run.
  • Configurable timeouts, read in the existing _env_int style:
    • UNSLOTH_STUDIO_TRAINING_STOP_GRACE_S (default 15)
    • UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S (default 600, save backstop)
    • UNSLOTH_STUDIO_TRAINING_CANCEL_TIMEOUT_S (default 120, cancel backstop)
  • Unit tests (fakes only, no GPU/subprocess) covering: escalation after the grace
    period once complete is seen; a save still saving (no complete) is not killed
    within the long window and the backstop only fires past it; cancel uses the
    shorter cap; no force-kill on a clean quick exit; finalize runs even when
    force_terminate raises; output_dir is preserved on finalize; a new run gets
    its own watcher; and termination targets only the captured process.

Notes

  • Platform-agnostic: a worker that exits cleanly and promptly is a no-op (no
    force-kill, no log), so Linux and macOS behavior is unchanged. The watchdog only
    fires when a requested stop fails to exit on its own.
  • The deeper layer-2 issue (the ROCm/HIP post-save teardown hang itself) is a
    separate problem and is out of scope here; this change bounds the recovery so the
    run always finalizes and the UI never gets stuck in "Stopping...".

danielhanchen and others added 2 commits July 13, 2026 00:44
A Stop-with-save only signals the worker and waits for it to save and exit;
force_terminate() was reachable only from the /reset cancel path. On Windows +
ROCm the worker saves the adapter fine but then wedges in post-save GPU/HIP
teardown and never exits, so the run stays in "Stopping..." forever, is_training
stays true, and /reset returns 409.

Add a stop watchdog: when a stop is requested, a daemon escalates to
force_terminate() a short grace after the worker's "complete" (save done), or
after an absolute cap covering a hang during save. After escalation the parent
state is finalized (is_training=False, "Training stopped.") even if the OS never
reaps the wedged worker, so the UI leaves "Stopping..." and a new run can start.
No behavior change on a clean quick exit. Grace and timeout are configurable via
UNSLOTH_STUDIO_TRAINING_STOP_GRACE_S (15) and
UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S (120).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a stop-watchdog mechanism to force-terminate training workers that hang during post-save teardown, ensuring parent state finalization and UI updates. It also adds comprehensive unit tests covering various watchdog scenarios. The review feedback suggests increasing the default absolute timeout from 120 to 600 seconds to accommodate large model checkpoint saves on slower storage, and naming the background watchdog thread to improve debuggability.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

# is seen, plus an absolute cap covering a hang during save. Guards against a wedged
# post-save GPU/driver teardown that never exits.
_STOP_GRACE_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_GRACE_S", 15)
_STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S", 120)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

For larger models (e.g., 30B or 70B parameters) or environments with slower disk I/O (such as network-attached storage or slower cloud VM disks), saving a checkpoint can easily take more than 2 minutes (120 seconds). If the absolute timeout is triggered while a legitimate save is still in progress, the watchdog will prematurely force-terminate the worker, leading to corrupted checkpoints and loss of training progress.

Increasing the default absolute timeout to a safer value (e.g., 600 seconds / 10 minutes) ensures that large model saves are not interrupted, while still providing a reliable fallback for genuine hangs.

Suggested change
_STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S", 120)
_STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S", 600)

Comment on lines +992 to +994
watchdog = threading.Thread(target = self._stop_watchdog_loop, args = (proc,), daemon = True)
self._stop_watchdog = watchdog
watchdog.start()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

It is highly recommended to explicitly name background threads. In a complex backend with multiple concurrent tasks, unnamed threads make thread dumps and debugging of potential thread leaks or deadlocks extremely difficult.

Naming the thread with the current job ID will greatly improve maintainability and debuggability.

Suggested change
watchdog = threading.Thread(target = self._stop_watchdog_loop, args = (proc,), daemon = True)
self._stop_watchdog = watchdog
watchdog.start()
watchdog = threading.Thread(
target = self._stop_watchdog_loop,
args = (proc,),
name = f"stop-watchdog-{self.current_job_id or 'unknown'}",
daemon = True,
)

@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: 6870afa67b

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

if complete_at is not None and now - complete_at >= _STOP_GRACE_S:
reason = "worker still alive after save"
break
if now - started >= _STOP_TIMEOUT_S:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid terminating legitimate saves on timeout

When Stop is requested with save=True, this absolute timeout starts immediately and fires even when _complete_seen is still unset. The worker only emits complete after the save returns (for example, the MLX path sends it after trainer.save_model(output_dir) and the embedding path after save_pretrained), so a large/full-model save or slow/network output directory that legitimately takes more than 120s will be killed mid-save and can leave the user without a usable checkpoint. Please gate pre-complete force-kill separately for cancel/no-save, make it opt-in, or otherwise avoid terminating an in-progress save by default.

Useful? React with 👍 / 👎.

if superseded or not target_proc.is_alive():
return
logger.warning("Stop watchdog force-terminating stuck training worker: %s", reason)
self.force_terminate()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Finalize even if force termination fails

In the Windows/ROCm stuck-stop case this is meant to recover from, force_terminate() can raise while re-issuing kill() against an already-terminating but still-alive child process. Because this call is not protected, the watchdog thread exits before _finalize_stopped_after_escalation() runs, so the parent can still remain in the stuck stopping state the watchdog was added to clear. Please run the finalization in a finally path or catch termination failures before finalizing parent state.

Useful? React with 👍 / 👎.

self._progress.status_message = "Training stopped."
self._proc = None
self._ensure_db_run_created()
self._finalize_run_in_db(status = "stopped")

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 output_dir when watchdog finalizes

When a stop-with-save has already emitted complete, _output_dir contains the saved checkpoint directory, but this watchdog finalization records the run without passing it. If the pump thread is still blocked in its DB/metric finalization and this watchdog path wins the _run_finalized race, the later pump finalization with output_dir is skipped, leaving run history without the saved output path and breaking resume/discovery for that stopped run. Pass the saved self._output_dir here when finalizing.

Useful? React with 👍 / 👎.

Comment on lines +987 to +988
if self._stop_watchdog is not None and self._stop_watchdog.is_alive():
return

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 Start a fresh watchdog for a new run

If a previous watchdog is still alive while a new run is already active, such as when the old stopped worker exited and the stale watchdog is still in its sleep before noticing it was superseded, a Stop on the new run returns here without creating a watcher. The stale watchdog then exits because self._proc no longer matches its target, leaving the new run without the force-terminate fallback and able to get stuck in Stopping again. Track the watched process and only suppress starting when the existing watchdog is watching the current worker.

Useful? React with 👍 / 👎.

if superseded or not target_proc.is_alive():
return
logger.warning("Stop watchdog force-terminating stuck training worker: %s", reason)
self.force_terminate()

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 Terminate only the process the watchdog checked

There is a race between the final liveness/superseded check and calling force_terminate(): if the watched process exits naturally and an automated client immediately starts another run in that window, force_terminate() acts on the current self._proc handle and can kill the new run instead of the stale one. Make the termination target-specific or revalidate/claim the same process under the lock used by the terminate call.

Useful? React with 👍 / 👎.

Address review feedback so a stop can never corrupt a checkpoint or leave the
run stuck:

- Never force-kill an in-progress save. The absolute cap is now a last-resort
  backstop: raise the save default to 600s and only kill past that long window;
  a not-yet-complete save is not treated as a hang. Cancels have nothing to save,
  so they keep a shorter 120s cap via UNSLOTH_STUDIO_TRAINING_CANCEL_TIMEOUT_S.
  The save vs cancel path is now explicit and the backstop logs a clear warning.
- Always finalize even if force_terminate raises on a wedged child (try/finally),
  so the watchdog never dies leaving the run in "Stopping...".
- Preserve output_dir when the watchdog finalizes so a saved checkpoint is still
  recorded in run history.
- Track the watched process per watchdog: a new run always gets its own watcher,
  and a stale watchdog on an old proc no longer suppresses it.
- Terminate only the captured proc; force_terminate revalidates under the lock
  that it is still the current worker, so it can never kill a fresh run.
- Name the watchdog thread for debuggability.
@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up in d055d53 addresses the review feedback:

  • The absolute timeout is now a last-resort backstop rather than a mid-save killer. UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S default is raised to 600s for a save=True stop (a not-yet-complete save is never treated as a hang before that window, and the backstop logs a loud warning if it ever fires), while a cancel (save=False) uses a shorter 120s cap via the new UNSLOTH_STUDIO_TRAINING_CANCEL_TIMEOUT_S. Save vs cancel is now explicit.
  • Finalization always runs: force_terminate() is wrapped in try/except/finally, so a raising kill on a wedged child never leaves the run stuck in "Stopping".
  • output_dir is preserved when the watchdog finalizes, so a saved checkpoint stays recorded in run history.
  • A new run always gets its own watchdog (the watcher tracks the exact process it watches), and force_terminate revalidates the captured handle under the lock and no-ops if a new run has replaced it, so it can never kill a fresh worker.
  • The watchdog thread is named stop-watchdog-{job_id}.

Tests extended to 12, covering the long save window, the cancel cap, finalize-on-raise, output_dir preservation, the per-run watcher, and target-specific termination.

@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: d055d5328d

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

except Exception:
logger.exception("Stop watchdog: force_terminate failed; finalizing anyway")
finally:
self._finalize_stopped_after_escalation()

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 Guard watchdog finalization against new runs

If the watched worker exits or is killed and /start installs a new _proc after the watchdog’s final superseded check but before this finally runs, force_terminate(target_proc=...) correctly no-ops, but _finalize_stopped_after_escalation() still unconditionally clears self._proc and finalizes current_job_id. That can mark the newly started run stopped and orphan its worker; fresh evidence beyond the earlier target-specific kill concern is that finalization is still not target-scoped.

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.

Fixed in e827a8c by the same change as the P1 above. force_terminate was already target-scoped; the escalation finalize is now target-scoped too (guarded on the captured proc) plus job-scoped (expected_job_id), so it no longer clears _proc or finalizes current_job_id for a run that superseded the watched worker.

Comment-only pass: collapse the watchdog docstrings and inline notes to fewer
lines while keeping the rationale. No behavior change.
@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: 3243f18f44

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

and self._stop_watchdog.is_alive()
and self._stop_watchdog_proc is proc
):
return

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 Honor later cancel requests in the watchdog

When a user first requests a normal stop with save=True and then sends a cancel (save=False) while the same worker is still alive, this early return keeps the original watchdog that captured cancel=False. The worker remains governed by _STOP_TIMEOUT_S (600s by default) instead of the shorter cancel cap, so a run that is already in the “Stopping...” state can still stay wedged for up to the save timeout even after the user explicitly cancels.

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.

Fixed in e827a8c. The watchdog now re-reads _cancel_requested each iteration and recomputes the cap, so a later Stop(save=False) tightens an in-flight save watchdog from the 600s save backstop to the shorter cancel cap instead of waiting out the full save timeout. Added test_later_cancel_tightens_watchdog_timeout.

Comment on lines +1057 to +1061
with self._lock:
self._progress.is_training = False
self._progress.status_message = "Training stopped."
output_dir = self._output_dir
self._proc = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard watchdog finalization against newer runs

If the watchdog finishes killing an old worker while a new /start is racing in, the start path can replace self._proc and current_job_id once the old process is no longer alive because _should_stop makes the backend look inactive. This finalizer then unconditionally clears _proc and finalizes the current job, so a freshly spawned training run can lose its process handle and be marked stopped by the old watchdog. Re-check the captured process/job before mutating shared state here.

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.

Fixed in e827a8c. _finalize_stopped_after_escalation now takes the watched proc, captures the job id under the lock, and no-ops the whole finalize (handle, progress, and the DB finalize) when self._proc has been replaced by a new run. The DB finalize is also guarded by expected_job_id, so a stale watchdog can neither null a fresh run's _proc nor mark its job stopped.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a stop-watchdog escalation mechanism to prevent training runs from getting stuck in the "Stopping..." state if the worker process wedges during teardown. It adds timeouts, a watchdog thread loop, and state finalization, along with comprehensive unit tests. The review feedback highlights a potential concurrency race condition between the watchdog and pump threads during finalization, suggests starting the watchdog thread outside of the lock block to reduce lock contention, and recommends using getattr in force_terminate to defensively handle partially-constructed objects.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +1053 to +1063
def _finalize_stopped_after_escalation(self) -> None:
"""Finalize parent state after a force-terminate so the UI leaves "Stopping..."
even if the worker is wedged in driver teardown. Dropping the handle is safe
(daemon bound to parent). Preserves output_dir so a saved checkpoint is kept."""
with self._lock:
self._progress.is_training = False
self._progress.status_message = "Training stopped."
output_dir = self._output_dir
self._proc = None
self._ensure_db_run_created()
self._finalize_run_in_db(status = "stopped", output_dir = output_dir)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Concurrency Race Condition between Watchdog and Pump Threads

There is a potential race condition when _finalize_stopped_after_escalation is called by the watchdog thread while the pump thread (_pump_loop) is also finalizing the run after the worker process exits.

Root Cause:

  1. _ensure_db_run_created: The check and update of self._db_run_created are performed outside of self._lock. If both threads execute this concurrently, both can see self._db_run_created as False and attempt to call create_run() with the same job_id, resulting in a sqlite3.IntegrityError.
  2. _finalize_run_in_db: Similarly, self._run_finalized is checked and set outside of self._lock. Both threads can concurrently proceed to finalize the run.
  3. _flush_metrics_to_db: Inside _flush_metrics_to_db, self._metric_buffer is copied (list(self._metric_buffer)) and sliced (del self._metric_buffer[: len(batch)]) without holding self._lock. Concurrent execution of this method will lead to list corruption, duplicate metric inserts, or silent deletion of unflushed metrics.

Recommended Fix:

To make these operations thread-safe, we should synchronize the state checks and mutations using self._lock.

  1. In _ensure_db_run_created:
def _ensure_db_run_created(self) -> None:
    with self._lock:
        if self._db_run_created or not self.current_job_id or not self._db_config:
            return
        self._db_run_created = True
    
    try:
        from storage.studio_db import create_run
        # ... (rest of the method)
    except Exception:
        with self._lock:
            self._db_run_created = False
        logger.warning("Failed to create DB run record for early failure", exc_info=True)
  1. In _finalize_run_in_db:
def _finalize_run_in_db(self, status: str, ...) -> None:
    with self._lock:
        if not self.current_job_id or not self._db_run_created or self._run_finalized:
            return
        self._run_finalized = True
    
    self._flush_metrics_to_db()
    try:
        from storage.studio_db import finish_run
        # ... (rest of the method)
    except Exception:
        with self._lock:
            self._run_finalized = False
        logger.warning("Failed to finalize run in DB", exc_info=True)
  1. In _flush_metrics_to_db (using a self._is_flushing flag initialized to False in __init__):
def _flush_metrics_to_db(self) -> None:
    with self._lock:
        if self._is_flushing or not self._metric_buffer or not self.current_job_id or not self._db_run_created:
            return
        self._is_flushing = True
        if len(self._metric_buffer) > 500:
            self._metric_buffer = self._metric_buffer[-500:]
        batch = list(self._metric_buffer)
    
    try:
        from storage.studio_db import insert_metrics_batch, update_run_progress
        insert_metrics_batch(self.current_job_id, batch)
        with self._lock:
            del self._metric_buffer[: len(batch)]
        update_run_progress(...)
    except Exception:
        logger.warning("Failed to flush metrics to DB", exc_info=True)
    finally:
        with self._lock:
            self._is_flushing = False

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.

Fixed in e827a8c. _ensure_db_run_created, _finalize_run_in_db, and _flush_metrics_to_db now claim their state flags and snapshot/trim the metric buffer under the lock, with the SQLite I/O still outside it so status polls stay responsive. finish_run is single-winner via the _run_finalized claim, and the buffer del is claimed under the lock and re-queued on failure. Duplicate metric rows were already prevented by the UNIQUE(run_id, step) upsert; the real defect was the unlocked buffer del racing the pump, which is what this closes. Added tests for single-winner finalize, expected_job_id, and concurrent flush claiming each metric once.

Comment on lines +984 to +1006
def _start_stop_watchdog(self, cancel: bool) -> None:
"""Start a daemon that force-terminates the worker if a requested stop does not
exit on its own. No-op if no worker is alive or a live watchdog already watches
this proc (a stale watchdog on an old proc never blocks a new run's watcher)."""
with self._lock:
proc = self._proc
if proc is None or not proc.is_alive():
return
if (
self._stop_watchdog is not None
and self._stop_watchdog.is_alive()
and self._stop_watchdog_proc is proc
):
return
watchdog = threading.Thread(
target = self._stop_watchdog_loop,
args = (proc, cancel),
name = f"stop-watchdog-{self.current_job_id or 'unknown'}",
daemon = True,
)
self._stop_watchdog = watchdog
self._stop_watchdog_proc = proc
watchdog.start()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Starting a thread while holding a lock (self._lock) can lead to unnecessary lock contention, especially since the thread's target (_stop_watchdog_loop) immediately attempts to acquire the same lock. It is safer and cleaner to start the thread outside of the lock block.

    def _start_stop_watchdog(self, cancel: bool) -> None:
        """Start a daemon that force-terminates the worker if a requested stop does not
        exit on its own. No-op if no worker is alive or a live watchdog already watches
        this proc (a stale watchdog on an old proc never blocks a new run's watcher)."""
        watchdog = None
        with self._lock:
            proc = self._proc
            if proc is None or not proc.is_alive():
                return
            if (
                self._stop_watchdog is not None
                and self._stop_watchdog.is_alive()
                and self._stop_watchdog_proc is proc
            ):
                return
            watchdog = threading.Thread(
                target = self._stop_watchdog_loop,
                args = (proc, cancel),
                name = f"stop-watchdog-{self.current_job_id or 'unknown'}",
                daemon = True,
            )
            self._stop_watchdog = watchdog
            self._stop_watchdog_proc = proc
        
        if watchdog is not None:
            watchdog.start()

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.

Leaving as is. Thread.start() returns once the thread is bootstrapped, before _stop_watchdog_loop reaches its with self._lock, and _start_stop_watchdog releases the lock the moment it returns, so there is no deadlock and only sub-microsecond contention. Starting the watcher under the lock is deliberate and mirrors the pump-start sites, so a not-yet-started thread cannot race a new run installing its own watcher.

Comment on lines +1065 to 1078
def force_terminate(self, target_proc: "Optional[mp.Process]" = None) -> None:
"""Force-kill the training subprocess so state can be reset immediately. With
``target_proc``, terminate only that handle and no-op if a new run has replaced
it, so the watchdog can never kill a fresh worker."""
with self._lock:
if self._proc is not None and self._proc.is_alive():
logger.info("Force-terminating training subprocess (pid=%s)", self._proc.pid)
self._proc.terminate()
proc = self._proc
if target_proc is not None and proc is not target_proc:
return # superseded by a new run; do not touch the new worker
if proc is not None and proc.is_alive():
logger.info("Force-terminating training subprocess (pid=%s)", proc.pid)
proc.terminate()
cancelled = self._cancel_requested
output_dir = self._output_dir

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Since force_terminate is a process termination path, it should defensively tolerate partially-constructed objects (e.g., if __init__ fails or if the object is instantiated via __new__ in tests). Accessing instance attributes using getattr prevents potential AttributeErrors. Note that self._pump_thread at line 1086 should also be accessed via getattr.

Suggested change
def force_terminate(self, target_proc: "Optional[mp.Process]" = None) -> None:
"""Force-kill the training subprocess so state can be reset immediately. With
``target_proc``, terminate only that handle and no-op if a new run has replaced
it, so the watchdog can never kill a fresh worker."""
with self._lock:
if self._proc is not None and self._proc.is_alive():
logger.info("Force-terminating training subprocess (pid=%s)", self._proc.pid)
self._proc.terminate()
proc = self._proc
if target_proc is not None and proc is not target_proc:
return # superseded by a new run; do not touch the new worker
if proc is not None and proc.is_alive():
logger.info("Force-terminating training subprocess (pid=%s)", proc.pid)
proc.terminate()
cancelled = self._cancel_requested
output_dir = self._output_dir
def force_terminate(self, target_proc: "Optional[mp.Process]" = None) -> None:
"""Force-kill the training subprocess so state can be reset immediately. With
``target_proc``, terminate only that handle and no-op if a new run has replaced
it, so the watchdog can never kill a fresh worker."""
lock = getattr(self, "_lock", None)
if lock is None:
return
with lock:
proc = getattr(self, "_proc", None)
if target_proc is not None and proc is not target_proc:
return # superseded by a new run; do not touch the new worker
if proc is not None and proc.is_alive():
logger.info("Force-terminating training subprocess (pid=%s)", proc.pid)
proc.terminate()
cancelled = getattr(self, "_cancel_requested", False)
output_dir = getattr(self, "_output_dir", None)
References
  1. Ensure that cleanup or teardown paths (such as process termination or object destruction) tolerate partially-constructed objects (e.g., when __init__ raises an exception before all attributes are initialized, or when the object is instantiated via __new__ in tests). Access instance attributes in these paths using getattr(self, 'attribute_name', None) instead of direct access to prevent AttributeError.

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.

Leaving force_terminate as direct attribute access. The backend is only ever constructed through init, which always sets _lock, _proc, and _pump_thread, and nothing instantiates it via new (the tests all use TrainingBackend()). getattr guards would only paper over a partially-constructed object that does not occur on any real path, so they would hide bugs rather than prevent them.

Target-scope the escalation finalize so a stale watchdog can never clobber a
run that replaced its worker: capture the watched proc and job id, and no-op
the finalize (handle, progress, and DB) when a new run has already taken over.
Honor a later cancel by tightening an in-flight save watchdog to the shorter
cancel cap. Serialize the DB helpers on the lock so the watchdog and pump can
no longer double-create, double-finalize, or corrupt the metric buffer when a
force-terminate hands off to a still-finalizing pump.

Add regression tests: finalize no-ops when superseded, finalize runs for its
own worker, a later cancel tightens the cap, finalize is single-winner under
concurrency, finalize honors expected_job_id, and concurrent flushes claim
each metric exactly once.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 14, 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: e827a8c00c

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

Comment on lines +1064 to +1065
if target_proc is not None and self._proc is not None and self._proc is not target_proc:
return # a new run replaced the worker; never touch its state

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard stale watchdogs by job id

When the old worker has already died, /start is allowed because is_training_active() returns false, and start_training() updates current_job_id/_progress before it installs the new _proc. A watchdog from the old run can enter here during that startup window while _proc is still the old dead handle (or None), so this proc-only guard does not detect supersession and the stale watchdog can mark the fresh run as Training stopped. and finalize it. Capture the watched job id when starting the watchdog and require it to still match before changing 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.

Fixed in 9866e61. The watchdog now captures the job id it is watching when it starts, and _finalize_stopped_after_escalation no-ops when current_job_id no longer matches it, in addition to the proc guard. Since start_training sets current_job_id before installing the new _proc, the job-id guard catches exactly the startup window where _proc is still the old dead handle.

Comment on lines +1699 to +1703
if expected_job_id is not None and self.current_job_id != expected_job_id:
return
if not self.current_job_id or not self._db_run_created or self._run_finalized:
return
self._run_finalized = True # claim so only one caller finalizes

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Snapshot the run before releasing the finalize lock

After this expected_job_id check passes, the lock is released but _flush_metrics_to_db() and finish_run() later read self.current_job_id and progress fields directly. In the watchdog path the backend has already been made inactive, so a new /start can change those fields between this check and the DB writes; the old finalizer can then flush metrics or write a stopped status onto the new run. Snapshot the job id/progress under this lock, or pass the expected job id through the flush/finish calls.

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.

Fixed in 9866e61. _finalize_run_in_db now snapshots the run id and the final progress fields under the same lock that claims the finalize, and threads run_id through _flush_metrics_to_db and finish_run. A new run that starts between the claim and the DB writes can no longer have the old finalizer flush metrics or write a stopped status onto it.

with self._lock:
if self._db_run_created or not self.current_job_id or not self._db_config:
return
self._db_run_created = True # claim so only one caller creates

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 Don't publish DB-created state before insert commits

When the initial DB row creation failed and the pump/watchdog both retry during stop finalization, this line makes other callers believe the row already exists while create_run() has not executed or committed yet. A concurrent _finalize_run_in_db() can then call finish_run() before the INSERT, which is an UPDATE that can affect zero rows without raising; the later INSERT leaves the run stuck with the default running status in history. Use a separate in-progress flag or only set _db_run_created after create_run() succeeds.

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.

Fixed in 9866e61. _ensure_db_run_created now uses a dedicated _db_create_in_progress flag and publishes _db_run_created only after create_run commits. A concurrent finalize during creation sees _db_run_created still false and no-ops, so finish_run can never UPDATE a not-yet-inserted row and leave the run stuck as running.

Guard the escalation finalize by the watched job id in addition to the proc:
start_training sets current_job_id before it installs the new _proc, so a stale
watchdog entering during that startup window still sees the old dead handle and
was not caught by the proc-only guard. Capture the job id when the watchdog
starts and require it to still match before touching state.

Snapshot the run id and final progress under the finalize lock and thread them
through the flush and finish_run calls, so a new run that starts between the
finalize claim and the DB writes cannot be flushed or marked stopped under the
old run's finalizer.

Publish _db_run_created only after create_run commits, gated by a dedicated
in-progress flag, so a concurrent finalize can no longer run finish_run against
a not-yet-inserted row and leave the run stuck as running.

Add regression tests for the startup-window job-id guard, run-id pinned flush,
snapshot-based finalize across a new run, and create-not-published-before-insert.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 14, 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: 9866e618e4

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

self._progress.is_training = False
self._progress.status_message = "Training stopped."
output_dir = self._output_dir
self._proc = None

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 Finalize the watched run before exposing idle state

When the watchdog handles a worker that still reports alive after force_terminate(), clearing _proc here makes is_training_active() return false before the old run has been finalized in the DB. If the user immediately starts a new run in that gap, current_job_id changes, so the subsequent _finalize_run_in_db(..., expected_job_id=watched_job_id) returns without finishing the old row, leaving the stopped run recorded as running. Snapshot/finalize the watched run before exposing the backend as idle, or finalize by captured run id rather than the mutable current_job_id.

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.

Fixed in eefa002. The escalation now finalizes the watched run by its captured id via _finish_stopped_run: it snapshots the run id, buffered metrics, and final progress under the lock (where current_job_id is guaranteed to still be the watched run), then writes finish_run(id=captured) after exposing idle state. A new run started in the gap gets its own fresh state and is never finalized, and the old run is still recorded stopped because finish_run targets the captured id (idempotent UPDATE, so a concurrent pump finalize is harmless).

Comment on lines +1036 to +1038
if now - started >= abs_timeout:
reason = "worker did not exit within the absolute timeout"
break

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 Don't kill slow save-stops on the absolute cap

For save=True stops, this absolute timeout is measured from when the watchdog starts and still fires when no complete event has been seen. If the worker has legitimately reached a large/full-model save or a slow network output directory and the write exceeds the 600s default, this path force-terminates mid-save, leaving a partial checkpoint despite the stop-with-save request. Consider only applying this cap to cancels or resetting/escalating it based on an explicit save-start/save-complete signal.

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.

This is an intentional last-resort backstop, and applying it only to cancels would reintroduce the hang this PR fixes. The primary escalation is the short grace after the worker sends complete (save done); the absolute cap only fires when complete is never seen, which for save=True is the wedged-before-completion case. If the cap did not apply to save=True, a stop-with-save whose worker wedges before finishing the save would hang forever with is_training stuck, which is the original bug. The save cap is deliberately long (600s default, configurable via UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S) so a normal save completes well within it, and a pre-completion fire logs a loud warning. A save-start/save-complete signal that resets the cap on save start is the ideal fix but needs a worker-side event and is the out-of-scope layer-2 work noted in the description.

If a new run starts in the gap after the watchdog clears _proc and marks the
backend idle, current_job_id changes, so the previous expected_job_id guard made
the finalize skip and left the stopped run recorded as running. Capture the run
id, metrics, and final progress under the lock (where current_job_id is still the
watched run) and finalize by that captured id via _finish_stopped_run: finish_run
is an idempotent UPDATE and insert_metrics_batch upserts, so a concurrent pump
finalize of the same run is harmless and a newly started run is never touched.

Add a test that the watched run is finalized by id with its buffered metrics, and
update the escalation tests to assert finalize goes through _finish_stopped_run.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 14, 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: eefa002e3c

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

final_step = final_loss = duration = None
loss_history: list = []
if not already_final:
self._run_finalized = True # claim this run's finalize

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 Don't claim finalization before the run row exists

When the initial run-row creation has failed and the pump retries it from a terminal complete event, the pump sets _complete_seen before calling _ensure_db_run_created(). If the watchdog fires while that create is still in progress, this assignment marks the run finalized even though db_created is still false, so _finish_stopped_run() is skipped; after the insert completes, the pump's _finalize_run_in_db() no-ops because _run_finalized is already true, leaving the DB row stuck as running. Defer this claim until the row exists, or let the in-progress create/finalize path complete.

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.

Fixed in e02c02c. The escalation now only claims _run_finalized when the DB row already exists (do_finalize = run_id and _db_run_created and not _run_finalized). If an early create failed and the pump is retrying it, the escalation no longer claims, so the pump's create-then-finalize still records the run stopped instead of being no-oped by a premature claim. Parent state (is_training, _proc) is still cleared so the UI unsticks.

Comment on lines +1148 to +1149
except Exception:
logger.warning("Failed to finalize stopped run %s in DB", run_id, exc_info = True)

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 Keep watchdog finalization retryable after DB errors

If the watchdog wins finalization and insert_metrics_batch() or finish_run() raises here, the exception is only logged even though the caller already set _run_finalized = True and drained _metric_buffer. A transient SQLite lock in this path therefore prevents the pump or any later retry from marking the run stopped, leaving history with an active run and lost buffered metrics; this path should unclaim/requeue on failure like _finalize_run_in_db() does.

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.

Fixed in e02c02c. _finish_stopped_run now, on a DB error, re-acquires the lock and unclaims _run_finalized plus requeues the drained metric batch when the run is still current, so a transient SQLite lock no longer strands the row as running or loses metrics: the pump or a later retry can still finalize. A superseded run's state is never touched (guarded on current_job_id == run_id).

…e row exists

Only claim _run_finalized in the escalation when the DB row already exists; if an
early create failed and the pump is retrying it, claiming would make the pump's
later finalize no-op and strand the row as running, so leave the finalize to that
create-then-finalize path.

On a DB error in _finish_stopped_run (e.g. a transient SQLite lock), unclaim the
finalize and requeue the drained metrics when the run is still current, so the
pump or a later retry can still record the run stopped instead of leaving history
with an active run and lost metrics. A superseded run's state is never touched.

Add tests: no claim before the row exists, requeue+unclaim on a DB error, and a
superseded run left untouched on error.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: e02c02c64c

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

Reduce the wording of the docstrings and inline comments added by this PR without
dropping any of the concurrency invariants (dual proc/job-id supersession guard,
finalize-by-captured-id, publish-after-commit, snapshot-under-lock, unclaim and
requeue on error). Comments and docstrings only; no code change.
@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: f1d3413bfb

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

Comment on lines +1036 to +1038
if now - started >= abs_timeout:
reason = "worker did not exit within the absolute timeout"
break

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 kill save-stops before completion

When a user stops with save=True and the checkpoint write takes longer than _STOP_TIMEOUT_S (600s by default), this branch fires even though _complete_seen is still false, and the code proceeds to force_terminate() with a warning that the worker may be mid-save. That breaks the save-on-stop contract for large models or slow/network disks and can leave a partially written checkpoint; the save path should wait for the worker's complete signal before escalating, or reserve this pre-completion timeout for cancel/no-save stops.

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.

Same as the earlier round on this line: this is the intentional last-resort backstop, and reserving the pre-completion cap for cancels (as suggested) would let a stop-with-save whose worker wedges before finishing the save hang forever with is_training stuck, which is the original bug. Primary escalation is the grace after the worker's complete signal; the cap only fires when complete is never seen. It is long (600s default) and configurable via UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S, and a pre-completion fire logs a loud warning. A save-start signal that resets the cap is the ideal fix but needs a worker-side event and is the out-of-scope layer-2 work noted in the description.

self._progress.is_training = False
self._progress.status_message = "Training stopped."
output_dir = self._output_dir
self._proc = None

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 a DB retry path after watchdog escalation

When escalation reaches this assignment before the run row exists, or _finish_stopped_run later requeues after a transient SQLite/DB error, setting _proc to None makes _pump_loop take its top-level _proc is None return path instead of creating/finalizing the row. In those failure cases the UI reports stopped but history can be left missing or stuck as running; either finalize/retry from the watchdog path or defer dropping _proc until the DB terminal state is recorded.

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.

Fixed in fc9c1d6. Right that the pump can never finalize a wedged worker (it reports alive, so _pump_loop stays at its is_alive continue and would bail on the _proc-is-None guard once the handle drops). The escalation is now the sole finalizer: it records the terminal DB state before dropping _proc (creates the row if a start-time create failed via _ensure_db_run_created, then finish_run by captured id). While the handle is held is_training_active() stays true, so no new run can start and current_job_id stays the watched run for the write. _finish_stopped_run retries a transient DB error a few times and unclaims only when the run is still current, since the pump can no longer retry once _proc is gone. _proc is dropped last, re-guarded on target_proc.

A wedged worker still reports alive, so the pump never reaches its own finalize
and bails on its _proc-is-None guard once the escalation drops the handle. So the
watchdog is the sole finalizer: record the terminal DB state (create the row if a
start-time create failed, then finish by captured id) BEFORE dropping _proc. While
the handle is held is_training_active() stays true, so no new run can start and
current_job_id stays the watched run for the write; _proc is dropped last, guarded
on target_proc so a run that did replace the worker keeps its handle.

_finish_stopped_run retries a transient DB error a few times (the pump can no
longer retry once _proc is gone) and unclaims on final failure only when the run
is still current. Add tests for create-then-finalize, retry-then-unclaim, and not
dropping a new run's handle.
@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: fc9c1d6e0b

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

Comment on lines +1803 to +1806
with self._lock:
if created:
self._db_run_created = True # publish only after the insert commits
self._db_create_in_progress = False

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 Guard DB create state by job id

When the watchdog is creating a missing DB row for an escalated stop, a new /start can already proceed because the killed process is no longer alive and _should_stop makes is_training_active() return false. If that new run starts before this old create_run returns, these backend-wide flags are published for the new current_job_id, so the new run's _ensure_db_run_created() can skip inserting its own row and later metric/finalize updates target a missing run. Guard the flag updates with the captured job_id (or make the in-progress state per-run) so stale watchdog work cannot satisfy a new run's DB 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.

Fixed in ff09f2e. _ensure_db_run_created now publishes _db_run_created / _db_create_in_progress only when the captured job id is still current: a killed worker lets a new /start proceed mid-create, and the stale create for the old job must not satisfy the new run's backend-wide flags. The row is still created by its captured id, so the old run is recorded, and the new run owns and creates its own row. start_training also resets _db_create_in_progress so a stale in-progress claim can't block a new run's create.

_ensure_db_run_created publishes backend-wide _db_run_created and
_db_create_in_progress flags. When the watchdog creates a missing row for an
escalated stop, the killed worker lets a new /start proceed mid-create, so the
stale create could publish those flags against the new current_job_id, making the
new run skip inserting its own row (metric/finalize then target a missing run).
Publish the flags only when the captured job id is still current; the row is still
created by id, and the new run owns/creates its own. Also reset
_db_create_in_progress in start_training so a stale claim can't block a new run.
@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: ff09f2eca9

ℹ️ 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 4beb0a3 into main Jul 15, 2026
39 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-training-stop-watchdog branch July 15, 2026 09:46
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