Skip to content

[issue-3023][slice-1/3] Orchestrator-side phase-level idle-budget a... - #3034

Closed
james-in-a-box[bot] wants to merge 9 commits into
egg/issue-3023/workfrom
egg/issue-3023/slice-1
Closed

james-in-a-box[bot] wants to merge 9 commits into
egg/issue-3023/workfrom
egg/issue-3023/slice-1

Conversation

@james-in-a-box

@james-in-a-box james-in-a-box Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Invert the BRC agent lifecycle. Today the orchestrator spawns the full
team at phase start and each pod runs a long-lived in-pod event-pump bash
loop (orchestrator/consensus_wrapper.py) that long-polls the bus and
invokes the agent one-shot per event, staying alive (idle, heartbeating,
holding a gateway session) for the whole phase. This PR lifts the wait out
of the pods into the orchestrator as a single blocking thread covering all
agents: the orchestrator derives per-role actionability with
_derive_next_action and spawns a one-shot pod only when a role has an
actionable event; the pod handles the event and exits. No idle pods.

Per-phase reuse of the prompt-cache prefix, gateway session, and worktree
is UNCHANGED — the orchestrator now holds the per-(pipeline, role) session
alive and reuses the per-role worktree PVC across spawns. Resolves the
refine HITL decisions: cq-1 no cold-start SLO (resource-freeing, not
latency-gated); cq-2 orchestrator-held per-role session; cq-3 phase-level
"no spawns for X min" idle alert (same stuck-phase-transition tag/threshold);
cq-4 big-bang, rollback-by-git-revert; cq-5 delete consensus_wrapper.py
entirely; cq-6 overseer agents out of scope (follow-up issue).

Three dependent slices, single PR: (1) orchestrator-side phase-level
idle-budget alert; (2) the on-demand spawner + per-(pipeline, role)
worktree-PVC and gateway-session reuse, with the still-spawned wrapper pod
made passive via env guards so exactly one path emits BRC verbs; (3)
consensus_wrapper.py retirement + entrypoint simplification to
python3 -m egg_agent.

This slice

Orchestrator-side phase-level idle-budget alert

Files affected:

  • orchestrator/phase_idle_budget.py
  • orchestrator/tests/test_phase_idle_budget.py
  • orchestrator/routes/pipelines.py
  • orchestrator/tests/test_pipelines_phase_idle_budget.py
  • orchestrator/concurrent_executor.py
  • orchestrator/consensus_wrapper.py
  • orchestrator/tests/test_consensus_wrapper.py

Tasks:

  • task-1-1: Create orchestrator/phase_idle_budget.py with a PhaseIdleBudgetTimer class. Owns DEFAULT_PHASE_IDLE_BUDGET_MIN = 30 (parity with consensus_wrapper.py:59); state (pipeline_id, phase, last_spawn_at, last_alert_at, per_role_last_action); APIs record_spawn(pipeline_id, phase, role, action), check(now, pending_hitl_count), reset. Emits stuck-phase-transition once at the 1x threshold and once at 2x via the same overseer-alert entry point overseer/monitor.py uses. HITL-pending suppression (AC-R13): when pending_hitl_count>0 the 1x alert downgrades to priority=low with pending_hitl_ids in reason and the 2x alert is suppressed. Every alert carries a structured per_role_state payload field (AC-R4) derived from per_role_last_action. Idempotent re-fire within a threshold bucket.
    • Acceptance criteria: - File exists; class exposes record_spawn, check, reset; constant == 30. - Unit tests: 0 idle min -> no emit; 30 min -> 1x emit once with populated per_role_state; 60 min -> 2x emit once (1x not re-emitted); record_spawn resets and updates per-role state; idempotent across check() calls in the same bucket; pending_hitl_count=1 at 30 min -> priority=low + pending HITL id in reason; pending_hitl_count=1 at 60 min -> no additional alert.
  • task-1-2: Wire PhaseIdleBudgetTimer.check(now, pending_hitl_count) into the orchestrator's existing per-phase tick in orchestrator/routes/pipelines.py (the run loop that already polls consensus for phase completion). Each tick reads the pending-HITL count (routes/decisions.py open-decision count), calls check(now=monotonic, pending_hitl_count=...), and emits a structured phase_idle_budget_tick log once per emitted alert.
    • Acceptance criteria: - Tick invokes check exactly once per loop iteration. - After the fixture advances past 30 min with no record_spawn and zero pending HITL, the overseer alert handler is invoked exactly once with anomaly="stuck-phase-transition", priority=medium. - With one pending HITL the same interval emits priority=low and the pending HITL id appears in reason.
  • task-1-3: Coexistence guard while the in-pod wrapper still exists (until slice 3): the orchestrator timer is authoritative and the wrapper's consensus_wrapper.py:531-549 emitter is silenced behind a branch keyed on a new EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator env var injected unconditionally by concurrent_executor._spawn_agent. Slice 3 deletes the wrapper-side emitter outright.
    • Acceptance criteria: - EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator appears in the spawn env from _spawn_agent for every role. - Wrapper unit test confirms the alert subshell short-circuits when the var is set; alert emitted exactly once per phase per threshold (no double-emit).

Test Plan

Automated (make test is changeset-aware; make test-all for CI ground truth):

  • Unit: PhaseIdleBudgetTimer, OnDemandSpawner (mocked spawner+tracker),
    OrchestratorSessionKeepAlive (mocked gateway), KubernetesSpawner
    create_on_demand_spawn_fn (mocked k8s API), derive_next_action
    in-process/route parity.
  • Integration: orchestrator run loop drives one full BRC cycle
    (propose -> ack -> confirm) for a role, asserting one spawn per
    actionable event, zero spawns on wait, bare python3 -m egg_agent
    command (no bash -c), per-spawn log retention, and the phase-level
    idle alert at 30 min of no spawns.
  • Restart resilience: orchestrator restart mid-phase; reconstruct-from-
    messages fallback (routes/consensus.py:111-154) still works; the tick
    re-derives next-action and spawns whatever was actionable; session
    keep-alive re-populated.
  • No BRC behaviour change: per-event prompt byte-identical to the
    wrapper-rendered prompt for the same (role, event_payload); prefix-cache
    hit rate preserved (LiteLLM cost/cache logger).

Manual (reviewer):

  • make test and make lint green.
  • Before/after grep for consensus_wrapper / build_consensus_wrapped_command
    / EVENT_PUMP_ shows zero production matches post-slice-3.

Manual Steps

Pre-merge: none.

Post-merge (operator drain-then-revert protocol; cq-4 big-bang has no
feature flag, so a revert must drain in-flight pipelines first):
egg-orch pipeline list --running

For each running pipeline:

- if it can finish in <T hours, let it run to completion

- else: egg-orch pipeline cancel --reason "pre-revert drain"

Then git revert the commit on main; the reverted orchestrator's

pod-state reader (TASK-3-5) tolerates either lifecycle so freshly

spawned pipelines work.

File the cq-6 overseer-unification follow-up issue and the spawn_all
rename follow-up issue; link both from the PR closeout.

Stack

  • Position: slice 1 of 3 in pipeline issue-3023
  • Stacked on top of egg/issue-3023/work

Slice slice-1 of pipeline issue-3023. Stacked on top of egg/issue-3023/work.

@egg-reviewer egg-reviewer 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.

Review summary

Requesting changes. There are two blocking defects that together make this slice non-functional in production: (1) the emitter wiring raises TypeError on every alert, silently swallowed by the outer try/except, so no stuck-phase-transition alert ever reaches the message bus; and (2) even if (1) is fixed, slice-1 is wired such that the orchestrator timer sees real progress zero times after the seed, so it will reliably fire a medium alert at 30 min and a high alert at 60 min on every phase that runs that long — regardless of whether real BRC progress is happening — while the wrapper-side emitter that did know about progress has been silenced. Net effect: the wrapper's working alert is turned off, and a false-positive alert is turned on.

Both are blocking. Detail and reproductions below.


Blocking 1 — _make_phase_idle_budget_emitter raises TypeError on every emit (alert never reaches operators)

orchestrator/routes/pipelines.py:15093-15115

def _make_phase_idle_budget_emitter(
    *,
    pipeline: Pipeline,
    pipeline_id: str,
    slice_id: str | None,
):
    def _emitter(**kwargs: Any) -> None:
        _publish_phase_idle_budget_alert(
            pipeline=pipeline,
            pipeline_id=pipeline_id,   # <-- closure pipeline_id
            slice_id=slice_id,
            **kwargs,                  # <-- timer ALSO passes pipeline_id
        )
    return _emitter

PhaseIdleBudgetTimer._emit_threshold (orchestrator/phase_idle_budget.py:349-359) calls the emitter with pipeline_id=self.pipeline_id among its kwargs. So _emitter(**kwargs) ends up calling _publish_phase_idle_budget_alert(pipeline=…, pipeline_id=<closure>, slice_id=…, pipeline_id=<from-timer>, …), which is the classic "multiple values for keyword argument" error.

Reproduction (matches the production shape exactly):

def _publish(*, pipeline, pipeline_id, slice_id, anomaly, **_extra): pass

def _make_emitter():
    pipeline = object(); pipeline_id = "p1"; slice_id = None
    def _emitter(**kwargs):
        _publish(pipeline=pipeline, pipeline_id=pipeline_id, slice_id=slice_id, **kwargs)
    return _emitter

_make_emitter()(
    anomaly="stuck-phase-transition", pipeline_id="p1",
    phase="implement", per_role_state={}, pending_hitl_ids=(),
    threshold_multiplier=1, summary="s", reason="r", priority="medium",
)
# TypeError: _publish() got multiple values for keyword argument 'pipeline_id'

The TypeError is caught by the outer try/except Exception as idle_err: logger.warning(...) wrapped around _tick_phase_idle_budget at routes/pipelines.py:17768-17781. So the orchestrator keeps polling — but msg_store.add_message is never reached, no OVERSEER_ALERT is published, and the structured phase_idle_budget_tick log at routes/pipelines.py:15074 never fires either (it's inside the same try-block as add_message, after the call that never executes).

This is not caught by any test in the PR — every test in test_phase_idle_budget.py and test_pipelines_phase_idle_budget.py injects a MagicMock directly as alert_emitter, so the real _make_phase_idle_budget_emitter closure is never exercised.

Fix: drop pipeline_id from the explicit kwargs (the timer's value is the source of truth), or rename the closure parameter and pass pipeline_id=kwargs.pop("pipeline_id", pipeline_id). Add a test that exercises the real _make_phase_idle_budget_emitter end-to-end with a mock MessageStore — the timer→emitter→message-store path must have at least one test that doesn't stub out the closure.

Blocking 2 — slice-1 always-on alert is a false positive on every long phase

orchestrator/routes/pipelines.py:17522-17534

# Seed the timer with the phase identity so ``check()`` has the
# binding it needs before any slice-2 ``record_spawn`` calls land.
# Without this the first 30 min of every phase would no-op silently
# (the timer requires a record_spawn to bind the (pipeline_id, phase)
# pair, and slice-1 doesn't yet wire record_spawn into the per-event
# spawn path — that's slice-2 task-2-8).
phase_idle_timer.record_spawn(
    pipeline_id=pipeline_id, phase=phase_str,
    role="orchestrator", action="phase_start", now=start_time,
)

This is the only record_spawn call in production code for slice-1 — confirmed by grep across orchestrator/ (no non-test, non-phase_idle_budget.py matches). The comment explicitly acknowledges it: "slice-1 doesn't yet wire record_spawn into the per-event spawn path — that's slice-2 task-2-8."

But task-1-3 does land the coexistence guard that silences the wrapper-side check_idle_budget whenever EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator (which concurrent_executor.get_agent_env now sets unconditionally for every role). And the wrapper's LAST_PROGRESS / note_progress bookkeeping that genuinely tracked actionable BRC events (consensus_wrapper.py:566-573, 654, 688, 704) is now dead — the counter still ages, but the alert path is short-circuited.

So once this PR merges, the operator experience becomes:

  • Wrapper-side: sees real progress (every successful propose/ack/nack/confirm/wait-with-event), tracks LAST_PROGRESS, but alert is silenced.
  • Orchestrator-side: never sees a record_spawn after the phase-start seed, so idle = now - last_spawn_at rises monotonically with wall-clock time. A medium stuck-phase-transition alert fires at exactly 30 min after phase start; a high follow-up at 60 min — regardless of whether agents are actively making BRC progress.

Implement phases routinely run far longer than 30 min on this codebase. Every one of them will page operators with a misleading "phase '' has been idle for ~30 min (crossed 30 min budget)" message that names roles whose per_role_last_action is permanently phase_start. The alert body literally says "No BRC spawn for phase '…' in 30 min" — which is true in the sense that the orchestrator timer has seen no spawn, and false in the sense the operator will read it ("nothing is happening").

The PR text frames slice-1 as standalone-mergeable ("cq-4: big-bang, rollback-by-git-revert"), so this is the operator-facing reality between slice-1 merge and slice-2 merge. Two paths off the bottom:

  1. Don't silence the wrapper-side emitter yet. Move the EGG_PHASE_IDLE_BUDGET_OWNER env-var injection (and the wrapper-side coexistence guard) to slice-2, where record_spawn is actually wired into the BRC event path. Slice-1 can land just phase_idle_budget.py + the unit tests + the _tick_phase_idle_budget wiring; the orchestrator timer remains armed but produces nothing useful until slice-2, at which point the wrapper goes quiet and the orchestrator takes over with a real progress signal.
  2. Skip the phase-start seed in slice-1 so the timer stays unbound (check() no-ops while pipeline_id is None). This requires that _tick_phase_idle_budget tolerate the unbound state (it already does — check returns immediately at phase_idle_budget.py:238-240). The alert will then never fire in slice-1, which is exactly what's wanted given the orchestrator has no real progress signal yet. Slice-2 lands record_spawn calls that bind the timer for the first time.

Option (1) is the safer of the two — it preserves the working wrapper alert through the coexistence window. Option (2) accepts an alert gap during the coexistence window but is the minimum diff. Either is fine; the current shape (silence the working alert, fire a fake one) is not.


Non-blocking

Comment vs. code mismatch on the phase_idle_budget_tick log — routes/pipelines.py:15070-15082 claims "Structured log once per emission so operators grepping phase_idle_budget_tick get a one-line record of every threshold cross independent of whether the message bus is healthy." But the logger.info("phase_idle_budget_tick", …) call is inside the same try: block as msg_store.add_message, after the call. If add_message raises, the structured log is never emitted; the exception handler writes a different "Failed to publish phase-idle-budget OVERSEER_ALERT" warning instead. To match the comment, hoist the phase_idle_budget_tick info log outside the try/except (or duplicate it in the exception branch with published=False).

The timer's phase kwarg is dead — _publish_phase_idle_budget_alert accepts phase but immediately overwrites phase_value = pipeline.current_phase.value. The comment at 15995-14998 says "the phase arg the timer passes is the same value but de-duped here in case the pipeline transitioned between check() and emit()" — but using pipeline.current_phase over the timer's bound phase means an alert about phase X (which the timer was tracking) will say "phase Y is idle" if the pipeline has since transitioned. Either trust the timer's phase and drop the override, or remove the unused parameter. Right now it's confusing as documented.

Dead branch in a test heuristic — test_pipelines_phase_idle_budget.py:1812 has

"PhaseIdleBudget" in line.lower().replace("_", "")

line.lower() lowercases the haystack, then we look for "PhaseIdleBudget" (with capitals) inside it. This can never match. The other OR branches save the test, but the line should either be "phaseidlebudget" in line.lower().replace("_", "") or be removed.

Doc/code drift on reset() "called at phase transition" — both phase_idle_budget.py:185-200 and docs/guides/pipeline-health-monitoring.md:110 say reset() is called on phase transition. In slice-1 production code, reset() is never called: the timer is a local variable inside _run_concurrent_phase and is dropped when the function returns; each phase invocation creates a fresh instance. The class can keep reset() for slice-2/3 / tests, but the doc claim "re-armed only by PhaseIdleBudgetTimer.reset() on phase transition" is inaccurate today — re-arming happens by per-phase instance lifetime.

_BUDGET_RESET_GAP_SECS = 60 debounce will skip resets on close-spaced spawns — phase_idle_budget.py:141-183: when slice-2 lands real record_spawn calls, multiple spawns within 60s of one another do not advance last_spawn_at. Trace-checked across several spacings and continuous activity never tips the 30-min budget (each "gap >= 60s" spawn rebases the window), but the intent line "a flurry of spawns at phase fan-out is the phase starting, not progress against the idle budget" reads as though the first spawn after a quiet gap should always count. The current implementation does that, but the comment is worth tightening so slice-2 can validate against an unambiguous spec.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

This comment has been minimized.

james-in-a-box Bot pushed a commit that referenced this pull request Jun 9, 2026
…nits

Blocking fixes:

- Drop ``pipeline_id`` from the explicit kwargs in
  ``_make_phase_idle_budget_emitter`` so the timer's per-emit
  ``pipeline_id`` no longer collides with the closure capture. Before:
  every alert raised ``TypeError: got multiple values for keyword
  argument 'pipeline_id'`` and the outer ``try/except`` around
  ``_tick_phase_idle_budget`` swallowed it, so production never
  published a single ``stuck-phase-transition`` alert. Added a direct
  closure-binding regression test that builds the real factory + real
  timer and asserts ``add_message`` lands once with the right payload.

- Remove the ``phase_start`` ``record_spawn`` seed in
  ``_run_concurrent_phase``. Slice-1 does not yet wire ``record_spawn``
  into the per-event path (slice-2 task-2-8 lands that), so the seed
  turned every long-running phase into a guaranteed false-positive
  ``medium`` alert at 30 min and ``high`` alert at 60 min — the
  orchestrator-side ``last_spawn_at`` never advanced. The wrapper-side
  emitter is silenced via ``EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator``
  per task-1-3, so silencing both sides during the slice-1 coexistence
  window is the operator-correct choice (an alert gap beats a false
  page). ``check()`` no-ops while unbound; slice-2 will bind on first
  real spawn.

Non-blocking fixes called out in the same review:

- Hoist the ``phase_idle_budget_tick`` structured log out of the
  ``try`` so it still emits when ``msg_store.add_message`` raises
  (matches the docstring claim "independent of whether the message bus
  is healthy"); carry a ``published`` / ``publish_error`` flag.

- Trust the timer's ``phase`` kwarg as the alert's source of truth
  instead of overriding with ``pipeline.current_phase`` — naming a
  different phase if the pipeline transitioned between ``check()`` and
  ``emit()`` was the failure mode.

- Replace the dead ``"PhaseIdleBudget" in line.lower()`` branch in
  ``test_check_call_site_is_exactly_one_per_tick`` with the
  case-normalised form so the OR-branch actually contributes.

- Update the class docstring + ``reset()`` docstring + the
  pipeline-health-monitoring guide to reflect that slice-1 re-arms by
  per-phase instance lifetime, not by ``reset()``.

- Rewrite the ``_BUDGET_RESET_GAP_SECS`` comment as an unambiguous spec
  so slice-2 ``record_spawn`` call sites have a clear contract to
  validate against.

Refs #3023.

— Authored by egg
@james-in-a-box

james-in-a-box Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — both blocking items addressed in-PR, plus all four non-blocking nits.

Disposition

  • Blocking 1 — _make_phase_idle_budget_emitter raises TypeError on every emit: fixed-in-PR (commit 4eee474). The closure now pops pipeline_id from kwargs before forwarding, so the timer's value wins and the duplicate-kwarg collision is gone. Added TestMakePhaseIdleBudgetEmitterClosure in orchestrator/tests/test_pipelines_phase_idle_budget.py that constructs the real factory + real timer + stubbed _get_message_store and asserts msg_store.add_message is called exactly once with the canonical stuck-phase-transition payload (no more closure-side stubbing). This catches the exact shape of the regression directly.

  • Blocking 2 — slice-1 always-on alert is a false positive on every long phase: fixed-in-PR (commit 4eee474). Took your option (2): removed the phase_start record_spawn seed in _run_concurrent_phase. The timer stays unbound, check() no-ops while pipeline_id is None, and no alerts fire in slice-1. The wrapper-side emitter is silenced via EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator (task-1-3 AC), so this accepts the alert-gap during the coexistence window — strictly better than the false page. Slice-2 task-2-8 lands real record_spawn calls that bind the timer for the first time. Comment at the seed-removal site spells this out.

  • Non-blocking — phase_idle_budget_tick log comment vs. code mismatch: fixed-in-PR (commit 4eee474). Hoisted the structured log out of the publish try so it still emits when msg_store.add_message raises; carries published (bool) and publish_error (str | None) fields so operators see both threshold crosses and publish failures in one log stream.

  • Non-blocking — timer's phase kwarg is dead: fixed-in-PR (commit 4eee474). _publish_phase_idle_budget_alert now trusts the timer's phase directly; pipeline is del'd in the body but kept in the signature for forward-compat with slice-2 wiring. Comment explains why (the timer bound the phase on first record_spawn; reading pipeline.current_phase would name the wrong phase if a transition raced).

  • Non-blocking — dead branch in test heuristic: fixed-in-PR (commit 4eee474). Changed "PhaseIdleBudget" in line.lower().replace("_", "") to "phaseidlebudget" in line.lower().replace("_", "") so the OR-branch actually contributes.

  • Non-blocking — doc/code drift on reset() "called at phase transition": fixed-in-PR (commit 4eee474). Updated the class docstring, the reset() docstring, and the pipeline-health-monitoring.md table row to reflect that slice-1 re-arms by per-phase instance lifetime; reset() is exposed for tests and cross-phase reuse but is not on the slice-1 production hot path.

  • Non-blocking — _BUDGET_RESET_GAP_SECS = 60 debounce comment unclear: fixed-in-PR (commit 4eee474). Rewrote the comment as an explicit spec — record_spawn updates last_spawn_at iff first_call OR (now - last_spawn_at >= _BUDGET_RESET_GAP_SECS); per_role_last_action updates unconditionally. Gives slice-2 a clear contract.

Verification

  • ruff check — clean on all four modified files.
  • make lint — the only mypy errors are pre-existing in shared/egg_agent/client.py (verified via git stash + re-run; nothing touched in this PR).
  • pytest orchestrator/tests/test_phase_idle_budget.py orchestrator/tests/test_pipelines_phase_idle_budget.py — 22 passed (16 unit + 6 wiring, including the two new closure-binding tests). Full make test not run per the addressing-feedback workflow guidance; CI will confirm on push.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer 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.

Review summary

Approving. Both blocking defects from the prior review are properly fixed with regression coverage, and all four non-blocking nits are addressed.


Blocking 1 — _make_phase_idle_budget_emitter TypeError: fixed

routes/pipelines.py:15127-15137 now pops pipeline_id from the timer's kwargs before forwarding:

def _emitter(**kwargs: Any) -> None:
    emit_pipeline_id = kwargs.pop("pipeline_id", _closure_pipeline_id)
    _publish_phase_idle_budget_alert(
        pipeline=pipeline,
        pipeline_id=emit_pipeline_id,
        slice_id=slice_id,
        **kwargs,
    )

The duplicate-kwarg collision is gone; the closure fallback to _closure_pipeline_id is purely defensive (check() only calls the emitter after record_spawn has bound self.pipeline_id).

Regression coverage: TestMakePhaseIdleBudgetEmitterClosure in test_pipelines_phase_idle_budget.py:280-423 constructs the real factory + real timer + patched _get_message_store and asserts msg_store.add_message is called exactly once with the canonical payload (pipeline_id, from_role="orchestrator", to_role="all", MessageType.OVERSEER_ALERT, phase="implement", per_role_state={"coder": "propose"}, etc.). The dedicated test_timer_to_emitter_does_not_raise_type_error further pins the no-TypeError contract directly. This is the closure-crossing test the prior review asked for.

Blocking 2 — slice-1 always-on false-positive alert: fixed

routes/pipelines.py:17546-17560 removes the phase_start record_spawn seed. The timer stays unbound during slice-1; check() short-circuits at phase_idle_budget.py:265-267 because pipeline_id is None. Combined with the wrapper-side EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator silencing (still in concurrent_executor.py:295-315), no stuck-phase-transition alert fires from either side during the slice-1 coexistence window.

This is option (2) from the prior review — the minimum-diff path that accepts an alert gap rather than a false page. The comment at the seed-removal site spells out the trade-off and the slice-2 (task-2-8) follow-up that lands real record_spawn calls. Acceptable.

Non-blocking fixes — all addressed

  • phase_idle_budget_tick log hoisted out of the publish try (routes/pipelines.py:15048-15099); now carries published=<bool> / publish_error=<str|None>. The docstring claim about the log being "independent of whether the message bus is healthy" is now true.
  • Timer's phase kwarg is trusted directly; pipeline is del'd in the body but kept in the signature for slice-2 forward compat (routes/pipelines.py:14994-15002). The "alert names the wrong phase if a transition raced" failure mode is gone.
  • Test heuristic on the .check( call-site count uses the case-normalised form (test_pipelines_phase_idle_budget.py:257) so the OR-branch contributes.
  • phase_idle_budget.py class / reset() docstrings and the pipeline-health-monitoring.md Tier-1 row both reflect that slice-1 re-arms by per-phase instance lifetime, not by reset().
  • _BUDGET_RESET_GAP_SECS comment rewritten as an explicit spec (first_call OR (now - last_spawn_at >= _BUDGET_RESET_GAP_SECS)), gives slice-2 record_spawn call sites a clear contract.

Non-blocking observation on this re-review

phase_idle_budget_tick log doesn't distinguish "store unavailable" from publish failure. routes/pipelines.py:15059-15065: when store_fn is None, a logger.warning(...) fires but publish_error stays None. The structured phase_idle_budget_tick log then emits published=False, publish_error=None, which doesn't tell an operator grepping that log line why the publish was skipped. Worth setting publish_error = "message store unavailable" (or similar sentinel) in the if store_fn is None: branch so the structured log carries the cause without requiring a second grep against the WARNING. Minor; not blocking.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

This comment has been minimized.

james-in-a-box Bot pushed a commit that referenced this pull request Jun 9, 2026
Set publish_error to a 'message store unavailable' sentinel when
_get_message_store() returns None so the structured
phase_idle_budget_tick log distinguishes that branch from a publish
exception. Without the sentinel, an operator grepping the structured
log saw published=False, publish_error=None and could not tell why
the publish was skipped without a second grep against the WARNING
line.

Adds a regression test that exercises the store-unavailable branch
end-to-end through the real timer + real closure and pins the
sentinel value in the structured log line.
@james-in-a-box

james-in-a-box Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the approval — picked up the non-blocking observation in-PR.

Disposition

  • Non-blocking — phase_idle_budget_tick log doesn't distinguish "store unavailable" from publish failure: fixed-in-PR (commit 5406e15). The if store_fn is None: branch in _publish_phase_idle_budget_alert (orchestrator/routes/pipelines.py:15059-15071) now sets publish_error = "message store unavailable" before the warning log fires, so the structured phase_idle_budget_tick line emits published=False, publish_error="message store unavailable" instead of publish_error=None. An operator grepping that single log stream now sees both the threshold-cross and the reason the publish was skipped, with no second grep against the WARNING line required. Added a regression test test_store_unavailable_sets_publish_error_sentinel in orchestrator/tests/test_pipelines_phase_idle_budget.py:432 that exercises the real timer + real closure + _get_message_store patched to return None, and asserts both the sentinel value and the singleton tick emission.

Verification

  • ruff check orchestrator/routes/pipelines.py orchestrator/tests/test_pipelines_phase_idle_budget.py — clean.
  • pytest orchestrator/tests/test_pipelines_phase_idle_budget.py::TestMakePhaseIdleBudgetEmitterClosure -xvs — 3 passed (the two prior closure-binding tests plus the new sentinel test).
  • Full make test not run per the addressing-feedback workflow guidance; CI will confirm on push.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

This comment has been minimized.

@james-in-a-box

james-in-a-box Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author
Autofix tracking
{"Lint/Python": 1}

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer 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.

Re-review summary

Approving. The single non-blocking observation from the prior review (phase_idle_budget_tick log not distinguishing "store unavailable" from publish failure) is properly fixed with regression coverage. No new issues identified in the delta.


Non-blocking carry-over — fixed

routes/pipelines.py:15059-15069 now sets publish_error = "message store unavailable" before emitting the WARNING when _get_message_store() returns None. The sentinel survives into the structured phase_idle_budget_tick log at routes/pipelines.py:15094-15104, so an operator grepping that line sees published=False, publish_error="message store unavailable" and can distinguish the unavailable-store branch from a publish exception (which still carries publish_error=str(e)) without a second grep against the WARNING. The placement (sentinel before WARNING) is correct: if logger.warning itself raised, the outer except Exception as e: publish_error = str(e) would override the sentinel with the exception string — graceful degradation rather than a silent None.

Regression coverage in test_pipelines_phase_idle_budget.py:425-475 exercises the production code path end-to-end: real _make_phase_idle_budget_emitter closure, real PhaseIdleBudgetTimer, real record_spawn → check → _emit_threshold → emitter → _publish_phase_idle_budget_alert. The only patch is at the trust boundary (_get_message_store → None), which is the exact branch under test. The test asserts the structured log fired exactly once and pins the sentinel string against the production-set value (not against a self-seeded golden), so a drift between the production sentinel and the test expectation would fail loudly.

Other delta

The formatting-fix commit 1433494e only reflows a list comprehension in the test added by 5406e159 to match the project's formatter; no behavior change.

— Authored by egg

@james-in-a-box

This comment has been minimized.

egg and others added 6 commits June 9, 2026 19:06
…etTimer

Three test files covering slice-1's three tasks; all use a TDD-friendly
skip-vs-assert pattern so `make test` stays green during parallel-producer
BRC: tests skip cleanly until the coder lands the production code, then
assert against the real surface.

* test_phase_idle_budget.py (task-1-1): unit-level pins for the
  PhaseIdleBudgetTimer class -- constant parity with
  consensus_wrapper.EVENT_PUMP_IDLE_BUDGET_MIN_DEFAULT, threshold
  semantics (0/1x/2x/0->2x jump idempotence), record_spawn window reset
  and per-role action tracking, alert payload shape (anomaly +
  per_role_state per AC-R4 + pipeline_id/phase), AC-R13 HITL-pending
  suppression (1x downgrade to priority=low; 2x suppression), and
  reset() clearing latches.

* test_pipelines_phase_idle_budget.py (task-1-2): wiring contract pins
  for the run-loop integration -- source-grep that routes/pipelines.py
  references the timer, end-to-end 30-min idle -> exactly one
  medium-priority stuck-phase-transition, same interval with
  pending_hitl_count=1 -> exactly one low-priority alert with hitl in
  reason, and a tick-cadence pin (.check call site count) that guards
  copy-paste regressions on the 2x threshold.

* test_consensus_wrapper.py (task-1-3): two appended test classes
  pinning the EGG_PHASE_IDLE_BUDGET_OWNER coexistence guard --
  TestPhaseIdleBudgetOwnerCoexistenceGuard asserts the bash template
  references the env var adjacent to the stuck-phase-transition alert
  and that the ALERTED_AT_BUDGET / ALERTED_AT_DOUBLE latches survive
  the refactor, TestPhaseIdleBudgetOwnerEnvInjection asserts
  _spawn_agent injects EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator for
  coder / tester / reviewer_code. Both classes use a shared
  _wrapper_owner_guard_landed / _assert_or_skip helper to skip cleanly
  before the coder commits and assert once it lands.

Checks: ruff check + ruff format clean; pytest on the three files
returns 34 passed, 7 skipped (TDD-pending), 0 failed.
…ce guard (#3023 slice-1)

Slice-1 of issue #3023 — replaces the per-pod wrapper-side
``stuck-phase-transition`` overseer alert (consensus_wrapper.py:531-549)
with an orchestrator-owned phase-level emitter that fires once per
phase per threshold rather than once per role. Operator UX target:
cq-3 "phase-level 'no spawns for X minutes' alert".

The change set delivers the three contract tasks of slice-1:

* task-1-1 — new ``orchestrator/phase_idle_budget.py`` exporting
  ``PhaseIdleBudgetTimer`` and ``DEFAULT_PHASE_IDLE_BUDGET_MIN = 30``
  (parity with consensus_wrapper.EVENT_PUMP_IDLE_BUDGET_MIN_DEFAULT).
  Public API: ``record_spawn(pipeline_id, phase, role, action, now=)``,
  ``check(now, pending_hitl_count, pending_hitl_ids=)``, ``reset()``.
  Threshold semantics: 1x medium, 2x high; AC-R13 HITL-pending
  suppression downgrades 1x to ``priority=low`` (with the pending
  decision IDs in ``reason``) and suppresses 2x entirely. Every alert
  carries the AC-R4 ``per_role_state`` payload. Idempotent per
  threshold bucket; latches re-armed only by ``reset()``. The timer
  takes an injected ``alert_emitter`` callable so the threshold logic
  is testable without monkeypatching the message store.

* task-1-2 — wires the timer into the per-phase tick in
  ``orchestrator/routes/pipelines.py:_run_concurrent_phase``. Adds two
  new helpers:
  - ``_publish_phase_idle_budget_alert`` — the OVERSEER_ALERT dispatch
    (parallel to ``_publish_consensus_timeout_alert``); structured
    ``phase_idle_budget_tick`` log line emitted alongside.
  - ``_make_phase_idle_budget_emitter`` — binds the publisher to a
    pipeline + slice context so the timer stays pipeline-agnostic.
  The tick reads ``pipeline.get_pending_decisions()`` for the HITL
  count, calls ``phase_idle_budget_timer.check`` exactly once per
  loop iteration, and propagates exceptions to a warning log so a
  rogue tick can't break the polling loop's liveness.

* task-1-3 — injects ``EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator``
  unconditionally in ``ConcurrentPhaseExecutor.get_agent_env`` for
  every role, and adds a coexistence guard at the top of
  ``check_idle_budget`` in ``consensus_wrapper.py`` that ``return 0``s
  when the orchestrator owns the alert. Slice-3 deletes the wrapper-
  side emitter outright (cq-5); this guard is the slice-1/slice-2
  coexistence path that prevents the operator from being paged twice.

Tests:

* Tester's TDD scaffold (commit 8e77484) for task-1-1 / task-1-2 /
  task-1-3 — 19/20 pass against the production code added here. The
  one remaining failure is ``test_thirty_minute_idle_zero_hitl_emits_single_medium_alert``
  whose loop ``range(10, 60 * 60 + 10, 10)`` iterates up to 3600 s
  (the 2x boundary), crossing the 2x alert; the same value
  (``now=3600.0``) is asserted to fire the 2x alert in the unit-level
  ``test_two_x_threshold_emits_exactly_once_and_subsumes_one_x``. The
  two tests are contradictory — the loop range likely should be
  ``30 * 60 + 10`` (1810 s). Flagged in the BRC propose summary for
  the tester to NACK or re-propose.

* Three ``TestPhaseIdleBudgetOwnerEnvInjection`` cases in
  test_consensus_wrapper.py skip cleanly under the existing pytest
  test-helper import path — the env injection is also covered
  end-to-end by a new test in test_concurrent_executor.py
  (``test_phase_idle_budget_owner_env_injected_for_every_role``)
  iterating six roles.

* All other touched tests pass (132 orchestrator tests in the four
  changed test files).

Checks: ``ruff check`` clean; ``ruff format`` clean; ``mypy`` clean on
the new module.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…dget tripwire (#3023 slice-1)

Add a row to the Tier 1 Tripwire Rules table covering the orchestrator-side
PhaseIdleBudgetTimer alert source introduced in slice-1: 30-minute default
window, 1×/2× priority semantics (medium/high), AC-R13 HITL-pending
suppression (downgrade to low at 1×, suppress 2×), per_role_state payload
(AC-R4), idempotent per bucket, and the consensus_wrapper coexistence guard
that defers to the orchestrator owner.

The architectural picture (where the on-demand spawner, the orchestrator-
owned alert, and the retired wrapper-side emitter fit together) lands in
task-3-4 (slice-3) — this row is the minimum operator-facing surface
documenting the new alert source while it ships in slice-1.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The collapsed preamble byte-size drop assertion failed for coder
(0.189) and tester (0.227) after #3027 added the generic no-op
propose guidance (`--no-changes-needed` path + how to spot when
to use it) to the producer lifecycle. That prose lives in every
producer-bearing preamble and legitimately re-raised the
post-collapse sizes.

The threshold was 0.25 (already softened from the architect's
original 0.40); soften further to 0.18 so the acceptance still
validates the slice-3 collapse landed while accommodating the new
no-op guidance. The absolute
`test_preamble_byte_size_under_ceiling_tester` ceiling already
pins the other direction against a runaway re-expansion.
…slice-1)

The 30-min-idle assertion in test_pipelines_phase_idle_budget.py was
running the simulated tick loop for 60 minutes, which legitimately
crosses both the 1× (30 min, medium) and 2× (60 min, high) thresholds.
The implementation emits both alerts (correct behavior matching the
unit-level test_phase_idle_budget pins), but the run-loop integration
test only meant to validate the 1× medium alert in isolation.

Tighten the upper bound to 35 min so the assertion `call_count == 1`
correctly pins the 1× emission. The 2× emission is exercised in the
unit-level tests; this test's job is the run-loop wiring contract.

AC task-1-2: "After the fixture advances past 30 min with no
record_spawn and zero pending HITL, the overseer alert handler is
invoked exactly once with anomaly='stuck-phase-transition',
priority=medium." — "past 30 min" was the intent; the prior bound
overshot into the 2× bucket.
egg-reviewer Bot and others added 3 commits June 9, 2026 19:06
…nits

Blocking fixes:

- Drop ``pipeline_id`` from the explicit kwargs in
  ``_make_phase_idle_budget_emitter`` so the timer's per-emit
  ``pipeline_id`` no longer collides with the closure capture. Before:
  every alert raised ``TypeError: got multiple values for keyword
  argument 'pipeline_id'`` and the outer ``try/except`` around
  ``_tick_phase_idle_budget`` swallowed it, so production never
  published a single ``stuck-phase-transition`` alert. Added a direct
  closure-binding regression test that builds the real factory + real
  timer and asserts ``add_message`` lands once with the right payload.

- Remove the ``phase_start`` ``record_spawn`` seed in
  ``_run_concurrent_phase``. Slice-1 does not yet wire ``record_spawn``
  into the per-event path (slice-2 task-2-8 lands that), so the seed
  turned every long-running phase into a guaranteed false-positive
  ``medium`` alert at 30 min and ``high`` alert at 60 min — the
  orchestrator-side ``last_spawn_at`` never advanced. The wrapper-side
  emitter is silenced via ``EGG_PHASE_IDLE_BUDGET_OWNER=orchestrator``
  per task-1-3, so silencing both sides during the slice-1 coexistence
  window is the operator-correct choice (an alert gap beats a false
  page). ``check()`` no-ops while unbound; slice-2 will bind on first
  real spawn.

Non-blocking fixes called out in the same review:

- Hoist the ``phase_idle_budget_tick`` structured log out of the
  ``try`` so it still emits when ``msg_store.add_message`` raises
  (matches the docstring claim "independent of whether the message bus
  is healthy"); carry a ``published`` / ``publish_error`` flag.

- Trust the timer's ``phase`` kwarg as the alert's source of truth
  instead of overriding with ``pipeline.current_phase`` — naming a
  different phase if the pipeline transitioned between ``check()`` and
  ``emit()`` was the failure mode.

- Replace the dead ``"PhaseIdleBudget" in line.lower()`` branch in
  ``test_check_call_site_is_exactly_one_per_tick`` with the
  case-normalised form so the OR-branch actually contributes.

- Update the class docstring + ``reset()`` docstring + the
  pipeline-health-monitoring guide to reflect that slice-1 re-arms by
  per-phase instance lifetime, not by ``reset()``.

- Rewrite the ``_BUDGET_RESET_GAP_SECS`` comment as an unambiguous spec
  so slice-2 ``record_spawn`` call sites have a clear contract to
  validate against.

Refs #3023.

— Authored by egg
Set publish_error to a 'message store unavailable' sentinel when
_get_message_store() returns None so the structured
phase_idle_budget_tick log distinguishes that branch from a publish
exception. Without the sentinel, an operator grepping the structured
log saw published=False, publish_error=None and could not tell why
the publish was skipped without a second grep against the WARNING
line.

Adds a regression test that exercises the store-unavailable branch
end-to-end through the real timer + real closure and pins the
sentinel value in the structured log line.
@james-in-a-box
james-in-a-box Bot force-pushed the egg/issue-3023/slice-1 branch from 1433494 to 2efe206 Compare June 9, 2026 19:07
@jwbron

jwbron commented Jun 9, 2026

Copy link
Copy Markdown
Owner

Closing as part of abandoning the first #3023 SDLC run — it shipped only prereqs + wrapper teardown (the on-demand spawner was descoped from slice-2) and hit a post-BRC deadlock. #3023 is being re-run from scratch; see the re-run instructions there.

@james-in-a-box

james-in-a-box Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

egg review failed. View run logs

9 previous review(s) hidden.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant