Skip to content

Fix: upload document might be hung the whole ragflow - #17537

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-upload-document-might-be-hung-the-whole-ragflow
Jul 30, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-upload-document-might-be-hung-the-whole-ragflow

Conversation

@wangq8

@wangq8 wangq8 commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Upload document might be causing the whole RAGFlow hung.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Browser-based PDF conversion and URL crawling now use bounded concurrency and explicit timeouts. Web-document conversion runs in a thread pool with error handling, while Selenium teardown and page-load timeout handling are adjusted.

Changes

Browser fetch control

Layer / File(s) Summary
Browser fetch limits
api/utils/web_utils.py
Environment-configured concurrency and timeout settings introduce semaphore-based browser fetch slots used by PDF conversion.
Selenium conversion timeout handling
api/utils/web_utils.py
Driver navigation handles page-load timeouts with warnings and only quits Selenium when initialization succeeded.
Upload and crawler integration
api/apps/restful_apis/document_api.py, api/db/services/file_service.py
Web-document PDF conversion runs through the thread pool with error results on failure; URL crawling uses a browser slot and an explicit timeout.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant UploadAPI
  participant ThreadPool
  participant html2pdf
  participant BrowserSlot
  participant AsyncWebCrawler
  UploadAPI->>ThreadPool: offload html2pdf(url)
  ThreadPool->>html2pdf: convert URL to PDF
  html2pdf->>BrowserSlot: acquire bounded slot
  BrowserSlot-->>html2pdf: grant slot or timeout
  UploadAPI->>BrowserSlot: acquire crawler slot
  BrowserSlot->>AsyncWebCrawler: run with explicit timeout
  AsyncWebCrawler-->>UploadAPI: return HTML or PDF payload
Loading

Suggested reviewers: jinhai-cn, buua436

Poem

A rabbit guards the browser gate,
While PDF pages patiently wait.
Slots bloom, timeouts softly chime,
Crawlers hop in bounded time.
Failed conversions leave a note—
Then safely close each browser boat.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description is too vague and lacks the summary detail and background context expected by the template. Expand the Summary with the issue context, affected upload flow, and the specific fix introduced by this PR.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: preventing document uploads from hanging the RAGFlow system.
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.

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 marked this pull request as ready for review July 30, 2026 02:38
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 30, 2026
@wangq8 wangq8 added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 30, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 30, 2026
@wangq8 wangq8 added ci Continue Integration and removed ci Continue Integration labels Jul 30, 2026

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

Code Review

Summary

This PR addresses a critical issue where browser-based document upload/conversion could hang the entire RAGFlow service. It adds concurrency limiting (via BoundedSemaphore), timeouts on browser operations, and fixes a blocking event-loop issue in the async handler. The overall approach is sound and the changes are well-structured.

Changes Breakdown

File Change Assessment
web_utils.py Added BoundedSemaphore + browser_fetch_slot() context manager, Selenium timeouts, driver cleanup fix Good
file_service.py Wrapped crawl4ai block in browser_fetch_slot(), added asyncio.wait_for() timeout Good
document_api.py Changed html2pdf(url) to await thread_pool_exec(html2pdf, url) Good

Positive Items

  • Event loop fix: html2pdf is a sync function using Selenium. Running it directly in an async handler (_upload_web_document) blocks the event loop. Moving it to thread_pool_exec is exactly the right fix.
  • Driver cleanup fix: Initializing driver = None and guarding driver.quit() with if driver: prevents UnboundLocalError when ChromeDriverManager().install() or webdriver.Chrome() raises.
  • Configurable limits: All three constants (RAGFLOW_BROWSER_FETCH_CONCURRENCY, RAGFLOW_BROWSER_FETCH_ACQUIRE_TIMEOUT, RAGFLOW_BROWSER_FETCH_TIMEOUT) are env-configurable with sensible defaults (2, 5s, 60s).
  • BoundedSemaphore: Using BoundedSemaphore (not Semaphore) adds a safety check — raises ValueError if released more than acquired, catching bugs.

Concerns

1. asyncio.wait_for cancellation may leak browser processes

