Repository navigation
Conversation
📝 WalkthroughWalkthroughBrowser-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. ChangesBrowser fetch control
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
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ 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 |
wangq8
left a comment
There was a problem hiding this comment.
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:
html2pdfis a sync function using Selenium. Running it directly in an async handler (_upload_web_document) blocks the event loop. Moving it tothread_pool_execis exactly the right fix. - Driver cleanup fix: Initializing
driver = Noneand guardingdriver.quit()withif driver:preventsUnboundLocalErrorwhenChromeDriverManager().install()orwebdriver.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: UsingBoundedSemaphore(notSemaphore) adds a safety check — raisesValueErrorif 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_TIMEOUTis shared between Selenium page load and crawl4aiarun, 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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
api/utils/web_utils.py (2)
54-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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 winMalformed env values crash module import.
int()/float()on the env vars run at import time; a typo inRAGFLOW_BROWSER_FETCH_TIMEOUTtakes 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 winSlot is held across the non-browser redirect resolution.
The redirect pre-resolution loop uses plain
requests, no browser, yet it runs insidebrowser_fetch_slot(). With up to 10 hops attimeout=10each, a single caller can pin one of onlyBROWSER_FETCH_CONCURRENCY(default 2) slots for ~100s before the browser even starts — and the acquire timeout is 5s, so concurrent callers getBrowserFetchBusywhile 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
adownloaddefinition 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
📒 Files selected for processing (3)
api/apps/restful_apis/document_api.pyapi/db/services/file_service.pyapi/utils/web_utils.py
| 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) |
There was a problem hiding this comment.
🩺 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.
| 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) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Driver can leak, or be None when __send_devtools runs.
Two gaps in the new control flow:
- Driver creation now sits inside the first
try, whose only handler isexcept TimeoutException: pass. Ifwebdriver.Chrome(...)succeeds butset_page_load_timeout/set_script_timeoutraises anything else, the exception escapes before the secondtryat Line 137, so thefinallyat Lines 148-149 never runs and the Chrome process leaks — the exact resource exhaustion this PR is trying to prevent. - Conversely, if the failure is a
TimeoutExceptionduring driver construction, it's swallowed anddriverstaysNone;__send_devtools(driver, ...)then dereferencesdriver.session_idand raisesAttributeErrorinstead 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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winBound browser lifecycle from driver acquisition through quit.
ChromeDriverManager().install()andwebdriver.Chrome(...)run after acquiringbrowser_fetch_slot()but beforeset_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 liftMove browser fetch throttling outside the per-request executor.
thread_pool_exec(html2pdf, url)submitshtml2pdfto a fresh single-workerThreadPoolExecutor(max_workers=1), buthtml2pdf()still tries to acquirebrowser_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 callingthread_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
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pyapi/utils/web_utils.py
| 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) |
There was a problem hiding this comment.
🔒 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 -SRepository: 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 || trueRepository: 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 -50Repository: 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:
- 1: https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/common/exceptions.html
- 2: https://selenium-python-api-docs.readthedocs.io/en/selenium-4.34.0/_modules/selenium/common/exceptions.html
- 3: https://github.com/SeleniumHQ/selenium/blob/1d05820edabd58c7e4b6afd04e5596404bd1cd7c/py/selenium/common/exceptions.py
- 4: Selenium 4 exceptions produce a Traceback that contains this superfluous 'Backtrace' info. SeleniumHQ/selenium#9977
🏁 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}")
PYRepository: 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:
- 1: https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/common/exceptions.html
- 2: https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/common/exceptions.py
- 3: https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/remote/errorhandler.html
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
There was a problem hiding this comment.
this is original code
There was a problem hiding this comment.
@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.
| 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) |
There was a problem hiding this comment.
🔒 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.
There was a problem hiding this comment.
this is original code
There was a problem hiding this comment.
@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.
Upload document might be causing the whole RAGFlow hung.