Repository navigation
Feat(ingestion): add canvas pipeline debug (dry-run) mode with View result log - #17538
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDataFlow 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. ChangesDataFlow debug execution and logging
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (8)
internal/ingestion/task/debug_pages_integration_test.go (1)
100-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueParser discovery here keeps the last match, while
injectDebugPageCapuses the first.The production loop
breaks on the firstParsercomponent; 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 abreakaligns 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 valueReuse the
debugvariable instead of re-testingDoc.ID.Line 446 repeats the
s.taskCtx.Doc.ID == CANVAS_DEBUG_DOC_IDcomparison already captured indebugat 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 winOnly the first
Parsercomponent gets the debug page cap.The loop
breaks on the first match, so a DSL containing more than oneParsernode 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.Suffixgets a leading dot here, unlike the rest of the codebase.
deriveDocSuffixAndTypereturns".pdf"for the suffix, while otherentity.Documentconstruction paths (e.g.internal/ingestion/task/pipeline_executor_persist_test.goline 40) use the bare"pdf". It is harmless today becauseSuffixis only read byrecordPipelineLog, which the debug path skips, but the divergence will bite if any component starts branching onDoc.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 valueConsider a typed
inputs map[string]anyparameter instead ofother ...any.The variadic
anymakes the contract untypeable at call sites (a caller passingmap[string]stringor a struct silently degrades to the default). Every observed caller (chunker/register.goline 86) passes the componentinputsmap, soIsPersist(ctx context.Context, inputs map[string]any) boolwould express the same behavior with compile-time checking.Separately, note the value-type asymmetry:
WithPersiststores abool, while the Globals and inputs fallbacks only accept the string"true"/"false". Apersistglobal published as a bool falls through to thetruedefault.🤖 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 winNormalize the hint in the exported wrapper.
pythonFamilyNamematches only lowercase, dot-less extensions, soParserFileFamily(".PDF")returns"". That silently turnsinjectDebugPageCapinto a no-op (uncapped debug parse) for any caller that passes the suffix form or mixed case.internal/ingestion/task/debug.gohappens to store a lowercase dot-lessDoc.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
stringsin 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 valueAssert against
CANVAS_DEBUG_DOC_IDrather 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 valueKeep changed Go comments focused on current behavior.
Remove Python-port/migration narrative and correct the stale claim that
debugRunnersupports webhook debug execution; webhooks reject DataFlow canvases.
internal/handler/agent.go#L95-L99: describedebugRunneras 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
📒 Files selected for processing (16)
internal/handler/agent.gointernal/handler/agent_dataflow_test.gointernal/handler/agent_test.gointernal/handler/agent_webhook.gointernal/handler/agent_webhook_test.gointernal/ingestion/component/chunker/image_upload_test.gointernal/ingestion/component/chunker/register.gointernal/ingestion/component/file.gointernal/ingestion/component/globals/globals.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/task/debug.gointernal/ingestion/task/debug_pages_integration_test.gointernal/ingestion/task/debug_test.gointernal/ingestion/task/pipeline_executor.gointernal/ingestion/task/pipeline_executor_persist_test.go
| // 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") |
There was a problem hiding this comment.
🎯 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 fromresult.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.
| // 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 | ||
| } |
There was a problem hiding this comment.
🗄️ 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.
left a comment
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/ingestion/component/tokenizer_nonpersist_test.go (1)
17-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep 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 rawgo 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
📒 Files selected for processing (1)
internal/ingestion/component/tokenizer_nonpersist_test.go
left a comment
There was a problem hiding this comment.
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 winGetAgentLogs silently returns success on genuine Redis failures.
redis.Client.Getalready converts a missing key (redis.Nil) into("", nil), so a non-nilrerrhere means a real backend/connectivity failure — yet the handler ignoresrerrentirely and returnscode=0with 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 winFix the
!cgoPDF crop fallback typecheck.
pdfcrop_nocgo.gois selected only whencgois disabled, butnewPDFEngineFromUpstreamstill uses*gorm.DBwithout importinggorm.io/gorm, so any typecheck/configuration that includes this file reportsundefined: gormand preventsgo 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 winDrop 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 filenametokenizer_nonpersist_test.goalso no longer matches what it tests, sincepersistgating is gone — a rename to something liketokenizer_debug_test.gowould 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 winShadowed
chunksmakes the validation call depend on in-place mutation.
chunks, tokenCount, err := c.embedChunks(...)declares a newchunksscoped to theifblock, so line 376 validates the outer slice. It works today only becauseembedChunksmutates elements through the shared backing array; if it ever reallocates (e.g. filtering/appending), validation andout["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_vecnever matches the real vector key formatq_<dim>_vec.Embedding vectors are written as
q_%d_vec(e.g.q_1024_vec, seeinternal/ingestion/component/tokenizer.goSetExtraValue), so the literalq_vecentry invectorKeysnever 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 valueComment is inaccurate.
runDataflowDebugalways callssink.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 valueCopy of an existing helper. The doc comment admits it duplicates
internal/service/agent_sessions.go'struncateRunes; consider promoting one copy to a shared internal util instead of keeping two. Also,maxshadows 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 winShare the key format with the reader.
GetAgentLogsbuilds the same key independently (internal/handler/agent.go:1566,fmt.Sprintf("%s-%s-logs", ...)). Export aDebugLogKey(canvasID, messageID string) stringhere 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
📒 Files selected for processing (22)
internal/handler/agent.gointernal/handler/agent_dataflow_test.gointernal/handler/agent_logs_test.gointernal/ingestion/component/chunker/image_upload_test.gointernal/ingestion/component/chunker/register.gointernal/ingestion/component/tokenizer.gointernal/ingestion/component/tokenizer_nonpersist_test.gointernal/ingestion/component/tokenizer_test.gointernal/ingestion/component/tokenizer_unit_test.gointernal/ingestion/pipeline/template_integration_test.gointernal/ingestion/task/constants.gointernal/ingestion/task/debug.gointernal/ingestion/task/debug_log_sink.gointernal/ingestion/task/debug_log_sink_test.gointernal/ingestion/task/debug_pages_integration_test.gointernal/ingestion/task/debug_result_dsl.gointernal/ingestion/task/debug_result_dsl_test.gointernal/ingestion/task/debug_test.gointernal/ingestion/task/pipeline_executor.gointernal/ingestion/task/pipeline_executor_persist_test.gointernal/ingestion/task/pipeline_executor_test.goweb/src/pages/agent/hooks/use-run-dataflow.ts
💤 Files with no reviewable changes (1)
- internal/ingestion/task/constants.go
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "math" | ||
| "strings" | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| "gorm.io/gorm" | ||
| "ragflow/internal/agent/runtime" | ||
| "ragflow/internal/ingestion/pipeline" | ||
| ) |
There was a problem hiding this comment.
🩺 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))}')
PYRepository: 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}')
PYRepository: 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))}')
PYRepository: 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")
PYRepository: 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
| // 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) | ||
| } |
There was a problem hiding this comment.
🩺 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.
| // 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.
b3a9209 to
b1a40d8
Compare
left a comment
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
internal/ingestion/component/parser_dispatch.go (1)
323-328: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDescribe 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 winRemove branch-history and raw-
go testcommentary.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 valueCollapse 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 winDownload failure is indistinguishable from "no file".
When
DownloadAgentFileerrors, 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 winUse
t.Errorfin the uploader stub.If
uploadChunkImagesever fans out per chunk,t.Fatalfonlyruntime.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.Errorfinstead oft.Fatalf, sincet.Fatalftriggersruntime.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 winConsider covering the reject path.
Both tests exercise the happy path; the new
len(fileData) == 0rejection inAgentChatCompletions(agent.go Line 1218) has no test. A third case withfiles: [](or afakeAgentFileServicereturning 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
📒 Files selected for processing (15)
internal/handler/agent.gointernal/handler/agent_dataflow_test.gointernal/handler/agent_logs_test.gointernal/handler/agent_test.gointernal/handler/agent_webhook.gointernal/handler/agent_webhook_test.gointernal/ingestion/component/chunker/image_upload_test.gointernal/ingestion/component/chunker/register.gointernal/ingestion/component/file.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/tokenizer.gointernal/ingestion/component/tokenizer_nonpersist_test.gointernal/ingestion/component/tokenizer_test.gointernal/ingestion/component/tokenizer_unit_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/parser.go
b1a40d8 to
2540d6c
Compare
left a comment
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (13)
internal/handler/agent.go (4)
629-635: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSwallowed download error. A failed
DownloadAgentFilesilently 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
KbIDis accepted but only ever logged. The debug path never forwards it (runDataflowDebugtakes 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 valueInterface leaks the concrete return type.
WithProgressSink(sink) *task.PipelineExecutorforces fakes to return a meaninglessnil(seeagent_logs_test.goline 342). SincerunDataflowDebugignores the return value, declaring it asWithProgressSink(sink pipelinepkg.ProgressSink)… isn't possible without changing the concrete method, but the interface can be narrowed to aSetProgressSink-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 liftExtra canvas load on every chat completion. This branch issues
LoadCanvasByIDfor all non-OpenAI chat requests just to readCanvasCategory, adding a DB round-trip to the hot chat path (the normal path loads the canvas again downstream inRunAgent). 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 winHoist the duplicated
message_idextraction. Both branches now run the identicalget(res, 'data.data.message_id')+setMessageIdblock.♻️ 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 valueThird string-pointer helper in the same package.
strPtralready exists ininternal/ingestion/task/pipeline_executor_test.goandtaskStrPtrininternal/ingestion/task/debug_pages_integration_test.go; reuse one instead of addingstrptr.🤖 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 winNormalize the input if this is billed as a "free-form" hint.
pythonFamilyNamematches only lower-case, dot-less extensions, so"PDF"or".pdf"return""— which ininjectDebugPageCapdegrades 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 valueConsider
filepath.Extinstead of manualLastIndex.
filepath.Ext(fileName)returns".pdf"directly and also handles path separators (a name likea.b/filecurrently 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 valueReuse the
debugvariable instead of re-deriving the same condition.Line 488 repeats
s.taskCtx.KB.ID == "", which is exactlydebugcomputed at line 458; fold the cap injection into the existingif debugblock 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 winSwallowed
BuildDebugResultDSLerror 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 winTiming 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 betweent1 := time.Now()and the secondOnComponentProgresspushes 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 valuePrefer
t.Errorfinside the uploader stub.If
uploadChunkImagesever fans out per-chunk uploads to goroutines,t.Fatalfhere only callsruntime.Goexit()on that goroutine and may not fail the test reliably.t.Errorf+returnis safe from any goroutine. Based on learnings: uset.Errorfinstead oft.Fatalfinside 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 winShadowed
chunksmakes the post-embedding validation implicit.
chunks, tokenCount, err := c.embedChunks(...)declares a newchunksscoped to theifblock, so line 376'svalidateTokenizerOutputs(chunks, ...)and the log at line 382 still refer to the outer slice. This only works becauseembedChunksmutates 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
📒 Files selected for processing (29)
internal/handler/agent.gointernal/handler/agent_dataflow_test.gointernal/handler/agent_logs_test.gointernal/handler/agent_test.gointernal/handler/agent_webhook.gointernal/handler/agent_webhook_test.gointernal/ingestion/component/chunker/image_upload_test.gointernal/ingestion/component/chunker/pdfcrop_nocgo.gointernal/ingestion/component/chunker/register.gointernal/ingestion/component/file.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/tokenizer.gointernal/ingestion/component/tokenizer_nonpersist_test.gointernal/ingestion/component/tokenizer_test.gointernal/ingestion/component/tokenizer_unit_test.gointernal/ingestion/pipeline/template_integration_test.gointernal/ingestion/task/constants.gointernal/ingestion/task/debug.gointernal/ingestion/task/debug_log_sink.gointernal/ingestion/task/debug_log_sink_test.gointernal/ingestion/task/debug_pages_integration_test.gointernal/ingestion/task/debug_result_dsl.gointernal/ingestion/task/debug_result_dsl_test.gointernal/ingestion/task/debug_test.gointernal/ingestion/task/pipeline_executor.gointernal/ingestion/task/pipeline_executor_persist_test.gointernal/ingestion/task/pipeline_executor_test.goweb/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
| 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) | ||
| }, | ||
| } |
There was a problem hiding this comment.
🩺 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=goRepository: 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())
PYRepository: 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.goRepository: 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=goRepository: 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=goRepository: 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`.
| payload, rerr := h.redisGet(key) | ||
| var data interface{} = map[string]interface{}{} | ||
| if rerr == nil { | ||
| data = parseAgentLogs(payload) | ||
| } |
There was a problem hiding this comment.
🩺 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.
| 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.
| // 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. |
There was a problem hiding this comment.
📐 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.
| // 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
| // 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 | ||
| } | ||
|
|
There was a problem hiding this comment.
📐 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.
| // 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.
2540d6c to
c658999
Compare
commented
Jul 30, 2026
|
@yingfeng @yuzhichang @JinHai-CN Please help to review |
| // 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, |
There was a problem hiding this comment.
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_idplumbing on the debug entry (request field + query fallback + leftover debug log). It was never consumed: the debug context is KB-less by construction (NewDebugTaskContextforcesKB.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 withagent_api.py; - the front-end
use-run-dataflow.tshook name, which predates this PR.
./build.sh --test ./internal/handler/... ./internal/ingestion/task/... passes.
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]>
7304c64 to
8cc0b0c
Compare
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:NewDebugTaskContextbuilds an in-memoryTaskContextwithKB.ID == ""— the single debug signal used across the ingestion pipeline. A canvas debug run has no knowledgebase, and production ingestion always supplies one, sokb_id == ""occurs ONLY in debug mode. Components gate their own side effects on this signal without any dedicated debug vocabulary (the formerCANVAS_DEBUG_DOC_IDmarker constant is removed).task/pipeline_executor.go:validateTaskContextno longer requires a KB whenKB.ID == ""(debug); debug runs returncollectDebugOutput(chunks) instead of a no-op; uploaded bytes are delivered asinputs['binary']for doc-less runs;injectDebugPageCapcaps the parser to the first pages for a fast preview via the productionoverride_paramschannel (Parser cpnID + family).component/tokenizer.go:shouldHaveEmbeddingskips embedding whenkb_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, skippingdoc_id-> storage resolution.handler/agent.go+agent_webhook.go: detectdataflow_canvasand 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 Pythonagent_api.py).parser_dispatch.go: exportParserFileFamilyfor 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: aDebugLogSinkrecords every component's lifecycle into a[{component_id, trace}]array (each trace entry carriesmessage,progress,timestamp,elapsed_time).Flushappends a terminalENDmarker 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 andelapsed_timeare in seconds (matching the rest of the app).task/debug_result_dsl.go:BuildDebugResultDSLbuilds thedslthe END marker carries — the Go analogue of Python'sGraph.__str__+ END-markerdslinrag/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-enddataflow-resultpage reads to render each step's parsed chunks. Raw embedding vectors (including the dimension-scopedq_<dim>_veckeys) are stripped so the stored log stays Python-scale.task/pipeline_executor.go: after the run, attach the builtdslto the END marker via theResultSinkcapability.handler/agent.go:runCanvasPipelineDebuggenerates a stablemessage_idup-front and always flushes the log (success or failure);respondWithDebugResultreturnsmessage_idin both the success and the error envelope so the front-end can poll the log. The debug-log endpointGET /agents/:id/logs/:message_idserves the array.web/src/pages/agent/hooks/use-run-dataflow.ts: on a run failure, also surfacemessage_idviasetMessageIdso the log sheet renders the failure timeline (the[ERROR]END marker is already written). Guarded byif (msgId), so it is a safe no-op when the back-end does not return an id.Behavioral notes
debugPageCapPages) for a fast preview; an explicitpagescap already present in the ParserConfig is respected.Test plan
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-markerdslcarries non-empty per-componentparams.outputswith chunks),debug_result_dsl_test.go(flat and real nestedoutput["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_ErrorCarriesMessageIDlockingmessage_idon failure), plus updates toagent_test.go/agent_webhook_test.go/chunker/image_upload_test.go/tokenizer*.go.go build ./...and./build.sh --testfor affected packages.🤖 Generated with CodeBuddy Code