Repository navigation
fix: handle missing ES/OpenSearch index in check_embedding (HTTP 500 on empty dataset) - #16650
Conversation
When check_embedding is called on a newly created dataset (before any document has been indexed), Elasticsearch raises NotFoundError because the tenant chunk index does not yet exist. sample_random_chunks_with_vectors had no try/except around the initial existence-probing search, so the exception propagated all the way up to the route handler and became an HTTP 500. Fix: catch not_found_exception / index_not_found_exception around the first docStoreConn.search() call and return an empty list, matching the behaviour for an existing-but-empty index. The caller (check_embedding) already handles the empty-sample case by returning (False, "No embedded chunks are available to compare."), so the user-facing response becomes a clear, actionable message instead of a generic 500. Fixes infiniflow#16649
📝 WalkthroughWalkthroughThe ChangesMissing Index Handling
Estimated code review effort: 1 (Trivial) | ~5 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/apps/services/dataset_api_service.py (1)
1150-1159: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winFragile exception matching via
repr(e)string search.Catching bare
Exceptionand pattern-matchingnot_found_exception/index_not_found_exceptionagainstrepr(e)is brittle — it depends on the exact string representation of exceptions from whichever backend (Elasticsearch, OpenSearch, Infinity) is configured, which can change across client library versions. Prefer catching the specific exception types raised by the concrete doc store connector (e.g.,elasticsearch.NotFoundError/opensearchpy.exceptions.NotFoundError) or checking a structured error attribute instead of parsingrepr().♻️ Suggested direction
- try: - res0 = docStoreConn.search(...) - except Exception as e: - if "not_found_exception" in repr(e) or "index_not_found_exception" in repr(e): - logging.info(...) - return [] - raise + try: + res0 = docStoreConn.search(...) + except (NotFoundError, ...) as e: # concrete backend exception types + logging.info(...) + return []🤖 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/dataset_api_service.py` around lines 1150 - 1159, The exception handling in sample_random_chunks_with_vectors is too brittle because it catches bare Exception and inspects repr(e) for not_found_exception/index_not_found_exception. Update this block to catch the concrete not-found exception types raised by the active doc store connector in dataset_api_service.py, or use a structured error attribute instead of string matching, while keeping the existing empty-list fallback for missing indexes. Ensure the logic stays localized to sample_random_chunks_with_vectors and preserves the current logging and return behavior for the expected missing-index case.
🤖 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.
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1150-1159: The exception handling in
sample_random_chunks_with_vectors is too brittle because it catches bare
Exception and inspects repr(e) for
not_found_exception/index_not_found_exception. Update this block to catch the
concrete not-found exception types raised by the active doc store connector in
dataset_api_service.py, or use a structured error attribute instead of string
matching, while keeping the existing empty-list fallback for missing indexes.
Ensure the logic stays localized to sample_random_chunks_with_vectors and
preserves the current logging and return behavior for the expected missing-index
case.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c22a29e2-9e89-4cc5-94de-4430492ebafd
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/apps/services/dataset_api_service.py (1)
1155-1176: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPrefer the existing
index_exist()helper over exception-string matching.The fix correctly prevents the 500, but it detects "index missing" by matching substrings in
repr(e). This is fragile — it depends on the exact wording embedded by the ES/OpenSearch client's exceptionrepr, and could silently stop matching after a client library upgrade or with a different doc-store backend. The same file already has an established, more robust pattern for exactly this check:_compiled_index_or_noneusessettings.docStoreConn.index_exist(index_nm, kb_id). Consider reusing it here for consistency and to avoid coupling to exception message text.Note also
"not_found_exception"is a substring of"index_not_found_exception", so the secondorclause is currently redundant.♻️ Proposed refactor using `index_exist`
index_nm = search.index_name(tenant_id) - try: - res0 = docStoreConn.search( - select_fields=[], - highlight_fields=[], - condition={"kb_id": kb_id, "available_int": 1}, - match_expressions=[], - order_by=OrderByExpr(), - offset=0, - limit=1, - index_names=index_nm, - knowledgebase_ids=[kb_id], - ) - except Exception as e: - if "not_found_exception" in repr(e) or "index_not_found_exception" in repr(e): - logging.info( - "sample_random_chunks_with_vectors: index %s not yet created for tenant %s; " - "returning empty sample set", - index_nm, - tenant_id, - ) - return [] - raise + if not docStoreConn.index_exist(index_nm, kb_id): + logging.info( + "sample_random_chunks_with_vectors: index %s not yet created for tenant %s; " + "returning empty sample set", + index_nm, + tenant_id, + ) + return [] + res0 = docStoreConn.search( + select_fields=[], + highlight_fields=[], + condition={"kb_id": kb_id, "available_int": 1}, + match_expressions=[], + order_by=OrderByExpr(), + offset=0, + limit=1, + index_names=index_nm, + knowledgebase_ids=[kb_id], + )🤖 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/dataset_api_service.py` around lines 1155 - 1176, The missing-index handling in sample_random_chunks_with_vectors should stop relying on repr(e) substring checks and instead use the existing index_exist() helper for a robust existence check. Rework the try/except around docStoreConn.search to follow the same pattern as _compiled_index_or_none, calling settings.docStoreConn.index_exist(index_nm, kb_id) before treating the index as missing and returning an empty list. Keep the logging and empty-result behavior, but remove the exception-message matching and the redundant not_found_exception condition.
🤖 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/dataset_api_service.py`:
- Around line 2065-2073: The `_wiki_entity_payload` and `_wiki_relation_payload`
helpers are swallowing JSON parse failures for `content_with_weight` without any
trace. Update the `json.loads` exception handling in these functions to log the
decode failure with enough context to identify the bad row, then continue
returning an empty payload as today. Use the existing service logger in
`DatasetApiService` and keep the behavior aligned across both payload helpers so
malformed persisted data is no longer silently dropped.
- Around line 2362-2406: The overview-mode loop in get_wiki_graph is currently
using an entity-count limit only, while cumulative_weight is incremented but
never enforced and the commented weight-check is dead code. Choose one semantic
for _wiki_graph_max_loading_entity: either remove cumulative_weight and the
stale commented logic if count-based capping is intended, or restore the
weight-budget check in the page iteration and update the stop
condition/docstring to match. Use get_wiki_graph, cumulative_weight, and
_wiki_search_entity_page to locate the loop and keep the behavior aligned with
the documented overview-mode contract.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1155-1176: The missing-index handling in
sample_random_chunks_with_vectors should stop relying on repr(e) substring
checks and instead use the existing index_exist() helper for a robust existence
check. Rework the try/except around docStoreConn.search to follow the same
pattern as _compiled_index_or_none, calling
settings.docStoreConn.index_exist(index_nm, kb_id) before treating the index as
missing and returning an empty list. Keep the logging and empty-result behavior,
but remove the exception-message matching and the redundant not_found_exception
condition.
🪄 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: 4ea30566-36ca-49e9-b1be-08822d182e98
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/apps/services/dataset_api_service.py (1)
1155-1176: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPrefer the existing
index_exist()helper over exception-string matching.The fix correctly prevents the 500, but it detects "index missing" by matching substrings in
repr(e). This is fragile — it depends on the exact wording embedded by the ES/OpenSearch client's exceptionrepr, and could silently stop matching after a client library upgrade or with a different doc-store backend. The same file already has an established, more robust pattern for exactly this check:_compiled_index_or_noneusessettings.docStoreConn.index_exist(index_nm, kb_id). Consider reusing it here for consistency and to avoid coupling to exception message text.Note also
"not_found_exception"is a substring of"index_not_found_exception", so the secondorclause is currently redundant.♻️ Proposed refactor using `index_exist`
index_nm = search.index_name(tenant_id) - try: - res0 = docStoreConn.search( - select_fields=[], - highlight_fields=[], - condition={"kb_id": kb_id, "available_int": 1}, - match_expressions=[], - order_by=OrderByExpr(), - offset=0, - limit=1, - index_names=index_nm, - knowledgebase_ids=[kb_id], - ) - except Exception as e: - if "not_found_exception" in repr(e) or "index_not_found_exception" in repr(e): - logging.info( - "sample_random_chunks_with_vectors: index %s not yet created for tenant %s; " - "returning empty sample set", - index_nm, - tenant_id, - ) - return [] - raise + if not docStoreConn.index_exist(index_nm, kb_id): + logging.info( + "sample_random_chunks_with_vectors: index %s not yet created for tenant %s; " + "returning empty sample set", + index_nm, + tenant_id, + ) + return [] + res0 = docStoreConn.search( + select_fields=[], + highlight_fields=[], + condition={"kb_id": kb_id, "available_int": 1}, + match_expressions=[], + order_by=OrderByExpr(), + offset=0, + limit=1, + index_names=index_nm, + knowledgebase_ids=[kb_id], + )🤖 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/dataset_api_service.py` around lines 1155 - 1176, The missing-index handling in sample_random_chunks_with_vectors should stop relying on repr(e) substring checks and instead use the existing index_exist() helper for a robust existence check. Rework the try/except around docStoreConn.search to follow the same pattern as _compiled_index_or_none, calling settings.docStoreConn.index_exist(index_nm, kb_id) before treating the index as missing and returning an empty list. Keep the logging and empty-result behavior, but remove the exception-message matching and the redundant not_found_exception condition.
🤖 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/dataset_api_service.py`:
- Around line 2065-2073: The `_wiki_entity_payload` and `_wiki_relation_payload`
helpers are swallowing JSON parse failures for `content_with_weight` without any
trace. Update the `json.loads` exception handling in these functions to log the
decode failure with enough context to identify the bad row, then continue
returning an empty payload as today. Use the existing service logger in
`DatasetApiService` and keep the behavior aligned across both payload helpers so
malformed persisted data is no longer silently dropped.
- Around line 2362-2406: The overview-mode loop in get_wiki_graph is currently
using an entity-count limit only, while cumulative_weight is incremented but
never enforced and the commented weight-check is dead code. Choose one semantic
for _wiki_graph_max_loading_entity: either remove cumulative_weight and the
stale commented logic if count-based capping is intended, or restore the
weight-budget check in the page iteration and update the stop
condition/docstring to match. Use get_wiki_graph, cumulative_weight, and
_wiki_search_entity_page to locate the loop and keep the behavior aligned with
the documented overview-mode contract.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1155-1176: The missing-index handling in
sample_random_chunks_with_vectors should stop relying on repr(e) substring
checks and instead use the existing index_exist() helper for a robust existence
check. Rework the try/except around docStoreConn.search to follow the same
pattern as _compiled_index_or_none, calling
settings.docStoreConn.index_exist(index_nm, kb_id) before treating the index as
missing and returning an empty list. Keep the logging and empty-result behavior,
but remove the exception-message matching and the redundant not_found_exception
condition.
🪄 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: 4ea30566-36ca-49e9-b1be-08822d182e98
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
🛑 Comments failed to post (2)
api/apps/services/dataset_api_service.py (2)
2065-2073: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Log JSON-decode failures instead of silently swallowing them.
Both
_wiki_entity_payloadand_wiki_relation_payloadcatchExceptionaroundjson.loadsandpass, discarding malformedcontent_with_weightrows without a trace (flagged by Ruff S110/BLE001). Since these are new flows, per coding guidelines new flows should include logging so malformed persisted data isn't silently lost from the graph view.As per coding guidelines,
**/*.py: "Add logging for new flows."🪵 Proposed logging addition
if isinstance(raw, str) and raw.strip(): try: parsed = json.loads(raw) if isinstance(parsed, dict): payload = parsed - except Exception: - pass + except Exception: + logging.debug("Failed to parse content_with_weight JSON for row=%s", row.get("id"), exc_info=True)(apply analogously to
_wiki_relation_payload)Also applies to: 2092-2100
🧰 Tools
🪛 Ruff (0.15.20)
[error] 2072-2073:
try-except-passdetected, consider logging the exception(S110)
[warning] 2072-2072: 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/services/dataset_api_service.py` around lines 2065 - 2073, The `_wiki_entity_payload` and `_wiki_relation_payload` helpers are swallowing JSON parse failures for `content_with_weight` without any trace. Update the `json.loads` exception handling in these functions to log the decode failure with enough context to identify the bad row, then continue returning an empty payload as today. Use the existing service logger in `DatasetApiService` and keep the behavior aligned across both payload helpers so malformed persisted data is no longer silently dropped.Sources: Coding guidelines, Linters/SAST tools
2362-2406: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Cumulative-weight budget is dead code; cap is actually entity count only.
The docstring for
get_wiki_graph(overview mode) states entities are appended "while the cumulative weight stays within_WIKI_GRAPH_MAX_LOADING_ENTITY," but the code that enforces that check is commented out (lines 2401-2402).cumulative_weightis accumulated (line 2403) but never read afterward — the only actual cap applied islen(entities) + len(e_sub) >= cap, i.e. an entity-count cap, not a weight-budget cap. This is a real discrepancy between documented and actual behavior; leaving the dead branch and stale comment risks confusing future maintainers about which semantics are in effect.🧹 Proposed fix — pick one semantics and remove the dead branch
- # Step 2: cumulative across the whole flow (per the spec). - # Stop when adding this entry would push the budget over. - # If even the first entity on a page can't fit, we exit the - # outer loop below; this preserves the "least-weight first - # excluded" semantics. - # if cumulative_weight + w > cap and len(entities) + len(e_sub) > 0: - # break - cumulative_weight += w + # Entity-count budget only; cumulative-weight capping removed. e_sub.append(payload) if len(entities) + len(e_sub) >= cap: break(or, if weight-based capping is actually desired, re-enable the check and update the loop's stop condition/docstring accordingly)
📝 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.cumulative_weight = 0 page = 1 while len(entities) < cap: offset = (page - 1) * page_size try: field_map = await _wiki_search_entity_page( index_nm, dataset_id, offset, page_size, ) except Exception: logging.exception( "get_wiki_graph: entity page fetch failed kb=%s page=%d", dataset_id, page, ) break if not field_map: break # Preserve weight_int DESC order from ES. Iteration over a dict # produced by get_fields keeps insertion order; ES returned them # sorted, so we can rely on that. page_rows = list(field_map.values()) e_sub: list[dict] = [] for row in page_rows: payload = _wiki_entity_payload(row) if payload is None: continue if payload["slug"] in entities: continue w = max(0, int(payload.get("weight") or 0)) # Entity-count budget only; cumulative-weight capping removed. e_sub.append(payload) if len(entities) + len(e_sub) >= cap: break🤖 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/dataset_api_service.py` around lines 2362 - 2406, The overview-mode loop in get_wiki_graph is currently using an entity-count limit only, while cumulative_weight is incremented but never enforced and the commented weight-check is dead code. Choose one semantic for _wiki_graph_max_loading_entity: either remove cumulative_weight and the stale commented logic if count-based capping is intended, or restore the weight-budget check in the page iteration and update the stop condition/docstring to match. Use get_wiki_graph, cumulative_weight, and _wiki_search_entity_page to locate the loop and keep the behavior aligned with the documented overview-mode contract.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16650 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Closes #16649
POST /api/v1/dataset/check_embeddingreturns HTTP 500 when called against a newly created dataset that has never had a document indexed. The root cause is thatsample_random_chunks_with_vectorsissues adocStoreConn.search()call against the tenant chunk index before that index has been created by Elasticsearch / OpenSearch. The client raisesNotFoundError(not_found_exception/index_not_found_exception), which propagates unhandled all the way to the route handler.Root cause
Fix
Wrap the initial existence-probing search in a
try/exceptthat catches index-missing errors and returns an empty list instead of re-raising:The caller (
check_embedding) already handles the empty-sample case by returning(False, "No embedded chunks are available to compare."), so the user-facing response becomes a clear, actionable 200 instead of a generic 500.How to reproduce
POST /api/v1/dataset/check_embeddingwith{"embd_id": "<any embedding model>"}.not_found_exceptiontraceback.{"data": false, "message": "No embedded chunks are available to compare."}.