Repository navigation
Implement builtin chunk method as ingestion pipeline in GO - #16822
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:
📝 WalkthroughWalkthroughThis PR expands ingestion with new parser formats, specialized chunkers, media and vision dispatch, MinerU PDF handling, tenant model resolution, canvas templates, file-type detection, metadata propagation, and runtime registration and seeding updates. ChangesIngestion and dispatch
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: 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: 9
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
internal/parser/parser/docx_parser.go (1)
55-99: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
internal/parser/parserdoesn’t compile in!cgobuilds
xls_parser.go/xlsx_parser.gostill defineNewXLSParser(libType string)andNewXLSXParser(libType string), whileoffice_parsers_no_cgo.goaddsNewXLSParser()andNewXLSXParser()under//go:build !cgo.GetParseralso still callsNewXLSXParser("")/NewXLSParser(""), so the package breaks in the non-CGO build path. Align the stub constructors with the call sites or gate the conflicting definitions.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/docx_parser.go` around lines 55 - 99, The !cgo parser constructors conflict with existing signatures and GetParser call sites. Update the !cgo definitions of NewXLSParser and NewXLSXParser in office_parsers_no_cgo.go to accept the libType string argument, matching xls_parser.go, xlsx_parser.go, and GetParser; alternatively consistently gate or adjust all conflicting definitions and callers so both CGO modes compile.Sources: Coding guidelines, Linters/SAST tools
internal/handler/components_testpkg/components_handler_test.go (1)
136-151: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winInclude
presentationchunkerin both ingestion expectation sets and fix the count text.
TestComponentsHandler_FilterIngestionandTestComponentsHandler_FilterMultipleboth list 11 names but the comment still ამბობს 10 / 6, and both omitpresentationchunkereven though it’s registered under ingestion.🤖 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/components_testpkg/components_handler_test.go` around lines 136 - 151, Update TestComponentsHandler_FilterIngestion and TestComponentsHandler_FilterMultiple to include the registered presentationchunker component in their expected name lists, and correct the ingestion count comments from 10 to 11 components and 6 chunker variants to 7.internal/ingestion/component/parser_test.go (1)
1-1: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGate the XLS/XLSX implementations behind
cgo
internal/parser/parser/xls_parser.goandinternal/parser/parser/xlsx_parser.goare untagged, so they compile together withinternal/parser/parser/office_parsers_no_cgo.goin!cgobuilds. That creates duplicateXLSParser/XLSXParserdeclarations and a constructor arity mismatch, which breaks the package. Add//go:build cgoto the real implementations or remove the no-cgo stubs.🤖 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_test.go` at line 1, Add a //go:build cgo constraint to the real XLSParser and XLSXParser implementations in xls_parser.go and xlsx_parser.go, ensuring they are excluded from !cgo builds and do not conflict with office_parsers_no_cgo.go; verify both cgo and !cgo package builds compile successfully.Source: Linters/SAST tools
internal/parser/parser/markdown_parser.go (1)
91-175: 🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy liftScope image lookup to the current block
internal/parser/parser/markdown_parser.go:126-214
walkMarkdownBlocksWithImagespasses the full document text intoresolveMarkdownImagefor every block, andresolveMarkdownImagealways prefers that non-empty string. Any markdown file with images will therefore attach the first image to every non-empty block. Walk the block subtree for*ast.Imageor use the block’s source span instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/markdown_parser.go` around lines 91 - 175, Scope image resolution to each current block instead of passing the full document text from walkMarkdownBlocksWithImages; inspect the block subtree for *ast.Image nodes or derive its source span, then pass only that block’s markdown to resolveMarkdownImage so unrelated blocks do not inherit the first document image.internal/ingestion/component/chunker/token.go (1)
680-721: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick winSilent content loss when merging into a previous chunk with empty
Text.In the merge branch,
prev.Textandprev.TKNumsare only updatedif prev.Text != "". If the previous merged text chunk happens to have emptyText(e.g., it was seeded from an empty-textckat the "start new chunk" branch), the currentck's text and token count are neither appended toprevnor pushed as a new chunk — they're dropped entirely.🐛 Proposed fix
// Merge into the accumulated text chunk. prev := &merged[len(merged)-1] - if prev.Text != "" { - prev.Text = prev.Text + "\n" + ck.Text - prev.TKNums = intPtr(intValue(prev.TKNums) + tk) - } + if prev.Text == "" { + prev.Text = ck.Text + } else { + prev.Text = prev.Text + "\n" + ck.Text + } + prev.TKNums = intPtr(intValue(prev.TKNums) + tk)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/component/chunker/token.go` around lines 680 - 721, The merge branch in the chunk-merging loop drops incoming text when the accumulated chunk’s Text is empty. Update the logic handling prev in the merge routine so every incoming text chunk is appended and its token count updated, including when prev.Text is empty; avoid gating the entire update on prev.Text being non-empty while preserving the existing newline behavior for non-empty text.
🟠 Major comments (17)
internal/ingestion/component/docx_vision_dispatch.go-258-272 (1)
258-272: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docxVisionPromptsBaseDirloses initialization error on subsequent calls.
initErris a local variable, butsync.Once.Doonly executes the closure on the first call. If the first call fails (e.g.,rag/promptsnot found),initErris set and the error is returned correctly. On subsequent calls,sync.Once.Dois a no-op, a freshinitErr(nil) is used, and the function returns("", nil)— an empty base directory with no error. This causesloadDOCXVisionPromptFileto construct a relative path (rag/prompts/<filename>) that may silently fail, losing the original diagnostic error.🐛 Proposed fix — move initErr to package level
var ( docxVisionPromptsBase string docxVisionPromptsOnce sync.Once + docxVisionPromptsErr error docxVisionPromptCache = make(map[string]string) docxVisionPromptMu sync.RWMutex )func docxVisionPromptsBaseDir() (string, error) { - var initErr error docxVisionPromptsOnce.Do(func() { root := utility.GetProjectRoot() if _, statErr := os.Stat(filepath.Join(root, "rag", "prompts")); statErr == nil { docxVisionPromptsBase = root return } - initErr = fmt.Errorf("rag/prompts not found under project root %q", root) + docxVisionPromptsErr = fmt.Errorf("rag/prompts not found under project root %q", root) }) - if initErr != nil { - return "", initErr + if docxVisionPromptsErr != nil { + return "", docxVisionPromptsErr } return docxVisionPromptsBase, 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/docx_vision_dispatch.go` around lines 258 - 272, docxVisionPromptsBaseDir loses the initialization error after the first failed call because initErr is local to each invocation. Store the initialization error in package-level state alongside docxVisionPromptsBase, set it inside the docxVisionPromptsOnce.Do callback, and return that persisted error on every subsequent call.internal/parser/parser/docx_parser.go-137-142 (1)
137-142: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winUse
docxContextWindowconstant instead of literal512.The constant
docxContextWindowis defined on line 169 but the calls tocollectDOCXPrevTextandcollectDOCXNextTexton lines 137 and 142 pass the literal512instead. Use the constant to keep the context window size DRY and avoid silent drift.♻️ Proposed fix
- above := collectDOCXPrevText(flat, i, 512) + above := collectDOCXPrevText(flat, i, docxContextWindow) fig.ContextAbove = strings.TrimSpace(above) - below := collectDOCXNextText(flat, i, 512) + below := collectDOCXNextText(flat, i, docxContextWindow) fig.ContextBelow = strings.TrimSpace(below)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/docx_parser.go` around lines 137 - 142, Replace the literal 512 arguments in the collectDOCXPrevText and collectDOCXNextText calls within the DOCX image-context handling with the existing docxContextWindow constant, keeping both scans aligned with the centralized context size.internal/parser/parser/pdf_parser_mineru.go-100-101 (1)
100-101: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winHandle the error from
NewMarkdownParser(GoMarkdown).Discarding the error with
mp, _ :=risks a nil-pointer dereference on the next line ifNewMarkdownParserever returns(nil, error). Even ifGoMarkdownis currently always valid, silently ignoring the error is fragile and makes future failures undiagnosable.🛡️ Proposed fix: propagate the error
- mp, _ := NewMarkdownParser(GoMarkdown) + mp, err := NewMarkdownParser(GoMarkdown) + if err != nil { + return ParseResult{Err: fmt.Errorf("parser: failed to create markdown parser: %w", err)} + } res := mp.ParseWithResult(filename, []byte(markdown))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/pdf_parser_mineru.go` around lines 100 - 101, Handle the error returned by NewMarkdownParser in the parsing flow before calling ParseWithResult: check the returned error and propagate or return it appropriately, rather than discarding it with mp, _. Use the existing parser function’s return conventions to preserve the failure details and prevent calling ParseWithResult on a nil parser.internal/parser/parser/audio_parser_test.go-1-98 (1)
1-98: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winFix the no-CGO
NewXLSXParsercallinternal/parser/parser/parser_type.gocallsNewXLSXParser(""), butinternal/parser/parser/office_parsers_no_cgo.goonly exportsNewXLSXParser()behind//go:build !cgo, so the parser package won’t compile in no-CGO builds.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/audio_parser_test.go` around lines 1 - 98, Update the no-CGO XLSX parser constructor usage so signatures match: change the call to NewXLSXParser in parser_type.go to use no arguments, consistent with the !cgo implementation in office_parsers_no_cgo.go. Verify both CGO and no-CGO builds compile successfully.Sources: Coding guidelines, Linters/SAST tools
internal/parser/parser/audio_parser.go-33-38 (1)
33-38: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winSynchronize
audioExtensionswithpythonFamilyNameaudio list inparser_dispatch.go.The
audioExtensionswhitelist and the audio case inpython_dispatch.go'spythonFamilyName(lines 309–311) are inconsistent:
pythonFamilyNamedispatches"alac","wv","opus"as audio →FileTypeAURAL→maybeDispatchAudio, butAudioParser.ParseWithResultrejects them because they're missing fromaudioExtensions.- Conversely,
"realaudio","vqf","oggvorbis"are inaudioExtensionsbut absent frompythonFamilyName, so files with those extensions never reach the audio dispatch path at all.This causes user-visible errors for valid audio files (alac/wv/opus) and silent misrouting for others (realaudio/vqf/oggvorbis).
🔧 Proposed fix: align both maps
var audioExtensions = map[string]bool{ "da": true, "wave": true, "wav": true, "mp3": true, "aac": true, "flac": true, "ogg": true, "aiff": true, "au": true, "midi": true, "wma": true, "realaudio": true, - "vqf": true, "oggvorbis": true, "ape": true, + "vqf": true, "oggvorbis": true, "ape": true, + "alac": true, "wv": true, "opus": true, }And in
parser_dispatch.gopythonFamilyName, add the missing entries:case "da", "wave", "wav", "mp3", "aac", "flac", "ogg", - "aiff", "au", "midi", "wma", "ape", "alac", "wv", "opus": + "aiff", "au", "midi", "wma", "realaudio", "vqf", + "oggvorbis", "ape", "alac", "wv", "opus": return "audio"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/audio_parser.go` around lines 33 - 38, Synchronize the audio extension whitelists used by AudioParser and pythonFamilyName. Update audioExtensions and the audio entries in pythonFamilyName to contain the same complete set, adding alac, wv, and opus where missing and ensuring realaudio, vqf, and oggvorbis are dispatched as audio; use the existing map definitions and audio dispatch case as references.internal/parser/parser/xls_tcadp.go-16-77 (1)
16-77: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winPropagate a caller context instead of hardcoding
context.Background().Both the submit (Line 41) and download (Line 62) requests use
context.Background()internally, with no parameter to accept a caller-supplied context/deadline. A hung or slow TCADP endpoint can block the calling goroutine indefinitely, and callers cannot cancel this call.🛠️ Proposed fix
-func parseSpreadsheetWithTCADP(filename string, data []byte, fileType string, tcadpAPIServer, tcadpAPIKey, tableResultType, markdownImageResponseType string, outputFormat string) ParseResult { +func parseSpreadsheetWithTCADP(ctx context.Context, filename string, data []byte, fileType string, tcadpAPIServer, tcadpAPIKey, tableResultType, markdownImageResponseType string, outputFormat string) ParseResult { if len(data) == 0 { return emptyPDFResult(filename) } @@ - resp, err := models.PostJSONRequest(context.Background(), models.NewDriverHTTPClient(), strings.TrimRight(baseURL, "/")+"/reconstruct_document", bearer(apiKey), requestBody) + resp, err := models.PostJSONRequest(ctx, models.NewDriverHTTPClient(), strings.TrimRight(baseURL, "/")+"/reconstruct_document", bearer(apiKey), requestBody) @@ - downloadReq, err := http.NewRequestWithContext(context.Background(), http.MethodGet, payload.DocumentRecognizeResultURL, nil) + downloadReq, err := http.NewRequestWithContext(ctx, http.MethodGet, payload.DocumentRecognizeResultURL, 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/parser/parser/xls_tcadp.go` around lines 16 - 77, Update parseSpreadsheetWithTCADP to accept a caller-provided context parameter and use it for both the models.PostJSONRequest submit call and the http.NewRequestWithContext download request instead of context.Background(). Propagate that context from every caller, preserving cancellation and deadlines through the entire TCADP operation.internal/ingestion/component/parser.go-313-327 (1)
313-327: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winErrors from
maybeDispatchDOCXVisionandmaybeDispatchMarkdownVisionare silently discarded.Both calls use
_, _to discard thehandledanderrreturn values. If vision enhancement fails (e.g., LLM unavailable, image extraction error), the error is swallowed and the dispatched content may silently lack vision descriptions. This degrades observability and makes debugging difficult.At minimum, log the errors so failures are visible. Consider whether partial vision enrichment should surface a warning to the user.
🔍 Proposed fix: log discarded errors
- dispatched, _, _ = maybeDispatchDOCXVision(fileTypeExt, dispatched, inputs, c.Param.Setups) + dispatched, _, docxVisErr := maybeDispatchDOCXVision(fileTypeExt, dispatched, inputs, c.Param.Setups) + if docxVisErr != nil { + log.Warnf("Parser: DOCX vision enhancement failed: %v", docxVisErr) + } // Markdown vision figure enhancement: enrich parsed // markdown JSON items with LLM-generated descriptions of // referenced images (). Mirrors Python's // enhance_media_sections_with_vision in _markdown. - dispatched, _, _ = maybeDispatchMarkdownVision(fileTypeExt, dispatched, inputs) + dispatched, _, mdVisErr := maybeDispatchMarkdownVision(fileTypeExt, dispatched, inputs) + if mdVisErr != nil { + log.Warnf("Parser: markdown vision enhancement failed: %v", mdVisErr) + }🤖 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.go` around lines 313 - 327, Handle the returned errors from maybeDispatchDOCXVision and maybeDispatchMarkdownVision instead of discarding them. After each call in the dispatch block, log any non-nil error with sufficient context using the parser’s existing logging mechanism, and preserve the dispatched payload; consider emitting a warning if enrichment is only partially completed.internal/ingestion/component/chunker/qa.go-127-131 (1)
127-131: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winSingle-letter
Q/Aprefix regex over-matches and corrupts content.The regex
^(...|Q|A|...)[\t:: ]+allowsQorAfollowed by a plain space. This strips legitimate text starting with "A " or "Q " — e.g., the answer"A programming language"becomes"programming language", and a heading like"A Brief History"becomes"Brief History". The multi-character alternatives (Question,Answer,user,assistant) are unambiguous with a space separator, but single letters are not.Fix: require a colon for single-letter prefixes while keeping the broader separator class for multi-character ones.
🛡️ Proposed fix: split the regex to require colon for single-letter prefixes
-var rmQAPrefixRe = regexp.MustCompile(`^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+`) +var rmQAPrefixRe = regexp.MustCompile(`^(问题|答案|回答|user|assistant|Question|Answer|问|答)[\t:: ]+|^(Q|A)[::]+`)🤖 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/qa.go` around lines 127 - 131, Update rmQAPrefixRe used by rmQAPrefix so single-letter Q and A prefixes only match when followed by a colon or full-width colon, while multi-character prefixes retain the existing separator handling. Preserve stripping for Question:, Answer, user, assistant, and related labels without removing legitimate text beginning with “A ” or “Q ”.internal/ingestion/component/chunker/nlp.go-431-458 (1)
431-458: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
FindCodecencoding detection is effectively non-functional beyond ASCII/UTF-8 — always guesses "gb2312".For any byte sequence that isn't valid UTF-8/ASCII,
tryCharMapDecodereturnstruewhenever the data merely contains a high-bit byte (hasHighBits). Since"gb2312"is the first non-utf8/ascii codec tried inallCodecs, this meansFindCodecreturns"gb2312"for essentially all non-ASCII content — Shift_JIS, EUC-KR, Big5, Windows-125x, ISO-8859-x files will all be misdetected, producing garbled text downstream despite the docstring's claim to mirror Python'schardet.detect.Consider using an established charset-detection library (e.g. a maintained Go port of chardet/uchardet) instead of this heuristic, per the general guideline to prefer well-known libraries over hand-rolled implementations of standard algorithms.
Also applies to: 462-486, 571-592
🤖 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/nlp.go` around lines 431 - 458, Replace the heuristic detection in FindCodec, including related logic in tryCharMapDecode and the additional codec-detection paths, with a maintained charset-detection library such as a Go chardet/uchardet port. Feed the library the sampled or full blob as appropriate, map its result to the project’s codec names, and retain UTF-8 as the fallback when detection fails or confidence is insufficient; remove the unconditional high-bit-byte acceptance that causes non-UTF-8 data to be labeled gb2312.internal/ingestion/component/chunker/nlp.go-1258-1353 (1)
1258-1353: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse
splitKeepingDelimhere
regexp.Splitdrops the delimiters, sosplitParts[j+1]is another text fragment, not sentence punctuation. That makestakeFromEnd/takeFromStartsplice adjacent sentences together and break the context boundaries around tables/images.Suggested direction
Reuse
splitKeepingDelim(cnt, splitPat)(already used elsewhere in this file) so the delimiter is preserved and sentence reconstruction stays aligned.🤖 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/nlp.go` around lines 1258 - 1353, Update addContext’s takeFromEnd and takeFromStart helpers to use the existing splitKeepingDelim(cnt, splitPat) instead of regexp.Split, preserving sentence delimiters and maintaining correct context boundaries around image/table chunks.internal/ingestion/component/chunker/nlp.go-1539-1588 (1)
1539-1588: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse
splitKeepingDelimhere tooDocTokenizeChunksWithImagesshould matchTokenizeChunksWithImages;re.Splitdrops the delimiter text, so the child chunks can be rebuilt with different boundaries.🤖 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/nlp.go` around lines 1539 - 1588, DocTokenizeChunksWithImages currently uses regexp.Split, which can discard delimiter text and produce inconsistent child boundaries. Replace the child-delim splitting logic in DocTokenizeChunksWithImages with the existing splitKeepingDelim helper, preserving delimiters when constructing each child chunk and matching TokenizeChunksWithImages behavior.agent/templates/ingestion_pipeline_book.json-148-161 (1)
148-161: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
{,2}is literal here — change it to{0,2}in both places.
[\\((][0-9]{,2}[\\))]does not match(5)or(5); it only matches the literal text5{,2}. Updateagent/templates/ingestion_pipeline_book.jsonand the duplicated node rule around lines 393–411.🤖 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 `@agent/templates/ingestion_pipeline_book.json` around lines 148 - 161, The numeric parenthesized heading regex uses invalid quantifier syntax. In both the shown rule set and the duplicated node rule, update the pattern containing `[\\((][0-9]{,2}[\\))]` to use `{0,2}` so it matches ASCII and Chinese parenthesized numbers correctly.internal/ingestion/component/chunker/nlp.go-1124-1229 (1)
1124-1229: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse
splitKeepingDelimhere
regexp.Regexp.Splitdrops the delimiter text in Go, so this branch never sees delimiter-only elements and can’t flushsegon custom delimiters. Replace it withsplitKeepingDelimto match the other chunking paths.🤖 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/nlp.go` around lines 1124 - 1229, In buildCks, the custom-delimiter branch currently uses regexp.Regexp.Split, which discards delimiters before processing. Replace customRe.Split(text, -1) with splitKeepingDelim using customRe so delimiter elements remain available and the existing flush logic can process them.internal/parser/parser/epub_parser.go-193-193 (1)
193-193: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winWhitespace normalization destroys structural newlines inserted by tag replacement.
The tag replacement logic (lines 248–269) inserts
\nfor block-level closing tags (</p>,</div>,</h1>, etc.), butepubWSRe.ReplaceAllString(s, " ")at line 273 replaces all\s+(including\n) with a single space, collapsing all paragraph breaks. The output becomes a single unstructured line, contradicting the intent of the tag replacement.🔧 Proposed fix
Change the whitespace regex to preserve newlines:
- epubWSRe = regexp.MustCompile(`\s+`) + epubWSRe = regexp.MustCompile(`[^\S\n]+`)Then add a step after whitespace normalization to collapse multiple consecutive newlines:
// Normalize whitespace. s = epubWSRe.ReplaceAllString(s, " ") + s = regexp.MustCompile(`\n{2,}`).ReplaceAllString(s, "\n") return strings.TrimSpace(s)Also applies to: 248-273
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/epub_parser.go` at line 193, Update the whitespace normalization used by the EPUB tag-replacement logic: change epubWSRe so it collapses horizontal whitespace without matching newlines, then add a subsequent normalization step to reduce consecutive newlines to one. Ensure the processing around the tag replacement and final normalization preserves the structural newlines inserted for block-level closing tags.internal/parser/parser/epub_parser.go-214-216 (1)
214-216: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUse
path.Joinfor ZIP entry names.archive/zipmatches entries with/, sofilepath.Joinwill generate\on Windows andr.Open(resolved)can miss the EPUB spine 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/parser/parser/epub_parser.go` around lines 214 - 216, Use path.Join instead of filepath.Join when resolving the EPUB ZIP entry in readEPUBContentFile, because archive/zip paths always use forward slashes across platforms. Preserve the existing base-directory and href resolution behavior so r.Open(resolved) locates spine files on Windows.internal/ingestion/component/chunker/token.go-297-299 (1)
297-299: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winSentence-delimiter split discards the punctuation, unlike the delimiter-preserving split used elsewhere.
sentenceDelim.Split(sec, -1)removes the matched separator (\n, CJK punctuation, or.) instead of keeping it attached to the segment, whereas the top-level split path (splitKeepingDelim) explicitly preserves delimiters. This silently drops sentence-ending punctuation from oversized-section chunks, altering chunk text fidelity compared to the rest of the file's delimiter handling.♻️ Suggested fix (keep the delimiter attached)
- parts := sentenceDelim.Split(sec, -1) + parts := splitKeepingDelim(sec, sentenceDelim)(reuse the existing
splitKeepingDelimhelper instead ofregexp.Split, so punctuation stays with the preceding sentence.)Also applies to: 357-378
🤖 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/token.go` around lines 297 - 299, Replace the regexp-based sentence splitting around sentenceDelim and the affected oversized-section handling with the existing splitKeepingDelim helper, passing the same sentence-boundary pattern. Ensure delimiters remain attached to the preceding chunk, preserving newline, CJK punctuation, and English “. ” in all affected paths.agent/templates/ingestion_pipeline_resume.json-403-430 (1)
403-430: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
promptsshape mismatch between component params and node form.
Extractor:ThreeDrinksAct.obj.params.promptsis an array of{content, role}objects (lines 38-43), but the corresponding graph node'sdata.form.prompts(line 421) is a plain string. If the canvas UI reconstructs/validates the form from this shape, loading this template could render incorrectly or throw, since the two representations disagree on structure.🐛 Proposed fix to align form.prompts with params.prompts
- "prompts": "Content: {TitleChunker:FlatMiceFix@chunks}", + "prompts": [ + { + "content": "Content: {TitleChunker:FlatMiceFix@chunks}", + "role": "user" + } + ],🤖 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 `@agent/templates/ingestion_pipeline_resume.json` around lines 403 - 430, Align the Auto Metadata node’s data.form.prompts with the Extractor:ThreeDrinksAct.obj.params.prompts schema by representing prompts as an array of objects containing the expected content and role fields, preserving the existing system and user prompt text. Update the corresponding template structure consistently so canvas loading and form validation receive the same prompt shape.
🟡 Minor comments (5)
internal/ingestion/component/docx_vision_dispatch.go-274-283 (1)
274-283: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse the figure’s real MIME type in
buildVisionMessagesoffice_oxidepreserves the embedded image bytes, so DOCX figures aren’t guaranteed to be PNG. Hardcodingdata:image/pngcan break non-PNG embeds; carry the MIME type through extraction or detect it from the bytes before building the data URI.🤖 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/docx_vision_dispatch.go` around lines 274 - 283, buildVisionMessages currently hardcodes image/png, but embedded DOCX figures may use other formats. Carry the extracted image MIME type alongside imageBase64 (or detect it from decoded bytes) and use it when constructing the data URI in buildVisionMessages, updating its callers and related extraction flow accordingly.internal/parser/parser/parse_result_test.go-133-133 (1)
133-133: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winCheck the constructor error before using the parser.
Ignoring the error from
NewMarkdownParserrisks a nil-pointer panic onp.ParseWithResultif construction ever fails, instead of a clear test failure.🛡️ Proposed fix
- p, _ := NewMarkdownParser(GoMarkdown) + p, err := NewMarkdownParser(GoMarkdown) + if err != nil { + t.Fatalf("NewMarkdownParser: %v", err) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/parse_result_test.go` at line 133, The test ignores the constructor error from NewMarkdownParser before using the parser. Capture and assert the returned error immediately, ensure the parser is non-nil, then call p.ParseWithResult only after successful construction.internal/parser/parser/json_parser.go-180-223 (1)
180-223: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winScanner errors are silently swallowed.
scanner.Err()is never checked after the loop; a line exceeding the 10MB cap or other scan failure truncates results without any signal to the caller.🛡️ Proposed fix
items = append(items, map[string]any{ "text": string(b), "doc_type_kwd": "text", }) } + if err := scanner.Err(); err != nil { + items = append(items, map[string]any{ + "text": "", + "doc_type_kwd": "text", + "_warning": fmt.Sprintf("jsonl scan error: %v", err), + }) + } return items }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/json_parser.go` around lines 180 - 223, Handle the scan failure in parseJSONLines by checking scanner.Err() after the scanning loop and expose it to the caller rather than silently returning partial results. Update the function’s return signature and all callers to propagate or handle the error, preserving the existing parsed items on success.internal/ingestion/component/dispatch_model.go-204-234 (1)
204-234: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winUse the same
activegate as the ID path. This branch only rejectsinactive, so any other non-activestatus resolves here even thoughresolveModelConfigByIDrequiresactive.🤖 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/dispatch_model.go` around lines 204 - 234, The name-based model resolution path accepts statuses other than active. In the modelErr == nil branch of the relevant resolver, replace the inactive-only check with the same active-status gate used by resolveModelConfigByID, rejecting any model whose status is not "active" while preserving the existing disabled-model error behavior.internal/parser/parser/markdown_parser.go-50-81 (1)
50-81: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winThread the markdown setup fields into the parser or remove them
ConfigureFromSetupstoresParseMethod,OutputFormat, andVLM, butParseWithResultnever reads them, and the markdown vision path only inspects the emitted result. That meansparse_method/output_format/vlmsettings are silently ignored for Markdown.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/markdown_parser.go` around lines 50 - 81, Markdown setup fields are stored but never applied during parsing. Update ParseWithResult and the Markdown vision-processing path to consume ParseMethod, OutputFormat, and VLM from MarkdownParser, or remove ConfigureFromSetup and the unused fields; ensure parse_method, output_format, and vlm settings affect Markdown behavior consistently.
🧹 Nitpick comments (11)
internal/ingestion/component/media_dispatch.go (1)
438-531: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy liftUse a cancellable context with timeout for OCR operations.
runLocalImageOCRcreatescontext.Background()(line 458) forOCRDetectandOCRRecognizecalls. If the DeepDoc service is slow or unresponsive, these calls block indefinitely with no way to cancel. Consider deriving a context with a timeout from the caller, or at minimum usingcontext.WithTimeouthere.♻️ Proposed refactor: add timeout context
- ctx := context.Background() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() boxes, err := client.OCRDetect(ctx, img)🤖 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/media_dispatch.go` around lines 438 - 531, Use a bounded, cancellable context in runLocalImageOCR instead of context.Background(). Create it with context.WithTimeout using an appropriate OCR timeout constant or duration, defer its cancellation, and pass it to both OCRDetect and OCRRecognize so unresponsive DeepDoc calls terminate promptly.internal/ingestion/component/pdf_vision_dispatch.go (1)
292-293: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
capshadows the builtin.Using
capas the loop variable (also at Line 296) shadows Go's builtincap. Harmless here but a readability trap; prefercaption.🤖 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/pdf_vision_dispatch.go` around lines 292 - 293, Rename the loop variable cap to caption in the table-caption iteration within the relevant function, including the occurrence around line 296, and update all references in those loops accordingly to avoid shadowing Go’s builtin cap.internal/ingestion/component/dispatch_model.go (1)
108-116: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueRedundant model lookup.
resolveModelConfigcallsmodelDAO.GetByID(modelRef)only to test existence, thenresolveModelConfigByIDfetches the same record again viamodelDAO.GetByID(modelRef)(Line 123). On the hot ingestion path this doubles the query. Consider reusing the first fetch or havingresolveModelConfigByIDaccept the already-loaded object.🤖 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/dispatch_model.go` around lines 108 - 116, Eliminate the duplicate model lookup in resolveModelConfig by reusing the record returned from the initial modelDAO.GetByID(modelRef) call. Update resolveModelConfigByID to accept the already-loaded model object (or otherwise pass it through), while preserving the existing not-found fallback to resolveModelConfigFromProviderInstance and non-not-found error handling.internal/ingestion/component/chunker/register_test.go (1)
25-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDoc comment is stale and carries migration wording.
The loop now also pins
ComponentNamePresentationChunker, but the comment only listsOneChunker, TagChunker and TableChunker. The trailing note about "an unrelated, pre-existing build break on the diverged branch" is migration-history commentary that guidelines ask to drop. Please update the comment to match the four names and remove the migration note.As per coding guidelines: "Drop stale comments and documentation describing a superseded design" and "Do not add new compatibility wording in comments or 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/ingestion/component/chunker/register_test.go` around lines 25 - 31, The TestNewChunkersRegistered doc comment is stale and contains migration-history wording. Update it to list OneChunker, TagChunker, TableChunker, and PresentationChunker, and remove the note about the parser package and pre-existing build break.Source: Coding guidelines
internal/ingestion/component/markdown_vision_dispatch.go (1)
110-131: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winLoad the vision prompt once before the goroutine loop.
buildMarkdownVisionPrompt()returns the same no-context prompt for every image, yet it's called inside each goroutine. IfloadDOCXVisionPromptFileperforms file I/O, this redundantly reads the same file up tomarkdownVisionConcurrencytimes concurrently. Loading once before the loop also fails fast — if the prompt is unavailable, skip all vision enhancement instead of silently failing per goroutine.♻️ Proposed refactor: hoist prompt loading
descriptions := make([]string, len(images)) var wg sync.WaitGroup sem := make(chan struct{}, markdownVisionConcurrency) + prompt, err := buildMarkdownVisionPrompt() + if err != nil { + return dispatched, false, nil + } + for i, img := range images { wg.Add(1) go func(pos int, item imgItem) { defer wg.Done() sem <- struct{}{} defer func() { <-sem }() - // Markdown images have no context — use the - // default (no-context) prompt template. - prompt, err := buildMarkdownVisionPrompt() - if err != nil { - return - } - messages := buildVisionMessages(prompt, item.imageB64) resp, err := visionChatInvoker(driver, modelName, messages, apiConfig) if err != nil { return } descriptions[pos] = extractDOCXVisionAnswer(resp) }(i, img) }🤖 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/markdown_vision_dispatch.go` around lines 110 - 131, The vision prompt is redundantly loaded inside each goroutine and errors are silently ignored. In the dispatch function containing the image loop, call buildMarkdownVisionPrompt once before launching goroutines, return or skip vision enhancement if it fails, and pass the resulting prompt into each goroutine for buildVisionMessages.internal/parser/parser/markdown_parser.go (1)
45-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueGlobal mutable
ssrfAllowLoopbackflag risks accidental SSRF-protection bypass and test races.A package-level boolean used purely to let tests bypass the loopback check is fragile: parallel tests toggling it can race, and any test that sets it
truebut fails to reset it (e.g. on a failed assertion before cleanup) leaves SSRF protection disabled for subsequent tests/code in the same process.Consider injecting an "allow-loopback" option into
fetchImageAsBase64/validateImageURLHost(e.g. via a parser field or function parameter) instead of a shared package-level flag.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/markdown_parser.go` around lines 45 - 48, Replace the package-level mutable ssrfAllowLoopback flag with instance-scoped or parameter-based configuration. Update fetchImageAsBase64 and validateImageURLHost to receive an explicit allow-loopback option, or store it on the parser instance, and adjust production callers to keep loopback disallowed while tests opt in without shared state or races.internal/service/ingestion_pipeline.go (1)
54-67: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLog DAO errors in
resolvePipelineDSLto distinguish "not found" from database failures.All errors from
canvasDAO.GetByIDandcanvasTemplateDAO.GetByIDare silently ignored. A database outage is indistinguishable from "not found", and the caller logs "not found" (line 46) which is misleading. Adding a warning log for non-nil errors would aid diagnosis without changing the fallback behavior.♻️ Proposed refactor
func (s *DocumentService) resolvePipelineDSL(pipelineID string) ([]byte, error) { // Try user_canvas first (user-created pipelines). - if canvas, err := s.canvasDAO.GetByID(pipelineID); err == nil && canvas != nil { - if dslBytes, err := json.Marshal(canvas.DSL); err == nil && len(dslBytes) > 0 { - return dslBytes, nil - } + canvas, err := s.canvasDAO.GetByID(pipelineID) + if err != nil { + common.Warn(fmt.Sprintf("resolvePipelineDSL: canvasDAO.GetByID(%s) error: %v", pipelineID, err)) + } else if canvas != nil { + if dslBytes, err := json.Marshal(canvas.DSL); err == nil && len(dslBytes) > 0 { + return dslBytes, nil + } } // Fallback to canvas_template (system templates). - if template, err := s.canvasTemplateDAO.GetByID(pipelineID); err == nil && template != nil { - if dslBytes, err := json.Marshal(template.DSL); err == nil && len(dslBytes) > 0 { - return dslBytes, nil - } + template, err := s.canvasTemplateDAO.GetByID(pipelineID) + if err != nil { + common.Warn(fmt.Sprintf("resolvePipelineDSL: canvasTemplateDAO.GetByID(%s) error: %v", pipelineID, err)) + } else if template != nil { + if dslBytes, err := json.Marshal(template.DSL); err == nil && len(dslBytes) > 0 { + return dslBytes, nil + } } return nil, nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/ingestion_pipeline.go` around lines 54 - 67, Update resolvePipelineDSL to log warning details whenever canvasDAO.GetByID or canvasTemplateDAO.GetByID returns a non-nil error, while preserving the existing fallback and return behavior. Use the service’s existing logger and include the pipelineID and the DAO error so database failures can be distinguished from missing records.internal/parser/parser/email_parser.go (1)
99-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winText output uses non-deterministic map iteration order.
rangeoveremailContent(amap[string]any) produces fields in random order, making the text output non-reproducible and harder to test. Iterate in a defined field order instead.♻️ Proposed refactor
+var emailFieldOrder = []string{"from", "to", "cc", "bcc", "date", "subject", "body", "attachments", "metadata"} + // Text output: flatten fields into a single string. var sb strings.Builder - for k, v := range emailContent { + for _, k := range emailFieldOrder { + v, ok := emailContent[k] + if !ok { + continue + } switch val := v.(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/parser/parser/email_parser.go` around lines 99 - 131, Make the text serialization deterministic by replacing the direct range over emailContent in the string-builder logic with iteration over a defined, stable field order, while preserving each value-type handler and output format. Use the ordered field keys to retrieve values from emailContent before applying the existing switch.internal/parser/parser/epub_parser.go (1)
192-192: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPrefer
html.UnescapeStringover manual entity decoding.The regex
&[a-zA-Z]+;misses numeric character references ( ,—) common in EPUBs, andxmlEntityValueonly handles a small subset of named entities.html.UnescapeStringfrom the standard library handles all HTML entities including numeric references, is simpler, and eliminates ~30 lines of custom code.♻️ Proposed refactor
import ( "archive/zip" "bytes" "encoding/xml" "fmt" + "html" "io" "path" "regexp" "strings" )Remove
epubEntityReandxmlEntityValue, replace the entity decoding call:- // Decode common XML entities. - s = epubEntityRe.ReplaceAllStringFunc(s, xmlEntityValue) + // Decode HTML entities (including numeric character references). + s = html.UnescapeString(s)Then delete the
xmlEntityValuefunction (lines 279–310) and theepubEntityReregex (line 192).Also applies to: 271-271, 279-310
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/epub_parser.go` at line 192, Replace the custom entity decoding in the EPUB parser with standard-library HTML decoding: import html, use html.UnescapeString at the current entity-decoding call site, and remove the epubEntityRe variable and xmlEntityValue function. This ensures named and numeric references are handled consistently.agent/templates/ingestion_pipeline_picture.json (1)
84-102: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStale "TokenChunker" id despite migrating to OneChunker.
The component/node id is still
TokenChunker:BrightColorsGloweven thoughobj.component_name/label/name are allOneChunker. Compare withingestion_pipeline_one.json, where the equivalent migration renamed the id itself toOneChunker:DryDrinksVisit. Leaving the stale prefix here is inconsistent and reads as a half-finished rename.♻️ Suggested rename for consistency
- "TokenChunker:BrightColorsGlow": { + "OneChunker:BrightColorsGlow": { "downstream": [ "Tokenizer:SharpLensFocus" ],(and update all references:
downstream,upstream, edge ids/source/target, node id)Also applies to: 238-254
🤖 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 `@agent/templates/ingestion_pipeline_picture.json` around lines 84 - 102, Rename the migrated node id from TokenChunker:BrightColorsGlow to a OneChunker-prefixed id, matching the established naming pattern in ingestion_pipeline_one.json. Update every reference to this node, including downstream/upstream entries and all edge ids, sources, targets, and node identifiers in the affected sections.internal/ingestion/component/chunker/token.go (1)
341-351: 🚀 Performance & Scalability | 🔵 TrivialDuplicated "tiny segment" merge logic.
The
tn < 8(andpn < 8) tiny-segment merge-or-append block is duplicated almost verbatim for section-level and sentence-part-level handling. Consider extracting a small helper (e.g.appendTiny(text string, tokens int)) to avoid the copy-pasted branch.♻️ Suggested extraction
appendTiny := func(text string, tokens int) { if len(cks) > 0 { cks[len(cks)-1] += text tkns[len(tkns)-1] += tokens } else { cks = append(cks, text) tkns = append(tkns, tokens) } }then call
appendTiny(t, tn)/appendTiny(p, pn)in place of the duplicated blocks.Also applies to: 367-376
🤖 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/token.go` around lines 341 - 351, Extract the duplicated tiny-segment merge-or-append logic from the section-level and sentence-part-level handling into a local helper such as appendTiny(text string, tokens int). Define it near the surrounding chunk assembly logic, then replace both the tn < 8 and pn < 8 branches with appendTiny(t, tn) and appendTiny(p, pn), preserving the existing cks and tkns updates.
| @@ -0,0 +1,820 @@ | |||
| // | |||
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical
Package-level build failure reported by static analysis (internal/parser/parser).
golangci-lint's typecheck reports XLSParser/XLSXParser/NewXLSParser/NewXLSXParser redeclared between xls_parser.go/xlsx_parser.go and office_parsers_no_cgo.go, plus a NewXLSXParser signature mismatch (parser_type.go:38) causing "not enough return values"/"too many arguments in call". This is a compile-breaking duplicate-implementation issue in internal/parser/parser, which is squarely in the actively-refactored path this PR touches.
Per coding guidelines, duplicate declarations across the CGO/no-CGO variants of these parsers should be collapsed into one path rather than left coexisting.
🔍 Verification script
#!/bin/bash
rg -n "func NewXLSXParser|func NewXLSParser|type XLSParser|type XLSXParser" internal/parser/parser/🤖 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/nlp_test.go` at line 1, The
internal/parser/parser package has duplicate XLS/XLSX parser declarations across
the CGO and no-CGO files, including incompatible NewXLSXParser signatures.
Consolidate these implementations into one canonical path by removing or
integrating the duplicate XLSParser, XLSXParser, NewXLSParser, and NewXLSXParser
declarations, then align parser_type.go call sites with the retained constructor
signatures so the package type-checks in both build configurations.
Sources: Coding guidelines, Linters/SAST tools
| func RemoveContentsTable(sections []string, eng bool) []string { | ||
| i := 0 | ||
| for i < len(sections) { | ||
| get := func(idx int) string { | ||
| if idx >= len(sections) { | ||
| return "" | ||
| } | ||
| s := sections[idx] | ||
| return strings.TrimSpace(strings.Split(s, "@@")[0]) | ||
| } | ||
|
|
||
| cleaned := regexp.MustCompile(`( |\t|`+"\u3000"+`)+`).ReplaceAllString(get(i), "") | ||
| if !tocPattern.MatchString(cleaned) { | ||
| i++ | ||
| continue | ||
| } | ||
| sections = append(sections[:i], sections[i+1:]...) | ||
| if i >= len(sections) { | ||
| break | ||
| } | ||
| prefix := "" | ||
| if !eng { | ||
| g := get(i) | ||
| runes := []rune(g) | ||
| if len(runes) >= 3 { | ||
| prefix = string(runes[:3]) | ||
| } | ||
| } else { | ||
| prefix = strings.Join(strings.Fields(get(i))[:2], " ") | ||
| } | ||
| for prefix == "" { | ||
| sections = append(sections[:i], sections[i+1:]...) | ||
| if i >= len(sections) { | ||
| break | ||
| } | ||
| if !eng { | ||
| runes := []rune(get(i)) | ||
| if len(runes) >= 3 { | ||
| prefix = string(runes[:3]) | ||
| } | ||
| } else { | ||
| prefix = strings.Join(strings.Fields(get(i))[:2], " ") | ||
| } | ||
| } | ||
| sections = append(sections[:i], sections[i+1:]...) | ||
| if i >= len(sections) || prefix == "" { | ||
| break | ||
| } | ||
| limit := i + 128 | ||
| if limit > len(sections) { | ||
| limit = len(sections) | ||
| } | ||
| for j := i; j < limit; j++ { | ||
| if !strings.HasPrefix(get(j), prefix) { | ||
| continue | ||
| } | ||
| sections = append(sections[:i], sections[j:]...) | ||
| break | ||
| } | ||
| } | ||
| return sections | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Out-of-bounds panic in RemoveContentsTable when eng == true and a line has fewer than 2 words.
At lines 772 and 785, strings.Fields(get(i))[:2] panics (slice bounds out of range) whenever get(i) returns an empty string or a single-word string — a routine occurrence (e.g. an empty line adjacent to a removed TOC entry). This is directly reachable from real document content and will crash the ingestion pipeline.
🐛 Proposed fix
- prefix = strings.Join(strings.Fields(get(i))[:2], " ")
+ fields := strings.Fields(get(i))
+ if len(fields) > 2 {
+ fields = fields[:2]
+ }
+ prefix = strings.Join(fields, " ")Apply the same fix at both occurrences (lines 772 and 785).
📝 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.
| func RemoveContentsTable(sections []string, eng bool) []string { | |
| i := 0 | |
| for i < len(sections) { | |
| get := func(idx int) string { | |
| if idx >= len(sections) { | |
| return "" | |
| } | |
| s := sections[idx] | |
| return strings.TrimSpace(strings.Split(s, "@@")[0]) | |
| } | |
| cleaned := regexp.MustCompile(`( |\t|`+"\u3000"+`)+`).ReplaceAllString(get(i), "") | |
| if !tocPattern.MatchString(cleaned) { | |
| i++ | |
| continue | |
| } | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) { | |
| break | |
| } | |
| prefix := "" | |
| if !eng { | |
| g := get(i) | |
| runes := []rune(g) | |
| if len(runes) >= 3 { | |
| prefix = string(runes[:3]) | |
| } | |
| } else { | |
| prefix = strings.Join(strings.Fields(get(i))[:2], " ") | |
| } | |
| for prefix == "" { | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) { | |
| break | |
| } | |
| if !eng { | |
| runes := []rune(get(i)) | |
| if len(runes) >= 3 { | |
| prefix = string(runes[:3]) | |
| } | |
| } else { | |
| prefix = strings.Join(strings.Fields(get(i))[:2], " ") | |
| } | |
| } | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) || prefix == "" { | |
| break | |
| } | |
| limit := i + 128 | |
| if limit > len(sections) { | |
| limit = len(sections) | |
| } | |
| for j := i; j < limit; j++ { | |
| if !strings.HasPrefix(get(j), prefix) { | |
| continue | |
| } | |
| sections = append(sections[:i], sections[j:]...) | |
| break | |
| } | |
| } | |
| return sections | |
| } | |
| func RemoveContentsTable(sections []string, eng bool) []string { | |
| i := 0 | |
| for i < len(sections) { | |
| get := func(idx int) string { | |
| if idx >= len(sections) { | |
| return "" | |
| } | |
| s := sections[idx] | |
| return strings.TrimSpace(strings.Split(s, "@@")[0]) | |
| } | |
| cleaned := regexp.MustCompile(`( |\t|`+"\u3000"+`)+`).ReplaceAllString(get(i), "") | |
| if !tocPattern.MatchString(cleaned) { | |
| i++ | |
| continue | |
| } | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) { | |
| break | |
| } | |
| prefix := "" | |
| if !eng { | |
| g := get(i) | |
| runes := []rune(g) | |
| if len(runes) >= 3 { | |
| prefix = string(runes[:3]) | |
| } | |
| } else { | |
| fields := strings.Fields(get(i)) | |
| if len(fields) > 2 { | |
| fields = fields[:2] | |
| } | |
| prefix = strings.Join(fields, " ") | |
| } | |
| for prefix == "" { | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) { | |
| break | |
| } | |
| if !eng { | |
| runes := []rune(get(i)) | |
| if len(runes) >= 3 { | |
| prefix = string(runes[:3]) | |
| } | |
| } else { | |
| fields := strings.Fields(get(i)) | |
| if len(fields) > 2 { | |
| fields = fields[:2] | |
| } | |
| prefix = strings.Join(fields, " ") | |
| } | |
| } | |
| sections = append(sections[:i], sections[i+1:]...) | |
| if i >= len(sections) || prefix == "" { | |
| break | |
| } | |
| limit := i + 128 | |
| if limit > len(sections) { | |
| limit = len(sections) | |
| } | |
| for j := i; j < limit; j++ { | |
| if !strings.HasPrefix(get(j), prefix) { | |
| continue | |
| } | |
| sections = append(sections[:i], sections[j:]...) | |
| break | |
| } | |
| } | |
| return sections | |
| } |
🤖 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/nlp.go` around lines 744 - 805, Remove
the out-of-bounds slicing in RemoveContentsTable when eng is true. At both
prefix-generation sites, inspect the result of strings.Fields(get(i)) and only
join the first two words when at least two exist; otherwise leave prefix empty
so the existing removal loop can continue safely.
2fffc70 to
9ce1507
Compare
9ce1507 to
15753f0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/ingestion/component/chunker/one.go (1)
17-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim the Python-port/migration wording from the doc comment.
The comment documents behavior via its Python origins (
rag/app/one.py,picture.py,audio.py) and a migration-style comparison toTokenChunker. Describe whatOneChunkerdoes in the current Go runtime instead of how it maps to the Python implementation.As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not migration history" and "Do not add new compatibility wording in comments or 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/ingestion/component/chunker/one.go` around lines 17 - 27, Revise the OneChunker doc comment to describe only its current Go-runtime behavior: emitting one chunk per upstream document while preserving the single item’s image attachment, media context, and doc_type. Remove Python file references, port/migration language, and comparisons with TokenChunker.Source: Coding guidelines
internal/parser/parser/factory.go (1)
55-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unused
NewPicturePDFParserstub
It has no remaining references outside its declaration, so it can be dropped with the other stub constructors.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/factory.go` at line 55, Remove the unused NewPicturePDFParser stub from the parser factory’s stub constructor declarations, leaving the referenced NewPictureParser behavior unchanged.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/parser/parser/epub_parser.go`:
- Around line 214-216: Update readEPUBContentFile to use slash-based path.Dir
and path.Join when resolving EPUB ZIP entry paths, replacing the OS-dependent
filepath operations. Preserve the existing relative href resolution and fallback
behavior.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/one.go`:
- Around line 17-27: Revise the OneChunker doc comment to describe only its
current Go-runtime behavior: emitting one chunk per upstream document while
preserving the single item’s image attachment, media context, and doc_type.
Remove Python file references, port/migration language, and comparisons with
TokenChunker.
In `@internal/parser/parser/factory.go`:
- Line 55: Remove the unused NewPicturePDFParser stub from the parser factory’s
stub constructor declarations, leaving the referenced NewPictureParser behavior
unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e0dd11bf-0f26-497c-b93a-bd182315fb8f
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (87)
agent/templates/ingestion_pipeline_audio.jsonagent/templates/ingestion_pipeline_book.jsonagent/templates/ingestion_pipeline_email.jsonagent/templates/ingestion_pipeline_general.jsonagent/templates/ingestion_pipeline_laws.jsonagent/templates/ingestion_pipeline_manual.jsonagent/templates/ingestion_pipeline_one.jsonagent/templates/ingestion_pipeline_paper.jsonagent/templates/ingestion_pipeline_picture.jsonagent/templates/ingestion_pipeline_presentation.jsonagent/templates/ingestion_pipeline_qa.jsonagent/templates/ingestion_pipeline_resume.jsonagent/templates/ingestion_pipeline_table.jsonagent/templates/ingestion_pipeline_tag.jsongo.modinternal/agent/dsl/normalize.gointernal/dao/canvas_template_seed.gointernal/engine/elasticsearch/chunk.gointernal/entity/kb.gointernal/entity/models/types.gointernal/handler/components_testpkg/components_handler_test.gointernal/ingestion/component/chunker/common.gointernal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/hierarchy.gointernal/ingestion/component/chunker/hierarchy_test.gointernal/ingestion/component/chunker/image.gointernal/ingestion/component/chunker/one.gointernal/ingestion/component/chunker/one_test.gointernal/ingestion/component/chunker/presentation.gointernal/ingestion/component/chunker/presentation_test.gointernal/ingestion/component/chunker/qa.gointernal/ingestion/component/chunker/qa_test.gointernal/ingestion/component/chunker/register_test.gointernal/ingestion/component/chunker/table.gointernal/ingestion/component/chunker/table_test.gointernal/ingestion/component/chunker/tag.gointernal/ingestion/component/chunker/tag_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/chunker/title_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_test.gointernal/ingestion/component/dispatch_model.gointernal/ingestion/component/docx_vision_dispatch.gointernal/ingestion/component/markdown_vision_dispatch.gointernal/ingestion/component/media_dispatch.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/parser_dispatch_test.gointernal/ingestion/component/parser_test.gointernal/ingestion/component/pdf_vision_dispatch.gointernal/ingestion/component/schema/chunk_types.gointernal/ingestion/component/schema/chunker.gointernal/ingestion/component/schema/parser.gointernal/parser/parser/audio_parser.gointernal/parser/parser/audio_parser_test.gointernal/parser/parser/csv_parser.gointernal/parser/parser/docx_parser.gointernal/parser/parser/email_parser.gointernal/parser/parser/email_parser_test.gointernal/parser/parser/epub_parser.gointernal/parser/parser/factory.gointernal/parser/parser/factory_test.gointernal/parser/parser/json_parser.gointernal/parser/parser/markdown_parser.gointernal/parser/parser/markdown_parser_test.gointernal/parser/parser/office_parsers_no_cgo.gointernal/parser/parser/office_parsers_nocgo_test.gointernal/parser/parser/office_parsers_shared.gointernal/parser/parser/paddleocr.gointernal/parser/parser/parse_result_test.gointernal/parser/parser/parser_type.gointernal/parser/parser/pdf_parser_mineru.gointernal/parser/parser/pdf_parser_plaintext_nocgo.gointernal/parser/parser/picture_parser.gointernal/parser/parser/picture_parser_test.gointernal/parser/parser/xls_parser.gointernal/parser/parser/xls_tcadp.gointernal/parser/parser/xls_tcadp_test.gointernal/parser/parser/xlsx_parser.gointernal/service/chunk/chunk.gointernal/service/components_service_test.gointernal/service/dataset.gointernal/service/document.gointernal/service/load_prompt.gointernal/tokenizer/tokenizer.gointernal/utility/file.go
💤 Files with no reviewable changes (6)
- internal/entity/kb.go
- internal/parser/parser/factory_test.go
- internal/service/dataset.go
- internal/service/chunk/chunk.go
- internal/service/document.go
- internal/parser/parser/office_parsers_nocgo_test.go
🚧 Files skipped from review as they are similar to previous changes (72)
- internal/parser/parser/office_parsers_shared.go
- go.mod
- agent/templates/ingestion_pipeline_qa.json
- internal/ingestion/component/schema/chunker.go
- agent/templates/ingestion_pipeline_presentation.json
- internal/ingestion/component/schema/parser.go
- internal/ingestion/component/parser_test.go
- internal/ingestion/component/chunker/one_test.go
- internal/service/components_service_test.go
- internal/dao/canvas_template_seed.go
- agent/templates/ingestion_pipeline_table.json
- internal/ingestion/component/chunker/image.go
- agent/templates/ingestion_pipeline_audio.json
- internal/entity/models/types.go
- internal/parser/parser/pdf_parser_plaintext_nocgo.go
- internal/ingestion/component/chunker/table_test.go
- agent/templates/ingestion_pipeline_tag.json
- internal/ingestion/component/schema/chunk_types.go
- internal/ingestion/component/chunker/presentation_test.go
- internal/ingestion/component/chunker/table.go
- internal/parser/parser/audio_parser.go
- internal/ingestion/component/chunker/register_test.go
- internal/parser/parser/picture_parser.go
- internal/parser/parser/pdf_parser_mineru.go
- internal/parser/parser/email_parser_test.go
- internal/service/load_prompt.go
- internal/parser/parser/csv_parser.go
- internal/parser/parser/markdown_parser_test.go
- internal/tokenizer/tokenizer.go
- internal/ingestion/component/docx_vision_dispatch.go
- internal/ingestion/component/markdown_vision_dispatch.go
- internal/ingestion/component/parser_dispatch.go
- internal/ingestion/component/chunker/hierarchy.go
- internal/utility/file.go
- internal/ingestion/component/chunker/presentation.go
- internal/ingestion/component/chunker/group_test.go
- internal/ingestion/component/chunker/token_test.go
- internal/parser/parser/xls_tcadp.go
- internal/agent/dsl/normalize.go
- internal/parser/parser/xls_tcadp_test.go
- internal/parser/parser/picture_parser_test.go
- internal/ingestion/component/chunker/tag_test.go
- internal/ingestion/component/media_dispatch.go
- agent/templates/ingestion_pipeline_picture.json
- internal/ingestion/component/chunker/qa_test.go
- internal/ingestion/component/parser.go
- internal/parser/parser/paddleocr.go
- agent/templates/ingestion_pipeline_paper.json
- internal/handler/components_testpkg/components_handler_test.go
- agent/templates/ingestion_pipeline_resume.json
- internal/ingestion/component/chunker/title_test.go
- internal/parser/parser/audio_parser_test.go
- internal/ingestion/component/chunker/tag.go
- internal/ingestion/component/dispatch_model.go
- internal/parser/parser/json_parser.go
- internal/engine/elasticsearch/chunk.go
- internal/ingestion/component/chunker/hierarchy_test.go
- agent/templates/ingestion_pipeline_email.json
- internal/parser/parser/xls_parser.go
- internal/parser/parser/xlsx_parser.go
- agent/templates/ingestion_pipeline_manual.json
- internal/parser/parser/email_parser.go
- internal/ingestion/component/pdf_vision_dispatch.go
- internal/parser/parser/markdown_parser.go
- agent/templates/ingestion_pipeline_one.json
- internal/parser/parser/docx_parser.go
- internal/ingestion/component/chunker/group.go
- agent/templates/ingestion_pipeline_general.json
- internal/ingestion/component/chunker/token.go
- agent/templates/ingestion_pipeline_book.json
- internal/ingestion/component/chunker/qa.go
- internal/ingestion/component/chunker/title.go
15753f0 to
8745209
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/component/parser_dispatch.go (1)
48-57: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
file_typestill collapsesxls/pptto the wrong parser
fileTypeFromInputsmaps family names before the direct-extension fallback, so explicitfile_type: "xls"andfile_type: "ppt"resolve toxlsx/pptxinstead of reachingutility.GetFileType("x."+lower). That bypasses the distinctXLSParser/PPTParserroutes. Special-case these extensions likecsv, or move the direct-extension lookup ahead of the family mapping.🤖 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 48 - 57, The fileTypeFromInputs resolution currently maps xls and ppt through family names, incorrectly selecting xlsx and pptx parsers. Update fileTypeFromInputs to handle explicit xls and ppt like csv, or perform direct-extension lookup before family mapping, so utility.GetFileType resolves them to the distinct XLSParser and PPTParser routes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/ingestion/component/parser_dispatch.go`:
- Around line 208-220: Update the hint resolution flow around pythonFamilyName
and familyToExt so utility.GetFileType("x."+lower) runs before family
collapsing, preserving exact file types such as xls and ppt. Keep the csv
special case intact and retain family-based fallback behavior only when no
direct extension match exists.
---
Outside diff comments:
In `@internal/ingestion/component/parser_dispatch.go`:
- Around line 48-57: The fileTypeFromInputs resolution currently maps xls and
ppt through family names, incorrectly selecting xlsx and pptx parsers. Update
fileTypeFromInputs to handle explicit xls and ppt like csv, or perform
direct-extension lookup before family mapping, so utility.GetFileType resolves
them to the distinct XLSParser and PPTParser routes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: dfbf7ebb-e66f-4061-b040-34eb321fee0a
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (87)
agent/templates/ingestion_pipeline_audio.jsonagent/templates/ingestion_pipeline_book.jsonagent/templates/ingestion_pipeline_email.jsonagent/templates/ingestion_pipeline_general.jsonagent/templates/ingestion_pipeline_laws.jsonagent/templates/ingestion_pipeline_manual.jsonagent/templates/ingestion_pipeline_one.jsonagent/templates/ingestion_pipeline_paper.jsonagent/templates/ingestion_pipeline_picture.jsonagent/templates/ingestion_pipeline_presentation.jsonagent/templates/ingestion_pipeline_qa.jsonagent/templates/ingestion_pipeline_resume.jsonagent/templates/ingestion_pipeline_table.jsonagent/templates/ingestion_pipeline_tag.jsongo.modinternal/agent/dsl/normalize.gointernal/dao/canvas_template_seed.gointernal/engine/elasticsearch/chunk.gointernal/entity/kb.gointernal/entity/models/types.gointernal/handler/components_testpkg/components_handler_test.gointernal/ingestion/component/chunker/common.gointernal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/hierarchy.gointernal/ingestion/component/chunker/hierarchy_test.gointernal/ingestion/component/chunker/image.gointernal/ingestion/component/chunker/one.gointernal/ingestion/component/chunker/one_test.gointernal/ingestion/component/chunker/presentation.gointernal/ingestion/component/chunker/presentation_test.gointernal/ingestion/component/chunker/qa.gointernal/ingestion/component/chunker/qa_test.gointernal/ingestion/component/chunker/register_test.gointernal/ingestion/component/chunker/table.gointernal/ingestion/component/chunker/table_test.gointernal/ingestion/component/chunker/tag.gointernal/ingestion/component/chunker/tag_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/chunker/title_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_test.gointernal/ingestion/component/dispatch_model.gointernal/ingestion/component/docx_vision_dispatch.gointernal/ingestion/component/markdown_vision_dispatch.gointernal/ingestion/component/media_dispatch.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/parser_dispatch_test.gointernal/ingestion/component/parser_test.gointernal/ingestion/component/pdf_vision_dispatch.gointernal/ingestion/component/schema/chunk_types.gointernal/ingestion/component/schema/chunker.gointernal/ingestion/component/schema/parser.gointernal/parser/parser/audio_parser.gointernal/parser/parser/audio_parser_test.gointernal/parser/parser/csv_parser.gointernal/parser/parser/docx_parser.gointernal/parser/parser/email_parser.gointernal/parser/parser/email_parser_test.gointernal/parser/parser/epub_parser.gointernal/parser/parser/factory.gointernal/parser/parser/factory_test.gointernal/parser/parser/json_parser.gointernal/parser/parser/markdown_parser.gointernal/parser/parser/markdown_parser_test.gointernal/parser/parser/office_parsers_no_cgo.gointernal/parser/parser/office_parsers_nocgo_test.gointernal/parser/parser/office_parsers_shared.gointernal/parser/parser/paddleocr.gointernal/parser/parser/parse_result_test.gointernal/parser/parser/parser_type.gointernal/parser/parser/pdf_parser_mineru.gointernal/parser/parser/pdf_parser_plaintext_nocgo.gointernal/parser/parser/picture_parser.gointernal/parser/parser/picture_parser_test.gointernal/parser/parser/xls_parser.gointernal/parser/parser/xls_tcadp.gointernal/parser/parser/xls_tcadp_test.gointernal/parser/parser/xlsx_parser.gointernal/service/chunk/chunk.gointernal/service/components_service_test.gointernal/service/dataset.gointernal/service/document.gointernal/service/load_prompt.gointernal/tokenizer/tokenizer.gointernal/utility/file.go
💤 Files with no reviewable changes (6)
- internal/entity/kb.go
- internal/parser/parser/factory_test.go
- internal/service/dataset.go
- internal/service/document.go
- internal/service/chunk/chunk.go
- internal/parser/parser/office_parsers_nocgo_test.go
🚧 Files skipped from review as they are similar to previous changes (75)
- internal/parser/parser/office_parsers_shared.go
- internal/service/components_service_test.go
- internal/dao/canvas_template_seed.go
- internal/parser/parser/parser_type.go
- agent/templates/ingestion_pipeline_presentation.json
- internal/ingestion/component/chunker/table.go
- internal/ingestion/component/parser_test.go
- internal/tokenizer/tokenizer.go
- internal/parser/parser/pdf_parser_mineru.go
- internal/entity/models/types.go
- internal/agent/dsl/normalize.go
- internal/ingestion/component/chunker/one_test.go
- internal/parser/parser/parse_result_test.go
- internal/ingestion/component/chunker/table_test.go
- internal/ingestion/component/schema/parser.go
- internal/ingestion/component/chunker/group_test.go
- internal/engine/elasticsearch/chunk.go
- agent/templates/ingestion_pipeline_table.json
- internal/parser/parser/pdf_parser_plaintext_nocgo.go
- internal/parser/parser/audio_parser_test.go
- internal/ingestion/component/chunker/presentation_test.go
- internal/ingestion/component/chunker/token_test.go
- internal/ingestion/component/chunker/register_test.go
- agent/templates/ingestion_pipeline_manual.json
- internal/ingestion/component/chunker/common.go
- internal/ingestion/component/chunker/one.go
- internal/ingestion/component/chunker/qa_test.go
- internal/parser/parser/markdown_parser_test.go
- internal/ingestion/component/chunker/presentation.go
- agent/templates/ingestion_pipeline_audio.json
- internal/ingestion/component/schema/chunker.go
- agent/templates/ingestion_pipeline_qa.json
- internal/parser/parser/picture_parser_test.go
- internal/ingestion/component/markdown_vision_dispatch.go
- go.mod
- internal/ingestion/component/chunker/title_test.go
- internal/ingestion/component/chunker/group.go
- internal/parser/parser/xls_tcadp_test.go
- internal/parser/parser/docx_parser.go
- internal/utility/file.go
- internal/parser/parser/factory.go
- internal/parser/parser/xls_parser.go
- internal/parser/parser/paddleocr.go
- agent/templates/ingestion_pipeline_paper.json
- internal/ingestion/component/chunker/hierarchy_test.go
- internal/ingestion/component/docx_vision_dispatch.go
- agent/templates/ingestion_pipeline_picture.json
- internal/parser/parser/xls_tcadp.go
- internal/parser/parser/email_parser_test.go
- agent/templates/ingestion_pipeline_resume.json
- agent/templates/ingestion_pipeline_email.json
- agent/templates/ingestion_pipeline_one.json
- internal/ingestion/component/chunker/qa.go
- internal/ingestion/component/chunker/tag_test.go
- agent/templates/ingestion_pipeline_laws.json
- agent/templates/ingestion_pipeline_general.json
- internal/service/load_prompt.go
- internal/parser/parser/csv_parser.go
- internal/ingestion/component/chunker/tag.go
- internal/parser/parser/audio_parser.go
- internal/parser/parser/picture_parser.go
- internal/ingestion/component/schema/chunk_types.go
- internal/ingestion/component/parser.go
- internal/parser/parser/email_parser.go
- internal/ingestion/component/media_dispatch.go
- internal/parser/parser/json_parser.go
- internal/handler/components_testpkg/components_handler_test.go
- internal/ingestion/component/chunker/title.go
- internal/parser/parser/epub_parser.go
- internal/ingestion/component/dispatch_model.go
- internal/parser/parser/xlsx_parser.go
- internal/parser/parser/markdown_parser.go
- agent/templates/ingestion_pipeline_book.json
- internal/ingestion/component/chunker/token.go
- internal/ingestion/component/pdf_vision_dispatch.go
8745209 to
a91ce79
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
internal/ingestion/pipeline/template_integration_test.go (1)
808-813: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep DSL construction coverage for skipped templates.
These skips occur before
NewPipelineFromDSL, so QA/Tag templates can regress in component registration or wiring without failing this smoke test. Construct and validate the pipeline first, then skip only execution requiring specialized input.As per coding guidelines, “Preserve valid behavior with focused tests.”
🤖 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/pipeline/template_integration_test.go` around lines 808 - 813, Move the templateUsesComponent checks for “QAChunker” and “TagChunker” to after NewPipelineFromDSL constructs and validates the pipeline. Keep the specialized-input skips before execution, preserving pipeline construction and component registration coverage for those templates.Source: Coding guidelines
internal/parser/parser/xlsx_parser.go (1)
27-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the ineffective
libTypeconstructor parameter.
libTypeis stored but never read, while the constructor returns an error it cannot produce. Collapse this to a no-argument constructor and update its callers instead of exposing a backend selector with no effect.Proposed simplification
type XLSXParser struct { - libType string ParseMethod string OutputFormat string TCADPAPIServer string TCADPAPIKey string TCADPTableResultType string TCADPMarkdownImageResponseType string } -func NewXLSXParser(libType string) (*XLSXParser, error) { - if libType == "" { - libType = "excelize" - } - return &XLSXParser{ - libType: libType, +func NewXLSXParser() *XLSXParser { + return &XLSXParser{ TCADPTableResultType: "1", TCADPMarkdownImageResponseType: "1", - }, nil + } }As per coding guidelines, “Reduce public surface area when a helper can be made private or internal” and “keep exported APIs only when currently needed.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/parser/parser/xlsx_parser.go` around lines 27 - 45, Change NewXLSXParser to a no-argument constructor that returns only *XLSXParser, remove the unused libType field and initialization, and update every caller to use the simplified signature without error handling for this construction step.Source: Coding guidelines
internal/ingestion/component/chunker/hierarchy.go (1)
147-156: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace migration-history comments with current runtime behavior.
References to Python parity and “Gap H” preserve implementation history rather than documenting this Go path.
Proposed comment cleanup
- // Mirror python HierarchyTitleChunker.build_chunks: accumulate - // contiguous text records into a run; on each non-text record flush - // the run (build the heading tree + emit its paths) and emit the - // non-text record as its own single-record group. A final flush - // handles the trailing run. - // - // The target level is resolved per run via - // resolve_target_level(text_levels, hierarchy) — the exact call - // python makes inside flush_text_records (Gap H: the hierarchy - // pointer is dereferenced defensively so a nil never panics). + // Flush each contiguous text run independently. Non-text records + // remain standalone groups, while text runs are grouped by their + // resolved hierarchy level before chunk construction. ... - // resolve_target_level returned None (no heading levels in - // the run): emit the whole run as a single group, exactly - // like python's `record_groups.append(text_records.copy())`. + // No headings were detected, so preserve the run as one group.As per coding guidelines, “Keep Go package comments and doc comments aligned with the current runtime path, not migration history.”
Also applies to: 171-173
🤖 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/hierarchy.go` around lines 147 - 156, Update the comments surrounding the chunk-building logic near the hierarchy target-level resolution to describe only the current Go runtime behavior. Remove references to Python parity, migration history, and “Gap H,” while retaining concise documentation of contiguous text accumulation, flushing on non-text records and at the end, and defensive handling of a nil hierarchy.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/parser/parser/xlsx_parser.go`:
- Around line 76-94: The ParseWithResult method must reject unsupported parse
methods instead of falling through to Excelize. After normalizeXLSXParseMethod,
explicitly allow only an empty method or “excelize” for the existing Excelize
path and “tcadp” for parseSpreadsheetWithTCADP; return a ParseResult containing
an error for any other value.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/hierarchy.go`:
- Around line 147-156: Update the comments surrounding the chunk-building logic
near the hierarchy target-level resolution to describe only the current Go
runtime behavior. Remove references to Python parity, migration history, and
“Gap H,” while retaining concise documentation of contiguous text accumulation,
flushing on non-text records and at the end, and defensive handling of a nil
hierarchy.
In `@internal/ingestion/pipeline/template_integration_test.go`:
- Around line 808-813: Move the templateUsesComponent checks for “QAChunker” and
“TagChunker” to after NewPipelineFromDSL constructs and validates the pipeline.
Keep the specialized-input skips before execution, preserving pipeline
construction and component registration coverage for those templates.
In `@internal/parser/parser/xlsx_parser.go`:
- Around line 27-45: Change NewXLSXParser to a no-argument constructor that
returns only *XLSXParser, remove the unused libType field and initialization,
and update every caller to use the simplified signature without error handling
for this construction step.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c0654c89-1766-45ed-93ff-14972db621a2
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (89)
agent/templates/ingestion_pipeline_audio.jsonagent/templates/ingestion_pipeline_book.jsonagent/templates/ingestion_pipeline_email.jsonagent/templates/ingestion_pipeline_general.jsonagent/templates/ingestion_pipeline_laws.jsonagent/templates/ingestion_pipeline_manual.jsonagent/templates/ingestion_pipeline_one.jsonagent/templates/ingestion_pipeline_paper.jsonagent/templates/ingestion_pipeline_picture.jsonagent/templates/ingestion_pipeline_presentation.jsonagent/templates/ingestion_pipeline_qa.jsonagent/templates/ingestion_pipeline_resume.jsonagent/templates/ingestion_pipeline_table.jsonagent/templates/ingestion_pipeline_tag.jsongo.modinternal/agent/dsl/normalize.gointernal/dao/canvas_template_seed.gointernal/engine/elasticsearch/chunk.gointernal/engine/elasticsearch/chunk_test.gointernal/entity/kb.gointernal/entity/models/types.gointernal/handler/components_testpkg/components_handler_test.gointernal/ingestion/component/chunker/common.gointernal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/hierarchy.gointernal/ingestion/component/chunker/hierarchy_test.gointernal/ingestion/component/chunker/image.gointernal/ingestion/component/chunker/one.gointernal/ingestion/component/chunker/one_test.gointernal/ingestion/component/chunker/presentation.gointernal/ingestion/component/chunker/presentation_test.gointernal/ingestion/component/chunker/qa.gointernal/ingestion/component/chunker/qa_test.gointernal/ingestion/component/chunker/register_test.gointernal/ingestion/component/chunker/table.gointernal/ingestion/component/chunker/table_test.gointernal/ingestion/component/chunker/tag.gointernal/ingestion/component/chunker/tag_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/chunker/title_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_test.gointernal/ingestion/component/dispatch_model.gointernal/ingestion/component/docx_vision_dispatch.gointernal/ingestion/component/markdown_vision_dispatch.gointernal/ingestion/component/media_dispatch.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/parser_dispatch_test.gointernal/ingestion/component/parser_test.gointernal/ingestion/component/pdf_vision_dispatch.gointernal/ingestion/component/schema/chunk_types.gointernal/ingestion/component/schema/chunker.gointernal/ingestion/component/schema/parser.gointernal/ingestion/pipeline/template_integration_test.gointernal/parser/parser/audio_parser.gointernal/parser/parser/audio_parser_test.gointernal/parser/parser/csv_parser.gointernal/parser/parser/docx_parser.gointernal/parser/parser/email_parser.gointernal/parser/parser/email_parser_test.gointernal/parser/parser/epub_parser.gointernal/parser/parser/factory.gointernal/parser/parser/factory_test.gointernal/parser/parser/json_parser.gointernal/parser/parser/markdown_parser.gointernal/parser/parser/markdown_parser_test.gointernal/parser/parser/office_parsers_no_cgo.gointernal/parser/parser/office_parsers_nocgo_test.gointernal/parser/parser/office_parsers_shared.gointernal/parser/parser/paddleocr.gointernal/parser/parser/parse_result_test.gointernal/parser/parser/parser_type.gointernal/parser/parser/pdf_parser_mineru.gointernal/parser/parser/pdf_parser_plaintext_nocgo.gointernal/parser/parser/picture_parser.gointernal/parser/parser/picture_parser_test.gointernal/parser/parser/xls_parser.gointernal/parser/parser/xls_tcadp.gointernal/parser/parser/xls_tcadp_test.gointernal/parser/parser/xlsx_parser.gointernal/service/chunk/chunk.gointernal/service/components_service_test.gointernal/service/dataset.gointernal/service/document.gointernal/service/load_prompt.gointernal/tokenizer/tokenizer.gointernal/utility/file.go
💤 Files with no reviewable changes (6)
- internal/entity/kb.go
- internal/service/document.go
- internal/service/chunk/chunk.go
- internal/parser/parser/factory_test.go
- internal/service/dataset.go
- internal/parser/parser/office_parsers_nocgo_test.go
🚧 Files skipped from review as they are similar to previous changes (73)
- internal/entity/models/types.go
- go.mod
- internal/parser/parser/pdf_parser_mineru.go
- internal/parser/parser/office_parsers_shared.go
- agent/templates/ingestion_pipeline_tag.json
- internal/parser/parser/parse_result_test.go
- internal/ingestion/component/schema/chunker.go
- agent/templates/ingestion_pipeline_audio.json
- internal/ingestion/component/chunker/table_test.go
- internal/ingestion/component/parser_test.go
- agent/templates/ingestion_pipeline_email.json
- internal/ingestion/component/chunker/register_test.go
- internal/ingestion/component/chunker/image.go
- internal/ingestion/component/chunker/tag_test.go
- internal/tokenizer/tokenizer.go
- internal/ingestion/component/chunker/common.go
- internal/ingestion/component/chunker/group_test.go
- internal/ingestion/component/chunker/title_test.go
- internal/parser/parser/markdown_parser_test.go
- internal/service/components_service_test.go
- agent/templates/ingestion_pipeline_picture.json
- internal/ingestion/component/chunker/one_test.go
- internal/parser/parser/audio_parser.go
- internal/parser/parser/picture_parser_test.go
- internal/parser/parser/audio_parser_test.go
- internal/parser/parser/pdf_parser_plaintext_nocgo.go
- internal/agent/dsl/normalize.go
- internal/parser/parser/picture_parser.go
- agent/templates/ingestion_pipeline_qa.json
- internal/parser/parser/factory.go
- internal/ingestion/component/chunker/table.go
- internal/ingestion/component/parser.go
- internal/parser/parser/paddleocr.go
- internal/engine/elasticsearch/chunk.go
- internal/ingestion/component/parser_dispatch.go
- internal/ingestion/component/chunker/qa_test.go
- internal/ingestion/component/schema/parser.go
- internal/ingestion/component/chunker/presentation_test.go
- internal/parser/parser/email_parser.go
- internal/ingestion/component/markdown_vision_dispatch.go
- internal/ingestion/component/docx_vision_dispatch.go
- internal/parser/parser/xls_tcadp.go
- internal/ingestion/component/chunker/title.go
- internal/ingestion/component/chunker/tag.go
- agent/templates/ingestion_pipeline_paper.json
- internal/parser/parser/docx_parser.go
- agent/templates/ingestion_pipeline_presentation.json
- internal/dao/canvas_template_seed.go
- agent/templates/ingestion_pipeline_manual.json
- internal/ingestion/component/chunker/qa.go
- internal/ingestion/component/chunker/presentation.go
- internal/ingestion/component/schema/chunk_types.go
- internal/parser/parser/json_parser.go
- internal/parser/parser/epub_parser.go
- internal/service/load_prompt.go
- internal/parser/parser/email_parser_test.go
- internal/ingestion/component/media_dispatch.go
- internal/parser/parser/xls_tcadp_test.go
- internal/ingestion/component/chunker/hierarchy_test.go
- internal/parser/parser/xls_parser.go
- internal/ingestion/component/chunker/one.go
- internal/parser/parser/office_parsers_no_cgo.go
- agent/templates/ingestion_pipeline_book.json
- internal/utility/file.go
- agent/templates/ingestion_pipeline_one.json
- internal/parser/parser/markdown_parser.go
- internal/ingestion/component/chunker/token_test.go
- agent/templates/ingestion_pipeline_general.json
- internal/parser/parser/csv_parser.go
- internal/ingestion/component/chunker/group.go
- internal/ingestion/component/chunker/token.go
- internal/ingestion/component/dispatch_model.go
- internal/ingestion/component/pdf_vision_dispatch.go
beb35d7 to
d6f64da
Compare
Summary
Implement builtin chunk mehtod as ingestion pipeline in GO