In file_service.py, asyncio.wait_for(crawler.arun(...), timeout=BROWSER_FETCH_TIMEOUT) will raise asyncio.TimeoutError which propagates out of the async with AsyncWebCrawler block. While __aexit__ should still run, crawl4ai has known edge cases where the underlying Chromium process is not properly terminated on task cancellation. Consider adding a cancellation handler or at least logging the timeout.

2. BrowserFetchBusy exception not caught at call site

In document_api.py:522, when thread_pool_exec(html2pdf, url) raises BrowserFetchBusy (semaphore acquisition timed out), there is no handler — it becomes a generic 500 error. Consider catching it and returning a user-friendly response, e.g. "Server is busy processing other documents. Please retry later."

3. Missing logging on timeout and busy conditions

Neither path logs when browser operations time out or when the semaphore is exhausted. This makes production debugging difficult. Consider adding logging.warning() calls.

Nit

  • BROWSER_FETCH_TIMEOUT is shared between Selenium page load and crawl4ai arun, which have quite different performance profiles. Consider separate env vars for each path if tuning needs diverge.

Verdict

The fixes are correct and address the root cause (unbounded browser instances + blocking event loop). The concerns above are about graceful error handling and resource cleanup in edge cases — they do not block merging but would improve robustness. LGTM with minor suggestions.

@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: 2

🧹 Nitpick comments (3)
api/utils/web_utils.py (2)

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

Add logging to the new slot-acquisition flow.

Slot exhaustion is invisible today: no log when acquisition blocks or fails, so a saturated browser pool is indistinguishable from a slow upstream.

♻️ Log busy rejections
 `@contextmanager`
 def browser_fetch_slot(timeout: float = BROWSER_FETCH_ACQUIRE_TIMEOUT):
     if not _BROWSER_FETCH_SEMAPHORE.acquire(timeout=timeout):
+        logging.warning("Browser fetch slot unavailable after %ss (concurrency=%s)", timeout, BROWSER_FETCH_CONCURRENCY)
         raise BrowserFetchBusy("Too many concurrent browser fetch requests")
     try:
         yield
     finally:
         _BROWSER_FETCH_SEMAPHORE.release()

As per coding guidelines: "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/utils/web_utils.py` around lines 54 - 61, Add logging to
browser_fetch_slot around _BROWSER_FETCH_SEMAPHORE.acquire: record when slot
acquisition fails and BrowserFetchBusy is raised, and log the relevant
acquisition flow without changing the timeout or release behavior.

Source: Coding guidelines


44-46: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Malformed env values crash module import.

int()/float() on the env vars run at import time; a typo in RAGFLOW_BROWSER_FETCH_TIMEOUT takes down the whole API rather than degrading to the default.

