Skip to content

Implement Delete in GO and refactor functions - #13974

Merged
yuzhichang merged 8 commits into
infiniflow:mainfrom
qinling0210:go_infinity_refactor
Apr 9, 2026
Merged

yuzhichang merged 8 commits into
infiniflow:mainfrom
qinling0210:go_infinity_refactor

Conversation

@qinling0210

@qinling0210 qinling0210 commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Implement Delete in GO and refactor functions

Type of change

  • Refactoring

Summary by CodeRabbit

  • New Features

    • Added a remove_chunks command to delete specific or all chunks from a document.
    • Added new endpoints for chunk removal and chunk update.
  • Refactor

    • Renamed index commands to dataset/metadata table terminology and updated REST routes accordingly.
    • Updated chunk update flow to a JSON POST style and improved metadata error messages.

@qinling0210 qinling0210 self-assigned this Apr 8, 2026
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors index-centric APIs and CLI to dataset/table and metadata-table semantics, removes document-level engine operations, adds chunk-removal end-to-end (CLI → client → handler → service → engine → DB), and updates routes, tokens, and engine interfaces accordingly.

Changes

Cohort / File(s) Summary
Python CLI & Client
admin/client/parser.py, admin/client/ragflow_client.py
Replaced index/doc_meta commands with dataset/metadata table commands; added remove_chunks parsing and client call; adjusted tokens (VECTOR SIZE TABLE) and endpoints; improved error messages.
Go CLI Lexer & Types
internal/cli/lexer.go, internal/cli/types.go
Added peekToken() lookahead; recognize DATASET TABLE and CHUNKS; replaced VECTOR_SIZE/DOC_META with VECTOR/SIZE/METADATA/TABLE tokens and new token constants.
Go CLI Parser & Dispatcher
internal/cli/user_parser.go, internal/cli/user_command.go, internal/cli/client.go
Parse/create/drop dataset/metadata table commands; added parseRemoveChunk/RemoveChunks; renamed handlers and updated HTTP endpoints; changed UpdateChunk to POST body flow.
Router & HTTP Handlers
internal/router/router.go, internal/handler/chunk.go, internal/handler/kb.go, internal/handler/tenant.go, internal/handler/document.go
Rewired routes: removed legacy chunk PUT route, added /api/v1/chunk/update and /api/v1/chunk/rm; renamed KB and tenant endpoints to doc-engine table paths; improved metadata error classification.
Service Layer
internal/service/chunk.go, internal/service/kb.go, internal/service/tenant.go
Added RemoveChunksRequest and ChunkService.RemoveChunks with tenant-aware validation; renamed KB/tenant service methods and request/response types to dataset/metadata table semantics.
Engine Interface & Implementations
internal/engine/engine.go, internal/engine/elasticsearch/index.go, internal/engine/elasticsearch/document.go, internal/engine/infinity/*.go
Replaced index/document APIs with dataset/table and metadata methods: CreateDataset, CreateMetadata, Delete(condition,...), DropTable, TableExists; removed many document-level methods; Elasticsearch document file deleted; Infinity engine: added metadata support and Delete/DropTable/TableExists implementations.
Removed/Deleted Files
internal/engine/elasticsearch/document.go, internal/engine/infinity/document.go
Deleted document-operation implementations and related bulk response types.

Sequence Diagram(s)

mermaid
sequenceDiagram
autonumber
participant CLI as CLI (admin/client / go-cli)
participant API as HTTP API (router/handler)
participant Service as ChunkService
participant Engine as DocEngine (CreateDataset/Delete/etc)
participant DB as DB/Table
CLI->>API: send remove_chunks / update_chunk request
API->>Service: bind and validate request, auth
Service->>Engine: call Delete(condition, indexName, datasetID)
Engine->>DB: resolve table, build filter, execute delete/drop
DB-->>Engine: deleted count / result
Engine-->>Service: return deleted count / error
Service-->>API: return JSON {deletedCount} / error
API-->>CLI: HTTP response success/failure

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibble tokens, swap index for table,

chunks tumble out when the command is able,
routes rebloom and engines refit,
a tidy delete with a gentle rabbit-bit,
hop—code aligned, now let’s ship that update!

🚥 Pre-merge checks | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete; it only provides a generic statement ('Implement Delete in GO and refactor functions') without explaining the specific problem being solved, the scope of changes across multiple modules (parser, handlers, services, engine), or why these refactorings were necessary. Expand the description to explain: (1) what specific problem the Delete implementation solves, (2) the scope of terminology changes (index→dataset/table), (3) affected components (CLI parser, handlers, services, engines), and (4) how chunk deletion and table lifecycle operations improve the system.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Implement Delete in GO and refactor functions' is vague and overly generic; it uses non-descriptive terms like 'refactor functions' that don't convey meaningful information about the specific changes across multiple files and systems. Consider a more specific title that highlights the main refactoring scope, such as 'Rename index operations to dataset/table terminology and implement chunk deletion' or 'Refactor doc engine API: consolidate index/table operations and add chunk deletion'.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@qinling0210 qinling0210 added the ci Continue Integration label Apr 8, 2026
@qinling0210
qinling0210 marked this pull request as ready for review April 8, 2026 07:16
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Apr 8, 2026
@codecov

codecov Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.52%. Comparing base (3b77238) to head (216fd17).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13974      +/-   ##
==========================================
- Coverage   98.11%   96.52%   -1.60%     
==========================================
  Files          10       10              
  Lines         690      690              
  Branches      108      108              
==========================================
- Hits          677      666      -11     
- Misses          4        8       +4     
- Partials        9       16       +7     

☔ View full report in Codecov by Sentry.
📢 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: 12

Caution

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

⚠️ Outside diff range comments (2)
internal/engine/elasticsearch/index.go (1)

30-64: ⚠️ Potential issue | 🟠 Major

Create and drop are targeting different Elasticsearch index names.

This method ignores datasetID and checks/creates only indexName. The new delete flow later drops ragflow_<tenant>_<kb_id> in internal/service/kb.go, so Elasticsearch will create one tenant-wide index, reject subsequent dataset-table creates as “already exists”, and never drop the created resource.

💡 Suggested fix
 func (e *elasticsearchEngine) CreateDataset(ctx context.Context, indexName, datasetID string, vectorSize int, parserID string) error {
+	physicalName := fmt.Sprintf("%s_%s", indexName, datasetID)
+
 	// Elasticsearch doesn't support vector_size or parser_id in the same way
 	// Build mapping for ES (if needed)
 	// TODO
 	mapping := map[string]interface{}{
 		"dataset_id": datasetID,
 	}
 
-	if indexName == "" {
+	if physicalName == "" {
 		return fmt.Errorf("index name cannot be empty")
 	}
 
 	// Check if index already exists
-	exists, err := e.TableExists(ctx, indexName)
+	exists, err := e.TableExists(ctx, physicalName)
 	if err != nil {
 		return fmt.Errorf("failed to check index existence: %w", err)
 	}
 	if exists {
-		return fmt.Errorf("index '%s' already exists", indexName)
+		return fmt.Errorf("index '%s' already exists", physicalName)
 	}
@@
 	// Create index
 	req := esapi.IndicesCreateRequest{
-		Index: indexName,
+		Index: physicalName,
 		Body:  body,
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/elasticsearch/index.go` around lines 30 - 64, CreateDataset
currently ignores datasetID and only uses indexName, causing name mismatch with
the delete flow that expects indices named like "ragflow_<tenant>_<kb_id>";
update CreateDataset to compute and use the canonical index name (the same
format used in internal/service/kb.go drop path) when calling TableExists and
when creating the index (e.g., replace uses of indexName in CreateDataset and in
the esapi.IndicesCreateRequest with the computed ragflow_<tenant>_<kb_id> index
string derived from datasetID/tenant), so creation, existence checks
(TableExists) and deletion operate on the same index name.
internal/handler/kb.go (1)

680-684: ⚠️ Potential issue | 🔴 Critical

Restrict doc-engine table mutations to owners/admins.

Accessible is the read-level check used by non-mutating KB flows. Using it here lets any user with shared access create or drop the backing table for someone else's dataset. These endpoints should require the same permission level as dataset deletion, and the service should enforce it too instead of trusting only the handler.

Also applies to: 723-729

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/kb.go` around lines 680 - 684, The handler currently uses
h.kbService.Accessible (a read-level check) to authorize table mutations;
replace those checks (including at the shown block and the similar checks around
lines 723-729) with a stricter owner/admin permission check (e.g., a new or
existing h.kbService.RequireOwnerOrAdmin or h.kbService.CanManage method) and
return jsonError when that stronger check fails. Also add the same owner/admin
enforcement inside the kbService methods that perform mutations (e.g.,
CreateDocEngineTable, DropDocEngineTable, and any dataset deletion paths) so the
service layer does not rely solely on the handler for authorization. Ensure the
new service method returns a clear authorization error which the handler maps to
common.CodeAuthenticationError.
🧹 Nitpick comments (4)
internal/engine/infinity/metadata.go (1)

42-49: Clarify the purpose of the explicit existence check.

The code checks if the table exists and returns an error if it does (line 48), but then uses ConflictTypeIgnore when creating the table (line 77). This is intentional defensive behavior, but the error message on line 48 could confuse callers who might expect idempotent behavior.

Consider whether this should be idempotent (return success if table already exists) or if the current strict behavior is required.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/infinity/metadata.go` around lines 42 - 49, The explicit
existence check using e.TableExists(ctx, indexName) followed by an error
conflicts with the later CreateTable call that uses ConflictTypeIgnore; make
this idempotent by removing the pre-check or by returning success when the table
already exists: either delete the TableExists check and rely on CreateTable(...,
ConflictTypeIgnore) to handle conflicts, or change the branch that currently
returns fmt.Errorf("metadata table '%s' already exists", indexName) to simply
return nil (success) when exists is true; update the code paths around
TableExists, indexName, and the CreateTable call that uses ConflictTypeIgnore
accordingly.
internal/handler/document.go (1)

465-476: Error handling uses fragile string matching with unnecessary dead code.

The handler checks for both "no such document" and "document not found", but the service layer (internal/service/document.go:284) only wraps errors with "document not found: %w". The "no such document" check is dead code that will never execute. More importantly, relying on error message substrings is brittle and prone to breaking if upstream messages change.

Consider using typed errors instead:

♻️ Suggested approach using typed errors

Define a custom error type in the service layer:

// In service package
var ErrDocumentNotFound = errors.New("document not found")

// Then wrap with:
return fmt.Errorf("%w: %v", ErrDocumentNotFound, err)

Then in the handler:

-	errMsg := err.Error()
-	if strings.Contains(errMsg, "no such document") || strings.Contains(errMsg, "document not found") {
+	if errors.Is(err, service.ErrDocumentNotFound) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    1,
-			"message": errMsg,
+			"message": err.Error(),
		})
	} else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/document.go` around lines 465 - 476, The handler in Set
metadata uses fragile substring checks ("no such document"/"document not
found"); update the service (internal/service/document.go) to expose a sentinel
error (e.g., ErrDocumentNotFound) and wrap underlying errors with
fmt.Errorf("%w: ...") where the service function (e.g., whatever function
returning the not-found error) currently returns that message, then change the
handler code in internal/handler/document.go to use errors.Is(err,
service.ErrDocumentNotFound) (instead of strings.Contains) to decide the
BadRequest path and remove the dead "no such document" branch; ensure imports
include "errors" and reference service.ErrDocumentNotFound from the handler.
internal/engine/engine.go (1)

57-60: Interface methods look correct, but note indentation inconsistency.

The Delete, DropTable, and TableExists methods are correctly defined to support both dataset and metadata table operations. However, line 59 uses spaces for indentation while the rest of the file uses tabs.

The Delete method signature matches the Infinity implementation in internal/engine/infinity/common.go (context snippet 1).

🔧 Fix indentation
 	// Operations for both dataset and metadata tables
 	Delete(ctx context.Context, condition map[string]interface{}, indexName string, datasetID string) (int64, error)
-    DropTable(ctx context.Context, indexName string) error
+	DropTable(ctx context.Context, indexName string) error
 	TableExists(ctx context.Context, indexName string) (bool, error)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/engine.go` around lines 57 - 60, The three interface methods
Delete, DropTable, and TableExists are correct but have inconsistent indentation
(line showing DropTable currently uses spaces); update the whitespace to match
the rest of the file by replacing the spaces with a tab so the signatures for
Delete(ctx context.Context, condition map[string]interface{}, indexName string,
datasetID string) (int64, error), DropTable(ctx context.Context, indexName
string) error and TableExists(ctx context.Context, indexName string) (bool,
error) align with the file’s tab-based indentation style.
admin/client/ragflow_client.py (1)

1620-1644: Consider defensive handling of response data type.

At line 1638, deleted_count = res_json.get("data", 0) assumes data is an integer. If the API response format changes or returns a dict/object, this could print incorrect information (e.g., printing a dict instead of a count).

🛡️ Proposed defensive fix
         if response.status_code == 200:
             if res_json.get("code") == 0:
-                deleted_count = res_json.get("data", 0)
+                data = res_json.get("data", 0)
+                deleted_count = data if isinstance(data, int) else data.get("deleted", 0) if isinstance(data, dict) else 0
                 print(f"Success to remove chunks from document {doc_id}: {deleted_count} chunks deleted")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@admin/client/ragflow_client.py` around lines 1620 - 1644, The code in
remove_chunks reads deleted_count = res_json.get("data", 0) assuming data is an
int; change this to defensively inspect and normalize the value returned by
res_json.get("data") (e.g., if it's an int use it, if it's a list use len(...),
if it's a dict check for a count field or treat as 1 or 0, otherwise fallback to
0) and update the success print to use the normalized integer (deleted_count) so
you never print a dict/list; perform this normalization immediately after the
code == 0 branch where res_json is available and before the success message is
constructed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@admin/client/parser.py`:
- Around line 696-705: In create_dataset_table, the relative indexing items[i-1]
and items[i-2] can raise IndexError or misidentify tokens; update the loop to
only check previous tokens when i >= 2 and ensure the previous elements actually
have a 'type' attribute (use hasattr/getattr) before comparing to
'SIZE'/'VECTOR', and keep converting the NUMBER token to int only after these
guards pass; this prevents out-of-bounds access and makes the token sequence
validation robust against grammar changes.
- Around line 830-858: The remove_chunks method has variable shadowing: the
inner loop uses "for i, item in enumerate(items)" which overrides the outer
"item"; change the inner loop to use distinct names (e.g., "for j, doc_item in
enumerate(items)") when locating the DOCUMENT token so you don't shadow the
outer "item", and update subsequent uses of that index/variable (items[i + 1] ->
items[j + 1], item -> doc_item) so the logic for extracting doc_id remains
correct.

In `@internal/cli/lexer.go`:
- Around line 225-237: The compound-keyword check in the lexer uses a
case-sensitive comparison (l.peekToken() == "TABLE") so "DATASET table" or
"DATASET Table" won't be detected; change the conditional to perform a
case-insensitive comparison (for example use strings.EqualFold(l.peekToken(),
"TABLE") or strings.ToUpper(l.peekToken()) == "TABLE") so the compound token
branch that returns Token{Type: TokenDatasetTable, Value: "DATASET TABLE"}
triggers regardless of TABLE's case, leaving the subsequent
whitespace/identifier skipping and the fallback Token{Type: TokenDataset, Value:
ident} behavior unchanged.

In `@internal/cli/user_command.go`:
- Around line 1783-1788: The code in user_command.go currently expects
resJSON["data"] to be a map with "deleted_count" but the handler in
internal/handler/chunk.go writes data as a bare JSON number; update the parsing
in the block that sets deletedCount so it handles both cases: if resJSON["data"]
is a float64 (or json.Number) convert that to int64 and assign to deletedCount,
otherwise fall back to the existing map lookup for data["deleted_count"];
reference the deletedCount variable and resJSON lookup to locate and change the
logic accordingly.

In `@internal/cli/user_parser.go`:
- Around line 2645-2655: After parsing doc_id with parseQuotedString() the
parser cursor isn't advanced so curToken still points at the quoted token and
the subsequent TokenSemicolon check never matches; after setting
cmd.Params["doc_id"] = docID call p.nextToken() to advance past the quoted
string before checking if p.curToken.Type == TokenSemicolon (and then optionally
calling p.nextToken() again if a semicolon is present).

In `@internal/engine/elasticsearch/index.go`:
- Around line 181-183: The Delete method on type elasticsearchEngine currently
returns (0, nil) which falsely signals success; change
elasticsearchEngine.Delete to return an explicit error (e.g. return 0,
fmt.Errorf("elasticsearchEngine.Delete not implemented") or errors.New(...)) so
callers like ChunkService.RemoveChunks do not assume deletion succeeded; update
the method body in Delete to return that error and add the necessary import (fmt
or errors) if missing.

In `@internal/engine/infinity/common.go`:
- Around line 207-210: The loop "for k, v := range condition" currently does a
direct comparison v == "" which panics when v is not a string (e.g.,
[]interface{}); change the check to first test for nil, then type-assert or
type-switch on v before comparing to the empty string — e.g., if v == nil {
continue } followed by a type assertion (s, ok := v.(string); if ok && s == "" {
continue }) or a type-switch to only treat string values as comparable to "" so
slices and other types are not compared to "".
- Around line 46-50: The current code treats any error from
db.GetTable(tableName) as a missing table and returns 0, nil; change this so
only a genuine "table not found" condition is swallowed: call
db.GetTable(tableName), and if err != nil check whether err denotes a missing
table (use the DB's sentinel error or errors.Is/db.IsTableNotFound helper if
available); if it is a not-found error log the warning and return 0, nil,
otherwise propagate the real error (return 0, err) and include the original err
in the log message instead of always returning success; update the branch around
db.GetTable, the logger.Warn call, and the return values accordingly.

In `@internal/engine/infinity/dataset.go`:
- Around line 586-596: The loop filling missing embedding columns in dataset.go
uses unsafe assertions ec[0].(string) and ec[1].(int) which can panic; update
the loop in the block that iterates embeddingCols to use safe type checks (e.g.,
s, ok := ec[0].(string) and n, ok := ec[1].(int) or handle numeric kinds like
int64/float64) and skip or log entries that don’t match expected types instead
of panicking; ensure you still create zeros slice only when both name and size
are valid and use the existing map d and identifiers embeddingCols/d to locate
the code.

In `@internal/engine/infinity/metadata.go`:
- Around line 206-207: The UpdateMetadata code builds a SQL filter string using
fmt.Sprintf with docID and kbID (filter := fmt.Sprintf("id = '%s' AND kb_id =
'%s'", docID, kbID)), which allows SQL injection; change UpdateMetadata to use a
parameterized/prepared query or the library's safe placeholder mechanism instead
of string interpolation: replace the formatted filter with a parameterized
condition and pass docID and kbID as bound parameters to the update call (or
escape via the DB driver's safe API) so the filter is constructed safely.
- Around line 162-176: The deletion filter builds SQL-like predicates from
insertMetadata using fmt.Sprintf without escaping user values (see idList and
the loop building docID/kbID) which allows SQL injection and breaks on embedded
quotes; fix by escaping single quotes on m["id"] and m["kb_id"] (e.g., use
strings.ReplaceAll(value, "'", "''")) before formatting, and replace the
delete-then-insert pattern with an atomic operation (use a transaction or
table.Upsert/Replace instead of table.Delete followed by insert) to avoid data
loss if the insert fails; ensure you update the logger.Debug/Info/ Warn usages
to reflect the escaped values or transaction outcome.

In `@internal/service/chunk.go`:
- Around line 1065-1078: The current delete condition in Build condition uses
only req.DocID when req.ChunkIDs is empty, allowing accidental full-document
deletes; update the logic in the chunk deletion routine to require an explicit
delete-all flag (req.DeleteAll) before building a doc-only condition: if
len(req.ChunkIDs) > 0 set condition["id"] and condition["doc_id"], else if
req.DeleteAll set condition["doc_id"], otherwise return a validation/error
response (e.g., bad request) preventing deletion; reference the request fields
req.ChunkIDs, req.DocID and req.DeleteAll and the chunk deletion function that
builds the condition.

---

Outside diff comments:
In `@internal/engine/elasticsearch/index.go`:
- Around line 30-64: CreateDataset currently ignores datasetID and only uses
indexName, causing name mismatch with the delete flow that expects indices named
like "ragflow_<tenant>_<kb_id>"; update CreateDataset to compute and use the
canonical index name (the same format used in internal/service/kb.go drop path)
when calling TableExists and when creating the index (e.g., replace uses of
indexName in CreateDataset and in the esapi.IndicesCreateRequest with the
computed ragflow_<tenant>_<kb_id> index string derived from datasetID/tenant),
so creation, existence checks (TableExists) and deletion operate on the same
index name.

In `@internal/handler/kb.go`:
- Around line 680-684: The handler currently uses h.kbService.Accessible (a
read-level check) to authorize table mutations; replace those checks (including
at the shown block and the similar checks around lines 723-729) with a stricter
owner/admin permission check (e.g., a new or existing
h.kbService.RequireOwnerOrAdmin or h.kbService.CanManage method) and return
jsonError when that stronger check fails. Also add the same owner/admin
enforcement inside the kbService methods that perform mutations (e.g.,
CreateDocEngineTable, DropDocEngineTable, and any dataset deletion paths) so the
service layer does not rely solely on the handler for authorization. Ensure the
new service method returns a clear authorization error which the handler maps to
common.CodeAuthenticationError.

---

Nitpick comments:
In `@admin/client/ragflow_client.py`:
- Around line 1620-1644: The code in remove_chunks reads deleted_count =
res_json.get("data", 0) assuming data is an int; change this to defensively
inspect and normalize the value returned by res_json.get("data") (e.g., if it's
an int use it, if it's a list use len(...), if it's a dict check for a count
field or treat as 1 or 0, otherwise fallback to 0) and update the success print
to use the normalized integer (deleted_count) so you never print a dict/list;
perform this normalization immediately after the code == 0 branch where res_json
is available and before the success message is constructed.

In `@internal/engine/engine.go`:
- Around line 57-60: The three interface methods Delete, DropTable, and
TableExists are correct but have inconsistent indentation (line showing
DropTable currently uses spaces); update the whitespace to match the rest of the
file by replacing the spaces with a tab so the signatures for Delete(ctx
context.Context, condition map[string]interface{}, indexName string, datasetID
string) (int64, error), DropTable(ctx context.Context, indexName string) error
and TableExists(ctx context.Context, indexName string) (bool, error) align with
the file’s tab-based indentation style.

In `@internal/engine/infinity/metadata.go`:
- Around line 42-49: The explicit existence check using e.TableExists(ctx,
indexName) followed by an error conflicts with the later CreateTable call that
uses ConflictTypeIgnore; make this idempotent by removing the pre-check or by
returning success when the table already exists: either delete the TableExists
check and rely on CreateTable(..., ConflictTypeIgnore) to handle conflicts, or
change the branch that currently returns fmt.Errorf("metadata table '%s' already
exists", indexName) to simply return nil (success) when exists is true; update
the code paths around TableExists, indexName, and the CreateTable call that uses
ConflictTypeIgnore accordingly.

In `@internal/handler/document.go`:
- Around line 465-476: The handler in Set metadata uses fragile substring checks
("no such document"/"document not found"); update the service
(internal/service/document.go) to expose a sentinel error (e.g.,
ErrDocumentNotFound) and wrap underlying errors with fmt.Errorf("%w: ...") where
the service function (e.g., whatever function returning the not-found error)
currently returns that message, then change the handler code in
internal/handler/document.go to use errors.Is(err, service.ErrDocumentNotFound)
(instead of strings.Contains) to decide the BadRequest path and remove the dead
"no such document" branch; ensure imports include "errors" and reference
service.ErrDocumentNotFound from the handler.
🪄 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

Run ID: 01f3ee36-fb8a-4708-9e1b-65050420e6f6

📥 Commits

Reviewing files that changed from the base of the PR and between ad789f5 and 9f32658.

📒 Files selected for processing (22)
  • admin/client/parser.py
  • admin/client/ragflow_client.py
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/engine/elasticsearch/document.go
  • internal/engine/elasticsearch/index.go
  • internal/engine/engine.go
  • internal/engine/infinity/common.go
  • internal/engine/infinity/dataset.go
  • internal/engine/infinity/document.go
  • internal/engine/infinity/metadata.go
  • internal/handler/chunk.go
  • internal/handler/document.go
  • internal/handler/kb.go
  • internal/handler/tenant.go
  • internal/router/router.go
  • internal/service/chunk.go
  • internal/service/kb.go
  • internal/service/tenant.go
💤 Files with no reviewable changes (2)
  • internal/engine/infinity/document.go
  • internal/engine/elasticsearch/document.go

Comment thread admin/client/parser.py Resolved
Comment thread admin/client/parser.py Resolved
Comment thread internal/cli/lexer.go Resolved
Comment thread internal/cli/user_command.go Resolved
Comment thread internal/cli/user_parser.go Resolved
Comment thread internal/engine/infinity/common.go Resolved
Comment thread internal/engine/infinity/dataset.go Resolved
Comment thread internal/engine/infinity/metadata.go Resolved
Comment thread internal/engine/infinity/metadata.go Resolved
Comment thread internal/service/chunk.go Resolved
@qinling0210
qinling0210 marked this pull request as draft April 8, 2026 11:23
qinling0210 and others added 7 commits April 8, 2026 20:00
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@qinling0210
qinling0210 force-pushed the go_infinity_refactor branch from 95f2d78 to 6415cec Compare April 8, 2026 12:00
@qinling0210
qinling0210 marked this pull request as ready for review April 8, 2026 12:04
@qinling0210
qinling0210 force-pushed the go_infinity_refactor branch from 6415cec to 216fd17 Compare April 8, 2026 12:05

@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

Caution

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

⚠️ Outside diff range comments (1)
internal/handler/chunk.go (1)

267-316: ⚠️ Potential issue | 🟠 Major

Restore typed validation for UpdateChunk.

Decoding into map[string]interface{} means bad types on allowed fields are now silently ignored. A payload like {"available": 1} or {"content": 42} falls through the type assertions, keeps the old value, and can still return 200. Please fail fast when an allowed field is present with the wrong type, or bind into the typed request struct directly instead of round-tripping through an untyped map.

Also applies to: 325-360

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/chunk.go` around lines 267 - 316, The handler currently
decodes request JSON into rawBody map[string]interface{} causing silent type
failures; change to bind the request into the typed UpdateChunk struct (or
explicitly validate types) so any present allowed field with wrong type fails
immediately. Specifically, replace the json.NewDecoder(...).Decode(&rawBody)
usage for update logic with binding to UpdateChunk (or run explicit checks
against rawBody for "available" (bool), "content" (string), "important_keywords"
(slice/array), "questions" (slice/array), "positions" (slice/array),
"tag_kwd"/"tag_feas" (string/appropriate types)) and return HTTP 400 when a
field is present but not the expected type; keep the existing ID
extraction/validation for dataset_id, document_id, and chunk_id but use the
typed struct or validated values when proceeding with the update.
♻️ Duplicate comments (2)
admin/client/parser.py (1)

696-705: ⚠️ Potential issue | 🟡 Minor

Index-based token parsing still lacks bounds checking.

The logic at line 703 uses relative indexing (items[i-1] and items[i-2]) without verifying i >= 2. This could raise IndexError if the grammar structure changes or produces unexpected token sequences.

🛡️ Proposed fix with bounds checking
     def create_dataset_table(self, items):
         dataset_name = None
         vector_size = None
         for i, item in enumerate(items):
             if hasattr(item, 'data') and item.data == 'quoted_string':
                 dataset_name = item.children[0].strip("'\"")
             if hasattr(item, 'type') and item.type == 'NUMBER':
-                if i > 0 and items[i-1].type == 'SIZE' and items[i-2].type == 'VECTOR':
+                if i >= 2 and hasattr(items[i-1], 'type') and items[i-1].type == 'SIZE' and hasattr(items[i-2], 'type') and items[i-2].type == 'VECTOR':
                     vector_size = int(item)
         return {"type": "create_dataset_table", "dataset_name": dataset_name, "vector_size": vector_size}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@admin/client/parser.py` around lines 696 - 705, The create_dataset_table
method accesses items[i-1] and items[i-2] without bounds checking which can
raise IndexError; update the loop in create_dataset_table to ensure i >= 2
before evaluating items[i-1].type and items[i-2].type (and only then parse
vector_size), and keep existing behavior for setting dataset_name and
vector_size; use the existing identifiers items, i, item, dataset_name, and
vector_size to locate and guard the index-based checks.
internal/engine/infinity/common.go (1)

46-50: ⚠️ Potential issue | 🟠 Major

Don't turn every GetTable failure into a successful no-op.

A missing table is fine to ignore, but this branch also swallows transport/auth/backend errors and reports 0, nil. That makes chunk deletion look successful when the engine was actually unavailable.

💡 Suggested fix
 	table, err := db.GetTable(tableName)
 	if err != nil {
-		logger.Warn(fmt.Sprintf("Table %s does not exist, skipping delete", tableName))
-		return 0, nil
+		errLower := strings.ToLower(err.Error())
+		if strings.Contains(errLower, "not found") || strings.Contains(errLower, "notexist") || strings.Contains(errLower, "doesn't exist") {
+			logger.Warn(fmt.Sprintf("Table %s does not exist, skipping delete", tableName))
+			return 0, nil
+		}
+		return 0, fmt.Errorf("failed to get table %s: %w", tableName, err)
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/infinity/common.go` around lines 46 - 50, The current code
treats any error from db.GetTable(tableName) as a benign "table missing" and
returns 0, nil; change the branch so only a real-not-found error is swallowed:
detect the not-found condition using the DB's sentinel or helper (e.g.
errors.Is(err, db.ErrTableNotFound) or db.IsNotFound(err)) and keep the
logger.Warn + return 0, nil in that case, but for any other error from GetTable
propagate the error (return 0, err or wrap it) instead; update imports (errors)
if needed and keep references to GetTable, tableName, logger.Warn and the
current return behavior clear.
🧹 Nitpick comments (3)
internal/handler/document.go (1)

465-476: Consider using sentinel errors or error types instead of string matching.

The string-based error detection is fragile and tightly coupled to the exact wording in the service layer. Based on internal/service/document.go:280-300, the service returns errors formatted as "document not found: %w", which will match your substring check. However, "no such document" doesn't appear to be used by the service layer, making that check dead code.

A more robust approach would be to define sentinel errors or use error types:

♻️ Suggested refactor using sentinel errors
// In service package
var ErrDocumentNotFound = errors.New("document not found")

// In handler
if errors.Is(err, service.ErrDocumentNotFound) {
    c.JSON(http.StatusBadRequest, gin.H{...})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/document.go` around lines 465 - 476, Replace fragile string
matching of the error message in handler/document.go with errors.Is checks
against a sentinel error from the service layer: define var ErrDocumentNotFound
= errors.New("document not found") in the service package
(internal/service/document.go) and in the handler use errors.Is(err,
service.ErrDocumentNotFound) to return the HTTP 400 response; remove the "no
such document" substring check and ensure you import the errors package and
reference service.ErrDocumentNotFound where the current errMsg-based branching
occurs (the block that builds the JSON response for set-metadata failure).
internal/engine/engine.go (1)

59-59: Inconsistent indentation: spaces instead of tabs.

Line 59 uses spaces for indentation while all other lines use tabs. This should be fixed for consistency.

♻️ Fix indentation
-    DropTable(ctx context.Context, indexName string) error
+	DropTable(ctx context.Context, indexName string) error
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/engine.go` at line 59, The declaration of the DropTable
method uses spaces for indentation while the rest of the file uses tabs; update
the indentation for the DropTable signature (DropTable(ctx context.Context,
indexName string) error) to use a leading tab character to match the file's
tab-based formatting and ensure consistent styling throughout the engine.go
file.
admin/client/ragflow_client.py (1)

1032-1099: Add structured logging for the new CLI mutation flows.

These new dataset-table, metadata-table, chunk-update, and chunk-removal paths only print to stdout. That makes schema changes and destructive operations hard to audit or trace in automation; please add logger calls alongside the user-facing output. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 1514-1644

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@admin/client/ragflow_client.py` around lines 1032 - 1099, The new CLI
mutation methods (create_dataset_table, drop_dataset_table,
create_metadata_table, drop_metadata_table and the additional flows referenced
at lines 1514-1644) currently only print to stdout; add structured logging calls
alongside each print using the module logger (e.g., logger =
logging.getLogger(__name__) if not present) and log at appropriate levels (info
for success, warning/error for failures) including the same contextual fields
(dataset_name, kb_id, response code/message) so these operations are auditable
and consistent with project logging guidelines.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@admin/client/ragflow_client.py`:
- Around line 1628-1634: The code currently treats a command with both
"delete_all" and "chunk_ids" by downgrading to delete_all; instead, detect this
ambiguity before building payload (check command_dict for both "delete_all" and
"chunk_ids") and reject it (raise a clear exception or return an error) so we
never send a silent delete_all; update the logic around command_dict/payload in
ragflow_client.py (the block that sets payload and calls
self.http_client.request("POST", "/chunk/rm", ...)) to validate mutual exclusion
and abort with an explicit error when both keys are present.

In `@internal/engine/engine.go`:
- Around line 44-60: The Elasticsearch backend's Delete method
(internal/engine/elasticsearch/index.go: Delete) is a TODO that returns 0, nil;
implement it to actually delete documents matching the provided condition from
the appropriate index/table (use indexName and datasetID to resolve the target),
perform the delete-by-query or bulk delete via the Elasticsearch client, handle
pagination/scroll if needed, and return the number of deleted documents and any
error; ensure the method signature matches Delete(ctx context.Context, condition
map[string]interface{}, indexName string, datasetID string) (int64, error) and
that errors from the ES client are propagated.

In `@internal/engine/infinity/common.go`:
- Around line 285-288: The current buildFilterFromCondition function returns
"1=1" when conditions is empty, which can match all rows; change it to fail-safe
behavior by returning an error or a no-match filter instead of "1=1". Update
buildFilterFromCondition to detect empty/nil conditions and either return an
error (propagate to callers such as the code in chunk.go) or return a safe
predicate like "0=1" (and document this contract), and adjust callers to handle
the error / no-match result appropriately so nothing is unintentionally deleted
or updated.

In `@internal/handler/chunk.go`:
- Around line 398-421: The handler currently converts all errors from
h.chunkService.RemoveChunks(&req, user.ID) into 500 responses; change this so
validation errors from ChunkService.RemoveChunks (e.g., when delete mode is
invalid such as "both set" or "neither set") return HTTP 400. Update the
RemoveChunks call handling in the chunk handler: detect the service's validation
error (by comparing the error value/type or matching its sentinel message
returned by RemoveChunks) and call c.JSON(http.StatusBadRequest,
gin.H{"code":400,"message":err.Error()}) for those cases, otherwise keep
returning 500 for genuine internal errors; keep references to req.DocID and
h.chunkService.RemoveChunks to locate the code.

---

Outside diff comments:
In `@internal/handler/chunk.go`:
- Around line 267-316: The handler currently decodes request JSON into rawBody
map[string]interface{} causing silent type failures; change to bind the request
into the typed UpdateChunk struct (or explicitly validate types) so any present
allowed field with wrong type fails immediately. Specifically, replace the
json.NewDecoder(...).Decode(&rawBody) usage for update logic with binding to
UpdateChunk (or run explicit checks against rawBody for "available" (bool),
"content" (string), "important_keywords" (slice/array), "questions"
(slice/array), "positions" (slice/array), "tag_kwd"/"tag_feas"
(string/appropriate types)) and return HTTP 400 when a field is present but not
the expected type; keep the existing ID extraction/validation for dataset_id,
document_id, and chunk_id but use the typed struct or validated values when
proceeding with the update.

---

Duplicate comments:
In `@admin/client/parser.py`:
- Around line 696-705: The create_dataset_table method accesses items[i-1] and
items[i-2] without bounds checking which can raise IndexError; update the loop
in create_dataset_table to ensure i >= 2 before evaluating items[i-1].type and
items[i-2].type (and only then parse vector_size), and keep existing behavior
for setting dataset_name and vector_size; use the existing identifiers items, i,
item, dataset_name, and vector_size to locate and guard the index-based checks.

In `@internal/engine/infinity/common.go`:
- Around line 46-50: The current code treats any error from
db.GetTable(tableName) as a benign "table missing" and returns 0, nil; change
the branch so only a real-not-found error is swallowed: detect the not-found
condition using the DB's sentinel or helper (e.g. errors.Is(err,
db.ErrTableNotFound) or db.IsNotFound(err)) and keep the logger.Warn + return 0,
nil in that case, but for any other error from GetTable propagate the error
(return 0, err or wrap it) instead; update imports (errors) if needed and keep
references to GetTable, tableName, logger.Warn and the current return behavior
clear.

---

Nitpick comments:
In `@admin/client/ragflow_client.py`:
- Around line 1032-1099: The new CLI mutation methods (create_dataset_table,
drop_dataset_table, create_metadata_table, drop_metadata_table and the
additional flows referenced at lines 1514-1644) currently only print to stdout;
add structured logging calls alongside each print using the module logger (e.g.,
logger = logging.getLogger(__name__) if not present) and log at appropriate
levels (info for success, warning/error for failures) including the same
contextual fields (dataset_name, kb_id, response code/message) so these
operations are auditable and consistent with project logging guidelines.

In `@internal/engine/engine.go`:
- Line 59: The declaration of the DropTable method uses spaces for indentation
while the rest of the file uses tabs; update the indentation for the DropTable
signature (DropTable(ctx context.Context, indexName string) error) to use a
leading tab character to match the file's tab-based formatting and ensure
consistent styling throughout the engine.go file.

In `@internal/handler/document.go`:
- Around line 465-476: Replace fragile string matching of the error message in
handler/document.go with errors.Is checks against a sentinel error from the
service layer: define var ErrDocumentNotFound = errors.New("document not found")
in the service package (internal/service/document.go) and in the handler use
errors.Is(err, service.ErrDocumentNotFound) to return the HTTP 400 response;
remove the "no such document" substring check and ensure you import the errors
package and reference service.ErrDocumentNotFound where the current errMsg-based
branching occurs (the block that builds the JSON response for set-metadata
failure).
🪄 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

Run ID: ca5837a0-e4d8-4210-9ec7-abd0fb3b7135

📥 Commits

Reviewing files that changed from the base of the PR and between 9f32658 and 216fd17.

📒 Files selected for processing (22)
  • admin/client/parser.py
  • admin/client/ragflow_client.py
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/engine/elasticsearch/document.go
  • internal/engine/elasticsearch/index.go
  • internal/engine/engine.go
  • internal/engine/infinity/common.go
  • internal/engine/infinity/dataset.go
  • internal/engine/infinity/document.go
  • internal/engine/infinity/metadata.go
  • internal/handler/chunk.go
  • internal/handler/document.go
  • internal/handler/kb.go
  • internal/handler/tenant.go
  • internal/router/router.go
  • internal/service/chunk.go
  • internal/service/kb.go
  • internal/service/tenant.go
💤 Files with no reviewable changes (2)
  • internal/engine/infinity/document.go
  • internal/engine/elasticsearch/document.go
✅ Files skipped from review due to trivial changes (1)
  • internal/cli/user_command.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/cli/types.go
  • internal/handler/tenant.go
  • internal/service/tenant.go
  • internal/router/router.go
  • internal/engine/elasticsearch/index.go
  • internal/engine/infinity/metadata.go
  • internal/engine/infinity/dataset.go
  • internal/service/kb.go

Comment on lines +1628 to +1634
if command_dict.get("delete_all"):
payload["delete_all"] = True
elif command_dict.get("chunk_ids"):
payload["chunk_ids"] = command_dict["chunk_ids"]

response = self.http_client.request("POST", "/chunk/rm", json_body=payload,
use_api_base=False, auth_kind="web")

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 | 🔴 Critical

Reject ambiguous delete commands instead of downgrading them to delete_all.

If command_dict contains both delete_all and chunk_ids, this if/elif drops chunk_ids and sends only delete_all=True. That bypasses the mutual-exclusion guard added in internal/service/chunk.go and can wipe the whole document.

🛡️ Suggested fix
-        if command_dict.get("delete_all"):
-            payload["delete_all"] = True
-        elif command_dict.get("chunk_ids"):
-            payload["chunk_ids"] = command_dict["chunk_ids"]
+        delete_all = bool(command_dict.get("delete_all"))
+        chunk_ids = command_dict.get("chunk_ids") or []
+        if delete_all and chunk_ids:
+            print("Specify either delete_all or chunk_ids, not both")
+            return
+        if not delete_all and not chunk_ids:
+            print("Specify chunk_ids or set delete_all=true")
+            return
+        if delete_all:
+            payload["delete_all"] = True
+        else:
+            payload["chunk_ids"] = chunk_ids
📝 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
if command_dict.get("delete_all"):
payload["delete_all"] = True
elif command_dict.get("chunk_ids"):
payload["chunk_ids"] = command_dict["chunk_ids"]
response = self.http_client.request("POST", "/chunk/rm", json_body=payload,
use_api_base=False, auth_kind="web")
delete_all = bool(command_dict.get("delete_all"))
chunk_ids = command_dict.get("chunk_ids") or []
if delete_all and chunk_ids:
print("Specify either delete_all or chunk_ids, not both")
return
if not delete_all and not chunk_ids:
print("Specify chunk_ids or set delete_all=true")
return
if delete_all:
payload["delete_all"] = True
else:
payload["chunk_ids"] = chunk_ids
response = self.http_client.request("POST", "/chunk/rm", json_body=payload,
use_api_base=False, auth_kind="web")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@admin/client/ragflow_client.py` around lines 1628 - 1634, The code currently
treats a command with both "delete_all" and "chunk_ids" by downgrading to
delete_all; instead, detect this ambiguity before building payload (check
command_dict for both "delete_all" and "chunk_ids") and reject it (raise a clear
exception or return an error) so we never send a silent delete_all; update the
logic around command_dict/payload in ragflow_client.py (the block that sets
payload and calls self.http_client.request("POST", "/chunk/rm", ...)) to
validate mutual exclusion and abort with an explicit error when both keys are
present.

Comment thread internal/engine/engine.go
Comment on lines +44 to +60
// Dataset operations
CreateDataset(ctx context.Context, indexName, datasetID string, vectorSize int, parserID string) error
InsertDataset(ctx context.Context, documents []map[string]interface{}, indexName string, knowledgebaseID string) ([]string, error)
InsertMetadata(ctx context.Context, documents []map[string]interface{}, tenantID string) ([]string, error)

// Update operations
UpdateDataset(ctx context.Context, condition map[string]interface{}, newValue map[string]interface{}, tableNamePrefix string, knowledgebaseID string) error
UpdateMetadata(ctx context.Context, docID string, kbID string, metaFields map[string]interface{}, tenantID string) error

// Document operations
IndexDocument(ctx context.Context, indexName, docID string, doc interface{}) error
BulkIndex(ctx context.Context, indexName string, docs []interface{}) (interface{}, error)
DeleteDocument(ctx context.Context, indexName, docID string) error

// Chunk operations
GetChunk(ctx context.Context, indexName, chunkID string, kbIDs []string) (interface{}, error)

// Doc metadata index operations (per-tenant)
CreateDocMetaIndex(ctx context.Context, indexName string) error
// Document metadata operations
CreateMetadata(ctx context.Context, indexName string) error
InsertMetadata(ctx context.Context, documents []map[string]interface{}, tenantID string) ([]string, error)
UpdateMetadata(ctx context.Context, docID string, kbID string, metaFields map[string]interface{}, tenantID string) error

// Operations for both dataset and metadata tables
Delete(ctx context.Context, condition map[string]interface{}, indexName string, datasetID string) (int64, error)
DropTable(ctx context.Context, indexName string) error
TableExists(ctx context.Context, indexName string) (bool, error)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the Elasticsearch Delete implementation is still a stub
rg -n -A5 'func.*elasticsearchEngine.*Delete' internal/engine/elasticsearch/

Repository: infiniflow/ragflow

Length of output: 404


LGTM on interface design; however, Elasticsearch implementation is incomplete.

The interface changes correctly capture the new dataset/table semantics. However, the Elasticsearch Delete method (internal/engine/elasticsearch/index.go:181-184) is a TODO stub that returns 0, nil without performing any deletion. This means chunk removal will silently succeed but leave data in place when using Elasticsearch, causing data integrity issues.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/engine.go` around lines 44 - 60, The Elasticsearch backend's
Delete method (internal/engine/elasticsearch/index.go: Delete) is a TODO that
returns 0, nil; implement it to actually delete documents matching the provided
condition from the appropriate index/table (use indexName and datasetID to
resolve the target), perform the delete-by-query or bulk delete via the
Elasticsearch client, handle pagination/scroll if needed, and return the number
of deleted documents and any error; ensure the method signature matches
Delete(ctx context.Context, condition map[string]interface{}, indexName string,
datasetID string) (int64, error) and that errors from the ES client are
propagated.

Comment on lines +285 to +288
if len(conditions) == 0 {
return "1=1"
}
return strings.Join(conditions, " AND ")

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

Returning 1=1 for empty conditions could delete all rows.

If buildFilterFromCondition is called with an empty or nil condition map where all values are nil/empty strings, it returns "1=1", which would match all rows. While the callers in chunk.go always populate conditions, this is a dangerous default that could cause data loss if a caller passes an empty map.

Consider returning an error or a filter that matches nothing when no conditions are provided:

🛡️ Suggested defensive change
 	if len(conditions) == 0 {
-		return "1=1"
+		return "1=0" // Match nothing to prevent accidental full-table delete
 	}
📝 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
if len(conditions) == 0 {
return "1=1"
}
return strings.Join(conditions, " AND ")
if len(conditions) == 0 {
return "1=0" // Match nothing to prevent accidental full-table delete
}
return strings.Join(conditions, " AND ")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/engine/infinity/common.go` around lines 285 - 288, The current
buildFilterFromCondition function returns "1=1" when conditions is empty, which
can match all rows; change it to fail-safe behavior by returning an error or a
no-match filter instead of "1=1". Update buildFilterFromCondition to detect
empty/nil conditions and either return an error (propagate to callers such as
the code in chunk.go) or return a safe predicate like "0=1" (and document this
contract), and adjust callers to handle the error / no-match result
appropriately so nothing is unintentionally deleted or updated.

Comment thread internal/handler/chunk.go
Comment on lines +398 to +421
var req service.RemoveChunksRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": err.Error(),
})
return
}

if req.DocID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "doc_id is required",
})
return
}

deletedCount, err := h.chunkService.RemoveChunks(&req, user.ID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"message": err.Error(),
})
return

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

Return invalid delete requests as 400s, not 500s.

ChunkService.RemoveChunks already rejects “both set” and “neither set” delete modes, but this handler turns those caller errors into internal-server errors. A request with only doc_id will look like a server fault instead of a bad request.

💡 Suggested guard in the handler
 	if req.DocID == "" {
 		c.JSON(http.StatusBadRequest, gin.H{
 			"code":    400,
 			"message": "doc_id is required",
 		})
 		return
 	}
+	if (req.DeleteAll && len(req.ChunkIDs) > 0) || (!req.DeleteAll && len(req.ChunkIDs) == 0) {
+		c.JSON(http.StatusBadRequest, gin.H{
+			"code":    400,
+			"message": "provide exactly one of delete_all or chunk_ids",
+		})
+		return
+	}
 
 	deletedCount, err := h.chunkService.RemoveChunks(&req, user.ID)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/chunk.go` around lines 398 - 421, The handler currently
converts all errors from h.chunkService.RemoveChunks(&req, user.ID) into 500
responses; change this so validation errors from ChunkService.RemoveChunks
(e.g., when delete mode is invalid such as "both set" or "neither set") return
HTTP 400. Update the RemoveChunks call handling in the chunk handler: detect the
service's validation error (by comparing the error value/type or matching its
sentinel message returned by RemoveChunks) and call
c.JSON(http.StatusBadRequest, gin.H{"code":400,"message":err.Error()}) for those
cases, otherwise keep returning 500 for genuine internal errors; keep references
to req.DocID and h.chunkService.RemoveChunks to locate the code.

@yuzhichang
yuzhichang merged commit 82fa85c into infiniflow:main Apr 9, 2026
1 check passed
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 13, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 13, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 23, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 23, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@coderabbitai coderabbitai Bot mentioned this pull request Apr 23, 2026
1 task done
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 27, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jasmingacic pushed a commit to jasmingacic/ragflow that referenced this pull request Apr 27, 2026
Implement Delete in GO and refactor functions

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
### What problem does this PR solve?

Implement Delete in GO and refactor functions

### Type of change

- [x] Refactoring

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added a remove_chunks command to delete specific or all chunks from a
document.
  * Added new endpoints for chunk removal and chunk update.

* **Refactor**
* Renamed index commands to dataset/metadata table terminology and
updated REST routes accordingly.
* Updated chunk update flow to a JSON POST style and improved metadata
error messages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@coderabbitai coderabbitai Bot mentioned this pull request Apr 30, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants