Skip to content

fix: stop three recurring errors on doc delete (#17685) - #17686

Merged
yuzhichang merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/17685-deleted-doc-id-and-json-contains
Aug 16, 2026
Merged

yuzhichang merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/17685-deleted-doc-id-and-json-contains

Conversation

@skbs-eng

@skbs-eng skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #17685.

Follow-up to #17526 ("Refactor: merge dataset scope graph"), which introduced two code paths that touch Infinity columns the deployed schema does not declare. This PR makes the runtime robust against the old schema while also adding the new column to the new schema so freshly created tables are correct.

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 OceanBase 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-#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.

3) (WARNING) "INFINITY get has only blank knowledgebase_ids for index ragflow_doc_meta_"

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.

Test Coverage

  • test/unit_test/common/test_infinity_condition.py — 29 cases for the json_contains/filter_fulltext routing in equivalent_condition_to_str, including Varchar and Json paths for every JSON-list column, apostrophe escaping, numeric handling on Json, and unknown-type skips.
  • 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.

Total: 43 unit tests passing.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 2, 2026
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Infinity document metadata now uses tenant-scoped tables. List filters support JSON and legacy Varchar columns. Deletion-marker writes upgrade existing tables when possible and include the new deleted_doc_id field.

Changes

Infinity compatibility changes

Layer / File(s) Summary
Table schema upgrade support
conf/infinity_mapping.json, rag/utils/infinity_conn.py, rag/utils/ob_conn.py, test/unit_test/rag/utils/test_infinity_conn_helpers.py
Infinity tables define deleted_doc_id. ensure_columns adds missing columns and releases connections safely.
Deletion marker integration
rag/svr/task_executor_refactor/dataset_structure_merger.py, test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py
record_doc_deletion ensures the marker column before insertion when the document store supports upgrades.
Tenant metadata table routing
api/db/services/doc_metadata_service.py, rag/utils/infinity_conn.py, test/unit_test/api/db/services/test_doc_metadata_service.py
Metadata operations pass empty knowledge-base scope values. get resolves tenant metadata indexes without KB suffixes.
Column-aware list conditions and deletion safety
common/doc_store/infinity_conn_base.py, test/unit_test/common/test_infinity_condition.py
List filters select predicates from column metadata, skip unsupported values or unknown columns, and prevent deletes with unconstrained filters.

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

Sequence Diagram(s)

sequenceDiagram
  participant DatasetStructureMerger
  participant InfinityConnection
  participant InfinityTable
  DatasetStructureMerger->>InfinityConnection: ensure_columns(index, knowledgebase_id, deleted_doc_id)
  InfinityConnection->>InfinityTable: inspect columns and add missing column
  DatasetStructureMerger->>InfinityConnection: insert deletion metadata
  InfinityConnection->>InfinityTable: insert marker row
Loading

Possibly related PRs

Suggested labels: 🐞 bug, ♾️infinity

Poem

A rabbit checks each table row,
Finds old columns left below.
JSON filters choose their type,
Metadata routes stay tight.
Deletion markers land just right. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 primary change: fixing three recurring errors during document deletion.
Description check ✅ Passed The description includes the required Summary section and provides clear causes, fixes, scope, and test coverage.
Linked Issues check ✅ Passed The changes address all three linked issue objectives: schema compatibility, legacy column handling, and per-tenant metadata routing [#17685].
Out of Scope Changes check ✅ Passed The code and test changes remain focused on resolving the three Infinity document-deletion errors described in the linked issue.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/utils/ob_conn.py (1)

102-146: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Add column_deleted_doc_id to EXTRA_COLUMNS.

EXTRA_COLUMNS is consumed by OBConnection.create_idx to add columns on existing OceanBase chunk tables. column_deleted_doc_id is only in column_definitions, so existing tables will keep missing it and can still fail when record_doc_deletion inserts deletion markers.

🛠️ Proposed fix
 EXTRA_COLUMNS: list[Column] = [
     column_order_id,
     column_group_id,
     column_mom_id,
     column_chunk_data,
     column_raptor_kwd,
     column_raptor_layer_int,
     column_n_hop_with_weight,
+    column_deleted_doc_id,
 ]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/ob_conn.py` around lines 102 - 146, Add column_deleted_doc_id to
the EXTRA_COLUMNS list used by OBConnection.create_idx, alongside the other
migration columns, so existing OceanBase chunk tables receive this column during
migration.
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/dataset_structure_merger.py (2)

184-194: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider caching the column-upgrade check to avoid a round trip on every deletion.

ensure_columns runs an extra get_table + show_columns round trip on every call to record_doc_deletion, even long after the column has already been confirmed present on that table. Since the upgrade is idempotent and only ever needs to happen once per table, cache the set of already-verified (tenant, kb) pairs in this module (or inside ensure_columns itself) and skip the call once a table is known to be up to date.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 184
- 194, Cache successfully verified (tenant, kb) pairs for the table upgrade
performed in record_doc_deletion, and skip ensure_columns for pairs already
confirmed. Add appropriate handling so a pair is cached only after
ensure_columns succeeds, preserving retries if the upgrade fails while leaving
the existing upgrade definition unchanged.

188-194: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Align the deleted_doc_id schema used by ensure_columns.

record_doc_deletion upgrades existing Infinity chunk tables with {"deleted_doc_id": {"type": "varchar", "default": ""}}, while conf/infinity_mapping.json declares the same column with "analyzer": "whitespace-#". Upgrades can leave deleted_doc_id as a non-analyzed varchar, so source this column definition from a single mapping to avoid schema drift.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/svr/task_executor_refactor/dataset_structure_merger.py` around lines 188
- 194, Update the ensure_columns call in record_doc_deletion to reuse the shared
deleted_doc_id definition from conf/infinity_mapping.json or its existing
mapping symbol, including the whitespace-# analyzer, instead of constructing a
separate varchar/default schema. Preserve the current index and kb_id upgrade
flow while eliminating duplicate column definitions.
🤖 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 `@common/doc_store/infinity_conn_base.py`:
- Around line 326-354: In the schema-dependent filtering loop around
is_json_col, col_present, and list_conditions, add debug logging once per field
indicating whether the JSON path, legacy Varchar path, or skipped path was
selected. Keep values out of log messages, and avoid logging once per item or
changing the existing predicates.
- Around line 326-347: Restrict the legacy branch in the value-condition loop to
columns whose detected type is Varchar, using the existing col_type value
alongside the string-item check. Keep JSON handling unchanged, skip unknown or
other known column types, and emit filter_fulltext only for Varchar columns.

---

Outside diff comments:
In `@rag/utils/ob_conn.py`:
- Around line 102-146: Add column_deleted_doc_id to the EXTRA_COLUMNS list used
by OBConnection.create_idx, alongside the other migration columns, so existing
OceanBase chunk tables receive this column during migration.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 184-194: Cache successfully verified (tenant, kb) pairs for the
table upgrade performed in record_doc_deletion, and skip ensure_columns for
pairs already confirmed. Add appropriate handling so a pair is cached only after
ensure_columns succeeds, preserving retries if the upgrade fails while leaving
the existing upgrade definition unchanged.
- Around line 188-194: Update the ensure_columns call in record_doc_deletion to
reuse the shared deleted_doc_id definition from conf/infinity_mapping.json or
its existing mapping symbol, including the whitespace-# analyzer, instead of
constructing a separate varchar/default schema. Preserve the current index and
kb_id upgrade flow while eliminating duplicate column definitions.
🪄 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: d0c92842-efa4-4756-a298-ac41190501e3

📥 Commits

Reviewing files that changed from the base of the PR and between d4ceeee and d47b1e0.

📒 Files selected for processing (10)
  • api/db/services/doc_metadata_service.py
  • common/doc_store/infinity_conn_base.py
  • conf/infinity_mapping.json
  • rag/svr/task_executor_refactor/dataset_structure_merger.py
  • rag/utils/infinity_conn.py
  • rag/utils/ob_conn.py
  • test/unit_test/api/db/services/test_doc_metadata_service.py
  • test/unit_test/common/test_infinity_condition.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py
  • test/unit_test/rag/utils/test_infinity_conn_helpers.py

Comment thread common/doc_store/infinity_conn_base.py Resolved
Comment thread common/doc_store/infinity_conn_base.py Resolved
@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai

Thank you for the review! All feedback items have been addressed in commit 5671f2b44:

  1. OceanBase EXTRA_COLUMNS Migration: Added column_deleted_doc_id to EXTRA_COLUMNS in rag/utils/ob_conn.py so existing OceanBase chunk tables acquire the column during migration/table initialization.
  2. Schema Alignment: Updated ensure_columns in dataset_structure_merger.py to include "analyzer": "whitespace-#" for deleted_doc_id matching conf/infinity_mapping.json.
  3. Table Upgrade Caching: Added _UPGRADED_TABLES cache in dataset_structure_merger.py to prevent redundant RPC/metadata lookups on repeated deletions for the same dataset.
  4. Dynamic Filter Type Check & Logging: Restricted the legacy fallback in InfinityConnectionBase.equivalent_condition_to_str explicitly to col_present and "char" in col_type and added field-level debug logging.
  5. Unit Tests: Updated unit test suite (test_dataset_structure_merger.py) to verify caching and schema alignment. All 44 unit tests pass.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@skbs-eng Thank you for the detailed update. The changes address the reported findings.

The OceanBase migration now upgrades existing chunk tables. The Infinity column definition now matches the mapping. The cache avoids repeated table-upgrade operations. The legacy filter fallback is limited to character columns. The updated tests cover the new behavior.

🐇 ✅


✏️ Learnings added
Learnt from: skbs-eng
URL: https://github.com/infiniflow/ragflow/pull/17686

Timestamp: 2026-08-02T12:13:07.194Z
Learning: In `rag/utils/ob_conn.py`, `column_deleted_doc_id` must be included in `EXTRA_COLUMNS` so existing OceanBase chunk tables receive the `deleted_doc_id` column during migration or table initialization.

Learnt from: skbs-eng
URL: https://github.com/infiniflow/ragflow/pull/17686

Timestamp: 2026-08-02T12:13:07.194Z
Learning: In `rag/svr/task_executor_refactor/dataset_structure_merger.py`, the Infinity `deleted_doc_id` column definition uses the `whitespace-#` analyzer to match `conf/infinity_mapping.json`, and `_UPGRADED_TABLES` prevents repeated schema-upgrade operations for the same dataset.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@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)
common/doc_store/infinity_conn_base.py (1)

354-360: 🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift

Do not drop unsupported filters before destructive operations.

When a legacy item is not a string, Line [345] skips it. If all items are skipped, Lines [354-360] add no condition. The helper then returns "1=1" at Line [410]. delete() passes that filter to table_instance.delete() at Lines [721-724]. The Infinity delete API applies the filter to selected rows. (infiniflow.org)

A condition such as {"source_doc_ids": [123]} can therefore delete every row instead of failing. The same risk exists when the column is missing from table metadata.

Return an explicit unsupported-condition result or raise an error. Ensure destructive callers abort before executing the delete. Add a regression test that verifies table_instance.delete() is not called.

🤖 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 354 - 360, Update the
filter-building helper around list_conditions so unsupported or skipped filter
values never produce an empty predicate or fall through to the "1=1" result;
instead return an explicit unsupported-condition result or raise an error.
Ensure delete() detects that result and aborts before calling
table_instance.delete(), including when column metadata is missing, and add a
regression test asserting the delete method is not invoked.
🤖 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
`@test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py`:
- Around line 72-77: Update the test around record_doc_deletion to exercise two
different knowledge-base IDs and verify caching remains scoped per knowledge
base. Assert mock_conn.insert received two records whose deleted_doc_id values
are distinct and match the requested document IDs, while preserving the
ensure_columns call-count checks.
- Around line 75-76: Update the caching flow used by record_doc_deletion so a
table is added to _UPGRADED_TABLES only after the deletion-marker insert
succeeds, or after ensure_columns explicitly reports a successful upgrade.
Preserve the existing single-call caching behavior for successful operations,
and add a test covering a swallowed upgrade failure followed by a second
deletion that retries ensure_columns.

---

Outside diff comments:
In `@common/doc_store/infinity_conn_base.py`:
- Around line 354-360: Update the filter-building helper around list_conditions
so unsupported or skipped filter values never produce an empty predicate or fall
through to the "1=1" result; instead return an explicit unsupported-condition
result or raise an error. Ensure delete() detects that result and aborts before
calling table_instance.delete(), including when column metadata is missing, and
add a regression test asserting the delete method is not invoked.
🪄 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: 76da1cff-153f-4bc3-8a17-f0fccd12dfb7

📥 Commits

Reviewing files that changed from the base of the PR and between d47b1e0 and 5671f2b.

📒 Files selected for processing (4)
  • common/doc_store/infinity_conn_base.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py
  • rag/utils/ob_conn.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • rag/utils/ob_conn.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py

@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai

Thank you for catching the unconstrained filter delete risk! Addressed in commit f954435cb:

  • Unconstrained Delete Guard: Added an explicit check in InfinityConnectionBase.delete to abort and log a warning if a non-empty condition generates an empty or "1=1" filter (e.g. when filtering on an unmapped column).
  • Regression Test: Added TestDeleteSafety.test_delete_aborts_when_condition_yields_unconstrained_filter in test_infinity_condition.py verifying that delete() returns 0 and table_instance.delete() is never invoked.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@skbs-eng The guard prevents deletion when a non-empty condition produces an unconstrained filter. The regression test verifies the required safe behavior. Thank you for the fix.

🐇 ✅

You are interacting with an AI system.

@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: 1

🤖 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 `@common/doc_store/infinity_conn_base.py`:
- Around line 722-724: Update the warning in the delete flow around the
condition/filter guard in the relevant method to stop interpolating the raw
condition or filter values. Keep the warning limited to stating that a non-empty
condition produced an unconstrained filter and include only the table name,
preserving the existing early return.
🪄 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: 84f86f4f-8692-47dd-b643-93447fc717d3

📥 Commits

Reviewing files that changed from the base of the PR and between 5671f2b and f954435.

📒 Files selected for processing (2)
  • common/doc_store/infinity_conn_base.py
  • test/unit_test/common/test_infinity_condition.py

Comment thread common/doc_store/infinity_conn_base.py Resolved
@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai

Updated the warning format in commit 8ec972014 to avoid interpolating raw condition dicts/filters:

self.logger.warning(
    "INFINITY delete aborted: non-empty condition produced an unconstrained filter on table %s.",
    table_name,
)

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@skbs-eng The updated warning format is appropriate. It does not log raw condition data or generated filters. It retains the table name needed for diagnosis.

🐇 ✅

You are interacting with an AI system.

@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai

All review feedback items have been fully addressed and verified:

  1. Table Upgrade Cache Timing: Moved _UPGRADED_TABLES.add((index, kb_id)) after settings.docStoreConn.insert(...) in dataset_structure_merger.py (54bfd484f) so schema upgrades are cached only after insertion succeeds. Failed attempts will automatically retry ensure_columns.
  2. Multi-KB Cache & Retry Test Coverage: Added test_record_doc_deletion_caches_upgraded_tables_per_kb and test_record_doc_deletion_retries_ensure_columns_on_insert_failure in test_dataset_structure_merger.py to test per-KB caching scope and error retry behavior.
  3. All PR Review Threads Resolved: Resolved all feedback threads on GitHub PR fix: stop three recurring errors on doc delete (#17685) #17686.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

impl="rag/svr/task_executor_refactor/dataset_structure_merger.py"
test_file="test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py"

ast-grep outline "$impl" --items all --match 'record_doc_deletion|_UPGRADED_TABLES' --view expanded || true
ast-grep outline "$test_file" --items all --match 'test_record_doc_deletion_caches_upgraded_tables_per_kb|test_record_doc_deletion_retries_ensure_columns_on_insert_failure' --view expanded || true

printf '\n--- relevant implementation occurrences ---\n'
rg -n -C 12 '_UPGRADED_TABLES|record_doc_deletion|docStoreConn\.insert' "$impl"

printf '\n--- relevant test occurrences ---\n'
rg -n -C 10 'test_record_doc_deletion_caches_upgraded_tables_per_kb|test_record_doc_deletion_retries_ensure_columns_on_insert_failure|_UPGRADED_TABLES' "$test_file"

Length of output: 11835


@skbs-eng The implementation now adds (index, kb_id) to _UPGRADED_TABLES only after settings.docStoreConn.insert(...) succeeds.

The new tests verify cache scope per knowledge base and retry behavior after an insertion failure. Static inspection confirms the reported behavior. Test execution was not performed in this verification.

🐇 ✅


✏️ Learnings added
Learnt from: skbs-eng
URL: https://github.com/infiniflow/ragflow/pull/17686

Timestamp: 2026-08-02T12:57:46.437Z
Learning: In `rag/svr/task_executor_refactor/dataset_structure_merger.py`, `record_doc_deletion` must add `(index, kb_id)` to `_UPGRADED_TABLES` only after `settings.docStoreConn.insert(...)` succeeds. This ensures that a failed deletion-marker insertion retries `ensure_columns` on the next deletion request, while successful upgrades are cached independently for each knowledge base.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

@yuzhichang please review

Copilot AI 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.

Pull request overview

This PR addresses three recurring Infinity-related errors/warnings during document deletion by making the runtime tolerant of older deployed schemas (missing columns and legacy Varchar-encoded “JSON list” fields) while also updating the “new table” mappings so freshly created tables are correct.

Changes:

  • Adds deleted_doc_id to Infinity and OceanBase chunk-table schemas and introduces a best-effort ensure_columns() helper to upgrade existing Infinity tables in place before first use.
  • Makes Infinity condition translation choose json_contains vs filter_fulltext based on the table’s actual column types, avoiding json_contains(Varchar, Varchar) failures on legacy tables.
  • Fixes doc-meta get() routing for ragflow_doc_meta_* tables and updates metadata service callers to pass empty knowledgebase_ids for per-tenant metadata indices; adds targeted unit tests.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
rag/utils/infinity_conn.py Special-cases doc-meta get() and adds ensure_columns() for best-effort schema upgrades on existing Infinity tables.
common/doc_store/infinity_conn_base.py Routes JSON-list predicates based on observed column type (Json vs Varchar) and adds a safety guard to abort deletes that would become unconstrained.
rag/svr/task_executor_refactor/dataset_structure_merger.py Ensures deleted_doc_id column exists (via ensure_columns) before writing deletion markers; caches upgraded (index,kb) pairs.
conf/infinity_mapping.json Adds deleted_doc_id to the Infinity mapping so newly created chunk tables include the column.
rag/utils/ob_conn.py Adds deleted_doc_id column to OceanBase chunk-table column definitions for schema parity.
api/db/services/doc_metadata_service.py Passes [] for knowledgebase_ids when using per-tenant doc-meta indexes to avoid incorrect <index>_<kb> table naming under Infinity.
test/unit_test/common/test_infinity_condition.py Adds unit coverage for json_contains vs filter_fulltext routing for JSON-list fields across Json/Varchar/unknown schema cases.
test/unit_test/rag/utils/test_infinity_conn_helpers.py Adds unit tests for doc-meta get() routing and ensure_columns() behavior (idempotency, missing-table, failure swallow).
test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger.py Adds unit tests verifying record_doc_deletion() invokes ensure_columns() and retries upgrade after insert failure.
test/unit_test/api/db/services/test_doc_metadata_service.py Adds unit tests ensuring metadata service uses empty knowledgebase_ids for doc-meta get() calls.

Comment thread rag/utils/infinity_conn.py Resolved
@skbs-eng

skbs-eng commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@coderabbitai @Copilot

All review feedback items have been fully addressed, verified with unit tests, and resolved:

  1. Selective Exception Handling in ensure_columns:
    Updated ensure_columns() in rag/utils/infinity_conn.py (3dcf6750b) to explicitly check e.error_code != ErrorCode.TABLE_NOT_EXIST (3022) when catching InfinityException on get_table(). Other InfinityException errors (e.g. auth, catalog, permission failures) are re-raised internally so they get caught and logged by the outer exception handler.

  2. Unit Test Coverage:
    Added test_logs_exception_when_other_infinity_error in test_infinity_conn_helpers.py to test that non-TABLE_NOT_EXIST errors trigger proper exception logging. All 47 unit tests across the test suite pass cleanly.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@skbs-eng The update handles ErrorCode.TABLE_NOT_EXIST as the expected missing-table case.

ensure_columns() now re-raises other InfinityException errors. The outer handler logs those errors. The new test covers this error path.

🐇 ✅


✏️ Learnings added
Learnt from: skbs-eng
URL: https://github.com/infiniflow/ragflow/pull/17686

Timestamp: 2026-08-03T03:37:25.025Z
Learning: In `rag/utils/infinity_conn.py`, `InfinityConnection.ensure_columns()` must suppress `InfinityException` only when `error_code` is `ErrorCode.TABLE_NOT_EXIST` (3022) during `get_table()`. It must re-raise other Infinity errors so the outer exception handler logs failures such as authentication, catalog, or permission errors. The unit test `test_logs_exception_when_other_infinity_error` in `test/unit_test/rag/utils/test_infinity_conn_helpers.py` covers this behavior.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@skbs-eng The change handles ErrorCode.TABLE_NOT_EXIST as the expected missing-table condition.

For other InfinityException values, ensure_columns() re-raises the exception. The outer handler then logs the failure.

The new test covers this error path. Thank you for the fix.

🐇 ✅

You are interacting with an AI system.

@skbs-eng

skbs-eng commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Added Go Infinity engine parity in commit c56109035:

  • DeleteChunks (internal/engine/infinity/chunk.go) and deleteMetadataWithTable (internal/engine/infinity/metadata.go) now abort deletion if a non-empty condition map yields an unconstrained ("1=1") filter, matching the Python infinity_conn_base.py guard.
  • Added unit test TestBuildFilterFromCondition_UnconstrainedFilter in internal/engine/infinity/sql_test.go.
  • Verified with go test ./internal/engine/infinity/... (ok ragflow/internal/engine/infinity 1.275s) and go vet.

@skbs-eng

skbs-eng commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Added Elasticsearch Go engine parity in commit 446a9ae80:

  • DeleteChunks in internal/engine/elasticsearch/chunk.go now aborts deletion if a non-empty condition map yields no query clauses (preventing execution of an unconstrained match_all query against the index).
  • Verified with go test ./internal/engine/elasticsearch/... (ok ragflow/internal/engine/elasticsearch 13.618s) and go vet.

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.
@skbs-eng
skbs-eng force-pushed the fix/17685-deleted-doc-id-and-json-contains branch from 51fc7f2 to e376ca7 Compare August 5, 2026 03:57
@skbs-eng

skbs-eng commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@yuzhichang please review

@yuzhichang
yuzhichang requested review from wangq8 and yuzhichang August 8, 2026 14:07
@wangq8
wangq8 requested a review from Lynn-Inf August 11, 2026 02:16

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

Excellent, well-structured fix. Here is my detailed review:

Overall: ✅ Approve

This is a high-quality PR — comprehensive, well-tested, and carefully defensive. 43 unit tests across 4 new test files covering all three error paths. The PR description is thorough and the commit is well-scoped.


Fix 1: deleted_doc_id column (ERROR 3013)

conf/infinity_mapping.json and rag/utils/ob_conn.py: ✅ Adding deleted_doc_id to the schema is correct. New tables will pick it up automatically.

rag/utils/infinity_conn.py — ensure_columns: ✅ Good pattern. Idempotent, best-effort, skips non-existent tables, swallows failures gracefully. The _UPGRADED_TABLES module-level cache is a reasonable optimization, though it will reset on process restart — harmless since ensure_columns is idempotent.

dataset_structure_merger.py — record_doc_deletion: ✅ The retry-on-failure behavior (not marking as upgraded until insert succeeds) is the right move. Clean docstring improvements too.

Fix 2: json_contains on Varchar columns (WARNING 3030)

common/doc_store/infinity_conn_base.py: ✅ The column-type-aware routing (json_contains for JSON, filter_fulltext for Varchar) is correct. The edge cases are well handled:

  • Numeric values on legacy Varchar: skipped (old encoding couldn't represent them searchably)
  • Unknown/missing columns: skipped rather than fabricating a query
  • Apostrophe escaping: correct in both paths

The extra show_columns() call was already happening when table_instance was passed — no new RTT overhead.

test/unit_test/common/test_infinity_condition.py: ✅ 29 cases covering the full matrix: JSON/Varchar × all 8 columns × string/numeric × apostrophe × unknown-type × no-table-metadata × other-condition-branches × delete-safety. Excellent.

Fix 3: Meta-table knowledgebase_ids (blank-list WARNING)

rag/utils/infinity_conn.py — get: ✅ Special-casing ragflow_doc_meta_ to query by index name only is consistent with how index_exist/insert/delete already handle meta tables. Moving the empty-list check before connection acquisition is a nice optimization — avoids burning pool connections on a programmer error.

api/db/services/doc_metadata_service.py: ✅ All three call sites now pass [] with clear comments explaining why. The comments reference _get_doc_meta_index_name for discoverability.


Go-side guards: ✅

The unconstrained-filter safety checks in internal/engine/infinity/chunk.go, internal/engine/infinity/metadata.go, and internal/engine/elasticsearch/chunk.go are a good defense-in-depth addition. If a non-empty condition map produces an empty or 1=1 filter, the delete is aborted rather than accidentally truncating a table.


Minor observation (non-blocking):

In dataset_structure_merger.py, the _UPGRADED_TABLES set is module-level and lives only for the process lifetime. After a restart, tables that were already upgraded will be retried. This is harmless (idempotent) but worth noting for future readers. A comment might help, though the existing code is self-documenting enough.


This is ready to merge. Nice work.

@Lynn-Inf Lynn-Inf 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.

Overall this PR reduces doc-meta residual data (the meta-table delete was previously always skipped), but the new delete safety guard introduces a silent residual-data path. Suggestions:

  1. Don't silently return 0 in the delete guard. When condition is non-empty but equivalent_condition_to_str degrades to 1=1 (e.g. column type unknown / JSON-list column skipped), the delete now returns 0 as if successful. Callers can't distinguish
    "0 rows = nothing matched" from "0 rows = predicate skipped". For a delete operation, raising an error is safer than silently no-op-ing.
  2. record_doc_deletion marker write should surface failures. ensure_columns and the outer insert are both swallowed via except Exception: logging.exception(...). If add_columns/insert fails (concurrent DDL, Infinity hiccup), the
    deleted_doc_id marker is lost and orphaned dataset-level entity rows won't be cleaned in the next structure merge — leaving permanent ghost entities. The failure should be observable (re-raise or explicit alert), not just logged.
  3. Differentiate skip behavior between query vs delete in equivalent_condition_to_str. Skipping an unknown-type predicate is acceptable for reads, but for deletes it should not be silently dropped — otherwise chunks/metadata can be left behind
    without notice.
  4. Add an integration test for the "legacy varchar chunk table + delete by source_doc_ids" scenario asserting deleted_rows > 0 (not aborted), to prevent regressions of silent partial deletes.

@skbs-eng

Copy link
Copy Markdown
Contributor Author

@Lynn-Inf Thanks for the thorough review and insightful suggestions! All 4 points have been addressed in commit e31a71491:

  1. Delete Guard Error Handling (Point 1):

    • Updated Python InfinityConnectionBase.delete (common/doc_store/infinity_conn_base.py) to raise ValueError instead of silently returning 0 when a non-empty condition degrades to an unconstrained filter (1=1 or empty).
    • Updated Go DeleteChunks in Infinity (internal/engine/infinity/chunk.go) and Elasticsearch (internal/engine/elasticsearch/chunk.go), as well as deleteMetadataWithTable (internal/engine/infinity/metadata.go), to return an explicit fmt.Errorf(...) instead of (0, nil).
  2. Observable Failures in record_doc_deletion (Point 2):

    • Modified record_doc_deletion in rag/svr/task_executor_refactor/dataset_structure_merger.py to re-raise exceptions if ensure_columns or deletion marker insert fails, surfacing failures directly to the caller.
  3. Differentiated Read vs. Delete Predicate Handling (Point 3):

    • Added is_delete: bool = False to equivalent_condition_to_str in common/doc_store/infinity_conn_base.py. When is_delete=True, if a condition key (e.g. JSON-list column) cannot build a valid predicate due to an unmapped column or type mismatch, equivalent_condition_to_str raises a ValueError rather than silently skipping the predicate.
  4. Integration Test for Legacy Varchar Chunk Table Deletion (Point 4):

    • Added test_legacy_varchar_chunk_table_delete_by_source_doc_ids in test/unit_test/common/test_infinity_condition.py asserting that deleting by source_doc_ids against a legacy Varchar column chunk table succeeds with deleted_rows > 0 using filter_fulltext('source_doc_ids', ...) fallback and is not aborted.

All 49 Python unit tests and Go package tests for internal/engine/infinity and internal/engine/elasticsearch pass cleanly.

@Lynn-Inf Lynn-Inf 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.

LGTM

@yuzhichang yuzhichang added the ci Continue Integration label Aug 14, 2026
@wangq8 wangq8 added ci Continue Integration and removed ci Continue Integration labels Aug 14, 2026
@wangq8

wangq8 commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

Please fix lint - lefthook - ruff.

@codecov

codecov Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (554fb11) to head (c4136da).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17686   +/-   ##
=======================================
  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.

@skbs-eng

Copy link
Copy Markdown
Contributor Author

all checks passes, please merge, thank you!

@yuzhichang
yuzhichang merged commit c6ba54b into infiniflow:main Aug 16, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Deleting documents on Infinity logs 3 recurring errors (#17526 follow-up)

5 participants