Skip to content

Fix ragflow server hung after parsing a big file - #17936

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-ragflow-server-hung
Aug 6, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-ragflow-server-hung

Conversation

@wangq8

@wangq8 wangq8 commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Fix:

[2026-08-06 11:28:11 +0800] [184365] [INFO] 127.0.0.1:37924 GET /api/v1/datasets/1793b408914611f1bff291ff2a1d387d/documents 1.1 200 3026 244753
2026-08-06 11:45:26,618 ERROR    184365 update_progress exception
Traceback (most recent call last):
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/_parsers/socket.py", line 65, in _read_from_socket
    data = self._sock.recv(socket_read_size)
TimeoutError: [Errno 110] Connection timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/lhp/qi/code/ragflow/api/ragflow_server.py", line 62, in update_progress
    if redis_lock.acquire():
       ~~~~~~~~~~~~~~~~~~^^
  File "/home/lhp/qi/code/ragflow/rag/utils/redis_conn.py", line 543, in acquire
    REDIS_CONN.delete_if_equal(self.lock_key, self.lock_value)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/rag/utils/redis_conn.py", line 517, in delete_if_equal
    return bool(self.lua_delete_if_equal(keys=[key], args=[expected_value], client=self.REDIS))
                ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/commands/core.py", line 6356, in call
    return client.evalsha(self.sha, len(keys), *args)
           ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/commands/core.py", line 5730, in evalsha
    return self._evalsha("EVALSHA", sha, numkeys, *keys_and_args)
           ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/commands/core.py", line 5714, in _evalsha
    return self.execute_command(command, sha, numkeys, *keys_and_args)
           ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 570, in execute_command
    response = conn.retry.call_with_retry(
        lambda: self._send_command_parse_response(
    ...<2 lines>...
        lambda error: self._disconnect_raise(conn, error),
    )
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/retry.py", line 65, in call_with_retry
    fail(error)
    ~~~~^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 574, in <lambda>
    lambda error: self._disconnect_raise(conn, error),
                  ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 556, in _disconnect_raise
    raise error
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/retry.py", line 62, in call_with_retry
    return do()
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 571, in <lambda>
    lambda: self._send_command_parse_response(
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        conn, command_name, *args, **options
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ),
    ^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 543, in _send_command_parse_response
    return self.parse_response(conn, command_name, **options)
           ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/client.py", line 590, in parse_response
    response = connection.read_response()
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/connection.py", line 546, in read_response
    response = self._parser.read_response(disable_decoding=disable_decoding)
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/_parsers/resp2.py", line 15, in read_response
    result = self._read_response(disable_decoding=disable_decoding)
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/_parsers/resp2.py", line 25, in _read_response
    raw = self._buffer.readline()
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/_parsers/socket.py", line 115, in readline
    self._read_from_socket()
    ~~~~~~~~~~~~~~~~~~~~~~^^
  File "/home/lhp/qi/code/ragflow/.venv/lib/python3.13/site-packages/valkey/_parsers/socket.py", line 78, in _read_from_socket
    raise TimeoutError("Timeout reading from socket")
valkey.exceptions.TimeoutError: Timeout reading from socket

@wangq8 wangq8 added the ci Continue Integration label Aug 6, 2026
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Redis 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.

Changes

Redis lock handling

Layer / File(s) Summary
Redis lock recovery
rag/utils/redis_conn.py
delete_if_equal logs script errors, reopens the connection, and returns False. RedisDistributedLock refreshes its underlying lock before synchronous and spinning acquisition attempts.
Progress update lock usage
api/ragflow_server.py
update_progress performs updates only after successful acquisition and releases the lock only when acquisition succeeded.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: kevinhush

Poem

A rabbit checks the Redis key,
And guards the lock with care.
If acquisition does not succeed,
No release floats through the air.
Fresh locks hop into each try.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request has no description, so it does not include the required summary or background context for reviewers. Add a Summary section that explains the server hang, its cause, and how the Redis lock changes resolve it.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main change: preventing the RAGFlow server from hanging after parsing a large file.

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

Comment @coderabbitai help to get the list of available commands.

@wangq8 wangq8 added ci Continue Integration and removed ci Continue Integration labels Aug 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
api/ragflow_server.py (1)

61-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log failed lock acquisition.

When redis_lock.acquire() returns False, the loop skips DocumentService.update_progress() and waits six seconds without logging. This hides the new lock-contention path. Add a rate-limited debug log or metric for the False result.

As per coding guidelines, **/*.py must 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 win

Catch only recoverable Valkey errors.

except Exception converts every failure into False and reopens the shared connection. It also catches local TypeError and AttributeError defects. Those defects then look like a Redis outage.

In Valkey 6.0.2, TimeoutError, ConnectionError, and ResponseError derive from valkey.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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d0d1ab and dc7f391.

📒 Files selected for processing (2)
  • api/ragflow_server.py
  • rag/utils/redis_conn.py

Comment thread rag/utils/redis_conn.py
Comment on lines 551 to +559
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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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 || true

Repository: 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}")
PY

Repository: 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:


🌐 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:


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

codecov Bot commented Aug 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (97f9ae5) to head (dc7f391).
⚠️ Report is 19 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. redis_conn.py – delete_if_equal: Wraps the Lua script call in try/except, reconnects on failure, returns False.
  2. redis_conn.py – RedisDistributedLock: Adds _refresh_lock() to recreate the Lock object with the current Redis connection, called before every acquire() / spin_acquire() attempt.
  3. ragflow_server.py – update_progress: Tracks acquired flag, only releases when lock was actually acquired.

✅ What Looks Good

  • Root cause addressed. The traceback shows TimeoutError in delete_if_equal (called from acquire()). By catching it + reconnecting + refreshing the Lock, subsequent retries use a healthy connection.
  • acquired flag is the right fix. The old finally block unconditionally called release(), 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__() replaces REDIS_CONN.REDIS, the old Lock instance holds a stale connection. Recreating it ensures acquire() uses the fresh client.
  • register_scripts in __open__ re-registers lua_delete_if_equal with the new connection, so the fix is self-consistent.
  • blocking_timeout stored is needed for _refresh_lock() to recreate the Lock with the same parameters.

⚠️ Minor Suggestions

  1. spin_acquire – delete_if_equal called only once before the loop:
    In spin_acquire, delete_if_equal is 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 calling delete_if_equal with 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.

  2. delete_if_equal semantic change: Previously it raised on connection errors; now it returns False. Callers that relied on the exception for error handling might silently not notice the failure. In this codebase, the only callers are acquire() and release(), both of which already handle False correctly (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. ✅

@wangq8
wangq8 merged commit 23b20a0 into infiniflow:main Aug 6, 2026
6 of 9 checks passed
mill413 pushed a commit to mill413/ragflow that referenced this pull request Sep 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant