Repository navigation
fix: handle disabled documents in dataset structures - #18033
Conversation
📝 WalkthroughWalkthroughThe change filters disabled-document graph data during retrieval, compilation, and merging. It expands provenance handling, deletes dataset-scoped graph rows, batches embeddings, processes buckets concurrently, and refreshes the index after processing. ChangesGraph lifecycle updates
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant DatasetStructure
participant DocumentService
participant GraphIndex
participant EmbeddingService
DatasetStructure->>DocumentService: load disabled document IDs
DatasetStructure->>GraphIndex: retrieve eligible graph rows
DatasetStructure->>EmbeddingService: embed merged entity and relation batches
DatasetStructure->>GraphIndex: write merged structures
DatasetStructure->>GraphIndex: refresh index after processing
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
api/apps/services/structure_graph_common.py (1)
241-317: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd aggregate logging for disabled-document processing.
Log the disabled-document count and filtered-row count for each rebuild or retrieval flow. Do not log document IDs. This makes incorrect filtering observable without exposing identifiers.
api/apps/services/structure_graph_common.py#L241-L317: count rows excluded while building each graph bucket.api/apps/services/dataset_api_service.py#L1848-L2052: log the disabled-document count used for structure retrieval.rag/advanced_rag/knowlege_compile/structure.py#L2228-L2249: log the disabled-document and skipped-row counts for dataset graph rebuilds.rag/svr/task_executor_refactor/dataset_structure_merger.py#L779-L780: log the skipped-row count during structure merging.As per coding guidelines, add logging for new flows.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/services/structure_graph_common.py` around lines 241 - 317, Add aggregate disabled-document processing logs without emitting document IDs: in api/apps/services/structure_graph_common.py:241-317, update build_bucket to count rows rejected by _row_has_enabled_source and log the disabled-document and filtered-row counts for each bucket build; in api/apps/services/dataset_api_service.py:1848-2052, log the disabled-document count used by structure retrieval; in rag/advanced_rag/knowlege_compile/structure.py:2228-2249, log disabled-document and skipped-row counts during dataset graph rebuilds; in rag/svr/task_executor_refactor/dataset_structure_merger.py:779-780, log the skipped-row count during structure merging, using the established logging facilities.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 `@api/apps/services/dataset_api_service.py`:
- Line 1848: Update get_dataset_structure to apply disabled_doc_ids to both the
template-less dataset_graph blob path and the keywords path, preventing entities
and relations from disabled documents from being returned. When rebuilding
legacy data, pass excluded_doc_ids into build_bucket() and keyword_subgraph()
wherever raw rows are selected, using _disabled_dataset_doc_ids or the existing
source-row lookup.
In `@api/apps/services/structure_graph_common.py`:
- Line 294: Update the query feeding set_a so enabled-source eligibility is
applied before the GRAPH_TOP_ENTITIES limit, or continue fetching pages until
GRAPH_TOP_ENTITIES eligible entities are collected. Preserve the existing
project_entity conversion and excluded_doc_ids validation while ensuring
disabled-document rows cannot consume the sample cap.
- Around line 244-250: Update the provenance filtering logic around source_ids
to read and normalize both doc_ids_kwd and source_doc_ids, combining their
values before checking excluded_doc_ids. Preserve support for scalar strings and
iterable collections, and return enabled when any combined ID is not excluded.
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2232-2243: Move the blocking disabled-document queries off the
event loop: in rag/advanced_rag/knowlege_compile/structure.py:2232-2243, execute
DocumentService.get_by_kb_id through thread_pool_exec while preserving
disabled_doc_ids filtering; in
rag/svr/task_executor_refactor/dataset_structure_merger.py:199-213, make
_disabled_doc_ids async and use thread_pool_exec for the same query; update
_run_structure_merge and its caller at
rag/svr/task_executor_refactor/dataset_structure_merger.py:907 to await
_disabled_doc_ids.
---
Nitpick comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 241-317: Add aggregate disabled-document processing logs without
emitting document IDs: in api/apps/services/structure_graph_common.py:241-317,
update build_bucket to count rows rejected by _row_has_enabled_source and log
the disabled-document and filtered-row counts for each bucket build; in
api/apps/services/dataset_api_service.py:1848-2052, log the disabled-document
count used by structure retrieval; in
rag/advanced_rag/knowlege_compile/structure.py:2228-2249, log disabled-document
and skipped-row counts during dataset graph rebuilds; in
rag/svr/task_executor_refactor/dataset_structure_merger.py:779-780, log the
skipped-row count during structure merging, using the established logging
facilities.
🪄 Autofix
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: b4539b9c-138f-4767-ab1d-3f758179033e
📒 Files selected for processing (4)
api/apps/services/dataset_api_service.pyapi/apps/services/structure_graph_common.pyrag/advanced_rag/knowlege_compile/structure.pyrag/svr/task_executor_refactor/dataset_structure_merger.py
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this PR! Good overall direction — handling disabled documents across dataset structures was definitely a gap. Some feedback:
Strengths:
- The disabled-document filtering is applied consistently across the full pipeline: graph view (get_dataset_structure), rebuild (_struct_rebuild_graph_json), merge (_do_build), alter detection (_current_dataset_docs, _eligible_doc_ids_for_kind), and provenance (_involved_doc_ids_paged).
- Batched embedding (_embed_rows) with a semaphore-based concurrency cap significantly reduces the serial bottleneck that existed in the old per-row encode loop.
- Concurrent bucket merging via _merge_buckets + asyncio.gather is a nice complement to the batching change.
- The rebuild_all trigger when disabled docs exist is the correct semantic — shared entities/relations need recalculation without the disabled document's data.
- Suppressing refresh on bulk inserts and doing one final refresh is a meaningful ES performance win.
Concerns / Suggestions:
-
Duplicated _disabled_doc_ids helper — The same logic appears in three places: dataset_structure_merger.py:_disabled_doc_ids, dataset_api_service.py:_disabled_dataset_doc_ids, and inline in structure.py:_struct_rebuild_graph_json. Consider extracting a shared utility (e.g. in document_service.py or a common helper) to avoid drift.
-
inspect.signature for refresh detection (dataset_structure_merger.py:161) — This is fragile. The refresh parameter exists in both the ES8 connector and the Infinity connector but might differ across backends. Using getattr with a default or a try/except at import time (caching the capability) would be more robust and avoids calling inspect.signature on every insert call.
-
_row_has_enabled_source fallthrough (structure_graph_common.py:255: "return not doc_id or ...") — When doc_id is absent the function returns True, meaning rows without any document association are never filtered. This is probably the correct default for safety, but it is worth documenting explicitly — a row with no provenance fields at all will pass through silently, which could hide data issues in production.
-
build_bucket large-bucket path — The small-bucket path (total below threshold) has the disabled-doc filter applied to all rows. The large-bucket sampling path applies it to top entities (set_a) and target entities (set_t), but the relation fetch is filtered only by source-entity membership (a_name_terms), not by document eligibility. Relations whose source entity passed the filter could still belong to disabled docs if those docs share entity names. This edge case is probably rare but worth noting.
-
The doc_ids_kwd field is now read alongside source_doc_ids in _involved_doc_ids_paged — this is correct and matches the merge code which writes both fields, but make sure the alter-check for mindmap and timeline kinds also picks up the right provenance field, since those stored rows may use different field naming.
Overall this is a solid fix. I would prioritize addressing concern #1 (deduplication) and #2 (inspect.signature) before merging. The rest can be follow-ups.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18033 +/- ##
==========================================
- Coverage 94.56% 90.65% -3.91%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 650 -28
- Misses 25 39 +14
- Partials 14 28 +14 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/services/structure_graph_common.py (1)
331-344: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftDo not let disabled rows consume
GRAPH_EXPANSION_CAP.The relation and neighbor queries apply the raw-row limit before
_row_has_enabled_source. Disabled rows can fill the cap, so enabled relations or target entities are omitted. Fetch enough rows to collect the enabled-result cap, or apply source eligibility in the document-store query. Add a regression test with disabled rows ahead of enabled rows.Also applies to: 415-433
🤖 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/structure_graph_common.py` around lines 331 - 344, Ensure relation and target-entity collection does not let rows rejected by _row_has_enabled_source consume GRAPH_EXPANSION_CAP: either push source eligibility into graph_search or fetch additional rows until the enabled results reach the cap. Apply this to the relation query and the target query around project_relation/project_entity, preserving the cap on enabled results, and add a regression test with disabled rows preceding enabled rows.
🧹 Nitpick comments (1)
api/apps/services/structure_graph_common.py (1)
304-321: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd bounded logging to both new disabled-document paths.
The new graph sampling path and disabled-document lookup have no diagnostic summary. Add debug-level logs without logging document ID values.
api/apps/services/structure_graph_common.py#L304-L321: log pages or rows scanned and accepted entity count after sampling.api/db/services/document_service.py#L45-L48: log the knowledge-base ID and disabled-document count after the lookup.🤖 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/structure_graph_common.py` around lines 304 - 321, Add bounded debug-level summaries to both disabled-document paths: in the graph sampling loop around graph_search, log pages or rows scanned and the accepted entity count after sampling; in the disabled-document lookup in document_service.py, log the knowledge-base ID and disabled-document count after retrieval. Do not include document ID values in either log, and update both specified files: api/apps/services/structure_graph_common.py lines 304-321 and api/db/services/document_service.py lines 45-48.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 `@api/apps/services/structure_graph_common.py`:
- Around line 389-398: Update the KNN retrieval flow around graph_search and
_row_has_enabled_source so disabled candidates do not exhaust the
GRAPH_TOP_ENTITIES window before eligibility filtering. Filter eligible rows
before applying the limit, or continue paging/expanding retrieval until an
enabled entity is found, while preserving the existing empty-result behavior
when no eligible entity exists.
In `@api/db/services/document_service.py`:
- Around line 45-48: Update DocumentService.get_disabled_doc_ids_by_kb_id to
extract the scalar document ID from each single-column row returned by tuples(),
rather than stringifying the entire tuple. Preserve the set[str] return type so
consumers receive values such as "disabled-doc".
---
Outside diff comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 331-344: Ensure relation and target-entity collection does not let
rows rejected by _row_has_enabled_source consume GRAPH_EXPANSION_CAP: either
push source eligibility into graph_search or fetch additional rows until the
enabled results reach the cap. Apply this to the relation query and the target
query around project_relation/project_entity, preserving the cap on enabled
results, and add a regression test with disabled rows preceding enabled rows.
---
Nitpick comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 304-321: Add bounded debug-level summaries to both
disabled-document paths: in the graph sampling loop around graph_search, log
pages or rows scanned and the accepted entity count after sampling; in the
disabled-document lookup in document_service.py, log the knowledge-base ID and
disabled-document count after retrieval. Do not include document ID values in
either log, and update both specified files:
api/apps/services/structure_graph_common.py lines 304-321 and
api/db/services/document_service.py lines 45-48.
🪄 Autofix
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: 92a034f0-de9d-4034-9351-7e51a6684c09
📒 Files selected for processing (5)
api/apps/services/dataset_api_service.pyapi/apps/services/structure_graph_common.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 (3)
- rag/advanced_rag/knowlege_compile/structure.py
- rag/svr/task_executor_refactor/dataset_structure_merger.py
- api/apps/services/dataset_api_service.py
| topn=GRAPH_TOP_ENTITIES, | ||
| extra_options={"similarity": 0.0}, | ||
| ) | ||
| top_fields = GRAPH_ENTITY_FIELDS + ["compilation_template_ids", "compile_kwd", "compilation_template_kind_kwd"] | ||
| top_map, _ = await graph_search(index_name, kb_id, top_fields, base_entity_condition, OrderByExpr(), 1, match_expressions=[match_expr]) | ||
| top_map, _ = await graph_search(index_name, kb_id, top_fields, base_entity_condition, OrderByExpr(), GRAPH_TOP_ENTITIES, match_expressions=[match_expr]) | ||
| if not top_map: | ||
| return None, [], [] | ||
| top_row = next(iter(top_map.values())) | ||
| top_row = next((row for row in top_map.values() if _row_has_enabled_source(row, excluded_doc_ids)), None) | ||
| if top_row is None: | ||
| return None, [], [] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Continue KNN retrieval after disabled candidates.
The KNN query returns only GRAPH_TOP_ENTITIES candidates before _row_has_enabled_source runs. If those candidates are all disabled, the function returns no subgraph even when an enabled match exists below the candidate window. Apply eligibility before the limit, or expand/page the candidate window until an enabled entity is found.
🧰 Tools
🪛 Ruff (0.16.1)
[warning] 392-392: Consider iterable unpacking instead of concatenation
Replace with iterable unpacking
(RUF005)
🤖 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/structure_graph_common.py` around lines 389 - 398, Update
the KNN retrieval flow around graph_search and _row_has_enabled_source so
disabled candidates do not exhaust the GRAPH_TOP_ENTITIES window before
eligibility filtering. Filter eligible rows before applying the limit, or
continue paging/expanding retrieval until an enabled entity is found, while
preserving the existing empty-result behavior when no eligible entity exists.
| @classmethod | ||
| @DB.connection_context() | ||
| def get_disabled_doc_ids_by_kb_id(cls, kb_id) -> set[str]: | ||
| return {str(doc_id) for doc_id in cls.model.select(cls.model.id).where((cls.model.kb_id == kb_id) & (cls.model.status == "0")).tuples()} |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python - <<'PY'
from peewee import Model, SqliteDatabase, TextField
db = SqliteDatabase(":memory:")
class Document(Model):
id = TextField(primary_key=True)
kb_id = TextField()
status = TextField()
class Meta:
database = db
db.create_tables([Document])
Document.create(id="disabled-doc", kb_id="kb", status="0")
def query():
return Document.select(Document.id).where(
(Document.kb_id == "kb") & (Document.status == "0")
)
assert list(query().tuples()) == [("disabled-doc",)]
assert list(query().scalars().iterator()) == ["disabled-doc"]
PYRepository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate and inspect the relevant service function and related usages around document IDs.
fd -a 'document_service.py' . | sed 's#^\./##' | while read -r f; do
echo "=== $f ==="
wc -l "$f"
sed -n '1,80p' "$f"
sed -n '1000,1035p' "$f"
done
echo "=== usages of get_disabled_doc_ids_by_kb_id ==="
rg -n "get_disabled_doc_ids_by_kb_id|disabled_doc_ids|disabled.*doc" . --glob '*.py' | head -200Repository: infiniflow/ragflow
Length of output: 10382
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Peewee version ==="
python - <<'PY'
import peewee
try:
print(peewee.__version__)
except Exception as e:
print(type(e).__name__, e)
PY
echo "=== Check installed peewee Query.select return/type if available ==="
python - <<'PY'
from peewee import Model, SqliteDatabase, TextField
db = SqliteDatabase(":memory:")
class Document(Model):
id = TextField(primary_key=True)
kb_id = TextField()
status = TextField()
class Meta:
database = db
db.create_tables([Document])
Document.create(id="doc", kb_id="kb", status="0")
q = Document.select(Document.id).where((Document.kb_id == "kb") & (Document.status == "0"))
print("query type:", type(q).__name__)
print("tuple result:", list(q.tuples()))
print("scalar type:", type(q.scalars()).__name__)
cols = q.columns
print("columns:", list(cols) if cols else "None")
if cols:
query = q.map_tuple(*cols)
print("mapped scalar result:", list(query.iterator()) if hasattr(query, "iterator") else list(query))
PY
echo "=== inspect consumers around str(row.get(...) ==="
sed -n '2220,2242p' rag/advanced_rag/knowlege_compile/structure.py
sed -n '204,216p' rag/svr/task_executor_refactor/dataset_structure_merger.py
sed -n '770,782p' rag/svr/task_executor_refactor/dataset_structure_merger.py
sed -n '1836,1860p' api/apps/services/dataset_api_service.py
sed -n '2090,2105p' api/apps/services/dataset_api_service.pyRepository: infiniflow/ragflow
Length of output: 444
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== get_get_model_id.py ==="
fd -a 'get_model_id.py' api . | sed 's#^\./##' | while read -r f; do
echo "--- $f"
wc -l "$f"
sed -n '1,180p' "$f"
done
echo "=== model_id usages ==="
rg -n "get_model_id\(|model_id|disabled_dataset_doc_ids|_disabled_doc_ids" api rag --glob '*.py' | head -200Repository: infiniflow/ragflow
Length of output: 14445
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== exact references in consumers ==="
rg -n "if str\\(row.get\\(\"doc_id\"\\) or \"\"\\) in disabled_doc_ids|if row.get\\(\"doc_id\"\\) or \"\" in disabled_doc_ids|in disabled_doc_ids" rag/advanced_rag/knowlege_compile/structure.py rag/svr/task_executor_refactor/dataset_structure_merger.py api/apps/services/dataset_api_service.py
echo "=== inspect row/document data shape in consumers ==="
sed -n '2234,2242p' rag/advanced_rag/knowlege_compile/structure.py
sed -n '776,782p' rag/svr/task_executor_refactor/dataset_structure_merger.py
sed -n '2086,2104p' api/apps/services/dataset_api_service.py
echo "=== peewee installed source hints if present ==="
python - <<'PY'
import inspect, peewee
for name in ("get_model_id", "scalars", "tuples", "__iter__"):
obj = getattr(peewee.ModelSelect if hasattr(peewee, "ModelSelect") else object, name, None)
if not obj:
print(name, "not found on ModelSelect")
continue
print(f"--- {name} ---")
print(inspect.getsourcefile(obj))
PYRepository: infiniflow/ragflow
Length of output: 2753
🌐 Web query:
Peewee 3.19 ModelSelect scalars tuples get_model_id
💡 Result:
In Peewee (including 3.19.x), ModelSelect row “scalars/tuples” won’t magically provide get_model_id. What you use instead depends on what you’re trying to fetch: 1) Getting scalar/tuple results - Query.scalar executes a select and returns the first selected column of the first row as a Python value.[1] - If you need multiple scalar columns, use scalar(as_tuple=True).[1] - For row-wise tuples (multiple columns per row), iterate over a Select query chained with.tuples.[2] 2) Getting a model instance’s primary key (“model id”) - Model instances have a get_id method that returns the primary-key of that instance.[3] - If you’re iterating rows as tuples/dicts (not as model instances), then get_id is not applicable; you should select the id column in SQL and read it from the tuple directly. 3) Getting the raw ForeignKey id (e.g., user_id) without extra queries - Peewee exposes the raw FK integer value via an “_id” accessor: if you have a ForeignKeyField named user, then tweet.user_id gives the underlying integer ID value without extra query.[4] - This is the mechanism you typically want when you say “get_model_id” in the context of a foreign-key relationship. Example patterns (conceptual) - Scalar aggregation: total = Model.select(fn.SUM(Model.amount)).scalar[1] (min_v, max_v) = Model.select(fn.MIN(Model.amount), fn.MAX(Model.amount)).scalar(as_tuple=True)[1] - Tuple rows: for (id_value, name) in Model.select(Model.id, Model.name).tuples:... # id_value is the primary key column - Model instance primary key: obj = Model.get(Model.some_field == x) obj.get_id # returns the instance primary key[3] - ForeignKey raw id: for tweet in Tweet.select: tweet.user_id # raw integer foreign key value (no join/query for User)[4] If you share the exact snippet you’re using (especially what you call “get_model_id” on, and whether you’re using.scalar/.tuples/.objects), I can map it precisely to the correct Peewee 3.19 idiom.
Citations:
- 1: https://github.com/coleifer/peewee/blob/master/docs/peewee/querying.rst
- 2: https://docs.peewee-orm.com/en/latest/peewee/querying.html
- 3: https://docs.peewee-orm.com/en/latest/peewee/api.html
- 4: https://peewee.readthedocs.io/en/latest/peewee/models.html
Return tuple IDs from disabled document rows.
get_disabled_doc_ids_by_kb_id() returns the one-element tuple from .tuples(), so disabled-doc filters compare row "doc_id" strings against "('disabled-doc',)". Use the tuple value, e.g. next(iter(row)) or unpack the single column, so the consumers see "disabled-doc".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/db/services/document_service.py` around lines 45 - 48, Update
DocumentService.get_disabled_doc_ids_by_kb_id to extract the scalar document ID
from each single-column row returned by tuples(), rather than stringifying the
entire tuple. Preserve the set[str] return type so consumers receive values such
as "disabled-doc".
There was a problem hiding this comment.
🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/structure.py (1)
2260-2270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd an exclusion summary log.
This new rebuild path suppresses rows from disabled documents. Add one debug log after the loop. Include
kb_id,compile_kwd, and the skipped-row count. Do not log document content.As per coding guidelines, “
**/*.py: 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 `@rag/advanced_rag/knowlege_compile/structure.py` around lines 2260 - 2270, Add a debug log immediately after the rows loop in the rebuild path, using the existing logger and reporting kb_id, compile_kwd, and the count of rows skipped because their document IDs are disabled. Track that count in the loop without logging document content.Source: Coding guidelines
api/apps/services/dataset_api_service.py (1)
2117-2125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog legacy reconstruction failures before continuing.
Lines 2117 and 2124 swallow failures with bare
continue, so partial legacy structure builds have no diagnostics. Log the failingcompile_kwd/dataset context for the bucket rebuild, and logjson.JSONDecodeErrorfor invalid legacy blobs.🤖 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 2117 - 2125, Update the exception handlers in the legacy bucket rebuild flow to log failures before continuing: include the relevant compile_kwd and dataset context when entity/relation reconstruction fails, and catch/log json.JSONDecodeError with the invalid legacy blob context before skipping it. Preserve the existing continue behavior after logging.Sources: Coding guidelines, Linters/SAST tools
🤖 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 2117-2125: Update the exception handlers in the legacy bucket
rebuild flow to log failures before continuing: include the relevant compile_kwd
and dataset context when entity/relation reconstruction fails, and catch/log
json.JSONDecodeError with the invalid legacy blob context before skipping it.
Preserve the existing continue behavior after logging.
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2260-2270: Add a debug log immediately after the rows loop in the
rebuild path, using the existing logger and reporting kb_id, compile_kwd, and
the count of rows skipped because their document IDs are disabled. Track that
count in the loop without logging document content.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fe0c671d-014f-4271-97fd-55e1903b956e
📒 Files selected for processing (2)
api/apps/services/dataset_api_service.pyrag/advanced_rag/knowlege_compile/structure.py
What problem does this PR solve?
Improve knowledge-base graph, timeline, and mindmap generation by batching concurrent embeddings, reducing Elasticsearch refresh overhead, correctly handling dataset-level deletion and alteration detection, and excluding disabled documents from viewing and rebuilding.
Type of change