Skip to content

Fix: display timeout error when checking model accessibility - #17080

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
Lynn-Inf:fix/display-timeout
Jul 20, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
Lynn-Inf:fix/display-timeout

Conversation

@Lynn-Inf

Copy link
Copy Markdown
Contributor

Summary

As title.

@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 20, 2026
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

verify_api_key now centralizes timeout and exception handling, verifies supported model modalities through a shared flow, records per-model outcomes, and determines overall success from passed modalities.

Changes

Provider verification flow

Layer / File(s) Summary
Centralized verification runtime
api/apps/services/provider_api_service.py
Adds _run_verification for shared timeout and exception handling and replaces modality-specific verification state initialization.
Unified modality verification
api/apps/services/provider_api_service.py
Uses shared verification for embedding, chat, rerank, OCR, TTS, vision, and ASR models, records results, tracks passed modalities, and computes overall success.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested reviewers: wangq8, b uua436

Poem

A rabbit checks each model in line,
With timeout bells that neatly chime.
Embeddings, chat, and vision race,
Passed types gather in one place.
“Success!” I twitch my whiskers bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description is too vague; it repeats the title and omits the required summary details and context. Expand the Summary with the problem, the approach taken, and any behavior changes or impact for reviewers.
✅ 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 matches the main change: improving timeout/error reporting during model accessibility checks.

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.

@Lynn-Inf Lynn-Inf changed the title Fix: display timeout error when check model accessable Fix: display timeout error when checking model accessibility Jul 20, 2026
@Lynn-Inf
Lynn-Inf requested a review from wangq8 July 20, 2026 03:06
@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jul 20, 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: 2

🤖 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/services/provider_api_service.py`:
- Around line 609-611: Update the asyncio.CancelledError handler in
verify_api_key to log if desired and re-raise the cancellation instead of
returning a failure tuple. Keep the existing result-tuple handling for
TimeoutError and generic exceptions unchanged.
- Around line 700-710: Update the embedding verification block around
EmbeddingModel and _run_verification to unpack result as embeddings and
used_tokens, then fail when embeddings[0] is empty or used_tokens equals zero.
Preserve the existing failure status, message, and continue behavior for invalid
results.
🪄 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

Run ID: bdf9f7e1-a856-4e73-a166-7af8a4e32fba

📥 Commits

Reviewing files that changed from the base of the PR and between 0f94e05 and 6127553.

📒 Files selected for processing (1)
  • api/apps/services/provider_api_service.py

Comment on lines +609 to +611
except asyncio.CancelledError:
logging.exception("Verification cancelled for %s", label)
return False, f"\n{label} verification aborted."

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

Don't swallow asyncio.CancelledError; re-raise it.

Catching CancelledError and returning (False, msg) breaks cooperative cancellation. When the surrounding verify_api_key task is cancelled (e.g. client disconnect / server shutdown), this converts the cancellation into a normal "failure" result and prevents propagation, so the outer task never actually unwinds. CancelledError should be logged (if at all) and re-raised; only TimeoutError and generic exceptions should be turned into result tuples.

🔧 Proposed fix
     except asyncio.CancelledError:
-        logging.exception("Verification cancelled for %s", label)
-        return False, f"\n{label} verification aborted."
+        logging.warning("Verification cancelled for %s", label)
+        raise
📝 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
except asyncio.CancelledError:
logging.exception("Verification cancelled for %s", label)
return False, f"\n{label} verification aborted."
except asyncio.CancelledError:
logging.warning("Verification cancelled for %s", label)
raise
🤖 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/services/provider_api_service.py` around lines 609 - 611, Update the
asyncio.CancelledError handler in verify_api_key to log if desired and re-raise
the cancellation instead of returning a failure tuple. Keep the existing
result-tuple handling for TimeoutError and generic exceptions unchanged.

Comment on lines +700 to +710
mdl = EmbeddingModel[provider_name](api_key_str, llm["llm_name"], base_url=base_url)
label = f"embedding model({llm['llm_name']})"
ok, result = await _run_verification(label, asyncio.to_thread(mdl.encode, ["Test if the api key is available"]), timeout_seconds)
if not ok:
msg += result
model_verify_result[llm["llm_name"]] = ModelVerifyStatusEnum.FAIL.value
continue
if len(result[0]) == 0:
msg += f"\nFail to access {label}."
model_verify_result[llm["llm_name"]] = ModelVerifyStatusEnum.FAIL.value
continue

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP -C3 '\bdef encode\s*\(' --type=py
rg -nP -C4 '\.encode\(\[.*Test if the api key' --type=py

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file and nearby code.
ast-grep outline api/apps/services/provider_api_service.py --view expanded || true

# Find encode definitions/usages more broadly.
rg -n -C 3 "def encode\s*\(" api -g '*.py' || true
rg -n -C 4 "\.encode\(\[" api -g '*.py' || true

# Show the target section with line numbers.
sed -n '680,725p' api/apps/services/provider_api_service.py
sed -n '740,770p' api/apps/services/provider_api_service.py

Repository: infiniflow/ragflow

Length of output: 10917


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path('api/apps/services/provider_api_service.py')
text = p.read_text()
for start in [680, 740]:
    print(f"\n--- {p}:{start}-"+str(start+45)+" ---")
    lines = text.splitlines()
    for i in range(start-1, min(len(lines), start+45)):
        print(f"{i+1:4d}: {lines[i]}")
PY

echo
echo '--- encode definitions/usages ---'
rg -n -C 3 'class .*EmbeddingModel|def encode\s*\(' api -g '*.py' || true
rg -n -C 3 'used_tokens|token_count|arr, tc|encode\(\[' api -g '*.py' || true

Repository: infiniflow/ragflow

Length of output: 34984


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the model implementation and call sites.
git ls-files | rg 'embedding|rerank|provider_api_service|provider.*service|model' || true

# Broader search for the verification label and result handling.
rg -n -C 3 'ModelVerifyStatusEnum\.FAIL|_run_verification|used_tokens|encode\(' api -g '*.py' || true

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '88,112p' api/apps/llm_app.py
sed -n '320,342p' api/apps/llm_app.py
sed -n '360,378p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 3624


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path('api/apps/llm_app.py')
lines = p.read_text().splitlines()
for start, end in [(92, 110), (324, 336), (364, 374)]:
    print(f"\n--- {p}:{start}-{end} ---")
    for i in range(start-1, end):
        print(f"{i+1:4d}: {lines[i]}")
PY

Repository: infiniflow/ragflow

Length of output: 2787


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '92,110p' api/apps/llm_app.py
sed -n '324,336p' api/apps/llm_app.py
sed -n '364,374p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 2419


Fix the embedding availability guard. mdl.encode(...) returns (embeddings, used_tokens), and len(result[0]) only checks how many embeddings came back. With a single probe text, an empty embedding vector can still pass this branch. Unpack the tuple and reject len(embeddings[0]) == 0 or used_tokens == 0 here.

🤖 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/services/provider_api_service.py` around lines 700 - 710, Update the
embedding verification block around EmbeddingModel and _run_verification to
unpack result as embeddings and used_tokens, then fail when embeddings[0] is
empty or used_tokens equals zero. Preserve the existing failure status, message,
and continue behavior for invalid results.

Source: Linters/SAST tools

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review: PR #17080 – Fix: display timeout error when checking model accessibility

Overall: A solid, well-structured refactoring that significantly reduces code duplication in verify_api_key. No regressions identified.

✅ Positive

1. _run_verification helper – Extracting the try/except/timeout boilerplate into a single helper is the right call. Every model-type check now has uniform error handling:

  • Timeout → "Timeout accessing {label}."
  • CancelledError → "{label} verification aborted." (previously unhandled!)
  • Generic exception → "Fail to access {label}.{str(e)}"

2. passed_types set replaces individual booleans – Much cleaner than the chat_passed, embd_passed, etc. flags. The any_passed/break logic is preserved with the same semantic.

3. assert → proper if-statement – Old code used assert provider_name in EmbeddingModel etc., which could be silently skipped with -O. The new code provides explicit error messages. Good defensive practice.

4. Iterating all model types per LLM – Old code elif-chained to the first matching type. New code tries all types if the first one fails. This is an improvement — a model that advertises both chat and vision types, for example, now gets a verification attempt on each type.

🔍 Behavior verification

  • OCR/ASR check_available() return unpacking: Correct. _run_verification returns (True, (ok, reason)) → ok2, reason = result.
  • VISION test_image reference: Old image_data = test_image; await ...(mdl.describe, image_data) ≡ new await ...(mdl.describe, test_image). Equivalent.
  • Success → msg = "" + break: Preserved from the old behavior.
  • model_verify_result overwrite per llm: Functionally identical — each llm gets a single SUCCESS/FAIL entry.

⚠️ Minor

  • The error message format has changed slightly (e.g., no more "using this api key" suffix). Error messages are now consistent across types but may differ from what downstream consumers expect.
  • _run_verification returns a tuple (bool, Any) — callers unpack result differently per type (some expect arr, tc, some a bool, some a tuple). This is the same fragility as the old code but now centralized.

Verdict: Well done. No blockers, ready to merge.

@codecov

codecov Bot commented Jul 20, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17080   +/-   ##
=======================================
  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 merged commit af3813b into infiniflow:main Jul 20, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. 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.

2 participants