Skip to content

fix: handle disabled documents in dataset structures - #18033

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b152
Aug 10, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b152

Conversation

@buua436

@buua436 buua436 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 10, 2026
@buua436
buua436 requested a review from wangq8 August 10, 2026 03:22
@buua436 buua436 added the ci Continue Integration label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Graph lifecycle updates

Layer / File(s) Summary
Graph source metadata and filtering
api/apps/services/structure_graph_common.py
Graph projections include document identifiers and source arrays. Bucket and keyword construction exclude rows whose sources are disabled.
Dataset structure deletion and retrieval
api/apps/services/dataset_api_service.py, api/db/services/document_service.py
Dataset-scoped entity and relation rows are deleted with merged graph rows. Retrieval, fallback reconstruction, and eligibility checks exclude disabled documents.
Structure provenance tracking
api/apps/services/dataset_api_service.py
Alteration tracking combines source_doc_ids and doc_ids_kwd, with fallbacks for missing provenance.
Dataset graph rebuilding
rag/advanced_rag/knowlege_compile/structure.py, api/db/services/document_service.py
Dataset-wide rebuilds preserve source document IDs, deduplicate dataset relations, and skip disabled-document rows.
Concurrent structure merging
rag/svr/task_executor_refactor/dataset_structure_merger.py
Embedding and bucket processing use bounded concurrency. Disabled documents trigger full rebuilds, and the index refreshes after processing completes.

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

Possibly related PRs

Suggested labels: 🌈 python

Suggested reviewers: kevinhush, wangq8

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
Loading

Poem

A rabbit checks each graph row,
Disabled sources no longer show.
Batches hop through buckets bright,
One index refresh makes things right.
Provenance trails remain in sight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: handling disabled documents in dataset structures.
Description check ✅ Passed The description explains the problem and lists the related improvements, but it does not use the required Summary heading.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
api/apps/services/structure_graph_common.py (1)

241-317: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d41ebd and 2595eea.

📒 Files selected for processing (4)
  • api/apps/services/dataset_api_service.py
  • api/apps/services/structure_graph_common.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. 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.

  2. 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.

  3. _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.

  4. 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.

  5. 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

codecov Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (99110c2) to head (05661e7).
⚠️ Report is 7 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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 lift

Do 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2595eea and 77d9709.

📒 Files selected for processing (5)
  • api/apps/services/dataset_api_service.py
  • api/apps/services/structure_graph_common.py
  • api/db/services/document_service.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/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

Comment on lines +389 to +398
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, [], []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 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.

Comment on lines +45 to +48
@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()}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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"]
PY

Repository: 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 -200

Repository: 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.py

Repository: 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 -200

Repository: 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))
PY

Repository: 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:


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".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/structure.py (1)

2260-2270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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 win

Log legacy reconstruction failures before continuing.

Lines 2117 and 2124 swallow failures with bare continue, so partial legacy structure builds have no diagnostics. Log the failing compile_kwd/dataset context for the bucket rebuild, and log json.JSONDecodeError for 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

📥 Commits

Reviewing files that changed from the base of the PR and between 58866b2 and 05661e7.

📒 Files selected for processing (2)
  • api/apps/services/dataset_api_service.py
  • rag/advanced_rag/knowlege_compile/structure.py

@wangq8
wangq8 merged commit c0582b8 into infiniflow:main Aug 10, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants