Skip to content

[Jobs] Emergency recovery: retry unexpected controller errors (reuse RECOVERING + recovery_source) - #9868

Merged
cg505 merged 31 commits into
masterfrom
jobs-emergency-recovery
Jul 14, 2026
Merged

cg505 merged 31 commits into
masterfrom
jobs-emergency-recovery

Conversation

@cg505

@cg505 cg505 commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Managed jobs today turn any unexpected controller-side problem into a
terminal FAILED_CONTROLLER with no retry β€” including cases where the
job's workload is healthy and only the controller's own bookkeeping hit
trouble (an unhandled exception, or the job's schedule/task state being
mutated out from under the controller, which makes the next transition
fail with 0 rows updated / AssertionError).

This PR adds emergency recovery: instead of failing the job, the
controller retries managing it in place, bounded by a per-job budget with
exponential backoff. Only when the budget is exhausted does the job go to
FAILED_CONTROLLER, with the same full cleanup as today.

Emergency recovery reuses the existing RECOVERING status (no new
user-facing status). To let downstream consumers tell recovery causes
apart, the cause is recorded on the RECOVERING job event as a
recovery_source:

  • FAILURE β€” preemption / node failure / user-code failure (the
    recovery the user actually asked managed jobs to do).
  • EMERGENCY β€” unexpected controller error (this PR).
  • RESTART β€” controller process restart (upgrade/rollout resume; the
    resume path is historically called "HA recovery" but runs on any
    controller restart).

This lets downstream consumers distinguish user-facing recoveries from
system-driven ones (emergency + restart) β€” e.g. reporting/metrics that
should count only genuine failure recoveries.

Daemon-side recovery (when the whole controller process dies, vs a
caught error) is intentionally out of scope and tracked separately. So is
cross-controller ownership fencing: in-place retry relies on the same
cluster-level concurrency protections the rest of SkyPilot already depends
on, and comprehensive controller-ownership fencing is a separate effort.

What it does

When an unexpected exception reaches JobController.run()'s catch-all:

  1. Budget β€” spend one unit of a bounded per-job retry budget (default
    10), written as an absolute value so a retried bookkeeping round can't
    double-spend; the counter decays after 6h.
  2. Mark RECOVERING (recovery_source=EMERGENCY). CANCELLING/terminal
    tasks are left untouched.
  3. Tear down the cluster immediately (best-effort, before the
    backoff): the retry always relaunches from scratch β€” even if the task
    was RUNNING when the error hit, since the error may be caused by the
    cluster's own state and relaunching is always safe (managed jobs are
    idempotent) β€” so the doomed cluster is not left running (and billing)
    through the backoff. Cleanup is idempotent and the retry's forced
    recovery re-runs it, so a failure here only delays the teardown.
  4. Reset any launch-adjacent schedule state (LAUNCHING /
    ALIVE_WAITING / ALIVE_BACKOFF β†’ ALIVE), then re-run the job loop
    after backoff (1m, 2m, 4m, 8m, 16m, then 30m capped β€” ~3h total across
    a full episode), reusing the existing restart-resume path. During the
    backoff the job therefore holds no launching slot, is invisible
    to the scheduler's highest-blocking-priority computation
    (a parked
    job must not block lower-priority jobs from scheduling), and stays
    ALIVE, which keeps the jobs controller from autostopping even
    though the backoff exceeds the 10-minute idle window β€” all pinned by
    unit tests.

The budget columns (emergency_recovery_count,
last_emergency_recovery_at) are the internal "is this an emergency /
apply backoff" tracking; the in-place retry loop drives the backoff and
the columns persist it across a controller restart. Separately from the
per-occurrence causes on the events, a boolean
spot.recovering_from_failure ("failure credit") tracks whether the
currently open recovery episode involves a genuine failure (cleared on
every exit from recovery) β€” deliberately a different fact from "what
caused the latest occurrence", which is what makes the recovery-count
accounting below robust to overlapping causes.

Notable details

  • No config knob. Bounds are module constants in
    sky/jobs/constants.py; rollback = revert the PR; the new nullable
    columns are inert without the code.
  • Recovery source on job_events (new nullable recovery_source
    column). Old RECOVERING rows have NULL source; consumers treat NULL as
    FAILURE for back-compat. (Bounded undercount: a preemption that happens
    while the controller is down is tagged RESTART on the first
    post-resume recovery β€” can't be distinguished from a pure restart
    without probing the cluster.)
  • recovery_count counts only genuine failure recoveries. Completing
    a recovery episode increments the user-visible "Recoveries" count only
    when the episode carries failure credit (recovering_from_failure TRUE;
    NULL β€” rows written before the column existed β€” is treated as credited
    for back-compat). Purely system-driven episodes (emergency, restart)
    complete without inflating the count. An emergency that interrupts an
    in-flight preemption recovery neither grants nor erases the credit, so
    that real recovery still counts.
  • One recovery event per episode. The forced first post-resume
    iteration derives its announcement from the task's current status: a
    task already RECOVERING (an interrupted preemption recovery, or an
    emergency retry whose handler already recorded the specific reason) is
    not re-announced β€” no duplicate, less-informative RECOVERING event, and
    the episode keeps its failure credit (a preemption recovery that a
    rollout interrupts is still a failure recovery, not a restart-driven
    one).
  • Restart resume of a STARTING task keeps STARTING. A
    controller-restart resume of a task that never reached RUNNING stays
    STARTING through
    the forced relaunch instead of flipping STARTING β†’ RECOVERING (it is
    still starting, not recovering, so it shouldn't be reported as a
    recovery). The cluster is still cleaned up first (no double-submit), and
    the task reaches RUNNING via set_started (or an uncounted
    set_recovered only if the relaunch itself had to retry and moved it to
    RECOVERING). Other restart resumes (non-STARTING, non-RECOVERING) go to
    RECOVERING tagged source=RESTART.

Test plan

  • Unit (tests/unit_tests/test_sky/jobs/test_emergency_recovery.py):
    state transitions + budget against a real temp SQLite DB β€” incl. the
    recovery_source tagging (FAILURE default, EMERGENCY on the emergency
    setter, RESTART on a forced resume), the failure-credit bit (granted by
    FAILURE, preserved across an interrupting emergency, cleared on every
    exit), and the recovery_count accounting (credited/legacy-NULL count;
    emergency/restart/launch-retry don't);
    plus the run() retry loop driven with mocked collaborators across
    every branch (retry, budget exhaustion, decay, cancel ordering,
    bookkeeping idempotency, backoff sequence).
  • Smoke (test_managed_jobs_emergency_recovery): mutates the job's
    schedule state during the launch-time window and asserts an
    EMERGENCY-tagged RECOVERING job event appears, exactly one attempt is
    recorded, the job ends SUCCEEDED, and the cluster is never duplicated.
  • Manual e2e on a local consolidation-mode API server (postgres +
    k8s): mutate β†’ emergency RECOVERING (exactly one source=EMERGENCY
    event) β†’ recover β†’ SUCCEEDED, single cluster throughout; crash-loop β†’
    bounded escape to FAILED_CONTROLLER with no leaked cluster; an HA
    resume of a STARTING task (API-server restart mid-launch) that keeps the
    task STARTING (no RECOVERING event) through to SUCCEEDED; and a
    RUNNING-origin emergency (task state mutated mid-run so set_succeeded
    hits 0-rows) validating the always-relaunch + counting semantics
    end-to-end: one source=EMERGENCY event, schedule state ALIVE
    (slot-free, autostop-blocking) through the whole backoff and LAUNCHING
    only while actually relaunching, old pod torn down (1β†’0β†’1), workload
    re-ran to SUCCEEDED with recovery_count=0, pods ≀ 1 throughout.

Note: this reworks an earlier revision of this PR that added a separate
EMERGENCY_RECOVERING status; that status is removed in favor of the
shared RECOVERING + recovery_source. (The migration is 022:
master's 021_add_status_override landed first, so this PR's migration
was renumbered from 021.)

πŸ€– Generated with Claude Code

cg505 and others added 10 commits June 12, 2026 23:41
…constants

Scaffolding for emergency recovery of managed jobs: a new non-terminal
EMERGENCY_RECOVERING status (controller-level recovery, distinct from
cluster-level RECOVERING), DB columns for the bounded retry budget and
saved pre-emergency task status, and the budget/backoff/decay constants.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…overy

set_emergency_recovering_async saves the prior task status (never
clobbering it on a bookkeeping re-run) and preserves CANCELLING/terminal
tasks untouched; set_emergency_recovered_async restores a re-attached
task to RUNNING. The budget write is an absolute-value update fenced on
(controller_pid, controller_pid_started_at) so a retried bookkeeping
round cannot double-spend the budget, and schedule-state normalization
releases a stuck LAUNCHING slot under the same fence.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
… the job

JobController.run() now wraps its body in a retry loop: an unexpected
exception verifies the controller still owns the job (standing down
without touching anything if not), spends one unit of a bounded per-job
budget, marks the task EMERGENCY_RECOVERING (saving its prior status),
releases any stuck LAUNCHING slot, and re-runs the job loop after an
exponential backoff. The resume path re-attaches RUNNING tasks to their
healthy cluster and force-recovers anything else. Budget exhaustion or
repeated bookkeeping failure falls back to the existing
FAILED_CONTROLLER handling with full cleanup.

Also: cancel_job no longer swallows a cancel signal aimed at a job loop
that already finished, and storage teardown / pool-job cancel during
cleanup now retry transient failures before alerting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…easons

Treat EMERGENCY_RECOVERING like RECOVERING everywhere a job is displayed
or accounted as actively recovering: duration calculation, terminal
last_recovered_at stamping, the recovery-reason details column, dashboard
status groups/badges/banners, and the CLI status help. Also adds the
missing WINDING_DOWN entry to the dashboard active-status group.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
State-layer tests run against a real temporary SQLite DB; the retry loop
in JobController.run() is driven directly with mocked state collaborators
so every decision branch (retry, usurped stand-down, budget exhaustion,
decay, cancellation ordering, bookkeeping resilience, backoff sequence)
is exercised deterministically.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Mutates the job's schedule_state during the LAUNCHING window (via the
local DB in consolidation mode, or ssh to the jobs controller otherwise)
and asserts the job passes through EMERGENCY_RECOVERING with exactly one
recorded attempt, ends SUCCEEDED, and never duplicates or leaks its
cluster. Environmental failures are labeled distinctly from recovery
failures.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Found in e2e testing: StrategyExecutor.make() strips job_recovery from
the in-memory task's resources, so re-running the job loop on the same
task objects hit 'assert job_recovery_strategy is not None' on every
retry. Each retry now starts from a freshly loaded DAG, which also
shields against any other in-memory mutation the failed attempt left
behind.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
_get_dag is lru_cached globally, so the reload was handed back the same
mutated Dag object. The retry path now parses a fresh Dag from the
stored YAML.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…DAG typing

