Repository navigation
Go: parse ingestion DSL - #15938
Go: parse ingestion DSL#15938
Conversation
📝 WalkthroughWalkthroughThis PR implements a complete text chunking pipeline system with a DSL-based engine for the ragflow ingestion framework. It introduces operators for preprocessing, splitting, and postprocessing text, an expression evaluator for conditional logic, and integrates the system into the CLI chunk command with explain and execute workflows. ChangesText Chunking Pipeline Implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (4)
internal/ingestion/chunk_engine_test.go (1)
231-295: ⚡ Quick winAssert pipeline semantics, not just successful execution.
These tests currently prove the happy path doesn't error, but they don't verify the new behavior strongly enough.
TestPlan_Execute_*only checks for non-empty output, andTestPlan_Explaindoesn't assert the rendered plan at all, so a regression that skips an operator or returns the wrong explanation would still pass. Please assert a few stable invariants here (for example, expected operator names in the explanation and expected metadata/index fields on produced chunks).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/chunk_engine_test.go` around lines 231 - 295, Add concrete assertions to the tests to verify pipeline semantics rather than only non-error behavior: in TestPlan_Execute_FullPipeline and TestPlan_Execute_MinimalPipeline assert stable invariants on ctx.ResultChunks (e.g., expected number of chunks or min count, specific chunk.Content prefixes, presence of required metadata keys like "source"/"index" and their types, and that chunk indices are monotonically increasing) by inspecting ctx.ResultChunks and c.Metadata; in TestPlan_Explain call engine.Explain(plan) and assert the returned explanation string contains expected operator names (e.g., the media-aware operators used in mediaAwareDSL and the minimal operators used in minimalDSL) and key phrases so regressions that remove or reorder operators fail. Use the existing symbols NewChunkEngine, Compile, Execute, Explain, ctx.ResultChunks, and c.Metadata to locate where to add these assertions.internal/ingestion/chunk/expression.go (1)
648-649: ⚡ Quick winRemove unused
mathimport workaround.The
var _ = math.NaNline appears to be a leftover to satisfy the compiler, butmathisn't used elsewhere. Remove both the import and this line.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/chunk/expression.go` around lines 648 - 649, Remove the unused math import workaround: delete the `var _ = math.NaN` line and remove the corresponding `import "math"` from the imports so the compiler no longer sees an unused import; ensure no other references to `math` remain in the file (search for `math.`) before committing the change.internal/ingestion/chunk/preprocess.go (1)
73-74: ⚡ Quick winRegex compiled on every
Executecall—move to package level.
regexp.MustCompileis expensive. Lines 73 and 102 compile regexes insideExecute, which runs once per pipeline invocation. Hoist them to package-level variables for better performance.♻️ Proposed fix
package chunk import ( "fmt" "regexp" "strings" ) +var ( + reMultipleNewlines = regexp.MustCompile(`\n{2,}`) + reSentenceEnd = regexp.MustCompile(`[.!?。!?][\s]*$`) +) + type PreprocessOperator struct { ... func (o *PreprocessOperator) Execute(chunkCtx *ChunkContext) error { ... if o.normalizeNewlines { text = strings.ReplaceAll(text, "\r\n", "\n") text = strings.ReplaceAll(text, "\r", "\n") - re := regexp.MustCompile(`\n{2,}`) - text = re.ReplaceAllString(text, "\n") + text = reMultipleNewlines.ReplaceAllString(text, "\n") } ... if o.softLineBreakMerging { ... - sentenceEnd := regexp.MustCompile(`[.!?][\s]*$`) for i, line := range lines { ... - if i == len(lines)-1 || sentenceEnd.MatchString(line) { + if i == len(lines)-1 || reSentenceEnd.MatchString(line) { merged = append(merged, current.String()) current.Reset() } } ... }Also applies to: 102-102
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/chunk/preprocess.go` around lines 73 - 74, The two regexes currently compiled inside Execute (e.g., re := regexp.MustCompile(`\n{2,}`) and the regex on line ~102) should be hoisted to package-level var(s) so they are compiled once; create package-level variables like collapseNewlinesRe and whatever the second regex represents (e.g., trimSpacesRe) using regexp.MustCompile(...) at top-level and replace the local regexp.MustCompile calls inside Execute with these variables (update usages in preprocess.go/Execute to reference collapseNewlinesRe and the other package-level re).internal/ingestion/chunk/type.go (1)
21-22: 💤 Low valueMisleading docstring for
Preparemethod.The comment says "Prepare configures the operator from a DSL stage config map" but
Preparereceives a*ChunkContext, not a config map. Configuration actually happens in the constructors (NewPreprocessOperator, etc.). Consider updating to something like "Prepare initializes operator state before execution."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/chunk/type.go` around lines 21 - 22, The docstring for the Prepare method is misleading: it claims Prepare "configures the operator from a DSL stage config map" but Prepare(ctx *ChunkContext) does not accept a config map and configuration is done in constructors like NewPreprocessOperator; update the comment on Prepare to accurately describe its purpose (e.g., "Prepare initializes operator state before execution" or "Prepare performs any runtime initialization using the provided ChunkContext") and ensure related constructors (NewPreprocessOperator, etc.) remain the documented place for configuration.
🤖 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/cli/cli.go`:
- Around line 1212-1217: printHelp() does not list the "\pwd" meta-command even
though handleMetaCommand implements it, making it undiscoverable in the
interactive help; update the help text generation in printHelp() to include an
entry for "\pwd" (matching the description used in handleMetaCommand) so users
see it in the CLI help output and can learn it from the interactive help.
In `@internal/cli/response.go`:
- Around line 551-556: ExplainResponse.PrintOut currently prints only the error
code on failure and drops r.Message; change the error branch in
ExplainResponse.PrintOut to include the failure message as well (e.g., print
both the code and r.Message such as "ERROR %d: %s\n" or similar) so failures
preserve the actual reason while keeping the existing successful-path behavior
when r.Code == 0.
In `@internal/cli/user_command.go`:
- Around line 3449-3504: The code unconditionally overwrites the user-facing
payload by setting result.Message = fmt.Sprintf("Success to chunk %s", filename)
at the end; instead, preserve the explain or chunk output placed into
result.Message and only set the generic success string when no other payload was
produced. Concretely: when explain is true assign engine.Explain(plan) to
result.Message and return (or skip the final overwrite); when running
engine.Execute(plan, ...) render chunkContext.ResultChunks into result.Message
(or a new field result.Chunks) rather than printing to stdout, and remove or
conditionalize the final assignment to result.Message so it only runs when
result.Message is empty. Update references: result.Message, engine.Explain,
engine.Execute, chunkContext.ResultChunks, and the final result.Message
assignment.
In `@internal/ingestion/chunk/expression.go`:
- Around line 438-447: CompileExpression currently re-panics on parse failures
which prevents callers (like the constructor in postprocess.go) from receiving
errors and leads to nil Condition and later dereference crashes in String;
change CompileExpression to catch parser panics and return a descriptive error
instead of panicking (e.g. recover and return fmt.Errorf("compile expression %q:
%v", exprStr, r)), update the parser entry (newParser/parse) signature if needed
to return (Expr, error) and propagate that error, then update the constructor in
postprocess.go (the function that calls CompileExpression at lines ~111-116) to
return or surface the error instead of silently ignoring it, and finally ensure
String() defensively handles a nil Condition (or relies on constructor to
guarantee non-nil) so no nil dereference can occur.
- Around line 489-527: The evalBinary function currently evaluates both operands
up front (via eval(e.left, vars) and eval(e.right, vars)), preventing true
short-circuiting; change evalBinary so it evaluates only the left operand first
(call eval on e.left), then for tokenAnd/tokenOr decide whether to call eval on
e.right based on the left value (for AND: if left is false return false without
evaluating e.right; for OR: if left is true return true without evaluating
e.right), using toBool to validate types and returning appropriate errors when a
needed operand is non-boolean; keep existing behavior for other ops but ensure
you no longer call eval(e.right, vars) before the switch.
In `@internal/ingestion/chunk/postprocess.go`:
- Line 276: In mergeChunks, the logic mixes rune counts and byte counts which
breaks merging for multi-byte characters: change all length math to use rune
counts consistently (e.g., replace len([]rune(c.Content)) and any uses of
buf.Len() added to nextLen with utf8.RuneCountInString equivalents or
consistently computed rune lengths), update the comparisons that use target to
compare against rune counts, and adjust nextLen accumulation to add rune counts
(not bytes) for the buffer; touch symbols mergeChunks, c.Content, target,
nextLen, and buf.Len()/buf to ensure all length checks and additions use rune
counts.
In `@internal/ingestion/chunk/preprocess.go`:
- Line 102: The sentence-end regex defined as sentenceEnd in preprocess.go only
matches ASCII punctuation and misses CJK sentence terminators; update the
pattern to include full-width CJK sentence-ending marks (e.g., '。', '?', '!' and
any variants) and still allow trailing whitespace before end-of-string so CJK
sentences are detected the same way as Latin ones; modify the regexp used to
construct sentenceEnd accordingly (preserving the use site in the preprocess
logic).
- Around line 126-133: The String() method of PreprocessOperator is missing the
softLineBreakMerging field in its output; update PreprocessOperator.String() to
include a formatted line for o.softLineBreakMerging (e.g., similar to the other
fmt.Fprintf lines) so all four config options are printed, referencing the
PreprocessOperator type and its softLineBreakMerging field.
In `@internal/ingestion/chunk/split.go`:
- Around line 171-186: splitByParagraph currently sets ChunkData.Index to the
loop variable i which creates non-contiguous indices when empty paragraphs are
skipped; change it to assign Index using the current length of the chunks slice
(e.g., len(chunks) before append) so indices are sequential; update the append
in splitByParagraph to set Index to the sequential value and keep other fields
(Content, Metadata via DetectLanguage) unchanged.
- Around line 157-169: splitByChar in SplitOperator is performing DetectLanguage
on the shrinking suffix each loop causing O(n²) work and incorrect per-chunk
language; fix by computing the language once per rune (or once for full text
depending on desired behavior) and pass the single-rune string to DetectLanguage
(or precompute a single language value) and then create ChunkData with that
language in Metadata. Locate splitByChar and change the DetectLanguage call to
use the single-character string (string(r)) or a precomputed language variable,
ensuring ChunkData.Metadata["language"] is set from that value and not from the
remaining text, which removes the quadratic cost.
---
Nitpick comments:
In `@internal/ingestion/chunk_engine_test.go`:
- Around line 231-295: Add concrete assertions to the tests to verify pipeline
semantics rather than only non-error behavior: in TestPlan_Execute_FullPipeline
and TestPlan_Execute_MinimalPipeline assert stable invariants on
ctx.ResultChunks (e.g., expected number of chunks or min count, specific
chunk.Content prefixes, presence of required metadata keys like "source"/"index"
and their types, and that chunk indices are monotonically increasing) by
inspecting ctx.ResultChunks and c.Metadata; in TestPlan_Explain call
engine.Explain(plan) and assert the returned explanation string contains
expected operator names (e.g., the media-aware operators used in mediaAwareDSL
and the minimal operators used in minimalDSL) and key phrases so regressions
that remove or reorder operators fail. Use the existing symbols NewChunkEngine,
Compile, Execute, Explain, ctx.ResultChunks, and c.Metadata to locate where to
add these assertions.
In `@internal/ingestion/chunk/expression.go`:
- Around line 648-649: Remove the unused math import workaround: delete the `var
_ = math.NaN` line and remove the corresponding `import "math"` from the imports
so the compiler no longer sees an unused import; ensure no other references to
`math` remain in the file (search for `math.`) before committing the change.
In `@internal/ingestion/chunk/preprocess.go`:
- Around line 73-74: The two regexes currently compiled inside Execute (e.g., re
:= regexp.MustCompile(`\n{2,}`) and the regex on line ~102) should be hoisted to
package-level var(s) so they are compiled once; create package-level variables
like collapseNewlinesRe and whatever the second regex represents (e.g.,
trimSpacesRe) using regexp.MustCompile(...) at top-level and replace the local
regexp.MustCompile calls inside Execute with these variables (update usages in
preprocess.go/Execute to reference collapseNewlinesRe and the other
package-level re).
In `@internal/ingestion/chunk/type.go`:
- Around line 21-22: The docstring for the Prepare method is misleading: it
claims Prepare "configures the operator from a DSL stage config map" but
Prepare(ctx *ChunkContext) does not accept a config map and configuration is
done in constructors like NewPreprocessOperator; update the comment on Prepare
to accurately describe its purpose (e.g., "Prepare initializes operator state
before execution" or "Prepare performs any runtime initialization using the
provided ChunkContext") and ensure related constructors (NewPreprocessOperator,
etc.) remain the documented place for configuration.
🪄 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: 9ec7a725-7d9a-40c0-a76f-5b72a43cd6e0
📒 Files selected for processing (11)
internal/cli/cli.gointernal/cli/response.gointernal/cli/user_command.gointernal/ingestion/chunk/expression.gointernal/ingestion/chunk/postprocess.gointernal/ingestion/chunk/preprocess.gointernal/ingestion/chunk/split.gointernal/ingestion/chunk/type.gointernal/ingestion/chunk_engine.gointernal/ingestion/chunk_engine_test.gointernal/ingestion/ingestion_service.go
| case "pwd": | ||
| dir, err := os.Getwd() | ||
| if err != nil { | ||
| return fmt.Errorf("get working directory: %w", err) | ||
| } | ||
| fmt.Println(dir) |
There was a problem hiding this comment.
Document \pwd in the interactive help.
handleMetaCommand supports \pwd, but printHelp() doesn't list it, so the new command is effectively undiscoverable from inside the CLI.
🤖 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/cli/cli.go` around lines 1212 - 1217, printHelp() does not list the
"\pwd" meta-command even though handleMetaCommand implements it, making it
undiscoverable in the interactive help; update the help text generation in
printHelp() to include an entry for "\pwd" (matching the description used in
handleMetaCommand) so users see it in the CLI help output and can learn it from
the interactive help.
| func (r *ExplainResponse) PrintOut() { | ||
| if r.Code == 0 { | ||
| fmt.Printf("\n%s\n", r.Message) | ||
| } else { | ||
| fmt.Printf("ERROR %d\n", r.Code) | ||
| } |
There was a problem hiding this comment.
Include the failure message in ExplainResponse.PrintOut().
The error branch drops r.Message, so explain failures lose the actual reason while most other response types in this file preserve it.
Suggested fix
func (r *ExplainResponse) PrintOut() {
if r.Code == 0 {
fmt.Printf("\n%s\n", r.Message)
} else {
- fmt.Printf("ERROR %d\n", r.Code)
+ fmt.Printf("ERROR %d, %s\n", r.Code, r.Message)
}
}📝 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 (r *ExplainResponse) PrintOut() { | |
| if r.Code == 0 { | |
| fmt.Printf("\n%s\n", r.Message) | |
| } else { | |
| fmt.Printf("ERROR %d\n", r.Code) | |
| } | |
| func (r *ExplainResponse) PrintOut() { | |
| if r.Code == 0 { | |
| fmt.Printf("\n%s\n", r.Message) | |
| } else { | |
| fmt.Printf("ERROR %d, %s\n", r.Code, r.Message) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/response.go` around lines 551 - 556, ExplainResponse.PrintOut
currently prints only the error code on failure and drops r.Message; change the
error branch in ExplainResponse.PrintOut to include the failure message as well
(e.g., print both the code and r.Message such as "ERROR %d: %s\n" or similar) so
failures preserve the actual reason while keeping the existing successful-path
behavior when r.Code == 0.
| var result ExplainResponse | ||
| start := time.Now() | ||
|
|
||
| filename, ok := cmd.Params["filename"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("filename not provided") | ||
| } | ||
| dsl, ok := cmd.Params["dsl"].(string) | ||
| dslFilename, ok := cmd.Params["dsl"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("dsl not provided") | ||
| } | ||
| dsl, err := os.ReadFile(dslFilename) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read dsl file: %w", err) | ||
| } | ||
|
|
||
| explain, ok := cmd.Params["explain"].(bool) | ||
| if !ok { | ||
| explain = false | ||
| } | ||
|
|
||
| engine := ingestion.NewChunkEngine() | ||
| plan, err := engine.Compile(string(dsl)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("compile failed: %w", err) | ||
| } | ||
|
|
||
| if explain { | ||
| fmt.Printf("Explain chunk file: %s, DSL: %s\n", filename, dsl) | ||
|
|
||
| explanation, err := engine.Explain(plan) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("explain error: %w", err) | ||
| } | ||
|
|
||
| result.Message = explanation | ||
| } else { | ||
| // TODO: not implemented | ||
| fmt.Printf("Chunk file: %s, DSL: %s\n", filename, dsl) | ||
| fileToChunking, err := os.ReadFile(filename) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read file: %w", err) | ||
| } | ||
|
|
||
| chunkContext, err := engine.Execute(plan, string(fileToChunking)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("chunking error: %w", err) | ||
| } | ||
|
|
||
| for _, resultChunk := range chunkContext.ResultChunks { | ||
| fmt.Printf("Chunk index: %d\n", resultChunk.Index) | ||
| fmt.Printf("Chunk size: %d\n", resultChunk.Size) | ||
| fmt.Printf("Chunk content: \n%s\n", resultChunk.Content) | ||
| } | ||
| } | ||
|
|
||
| var result SimpleResponse | ||
| result.Duration = time.Since(start).Seconds() | ||
| result.Code = 0 | ||
| result.Message = fmt.Sprintf("Success to chunk %s", filename) |
There was a problem hiding this comment.
Don't overwrite or bypass the chunk/explain payload.
Line 3483 stores the explanation in result.Message, but Line 3504 unconditionally replaces it with "Success to chunk ...", so explain chunk ... never shows the plan. The execute branch has the same contract break in reverse: it prints chunk data directly to stdout and then returns a response that prints the generic success string. Keep the rendered output in the response object and only fall back to a generic success message when there is no user-facing payload.
Suggested fix
var result ExplainResponse
start := time.Now()
@@
if explain {
-
explanation, err := engine.Explain(plan)
if err != nil {
return nil, fmt.Errorf("explain error: %w", err)
}
-
result.Message = explanation
} else {
fileToChunking, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
chunkContext, err := engine.Execute(plan, string(fileToChunking))
if err != nil {
return nil, fmt.Errorf("chunking error: %w", err)
}
+ var out strings.Builder
for _, resultChunk := range chunkContext.ResultChunks {
- fmt.Printf("Chunk index: %d\n", resultChunk.Index)
- fmt.Printf("Chunk size: %d\n", resultChunk.Size)
- fmt.Printf("Chunk content: \n%s\n", resultChunk.Content)
+ fmt.Fprintf(&out, "Chunk index: %d\n", resultChunk.Index)
+ fmt.Fprintf(&out, "Chunk size: %d\n", resultChunk.Size)
+ fmt.Fprintf(&out, "Chunk content:\n%s\n", resultChunk.Content)
}
+ result.Message = out.String()
}
result.Duration = time.Since(start).Seconds()
result.Code = 0
- result.Message = fmt.Sprintf("Success to chunk %s", filename)
+ if result.Message == "" {
+ result.Message = fmt.Sprintf("Success to chunk %s", filename)
+ }
return &result, 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/cli/user_command.go` around lines 3449 - 3504, The code
unconditionally overwrites the user-facing payload by setting result.Message =
fmt.Sprintf("Success to chunk %s", filename) at the end; instead, preserve the
explain or chunk output placed into result.Message and only set the generic
success string when no other payload was produced. Concretely: when explain is
true assign engine.Explain(plan) to result.Message and return (or skip the final
overwrite); when running engine.Execute(plan, ...) render
chunkContext.ResultChunks into result.Message (or a new field result.Chunks)
rather than printing to stdout, and remove or conditionalize the final
assignment to result.Message so it only runs when result.Message is empty.
Update references: result.Message, engine.Explain, engine.Execute,
chunkContext.ResultChunks, and the final result.Message assignment.
| // CompileExpression parses an expression string into a reusable AST. | ||
| func CompileExpression(exprStr string) (Expr, error) { | ||
| defer func() { | ||
| if r := recover(); r != nil { | ||
| panic(fmt.Sprintf("compile expression %q: %v", exprStr, r)) | ||
| } | ||
| }() | ||
| p := newParser(exprStr) | ||
| return p.parse(), nil | ||
| } |
There was a problem hiding this comment.
Expression compilation error handling chain in expression.go and postprocess.go.
The root cause is CompileExpression (in expression.go) re-panicking instead of returning errors. This cascades into postprocess.go: the constructor at lines 111-116 silently ignores compile failures (leaving Condition nil), and String() at line 218 crashes when it dereferences that nil. Fixing CompileExpression to return proper errors enables the constructor to propagate them, which then removes the nil-condition scenario that causes the crash.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/expression.go` around lines 438 - 447,
CompileExpression currently re-panics on parse failures which prevents callers
(like the constructor in postprocess.go) from receiving errors and leads to nil
Condition and later dereference crashes in String; change CompileExpression to
catch parser panics and return a descriptive error instead of panicking (e.g.
recover and return fmt.Errorf("compile expression %q: %v", exprStr, r)), update
the parser entry (newParser/parse) signature if needed to return (Expr, error)
and propagate that error, then update the constructor in postprocess.go (the
function that calls CompileExpression at lines ~111-116) to return or surface
the error instead of silently ignoring it, and finally ensure String()
defensively handles a nil Condition (or relies on constructor to guarantee
non-nil) so no nil dereference can occur.
| func evalBinary(e binaryExpr, vars map[string]interface{}) (interface{}, error) { | ||
| left, err := eval(e.left, vars) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| right, err := eval(e.right, vars) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| switch e.op { | ||
| case tokenAnd: | ||
| l, ok := toBool(left) | ||
| if !ok { | ||
| return false, fmt.Errorf("AND requires boolean left operand") | ||
| } | ||
| if !l { | ||
| return false, nil | ||
| } | ||
| r, ok := toBool(right) | ||
| if !ok { | ||
| return false, fmt.Errorf("AND requires boolean right operand") | ||
| } | ||
| return r, nil | ||
|
|
||
| case tokenOr: | ||
| l, ok := toBool(left) | ||
| if !ok { | ||
| return false, fmt.Errorf("OR requires boolean left operand") | ||
| } | ||
| if l { | ||
| return true, nil | ||
| } | ||
| r, ok := toBool(right) | ||
| if !ok { | ||
| return false, fmt.Errorf("OR requires boolean right operand") | ||
| } | ||
| return r, nil | ||
|
|
There was a problem hiding this comment.
AND/OR evaluation is not short-circuiting despite the control flow.
Both operands are evaluated via eval(e.right, vars) before the switch statement, so expressions like false AND undefined_var will error out even though short-circuit semantics would skip evaluating the right side. If users write expressions relying on short-circuit behavior to guard against undefined variables, they'll get unexpected errors.
♻️ Proposed fix for true short-circuit evaluation
func evalBinary(e binaryExpr, vars map[string]interface{}) (interface{}, error) {
left, err := eval(e.left, vars)
if err != nil {
return nil, err
}
- right, err := eval(e.right, vars)
- if err != nil {
- return nil, err
- }
switch e.op {
case tokenAnd:
l, ok := toBool(left)
if !ok {
return false, fmt.Errorf("AND requires boolean left operand")
}
if !l {
return false, nil
}
+ right, err := eval(e.right, vars)
+ if err != nil {
+ return nil, err
+ }
r, ok := toBool(right)
if !ok {
return false, fmt.Errorf("AND requires boolean right operand")
}
return r, nil
case tokenOr:
l, ok := toBool(left)
if !ok {
return false, fmt.Errorf("OR requires boolean left operand")
}
if l {
return true, nil
}
+ right, err := eval(e.right, vars)
+ if err != nil {
+ return nil, err
+ }
r, ok := toBool(right)
if !ok {
return false, fmt.Errorf("OR requires boolean right operand")
}
return r, nil
case tokenEq:
+ right, err := eval(e.right, vars)
+ if err != nil {
+ return nil, err
+ }
return compareEq(left, right), nil
case tokenNeq:
+ right, err := eval(e.right, vars)
+ if err != nil {
+ return nil, err
+ }
return !compareEq(left, right), nil
case tokenGt, tokenLt, tokenGte, tokenLte:
+ right, err := eval(e.right, vars)
+ if err != nil {
+ return nil, err
+ }
return compareOrder(left, right, e.op)
default:
return false, fmt.Errorf("unknown binary op %d", e.op)
}
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/expression.go` around lines 489 - 527, The
evalBinary function currently evaluates both operands up front (via eval(e.left,
vars) and eval(e.right, vars)), preventing true short-circuiting; change
evalBinary so it evaluates only the left operand first (call eval on e.left),
then for tokenAnd/tokenOr decide whether to call eval on e.right based on the
left value (for AND: if left is false return false without evaluating e.right;
for OR: if left is true return true without evaluating e.right), using toBool to
validate types and returning appropriate errors when a needed operand is
non-boolean; keep existing behavior for other ops but ensure you no longer call
eval(e.right, vars) before the switch.
|
|
||
| for i, c := range chunks { | ||
| // If this single chunk already exceeds target, flush first then add | ||
| if len([]rune(c.Content)) >= target { |
There was a problem hiding this comment.
Inconsistent byte vs rune counting in mergeChunks.
Line 276 compares len([]rune(c.Content)) (rune count) against target, but line 298 adds buf.Len() (byte count) to nextLen (rune count). For CJK text where each character is 3 bytes, this causes incorrect merge decisions. Use consistent units throughout.
🐛 Proposed fix to use consistent rune counting
func (o *PostprocessOperator) mergeChunks(chunks []ChunkData) []ChunkData {
target := o.merge.TargetSize
if target <= 0 {
target = 500
}
var merged []ChunkData
var buf strings.Builder
var bufMeta map[string]interface{}
+ var bufRuneLen int
firstIndex := 0
for i, c := range chunks {
+ contentRuneLen := len([]rune(c.Content))
// If this single chunk already exceeds target, flush first then add
- if len([]rune(c.Content)) >= target {
- if buf.Len() > 0 {
+ if contentRuneLen >= target {
+ if bufRuneLen > 0 {
merged = append(merged, ChunkData{
Content: buf.String(),
Index: firstIndex,
Metadata: bufMeta,
})
buf.Reset()
bufMeta = nil
+ bufRuneLen = 0
}
merged = append(merged, c)
firstIndex = i + 1
continue
}
- if buf.Len() == 0 {
+ if bufRuneLen == 0 {
buf.WriteString(c.Content)
bufMeta = c.Metadata
firstIndex = c.Index
+ bufRuneLen = contentRuneLen
} else {
- nextLen := len([]rune(c.Content))
// If adding this chunk would exceed target, flush current and start new
- if buf.Len()+nextLen+1 > target {
+ if bufRuneLen+contentRuneLen+1 > target {
merged = append(merged, ChunkData{
Content: buf.String(),
Index: firstIndex,
Metadata: bufMeta,
})
buf.Reset()
buf.WriteString(c.Content)
bufMeta = c.Metadata
firstIndex = c.Index
+ bufRuneLen = contentRuneLen
} else {
buf.WriteString(" ")
buf.WriteString(c.Content)
+ bufRuneLen += contentRuneLen + 1
// Merge metadata ...Also applies to: 296-298
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/postprocess.go` at line 276, In mergeChunks, the
logic mixes rune counts and byte counts which breaks merging for multi-byte
characters: change all length math to use rune counts consistently (e.g.,
replace len([]rune(c.Content)) and any uses of buf.Len() added to nextLen with
utf8.RuneCountInString equivalents or consistently computed rune lengths),
update the comparisons that use target to compare against rune counts, and
adjust nextLen accumulation to add rune counts (not bytes) for the buffer; touch
symbols mergeChunks, c.Content, target, nextLen, and buf.Len()/buf to ensure all
length checks and additions use rune counts.
| var merged []string | ||
| var current strings.Builder | ||
|
|
||
| sentenceEnd := regexp.MustCompile(`[.!?][\s]*$`) |
There was a problem hiding this comment.
Sentence-end pattern misses CJK punctuation.
The regex [.!?][\s]*$ only matches English punctuation. For consistent behavior with CJK text (used in tests), include Chinese/Japanese sentence-ending marks.
🐛 Proposed fix
- sentenceEnd := regexp.MustCompile(`[.!?][\s]*$`)
+ sentenceEnd := regexp.MustCompile(`[.!?。!?][\s]*$`)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/preprocess.go` at line 102, The sentence-end regex
defined as sentenceEnd in preprocess.go only matches ASCII punctuation and
misses CJK sentence terminators; update the pattern to include full-width CJK
sentence-ending marks (e.g., '。', '?', '!' and any variants) and still allow
trailing whitespace before end-of-string so CJK sentences are detected the same
way as Latin ones; modify the regexp used to construct sentenceEnd accordingly
(preserving the use site in the preprocess logic).
| func (o *PreprocessOperator) String() string { | ||
| var buf strings.Builder | ||
| buf.WriteString("preprocess:\n") | ||
| fmt.Fprintf(&buf, " normalize_newlines: %t\n", o.normalizeNewlines) | ||
| fmt.Fprintf(&buf, " strip_whitespace: %t\n", o.stripWhitespace) | ||
| fmt.Fprintf(&buf, " remove_empty_lines: %t\n", o.removeEmptyLines) | ||
| return buf.String() | ||
| } |
There was a problem hiding this comment.
String() omits softLineBreakMerging option.
The method prints 3 of 4 configuration options but doesn't include softLineBreakMerging.
🐛 Proposed fix
func (o *PreprocessOperator) String() string {
var buf strings.Builder
buf.WriteString("preprocess:\n")
fmt.Fprintf(&buf, " normalize_newlines: %t\n", o.normalizeNewlines)
fmt.Fprintf(&buf, " strip_whitespace: %t\n", o.stripWhitespace)
fmt.Fprintf(&buf, " remove_empty_lines: %t\n", o.removeEmptyLines)
+ fmt.Fprintf(&buf, " soft_line_break_merging: %t\n", o.softLineBreakMerging)
return buf.String()
}📝 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 (o *PreprocessOperator) String() string { | |
| var buf strings.Builder | |
| buf.WriteString("preprocess:\n") | |
| fmt.Fprintf(&buf, " normalize_newlines: %t\n", o.normalizeNewlines) | |
| fmt.Fprintf(&buf, " strip_whitespace: %t\n", o.stripWhitespace) | |
| fmt.Fprintf(&buf, " remove_empty_lines: %t\n", o.removeEmptyLines) | |
| return buf.String() | |
| } | |
| func (o *PreprocessOperator) String() string { | |
| var buf strings.Builder | |
| buf.WriteString("preprocess:\n") | |
| fmt.Fprintf(&buf, " normalize_newlines: %t\n", o.normalizeNewlines) | |
| fmt.Fprintf(&buf, " strip_whitespace: %t\n", o.stripWhitespace) | |
| fmt.Fprintf(&buf, " remove_empty_lines: %t\n", o.removeEmptyLines) | |
| fmt.Fprintf(&buf, " soft_line_break_merging: %t\n", o.softLineBreakMerging) | |
| return buf.String() | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/preprocess.go` around lines 126 - 133, The String()
method of PreprocessOperator is missing the softLineBreakMerging field in its
output; update PreprocessOperator.String() to include a formatted line for
o.softLineBreakMerging (e.g., similar to the other fmt.Fprintf lines) so all
four config options are printed, referencing the PreprocessOperator type and its
softLineBreakMerging field.
| func (o *SplitOperator) splitByChar(text string) []ChunkData { | ||
| var chunks []ChunkData | ||
| for len(text) > 0 { | ||
| r, size := utf8.DecodeRuneInString(text) | ||
| chunks = append(chunks, ChunkData{ | ||
| Content: string(r), | ||
| Index: len(chunks), | ||
| Metadata: map[string]interface{}{"language": DetectLanguage(text)}, | ||
| }) | ||
| text = text[size:] | ||
| } | ||
| return chunks | ||
| } |
There was a problem hiding this comment.
splitByChar has O(n²) complexity and incorrect language metadata.
DetectLanguage(text) is called on the remaining text (which shrinks each iteration), not on the single rune. This results in O(n²) work and metadata that varies per chunk based on the suffix rather than the character itself.
🐛 Proposed fix
func (o *SplitOperator) splitByChar(text string) []ChunkData {
var chunks []ChunkData
+ lang := DetectLanguage(text) // detect once for entire text
for len(text) > 0 {
r, size := utf8.DecodeRuneInString(text)
chunks = append(chunks, ChunkData{
Content: string(r),
Index: len(chunks),
- Metadata: map[string]interface{}{"language": DetectLanguage(text)},
+ Metadata: map[string]interface{}{"language": lang},
})
text = text[size:]
}
return chunks
}📝 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 (o *SplitOperator) splitByChar(text string) []ChunkData { | |
| var chunks []ChunkData | |
| for len(text) > 0 { | |
| r, size := utf8.DecodeRuneInString(text) | |
| chunks = append(chunks, ChunkData{ | |
| Content: string(r), | |
| Index: len(chunks), | |
| Metadata: map[string]interface{}{"language": DetectLanguage(text)}, | |
| }) | |
| text = text[size:] | |
| } | |
| return chunks | |
| } | |
| func (o *SplitOperator) splitByChar(text string) []ChunkData { | |
| var chunks []ChunkData | |
| lang := DetectLanguage(text) // detect once for entire text | |
| for len(text) > 0 { | |
| r, size := utf8.DecodeRuneInString(text) | |
| chunks = append(chunks, ChunkData{ | |
| Content: string(r), | |
| Index: len(chunks), | |
| Metadata: map[string]interface{}{"language": lang}, | |
| }) | |
| text = text[size:] | |
| } | |
| return chunks | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/split.go` around lines 157 - 169, splitByChar in
SplitOperator is performing DetectLanguage on the shrinking suffix each loop
causing O(n²) work and incorrect per-chunk language; fix by computing the
language once per rune (or once for full text depending on desired behavior) and
pass the single-rune string to DetectLanguage (or precompute a single language
value) and then create ChunkData with that language in Metadata. Locate
splitByChar and change the DetectLanguage call to use the single-character
string (string(r)) or a precomputed language variable, ensuring
ChunkData.Metadata["language"] is set from that value and not from the remaining
text, which removes the quadratic cost.
| func (o *SplitOperator) splitByParagraph(text string) []ChunkData { | ||
| paragraphs := strings.Split(text, "\n") | ||
| chunks := make([]ChunkData, 0, len(paragraphs)) | ||
| for i, p := range paragraphs { | ||
| trimmed := strings.TrimSpace(p) | ||
| if trimmed == "" { | ||
| continue | ||
| } | ||
| chunks = append(chunks, ChunkData{ | ||
| Content: trimmed, | ||
| Index: i, | ||
| Metadata: map[string]interface{}{"language": DetectLanguage(trimmed)}, | ||
| }) | ||
| } | ||
| return chunks | ||
| } |
There was a problem hiding this comment.
splitByParagraph uses inconsistent chunk indexing.
The Index is set to loop variable i, but empty paragraphs are skipped, creating gaps in the index sequence (e.g., 0, 2, 5). Other strategies use len(chunks) for sequential indices. This inconsistency could confuse downstream consumers expecting contiguous indices.
🐛 Proposed fix
func (o *SplitOperator) splitByParagraph(text string) []ChunkData {
paragraphs := strings.Split(text, "\n")
chunks := make([]ChunkData, 0, len(paragraphs))
- for i, p := range paragraphs {
+ for _, p := range paragraphs {
trimmed := strings.TrimSpace(p)
if trimmed == "" {
continue
}
chunks = append(chunks, ChunkData{
Content: trimmed,
- Index: i,
+ Index: len(chunks),
Metadata: map[string]interface{}{"language": DetectLanguage(trimmed)},
})
}
return chunks
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/chunk/split.go` around lines 171 - 186, splitByParagraph
currently sets ChunkData.Index to the loop variable i which creates
non-contiguous indices when empty paragraphs are skipped; change it to assign
Index using the current length of the chunks slice (e.g., len(chunks) before
append) so indices are sequential; update the append in splitByParagraph to set
Index to the sequential value and keep other fields (Content, Metadata via
DetectLanguage) unchanged.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15938 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
dsl.json
Type of change