Refactor GPU orchestrator worker health/lifecycle into single source of truth. Currently 3 separate places assess worker health with overlapping inconsistent logic: worker_state.py _determine_lifecycle, control_loop.py _failsafe_stale_worker_check, control_loop.py _reconcile_orphaned_tasks. Each has own idea of should-I-kill-this-worker and they diverge. startup_phase had to be patched into all 3 independently. Goal: DerivedWorkerState is the ONE verdict, everything else reads it. control/phases/ refactoring started but not wired in. Make obvious and easy to understand. Key files: gpu_orchestrator/worker_state.py, gpu_orchestrator/control_loop.py (1600+ lines god object), gpu_orchestrator/control/phases/*.py, gpu_orchestrator/database.py
code
Plan:
# Implementation Plan: Single Source of Truth for Worker Health Verdicts
Overview
The GPU orchestrator has three overlapping paths that independently assess worker health:
derive_worker_state() (worker_state.py:110-274) — Pure function computing DerivedWorkerState with should_terminate, termination_reason, lifecycle state. This is the intended single source of truth.
_health_check_active_workers() (control_loop.py:484-615) — Re-derives health decisions inline: checks heartbeat staleness (line 543), idle-with-tasks-queued (line 539-562), idle timeout (line 566-573), performs _basic_health_check(), and checks failure streaks — all of which duplicate or conflict with DerivedWorkerState verdicts.
_failsafe_stale_worker_check() (control_loop.py:1577-1641) — Raw datetime arithmetic on heartbeats, completely independent of DerivedWorkerState. Has its own startup_phase gate (lines 1592-1595) that duplicates worker_state.py:308.
The control/phases/ directory has mixin implementations of these methods but they are not wired in — OrchestratorControlLoop still has all 1699 lines inline.
(+ a new ) is the ONE verdict. becomes a thin executor. reads derived state instead of doing its own math. Then wire in the phase mixins to decompose the god object.
Assistant
User
Assistant
{"flags":[{"id":"worker-lifecycle-failsafe-verdict-still-duplicated","concern":"Worker lifecycle: the revised Step 3 still leaves _failsafe_stale_worker_check() as a second health-verdict engine. It stops parsing raw timestamps, but it still recomputes age > cutoff inside control_loop.py instead of consuming a precomputed verdict from DerivedWorkerState, so it does not fully achieve the stated goal that derived state is the one verdict and everything else only reads it.","category":"correctness","severity_hint":"likely-significant","evidence":"In the repo today, DerivedWorkerState exposes raw timing fields plus one termination verdict (, ). The current failsafe is a separate evaluator that applies its own cutoff math (). The revised plan replaces raw datetime parsing with / , but it still keeps the cutoff comparison in failsafe rather than moving that verdict into ."},{"id":"plan-structure-numbered-substeps","concern":"Plan structure: the plan is mostly well-formed, but it still does not fully match the requested step format because some step sections are prose-driven rather than clearly numbered substeps.","category":"completeness","severity_hint":"likely-minor","evidence":"The validator already reports In practice, and are organized around prose/'Remove/Keep' blocks instead of a clean numbered action list."}],"verified_flag_ids":["worker-lifecycle-root-cause-mismatch","worker-lifecycle-startup-phase-regression","scaling-health-boundary-idle-timeout","control-refactor-scope-creep"],"disputed_flag_ids":[]}
Goal:
DerivedWorkerState.should_terminate
should_terminate_failsafe
_health_check_active_workers
_failsafe_stale_worker_check
Phase 1: Consolidate Health Verdicts into DerivedWorkerState
Step 1: Extend DerivedWorkerState with missing health signals (gpu_orchestrator/worker_state.py)
Scope: Medium
Currently derive_worker_state() sets should_terminate for timeout conditions but doesn't cover:
Idle-with-tasks-queued (currently only in _health_check_active_workers line 539-562)
Task failure streak (currently only checked in health phase line 595-610)
Basic health check failure (currently _perform_basic_health_check, line 550-553)
Addidle_with_queued_tasks: bool field to DerivedWorkerState — set when worker is active, has no active task, heartbeat is fresh, but queued_count > 0. The health phase already receives task_counts.queued, and derive_worker_state already takes a queued_count parameter (it's available but unused for this check).
Move the idle-with-stale-heartbeat-while-tasks-queued termination logic from _health_check_active_workers (lines 543-547) into derive_worker_state() as a new termination condition. When lifecycle == ACTIVE_STALE and queued_count > 0, set should_terminate = True, termination_reason = "Idle with stale heartbeat while tasks queued".
Move the no-heartbeat-while-tasks-queued check (lines 556-562) into derive_worker_state() — when active, no heartbeat, effective_age > idle_timeout, and queued > 0.
Addis_failsafe_stale: bool field to DerivedWorkerState — set when heartbeat age exceeds the failsafe cutoff regardless of lifecycle. This replaces the raw datetime logic in _failsafe_stale_worker_check.
Verify that startup_phase gating for failsafe is already handled: if startup_phase is active, _determine_lifecycle returns ACTIVE_INITIALIZING, which has its own timeout (startup_grace_period_sec). The failsafe's separate startup_phase check becomes redundant once we use derived state.
Step 2: Simplify _health_check_active_workers to a thin executor (gpu_orchestrator/control_loop.py:484-615)
Scope: Medium
Remove all inline health re-derivation from _health_check_active_workers:
Delete the idle-with-tasks-queued block (lines 538-562) — now in derived state
Delete the idle-timeout-with-no-work block (lines 564-573) — already in derived state as is_not_claiming
Keep the ws.should_terminate check at the top (lines 499-518) — this is the correct pattern
Simplify the has-active-task path (lines 521-530): keep as-is since it validates heartbeat existence (a real-time check, not a verdict)
Keep_check_stuck_tasks and _check_worker_task_failure_streak calls — these are side-effect-producing checks that query the DB for task history. They can stay in the health phase for now, but their verdicts should flow through DerivedWorkerState in a future pass.
Remove the redundant _perform_basic_health_check call at line 587-589 — this checks heartbeat_age < 60s, which is already captured by heartbeat_is_recent in derived state.
Step 3: Rewrite _failsafe_stale_worker_check to use derived state (gpu_orchestrator/control_loop.py:1577-1641)
Scope: Small
Change signature to accept worker_states: List[DerivedWorkerState] instead of raw workers: List[Dict].
Replace the raw datetime loop (lines 1583-1613) with a filter: stale = [ws for ws in worker_states if ws.is_failsafe_stale and not ws.is_terminal].
Keep the termination action loop (lines 1615-1638) but use ws.runpod_id and ws.worker_id from derived state.
Delete the inline startup_phase gate (lines 1592-1595) — redundant with _determine_lifecycle handling.
Step 4: Add/update tests for consolidated verdicts (tests/gpu_orchestrator/)
Scope: Medium
Add unit tests for the new derive_worker_state() conditions:
Update existing tests in tests/test_scaling_decision_spawn.py and tests/test_scaling_decision_limits.py if they reference the old health check paths.
Run the full test suite to verify no regressions.
Phase 2: Wire in Phase Mixins (Decompose the God Object)
Step 5: Create mixin base and wire phase modules into OrchestratorControlLoop (gpu_orchestrator/control_loop.py, gpu_orchestrator/control/phases/*.py)
Scope: Large
Update each phase mixin to use the simplified logic from Phase 1 (not the old copied code that still has inline health checks).
MakeOrchestratorControlLoop inherit from the mixins:
python
class OrchestratorControlLoop(
StatePhaseMixin,
HealthPhaseMixin,
LifecyclePhaseMixin,
WorkerCapacityPhaseMixin,
ScalingDecisionPhaseMixin,
PeriodicChecksMixin,
):
Delete the corresponding inline methods from control_loop.py as each mixin method is verified to work. Target: reduce control_loop.py from 1699 lines to ~300 (init, run_single_cycle, shared helpers like _mark_worker_error).
Move shared helpers (_mark_worker_error, _mark_worker_error_by_id, _log_detailed_task_breakdown, _log_scaling_decision) to a control/phases/shared.py mixin or keep them on the host class — they satisfy the ControlHost protocol.
VerifyControlHost protocol (control/contracts.py) is satisfied by the resulting class.
Step 6: Integration test the full cycle (tests/gpu_orchestrator/)
Scope: Medium
Run existing integration tests that exercise run_single_cycle.
Add a test that verifies the mixin composition: instantiate OrchestratorControlLoop and confirm all phase methods resolve.
Run_failsafe_stale_worker_check test with mocked derived states to confirm it no longer does raw datetime parsing.
Execution Order
Steps 1-3 first (Phase 1) — consolidate verdicts. This is the high-value change and can land independently.
Step 4 — tests to lock in the new behavior before wiring mixins.
Steps 5-6 (Phase 2) — decompose the god object. This is mechanical refactoring that's lower risk once verdicts are consolidated.
Validation Order
Unit tests for derive_worker_state() (Step 4) — cheapest, most targeted.
Grep for any remaining raw heartbeat datetime arithmetic outside worker_state.py — there should be none after Step 3.
Full test suite after each step to catch regressions.
Manual verification: read the final _health_check_active_workers and confirm it makes NO health decisions — only executes verdicts from DerivedWorkerState.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-29T21:36:34Z",
"hash": "sha256:faf1220e33ec25f447c8f6dd980a68c41f1400a995d1e66789c5bc891a1e2cba",
"questions": [
"Should _check_worker_task_failure_streak (queries DB for failure history) also be absorbed into derive_worker_state(), or should it remain a side-effect in the health phase? Moving it would require making derive_worker_state() async (it's currently a pure function), which changes its testing story significantly.",
"The _perform_basic_health_check function (control_loop.py ~line 550) does a RunPod SSH check beyond just heartbeat age. Should this be kept as a separate real-time probe, or should its result be cached/folded into derived state? It seems like a genuine runtime check vs. a derivable verdict.",
"For Phase 2 (mixin wiring): the phases/ files currently contain copies of the old logic including the duplicate health checks. Should we update them in-place during Step 5, or first land Phase 1 on control_loop.py, verify it works, THEN update the mixin copies to match? (I assume the latter \u2014 incremental is safer.)",
"Is there a CI pipeline or specific test command to run? I see tests/ but want to confirm the right invocation (pytest, specific markers, etc)."
],
"success_criteria": [
"DerivedWorkerState is the ONLY place that computes should_terminate verdicts \u2014 grep for heartbeat datetime arithmetic in control_loop.py returns zero matches outside of worker_state.py",
"_health_check_active_workers contains no if-branches that compute health verdicts \u2014 it only reads ws.should_terminate and ws.termination_reason and acts on them",
"_failsafe_stale_worker_check operates on List[DerivedWorkerState] not List[Dict] \u2014 no raw heartbeat parsing",
"startup_phase is checked in exactly ONE place: _determine_lifecycle in worker_state.py",
"All existing tests pass after Phase 1",
"control_loop.py reduced to <400 lines after Phase 2 (from 1699)",
"New unit tests cover: idle-with-queued-tasks termination, failsafe-stale derivation, startup_phase gating of failsafe"
],
"assumptions": [
"derive_worker_state() should remain a pure (sync) function \u2014 we won't fold async DB queries like failure streak into it. Those checks stay in the health phase as action triggers, not verdicts.",
"The _perform_basic_health_check SSH probe is a runtime check that can't be pre-derived. It stays as a separate call but is only used as a supplementary signal, not a termination verdict source.",
"Phase 1 lands on the inline control_loop.py methods first. Phase 2 updates the mixin copies to match and wires them in. We don't try to do both simultaneously.",
"The control/phases/ mixin files are the target destination but their current contents are stale copies \u2014 they need to be rewritten with the Phase 1 logic, not merged.",
"Task failure streak checking remains a side-effect in the health phase for now, with a future option to cache results in derived state if needed.",
"The idle-timeout-with-no-work logic (control_loop.py:564-573) is already represented by is_not_claiming in DerivedWorkerState and doesn't need a separate field."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Requirements:
- First, assess whether the plan targets the correct root cause. If the proposed fix already exists in the codebase, or if the plan contradicts evidence you find, flag this as CRITICAL — the plan needs a fundamentally different approach, not just adjustments.
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"worker-lifecycle-root-cause-mismatch","concern":"Worker lifecycle: CRITICAL: the plan's root-cause analysis is not aligned with the repo. derive_worker_state() already owns several queued/stale termination verdicts, and _reconcile_orphaned_tasks() is not a competing kill-worker path at all. The remaining duplication is narrower: inline health checks plus failsafe, and the stale copies in control/phases/.","category":"correctness","severity_hint":"likely-significant","evidence":"gpu_orchestrator/worker_state.py:191-223 already terminates ACTIVE_STALE workers with queued tasks and ACTIVE_READY workers that stay idle with queued work. gpu_orchestrator/control_loop.py:766-791_reconcile_orphaned_tasks() only resets tasks for workers already in ERROR/TERMINATED; it does not decide worker health."},{"id":"worker-lifecycle-startup-phase-regression","concern":"Worker lifecycle: CRITICAL: Step 3's plan to delete the failsafe startup_phase guard is unsafe. In the current code, _determine_lifecycle() only consults startup_phase after a real heartbeat exists, so no-heartbeat startup workers would lose their only protection and become failsafe-eligible once they exceed spawning_timeout_sec.","category":"correctness","severity_hint":"likely-significant","evidence":"gpu_orchestrator/control_loop.py:1590-1595 explicitly skips workers in deps_installing/deps_verified/worker_starting during failsafe cleanup. In gpu_orchestrator/worker_state.py:297-323, startup_phase is checked only inside if has_heartbeat:; the no-heartbeat branch still returns spawning states based on startup_script_launched alone."},{"id":"scaling-health-boundary-idle-timeout","concern":"Scaling/health boundary: Step 2 removes the no-work idle-timeout branch on the claim that DerivedWorkerState.is_not_claiming already covers it, but the repo does not support that. is_not_claiming is only derived when queued work exists, while the current no-work path depends on task-history queries and is also reused by scale-down execution. The plan needs an explicit owner for that behavior instead of treating it as already derived.","category":"correctness","severity_hint":"likely-significant","evidence":"gpu_orchestrator/worker_state.py:209-223 sets is_not_claiming only under queued_count > 0. The branch the plan wants to delete is gpu_orchestrator/control_loop.py:564-573, and its semantics come from _is_worker_idle_with_timeout() at gpu_orchestrator/control_loop.py:1271-1302, which checks recent completions and last completion time rather than heartbeat-derived lifecycle."},{"id":"control-refactor-scope-creep","concern":"Control refactor: Scope creep: Phase 2 turns a focused health-verdict consolidation into a second broad class-decomposition project. The mixin infrastructure already exists, so bundling full host rewiring and a <400-line target into the same change increases risk without being necessary to prove the single-source-of-truth fix.","category":"maintainability","severity_hint":"likely-significant","evidence":"gpu_orchestrator/control/contracts.py:11-43 already defines ControlHost; shared helpers already live in gpu_orchestrator/control/diagnostics.py:18-35 and gpu_orchestrator/control/decision_io.py:17-27; phase modules already exist under gpu_orchestrator/control/phases/. Current file sizes are 1699 lines for gpu_orchestrator/control_loop.py and roughly 1400 additional lines across the phase modules (wc -l gpu_orchestrator/control_loop.py gpu_orchestrator/control/phases/*.py)."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Refactor GPU orchestrator worker health/lifecycle into single source of truth. Currently 3 separate places assess worker health with overlapping inconsistent logic: worker_state.py _determine_lifecycle, control_loop.py _failsafe_stale_worker_check, control_loop.py _reconcile_orphaned_tasks. Each has own idea of should-I-kill-this-worker and they diverge. startup_phase had to be patched into all 3 independently. Goal: DerivedWorkerState is the ONE verdict, everything else reads it. control/phases/ refactoring started but not wired in. Make obvious and easy to understand. Key files: gpu_orchestrator/worker_state.py, gpu_orchestrator/control_loop.py (1600+ lines god object), gpu_orchestrator/control/phases/*.py, gpu_orchestrator/database.py
code
Plan:
# Implementation Plan: Single Source of Truth for Worker Health Verdicts
Overview
The GPU orchestrator has two places that independently re-derive health verdicts already computed by DerivedWorkerState:
_health_check_active_workers() (control_loop.py:484-615) — Contains inline checks that duplicate verdicts from derive_worker_state(), plus dead-code branches that are unreachable when using derived state, alongside legitimate async checks that must remain.
_failsafe_stale_worker_check() (control_loop.py:1577-1641) — Raw datetime arithmetic on heartbeats, completely independent of DerivedWorkerState. Has its own startup_phase gate that duplicates worker_state.py:308.
Corrected root cause (vs. v1 plan):_reconcile_orphaned_tasks() (control_loop.py:766-795) is NOT a competing health path — it only resets tasks for workers already in ERROR/TERMINATED state. The actual duplication is narrower than v1 assumed:
The health phase re-checks stale+queued at lines 539-547 (pure duplicate) and has unreachable no-heartbeat branches at lines 521-528 and 556-562 (active workers always have heartbeats by definition of _determine_lifecycle).
The health phase's legitimate non-derived logic that must stay: idle-timeout-with-no-work (line 564-573, uses async _is_worker_idle_with_timeout DB queries), _check_stuck_tasks, _check_worker_task_failure_streak, and _perform_basic_health_check (heartbeat < 60s tighter check).
Startup phase safety constraint:_determine_lifecycle() only checks startup_phase inside the if has_heartbeat: branch (line 298-308). Pre-heartbeat workers in startup phases (e.g., deps_installing) fall into the SPAWNING_* path. The failsafe's separate startup_phase guard (lines 1592-1595) protects these workers when their DB status is active but they haven't heartbeated yet. This guard cannot simply be deleted — it must be preserved in derived state.
Scope: This plan consolidates health verdicts only. God-object decomposition (mixin wiring) is a separate follow-up — the mixin infrastructure already exists in control/phases/ and doesn't need to be bundled here.
Main Phase
Step 1: Add in_startup_phase to DerivedWorkerState (gpu_orchestrator/worker_state.py:40-108)
Scope: Small
The failsafe currently reads raw metadata.startup_phase to skip workers in startup. To make failsafe consume derived state without losing this protection, we need to surface the signal.
Add field in_startup_phase: bool to DerivedWorkerState (after ready_for_tasks, around line 68).
Set it in derive_worker_state() — in_startup_phase = startup_phase in ('deps_installing', 'deps_verified', 'worker_starting'). This is set regardless of heartbeat status, capturing both the heartbeat and no-heartbeat paths.
Set it in the return statement (worker_state.py:250-274).
This is the key safety addition: failsafe stale detection can now skip startup workers by reading ws.in_startup_phase instead of parsing raw metadata.
Step 2: Remove duplicate and dead-code health checks from _health_check_active_workers (gpu_orchestrator/control_loop.py:484-615)
Scope: Medium
Precise identification of what to remove vs. keep:
Remove — duplicate of derived state (lines 539-547):
python
if task_counts.queued > 0:
if ws.has_heartbeat and ws.heartbeat_age_sec is not None:
if ws.heartbeat_age_sec > self.config.gpu_idle_timeout_sec:
# This is STALE_HEARTBEAT_TASKS_QUEUED — already in derive_worker_state line 197-200
This entire stale+queued branch fires only when ACTIVE_STALE + queued > 0, which derive_worker_state already sets as should_terminate=True with error code STALE_HEARTBEAT_TASKS_QUEUED. The ws.should_terminate check at line 499 handles it.
Remove — unreachable dead code (lines 521-528):
python
if ws.has_active_task:
if not ws.has_heartbeat: # Can never be True for active workers
is_active (line 491 filter) requires ACTIVE_* lifecycle. _determine_lifecycle only returns ACTIVE_* when has_heartbeat=True (line 298). So not ws.has_heartbeat is always False here.
Remove — unreachable dead code (lines 556-562):
python
else: # No heartbeat while tasks are queued
worker_age = ...
Same reasoning — active workers always have heartbeats. This branch is unreachable.
Keep — legitimate async/runtime checks:
Lines 549-553: _perform_basic_health_check (tighter 60s heartbeat check for fresh-but-not-claiming workers with queued tasks). Not a duplicate — derive_worker_state uses gpu_idle_timeout_sec for ACTIVE_STALE, while this uses a tighter 60s window.
Lines 564-573: idle-timeout-with-no-work via _is_worker_idle_with_timeout(). This queries task completion history (async DB call at control_loop.py:1271-1302) and is used by scale-down. Cannot be pre-derived.
Lines 592-610: _check_stuck_tasks and _check_worker_task_failure_streak — async DB queries, side-effect producing.
Lines 587-589: _perform_basic_health_check for idle workers with fresh heartbeat (supplementary signal).
Step 3: Rewrite _failsafe_stale_worker_check to use derived state (gpu_orchestrator/control_loop.py:1577-1641)
Scope: Medium
Change signature to accept worker_states: List[DerivedWorkerState] instead of raw workers: List[Dict].
Replace the raw datetime loop (lines 1583-1613) with a filter on derived state:
python
stale_workers = []
for ws in worker_states:
if ws.is_terminal:
continue
if ws.in_startup_phase:
continue # Preserve startup protection — matches current line 1592-1595
if ws.should_terminate:
continue # Already handled by health phase
# Use derived heartbeat_age_sec and effective_age_sec instead of raw datetime parsing
cutoff_sec = self.config.spawning_timeout_sec if ws.is_spawning else self.config.gpu_idle_timeout_sec
age = ws.heartbeat_age_sec if ws.has_heartbeat else ws.effective_age_sec
if age is not None and age > cutoff_sec:
stale_workers.append(ws)
Update the termination loop (lines 1615-1638) to use ws.runpod_id and ws.worker_id instead of raw dict access.
Update the caller in _run_periodic_checks to pass worker_states instead of raw workers.
Safety note: The in_startup_phase check preserves the exact semantics of the current startup_phase guard at lines 1592-1595, including protection for pre-heartbeat workers whose _determine_lifecycle path doesn't check startup_phase.
Find the _run_periodic_checks method and update its call to _failsafe_stale_worker_check to pass worker_states (derived) instead of raw workers.
Verify that worker_states is available in scope at the call site — it's passed as a parameter to _run_periodic_checks already or can be threaded through from run_single_cycle.
Step 5: Update stale phase copies (gpu_orchestrator/control/phases/health.py, gpu_orchestrator/control/phases/periodic.py)
Scope: Small
The control/phases/ files contain stale copies of the old logic. Update them to match the changes from Steps 2-3 so they don't drift further:
Updatephases/health.py_health_check_active_workers — remove the same duplicate/dead-code branches removed in Step 2.
Updatephases/periodic.py_failsafe_stale_worker_check — apply the same derived-state rewrite from Step 3.
Step 6: Add tests for the changes (tests/gpu_orchestrator/)
test_in_startup_phase_set_without_heartbeat — startup_phase='deps_installing' + no heartbeat → in_startup_phase=True (the key safety case)
test_in_startup_phase_false_when_none — no startup_phase → in_startup_phase=False
Add regression test for the startup-phase failsafe protection:
test_failsafe_skips_startup_phase_workers — worker with in_startup_phase=True is not marked stale by failsafe
Verify existing tests still pass — the derived state changes are additive (new field), and health check changes only remove duplicate/dead paths.
Run full test suite.
Execution Order
Step 1 first — additive change to DerivedWorkerState, zero risk, enables everything else.
Steps 2-4 together — remove duplicates from health phase and rewrite failsafe. These are coupled.
Step 5 — sync stale phase copies after the canonical code is updated.
Step 6 — tests to lock in behavior.
Validation Order
Unit tests for derive_worker_state() with new in_startup_phase field (Step 6.1-6.3).
Grep for raw startup_phase metadata access outside worker_state.py — after Step 3, the failsafe should read ws.in_startup_phase not metadata.get('startup_phase').
Grep for raw heartbeat datetime arithmetic in _failsafe_stale_worker_check — should be zero after Step 3.
Manual verification: read final _health_check_active_workers and confirm the only verdict-computing branch is ws.should_terminate at the top. The remaining branches should be async DB queries or runtime probes, not heartbeat arithmetic.
Full test suite pass.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-03-29T21:59:04Z",
"hash": "sha256:c442fd70c156b7bed597731133dd2a40558310015eb2656c5f74600b07ba1ad7",
"changes_summary": "Corrected root-cause analysis (removed _reconcile_orphaned_tasks as a competing path \u2014 it only handles dead workers). Preserved failsafe startup_phase guard via new in_startup_phase field on DerivedWorkerState. Narrowed health check cleanup to actual duplicates (stale+queued at lines 539-547) and dead code (no-heartbeat branches at 521-528, 556-562), explicitly keeping legitimate async checks (idle timeout, failure streaks, basic health). Dropped Phase 2 (mixin wiring) as out of scope.",
"flags_addressed": [
"worker-lifecycle-root-cause-mismatch",
"worker-lifecycle-startup-phase-regression",
"scaling-health-boundary-idle-timeout",
"control-refactor-scope-creep"
],
"questions": [
"Is there a CI pipeline or specific test command to run? I see tests/ but want to confirm the right invocation (pytest, specific markers, etc).",
"The _perform_basic_health_check at line 549-553 (fresh heartbeat but not claiming, with queued tasks) applies a 60s threshold that's tighter than gpu_idle_timeout_sec. Should this tighter check eventually move into derive_worker_state as a separate termination condition, or is it intentionally a supplementary runtime probe?"
],
"success_criteria": [
"DerivedWorkerState has in_startup_phase: bool field that is set regardless of heartbeat status",
"_failsafe_stale_worker_check accepts List[DerivedWorkerState] and does zero raw datetime parsing or metadata access",
"_health_check_active_workers has no duplicate stale+queued check \u2014 the only verdict branch is ws.should_terminate at the top",
"Dead code removed: no-heartbeat branches in health check (lines 521-528, 556-562) are gone",
"startup_phase raw metadata access (metadata.get('startup_phase')) does not appear in _failsafe_stale_worker_check",
"Idle-timeout-with-no-work path (lines 564-573) is preserved unchanged in health phase",
"All existing tests pass",
"New tests cover: in_startup_phase field derivation (with and without heartbeat), failsafe skipping startup workers"
],
"assumptions": [
"derive_worker_state() remains a pure synchronous function \u2014 async DB queries (failure streaks, task history, idle timeout) stay in the health phase.",
"_perform_basic_health_check (heartbeat < 60s) is a tighter threshold than the stale detection in derive_worker_state (gpu_idle_timeout_sec). It stays in the health phase as a supplementary probe for the fresh-but-not-claiming case.",
"The control/phases/ mixin files are stale copies that should be updated to match canonical code but NOT wired in as part of this plan.",
"_reconcile_orphaned_tasks is NOT a health verdict path and requires no changes in this plan \u2014 it correctly only handles ERROR/TERMINATED workers.",
"The idle-timeout-with-no-work path (lines 564-573) using _is_worker_idle_with_timeout is a scale-down concern, not a health verdict. It stays in the health phase and is NOT mapped to any derived field."
],
"structure_warnings": [
"Each step section should include at least one numbered substep."
],
"delta_from_previous_percent": 85.03
}
code
Plan structure warnings from validator:
[
"Each step section should include at least one numbered substep."
]
code
Existing flags:
[
{
"id": "worker-lifecycle-root-cause-mismatch",
"concern": "Worker lifecycle: CRITICAL: the plan's root-cause analysis is not aligned with the repo. derive_worker_state() already owns several queued/stale termination verdicts, and _reconcile_orphaned_tasks() is not a competing kill-worker path at all. The remaining duplication is narrower: inline health checks plus failsafe, and the stale copies in control/phases/.",
"status": "addressed",
"severity": "significant"
},
{
"id": "worker-lifecycle-startup-phase-regression",
"concern": "Worker lifecycle: CRITICAL: Step 3's plan to delete the failsafe startup_phase guard is unsafe. In the current code, _determine_lifecycle() only consults startup_phase after a real heartbeat exists, so no-heartbeat startup workers would lose their only protection and become failsafe-eligible once they exceed spawning_timeout_sec.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scaling-health-boundary-idle-timeout",
"concern": "Scaling/health boundary: Step 2 removes the no-work idle-timeout branch on the claim that DerivedWorkerState.is_not_claiming already covers it, but the repo does not support that. is_not_claiming is only derived when queued work exists, while the current no-work path depends on task-history queries and is also reused by scale-down execution. The plan needs an explicit owner for that behavior instead of treating it as already derived.",
"status": "addressed",
"severity": "significant"
},
{
"id": "control-refactor-scope-creep",
"concern": "Control refactor: Scope creep: Phase 2 turns a focused health-verdict consolidation into a second broad class-decomposition project. The mixin infrastructure already exists, so bundling full host rewiring and a <400-line target into the same change increases risk without being necessary to prove the single-source-of-truth fix.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Requirements:
- First, assess whether the plan targets the correct root cause. If the proposed fix already exists in the codebase, or if the plan contradicts evidence you find, flag this as CRITICAL — the plan needs a fundamentally different approach, not just adjustments.
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
gpu_orchestrator/worker_state.py:40-79
gpu_orchestrator/worker_state.py:182-238
gpu_orchestrator/control_loop.py:1577-1613
ws.heartbeat_age_sec
ws.effective_age_sec
worker_state.py
Each step section should include at least one numbered substep.
### Step 2
### Step 5
“You are an independent reviewer. Critique the plan against the actual repository.….” Conversation with gpt-5.4, from the Peter O’Mallet DataClaw Conversations dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80eq00dw7j65q9avzqd75na