- Smoke test now gates the schedule-state mutation on the task being
  STARTING, so it only hits the launch-time LAUNCHING window (the
  claim-time window self-heals and would false-fail the assertion).
- run_job_loop's CancelledError handler stands down (re-raises without
  touching job state) when the controller was usurped, closing a narrow
  cancel-during-stand-down corruption window.
- Concretely typing the reloaded DAG surfaced two latent Optional[str]
  issues in job-group handling; narrowed both (job-group tasks are
  always named).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@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 an emergency recovery mechanism for managed jobs in SkyPilot, allowing the controller to automatically retry managing a job in place when encountering unexpected internal errors. It adds a new EMERGENCY_RECOVERING status, updates the dashboard, CLI, and state management, and implements database migrations and comprehensive tests. Feedback on the changes highlights a potential IndexError in sky/jobs/controller.py where a database-retrieved task_id could exceed the bounds of the in-memory DAG tasks list, and suggests clamping the index to ensure robust error handling.

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 thread sky/jobs/controller.py Resolved
…op EMERGENCY_RECOVERING)

Reverses the earlier EMERGENCY_RECOVERING-status approach. Emergency
recovery now reuses the normal RECOVERING status; the cause is recorded
as a RecoverySource (FAILURE / EMERGENCY / HA) on the RECOVERING job
event (new nullable job_events.recovery_source column), so consumers
(ROI display, SKY-6016) can count only failure-driven recoveries and
exclude system-driven ones. No new user-facing status.

- Drop the EMERGENCY_RECOVERING enum value / proto / dashboard / CLI /
  README additions (dashboard now matches master).
- set_emergency_recovering_async writes RECOVERING + emits a RECOVERING
  event tagged EMERGENCY, and saves status_before_emergency only when
  unset (the non-NULL marker, not the status, is what identifies an
  emergency-origin RECOVERING now that the status is shared).
- Clear status_before_emergency on every exit (set_recovered/_failed/
  _succeeded/_cancelled/_started) so a stale marker can't misclassify a
  later real preemption as emergency-origin (would re-attach to a dead
  cluster). [adversarial-review CRITICAL]
- Resume block keys 'emergency-origin' off status_before_emergency; the
  forced recovery on a controller-restart resume is tagged HA, an
  emergency-origin one EMERGENCY, and ordinary preemptions FAILURE.
- The budget columns (emergency_recovery_count, last_emergency_recovery_at)
  remain the internal backoff tracking; the in-place retry loop is
  unchanged.

Tests updated; smoke test asserts an EMERGENCY-tagged RECOVERING event.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505 cg505 changed the title [Jobs] Emergency recovery: retry unexpected controller errors instead of failing the job [Jobs] Emergency recovery: retry unexpected controller errors (reuse RECOVERING + recovery_source) Jun 29, 2026
cg505 and others added 3 commits June 29, 2026 20:03
- Emergency-origin force-recovery no longer re-emits a RECOVERING event:
  the exception handler already transitioned to RECOVERING with the
  specific reason, so the retry's generic set_recovering is skipped
  (cleanup + recover() + set_recovered still run). One EMERGENCY event
  per episode instead of two.
- A controller-restart (HA) resume of a still-STARTING task keeps the
  STARTING status through the forced relaunch instead of flipping
  STARTING -> RECOVERING (it never reached RUNNING β€” it is starting, not
  recovering). The cluster is still cleaned up first, and the task reaches
  RUNNING via set_started (set_recovered only if the relaunch itself had to
  retry and moved it to RECOVERING). Threaded through the chain-DAG and
  JobGroup resume paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…ed retry

Emergency recovery previously fenced its bookkeeping on the controller's
(pid, started_at) identity and stood down if another controller had taken
the job over. That partial, pid-based ownership guard is the wrong layer:
in-place retry relies on the same cluster-level concurrency protections the
rest of SkyPilot already depends on, and comprehensive controller-ownership
fencing is a separate effort. Remove it so this change stays scoped to the
retry-in-place behavior.

This removes:
- the _EmergencyDecision enum (handlers now return Optional[str]: None to
  retry, a failure note to fail)
- the JobController controller_pid_record thread, the `usurped` flag/property,
  and the two usurped-gated guards in run_job_loop
- the three stand-down branches in _attempt_emergency_recovery
- the pid/started_at fence params on record_emergency_recovery_attempt_async
  and normalize_schedule_state_for_emergency_retry_async

The controller_pid columns, ControllerPidRecord, and get_job_controller_process
stay -- they are still used by the liveness sweep, HA recovery, and the
scheduler. Budget, resume (status_before_emergency), and recovery_source are
unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The controller mutates the in-memory task objects while running a job (e.g.
StrategyExecutor.make strips job_recovery from the task's resources), but
_load_dag handed it the process-global lru_cached DAG object -- so the cache
returned a shared, mutated object to every later caller. Emergency recovery
worked around this with a fresh=True bypass, leaving confusing semantics
(_get_dag would still hand back the stale mutated object after a "fresh"
reload).

Fix the root cause: drop the cache so _get_dag always parses a fresh DAG.
Each caller (controller init, emergency retry, cleanup, cancel) now gets its
own object to mutate, and the fresh= flag / cached-vs-uncached split go away.
The cache was only hit ~3x per job lifetime (all once-per-lifecycle paths),
so removing it costs a negligible re-parse and removes a shared-mutable-state
footgun.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread sky/jobs/controller.py Resolved
cg505 and others added 4 commits June 30, 2026 23:35
_cleanup_with_retries wrapped pool-job cancel and ephemeral-storage teardown
in a retry loop. It is independent cleanup hardening (the _cleanup path runs
on every job termination, not just emergency recovery) and doesn't belong in
this PR -- reverting to the direct calls. Will land separately as its own
focused change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…veries

Three coupled changes to the recovery/resume semantics:

1. An emergency retry always tears down and relaunches the cluster, even
   if the task was RUNNING when the error hit. The error may be caused by
   the cluster's own state, so re-attaching could just keep hitting it;
   relaunching is always safe (managed jobs are idempotent) and only
   costs time. This removes the RUNNING re-attach special case and with
   it the entire status_before_emergency mechanism
   (set_emergency_recovered_async, get_status_before_emergency_async, the
   save-guard, and the clear-on-every-exit plumbing).

2. The resume path derives its announcement from the task's current
   status at the point of recovery instead of threading
   resume_recovery_source/resume_keep_starting through every layer:
   already-RECOVERING tasks are not re-announced (no duplicate event, and
   the episode keeps its original source -- a preemption recovery that a
   rollout interrupts stays a FAILURE recovery instead of being relabeled
   HA), STARTING tasks keep STARTING, and anything else opens an
   HA-sourced episode.

3. recovery_count now counts only genuine failure recoveries. The
   episode's cause is stamped on a new spot.recovery_source column
   (replacing status_before_emergency in migration 021; cleared on every
   exit from recovery), and set_recovered_async increments only when the
   episode source is FAILURE (NULL, i.e. pre-migration rows, counts as
   FAILURE). EMERGENCY and HA episodes, and launch-retry drift on a
   kept-STARTING resume, no longer inflate the user-visible Recoveries
   count. set_emergency_recovering_async labels the episode
   save-only-if-unset, so an emergency interrupting an in-flight FAILURE
   recovery keeps that episode countable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Max attempts 5 -> 10 and backoff cap 8m -> 30m (sequence: 1m, 2m, 4m, 8m,
16m, then 30m capped; ~3h of total backoff per episode), giving transient
controller-side incidents more chances to clear before the job goes
terminal.

The old cap was chosen to stay under the jobs controller's 10-minute idle
autostop window. That rationale is replaced by the real invariants, now
pinned with unit tests: during the emergency backoff the job (a) holds no
launching slot -- the LAUNCHES_PER_WORKER gate is the in-memory `starting`
set, which scheduled_launch's finally releases when the error escapes the
launch, and the stuck DB LAUNCHING state is normalized back to ALIVE by the
emergency bookkeeping -- and (b) keeps the controller alive: the skylet
autostop check (events.py::AutostopEvent) counts get_num_alive_jobs(),
which includes every schedule state a backing-off job can hold (ALIVE /
ALIVE_BACKOFF / ALIVE_WAITING / LAUNCHING).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread sky/jobs/controller.py Resolved
Comment thread sky/jobs/state.py Resolved
…l_job change

Three review-driven changes:

1. Replace the episode-scoped spot.recovery_source enum with a boolean,
   spot.recovering_from_failure ("failure credit"). Whether a recovery
   episode involves a genuine failure is a different fact from what caused
   each RECOVERING occurrence (job_events.recovery_source keeps the
   per-occurrence causes): a system-driven interruption (emergency or
   restart) of a failure recovery neither grants nor erases the credit.
   Encoding this as an enum with a keep-first save-guard made the counting
   rule easy to misread; the bit states it directly. set_recovering opens
   an episode with credit = (source == FAILURE); set_emergency_recovering
   sets FALSE only when no episode is open; set_recovered increments
   recovery_count only for credited (or legacy-NULL) episodes.

2. Rename RecoverySource.HA -> RESTART before the value is enshrined in
   the database: the resume path is historically called "HA recovery" but
   runs on any controller restart (e.g. a normal upgrade/rollout). Naming
   quirk documented on the enum and on ha_recovery_for_consolidation_mode.

3. Drop the cancel_job done-task change. Its "leave the signal" branch
   existed for the ownership stand-down case that was removed from this PR;
   without stand-down, a done job loop is always about to be terminal (the
   run_job_loop finally guarantees it), so a cancel signal in that window
   is moot and master's behavior (consume + no-op) is fine.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test -k job --remote-server
/smoke-test -k job --jobs-consolidation
/smoke-test -k job

…very

Conflicts resolved:
- sky/utils/db/migration_utils.py + migration renumber: master landed its
  own spot_jobs migration 021 (status_override), so the emergency-recovery
  migration moves to 022 and SPOT_JOBS_VERSION becomes '022'.
- sky/jobs/state.py: keep both new spot columns (recovering_from_failure +
  master's status_override); merge the _get_latest_event_reasons docstring.
- sky/jobs/controller.py: keep the None-safe job-group name filter plus
  master's fresh-launch STARTING comment.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test -k job --remote-server
/smoke-test -k job --jobs-consolidation
/smoke-test -k job

@cg505

cg505 commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

/quicktest-core

Comment thread sky/jobs/controller.py Resolved
Comment thread sky/jobs/controller.py Resolved
…all launch-adjacent states

Review follow-ups:

1. The doomed cluster is now torn down during the emergency bookkeeping
   (best-effort), not deferred to the retry's forced recovery: the retry
   always relaunches from scratch, and the backoff can be 30 minutes, so
   deferring left a dead-weight cluster running (and billing) through the
   backoff. terminate_cluster is idempotent and the retry still runs the
   same cleanup, so a teardown failure only delays it. No-op for pool jobs
   (no dedicated cluster). Also fixes a stale comment that still described
   the removed RUNNING re-attach.

2. normalize_schedule_state_for_emergency_retry_async now resets all
   launch-adjacent schedule states (LAUNCHING, ALIVE_WAITING,
   ALIVE_BACKOFF) to ALIVE, not just LAUNCHING. Beyond launch-slot
   accounting, those states sit in the scheduler's
   highest-blocking-priority set, so a job parked there through a long
   emergency backoff would block lower-priority jobs from scheduling.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@aylei aylei left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Amazing, thanks @cg505 !

Comment thread tests/smoke_tests/test_managed_job.py Outdated
Comment on lines +3532 to +3534
if smoke_tests_utils.is_remote_server_test():
pytest.skip('Requires direct access to the managed-jobs DB '
'(local API server only).')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

IIUC we should use @pytest.mark.no_remote_server here so we do not collect this case in --env-file as well

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

cc @zpoint for double check

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good call β€” added in 65d284e. The test already skipped at runtime via is_remote_server_test(), but the marker also deselects it at collection time so --env-file/remote-server runs never pick it up, per the suite convention.

-Claude

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If we already added no_remote_server, there's no need for if smoke_tests_utils.is_remote_server_test β€” it's dead code.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch β€” removed in fc14360. Confirmed it's dead: PYTEST_SKYPILOT_REMOTE_SERVER_TEST (what is_remote_server_test() reads) is only ever set under the same two conditions the no_remote_server marker keys on (the --remote-server flag, or an --env-file with api_server config), and collection-time deselection runs before the fixtures that set it β€” so the runtime skip could never fire.

-Claude

Comment thread sky/jobs/controller.py
common_utils.format_exception(e, use_bracket=True))
logger.error(msg)
try:
failure_note = (await self._handle_unexpected_error(e))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not need be in this PR: it is worth to identify emergency recovery jobs in our metrics

class ManagedJobsCollector:
, so user can alert for frequent or large scale emergency recovery jobs

cc @DanielZhangQD for double check here

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Yes, I will add metrics and alert for this after this PR is merged.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed β€” an emergency-recovery metric would pair well with this. The pieces this PR leaves for it: every emergency occurrence is a RECOVERING job event tagged recovery_source='EMERGENCY' (append-only, so a poller/counter can cursor over job_events), and job_info.emergency_recovery_count tracks the in-episode attempt count. One suggestion for the alerting semantics when you pick this up: alert per job/episode rather than per event β€” a single stuck job can emit up to 10 EMERGENCY events over ~3h of backoff before going terminal. Thanks @DanielZhangQD!

-Claude

cg505 and others added 2 commits July 8, 2026 20:10
The test mutates the managed-jobs DB directly on the API server host, so
it cannot run against a remote API server. It already skipped at runtime
via is_remote_server_test(); the marker also deselects it at collection
time (e.g. --env-file remote-server runs), per the suite convention.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…budget

Six edge cases in the emergency-recovery path, each with a red/green
regression test in test_emergency_recovery.py:

1. Pool jobs: concurrent duplicate execution. A forced (emergency /
   controller-restart) recovery of a pool job resubmits via sdk.exec
   without cancelling the previous submission (_try_cancel_jobs no-ops
   for pools), so two copies of the user code run concurrently on the
   shared pool cluster. Cancel the stale job_id_on_pool_cluster before
   recover() resubmits (best-effort, mirrors task_cleanup), only on the
   forced path.

2. Batch coordinator ends FAILED after succeeding. An emergency marks
   the coordinator RECOVERING; the batch resume runs to completion and
   calls set_succeeded_async, which only transitions from
   RUNNING/WINDING_DOWN, so a fully successful run ended FAILED. The
   batch resume now restores RUNNING first (count_recovery=False).

3. Emergency on a PENDING task skipped initialization forever. PENDING
   is in processing_statuses(), so an uninitialized task could be marked
   RECOVERING; the retry then took is_resume=True and never ran
   set_starting_async, leaving submitted_at/resources/specs NULL
   (get_task_specs -> json.loads(None) -> TypeError). set_emergency_
   recovering_async now excludes PENDING; the controller leaves the task
   PENDING and relaunches it fresh, still budgeted and backed off.

4. Eager teardown defeated the runtime log-capture hook. The pre-backoff
   teardown removed the cluster before on_before_recovery could snapshot
   the run's logs. Invoke on_before_recovery (best-effort) before the
   teardown, mirroring the normal recovery path.

5. Parked episode held a LAUNCHES_PER_WORKER slot for the whole backoff.
   scheduled_launch's finally only frees the slot for errors escaping
   inside the launch context; pre/post-launch bookkeeping errors and pool
   jobs (which bypass scheduled_launch's slot accounting) kept the slot
   for up to ~3h. The bookkeeping now discards the job from `starting`
   (+ notifies) before the backoff. Corrects the constants.py comment.

6. Budget double-spend across bookkeeping rounds. The outer retry
   re-read the budget each round, so a transient failure after the
   attempt was recorded re-read the incremented count and spent again
   (up to 5 of 10 units on one error). The attempt number is now
   computed once per escaped error and reused for every round's absolute
   write; the RECOVERING event is emitted once (emit_event guard) so a
   re-run cannot duplicate it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed a follow-up commit (108e59c) fixing six edge cases in the emergency-recovery path that a closer review turned up. Flagging since it lands after the approval β€” happy to split any of these out if you'd prefer to review separately.

Each has a red/green unit test in test_emergency_recovery.py (verified to fail behaviorally on the pre-fix code, not just on a missing symbol):

  1. Pool jobs: concurrent duplicate execution. On a forced (emergency / controller-restart) recovery of a pool job, recover() resubmits via sdk.exec without cancelling the previous submission (_try_cancel_jobs early-returns for pools), so two copies of the user code could run concurrently on the shared pool cluster. Now the stale job_id_on_pool_cluster is cancelled before the relaunch (best-effort, mirroring task_cleanup), on the forced path only.
  2. Batch coordinator ended FAILED after succeeding. An emergency marks the coordinator RECOVERING; the batch resume completes via set_succeeded_async (which only transitions from RUNNING/WINDING_DOWN), so a fully successful run went to FAILED. The batch resume now restores RUNNING first.
  3. Emergency on a PENDING task skipped initialization. PENDING was in the emergency transition's status set, so an uninitialized task could be marked RECOVERING; the retry then treated it as a resume and skipped set_starting, leaving submitted_at/resources/specs NULL. PENDING is now excluded β€” the task is relaunched fresh (still budgeted + backed off).
  4. Pre-backoff teardown ran before the recovery hook. The teardown removed the cluster before on_before_recovery could run; the hook is now invoked (best-effort) before the teardown, mirroring the normal recovery path.
  5. A backing-off episode could hold a launch slot for the whole backoff. scheduled_launch's finally only frees the slot for errors escaping inside the launch context; pre/post-launch bookkeeping errors and pool jobs kept it for up to the full backoff. The bookkeeping now releases the slot before backing off.
  6. Budget double-spend across bookkeeping rounds. The outer retry re-read the budget each round, so a transient failure after recording an attempt re-read the incremented count and spent again. The attempt number is now computed once per error and reused; the RECOVERING event is emitted once so a re-run can't duplicate it.

-Claude

…tries

A systemic incident (DB instability, a bad rollout) tends to push many
managed jobs into emergency recovery at the same instant. With a
deterministic backoff (1m, 2m, 4m, ...) all of them retry at the same
moments, resynchronizing their DB-write bookkeeping into load waves that
re-hit the already-struggling DB β€” worst under consolidation mode's
shared DB.

Jitter the sleep +/-50% around the nominal backoff. Centered on the
nominal value, so the average (and the ~3h expected episode length) is
unchanged. The controller logs both the nominal and the jittered sleep.

test_backoff_sequence_and_final_escape now asserts each sleep is within
+/-50% of its nominal rather than an exact value; a new
test_backoff_is_jittered asserts the capped steady-state sleeps actually
differ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

/quicktest-core
/smoke-test
/smoke-test --managed-jobs --jobs-consolidation
/smoke-test --remote-server -k job

…k check

The emergency-recovery smoke test asserted the job cluster was gone
immediately after the job reached SUCCEEDED. But a managed job is marked
SUCCEEDED before its cluster is torn down (set_succeeded runs first for
responsiveness, then log download, then terminate), so on a real cloud
the assert raced the teardown and could see the still-terminating cluster
(observed on AWS: "Job cluster still exists after SUCCEEDED").

The controller's schedule_state only reaches DONE after run_job_loop's
_cleanup tears the cluster down (it runs before scheduler.job_done), so
wait for DONE β€” the controller's authoritative "fully cleaned up" signal
β€” before checking for a leaked cluster. A genuine leak still fails (the
DONE-wait deadline elapses, or the cluster is still present at DONE).

Also drop a now-inaccurate comment: the RECOVERING event is recorded when
the emergency is detected (before the backoff) and persists in
job_events, so the poll catches it regardless of the backoff duration
(which is jittered).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

/quicktest-core
/smoke-test
/smoke-test --managed-jobs --jobs-consolidation
/smoke-test --remote-server -k job

cg505 added a commit that referenced this pull request Jul 10, 2026
Preemptive merge: #9868 (emergency recovery) is expected to land on master
before this branch, and the two PRs overlap on run(), the state writers,
and the spot_jobs migration chain. Resolution decisions:

- Migration renumbered 021 -> 023 (master took 021 for status_override,
  #9868 takes 022 for the emergency recovery columns); SPOT_JOBS_VERSION
  is now '023'.
- JobsController.run(): kept #9868's retry-loop structure and re-grafted
  the fencing pieces into it: the JobOwnershipLostError passthrough now
  sits above the broad except *inside* the retry loop (an ownership loss
  is never retry-eligible -- it must route to stand-down, not be retried
  in place), and the finally keeps the fence.lost skip semantics.
- run_job_loop finally: kept the stand-down/finalize split; ported
  #9868's clearer cleanup-failure message into _finalize_job_loop.
- set_recovering/set_recovered/set_starting call sites: kept #9868's
  resume-classification branching, threading fence= into each write.
- state.py writers: merged fence= with the new recovery_source /
  count_recovery params and the episode-close values.
- #9868's controller test harnesses construct JobController without
  __init__; seeded jc._fence = None there.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
cg505 added a commit that referenced this pull request Jul 10, 2026
Emergency recovery (#9868) retries unexpected controller errors in place.
An ownership loss must never take that path: retrying keeps a stale
claimant driving (cleanup + relaunch) a job that now belongs to another
controller, and the give-up path writes FAILED_CONTROLLER over the new
claimant's job. Route it to the stand-down disposition instead:

- run()'s retry loop re-raises JobOwnershipLostError above its broad
  except (added in the merge commit); _handle_unexpected_error's
  bookkeeping retry now does the same instead of treating the loss as a
  transient bookkeeping failure (which retried it for 5 rounds and then
  failed the job).
- _attempt_emergency_recovery opens with an ownership pre-check, and its
  best-effort cluster teardown re-raises the loss from _cleanup_cluster's
  gate instead of swallowing it as a teardown failure.
- The bookkeeping's writers are fenced like every other claim-scoped
  writer: set_emergency_recovering_async (a stale claimant cannot mark
  the new claimant's task RECOVERING), record_emergency_recovery_attempt
  (cannot spend the new claimant's retry budget), and
  normalize_schedule_state_for_emergency_retry (cannot flip the new
  claimant's LAUNCHING back to ALIVE).

Red/green: the three new retry-loop tests and the state-writer test fail
on the merge commit and pass here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
cg505 added a commit that referenced this pull request Jul 10, 2026
jobs-claim-fencing-diffbase is #9858 + #9868 + current master merged
with no fencing changes. Merging it with the 'ours' strategy changes
nothing in this branch's tree; it only makes the diff-base commit part
of this PR so that the pull request's ranged files view
(/pull/9869/files/<diffbase>..<head>) can render the fencing-only diff
with inline commenting.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@cg505

cg505 commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

/quicktest-core
/smoke-test
/smoke-test --managed-jobs --jobs-consolidation
/smoke-test --remote-server -k job

…overy

The no_remote_server marker already deselects this test at collection
time whenever a remote API server is in play (the --remote-server flag or
an --env-file with api_server config). PYTEST_SKYPILOT_REMOTE_SERVER_TEST
β€” what is_remote_server_test() reads β€” is set only under those same two
conditions, and collection-time deselection runs before the fixtures that
set it, so the runtime pytest.skip could never fire. Remove the dead
check (per review).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test -k test_managed_jobs_emergency_recovery

@cg505

cg505 commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test --kubernetes --managed-jobs

The emergency-recovery smoke test's non-consolidation path runs sql on the
jobs controller over ssh (`_run_sql_on_controller`). On failure it raised a
bare CalledProcessError, discarding the remote python's traceback (in
.stderr) β€” so a non-consolidation smoke failure gave no clue *why* the read
failed. Propagate the remote stdout/stderr in the raised error instead.

Pure observability: the ssh command and the sqlite connection are
unchanged, so this masks nothing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

Added observability (12b2b31) so the non-consolidation controller sql read surfaces the remote python's stdout/stderr instead of a bare CalledProcessError β€” retriggering to capture the actual error behind the AWS failure (schema/migration on the controller is confirmed fine, so this should show the real remote traceback).

/smoke-test -k test_managed_jobs_emergency_recovery

-Claude

@cg505

cg505 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test --kubernetes -k test_managed_jobs_emergency_recovery

…ugs)

The emergency-recovery smoke test's non-consolidation path
(`_run_sql_on_controller`) had two real bugs, both surfaced by the
observability added in the previous commit:

1. SyntaxError (the AWS failure). The SQL was embedded as
   `conn.execute('''{sql}''')`. A query ending in a quoted literal β€”
   `emergency_event_sql` (…recovery_source='EMERGENCY'), and likewise
   `count_sql`/`done_sql` β€” produced `…'EMERGENCY''''`, four adjacent
   quotes that close the triple-quoted string early:
   `SyntaxError: unterminated string literal`. The mutation query (ends in
   `)`) was unaffected, which is why the failure only hit the read loops.
   Fixed by passing the SQL as a repr'd literal, `conn.execute({sql!r})`,
   which is safe for any quoting. (Consolidation mode was immune β€”
   `_run_sql_locally` hands the SQL straight to SQLAlchemy.)

2. `python3: command not found` (the Kubernetes failure). Bare `python3`
   is not on the non-interactive ssh PATH on a k8s controller pod (no
   system python3 β€” only the SkyPilot runtime env). Resolve the
   interpreter the way SkyPilot does, via the path in ~/.sky/python_path,
   falling back to python3 on VM controllers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cg505

cg505 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

Root cause found via the observability: the non-consolidation controller read built its remote python as conn.execute('''{sql}'''), so any query ending in a quoted literal (e.g. recovery_source='EMERGENCY') closed the triple-quoted string early β†’ SyntaxError. Fixed to pass the SQL as a repr'd literal (72e4ad9), plus resolve the interpreter via ~/.sky/python_path (k8s controller pods have no system python3). Retriggering to verify both.

/smoke-test -k test_managed_jobs_emergency_recovery

-Claude

@cg505

cg505 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

/smoke-test --kubernetes -k test_managed_jobs_emergency_recovery

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.

4 participants