♻️ Fall back to defaults on parse failure
+def _env_number(name: str, default: float, cast=float, minimum=None):
+    raw = os.getenv(name)
+    if raw is None:
+        return default
+    try:
+        value = cast(raw)
+    except ValueError:
+        logging.warning("Invalid %s=%r, falling back to %s", name, raw, default)
+        return default
+    return max(minimum, value) if minimum is not None else value
+
+
-BROWSER_FETCH_CONCURRENCY = max(1, int(os.getenv("RAGFLOW_BROWSER_FETCH_CONCURRENCY", "2")))
-BROWSER_FETCH_ACQUIRE_TIMEOUT = float(os.getenv("RAGFLOW_BROWSER_FETCH_ACQUIRE_TIMEOUT", "5"))
-BROWSER_FETCH_TIMEOUT = float(os.getenv("RAGFLOW_BROWSER_FETCH_TIMEOUT", "60"))
+BROWSER_FETCH_CONCURRENCY = _env_number("RAGFLOW_BROWSER_FETCH_CONCURRENCY", 2, int, 1)
+BROWSER_FETCH_ACQUIRE_TIMEOUT = _env_number("RAGFLOW_BROWSER_FETCH_ACQUIRE_TIMEOUT", 5.0)
+BROWSER_FETCH_TIMEOUT = _env_number("RAGFLOW_BROWSER_FETCH_TIMEOUT", 60.0)
🤖 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/utils/web_utils.py` around lines 44 - 46, Update the browser fetch
configuration initialization for BROWSER_FETCH_CONCURRENCY,
BROWSER_FETCH_ACQUIRE_TIMEOUT, and BROWSER_FETCH_TIMEOUT to safely handle
invalid environment values without raising during module import. Reuse the
intended defaults (including the existing minimum-concurrency behavior) whenever
parsing fails, while preserving valid parsed values.
api/db/services/file_service.py (1)

769-803: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Slot is held across the non-browser redirect resolution.

The redirect pre-resolution loop uses plain requests, no browser, yet it runs inside browser_fetch_slot(). With up to 10 hops at timeout=10 each, a single caller can pin one of only BROWSER_FETCH_CONCURRENCY (default 2) slots for ~100s before the browser even starts — and the acquire timeout is 5s, so concurrent callers get BrowserFetchBusy while no browser is actually running.

Acquire the slot only around the crawl.

♻️ Narrow the slot to the browser phase
-            with browser_fetch_slot():
-                # Pre-resolve the full redirect chain so that AsyncWebCrawler never
+            # Pre-resolve the full redirect chain so that AsyncWebCrawler never
...
-                page = asyncio.run(adownload())
+            with browser_fetch_slot():
+                page = asyncio.run(adownload())

(De-indent the redirect-resolution block accordingly; keep adownload definition outside the slot.)

🤖 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/db/services/file_service.py` around lines 769 - 803, Move the redirect
pre-resolution loop and its URL validation/host_pins setup outside the
browser_fetch_slot() context, while keeping the resulting adownload definition
outside the slot as requested. Acquire browser_fetch_slot() only around the
AsyncWebCrawler execution so non-browser requests do not consume browser
concurrency slots.
🤖 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 `@api/apps/restful_apis/document_api.py`:
- Line 522: Update the conversion flow around html2pdf to import and catch
BrowserFetchBusy, mapping slot exhaustion to the endpoint’s retryable “server
busy” response instead of allowing an unhandled exception/500; preserve existing
handling for genuine conversion failures.

In `@api/utils/web_utils.py`:
- Around line 121-131: Update the surrounding flow containing driver creation,
timeout configuration, and __send_devtools so it uses one encompassing
try/finally that always quits a successfully created driver, including
unexpected setup failures. Before invoking __send_devtools, explicitly verify
that driver was created and fail fast with a meaningful error when it remains
None; do not swallow driver-construction TimeoutException into the send path.

---

Nitpick comments:
In `@api/db/services/file_service.py`:
- Around line 769-803: Move the redirect pre-resolution loop and its URL
validation/host_pins setup outside the browser_fetch_slot() context, while
keeping the resulting adownload definition outside the slot as requested.
Acquire browser_fetch_slot() only around the AsyncWebCrawler execution so
non-browser requests do not consume browser concurrency slots.

In `@api/utils/web_utils.py`:
- Around line 54-61: Add logging to browser_fetch_slot around
_BROWSER_FETCH_SEMAPHORE.acquire: record when slot acquisition fails and
BrowserFetchBusy is raised, and log the relevant acquisition flow without
changing the timeout or release behavior.
- Around line 44-46: Update the browser fetch configuration initialization for
BROWSER_FETCH_CONCURRENCY, BROWSER_FETCH_ACQUIRE_TIMEOUT, and
BROWSER_FETCH_TIMEOUT to safely handle invalid environment values without
raising during module import. Reuse the intended defaults (including the
existing minimum-concurrency behavior) whenever parsing fails, while preserving
valid parsed values.
🪄 Autofix (Beta)

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: 1280e55e-f441-4805-a440-50cbcf4226b6

📥 Commits

Reviewing files that changed from the base of the PR and between dcaa62f and 7b72f2e.

📒 Files selected for processing (3)
  • api/apps/restful_apis/document_api.py
  • api/db/services/file_service.py
  • api/utils/web_utils.py

Comment thread api/apps/restful_apis/document_api.py Outdated
return get_error_data_result(message="The URL format is invalid", code=RetCode.ARGUMENT_ERROR)

blob = html2pdf(url)
blob = await thread_pool_exec(html2pdf, url)

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

Offloading is right, but the new BrowserFetchBusy path is unhandled.

html2pdf now raises BrowserFetchBusy once the bounded slots are saturated (api/utils/web_utils.py Lines 54-57). With no handler here, that surfaces as an unhandled exception/500 rather than a retryable "server busy" response, so clients can't distinguish overload from a genuine conversion failure.

