From 9490b27c2d21fbf55fa238f4a14c2bfbe0bfa6c9 Mon Sep 17 00:00:00 2001 From: James Wiesebron Date: Wed, 6 May 2026 20:03:09 -0700 Subject: [PATCH 1/3] Fix #2501: extend probe freshness while a probe is in flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `StateStoreProbe.snapshot()` flipped the cached `healthy` to `False` purely because the cache age crossed `interval * stale_multiplier`, even when a probe was actively running and about to refresh it. Under slice-spawn load `git worktree add` occasionally ran 30-40s, longer than the 30s default staleness window, so the request-path dual-write in `routes/health.py` recorded `unhealthy` and the BG callback recorded `healthy` 0-3s later when the same probe completed — producing the spurious `recent_transitions` flap pairs reported in the issue. Track probe start time and, while a probe is in flight, treat the cache as fresh until the in-flight probe itself has been running longer than the staleness window. A genuinely wedged probe still surfaces as stale once that bound is exceeded. --- orchestrator/state_store_probe.py | 28 ++++++++-- orchestrator/tests/test_state_store_probe.py | 56 ++++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/orchestrator/state_store_probe.py b/orchestrator/state_store_probe.py index 8e66645f78..d795f4787c 100644 --- a/orchestrator/state_store_probe.py +++ b/orchestrator/state_store_probe.py @@ -138,6 +138,7 @@ def __init__( self._stop_event = threading.Event() self._thread: threading.Thread | None = None self._probe_in_flight = False + self._probe_started_at_monotonic: float | None = None self._on_observation = on_observation @property @@ -178,6 +179,7 @@ def probe_now(self) -> tuple[bool, str]: healthy = bool(self._healthy) if self._healthy is not None else False return healthy, self._message self._probe_in_flight = True + self._probe_started_at_monotonic = time.monotonic() try: base_path = _resolve_base_path() @@ -202,6 +204,7 @@ def probe_now(self) -> tuple[bool, str]: finally: with self._lock: self._probe_in_flight = False + self._probe_started_at_monotonic = None if callback is not None: try: @@ -223,7 +226,14 @@ def snapshot(self) -> dict[str, Any]: ``{"status": "error", "error": "..."}``. Empty when the probe was skipped or has not yet run (#2176). - ``fresh``: bool — whether the most recent probe is within the - staleness window (``interval * stale_multiplier``). + staleness window (``interval * stale_multiplier``). When a + probe is currently in flight the window is extended for the + duration of that probe (up to one additional staleness window), + so a single slow-but-completing probe doesn't trigger a + spurious unhealthy flip on the request path while the BG + callback later records healthy from the same probe (#2501). + A wedged probe (in-flight indefinitely) still surfaces as + stale once its in-flight age exceeds the staleness window. - ``age_seconds``: float | None — seconds since the most recent probe, ``None`` if the BG thread has not run yet. """ @@ -232,6 +242,8 @@ def snapshot(self) -> dict[str, Any]: message = self._message repos = dict(self._repos) last = self._last_check_monotonic + in_flight = self._probe_in_flight + started = self._probe_started_at_monotonic if last is None: return { @@ -242,8 +254,18 @@ def snapshot(self) -> dict[str, Any]: "age_seconds": None, } - age = time.monotonic() - last - fresh = age <= self._interval * self._stale_multiplier + now = time.monotonic() + age = now - last + stale_window = self._interval * self._stale_multiplier + fresh = age <= stale_window + if not fresh and in_flight and started is not None: + # Don't penalize the cache for a probe that's still in + # progress: the BG callback will record the result from this + # same probe shortly. Bound the grace by the staleness window + # so a wedged probe (in-flight forever) still flips stale. + in_flight_age = now - started + if in_flight_age <= stale_window: + fresh = True return { "healthy": bool(healthy) if fresh else False, "message": message if fresh else f"stale (age={age:.1f}s): {message}", diff --git a/orchestrator/tests/test_state_store_probe.py b/orchestrator/tests/test_state_store_probe.py index c5b09328d9..0bea103f3d 100644 --- a/orchestrator/tests/test_state_store_probe.py +++ b/orchestrator/tests/test_state_store_probe.py @@ -154,6 +154,62 @@ def test_stale_observation_flips_healthy_to_false(self, with_repo_path): assert snap["healthy"] is False assert "stale" in snap["message"] + def test_in_flight_probe_extends_freshness_window(self, with_repo_path): + """A probe that's still running shouldn't cause a spurious + unhealthy flip on the request path. While the BG probe is + in-flight, the cache stays fresh past the normal staleness + window — the in-flight probe will refresh the cache when it + completes (#2501).""" + from state_store_probe import StateStoreProbe + + probe = StateStoreProbe(interval=1.0, stale_multiplier=2.0) + with patch( + "state_store_probe.probe_state_store_at", + return_value=(True, "ok", {"/sentinel/repo/path": {"status": "ok"}}), + ): + probe.probe_now() + + # Cache age is now > 2*interval (3s in the past), but a probe + # is in flight that started 1s ago — well within the staleness + # window. snapshot() must not flip the cached healthy=True. + now = time.monotonic() + with probe._lock: # type: ignore[attr-defined] + probe._last_check_monotonic = now - 3.0 # type: ignore[attr-defined] + probe._probe_in_flight = True # type: ignore[attr-defined] + probe._probe_started_at_monotonic = now - 1.0 # type: ignore[attr-defined] + + snap = probe.snapshot() + assert snap["fresh"] is True + assert snap["healthy"] is True + assert snap["message"] == "ok" + + def test_in_flight_probe_still_flips_stale_once_wedged(self, with_repo_path): + """The in-flight grace is bounded: once the in-flight probe + itself has been running for longer than the staleness window, + we admit the cache is stale and report unhealthy. Otherwise a + wedged ``git worktree add`` would never surface as a wedge.""" + from state_store_probe import StateStoreProbe + + probe = StateStoreProbe(interval=1.0, stale_multiplier=2.0) + with patch( + "state_store_probe.probe_state_store_at", + return_value=(True, "ok", {"/sentinel/repo/path": {"status": "ok"}}), + ): + probe.probe_now() + + # Cache age 5s, in-flight probe has been running 4s (> 2*interval). + # The grace is exhausted — should flip stale. + now = time.monotonic() + with probe._lock: # type: ignore[attr-defined] + probe._last_check_monotonic = now - 5.0 # type: ignore[attr-defined] + probe._probe_in_flight = True # type: ignore[attr-defined] + probe._probe_started_at_monotonic = now - 4.0 # type: ignore[attr-defined] + + snap = probe.snapshot() + assert snap["fresh"] is False + assert snap["healthy"] is False + assert "stale" in snap["message"] + class TestExceptionIsolation: """Exceptions in the underlying probe must not crash the BG thread From 4736b4be32b826b9d0a696a42ba2fb4a5354dd75 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 03:20:22 +0000 Subject: [PATCH 2/3] Address review feedback on #2501 in-flight grace fix - Document worst-case ~2*stale_window wedge-detection bound and the intentional 'fresh-but-old' semantics during the grace in snapshot()'s docstring (reviewer minor: source-recoverable rationale). - Expand the inline comment in the grace branch to cite the 'fix #1' framing from #2501 so the bound's rationale is recoverable from the source alone (reviewer minor). - Add an integration-level test that drives snapshot() while a real probe_now() is parked mid-probe on a worker thread, populating the in-flight flag and _probe_started_at_monotonic via the production code path. Closes the loop end-to-end so a future refactor that stops setting _probe_started_at_monotonic from probe_now() fails this test where the field-poking variants would silently keep passing (reviewer non-blocking suggestion). --- orchestrator/state_store_probe.py | 20 +++++++- orchestrator/tests/test_state_store_probe.py | 51 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/orchestrator/state_store_probe.py b/orchestrator/state_store_probe.py index d795f4787c..e15eaa7961 100644 --- a/orchestrator/state_store_probe.py +++ b/orchestrator/state_store_probe.py @@ -234,6 +234,16 @@ def snapshot(self) -> dict[str, Any]: callback later records healthy from the same probe (#2501). A wedged probe (in-flight indefinitely) still surfaces as stale once its in-flight age exceeds the staleness window. + Worst-case wedge detection latency is therefore bounded at + ~``2 * stale_window`` after the last good probe (one window + for the in-flight grace plus one for the existing cache age), + versus ~``stale_window`` before #2501. With the 30s default + this is ~60s of blindness in the pathological case — the + documented trade-off for eliminating the dual-write flap. + During the grace, ``fresh=True`` is reported even though + ``age_seconds`` may exceed ``stale_window``; operators + inspecting ``/api/v1/health`` mid-grace will see a + "fresh-but-old" response, which is intentional. - ``age_seconds``: float | None — seconds since the most recent probe, ``None`` if the BG thread has not run yet. """ @@ -261,8 +271,14 @@ def snapshot(self) -> dict[str, Any]: if not fresh and in_flight and started is not None: # Don't penalize the cache for a probe that's still in # progress: the BG callback will record the result from this - # same probe shortly. Bound the grace by the staleness window - # so a wedged probe (in-flight forever) still flips stale. + # same probe shortly (this is "fix #1" of the #2501 dual- + # write race — addressing the symptom on the snapshot side + # so the request path doesn't observe a transient unhealthy + # state from the same probe the BG thread will record as + # healthy seconds later). Bound the grace by the staleness + # window so a wedged probe (in-flight forever) still flips + # stale — without this bound the cache would become a + # permanent lie on a real wedge. in_flight_age = now - started if in_flight_age <= stale_window: fresh = True diff --git a/orchestrator/tests/test_state_store_probe.py b/orchestrator/tests/test_state_store_probe.py index 0bea103f3d..e5ef1a97e6 100644 --- a/orchestrator/tests/test_state_store_probe.py +++ b/orchestrator/tests/test_state_store_probe.py @@ -210,6 +210,57 @@ def test_in_flight_probe_still_flips_stale_once_wedged(self, with_repo_path): assert snap["healthy"] is False assert "stale" in snap["message"] + def test_snapshot_during_real_in_flight_probe_stays_fresh(self, with_repo_path): + """Integration check: drive ``snapshot()`` while a real + ``probe_now()`` is parked mid-probe in another thread, so the + in-flight flag and ``_probe_started_at_monotonic`` are both + populated by the production code path (not by manual field + pokes). Closes the loop end-to-end: if a future refactor stops + populating ``_probe_started_at_monotonic`` from inside + ``probe_now``, this test fails where the field-poking variants + above would silently keep passing.""" + from state_store_probe import StateStoreProbe + + probe = StateStoreProbe(interval=1.0, stale_multiplier=2.0) + probe_started = threading.Event() + release_probe = threading.Event() + + def slow_probe(_path: Path) -> tuple[bool, str, dict[str, dict[str, str]]]: + probe_started.set() + release_probe.wait(timeout=2.0) + return True, "ok-slow", {str(_path): {"status": "ok"}} + + with patch("state_store_probe.probe_state_store_at", side_effect=slow_probe): + # Prime the cache with a healthy result first so snapshot() + # has something to extend the freshness of, then artificially + # age that cache so the in-flight grace is the only thing + # keeping snapshot() fresh. + with patch( + "state_store_probe.probe_state_store_at", + return_value=(True, "ok", {"/sentinel/repo/path": {"status": "ok"}}), + ): + probe.probe_now() + with probe._lock: # type: ignore[attr-defined] + probe._last_check_monotonic -= 10.0 # type: ignore[attr-defined,operator] + + # Park a real probe mid-flight on a worker thread. + t = threading.Thread(target=probe.probe_now) + t.start() + try: + assert probe_started.wait(timeout=1.0), "in-flight probe never started" + + snap = probe.snapshot() + # Cache age is 10s (> 2*interval=2s), but the in-flight + # probe started <1s ago — grace must keep snapshot fresh. + assert snap["fresh"] is True + assert snap["healthy"] is True + assert snap["message"] == "ok" + assert snap["age_seconds"] is not None + assert snap["age_seconds"] >= 10.0 + finally: + release_probe.set() + t.join(timeout=2.0) + class TestExceptionIsolation: """Exceptions in the underlying probe must not crash the BG thread From 4ae5642504fb2bfade3c90abcac32db0a4649f50 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 03:35:57 +0000 Subject: [PATCH 3/3] Tighten worst-case wedge detection bound in snapshot() docstring Reviewer noted that the '~2 * stale_window' / '60s with 30s default' framing is loose. The BG loop fires every `interval` seconds, so the in-flight probe starts within `interval` of the last good completion, and the grace extends only until that probe's own age exceeds `stale_window`. The tight bound is therefore `stale_window + interval`, which under the defaults (interval=15s, stale_multiplier=2.0) is ~45s of blindness, not ~60s. The 2 * stale_window framing only saturates when stale_multiplier=1.0. Address-only docstring change; no behavior change. --- orchestrator/state_store_probe.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/orchestrator/state_store_probe.py b/orchestrator/state_store_probe.py index e15eaa7961..102b991f77 100644 --- a/orchestrator/state_store_probe.py +++ b/orchestrator/state_store_probe.py @@ -235,11 +235,18 @@ def snapshot(self) -> dict[str, Any]: A wedged probe (in-flight indefinitely) still surfaces as stale once its in-flight age exceeds the staleness window. Worst-case wedge detection latency is therefore bounded at - ~``2 * stale_window`` after the last good probe (one window - for the in-flight grace plus one for the existing cache age), - versus ~``stale_window`` before #2501. With the 30s default - this is ~60s of blindness in the pathological case — the - documented trade-off for eliminating the dual-write flap. + ``stale_window + interval`` after the last good probe — the + existing cache stays fresh for ``stale_window``, then the + next BG probe starts (within ``interval`` seconds of the + last completion) and the in-flight grace extends freshness + until that probe's own age exceeds ``stale_window``. With + the defaults (``interval=15s``, ``stale_multiplier=2.0`` → + ``stale_window=30s``) that's ~45s of blindness in the + pathological case, versus ~``stale_window`` (30s) before + #2501 — the documented trade-off for eliminating the + dual-write flap. The looser ``2 * stale_window`` upper bound + only saturates when ``stale_multiplier=1.0`` (interval + equals stale_window). During the grace, ``fresh=True`` is reported even though ``age_seconds`` may exceed ``stale_window``; operators inspecting ``/api/v1/health`` mid-grace will see a