diff --git a/orchestrator/state_store_probe.py b/orchestrator/state_store_probe.py index 8e66645f78..102b991f77 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,31 @@ 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. + Worst-case wedge detection latency is therefore bounded at + ``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 + "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. """ @@ -232,6 +259,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 +271,24 @@ 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 (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 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..e5ef1a97e6 100644 --- a/orchestrator/tests/test_state_store_probe.py +++ b/orchestrator/tests/test_state_store_probe.py @@ -154,6 +154,113 @@ 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"] + + 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