Repository navigation
Fix ragflow server hung after parsing a big file - #17936
Conversation
📝 WalkthroughWalkthroughRedis lock operations now recover from script errors and refresh lock instances before acquisition. Progress updates now conditionally execute and release locks based on acquisition success. ChangesRedis lock handling
Estimated code review effort: 2 (Simple) | ~10 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
api/ragflow_server.py (1)
61-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog failed lock acquisition.
When
redis_lock.acquire()returnsFalse, the loop skipsDocumentService.update_progress()and waits six seconds without logging. This hides the new lock-contention path. Add a rate-limited debug log or metric for theFalseresult.As per coding guidelines,
**/*.pymust add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/ragflow_server.py` around lines 61 - 73, Update the lock-handling flow around redis_lock.acquire() to record when acquisition returns False, using a rate-limited debug log or metric before the existing wait cycle. Keep DocumentService.update_progress() restricted to successful acquisitions and preserve the current exception and release handling.Source: Coding guidelines
rag/utils/redis_conn.py (1)
517-522: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCatch only recoverable Valkey errors.
except Exceptionconverts every failure intoFalseand reopens the shared connection. It also catches localTypeErrorandAttributeErrordefects. Those defects then look like a Redis outage.In Valkey 6.0.2,
TimeoutError,ConnectionError, andResponseErrorderive fromvalkey.exceptions.ValkeyError. Catch that base class, or a narrower set. Let unrelated exceptions propagate. (raw.githubusercontent.com)Suggested fix
- except Exception as e: + except redis.exceptions.ValkeyError as e:Please verify the exception policy and add tests for timeout, script, and programmer-error paths.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/utils/redis_conn.py` around lines 517 - 522, Update the exception handling in delete_if_equal to catch only recoverable valkey.exceptions.ValkeyError failures, preserving the warning, connection reopen, and False return for those errors. Let unrelated TypeError and AttributeError defects propagate, and add tests covering timeout, script/response, and programmer-error paths.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/utils/redis_conn.py`:
- Around line 551-559: Update acquire and spin_acquire to catch and re-raise
Valkey errors from lock acquisition while deleting the lock only when the
current self.lock_value still owns it; preserve clean False acquisition results
without cleanup, and apply the same failure handling to both methods.
---
Nitpick comments:
In `@api/ragflow_server.py`:
- Around line 61-73: Update the lock-handling flow around redis_lock.acquire()
to record when acquisition returns False, using a rate-limited debug log or
metric before the existing wait cycle. Keep DocumentService.update_progress()
restricted to successful acquisitions and preserve the current exception and
release handling.
In `@rag/utils/redis_conn.py`:
- Around line 517-522: Update the exception handling in delete_if_equal to catch
only recoverable valkey.exceptions.ValkeyError failures, preserving the warning,
connection reopen, and False return for those errors. Let unrelated TypeError
and AttributeError defects propagate, and add tests covering timeout,
script/response, and programmer-error paths.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 21570985-859e-4f3e-b162-84b5da27db2d
📒 Files selected for processing (2)
api/ragflow_server.pyrag/utils/redis_conn.py
| def acquire(self): | ||
| REDIS_CONN.delete_if_equal(self.lock_key, self.lock_value) | ||
| self._refresh_lock() | ||
| return self.lock.acquire(token=self.lock_value) | ||
|
|
||
| async def spin_acquire(self): | ||
| REDIS_CONN.delete_if_equal(self.lock_key, self.lock_value) | ||
| while True: | ||
| self._refresh_lock() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate file =="
fd -a 'redis_conn.py' . || true
echo "== file size and relevant sections =="
wc -l rag/utils/redis_conn.py
sed -n '480,610p' rag/utils/redis_conn.py | cat -n
echo "== callers and lock usage =="
rg -n "RedisDistributedLock|update_progress|spin_acquire|acquire\\(" rag -S || true
echo "== imports and dependency versions =="
rg -n "redis|valkey|redis-py|valkey-py" pyproject.toml requirements*.txt setup.py setup.cfg tox.ini constraints*.txt 2>/dev/null || trueRepository: infiniflow/ragflow
Length of output: 6576
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== RedisDB class outline and relevant sections =="
sed -n '545,598p' rag/utils/redis_conn.py | cat -n
echo "== task executor lock usage =="
sed -n '1800,1895p' rag/svr/task_executor.py | cat -n
echo "== graphrag lock usage =="
sed -n '180,210p' rag/graphrag/general/index.py | cat -n
sed -n '455,485p' rag/graphrag/general/index.py | cat -n
echo "== task limiter implementation =="
sed -n '1820,1855p' rag/svr/task_executor.py | cat -n
echo "== direct usages of redis_lock.acquire and spin_acquire across repo =="
python3 - <<'PY'
import ast
from pathlib import Path
for path in Path('.').rglob('*.py'):
if '.git' in path.parts or '__pycache__' in path.parts:
continue
try:
tree = ast.parse(path.read_text(errors='ignore'), filename=str(path))
except Exception:
continue
for node in ast.walk(tree):
if isinstance(node, ast.AnnAssign) and isinstance(node.value, ast.Await):
val = ast.unparse(node.value) if hasattr(ast, 'unparse') else ''
if 'spin_acquire' in val:
print(f"{path}:{node.lineno}: await {val}")
elif isinstance(node, ast.Call):
func = node.func
text = ast.unparse(func) if hasattr(ast, 'unparse') else ''
if 'spin_acquire' in text or 'acquire(' in text and 'set_default_thread' not in text:
print(f"{path}:{node.lineno}: {text}")
PY
echo "== valkey lock source from installed package if available =="
python3 - <<'PY'
try:
import valkey.lock as valkey_lock_module
print(valkey_lock_module.__file__)
import inspect
for name in ["Lock", "acquire", "lock", "SETNX", "setnx", "set_lock"]:
for obj_name in [name]:
obj = getattr(valkey_lock_module, obj_name, None)
if obj:
print(f"\n--- {obj_name} ---")
print(inspect.getsource(obj)[:3500] if callable(obj) else "class")
except ModuleNotFoundError as e:
print(f"valkey module not installed: {e}")
PYRepository: infiniflow/ragflow
Length of output: 10875
🌐 Web query:
valkey-py 6.0.2 lock acquire token SET NX response may be lost acquire returns False behavior
💡 Result:
In valkey-py, the Lock.acquire method uses the SET command with NX (and optionally PX) to perform distributed locking [1][2]. It does not generally suffer from a "lost response" issue where a successful acquisition is incorrectly reported as False, provided the underlying connection and Valkey server are stable [1][2]. The acquire method relies on the response of the valkey.set(..., nx=True) call [2]. Under normal conditions: 1. If SET... NX succeeds, Valkey returns OK, and valkey-py evaluates this as a successful acquisition (returns True) [3][2]. 2. If the key already exists, SET... NX returns None (or nil), and valkey-py evaluates this as a failure to acquire the lock (returns False) [3][2]. If you are experiencing scenarios where acquire returns False despite expecting success, this is typically due to: - Contention: Another client already holds the lock, causing the NX condition to fail as designed [4][3]. - Network/Timeout issues: If a network issue or timeout occurs during the request, the client may fail to receive the OK response, leading to a failure state. - Improper Token Handling: While valkey-py handles token generation (or allows custom tokens) to ensure safe release, losing the token itself is generally not the cause of an acquire failure; rather, it would be an issue during the release phase if the token does not match [5][3]. If you suspect that the response is being misinterpreted due to the use of the GET parameter (which can return nil even on success in specific newer Valkey versions), note that standard valkey-py Lock usage typically does not include the GET option by default [2][6]. If you have customized the lock implementation to include GET, the logic for determining "success" must be updated to account for the command's return value [6]. For standard distributed locking, ensure you are following the recommended pattern of using a random, non-guessable token for each lock attempt to allow for safe release [3].
Citations:
- 1: https://valkey-py.readthedocs.io/en/stable/lock.html
- 2: https://valkey-py.readthedocs.io/en/stable/_modules/valkey/lock.html
- 3: https://valkey.io/commands/set/
- 4: https://valkey.io/topics/distlock/
- 5: https://github.com/valkey-io/valkey-py/blob/69b8245d/tests/test_lock.py
- 6: Some issues about the GET parameter in the SET command valkey-io/valkey#1415
🌐 Web query:
github valkey-io valkey-py 69b8245 valkey/lock.py acquire token self._lock.acquire
💡 Result:
In the valkey-py library (at commit 69b8245), the acquire method of the Lock class is responsible for obtaining a distributed lock [1][2][3]. The method signature is: acquire(sleep=None, blocking=None, blocking_timeout=None, token=None) [1][2] Key details regarding the token parameter and acquisition process include: 1. Purpose of the token: The token serves as a unique identifier for the lock instance, ensuring that a client can only release a lock that it currently owns [1][2][3]. If a token is not provided, a UUID is automatically generated for this purpose [1][2]. 2. Storage: When acquire succeeds, the token is typically stored in the client's self.local.token (if thread_local is enabled) [1][3]. 3. Acquisition Logic: The method enters a loop that calls self.do_acquire(token) [1]. The do_acquire method uses the Valkey SET command with the nx=True (set if not exist) option to attempt to set the lock key to the token value [1]. 4. Blocking Behavior: If blocking is set to True (default), the method will retry the acquisition at intervals defined by sleep until the lock is obtained or the blocking_timeout is reached [1][2]. The valkey-py library is a fork of redis-py, and its locking mechanism follows similar distributed locking patterns [4][5]. Tests in the codebase verify that the token is correctly set in Valkey and stored in the local object upon successful acquisition [3].
Citations:
- 1: https://valkey-py.readthedocs.io/en/stable/_modules/valkey/lock.html
- 2: https://valkey-py.readthedocs.io/en/stable/lock.html
- 3: https://github.com/valkey-io/valkey-py/blob/69b8245d/tests/test_lock.py
- 4: https://github.com/valkey-io/valkey-py
- 5: https://github.com/valkey-io/valkey-py/blob/69b8245d/pyproject.toml
Clean up an indeterminate lock acquisition.
If self.lock.acquire() raises after Valkey commits the SET NX but before the response is returned, acquire() propagates the exception without deleting its token. In this caller path, the caller treats the failure as acquired = False and skips its release block, so the server-held lock can block other work until it expires.
Catch the Valkey acquisition error, call REDIS_CONN.delete_if_equal(self.lock_key, self.lock_value), then re-raise. Apply the same ownership cleanup to spin_acquire() as well. Do not clean up after a clean False result from SET NX.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/utils/redis_conn.py` around lines 551 - 559, Update acquire and
spin_acquire to catch and re-raise Valkey errors from lock acquisition while
deleting the lock only when the current self.lock_value still owns it; preserve
clean False acquisition results without cleanup, and apply the same failure
handling to both methods.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17936 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
wangq8
left a comment
There was a problem hiding this comment.
PR Review: Fix ragflow server hung after parsing a big file
Author: @wangq8
Files: api/ragflow_server.py, rag/utils/redis_conn.py (+20 / −7)
Summary
This PR fixes a bug where the ragflow server hangs after parsing a large file because a Valkey connection timeout during update_progress causes lock state corruption. The fix has three parts:
redis_conn.py–delete_if_equal: Wraps the Lua script call in try/except, reconnects on failure, returnsFalse.redis_conn.py–RedisDistributedLock: Adds_refresh_lock()to recreate the Lock object with the current Redis connection, called before everyacquire()/spin_acquire()attempt.ragflow_server.py–update_progress: Tracksacquiredflag, only releases when lock was actually acquired.
✅ What Looks Good
- Root cause addressed. The traceback shows
TimeoutErrorindelete_if_equal(called fromacquire()). By catching it + reconnecting + refreshing the Lock, subsequent retries use a healthy connection. acquiredflag is the right fix. The oldfinallyblock unconditionally calledrelease(), which could re-raise and mask the original error. Now release is only attempted when the lock was truly held._refresh_lock()pattern is consistent. After__open__()replacesREDIS_CONN.REDIS, the oldLockinstance holds a stale connection. Recreating it ensuresacquire()uses the fresh client.register_scriptsin__open__re-registerslua_delete_if_equalwith the new connection, so the fix is self-consistent.blocking_timeoutstored is needed for_refresh_lock()to recreate the Lock with the same parameters.
⚠️ Minor Suggestions
-
spin_acquire–delete_if_equalcalled only once before the loop:
Inspin_acquire,delete_if_equalis called once before entering the while loop. If that call fails (connection error → reconnect), the stale lock is not cleaned up. The_refresh_lock()inside the loop handles the connection, but the stale lock from a previous crashed owner might persist until its TTL expires. Consider also callingdelete_if_equalwith a fresh connection on each iteration (or at least after a reconnect):async def spin_acquire(self): while True: REDIS_CONN.delete_if_equal(self.lock_key, self.lock_value) self._refresh_lock() if self.lock.acquire(token=self.lock_value): break await asyncio.sleep(10)
This is non-blocking, but worth considering for robustness.
-
delete_if_equalsemantic change: Previously it raised on connection errors; now it returnsFalse. Callers that relied on the exception for error handling might silently not notice the failure. In this codebase, the only callers areacquire()andrelease(), both of which already handleFalsecorrectly (just fail to acquire/release), so this is fine — but worth noting for any future callers.
Verdict
LGTM. The fix is clean, well-scoped, and directly addresses the connection-timeout → lock-corruption chain. The minor suggestion on spin_acquire is optional polish — the core bug is fixed. ✅
Fix: