Fix NamespaceLock context variable timing to prevent lock bricking

* Acquire lock before setting ContextVar
* Prevent state corruption on cancellation
* Fix permanent lock brick scenario
* Store context only after success
* Handle acquisition failure properly
This commit is contained in:
yangdx 2025-11-17 06:43:37 +08:00
parent 95e1fb1612
commit e8383df3b8

View file

@ -1514,9 +1514,12 @@ class NamespaceLock:
enable_logging=self._enable_logging, enable_logging=self._enable_logging,
) )
# Store context in this coroutine's ContextVar # Acquire the lock first, then store context only after successful acquisition
# This prevents the ContextVar from being set if acquisition fails (e.g., due to cancellation),
# which would permanently brick the lock
result = await ctx.__aenter__()
self._ctx_var.set(ctx) self._ctx_var.set(ctx)
return await ctx.__aenter__() return result
async def __aexit__(self, exc_type, exc_val, exc_tb): async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Exit the current context and clean up""" """Exit the current context and clean up"""