Skip to content

fix: support Infinity knowledge compilation - #17288

Merged
yingfeng merged 9 commits into
infiniflow:mainfrom
buua436:b121
Jul 23, 2026
Merged

yingfeng merged 9 commits into
infiniflow:mainfrom
buua436:b121

Conversation

@buua436

@buua436 buua436 commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix Infinity compatibility issues in knowledge compilation.

This change:

  • Stores compilation source ID lists as JSON arrays in Infinity.
  • Parses JSON array fields when reading compiled documents.
  • Uses json_contains for filtering JSON array fields.
  • Adds the missing name column to the Infinity mapping.
  • Updates dataset navigation KNN search to use the unified MatchDenseExpr interface.
  • Handles unavailable embeddings without querying an invalid q_0_vec field.

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. ♾️infinity Pull requests that‘s involved with infinity(DB) 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 23, 2026
@buua436 buua436 added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. 🌈 python Pull requests that update Python code ♾️infinity Pull requests that‘s involved with infinity(DB) labels Jul 23, 2026
@buua436
buua436 requested review from qinling0210 and wangq8 July 23, 2026 07:41
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change converts Infinity metadata fields to JSON arrays with compatible storage and query handling. Dataset navigation uses direct cosine KNN retrieval and handles empty embeddings, while document ingest deduplicates identical in-flight requests.

Changes

JSON Fields and Dataset Navigation

Layer / File(s) Summary
JSON identifier field storage
conf/infinity_mapping.json, rag/utils/infinity_conn.py, docker/.env
Metadata fields use JSON array schemas, JSON serialization and decoding, legacy fallback support, and Infinity becomes the default document engine.
JSON identifier predicates
common/doc_store/infinity_conn_base.py
Identifier conditions produce parenthesized json_contains predicates joined with OR.
Dataset navigation KNN flow
rag/advanced_rag/knowlege_compile/dataset_nav.py
KNN lookup uses MatchDenseExpr, vector dimensions come from embedding length, and empty embeddings skip cluster lookup with neutral results.

Document Ingest Request Deduplication

Layer / File(s) Summary
In-flight ingest request deduplication
web/src/hooks/use-document-request.ts
Identical document ingest calls share an in-flight promise, which is removed after completion or failure.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Sequence Diagram(s)

sequenceDiagram
  participant upsert_dataset_nav_doc
  participant _find_best_cluster
  participant docStoreConn
  upsert_dataset_nav_doc->>_find_best_cluster: non-empty doc_embedding
  _find_best_cluster->>docStoreConn: search with MatchDenseExpr
  docStoreConn-->>_find_best_cluster: top-k cosine matches
  _find_best_cluster-->>upsert_dataset_nav_doc: best cluster and similarity
Loading

Possibly related PRs

Suggested reviewers: magicbook1108, asiroliu, jinhai-cn

Poem

I hop through JSON fields, neat and bright,
Cosine carrots guide the flight.
Empty vectors take a rest,
Shared requests avoid a quest.
Squeak—the data flows just right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: improving Infinity support for knowledge compilation.
Description check ✅ Passed The description explains the problem, lists the main fixes, and gives the change type, which is sufficient for this template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Checkov (3.3.8)
conf/infinity_mapping.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'


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 (3)
rag/advanced_rag/knowlege_compile/dataset_nav.py (1)

549-558: 🩺 Stability & Availability | 🔵 Trivial

LGTM on the empty-embedding guard — it correctly prevents _find_best_cluster/_store_knn from being invoked with vec_dim=0 (which would target the invalid q_0_vec field), and the warning satisfies the logging-for-new-flows guideline.

One operational note: since best_name stays None here, execution falls through to the root-cluster-creation branch (Line 641+) for every doc lacking an embedding, so repeated embedding failures will create one new root cluster per doc rather than merging. Worth keeping an eye on if embedding failures become frequent in production.

As per coding guidelines, "Add logging for new flows" is satisfied by the logging.warning at Line 557.

🤖 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/dataset_nav.py` around lines 549 - 558, The
empty-embedding path in the document cluster-placement flow intentionally skips
KNN and falls through to root-cluster creation, which can create a separate root
for every document. Review the branch following `_find_best_cluster` in the
surrounding document-processing function and update the no-embedding handling to
avoid repeated root creation, while preserving the existing warning and valid
embedding-based placement behavior.

Source: Coding guidelines

common/doc_store/infinity_conn_base.py (1)

307-315: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add diagnostic logging for the new JSON predicate path.

This branch changes filter construction but emits no signal when a JSON-list predicate is generated. Log the field and number of values—not the identifier contents—at debug level so rollout mismatches can be diagnosed.

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 `@common/doc_store/infinity_conn_base.py` around lines 307 - 315, In the JSON
predicate branch of the filter-building method, add a debug log when generating
predicates that records the field name and count of values, without logging
identifier contents. Use the module’s existing logging convention and keep the
current condition construction unchanged.

Source: Coding guidelines

rag/utils/infinity_conn.py (1)

29-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Centralize the JSON-list field registry.

The same three field names are hardcoded in common/doc_store/infinity_conn_base.py Lines 307-315. Keep one private shared constant for storage, decoding, and predicates so future fields cannot be added to only one layer.

🤖 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/utils/infinity_conn.py` around lines 29 - 31, Replace the local JSON-list
field registry near _JSON_LIST_FIELDS with a single private shared constant used
by both rag/utils/infinity_conn.py and common/doc_store/infinity_conn_base.py.
Update storage, decoding, and predicate logic to reference that shared registry,
preserving the existing three field names and preventing layer-specific
additions.
🤖 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 `@conf/infinity_mapping.json`:
- Around line 47-49: Add a versioned migration before enabling the updated
mapping schema to find existing varchar identifier columns, recreate or alter
them to the JSON type, and backfill legacy ### values into valid JSON arrays.
Integrate it with the existing migration mechanism and ensure it runs for
existing tables before JSON writes or json_contains filters are used.

In `@rag/utils/infinity_conn.py`:
- Around line 465-466: Update the JSON-list encoding used by both insert and
update, including the branches around _JSON_LIST_FIELDS, to share one
validator/encoder rather than converting unsupported values to []. Accept list,
tuple, set, and explicit None for clearing; log and reject strings, malformed
values, and other unsupported shapes. Preserve valid identifier serialization
and add logging for the rejection path.
- Around line 583-584: Update the remove-path write around the `{k:
"###".join(v)}` construction to use the same JSON encoding applied by the
`_JSON_LIST_FIELDS` branch, preserving valid JSON for affected columns so
subsequent `json_contains` filters and updates continue to work.
- Around line 802-816: Update the local parse_json_list function in the
_JSON_LIST_FIELDS branch to accept only JSON arrays; route scalar or malformed
values through the legacy ### string fallback so identifiers become strings, and
add logging for fallback/malformed decoding without including identifier
contents.

---

Nitpick comments:
In `@common/doc_store/infinity_conn_base.py`:
- Around line 307-315: In the JSON predicate branch of the filter-building
method, add a debug log when generating predicates that records the field name
and count of values, without logging identifier contents. Use the module’s
existing logging convention and keep the current condition construction
unchanged.

In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 549-558: The empty-embedding path in the document
cluster-placement flow intentionally skips KNN and falls through to root-cluster
creation, which can create a separate root for every document. Review the branch
following `_find_best_cluster` in the surrounding document-processing function
and update the no-embedding handling to avoid repeated root creation, while
preserving the existing warning and valid embedding-based placement behavior.

In `@rag/utils/infinity_conn.py`:
- Around line 29-31: Replace the local JSON-list field registry near
_JSON_LIST_FIELDS with a single private shared constant used by both
rag/utils/infinity_conn.py and common/doc_store/infinity_conn_base.py. Update
storage, decoding, and predicate logic to reference that shared registry,
preserving the existing three field names and preventing layer-specific
additions.
🪄 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: b9bcca19-183e-47cb-97ed-f58455a9e862

📥 Commits

Reviewing files that changed from the base of the PR and between e3e2d0a and 09275a6.

📒 Files selected for processing (4)
  • common/doc_store/infinity_conn_base.py
  • conf/infinity_mapping.json
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/utils/infinity_conn.py

Comment thread conf/infinity_mapping.json Outdated
Comment on lines +47 to +49
"source_chunk_ids": {"type": "json", "default": "[]"},
"source_doc_ids": {"type": "json", "default": "[]"},
"compilation_template_ids": {"type": "json", "default": "[]"},

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 | 🏗️ Heavy lift

Add a migration for existing varchar identifier columns.

These mapping changes only affect newly created tables. common/doc_store/infinity_conn_base.py only adds missing columns at Lines 210-216; it does not alter existing column types or backfill legacy ### values. Existing tables can therefore remain varchar while the new code writes JSON and filters with json_contains, causing incorrect or failed queries. Add a versioned backfill/recreation migration before enabling this schema.

🤖 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 `@conf/infinity_mapping.json` around lines 47 - 49, Add a versioned migration
before enabling the updated mapping schema to find existing varchar identifier
columns, recreate or alter them to the JSON type, and backfill legacy ### values
into valid JSON arrays. Integrate it with the existing migration mechanism and
ensure it runs for existing tables before JSON writes or json_contains filters
are used.

Comment thread rag/utils/infinity_conn.py Outdated
Comment on lines +465 to +466
elif k in _JSON_LIST_FIELDS:
d[k] = json.dumps(list(v) if isinstance(v, (list, tuple, set)) else [], ensure_ascii=False)

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

Reject unsupported values instead of silently clearing identifiers.

Both branches convert every non-list/tuple/set value to []. A legacy/pre-serialized string or malformed value can therefore erase all identifiers without an error. Validate the input shape, allow None only for an explicit clear operation, and log then reject unsupported values rather than silently losing data. Share the encoder between insert and update.

As per coding guidelines: **/*.py: Add logging for new flows.

Proposed validation shape
- d[k] = json.dumps(list(v) if isinstance(v, (list, tuple, set)) else [], ensure_ascii=False)
+ if v is None:
+     values = []
+ elif isinstance(v, (list, tuple, set)):
+     values = list(v)
+ else:
+     self.logger.warning("Unsupported JSON-list value for field %s", k)
+     raise TypeError(f"{k} must be a list-like value")
+ d[k] = json.dumps(values, ensure_ascii=False)

Also applies to: 583-584

🧰 Tools
🪛 ast-grep (0.44.1)

[info] 465-465: use jsonify instead of json.dumps for JSON output
Context: json.dumps(list(v) if isinstance(v, (list, tuple, set)) else [], 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/utils/infinity_conn.py` around lines 465 - 466, Update the JSON-list
encoding used by both insert and update, including the branches around
_JSON_LIST_FIELDS, to share one validator/encoder rather than converting
unsupported values to []. Accept list, tuple, set, and explicit None for
clearing; log and reject strings, malformed values, and other unsupported
shapes. Preserve valid identifier serialization and add logging for the
rejection path.

Source: Coding guidelines

Comment thread rag/utils/infinity_conn.py Resolved
Comment thread rag/utils/infinity_conn.py Outdated
Comment on lines +802 to +816
elif k in _JSON_LIST_FIELDS:

def parse_json_list(value):
if isinstance(value, list):
return value
if not value:
return []
try:
parsed = json.loads(value)
return parsed if isinstance(parsed, list) else [parsed]
except (TypeError, json.JSONDecodeError):
# Read rows written by the previous varchar encoding.
return [item for item in str(value).split("###") if item]

res2[column] = res2[column].apply(parse_json_list)

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 | 🟡 Minor | ⚡ Quick win

Do not treat scalar JSON as a valid identifier list.

For a legacy single value such as 123, json.loads returns an integer and this code produces [123] instead of ["123"], so string-ID lookups can miss the row. Only accept parsed lists; otherwise use the legacy ### fallback (or reject malformed data). Log fallback/malformed decoding without logging the identifier contents.

As per coding guidelines: **/*.py: Add logging for new flows.

Proposed fix
- return parsed if isinstance(parsed, list) else [parsed]
+ if isinstance(parsed, list):
+     return parsed
+ return [item for item in str(value).split("###") if item]
🤖 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/utils/infinity_conn.py` around lines 802 - 816, Update the local
parse_json_list function in the _JSON_LIST_FIELDS branch to accept only JSON
arrays; route scalar or malformed values through the legacy ### string fallback
so identifiers become strings, and add logging for fallback/malformed decoding
without including identifier contents.

Source: Coding guidelines

@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. The approach of using native JSON arrays in Infinity for compilation ID lists is the right direction. Here are my observations:

What works well:

  • JSON array serialization in insert() / update() and deserialization in get_fields() is cleanly implemented.
  • The backward-compatible parse_json_list fallback (trying json.loads, then ###-splitting for old varchar rows) is a nice touch.
  • Guarding against unavailable embeddings in upsert_dataset_nav_doc avoids a real crash path — good fix.
  • Using MatchDenseExpr directly instead of the try/except fallback is cleaner and removes an error-silencing anti-pattern.

Concerns / suggestions:

  1. Migration path for existing Infinity instances: The schema changes (3 columns from varchar to json + new name column) will break existing Infinity tables that already have data. Users will get errors on the next insert/search against those columns. At minimum this needs a doc note; ideally a migration step that alters the column types or a versioned mapping file.

  2. name column placement: The new name column in infinity_mapping.json is added between docnm and name_kwd with analyzer whitespace-#. But name_kwd appears to be the keyword/tokenized variant of name. Are there any code paths that write to name? If name values are always routed through name_kwd today, this column might be unused. Worth double-checking.

  3. Function-level imports: MatchDenseExpr and OrderByExpr are imported inside _store_knn rather than at module level. If there is no circular import issue, moving them to the top of the module would be preferred.

No blocking issues — LGTM overall.

@buua436 buua436 closed this Jul 23, 2026
@buua436 buua436 reopened this Jul 23, 2026
Comment thread conf/infinity_mapping.json Outdated
"source_chunk_ids": {"type": "varchar", "default": "", "analyzer": "whitespace-#"},
"source_doc_ids": {"type": "varchar", "default": "", "analyzer": "whitespace-#"},
"compilation_template_ids": {"type": "varchar", "default": "", "analyzer": "whitespace-#"},
"source_chunk_ids": {"type": "json", "default": "[]"},

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.

It is better that we create secondary index (low cardinality) on the json column.

Refer to
"available_int": {"type": "integer", "default": 1, "index_type": {"type": "secondary", "cardinality": "low"}},

@buua436 buua436 closed this Jul 23, 2026
@buua436 buua436 reopened this Jul 23, 2026
@buua436
buua436 marked this pull request as draft July 23, 2026 09:13
@buua436
buua436 marked this pull request as ready for review July 23, 2026 09:13
@dosubot dosubot Bot added ♾️infinity Pull requests that‘s involved with infinity(DB) 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 23, 2026
@buua436
buua436 marked this pull request as draft July 23, 2026 09:28
@buua436
buua436 marked this pull request as ready for review July 23, 2026 09:28
@buua436
buua436 marked this pull request as draft July 23, 2026 09:30
@buua436
buua436 marked this pull request as ready for review July 23, 2026 09:30
@codecov

codecov Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (8af2467) to head (0432e8c).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17288   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

@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

🧹 Nitpick comments (1)
common/doc_store/infinity_conn_base.py (1)

307-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for the new JSON predicate path.

This branch changes query construction for nine fields but currently provides no trace when values are normalized or emitted. Add a debug log containing the field name and value count, without logging identifiers or raw SQL, so Infinity filter mismatches can be diagnosed safely.

As per coding guidelines, **/*.py: Add logging for new flows.

Suggested change
                 values = v if isinstance(v, list) else [v]
+                self.logger.debug("Infinity JSON filter field=%s value_count=%d", k, len(values))
                 json_conditions = []
🤖 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 `@common/doc_store/infinity_conn_base.py` around lines 307 - 324, Add a debug
log within the JSON predicate branch before constructing predicates, recording
the field name k and the normalized values count, while excluding item
identifiers, raw values, and generated SQL. Use the module’s existing logging
mechanism and keep the json_conditions construction unchanged.

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/utils/infinity_conn.py`:
- Around line 457-458: Centralize JSON-list validation and serialization in a
shared encoder, accepting list-like values and explicit None for intentional
clearing while logging or rejecting unsupported shapes instead of replacing them
with []. Update the insert path at rag/utils/infinity_conn.py:457-458 and the
update path at rag/utils/infinity_conn.py:598-599 to call this encoder
consistently.

In `@web/src/hooks/use-document-request.ts`:
- Around line 400-404: Canonicalize params.option before constructing the
JSON.stringify key in the deduplication logic around documentIds, run, and
option. Ensure option object properties are serialized in a deterministic order
so equivalent options produce the same key, while preserving the existing null
fallback for absent options.

---

Nitpick comments:
In `@common/doc_store/infinity_conn_base.py`:
- Around line 307-324: Add a debug log within the JSON predicate branch before
constructing predicates, recording the field name k and the normalized values
count, while excluding item identifiers, raw values, and generated SQL. Use the
module’s existing logging mechanism and keep the json_conditions construction
unchanged.
🪄 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: 9ee6a9bd-8f88-4a92-b80a-090c3d27282d

📥 Commits

Reviewing files that changed from the base of the PR and between ff88439 and d1954ad.

📒 Files selected for processing (6)
  • common/doc_store/infinity_conn_base.py
  • conf/infinity_mapping.json
  • docker/.env
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/utils/infinity_conn.py
  • web/src/hooks/use-document-request.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/advanced_rag/knowlege_compile/dataset_nav.py

Comment on lines +457 to +458
elif k in _JSON_LIST_FIELDS:
d[k] = json.dumps(list(v) if isinstance(v, (list, tuple, set)) else [], ensure_ascii=False)

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.

⚠️ Potential issue | 🟠 Major

Use one validated JSON-list encoder for both write paths.

Both branches silently convert unsupported values to [], which can erase identifiers. Centralize validation/serialization, accept list-like values and explicit None only when clearing is intended, and log/reject other shapes.

  • rag/utils/infinity_conn.py#L457-L458: use the shared encoder for inserts.
  • rag/utils/infinity_conn.py#L598-L599: use the same encoder for updates.
🧰 Tools
🪛 ast-grep (0.44.1)

[info] 457-457: use jsonify instead of json.dumps for JSON output
Context: json.dumps(list(v) if isinstance(v, (list, tuple, set)) else [], ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

📍 Affects 1 file
  • rag/utils/infinity_conn.py#L457-L458 (this comment)
  • rag/utils/infinity_conn.py#L598-L599
🤖 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/utils/infinity_conn.py` around lines 457 - 458, Centralize JSON-list
validation and serialization in a shared encoder, accepting list-like values and
explicit None for intentional clearing while logging or rejecting unsupported
shapes instead of replacing them with []. Update the insert path at
rag/utils/infinity_conn.py:457-458 and the update path at
rag/utils/infinity_conn.py:598-599 to call this encoder consistently.

Source: Coding guidelines

Comment on lines +400 to +404
const key = JSON.stringify({
documentIds: [...params.documentIds].sort(),
run: params.run,
option: params.option || null,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Canonicalize option before creating the deduplication key.

JSON.stringify preserves property insertion order, so { delete: true, apply_kb: false } and { apply_kb: false, delete: true } generate different keys even though they produce the same ingest payload. This bypasses the new in-flight deduplication and issues duplicate POST requests.

Proposed fix
       const key = JSON.stringify({
         documentIds: [...params.documentIds].sort(),
         run: params.run,
-        option: params.option || null,
+        option: params.option
+          ? {
+              delete: params.option.delete,
+              apply_kb: params.option.apply_kb,
+            }
+          : null,
       });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const key = JSON.stringify({
documentIds: [...params.documentIds].sort(),
run: params.run,
option: params.option || null,
});
const key = JSON.stringify({
documentIds: [...params.documentIds].sort(),
run: params.run,
option: params.option
? {
delete: params.option.delete,
apply_kb: params.option.apply_kb,
}
: null,
});
🤖 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 `@web/src/hooks/use-document-request.ts` around lines 400 - 404, Canonicalize
params.option before constructing the JSON.stringify key in the deduplication
logic around documentIds, run, and option. Ensure option object properties are
serialized in a deterministic order so equivalent options produce the same key,
while preserving the existing null fallback for absent options.

@buua436 buua436 closed this Jul 23, 2026
@buua436 buua436 reopened this Jul 23, 2026
@yingfeng
yingfeng merged commit 0c57321 into infiniflow:main Jul 23, 2026
3 checks passed
skbs-eng added a commit to skbs-eng/ragflow that referenced this pull request Aug 5, 2026
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.
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 ♾️infinity Pull requests that‘s involved with infinity(DB) 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants