From c18cf8e69a4cf24fe67ba87b1344bc938e2cf84b Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Thu, 18 Jun 2026 11:04:33 +0200 Subject: [PATCH 1/3] feat(heartbeat): report update_in_progress so the manager can clear `updating` The greffer now reports update_in_progress in every heartbeat: the same non-blocking flock probe of $GREFFON_PATH/.update.lock the controller uses to 409 start/stop/update (HLD section 10). The manager uses a settled false to clear its transient `updating` UI flag, which otherwise stuck for the full 600s grace after a manager-triggered update. This is the signal that covers an update which FAILS WITHOUT restarting the node (the updater dies during verify/pull before any recreate): the node keeps beating, so no re-register fires, and the manager would otherwise show "updating" until the grace lapsed. The probe fails safe to False. Bump 0.3.9 -> 0.3.10. Pairs with the manager fix; the manager handles the field's absence (older greffers) gracefully. --- app/__init__.py | 2 +- app/workers/heartbeat.py | 21 +++++++++++++++++++++ pyproject.toml | 2 +- tests/test_workers_heartbeat.py | 23 +++++++++++++++++++++++ tests/test_workers_register.py | 4 ++-- 5 files changed, 48 insertions(+), 4 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 5a1f0833..66ef04ad 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,4 +2,4 @@ # per-greffon ``min_greffer_version`` compatibility gate can refuse deploying an # L4 (or any version-floored) greffon onto a greffer too old to run it. Keep in # sync with pyproject.toml. Single source for the register report. -__version__ = "0.3.9" +__version__ = "0.3.10" diff --git a/app/workers/heartbeat.py b/app/workers/heartbeat.py index 526b8f14..d3aa7ac6 100644 --- a/app/workers/heartbeat.py +++ b/app/workers/heartbeat.py @@ -105,6 +105,23 @@ def _disk_free_bytes(settings: Settings) -> int | None: return None +def _update_in_progress(settings: Settings) -> bool: + """Whether a self-update currently holds the ``/data`` update lock. + + Reports the SAME non-blocking lock probe the controller uses to 409 + start/stop/update (HLD section 10), at the SAME path + (``$GREFFON_PATH/.update.lock``). The manager reads this to clear its + transient ``updating`` flag once an update finishes OR fails without + restarting the node (the updater dying mid-verify releases the lock but never + recreates the greffer, so no re-register fires). The probe itself fails safe + to False (cannot tell -> do not claim updating).""" + from pathlib import Path + + from apps.utils.docker import updater + + return updater.update_in_progress(Path(settings.greffon_path) / ".update.lock") + + def _read_meminfo() -> tuple[int | None, int | None]: """Host memory ``(used, total)`` in bytes from ``/proc/meminfo``, or ``(None, None)``. @@ -202,6 +219,10 @@ def _one_heartbeat(app: FastAPI, seq: int) -> int: "reasons": reasons, "disk_free_bytes": _disk_free_bytes(settings), "instances": status_map, + # Lets the manager clear its transient "updating" flag the moment a + # self-update finishes or fails (lock released), instead of waiting out + # its grace window (covers a failed update that never restarts the node). + "update_in_progress": _update_in_progress(settings), } # Host vitals (resource-monitoring epic, Feature 1). Read from /proc, # independent of the docker status collection above, so they ride even a diff --git a/pyproject.toml b/pyproject.toml index 80f5ce54..c7422e23 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "greffer" -version = "0.3.9" +version = "0.3.10" description = "" authors = ["Greffon "] license = "AGPL-3.0-only" diff --git a/tests/test_workers_heartbeat.py b/tests/test_workers_heartbeat.py index 55bdc750..ea974761 100644 --- a/tests/test_workers_heartbeat.py +++ b/tests/test_workers_heartbeat.py @@ -49,6 +49,29 @@ def test_one_heartbeat_posts_payload_with_token( assert body["degraded"] is False assert body["interval"] == settings.heartbeat_interval assert "captured_at" in body and "uptime_s" in body + # No update lock held under a fresh tmp greffon_path -> reports not-updating. + assert body["update_in_progress"] is False + + +def test_one_heartbeat_reports_update_in_progress( + settings: Settings, tmp_path +) -> None: + """When a self-update holds the /data lock, the beat reports it so the manager + can keep ``updating`` true (and later clear it when this flips back to False).""" + settings.greffon_path = tmp_path # type: ignore[misc] + app = create_app(token="hb-tok", settings=settings) + app.state.status_map = {"map": {}, "at": time.monotonic()} + + with patch("app.workers.heartbeat.requests") as mock_requests, \ + patch("apps.utils.docker.updater.update_in_progress", + return_value=True) as probe: + mock_requests.post.return_value.status_code = 200 + _one_heartbeat(app, 1) + + body = mock_requests.post.call_args.kwargs["json"] + assert body["update_in_progress"] is True + # Probes the SAME path the controller 409s on (HLD section 10). + assert probe.call_args.args[0] == tmp_path / ".update.lock" def test_collect_or_reuse_uses_fresh_cache(settings: Settings) -> None: diff --git a/tests/test_workers_register.py b/tests/test_workers_register.py index 1a664755..32184333 100644 --- a/tests/test_workers_register.py +++ b/tests/test_workers_register.py @@ -78,12 +78,12 @@ def test_post_register_version_defaults_to_app_version(settings: Settings) -> No from app import __version__ # Sanity: the fixture didn't set GREFFER_VERSION, so the default applies. - assert settings.greffer_version == __version__ == "0.3.9" + assert settings.greffer_version == __version__ == "0.3.10" with patch("app.workers.register.requests") as mock_requests: mock_requests.post.return_value.status_code = 200 _post_register(settings, "10.0.0.1", "tok") kwargs = mock_requests.post.call_args.kwargs - assert kwargs["json"]["version"] == "0.3.9" + assert kwargs["json"]["version"] == "0.3.10" def test_post_register_version_overridable_via_env( From 2dfc315b7fabbf91fa575eb2d30ec0fdb054e2eb Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Thu, 18 Jun 2026 11:31:00 +0200 Subject: [PATCH 2/3] fix(updater): retry the /data lock acquire so a probe hold can't refuse an update Codex review (greffer#98): the new heartbeat update_in_progress probe (and the controller's start/stop/update guard) take LOCK_EX|LOCK_NB on /data/.update.lock acquire-then-immediately-release. The detached updater's one-shot acquire could land inside that microsecond hold and exit EXIT_REFUSED ("another update in progress") before the update even starts. acquire_lock now retries briefly (~1s) before giving up: a transient probe hold is absorbed, while a genuine concurrent update (holds the lock for its whole run) still refuses after the bounded retry. Also hardens the pre-existing controller-probe vs updater-acquire contention. --- cli/greffer_cli/updater/__main__.py | 33 +++++++++++++++++++++-------- cli/tests/test_updater_main.py | 32 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/cli/greffer_cli/updater/__main__.py b/cli/greffer_cli/updater/__main__.py index 8e6ef930..8cc7b025 100644 --- a/cli/greffer_cli/updater/__main__.py +++ b/cli/greffer_cli/updater/__main__.py @@ -17,6 +17,7 @@ import os import sys +import time from pathlib import Path from . import engine @@ -42,21 +43,35 @@ def _config_from_env(env: dict) -> dict: } -def acquire_lock(lock_path: Path = DEFAULT_LOCK): +def acquire_lock(lock_path: Path = DEFAULT_LOCK, *, + attempts: int = 20, retry_sleep_s: float = 0.05, + _sleep=time.sleep): """Exclusive flock on ``/data/.update.lock``. Returns a handle to release, or - None if another actor holds it (the caller refuses), or ``_NO_LOCK`` on a - platform without fcntl.""" + None if another actor genuinely holds it (the caller refuses), or ``_NO_LOCK`` + on a platform without fcntl. + + Retries briefly (``attempts`` x ``retry_sleep_s``, ~1s) before giving up. The + lock is also PROBED, non-blocking, acquire-then-immediately-release, by the + controller's start/stop/update guard and by every heartbeat + (``apps.utils.docker.updater.update_in_progress``). Those probes hold LOCK_EX + for only microseconds, but a one-shot acquire here could still land inside that + window and refuse a perfectly valid update. A genuine concurrent update holds + the lock for its whole run (minutes), so it still refuses after the short + retry; a transient probe hold is absorbed.""" try: import fcntl except ImportError: return _NO_LOCK fh = open(lock_path, "w", encoding="utf-8") - try: - fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: - fh.close() - return None - return fh + for attempt in range(attempts): + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return fh + except OSError: + if attempt < attempts - 1: + _sleep(retry_sleep_s) + fh.close() + return None def release_lock(handle) -> None: diff --git a/cli/tests/test_updater_main.py b/cli/tests/test_updater_main.py index 2109f638..c66292e1 100644 --- a/cli/tests/test_updater_main.py +++ b/cli/tests/test_updater_main.py @@ -74,6 +74,38 @@ def test_release_lock_tolerates_sentinels(): entry.release_lock(entry._NO_LOCK) # must not raise +def test_acquire_lock_retries_through_transient_probe_hold(tmp_path): + # A heartbeat/controller probe holds LOCK_EX for only microseconds; a one-shot + # acquire could land in that window and wrongly refuse. acquire_lock retries, + # so a hold released during the backoff is absorbed and the update proceeds. + fcntl = pytest.importorskip("fcntl") + lock = tmp_path / ".update.lock" + holder = open(lock, "w", encoding="utf-8") + fcntl.flock(holder.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + # Release the "probe" hold during the first backoff sleep (no real sleeping). + handle = entry.acquire_lock( + lock, attempts=5, + _sleep=lambda _s: fcntl.flock(holder.fileno(), fcntl.LOCK_UN)) + assert handle is not None + entry.release_lock(handle) + holder.close() + + +def test_acquire_lock_gives_up_on_persistent_hold(tmp_path): + # A genuine concurrent update holds the lock for its whole run, so acquire_lock + # still refuses after the bounded retry (it does not block forever). + fcntl = pytest.importorskip("fcntl") + lock = tmp_path / ".update.lock" + holder = open(lock, "w", encoding="utf-8") + fcntl.flock(holder.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + sleeps = {"n": 0} + handle = entry.acquire_lock( + lock, attempts=3, _sleep=lambda _s: sleeps.__setitem__("n", sleeps["n"] + 1)) + assert handle is None + assert sleeps["n"] == 2 # slept between attempts, not after the last + holder.close() + + def test_default_lock_is_data_update_lock(): # the in-container updater must flock the SAME filename on /data that the host # v1 `greffer update` resolves on the volume mountpoint, else they never From 719164c24af3b8728834b342331697cddc565eb8 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Thu, 18 Jun 2026 11:47:28 +0200 Subject: [PATCH 3/3] fix(update): retry the host CLI /data lock too (probe-race parity) Codex review (greffer#98 round 2): the bounded-retry fix for the in-container updater's acquire_lock left the HOST `greffer update` path (update.py _acquire_update_lock) still doing a one-shot LOCK_EX|LOCK_NB. The greffer's new per-heartbeat update_in_progress probe holds the same /data/.update.lock for microseconds, so a manual `greffer update` landing in that window would be spuriously refused (EXIT_PREFLIGHT_REFUSED). Apply the same ~1s bounded retry to the host lock: a transient probe hold is absorbed; a genuine concurrent run (host or in-container updater) still refuses after the retry. --- cli/greffer_cli/update.py | 28 ++++++++++++++++++++-------- cli/tests/test_update.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index 133e38b8..24a5c286 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -367,7 +367,8 @@ def _update_lock_path(cfg: Path) -> Path: return (Path(mountpoint) if mountpoint else cfg) / ".update.lock" -def _acquire_update_lock(cfg: Path): +def _acquire_update_lock(cfg: Path, *, attempts: int = 20, + retry_sleep_s: float = 0.05, _sleep=time.sleep): """Take an exclusive host lock so two concurrent ``greffer update`` runs can't interleave the compose rewrite and rollback-baseline capture (run B reading the file after run A already retagged it would record A's @@ -376,7 +377,15 @@ def _acquire_update_lock(cfg: Path): Returns an open handle to release later, ``None`` if another run already holds the lock, or ``_NO_HOST_LOCK`` on a platform without ``fcntl`` (Windows) where we proceed unlocked; concurrent runs there are the - operator's responsibility (v1 is operator-run).""" + operator's responsibility (v1 is operator-run). + + Retries briefly (~1s) before giving up: the same ``/data/.update.lock`` is + PROBED, non-blocking acquire-then-release, by the greffer's per-heartbeat + update_in_progress check and its controller start/stop/update guard. Those + holds are microseconds, but a one-shot acquire here could land inside one and + spuriously refuse a valid manual update. A genuine concurrent run (host or the + in-container updater) holds the lock for its whole run, so it still refuses + after the retry. Mirrors the in-container updater's acquire_lock.""" try: import fcntl except ImportError: @@ -402,12 +411,15 @@ def _acquire_update_lock(cfg: Path): "dir instead, so a concurrent remote update may not be detected.", file=sys.stderr, ) - try: - fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: - fh.close() - return None - return fh + for attempt in range(attempts): + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return fh + except OSError: + if attempt < attempts - 1: + _sleep(retry_sleep_s) + fh.close() + return None def _release_update_lock(handle) -> None: diff --git a/cli/tests/test_update.py b/cli/tests/test_update.py index bdc2112b..ff78c2ff 100644 --- a/cli/tests/test_update.py +++ b/cli/tests/test_update.py @@ -677,6 +677,38 @@ def test_bad_manifest_message_distinct_from_unreachable( assert "did not name a usable latest" in err # UPDATE_BAD_MANIFEST, not "unreachable" +def test_acquire_update_lock_retries_through_transient_probe_hold( + tmp_path: Path, monkeypatch) -> None: + # The greffer's per-heartbeat update_in_progress probe (and controller guard) + # briefly hold this same /data/.update.lock; a one-shot acquire would wrongly + # refuse a manual `greffer update` that lands in that window. Retry absorbs it. + fcntl = pytest.importorskip("fcntl") + monkeypatch.setattr(compose, "data_volume_mountpoint", lambda f: None) # cfg lock + holder = open(tmp_path / ".update.lock", "w", encoding="utf-8") + fcntl.flock(holder.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + handle = update._acquire_update_lock( + tmp_path, attempts=5, + _sleep=lambda _s: fcntl.flock(holder.fileno(), fcntl.LOCK_UN)) + assert handle not in (None, update._NO_HOST_LOCK) + update._release_update_lock(handle) + holder.close() + + +def test_acquire_update_lock_gives_up_on_persistent_hold( + tmp_path: Path, monkeypatch) -> None: + fcntl = pytest.importorskip("fcntl") + monkeypatch.setattr(compose, "data_volume_mountpoint", lambda f: None) + holder = open(tmp_path / ".update.lock", "w", encoding="utf-8") + fcntl.flock(holder.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + sleeps = {"n": 0} + handle = update._acquire_update_lock( + tmp_path, attempts=3, + _sleep=lambda _s: sleeps.__setitem__("n", sleeps["n"] + 1)) + assert handle is None + assert sleeps["n"] == 2 # slept between attempts, not after the last + holder.close() + + # --- ยง10 lock relocation: host lock -> /data volume rendezvous ------ def test_update_lock_path_uses_data_volume_mountpoint(tmp_path: Path, monkeypatch) -> None: