Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

test: add text&code parser-to-chunker parity golden (#18311)

ming15236756b48f105d
diff --git a/internal/ingestion/component/chunker/testdata/textcode/python.en.golden.json b/internal/ingestion/component/chunker/testdata/textcode/python.en.golden.json
new file mode 100644
index 0000000000..0354f3108f
--- /dev/null
+++ b/internal/ingestion/component/chunker/testdata/textcode/python.en.golden.json
@@ -0,0 +1,16 @@
+{
+ "meta": {
+ "generator": "deepdoc.parser.txt_parser.RAGFlowTxtParser (parser._code)",
+ "sample": "internal/parser/parser/testdata/textcode.sample.en.txt",
+ "delimiter": "\n!?;。;!?",
+ "chunk_token_size": 128,
+ "keep_delimiters": true,
+ "comparison": "content-equivalent after delimiter removal and whitespace collapse"
+ },
+ "chunks": [
+ {
+ "text": "RAGFlow parses plain text and source code through the text&code family. This is the first English sentence. Here is a second sentence with more detail!\n Is this a question that the parser should handle?\nA blank line separates paragraphs. Semicolons also act as delimiters;\n this clause stays attached to the previous one. The parser keeps the trailing punctuation so sentence boundaries survive the split.\n\ndef greet(name):\n\n return f\"hello, {name}\"\n\ndef main():\n\n print(greet(\"world\"))\n\nLong code lines are kept as their own segments. The parser does not perform the token merge;\n the downstream chunker owns chunking per PARSER_ALIGNMENT_HANDOFF.md section 2.3.\n",
+ "doc_type_kwd": "text"
+ }
+ ]
+}
diff --git a/internal/ingestion/component/chunker/testdata/textcode/python.zh.golden.json b/internal/ingestion/component/chunker/testdata/textcode/python.zh.golden.json
new file mode 100644
index 0000000000..7434e232aa
--- /dev/null
+++ b/internal/ingestion/component/chunker/testdata/textcode/python.zh.golden.json
@@ -0,0 +1,16 @@
+{
+ "meta": {
+ "generator": "deepdoc.parser.txt_parser.RAGFlowTxtParser (parser._code)",
+ "sample": "internal/parser/parser/testdata/textcode.sample.zh.txt",
+ "delimiter": "\n!?;。;!?",
+ "chunk_token_size": 128,
+ "keep_delimiters": true,
+ "comparison": "content-equivalent after delimiter removal and whitespace collapse"
+ },
+ "chunks": [
+ {
+ "text": "这是第一段中文。\n逗号不是分隔符,但句号是!\n第二句以感叹号结尾?\n第三句以问号结尾。\n中文段落同样按默认分隔符切分。",
+ "doc_type_kwd": "text"
+ }
+ ]
+}
diff --git a/internal/ingestion/component/chunker/textcode_parity_test.go b/internal/ingestion/component/chunker/textcode_parity_test.go
new file mode 100644
index 0000000000..e7ba5a50b6
--- /dev/null
+++ b/internal/ingestion/component/chunker/textcode_parity_test.go
@@ -0,0 +1,158 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package chunker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+
+ "ragflow/internal/parser/parser"
+)
+
+const (
+ textCodeDelimiter = "\n!?;。;!?"
+ textCodeTokenSize = 128
+)
+
+type textCodeGolden struct {
+ Meta map[string]any `json:"meta"`
+ Chunks []map[string]any `json:"chunks"`
+}
+
+// TestTextParserTokenChunkerParity covers the production text&code handoff:
+// TextParser.ParseWithResult emits structured JSON items after splitting on
+// the text&code delimiters while keeping matched delimiters in the item text;
+// TokenChunker owns the final token-budget merge. The Python golden is
+// generated by the same TxtParser path used by parser._code; comparison
+// follows the parser alignment contract and ignores representation-only chunk
+// boundaries and whitespace.
+func TestTextParserTokenChunkerParity(t *testing.T) {
+ cases := []struct {
+ name string
+ samplePath string
+ goldenPath string
+ minChunks int
+ }{
+ {
+ name: "en",
+ samplePath: "../../../parser/parser/testdata/textcode.sample.en.txt",
+ goldenPath: "testdata/textcode/python.en.golden.json",
+ minChunks: 1,
+ },
+ {
+ name: "zh",
+ samplePath: "../../../parser/parser/testdata/textcode.sample.zh.txt",
+ goldenPath: "testdata/textcode/python.zh.golden.json",
+ minChunks: 1,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ sample, err := os.ReadFile(tc.samplePath)
+ if err != nil {
+ t.Fatalf("read sample: %v", err)
+ }
+ goldenRaw, err := os.ReadFile(tc.goldenPath)
+ if err != nil {
+ t.Fatalf("read golden: %v", err)
+ }
+ var golden textCodeGolden
+ if err := json.Unmarshal(goldenRaw, &golden); err != nil {
+ t.Fatalf("decode golden: %v", err)
+ }
+ if len(golden.Chunks) == 0 {
+ t.Fatal("golden has no chunks")
+ }
+
+ parsed := parser.NewTextParser().ParseWithResult(
+ t.Context(), tc.samplePath, sample,
+ )
+ if parsed.Err != nil {
+ t.Fatalf("TextParser.ParseWithResult: %v", parsed.Err)
+ }
+
+ component, err := NewTokenChunker(map[string]any{
+ "chunk_token_size": float64(textCodeTokenSize),
+ // Parser already consumed the text&code delimiters. An empty
+ // list makes this invocation exercise only the downstream merge.
+ "delimiters": []string{},
+ })
+ if err != nil {
+ t.Fatalf("NewTokenChunker: %v", err)
+ }
+ out, err := component.Invoke(context.Background(), nil, map[string]any{
+ "name": tc.samplePath,
+ "output_format": "json",
+ "json": parsed.JSON,
+ })
+ if err != nil {
+ t.Fatalf("TokenChunker.Invoke: %v", err)
+ }
+ if msg, ok := out["_ERROR"].(string); ok && msg != "" {
+ t.Fatalf("TokenChunker returned _ERROR: %s", msg)
+ }
+ got, ok := out["chunks"].([]map[string]any)
+ if !ok {
+ t.Fatalf("TokenChunker chunks has type %T", out["chunks"])
+ }
+ if len(got) < tc.minChunks {
+ t.Fatalf("final chunk count = %d, want at least %d", len(got), tc.minChunks)
+ }
+
+ wantText := normalizeTextCodeGolden(golden.Chunks, textCodeDelimiter)
+ gotText := normalizeTextCodeGolden(got, textCodeDelimiter)
+ if gotText != wantText {
+ t.Fatalf("text&code final chunks diverged:\n%s", textCodeDiff(gotText, wantText))
+ }
+ })
+ }
+}
+
+func normalizeTextCodeGolden(items []map[string]any, delimiter string) string {
+ parts := make([]string, 0, len(items))
+ for _, item := range items {
+ text, _ := item["text"].(string)
+ var normalized strings.Builder
+ for _, r := range text {
+ if strings.ContainsRune(delimiter, r) {
+ normalized.WriteByte(' ')
+ } else {
+ normalized.WriteRune(r)
+ }
+ }
+ if text := strings.Join(strings.Fields(normalized.String()), " "); text != "" {
+ parts = append(parts, text)
+ }
+ }
+ return strings.Join(parts, " ")
+}
+
+func textCodeDiff(got, want string) string {
+ const max = 2000
+ if len(got) > max {
+ got = got[:max] + "...(truncated)"
+ }
+ if len(want) > max {
+ want = want[:max] + "...(truncated)"
+ }
+ return fmt.Sprintf("--- GO ---\n%s\n--- PYTHON ---\n%s", got, want)
+}
diff --git a/internal/ingestion/component/chunker/tool-py/capture_textcode_golden.py b/internal/ingestion/component/chunker/tool-py/capture_textcode_golden.py
new file mode 100644
index 0000000000..425b1c3031
--- /dev/null
+++ b/internal/ingestion/component/chunker/tool-py/capture_textcode_golden.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Regenerate the Python text&code final-chunk parity goldens.
+
+Run from the repository root with the supported RAGFlow Python environment:
+
+ python internal/ingestion/component/chunker/tool-py/capture_textcode_golden.py
+
+The production ``parser._code`` path delegates text&code parsing to
+``RAGFlowTxtParser``. Calling that parser directly here keeps the fixture
+focused on its real output and avoids constructing a graph or starting a
+pipeline worker.
+"""
+
+from __future__ import annotations
+
+import json
+import importlib.util
+import logging
+import sys
+import types
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parents[4]
+SAMPLE_DIR = ROOT / "internal/parser/parser/testdata"
+GOLDEN_DIR = ROOT / "internal/ingestion/component/chunker/testdata/textcode"
+DELIMITER = "\n!?;。;!?"
+TOKEN_SIZE = 128
+
+
+def load_txt_parser():
+ """Load the production text parser without importing unrelated parsers.
+
+ ``deepdoc.parser.__init__`` eagerly registers every document parser. That
+ broad registry is unnecessary for this fixture and pulls in optional
+ native dependencies such as NumPy. Loading the two modules used by the
+ text parser keeps regeneration deterministic and still executes the
+ production ``RAGFlowTxtParser`` implementation.
+ """
+ sys.path.insert(0, str(ROOT))
+ deepdoc = sys.modules.setdefault("deepdoc", types.ModuleType("deepdoc"))
+ deepdoc.__path__ = [str(ROOT / "deepdoc")]
+ parser_pkg = types.ModuleType("deepdoc.parser")
+ parser_pkg.__path__ = [str(ROOT / "deepdoc/parser")]
+ sys.modules["deepdoc.parser"] = parser_pkg
+ for name in ("utils", "txt_parser"):
+ module_name = f"deepdoc.parser.{name}"
+ spec = importlib.util.spec_from_file_location(module_name, ROOT / "deepdoc/parser" / f"{name}.py")
+ if spec is None or spec.loader is None:
+ raise RuntimeError(f"cannot load {module_name}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return sys.modules["deepdoc.parser.txt_parser"].RAGFlowTxtParser
+
+
+def capture(name: str) -> dict:
+ sample_path = SAMPLE_DIR / f"textcode.sample.{name}.txt"
+ parser = load_txt_parser()
+ sections = parser()(str(sample_path), sample_path.read_bytes(), TOKEN_SIZE, DELIMITER, True)
+ return {
+ "meta": {
+ "generator": "deepdoc.parser.txt_parser.RAGFlowTxtParser (parser._code)",
+ "sample": str(sample_path.relative_to(ROOT)),
+ "delimiter": DELIMITER,
+ "chunk_token_size": TOKEN_SIZE,
+ "keep_delimiters": True,
+ "comparison": "content-equivalent after delimiter removal and whitespace collapse",
+ },
+ "chunks": [{"text": text, "doc_type_kwd": "text"} for text, _ in sections if text],
+ }
+
+
+def main() -> None:
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
+ GOLDEN_DIR.mkdir(parents=True, exist_ok=True)
+ for name in ("en", "zh"):
+ path = GOLDEN_DIR / f"python.{name}.golden.json"
+ result = capture(name)
+ path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ logging.info("wrote %s (%d chunks)", path.relative_to(ROOT), len(result["chunks"]))
+
+
+if __name__ == "__main__":
+ main()