Repository navigation
[Jobs] Retry transient cluster-status errors in controller monitor loop - #10040
Conversation
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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)
continueReferences
- Follow PEP 8 guidelines for naming variables and keeping code clean and readable. (link)
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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>
2e20d0d to
c9e6884
Compare
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
|
/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>
80fbbcd to
f8bb4ef
Compare
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.
Summary
The managed-jobs controller monitor loop (
_monitor_one_taskinsky/jobs/controller.py) refreshes cluster status on every poll iteration viabackend_utils.refresh_cluster_status_handle. A brief cloud-provider API blip during that refresh — for example an HTTP 503ServiceUnavailablefrom the Kubernetes API server, or a momentary network drop on the path to the provider API — surfaces asexceptions.ClusterStatusFetchingError. That call site was not wrapped in atry/except, so the error propagated torun()'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
_monitor_one_taskcallsmanaged_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 inget_job_statusitself is also recognized as a potential transient error and likewise falls through to the cluster-status check.backend_utils.refresh_cluster_status_handle(cluster_name, force_refresh_statuses=set(status_lib.ClusterStatus)).list_namespaced_podhits a network error and urllib3 exhausts its socket-level retries inside the client timeout —backend_utilswraps it inexceptions.ClusterStatusFetchingError. Nothing in_monitor_one_taskcaught it, so it propagated torun()'s broadexcept (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 markedFAILED_CONTROLLER.UPstatus, 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
sky/utils/cloud_api_retries.py: a thin retry wrapper built on the existingcommon_utils.Backoff(no new deps), scoped toClusterStatusFetchingError. It is deliberately separate fromsky/utils/db/retries.py— a provider API 503 is not a DB error, and the two have different retryable exception sets.refresh_cluster_status_handlecall in_monitor_one_taskwith it (5 attempts, exponential backoff capped at 5s) so a momentary blip is absorbed transparently.continueon 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 asget_job_statuskeeps 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).UPstatus 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):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 custommax_retries; does not retry non-retryable errors; and rejects invalidmax_retries.tests/unit_tests/test_sky/jobs/test_controller.pyalso 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).