From e8383df3b80097715b4355e4156109aa4c9c8cf5 Mon Sep 17 00:00:00 2001 From: yangdx Date: Mon, 17 Nov 2025 06:43:37 +0800 Subject: [PATCH] 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 --- lightrag/kg/shared_storage.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lightrag/kg/shared_storage.py b/lightrag/kg/shared_storage.py index 576d6a8d..284beb00 100644 --- a/lightrag/kg/shared_storage.py +++ b/lightrag/kg/shared_storage.py @@ -1514,9 +1514,12 @@ class NamespaceLock: 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) - return await ctx.__aenter__() + return result async def __aexit__(self, exc_type, exc_val, exc_tb): """Exit the current context and clean up"""