Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughAdds a dataset document upload API with local multipart uploads (blob storage + deduplication), empty virtual documents, and web-upload validation; implements service/DAO/utility helpers, route wiring, handler validation/mapping, and tests. ChangesDocument Upload Feature
Sequence DiagramsequenceDiagram
participant Client
participant Handler as UploadDocuments
participant Dispatcher as TypeRouter
participant Local as uploadLocalDocuments
participant Empty as uploadEmptyDocument
participant Web as uploadWebDocument
participant Service as DocumentService
participant Storage as ObjectStorage
participant DB as Database
Client->>Handler: POST /datasets/:id/documents (type, files or name/url)
Handler->>Handler: Validate dataset exists\nCheck tenant access
Handler->>Dispatcher: Route by type
alt Local Upload
Dispatcher->>Local: multipart form-data
Local->>Local: Validate file parts\nParse parser_config override
Local->>Service: UploadLocalDocuments
Service->>Service: Deduplicate names\nRead file bytes\nCompute xxh3 hash
Service->>Storage: Upload blob
Service->>DB: Create Document row / File linkage
Service-->>Local: Raw document maps + per-file errors
Local->>Local: Map keys with UNSTART run
Local-->>Client: Success envelope
else Empty Upload
Dispatcher->>Empty: JSON name payload
Empty->>Empty: Validate name non-empty
Empty->>Service: UploadEmptyDocument
Service->>DB: Create Document row / File linkage
Service-->>Empty: Raw document map
Empty->>Empty: Map keys with UNSTART run
Empty-->>Client: Success envelope
else Web Upload
Dispatcher->>Web: form name/url payload
Web->>Web: Validate name/url\nCheck HTTP/HTTPS scheme
Web->>Service: UploadWebDocument
Service-->>Web: Not-supported error
Web-->>Client: Error response
end
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/service/document.go (1)
217-219: 💤 Low valueConsider bounded retry for storage collision loop.
The collision handling appends
_in a loop untilObjExistreturns false. While collisions should be rare, consider adding a maximum retry count (e.g., 100) to prevent infinite loops ifObjExisthas a bug or returns incorrect results.🛡️ Defensive retry limit
location = safeParent + "/" + filename } - for storageImpl.ObjExist(kb.ID, location) { + for i := 0; i < 100 && storageImpl.ObjExist(kb.ID, location); i++ { location += "_" } + if storageImpl.ObjExist(kb.ID, location) { + errMsgs = append(errMsgs, fh.Filename+": too many storage collisions") + continue + }🤖 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 `@internal/service/document.go` around lines 217 - 219, The loop that appends "_" to location while storageImpl.ObjExist(kb.ID, location) can loop forever; add a bounded retry counter (e.g., maxRetries = 100) around that logic (replace the current while loop with a for loop or counter-based loop) and if the counter exceeds maxRetries return a clear error (or propagate an error) from the surrounding function instead of looping indefinitely; reference storageImpl.ObjExist, kb.ID and location when implementing this change.internal/handler/document.go (1)
180-194: ⚡ Quick winConsider reporting invalid parser_config JSON to user.
Invalid
parser_configJSON is silently ignored (line 183 checks== nilafterUnmarshal). While this is defensive, users might not realize their configuration is being ignored due to a syntax error. Consider returning a validation error when JSON parsing fails to provide clearer feedback.💬 Improved validation with error feedback
var override map[string]interface{} if raw := strings.TrimSpace(c.PostForm("parser_config")); raw != "" { var parsed map[string]interface{} - if json.Unmarshal([]byte(raw), &parsed) == nil { + if err := json.Unmarshal([]byte(raw), &parsed); err != nil { + jsonError(c, common.CodeArgumentError, "Invalid parser_config JSON: "+err.Error()) + return + } else { override = map[string]interface{}{} for _, k := range []string{"table_column_mode", "table_column_roles"} { if v, ok := parsed[k]; ok { override[k] = v } } if len(override) == 0 { override = nil } } }🤖 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 `@internal/handler/document.go` around lines 180 - 194, The current parsing of the "parser_config" POST form silently ignores JSON syntax errors (json.Unmarshal(...)=nil check) so users don't know their config failed; update the handler in internal/handler/document.go to capture and check the error returned by json.Unmarshal when parsing raw (the parser_config variable), and if non-nil return a clear validation response to the client (e.g., HTTP 400 with a message indicating invalid parser_config JSON and the parse error) instead of silently proceeding to build override; keep building override from parsed only on successful unmarshal and preserve the existing keys ("table_column_mode", "table_column_roles").
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/handler/document.go`:
- Around line 180-194: The current parsing of the "parser_config" POST form
silently ignores JSON syntax errors (json.Unmarshal(...)=nil check) so users
don't know their config failed; update the handler in
internal/handler/document.go to capture and check the error returned by
json.Unmarshal when parsing raw (the parser_config variable), and if non-nil
return a clear validation response to the client (e.g., HTTP 400 with a message
indicating invalid parser_config JSON and the parse error) instead of silently
proceeding to build override; keep building override from parsed only on
successful unmarshal and preserve the existing keys ("table_column_mode",
"table_column_roles").
In `@internal/service/document.go`:
- Around line 217-219: The loop that appends "_" to location while
storageImpl.ObjExist(kb.ID, location) can loop forever; add a bounded retry
counter (e.g., maxRetries = 100) around that logic (replace the current while
loop with a for loop or counter-based loop) and if the counter exceeds
maxRetries return a clear error (or propagate an error) from the surrounding
function instead of looping indefinitely; reference storageImpl.ObjExist, kb.ID
and location when implementing this change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d38ea7ee-11e1-4099-8c31-c2a955706a78
📒 Files selected for processing (8)
internal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/document_upload_test.gointernal/router/router.gointernal/service/dataset.gointernal/service/document.gointernal/utility/file.go
| hash := fmt.Sprintf("%016x", xxhash.Sum64(blob)) | ||
| doc.ContentHash = &hash |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for Python hash computation to verify format compatibility
rg -n 'content_hash|xxhash|hashlib' --glob='*.py'Repository: infiniflow/ragflow
Length of output: 10337
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show relevant Go code around internal/service/document.go lines 260-320 (approx)
sed -n '240,330p' internal/service/document.go | nl -ba | sed -n '1,120p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# find all xxhash.Sum64/Sum128 usage in Go
rg -n --glob='*.go' 'xxhash\.Sum(64|128)|xxhash\.New|xxhash\.' internal || trueRepository: infiniflow/ragflow
Length of output: 197
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# inspect Python content_hash computation around the doc content_hash column usage
rg -n --glob='*.py' 'xxhash\.xxh(64|128)\(|content_hash' api rag common common/data_source tools | head -n 200Repository: infiniflow/ragflow
Length of output: 6516
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show the Python code that sets Document.content_hash (file_service.py around the lines found)
sed -n '450,580p' api/db/services/file_service.py | nl -ba | sed -n '1,160p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show the Python model definition for content_hash field length/help text
sed -n '880,980p' api/db/db_models.py | nl -ba | sed -n '1,140p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show relevant Go code around internal/service/document.go lines 260-330 (approx)
sed -n '240,330p' internal/service/document.go | nl -ba | sed -n '1,120p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# find all xxhash.Sum64/Sum128 usage in Go
rg -n --glob='*.go' 'xxhash\.Sum(64|128)|xxhash\.New|xxhash\.' internal || trueRepository: infiniflow/ragflow
Length of output: 197
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# inspect Python content_hash computation around the doc content_hash column usage
rg -n --glob='*.py' 'xxhash\.xxh(64|128)\(|content_hash' api rag common tools | head -n 200Repository: infiniflow/ragflow
Length of output: 5396
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show the Python code that sets Document.content_hash (file_service.py around the lines found)
sed -n '450,580p' api/db/services/file_service.py | nl -ba | sed -n '1,160p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show the Python model definition for content_hash field length/help text
sed -n '900,980p' api/db/db_models.py | nl -ba | sed -n '1,140p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show relevant Go code around internal/service/document.go lines 260-320
sed -n '260,320p' internal/service/document.go | nl -baRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# find all xxhash-related hashing in Go under internal/
rg -n --glob='*.go' 'xxhash\.' internal || trueRepository: infiniflow/ragflow
Length of output: 197
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# inspect Python usage of xxhash and content_hash fields
rg -n --glob='*.py' 'xxhash\.xxh(64|128)\(|content_hash' api rag common tools | head -n 200Repository: infiniflow/ragflow
Length of output: 5396
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show Python model field definition for content_hash
rg -n 'content_hash = CharField' api/db/db_models.py
sed -n '900,960p' api/db/db_models.py | nl -baRepository: infiniflow/ragflow
Length of output: 270
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show Python code where content_hash is computed from blob/ETag
sed -n '470,540p' api/db/services/file_service.py | nl -baRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show relevant Go code around internal/service/document.go lines 260-320
sed -n '260,320p' internal/service/document.go | nl -baRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# find all xxhash-related hashing in Go under internal/
rg -n --glob='*.go' 'xxhash\.' internal || trueRepository: infiniflow/ragflow
Length of output: 197
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# inspect Python usage of xxhash and content_hash fields
rg -n --glob='*.py' 'xxhash\.xxh(64|128)\(|content_hash' api rag common tools | head -n 200Repository: infiniflow/ragflow
Length of output: 5396
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show Python model field definition for content_hash
rg -n 'content_hash = CharField' api/db/db_models.py
sed -n '900,960p' api/db/db_models.py | nl -baRepository: infiniflow/ragflow
Length of output: 270
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# show Python code where content_hash is computed from blob/ETag
sed -n '470,540p' api/db/services/file_service.py | nl -baRepository: infiniflow/ragflow
Length of output: 105
Fix cross-language content_hash hashing mismatch (xxh64 vs xxh128).
internal/service/document.go writes doc.ContentHash as xxhash.Sum64(blob) formatted with %016x (16 hex chars), but Python persists Document.content_hash as xxhash.xxh128(blob).hexdigest() (32 hex chars) and the DB field is max_length=32 (“xxhash128 …”). This will prevent consistent dedup/change-detection across Go/Python.
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
4092cd3 to
fe57ebf
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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 `@internal/handler/document.go`:
- Around line 185-197: The handler currently swallows malformed or non-object
parser_config JSON (the block reading c.PostForm("parser_config") into parsed
via json.Unmarshal and then building override), causing uploads to proceed with
defaults; change that logic to validate json parsing and type and return a
client error instead of silently dropping it: when json.Unmarshal returns an
error or the decoded value is not a map[string]interface{} (or contains
unexpected types), respond with a BadRequest (or appropriate error) and stop
processing; keep the existing extraction of allowed keys ("table_column_mode",
"table_column_roles") into override only after successful validation so
parser_config is enforced rather than ignored.
In `@internal/service/document.go`:
- Around line 416-420: The current logic ignores errors from
s.documentDAO.ListNamesByKbID and treats them as "no existing names", which
disables duplicate-name protection on transient DAO failures; change both
occurrences (the ListNamesByKbID calls in internal/service/document.go) to check
if err != nil and return a server/internal error (do not populate or assume
taken names) so uploads fail fast when the DAO lookup fails—use the existing
service error-wrapping pattern to return an appropriate error to the caller
instead of proceeding with the upload.
- Around line 572-578: The readFileHeaderBytes helper unboundedly reads the
whole multipart file into memory; guard against oversized uploads by checking
fh.Size before calling io.ReadAll (or switch to streaming writes) — update
readFileHeaderBytes to reject when fh.Size exceeds a configured max (e.g.,
maxUploadSize) and return a clear error, and ensure callers like
UploadLocalDocuments propagate that error; alternatively change
UploadLocalDocuments to stream from fh.Open() to disk or cloud storage instead
of using readFileHeaderBytes for large files.
- Around line 425-458: The upload currently calls storageImpl.Put(...) before
persisting the DB row (s.documentDAO.Create), which can leave orphaned blobs on
DB errors; to make per-file writes atomic, after a successful
storageImpl.Put(kb.ID, location, blob) ensure you delete the blob if any
subsequent step fails (wrap following logic so that on s.documentDAO.Create(doc)
error you call storageImpl.Delete(kb.ID, location) and remove any partial
state), only append to results after both Put and Create succeed, and apply the
same cleanup for any other post-Put failures; locate this logic around
uniqueUploadName, storageImpl.Put, s.newDatasetDocument and s.documentDAO.Create
in the loop and add the rollback delete on 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: e152794e-5a06-42be-b01e-f2fde688c60c
📒 Files selected for processing (8)
internal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/document_upload_test.gointernal/router/router.gointernal/service/dataset.gointernal/service/document.gointernal/utility/file.go
🚧 Files skipped from review as they are similar to previous changes (6)
- internal/router/router.go
- internal/service/dataset.go
- internal/dao/document.go
- internal/handler/document_test.go
- internal/utility/file.go
- internal/handler/document_upload_test.go
| if raw := strings.TrimSpace(c.PostForm("parser_config")); raw != "" { | ||
| var parsed map[string]interface{} | ||
| if json.Unmarshal([]byte(raw), &parsed) == nil { | ||
| override = map[string]interface{}{} | ||
| for _, k := range []string{"table_column_mode", "table_column_roles"} { | ||
| if v, ok := parsed[k]; ok { | ||
| override[k] = v | ||
| } | ||
| } | ||
| if len(override) == 0 { | ||
| override = nil | ||
| } | ||
| } |
There was a problem hiding this comment.
Reject malformed parser_config instead of silently dropping it.
If parser_config is invalid JSON or not an object, this path just ignores it and creates the document with the dataset default config. That makes the upload look successful while saving the wrong parse settings for the later parse step.
Proposed fix
var override map[string]interface{}
if raw := strings.TrimSpace(c.PostForm("parser_config")); raw != "" {
var parsed map[string]interface{}
- if json.Unmarshal([]byte(raw), &parsed) == nil {
- override = map[string]interface{}{}
- for _, k := range []string{"table_column_mode", "table_column_roles"} {
- if v, ok := parsed[k]; ok {
- override[k] = v
- }
- }
- if len(override) == 0 {
- override = nil
- }
+ if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
+ jsonError(c, common.CodeArgumentError, `"parser_config" must be a valid JSON object.`)
+ return
+ }
+ override = map[string]interface{}{}
+ for _, k := range []string{"table_column_mode", "table_column_roles"} {
+ if v, ok := parsed[k]; ok {
+ override[k] = v
+ }
+ }
+ if len(override) == 0 {
+ override = nil
}
}🤖 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 `@internal/handler/document.go` around lines 185 - 197, The handler currently
swallows malformed or non-object parser_config JSON (the block reading
c.PostForm("parser_config") into parsed via json.Unmarshal and then building
override), causing uploads to proceed with defaults; change that logic to
validate json parsing and type and return a client error instead of silently
dropping it: when json.Unmarshal returns an error or the decoded value is not a
map[string]interface{} (or contains unexpected types), respond with a BadRequest
(or appropriate error) and stop processing; keep the existing extraction of
allowed keys ("table_column_mode", "table_column_roles") into override only
after successful validation so parser_config is enforced rather than ignored.
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
…(issue infiniflow#15240) Port Python upload_document to Go: dispatches on type=local|web|empty. - local: store each file in object storage + insert a Document row with filetype-derived parser_id, parser_config override merge, dedup-rename, size and xxhash content hash (no tokenization/embedding — that is the separate parse step). - empty: insert a zero-byte virtual document (dup-name guarded). - web: full request validation; the URL->PDF fetch is reported unsupported (html2pdf/thumbnail have no Go equivalent yet). Existence-before-permission error ordering matches Python (DATA_ERROR vs AUTHENTICATION_ERROR). Adds utility.GetParser, DocumentDAO.ListNamesByKbID, DatasetService.GetKBByID, and handler fake-harness tests.
fe57ebf to
6d617d9
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
internal/handler/document.go (1)
185-197:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject malformed
parser_configinstead of silently dropping it.If
parser_configis invalid JSON or not an object, this path just ignores it and creates the document with the dataset default config. That makes the upload look successful while saving the wrong parse settings for the later parse step.🐛 Proposed fix
var override map[string]interface{} if raw := strings.TrimSpace(c.PostForm("parser_config")); raw != "" { var parsed map[string]interface{} - if json.Unmarshal([]byte(raw), &parsed) == nil { - override = map[string]interface{}{} - for _, k := range []string{"table_column_mode", "table_column_roles"} { - if v, ok := parsed[k]; ok { - override[k] = v - } - } - if len(override) == 0 { - override = nil - } + if err := json.Unmarshal([]byte(raw), &parsed); err != nil { + jsonError(c, common.CodeArgumentError, `"parser_config" must be a valid JSON object.`) + return + } + override = map[string]interface{}{} + for _, k := range []string{"table_column_mode", "table_column_roles"} { + if v, ok := parsed[k]; ok { + override[k] = v + } + } + if len(override) == 0 { + override = nil } }🤖 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 `@internal/handler/document.go` around lines 185 - 197, The handler currently reads c.PostForm("parser_config") into raw and silently ignores invalid JSON or non-object values by leaving override nil; instead, validate parser_config strictly: attempt json.Unmarshal into an interface{}, check for errors and that the result is a map[string]interface{} (not just nil or another type), and if either check fails return a 4xx error response to the client rather than proceeding; only when json.Unmarshal succeeds and the value is an object, extract the allowed keys into override (as the existing loop does) and continue. Ensure you update the logic around raw, parsed and override to perform these checks and produce an explicit error response (e.g., c.JSON/c.AbortWithStatusJSON) when parser_config is malformed.
🤖 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 `@internal/handler/document.go`:
- Line 225: The call to ShouldBindJSON(&req) in the document handler currently
ignores binding errors; update the handler to capture the returned error (err :=
c.ShouldBindJSON(&req)), check for err, and when present respond with a 400 and
a clear JSON error message (or use c.Error handling) indicating a malformed
JSON/syntax error instead of proceeding to validation that produces "File name
can't be empty."; ensure you reference the binding site (ShouldBindJSON in this
handler function) and return early on binding failure so subsequent logic (e.g.,
file name validation) is not executed.
---
Duplicate comments:
In `@internal/handler/document.go`:
- Around line 185-197: The handler currently reads c.PostForm("parser_config")
into raw and silently ignores invalid JSON or non-object values by leaving
override nil; instead, validate parser_config strictly: attempt json.Unmarshal
into an interface{}, check for errors and that the result is a
map[string]interface{} (not just nil or another type), and if either check fails
return a 4xx error response to the client rather than proceeding; only when
json.Unmarshal succeeds and the value is an object, extract the allowed keys
into override (as the existing loop does) and continue. Ensure you update the
logic around raw, parsed and override to perform these checks and produce an
explicit error response (e.g., c.JSON/c.AbortWithStatusJSON) when parser_config
is malformed.
🪄 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: 891349b7-ae7b-49ee-b0de-46409b71f84e
📒 Files selected for processing (8)
internal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/document_upload_test.gointernal/router/router.gointernal/service/dataset.gointernal/service/document.gointernal/utility/file.go
🚧 Files skipped from review as they are similar to previous changes (7)
- internal/dao/document.go
- internal/service/dataset.go
- internal/router/router.go
- internal/utility/file.go
- internal/handler/document_test.go
- internal/service/document.go
- internal/handler/document_upload_test.go
Haruko386
left a comment
There was a problem hiding this comment.
I test it in RAGFLow front-end
and I can't upload any file with your code.
fix it plz
|
@dripsmvcp you can make it |
…w#15715 review) Uploaded documents never appeared in the dataset list because DocumentDAO.ListByKBID inner-joins file2document + file, but the upload path created only the Document row. Port Python add_file_from_kb / get_kb_folder / new_a_file_from_kb: ensure the root -> .knowledgebase -> <dataset> folder chain and create a File row + file2document mapping for each uploaded (local and empty) document, with rollback of the blob/row on linkage failure. Also addresses the inline review items: reject malformed parser_config instead of silently dropping it; surface ListNamesByKbID lookup errors instead of disabling dedupe; clean up orphaned blobs when the document insert fails; bound file size before io.ReadAll (128 MiB, matching DOC_MAXIMUM_SIZE) and guard with io.LimitReader; report JSON binding errors on empty-document upload; and compute content_hash with XXH3-128 (32-char hexdigest) to match Python xxhash.xxh128 and the content_hash column.
…nfiniflow#15715) Regression test for the reviewer's 'can't upload any file' report: assert UploadEmptyDocument links the document via File + file2document so DocumentDAO.ListByKBID (which inner-joins those tables) surfaces it, and that the root/.knowledgebase/dataset folder chain is created once and reused across uploads.
|
@dripsmvcp Could you please resolve the merge conflicts and update this PR? |
…nfiniflow#15715) Resolve conflicts: drop the duplicate File2DocumentDAO.Create (main added an identical method in infiniflow#15533) and union fakeDocumentService's upload* and metadata* test fields. Build, vet, gofmt and the service/handler/dao/router tests (incl. the upload-linkage regression tests) pass.
|
@Hz-186 Resolved the issue |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15715 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…nfiniflow#15715) Resolve conflicts from main's ingestion refactor (infiniflow#15327) and handler-error redaction (infiniflow#15746): union the documentServiceIface upload* and *IngestionTasks methods, adopt main's renamed ingestionTaskDAO/ingestionTaskLogDAO while keeping fileDAO, and dedupe the internal/server import. Build, vet, gofmt and service/handler/dao/router tests (incl. upload-linkage regression tests) pass.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/document.go (1)
591-599:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRollback the
Filerow when thefile2documentinsert fails.Line 591 commits the file-manager entry before Line 595 writes the mapping. If the mapping insert fails, both upload callers return an error after deleting only the document/blob, which leaves an orphaned
filerow behind. DeletefileIDon that error path, or wrap the two writes in one transaction.Suggested fix
if err := s.fileDAO.Create(file); err != nil { return err } docID := doc.ID - return s.file2DocumentDAO.Create(&entity.File2Document{ + if err := s.file2DocumentDAO.Create(&entity.File2Document{ ID: strings.ReplaceAll(uuid.New().String(), "-", ""), FileID: &fileID, DocumentID: &docID, - }) + }); err != nil { + _, _ = s.fileDAO.DeleteByIDs([]string{fileID}) + return err + } + return nil🤖 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 `@internal/service/document.go` around lines 591 - 599, The file row is created with s.fileDAO.Create(file) before writing the mapping with s.file2DocumentDAO.Create, leaving an orphaned file if the mapping insert fails; update the upload flow in the function containing these calls to either wrap both operations in a single DB transaction (so both create operations are committed or rolled back together) or, if a transaction is not available, call s.fileDAO.Delete(fileID) when s.file2DocumentDAO.Create(&entity.File2Document{...}) returns an error (ensure you use the same fileID variable and handle/delete any errors from the delete call).
♻️ Duplicate comments (1)
internal/service/document.go (1)
637-640:⚠️ Potential issue | 🟠 MajorUse the same hash algorithm as Python here.
The 32-character width now matches, but
xxh3.Hash128computes XXH3_128, not Python’sxxhash.xxh128. Identical uploads from Go and Python will still get differentcontent_hashvalues.Does `github.com/zeebo/xxh3.Hash128` produce the same digest as Python `xxhash.xxh128(...)`, or is it the XXH3_128 algorithm rather than XXH128?🤖 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 `@internal/service/document.go` around lines 637 - 640, The code is using xxh3.Hash128 (XXH3_128) which differs from Python's xxhash.xxh128 (XXH128); replace the xxh3.Hash128(blob) call with a Go implementation of XXH128 (the same algorithm Python uses), e.g., call the library's XXH128 Sum/Hash function (instead of xxh3.Hash128) so the produced 16-byte sum matches Python's xxh128, keep the canonical big-endian ordering when converting to bytes and then hex.EncodeToString(sum[:]) to produce the 32-char content_hash, and update imports accordingly; locate the current usage of xxh3.Hash128 and variables sum/hash in this function and swap to the XXH128 implementation.
🤖 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 `@internal/service/document.go`:
- Around line 1081-1107: The code retrieves a document with
s.documentDAO.GetByID but never verifies it belongs to the provided datasetID;
before creating the ingestion task (and before calling CheckAndCreate), compare
doc.KbID (or the document's dataset identifier field) to datasetID and, if they
differ, append a ParseDocumentResponse for that docID with an appropriate error
like "document does not belong to dataset" and continue; ensure this check is
done immediately after the nil check for doc and before constructing the
entity.IngestionTask/CheckAndCreate call to prevent cross-dataset ingestion.
- Around line 1109-1135: You’re creating a persisted ingestion task with
s.ingestionTaskDAO.CheckAndCreate then marshaling and publishing it via
json.Marshal and msgQueueEngine.PublishTask; if marshal/publish fails you
currently return and leave a CREATED DB row. Fix by ensuring cleanup/rollback
when enqueue fails: after a marshal or PublishTask error, call the DAO to either
delete the task or update its status to FAILED (e.g., using
s.ingestionTaskDAO.Delete(task.ID) or s.ingestionTaskDAO.UpdateStatus(task.ID,
FAILED)); handle and log any cleanup errors but still return the original
marshal/publish error; alternatively move the DB write behind an outbox boundary
so the task is only persisted after successful enqueue.
- Around line 1148-1158: StopIngestionTasks currently calls
ingestionTaskDAO.SetStoppingByAPIServer(taskID) without checking ownership;
update StopIngestionTasks to scope by userID by calling an ownership-aware DAO
method (the same pattern used by RemoveIngestionTasks) — e.g., replace
SetStoppingByAPIServer(taskID) with a DAO method that accepts userID (like
SetStoppingByAPIServerForUser(taskID, userID) or equivalent), or add such a DAO
method if missing, and ensure it returns a not-found/forbidden error when the
task does not belong to userID so stops cannot be invoked on other users'
ingestion jobs.
---
Outside diff comments:
In `@internal/service/document.go`:
- Around line 591-599: The file row is created with s.fileDAO.Create(file)
before writing the mapping with s.file2DocumentDAO.Create, leaving an orphaned
file if the mapping insert fails; update the upload flow in the function
containing these calls to either wrap both operations in a single DB transaction
(so both create operations are committed or rolled back together) or, if a
transaction is not available, call s.fileDAO.Delete(fileID) when
s.file2DocumentDAO.Create(&entity.File2Document{...}) returns an error (ensure
you use the same fileID variable and handle/delete any errors from the delete
call).
---
Duplicate comments:
In `@internal/service/document.go`:
- Around line 637-640: The code is using xxh3.Hash128 (XXH3_128) which differs
from Python's xxhash.xxh128 (XXH128); replace the xxh3.Hash128(blob) call with a
Go implementation of XXH128 (the same algorithm Python uses), e.g., call the
library's XXH128 Sum/Hash function (instead of xxh3.Hash128) so the produced
16-byte sum matches Python's xxh128, keep the canonical big-endian ordering when
converting to bytes and then hex.EncodeToString(sum[:]) to produce the 32-char
content_hash, and update imports accordingly; locate the current usage of
xxh3.Hash128 and variables sum/hash in this function and swap to the XXH128
implementation.
🪄 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: 2e404b62-d056-4e61-8336-2123a35a327c
📒 Files selected for processing (5)
go.modinternal/handler/document.gointernal/handler/document_test.gointernal/router/router.gointernal/service/document.go
✅ Files skipped from review due to trivial changes (1)
- go.mod
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/router/router.go
- internal/handler/document_test.go
- internal/handler/document.go
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/document.go (1)
591-599:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRollback the
Filerow when thefile2documentinsert fails.Line 591 commits the file-manager entry before Line 595 writes the mapping. If the mapping insert fails, both upload callers return an error after deleting only the document/blob, which leaves an orphaned
filerow behind. DeletefileIDon that error path, or wrap the two writes in one transaction.Suggested fix
if err := s.fileDAO.Create(file); err != nil { return err } docID := doc.ID - return s.file2DocumentDAO.Create(&entity.File2Document{ + if err := s.file2DocumentDAO.Create(&entity.File2Document{ ID: strings.ReplaceAll(uuid.New().String(), "-", ""), FileID: &fileID, DocumentID: &docID, - }) + }); err != nil { + _, _ = s.fileDAO.DeleteByIDs([]string{fileID}) + return err + } + return nil🤖 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 `@internal/service/document.go` around lines 591 - 599, The file row is created with s.fileDAO.Create(file) before writing the mapping with s.file2DocumentDAO.Create, leaving an orphaned file if the mapping insert fails; update the upload flow in the function containing these calls to either wrap both operations in a single DB transaction (so both create operations are committed or rolled back together) or, if a transaction is not available, call s.fileDAO.Delete(fileID) when s.file2DocumentDAO.Create(&entity.File2Document{...}) returns an error (ensure you use the same fileID variable and handle/delete any errors from the delete call).
♻️ Duplicate comments (1)
internal/service/document.go (1)
637-640:⚠️ Potential issue | 🟠 MajorUse the same hash algorithm as Python here.
The 32-character width now matches, but
xxh3.Hash128computes XXH3_128, not Python’sxxhash.xxh128. Identical uploads from Go and Python will still get differentcontent_hashvalues.Does `github.com/zeebo/xxh3.Hash128` produce the same digest as Python `xxhash.xxh128(...)`, or is it the XXH3_128 algorithm rather than XXH128?🤖 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 `@internal/service/document.go` around lines 637 - 640, The code is using xxh3.Hash128 (XXH3_128) which differs from Python's xxhash.xxh128 (XXH128); replace the xxh3.Hash128(blob) call with a Go implementation of XXH128 (the same algorithm Python uses), e.g., call the library's XXH128 Sum/Hash function (instead of xxh3.Hash128) so the produced 16-byte sum matches Python's xxh128, keep the canonical big-endian ordering when converting to bytes and then hex.EncodeToString(sum[:]) to produce the 32-char content_hash, and update imports accordingly; locate the current usage of xxh3.Hash128 and variables sum/hash in this function and swap to the XXH128 implementation.
🤖 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 `@internal/service/document.go`:
- Around line 1081-1107: The code retrieves a document with
s.documentDAO.GetByID but never verifies it belongs to the provided datasetID;
before creating the ingestion task (and before calling CheckAndCreate), compare
doc.KbID (or the document's dataset identifier field) to datasetID and, if they
differ, append a ParseDocumentResponse for that docID with an appropriate error
like "document does not belong to dataset" and continue; ensure this check is
done immediately after the nil check for doc and before constructing the
entity.IngestionTask/CheckAndCreate call to prevent cross-dataset ingestion.
- Around line 1109-1135: You’re creating a persisted ingestion task with
s.ingestionTaskDAO.CheckAndCreate then marshaling and publishing it via
json.Marshal and msgQueueEngine.PublishTask; if marshal/publish fails you
currently return and leave a CREATED DB row. Fix by ensuring cleanup/rollback
when enqueue fails: after a marshal or PublishTask error, call the DAO to either
delete the task or update its status to FAILED (e.g., using
s.ingestionTaskDAO.Delete(task.ID) or s.ingestionTaskDAO.UpdateStatus(task.ID,
FAILED)); handle and log any cleanup errors but still return the original
marshal/publish error; alternatively move the DB write behind an outbox boundary
so the task is only persisted after successful enqueue.
- Around line 1148-1158: StopIngestionTasks currently calls
ingestionTaskDAO.SetStoppingByAPIServer(taskID) without checking ownership;
update StopIngestionTasks to scope by userID by calling an ownership-aware DAO
method (the same pattern used by RemoveIngestionTasks) — e.g., replace
SetStoppingByAPIServer(taskID) with a DAO method that accepts userID (like
SetStoppingByAPIServerForUser(taskID, userID) or equivalent), or add such a DAO
method if missing, and ensure it returns a not-found/forbidden error when the
task does not belong to userID so stops cannot be invoked on other users'
ingestion jobs.
---
Outside diff comments:
In `@internal/service/document.go`:
- Around line 591-599: The file row is created with s.fileDAO.Create(file)
before writing the mapping with s.file2DocumentDAO.Create, leaving an orphaned
file if the mapping insert fails; update the upload flow in the function
containing these calls to either wrap both operations in a single DB transaction
(so both create operations are committed or rolled back together) or, if a
transaction is not available, call s.fileDAO.Delete(fileID) when
s.file2DocumentDAO.Create(&entity.File2Document{...}) returns an error (ensure
you use the same fileID variable and handle/delete any errors from the delete
call).
---
Duplicate comments:
In `@internal/service/document.go`:
- Around line 637-640: The code is using xxh3.Hash128 (XXH3_128) which differs
from Python's xxhash.xxh128 (XXH128); replace the xxh3.Hash128(blob) call with a
Go implementation of XXH128 (the same algorithm Python uses), e.g., call the
library's XXH128 Sum/Hash function (instead of xxh3.Hash128) so the produced
16-byte sum matches Python's xxh128, keep the canonical big-endian ordering when
converting to bytes and then hex.EncodeToString(sum[:]) to produce the 32-char
content_hash, and update imports accordingly; locate the current usage of
xxh3.Hash128 and variables sum/hash in this function and swap to the XXH128
implementation.
🪄 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: 2e404b62-d056-4e61-8336-2123a35a327c
📒 Files selected for processing (5)
go.modinternal/handler/document.gointernal/handler/document_test.gointernal/router/router.gointernal/service/document.go
✅ Files skipped from review due to trivial changes (1)
- go.mod
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/router/router.go
- internal/handler/document_test.go
- internal/handler/document.go
🛑 Comments failed to post (3)
internal/service/document.go (3)
1081-1107:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject documents that do not belong to
datasetID.This loop only checks that the document exists, then writes the caller-supplied
datasetIDinto the ingestion task. AdocIDfrom another dataset will still be queued under the wrong dataset and can bypass dataset scoping upstream. Comparedoc.KbIDtodatasetIDbeforeCheckAndCreate.🤖 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 `@internal/service/document.go` around lines 1081 - 1107, The code retrieves a document with s.documentDAO.GetByID but never verifies it belongs to the provided datasetID; before creating the ingestion task (and before calling CheckAndCreate), compare doc.KbID (or the document's dataset identifier field) to datasetID and, if they differ, append a ParseDocumentResponse for that docID with an appropriate error like "document does not belong to dataset" and continue; ensure this check is done immediately after the nil check for doc and before constructing the entity.IngestionTask/CheckAndCreate call to prevent cross-dataset ingestion.
1109-1135:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon’t leave a persisted ingestion task behind when enqueueing fails.
CheckAndCreatewrites the task before Line 1133 publishes it. If marshal/publish fails, the function returns immediately and the DB keeps aCREATEDtask that will never run. Delete or mark that task failed before returning, or move this behind an outbox-style boundary.🤖 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 `@internal/service/document.go` around lines 1109 - 1135, You’re creating a persisted ingestion task with s.ingestionTaskDAO.CheckAndCreate then marshaling and publishing it via json.Marshal and msgQueueEngine.PublishTask; if marshal/publish fails you currently return and leave a CREATED DB row. Fix by ensuring cleanup/rollback when enqueue fails: after a marshal or PublishTask error, call the DAO to either delete the task or update its status to FAILED (e.g., using s.ingestionTaskDAO.Delete(task.ID) or s.ingestionTaskDAO.UpdateStatus(task.ID, FAILED)); handle and log any cleanup errors but still return the original marshal/publish error; alternatively move the DB write behind an outbox boundary so the task is only persisted after successful enqueue.
1148-1158:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winUse
userIDto scope stop operations.
RemoveIngestionTasksalready passesuserIDinto an ownership-aware DAO path, butStopIngestionTasksignores it and callsSetStoppingByAPIServer(taskID)directly. Unless ownership is rechecked elsewhere, task IDs become stop capabilities for other users’ ingestion jobs.🤖 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 `@internal/service/document.go` around lines 1148 - 1158, StopIngestionTasks currently calls ingestionTaskDAO.SetStoppingByAPIServer(taskID) without checking ownership; update StopIngestionTasks to scope by userID by calling an ownership-aware DAO method (the same pattern used by RemoveIngestionTasks) — e.g., replace SetStoppingByAPIServer(taskID) with a DAO method that accepts userID (like SetStoppingByAPIServerForUser(taskID, userID) or equivalent), or add such a DAO method if missing, and ensure it returns a not-found/forbidden error when the task does not belong to userID so stops cannot be invoked on other users' ingestion jobs.
Ports the Python `upload_document` endpoint (`api/apps/restful_apis/document_api.py:367`) to the Go server. Part of #15240.
What it does
`POST /api/v1/datasets/:dataset_id/documents` dispatches on the `type` query param:
It mirrors Python behavior closely: existence check before permission check (so a missing dataset returns
DATA_ERRORand an inaccessible one returnsAUTHENTICATION_ERROR), and the response keys are remapped to the public shape (`chunk_num→chunk_count`, `token_num→token_count`, `kb_id→dataset_id`, `parser_id→chunk_method`, `run→"UNSTART"`). No tokenization/embedding/doc-store writes happen here — that is the separate parse step.Not yet ported (documented gaps, no Go equivalent)
Tests
`internal/handler/document_upload_test.go` — handler tests via the fake-service harness + an in-memory dataset DB: unknown-type, dataset-not-found, no-permission (existence-before-permission), local no-file-part / success-with-mapped-keys / service-error, empty blank-name / success, web missing-name. `go build ./...`, `go vet`, and `gofmt` are clean.