Skip to content

[Jobs] Retry transient cluster-status errors in controller monitor loop - #10040

Merged
kevinmingtarja merged 2 commits into
masterfrom
jobs/retry-transient-cluster-status
Jul 25, 2026
Merged

kevinmingtarja merged 2 commits into
masterfrom
jobs/retry-transient-cluster-status

Conversation

@kevinmingtarja

@kevinmingtarja kevinmingtarja commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The managed-jobs controller monitor loop (_monitor_one_task in sky/jobs/controller.py) refreshes cluster status on every poll iteration via backend_utils.refresh_cluster_status_handle. A brief cloud-provider API blip during that refresh — for example an HTTP 503 ServiceUnavailable from the Kubernetes API server, or a momentary network drop on the path to the provider API — surfaces as exceptions.ClusterStatusFetchingError. That call site was not wrapped in a try/except, so the error propagated to run()'s catch-all and triggered emergency recovery on a perfectly healthy job: the cluster is torn down and relaunched from scratch, and the job restarts. One failed 5s status poll should not cost a multi-node job a full restart.

This is the cloud-provider-API twin of the transient-DB-error handling added in #9748 ("[Jobs] Retry transient DB errors in controller monitor loop and cleanup"): the same "a momentary blip must not kill a healthy job" property, for the provider-API path instead of the DB path.

Root cause

  1. On each poll, _monitor_one_task calls managed_job_utils.get_job_status(). For multi-node jobs, even a healthy non-terminal job status falls through to check the actual cluster status (partial preemptions/node failures may not fail the user program immediately). A transient error in get_job_status itself is also recognized as a potential transient error and likewise falls through to the cluster-status check.
  2. That check calls backend_utils.refresh_cluster_status_handle(cluster_name, force_refresh_statuses=set(status_lib.ClusterStatus)).
  3. If the provider status query fails there — e.g. the underlying list_namespaced_pod hits a network error and urllib3 exhausts its socket-level retries inside the client timeout — backend_utils wraps it in exceptions.ClusterStatusFetchingError. Nothing in _monitor_one_task caught it, so it propagated to run()'s broad except (Exception, SystemExit) → "Unexpected controller error" → emergency recovery: best-effort teardown of the (healthy) cluster, backoff, relaunch. After the emergency-recovery budget is exhausted, the job is marked FAILED_CONTROLLER.
  4. Contrast: when the refresh instead returns a non-UP status, the loop routes into the normal preemption-recovery path. So a transient failure to fetch the cluster status should be retried / treated as transient — not escalated as an unexpected controller error.

Note there is no application-level retry anywhere on this path: the Kubernetes client's own retries operate at the socket level and exhaust within seconds, so any blip longer than that (but far shorter than a real outage) escapes as ClusterStatusFetchingError.

Change

  • Add sky/utils/cloud_api_retries.py: a thin retry wrapper built on the existing common_utils.Backoff (no new deps), scoped to ClusterStatusFetchingError. It is deliberately separate from sky/utils/db/retries.py — a provider API 503 is not a DB error, and the two have different retryable exception sets.
  • Wrap the refresh_cluster_status_handle call in _monitor_one_task with it (5 attempts, exponential backoff capped at 5s) so a momentary blip is absorbed transparently.
  • If the refresh still fails after the retry budget, treat it as a transient condition and back off + continue on the next loop iteration, reusing the existing transient-job-status-check window (JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS). A sustained outage that also breaks the job-status probe still escalates once the total timeout is exceeded; as long as get_job_status keeps returning a healthy status (i.e. we have a direct positive signal the job is alive and only the provider status query is failing), the loop keeps retrying rather than restarting a demonstrably running job it could not relaunch anyway (recovery needs the same provider API).
  • The non-transient path is unchanged: a returned non-UP status still routes into recovery exactly as before.

Tested

Unit tests in tests/unit_tests/test_sky/utils/test_cloud_api_retries.py (9 tests, all pass):

$ pytest tests/unit_tests/test_sky/utils/test_cloud_api_retries.py -q
9 passed

Coverage: returns immediately on success; retries each transient ClusterStatusFetchingError; succeeds after N transient failures (proving the transient error does not propagate to the controller catch-all); raises after exhausting the retry budget (a sustained outage still surfaces); respects a custom max_retries; does not retry non-retryable errors; and rejects invalid max_retries.

tests/unit_tests/test_sky/jobs/test_controller.py also passes (including the post-recovery window-reset test from #10156, which shares the transient window this change reuses).

bash format.sh --files <changed files> is clean (yapf, isort, mypy, pylint 10.00/10).

@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 retry mechanism with exponential backoff for transient cloud-provider API errors during cluster status refreshes, preventing momentary API failures from incorrectly marking healthy jobs as failed. The review feedback identifies a critical bug in the retry logic within sky/jobs/controller.py: because transient_job_check_error_start_time is reset elsewhere in the loop, a continuous failure in cluster status fetching would reset the timer and retry indefinitely without ever timing out. The reviewer suggests tracking the transient cluster status errors using separate variables stored on self to ensure the timeout is correctly enforced.

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
Comment on lines +906 to +940
try:
(cluster_status, handle) = await asyncio.to_thread(
cloud_api_retries.with_cloud_api_retries,
lambda: backend_utils.refresh_cluster_status_handle(
cluster_name,
force_refresh_statuses=set(status_lib.ClusterStatus)))
except exceptions.ClusterStatusFetchingError as e:
# The refresh kept failing after retries. Treat it as a
# transient condition and back off, reusing the same window as
# a transient job-status check error so a sustained outage
# still surfaces cleanly once the total timeout is exceeded.
if transient_job_check_error_start_time is None:
transient_job_check_error_start_time = time.time()
job_check_backoff = common_utils.Backoff(
initial_backoff=1, max_backoff_factor=5)
elapsed = time.time() - transient_job_check_error_start_time
timeout = (
managed_job_utils.JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS)
if elapsed >= timeout:
logger.error(
'Failed to refresh cluster status after retrying for '
f'{elapsed:.1f} seconds: '
f'{common_utils.format_exception(e)}')
raise
assert job_check_backoff is not None, (
transient_job_check_error_start_time, job_check_backoff)
backoff_time = min(job_check_backoff.current_backoff(),
timeout - elapsed)
logger.info(
'Failed to refresh cluster status, likely due to a '
'transient provider API error. Retrying to avoid a false '
f'alarm for job failure. Retrying in {backoff_time:.1f} '
f'seconds: {common_utils.format_exception(e)}')
await asyncio.sleep(backoff_time)
continue

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

In the current implementation, transient_job_check_error_start_time is reset to None at line 821 on every iteration where get_job_status succeeds (i.e., transient_job_check_error_reason is None).

If get_job_status succeeds but refresh_cluster_status_handle continuously fails with ClusterStatusFetchingError, transient_job_check_error_start_time will be reset to None at the start of the next iteration, and then set to time.time() again in the except exceptions.ClusterStatusFetchingError block.

As a result, elapsed will always be calculated as approximately 0 seconds, and the loop will retry indefinitely without ever timing out or raising the error after JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS has passed.

To fix this, we should track the transient cluster status refresh errors using a separate set of variables (e.g., stored on self to persist across iterations without needing modifications outside the diff hunks).

            try:
                (cluster_status, handle) = await asyncio.to_thread(
                    cloud_api_retries.with_cloud_api_retries,
                    lambda: backend_utils.refresh_cluster_status_handle(
                        cluster_name,
                        force_refresh_statuses=set(status_lib.ClusterStatus)))
                self._transient_cluster_status_error_start_time = None
                self._cluster_status_backoff = None
            except exceptions.ClusterStatusFetchingError as e:
                # The refresh kept failing after retries. Treat it as a
                # transient condition and back off, using a separate window
                # so a sustained outage still surfaces cleanly once the total
                # timeout is exceeded.
                if getattr(self, '_transient_cluster_status_error_start_time', None) is None:
                    self._transient_cluster_status_error_start_time = time.time()
                    self._cluster_status_backoff = common_utils.Backoff(
                        initial_backoff=1, max_backoff_factor=5)
                elapsed = time.time() - self._transient_cluster_status_error_start_time
                timeout = (
                    managed_job_utils.JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS)
                if elapsed >= timeout:
                    logger.error(
                        'Failed to refresh cluster status after retrying for '
                        f'{elapsed:.1f} seconds: '
                        f'{common_utils.format_exception(e)}')
                    raise
                assert self._cluster_status_backoff is not None, (
                    self._transient_cluster_status_error_start_time, self._cluster_status_backoff)
                backoff_time = min(self._cluster_status_backoff.current_backoff(),
                                   timeout - elapsed)
                logger.info(
                    'Failed to refresh cluster status, likely due to a '
                    'transient provider API error. Retrying to avoid a false '
                    f'alarm for job failure. Retrying in {backoff_time:.1f} '
                    f'seconds: {common_utils.format_exception(e)}')
                await asyncio.sleep(backoff_time)
                continue
References
  1. Follow PEP 8 guidelines for naming variables and keeping code clean and readable. (link)

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.

@gemini-code-assist Thanks — your dataflow observation is correct: a successful get_job_status resets the shared window, so an outage that breaks only the cluster-status refresh retries indefinitely. That behavior is intentional, and f8bb4ef updates the comment to document it. A successful get_job_status is a direct positive liveness signal for the job; giving the refresh handler its own window would escalate after 60s and tear down a job we can directly observe running, purely because the provider status API is unreachable — which is exactly the false alarm this handler exists to prevent (and recovery could not relaunch anyway while that API is down). Escalation to the controller's unexpected-error handling is reserved for the case where both get_job_status and this refresh keep failing for JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS.

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.

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

The managed-jobs controller monitor loop refreshes cluster status on every
poll iteration via backend_utils.refresh_cluster_status_handle. A brief
cloud-provider API blip during that refresh -- for example an HTTP 503
ServiceUnavailable from the Kubernetes API server -- surfaces as
exceptions.ClusterStatusFetchingError. That call site was not wrapped in a
try/except, so the error propagated to run()'s catch-all and marked a
perfectly healthy job FAILED_CONTROLLER, tearing down its cluster.

This is the cloud-provider-API twin of the transient-DB-error handling added
in #9748: the same "a momentary blip must not kill a healthy job" property,
for the provider-API path instead of the DB path.

Add sky/utils/cloud_api_retries.py, a thin retry wrapper built on the
existing common_utils.Backoff (no new deps), scoped to
ClusterStatusFetchingError. It is deliberately separate from
sky/utils/db/retries.py -- a provider API 503 is not a DB error and the two
have different retryable exception sets.

Wrap the refresh_cluster_status_handle call in _monitor_one_task with it
(5 attempts, exponential backoff capped at 5s) so a momentary blip is
absorbed transparently. If the refresh still fails after the retry budget,
treat it as a transient condition and back off + retry on the next loop
iteration, reusing the existing transient-job-status-check window
(JOB_STATUS_FETCH_TOTAL_TIMEOUT_SECONDS) so a sustained outage still
surfaces cleanly as FAILED_CONTROLLER once the total timeout is exceeded --
rather than turning a single 503 into a dead job.

Tested:
- Unit tests in tests/unit_tests/test_sky/utils/test_cloud_api_retries.py
  (9 tests, all pass): retries each transient ClusterStatusFetchingError,
  succeeds after N transient failures, raises after exhausting the budget,
  respects a custom max_retries, does not retry non-retryable errors, and
  rejects invalid max_retries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@kevinmingtarja
kevinmingtarja force-pushed the jobs/retry-transient-cluster-status branch from 2e20d0d to c9e6884 Compare July 25, 2026 18:21
@kevinmingtarja
kevinmingtarja marked this pull request as ready for review July 25, 2026 18:22
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@kevinmingtarja

Copy link
Copy Markdown
Collaborator Author

/smoke-test --kubernetes --no-resource-heavy

A healthy get_job_status is a direct liveness signal; escalation to
emergency recovery is reserved for the case where both the job-status
probe and the cluster-status refresh fail for the full window.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@kevinmingtarja
kevinmingtarja force-pushed the jobs/retry-transient-cluster-status branch from 80fbbcd to f8bb4ef Compare July 25, 2026 18:26
@kevinmingtarja
kevinmingtarja merged commit 6f7eae4 into master Jul 25, 2026
21 checks passed
@kevinmingtarja
kevinmingtarja deleted the jobs/retry-transient-cluster-status branch July 25, 2026 19:13
joseph-zhong added a commit to inductivebias/skypilot that referenced this pull request Sep 9, 2026
Backport skypilot-org/skypilot#10040 commits c9e68840a and f8bb4ef1e onto the deployed Flourish 0.13.0 release line. Brief cluster-status query failures now retry without immediately escalating a healthy managed job to FAILED_CONTROLLER.

Test plan:

- `SKYPILOT_DISABLE_USAGE_COLLECTION=1 SKYPILOT_SKIP_CLOUD_IDENTITY_CHECK=1 .venv/bin/pytest -n 0 --dist no tests/unit_tests/test_sky/utils/test_cloud_api_retries.py tests/unit_tests/test_sky/jobs/test_controller.py`
  `42 passed, 9 warnings in 0.13s`
- `.venv/bin/python -m py_compile sky/jobs/controller.py sky/utils/cloud_api_retries.py tests/unit_tests/test_sky/utils/test_cloud_api_retries.py`
  Exit 0 with no output.
- `.venv/bin/yapf --diff --recursive sky/jobs/controller.py sky/utils/cloud_api_retries.py tests/unit_tests/test_sky/utils/test_cloud_api_retries.py`
  Exit 0 with no output.
- `.venv/bin/isort --check-only sky/jobs/controller.py sky/utils/cloud_api_retries.py tests/unit_tests/test_sky/utils/test_cloud_api_retries.py`
  Exit 0 with no output.
- `.venv/bin/pylint --load-plugins pylint_quotes --ignore-paths "sky/schemas/generated|sky/skylet/providers/ibm" sky/jobs/controller.py sky/utils/cloud_api_retries.py tests/unit_tests/test_sky/utils/test_cloud_api_retries.py`
  `Your code has been rated at 10.00/10`
- `git diff --cached --check`
  Exit 0 with no output.
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.

2 participants