Skip to content

Feat(ingestion): add canvas pipeline debug (dry-run) mode with View result log - #17538

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
xugangqiang:fix/canvas-debug
Jul 31, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
xugangqiang:fix/canvas-debug

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a side-effect-free DataFlow canvas debug (dry-run) mode plus a debug run log with a "View result" panel, so a canvas can be executed synchronously and inspected end-to-end (per-component progress and parsed chunks) without persisting anything.

Dry-run execution (inline parsed chunks)

  • task/debug.go: NewDebugTaskContext builds an in-memory TaskContext with KB.ID == "" — the single debug signal used across the ingestion pipeline. A canvas debug run has no knowledgebase, and production ingestion always supplies one, so kb_id == "" occurs ONLY in debug mode. Components gate their own side effects on this signal without any dedicated debug vocabulary (the former CANVAS_DEBUG_DOC_ID marker constant is removed).
  • task/pipeline_executor.go: validateTaskContext no longer requires a KB when KB.ID == "" (debug); debug runs return collectDebugOutput (chunks) instead of a no-op; uploaded bytes are delivered as inputs['binary'] for doc-less runs; injectDebugPageCap caps the parser to the first pages for a fast preview via the production override_params channel (Parser cpnID + family).
  • component/tokenizer.go: shouldHaveEmbedding skips embedding when kb_id == "" — the embedder is configured on the knowledgebase, so a debug run has nothing to resolve against and stays side-effect free.
  • chunker/register.go: chunk images are uploaded to MinIO only when a KB is present (persist run). In debug mode the raw image bytes are intentionally dropped (delete(ck, "image")) — the debug preview does not render chunk images, and dropping the bytes keeps them out of memory and out of the Redis-stored debug log. This is a deliberate trade-off, not an oversight.
  • component/file.go: pass through in-memory binary bytes, skipping doc_id -> storage resolution.
  • handler/agent.go + agent_webhook.go: detect dataflow_canvas and run a sync debug returning chunks inline on the existing chat/completions endpoint; reject DataFlow canvases from webhooks (fixes the previously dead == "DataFlow" check; mirrors Python agent_api.py).
  • parser_dispatch.go: export ParserFileFamily for the executor's page-cap injection.

Debug run log + "View result"

Mirrors Python's debug-log contract so the front-end can replay each component's progress and parsed output:

  • task/debug_log_sink.go: a DebugLogSink records every component's lifecycle into a [{component_id, trace}] array (each trace entry carries message, progress, timestamp, elapsed_time). Flush appends a terminal END marker whose first trace message is non-empty so the front-end detects completion. On failure the END marker is prefixed [ERROR] yet still carries the run, so the failure timeline renders instead of being stuck empty. Timestamps and elapsed_time are in seconds (matching the rest of the app).
  • task/debug_result_dsl.go: BuildDebugResultDSL builds the dsl the END marker carries — the Go analogue of Python's Graph.__str__ + END-marker dsl in rag/flow/pipeline.py. It combines the static DSL structure (component_name / downstream / params / graph.nodes) with the run output map (output["state"][<id>]) to emit, per component, obj.params.outputs[<format>].value (chunks / text / json / html / markdown) — the exact keys the front-end dataflow-result page reads to render each step's parsed chunks. Raw embedding vectors (including the dimension-scoped q_<dim>_vec keys) are stripped so the stored log stays Python-scale.
  • task/pipeline_executor.go: after the run, attach the built dsl to the END marker via the ResultSink capability.
  • handler/agent.go: runCanvasPipelineDebug generates a stable message_id up-front and always flushes the log (success or failure); respondWithDebugResult returns message_id in both the success and the error envelope so the front-end can poll the log. The debug-log endpoint GET /agents/:id/logs/:message_id serves the array.
  • web/src/pages/agent/hooks/use-run-dataflow.ts: on a run failure, also surface message_id via setMessageId so the log sheet renders the failure timeline (the [ERROR] END marker is already written). Guarded by if (msgId), so it is a safe no-op when the back-end does not return an id.

Behavioral notes

  • Debug parses only the first pages (debugPageCapPages) for a fast preview; an explicit pages cap already present in the ParserConfig is respected.
  • Debug mode does not keep chunk images (see above) and does not compute embeddings — it exercises parse + chunk only.

Test plan

  • Go: debug_test.go, debug_log_sink_test.go (trace pairing, END marker, [ERROR] prefix, fractional-second timestamp/elapsed_time, size caps, and a real-pipeline test asserting the END-marker dsl carries non-empty per-component params.outputs with chunks), debug_result_dsl_test.go (flat and real nested output["state"] shapes, vector stripping, format priority), debug_pages_integration_test.go, pipeline_executor_persist_test.go, handler/agent_pipeline_debug_test.go, handler/agent_logs_test.go (incl. TestRunCanvasPipelineDebug_ErrorStillExposesMessageID / TestRespondWithDebugResult_ErrorCarriesMessageID locking message_id on failure), plus updates to agent_test.go / agent_webhook_test.go / chunker/image_upload_test.go / tokenizer*.go.
  • go build ./... and ./build.sh --test for affected packages.

🤖 Generated with CodeBuddy Code

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 29, 2026
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

DataFlow chat requests now execute synchronous dry-run ingestion with in-memory files, empty KB identity, bounded Redis logs, stable message IDs, result chunks, and debug DSL output. Handler contracts, webhook validation, component side effects, and frontend failure polling were updated accordingly.

Changes

DataFlow debug execution and logging

Layer / File(s) Summary
Debug task and component execution contract
internal/ingestion/task/*, internal/ingestion/component/*
Debug runs use empty KB identity, transient document IDs, in-memory binary input, skip persistence-related embedding and image-upload work, and inject parser page caps.
Pipeline execution and result formatting
internal/ingestion/task/pipeline_executor.go, internal/ingestion/task/debug_result_dsl.go
Debug execution returns chunks without indexing or pipeline logs and builds vector-stripped UI result DSL output.
Progress tracing and log persistence
internal/ingestion/task/debug_log_sink.go, internal/ingestion/task/*test.go
Progress traces are bounded, flushed with terminal END markers, and stored under message-keyed Redis entries.
Handler and frontend integration
internal/handler/agent.go, internal/handler/*test.go, web/src/pages/agent/hooks/use-run-dataflow.ts
The handler accepts nested files, runs DataFlow debug requests, returns message IDs and chunks, reads malformed or missing logs safely, and preserves message IDs on failures.
Related contract and build updates
internal/handler/agent_webhook.go, internal/ingestion/pipeline/template_integration_test.go, internal/ingestion/component/chunker/pdfcrop_nocgo.go
Webhook rejection uses dataflow_canvas, integration fixtures provide KB identifiers and test databases, and the no-CGO PDF stub retains its GORM signature dependency.

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

Possibly related PRs

Suggested reviewers: jinhai-cn, yuzhichang

Poem

A rabbit runs a dry-run trail,
With chunks and logs that never fail.
Redis keeps each hopping clue,
An END says, “Done!” when work is through. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main change: adding DataFlow canvas debug mode and View result logging.
Description check ✅ Passed The description includes the required Summary section and clearly explains the purpose, implementation, behavior, and test coverage.

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 changed the title feat(ingestion): add DataFlow canvas debug (dry-run) mode WIP Feat(ingestion): add DataFlow canvas debug (dry-run) mode Jul 29, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Jul 29, 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: 2

🧹 Nitpick comments (8)
internal/ingestion/task/debug_pages_integration_test.go (1)

100-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Parser discovery here keeps the last match, while injectDebugPageCap uses the first.

The production loop breaks on the first Parser component; this loop keeps the last. With the current single-Parser template both agree, but if the template gains another Parser the test would assert against a cpnID the executor never touches. Adding a break aligns the two.

🤖 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/debug_pages_integration_test.go` around lines 100 -
104, Update the parser discovery loop over schemas to break immediately after
assigning parserCpnID for the first ComponentNameParser match, matching
injectDebugPageCap’s first-match behavior.
internal/ingestion/task/pipeline_executor.go (2)

416-448: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse the debug variable instead of re-testing Doc.ID.

Line 446 repeats the s.taskCtx.Doc.ID == CANVAS_DEBUG_DOC_ID comparison already captured in debug at line 416.

♻️ Proposed tweak
-	if s.taskCtx.Doc.ID == CANVAS_DEBUG_DOC_ID {
+	if debug {
 		injectDebugPageCap(dsl, parserConfig, s.taskCtx.Doc.Type)
 	}
🤖 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/pipeline_executor.go` around lines 416 - 448, Reuse
the existing debug variable for the page-cap condition instead of comparing
s.taskCtx.Doc.ID again. Update the conditional surrounding injectDebugPageCap,
while leaving the input setup and page-cap behavior unchanged.

507-516: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Only the first Parser component gets the debug page cap.

The loop breaks on the first match, so a DSL containing more than one Parser node leaves the remaining parsers uncapped and the debug preview parses those documents in full. Collecting every Parser cpnID and injecting the cap under each is a small change and keeps the preview bounded.

♻️ Apply the cap to every Parser component
-	var parserCpnID string
-	for _, s := range schemas {
-		if s.ComponentName == component.ComponentNameParser {
-			parserCpnID = s.CpnID
-			break
-		}
-	}
-	if parserCpnID == "" {
-		return
-	}
+	var parserCpnIDs []string
+	for _, s := range schemas {
+		if s.ComponentName == component.ComponentNameParser {
+			parserCpnIDs = append(parserCpnIDs, s.CpnID)
+		}
+	}
+	if len(parserCpnIDs) == 0 {
+		return
+	}

then loop the remaining body over parserCpnIDs.

🤖 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/pipeline_executor.go` around lines 507 - 516, Update
the parser component ID collection in the surrounding pipeline executor flow to
gather every schema whose ComponentName is component.ComponentNameParser,
removing the early break and returning only when no IDs were found. Then iterate
the remaining debug-cap injection logic over all collected parser CpnIDs so each
Parser component receives the preview document limit.
internal/ingestion/task/debug.go (1)

47-50: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Doc.Suffix gets a leading dot here, unlike the rest of the codebase.

deriveDocSuffixAndType returns ".pdf" for the suffix, while other entity.Document construction paths (e.g. internal/ingestion/task/pipeline_executor_persist_test.go line 40) use the bare "pdf". It is harmless today because Suffix is only read by recordPipelineLog, which the debug path skips, but the divergence will bite if any component starts branching on Doc.Suffix. Consider returning the extension without the dot for consistency.

🤖 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/debug.go` around lines 47 - 50, Update
deriveDocSuffixAndType to return the file extension without its leading dot, so
the Doc.Suffix assignment in the debug ingestion path matches other
entity.Document construction paths while preserving the existing document type
behavior.
internal/ingestion/component/globals/globals.go (1)

134-152: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a typed inputs map[string]any parameter instead of other ...any.

The variadic any makes the contract untypeable at call sites (a caller passing map[string]string or a struct silently degrades to the default). Every observed caller (chunker/register.go line 86) passes the component inputs map, so IsPersist(ctx context.Context, inputs map[string]any) bool would express the same behavior with compile-time checking.

Separately, note the value-type asymmetry: WithPersist stores a bool, while the Globals and inputs fallbacks only accept the string "true"/"false". A persist global published as a bool falls through to the true default.

🤖 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/component/globals/globals.go` around lines 134 - 152,
Change IsPersist to accept a typed inputs map[string]any parameter instead of
variadic any, and update its callers accordingly while preserving the existing
precedence and default behavior. Make the Globals and inputs fallback handling
accept bool values consistently with WithPersist, while retaining support for
the existing string "true"/"false" representation.
internal/ingestion/component/parser_dispatch.go (1)

329-331: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Normalize the hint in the exported wrapper.

pythonFamilyName matches only lowercase, dot-less extensions, so ParserFileFamily(".PDF") returns "". That silently turns injectDebugPageCap into a no-op (uncapped debug parse) for any caller that passes the suffix form or mixed case. internal/ingestion/task/debug.go happens to store a lowercase dot-less Doc.Type, but an exported cross-package entry point should not depend on that.

♻️ Proposed normalization
 func ParserFileFamily(ext string) string {
-	return pythonFamilyName(ext)
+	return pythonFamilyName(strings.ToLower(strings.TrimPrefix(ext, ".")))
 }

Requires strings in the import block if not already present.

🤖 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/component/parser_dispatch.go` around lines 329 - 331,
Update the exported ParserFileFamily wrapper to normalize ext by removing any
leading dot and converting it to lowercase before passing it to
pythonFamilyName. Preserve pythonFamilyName’s existing matching behavior while
ensuring suffix-form and mixed-case inputs produce the correct family.
internal/ingestion/task/debug_test.go (1)

44-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert against CANVAS_DEBUG_DOC_ID rather than the literal.

The test is in-package, so hard-coding "dataflow_x" only duplicates the constant and will drift if the constant is ever renumbered.

♻️ Proposed tweak
-	if taskCtx.Doc.ID != "dataflow_x" {
-		t.Errorf("Doc.ID = %q, want dataflow_x", taskCtx.Doc.ID)
+	if taskCtx.Doc.ID != CANVAS_DEBUG_DOC_ID {
+		t.Errorf("Doc.ID = %q, want %q", taskCtx.Doc.ID, CANVAS_DEBUG_DOC_ID)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/task/debug_test.go` around lines 44 - 46, Update the
Doc.ID assertion in the debug task test to compare against the in-package
CANVAS_DEBUG_DOC_ID constant instead of the hard-coded "dataflow_x" literal,
while preserving the existing error reporting.
internal/handler/agent.go (1)

95-99: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Keep changed Go comments focused on current behavior.

Remove Python-port/migration narrative and correct the stale claim that debugRunner supports webhook debug execution; webhooks reject DataFlow canvases.

  • internal/handler/agent.go#L95-L99: describe debugRunner as a chat-completions debug test seam only.
  • internal/handler/agent.go#L473-L483: document current debug execution inputs and non-persistence without Python-path references.
  • internal/handler/agent.go#L515-L520: do not claim a file-less pipeline run when the caller rejects empty file data.
  • internal/handler/agent.go#L954-L968: document the current 2D request shape and optional KB semantics only.
  • internal/handler/agent.go#L1107-L1115: describe the Go branch conditions without migration references.
  • internal/handler/agent_test.go#L1231-L1235: retain the 2D contract explanation without Python references.
  • internal/handler/agent_webhook.go#L136-L139: retain the rejection rationale without Python references.
  • internal/handler/agent_webhook_test.go#L156-L160: keep the test’s current rejection contract without migration commentary.

As per coding guidelines, keep Go comments aligned with the current runtime path and remove migration notes.

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

In `@internal/handler/agent.go` around lines 95 - 99, Remove migration/Python-port
language from comments across internal/handler/agent.go (95-99, 473-483,
515-520, 954-968, 1107-1115), internal/handler/agent_test.go (1231-1235),
internal/handler/agent_webhook.go (136-139), and
internal/handler/agent_webhook_test.go (156-160). Update the debugRunner comment
to describe only the chat-completions test seam, document current inputs and
non-persistence, avoid claiming file-less runs or webhook support, and
accurately describe the 2D request shape, optional KB behavior, Go branch
conditions, and webhook rejection contract.

Source: Coding guidelines

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

Inline comments:
In `@internal/handler/agent.go`:
- Around line 499-512: The DataFlow debug response currently returns chunks
without token usage. Update respondWithDebugResult in
internal/handler/agent.go:499-512 to return an envelope containing the chunk
list and a usage field sourced from result.TokenConsumption, while preserving
error and empty-result handling; update
internal/handler/agent_dataflow_test.go:57-118 to stub a non-zero token count
and assert the usage field is returned.

In `@internal/ingestion/component/file.go`:
- Around line 154-161: The FileComponent output schema must declare the binary
data emitted by Invoke. Update FileComponent.Outputs() to add a binary output
port matching the in-memory bytes in in.binary, so DSL wiring and output
validation can pass it to ParserComponent.

---

Nitpick comments:
In `@internal/handler/agent.go`:
- Around line 95-99: Remove migration/Python-port language from comments across
internal/handler/agent.go (95-99, 473-483, 515-520, 954-968, 1107-1115),
internal/handler/agent_test.go (1231-1235), internal/handler/agent_webhook.go
(136-139), and internal/handler/agent_webhook_test.go (156-160). Update the
debugRunner comment to describe only the chat-completions test seam, document
current inputs and non-persistence, avoid claiming file-less runs or webhook
support, and accurately describe the 2D request shape, optional KB behavior, Go
branch conditions, and webhook rejection contract.

In `@internal/ingestion/component/globals/globals.go`:
- Around line 134-152: Change IsPersist to accept a typed inputs map[string]any
parameter instead of variadic any, and update its callers accordingly while
preserving the existing precedence and default behavior. Make the Globals and
inputs fallback handling accept bool values consistently with WithPersist, while
retaining support for the existing string "true"/"false" representation.

In `@internal/ingestion/component/parser_dispatch.go`:
- Around line 329-331: Update the exported ParserFileFamily wrapper to normalize
ext by removing any leading dot and converting it to lowercase before passing it
to pythonFamilyName. Preserve pythonFamilyName’s existing matching behavior
while ensuring suffix-form and mixed-case inputs produce the correct family.

In `@internal/ingestion/task/debug_pages_integration_test.go`:
- Around line 100-104: Update the parser discovery loop over schemas to break
immediately after assigning parserCpnID for the first ComponentNameParser match,
matching injectDebugPageCap’s first-match behavior.

In `@internal/ingestion/task/debug_test.go`:
- Around line 44-46: Update the Doc.ID assertion in the debug task test to
compare against the in-package CANVAS_DEBUG_DOC_ID constant instead of the
hard-coded "dataflow_x" literal, while preserving the existing error reporting.

In `@internal/ingestion/task/debug.go`:
- Around line 47-50: Update deriveDocSuffixAndType to return the file extension
without its leading dot, so the Doc.Suffix assignment in the debug ingestion
path matches other entity.Document construction paths while preserving the
existing document type behavior.

In `@internal/ingestion/task/pipeline_executor.go`:
- Around line 416-448: Reuse the existing debug variable for the page-cap
condition instead of comparing s.taskCtx.Doc.ID again. Update the conditional
surrounding injectDebugPageCap, while leaving the input setup and page-cap
behavior unchanged.
- Around line 507-516: Update the parser component ID collection in the
surrounding pipeline executor flow to gather every schema whose ComponentName is
component.ComponentNameParser, removing the early break and returning only when
no IDs were found. Then iterate the remaining debug-cap injection logic over all
collected parser CpnIDs so each Parser component receives the preview document
limit.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ecd439f3-e222-4bb3-9555-1fb8b070dbb5

📥 Commits

Reviewing files that changed from the base of the PR and between f8e01d5 and 3ba3cf4.

📒 Files selected for processing (16)
  • internal/handler/agent.go
  • internal/handler/agent_dataflow_test.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook.go
  • internal/handler/agent_webhook_test.go
  • internal/ingestion/component/chunker/image_upload_test.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/globals/globals.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/parser_dispatch.go
  • internal/ingestion/task/debug.go
  • internal/ingestion/task/debug_pages_integration_test.go
  • internal/ingestion/task/debug_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_executor_persist_test.go

Comment thread internal/handler/agent.go Outdated
Comment on lines +499 to +512
// respondWithDebugResult writes the outcome of a dataflow debug run: on
// error it surfaces a server error; otherwise it returns the chunks inline
// (empty slices become `[]` rather than `null`). It is the single wire-shape
// helper for the chat/completions DataFlow debug entry point.
func respondWithDebugResult(c *gin.Context, result *task.PipelineResult, err error) {
if err != nil {
common.ResponseWithCodeData(c, common.CodeServerError, nil, err.Error())
return
}
if result == nil || len(result.Chunks) == 0 {
common.SuccessWithData(c, []map[string]any{}, "success")
return
}
common.SuccessWithData(c, result.Chunks, "success")

ghost Jul 29, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Return token usage from the DataFlow debug endpoint.

respondWithDebugResult discards PipelineResult.TokenConsumption, so the synchronous debug API returns chunks but not the token usage required by this PR.

  • internal/handler/agent.go#L499-L512: return a response envelope containing the chunk list and a usage field sourced from result.TokenConsumption.
  • internal/handler/agent_dataflow_test.go#L57-L118: assert the usage field for a stubbed non-zero token count.
📍 Affects 2 files
  • internal/handler/agent.go#L499-L512 (this comment)
  • internal/handler/agent_dataflow_test.go#L57-L118
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/agent.go` around lines 499 - 512, The DataFlow debug
response currently returns chunks without token usage. Update
respondWithDebugResult in internal/handler/agent.go:499-512 to return an
envelope containing the chunk list and a usage field sourced from
result.TokenConsumption, while preserving error and empty-result handling;
update internal/handler/agent_dataflow_test.go:57-118 to stub a non-zero token
count and assert the usage field is returned.

Comment on lines +154 to +161
// Pass through in-memory bytes when present (debug / dataflow dry-run
// where no doc row exists in storage). The downstream Parser reads
// `binary` first and skips the doc_id → storage lookup, so a debug run
// can parse the uploaded file without a persisted document. Persist
// runs set no `binary` here, so they keep resolving from storage.
if len(in.binary) > 0 {
out["binary"] = in.binary
}

ghost Jul 29, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Declare binary in FileComponent.Outputs().

Invoke now emits binary, but the component output schema has no binary port. Add it so debug DSL wiring and any output-schema validation can pass the in-memory bytes to ParserComponent.

Proposed fix
 func (c *FileComponent) Outputs() map[string]string {
     return map[string]string{
+        "binary": "In-memory file bytes for non-persist debug parsing.",
         "doc_id": "Document ID echoed for downstream Parser storage lookup.",
🤖 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/component/file.go` around lines 154 - 161, The
FileComponent output schema must declare the binary data emitted by Invoke.
Update FileComponent.Outputs() to add a binary output port matching the
in-memory bytes in in.binary, so DSL wiring and output validation can pass it to
ParserComponent.

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

🧹 Nitpick comments (1)
internal/ingestion/component/tokenizer_nonpersist_test.go (1)

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

Keep test documentation focused on the current runtime path.

Lines 17-20 preserve PR-branch migration history, while lines 40-42 advertise raw go test. Both can become stale, and the latter conflicts with the repository’s preferred Go test workflow. Keep the behavioral contract, but remove the branch rationale and either remove the command note or reference the supported package-scoped wrapper.

Suggested cleanup
-// Regression guard for the non-persist (canvas-debug) run contract. It lives in
-// the canvas-debug branch (not the ingestion-fixes branch) because it depends on
-// component/globals.WithPersist, which is defined by the debug feature, keeping
-// the ingestion-fixes branch compilable on its own.
+// Regression guard for the non-persist (canvas-debug) run contract.
...
-// It uses embedding-only search_method so it runs without the C++ RAGAnalyzer
-// pool (plain `go test`, no -tags integration), keeping the regression gate
-// executable in every environment.
+// It uses embedding-only search_method, so it does not require the C++
+// RAGAnalyzer pool.

As per coding guidelines, Go comments should reflect the current runtime path rather than migration history, and Go changes should prefer package-scoped bash build.sh --test ... over raw go test.

Also applies to: 40-42

🤖 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/component/tokenizer_nonpersist_test.go` around lines 17 -
20, Update the comments in the non-persist tokenizer regression test to document
only the current runtime behavior: remove the branch and migration rationale,
and remove the raw go test command or replace it with the supported
package-scoped bash build.sh --test workflow. Preserve the behavioral contract
being tested.

Source: Coding guidelines

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

Nitpick comments:
In `@internal/ingestion/component/tokenizer_nonpersist_test.go`:
- Around line 17-20: Update the comments in the non-persist tokenizer regression
test to document only the current runtime behavior: remove the branch and
migration rationale, and remove the raw go test command or replace it with the
supported package-scoped bash build.sh --test workflow. Preserve the behavioral
contract being tested.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d62823dc-6200-410f-b4db-475840c94b46

📥 Commits

Reviewing files that changed from the base of the PR and between 3ba3cf4 and 85c314a.

📒 Files selected for processing (1)
  • internal/ingestion/component/tokenizer_nonpersist_test.go

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 30, 2026
@xugangqiang xugangqiang changed the title WIP Feat(ingestion): add DataFlow canvas debug (dry-run) mode Feat(ingestion): add DataFlow canvas debug (dry-run) mode with View result log Jul 30, 2026

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

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

1552-1573: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

GetAgentLogs silently returns success on genuine Redis failures.

redis.Client.Get already converts a missing key (redis.Nil) into ("", nil), so a non-nil rerr here means a real backend/connectivity failure — yet the handler ignores rerr entirely and returns code=0 with empty data, with no logging. Clients polling for debug logs during a Redis outage will see "no logs yet" instead of a diagnosable failure.

🔧 Proposed fix
 	key := fmt.Sprintf("%s-%s-logs", canvasID, messageID)
 	payload, rerr := h.redisGet(key)
 	var data interface{} = map[string]interface{}{}
 	if rerr == nil {
 		data = parseAgentLogs(payload)
+	} else {
+		common.Warn("GetAgentLogs: redis get failed", zap.String("key", key), zap.Error(rerr))
 	}
 	common.SuccessWithData(c, data, "success")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/agent.go` around lines 1552 - 1573, Update GetAgentLogs to
handle a non-nil rerr from redisGet as a backend failure instead of returning
success with empty data: log the Redis error using the handler’s established
logging pattern and respond with the appropriate internal-error code/message,
while preserving the existing successful parseAgentLogs flow and missing-key
behavior.
internal/ingestion/component/chunker/image_upload_test.go (1)

1-1: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Fix the !cgo PDF crop fallback typecheck.

pdfcrop_nocgo.go is selected only when cgo is disabled, but newPDFEngineFromUpstream still uses *gorm.DB without importing gorm.io/gorm, so any typecheck/configuration that includes this file reports undefined: gorm and prevents go build ./internal/ingestion/component/chunker/... for the no-CGO variant.

🤖 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/component/chunker/image_upload_test.go` at line 1, Fix the
no-CGO implementation in pdfcrop_nocgo.go by adding the required gorm.io/gorm
import so the *gorm.DB parameter used by newPDFEngineFromUpstream resolves
during typechecking. Preserve the existing fallback behavior and function
signature.

Source: Linters/SAST tools

🧹 Nitpick comments (6)
internal/ingestion/component/tokenizer_nonpersist_test.go (1)

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

Drop the branch-bookkeeping note from the file comment.

Lines 19-21 explain which development branch this file lives in rather than the behavior under test; keep the comment on the kb_id == "" debug contract only. (The filename tokenizer_nonpersist_test.go also no longer matches what it tests, since persist gating is gone — a rename to something like tokenizer_debug_test.go would keep it aligned.)

As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history".

♻️ Proposed edit
 // Regression guard for the canvas-debug (dry-run) run contract: a debug run
 // carries no KB (kb_id == ""), so the tokenizer must skip embedding rather than
-// resolving an embedder. It lives in the canvas-debug branch (not the
-// ingestion-fixes branch) so the ingestion-fixes branch stays compilable on its
-// own.
+// resolving an embedder.
🤖 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/component/tokenizer_nonpersist_test.go` around lines 17 -
21, Remove the branch-bookkeeping sentences from the file comment, retaining
only the canvas-debug contract that an empty kb_id skips embedding without
resolving an embedder. Rename tokenizer_nonpersist_test.go to a debug-focused
name such as tokenizer_debug_test.go so the filename reflects the behavior under
test.

Source: Coding guidelines

internal/ingestion/component/tokenizer.go (1)

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

Shadowed chunks makes the validation call depend on in-place mutation.

chunks, tokenCount, err := c.embedChunks(...) declares a new chunks scoped to the if block, so line 376 validates the outer slice. It works today only because embedChunks mutates elements through the shared backing array; if it ever reallocates (e.g. filtering/appending), validation and out["chunks"] would silently diverge. Assign to the outer variable instead.

♻️ Proposed refactor
 	if shouldHaveEmbedding(c.param.SearchMethod, kbID) {
-		chunks, tokenCount, err := c.embedChunks(ctx, tenantID, kbID, embeddingModel, name, chunks)
-		if err != nil {
+		embedded, tokenCount, err := c.embedChunks(ctx, tenantID, kbID, embeddingModel, name, chunks)
+		if err != nil {
 			return nil, err
 		}
+		chunks = embedded
 		out["embedding_token_consumption"] = tokenCount
 		out["chunks"] = schema.ChunkDocsToMaps(chunks)
 	}
🤖 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/component/tokenizer.go` around lines 368 - 376, Update the
embedding branch in the surrounding tokenizer method to assign the result of
c.embedChunks to the existing outer chunks variable rather than redeclaring it
with :=. Preserve tokenCount and err handling, and ensure both out["chunks"] and
validateTokenizerOutputs consume the updated slice returned by embedChunks.
internal/ingestion/task/debug_result_dsl.go (1)

49-54: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

q_vec never matches the real vector key format q_<dim>_vec.

Embedding vectors are written as q_%d_vec (e.g. q_1024_vec, see internal/ingestion/component/tokenizer.go SetExtraValue), so the literal q_vec entry in vectorKeys never fires. Today debug runs skip embedding so this is latent, but any payload that does carry vectors would ship full float arrays into the 1 MiB-capped Redis log and to the UI. Match the pattern instead of the literal.

♻️ Proposed fix
 	case map[string]any:
 		cp := make(map[string]any, len(val))
 		for k, vv := range val {
-			if _, drop := vectorKeys[k]; drop {
+			if isVectorKey(k) {
 				continue
 			}
 			cp[k] = deepCopyStrip(vv)
 		}
 		return cp
// isVectorKey reports whether k holds raw embedding data: either a fixed name
// or the dynamic q_<dim>_vec form emitted by the Tokenizer.
func isVectorKey(k string) bool {
	if _, ok := vectorKeys[k]; ok {
		return true
	}
	return strings.HasPrefix(k, "q_") && strings.HasSuffix(k, "_vec")
}

Also applies to: 207-216

🤖 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/debug_result_dsl.go` around lines 49 - 54, Update
vector-key detection around vectorKeys and its consumers to recognize dynamic
embedding keys in the q_<dim>_vec format, not only the ineffective literal q_vec
entry. Add or reuse an isVectorKey helper that preserves fixed-key matching
while checking the q_ prefix and _vec suffix, and ensure all relevant filtering
paths use it.
internal/handler/agent_dataflow_test.go (1)

65-67: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment is inaccurate. runDataflowDebug always calls sink.Flush (internal/handler/agent.go:539-571), so the write is not skipped — the store is needed because it is exercised.

📝 Wording tweak
-	// runDataflowDebug flushes the debug log via redisStore; inject a no-op
-	// store so the (skipped in this test) log write does not nil-panic.
+	// runDataflowDebug always flushes the debug log via redisStore; inject a
+	// capturing store so the write has somewhere to 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/handler/agent_dataflow_test.go` around lines 65 - 67, Update the
comment beside WithRedisStore in the test to accurately state that
runDataflowDebug exercises sink.Flush and requires the injected no-op store,
rather than claiming the log write is skipped.
internal/ingestion/task/debug_log_sink.go (2)

256-267: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Copy of an existing helper. The doc comment admits it duplicates internal/service/agent_sessions.go's truncateRunes; consider promoting one copy to a shared internal util instead of keeping two. Also, max shadows the builtin.

As per coding guidelines: "collapse duplicate implementations".

🤖 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/debug_log_sink.go` around lines 256 - 267,
Consolidate the duplicate truncateRunes implementation used by the debug log
sink and internal/service/agent_sessions.go into one shared internal utility,
then update both callers to reuse it and remove the local copy and duplication
comment. Rename the shared helper’s max parameter to avoid shadowing the builtin
while preserving the existing truncation behavior.

Source: Coding guidelines


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

Share the key format with the reader.

GetAgentLogs builds the same key independently (internal/handler/agent.go:1566, fmt.Sprintf("%s-%s-logs", ...)). Export a DebugLogKey(canvasID, messageID string) string here and use it on both sides so the format can't drift.

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

In `@internal/ingestion/task/debug_log_sink.go` around lines 252 - 253, Extract
the shared log-key construction from the sink code into an exported
DebugLogKey(canvasID, messageID string) helper, then replace the local
concatenation in the sink and the independently formatted key in GetAgentLogs
with calls to this helper. Preserve the existing “canvasID-messageID-logs”
format.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/agent.go`:
- Around line 585-604: Update respondWithDebugResult to include
result.TokenConsumption in the successful response payload alongside message_id
and chunks, while preserving the existing empty-chunk handling and error
response behavior.

In `@internal/ingestion/task/debug_log_sink_test.go`:
- Around line 19-34: The no-CGO fallback stub fails to compile because
newPDFEngineFromUpstream references *gorm.DB without importing gorm. Update
newPDFEngineFromUpstream in pdfcrop_nocgo.go to accept a typed fallback value
that avoids exposing gorm.DB, while preserving the caller-facing behavior and
no-op semantics; adjust its call sites as needed for the signature change.

In `@internal/ingestion/task/debug_log_sink.go`:
- Around line 244-254: Update trimToPayloadBudget and the surrounding payload
handling so the serialized log value never exceeds maxPayloadBytes, including
when the END entry’s resultDSL alone is oversized. After removing other entries,
clear or otherwise drop resultDSL from the retained END entry as the final
fallback, then re-marshal and verify the size before calling s.store.Set in the
enclosing method.

In `@internal/ingestion/task/debug_result_dsl.go`:
- Around line 186-227: Update deepCopy and deepCopyStrip to recursively handle
[]map[string]any in addition to map[string]any and []any. Ensure each map
element is copied independently, and deepCopyStrip removes vectorKeys from every
nested map while preserving the existing behavior for other values and slice
types.

---

Outside diff comments:
In `@internal/handler/agent.go`:
- Around line 1552-1573: Update GetAgentLogs to handle a non-nil rerr from
redisGet as a backend failure instead of returning success with empty data: log
the Redis error using the handler’s established logging pattern and respond with
the appropriate internal-error code/message, while preserving the existing
successful parseAgentLogs flow and missing-key behavior.

In `@internal/ingestion/component/chunker/image_upload_test.go`:
- Line 1: Fix the no-CGO implementation in pdfcrop_nocgo.go by adding the
required gorm.io/gorm import so the *gorm.DB parameter used by
newPDFEngineFromUpstream resolves during typechecking. Preserve the existing
fallback behavior and function signature.

---

Nitpick comments:
In `@internal/handler/agent_dataflow_test.go`:
- Around line 65-67: Update the comment beside WithRedisStore in the test to
accurately state that runDataflowDebug exercises sink.Flush and requires the
injected no-op store, rather than claiming the log write is skipped.

In `@internal/ingestion/component/tokenizer_nonpersist_test.go`:
- Around line 17-21: Remove the branch-bookkeeping sentences from the file
comment, retaining only the canvas-debug contract that an empty kb_id skips
embedding without resolving an embedder. Rename tokenizer_nonpersist_test.go to
a debug-focused name such as tokenizer_debug_test.go so the filename reflects
the behavior under test.

In `@internal/ingestion/component/tokenizer.go`:
- Around line 368-376: Update the embedding branch in the surrounding tokenizer
method to assign the result of c.embedChunks to the existing outer chunks
variable rather than redeclaring it with :=. Preserve tokenCount and err
handling, and ensure both out["chunks"] and validateTokenizerOutputs consume the
updated slice returned by embedChunks.

In `@internal/ingestion/task/debug_log_sink.go`:
- Around line 256-267: Consolidate the duplicate truncateRunes implementation
used by the debug log sink and internal/service/agent_sessions.go into one
shared internal utility, then update both callers to reuse it and remove the
local copy and duplication comment. Rename the shared helper’s max parameter to
avoid shadowing the builtin while preserving the existing truncation behavior.
- Around line 252-253: Extract the shared log-key construction from the sink
code into an exported DebugLogKey(canvasID, messageID string) helper, then
replace the local concatenation in the sink and the independently formatted key
in GetAgentLogs with calls to this helper. Preserve the existing
“canvasID-messageID-logs” format.

In `@internal/ingestion/task/debug_result_dsl.go`:
- Around line 49-54: Update vector-key detection around vectorKeys and its
consumers to recognize dynamic embedding keys in the q_<dim>_vec format, not
only the ineffective literal q_vec entry. Add or reuse an isVectorKey helper
that preserves fixed-key matching while checking the q_ prefix and _vec suffix,
and ensure all relevant filtering paths use it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3f8276ff-f013-46d9-930c-186755826f78

📥 Commits

Reviewing files that changed from the base of the PR and between 85c314a and b3a9209.

📒 Files selected for processing (22)
  • internal/handler/agent.go
  • internal/handler/agent_dataflow_test.go
  • internal/handler/agent_logs_test.go
  • internal/ingestion/component/chunker/image_upload_test.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_nonpersist_test.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/debug.go
  • internal/ingestion/task/debug_log_sink.go
  • internal/ingestion/task/debug_log_sink_test.go
  • internal/ingestion/task/debug_pages_integration_test.go
  • internal/ingestion/task/debug_result_dsl.go
  • internal/ingestion/task/debug_result_dsl_test.go
  • internal/ingestion/task/debug_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_executor_persist_test.go
  • internal/ingestion/task/pipeline_executor_test.go
  • web/src/pages/agent/hooks/use-run-dataflow.ts
💤 Files with no reviewable changes (1)
  • internal/ingestion/task/constants.go

Comment thread internal/handler/agent.go Resolved
Comment on lines +19 to +34
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"

"gorm.io/gorm"
"ragflow/internal/agent/runtime"
"ragflow/internal/ingestion/pipeline"
)

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'pdfcrop.*\.go' internal/ingestion/component/chunker --exec cat -n {}

Repository: infiniflow/ragflow

Length of output: 15586


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate chunker source files and inspect the function signature that uses gorm.DB.
fd -Tf '.*\.go$' internal/ingestion/component/chunker | sort | sed -n '1,120p'

printf '\n--- references to newPDFEngineFromUpstream and ChunkerFromUpstream ---\n'
rg -n "newPDFEngineFromUpstream|ChunkerFromUpstream|gorm\.DB|gorm\.gorm" internal/ingestion/component/chunker internal/ingestion/pipeline internal/ingestion -g '*.go' | sed -n '1,200p'

printf '\n--- build/test scripts ---\n'
ls -la build.sh 2>/dev/null || true
sed -n '1,220p' build.sh 2>/dev/null || true

printf '\n--- go files mentioning gorm import in chunker package ---\n'
python3 - <<'PY'
import pathlib, re
p = pathlib.Path('internal/ingestion/component/chunker')
for path in sorted(p.glob('*.go')):
    text = path.read_text()
    if text.startswith('package chunker'):
        has_gorm_import = bool(re.search(r'"[^"]*/?gorm\.io/gorm"', text))
        has_gorm_type = bool(re.search(r'\bgorm\.', text))
        print(f'{path}: has_gorm_import={has_gorm_import}, has_gorm_type={has_gorm_type}, build_tags={" ".join(re.findall(r"//go:build (.*)", text))}')
PY

Repository: infiniflow/ragflow

Length of output: 317


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate chunker source files and inspect the function signature that uses gorm.DB.
fd -t f '.*\.go$' internal/ingestion/component/chunker | sort | sed -n '1,120p'

printf '\n--- references to gorm in chunker and ingestion Go files ---\n'
rg -n "\bgorm\." internal/ingestion/component/chunker internal/ingestion -g '*.go' | sed -n '1,240p'

printf '\n--- build/test scripts ---\n'
if [ -f build.sh ]; then
  ls -la build.sh
  sed -n '1,240p' build.sh
else
  echo "build.sh not found"
fi

printf '\n--- chunker Go files with gorm references/import status ---\n'
python3 - <<'PY'
import pathlib, re
p = pathlib.Path('internal/ingestion/component/chunker')
for path in sorted(p.glob('*.go')):
    text = path.read_text()
    if text.startswith('package chunker'):
        match = re.search(r'(?s)^//go:build (.*?)\n\n|^\n\n', text)
        build_tags = match.group(1) if match else ''
        has_gorm_import = bool(re.search(r'"gomadisin/cellx/gorm\.io/cellx|gorm\.io/gorm"', text)) or 'gorm' in text and 'import' in text
        has_gorm_type = bool(re.search(r'\bgorm\.', text))
        print(f'{path}: build_tags={build_tags!r}, has_gorm_reference={has_gorm_type}, has_gorm_import_literal={has_gorm_import}')
PY

Repository: infiniflow/ragflow

Length of output: 32510


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- pdfcrop files headers and gorm references ---'
for f in internal/ingestion/component/chunker/pdfcrop_nocgo.go internal/ingestion/component/chunker/pdfcrop_cgo.go; do
  echo "### $f"
  sed -n '1,25p' "$f"
  rg -n "\bgorm\b" "$f"
done

printf '%s\n' '--- imports in internal/ingestone/component/chunker Go files ---'
python3 - <<'PY'
import ast, pathlib, re
p = pathlib.Path('internal/ingestion/component/chunker')
for path in sorted(p.glob('*.go')):
    text = path.read_text()
    if not re.search(r'^package chunker\b', text, re.M):
        continue
    try:
        tree = ast.parse(text)
    except SyntaxError as e:
        print(f'{path}: SYNTAX_ERROR {e.msg}')
        continue
    build_tags = []
    for token in re.findall(r'^//go:build\s+(.*?)(?:\n|$)', text, re.M):
        build_tags.append(token)
    imports = [imp.name for imp in tree.body if isinstance(imp, ast.Import) for imp in imp.names] + [imp.module for imp in tree.body if isinstance(imp, ast.ImportFrom) and imp.module]
    print(f'{path}: tags={build_tags}, imports_gorm={any("gorm.io/gorm" in imp or "gorm" in imp for imp in imports)}, has_gorm_dot={bool(re.search(r"\bgorm\.", text))}')
PY

Repository: infiniflow/ragflow

Length of output: 2635


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- all chunker Go files mentioning gorm type ---'
python3 - <<'PY'
import pathlib, re
p = pathlib.Path('internal/ingestion/component/chunker')
for path in sorted(p.glob('*.go')):
    text = path.read_text()
    if not re.search(r'^package chunker\b', text, re.M):
        continue
    build_tags = re.findall(r'^//go:build\s+(.*?)(?:\n|$)', text, re.M)
    has_gorm_import = bool(re.search(r'["\'](ragflow/.*/gorm|gorm\.io/gorm)["\']', text))
    has_gorm_type = bool(re.search(r'\bgorm\.', text))
    if has_gorm_type:
        print(f"{path}: build_tags={build_tags!r} imports_gorm={has_gorm_import} has_gorm_type=True")
PY

Repository: infiniflow/ragflow

Length of output: 1415


Fix the no-CGO build by passing a typed value through the fallback path. In internal/ingestion/component/chunker/pdfcrop_nocgo.go, newPDFEngineFromUpstream uses *gorm.DB without importing gorm.io/gorm, so the !cgo build cannot compile while other chunker files do import gorm. Keep the public signature if callers still want it, but avoid exposing gorm.DB in this no-op stub.

🤖 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/debug_log_sink_test.go` around lines 19 - 34, The
no-CGO fallback stub fails to compile because newPDFEngineFromUpstream
references *gorm.DB without importing gorm. Update newPDFEngineFromUpstream in
pdfcrop_nocgo.go to accept a typed fallback value that avoids exposing gorm.DB,
while preserving the caller-facing behavior and no-op semantics; adjust its call
sites as needed for the signature change.

Source: Linters/SAST tools

Comment on lines +244 to +254
// Hard ceiling: if a buggy/abusive run still exceeds it, drop the middle
// entries (keeping the first few and the END marker) until under budget.
if len(payload) > maxPayloadBytes {
entries = trimToPayloadBudget(entries, maxPayloadBytes)
if payload, err = json.Marshal(entries); err != nil {
return
}
}
key := s.canvasID + "-" + s.messageID + "-logs"
s.store.Set(key, string(payload), s.ttl)
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

The 1 MiB ceiling isn't actually enforced for the most likely large payload.

trimToPayloadBudget always keeps the END marker, and that marker carries resultDSL (all parsed chunks). If the DSL alone exceeds maxPayloadBytes, the loop bottoms out at len(entries) == 2 — and it exits on that condition without re-checking the budget — so Set still writes an oversized value to Redis. Same for a single over-budget END entry.

🛠️ Proposed fix: drop the DSL as a last resort
 	if len(payload) > maxPayloadBytes {
 		entries = trimToPayloadBudget(entries, maxPayloadBytes)
 		if payload, err = json.Marshal(entries); err != nil {
 			return
 		}
+		if len(payload) > maxPayloadBytes && len(entries) > 0 {
+			// The END marker's result DSL alone busts the budget; drop it so the
+			// completion signal still fits (the front-end degrades to no result).
+			last := len(entries) - 1
+			if len(entries[last].Trace) > 0 {
+				entries[last].Trace[0].Dsl = nil
+			}
+			if payload, err = json.Marshal(entries); err != nil || len(payload) > maxPayloadBytes {
+				return
+			}
+		}
 	}
📝 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
// Hard ceiling: if a buggy/abusive run still exceeds it, drop the middle
// entries (keeping the first few and the END marker) until under budget.
if len(payload) > maxPayloadBytes {
entries = trimToPayloadBudget(entries, maxPayloadBytes)
if payload, err = json.Marshal(entries); err != nil {
return
}
}
key := s.canvasID + "-" + s.messageID + "-logs"
s.store.Set(key, string(payload), s.ttl)
}
// Hard ceiling: if a buggy/abusive run still exceeds it, drop the middle
// entries (keeping the first few and the END marker) until under budget.
if len(payload) > maxPayloadBytes {
entries = trimToPayloadBudget(entries, maxPayloadBytes)
if payload, err = json.Marshal(entries); err != nil {
return
}
if len(payload) > maxPayloadBytes && len(entries) > 0 {
// The END marker's result DSL alone busts the budget; drop it so the
// completion signal still fits (the front-end degrades to no result).
last := len(entries) - 1
if len(entries[last].Trace) > 0 {
entries[last].Trace[0].Dsl = nil
}
if payload, err = json.Marshal(entries); err != nil || len(payload) > maxPayloadBytes {
return
}
}
}
key := s.canvasID + "-" + s.messageID + "-logs"
s.store.Set(key, string(payload), s.ttl)
}
🤖 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/debug_log_sink.go` around lines 244 - 254, Update
trimToPayloadBudget and the surrounding payload handling so the serialized log
value never exceeds maxPayloadBytes, including when the END entry’s resultDSL
alone is oversized. After removing other entries, clear or otherwise drop
resultDSL from the retained END entry as the final fallback, then re-marshal and
verify the size before calling s.store.Set in the enclosing method.

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
internal/ingestion/component/parser_dispatch.go (1)

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

Describe the current parser contract, not the Python implementation.

Remove the “python-side” wording; this exported API now serves the Go runtime’s canonical parser-config family lookup.

Proposed fix
-// python-side family identifier used as the key into a Parser component's
+// canonical family identifier used as the key into a Parser component's
🤖 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/component/parser_dispatch.go` around lines 323 - 328,
Update the documentation for the exported ParserFileFamily function to remove
“python-side” wording and describe its role in the Go runtime’s canonical
parser-config family lookup, including its use as the family key for
ParserConfig setups and page overrides.

Source: Coding guidelines

internal/ingestion/component/tokenizer_nonpersist_test.go (1)

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

Remove branch-history and raw-go test commentary.

Keep this regression test documented in terms of its runtime contract; branch topology and raw validation commands are stale and conflict with the project’s required Go validation path.

Proposed fix
-// against, and a debug run must stay side-effect free. The tokenizer must
-// return its chunks without error, without invoking the embedder, and without
-// attaching embedding vectors. Conversely, when a kb_id is present the embedding
-// path must run.
-//
-// It uses embedding-only search_method so it runs without the C++ RAGAnalyzer
-// pool (plain `go test`, no -tags integration), keeping the regression gate
-// executable in every environment.
+// against, and a debug run must stay side-effect free. The tokenizer must
+// return its chunks without error, without invoking the embedder, and without
+// attaching embedding vectors. Conversely, when a kb_id is present the embedding
+// path must run.

Also applies to: 38-40

🤖 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/component/tokenizer_nonpersist_test.go` around lines 17 -
21, Update the comments surrounding the regression test in the tokenizer test
file to describe only the runtime contract: dry-run requests with an empty kb_id
must skip embedding and avoid resolving an embedder. Remove all references to
branch names, branch history, and raw go test or validation commands.

Source: Coding guidelines

internal/handler/agent.go (2)

520-538: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Collapse the duplicated doc comment.

Lines 520-532 and 533-538 both open with "runDataflowDebug runs a canvas in dataflow dry-run (debug) mode…"; the function has two stacked summaries saying largely the same thing.

♻️ Proposed consolidation
-// runDataflowDebug runs a canvas in dataflow dry-run (debug) mode: it builds
-// an in-memory debug TaskContext and executes the pipeline synchronously,
-// returning the produced chunks. It performs no persistence (no MinIO upload,
-// index insert, or pipeline_log) because the debug context carries no KB
-// (KB.ID == ""), which is the single debug signal used across the ingestion
-// pipeline: the tokenizer skips embedding and the executor skips the persist
-// stage. kb_id == "" occurs ONLY in debug mode; production ingestion always
-// supplies a KB, so this path is never taken in normal operation.
-//
-// The request's kb_id is intentionally never forwarded: debug never resolves
-// an embedder or writes to a KB, and parse/chunk work without it. Callers
-// extract the (fileName, fileData) pair from their own request shape and pass
-// them in.
-// runDataflowDebug runs a canvas in dataflow dry-run (debug) mode and returns
-// the produced chunks. The run is fully synchronous: the complete debug log
-// (including the terminal END marker) is flushed to Redis BEFORE this method
-// returns, so the message_id it yields is for *replay* — re-fetching the log
-// after a page refresh or from a shared link — not for incremental streaming.
-// The front-end's poll therefore receives a finished log on the first request.
+// runDataflowDebug runs a canvas in dataflow dry-run (debug) mode: it builds an
+// in-memory debug TaskContext, executes the pipeline synchronously, and returns
+// the produced chunks. The debug context carries no KB (KB.ID == ""), which is
+// the single debug signal across the ingestion pipeline, so no persistence
+// happens (no MinIO upload, index insert, or pipeline_log) and the request's
+// kb_id is never forwarded. The complete debug log (including the terminal END
+// marker) is flushed to Redis before returning, so the returned message_id is a
+// replay key rather than a streaming subscription.

As per coding guidelines: "drop stale comments and documentation".

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

In `@internal/handler/agent.go` around lines 520 - 538, Consolidate the duplicated
documentation immediately above runDataflowDebug into one concise comment.
Retain only the current behavior details needed to describe synchronous
execution, completed log flushing before return, replay-oriented message_id
semantics, and the debug-only no-persistence behavior; remove the repeated or
stale summary text.

Source: Coding guidelines


629-635: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Download failure is indistinguishable from "no file".

When DownloadAgentFile errors, the error is dropped and the caller at Line 1218 reports "dataflow debug requires an uploaded file" — the operator sees a bogus validation message instead of the storage failure. Consider returning the error (or at least logging it) so the real cause is observable.

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

In `@internal/handler/agent.go` around lines 629 - 635, Update the
DownloadAgentFile handling in the relevant agent handler to preserve and
propagate its error instead of treating it like empty data. Keep the existing
fallback behavior only for successful downloads with no file, and ensure callers
such as the dataflow debug validation receive the storage failure.
internal/ingestion/component/chunker/image_upload_test.go (1)

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

Use t.Errorf in the uploader stub.

If uploadChunkImages ever fans out per chunk, t.Fatalf only runtime.Goexit()s that goroutine and the test can pass despite the violation.

💚 Proposed fix
 	ChunkImageUploader = func(_ context.Context, _, _ string, _ []byte) (string, error) {
-		t.Fatalf("ChunkImageUploader must not be called in a debug run")
-		return "", nil
+		t.Errorf("ChunkImageUploader must not be called in a debug run")
+		return "", nil
 	}

Based on learnings: in Go test callbacks that may run off the test goroutine, use t.Errorf instead of t.Fatalf, since t.Fatalf triggers runtime.Goexit() only on the current goroutine.

🤖 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/component/chunker/image_upload_test.go` around lines 288 -
291, Update the ChunkImageUploader test stub to call t.Errorf instead of
t.Fatalf when it is unexpectedly invoked, so violations are recorded even if
uploadChunkImages invokes the callback from another goroutine.

Source: Learnings

internal/handler/agent_dataflow_test.go (1)

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

Consider covering the reject path.

Both tests exercise the happy path; the new len(fileData) == 0 rejection in AgentChatCompletions (agent.go Line 1218) has no test. A third case with files: [] (or a fakeAgentFileService returning an error) would pin that contract cheaply.

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

In `@internal/handler/agent_dataflow_test.go` around lines 57 - 130, The DataFlow
chat completion tests only cover successful file handling and omit the
empty-file rejection path. Add a focused test alongside
TestAgentChatCompletions_DataFlowReturnsChunks that submits files: [] to
AgentChatCompletions, then assert the response has the expected rejection status
and error payload produced when len(fileData) == 0; keep the existing happy-path
tests 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/handler/agent.go`:
- Around line 1045-1054: Update the agent run request contract documentation for
the "files" parameter to describe the accepted nested shape, list[list[object]]
or equivalent [[file-object]], instead of list[object]. Ensure the example or
description makes clear that file objects must be wrapped in an outer list,
matching the Files field contract.

---

Nitpick comments:
In `@internal/handler/agent_dataflow_test.go`:
- Around line 57-130: The DataFlow chat completion tests only cover successful
file handling and omit the empty-file rejection path. Add a focused test
alongside TestAgentChatCompletions_DataFlowReturnsChunks that submits files: []
to AgentChatCompletions, then assert the response has the expected rejection
status and error payload produced when len(fileData) == 0; keep the existing
happy-path tests unchanged.

In `@internal/handler/agent.go`:
- Around line 520-538: Consolidate the duplicated documentation immediately
above runDataflowDebug into one concise comment. Retain only the current
behavior details needed to describe synchronous execution, completed log
flushing before return, replay-oriented message_id semantics, and the debug-only
no-persistence behavior; remove the repeated or stale summary text.
- Around line 629-635: Update the DownloadAgentFile handling in the relevant
agent handler to preserve and propagate its error instead of treating it like
empty data. Keep the existing fallback behavior only for successful downloads
with no file, and ensure callers such as the dataflow debug validation receive
the storage failure.

In `@internal/ingestion/component/chunker/image_upload_test.go`:
- Around line 288-291: Update the ChunkImageUploader test stub to call t.Errorf
instead of t.Fatalf when it is unexpectedly invoked, so violations are recorded
even if uploadChunkImages invokes the callback from another goroutine.

In `@internal/ingestion/component/parser_dispatch.go`:
- Around line 323-328: Update the documentation for the exported
ParserFileFamily function to remove “python-side” wording and describe its role
in the Go runtime’s canonical parser-config family lookup, including its use as
the family key for ParserConfig setups and page overrides.

In `@internal/ingestion/component/tokenizer_nonpersist_test.go`:
- Around line 17-21: Update the comments surrounding the regression test in the
tokenizer test file to describe only the runtime contract: dry-run requests with
an empty kb_id must skip embedding and avoid resolving an embedder. Remove all
references to branch names, branch history, and raw go test or validation
commands.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5d40bb89-6cd5-4aa1-b8b7-bc27020e9904

📥 Commits

Reviewing files that changed from the base of the PR and between b3a9209 and b1a40d8.

📒 Files selected for processing (15)
  • internal/handler/agent.go
  • internal/handler/agent_dataflow_test.go
  • internal/handler/agent_logs_test.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook.go
  • internal/handler/agent_webhook_test.go
  • internal/ingestion/component/chunker/image_upload_test.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/parser_dispatch.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_nonpersist_test.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/ingestion/component/parser.go

Comment thread internal/handler/agent.go Resolved

ghost 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: 6

🧹 Nitpick comments (13)
internal/handler/agent.go (4)

629-635: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Swallowed download error. A failed DownloadAgentFile silently degrades to "no bytes", after which the caller returns the generic "dataflow debug requires an uploaded file" message — the real cause (missing object, storage outage) is invisible. Log the error before falling back.

♻️ Suggested change
 	data, err := h.fileService.DownloadAgentFile(ctx, user.ID, id)
 	if err != nil || len(data) == 0 {
+		if err != nil {
+			common.Warn("dataflow debug: file download failed",
+				zap.String("file_id", id), zap.Error(err))
+		}
 		if name == "" {
 			return "debug", nil
 		}
 		return name, nil
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/agent.go` around lines 629 - 635, Update the
DownloadAgentFile error path in the surrounding handler method to log the
non-nil download error before returning the existing fallback values. Preserve
the current name and empty-data behavior, but ensure storage failures are
recorded with sufficient context for diagnosis.

1055-1059: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

KbID is accepted but only ever logged. The debug path never forwards it (runDataflowDebug takes no kb id), so this field is effectively write-only surface. Per the project's preference for reducing public surface, either drop it or document explicitly that it is ignored.

As per coding guidelines: "remove compatibility-only surfaces unless explicitly requested".

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

In `@internal/handler/agent.go` around lines 1055 - 1059, Remove the unused KbID
field and its compatibility-only explanatory comment from the debug trigger
payload, and update any related parsing or references so the debug path no
longer accepts this write-only input. Keep runDataflowDebug behavior unchanged.

Source: Coding guidelines


113-119: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Interface leaks the concrete return type. WithProgressSink(sink) *task.PipelineExecutor forces fakes to return a meaningless nil (see agent_logs_test.go line 342). Since runDataflowDebug ignores the return value, declaring it as WithProgressSink(sink pipelinepkg.ProgressSink) … isn't possible without changing the concrete method, but the interface can be narrowed to a SetProgressSink-style adapter or the returned type can be dropped by wrapping the executor. Minor ergonomics only.

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

In `@internal/handler/agent.go` around lines 113 - 119, Update the debugExecutor
abstraction used by runDataflowDebug to avoid exposing *task.PipelineExecutor
from WithProgressSink. Since runDataflowDebug ignores the return value,
introduce a sink-setting adapter or wrapper that provides a no-return method and
delegate the concrete executor through it; update affected fakes and call sites
accordingly while preserving progress-sink behavior.

1207-1226: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Extra canvas load on every chat completion. This branch issues LoadCanvasByID for all non-OpenAI chat requests just to read CanvasCategory, adding a DB round-trip to the hot chat path (the normal path loads the canvas again downstream in RunAgent). Consider having the runner surface the category, or reusing the loaded canvas for the agent path as well.

Also note the debug run executes the full ingestion pipeline synchronously on the request goroutine; only the client-cancellable request context bounds it. A server-side deadline would protect the worker pool from a pathological file.

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

In `@internal/handler/agent.go` around lines 1207 - 1226, Eliminate the duplicate
canvas database load in the dataflow branch around LoadCanvasByID by reusing the
canvas already loaded by RunAgent or having the runner expose CanvasCategory for
routing. Add a server-side timeout around runDataflowDebug, while preserving
cancellation from c.Request.Context(), so synchronous ingestion cannot run
indefinitely.
web/src/pages/agent/hooks/use-run-dataflow.ts (1)

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

Hoist the duplicated message_id extraction. Both branches now run the identical get(res, 'data.data.message_id') + setMessageId block.

♻️ Suggested refactor
-      if (res && res?.response.status === 200 && get(res, 'data.code') === 0) {
+      // Even on a run failure the debug log (with the [ERROR] END marker) is
+      // already written, so the polling key is surfaced for both outcomes.
+      const msgId = get(res, 'data.data.message_id');
+      if (msgId) {
+        setMessageId(msgId);
+      }
+
+      if (res && res?.response.status === 200 && get(res, 'data.code') === 0) {
         // fetch canvas
         setUploadedFileData(fileResponseData.file[0]);
-        const msgId = get(res, 'data.data.message_id');
-        if (msgId) {
-          setMessageId(msgId);
-        }
-
         return msgId;
       } else {
-        // Even on a run failure the debug log (with the [ERROR] END marker) is
-        // already written; surface its polling key so the log sheet can render
-        // the failure timeline instead of leaving it stuck on an empty state.
-        const msgId = get(res, 'data.data.message_id');
-        if (msgId) {
-          setMessageId(msgId);
-        }
         message.error(get(res, 'data.message', ''));
       }
🤖 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 `@web/src/pages/agent/hooks/use-run-dataflow.ts` around lines 47 - 53, Hoist
the shared message_id extraction and setMessageId call out of the duplicated
branches in the dataflow response handling, such as immediately after the branch
completes. Keep the existing truthy check and ensure both success and failure
paths still update the polling key.

Source: Coding guidelines

internal/ingestion/task/pipeline_executor_persist_test.go (1)

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

Third string-pointer helper in the same package.

strPtr already exists in internal/ingestion/task/pipeline_executor_test.go and taskStrPtr in internal/ingestion/task/debug_pages_integration_test.go; reuse one instead of adding strptr.

🤖 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/pipeline_executor_persist_test.go` at line 27, Remove
the duplicate strptr helper from the test code and reuse the existing
package-level strPtr or taskStrPtr helper for string pointers, updating call
sites as needed without adding another equivalent helper.
internal/ingestion/component/parser_dispatch.go (1)

323-331: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Normalize the input if this is billed as a "free-form" hint.

pythonFamilyName matches only lower-case, dot-less extensions, so "PDF" or ".pdf" return "" — which in injectDebugPageCap degrades silently to "parse everything". Trim and lower-case here.

♻️ Proposed fix
 func ParserFileFamily(ext string) string {
-	return pythonFamilyName(ext)
+	return pythonFamilyName(strings.ToLower(strings.TrimPrefix(strings.TrimSpace(ext), ".")))
 }
🤖 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/component/parser_dispatch.go` around lines 323 - 331,
Update the exported ParserFileFamily function to trim surrounding whitespace and
convert the extension hint to lowercase before passing it to pythonFamilyName.
Preserve pythonFamilyName as the canonical family resolver while ensuring inputs
such as “PDF” and “.pdf” are normalized consistently; do not change
injectDebugPageCap.
internal/ingestion/task/debug.go (1)

74-81: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider filepath.Ext instead of manual LastIndex.

filepath.Ext(fileName) returns ".pdf" directly and also handles path separators (a name like a.b/file currently yields a bogus suffix from the directory dot).

♻️ Proposed refactor
-	dot := strings.LastIndex(fileName, ".")
-	if dot < 0 || dot == len(fileName)-1 {
-		return "", ""
-	}
-	ext := strings.ToLower(fileName[dot+1:])
-	return "." + ext, ext
+	ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(fileName), "."))
+	if ext == "" {
+		return "", ""
+	}
+	return "." + ext, ext
🤖 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/debug.go` around lines 74 - 81, Update
deriveDocSuffixAndType to use filepath.Ext for extension extraction instead of
strings.LastIndex, preserving lowercase suffix and document type results while
correctly handling path separators and filenames without extensions.
internal/ingestion/task/pipeline_executor.go (2)

457-490: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse the debug variable instead of re-deriving the same condition.

Line 488 repeats s.taskCtx.KB.ID == "", which is exactly debug computed at line 458; fold the cap injection into the existing if debug block so the two gates cannot drift.

♻️ Proposed refactor
-	if s.taskCtx.KB.ID == "" {
+	if debug {
 		injectDebugPageCap(dsl, parserConfig, s.taskCtx.Doc.Type)
 	}
🤖 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/pipeline_executor.go` around lines 457 - 490, Reuse
the existing debug variable in the page-cap injection condition instead of
repeating s.taskCtx.KB.ID == "". Move the injectDebugPageCap call into the
existing if debug block, preserving the current behavior and keeping all
debug-only handling under one gate.

500-511: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Swallowed BuildDebugResultDSL error leaves "View result" silently empty.

When the build fails the sink gets no result DSL, the END marker carries no dsl, and the front-end renders blank tabs with no trace of why. Log it.

🛠️ Proposed fix
 	if rs, ok := s.progressSink.(ResultSink); ok {
-		if resultDSL, e := BuildDebugResultDSL(dsl, output); e == nil {
+		resultDSL, e := BuildDebugResultDSL(dsl, output)
+		if e != nil {
+			common.Warn(fmt.Sprintf("debug run: build result dsl failed: %v", e))
+		} else {
 			rs.SetResult(resultDSL)
 		}
 	}
🤖 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/pipeline_executor.go` around lines 500 - 511, Update
the ResultSink handling around BuildDebugResultDSL so a build error is logged
with its error details instead of being silently ignored. Preserve setting the
result DSL on successful builds and leave non-ResultSink behavior unchanged.
internal/ingestion/task/debug_log_sink_test.go (1)

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

Timing tolerance is tight enough to flake on loaded CI.

The gap is 20 ms and the tolerance is max(gapSeconds*0.5, 0.01) = 10 ms; a scheduling hiccup between t1 := time.Now() and the second OnComponentProgress pushes the recorded elapsed past the bound. Since the contract under test is the unit scale (seconds vs microseconds), an order-of-magnitude assertion is both sufficient and stable.

💚 Proposed fix
-	if math.Abs(elapsed-gapSeconds) > math.Max(gapSeconds*0.5, 0.01) {
-		t.Fatalf("elapsed_time=%v want ~%v seconds (sink must divide the UnixMicro delta by 1e6)", elapsed, gapSeconds)
+	// Scale check only: a microsecond delta would be ~1e6x larger.
+	if elapsed < gapSeconds*0.5 || elapsed > gapSeconds*100 {
+		t.Fatalf("elapsed_time=%v want same seconds scale as %v (sink must divide the UnixMicro delta by 1e6)", elapsed, gapSeconds)
 	}
🤖 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/debug_log_sink_test.go` around lines 569 - 611, Relax
the elapsed-time assertion in TestDebugLogSink_ElapsedTimeIsInSeconds to verify
the recorded value is in seconds by using an order-of-magnitude comparison
rather than the tight gap-based tolerance. Keep the existing elapsed_time
extraction and failure diagnostics, while ensuring the test still rejects
microsecond-scale values.
internal/ingestion/component/chunker/image_upload_test.go (1)

287-292: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer t.Errorf inside the uploader stub.

If uploadChunkImages ever fans out per-chunk uploads to goroutines, t.Fatalf here only calls runtime.Goexit() on that goroutine and may not fail the test reliably. t.Errorf + return is safe from any goroutine. Based on learnings: use t.Errorf instead of t.Fatalf inside handler/worker goroutines in Go tests.

♻️ Proposed change
 	ChunkImageUploader = func(_ context.Context, _, _ string, _ []byte) (string, error) {
-		t.Fatalf("ChunkImageUploader must not be called in a debug run")
+		t.Errorf("ChunkImageUploader must not be called in a debug run")
 		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/component/chunker/image_upload_test.go` around lines 287 -
292, Replace t.Fatalf with t.Errorf in the ChunkImageUploader stub used by the
debug-run test, preserving the existing return values and cleanup behavior.
Ensure the stub reliably records a failure even if uploadChunkImages invokes it
from a worker goroutine.

Source: Learnings

internal/ingestion/component/tokenizer.go (1)

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

Shadowed chunks makes the post-embedding validation implicit.

chunks, tokenCount, err := c.embedChunks(...) declares a new chunks scoped to the if block, so line 376's validateTokenizerOutputs(chunks, ...) and the log at line 382 still refer to the outer slice. This only works because embedChunks mutates the chunk elements in place; a future change that returns a rebuilt slice would silently break embedding validation. Assigning to the outer variable makes the dependency explicit.

♻️ Proposed clarification
 	if shouldHaveEmbedding(c.param.SearchMethod, kbID) {
-		chunks, tokenCount, err := c.embedChunks(ctx, tenantID, kbID, embeddingModel, name, chunks)
+		embedded, tokenCount, err := c.embedChunks(ctx, tenantID, kbID, embeddingModel, name, chunks)
 		if err != nil {
 			return nil, err
 		}
+		chunks = embedded
 		out["embedding_token_consumption"] = tokenCount
 		out["chunks"] = schema.ChunkDocsToMaps(chunks)
 	}
🤖 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/component/tokenizer.go` around lines 368 - 376, Update the
embedding branch around c.embedChunks so its returned chunks slice is assigned
to the existing outer chunks variable rather than redeclared within the if
block. Preserve tokenCount and err handling, ensuring validateTokenizerOutputs
and subsequent logging use the returned embedded slice explicitly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/agent.go`:
- Around line 520-538: Merge the two consecutive documentation blocks for
runDataflowDebug into a single comment, retaining only the current behavior and
contract details from the latter description while removing the duplicated and
stale explanation.
- Around line 1567-1571: Update the Redis retrieval flow around h.redisGet and
parseAgentLogs to log any non-nil rerr before returning or continuing with the
empty response path. Preserve the existing handling for a missing key mapped to
nil, but ensure genuine Redis failures are surfaced through the handler’s
established logging mechanism so polling does not fail silently.
- Around line 138-143: Replace the `redisStore: redis.Get()` default in the
`newExecutor` setup with a fail-safe no-op or configured non-nil wrapper
implementing `Set(key, value, ttl) bool`. Ensure `DebugLogSink.Flush` can safely
use the resulting `TaskDebugLogStore` when Redis is disabled or uninitialized,
without invoking methods on a nil `*redis.Client`.

In `@internal/ingestion/component/tokenizer_nonpersist_test.go`:
- Around line 17-21: Remove the branch-topology sentence from the comment above
the tokenizer regression test, retaining only the current runtime contract
describing that canvas-debug runs have no KB and skip embedder resolution.

In `@internal/ingestion/task/debug_result_dsl.go`:
- Around line 46-54: Update vectorKeys and the payload-stripping logic in the
debug-result flow to recognize dimension-scoped embedding keys matching the
tokenizer’s q_ prefix and _vec suffix pattern, rather than relying on the
ineffective literal q_vec entry. Reuse the same pattern semantics as
hasEmbeddingVector in the tokenizer so keys such as q_4_vec and q_1024_vec are
removed while preserving handling for the other vector keys.

In `@internal/ingestion/task/pipeline_executor.go`:
- Around line 208-223: Update the comment above
PipelineExecutor.collectDebugOutput to remove the claim that debug runs compute
and retain embedding vectors, and describe only the chunks surfaced without
DB/index writes. Clean up collectDebugOutput by removing the unused ctx
parameter and changing its return type to *PipelineResult, then update all
callers to use the simplified signature and return value while preserving the
existing result fields.

---

Nitpick comments:
In `@internal/handler/agent.go`:
- Around line 629-635: Update the DownloadAgentFile error path in the
surrounding handler method to log the non-nil download error before returning
the existing fallback values. Preserve the current name and empty-data behavior,
but ensure storage failures are recorded with sufficient context for diagnosis.
- Around line 1055-1059: Remove the unused KbID field and its compatibility-only
explanatory comment from the debug trigger payload, and update any related
parsing or references so the debug path no longer accepts this write-only input.
Keep runDataflowDebug behavior unchanged.
- Around line 113-119: Update the debugExecutor abstraction used by
runDataflowDebug to avoid exposing *task.PipelineExecutor from WithProgressSink.
Since runDataflowDebug ignores the return value, introduce a sink-setting
adapter or wrapper that provides a no-return method and delegate the concrete
executor through it; update affected fakes and call sites accordingly while
preserving progress-sink behavior.
- Around line 1207-1226: Eliminate the duplicate canvas database load in the
dataflow branch around LoadCanvasByID by reusing the canvas already loaded by
RunAgent or having the runner expose CanvasCategory for routing. Add a
server-side timeout around runDataflowDebug, while preserving cancellation from
c.Request.Context(), so synchronous ingestion cannot run indefinitely.

In `@internal/ingestion/component/chunker/image_upload_test.go`:
- Around line 287-292: Replace t.Fatalf with t.Errorf in the ChunkImageUploader
stub used by the debug-run test, preserving the existing return values and
cleanup behavior. Ensure the stub reliably records a failure even if
uploadChunkImages invokes it from a worker goroutine.

In `@internal/ingestion/component/parser_dispatch.go`:
- Around line 323-331: Update the exported ParserFileFamily function to trim
surrounding whitespace and convert the extension hint to lowercase before
passing it to pythonFamilyName. Preserve pythonFamilyName as the canonical
family resolver while ensuring inputs such as “PDF” and “.pdf” are normalized
consistently; do not change injectDebugPageCap.

In `@internal/ingestion/component/tokenizer.go`:
- Around line 368-376: Update the embedding branch around c.embedChunks so its
returned chunks slice is assigned to the existing outer chunks variable rather
than redeclared within the if block. Preserve tokenCount and err handling,
ensuring validateTokenizerOutputs and subsequent logging use the returned
embedded slice explicitly.

In `@internal/ingestion/task/debug_log_sink_test.go`:
- Around line 569-611: Relax the elapsed-time assertion in
TestDebugLogSink_ElapsedTimeIsInSeconds to verify the recorded value is in
seconds by using an order-of-magnitude comparison rather than the tight
gap-based tolerance. Keep the existing elapsed_time extraction and failure
diagnostics, while ensuring the test still rejects microsecond-scale values.

In `@internal/ingestion/task/debug.go`:
- Around line 74-81: Update deriveDocSuffixAndType to use filepath.Ext for
extension extraction instead of strings.LastIndex, preserving lowercase suffix
and document type results while correctly handling path separators and filenames
without extensions.

In `@internal/ingestion/task/pipeline_executor_persist_test.go`:
- Line 27: Remove the duplicate strptr helper from the test code and reuse the
existing package-level strPtr or taskStrPtr helper for string pointers, updating
call sites as needed without adding another equivalent helper.

In `@internal/ingestion/task/pipeline_executor.go`:
- Around line 457-490: Reuse the existing debug variable in the page-cap
injection condition instead of repeating s.taskCtx.KB.ID == "". Move the
injectDebugPageCap call into the existing if debug block, preserving the current
behavior and keeping all debug-only handling under one gate.
- Around line 500-511: Update the ResultSink handling around BuildDebugResultDSL
so a build error is logged with its error details instead of being silently
ignored. Preserve setting the result DSL on successful builds and leave
non-ResultSink behavior unchanged.

In `@web/src/pages/agent/hooks/use-run-dataflow.ts`:
- Around line 47-53: Hoist the shared message_id extraction and setMessageId
call out of the duplicated branches in the dataflow response handling, such as
immediately after the branch completes. Keep the existing truthy check and
ensure both success and failure paths still update the polling key.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8e84e4c1-2425-488a-bb0a-775f58400807

📥 Commits

Reviewing files that changed from the base of the PR and between b1a40d8 and 2540d6c.

📒 Files selected for processing (29)
  • internal/handler/agent.go
  • internal/handler/agent_dataflow_test.go
  • internal/handler/agent_logs_test.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook.go
  • internal/handler/agent_webhook_test.go
  • internal/ingestion/component/chunker/image_upload_test.go
  • internal/ingestion/component/chunker/pdfcrop_nocgo.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/parser_dispatch.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_nonpersist_test.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/task/constants.go
  • internal/ingestion/task/debug.go
  • internal/ingestion/task/debug_log_sink.go
  • internal/ingestion/task/debug_log_sink_test.go
  • internal/ingestion/task/debug_pages_integration_test.go
  • internal/ingestion/task/debug_result_dsl.go
  • internal/ingestion/task/debug_result_dsl_test.go
  • internal/ingestion/task/debug_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_executor_persist_test.go
  • internal/ingestion/task/pipeline_executor_test.go
  • web/src/pages/agent/hooks/use-run-dataflow.ts
💤 Files with no reviewable changes (1)
  • internal/ingestion/task/constants.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/handler/agent_webhook.go
  • internal/ingestion/component/parser.go

Comment thread internal/handler/agent.go
Comment on lines +138 to 143
redisGet: func(key string) (string, error) { return redis.Get().Get(key) },
redisStore: redis.Get(),
newExecutor: func(taskCtx *task.TaskContext, canvasID string, docBulkSize int) (debugExecutor, error) {
return task.NewPipelineExecutor(taskCtx, canvasID, docBulkSize)
},
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'redis.go' internal/engine/redis --exec cat -n {}
rg -nP -C3 'NewAgentHandler\(' --type=go -g '!**/*_test.go'
rg -nP -C3 'redis\.Init|globalClient\s*=' --type=go

Repository: infiniflow/ragflow

Length of output: 33497


🏁 Script executed:

#!/bin/bash
set -u

printf '--- locate agent.go ---\n'
fd -t f 'agent\.go$' internal || true

printf '\n--- relevant agent.go sections ---\n'
F="$(fd -t f 'agent\.go$' internal | head -n 1)"
if [ -n "${F:-}" ]; then
  wc -l "$F"
  sed -n '1,260p' "$F" | cat -n
fi

printf '\n--- call graph for NewAgentHandler and init ordering ---\n'
rg -n -C4 'NewAgentHandler\(|redis\.Init\(|Get\(\)\.Set\(|DebugLogSink\.Flush|DebugLogStore' --type=go -g '!**/*_test.go'

printf '\n--- redis.go nil receiver semantic probe ---\n'
python3 - <<'PY'
src=open('internal/engine/redis/redis.go').read()
for name in ['Health','Info','Set','Get']:
    idx=src.find(f'func (r *Client) {name}')
    if idx!=-1:
        end=src.find('\n}', idx)
        print(f"\n{name}:")
        lines=src[idx:end+2].splitlines(keepends=True)[:5]
        for line in lines:
            print(line.rstrip())
PY

Repository: infiniflow/ragflow

Length of output: 11377


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- relevant internal/handler/agent.go sections ---'
sed -n '1,220p' internal/handler/agent.go | cat -n

printf '%s\n' '--- NewAgentHandler calls and Redis initialization uses ---'
rg -n -C5 'NewAgentHandler\(|redis\.Init\(|Get\(\)\.Set\(.*Debug|DebugLogSink\.Flush|DebugLogStore|DebugLog' internal --type=go -g '!**/*_test.go'

printf '%s\n' '--- redis wrapper nil-receiver snippets ---'
rg -n -C3 '^\s*func \(r \*Client\) (Health|Info|Set|Get)\(|if r == nil \|\| r\.client == nil|if r\.client == nil' internal/engine/redis/redis.go

Repository: infiniflow/ragflow

Length of output: 30816


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- Go nil-embedded-interface semantic probe ---'
tmpdir="$(mktemp -d)"
cat > "$tmpdir/probe.go" <<'EOF'
package main

import "fmt"

type Store interface { Set(key, value string) bool }

type nilReceiver struct{ store string }
func (n *nilReceiver) Set(key, value string) bool {
    if n.store == "" {
        return false
    }
    fmt.Println("writing", key, value)
    return true
}

func main() {
    var s **nilReceiver
    store := Store(s)
    fmt.Printf("interface value type nil=%t\n", store == nil)
    fmt.Printf("interface is nil=%v\n", store == (Store)(nil))
    result := store.Set("k", "v")
    fmt.Println("Set result:", result)
}
EOF
go run "$tmpdir/probe.go"
rm -rf "$tmpdir"

printf '%s\n' '--- Redis global/initialization call sites ---'
rg -n -C3 '\brobot\.(Init|Get|Close|Health|Init|Close)\(|redis\.(Init|Get|Close|Health|Init|Close)\(' --type=go

Repository: infiniflow/ragflow

Length of output: 438


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- Go nil-pointer embedded-interface semantic probe ---'
tmpdir="$(mktemp -d)"
cat > "$tmpdir/probe.go" <<'EOF'
package main

import "fmt"

type Store interface { Set(key, value string) bool }

type nilReceiver struct{ store string }
func (n *nilReceiver) Set(key, value string) bool {
    if n.store == "" {
        return false
    }
    fmt.Println("writing", key, value)
    return true
}

func panicOnNilStore(s Store) {
    defer func() { fmt.Println("DETECTED PANIC:", recover()) }()
    _ = s.Set("k", "v")
    fmt.Println("no panic")
}

func panicOnNilFunc(f func() int) {
    defer func() { fmt.Println("DETECTED PANIC:", recover()) }()
    _ = f()
    fmt.Println("no panic")
}

func main() {
    var ptr *nilReceiver
    store := Store(ptr)
    fmt.Printf("interface value type nil=%t\n", store == nil)
    fmt.Printf("interface nil equality=%v\n", store == (Store)(nil))
    panicOnNilStore(store)

    var fn func() int
    panicOnNilFunc(fn)
}
EOF
go run "$tmpdir/probe.go"
rm -rf "$tmpdir"

printf '%s\n' '--- Redis global/initialization call sites ---'
rg -n -C3 '\brobot\.(Init|Get|Close|Health)\(|redis\.(Init|Get|Close|Health)\(' --type=go

Repository: infiniflow/ragflow

Length of output: 482


Don’t use redis.Get() as the default debug Redis store. If Redis is disabled or not initialized, redis.Get() returns nil, and assigning it to TaskDebugLogStore creates a non-nil interface with a nil *redis.Client receiver; DebugLogSink.Flush then calls (*redis.Client).Set on that nil receiver and panics. Use a fail-safe/no-op store that preserves Set(key, value, ttl) bool, or pass in a configured non-nil wrapper.

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

In `@internal/handler/agent.go` around lines 138 - 143, Replace the `redisStore:
redis.Get()` default in the `newExecutor` setup with a fail-safe no-op or
configured non-nil wrapper implementing `Set(key, value, ttl) bool`. Ensure
`DebugLogSink.Flush` can safely use the resulting `TaskDebugLogStore` when Redis
is disabled or uninitialized, without invoking methods on a nil `*redis.Client`.

Comment thread internal/handler/agent.go Resolved
Comment thread internal/handler/agent.go
Comment on lines +1567 to 1571
payload, rerr := h.redisGet(key)
var data interface{} = map[string]interface{}{}
if rerr == nil {
data = parseAgentLogs(payload)
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Redis failures are indistinguishable from a missing key. h.redisGet already maps redis.Nil to ("", nil), so a non-nil rerr is a genuine infrastructure error yet it silently becomes code == 0, data == {} and the frontend keeps polling forever. At minimum log it.

🛠️ Suggested change
 	payload, rerr := h.redisGet(key)
 	var data interface{} = map[string]interface{}{}
 	if rerr == nil {
 		data = parseAgentLogs(payload)
+	} else {
+		common.Warn("agent logs: redis read failed",
+			zap.String("key", key), zap.Error(rerr))
 	}
📝 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
payload, rerr := h.redisGet(key)
var data interface{} = map[string]interface{}{}
if rerr == nil {
data = parseAgentLogs(payload)
}
payload, rerr := h.redisGet(key)
var data interface{} = map[string]interface{}{}
if rerr == nil {
data = parseAgentLogs(payload)
} else {
common.Warn("agent logs: redis read failed",
zap.String("key", key), zap.Error(rerr))
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/agent.go` around lines 1567 - 1571, Update the Redis
retrieval flow around h.redisGet and parseAgentLogs to log any non-nil rerr
before returning or continuing with the empty response path. Preserve the
existing handling for a missing key mapped to nil, but ensure genuine Redis
failures are surfaced through the handler’s established logging mechanism so
polling does not fail silently.

Comment on lines +17 to +21
// Regression guard for the canvas-debug (dry-run) run contract: a debug run
// carries no KB (kb_id == ""), so the tokenizer must skip embedding rather than
// resolving an embedder. It lives in the canvas-debug branch (not the
// ingestion-fixes branch) so the ingestion-fixes branch stays compilable on its
// own.

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Drop the branch-topology note from the file comment.

The "lives in the canvas-debug branch (not the ingestion-fixes branch)" sentence documents migration/branch history rather than the current runtime path and will go stale after merge.

♻️ Proposed change
 // Regression guard for the canvas-debug (dry-run) run contract: a debug run
 // carries no KB (kb_id == ""), so the tokenizer must skip embedding rather than
-// resolving an embedder. It lives in the canvas-debug branch (not the
-// ingestion-fixes branch) so the ingestion-fixes branch stays compilable on its
-// own.
+// resolving an embedder.

As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history".

📝 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
// Regression guard for the canvas-debug (dry-run) run contract: a debug run
// carries no KB (kb_id == ""), so the tokenizer must skip embedding rather than
// resolving an embedder. It lives in the canvas-debug branch (not the
// ingestion-fixes branch) so the ingestion-fixes branch stays compilable on its
// own.
// Regression guard for the canvas-debug (dry-run) run contract: a debug run
// carries no KB (kb_id == ""), so the tokenizer must skip embedding rather than
// resolving an embedder.
🤖 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/component/tokenizer_nonpersist_test.go` around lines 17 -
21, Remove the branch-topology sentence from the comment above the tokenizer
regression test, retaining only the current runtime contract describing that
canvas-debug runs have no KB and skip embedder resolution.

Source: Coding guidelines

Comment on lines +208 to +223
// collectDebugOutput builds a PipelineResult for a debug (dry-run) run.
// It surfaces the pipeline's chunks so a debug endpoint can render them, but
// performs no DB/index writes — the embedding vectors already computed by the
// pipeline run are left on the chunks. This keeps debug runs side-effect free.
func (s *PipelineExecutor) collectDebugOutput(ctx context.Context, pipelineOutput map[string]any, start time.Time) (*PipelineResult, error) {
chunks := NormalizeChunks(pipelineOutput)
return &PipelineResult{
DocID: s.taskCtx.Doc.ID,
KbID: s.taskCtx.Doc.KbID,
Chunks: chunks,
ChunkCount: countDistinctChunkIDs(chunks),
TokenConsumption: GetEmbeddingTokenConsumption(pipelineOutput),
Duration: time.Since(start).Seconds(),
}, nil
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Stale comment: debug runs never compute vectors.

The tokenizer skips embedding entirely when kb_id == "" (see internal/ingestion/component/tokenizer_nonpersist_test.go), so "the embedding vectors already computed by the pipeline run are left on the chunks" is inaccurate and misleading for anyone reasoning about the size of the debug HTTP payload. Also, ctx is unused here and the error return is always nil.

♻️ Proposed cleanup
-// collectDebugOutput builds a PipelineResult for a debug (dry-run) run.
-// It surfaces the pipeline's chunks so a debug endpoint can render them, but
-// performs no DB/index writes — the embedding vectors already computed by the
-// pipeline run are left on the chunks. This keeps debug runs side-effect free.
-func (s *PipelineExecutor) collectDebugOutput(ctx context.Context, pipelineOutput map[string]any, start time.Time) (*PipelineResult, error) {
+// collectDebugOutput builds a PipelineResult for a debug (dry-run) run.
+// It surfaces the pipeline's chunks so a debug endpoint can render them and
+// performs no DB/index writes, keeping debug runs side-effect free.
+func (s *PipelineExecutor) collectDebugOutput(pipelineOutput map[string]any, start time.Time) *PipelineResult {
 	chunks := NormalizeChunks(pipelineOutput)
-	return &PipelineResult{
+	return &PipelineResult{
 		DocID:            s.taskCtx.Doc.ID,
 		KbID:             s.taskCtx.Doc.KbID,
 		Chunks:           chunks,
 		ChunkCount:       countDistinctChunkIDs(chunks),
 		TokenConsumption: GetEmbeddingTokenConsumption(pipelineOutput),
 		Duration:         time.Since(start).Seconds(),
-	}, nil
+	}
 }
📝 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
// collectDebugOutput builds a PipelineResult for a debug (dry-run) run.
// It surfaces the pipeline's chunks so a debug endpoint can render them, but
// performs no DB/index writes — the embedding vectors already computed by the
// pipeline run are left on the chunks. This keeps debug runs side-effect free.
func (s *PipelineExecutor) collectDebugOutput(ctx context.Context, pipelineOutput map[string]any, start time.Time) (*PipelineResult, error) {
chunks := NormalizeChunks(pipelineOutput)
return &PipelineResult{
DocID: s.taskCtx.Doc.ID,
KbID: s.taskCtx.Doc.KbID,
Chunks: chunks,
ChunkCount: countDistinctChunkIDs(chunks),
TokenConsumption: GetEmbeddingTokenConsumption(pipelineOutput),
Duration: time.Since(start).Seconds(),
}, nil
}
// collectDebugOutput builds a PipelineResult for a debug (dry-run) run.
// It surfaces the pipeline's chunks so a debug endpoint can render them and
// performs no DB/index writes, keeping debug runs side-effect free.
func (s *PipelineExecutor) collectDebugOutput(pipelineOutput map[string]any, start time.Time) *PipelineResult {
chunks := NormalizeChunks(pipelineOutput)
return &PipelineResult{
DocID: s.taskCtx.Doc.ID,
KbID: s.taskCtx.Doc.KbID,
Chunks: chunks,
ChunkCount: countDistinctChunkIDs(chunks),
TokenConsumption: GetEmbeddingTokenConsumption(pipelineOutput),
Duration: time.Since(start).Seconds(),
}
}
🤖 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/pipeline_executor.go` around lines 208 - 223, Update
the comment above PipelineExecutor.collectDebugOutput to remove the claim that
debug runs compute and retain embedding vectors, and describe only the chunks
surfaced without DB/index writes. Clean up collectDebugOutput by removing the
unused ctx parameter and changing its return type to *PipelineResult, then
update all callers to use the simplified signature and return value while
preserving the existing result fields.

@xugangqiang

ghost commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@yingfeng @yuzhichang @JinHai-CN Please help to review

Comment thread internal/handler/agent.go Outdated
// forwarded: debug never resolves an embedder or writes to a KB, and
// parse/chunk work without it. Callers extract the (fileName, fileData) pair
// from their own request shape and pass them in.
func (h *AgentHandler) runDataflowDebug(ctx context.Context, user *entity.User,

ghost Jul 30, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Remove the dataflow concept.

ghost Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 925218e — the Go side no longer introduces a dataflow concept of its own:

  • runDataflowDebug → runCanvasPipelineDebug, so the handler stays with the existing ingestion-side "pipeline" vocabulary (internal/ingestion/pipeline, PipelineExecutor). All doc comments referencing it were updated.
  • agent_dataflow_test.go → agent_pipeline_debug_test.go, TestRunDataflowDebug_* → TestRunCanvasPipelineDebug_*.
  • Dropped the dead kb_id plumbing on the debug entry (request field + query fallback + leftover debug log). It was never consumed: the debug context is KB-less by construction (NewDebugTaskContext forces KB.ID == ""), so that concept is gone from the entry point too.

What I deliberately kept, please tell me if you want these changed as well:

  • the "dataflow_canvas" category literal — it is the DB/API contract shared with Python (CanvasCategory.DataFlow);
  • the webhook rejection message "Dataflow can not be triggered by webhook." — verbatim parity with agent_api.py;
  • the front-end use-run-dataflow.ts hook name, which predates this PR.

./build.sh --test ./internal/handler/... ./internal/ingestion/task/... passes.

xugangqiang and others added 7 commits July 31, 2026 11:27
Introduce a side-effect-free DataFlow canvas debug (dry-run) mode so a canvas can be executed synchronously and its parsed chunks returned inline, without persisting anything.

- task/debug.go: NewDebugTaskContext builds an in-memory TaskContext flagged with CANVAS_DEBUG_DOC_ID, which disables the executor's persist gate (no MinIO upload, index insert, or pipeline_log).
- task/pipeline_executor.go: thread a persist flag; non-persist runs return collectDebugOutput (chunks + token consumption) instead of a no-op; deliver uploaded bytes as inputs['binary'] for doc-less runs; injectDebugPageCap caps the parser to the first pages for a fast preview via the production override_params channel (Parser cpnID + family).
- globals/globals.go: WithPersist/IsPersist context flag so components gate writes without knowing the debug vocabulary.
- chunker/register.go: only upload chunk images when persisting; otherwise drop raw bytes.
- component/file.go: pass through in-memory binary bytes, skipping doc_id -> storage resolution.
- handler/agent.go + agent_webhook.go: detect dataflow_canvas and run a sync debug returning chunks inline on the existing chat/completions endpoint; reject dataflow canvases from webhooks (mirrors Python agent_api.py).
- parser_dispatch.go: export ParserFileFamily for the executor's page-cap injection.
…canvas-debug

The TestTokenizerComponent_EmbeddingRunsWhenNonPersist regression gate depends on
component/globals.WithPersist, which is defined by the debug feature. Keep it in
the canvas-debug branch so the ingestion-fixes branch compiles standalone.
…plumbing

Address review feedback on the canvas-debug PR:

- Rename runDataflowDebug -> runCanvasPipelineDebug so the handler stays
  with the ingestion-side "pipeline" vocabulary instead of introducing a
  parallel "dataflow" concept; update all doc comments referencing it.
- Rename agent_dataflow_test.go -> agent_pipeline_debug_test.go and
  TestRunDataflowDebug_* -> TestRunCanvasPipelineDebug_* accordingly.
- Drop the dead kb_id plumbing from the debug entry: the KbID request
  field, the query-param fallback, and the leftover debug log were never
  consumed - the debug context always runs KB-less by construction
  (NewDebugTaskContext forces KB.ID == ""). Remove the now-pointless
  "explicit kb_id is accepted" test with it.
…sDebug

Replace three scattered `taskCtx.KB.ID == ""` checks in pipeline_executor.go
with a single IsDebug() method on TaskContext, the canonical debug signal
used across the ingestion pipeline. This removes duplicated inline comments
and centralizes the dry-run detection so every caller reads the same source
of truth.

Co-authored-by: CodeBuddy Code <[email protected]>
@xugangqiang xugangqiang changed the title Feat(ingestion): add DataFlow canvas debug (dry-run) mode with View result log Feat(ingestion): add canvas pipeline debug (dry-run) mode with View result log Jul 31, 2026
@xugangqiang

ghost commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Design-review tracking for internal/ingestion/task/pipeline_executor.go is captured in issue #17607 (assigned to xugangqiang). Full CTO / senior-backend review of the god-object concerns and proposed refactors: #17607

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.

2 participants