Repository navigation
Refactor: merge dataset scope graph. - #17526
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDataset structure storage now distinguishes document and dataset scopes. Dataset graphs are persisted as searchable entity and relation rows, while structure merging uses incremental bucketed processing, build timestamps, deletion metadata, and optional embeddings. The dataset structure API requests dataset-scoped buckets. ChangesDataset structure graph pipeline
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant DocumentService
participant StructureMergeTask
participant StructureStore
participant DatasetStructureAPI
DocumentService->>StructureMergeTask: record document deletion marker
StructureMergeTask->>StructureStore: scan document entity and relation rows
StructureMergeTask->>StructureStore: merge and persist dataset-scoped rows
DatasetStructureAPI->>StructureStore: discover and request dataset-scoped structure
StructureStore-->>DatasetStructureAPI: return entities and relations
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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.
Actionable comments posted: 16
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/svr/task_executor_refactor/dataset_structure_merger.py (1)
481-497: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winPreserve
dataset_mergeas the dataset-merge opt-in.
dataset_mergeis documented as the per-template flag that decides whole-dataset merging; dropping it fromrun_structure_mergemeans every saved template of the requested kind gets rebuild work, including templates the user did not opt into for KB-wide merge.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 481 - 497, Update the template filtering logic in _resolve_template to honor each saved template’s dataset_merge opt-in before setting keep true for dataset-wide merging. Preserve the existing structure_kind and target_kind checks, and ensure templates without dataset_merge enabled are excluded even when merge_all is true.
🧹 Nitpick comments (4)
api/apps/services/dataset_api_service.py (1)
1917-1917: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logging for the new dataset-scoped flow.
Log the dataset/template scope before building each bucket so this new query path is observable.
Suggested change
try: + logging.debug( + "get_dataset_structure: building dataset-scoped bucket for kb=%s template=%s", + dataset_id, + tid, + ) entities, relations = await sgc.build_bucket(As per coding guidelines, Python files should 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/apps/services/dataset_api_service.py` at line 1917, Add a log statement immediately before the sgc.build_bucket call in the dataset-scoped flow, including the dataset_id and template ID (tid) being used. Use the service’s existing logging mechanism and preserve the current bucket-building behavior.Source: Coding guidelines
rag/svr/task_executor_refactor/dataset_structure_merger.py (2)
394-396: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDead guard.
_bucket_idalready returns% _BUCKET_COUNT, sobid < _BUCKET_COUNTis always true. Drop the branch.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 394 - 396, Remove the redundant bid < _BUCKET_COUNT conditional in the bucket assignment logic using _bucket_id, and append each row directly to buckets[bid]. Preserve the existing bucket computation and row placement behavior.
191-195: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueDon't pass
idinside the update payload.
settings.docStoreConn.update(condition, new_value, ...)strips"id"fromnew_valuebefore writing, so including"id": meta_idinpayloadis pointless. Drop it here to keep the upsert payload focused on fields that should change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 191 - 195, Update the existing-record branch around settings.docStoreConn.update to remove the id field from payload before passing it as new_value, since the document ID is already supplied by the update condition. Keep the insert branch unchanged and preserve all other payload fields.rag/advanced_rag/knowlege_compile/structure.py (1)
2306-2311: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winBatch the embedding calls.
_encodeis awaited once per entity, andthread_pool_execcreates a new single-workerThreadPoolExecutorper call, so a KB-wide graph triggers thousands of round-trips plus executor churn. Collect descriptions and encode in batches, then attach vectors by index.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/advanced_rag/knowlege_compile/structure.py` around lines 2306 - 2311, Update the re-embedding flow around _encode and thread_pool_exec to collect entity descriptions first, encode them in batches with a shared execution path, and then associate each returned vector with its description by index. Remove the per-entity await and avoid creating a new single-worker executor for every embedding call, while preserving the existing dimension-based q_{dim}_vec assignment and skipping invalid or empty vectors.
🤖 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`:
- Line 1917: Update the keyword-mode call to _scope_for_template so it includes
scope_kwd set to dataset alongside compilation_template_ids, matching the scope
passed to sgc.build_bucket in normal mode and keeping KNN discovery and 1-hop
expansion consistently dataset-scoped.
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2274-2312: The entity row ID currently depends on the mutable
payload description, causing stale dataset duplicates across reruns. Update the
_stable_row_id call in the entity-row construction to use only the stable
identity components—kb_id_str, compile_kwd, compilation_template_id, "dataset",
and ent_name—matching _dataset_entity_row_id, while leaving payload content and
embedding behavior unchanged.
- Around line 2338-2340: Update the relation-row construction near the
rows.append flow to set the compilation_template_kind_kwd field, matching the
structure_kind stamping used for entity rows. Ensure the value identifies the
row as a relation so get_dataset_structure and other kind-scoped consumers
include dataset relations.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 536-544: Update the pair-scan query arguments in the visible
merger flow to include “scope_kwd” constrained to [_SCOPE_KWD_DOC] alongside the
existing knowledge_graph_kwd filter. Preserve the current ordering, pagination,
and other query parameters so only source-document graph rows are scanned.
- Around line 397-408: Consolidate dataset-scoped entity persistence into
_merge_bucket: add relation merging or delegate row construction to the shared
helper so it is the sole writer for entity rows. In
rag/svr/task_executor_refactor/dataset_structure_merger.py lines 397-408, update
the bucket flush path accordingly; in
rag/advanced_rag/knowlege_compile/structure.py lines 2274-2312, remove
entity/relation row emission from _struct_upsert_dataset_graph_json and retain
only the meta-row write.
- Around line 397-408: The bucket flush path around _merge_bucket must preserve
cumulative state for each (name, type) across all pages instead of materializing
independent partial rows with the same _dataset_entity_row_id. Update the
bucket/group handling so repeated entities merge their source_chunk_ids,
doc_ids_kwd, and mention_count before producing one final row per entity, and
ensure all_rows_out contains no duplicate row IDs.
- Around line 362-364: Remove the all_rows_out accumulator from the
bucket-merging flow and write each _merge_bucket result directly to the output
as soon as it is produced. Preserve the existing 256×500 bucket flushing
behavior and update the final return/output handling so it no longer depends on
retaining every merged row in memory.
- Around line 456-471: Ensure embedding-model binding failure in the dataset
structure merge path is surfaced through progress or causes the build to abort,
rather than continuing with embd_mdl unset and reporting success; update the
exception handling around LLMBundle in the merge flow and remove the redundant
kb = None assignment before KnowledgebaseService.get_by_id.
- Around line 512-519: The eligible-template build loop must honor task
cancellation before starting each build. In the loop around _do_build, add the
existing task cancellation check at the start of every iteration, before
invoking _do_build, so cancellation stops further dataset graph merges while
preserving the current progress and error handling.
- Around line 342-358: Update the doc_graph query construction around base_cond
so full and incremental scans constrain scope_kwd to doc rows or rows where
scope_kwd is absent, preventing dataset rows from being reprocessed. Push the
incremental create_timestamp_flt window into base_cond as well, and remove the
stale backward-compatibility comment; eliminate the separate row-by-row
timestamp filtering path if it becomes redundant.
- Around line 459-461: Update the import block in dataset_structure_merger.py to
import resolve_model_config directly from
api.db.joint_services.tenant_model_service instead of
api.apps.services.dataset_api_service, while leaving the LLMBundle and LLMType
imports unchanged.
- Around line 138-143: The _es_delete exception handler currently suppresses
failed deletions; update it to log the caught exception using the module’s
established logger while preserving the existing non-raising behavior. Keep the
logging scoped to this delete failure and include enough context to identify the
affected tenant, knowledge base, or index.
- Around line 96-97: The dataset merge currently processes only entity rows, so
relation-only changes are omitted while _dataset_relation_row_id remains unused.
Update _merge_bucket and _do_build to include dataset-scoped relation doc_graph
rows, generate matching relation row IDs with _dataset_relation_row_id, and
ensure additions, updates, and deletions are represented in the merged output;
otherwise remove the unused relation row builder.
- Around line 167-173: Update the build-timestamp retrieval logic to treat
missing or non-positive build_timestamp_flt values as absent by returning None,
ensuring _do_build selects the full-rebuild path. In the exception handler
around thread_pool_exec, replace the silent pass with logging of the exception
using the surrounding logger.
- Around line 386-390: Update _do_build’s incremental path to include
create_timestamp_flt in the selected field list, then compare the row timestamp
against the scalar ts_cond["create_timestamp_flt"]["gte"] value instead of
indexing that condition with [0]. Preserve skipping rows older than the
incremental cutoff.
- Around line 249-262: The merged entity payload currently uses the grouping key
name_lower, losing the original casing. In the entity-merging logic that builds
payload_out, retain a representative original-cased name from the merged
occurrences for payload_out["name"], while continuing to use name_lower for
name_kwd, row identity, and grouping.
---
Outside diff comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 481-497: Update the template filtering logic in _resolve_template
to honor each saved template’s dataset_merge opt-in before setting keep true for
dataset-wide merging. Preserve the existing structure_kind and target_kind
checks, and ensure templates without dataset_merge enabled are excluded even
when merge_all is true.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Line 1917: Add a log statement immediately before the sgc.build_bucket call in
the dataset-scoped flow, including the dataset_id and template ID (tid) being
used. Use the service’s existing logging mechanism and preserve the current
bucket-building behavior.
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2306-2311: Update the re-embedding flow around _encode and
thread_pool_exec to collect entity descriptions first, encode them in batches
with a shared execution path, and then associate each returned vector with its
description by index. Remove the per-entity await and avoid creating a new
single-worker executor for every embedding call, while preserving the existing
dimension-based q_{dim}_vec assignment and skipping invalid or empty vectors.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 394-396: Remove the redundant bid < _BUCKET_COUNT conditional in
the bucket assignment logic using _bucket_id, and append each row directly to
buckets[bid]. Preserve the existing bucket computation and row placement
behavior.
- Around line 191-195: Update the existing-record branch around
settings.docStoreConn.update to remove the id field from payload before passing
it as new_value, since the document ID is already supplied by the update
condition. Keep the insert branch unchanged and preserve all other payload
fields.
🪄 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: 40c49641-9196-4753-8bce-406c41af3f43
📒 Files selected for processing (4)
api/apps/services/dataset_api_service.pyconf/infinity_mapping.jsonrag/advanced_rag/knowlege_compile/structure.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
| if compilation_template_id: | ||
| row["compilation_template_ids"] = [compilation_template_id] | ||
| rows.append(row) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Relation rows drop compilation_template_kind_kwd.
Entity rows stamp structure_kind (Line 2302) but relation rows do not, so any consumer that scopes raw rows by kind (as get_dataset_structure does in its keywords path) will miss dataset relations. Stamp it here too.
🛠️ Proposed fix
if compilation_template_id:
row["compilation_template_ids"] = [compilation_template_id]
+ if structure_kind:
+ row["compilation_template_kind_kwd"] = str(structure_kind)
rows.append(row)📝 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.
| if compilation_template_id: | |
| row["compilation_template_ids"] = [compilation_template_id] | |
| rows.append(row) | |
| if compilation_template_id: | |
| row["compilation_template_ids"] = [compilation_template_id] | |
| if structure_kind: | |
| row["compilation_template_kind_kwd"] = str(structure_kind) | |
| rows.append(row) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/knowlege_compile/structure.py` around lines 2338 - 2340,
Update the relation-row construction near the rows.append flow to set the
compilation_template_kind_kwd field, matching the structure_kind stamping used
for entity rows. Ensure the value identifies the row as a relation so
get_dataset_structure and other kind-scoped consumers include dataset relations.
| from api.db.services.llm_service import LLMBundle | ||
| from api.apps.services.dataset_api_service import resolve_model_config | ||
| from api.db import LLMType |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP 'resolve_model_config' api/apps/services/dataset_api_service.py | head -20
rg -nP 'def resolve_model_config' -r '$0' -g '*.py' .Repository: infiniflow/ragflow
Length of output: 1213
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== dataset_structure_merger relevant imports =="
sed -n '440,475p' rag/svr/task_executor_refactor/dataset_structure_merger.py
echo
echo "== tenant_model_service definition =="
sed -n '240,285p' api/db/joint_services/tenant_model_service.py
echo
echo "== dataset_api_service resolve_model_config definition/imports =="
sed -n '1,40p' api/apps/services/dataset_api_service.py
sed -n '1070,1090p' api/apps/services/dataset_api_service.py
sed -n '1872,1888p' api/apps/services/dataset_api_service.py
echo
echo "== Python import semantics probe for dataset_api_service.py =="
python3 - <<'PY'
import ast
from pathlib import Path
p = Path("api/apps/services/dataset_api_service.py")
tree = ast.parse(p.read_text(), filename=str(p))
imports = []
names = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
if node.module == "api.db.joint_services.tenant_model_service":
imports.append([n.name for n in node.names])
elif node.module == "api.apis.services.dataset_api_service":
imports.append([n.name for n in node.names])
elif isinstance(node, ast.FunctionDef):
names.append(node.name)
print({
"file": str(p),
"resolve_model_config_defined": "resolve_model_config" in names,
"tenant_model_service_imports_resolve_model_config": "resolve_model_config" in [n for seq in imports for n in seq],
"relevant_import_lines": [(line_no, ast.unparse(node) if hasattr(ast, "unparse") else str(node))
for line_no, node in ((n.lineno, n) for n in tree.body if isinstance(n, ast.ImportFrom))]
})
PYRepository: infiniflow/ragflow
Length of output: 9200
Import resolve_model_config from its owner module.
resolve_model_config is not defined in api/apps/services/dataset_api_service.py; it is imported there from api.db.joint_services.tenant_model_service. Import it directly from api.db.joint_services.tenant_model_service to keep the task worker from depending on a transient HTTP-service re-export.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 459
- 461, Update the import block in dataset_structure_merger.py to import
resolve_model_config directly from api.db.joint_services.tenant_model_service
instead of api.apps.services.dataset_api_service, while leaving the LLMBundle
and LLMType imports unchanged.
Source: Coding guidelines
| ["id", "compile_kwd", "compilation_template_ids"], | ||
| [], | ||
| {"knowledge_graph_kwd": ["entity"]}, | ||
| [], | ||
| OrderByExpr(), | ||
| offset, | ||
| _PAGE_SIZE, | ||
| index, | ||
| [kb_id], |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Restrict the pair scan to doc-scoped rows.
{"knowledge_graph_kwd": ["entity"]} also matches the scope_kwd="dataset" rows written by previous merges, so pairs can be discovered from merge output rather than source documents (and paging cost grows with every rebuild). Add "scope_kwd": [_SCOPE_KWD_DOC]. The docstring already claims doc_graph rows only.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 536
- 544, Update the pair-scan query arguments in the visible merger flow to
include “scope_kwd” constrained to [_SCOPE_KWD_DOC] alongside the existing
knowledge_graph_kwd filter. Preserve the current ordering, pagination, and other
query parameters so only source-document graph rows are scanned.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/dataset_structure_merger.py (2)
26-28: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRuff flags ambiguous Unicode in the new docstring/comments.
Line 26 uses an EN DASH (RUF002) and the new section comments at Lines 353, 387, 465 use narrow no-break spaces (RUF003). Replace with plain ASCII
-/space soruff checkon this file stays clean.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 26 - 28, Replace the Unicode punctuation in the documentation comments: change the EN DASH in the document-deletion comment near record_doc_deletion() to an ASCII hyphen, and replace narrow no-break spaces in the section comments near the relevant build logic with regular spaces. Preserve the comment wording and behavior while ensuring ruff check passes for the file.Source: Linters/SAST tools
419-430: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valuePaging with a mutating result set skips rows.
Ghost rows discovered on page N are deleted (Lines 433-440) only after the whole scan completes — that part is fine — but shared rows are not modified during the scan either, so offsets stay stable. The
doc_ids_kwdupdate loop at Lines 450-458, however, issues one store round-trip per row with no batching; for a large KB deletion this is thousands of sequential calls on the merge worker. Consider grouping rows by identicalremaininglist, or updating in bounded batches.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 419 - 430, Batch the shared-row updates collected in ids_to_update instead of issuing one store round-trip per row. Group rows with identical remaining doc_ids_kwd values or process updates in bounded batches, while preserving the existing deletion and update semantics and ensuring all collected rows are applied after scanning.
🤖 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/db/services/document_service.py`:
- Around line 509-519: The deletion marker is removed by the same-request chunk
sweep and reuses the sweep’s doc_id field. In
api/db/services/document_service.py lines 509-519, move record_doc_deletion
after the settings.docStoreConn.delete({"doc_id": doc.id}, ...) sweep but before
knowledge-graph cleanup; in
rag/svr/task_executor_refactor/dataset_structure_merger.py lines 179-189, store
the marker under deleted_doc_id and update _cleanup_deleted_docs Passes 1 and 2
to read that field.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 465-468: Fix Pass 3 in the per-pair cleanup flow so kb-global
deletion markers are not removed after the first `(compile_kwd, template_id)`
pair; consume them only after all eligible pairs process them, or track and
delete them only after every pair has handled each marker. Ensure Pass 3 is
skipped whenever the Pass-2 scan aborts due to a store error, preserving markers
for retry.
- Around line 356-374: Update both scan loops in the dataset structure merger,
including the loop containing settings.docStoreConn.search and the corresponding
loop near the second exception block, to catch the exception as an error value
and log it with the module’s existing logger before breaking. Preserve the
current break behavior for terminating the scan, and avoid bare Exception
handling that triggers BLE001.
---
Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 26-28: Replace the Unicode punctuation in the documentation
comments: change the EN DASH in the document-deletion comment near
record_doc_deletion() to an ASCII hyphen, and replace narrow no-break spaces in
the section comments near the relevant build logic with regular spaces. Preserve
the comment wording and behavior while ensuring ruff check passes for the file.
- Around line 419-430: Batch the shared-row updates collected in ids_to_update
instead of issuing one store round-trip per row. Group rows with identical
remaining doc_ids_kwd values or process updates in bounded batches, while
preserving the existing deletion and update semantics and ensuring all collected
rows are applied after scanning.
🪄 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: f1a422b8-b2cf-4d4d-acff-4062b5ea6c1e
📒 Files selected for processing (2)
api/db/services/document_service.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
| while True: | ||
| try: | ||
| res = await thread_pool_exec( | ||
| settings.docStoreConn.search, | ||
| select_fields, | ||
| ["id", "doc_id"], | ||
| [], | ||
| {"knowledge_graph_kwd": ["entity", "relation"]}, | ||
| {"kb_id": [kb_id], "knowledge_graph_kwd": [_DELETION_META_KWD]}, | ||
| [], | ||
| OrderByExpr(), | ||
| offset, | ||
| page_size, | ||
| _PAGE_SIZE, | ||
| index, | ||
| [kb_id], | ||
| ) | ||
| field_map = settings.docStoreConn.get_fields(res, select_fields) or {} | ||
| fm = settings.docStoreConn.get_fields(res, ["id", "doc_id"]) or {} | ||
| except Exception: | ||
| logging.exception("structure_merge: failed to scan entity/relation rows for kb=%s", kb_id) | ||
| break | ||
| if not field_map: | ||
| if not fm: | ||
| break |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Silent break hides store failures in both scan loops.
Lines 371-372 and 415-416 swallow the exception with a bare break, so a store error is indistinguishable from "no pending deletions". Log it (Ruff also flags BLE001 here).
As per coding guidelines, "Add logging for new flows".
🪵 Proposed fix
- except Exception:
- break
+ except Exception:
+ logging.exception("structure_merge: deletion-meta scan failed for kb=%s", kb_id)
+ break📝 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.
| while True: | |
| try: | |
| res = await thread_pool_exec( | |
| settings.docStoreConn.search, | |
| select_fields, | |
| ["id", "doc_id"], | |
| [], | |
| {"knowledge_graph_kwd": ["entity", "relation"]}, | |
| {"kb_id": [kb_id], "knowledge_graph_kwd": [_DELETION_META_KWD]}, | |
| [], | |
| OrderByExpr(), | |
| offset, | |
| page_size, | |
| _PAGE_SIZE, | |
| index, | |
| [kb_id], | |
| ) | |
| field_map = settings.docStoreConn.get_fields(res, select_fields) or {} | |
| fm = settings.docStoreConn.get_fields(res, ["id", "doc_id"]) or {} | |
| except Exception: | |
| logging.exception("structure_merge: failed to scan entity/relation rows for kb=%s", kb_id) | |
| break | |
| if not field_map: | |
| if not fm: | |
| break | |
| while True: | |
| try: | |
| res = await thread_pool_exec( | |
| settings.docStoreConn.search, | |
| ["id", "doc_id"], | |
| [], | |
| {"kb_id": [kb_id], "knowledge_graph_kwd": [_DELETION_META_KWD]}, | |
| [], | |
| OrderByExpr(), | |
| offset, | |
| _PAGE_SIZE, | |
| index, | |
| [kb_id], | |
| ) | |
| fm = settings.docStoreConn.get_fields(res, ["id", "doc_id"]) or {} | |
| except Exception: | |
| logging.exception("structure_merge: deletion-meta scan failed for kb=%s", kb_id) | |
| break | |
| if not fm: | |
| break |
🧰 Tools
🪛 Ruff (0.16.0)
[warning] 371-371: 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 `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 356
- 374, Update both scan loops in the dataset structure merger, including the
loop containing settings.docStoreConn.search and the corresponding loop near the
second exception block, to catch the exception as an error value and log it with
the module’s existing logger before breaking. Preserve the current break
behavior for terminating the scan, and avoid bare Exception handling that
triggers BLE001.
Sources: Coding guidelines, Linters/SAST tools
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
rag/svr/task_executor_refactor/dataset_structure_merger.py (3)
656-675: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
_index_insertfailures are swallowed while the build timestamp still advances — merged rows can be permanently lost.
_index_insert(Lines 145-152) only logs on failure and returns nothing; its result is never checked at the call site (Lines 668-669)._do_buildstill unconditionally calls_save_build_timewithnow()right after (Line 674) and returnscleanup_ok(which only reflects ghost-cleanup status, not insert status). If the insert of a merged bucket fails (e.g. transient store error), the watermark still advances past those rows'create_timestamp_flt, so the next incremental scan will never pick them up again.🐛 Proposed fix
+ insert_ok = True for bi in range(_BUCKET_COUNT): if buckets[bi]: out = await _merge_bucket(...) if out: for start in range(0, len(out), _BUCKET_FLUSH_THRESHOLD): - await _index_insert(tenant_id, kb_id, out[start : start + _BUCKET_FLUSH_THRESHOLD]) + ok = await _index_insert(tenant_id, kb_id, out[start : start + _BUCKET_FLUSH_THRESHOLD]) + insert_ok = insert_ok and ok # ── Save build timestamp ───────────────────────────────────────── - await _save_build_time(...) - return cleanup_ok + if insert_ok: + await _save_build_time(...) + return cleanup_ok and insert_ok🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 656 - 675, Update the bucket flush flow in _do_build to detect and propagate failures from _index_insert instead of ignoring its result. Only call _save_build_time after every merged batch is inserted successfully, and return a failure status when any insert fails so the watermark cannot advance past lost rows.
557-589: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick winQuery from offset 0 until the deletion list is empty.
When
del_condmatches more than 1000 dataset rows, this offset-based loop deletes one full page, then incrementsoffsetfor the next query against an already-shrunken result set. Once fewer thanoffsetmatched rows remain, the next search returns empty and the loop exits, leaving stale dataset rows behind on full rebuilds. Re-query withoffset=0each iteration and only stop when a page is empty or has fewer than 1000 IDs.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 557 - 589, Update the full-rebuild deletion loop around del_cond to query with offset=0 on every iteration after deletions shrink the result set. Continue deleting each returned page, and stop only when the page is empty or contains fewer than 1000 IDs, ensuring all matching dataset rows are removed.
256-263: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick winInclude the entity type in the dataset entity row id.
groupsis keyed by(name_lower, typ), butrow_idand_bucket_id(name)only use the entity name. Same-name entities with different types can be emitted into the same stable_row_id/hash, so one entity overwrites the other in the dataset graph.🐛 Proposed fix
- row_id = _dataset_entity_row_id(kb_id, compile_kwd, template_id, name_lower) + row_id = _dataset_entity_row_id(kb_id, compile_kwd, template_id, name_lower, typ)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 256 - 263, The grouping logic includes entity type, but generated dataset identifiers do not. Update the row ID and bucket ID generation in the merger flow to incorporate the normalized entity type alongside the entity name, ensuring same-name entities with different types receive distinct stable IDs and cannot overwrite one another.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/dataset_structure_merger.py (1)
17-24: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftDesign now buffers every scanned entity mention row in memory for the full scan window before merging.
The mid-scan bucket-flush bug (overwriting earlier partial merges) is fixed by accumulating all rows per bucket across the entire scan and merging once (Lines 615, 656-669) — correct, but per the header comment (Line 24) this means peak memory now scales with the total number of doc-scoped entity mention rows for the whole
(compile_kwd, template_id)scope, for very large KBs this could be sizable. Consider per-key running aggregation (accumulatesource_chunk_ids/doc_ids/description candidates keyed by(name, type)instead of raw rows) to bound memory while keeping correctness.Also applies to: 606-669
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 17 - 24, Replace raw-row buffering in the scan and bucket-flush flow around the merge logic at lines 606-669 with per-key running aggregation keyed by (name, type). Accumulate source_chunk_ids, doc_ids, and description candidates for each key across the full scan, then perform the final bucket merges from these aggregates so memory is not proportional to all scanned mention rows and earlier partial results remain preserved.
🤖 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.
Outside diff comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 656-675: Update the bucket flush flow in _do_build to detect and
propagate failures from _index_insert instead of ignoring its result. Only call
_save_build_time after every merged batch is inserted successfully, and return a
failure status when any insert fails so the watermark cannot advance past lost
rows.
- Around line 557-589: Update the full-rebuild deletion loop around del_cond to
query with offset=0 on every iteration after deletions shrink the result set.
Continue deleting each returned page, and stop only when the page is empty or
contains fewer than 1000 IDs, ensuring all matching dataset rows are removed.
- Around line 256-263: The grouping logic includes entity type, but generated
dataset identifiers do not. Update the row ID and bucket ID generation in the
merger flow to incorporate the normalized entity type alongside the entity name,
ensuring same-name entities with different types receive distinct stable IDs and
cannot overwrite one another.
---
Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 17-24: Replace raw-row buffering in the scan and bucket-flush flow
around the merge logic at lines 606-669 with per-key running aggregation keyed
by (name, type). Accumulate source_chunk_ids, doc_ids, and description
candidates for each key across the full scan, then perform the final bucket
merges from these aggregates so memory is not proportional to all scanned
mention rows and earlier partial results remain preserved.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b6d7b1b7-4a93-424e-b842-a59416e4bdda
📒 Files selected for processing (4)
api/apps/services/dataset_api_service.pyapi/db/services/document_service.pyrag/advanced_rag/knowlege_compile/structure.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
🚧 Files skipped from review as they are similar to previous changes (2)
- api/apps/services/dataset_api_service.py
- rag/advanced_rag/knowlege_compile/structure.py
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 1836-1883: Update the dataset structure discovery flow around the
metadata scan to also detect datasets containing only the legacy dataset_graph
blob, setting has_templateless when that blob exists even without dataset-scoped
entity/relation rows. Ensure the existing fallback path can then execute for
blob-only legacy graphs, and add a regression test covering a dataset with only
the legacy blob.
- Around line 1836-1883: Track the number of discovery pages processed in the
dataset-structure scan, incrementing it for each successful search, including
the final empty page when applicable. After the loop completes successfully, add
a concise debug/info log containing dataset_id, the page count, and
len(kind_template_ids). Keep the existing failure logging and early return
unchanged.
- Around line 1847-1883: The metadata discovery loop in the dataset structure
collection must use deterministic ordering before offset pagination. Update the
`settings.docStoreConn.search` call to pass an explicit
`Order_ByIdExpr().asc("_order_id").asc("_doc_id")` (or the existing equivalent
stable ordering) instead of `OrderByExpr()`, preserving the current pagination
and filtering behavior.
🪄 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: 63f48a47-f7b3-4c83-972a-d35ed59a3f08
📒 Files selected for processing (2)
api/apps/services/dataset_api_service.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/svr/task_executor_refactor/dataset_structure_merger.py
| offset = 0 | ||
| page_size = 1000 | ||
| while True: | ||
| try: | ||
| res = await thread_pool_exec( | ||
| settings.docStoreConn.search, | ||
| meta_fields, | ||
| [], | ||
| {"knowledge_graph_kwd": ["entity", "relation"], "scope_kwd": ["dataset"]}, | ||
| [], | ||
| OrderByExpr(), | ||
| offset, | ||
| page_size, | ||
| index_nm, | ||
| [dataset_id], | ||
| ) | ||
| meta_rows = settings.docStoreConn.get_fields(res, meta_fields) or {} | ||
| except Exception: | ||
| logging.exception("get_dataset_structure: docStore discovery failed for kb=%s", dataset_id) | ||
| return True, empty | ||
| if not meta_rows: | ||
| break | ||
| for row in meta_rows.values(): | ||
| tid = _row_template_id(row) | ||
| stamped_kind = (row.get("compilation_template_kind_kwd") or "").strip() | ||
| row_kind = stamped_kind or _template_meta(tid) or "" | ||
| if _resolve_dataset_structure_kind(row_kind) != resolved_kind: | ||
| continue | ||
| if tid: | ||
| if tid not in seen_tid: | ||
| seen_tid.add(tid) | ||
| kind_template_ids.append(tid) | ||
| else: | ||
| has_templateless = True | ||
| if len(meta_rows) < page_size: | ||
| break | ||
| offset += page_size |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline common/doc_store --items all --type function --match 'search'
rg -n -A100 -B20 'def search\(' common/doc_store -g '*.py'
rg -n -A20 -B10 'offset|page_size|order_by|OrderByExpr' common/doc_store -g '*.py'Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== doc_store files =="
git ls-files common/doc_store | sed -n '1,120p'
echo
echo "== search implementations =="
for f in common/doc_store/doc_store_base.py common/doc_store/es_conn_base.py common/doc_store/ob_conn_base.py common/doc_store/infinity_conn_base.py; do
echo "--- $f ---"
rg -n -A90 -B30 'def search\(' "$f"
done
echo
echo "== OrderByExpr usage =="
rg -n -B5 -A30 'OrderByExpr\(\)|\.asc\(|\.desc\(|order_by' common api -g '*.py' | sed -n '1,240p'Repository: infiniflow/ragflow
Length of output: 34257
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate generated doc store concrete implementations =="
git ls-files | rg 'doc_store|DatasetAPI' | sed -n '1,200p'
echo
echo "== get_fields implementations and references =="
rg -n -B10 -A50 'class .*Connection|def get_fields\(' common -g '*.py'
rg -n -B20 -A5 'settings\.docStoreConn|docStoreConn' api apps common -g '*.py' | sed -n '1,260p'
echo
echo "== app service relevant methods =="
ast-grep outline api/apps/services/dataset_api_service.py --match 'get_dataset_structure' --view expanded || true
rg -n -B30 -A80 'def get_dataset_structure|get_dataset_structure\(' api/apps/services/dataset_api_service.pyRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== settings file snippets =="
sed -n '300,330p' common/settings.py
sed -n '1,40p' rag/utils/__init__.py
fd -e py 'es_conn|infinity_conn|ob_conn' rag -x sh -c 'echo "--- $1"; sed -n "1,160p" "$1"' sh {}
echo
echo "== get_dataset_structure implementation =="
sed -n '1800,1910p' api/apps/services/dataset_api_service.py
echo
echo "== docStoreConn import/use =="
rg -n 'from common import settings|settings\.docStoreConn|docStoreConn' api apps rag -g '*.py' | sed -n '1,220p'Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
for f in rag/utils/es_conn.py rag/utils/infinity_conn.py rag/utils/ob_conn.py rag/utils/opensearch_conn.py; do
echo "--- $f ---"
rg -n -A110 -B30 'def search\(' "$f"
done
echo
echo "--- search implementations without huge context ---"
for f in rag/utils/es_conn.py rag/utils/infinity_conn.py rag/utils/ob_conn.py rag/utils/opensearch_conn.py; do
echo "=== $f ==="
python3 - <<PY "$f"
import re, sys
p=sys.argv[1]
text=open(p).read()
for m in re.finditer(r'^\s+def search\(', text, re.M):
start=m.start()
before=text.rfind("\n def ", 0, start)
if before==-1: before=0
lines=text[before:m.end()+1].splitlines()
# find next same-indent def
end=len(lines)
for i,l in enumerate(lines):
if re.match(r'^ def ', l) and i>1:
end=i
break
print("\n".join(lines[:end]))
PY
doneRepository: infiniflow/ragflow
Length of output: 34031
Add an explicit stable sort before offset paging.
This discovery loop pages with OrderByExpr() but the metadata search does not include _order_id or _doc_id in the query order, so the result order can be nondeterministic on every backend that relies on _score/vector similarity and tie-breaks. Add Order_ByIdExpr().asc("_order_id").asc("_doc_id") or equivalent stable ordering to avoid offset/overlap issues when collecting template buckets.
🤖 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 1847 - 1883, The
metadata discovery loop in the dataset structure collection must use
deterministic ordering before offset pagination. Update the
`settings.docStoreConn.search` call to pass an explicit
`Order_ByIdExpr().asc("_order_id").asc("_doc_id")` (or the existing equivalent
stable ordering) instead of `OrderByExpr()`, preserving the current pagination
and filtering behavior.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/svr/task_executor_refactor/dataset_structure_merger.py (1)
698-709: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRequest
knowledge_graph_kwddirectly instead of relying on key absence for classification.The field list passed to
_index_searchdoes not includeknowledge_graph_kwd, so the primaryis_relbranch is ignored; relation/entity distribution then depends on whether the active doc store omits absent requested fields or includes them withNone. Request the classification field sorelation_rowsis populated from the stored row type independent of connector field-presence semantics.🐛 Proposed fix
[ "id", "content_with_weight", "source_chunk_ids", "doc_id", "name_kwd", "mention_count_int", "compilation_template_ids", "create_timestamp_flt", "from_entity_kwd", "to_entity_kwd", + "knowledge_graph_kwd", ],🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 698 - 709, Update the field list passed to _index_search to include knowledge_graph_kwd, ensuring the is_rel classification branch uses the stored row type and relation_rows is populated consistently regardless of how the document store represents absent fields.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/dataset_structure_merger.py (1)
752-765: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo logging around relation merge/insert.
_cleanup_deleted_docslogs counts for deletes/updates, but the relation merge-and-insert path here is silent even on success/failure, making incremental relation-merge issues (e.g. zero relations merged when some were expected) hard to diagnose in production.As per coding guidelines, "Add logging for new flows."
♻️ Suggested addition
if relation_rows: rel_out = await _merge_relations( tenant_id, kb_id, compile_kwd, template_id, relation_rows, structure_kind, ) if rel_out: + logging.info( + "structure_merge: merged %d relation rows for kb=%s compile=%s", + len(rel_out), kb_id, compile_kwd, + ) for start in range(0, len(rel_out), _BUCKET_FLUSH_THRESHOLD): await _index_insert(tenant_id, kb_id, rel_out[start : start + _BUCKET_FLUSH_THRESHOLD])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 752 - 765, The relation merge-and-insert flow around _merge_relations and _index_insert lacks operational logging. Add concise success and failure logging for the relation merge result and each insertion outcome, including useful context such as tenant_id, kb_id, and relation counts; ensure zero merged relations and exceptions are explicitly recorded without changing the existing merge or batching behavior.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Line 690: The relation processing path currently accumulates all rows in
relation_rows until the scan finishes, causing unbounded memory use. Update the
scan and post-scan logic around relation_rows to distribute each relation into
the existing _BUCKET_COUNT buckets using a stable hash of src/tgt, then merge
and flush each bucket as it is completed, matching the entity bucket flow and
preserving relation insertion behavior.
- Around line 333-399: Update _merge_relations and its call site to accept and
thread embd_mdl, then generate the relation embedding inside each per-group loop
using the same optional re-embedding logic and vector-field naming used by
_merge_bucket. Attach the resulting q_<dim>_vec field to every dataset-scoped
relation row while preserving the existing deduplication and tokenization
behavior.
- Around line 359-392: Update the relation payload built in the dataset merger
so the computed best_desc is persisted in content_with_weight alongside from,
to, and type. Keep the existing tokenization and row fields unchanged, ensuring
consumers can access the human-readable description.
---
Outside diff comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 698-709: Update the field list passed to _index_search to include
knowledge_graph_kwd, ensuring the is_rel classification branch uses the stored
row type and relation_rows is populated consistently regardless of how the
document store represents absent fields.
---
Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 752-765: The relation merge-and-insert flow around
_merge_relations and _index_insert lacks operational logging. Add concise
success and failure logging for the relation merge result and each insertion
outcome, including useful context such as tenant_id, kb_id, and relation counts;
ensure zero merged relations and exceptions are explicitly recorded without
changing the existing merge or batching behavior.
🪄 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: f8ffe238-1f38-42e3-bb88-6cfcd861673c
📒 Files selected for processing (2)
rag/advanced_rag/knowlege_compile/structure.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/advanced_rag/knowlege_compile/structure.py
| # Use the longest description for tokenization | ||
| all_desc: list[str] = [] | ||
| for r in rows: | ||
| payload = json.loads(r.get("content_with_weight") or "{}") | ||
| chunks = r.get("source_chunk_ids") or [] | ||
| for c in chunks: | ||
| if c not in all_chunks: | ||
| all_chunks.append(c) | ||
| doc = r.get("doc_id") or "" | ||
| if doc and doc not in all_docs: | ||
| all_docs.append(doc) | ||
| desc = payload.get("description") or f"{src} {rel_type} {tgt}" | ||
| if desc not in all_desc: | ||
| all_desc.append(desc) | ||
| best_desc = max(all_desc, key=len) | ||
| ltks, sm_ltks = _tokenize_for_search(best_desc) | ||
|
|
||
| row_id = _dataset_relation_row_id(kb_id, compile_kwd, template_id, src, tgt, rel_type) | ||
| row = { | ||
| "id": row_id, | ||
| "content_with_weight": json.dumps({"from": src, "to": tgt, "type": rel_type}, ensure_ascii=False), | ||
| "compile_kwd": compile_kwd, | ||
| "knowledge_graph_kwd": "relation", | ||
| "scope_kwd": _SCOPE_KWD_DATASET, | ||
| "doc_id": kb_id, | ||
| "kb_id": kb_id, | ||
| "from_entity_kwd": src, | ||
| "to_entity_kwd": tgt, | ||
| "source_chunk_ids": all_chunks, | ||
| "doc_ids_kwd": all_docs, | ||
| "content_ltks": ltks, | ||
| "content_sm_ltks": sm_ltks, | ||
| "available_int": 1, | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Computed relation description is discarded from the payload.
best_desc is computed and tokenized (Lines 370-374) but never written into content_with_weight (Line 379), unlike the entity payload which persists description. Dataset-scoped relation rows therefore have no human-readable description available to consumers that render them (e.g. mind-map/graph rendering).
🐛 Proposed fix
- "content_with_weight": json.dumps({"from": src, "to": tgt, "type": rel_type}, ensure_ascii=False),
+ "content_with_weight": json.dumps({"from": src, "to": tgt, "type": rel_type, "description": best_desc}, ensure_ascii=False),📝 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.
| # Use the longest description for tokenization | |
| all_desc: list[str] = [] | |
| for r in rows: | |
| payload = json.loads(r.get("content_with_weight") or "{}") | |
| chunks = r.get("source_chunk_ids") or [] | |
| for c in chunks: | |
| if c not in all_chunks: | |
| all_chunks.append(c) | |
| doc = r.get("doc_id") or "" | |
| if doc and doc not in all_docs: | |
| all_docs.append(doc) | |
| desc = payload.get("description") or f"{src} {rel_type} {tgt}" | |
| if desc not in all_desc: | |
| all_desc.append(desc) | |
| best_desc = max(all_desc, key=len) | |
| ltks, sm_ltks = _tokenize_for_search(best_desc) | |
| row_id = _dataset_relation_row_id(kb_id, compile_kwd, template_id, src, tgt, rel_type) | |
| row = { | |
| "id": row_id, | |
| "content_with_weight": json.dumps({"from": src, "to": tgt, "type": rel_type}, ensure_ascii=False), | |
| "compile_kwd": compile_kwd, | |
| "knowledge_graph_kwd": "relation", | |
| "scope_kwd": _SCOPE_KWD_DATASET, | |
| "doc_id": kb_id, | |
| "kb_id": kb_id, | |
| "from_entity_kwd": src, | |
| "to_entity_kwd": tgt, | |
| "source_chunk_ids": all_chunks, | |
| "doc_ids_kwd": all_docs, | |
| "content_ltks": ltks, | |
| "content_sm_ltks": sm_ltks, | |
| "available_int": 1, | |
| } | |
| # Use the longest description for tokenization | |
| all_desc: list[str] = [] | |
| for r in rows: | |
| payload = json.loads(r.get("content_with_weight") or "{}") | |
| chunks = r.get("source_chunk_ids") or [] | |
| for c in chunks: | |
| if c not in all_chunks: | |
| all_chunks.append(c) | |
| doc = r.get("doc_id") or "" | |
| if doc and doc not in all_docs: | |
| all_docs.append(doc) | |
| desc = payload.get("description") or f"{src} {rel_type} {tgt}" | |
| if desc not in all_desc: | |
| all_desc.append(desc) | |
| best_desc = max(all_desc, key=len) | |
| ltks, sm_ltks = _tokenize_for_search(best_desc) | |
| row_id = _dataset_relation_row_id(kb_id, compile_kwd, template_id, src, tgt, rel_type) | |
| row = { | |
| "id": row_id, | |
| "content_with_weight": json.dumps({"from": src, "to": tgt, "type": rel_type, "description": best_desc}, ensure_ascii=False), | |
| "compile_kwd": compile_kwd, | |
| "knowledge_graph_kwd": "relation", | |
| "scope_kwd": _SCOPE_KWD_DATASET, | |
| "doc_id": kb_id, | |
| "kb_id": kb_id, | |
| "from_entity_kwd": src, | |
| "to_entity_kwd": tgt, | |
| "source_chunk_ids": all_chunks, | |
| "doc_ids_kwd": all_docs, | |
| "content_ltks": ltks, | |
| "content_sm_ltks": sm_ltks, | |
| "available_int": 1, | |
| } |
🧰 Tools
🪛 ast-grep (0.45.0)
[info] 378-378: use jsonify instead of json.dumps for JSON output
Context: json.dumps({"from": src, "to": tgt, "type": rel_type}, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 359
- 392, Update the relation payload built in the dataset merger so the computed
best_desc is persisted in content_with_weight alongside from, to, and type. Keep
the existing tokenization and row fields unchanged, ensuring consumers can
access the human-readable description.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17526 +/- ##
=======================================
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:
|
Follow-up to infiniflow#17526 ("Refactor: merge dataset scope graph"), which introduced two code paths that touch Infinity columns the deployed schema does not declare. This PR makes the runtime robust against the old schema while also adding the new column to the new schema so freshly created tables are correct. 1) (ERROR 3013) "Column deleted_doc_id not found in table …" 'record_doc_deletion' writes a 'doc_deleted' marker row with a 'deleted_doc_id' column, but conf/infinity_mapping.json and rag/utils/ob_conn.py's chunk column list never declared it. • conf/infinity_mapping.json: add 'deleted_doc_id' so new tables pick it up. • rag/utils/ob_conn.py: add 'column_deleted_doc_id' so new OB chunk tables pick it up. • rag/utils/infinity_conn.py: add 'ensure_columns', a best-effort helper that calls Infinity 'add_columns' for any columns missing on an existing chunk table (idempotent for already-present ones). • rag/svr/task_executor_refactor/dataset_structure_merger.py: 'record_doc_deletion' now invokes 'ensure_columns' before 'insert' so pre-existing chunk tables get the column in place during the first delete after upgrade. 2) (WARNING 3030) "json_contains(Varchar, Varchar) not found" The migrated JSON-list columns (source_doc_ids, source_chunk_ids, …) emit 'json_contains(col, "<json-literal>")'. On pre-infiniflow#17288 chunk tables those columns are still Varchar (whitespace analyzer, '###'-joined encoding) and Infinity rejects the call. • common/doc_store/infinity_conn_base.py: 'equivalent_condition_to_str' now reads the actual column type from 'table_instance.show_columns()' and falls back to 'filter_fulltext(col, <bare value>)' when the column is Varchar. New JSON tables keep the 'json_contains' path. Unknown-type columns are skipped (better than emitting a query Infinity would reject). 3) (WARNING) "INFINITY get has only blank knowledgebase_ids for index ragflow_doc_meta_<tenant>" 'DocMetadataService.delete_document_metadata' passed ['"] as the 'knowledgebase_ids' for a per-tenant meta table; the connector then built an empty 'f"<index>_<kb>"' list and logged a misleading warning. Two other call sites passed '[kb_id]' for a per-tenant meta table, which under the old code queried a non-existent '<index>_<kb>' table. • rag/utils/infinity_conn.py: 'get' now special-cases 'ragflow_doc_meta_' (like 'index_exist' / 'insert' / 'delete' already do): the meta table is queried by index name only. The empty-list check is hoisted above the connection acquisition so the blank-list case no longer burns a connection from the pool. • api/db/services/doc_metadata_service.py: the three meta-table 'get' call sites now pass '[]' with a comment explaining why. Tests test/unit_test/common/test_infinity_condition.py — 29 cases for the json_contains/filter_fulltext routing in 'equivalent_condition_to_str', including the Varchar and Json paths for every JSON-list column, apostrophe escaping, numeric handling on Json, and the unknown-type skip. test/unit_test/rag/utils/test_infinity_conn_helpers.py — 9 cases for 'InfinityConnection.get' (meta-table routing) and 'InfinityConnection.ensure_columns' (idempotent column upgrade). test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py — 3 cases for 'record_doc_deletion' invoking 'ensure_columns' and 'insert'. test/unit_test/api/db/services/test_doc_metadata_service.py — 2 cases for 'DocMetadataService' metadata get/delete passing empty knowledgebase_ids list.
Follow-up to #17526 ("Refactor: merge dataset scope graph"), which introduced two code paths that touch Infinity columns the deployed schema does not declare. This PR makes the runtime robust against the old schema while also adding the new column to the new schema so freshly created tables are correct.
Summary
merge dataset scope graph.