🐛 Map slot exhaustion to a retryable error
-    blob = await thread_pool_exec(html2pdf, url)
+    try:
+        blob = await thread_pool_exec(html2pdf, url)
+    except BrowserFetchBusy as e:
+        logging.warning("Browser fetch slots exhausted for %s", dataset_id)
+        return get_error_data_result(message=str(e), code=RetCode.SERVER_ERROR)
     if not blob:
         return server_error_response(ValueError("Download failure."))

Requires importing BrowserFetchBusy from api.utils.web_utils.

🤖 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/apps/restful_apis/document_api.py` at line 522, Update the conversion
flow around html2pdf to import and catch BrowserFetchBusy, mapping slot
exhaustion to the endpoint’s retryable “server busy” response instead of
allowing an unhandled exception/500; preserve existing handling for genuine
conversion failures.

Comment thread api/utils/web_utils.py Outdated
Comment on lines +121 to +131
driver = None
try:
if install_driver:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=webdriver_options)
else:
driver = webdriver.Chrome(options=webdriver_options)

driver.get(path)
driver.set_page_load_timeout(BROWSER_FETCH_TIMEOUT)
driver.set_script_timeout(BROWSER_FETCH_TIMEOUT)
driver.get(path)

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 | 🔴 Critical | ⚡ Quick win

Driver can leak, or be None when __send_devtools runs.

Two gaps in the new control flow:

  1. Driver creation now sits inside the first try, whose only handler is except TimeoutException: pass. If webdriver.Chrome(...) succeeds but set_page_load_timeout/set_script_timeout raises anything else, the exception escapes before the second try at Line 137, so the finally at Lines 148-149 never runs and the Chrome process leaks — the exact resource exhaustion this PR is trying to prevent.
  2. Conversely, if the failure is a TimeoutException during driver construction, it's swallowed and driver stays None; __send_devtools(driver, ...) then dereferences driver.session_id and raises AttributeError instead of a meaningful error.

Wrap the whole body in one try/finally and fail fast when the driver was never created.

🐛 Single try/finally with an explicit driver guard
     driver = None
-    try:
-        if install_driver:
-            service = Service(ChromeDriverManager().install())
-            driver = webdriver.Chrome(service=service, options=webdriver_options)
-        else:
-            driver = webdriver.Chrome(options=webdriver_options)
-
-        driver.set_page_load_timeout(BROWSER_FETCH_TIMEOUT)
-        driver.set_script_timeout(BROWSER_FETCH_TIMEOUT)
-        driver.get(path)
-
-        WebDriverWait(driver, timeout).until(staleness_of(driver.find_element(by=By.TAG_NAME, value="html")))
-    except TimeoutException:
-        pass
-
     try:
+        if install_driver:
+            service = Service(ChromeDriverManager().install())
+            driver = webdriver.Chrome(service=service, options=webdriver_options)
+        else:
+            driver = webdriver.Chrome(options=webdriver_options)
+
+        driver.set_page_load_timeout(BROWSER_FETCH_TIMEOUT)
+        driver.set_script_timeout(BROWSER_FETCH_TIMEOUT)
+        try:
+            driver.get(path)
+            WebDriverWait(driver, timeout).until(staleness_of(driver.find_element(by=By.TAG_NAME, value="html")))
+        except TimeoutException:
+            logging.warning("Timed out loading %s; printing current page state", path)
+
         calculated_print_options = {
             "landscape": False,
             "displayHeaderFooter": False,
             "printBackground": True,
             "preferCSSPageSize": True,
         }
         calculated_print_options.update(print_options)
         result = __send_devtools(driver, "Page.printToPDF", calculated_print_options)
         return base64.b64decode(result["data"])
     finally:
-        if driver:
+        if driver is not None:
             driver.quit()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
driver = None
try:
if install_driver:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=webdriver_options)
else:
driver = webdriver.Chrome(options=webdriver_options)
driver.get(path)
driver.set_page_load_timeout(BROWSER_FETCH_TIMEOUT)
driver.set_script_timeout(BROWSER_FETCH_TIMEOUT)
driver.get(path)
driver = None
try:
if install_driver:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=webdriver_options)
else:
driver = webdriver.Chrome(options=webdriver_options)
driver.set_page_load_timeout(BROWSER_FETCH_TIMEOUT)
driver.set_script_timeout(BROWSER_FETCH_TIMEOUT)
try:
driver.get(path)
WebDriverWait(driver, timeout).until(staleness_of(driver.find_element(by=By.TAG_NAME, value="html")))
except TimeoutException:
logging.warning("Timed out loading %s; printing current page state", path)
calculated_print_options = {
"landscape": False,
"displayHeaderFooter": False,
"printBackground": True,
"preferCSSPageSize": True,
}
calculated_print_options.update(print_options)
result = __send_devtools(driver, "Page.printToPDF", calculated_print_options)
return base64.b64decode(result["data"])
finally:
if driver is not None:
driver.quit()
🤖 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/utils/web_utils.py` around lines 121 - 131, Update the surrounding flow
containing driver creation, timeout configuration, and __send_devtools so it
uses one encompassing try/finally that always quits a successfully created
driver, including unexpected setup failures. Before invoking __send_devtools,
explicitly verify that driver was created and fail fast with a meaningful error
when it remains None; do not swallow driver-construction TimeoutException into
the send path.

@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (dcaa62f) to head (7ef58db).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17537   +/-   ##
=======================================
  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.

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
api/utils/web_utils.py (2)

122-131: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Bound browser lifecycle from driver acquisition through quit.

ChromeDriverManager().install() and webdriver.Chrome(...) run after acquiring browser_fetch_slot() but before set_page_load_timeout() / driver.quit(). If driver download/selection or Chrome startup never returns, the worker can hold a browser slot indefinitely instead of failing within a configured startup deadline.

🤖 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/utils/web_utils.py` around lines 122 - 131, Extend the timeout-bounded
browser lifecycle around driver acquisition in the existing try flow: ensure
both ChromeDriverManager().install() and webdriver.Chrome(...) execute under the
configured startup deadline after browser_fetch_slot() is acquired. On timeout
or startup failure, release the slot and perform any available driver cleanup
before propagating the failure, while preserving the existing timeout setup and
driver.quit() behavior.

94-95: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Move browser fetch throttling outside the per-request executor.

thread_pool_exec(html2pdf, url) submits html2pdf to a fresh single-worker ThreadPoolExecutor(max_workers=1), but html2pdf() still tries to acquire browser_fetch_slot() in that worker. When browser fetches are saturated, requests block inside fresh request-scoped threads instead of a shared bounded capacity; acquire a global concurrency token before calling thread_pool_exec, or use a shared bounded executor/async semaphore for browser fetches.

🤖 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/utils/web_utils.py` around lines 94 - 95, Move browser fetch throttling
out of the per-request executor by acquiring the shared browser-fetch capacity
before invoking thread_pool_exec(html2pdf, url). Remove the browser_fetch_slot()
acquisition from html2pdf’s worker-side path while preserving token release
after the request completes, so saturation is governed by shared bounded
capacity rather than fresh single-worker executors.
🤖 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 `@api/apps/restful_apis/document_api.py`:
- Around line 522-526: Update the error handling around the html2pdf call in the
document API: catch only the known conversion and busy/driver exceptions, log
them with logging.exception() including dataset context, and return
get_error_data_result() with a stable generic server-error message rather than
str(e). Remove the broad Exception catch so unexpected failures are not exposed
through the API response.

In `@api/utils/web_utils.py`:
- Around line 133-137: Update the TimeoutException warning in the driver-loading
flow around driver.get and WebDriverWait to avoid logging the raw user-supplied
path. Sanitize path before logging, retaining only a redacted host/path or use
an available request identifier, while preserving the timeout warning behavior.

---

Outside diff comments:
In `@api/utils/web_utils.py`:
- Around line 122-131: Extend the timeout-bounded browser lifecycle around
driver acquisition in the existing try flow: ensure both
ChromeDriverManager().install() and webdriver.Chrome(...) execute under the
configured startup deadline after browser_fetch_slot() is acquired. On timeout
or startup failure, release the slot and perform any available driver cleanup
before propagating the failure, while preserving the existing timeout setup and
driver.quit() behavior.
- Around line 94-95: Move browser fetch throttling out of the per-request
executor by acquiring the shared browser-fetch capacity before invoking
thread_pool_exec(html2pdf, url). Remove the browser_fetch_slot() acquisition
from html2pdf’s worker-side path while preserving token release after the
request completes, so saturation is governed by shared bounded capacity rather
than fresh single-worker executors.
🪄 Autofix (Beta)

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: 63385285-9985-4bd2-af79-e20247410995

📥 Commits

Reviewing files that changed from the base of the PR and between 7b72f2e and 7ef58db.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • api/utils/web_utils.py

Comment on lines +522 to +526
try:
blob = await thread_pool_exec(html2pdf, url)
except Exception as e:
logging.warning("html2pdf failed for %s, %s", dataset_id, str(e))
return get_error_data_result(message=str(e), code=RetCode.SERVER_ERROR)

@coderabbitai coderabbitai Bot Jul 30, 2026 •

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | rg '(^|/)document_api\.py$|restful_apis' || true

echo "== relevant lines =="
sed -n '500,540p' api/apps/restful_apis/document_api.py

echo "== get_error_data_result definitions/usages =="
rg -n "def get_error_data_result|get_error_data_result\(" api -S

echo "== html2pdf call sites / relevant exception imports =="
rg -n "thread_pool_exec|html2pdf|get_error_data_result|logging\.(warning|exception|error)\(" api/apps/restful_apis/document_api.py -S

Repository: infiniflow/ragflow

Length of output: 49974


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== get_error_data_result definition =="
sed -n '280,325p' api/utils/api_utils.py

echo "== html2pdf definition and dependencies =="
fd -a 'web_utils.py|__init__\.py|thread_pool_utils.py|misc_utils.py' api . | sed 's#^\./##' | rg 'html2pdf|web_utils|thread_pool_exec|misc_utils' || true
sed -n '1,220p' api/utils/web_utils.py

echo "== thread_pool_exec definition =="
rg -n "def thread_pool_exec|thread_pool_exec" api/common api/scheduler -S || true

Repository: infiniflow/ragflow

Length of output: 9151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package files for dependency context =="
for f in pyproject.toml requirements.txt requirements-dev.txt setup.py setup.cfg Pipfile poetry.lock uv.lock; do
  [ -f "$f" ] && echo "--- $f" && rg -n "playwright|selenium|webdriver|pytest" "$f" -S || true
done
fd -a 'requirements.*|pyproject.toml' . | head -50

Repository: infiniflow/ragflow

Length of output: 9623


🌐 Web query:

Python selenium WebDriver exception string message contains stack trace URL?

💡 Result:

The message component of a Python Selenium WebDriverException does not inherently contain a URL [1][2]. When a Selenium WebDriver exception occurs, the exception object is composed of several distinct attributes, including a message (msg), a screenshot (screen, if available), and a stack trace (stacktrace) [1][3]. The string representation (str) of the exception specifically concatenates these fields into the final error output: 1. Message: The main error message text [1][2]. 2. Screenshot: A reference indicating if a screenshot is available [1][2]. 3. Stacktrace: The remote stack trace information returned by the browser driver [1][4][2]. While the standard message itself does not contain a URL, some specific exceptions, such as NoSuchDriverException, explicitly append a documentation URL to their message string during initialization to help users diagnose common setup issues [1]. Additionally, the stack trace field may contain internal driver-specific debugging information (often labeled as "Backtrace"), which can be quite verbose, but this is distinct from the exception message string [4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== common/misc_utils.py relevant implementation =="
sed -n '1,220p' common/misc_utils.py

echo "== behavioral probe of exception string contents =="
python3 - <<'PY'
from selenium.common.exceptions import TimeoutException
e = TimeoutException("load timed out", "", driver_url="http://127.0.0.1:4444/session/abc", stacktrace="backtrace")
print("str:")
print(e)
print("attrs include path/driver fields:")
for attr in ("msg", "driver_url", "stacktrace", "screen"):
    print(f"{attr}: {(getattr(e, attr, None) or '').splitlines()[0]!r}")
PY

Repository: infiniflow/ragflow

Length of output: 8501


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== rest of common/misc_utils.py =="
sed -n '220,340p' common/misc_utils.py

echo "== inspect driver/command_executor internals in source packages if available =="
python3 - <<'PY'
import importlib.util
for name in ("selenium.webdriver.remote.webdriver", "selenium.webdriver.remote.remote_connection"):
    spec = importlib.util.find_spec(name)
    print(f"{name}: {spec.origin if spec else None}")
PY

echo "== search for explicit webdriver Exception class message construction =="
rg -n "class WebDriver|def __init__\\(self, msg|driver_url|stacktrace|stringification" -S --glob '*.py' .

Repository: infiniflow/ragflow

Length of output: 2032


🌐 Web query:

selenium python WebDriverException __str__ stacktrace screen source

💡 Result:

In Selenium for Python, WebDriverException is the base class for all WebDriver-related exceptions [1][2]. It includes optional attributes designed to capture diagnostic information provided by the remote WebDriver [1][2]. Attributes: - msg: The error message string associated with the exception [1][2]. - screen: A string, if available, representing a base64-encoded screenshot of the browser at the time the exception occurred [1][3]. - stacktrace: A sequence of strings representing the server-side stack trace associated with the error [1][2]. The str method of WebDriverException is implemented to format these attributes into a readable string [1][2]. It explicitly includes the error message, indicates if a screenshot is available, and, if the stack trace is present, formats and appends the lines of the stack trace to the exception message [1][2]. When an error occurs, the ErrorHandler in Selenium processes the response from the remote server [3]. If the server provides "screen" or "stackTrace" / "stacktrace" data in its response, this information is extracted and passed to the exception instance during initialization [3]. The stack trace, if provided as a structured list of frames, is converted into a list of formatted strings by the ErrorHandler before being assigned to the exception [3]. For developers, accessing these attributes directly from an caught exception instance (e.g., e.screen or e.stacktrace) allows for programmatic retrieval of the diagnostic data [1][2].

Citations:


Log the error and return a safe generic response.

get_error_data_result() returns message directly, so catching all Selenium/driver failures here can leak driver stack traces/screenshots through the API. Log with logging.exception(), convert to a stable internal error message, and catch known conversion/busy exceptions explicitly instead of relying on a broad Exception catch.

🧰 Tools
🪛 Ruff (0.16.0)

[warning] 524-524: Do not catch blind exception: Exception

(BLE001)

🤖 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/apps/restful_apis/document_api.py` around lines 522 - 526, Update the
error handling around the html2pdf call in the document API: catch only the
known conversion and busy/driver exceptions, log them with logging.exception()
including dataset context, and return get_error_data_result() with a stable
generic server-error message rather than str(e). Remove the broad Exception
catch so unexpected failures are not exposed through the API response.

Source: Linters/SAST tools

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.

this is original code

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.

@wangq8, understood. The direct html2pdf(url) call is original; my finding applies only to the newly added except Exception branch, specifically returning str(e) to the client. That new path can expose driver/conversion internals, so it should use a stable generic error message while logging the full exception server-side.

You are interacting with an AI system.

Comment thread api/utils/web_utils.py
Comment on lines +133 to +137
try:
driver.get(path)
WebDriverWait(driver, timeout).until(staleness_of(driver.find_element(by=By.TAG_NAME, value="html")))
except TimeoutException:
logging.warning("Timed out loading %s; printing current page state", path)

@coderabbitai coderabbitai Bot Jul 30, 2026 •

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Redact path before logging it.

path originates from the user-supplied upload URL in api/apps/restful_apis/document_api.py Lines 508-523. Logging it verbatim can persist query credentials, tokens, or other sensitive data. Log only a redacted host/path or a request identifier.

🤖 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/utils/web_utils.py` around lines 133 - 137, Update the TimeoutException
warning in the driver-loading flow around driver.get and WebDriverWait to avoid
logging the raw user-supplied path. Sanitize path before logging, retaining only
a redacted host/path or use an available request identifier, while preserving
the timeout warning behavior.

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.

this is original code

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.

@wangq8, agreed that path itself and its use in driver.get(path) are original code. The concern is specifically the new timeout warning: previously TimeoutException was silently ignored, while this PR now logs the raw user-supplied URL.

Could we redact the query/fragment before logging so tokens or credentials are not persisted in logs?

You are interacting with an AI system.

@wangq8
wangq8 merged commit 6e0e495 into infiniflow:main Jul 30, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant