Skip to content

fix(lifecycle): confirm a lost lifecycle lease before renewal stops - #32

Merged
ImMohammad20000 merged 2 commits into
PasarGuard:mainfrom
Free-Guy-IR:upn/lifecycle-lease-w
Nov 4, 2026
Merged

ImMohammad20000 merged 2 commits into
PasarGuard:mainfrom
Free-Guy-IR:upn/lifecycle-lease-w

Conversation

@Free-Guy-IR

Copy link
Copy Markdown
Contributor

Fixes #29

What

When coordinator.heartbeat(lease) returns False, the heartbeat now reads coordinator.get_state(node_id) before giving up. It keeps renewing while the state shows the same epoch, owner and operation and the lease cannot have expired yet (measured from the last granted renewal, or from the acquire request). A different owner or epoch, a missing lease, or a lease that may already have expired stops renewal and logs "was lost" as before.

diff --git a/PasarGuardNodeBridge/controller.py b/PasarGuardNodeBridge/controller.py
index 839ed5b..179e6d2 100644
--- a/PasarGuardNodeBridge/controller.py
+++ b/PasarGuardNodeBridge/controller.py
@@ -415,11 +415,32 @@ class Controller:
         node_version = await self.node_version()
         return self._is_version_at_least(node_version, "0.2.0"), node_version
 
-    async def _heartbeat_lifecycle_lease(self, lease: LifecycleLease) -> None:
+    async def _lifecycle_lease_still_held(self, lease: LifecycleLease, valid_until: float) -> bool:
+        if asyncio.get_running_loop().time() >= valid_until:
+            return False
+        try:
+            state = await self._lifecycle_coordinator.get_state(lease.node_id)
+        except Exception as e:
+            self.logger.warning(
+                f"[{self.name}] Lifecycle lease state read failed | Error: {type(e).__name__} - {e!s}"
+            )
+            return True
+        return (
+            state is not None
+            and state.epoch == lease.epoch
+            and state.owner == lease.worker_id
+            and state.operation == lease.operation
+        )
+
+    async def _heartbeat_lifecycle_lease(self, lease: LifecycleLease, acquired_at: float) -> None:
         interval = max(self._lifecycle_lease_seconds / 3, 0.01)
+        loop = asyncio.get_running_loop()
+        renewal = asyncio.current_task()
+        valid_until = acquired_at + lease.lease_seconds
         try:
-            while True:
+            while not renewal.cancelling():
                 await asyncio.sleep(interval)
+                sent_at = loop.time()
                 try:
                     renewed = await self._lifecycle_coordinator.heartbeat(lease)
                 except Exception as e:
@@ -430,18 +451,29 @@ class Controller:
                     )
                     continue
                 if renewed is False:  # coordinators that report it: the lease is gone, stop renewing
+                    if await self._lifecycle_lease_still_held(lease, valid_until):
+                        self.logger.warning(
+                            f"[{self.name}] Lifecycle lease for {lease.operation} was not renewed but is still "
+                            "held; renewing again"
+                        )
+                        continue
                     self.logger.warning(f"[{self.name}] Lifecycle lease for {lease.operation} was lost")
                     return
+                if renewed is True:
+                    valid_until = sent_at + lease.lease_seconds
         except asyncio.CancelledError:
             pass
 
     async def _acquire_lifecycle_lease(self, operation: LifecycleOperation) -> LifecycleLease:
+        requested_at = asyncio.get_running_loop().time()
         lease = await self._lifecycle_coordinator.try_acquire(
             self.node_id, self.worker_id, operation, self._lifecycle_lease_seconds
         )
         if lease is None:
             raise NodeAPIError(409, f"Node lifecycle operation already in progress for {self.node_id}")
-        self._lifecycle_heartbeat_tasks[lease.token] = asyncio.create_task(self._heartbeat_lifecycle_lease(lease))
+        self._lifecycle_heartbeat_tasks[lease.token] = asyncio.create_task(
+            self._heartbeat_lifecycle_lease(lease, requested_at)
+        )
         return lease
 
     async def _release_lifecycle_lease(

tests/test_maintenance.py: LostLeaseCoordinator now releases the lease when it reports it lost, so that test still checks a real loss.

Why

See the issue. A coordinator can answer False without the lease being gone (the panel's NATS coordinator does this when its compare-and-set retries are exhausted). Stopping renewal on that answer lets the lease expire in the middle of a long update, and a second worker then acts on the same node.

Relation to #18

The open PR #18 also treats a False heartbeat as a lost lease: it turns it into LifecycleLeaseLostError. This PR changes exactly that interpretation: False alone is no longer taken as proof of loss; the stored state decides. If #18 lands first, its False branch should consult the stored state in the same way.

Tests

  • tests/test_lifecycle_heartbeat.py: test_an_unconfirmed_renewal_while_the_lease_is_still_held_keeps_renewing, a renewal answered False while the lease is still held keeps renewing, so no other worker can take the lease mid-update.
  • tests/test_maintenance.py: a lease that is really lost still stops renewal.
  • tests/test_lifecycle_lease_interleave.py: test_two_workers_never_both_renew_one_lease, two workers on one node; the second must be rejected on all twelve acquire attempts while the first is still updating.

Before the fix (v0.9.4):

FAIL: test_two_workers_never_both_renew_one_lease (tests.test_lifecycle_lease_interleave.LeaseInterleaveTests.test_two_workers_never_both_renew_one_lease)
AssertionError: second worker acquired while the first still renewed
Ran 1 test in 1.690s
FAILED (failures=1)

After the fix, the full suite (python -m unittest tests.test_lifecycle_heartbeat tests.test_lifecycle_lease_interleave tests.test_maintenance tests.test_storage tests.test_sync_transport tests.test_user_sync): Ran 75 tests in 34.134s OK.

The heartbeat stopped renewing the first time a coordinator answered False. A coordinator may answer False while the lease is still this worker's, for example when its compare-and-set retries run out under contention, so one busy moment of the store let the lease expire under a long node or core update and another worker could start the node in the middle of it. A False answer is now checked against the coordinator state: renewal continues while the state shows the same epoch, owner and operation and the lease cannot have run out since the last granted renewal. Another owner or epoch, no lease, or a lease that may have expired stops renewal as before.
@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3431891a-23a9-4110-96d5-ab41e2802555
Commits

Reviewing files that changed from the base of the PR and between f892a5c and 020962c.

Files selected for processing: 4
  • PasarGuardNodeBridge/controller.py
  • tests/test_lifecycle_heartbeat.py
  • tests/test_lifecycle_lease_interleave.py
  • tests/test_maintenance.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@ImMohammad20000
ImMohammad20000 merged commit 80f81ad into PasarGuard:main Nov 4, 2026
5 checks passed
Free-Guy-IR added a commit to Free-Guy-IR/node_bridge_py that referenced this pull request Nov 7, 2026
Takes the interleaving test of upstream 80f81ad (PasarGuard#32) unchanged. The
controller part of 80f81ad has been on fork main since d6f43c7, which
it was upstreamed from; c1958a8 later made the renewal loop run while
the lease token is still registered instead of until the task is
cancelling.

On fork main the test passes on Python 3.12 and 3.14. With the
still-held check removed from _heartbeat_lifecycle_lease it fails:
the second worker acquires the lease while the first still renews it.
@Free-Guy-IR

Copy link
Copy Markdown
Contributor Author

A correction to the impact line of #29, which said that "one busy moment of the shared store" lets a second worker act on the same node. That overstated it. Re-checked on main c5632b6 with panel dev f92acaf51cec. The problem was found by code review and was never seen in production.

What it really takes:

  • the panel's shared NATS memory (NatsNodeLifecycleCoordinator); the panel uses it only when NATS is enabled with more than one worker (app/nats/__init__.py:19-21). The bridge's bundled in-memory coordinator returns False only when it holds no lease for the node or holds it under another token (PasarGuardNodeBridge/storage.py:355-362);
  • all 32 compare-and-set writes of one renewal failing in a row (app/node/nats_memory.py:841-858). A write that fails 31 times and then succeeds renews normally;
  • the reads still succeeding. If the read raises, heartbeat() raises, and the bridge already keeps renewing on an exception (controller.py:425-431 at v0.9.4 f892a5c).

Lab run (macOS, real nats-server v2.10.25, the panel's real coordinator, the bridge's real lease code; lease 6 s; two runs each). The only thing injected: before each of worker A's next N renewal writes (N as in the table), a separate NATS connection rewrote the same key with its current value, so the real server rejected A's write as a stale revision:

Writes failed in a row v0.9.4 f892a5c c5632b6
31 second worker never acquired (2/2) never acquired (2/2)
32 second worker acquired after about 6 s (2/2) never acquired (2/2)

One limit: the fix cannot help when the renewal's own retries outlast the lease. With a 1 s lease and the injection set to 32 conflicts in the same lab, the second worker acquired on c5632b6 too (3/3 runs, at 1.02-1.04 s), because worker A's renewal did not succeed before the stored lease expired. In one run B took over after 31 injected conflicts, while A was still retrying; in one A logged that the lease was still held and kept renewing; in one A had already given up because the lease could have expired (controller.py:418-420). The bridge default, which the panel does not override, is 60 s (controller.py:147).

Free-Guy-IR added a commit to Free-Guy-IR/node_bridge_py that referenced this pull request Nov 11, 2026
The public part moves from 0.9.2 to 0.10.0 in one step because that is
upstream's own release line: upstream v0.10.0 (c5632b6) is a
version-only bump over v0.9.5, and every upstream release commit from
v0.9.2 to v0.10.0 is now carried here or refused on record.

Carried, each re-checked against this tree: PasarGuard#23 maintenance timeouts
(b7df83f), every hunk of which that upstream v0.10.0 still has is
here; PasarGuard#24 Masque (33276ea, f707f09), all of it except Masque masque =
7, which rides Proxy field 12 because field 7 is Hysteria2 here; PasarGuard#27
rejected-user isolation (67b35df, e4fe5b1, c8b6707), whose sorted
changed lines equal a01bdbb's, 934 lines, and which later fork commits
build on; PasarGuard#32 lifecycle lease confirmation (d6f43c7), whose
_lifecycle_lease_still_held is upstream's line for line while the
renewal loop ends on the lease's release rather than on any cancel
request; and the WireGuard pre_shared_key of PasarGuard#26 (4ee34d0).

Refused on record: the MTProto half of PasarGuard#26, BackendType MTPROTO = 2 and
Proxy mtproto = 8, because 2 and 8 are SING_BOX and open_vpn here and
the fork has no MTProto backend. Not taken: the bridge's own
development uv.lock refresh of v0.9.5; the panel resolves those
libraries from its own lock.

The local label restarts at singbox.1 on the new public version.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lifecycle lease heartbeat stops renewing on the first False, even when the coordinator still shows the lease as ours

2 participants