Skip to content

Go: parse ingestion DSL - #15938

Merged
JinHai-CN merged 14 commits into
infiniflow:mainfrom
JinHai-CN:fix453
Jun 12, 2026
Merged

JinHai-CN merged 14 commits into
infiniflow:mainfrom
JinHai-CN:fix453

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(api/default)> explain chunk 'filename' with 'dsl.json';
Chunk Pipeline Plan:
......
RAGFlow(api/default)> chunk 'filename' with 'dsl.json';
Chunk file: filename, DSL: {
  "version": "1.0",
......
RAGFlow(api/default)> \pwd
/home/infiniflow/Documents/development/ragflow

dsl.json

{
  "version": "1.0",
  "name": "media_aware_chunking",
  "description": "Disable overlap when encountering image/video URLs",

  "pipeline": [
    {
      "operator": "preprocess",
      "normalize_newlines": true,
      "strip_whitespace": true,
      "remove_empty_lines": true,
      "soft_line_break_merging": true
    },

    {
      "operator": "split",
      "strategy": "sentence",
      "params": {
        "boundaries": [".\n", "!\n", "?\n"],
        "keep_separators": true
      }
    },

    {
      "operator": "postprocess",
      "merge": {
        "target_size": 500,
        "strategy": "greedy"
      },
      "filter": {
        "min_length": 10,
        "max_length": 12000
      },
      "add_metadata": {
        "include_index": true,
        "custom_fields": {
          "has_media_url": "auto_detect"
        }
      }
    }
  ]
}

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Text Chunking Pipeline Implementation

Layer / File(s) Summary
Core pipeline types
internal/ingestion/chunk/type.go
Foundation for all operators: Operator interface with lifecycle methods (Prepare, Execute, Finish), ChunkData struct for chunks with optional metadata, and ChunkContext for state passing through pipeline stages.
Boolean expression evaluator
internal/ingestion/chunk/expression.go
Lexer, recursive-descent parser, and AST evaluator supporting comparisons (=, !=, >, <, >=, <=) and boolean operators (AND, OR, NOT) with proper precedence; helpers for language detection (Han character ratio), rune counting, and URL pattern detection used in conditional overlap logic.
Preprocessing operator
internal/ingestion/chunk/preprocess.go
Configurable text normalization: newline canonicalization (\r\n/\r to \n), per-line whitespace trimming, empty line removal, and optional soft line-break merging based on sentence-ending punctuation patterns.
Splitting operator
internal/ingestion/chunk/split.go
Three configurable strategies for breaking preprocessed text into chunks: sentence-boundary-based splitting (with customizable boundaries), character-by-character (UTF-8 rune) splitting, and paragraph-based splitting; all output includes auto-detected language metadata.
Postprocessing operator
internal/ingestion/chunk/postprocess.go
Four-stage transformation pipeline: greedy chunk merging (concatenate up to target size), conditional overlap prepending (using expression evaluation against chunk variables), length-based filtering (min/max rune counts), and metadata enrichment with auto-detected fields (URL flags, language, rune count); reindexes and recalculates chunk sizes after transformations.
ChunkEngine and pipeline tests
internal/ingestion/chunk_engine.go, internal/ingestion/chunk_engine_test.go
ChunkEngine parses JSON DSL into ChunkPlan, instantiates operators, and executes the pipeline by calling lifecycle methods on each operator in sequence; includes DSL compilation tests, execution integration tests, error handling validation, edge case tests, and performance benchmarks for both compilation and execution.
CLI command integration
internal/cli/cli.go, internal/cli/response.go, internal/cli/user_command.go
Adds \pwd meta-command for displaying current working directory, introduces ExplainResponse type for chunk explain results, and rewrites ChunkCommand to read DSL from file, compile via ChunkEngine, conditionally run explain or execute against input file, and report duration and results.
License header
internal/ingestion/ingestion_service.go
Adds Apache 2.0 license header to ingestion service file.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • infiniflow/ragflow#15936: Adds ChunkCommand/EXPLAIN CHUNK CLI routing and parsing; this PR implements the actual engine execution path.
  • infiniflow/ragflow#15327: Modifies the same ChunkCommand execution path in user_command.go; integration point for chunking behavior.

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 Chunks of text now leap and bound,
Through preprocess, split around,
Overlap stitched with expressions true,
A pipeline built for parsing through,
DSL-driven, neat and sound! 📋✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding support for parsing an ingestion DSL in Go, which aligns with the substantial additions to chunk processing operators and the ChunkEngine implementation.
Description check ✅ Passed The description includes concrete CLI usage examples demonstrating the new functionality and a complete sample DSL configuration. However, it lacks the required 'Type of change' checkbox selection structure, though the intent (New Feature) is mentioned at the end.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 12, 2026 08:19
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 10

🧹 Nitpick comments (4)
internal/ingestion/chunk_engine_test.go (1)

231-295: ⚡ Quick win

Assert 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, and TestPlan_Explain doesn'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 win

Remove unused math import workaround.

The var _ = math.NaN line appears to be a leftover to satisfy the compiler, but math isn'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 win

Regex compiled on every Execute call—move to package level.

regexp.MustCompile is expensive. Lines 73 and 102 compile regexes inside Execute, 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 value

Misleading docstring for Prepare method.

The comment says "Prepare configures the operator from a DSL stage config map" but Prepare receives 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

📥 Commits

Reviewing files that changed from the base of the PR and between 22a058f and 13ca28e.

📒 Files selected for processing (11)
  • internal/cli/cli.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/ingestion/chunk/expression.go
  • internal/ingestion/chunk/postprocess.go
  • internal/ingestion/chunk/preprocess.go
  • internal/ingestion/chunk/split.go
  • internal/ingestion/chunk/type.go
  • internal/ingestion/chunk_engine.go
  • internal/ingestion/chunk_engine_test.go
  • internal/ingestion/ingestion_service.go

Comment thread internal/cli/cli.go
Comment on lines +1212 to +1217
case "pwd":
dir, err := os.Getwd()
if err != nil {
return fmt.Errorf("get working directory: %w", err)
}
fmt.Println(dir)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment thread internal/cli/response.go
Comment on lines +551 to +556
func (r *ExplainResponse) PrintOut() {
if r.Code == 0 {
fmt.Printf("\n%s\n", r.Message)
} else {
fmt.Printf("ERROR %d\n", r.Code)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +3449 to 3504
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +438 to +447
// 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +489 to +527
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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]*$`)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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

Comment on lines +126 to +133
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()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +157 to +169
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +171 to +186
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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

codecov Bot commented Jun 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (22a058f) to head (13ca28e).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 115b730 into infiniflow:main Jun 12, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant