Skip to content

Feature: task executor migration to go - #16549

Merged
yingfeng merged 4 commits into
infiniflow:mainfrom
xugangqiang:feat/te-pipeline
Jul 8, 2026
Merged

yingfeng merged 4 commits into
infiniflow:mainfrom
xugangqiang:feat/te-pipeline

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Feature: Integrate parser

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ef0d40e4-5e94-41b2-9e70-cbcdc045ed67

📥 Commits

Reviewing files that changed from the base of the PR and between f316153 and bd41a81.

📒 Files selected for processing (2)
  • cmd/ragflow_server.go
  • internal/ingestion/testutil/mocks.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/ragflow_server.go
  • internal/ingestion/testutil/mocks.go

📝 Walkthrough

Walkthrough

This PR updates ingestion execution, chunk processing, and pipeline tooling, while adding real integration coverage and supporting DAO/test utilities. It also adjusts analyzer build tags, parser factory stubs, metadata merging, and a few document/service behaviors.

Changes

Ingestion Pipeline: Task Routing, Dataflow, and Chunk Processing

Layer / File(s) Summary
CGO/non-CGO analyzer binding relocation
internal/binding/rag_analyzer.go, internal/binding/rag_analyzer_nocgo.go, internal/deepdoc/parser/pdf/parse_nocgo.go
Moves the CGO build tag and adds license headers to non-CGO stub files.
Task context, handler routing, and ingestion service
internal/ingestion/task/constants.go, task_context*.go, task_handler*.go, real_consumer_test.go, internal/ingestion/service/*.go, internal/ingestion/testutil/*.go, internal/dao/document.go, internal/dao/ingestion.go, internal/dao/pipeline_operation_log.go, internal/dao/task*.go, internal/entity/models/types.go, internal/handler/document.go, cmd/ragflow_server.go, internal/service/document.go
Adds task context loading, task routing, ingestion worker execution, DAO helpers, test utilities/mocks, startup wiring, and document ingest/count updates.
DataflowExecutor orchestration
internal/ingestion/task/dataflow_service*.go, embedding*.go, has_vectors_test.go, dataflow_chunk_assets.go, dataflow_e2e_test.go
Replaces the dataflow service with a PipelineExecutor flow for loading DSL, running pipelines, processing chunks, inserting results, and reporting progress.
Chunk processing, merging, and golden tooling
chunk_builder*.go, chunk_process*.go, chunk_utils*.go, position*.go, naive_merge*.go, golden_compare*.go, tool/compare_dataflow_golden.go, pipeline_run_output_checklist.md, dataflow_real_pipeline_integration_test.go, .gitignore
Adds chunk builders, post-processing utilities, naive merge logic, golden replay comparison tooling, output-contract notes, real pipeline integration tests, and ignore rules for the compare tool.
Metadata merge utility
internal/utility/metadata*.go
Implements normalized metadata merging with unit tests.
Real storage and template pipeline integration tests
internal/ingestion/pipeline/*_test.go
Adds real MySQL/MinIO integration coverage and font-discovery fallback updates.
Parser factory stub
internal/parser/parser/factory*.go
Adds a parser factory returning stub parsers per parser ID, with tests.

Estimated code review effort: 5 (Critical) | ~120 minutes

Suggested labels: 💞 feature, ci, size:XXL

Suggested reviewers: yingfeng, JinHai-CN, yuzhichang

Poem

A rabbit bounced through queues and flows,
Where chunks and tokens deftlyോസ്?
The golden tool now checks the trail,
And parser stubs won’t miss their mail.
🐇 Thump! The pipeline hops ahead.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has a Summary section, but its content is off-topic and does not describe the actual PR changes. Replace it with a brief summary of the Go task-executor migration and key ingestion/dataflow/parser changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: migrating the task executor/ingestion path to Go.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@xugangqiang
xugangqiang force-pushed the feat/te-pipeline branch 2 times, most recently from 2eceb07 to 908188c Compare July 2, 2026 09:49
@xugangqiang xugangqiang added the ci Continue Integration label Jul 3, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review July 3, 2026 13:36
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 3, 2026
@xugangqiang
xugangqiang marked this pull request as draft July 3, 2026 13:39
@xugangqiang
xugangqiang marked this pull request as ready for review July 3, 2026 13:39
@xugangqiang xugangqiang changed the title Feature: Integrate parser Feature: task executor migration to go Jul 3, 2026

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

🧹 Nitpick comments (12)
internal/deepdoc/parser/pdf/parse_nocgo.go (1)

1-16: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add the Apache-2.0 header here to match the rest of internal/deepdoc/parser/pdf.

🤖 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/deepdoc/parser/pdf/parse_nocgo.go` around lines 1 - 16, The stub in
Parser.Parse under parse_nocgo.go is missing the Apache-2.0 license header used
by the rest of internal/deepdoc/parser/pdf. Add the standard Apache-2.0 header
comment at the top of this file, keeping the existing //go:build !cgo directive
and the Parse method unchanged.
internal/ingestion/task/task_handler.go (1)

30-36: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider guarding against a nil TaskContext.

Handle() dereferences h.ctx.Task unconditionally. If a caller ever passes a nil context (e.g., neglecting to check LoadTaskContext's error before constructing the handler), this panics and could take down the processing loop.

🛡️ Proposed defensive guard
 func (h *TaskHandler) Handle() error {
+	if h.ctx == nil {
+		return fmt.Errorf("task handler: nil task context")
+	}
 	taskType := h.ctx.Task.TaskType
🤖 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/ingestion/task/task_handler.go` around lines 30 - 36, Add a
defensive nil check in NewTaskHandler/Handle for TaskContext before
dereferencing h.ctx.Task, since Handle currently assumes ctx is always present.
Update TaskHandler.Handle to return a meaningful error when h.ctx is nil (and/or
h.ctx.Task is nil) instead of panicking, so callers that misuse LoadTaskContext
don’t crash the processing loop.
internal/ingestion/task/real_consumer_test.go (1)

112-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent return on task-not-found hides skipped assertions.

Returning instead of calling t.Skip(...) makes the test report PASS even though none of the downstream assertions (LoadTaskContext, Handle(), final status check) ran. Prefer t.Skip so the test result clearly communicates the run was incomplete.

♻️ Proposed fix
 		if errors.Is(err, common.ErrTaskNotFound) {
 			t.Logf("Consumer: task %s not found in ingestion_task table — skipped", taskMsg.TaskID)
 			taskHandle.Ack()
-			return
+			t.Skip("task not found in ingestion_task table")
 		}
🤖 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/ingestion/task/real_consumer_test.go` around lines 112 - 124, The
task-not-found branch in real_consumer_test.go currently returns early from the
test after SetRunningByIngestor, which makes the run look like a pass even
though the later LoadTaskContext, Handle(), and status assertions are skipped.
Update the error handling around dao.NewIngestionTaskDAO().SetRunningByIngestor
so that when errors.Is(err, common.ErrTaskNotFound) is true, the test uses
t.Skip(...) instead of returning, keeping the intent clear while preserving the
existing taskHandle.Ack() cleanup.
internal/ingestion/parser/post/post_steps.go (1)

246-292: 🚀 Performance & Scalability | 🔵 Trivial

Silent failures in VLM enhancement.

Individual DescribeImage/DecodeBase64PNG errors inside the goroutine are swallowed (if err != nil ... return) with no logging, making systemic failures (e.g. bad API key causing 100% describe failures) invisible in production.

🤖 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/ingestion/parser/post/post_steps.go` around lines 246 - 292, The VLM
enrichment path in enhanceWithVision currently swallows DecodeBase64PNG and
DescribeImage failures inside the goroutine, which hides repeated system-wide
failures. Update enhanceWithVision to log decode/describe errors with enough
context (section index and DocTypeKwd/image state) before returning, and keep
the existing early-return behavior so one bad image does not stop the rest. Use
the existing enhanceWithVision, DescribeImage, and util.DecodeBase64PNG call
sites to place the logging directly where the failures occur.
internal/ingestion/parser/post/post_steps_test.go (1)

239-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test doesn't actually assert anything — t.Log instead of t.Error.

This test will pass even if reorderMultiColumn is completely broken, since the conditional only logs and never fails the test.

✅ Proposed fix
 	reorderMultiColumn(result, 600.0, 1.0)
-	if result.Sections[0].Positions[0].Left > result.Sections[1].Positions[0].Left {
-		t.Log("multi-column: sections reordered")
-	}
+	if result.Sections[0].Text != "A" || result.Sections[1].Text != "B" {
+		t.Errorf("expected reorder to [A, B], got [%s, %s]", result.Sections[0].Text, result.Sections[1].Text)
+	}
 }
🤖 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/ingestion/parser/post/post_steps_test.go` around lines 239 - 248,
The test TestReorderMultiColumn_MultiCol currently only calls t.Log after
checking reorderMultiColumn, so it never fails when the ordering is wrong.
Update the assertion in this test to actively fail the test when
result.Sections[0].Positions[0].Left is not less than
result.Sections[1].Positions[0].Left, using t.Error/t.Fatalf or an equivalent
assert so the behavior of reorderMultiColumn is actually validated.
internal/ingestion/e2e_parse_test.go (1)

185-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

E2E test only checks for a nil error — doesn't verify actual parse output.

TestE2E_ParseDocument_RealPDF exercises the full DB → storage → PDF-parse → chunk chain but only asserts err == nil. A regression causing ParseWithDeepDoc to silently return zero sections (or prepareDocs/UploadChunkImages to no-op) would still pass this test. Consider asserting on chunk count (e.g., via the DAO or by having parseDocument return the generated chunks) to make the "full chain verified" claim meaningful.

🤖 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/ingestion/e2e_parse_test.go` around lines 185 - 222,
TestE2E_ParseDocument_RealPDF only asserts that ingestor.parseDocument returns
nil, so it can miss regressions where the PDF parsing or chunking pipeline
produces no output. Update this test to verify actual parse results by checking
the generated chunks/sections through the DAO or by exposing the output from
parseDocument, and assert that the expected non-zero chunk count is produced
after ParseWithDeepDoc/prepareDocs/UploadChunkImages run.
internal/ingestion/ingestion_service.go (2)

666-676: 🎯 Functional Correctness | 🔵 Trivial

FIXME: hardcoded parser config ignores per-document settings.

doctype.DefaultParserConfig() is used unconditionally, ignoring doc.ParserConfig (which the e2e test seeds as entity.JSONMap{}, implying it's meant to be consumed eventually). This is already called out via the FIXME/TODO comments. Want me to draft the mapping from entity.Document.ParserConfig to doctype.ParserConfig, or should this be tracked as a follow-up issue?

🤖 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/ingestion/ingestion_service.go` around lines 666 - 676, The PDF
parsing path in ingestion_service’s ParseWithDeepDoc call is always using
doctype.DefaultParserConfig(), so per-document settings from
entity.Document.ParserConfig are ignored. Update the parsing flow to read and
map doc.ParserConfig into the parser config passed to p.ParseWithDeepDoc, and
keep the fallback to defaults only when no document-specific config is present.
Use the existing p setup in the ingestion service to locate the change.

646-664: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Storage fetch happens before the cheap PDF type-check.

Step 3 (fetching the full document bytes from storage) runs unconditionally before step 4's lightweight doc.Type/doc.Suffix check that immediately skips non-PDF documents. Reordering the type-check ahead of the storage fetch avoids unnecessary network/storage I/O for every non-PDF document.

♻️ Proposed reorder
+	// Only PDF parsing for now (hardcoded)
+	if !strings.EqualFold(doc.Type, "pdf") && !strings.HasSuffix(strings.ToLower(doc.Suffix), ".pdf") {
+		common.Info(fmt.Sprintf("Skipping non-PDF: type=%s suffix=%s", doc.Type, doc.Suffix))
+		return nil
+	}
+
 	// 3. Fetch binary from storage
 	storageImpl := e.storageImpl
 	...
 	common.Info(fmt.Sprintf("Fetched %d bytes from storage", len(data)))
-
-	// 4. Only PDF parsing for now (hardcoded)
-	if !strings.EqualFold(doc.Type, "pdf") && !strings.HasSuffix(strings.ToLower(doc.Suffix), ".pdf") {
-		common.Info(fmt.Sprintf("Skipping non-PDF: type=%s suffix=%s", doc.Type, doc.Suffix))
-		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/ingestion/ingestion_service.go` around lines 646 - 664, The
ingestion flow in ingestion_service.go fetches the document bytes from storage
before checking whether the document is a PDF, which causes unnecessary I/O for
non-PDFs. Move the lightweight PDF gate in the ingestion path (the
doc.Type/doc.Suffix check in the same block that currently logs “Skipping
non-PDF”) to run before calling storageImpl.Get, and only fetch from storage
when the document passes that check. Keep the existing logging and error
handling in the storage fetch path unchanged.
internal/ingestion/chunk_builder_test.go (1)

97-112: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Regex allows variable-length IDs, masking the zero-padding bug.

^[0-9a-f]{1,16}$ accepts IDs shorter than 16 hex chars, so this test won't catch the missing zero-padding in chunkID (see comment on chunk_builder.go chunkID). Consider tightening to ^[0-9a-f]{16}$ once the underlying fix lands.

🤖 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/ingestion/chunk_builder_test.go` around lines 97 - 112, The ID
format test in TestPrepareDocs_IDFormat is too permissive because the regex
allows 1–16 hex characters, so it won’t detect the zero-padding issue in
chunkID. Tighten the assertion on chunks[0].ID to require exactly 16 lowercase
hex characters after the chunkID fix is in place, and keep the empty-ID check so
the test verifies both presence and correct fixed-width formatting.
internal/ingestion/naive_merge.go (2)

169-243: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Dead delimiter-match check recompiles a regex on every part inside the split loop.

In the oversized-text branch (lines 174-191), regexp.MatchString("^("+delimPattern+")$", part) is called for every split part — this compiles a fresh regex on each call, which is wasteful in a hot loop over potentially many segments/pages. Additionally, this check is unreachable: re.Split (line 178) already strips matched delimiters entirely (capture groups don't change this), so part can never equal the delimiter pattern. Recommend dropping the check and precompiling any regex used outside the loop.

Also, tk := tokenizer.NumTokensFromString(sub.text) (line 201) is computed and discarded via _ = tk (line 238) without ever being used — dead local.

🧹 Proposed cleanup
 			for _, part := range parts {
 				if part == "" {
 					continue
 				}
-				if matched, _ := regexp.MatchString("^("+delimPattern+")$", part); matched {
-					continue
-				}
 				subSegments = append(subSegments, indexedText{
					text: "\n" + part,
					idx:  it.idx,
					pos:  it.pos,
				})
			}
 		for _, sub := range subSegments {
-			tk := tokenizer.NumTokensFromString(sub.text)
 			pos := resolvePosition(sub.text, sub.pos)
🤖 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/ingestion/naive_merge.go` around lines 169 - 243, The oversized-text
path in mergeByTokenCount contains a redundant delimiter check that recompiles a
regex for every split part; remove the
regexp.MatchString("^("+delimPattern+")$", part) branch inside the re.Split loop
since split parts cannot equal the delimiter, and keep any needed regex usage
precompiled outside the loop. Also remove the unused tk local in the subSegments
loop, including the final dead assignment, to clean up the token-count path in
mergeByTokenCount.

126-165: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Drop the dead delimiter check in internal/ingestion/naive_merge.go. regexp.Split already strips the matched delimiter, so part == d can never be true here.

🤖 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/ingestion/naive_merge.go` around lines 126 - 165, The dead delimiter
check inside mergeByCustomDelimiters is unreachable because regexp.Split already
removes the matched delimiters, so the part == d branch can never fire. Remove
that isDelimiter loop from mergeByCustomDelimiters and keep the remaining
split-and-append flow intact using the existing pattern, customDels, and
MergedSegment construction.
internal/ingestion/parse_document_test.go (1)

175-188: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Error-content assertion is a no-op.

errors.Is(err, errors.New("record not found")) will always return false (two separate errors.New calls are never equal, and errors.Is doesn't do string comparison), so !errors.Is(...) is always true and the guarded block — which only contains a comment — never actually validates anything about the error's content. This test currently only checks err != nil.

✅ Proposed fix
 	err := e.parseDocument(context.Background(), testTask("doc-1"))
 	if err == nil {
 		t.Fatal("expected error for doc not found")
 	}
-	if !errors.Is(err, errors.New("record not found")) {
-		// Just check it contains the root error
-	}
+	if !strings.Contains(err.Error(), "record not found") {
+		t.Errorf("error %q does not contain expected root cause", err)
+	}

(would additionally require importing "strings")

🤖 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/ingestion/parse_document_test.go` around lines 175 - 188, The
error-content assertion in TestParseDocument_DocNotFound is ineffective because
it compares against a fresh errors.New value, so it never validates the returned
error. Update the test around parseDocument and mockDocDAO to assert the actual
error message content instead, for example by checking the returned error string
contains “record not found” (and import strings if needed), or by comparing
against a shared sentinel error rather than constructing a new one inline.
🤖 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/ingestion/chunk_builder.go`:
- Around line 103-111: The chunkID helper is dropping leading zeroes because
strconv.FormatUint does not produce a fixed-width xxhash hex string. Update
chunkID in chunkID to zero-pad the xxhash.Sum64String result to 16 hex
characters so it matches Python’s xxhash.xxh64(...).hexdigest() output, and
adjust the chunk ID format test to assert the returned ID length is 16.

In `@internal/ingestion/ingestion_service.go`:
- Around line 580-583: The checkpoint update in the ingestion flow is being
mutated on latestLog but never written back, so the change has no effect. In the
code around the checkpoint bump in ingestion_service.go, either persist
latestLog through the existing DAO/repository method after setting
latestLog.Checkpoint, or remove the dead checkpointMap/current_step mutation and
the unused totalStep reference if resumability is no longer needed. Use the
surrounding ingestion checkpoint logic to locate the right save path and keep
the behavior consistent with the rest of the ingestion service.
- Around line 689-697: The chunk summary logging in the ingestion flow is
exposing document content through c.String() at Info level, which can leak user
data. Update the chunk logging in the ingestion service to avoid printing
content previews and only log safe metadata like chunk count and identifiers, or
move the detailed output behind a debug-level or feature-flagged path. Locate
the summary loop in the ingestion pipeline around the chunk generation section
and adjust the logging calls accordingly.

In `@internal/ingestion/parser/factory.go`:
- Around line 24-52: GetParser currently պահանջs lib_type before the switch even
for parser types that never use it, causing unnecessary “missing lib_type
config” errors for FileTypePDF, FileTypeHTML, and FileTypeMarkdown. Move the
config["lib_type"] lookup and validation into only the branches that call
NewPPTXParser, NewPPTParser, NewXLSXParser, NewXLSParser, NewDOCXParser, and
NewDOCParser, while leaving NewPDFParser, NewHTMLParser, and NewMarkdownParser
independent of libType. Keep the unsupported-file-type error path unchanged and
use GetParser’s existing switch plus the constructor names to guide the
refactor.

In `@internal/ingestion/parser/pdf_parser.go`:
- Around line 48-66: ParseWithDeepDoc is hardcoding the DeepDoc endpoint to
localhost, which bypasses the configured DeepDoc URL. Update the client creation
in PDFParser.ParseWithDeepDoc to read and use the existing DeepDoc configuration
source (including DEEPDOC_URL and any TENSORRT_DLA_SVR fallback) instead of
passing a fixed URL to i.NewClient, so remote or containerized deployments
resolve correctly.
- Around line 60-63: ParseWithDeepDoc currently builds the pipeline config from
an empty map, so parser settings like page_width, remove_toc,
flatten_media_to_text, tenant_id, and vlm_llm_id never reach post-processing.
Update ParseWithDeepDoc in pdf_parser.go to thread the parser’s pipeline-related
config into buildPipelineConfig instead of using make(map[string]any), and
ensure the relevant fields are exposed on the parser config and passed through
to post.PostProcess so the optional post-processing steps can be controlled from
this entry point.

In `@internal/ingestion/parser/post/model_image_describer.go`:
- Around line 57-62: `NewModelImageDescriber` accepts maxTokens, but the value
is never propagated because `ChatConfig` has no `MaxTokens` field and the
`chatCfg` assignment in `Describe`/request setup is effectively a no-op. Add a
`MaxTokens` field to `ChatConfig` and make the `ModelImageDescriber` flow
populate it when `maxTokens > 0`, then ensure the chat request path actually
reads that field so the limit is applied as intended.
- Around line 84-91: The image description flow in the method that calls
d.driver.ChatWithMessages must defensively handle a nil response before
accessing resp.Answer. Update the nil/empty validation in
model_image_describer.go so it treats resp == nil the same as an empty answer
and returns a clear error instead of dereferencing it. Keep the fix localized to
the ChatWithMessages response handling in the image describer path.

In `@internal/ingestion/parser/post/post_steps.go`:
- Around line 152-163: The VLM enhancement block in postSteps currently calls
resolveImageDescriber without checking whether the resolver was registered,
which can panic when tenantID and vlmLLMID are set. Add a nil guard around
resolveImageDescriber before invoking it, and either return a clear error or
skip the enhanceWithVision path when the resolver is absent. Use the existing
postSteps VLM enhancement flow and the resolveImageDescriber / enhanceWithVision
symbols to place the fix correctly.

In `@internal/ingestion/task/real_consumer_test.go`:
- Around line 37-46: The real consumer test is currently an unconditional
network-dependent unit test and can pass without covering the missing-task
failure path. Update TestRealProducerConsumer to be gated as an integration test
so it only runs when a NATS broker is available, and adjust the ErrTaskNotFound
branch so it fails the test instead of logging and returning early. Keep the
final assertions in the test flow and use the existing nats.NewNatsEngine,
InitConsumer, and ErrTaskNotFound symbols to locate the checks.

---

Nitpick comments:
In `@internal/deepdoc/parser/pdf/parse_nocgo.go`:
- Around line 1-16: The stub in Parser.Parse under parse_nocgo.go is missing the
Apache-2.0 license header used by the rest of internal/deepdoc/parser/pdf. Add
the standard Apache-2.0 header comment at the top of this file, keeping the
existing //go:build !cgo directive and the Parse method unchanged.

In `@internal/ingestion/chunk_builder_test.go`:
- Around line 97-112: The ID format test in TestPrepareDocs_IDFormat is too
permissive because the regex allows 1–16 hex characters, so it won’t detect the
zero-padding issue in chunkID. Tighten the assertion on chunks[0].ID to require
exactly 16 lowercase hex characters after the chunkID fix is in place, and keep
the empty-ID check so the test verifies both presence and correct fixed-width
formatting.

In `@internal/ingestion/e2e_parse_test.go`:
- Around line 185-222: TestE2E_ParseDocument_RealPDF only asserts that
ingestor.parseDocument returns nil, so it can miss regressions where the PDF
parsing or chunking pipeline produces no output. Update this test to verify
actual parse results by checking the generated chunks/sections through the DAO
or by exposing the output from parseDocument, and assert that the expected
non-zero chunk count is produced after
ParseWithDeepDoc/prepareDocs/UploadChunkImages run.

In `@internal/ingestion/ingestion_service.go`:
- Around line 666-676: The PDF parsing path in ingestion_service’s
ParseWithDeepDoc call is always using doctype.DefaultParserConfig(), so
per-document settings from entity.Document.ParserConfig are ignored. Update the
parsing flow to read and map doc.ParserConfig into the parser config passed to
p.ParseWithDeepDoc, and keep the fallback to defaults only when no
document-specific config is present. Use the existing p setup in the ingestion
service to locate the change.
- Around line 646-664: The ingestion flow in ingestion_service.go fetches the
document bytes from storage before checking whether the document is a PDF, which
causes unnecessary I/O for non-PDFs. Move the lightweight PDF gate in the
ingestion path (the doc.Type/doc.Suffix check in the same block that currently
logs “Skipping non-PDF”) to run before calling storageImpl.Get, and only fetch
from storage when the document passes that check. Keep the existing logging and
error handling in the storage fetch path unchanged.

In `@internal/ingestion/naive_merge.go`:
- Around line 169-243: The oversized-text path in mergeByTokenCount contains a
redundant delimiter check that recompiles a regex for every split part; remove
the regexp.MatchString("^("+delimPattern+")$", part) branch inside the re.Split
loop since split parts cannot equal the delimiter, and keep any needed regex
usage precompiled outside the loop. Also remove the unused tk local in the
subSegments loop, including the final dead assignment, to clean up the
token-count path in mergeByTokenCount.
- Around line 126-165: The dead delimiter check inside mergeByCustomDelimiters
is unreachable because regexp.Split already removes the matched delimiters, so
the part == d branch can never fire. Remove that isDelimiter loop from
mergeByCustomDelimiters and keep the remaining split-and-append flow intact
using the existing pattern, customDels, and MergedSegment construction.

In `@internal/ingestion/parse_document_test.go`:
- Around line 175-188: The error-content assertion in
TestParseDocument_DocNotFound is ineffective because it compares against a fresh
errors.New value, so it never validates the returned error. Update the test
around parseDocument and mockDocDAO to assert the actual error message content
instead, for example by checking the returned error string contains “record not
found” (and import strings if needed), or by comparing against a shared sentinel
error rather than constructing a new one inline.

In `@internal/ingestion/parser/post/post_steps_test.go`:
- Around line 239-248: The test TestReorderMultiColumn_MultiCol currently only
calls t.Log after checking reorderMultiColumn, so it never fails when the
ordering is wrong. Update the assertion in this test to actively fail the test
when result.Sections[0].Positions[0].Left is not less than
result.Sections[1].Positions[0].Left, using t.Error/t.Fatalf or an equivalent
assert so the behavior of reorderMultiColumn is actually validated.

In `@internal/ingestion/parser/post/post_steps.go`:
- Around line 246-292: The VLM enrichment path in enhanceWithVision currently
swallows DecodeBase64PNG and DescribeImage failures inside the goroutine, which
hides repeated system-wide failures. Update enhanceWithVision to log
decode/describe errors with enough context (section index and DocTypeKwd/image
state) before returning, and keep the existing early-return behavior so one bad
image does not stop the rest. Use the existing enhanceWithVision, DescribeImage,
and util.DecodeBase64PNG call sites to place the logging directly where the
failures occur.

In `@internal/ingestion/task/real_consumer_test.go`:
- Around line 112-124: The task-not-found branch in real_consumer_test.go
currently returns early from the test after SetRunningByIngestor, which makes
the run look like a pass even though the later LoadTaskContext, Handle(), and
status assertions are skipped. Update the error handling around
dao.NewIngestionTaskDAO().SetRunningByIngestor so that when errors.Is(err,
common.ErrTaskNotFound) is true, the test uses t.Skip(...) instead of returning,
keeping the intent clear while preserving the existing taskHandle.Ack() cleanup.

In `@internal/ingestion/task/task_handler.go`:
- Around line 30-36: Add a defensive nil check in NewTaskHandler/Handle for
TaskContext before dereferencing h.ctx.Task, since Handle currently assumes ctx
is always present. Update TaskHandler.Handle to return a meaningful error when
h.ctx is nil (and/or h.ctx.Task is nil) instead of panicking, so callers that
misuse LoadTaskContext don’t crash the processing loop.
🪄 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: c0f74b95-a0ae-45a9-a1fc-f468ab345977

📥 Commits

Reviewing files that changed from the base of the PR and between 2ef7818 and 908188c.

📒 Files selected for processing (29)
  • internal/binding/rag_analyzer.go
  • internal/binding/rag_analyzer_stub.go
  • internal/deepdoc/parser/pdf/parse_nocgo.go
  • internal/ingestion/chunk_builder.go
  • internal/ingestion/chunk_builder_test.go
  • internal/ingestion/e2e_parse_test.go
  • internal/ingestion/ingestion_service.go
  • internal/ingestion/naive_merge.go
  • internal/ingestion/naive_merge_test.go
  • internal/ingestion/parse_document_test.go
  • internal/ingestion/parser/factory.go
  • internal/ingestion/parser/parser_factory_test.go
  • internal/ingestion/parser/pdf_parser.go
  • internal/ingestion/parser/pdf_parser_test.go
  • internal/ingestion/parser/post/model_image_describer.go
  • internal/ingestion/parser/post/model_image_describer_test.go
  • internal/ingestion/parser/post/outline_postprocess_test.go
  • internal/ingestion/parser/post/post_steps.go
  • internal/ingestion/parser/post/post_steps_test.go
  • internal/ingestion/parser/post/vision_describe.go
  • internal/ingestion/parser/post/vision_describe_test.go
  • internal/ingestion/parser/stub_parsers.go
  • internal/ingestion/parser/type.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/real_consumer_test.go
  • internal/ingestion/task/task_context.go
  • internal/ingestion/task/task_context_test.go
  • internal/ingestion/task/task_handler.go
  • internal/ingestion/task/task_handler_test.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/parser/type.go

Comment thread internal/ingestion/chunk_builder.go Outdated
Comment on lines +103 to +111
// chunkID generates a deterministic chunk identifier matching Python's:
//
// xxhash.xxh64((content_with_weight + str(doc_id)).encode("utf-8", "surrogatepass")).hexdigest()
func chunkID(contentWithWeight, docID string) string {
return strconv.FormatUint(
xxhash.Sum64String(contentWithWeight+docID),
16,
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== target file outline ==\n'
ast-grep outline internal/ingestion/chunk_builder.go --view expanded || true

printf '\n== target file lines 90-125 ==\n'
sed -n '90,125p' internal/ingestion/chunk_builder.go

printf '\n== related test lines ==\n'
rg -n "TestPrepareDocs_IDFormat|chunkID|xxhash|FormatUint|%016x" internal/ingestion -S

printf '\n== chunk_builder_test excerpt ==\n'
sed -n '1,220p' internal/ingestion/chunk_builder_test.go

Repository: infiniflow/ragflow

Length of output: 10325


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== usages of chunkID ==\n'
rg -n "chunkID\\(" -S .

printf '\n== references to chunk id format/length ==\n'
rg -n "chunk.?id|chunkID|16-hex|hexdigest|xxhash.xxh64|zero-pad|zero pad|fixed-length|fixed width" -S internal .

Repository: infiniflow/ragflow

Length of output: 50376


chunkID should zero-pad to 16 hex chars. xxhash.xxh64(...).hexdigest() is fixed-width, but strconv.FormatUint(..., 16) drops leading zeroes. That makes some chunk IDs shorter than the documented Python form and breaks Go/Python parity. The ID-format test should also assert len(id) == 16.

🤖 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/ingestion/chunk_builder.go` around lines 103 - 111, The chunkID
helper is dropping leading zeroes because strconv.FormatUint does not produce a
fixed-width xxhash hex string. Update chunkID in chunkID to zero-pad the
xxhash.Sum64String result to 16 hex characters so it matches Python’s
xxhash.xxh64(...).hexdigest() output, and adjust the chunk ID format test to
assert the returned ID length is 16.

Comment thread internal/ingestion/ingestion_service.go Resolved
Comment thread internal/ingestion/ingestion_service.go Resolved
Comment thread internal/ingestion/parser/factory.go Resolved
Comment thread internal/ingestion/parser/pdf_parser.go Resolved
Comment thread internal/ingestion/parser/pdf_parser.go Outdated
Comment on lines +60 to +63
pipeCfg := buildPipelineConfig(make(map[string]any))
if err := post.PostProcess(ctx, result, pipeCfg); err != nil {
return nil, fmt.Errorf("pdf post-process: %w", err)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how ingestion_service.go calls ParseWithDeepDoc and whether it plans to pass tenant/vlm/remove_toc settings.
rg -n -A5 -B5 'ParseWithDeepDoc' internal/ingestion/ingestion_service.go

Repository: infiniflow/ragflow

Length of output: 1502


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== pdf_parser.go =="
sed -n '1,220p' internal/ingestion/parser/pdf_parser.go

echo
echo "== post_steps.go (relevant section) =="
sed -n '1,240p' internal/ingestion/parser/post/post_steps.go

echo
echo "== parser config types =="
sed -n '180,260p' internal/deepdoc/parser/type/types.go

echo
echo "== DefaultParserConfig and ParseWithDeepDoc usages =="
rg -n -A4 -B4 'DefaultParserConfig|ParseWithDeepDoc\(' internal/deepdoc internal/ingestion

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -A3 -B3 'buildPipelineConfig\(' internal

Repository: infiniflow/ragflow

Length of output: 1279


Thread pipeline settings into ParseWithDeepDoc internal/ingestion/parser/pdf_parser.go:60-63 builds pipeCfg from an empty map, and the current parser config type doesn’t expose page_width, remove_toc, flatten_media_to_text, tenant_id, or vlm_llm_id. Those post-processing toggles are unreachable from this entry point, so only the always-on steps run.

🤖 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/ingestion/parser/pdf_parser.go` around lines 60 - 63,
ParseWithDeepDoc currently builds the pipeline config from an empty map, so
parser settings like page_width, remove_toc, flatten_media_to_text, tenant_id,
and vlm_llm_id never reach post-processing. Update ParseWithDeepDoc in
pdf_parser.go to thread the parser’s pipeline-related config into
buildPipelineConfig instead of using make(map[string]any), and ensure the
relevant fields are exposed on the parser config and passed through to
post.PostProcess so the optional post-processing steps can be controlled from
this entry point.

Comment on lines +152 to +163
// 6. VLM enhancement
tenantID := config.String(ConfigKeyTenantID)
vlmLLMID := config.String(ConfigKeyVLMLLMID)
if tenantID != "" && vlmLLMID != "" {
describer, err := resolveImageDescriber(tenantID, vlmLLMID)
if err != nil {
return err
}
if err := enhanceWithVision(ctx, result, describer); err != nil {
return err
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether an init()-based registration file exists for resolveImageDescriber and always assigns a non-nil func.
fd -e go post_steps_cgo post_steps_no_cgo
rg -n 'SetImageDescriberResolver' -C5

Repository: infiniflow/ragflow

Length of output: 261


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the relevant file and any resolver wiring.
git ls-files | rg '^internal/ingestion/parser/post/'
rg -n 'resolveImageDescriber|SetImageDescriberResolver|ImageDescriber' internal/ingestion/parser/post -C 3

# Show the relevant section of post_steps.go with line numbers.
sed -n '140,210p' internal/ingestion/parser/post/post_steps.go

Repository: infiniflow/ragflow

Length of output: 20126


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the resolver registration files.
sed -n '1,220p' internal/ingestion/parser/post/post_steps_cgo.go
printf '\n---\n'
sed -n '1,220p' internal/ingestion/parser/post/post_steps_no_cgo.go
printf '\n---\n'
rg -n 'SetImageDescriberResolver|resolveImageDescriber\s*=' internal/ingestion/parser/post -C 3

Repository: infiniflow/ragflow

Length of output: 248


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate all post parser files and any resolver registration/assignment.
git ls-files internal/ingestion/parser/post
printf '\n---\n'
rg -n 'SetImageDescriberResolver|resolveImageDescriber\s*=|init\(\)' internal/ingestion/parser/post -C 3
printf '\n---\n'
find internal/ingestion/parser/post -maxdepth 1 -type f | sort

Repository: infiniflow/ragflow

Length of output: 2655


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search the whole repository for resolver registration or assignments.
rg -n 'SetImageDescriberResolver|resolveImageDescriber\s*=' . -C 2

Repository: infiniflow/ragflow

Length of output: 1157


Guard the resolver before calling it.

resolveImageDescriber is nil until registered, so this path will panic if tenantID/vlmLLMID are set but no init-time resolver was wired up. Return a clear error, or skip VLM enhancement when the resolver is absent.

🤖 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/ingestion/parser/post/post_steps.go` around lines 152 - 163, The VLM
enhancement block in postSteps currently calls resolveImageDescriber without
checking whether the resolver was registered, which can panic when tenantID and
vlmLLMID are set. Add a nil guard around resolveImageDescriber before invoking
it, and either return a clear error or skip the enhanceWithVision path when the
resolver is absent. Use the existing postSteps VLM enhancement flow and the
resolveImageDescriber / enhanceWithVision symbols to place the fix correctly.

Comment on lines +37 to +46
func TestRealProducerConsumer(t *testing.T) {
// ── 1. NATS ──
natsEngine := nats.NewNatsEngine("localhost", 4222)
if err := natsEngine.Init(); err != nil {
t.Fatalf("NATS Init: %v", err)
}
if err := natsEngine.InitConsumer("tasks.>"); err != nil {
t.Fatalf("InitConsumer: %v", err)
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether other "real_*_test.go" or e2e test files in the repo use a build tag or CI service for NATS.
rg -n "go:build" --type=go -g '*real_*_test.go' -g '*e2e*test.go'
rg -n "nats" -i .github/workflows 2>/dev/null

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the target test file around the cited sections.
wc -l internal/ingestion/task/real_consumer_test.go
cat -n internal/ingestion/task/real_consumer_test.go | sed -n '1,220p'

# Look for integration-test conventions and skip/build-tag patterns in the repo.
rg -n --hidden --glob '!**/.git/**' --glob '*_test.go' 'go:build|t\.Skip|integration|e2e|localhost:4222|ErrTaskNotFound|Ack\(\)' .

# Check for any repo-wide build tags on test files that might opt these tests out.
fd -a -t f '*_test.go' . | xargs -r rg -n 'go:build|// \+build'

Repository: infiniflow/ragflow

Length of output: 32755


Gate this as an integration test and fail the ErrTaskNotFound path.
It connects to localhost:4222 unconditionally, so go test ./... will fail anywhere a NATS broker isn’t running. The ErrTaskNotFound branch also logs and returns early, which can let the test pass without exercising the final assertions.

🤖 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/ingestion/task/real_consumer_test.go` around lines 37 - 46, The real
consumer test is currently an unconditional network-dependent unit test and can
pass without covering the missing-task failure path. Update
TestRealProducerConsumer to be gated as an integration test so it only runs when
a NATS broker is available, and adjust the ErrTaskNotFound branch so it fails
the test instead of logging and returning early. Keep the final assertions in
the test flow and use the existing nats.NewNatsEngine, InitConsumer, and
ErrTaskNotFound symbols to locate the checks.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jul 3, 2026
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 3, 2026
@xugangqiang
xugangqiang marked this pull request as draft July 3, 2026 14:37
@xugangqiang
xugangqiang marked this pull request as ready for review July 3, 2026 14:37

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

Caution

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

⚠️ Outside diff range comments (1)
internal/ingestion/task/dataflow_service.go.bak (1)

1-464: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Stray .bak backup file checked into the repo, with broken syntax.

This file duplicates dataflow_service.go logic but has invalid Go syntax (see below), confirming it's a stale backup rather than intentional code. Recommend removing it — .bak files add confusion and shouldn't be version-controlled alongside the real implementation.

🤖 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/ingestion/task/dataflow_service.go.bak` around lines 1 - 464, The
checked-in dataflow_service.go.bak is a stale backup file and contains invalid
Go syntax, so it should not remain in the repository. Remove the entire .bak
file rather than trying to fix its contents, and make sure the real
implementation stays in the canonical DataflowService code path so there is only
one maintained copy.
🧹 Nitpick comments (13)
internal/ingestion/parser/post/post_steps_test.go (1)

239-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

These reorder tests can never fail — replace t.Log with a real assertion.

Both TestReorderMultiColumn_MultiCol and TestPostProcess_ReorderOnly guard the check with if cond { t.Log(...) } and never call t.Error/t.Fatal. Worse, tracing through reorderMultiColumn for this input shows the guarded condition (Sections[0].Left > Sections[1].Left) evaluates to false even on correct reordering (A: Left=50 ends up first, B: Left=300 second), so the log branch is dead code either way — the test provides no real coverage of the multi-column reordering logic.

♻️ Proposed fix
 func TestReorderMultiColumn_MultiCol(t *testing.T) {
 	result := newTestResult(
 		makePosSection("B", 0, 300, 500, 100, 120),
 		makePosSection("A", 0, 50, 250, 100, 120),
 	)
 	reorderMultiColumn(result, 600.0, 1.0)
-	if result.Sections[0].Positions[0].Left > result.Sections[1].Positions[0].Left {
-		t.Log("multi-column: sections reordered")
-	}
+	if result.Sections[0].Text != "A" || result.Sections[1].Text != "B" {
+		t.Errorf("expected A then B, got %s then %s", result.Sections[0].Text, result.Sections[1].Text)
+	}
 }

Apply the equivalent fix to TestPostProcess_ReorderOnly.

Also applies to: 414-434

🤖 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/ingestion/parser/post/post_steps_test.go` around lines 239 - 248,
The reorder tests are currently non-assertive because they only call t.Log
inside an if branch, so they can never fail. Update
TestReorderMultiColumn_MultiCol and TestPostProcess_ReorderOnly to use real
assertions against reorderMultiColumn/postProcess behavior, checking that the
sections end up in the expected order rather than logging when a condition
happens to pass. Use the existing test helpers like newTestResult,
makePosSection, and reorderMultiColumn to validate the final ordering and fail
the test when it is wrong.
internal/ingestion/task/dataflow_service.go (1)

311-326: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate question-splitting logic instead of reusing SplitQuestions.

processChunkQuestions inlines strings.Split(q, "\n") directly, while the sibling processChunkKeywords correctly delegates to the exported SplitKeywords helper. Reusing the already-exported SplitQuestions (chunk_process.go) here avoids future divergence between the two implementations.

♻️ Proposed fix
 		q, _ := ck["questions"].(string)
-		ck["question_kwd"] = strings.Split(q, "\n")
+		ck["question_kwd"] = SplitQuestions(q)
🤖 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/ingestion/task/dataflow_service.go` around lines 311 - 326, The
question-processing path in processChunkQuestions duplicates newline-splitting
logic instead of reusing the existing SplitQuestions helper. Update
processChunkQuestions to delegate the question splitting to SplitQuestions,
matching how processChunkKeywords uses SplitKeywords, and keep the rest of the
tokenization and field cleanup logic unchanged so the two implementations stay
consistent.
internal/ingestion/task/chunk_process.go (1)

34-59: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Configure tiktoken for offline loading in Go.
TruncateTexts still depends on tiktoken.GetEncoding("cl100k_base") at runtime, but this Go path doesn’t point tiktoken at the bundled cache. The image ships cl100k_base.tiktoken for Python, yet the Go process can still fall back to “no truncation” if the encoding isn’t already cached.

🤖 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/ingestion/task/chunk_process.go` around lines 34 - 59, TruncateTexts
still relies on tiktoken.GetEncoding("cl100k_base") at runtime, so it can fall
back to returning texts unchanged if the encoding is not cached. Update the
tiktoken setup used by TruncateTexts in chunk_process.go to load cl100k_base
from the bundled offline cache or local file path before truncation, and keep
the existing fallback only for true load failures. Ensure the encoding
initialization is wired so the Go path does not depend on network or preexisting
cache state.
internal/entity/models/types.go (1)

68-69: 🗄️ Data Integrity & Integration | 🔵 Trivial

TODO: TokenCount is a placeholder, always zero.

Consumers of EmbeddingData.TokenCount will silently receive 0 until this is implemented. Do you want help wiring up actual token accounting from the model driver responses, or should I open a tracking issue?

🤖 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/entity/models/types.go` around lines 68 - 69, The TokenCount field
in EmbeddingData is currently a placeholder that always stays zero, so wire it
to real token accounting instead of leaving the TODO in types.go. Update the
embedding flow and the relevant model driver response handling to populate
TokenCount from actual usage metadata, and ensure any constructors or mappers
that build EmbeddingData set it consistently.
internal/ingestion/task/task_handler.go (1)

55-89: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Drop the duplicate CANVAS_DEBUG_DOC_ID case. handleDataflow() already routes through DataflowService.Run(), which handles CANVAS_DEBUG_DOC_ID specially; this switch arm doesn’t change behavior and only adds noise.

🤖 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/ingestion/task/task_handler.go` around lines 55 - 89, Remove the
redundant `taskType == "dataflow" && h.ctx.Doc.ID == CANVAS_DEBUG_DOC_ID` branch
in `TaskHandler.handle` and rely on the existing `strings.HasPrefix(taskType,
"dataflow")` path to call `handleDataflow()`. The special `CANVAS_DEBUG_DOC_ID`
handling already happens inside `handleDataflow()` via
`newDataflowService(...).Run(...)`, so keep the switch minimal and preserve the
current behavior.
internal/ingestion/task/chunk_builder.go (1)

129-137: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

No bounds check before indexing sections[i].

If len(sections) < len(chunks), this panics with index-out-of-range instead of returning a handled error, despite the function otherwise returning errors for other failure modes (decode/upload).

🛡️ Proposed defensive check
 func UploadChunkImages(sections []map[string]any, chunks []Chunk, kbID string, putFn func(bucket, fnm string, binary []byte) error) error {
+	if len(sections) != len(chunks) {
+		return fmt.Errorf("sections/chunks length mismatch: %d sections, %d chunks", len(sections), len(chunks))
+	}
 	for i := range chunks {
 		sec := sections[i]
🤖 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/ingestion/task/chunk_builder.go` around lines 129 - 137, Add a
defensive bounds check in UploadChunkImages before indexing sections[i], since
len(sections) may be smaller than len(chunks) and cause an index-out-of-range
panic. Validate the sections/chunks length relationship at the start of the loop
(or before it) and return a handled error when there is no matching section for
a chunk. Keep the existing img_id handling in UploadChunkImages unchanged once
the section is confirmed valid.
internal/ingestion/task/tool/compare_dataflow_golden.go (1)

279-284: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the manual min helper Go 1.21+ already provides min for ordered types, so this helper is redundant.

🤖 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/ingestion/task/tool/compare_dataflow_golden.go` around lines 279 -
284, Remove the custom min helper in compare_dataflow_golden.go because Go 1.21+
already provides a built-in min for ordered types. Update the nearby code paths
that call min to use the standard min directly, and delete the local min
function so there is no naming conflict or redundant implementation.
internal/ingestion/task/naive_merge.go (2)

213-214: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Recomputing tokens on the growing accumulator each iteration is O(n²).

tokenizer.NumTokensFromString(last.Text) is re-run on the full (growing) merged text every time a new segment is compared against it. Track a running token count incrementally instead (e.g., lastTk += tk on merge) to avoid repeated re-tokenization of an ever-larger string on the ingestion hot path.

🤖 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/ingestion/task/naive_merge.go` around lines 213 - 214, The token
count for the merged accumulator is being recomputed from the full growing text
in the naive merge path, which makes the ingestion hot path O(n²). Update the
merge logic in the accumulator handling within naive merge so the running token
total is maintained incrementally in the same place you append/merge segments,
using the existing tokenizer output for the new segment instead of calling
tokenizer.NumTokensFromString on last.Text each iteration.

169-198: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Regex compiled inside loops; delimiter-match check appears unreachable.

regexp.MustCompile (Line 177) and regexp.MatchString (Line 183, which itself compiles a pattern on every call) run once per text/part inside nested loops rather than once per NaiveMerge call. Additionally, Go's regexp.Split already excludes matched separators from its output, so the subsequent isDelimiter/matched checks (here and the identical pattern at Lines 143-149 in mergeByCustomDelimiters) look unreachable in practice.

Also applies to: 126-152

🤖 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/ingestion/task/naive_merge.go` around lines 169 - 198, In
mergeByTokenCount, the delimiter regex is being compiled repeatedly inside the
text/part loops, and the post-Split delimiter match check is effectively
redundant. Precompile the regexp once per NaiveMerge call (or reuse a helper)
and pass it through the loop, then remove the unnecessary matched/isDelimiter
filtering after regexp.Split. Apply the same cleanup to mergeByCustomDelimiters
so both merge paths use the same precompiled delimiter handling and avoid
per-iteration regex compilation.
internal/ingestion/task/naive_merge_test.go (1)

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

maxTokens invariant is declared but never tested.

No table case sets maxTokens to a nonzero value, so the check at Lines 197-204 (that no chunk exceeds the token cap) is dead in every test run. This is the most safety-critical invariant of a chunker and currently has zero coverage.

Also applies to: 197-204, 42-182

🤖 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/ingestion/task/naive_merge_test.go` at line 37, The maxTokens
invariant in the naive merge chunker is declared but not exercised by the
current table tests, so add at least one case in the naive_merge_test.go table
that sets maxTokens to a nonzero limit and uses expectations that would fail if
any chunk exceeded that cap. Update the test flow around the existing chunker
checks (including the assertions covering the token-cap logic) to validate the
no-chunk-over-maxTokens invariant through the NaiveMergeChunker test cases
rather than leaving it unreachable.
internal/ingestion/task/tool/generate_dataflow_golden.py (2)

1-86: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No logging added for this new flow.

This new CLI utility has no logging calls anywhere (no progress/output/error reporting beyond writing files). As per coding guidelines, **/*.py changes should add logging for new flows.

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

In `@internal/ingestion/task/tool/generate_dataflow_golden.py` around lines 1 -
86, The new CLI flow in main() and write_json() has no logging, so add standard
logging for startup, key milestones, and failures. Introduce a logger in
generate_dataflow_golden.py and emit messages around parsing args, reading
input.json, running DataflowService._normalize_chunks and _process_chunks, and
writing output files, including any caught exception details in the
process_error path. Keep the logging tied to the existing
main/write_json/DataflowService flow so the new utility reports progress and
errors consistently.

Source: Coding guidelines


55-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Blind except Exception flagged by ruff (BLE001).

Given the coding guideline to lint with ruff check, consider narrowing this to the specific exception types _process_chunks can raise, or at least log the exception before recording it, per the "add logging" guideline.

🤖 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/ingestion/task/tool/generate_dataflow_golden.py` around lines 55 -
61, The broad exception handler around svc._process_chunks in
generate_dataflow_golden.py is flagged by BLE001 and should be narrowed or
supplemented with logging. Update the try/except to catch only the specific
exceptions that _process_chunks can actually raise, using the _process_chunks
call site as the anchor. If a broad catch is still required, log the exception
with context before populating process_error so the failure is visible while
preserving the existing error payload structure.

Sources: Coding guidelines, Linters/SAST tools

internal/ingestion/service/e2e_parse_test.go (1)

154-165: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fragile relative path resolution for test fixture.

Path resolution depends on the working directory of go test, relying on a hardcoded "../../" fallback. Works today but is brittle if package depth changes.

🤖 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/ingestion/service/e2e_parse_test.go` around lines 154 - 165, The
test fixture lookup in loadTestPDFBytes is using a brittle hardcoded relative
fallback path, which depends on the current working directory. Replace the
os.ReadFile(path) and "../../"+path fallback with a more robust fixture
resolution approach tied to the test package, such as locating the fixture from
the test data directory via a stable helper or embedding the file, and keep the
failure handling in loadTestPDFBytes so the test still fatal-errors with a clear
message if the PDF cannot be read.
🤖 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/ingestion/service/e2e_parse_test.go`:
- Around line 38-61: The setupE2EDB helper is using a per-connection in-memory
SQLite database, which can drop schema/data across calls. Update setupE2EDB to
open SQLite with the shared in-memory DSN and configure the underlying sql.DB
from gorm.DB to use a single open connection so AutoMigrate, seeding, and reads
all see the same database.

In `@internal/ingestion/service/execute_task_test.go`:
- Around line 90-98: The progress assertions in the test are hardcoded and do
not verify the actual callback behavior from runDocumentTask. Update the mock in
executeTask test to capture the values passed into progressFn instead of
appending fixed literals, then assert against those captured arguments for the
routedToDataflow path. Use the existing symbols runDocumentTask, progressFn,
gotProgress, and gotMsgs to ensure the test validates real progress updates
rather than tautological values.

In `@internal/ingestion/service/ingestion_service.go`:
- Around line 659-676: The storage path resolution in ingestion_service should
default the fallback bucket to doc.KbID instead of an empty string when the
File2Document→File lookup does not resolve a bucket. Update the bucket
initialization and keep the existing File2DocumentDAO and FileDAO lookup flow in
the document location resolution logic so the fallback behavior matches the rest
of the package.
- Around line 617-630: The runTask flow in Ingestor is swallowing
LoadTaskContext failures by falling back to parseDocument, which can hide real
DB/FK errors and route a dataflow task down the legacy path. Change the
branching in runTask so task type is checked before calling
taskpkg.LoadTaskContext, or otherwise return the LoadTaskContext error directly
instead of defaulting to parseDocument. Keep the dataflow path in
runDocumentTask and preserve the existing progressFn behavior, but do not treat
LoadTaskContext errors as a normal fallback case.

In `@internal/ingestion/service/parse_document_test.go`:
- Around line 175-188: The TestParseDocument_DocNotFound assertion is
ineffective because errors.New("record not found") creates a different error
value each time, so the errors.Is check never succeeds and the block does not
validate anything. Update the test around parseDocument and mockDocDAO to
compare the returned error against a reusable sentinel or, more appropriately
here, assert on the error message/content from parseDocument so the test
actually verifies the "record not found" case.

In `@internal/ingestion/service/real_consumer_dataflow_test.go`:
- Around line 39-44: The SQLite test setup in real_consumer_dataflow_test.go is
using a per-connection in-memory database, which can lead to intermittent
empty-state failures when GORM opens another connection. Update the gorm.Open
initialization to use a shared in-memory DSN and, on the resulting db handle,
configure the pool to a single connection so the same database instance is
reused throughout the test.

In `@internal/ingestion/task/chunk_builder.go`:
- Around line 110-117: The String method on Chunk is truncating preview with a
byte slice, which can split UTF-8 runes and produce invalid output. Update
Chunk.String to truncate ContentWithWeight in a rune-safe way before formatting
the log string, preserving valid UTF-8 for the preview while keeping the
existing output structure in fmt.Sprintf.

In `@internal/ingestion/task/chunk_utils.go`:
- Around line 126-164: `MustGetChunkTextString`, `AttachVectors`, and the
ingestion `workerLoop` currently let malformed data trigger unrecovered panics
that can crash the worker. Replace the panic paths in those helpers with
task-scoped errors (or return status) and make `workerLoop` recover around
`executeTask`/`executeTasklet` so a bad chunk or vector mismatch only fails that
job. Keep the existing symbols in place so callers can still use
`MustGetChunkTextString` and `AttachVectors` while the worker handles errors
safely.

In `@internal/ingestion/task/dataflow_service.go`:
- Around line 269-293: The EmbedLimiter slot is leaked when encodeTexts fails
after a successful lim.Acquire in the batch loop. Update the embedding path in
dataflow_service.go so any successful Acquire is always paired with Release(1),
even on early returns from encodeTexts or other errors; use the existing
s.taskCtx.EmbedLimiter and the batch-processing loop around encodeTexts to
ensure the limiter is released on every exit path.
- Around line 400-411: The batching progress update in the chunk insertion loop
is effectively gated by a modulo on the loop offset, so it only fires reliably
when bulkSize divides 128. Update the progress trigger in the chunk-processing
loop in dataflow_service.go to use a batch counter or elapsed batch count
instead of b%128, and keep calling s.progress from the insertChunksFunc loop so
intermediate indexing progress is reported consistently for large documents
regardless of bulkSize.

In `@internal/ingestion/task/dataflow_service.go.bak`:
- Around line 145-150: Fix the broken syntax in the dataflow service builder
methods by restoring the missing function declaration for
WithGetEmbeddingModelFunc and ensuring its body is inside a valid
method/function. Use the nearby builder methods in dataflow_service.go.bak,
especially WithGetEmbeddingModelFunc and the following setter that references d,
to reattach the floating statements to the correct receiver and parameter names
so the file compiles again.
- Around line 296-305: The vector-count mismatch handling in embedChunks should
not call panic, because Run and RunDataflow do not recover it and it can crash
ingestion. Replace the panic in embedChunks with a returned error, or add
recovery at the task boundary in Run/RunDataflow so the mismatch is surfaced as
a normal failure. Use the existing embedChunks, Run, and RunDataflow flow to
propagate the error back to the caller instead of terminating the process.

In `@internal/ingestion/task/task_handler.go`:
- Around line 144-150: The helper getEmbeddingDimension in task_handler.go
should not index embeds[0] without verifying the slice is non-empty. Update the
Embed call handling so that after a successful call you check len(embeds) before
reading the first item, and return a descriptive error if it is zero-length.
Keep the fix localized to getEmbeddingDimension and preserve the existing error
wrapping style.

In `@internal/ingestion/task/tool/compare_dataflow_golden.go`:
- Around line 31-43: The compare_dataflow_golden flow has an unguarded direct
call to task.ProcessPipelineOutputForGolden that bypasses the intended recovery
path for expected process-error cases. Remove that redundant call and rely on
runActual to execute the pipeline under recover() so expected-error inputs can
be validated safely; keep the subsequent expected/actual error handling in
compare_dataflow_golden unchanged.

In `@internal/utility/metadata.go`:
- Around line 71-100: normalizeMetaValue currently treats case string
differently from the slice branches by returning empty strings as-is, which lets
blank metadata values be stored. Update normalizeMetaValue so an empty string is
handled the same way as empty elements in []string and []any: return nil for ""
and only return non-empty strings. Keep the behavior consistent across
normalizeMetaValue, dedupeStrings, and the target[k] assignment path that
consumes its result.

---

Outside diff comments:
In `@internal/ingestion/task/dataflow_service.go.bak`:
- Around line 1-464: The checked-in dataflow_service.go.bak is a stale backup
file and contains invalid Go syntax, so it should not remain in the repository.
Remove the entire .bak file rather than trying to fix its contents, and make
sure the real implementation stays in the canonical DataflowService code path so
there is only one maintained copy.

---

Nitpick comments:
In `@internal/entity/models/types.go`:
- Around line 68-69: The TokenCount field in EmbeddingData is currently a
placeholder that always stays zero, so wire it to real token accounting instead
of leaving the TODO in types.go. Update the embedding flow and the relevant
model driver response handling to populate TokenCount from actual usage
metadata, and ensure any constructors or mappers that build EmbeddingData set it
consistently.

In `@internal/ingestion/parser/post/post_steps_test.go`:
- Around line 239-248: The reorder tests are currently non-assertive because
they only call t.Log inside an if branch, so they can never fail. Update
TestReorderMultiColumn_MultiCol and TestPostProcess_ReorderOnly to use real
assertions against reorderMultiColumn/postProcess behavior, checking that the
sections end up in the expected order rather than logging when a condition
happens to pass. Use the existing test helpers like newTestResult,
makePosSection, and reorderMultiColumn to validate the final ordering and fail
the test when it is wrong.

In `@internal/ingestion/service/e2e_parse_test.go`:
- Around line 154-165: The test fixture lookup in loadTestPDFBytes is using a
brittle hardcoded relative fallback path, which depends on the current working
directory. Replace the os.ReadFile(path) and "../../"+path fallback with a more
robust fixture resolution approach tied to the test package, such as locating
the fixture from the test data directory via a stable helper or embedding the
file, and keep the failure handling in loadTestPDFBytes so the test still
fatal-errors with a clear message if the PDF cannot be read.

In `@internal/ingestion/task/chunk_builder.go`:
- Around line 129-137: Add a defensive bounds check in UploadChunkImages before
indexing sections[i], since len(sections) may be smaller than len(chunks) and
cause an index-out-of-range panic. Validate the sections/chunks length
relationship at the start of the loop (or before it) and return a handled error
when there is no matching section for a chunk. Keep the existing img_id handling
in UploadChunkImages unchanged once the section is confirmed valid.

In `@internal/ingestion/task/chunk_process.go`:
- Around line 34-59: TruncateTexts still relies on
tiktoken.GetEncoding("cl100k_base") at runtime, so it can fall back to returning
texts unchanged if the encoding is not cached. Update the tiktoken setup used by
TruncateTexts in chunk_process.go to load cl100k_base from the bundled offline
cache or local file path before truncation, and keep the existing fallback only
for true load failures. Ensure the encoding initialization is wired so the Go
path does not depend on network or preexisting cache state.

In `@internal/ingestion/task/dataflow_service.go`:
- Around line 311-326: The question-processing path in processChunkQuestions
duplicates newline-splitting logic instead of reusing the existing
SplitQuestions helper. Update processChunkQuestions to delegate the question
splitting to SplitQuestions, matching how processChunkKeywords uses
SplitKeywords, and keep the rest of the tokenization and field cleanup logic
unchanged so the two implementations stay consistent.

In `@internal/ingestion/task/naive_merge_test.go`:
- Line 37: The maxTokens invariant in the naive merge chunker is declared but
not exercised by the current table tests, so add at least one case in the
naive_merge_test.go table that sets maxTokens to a nonzero limit and uses
expectations that would fail if any chunk exceeded that cap. Update the test
flow around the existing chunker checks (including the assertions covering the
token-cap logic) to validate the no-chunk-over-maxTokens invariant through the
NaiveMergeChunker test cases rather than leaving it unreachable.

In `@internal/ingestion/task/naive_merge.go`:
- Around line 213-214: The token count for the merged accumulator is being
recomputed from the full growing text in the naive merge path, which makes the
ingestion hot path O(n²). Update the merge logic in the accumulator handling
within naive merge so the running token total is maintained incrementally in the
same place you append/merge segments, using the existing tokenizer output for
the new segment instead of calling tokenizer.NumTokensFromString on last.Text
each iteration.
- Around line 169-198: In mergeByTokenCount, the delimiter regex is being
compiled repeatedly inside the text/part loops, and the post-Split delimiter
match check is effectively redundant. Precompile the regexp once per NaiveMerge
call (or reuse a helper) and pass it through the loop, then remove the
unnecessary matched/isDelimiter filtering after regexp.Split. Apply the same
cleanup to mergeByCustomDelimiters so both merge paths use the same precompiled
delimiter handling and avoid per-iteration regex compilation.

In `@internal/ingestion/task/task_handler.go`:
- Around line 55-89: Remove the redundant `taskType == "dataflow" &&
h.ctx.Doc.ID == CANVAS_DEBUG_DOC_ID` branch in `TaskHandler.handle` and rely on
the existing `strings.HasPrefix(taskType, "dataflow")` path to call
`handleDataflow()`. The special `CANVAS_DEBUG_DOC_ID` handling already happens
inside `handleDataflow()` via `newDataflowService(...).Run(...)`, so keep the
switch minimal and preserve the current behavior.

In `@internal/ingestion/task/tool/compare_dataflow_golden.go`:
- Around line 279-284: Remove the custom min helper in
compare_dataflow_golden.go because Go 1.21+ already provides a built-in min for
ordered types. Update the nearby code paths that call min to use the standard
min directly, and delete the local min function so there is no naming conflict
or redundant implementation.

In `@internal/ingestion/task/tool/generate_dataflow_golden.py`:
- Around line 1-86: The new CLI flow in main() and write_json() has no logging,
so add standard logging for startup, key milestones, and failures. Introduce a
logger in generate_dataflow_golden.py and emit messages around parsing args,
reading input.json, running DataflowService._normalize_chunks and
_process_chunks, and writing output files, including any caught exception
details in the process_error path. Keep the logging tied to the existing
main/write_json/DataflowService flow so the new utility reports progress and
errors consistently.
- Around line 55-61: The broad exception handler around svc._process_chunks in
generate_dataflow_golden.py is flagged by BLE001 and should be narrowed or
supplemented with logging. Update the try/except to catch only the specific
exceptions that _process_chunks can actually raise, using the _process_chunks
call site as the anchor. If a broad catch is still required, log the exception
with context before populating process_error so the failure is visible while
preserving the existing error payload structure.
🪄 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: a8855b5b-a323-4601-bc62-397fb5515bec

📥 Commits

Reviewing files that changed from the base of the PR and between b9d6346 and 9bb1234.

📒 Files selected for processing (55)
  • .gitignore
  • internal/binding/rag_analyzer.go
  • internal/binding/rag_analyzer_stub.go
  • internal/dao/pipeline_operation_log.go
  • internal/deepdoc/parser/pdf/parse_nocgo.go
  • internal/deepdoc/parser/pdf/table/table_post.go
  • internal/entity/models/types.go
  • internal/ingestion/parser/factory.go
  • internal/ingestion/parser/parser_factory_test.go
  • internal/ingestion/parser/pdf_parser.go
  • internal/ingestion/parser/pdf_parser_test.go
  • internal/ingestion/parser/post/model_image_describer.go
  • internal/ingestion/parser/post/model_image_describer_test.go
  • internal/ingestion/parser/post/outline_postprocess_test.go
  • internal/ingestion/parser/post/post_steps.go
  • internal/ingestion/parser/post/post_steps_test.go
  • internal/ingestion/parser/post/vision_describe.go
  • internal/ingestion/parser/post/vision_describe_test.go
  • internal/ingestion/parser/stub_parsers.go
  • internal/ingestion/parser/type.go
  • internal/ingestion/service/e2e_parse_test.go
  • internal/ingestion/service/execute_task_test.go
  • internal/ingestion/service/ingestion_service.go
  • internal/ingestion/service/parse_document_test.go
  • internal/ingestion/service/real_consumer_dataflow_test.go
  • internal/ingestion/task/chunk_builder.go
  • internal/ingestion/task/chunk_builder_test.go
  • internal/ingestion/task/chunk_process.go
  • internal/ingestion/task/chunk_process_test.go
  • internal/ingestion/task/chunk_utils.go
  • internal/ingestion/task/chunk_utils_test.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/dataflow_service.go
  • internal/ingestion/task/dataflow_service.go.bak
  • internal/ingestion/task/dataflow_service_test.go
  • internal/ingestion/task/embedding_test.go
  • internal/ingestion/task/embedding_token_test.go
  • internal/ingestion/task/golden_compare.go
  • internal/ingestion/task/golden_compare_test.go
  • internal/ingestion/task/has_vectors_test.go
  • internal/ingestion/task/naive_merge.go
  • internal/ingestion/task/naive_merge_test.go
  • internal/ingestion/task/position.go
  • internal/ingestion/task/position_test.go
  • internal/ingestion/task/real_consumer_test.go
  • internal/ingestion/task/task_context.go
  • internal/ingestion/task/task_context_test.go
  • internal/ingestion/task/task_handler.go
  • internal/ingestion/task/task_handler_test.go
  • internal/ingestion/task/tool/README.md
  • internal/ingestion/task/tool/compare_dataflow_golden.go
  • internal/ingestion/task/tool/generate_dataflow_golden.py
  • internal/service/document.go
  • internal/utility/metadata.go
  • internal/utility/metadata_test.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/parser/type.go
✅ Files skipped from review due to trivial changes (3)
  • internal/deepdoc/parser/pdf/table/table_post.go
  • .gitignore
  • internal/ingestion/task/tool/README.md
🚧 Files skipped from review as they are similar to previous changes (15)
  • internal/deepdoc/parser/pdf/parse_nocgo.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/parser/post/outline_postprocess_test.go
  • internal/ingestion/parser/pdf_parser_test.go
  • internal/ingestion/parser/parser_factory_test.go
  • internal/ingestion/parser/post/model_image_describer_test.go
  • internal/ingestion/parser/factory.go
  • internal/ingestion/parser/stub_parsers.go
  • internal/binding/rag_analyzer.go
  • internal/ingestion/parser/post/vision_describe.go
  • internal/binding/rag_analyzer_stub.go
  • internal/ingestion/task/task_context_test.go
  • internal/ingestion/parser/pdf_parser.go
  • internal/ingestion/task/real_consumer_test.go
  • internal/ingestion/parser/post/model_image_describer.go

Comment thread internal/ingestion/ingestion_service.go Resolved
Comment thread internal/ingestion/task/task_handler.go Resolved
Comment thread internal/utility/metadata.go Resolved
@codecov

codecov Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a0e6563) to head (0317f6c).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16549      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jul 6, 2026
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 6, 2026
@dosubot dosubot Bot removed the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 6, 2026
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 8, 2026
@xugangqiang
xugangqiang marked this pull request as draft July 8, 2026 08:20
@xugangqiang
xugangqiang marked this pull request as ready for review July 8, 2026 08:20
@xugangqiang
xugangqiang marked this pull request as draft July 8, 2026 08:33
@xugangqiang
xugangqiang marked this pull request as ready for review July 8, 2026 08:34
1. e2e - execute pipeline to parse pdf file and save chunks to ES
2. chunks can be retrieved for using in chat

@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

Caution

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

⚠️ Outside diff range comments (2)
internal/binding/rag_analyzer_stub.go (1)

17-87: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Critical: Duplicate declarations conflict with rag_analyzer_nocgo.go — non-CGO builds will fail to compile.

Both rag_analyzer_stub.go (this file, //go:build !cgo) and the pre-existing rag_analyzer_nocgo.go declare the same types (Token, TokenWithPosition, Analyzer) and methods (NewAnalyzer, Load, SetFineGrained, etc.). When CGO is disabled, both files are compiled into the same package, producing redeclaration errors. This breaks all non-CGO builds.

The fix is to delete the old rag_analyzer_nocgo.go since this new file supersedes it:

#!/bin/bash
# Verify that rag_analyzer_nocgo.go has the same build tag and is the old duplicate
head -20 internal/binding/rag_analyzer_nocgo.go
🔧 Proposed fix: remove the old stub file
-# Delete the old file that this new file replaces
-git rm internal/binding/rag_analyzer_nocgo.go
🤖 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/binding/rag_analyzer_stub.go` around lines 17 - 87, The non-CGO stub
now exists in rag_analyzer_stub.go, so the duplicate declarations in
rag_analyzer_nocgo.go are causing redeclaration conflicts for the same Token,
TokenWithPosition, Analyzer, and methods like NewAnalyzer, Load, Analyze, and
TokenizeWithPosition. Remove the older rag_analyzer_nocgo.go stub so only the
new !cgo implementation remains, and verify the package still builds cleanly
when CGO is disabled.

Source: Linters/SAST tools

internal/dao/ingestion.go (1)

405-405: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add an id tie-breaker to the latest-log query. create_time is only millisecond precision, so two rows for the same task can sort ambiguously. executeTask uses this row to seed and advance the checkpoint, so make the lookup deterministic with Order("create_time DESC, id DESC").

🤖 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/dao/ingestion.go` at line 405, The latest-log lookup in the task
ingestion flow is nondeterministic because `create_time` alone can return
ambiguous ordering for rows with the same timestamp. Update the
`DB.Where(...).Order(...).First(&task)` query used by `executeTask` in
`ingestion.go` to add a deterministic tie-breaker on `id`, so the newest row is
selected consistently with `Order("create_time DESC, id DESC")`.
🧹 Nitpick comments (2)
cmd/ragflow_server.go (1)

475-486: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Tokenizer env fallback duplicates tokenizer.Init's built-in logic.

tokenizer.Init (lines 93-100 in tokenizer.go) already checks RAGFLOW_DICT_PATH and defaults to /usr/share/infinity/resource when DictPath is empty. The manual env check here is redundant. Passing &tokenizer.PoolConfig{} (or even nil) achieves the same behavior, keeping the default path logic in one place.

♻️ Proposed refactor: delegate env fallback to tokenizer.Init
 func runIngestor(args *serverArgs) error {
 	// Initialize tokenizer (rag_analyzer)
-	dictPath := os.Getenv("RAGFLOW_DICT_PATH")
-	if dictPath == "" {
-		dictPath = "/usr/share/infinity/resource"
-	}
-	tokenizerCfg := &tokenizer.PoolConfig{
-		DictPath: dictPath,
-	}
+	tokenizerCfg := &tokenizer.PoolConfig{}
 	if err := tokenizer.Init(tokenizerCfg); err != nil {
 		common.Fatal("Failed to initialize tokenizer", zap.Error(err))
 	}
 	defer tokenizer.Close()
🤖 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 `@cmd/ragflow_server.go` around lines 475 - 486, The tokenizer initialization
in the server startup duplicates the default-path fallback already handled by
tokenizer.Init. Remove the manual RAGFLOW_DICT_PATH lookup in the startup flow
and let tokenizer.Init handle the fallback by passing an empty PoolConfig (or
nil) from the tokenizer initialization block, keeping the logic centralized in
tokenizer.Init and preserving the existing common.Fatal and defer
tokenizer.Close behavior.
internal/dao/ingestion.go (1)

393-395: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

DB.Save performs a full-row update — consider Updates for targeted field writes.

Save writes every struct field to the database, including zero-valued ones. In the executeTask flow (ingestion_service.go:244-283), when a new log is created with only ID, TaskID, and Checkpoint set, subsequent Save calls could overwrite database-populated fields with zero values. Additionally, full-row writes risk clobbering concurrent modifications. If only the checkpoint needs updating, Updates with a field map is safer.

♻️ Proposed refactor: use targeted Updates instead of Save
 func (dao *IngestionTaskLogDAO) Update(ingestionLog *entity.IngestionTaskLog) error {
-	return DB.Save(ingestionLog).Error
+	return DB.Model(ingestionLog).Updates(map[string]interface{}{
+		"checkpoint": ingestionLog.Checkpoint,
+	}).Error
 }
🤖 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/dao/ingestion.go` around lines 393 - 395, The Update method on
IngestionTaskLogDAO is using DB.Save, which performs a full-row write and can
overwrite zero-valued or concurrently updated fields. Change this to a targeted
write using Updates so only the intended fields, such as Checkpoint, are
persisted. Update the IngestionTaskLogDAO.Update implementation to accept the
existing entity.IngestionTaskLog and use a field-scoped update path instead of
Save.
🤖 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/dao/task.go`:
- Around line 54-61: `DeleteIngestionTasksByDocIDs` is filtering the wrong
column, so it won’t match ingestion-task records. Update the
`TaskDAO.DeleteIngestionTasksByDocIDs` query to use the `document_id` field when
deleting `entity.IngestionTask`, not `doc_id`, and keep the hard-delete behavior
with `DB.Unscoped()`. Verify the `Where(...)` clause and related call sites
still pass document IDs consistently.

---

Outside diff comments:
In `@internal/binding/rag_analyzer_stub.go`:
- Around line 17-87: The non-CGO stub now exists in rag_analyzer_stub.go, so the
duplicate declarations in rag_analyzer_nocgo.go are causing redeclaration
conflicts for the same Token, TokenWithPosition, Analyzer, and methods like
NewAnalyzer, Load, Analyze, and TokenizeWithPosition. Remove the older
rag_analyzer_nocgo.go stub so only the new !cgo implementation remains, and
verify the package still builds cleanly when CGO is disabled.

In `@internal/dao/ingestion.go`:
- Line 405: The latest-log lookup in the task ingestion flow is nondeterministic
because `create_time` alone can return ambiguous ordering for rows with the same
timestamp. Update the `DB.Where(...).Order(...).First(&task)` query used by
`executeTask` in `ingestion.go` to add a deterministic tie-breaker on `id`, so
the newest row is selected consistently with `Order("create_time DESC, id
DESC")`.

---

Nitpick comments:
In `@cmd/ragflow_server.go`:
- Around line 475-486: The tokenizer initialization in the server startup
duplicates the default-path fallback already handled by tokenizer.Init. Remove
the manual RAGFLOW_DICT_PATH lookup in the startup flow and let tokenizer.Init
handle the fallback by passing an empty PoolConfig (or nil) from the tokenizer
initialization block, keeping the logic centralized in tokenizer.Init and
preserving the existing common.Fatal and defer tokenizer.Close behavior.

In `@internal/dao/ingestion.go`:
- Around line 393-395: The Update method on IngestionTaskLogDAO is using
DB.Save, which performs a full-row write and can overwrite zero-valued or
concurrently updated fields. Change this to a targeted write using Updates so
only the intended fields, such as Checkpoint, are persisted. Update the
IngestionTaskLogDAO.Update implementation to accept the existing
entity.IngestionTaskLog and use a field-scoped update path instead of Save.
🪄 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: 7679c6f5-b8b0-4a5c-985c-8df945a1a94b

📥 Commits

Reviewing files that changed from the base of the PR and between d091cf5 and 766eef7.

📒 Files selected for processing (26)
  • .gitignore
  • cmd/ragflow_server.go
  • internal/binding/rag_analyzer.go
  • internal/binding/rag_analyzer_stub.go
  • internal/dao/document.go
  • internal/dao/ingestion.go
  • internal/dao/pipeline_operation_log.go
  • internal/dao/task.go
  • internal/entity/models/types.go
  • internal/handler/document.go
  • internal/ingestion/ingestion_service.go
  • internal/ingestion/pipeline/real_storage_integration_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/service/execute_task_test.go
  • internal/ingestion/service/ingestion_service.go
  • internal/ingestion/service/real_consumer_dataflow_test.go
  • internal/ingestion/service/test_helpers.go
  • internal/ingestion/task/chunk_builder.go
  • internal/ingestion/task/chunk_builder_test.go
  • internal/ingestion/task/chunk_process.go
  • internal/ingestion/task/chunk_process_test.go
  • internal/ingestion/task/chunk_utils.go
  • internal/ingestion/task/chunk_utils_test.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/dataflow_chunk_assets.go
  • internal/ingestion/task/dataflow_e2e_test.go
💤 Files with no reviewable changes (18)
  • internal/ingestion/task/dataflow_chunk_assets.go
  • internal/ingestion/task/constants.go
  • internal/entity/models/types.go
  • internal/ingestion/service/test_helpers.go
  • internal/ingestion/task/dataflow_e2e_test.go
  • internal/ingestion/task/chunk_builder_test.go
  • internal/ingestion/task/chunk_builder.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/handler/document.go
  • internal/ingestion/service/execute_task_test.go
  • internal/ingestion/ingestion_service.go
  • internal/ingestion/task/chunk_utils_test.go
  • internal/ingestion/task/chunk_process_test.go
  • internal/ingestion/pipeline/real_storage_integration_test.go
  • internal/ingestion/task/chunk_utils.go
  • internal/ingestion/task/chunk_process.go
  • internal/ingestion/service/real_consumer_dataflow_test.go
  • internal/ingestion/service/ingestion_service.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/dao/pipeline_operation_log.go
  • internal/binding/rag_analyzer.go

Comment thread internal/dao/task.go Resolved

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

🧹 Nitpick comments (7)
internal/parser/parser/factory.go (2)

72-86: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Unexport stub constructors — they're only used by GetParserByID in the same package.

Per coding guidelines: "Keep exported Go APIs only when the current code actually needs them." These 15 New*Parser() functions are only called from GetParserByID in this file and not from the test file. They should be unexported to reduce the public API surface.

As per coding guidelines: internal/**/*.go — "Keep exported Go APIs only when the current code actually needs them."

♻️ Proposed refactor
-// Stub constructors for each parser type.
-func NewNaivePDFParser() *stubParser    { return &stubParser{name: "naive"} }
-func NewPaperPDFParser() *stubParser    { return &stubParser{name: "paper"} }
-func NewBookPDFParser() *stubParser     { return &stubParser{name: "book"} }
-func NewPresentationParser() *stubParser  { return &stubParser{name: "presentation"} }
-func NewManualPDFParser() *stubParser   { return &stubParser{name: "manual"} }
-func NewLawsPDFParser() *stubParser     { return &stubParser{name: "laws"} }
-func NewQAPDFParser() *stubParser       { return &stubParser{name: "qa"} }
-func NewTableParser() *stubParser       { return &stubParser{name: "table"} }
-func NewResumePDFParser() *stubParser   { return &stubParser{name: "resume"} }
-func NewPicturePDFParser() *stubParser  { return &stubParser{name: "picture"} }
-func NewOnePDFParser() *stubParser      { return &stubParser{name: "one"} }
-func NewAudioParser() *stubParser       { return &stubParser{name: "audio"} }
-func NewEmailParser() *stubParser       { return &stubParser{name: "email"} }
-func NewTagPDFParser() *stubParser      { return &stubParser{name: "tag"} }
-func NewKGPDFParser() *stubParser       { return &stubParser{name: "knowledge_graph"} }
+// Stub constructors for each parser type.
+func newNaivePDFParser() *stubParser       { return &stubParser{name: "naive"} }
+func newPaperPDFParser() *stubParser       { return &stubParser{name: "paper"} }
+func newBookPDFParser() *stubParser        { return &stubParser{name: "book"} }
+func newPresentationParser() *stubParser  { return &stubParser{name: "presentation"} }
+func newManualPDFParser() *stubParser      { return &stubParser{name: "manual"} }
+func newLawsPDFParser() *stubParser        { return &stubParser{name: "laws"} }
+func newQAPDFParser() *stubParser          { return &stubParser{name: "qa"} }
+func newTableParser() *stubParser          { return &stubParser{name: "table"} }
+func newResumePDFParser() *stubParser      { return &stubParser{name: "resume"} }
+func newPicturePDFParser() *stubParser     { return &stubParser{name: "picture"} }
+func newOnePDFParser() *stubParser         { return &stubParser{name: "one"} }
+func newAudioParser() *stubParser          { return &stubParser{name: "audio"} }
+func newEmailParser() *stubParser         { return &stubParser{name: "email"} }
+func newTagPDFParser() *stubParser         { return &stubParser{name: "tag"} }
+func newKGPDFParser() *stubParser         { return &stubParser{name: "knowledge_graph"} }

And update the switch cases accordingly:

 	switch parserID {
-	case "naive", "general":
-		return NewNaivePDFParser(), nil
+	case "naive", "general":
+		return newNaivePDFParser(), nil
 	case "paper":
-		return NewPaperPDFParser(), nil
+		return newPaperPDFParser(), nil
 	// ... etc.
🤖 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/parser/parser/factory.go` around lines 72 - 86, The stub parser
constructors in factory.go are exported unnecessarily; make the New*Parser
helpers unexported since only GetParserByID in the same package uses them.
Rename each constructor to a lowercase form, then update the switch in
GetParserByID to call the new unexported names so the public API surface is
reduced without changing behavior.

Source: Coding guidelines


35-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider using entity.ParserType* constants instead of hardcoded string literals.

The switch uses string literals ("naive", "paper", etc.) while the test file uses string(entity.ParserTypeNaive) etc. If the entity constants change, the factory won't automatically update, creating a silent contract break. Using the constants directly (or at least referencing them in a compatibility test) makes the contract explicit.

🤖 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/parser/parser/factory.go` around lines 35 - 68, The parser switch in
the factory uses hardcoded string literals, which can drift from the canonical
parser type values. Update the parser selection logic in the factory function to
use the corresponding entity.ParserType* constants (or a shared mapping derived
from them) for each case like NewNaivePDFParser, NewPaperPDFParser, and the
other parser constructors, so the contract stays aligned if the entity values
change.
internal/ingestion/task/dataflow_service_test.go (1)

445-450: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fix duplicate section header comment.

The updateDocumentMetadata section header is duplicated from the previous block (lines 395-397), and incrementChunkNum is missing its top border line. This is a copy-paste error.

Proposed fix
 // =============================================================================
-// updateDocumentMetadata
-// =============================================================================
-
-// incrementChunkNum
+// incrementChunkNum
 // =============================================================================
🤖 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/ingestion/task/dataflow_service_test.go` around lines 445 - 450, The
section header comments around updateDocumentMetadata and incrementChunkNum were
copy-pasted incorrectly, leaving a duplicated header and a missing top border
line. Update the comment block in dataflow_service_test.go so
updateDocumentMetadata has the correct unique section header and
incrementChunkNum includes its full three-line header format, matching the
surrounding comment style used elsewhere in the test file.
internal/service/document.go (1)

1292-1300: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Use fmt.Sprintf instead of string concatenation in log messages.

Lines 1293 and 1299 use + concatenation to build log messages from potentially user-controlled input (run from req.Run). Static analysis flags this as CWE-117 (log injection). Other log calls in the same function already use fmt.Sprintf with format specifiers.

Proposed fix
-	common.Warn("go side, ingest:run " + run)
+	common.Warn(fmt.Sprintf("go side, ingest:run %s", run))
-	common.Warn("go side, ingest for doc " + docs[0].ID)
+	common.Warn(fmt.Sprintf("go side, ingest for doc %s", docs[0].ID))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/document.go` around lines 1292 - 1300, The logging in the
document ingest flow is building messages with string concatenation, which can
trigger CWE-117 concerns. Update the `common.Warn` calls in `document.go` around
the ingest path to use `fmt.Sprintf` with explicit format specifiers instead of
`+`, especially for values derived from `req.Run` and `docs[0].ID`. Keep the
existing message content the same, but construct it through formatted logging
consistently with the other `common.Warn` calls in `s.documentDAO.GetByIDs`
flow.
internal/ingestion/task/task_context.go (1)

122-190: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unused compatibility loaders

  • Load and LoadTaskContext duplicate the same FK traversal as LoadFromIngestionTask, and there are no in-repo call sites for either wrapper. Drop the backward-compatibility entry points and keep one shared loader path.
🤖 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/ingestion/task/task_context.go` around lines 122 - 190, The
compatibility wrappers Load and LoadTaskContext are redundant because they
duplicate the FK traversal already handled by LoadFromIngestionTask and have no
in-repo callers. Remove both functions from task_context.go, along with any
now-unused imports or helper code they require, and keep the shared loader path
as the only entry point. Make sure any references to these symbols elsewhere are
updated or deleted if found.
internal/ingestion/service/ingestion_service.go (1)

309-346: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

getPipelineID persists a new UserCanvas row on every task execution.

Each task run reads the mock template and calls dao.NewUserCanvasDAO().Create(...), accumulating orphan canvas rows in the DB per execution. This is already flagged with FIXME/mock, but it will leak records under real load. Want me to open an issue to track replacing this mock with a resolved pipeline ID and to avoid per-task writes?

🤖 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/ingestion/service/ingestion_service.go` around lines 309 - 346,
getPipelineID is writing a new UserCanvas record on every execution, which
causes orphan rows to accumulate. Update getPipelineID in ingestion_service.go
to stop calling dao.NewUserCanvasDAO().Create for the mocked pipeline path, and
instead resolve or return an existing pipeline/template ID without persisting
new data. Keep the mock/template loading logic in place only if needed for
lookup, but make the function read-only and use the existing symbols
getPipelineID and NewUserCanvasDAO as the main locations to change.
internal/ingestion/task/naive_merge.go (1)

200-239: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead computation: tk is computed but only discarded.

tk := tokenizer.NumTokensFromString(sub.text) on Line 201 is never used (only _ = tk on Line 238), so each sub-segment pays for a tokenizer pass with no effect. Drop it.

♻️ Proposed cleanup
 		for _, sub := range subSegments {
-			tk := tokenizer.NumTokensFromString(sub.text)
 			pos := resolvePosition(sub.text, sub.pos)
@@
 				if last.Position == "" && pos != "" {
 					last.Position = pos
 				}
 			}
-			_ = tk
 		}
🤖 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/ingestion/task/naive_merge.go` around lines 200 - 239, In the merge
loop inside the naive segment merging logic, `tk` is computed for each
`subSegment` but never affects control flow or output, so remove the dead
tokenization work entirely. Update the code in the `naiveMerge` path that
iterates over `subSegments` so it no longer calls
`tokenizer.NumTokensFromString(sub.text)` just to discard the result, and delete
the trailing discard assignment. Keep the rest of the merging behavior in
`MergedSegment` unchanged.
🤖 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/binding/rag_analyzer_stub.go`:
- Around line 17-86: The !cgo stub in rag_analyzer_stub.go overlaps with
rag_analyzer_nocgo.go, causing duplicate type and method declarations when CGO
is disabled. Update the build constraints so only one no-CGO implementation of
Analyzer, Token, TokenWithPosition, and their methods is compiled, or remove the
redundant stub file entirely.

In `@internal/ingestion/service/ingestion_service.go`:
- Around line 266-277: In ingestion_service.go, the checkpoint parsing in the
task handling flow should not call common.Fatal when current_step or total_step
is missing or malformed, because that can terminate the whole worker. Update the
logic around latestLog.Checkpoint, common.GetInt, and the currentStep/totalStep
extraction to log the parse error, mark the task as FAILED, and return early
instead of exiting. Also fix the total_step error message so it references
“total step” rather than “current step”.
- Around line 249-264: The LatestLogByTaskID handling in ingestion_service.go
currently treats every lookup error as a missing log and creates a new
IngestionTaskLog, which can mask real DB failures and reset progress. Update the
logic around e.ingestionTaskLogDAO.LatestLogByTaskID so only a not-found result
triggers initialization of the new checkpoint record, and make all other errors
return immediately. Use the existing LatestLogByTaskID and
ingestionTaskLogDAO.Create flow, and preserve the current_step/total_step
initialization only for the true missing-log case.

In `@internal/ingestion/service/real_consumer_dataflow_test.go`:
- Around line 103-104: progressFn is used in the real_consumer_dataflow_test
integration test without being in scope, so the test won’t compile. In the test
around the mock queue dataflow progress updates, either define a local helper
named progressFn that records into progressEvents or replace the calls with
direct progressEvents appends, making sure the existing test flow still captures
the same progress values and messages.

In `@internal/ingestion/task/chunk_process.go`:
- Around line 237-245: processChunkPositions currently deletes positions even
when the decoded JSON shape is not []float64, so AddPositions never gets a
chance to run for nested-array input. Update processChunkPositions to normalize
the JSON-shaped positions value into the slice format AddPositions expects, or
only delete the positions field after a successful conversion and AddPositions
call; use processChunkPositions and AddPositions as the key entry points when
fixing this.

In `@internal/ingestion/task/chunk_utils.go`:
- Around line 75-103: The deep-copy helper in deepCopyChunks is still shallow
for reference types, so add handling for []any and nested map[string]any values
instead of falling through to the default cp[k] = v case. Update the copy logic
in deepCopyChunks to recurse or otherwise deep-copy these composite values so
the returned chunk maps do not share mutable underlying data with the input,
preserving the copy.deepcopy contract noted in the docstring.

In `@internal/ingestion/task/dataflow_e2e_test.go`:
- Around line 132-134: The startsWithHTTP helper can panic for 4-character
inputs because it slices s[:5] even when len(s) == 4; update the function to use
a safe prefix check on the full string instead of manual slicing. Keep the fix
localized to startsWithHTTP in dataflow_e2e_test.go, and remove the redundant
https-specific comparison since checking for the http prefix already covers both
http and https.

In `@internal/ingestion/task/dataflow_service.go`:
- Around line 504-512: The global EncodeFunc swap in defaultRunPipeline is
unsafe under concurrent dataflow tasks because overlapping calls can clobber and
restore the wrong factory. Update the pipeline to use a per-run encoder factory
passed through from dataflowService/defaultRunPipeline instead of mutating
componentpkg.EncodeFunc globally, or protect the swap/restore with
synchronization as an interim fix. Use the existing symbols defaultRunPipeline,
componentpkg.EncodeFunc, and getEmbeddingModelFunc to locate the change and
ensure each task uses its own embedder consistently.

In `@internal/ingestion/task/golden_compare.go`:
- Line 44: The golden comparison path is non-deterministic because
`RunGoldenCompare` (or the helper calling `ProcessChunksForDataflow`) passes
`time.Now()` directly into deterministic post-processing. Update
`ProcessChunksForDataflow` and its call site in `golden_compare.go` to accept a
caller-provided `time.Time` (or otherwise use a fixed timestamp for tests) so
the timestamp can be controlled and golden outputs stay stable.

In `@internal/ingestion/task/real_consumer_test.go`:
- Around line 165-166: The test in real_consumer_test.go ignores the error
returned by GetByID and then dereferences final, which can panic if the lookup
fails. Update the validation around ingestionTaskDAO.GetByID(task.ID) to capture
and assert the error before accessing final.Status, and only read Status after
confirming the fetch succeeded. Use the GetByID call and final variable in
real_consumer_test.go to locate the check.
- Around line 60-67: The test setup in real_consumer_test.go uses a private
":memory:" SQLite database, which can lead to separate empty databases across
pooled connections and intermittent no-row failures in dao.DB queries like
GetByID. Update the gorm.Open call in the test setup to use a shared in-memory
SQLite DSN and configure the underlying SQL pool to a single connection, keeping
the change localized around the DB initialization and dao.DB swap in the test.

In `@internal/ingestion/task/task_context_test.go`:
- Around line 95-98: The test setup in task_context_test ignores errors from the
db.Create calls for tenant, kb, doc, and task, which can hide fixture creation
failures and lead to misleading assertions later. Update the setup around the
db.Create calls in the test to capture and check each returned error
immediately, and fail the test early with a clear setup message if any insert
fails; use the existing test function and the db.Create calls as the reference
points.

In `@internal/ingestion/task/task_context.go`:
- Around line 156-160: LoadTaskContext currently assumes
dao.NewTaskDAO().GetByID always returns a non-nil task when err is nil, which
can lead to a nil pointer dereference later in the function. Add an explicit nil
check for task immediately after GetByID in LoadTaskContext, before any access
to task.DocID or other fields, and return a wrapped error if the task is nil;
keep the existing nil-safe checks for the document and KB lookups consistent
with this handling.

In `@internal/ingestion/task/task_handler.go`:
- Around line 93-97: The handleDataflow logic in TaskHandler is checking
PipelineID with trimming but still assigning the untrimmed value to dataflowID,
which can carry surrounding spaces into downstream task matching. Update
handleDataflow to use the trimmed PipelineID value for both the non-empty check
and the assignment, mirroring the trim-space handling used in Ingest in
document.go so dataflowID is always normalized before use.

In `@internal/service/document.go`:
- Around line 1319-1322: The knowledgebase lookup path in the document service
is using misleading diagnostics and lacks a nil guard. In the kbDAO.GetByID
check, replace the tenant/dataset wording with a message that clearly identifies
the knowledgebase or dataset lookup failure, and return an error that reflects
that same failure instead of "tenant not found". Also add an explicit nil check
for kb before any later use of kb.ID in this flow, and handle the nil case with
the same lookup-failure path to avoid a panic.

---

Nitpick comments:
In `@internal/ingestion/service/ingestion_service.go`:
- Around line 309-346: getPipelineID is writing a new UserCanvas record on every
execution, which causes orphan rows to accumulate. Update getPipelineID in
ingestion_service.go to stop calling dao.NewUserCanvasDAO().Create for the
mocked pipeline path, and instead resolve or return an existing
pipeline/template ID without persisting new data. Keep the mock/template loading
logic in place only if needed for lookup, but make the function read-only and
use the existing symbols getPipelineID and NewUserCanvasDAO as the main
locations to change.

In `@internal/ingestion/task/dataflow_service_test.go`:
- Around line 445-450: The section header comments around updateDocumentMetadata
and incrementChunkNum were copy-pasted incorrectly, leaving a duplicated header
and a missing top border line. Update the comment block in
dataflow_service_test.go so updateDocumentMetadata has the correct unique
section header and incrementChunkNum includes its full three-line header format,
matching the surrounding comment style used elsewhere in the test file.

In `@internal/ingestion/task/naive_merge.go`:
- Around line 200-239: In the merge loop inside the naive segment merging logic,
`tk` is computed for each `subSegment` but never affects control flow or output,
so remove the dead tokenization work entirely. Update the code in the
`naiveMerge` path that iterates over `subSegments` so it no longer calls
`tokenizer.NumTokensFromString(sub.text)` just to discard the result, and delete
the trailing discard assignment. Keep the rest of the merging behavior in
`MergedSegment` unchanged.

In `@internal/ingestion/task/task_context.go`:
- Around line 122-190: The compatibility wrappers Load and LoadTaskContext are
redundant because they duplicate the FK traversal already handled by
LoadFromIngestionTask and have no in-repo callers. Remove both functions from
task_context.go, along with any now-unused imports or helper code they require,
and keep the shared loader path as the only entry point. Make sure any
references to these symbols elsewhere are updated or deleted if found.

In `@internal/parser/parser/factory.go`:
- Around line 72-86: The stub parser constructors in factory.go are exported
unnecessarily; make the New*Parser helpers unexported since only GetParserByID
in the same package uses them. Rename each constructor to a lowercase form, then
update the switch in GetParserByID to call the new unexported names so the
public API surface is reduced without changing behavior.
- Around line 35-68: The parser switch in the factory uses hardcoded string
literals, which can drift from the canonical parser type values. Update the
parser selection logic in the factory function to use the corresponding
entity.ParserType* constants (or a shared mapping derived from them) for each
case like NewNaivePDFParser, NewPaperPDFParser, and the other parser
constructors, so the contract stays aligned if the entity values change.

In `@internal/service/document.go`:
- Around line 1292-1300: The logging in the document ingest flow is building
messages with string concatenation, which can trigger CWE-117 concerns. Update
the `common.Warn` calls in `document.go` around the ingest path to use
`fmt.Sprintf` with explicit format specifiers instead of `+`, especially for
values derived from `req.Run` and `docs[0].ID`. Keep the existing message
content the same, but construct it through formatted logging consistently with
the other `common.Warn` calls in `s.documentDAO.GetByIDs` flow.
🪄 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: cf27130b-f7a2-43f0-962a-e5ef29525a13

📥 Commits

Reviewing files that changed from the base of the PR and between 766eef7 and 18af99c.

📒 Files selected for processing (53)
  • .gitignore
  • cmd/ragflow_server.go
  • internal/binding/rag_analyzer.go
  • internal/binding/rag_analyzer_stub.go
  • internal/dao/document.go
  • internal/dao/ingestion.go
  • internal/dao/pipeline_operation_log.go
  • internal/dao/task.go
  • internal/entity/models/types.go
  • internal/handler/document.go
  • internal/ingestion/ingestion_service.go
  • internal/ingestion/ingestion_service_test.go
  • internal/ingestion/pipeline/real_storage_integration_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/service/execute_task_test.go
  • internal/ingestion/service/ingestion_service.go
  • internal/ingestion/service/real_consumer_dataflow_test.go
  • internal/ingestion/service/test_helpers.go
  • internal/ingestion/task/chunk_builder.go
  • internal/ingestion/task/chunk_builder_test.go
  • internal/ingestion/task/chunk_process.go
  • internal/ingestion/task/chunk_process_test.go
  • internal/ingestion/task/chunk_utils.go
  • internal/ingestion/task/chunk_utils_test.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/dataflow_chunk_assets.go
  • internal/ingestion/task/dataflow_e2e_test.go
  • internal/ingestion/task/dataflow_real_pipeline_integration_test.go
  • internal/ingestion/task/dataflow_service.go
  • internal/ingestion/task/dataflow_service_test.go
  • internal/ingestion/task/embedding_test.go
  • internal/ingestion/task/embedding_token_test.go
  • internal/ingestion/task/golden_compare.go
  • internal/ingestion/task/golden_compare_test.go
  • internal/ingestion/task/has_vectors_test.go
  • internal/ingestion/task/naive_merge.go
  • internal/ingestion/task/naive_merge_test.go
  • internal/ingestion/task/pipeline_run_output_checklist.md
  • internal/ingestion/task/position.go
  • internal/ingestion/task/position_test.go
  • internal/ingestion/task/real_consumer_test.go
  • internal/ingestion/task/task_context.go
  • internal/ingestion/task/task_context_test.go
  • internal/ingestion/task/task_handler.go
  • internal/ingestion/task/task_handler_test.go
  • internal/ingestion/task/tool/compare_dataflow_golden.go
  • internal/ingestion/testutil/helpers.go
  • internal/ingestion/testutil/mocks.go
  • internal/parser/parser/factory.go
  • internal/parser/parser/factory_test.go
  • internal/service/document.go
  • internal/utility/metadata.go
  • internal/utility/metadata_test.go
💤 Files with no reviewable changes (2)
  • internal/ingestion/ingestion_service_test.go
  • internal/ingestion/ingestion_service.go
✅ Files skipped from review due to trivial changes (3)
  • .gitignore
  • internal/handler/document.go
  • internal/binding/rag_analyzer.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/ingestion/task/dataflow_chunk_assets.go
  • internal/dao/pipeline_operation_log.go
  • internal/entity/models/types.go
  • internal/dao/document.go
  • internal/dao/ingestion.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/dao/task.go
  • cmd/ragflow_server.go

Comment thread internal/binding/rag_analyzer_stub.go Resolved
Comment on lines +249 to +264
latestLog, err := e.ingestionTaskLogDAO.LatestLogByTaskID(task.ID)
if err != nil {
latestLog = &entity.IngestionTaskLog{
ID: 0,
TaskID: task.ID,
Checkpoint: entity.JSONMap{
"current_step": 1,
"total_step": 5,
},
}
err = e.ingestionTaskLogDAO.Create(latestLog)
if err != nil {
common.Error(fmt.Sprintf("Failed to create task log for task %s", task.ID), err)
return
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== File outline =="
ast-grep outline internal/ingestion/service/ingestion_service.go --view expanded || true

echo
echo "== Relevant slice in ingestion_service.go =="
sed -n '220,290p' internal/ingestion/service/ingestion_service.go | cat -n

echo
echo "== Search for LatestLogByTaskID definition/usages =="
rg -n "LatestLogByTaskID|ingestionTaskLogDAO|not found|Err.*NotFound|Err.*No.*Record|sql.ErrNoRows" internal -S

echo
echo "== DAO files with task log =="
fd -a ".*task.*log.*\.go$|.*ingestion.*log.*\.go$" internal || true

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the DAO implementation(s) related to LatestLogByTaskID
for f in $(rg -l "func .*LatestLogByTaskID|LatestLogByTaskID" internal -S); do
  echo "===== $f ====="
  # show a compact outline first if possible
  ast-grep outline "$f" --view expanded || true
  echo
  rg -n "LatestLogByTaskID|Create\(|sql.ErrNoRows|not found|NotFound|NoRows|Err" "$f" -S || true
  echo
done

# Also inspect the entity/error definitions if they exist
echo "== Search for error sentinels =="
rg -n "Err.*NotFound|NotFoundError|sql.ErrNoRows|errors.Is\\(" internal -S

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== internal/dao/ingestion.go: LatestLogByTaskID slice =="
sed -n '399,408p' internal/dao/ingestion.go | cat -n

echo
echo "== internal/ingestion/service/ingestion_service.go imports and executeTask slice =="
sed -n '1,40p' internal/ingestion/service/ingestion_service.go | cat -n
sed -n '244,265p' internal/ingestion/service/ingestion_service.go | cat -n

Repository: infiniflow/ragflow

Length of output: 2813


Distinguish missing logs from lookup failures
LatestLogByTaskID returns raw DB errors, but this path treats every error as “no log exists” and creates a fresh current_step: 1 record. That can hide transient DB failures and reset checkpoint progress. Only initialize on a not-found result; propagate all other errors.

🤖 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/ingestion/service/ingestion_service.go` around lines 249 - 264, The
LatestLogByTaskID handling in ingestion_service.go currently treats every lookup
error as a missing log and creates a new IngestionTaskLog, which can mask real
DB failures and reset progress. Update the logic around
e.ingestionTaskLogDAO.LatestLogByTaskID so only a not-found result triggers
initialization of the new checkpoint record, and make all other errors return
immediately. Use the existing LatestLogByTaskID and ingestionTaskLogDAO.Create
flow, and preserve the current_step/total_step initialization only for the true
missing-log case.

Comment on lines +266 to +277
var checkpointMap map[string]interface{}
checkpointMap = latestLog.Checkpoint
currentStep, ok := common.GetInt(checkpointMap["current_step"])
if !ok {
common.Fatal(fmt.Sprintf("Failed to get current step from task log for task %s", task.ID))
return
}
totalStep, ok := common.GetInt(checkpointMap["total_step"])
if !ok {
common.Fatal(fmt.Sprintf("Failed to get current step from task log for task %s", task.ID))
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
ast-grep run --pattern 'func Fatal($$$) { $$$ }' --lang go internal/common
rg -nP '\bfunc Fatal\b' internal/common

Repository: infiniflow/ragflow

Length of output: 801


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== internal/common/logger.go =="
sed -n '160,190p' internal/common/logger.go

echo
echo "== internal/ingestion/service/ingestion_service.go around executeTask =="
sed -n '220,310p' internal/ingestion/service/ingestion_service.go

echo
echo "== search for fatal/error handling in ingestion service =="
rg -n "Fatal\\(|FAILED|panic\\(|recover\\(" internal/ingestion/service internal/common -g '*.go'

Repository: infiniflow/ragflow

Length of output: 5131


Avoid fatal exit on checkpoint parse errors common.Fatal terminates the process, so a malformed current_step or total_step in one task log can kill the whole ingestion worker. Log the error, mark the task FAILED, and return instead. Also, the total_step branch still says “current step”.

🤖 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/ingestion/service/ingestion_service.go` around lines 266 - 277, In
ingestion_service.go, the checkpoint parsing in the task handling flow should
not call common.Fatal when current_step or total_step is missing or malformed,
because that can terminate the whole worker. Update the logic around
latestLog.Checkpoint, common.GetInt, and the currentStep/totalStep extraction to
log the parse error, mark the task as FAILED, and return early instead of
exiting. Also fix the total_step error message so it references “total step”
rather than “current step”.

Comment on lines +103 to +104
progressFn(0.82, "mock queue dataflow start")
progressFn(1.0, "mock queue dataflow done")

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if progressFn is defined anywhere in the service package
rg -n 'progressFn' internal/ingestion/service/ --type=go -C3

Repository: infiniflow/ragflow

Length of output: 1025


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file outline =="
ast-grep outline internal/ingestion/service/real_consumer_dataflow_test.go --view expanded || true

echo
echo "== search for progressFn across repo =="
rg -n --hidden --glob '!**/.git/**' 'progressFn' .

echo
echo "== surrounding lines in target file =="
sed -n '1,180p' internal/ingestion/service/real_consumer_dataflow_test.go

Repository: infiniflow/ragflow

Length of output: 4883


Define progressFn in internal/ingestion/service/real_consumer_dataflow_test.go:103-104 progressFn is not in scope here, so this integration test will not compile. Declare the helper locally or append directly to progressEvents.

🤖 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/ingestion/service/real_consumer_dataflow_test.go` around lines 103 -
104, progressFn is used in the real_consumer_dataflow_test integration test
without being in scope, so the test won’t compile. In the test around the mock
queue dataflow progress updates, either define a local helper named progressFn
that records into progressEvents or replace the calls with direct progressEvents
appends, making sure the existing test flow still captures the same progress
values and messages.

Comment on lines +237 to +245
func processChunkPositions(ck map[string]any) {
poss, exists := ck["positions"]
if !exists {
return
}
if positions, ok := poss.([]float64); ok {
AddPositions(ck, positions)
}
delete(ck, "positions")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how positions are set in chunk maps — are they always []float64 or sometimes []any?
rg -n '"positions"' internal/ingestion/ internal/parser/ --type go -C3
# Check AddPositions signature to understand expected input type
rg -n 'func AddPositions\b' internal/ --type go -C2

Repository: infiniflow/ragflow

Length of output: 7905


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the chunk processing path and nearby callers.
sed -n '1,320p' internal/ingestion/task/chunk_process.go
printf '\n==== position.go ====\n'
sed -n '1,220p' internal/ingestion/task/position.go
printf '\n==== chunk_builder.go ====\n'
sed -n '1,180p' internal/ingestion/task/chunk_builder.go
printf '\n==== schema/chunk_types.go (relevant sections) ====\n'
sed -n '1,320p' internal/ingestion/component/schema/chunk_types.go
printf '\n==== pdf_parser_common.go (positions normalization) ====\n'
sed -n '300,360p' internal/parser/parser/pdf_parser_common.go
printf '\n==== pdf_parser_remote_common.go (positions handling) ====\n'
sed -n '70,110p' internal/parser/parser/pdf_parser_remote_common.go

# Check the concrete runtime type produced by JSON unmarshaling for a positions array.
python3 - <<'PY'
import json
v = json.loads('{"positions":[1,2,3,4,5]}')
print(type(v["positions"]).__name__)
print(type(v["positions"][0]).__name__)
PY

Repository: infiniflow/ragflow

Length of output: 27525


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show how positions are normalized/decoded and what shape ToMap emits.
sed -n '1,220p' internal/ingestion/component/schema/chunk_types.go
printf '\n==== normalizePDFPositions / helpers ====\n'
rg -n 'func normalizePDFPositions|func decodeStructuredValue|func firstPageNumber' internal/parser/parser/pdf_parser_common.go -A40 -B10
printf '\n==== any call sites of ProcessChunksForDataflow ====\n'
rg -n 'ProcessChunksForDataflow\(' internal/ -C3
printf '\n==== any direct uses of processChunkPositions / AddPositions ====\n'
rg -n 'processChunkPositions\(|AddPositions\(' internal/ -C3

Repository: infiniflow/ragflow

Length of output: 28140


Handle JSON-shaped positions before deleting the field
processChunkPositions only accepts []float64, but chunks coming from JSON carry positions as nested arrays, so AddPositions never runs and the field is deleted anyway. Normalize the decoded shape or leave positions in place when conversion fails.

🤖 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/ingestion/task/chunk_process.go` around lines 237 - 245,
processChunkPositions currently deletes positions even when the decoded JSON
shape is not []float64, so AddPositions never gets a chance to run for
nested-array input. Update processChunkPositions to normalize the JSON-shaped
positions value into the slice format AddPositions expects, or only delete the
positions field after a successful conversion and AddPositions call; use
processChunkPositions and AddPositions as the key entry points when fixing this.

Comment on lines +165 to +166
final, _ := ingestionTaskDAO.GetByID(task.ID)
if final.Status != common.COMPLETED {

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Check error from GetByID before dereferencing final.

If GetByID returns an error, final may be nil, and final.Status on the next line will panic with a nil pointer dereference.

🛡️ Proposed fix
-final, _ := ingestionTaskDAO.GetByID(task.ID)
+final, err := ingestionTaskDAO.GetByID(task.ID)
+if err != nil {
+	t.Fatalf("GetByID: %v", err)
+}
📝 Committable suggestion

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

Suggested change
final, _ := ingestionTaskDAO.GetByID(task.ID)
if final.Status != common.COMPLETED {
final, err := ingestionTaskDAO.GetByID(task.ID)
if err != nil {
t.Fatalf("GetByID: %v", err)
}
if final.Status != common.COMPLETED {
🤖 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/ingestion/task/real_consumer_test.go` around lines 165 - 166, The
test in real_consumer_test.go ignores the error returned by GetByID and then
dereferences final, which can panic if the lookup fails. Update the validation
around ingestionTaskDAO.GetByID(task.ID) to capture and assert the error before
accessing final.Status, and only read Status after confirming the fetch
succeeded. Use the GetByID call and final variable in real_consumer_test.go to
locate the check.

Comment on lines +95 to +98
db.Create(tenant)
db.Create(kb)
db.Create(doc)
db.Create(task)

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Check db.Create errors in test setup.

All four db.Create calls ignore the returned error. If any create fails (e.g., FK constraint violation), the test proceeds with missing data and produces confusing assertion failures downstream instead of a clear setup error.

Proposed fix
 	db.Create(tenant)
 	db.Create(kb)
 	db.Create(doc)
 	db.Create(task)
+	if err := db.Create(tenant).Error; err != nil {
+		t.Fatalf("create tenant: %v", err)
+	}
+	if err := db.Create(kb).Error; err != nil {
+		t.Fatalf("create kb: %v", err)
+	}
+	if err := db.Create(doc).Error; err != nil {
+		t.Fatalf("create doc: %v", err)
+	}
+	if err := db.Create(task).Error; err != nil {
+		t.Fatalf("create task: %v", err)
+	}
🤖 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/ingestion/task/task_context_test.go` around lines 95 - 98, The test
setup in task_context_test ignores errors from the db.Create calls for tenant,
kb, doc, and task, which can hide fixture creation failures and lead to
misleading assertions later. Update the setup around the db.Create calls in the
test to capture and check each returned error immediately, and fail the test
early with a clear setup message if any insert fails; use the existing test
function and the db.Create calls as the reference points.

Comment on lines +156 to +160
func LoadTaskContext(taskID string) (*TaskContext, error) {
task, err := dao.NewTaskDAO().GetByID(taskID)
if err != nil {
return nil, fmt.Errorf("task %s: %w", taskID, err)
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Add nil check for task after GetByID.

LoadTaskContext checks err != nil but not task == nil. If TaskDAO.GetByID returns (nil, nil), task.DocID on line 162 will panic with a nil pointer dereference. The document and KB lookups in this same function (lines 163, 168) correctly check for nil.

Proposed fix
 	task, err := dao.NewTaskDAO().GetByID(taskID)
-	if err != nil {
+	if err != nil || task == nil {
 		return nil, fmt.Errorf("task %s: %w", taskID, err)
 	}
📝 Committable suggestion

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

Suggested change
func LoadTaskContext(taskID string) (*TaskContext, error) {
task, err := dao.NewTaskDAO().GetByID(taskID)
if err != nil {
return nil, fmt.Errorf("task %s: %w", taskID, err)
}
func LoadTaskContext(taskID string) (*TaskContext, error) {
task, err := dao.NewTaskDAO().GetByID(taskID)
if err != nil || task == nil {
return nil, fmt.Errorf("task %s: %w", taskID, err)
}
🤖 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/ingestion/task/task_context.go` around lines 156 - 160,
LoadTaskContext currently assumes dao.NewTaskDAO().GetByID always returns a
non-nil task when err is nil, which can lead to a nil pointer dereference later
in the function. Add an explicit nil check for task immediately after GetByID in
LoadTaskContext, before any access to task.DocID or other fields, and return a
wrapped error if the task is nil; keep the existing nil-safe checks for the
document and KB lookups consistent with this handling.

Comment on lines +93 to +97
func (h *TaskHandler) handleDataflow() error {
dataflowID := ""
if strings.Trim(h.ctx.PipelineID, " ") != "" {
dataflowID = h.ctx.PipelineID
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assign trimmed PipelineID to dataflowID.

strings.Trim is used for the emptiness check but the raw h.ctx.PipelineID is assigned to dataflowID. If PipelineID has surrounding spaces, dataflowID will contain them, causing downstream mismatches. The Ingest method in document.go consistently uses strings.TrimSpace(*doc.PipelineID) when queuing dataflow tasks.

Proposed fix
 func (h *TaskHandler) handleDataflow() error {
 	dataflowID := ""
-	if strings.Trim(h.ctx.PipelineID, " ") != "" {
-		dataflowID = h.ctx.PipelineID
+	if trimmed := strings.TrimSpace(h.ctx.PipelineID); trimmed != "" {
+		dataflowID = trimmed
 	}
 	svc, err := h.newDataflowService(h.ctx, dataflowID)
📝 Committable suggestion

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

Suggested change
func (h *TaskHandler) handleDataflow() error {
dataflowID := ""
if strings.Trim(h.ctx.PipelineID, " ") != "" {
dataflowID = h.ctx.PipelineID
}
func (h *TaskHandler) handleDataflow() error {
dataflowID := ""
if trimmed := strings.TrimSpace(h.ctx.PipelineID); trimmed != "" {
dataflowID = trimmed
}
🤖 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/ingestion/task/task_handler.go` around lines 93 - 97, The
handleDataflow logic in TaskHandler is checking PipelineID with trimming but
still assigning the untrimmed value to dataflowID, which can carry surrounding
spaces into downstream task matching. Update handleDataflow to use the trimmed
PipelineID value for both the non-empty check and the assignment, mirroring the
trim-space handling used in Ingest in document.go so dataflowID is always
normalized before use.

Comment on lines 1319 to +1322
kb, err := s.kbDAO.GetByID(doc.KbID)
if err != nil {
return common.CodeDataError, fmt.Errorf("Tenant not found!")
common.Warn(fmt.Sprintf("go side, start to process %s, dataset is nil", docID))
return common.CodeDataError, fmt.Errorf("tenant not found")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix misleading error message for knowledgebase lookup failure.

kbDAO.GetByID fails but the error message says "tenant not found" and the log says "dataset is nil". Both are incorrect — the knowledgebase/dataset lookup failed, not the tenant. This will mislead debugging. Additionally, there is no nil check for kb — if GetByID returns (nil, nil), kb.ID on line 1325 will panic.

Proposed fix
 	kb, err := s.kbDAO.GetByID(doc.KbID)
-	if err != nil {
-		common.Warn(fmt.Sprintf("go side, start to process %s, dataset is nil", docID))
-		return common.CodeDataError, fmt.Errorf("tenant not found")
+	if err != nil || kb == nil {
+		common.Warn(fmt.Sprintf("go side, start to process %s, dataset not found", docID))
+		return common.CodeDataError, fmt.Errorf("dataset not found for doc %s", docID)
 	}
📝 Committable suggestion

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

Suggested change
kb, err := s.kbDAO.GetByID(doc.KbID)
if err != nil {
return common.CodeDataError, fmt.Errorf("Tenant not found!")
common.Warn(fmt.Sprintf("go side, start to process %s, dataset is nil", docID))
return common.CodeDataError, fmt.Errorf("tenant not found")
kb, err := s.kbDAO.GetByID(doc.KbID)
if err != nil || kb == nil {
common.Warn(fmt.Sprintf("go side, start to process %s, dataset not found", docID))
return common.CodeDataError, fmt.Errorf("dataset not found for doc %s", docID)
🤖 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 1319 - 1322, The knowledgebase
lookup path in the document service is using misleading diagnostics and lacks a
nil guard. In the kbDAO.GetByID check, replace the tenant/dataset wording with a
message that clearly identifies the knowledgebase or dataset lookup failure, and
return an error that reflects that same failure instead of "tenant not found".
Also add an explicit nil check for kb before any later use of kb.ID in this
flow, and handle the nil case with the same lookup-failure path to avoid a
panic.

@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

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)

114-114: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

JSON tag progress_duration likely mismatches the intended process_duration field.

The field maps to the document's process_duration column (see internal/entity/document.go, json:"process_duration"), but this request field binds progress_duration. Any caller sending process_duration will be silently dropped. The preceding FIXME suggests this is already known.

Want me to open an issue to track aligning this tag (and any dependent callers/serializers)?

Proposed fix
-	ProcessDuration *float64 `json:"progress_duration"`
+	ProcessDuration *float64 `json:"process_duration"`
🤖 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` at line 114, The request model in Document
currently uses a mismatched JSON tag for the duration field, so update the tag
on ProcessDuration in the Document struct to align with the entity’s
process_duration naming used elsewhere. Check the related Document types and any
serializers/binders that read or write this field so callers sending
process_duration are accepted consistently. Use the existing Document struct and
the corresponding entity field naming as the source of truth.
🧹 Nitpick comments (1)
internal/service/document.go (1)

623-648: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Consider reusing the DAO instead of inlining the document increment.

The document-side update here duplicates DocumentDAO.IncrementCounts (internal/dao/document.go), which already increments chunk_num/token_num/process_duration via gorm.Expr. Inlining the same SQL in the service layer risks divergence if the DAO logic changes. You could run the DAO call plus the KB increment inside this transaction to keep a single source of truth.

🤖 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 623 - 648, The document increment
logic is duplicated in DocumentService.IncrementChunkNum instead of reusing
DocumentDAO.IncrementCounts, which risks the service and DAO drifting apart.
Update IncrementChunkNum to call the DAO’s increment method for the
document-side update, and keep the knowledgebase chunk/token increment in the
same transaction. Use the existing DocumentDAO.IncrementCounts and the
transaction in IncrementChunkNum to preserve a single source of truth.
🤖 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.

Outside diff comments:
In `@internal/service/document.go`:
- Line 114: The request model in Document currently uses a mismatched JSON tag
for the duration field, so update the tag on ProcessDuration in the Document
struct to align with the entity’s process_duration naming used elsewhere. Check
the related Document types and any serializers/binders that read or write this
field so callers sending process_duration are accepted consistently. Use the
existing Document struct and the corresponding entity field naming as the source
of truth.

---

Nitpick comments:
In `@internal/service/document.go`:
- Around line 623-648: The document increment logic is duplicated in
DocumentService.IncrementChunkNum instead of reusing
DocumentDAO.IncrementCounts, which risks the service and DAO drifting apart.
Update IncrementChunkNum to call the DAO’s increment method for the
document-side update, and keep the knowledgebase chunk/token increment in the
same transaction. Use the existing DocumentDAO.IncrementCounts and the
transaction in IncrementChunkNum to preserve a single source of truth.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7f626f3f-2139-44ef-acec-07697783c518

📥 Commits

Reviewing files that changed from the base of the PR and between 18af99c and f316153.

📒 Files selected for processing (5)
  • internal/binding/rag_analyzer_nocgo.go
  • internal/dao/task.go
  • internal/dao/task_test.go
  • internal/deepdoc/parser/pdf/parse_nocgo.go
  • internal/service/document.go
✅ Files skipped from review due to trivial changes (2)
  • internal/binding/rag_analyzer_nocgo.go
  • internal/deepdoc/parser/pdf/parse_nocgo.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/dao/task.go

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

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants