Skip to content

feat[Go]: implement POST /datasets/<dataset_id>/documents upload (issue #15240) - #15715

Closed
dripsmvcp wants to merge 5 commits into
infiniflow:mainfrom
dripsmvcp:feat/go-api-document-upload
Closed

dripsmvcp wants to merge 5 commits into
infiniflow:mainfrom
dripsmvcp:feat/go-api-document-upload

Conversation

@dripsmvcp

Copy link
Copy Markdown
Contributor

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:

  • local (default): for each multipart `file`, stores the blob in object storage and inserts a `Document` row — filetype-derived `parser_id` (via the new `utility.GetParser`, mirroring `FileService.get_parser`), `parser_config` override merge (allow-listed `table_column_mode`/`table_column_roles` only), dedup filename rename, `size`, and an xxhash `content_hash`. Supports `parent_path` and `return_raw_files`.
  • empty: inserts a zero-byte `virtual` document, guarded against duplicate names.
  • web: performs the full request validation (name/url/length/URL format) and then returns an explicit unsupported error for the fetch step.

It mirrors Python behavior closely: existence check before permission check (so a missing dataset returns DATA_ERROR and an inaccessible one returns AUTHENTICATION_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)

  • web URL→PDF conversion (`html2pdf`) and thumbnail generation — surfaced as an explicit error rather than silent misbehavior.
  • `read_potential_broken_pdf` repair and the file-manager folder linking (`add_file_from_kb`/`file2document`). The `Document` row alone makes the file visible and parseable in the dataset.

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.

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

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e404b62-d056-4e61-8336-2123a35a327c

📥 Commits

Reviewing files that changed from the base of the PR and between a3362dd and 73e91f9.

📒 Files selected for processing (5)
  • go.mod
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/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

📝 Walkthrough

Walkthrough

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

Changes

Document Upload Feature

Layer / File(s) Summary
Data Access & Utility Foundations
internal/dao/document.go, internal/service/dataset.go, internal/utility/file.go, go.mod
DAO adds ListNamesByKbID. DatasetService adds GetKBByID. File utility adds GetParser. go.mod adds github.com/zeebo/xxh3.
HTTP Handler & Response Mapping
internal/handler/document.go
Adds UploadDocuments handler, multipart/form parsing imports, extends documentServiceIface with three upload methods, validates dataset access and inputs, dispatches by type (local/web/empty), parses allow-listed parser_config, maps service output to response shape forcing run to UNSTART, and adds shared helpers (success envelope, key mapping, URL validation).
Document Upload Service Implementation
internal/service/document.go
Adds UploadLocalDocuments (reads multipart bytes, validates type, deduplicates names, computes unique filenames, uploads blobs, creates Document rows with merged parser config and xxhash content hash, links into file-manager), UploadEmptyDocument (creates zero-byte virtual document row and links it), and UploadWebDocument (returns not-supported). Includes helpers to build Document rows, map to raw response, ensure unique names, and read multipart bytes.
Tests & Route Registration
internal/router/router.go, internal/handler/document_test.go, internal/handler/document_upload_test.go, internal/service/document_upload_link_test.go
Registers POST /api/v1/datasets/:dataset_id/documents. Adds upload test harness wiring a fake document service, multipart request helpers, extends fake service with upload stubs/state, and tests covering unknown type, dataset not found, permission denial, local upload validation/success/error, empty upload validation/success, web upload validation, and service-level linkage tests.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Suggested labels

💞 feature, size:XXL

Suggested reviewers

  • Hz-186

Poem

🐰 I hopped through code, a tiny clerk,

Multipart files and names that work,
Blobs tucked safe in object stores,
Empty seeds and dedupe scores,
Datasets hum with tidy perks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing a POST endpoint for document uploads in the Go server, mapping directly to the changeset focus.
Description check ✅ Passed The description comprehensively explains the problem solved (porting Python endpoint), implementation details for each upload type, response key mapping, test coverage, and acknowledged gaps. However, it does not follow the required template structure with 'Type of change' checkbox.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/service/document.go (1)

217-219: 💤 Low value

Consider bounded retry for storage collision loop.

The collision handling appends _ in a loop until ObjExist returns false. While collisions should be rare, consider adding a maximum retry count (e.g., 100) to prevent infinite loops if ObjExist has 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 win

Consider reporting invalid parser_config JSON to user.

Invalid parser_config JSON is silently ignored (line 183 checks == nil after Unmarshal). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1deb131 and 4092cd3.

📒 Files selected for processing (8)
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/handler/document_upload_test.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
  • internal/utility/file.go

Comment thread internal/service/document.go Outdated
Comment on lines +288 to +289
hash := fmt.Sprintf("%016x", xxhash.Sum64(blob))
doc.ContentHash = &hash

@coderabbitai coderabbitai Bot Jun 5, 2026 •

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

🧩 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 || true

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

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

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

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

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

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

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

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

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 -ba

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

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

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

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@dripsmvcp fix this

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.

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!

@dripsmvcp
dripsmvcp force-pushed the feat/go-api-document-upload branch from 4092cd3 to fe57ebf Compare June 8, 2026 08: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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4092cd3 and fe57ebf.

📒 Files selected for processing (8)
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/handler/document_upload_test.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
  • internal/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

Comment on lines +185 to +197
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
}
}

@coderabbitai coderabbitai Bot Jun 8, 2026 •

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@dripsmvcp fix this

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.

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!

Comment thread internal/service/document.go Resolved
Comment thread internal/service/document.go Resolved
Comment thread internal/service/document.go Resolved
…(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.
@dripsmvcp
dripsmvcp force-pushed the feat/go-api-document-upload branch from fe57ebf to 6d617d9 Compare June 9, 2026 02:06

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
internal/handler/document.go (1)

185-197: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe57ebf and 6d617d9.

📒 Files selected for processing (8)
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/handler/document_upload_test.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
  • internal/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

Comment thread internal/handler/document.go Resolved
@Haruko386 Haruko386 added the ci Continue Integration label Jun 9, 2026

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I test it in RAGFLow front-end
and I can't upload any file with your code.

fix it plz

@Haruko386
Haruko386 marked this pull request as draft June 9, 2026 02:41
@Haruko386

Copy link
Copy Markdown
Member

@dripsmvcp you can make it ready to review when you fix the issue, and then, CI will run with you click

dripsmvcp added 2 commits June 9, 2026 12:33
…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.
@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

@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.
@dripsmvcp
dripsmvcp marked this pull request as ready for review June 12, 2026 04:51
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 12, 2026
@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@Hz-186 Resolved the issue

@codecov

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (22a058f) to head (73e91f9).
⚠️ Report is 1144 commits behind head on main.

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

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

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

Rollback the File row when the file2document insert 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 file row behind. Delete fileID on 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 | 🟠 Major

Use the same hash algorithm as Python here.

The 32-character width now matches, but xxh3.Hash128 computes XXH3_128, not Python’s xxhash.xxh128. Identical uploads from Go and Python will still get different content_hash values.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3362dd and 73e91f9.

📒 Files selected for processing (5)
  • go.mod
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/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

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

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 win

Rollback the File row when the file2document insert 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 file row behind. Delete fileID on 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 | 🟠 Major

Use the same hash algorithm as Python here.

The 32-character width now matches, but xxh3.Hash128 computes XXH3_128, not Python’s xxhash.xxh128. Identical uploads from Go and Python will still get different content_hash values.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3362dd and 73e91f9.

📒 Files selected for processing (5)
  • go.mod
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/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 win

Reject documents that do not belong to datasetID.

This loop only checks that the document exists, then writes the caller-supplied datasetID into the ingestion task. A docID from another dataset will still be queued under the wrong dataset and can bypass dataset scoping upstream. Compare doc.KbID to datasetID before CheckAndCreate.

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

Don’t leave a persisted ingestion task behind when enqueueing fails.

CheckAndCreate writes the task before Line 1133 publishes it. If marshal/publish fails, the function returns immediately and the DB keeps a CREATED task 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 win

Use userID to scope stop operations.

RemoveIngestionTasks already passes userID into an ownership-aware DAO path, but StopIngestionTasks ignores it and calls SetStoppingByAPIServer(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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants