The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop,pm): stop the boot parking on a failed update receipt and bound completion retries (#122206)
Brooklyn Nicholson8b4b440ef3dc
diff --git a/apps/desktop/electron/backend-ready.test.ts b/apps/desktop/electron/backend-ready.test.tsindex 9a412c6ad19..685128289f2 100644--- a/apps/desktop/electron/backend-ready.test.ts+++ b/apps/desktop/electron/backend-ready.test.ts@@ -322,3 +322,50 @@ test('the merged-tail seed does not match prose that merely names the sentinel',await assert.rejects(wait, /Timed out waiting/)})++// ---------------------------------------------------------------------------+// source-update completion banners extend the deadline (#122206)+// ---------------------------------------------------------------------------++test('a completion banner re-arms the deadline past the original timeout', async () => {+ // The backend prints venv_sync's banner (finishing an owed update tail)+ // after the normal budget would have expired. The wait must keep waiting+ // while the repair is in progress, then resolve on the late announcement.+ const child = makeFakeChild()+ const p = waitForDashboardPort(child, 40)+ child.stdout.emit('data', 'hermes: finishing an interrupted source update...\n')+ // Past the original 40ms deadline: without the banner grace this wait has+ // already rejected. Give the "repair" a moment, then announce.+ await new Promise(resolve => setTimeout(resolve, 80))+ child.stdout.emit('data', 'HERMES_BACKEND_READY port=4455\n')+ assert.equal(await p, 4455)+})++test('a stalled completion banner is capped, not waited out forever', async () => {+ // The banner says a repair is in progress but nothing ever resolves: the+ // wait must still fail (bounded), and the message must carry that the+ // completion was in progress — truthful and actionable instead of a bare+ // 90s timeout that hides a multi-minute repair. The 5-minute grace is+ // wall-clock, so this holds the wait past it with a long test budget.+ const child = makeFakeChild()+ const wait = waitForDashboardPort(child, 20)+ wait.catch(() => {}) // mark handled; the assertion below re-awaits++ child.stdout.emit('data', 'hermes: finishing an interrupted source update...\n')+ await assert.rejects(+ wait,+ /Timed out waiting for Hermes backend port announcement .* while an update completion was in progress/+ )+}, 6 * 60_000)++test('a banner already in the spawn-time tail also re-arms', async () => {+ // The dormant bufferedOutput gap (#60323): the banner was flushed before the+ // listener attached. Seeding from the tail must extend the deadline too.+ const child = makeFakeChild()+ const p = waitForDashboardPort(child, 40, () => '', () =>+ 'hermes: completing source-update dependencies...\n'+ )+ await new Promise(resolve => setTimeout(resolve, 80))+ child.stdout.emit('data', 'HERMES_BACKEND_READY port=4471\n')+ assert.equal(await p, 4471)+}, 10_000)diff --git a/apps/desktop/electron/backend-ready.ts b/apps/desktop/electron/backend-ready.tsindex 7fd8287d61b..fb9802f46b3 100644--- a/apps/desktop/electron/backend-ready.ts+++ b/apps/desktop/electron/backend-ready.ts@@ -24,6 +24,30 @@ const DEFAULT_PORT_ANNOUNCE_TIMEOUT_MS = 90_000// (the historical default) so a malformed override can't reintroduce the loop.const MIN_PORT_ANNOUNCE_TIMEOUT_MS = 45_000+// While the backend prints venv_sync's source-update completion banners it is+// finishing an owed update tail BEFORE `hermes serve` starts, and that tail+// legitimately runs minutes (dependency sync alone measured at ~19-22 min,+// #122206) — far past the 90s cold-start budget, which is sized for imports+// and AV scans, not repairs. Killing the child mid-repair and respawning it+// (what the old timeout did) re-runs the repair from scratch on every boot.+// While a banner is present the deadline is re-armed instead, up to this+// total cap; a tail that outlasts the cap fails with the usual timeout and+// the banner text in the output tail, which is truthful and actionable.+const SOURCE_COMPLETION_BANNER_RE = /finishing an interrupted source update|completing source-update dependencies/+const SOURCE_COMPLETION_GRACE_MS = 5 * 60_000+const SOURCE_COMPLETION_MAX_TOTAL_MS = 30 * 60_000++/**+ * The source-completion grace resolves against the REAL clock, not the faked+ * one: vitest's advanceTimersByTimeAsync advances Date.now() with the timers,+ * so a `Date.now() + GRACE` deadline re-computed each tick stays GRACE away+ * forever and the cap never fires under tests. The real clock also matches+ * production semantics — the grace measures wall-clock repair time.+ */+function realNow() {+ return Number(process.hrtime.bigint() / 1_000_000n)+}+/*** Resolve the port-announcement deadline. Honors the* HERMES_DESKTOP_PORT_ANNOUNCE_TIMEOUT_MS env override (for users on slow@@ -74,6 +98,28 @@ function waitForDashboardPort(// trailing partial line) makes the listener-attach ordering irrelevant.let buf = ''let done = false+ // #122206: the child is finishing an owed source-update completion+ // (venv_sync banners) before `hermes serve` starts. While that repair is+ // visibly in progress the 90s deadline is re-armed, up to the total cap,+ // instead of killing a healthy repair mid-run.+ const startedAt = realNow()+ let completionInProgress = false+ let timer++ function completionDeadline() {+ return completionInProgress+ ? Math.min(startedAt + SOURCE_COMPLETION_MAX_TOTAL_MS, realNow() + SOURCE_COMPLETION_GRACE_MS)+ : null+ }++ function rearmTimer() {+ clearTimeout(timer)+ const deadline = completionDeadline()+ timer = setTimeout(() => {+ cleanup()+ reject(new Error(`Timed out waiting for Hermes backend port announcement (${timeoutMs}ms)${deadline ? ' while an update completion was in progress' : ''}`))+ }, Math.max(0, (deadline ?? startedAt + timeoutMs) - realNow()))+ }function cleanup() {if (done) {@@ -102,6 +148,14 @@ function waitForDashboardPort(return}++ // venv_sync's banner is the signal that an owed source-update tail is+ // running ahead of `hermes serve` (#122206): re-arm the deadline so a+ // healthy multi-minute repair is not killed and re-run per boot.+ if (SOURCE_COMPLETION_BANNER_RE.test(line)) {+ completionInProgress = true+ rearmTimer()+ }}}@@ -115,11 +169,7 @@ function waitForDashboardPort(reject(err)}- const timer = setTimeout(() => {- cleanup()- reject(new Error(`Timed out waiting for Hermes backend port announcement (${timeoutMs}ms)`))- }, timeoutMs)-+ rearmTimer()child.stdout.on('data', onData)child.on('exit', onExit)child.on('error', onError)@@ -137,6 +187,11 @@ function waitForDashboardPort(if (m) {cleanup()resolve(parseInt(m[1], 10))+ } else if (alreadyBuffered && SOURCE_COMPLETION_BANNER_RE.test(alreadyBuffered)) {+ // The repair started before this listener attached (the dormant-gap+ // path above): seed the banner so the deadline re-arms like a live one.+ completionInProgress = true+ rearmTimer()}}})diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex d662a5ad3a6..653cce749da 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -2792,7 +2792,16 @@ function updateGateDeps() {return {hasLiveMarker: () => Boolean(readLiveUpdateMarker(HERMES_HOME)),isUpdateInFlight: () => updateInFlight,- isHandoffActive: () => isQuittingForHandoff+ isHandoffActive: () => isQuittingForHandoff,+ // The latest receipt is cross-process truth: a `hermes update` that failed+ // records outcome "failed" even when its marker write/release raced a+ // crash (#122206). Only a TERMINAL failure counts — "running" must keep+ // parking, and "partial" kept the install usable.+ hasFailedReceipt: () => {+ const receipt = readLatestSyncReceipt()++ return receipt?.outcome === 'failed'+ }}}@@ -2854,9 +2863,27 @@ function relaunchIntoSwappedBundle() {// rather than a frozen splash. Returns true if it parked at all.async function waitForUpdateToFinish() {let announced = false+ let parkedOnFailedReceipt = falseconst outcome = await waitForUpdateClearance(updateGateDeps(), {signal: localBackendLifecycle.signal,+ abandonOn: reason => {+ // The update that owns the gate already recorded a terminal failure+ // (#122206): parking the full 20-minute budget on a receipt that says+ // "failed" strands the window behind a dead updater (486 silent polls+ // measured). Stop waiting; the failure dialog below carries the+ // recovery guidance and the backend's own launch path finishes only+ // what is safely retryable, bounded by venv_sync's completion-retry+ // backoff.+ if (reason === 'failed-receipt') {+ parkedOnFailedReceipt = true+ rememberLog('[updates] latest update receipt records a failure; not parking the boot on it')++ return true+ }++ return false+ },onWaitTick: async reason => {if (!announced) {announced = true@@ -2937,6 +2964,11 @@ async function waitForUpdateToFinish() {if (outcome === 'timeout') {rememberLog('[updates] update still in progress after wait timeout; starting backend anyway')+ } else if (parkedOnFailedReceipt) {+ // The gate closed on a terminal failure, not a live update: no swap to+ // relaunch into (the update never succeeded), so boot the current build+ // and let the failure dialog above carry the recovery guidance.+ rememberLog('[updates] proceeding with backend start despite the failed update receipt')} else if (relaunchIntoSwappedBundle()) {await advanceBootProgress('backend.update-restart', 'Restarting Hermes to load the updated app…', 14)// Park while the scheduled exit lands so this stale build never starts adiff --git a/apps/desktop/electron/update-gate.test.ts b/apps/desktop/electron/update-gate.test.tsindex 8a4cd2e5f99..6d85c985868 100644--- a/apps/desktop/electron/update-gate.test.ts+++ b/apps/desktop/electron/update-gate.test.ts@@ -171,3 +171,105 @@ test('returns timeout when the gate never opens', async () => {assert.equal(outcome, 'timeout')})++// ---------------------------------------------------------------------------+// failed-receipt signal (#122206)+// ---------------------------------------------------------------------------++test('a failed receipt outranks a live marker as the reported reason', () => {+ assert.equal(+ updateGateReason({ ...deps(true, false), hasFailedReceipt: () => true }),+ 'failed-receipt'+ )+})++test('a failed receipt without a live marker keeps the gate open', () => {+ // The receipt only RECLASSIFIES a closed gate; it must not close an open+ // one — a failed update from last week must not defer any boot.+ assert.equal(updateGateReason({ ...deps(false, false), hasFailedReceipt: () => true }), null)+})++test('a running or partial receipt keeps the marker reason', () => {+ // Only a TERMINAL failure is actionable: "running" must keep parking.+ assert.equal(+ updateGateReason({ ...deps(true, false), hasFailedReceipt: () => false }),+ 'marker'+ )+})++test('abandonOn returns abandoned instead of parking on a failed receipt', async () => {+ let slept = 0++ const outcome = await waitForUpdateClearance(+ { ...deps(true, false), hasFailedReceipt: () => true },+ {+ abandonOn: reason => reason === 'failed-receipt',+ pollMs: 10,+ sleep: async () => {+ slept += 1+ },+ timeoutMs: 10_000+ }+ )++ assert.equal(outcome, 'abandoned')+ assert.equal(slept, 0)+})++test('a mid-wait receipt finalization abandons the park', async () => {+ // The gate closed on a live marker (update running); the update then fails+ // and finalizes its receipt while we are parked. The wait must abandon on+ // the next poll instead of counting down to the 20-minute deadline.+ let failedReceipt = false+ let polls = 0++ const outcome = await waitForUpdateClearance(+ { ...deps(true, false), hasFailedReceipt: () => failedReceipt },+ {+ abandonOn: reason => reason === 'failed-receipt',+ onWaitTick: () => {+ polls += 1++ if (polls === 3) {+ failedReceipt = true+ }+ },+ pollMs: 1,+ sleep: async () => {},+ timeoutMs: 10_000+ }+ )++ assert.equal(outcome, 'abandoned')+ assert.equal(polls, 3)+})++test('abandonOn declining keeps the historical parking', async () => {+ let ticks = 0+ let marker = true++ const outcome = await waitForUpdateClearance(+ {+ hasLiveMarker: () => marker,+ isUpdateInFlight: () => false,+ isHandoffActive: () => false,+ hasFailedReceipt: () => true+ },+ {+ abandonOn: () => false,+ onWaitTick: () => {+ ticks += 1++ if (ticks === 2) {+ marker = false+ }+ },+ pollMs: 1,+ sleep: async () => {},+ timeoutMs: 10_000+ }+ )++ assert.equal(outcome, 'finished')+ assert.equal(ticks, 2)+})diff --git a/apps/desktop/electron/update-gate.ts b/apps/desktop/electron/update-gate.tsindex 7f537310c42..a8db9719b92 100644--- a/apps/desktop/electron/update-gate.ts+++ b/apps/desktop/electron/update-gate.ts@@ -8,7 +8,7 @@ import { runBackendStartStep } from './backend-start-cancellation'* Pure, dependency-injected gate that parks local backend spawns while an* in-app update is running (#73822, #50238).*- * Three independent signals mean "an update owns the local runtime right now":+ * Four independent signals mean "an update owns the local runtime right now":** - the on-disk marker (`HERMES_HOME/.hermes-update-in-progress`), written* by the updater — and by the desktop itself just before hand-off — and@@ -24,9 +24,21 @@ import { runBackendStartStep } from './backend-start-cancellation'* window. On success the marker is written BEFORE the flag clears in `applyUpdates`'* `finally`, so there is no instant where both signals are false and a* waiter could slip through mid-update.+ *+ * The fourth signal is different in kind: `failedReceipt` names a FINISHED,+ * failed update. A failed `hermes update` releases the marker in its `finally`+ * only when the failure happened after the lock was claimed; preparation-stage+ * failures (uv sync network errors) can exit with the marker left pointing at+ * a dead or recycled pid while `readLiveUpdateMarker`'s liveness probe keeps+ * answering true on Windows, and even a cleanly released marker leaves the+ * boot nothing to wait for. Parking the full 20-minute budget on a receipt+ * that already says `failed` strands the window (#122206: 486 polls /+ * 20 minutes after a receipt-marked failure). The gate reports it separately+ * so the boot path can surface the terminal failure instead of silently+ * counting down.*/-export type UpdateGateReason = 'marker' | 'update-in-flight' | 'handoff' | null+export type UpdateGateReason = 'marker' | 'update-in-flight' | 'handoff' | 'failed-receipt' | nullexport interface UpdateGateDeps {/** True when a live on-disk update marker exists (see update-marker.ts). */@@ -35,11 +47,24 @@ export interface UpdateGateDeps {isUpdateInFlight: () => boolean/** True after a detached updater hand-off is viable and this Desktop will quit. */isHandoffActive: () => boolean+ /**+ * True when the latest update receipt records a terminal failure (see+ * main.ts readLatestSyncReceipt). Optional: older callers (and the pool+ * spawn path, which is not user-visible) may omit it, in which case a+ * live marker keeps the historical parking behavior.+ */+ hasFailedReceipt?: () => boolean}/** Why the gate is closed right now, or null when it is open. */export function updateGateReason(deps: UpdateGateDeps): UpdateGateReason {if (deps.hasLiveMarker()) {+ // A failed receipt with a live marker is still the marker's wait — but the+ // receipt is what the boot path needs to know about, so it wins here.+ if (deps.hasFailedReceipt?.()) {+ return 'failed-receipt'+ }+return 'marker'}@@ -54,7 +79,7 @@ export function updateGateReason(deps: UpdateGateDeps): UpdateGateReason {return null}-export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout' | 'cancelled'+export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout' | 'cancelled' | 'abandoned'export interface WaitForUpdateClearanceOptions {signal?: AbortSignal@@ -63,6 +88,13 @@ export interface WaitForUpdateClearanceOptions {pollMs: number/** Invoked once per poll while parked (boot progress / logging). */onWaitTick?: (reason: Exclude<UpdateGateReason, null>) => void | Promise<void>+ /**+ * Consulted whenever the gate is closed. Returning true makes the wait+ * return 'abandoned' immediately instead of parking. The primary boot path+ * uses this for the terminal failed-receipt signal (#122206): a receipt+ * that already says "failed" must not consume the parking budget.+ */+ abandonOn?: (reason: Exclude<UpdateGateReason, null>) => booleannow?: () => numbersleep?: (ms: number) => Promise<void>}@@ -71,7 +103,8 @@ export interface WaitForUpdateClearanceOptions {* Park until no update signal remains, or the deadline passes.** Returns 'clear' when the gate was already open (no wait happened),- * 'finished' when it opened during the wait, and 'timeout' when the deadline+ * 'finished' when it opened during the wait, 'abandoned' when `abandonOn`+ * accepted the closed-gate reason, and 'timeout' when the deadline* expired with the gate still closed (callers proceed anyway — matching the* long-standing marker-gate behavior, since a wedged updater must not brick* the app forever).@@ -95,6 +128,10 @@ export async function waitForUpdateClearance(return 'clear'}+ if (options.abandonOn?.(reason)) {+ return 'abandoned'+ }+const deadline = now() + options.timeoutMswhile (reason && now() < deadline) {@@ -135,6 +172,10 @@ export async function waitForUpdateClearance(}reason = updateGateReason(deps)++ if (reason && options.abandonOn?.(reason)) {+ return 'abandoned'+ }}return reason ? 'timeout' : 'finished'diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex 2a1a7238ee9..a483b1356d1 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -176,8 +176,81 @@ def arm_completion(project_root: Path) -> Path:return pending-def clear_completion(project_root: Path) -> None:- completion_pending_path(project_root).unlink(missing_ok=True)+#: Relaunch-driven completion retries are bounded (#122206): a tail that keeps+#: failing re-runs on every launch ("every launch burns ~4 minutes"), so after+#: this many consecutive failures the tail waits out a backoff window before+#: trying again, and past the cap it stops self-starting entirely and leaves+#: the marker for an explicit ``hermes update`` instead. The counter is the+#: tail's own attempt record beside the pending marker: same lifetime, same+#: install scope, cleared by the same success path.+COMPLETION_RETRY_BACKOFF_ATTEMPTS = 2+COMPLETION_RETRY_BACKOFF_SECONDS = 15 * 60+COMPLETION_RETRY_MAX_ATTEMPTS = 6+++def _completion_attempts_path(project_root: Path) -> Path:+ return completion_pending_path(project_root).with_name("source-completion-attempts")+++def _record_completion_attempt(root: Path, *, failed: bool) -> None:+ """Track consecutive completion-tail failures beside the pending marker.++ The pending marker itself is armed *before* the tail runs (a crash between+ the dependency commit and the tail must leave the obligation), so the+ marker alone cannot distinguish "never tried" from "tried and failed N+ times". The attempts record can: success clears both, failure bumps it.+ """+ record = _completion_attempts_path(root)+ if not failed:+ record.unlink(missing_ok=True)+ return+ try:+ attempts = int(record.read_text(encoding="utf-8-sig").strip() or "0") + 1+ except (OSError, ValueError):+ attempts = 1+ try:+ record.write_text(f"{attempts}\n", encoding="utf-8")+ except OSError:+ pass # a read-only install state degrades to unbounded retries, never blocks boot+++def completion_retry_state(project_root: Path, *, now=None) -> tuple[bool, int, int]:+ """``(may_retry_now, attempts, backoff_seconds)`` for the owed tail.++ Never raises; an unreadable record answers ``(True, 0, 0)`` — the+ historical unbounded behavior — because a bookkeeping failure must not+ stop a launch from finishing its own update.+ """+ import time as _time++ record = _completion_attempts_path(project_root)+ try:+ attempts = int(record.read_text(encoding="utf-8-sig").strip() or "0")+ except (OSError, ValueError):+ return True, 0, 0+ if attempts <= 0:+ return True, 0, 0+ if attempts >= COMPLETION_RETRY_MAX_ATTEMPTS:+ return False, attempts, 0+ if attempts < COMPLETION_RETRY_BACKOFF_ATTEMPTS:+ # A single failure is the historical case (a flaky tail that a plain+ # relaunch fixes): retry immediately, exactly as before (#122206's+ # "the next launch owes the tail only" contract).+ return True, attempts, 0+ try:+ mtime = record.stat().st_mtime+ except OSError:+ return True, attempts, 0+ reference = (now or _time.time)()+ age = max(0.0, reference - mtime)+ if age >= COMPLETION_RETRY_BACKOFF_SECONDS:+ return True, attempts, COMPLETION_RETRY_BACKOFF_SECONDS+ return False, attempts, int(COMPLETION_RETRY_BACKOFF_SECONDS - age)+++def clear_completion(root: Path) -> None:+ completion_pending_path(root).unlink(missing_ok=True)+ _completion_attempts_path(root).unlink(missing_ok=True)def refuse_foreign_owned_venv(project_root: Path) -> None:@@ -282,7 +355,21 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:current = pm.venv_is_current(project_root=root)pending = completion_pending_path(root)owed_to_cli = current and pending.is_file() and _supervised_child()- if not owed_to_cli and (not current or pending.is_file()):+ _may_retry, _attempts, _backoff = completion_retry_state(root)+ if not _may_retry and _attempts >= COMPLETION_RETRY_MAX_ATTEMPTS:+ # The tail has failed often enough that every relaunch re-running it+ # does more harm than good (#122206: "every launch burns ~4 minutes").+ # Leave the marker for an explicit `hermes update`; say so once.+ print(+ f"hermes: a source update could not be finished automatically "+ f"({_attempts} attempts); run `hermes update` from a shell to finish it",+ file=sys.stderr, flush=True,+ )+ elif not _may_retry:+ # Backoff window not yet elapsed: skip this launch's retry without+ # noise (the record's age tracks the wait), leaving the marker armed.+ pass+ elif not owed_to_cli and (not current or pending.is_file()):lock = UpdateLock()if not lock.acquire():raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")@@ -359,6 +446,7 @@ def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:cwd=root, env=activation_environment(root), stdout=sys.__stderr__,)if code != 0:+ _record_completion_attempt(root, failed=True)raise RuntimeError("source update completion failed; run `hermes update` to finish it")diff --git a/tests/hermes_cli/test_update_launch_completion.py b/tests/hermes_cli/test_update_launch_completion.pyindex 7516692bbcb..6ef21c78a6c 100644--- a/tests/hermes_cli/test_update_launch_completion.py+++ b/tests/hermes_cli/test_update_launch_completion.py@@ -95,6 +95,12 @@ def test_failed_completion_tail_is_retried_without_rebuilding_dependencies(tmp_passert len(completion_tail) == 2completion_tail.exit_code = 0+ # Age the recorded failure past the backoff window (#122206): a flaky+ # tail that a plain relaunch fixes is the historical case, but only once+ # the backoff window has elapsed — fresh failures wait it out.+ attempts = venv_sync._completion_attempts_path(root)+ old = 1.0+ os.utime(attempts, (old, old))# Dependencies are already this interpreter's: the tail alone owes no re-exec.assert venv_sync.prepare_launch(root, []) is Noneassert len(syncs) == 1 and len(completion_tail) == 3diff --git a/tests/pm/test_source_update_launch.py b/tests/pm/test_source_update_launch.pyindex 377032c3151..81624f93342 100644--- a/tests/pm/test_source_update_launch.py+++ b/tests/pm/test_source_update_launch.py@@ -498,3 +498,96 @@ def test_failed_launch_completion_degrades_to_a_warning(source_launch, tmp_path,assert "source-update completion failed" in result.stderrassert "hermes update" in result.stderr+[email protected]("posix")+def test_completion_retry_backoff_and_cap(tmp_path, monkeypatch):+ """Consecutive completion-tail failures back off and finally stop self-starting (#122206:+ an environment where every launch re-runs a doomed ~4-minute tail)."""+ from hermes_cli import venv_sync++ monkeypatch.setattr(venv_sync, "completion_pending_path",+ lambda root: tmp_path / "source-completion-pending")+ record = tmp_path / "source-completion-attempts"++ # No record yet: the first retry is immediate (historical behavior).+ assert venv_sync.completion_retry_state(tmp_path) == (True, 0, 0)++ # One recorded failure: the historical flaky case — retry immediately.+ record.write_text("1\n", encoding="utf-8")+ assert venv_sync.completion_retry_state(tmp_path) == (True, 1, 0)++ # Two consecutive failures: the next retry must wait out the backoff window.+ record.write_text("2\n", encoding="utf-8")+ may_retry, attempts, _backoff = venv_sync.completion_retry_state(tmp_path)+ assert (may_retry, attempts) == (False, 2)+ # After the backoff window the tail may run again.+ past = 12345.0+ old_mtime = past - venv_sync.COMPLETION_RETRY_BACKOFF_SECONDS - 1+ os.utime(record, (old_mtime, old_mtime))+ may_retry, attempts, _backoff = venv_sync.completion_retry_state(tmp_path, now=lambda: past)+ assert (may_retry, attempts) == (True, 2)++ # At the cap the tail never self-starts, regardless of age.+ record.write_text(f"{venv_sync.COMPLETION_RETRY_MAX_ATTEMPTS}\n", encoding="utf-8")+ for now_value in (past, past + 10 * venv_sync.COMPLETION_RETRY_BACKOFF_SECONDS):+ may_retry, attempts, _backoff = venv_sync.completion_retry_state(tmp_path, now=now_value)+ assert (may_retry, attempts) == (False, venv_sync.COMPLETION_RETRY_MAX_ATTEMPTS)++ # A corrupt record degrades to the historical unbounded behavior.+ record.write_text("not a number\n", encoding="utf-8")+ assert venv_sync.completion_retry_state(tmp_path) == (True, 0, 0)++[email protected]("posix")+def test_capped_completion_attempts_leave_marker_for_explicit_update(source_launch, tmp_path, capsys):+ """Past the retry cap a launch must NOT re-run the tail; it keeps the pending marker+ and points the operator at `hermes update` instead of burning another doomed attempt."""+ root, store_python, _ = source_launch+ from hermes_cli.venv_sync import ( # noqa: F401 — import for the paths under test+ _completion_attempts_path,+ arm_completion,+ completion_pending_path,+ )++ pm.sync_venv(["all"], explicit=True, project_root=root)+ arm_completion(root)+ attempts = _completion_attempts_path(root)+ attempts.write_text("99\n", encoding="utf-8")+ os.utime(attempts, (1.0, 1.0)) # ancient: age cannot rescue a capped record++ # The supervised-child carve-out does not apply: an unsupervised launch+ # would have re-run the tail here; capped, it must not. The launch itself+ # still resolves normally (the store python), only the tail is skipped.+ assert venv_sync.prepare_launch(root, []) == store_python+ out = capsys.readouterr().err+ assert "could not be finished automatically" in out+ assert "hermes update" in out+ assert completion_pending_path(root).is_file(), "the owed completion is still recorded"+ assert not (tmp_path / "completion-calls").exists(), "a capped launch re-ran the tail"++[email protected]("posix")+def test_failed_tail_attempt_is_counted_and_success_clears_it(source_launch, tmp_path, monkeypatch, capsys):+ """A failing completion tail records the attempt; the successful retry clears the record."""+ root, store_python, _ = source_launch+ from hermes_cli.venv_sync import _completion_attempts_path, arm_completion, completion_pending_path++ pm.sync_venv(["all"], explicit=True, project_root=root)+ arm_completion(root)+ # The tail script the fixture records calls with — make it fail, then succeed.+ calls = (root / "hermes_cli" / "source_completion.py")+ original = calls.read_text(encoding="utf-8")+ calls.write_text("import sys\nsys.exit(3)\n", encoding="utf-8")+ with pytest.raises(RuntimeError, match="source update completion failed"):+ venv_sync.prepare_launch(root, [])+ assert _completion_attempts_path(root).read_text(encoding="utf-8").strip() == "1"+ assert completion_pending_path(root).is_file(), "a failed attempt must keep the obligation"++ calls.write_text(original, encoding="utf-8")+ old = 1.0+ os.utime(_completion_attempts_path(root), (old, old))+ # A successful retry still launches normally and clears the obligation.+ assert venv_sync.prepare_launch(root, []) == store_python+ assert not completion_pending_path(root).exists()+ assert not _completion_attempts_path(root).exists(), "success cleared the attempt record"+