Skip to content

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

55.9 KB
Raw Blame
//
//  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 (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"image"
	"image/color"
	"image/jpeg"
	"reflect"
	"strings"
	"testing"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zaptest/observer"

	"ragflow/internal/agent/runtime"
	"ragflow/internal/common"
	"ragflow/internal/entity"
	"ragflow/internal/ingestion/component/schema"
	"ragflow/internal/ingestion/task/indexdoc"
	parserlib "ragflow/internal/parser/parser"
	"ragflow/internal/parser/tableutil"
)

// spreadsheetSegmentItem builds one wire-format spreadsheet table segment:
// the markup the parser renders (captioned <table>, <th> header, <td> rows)
// plus the row-aligned positions matrix (one tuple per <tr>, header first).
// firstRow is the sheet row of the first DATA row; the header tuple covers
// firstRow-1. It emits the structured TableData contract a post-migration
// producer writes (caption = sheet name, header rows, data rows), not HTML
// markup.
func spreadsheetSegmentItem(sheet string, header []string, rows [][]string, sheetIndex, firstRow int) map[string]any {
	allRows := make([][]string, 0, len(rows)+1)
	if len(header) > 0 {
		allRows = append(allRows, header)
	}
	allRows = append(allRows, rows...)

	tuple := func(row int) []float64 {
		return []float64{float64(sheetIndex), float64(row), float64(row), 1, float64(len(header))}
	}
	matrix := [][]float64{tuple(firstRow - 1)}
	for i := range rows {
		matrix = append(matrix, tuple(firstRow+i))
	}
	tdGrid := make([][]entity.TableCell, 0, len(allRows))
	for _, r := range allRows {
		cells := make([]entity.TableCell, 0, len(r))
		for _, c := range r {
			cells = append(cells, entity.TableCell{Text: c})
		}
		tdGrid = append(tdGrid, cells)
	}
	td := &entity.TableData{Grid: tdGrid, HeaderRows: 1, Caption: sheet}
	return map[string]any{
		"table": map[string]any{
			"grid":        tdGrid,
			"header_rows": 1,
			"caption":     sheet,
		},
		// Mirror what the chunker derives from TableData (its HTML rendering)
		// so text-bound assertions (e.g. TokenChunker boundary tests) stay valid.
		"text":         tableutil.RenderTableHTML(td),
		"doc_type_kwd": "table",
		"sheet_index":  sheetIndex,
		"positions":    matrix,
	}
}

func TestSpreadsheetIndexPositionsStartWithDataRow(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1000})
	if err != nil {
		t.Fatal(err)
	}
	item := spreadsheetSegmentItem("Sheet1", []string{"Name"}, [][]string{{"Alice"}, {"Bob"}}, 1, 20)
	out, err := component.Invoke(t.Context(), nil, map[string]any{"name": "test.xlsx", "file_type": "xlsx", "output_format": "json", "json": []map[string]any{item}})
	if err != nil {
		t.Fatal(err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("got %d chunks", len(chunks))
	}
	want := [][]int{{1, 20, 20, 1, 1}, {1, 19, 19, 1, 1}, {1, 21, 21, 1, 1}}
	var previewPositions [][]int
	raw, err := json.Marshal(chunks[0]["positions"])
	if err != nil {
		t.Fatal(err)
	}
	if err := json.Unmarshal(raw, &previewPositions); err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(previewPositions, want) {
		t.Fatalf("chunk preview positions = %v, want data row first", previewPositions)
	}
	if _, err := indexdoc.ProcessChunksForPipeline(chunks, "doc", "test.xlsx", time.Now()); err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(chunks[0]["position_int"], want) {
		t.Fatalf("positions = %v, want %v", chunks[0]["position_int"], want)
	}
}

func TestSpreadsheetIndexPositionsKeepHeaderWhenNoData(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1000})
	if err != nil {
		t.Fatal(err)
	}
	item := spreadsheetSegmentItem("Sheet1", []string{"Name"}, nil, 1, 20)
	out, err := component.Invoke(t.Context(), nil, map[string]any{"name": "test.xlsx", "file_type": "xlsx", "output_format": "json", "json": []map[string]any{item}})
	if err != nil {
		t.Fatal(err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("got %d chunks", len(chunks))
	}
	if _, err := indexdoc.ProcessChunksForPipeline(chunks, "doc", "test.xlsx", time.Now()); err != nil {
		t.Fatal(err)
	}
	want := [][]int{{1, 19, 19, 1, 1}}
	if !reflect.DeepEqual(chunks[0]["position_int"], want) {
		t.Fatalf("positions = %v, want %v", chunks[0]["position_int"], want)
	}
}

func TestGeneralChunkerRegistered(t *testing.T) {
	factory, category, metadata, ok := runtime.DefaultRegistry.Lookup(ComponentNameGeneralChunker)
	if !ok {
		t.Fatal("GeneralChunker is not registered")
	}
	if category != runtime.CategoryIngestion {
		t.Errorf("category = %q, want %q", category, runtime.CategoryIngestion)
	}
	if factory == nil {
		t.Fatal("factory is nil")
	}
	if _, ok := metadata.Inputs["file_type"]; !ok {
		t.Error("registered inputs missing file_type")
	}
	component, err := factory(ComponentNameGeneralChunker, nil)
	if err != nil {
		t.Fatalf("factory: %v", err)
	}
	if component == nil {
		t.Fatal("factory returned nil component")
	}
}

func TestGeneralChunkerDefaults(t *testing.T) {
	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	general := component.(*GeneralChunkerComponent)
	if general.param.ChunkTokenSize != 512 {
		t.Errorf("ChunkTokenSize = %d, want 512", general.param.ChunkTokenSize)
	}
	if general.param.OverlappedPercent != 0 {
		t.Errorf("OverlappedPercent = %v, want 0", general.param.OverlappedPercent)
	}
	if general.param.TableContextSize != 0 || general.param.ImageContextSize != 0 {
		t.Errorf("context sizes = (%d, %d), want (0, 0)", general.param.TableContextSize, general.param.ImageContextSize)
	}
	if len(general.param.Delimiters) != 1 || general.param.Delimiters[0] != "\n" {
		t.Errorf("Delimiters = %q, want [newline]", general.param.Delimiters)
	}
	if len(general.param.ChildrenDelimiters) != 0 {
		t.Errorf("ChildrenDelimiters = %q, want empty", general.param.ChildrenDelimiters)
	}
}

func TestGeneralChunkerParamsNormalizeConfiguration(t *testing.T) {
	delimiters := []string{"\n", "`---`"}
	children := []any{". ", "! "}
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":    0,
		"delimiters":          delimiters,
		"overlapped_percent":  0.25,
		"children_delimiters": children,
		"table_context_size":  -2,
		"image_context_size":  7,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	general := component.(*GeneralChunkerComponent)
	if general.param.ChunkTokenSize != 0 {
		t.Errorf("ChunkTokenSize = %d, want 0", general.param.ChunkTokenSize)
	}
	if general.param.OverlappedPercent != 25 {
		t.Errorf("OverlappedPercent = %v, want 25", general.param.OverlappedPercent)
	}
	if got := strings.Join(general.param.Delimiters, "|"); got != "\n|`---`" {
		t.Errorf("Delimiters = %q", got)
	}
	if got := strings.Join(general.param.ChildrenDelimiters, "|"); got != ". |! " {
		t.Errorf("ChildrenDelimiters = %q", got)
	}
	if general.param.TableContextSize != 0 || general.param.ImageContextSize != 7 {
		t.Errorf("context sizes = (%d, %d), want (0, 7)", general.param.TableContextSize, general.param.ImageContextSize)
	}

	delimiters[0] = "changed"
	children[0] = "changed"
	if general.param.Delimiters[0] != "\n" || general.param.ChildrenDelimiters[0] != ". " {
		t.Fatal("component params retain caller-owned slices")
	}
}

func TestGeneralChunkerRejectsNegativeTokenBudget(t *testing.T) {
	if _, err := NewGeneralChunker(map[string]any{"chunk_token_size": -1}); err == nil {
		t.Fatal("NewGeneralChunker accepted a negative chunk_token_size")
	}
}

func TestGeneralChunkerNormalizesLegacyDelimiterString(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"delimiter": "\n!?;。;!?",
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	general := component.(*GeneralChunkerComponent)
	want := []string{"\n", "!", "?", ";", "。", ";", "!", "?"}
	if !reflect.DeepEqual(general.param.Delimiters, want) {
		t.Fatalf("Delimiters = %#v, want %#v", general.param.Delimiters, want)
	}
}

func TestGeneralStrategyForFileType(t *testing.T) {
	tests := []struct {
		fileType string
		want     generalStrategy
	}{
		{"pdf", generalStrategyPDF},
		{"docx", generalStrategyDOCX},
		{"md", generalStrategyMarkdown},
		{"xls", generalStrategySpreadsheet},
		{"xlsx", generalStrategySpreadsheet},
		{"csv", generalStrategySpreadsheet},
		{"txt", generalStrategyText},
		{"other", generalStrategyText},
	}
	for _, test := range tests {
		t.Run(test.fileType, func(t *testing.T) {
			if got := generalStrategyForFileType(test.fileType); got != test.want {
				t.Errorf("generalStrategyForFileType(%q) = %v, want %v", test.fileType, got, test.want)
			}
		})
	}
}

func TestGeneralChunkerLogsUnknownFileTypeFallback(t *testing.T) {
	core, logs := observer.New(zap.DebugLevel)
	originalLogger := common.Logger
	common.Logger = zap.New(core)
	t.Cleanup(func() { common.Logger = originalLogger })

	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	_, err = component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.bin",
		"file_type":     "application/x-custom",
		"output_format": "json",
		"json":          []map[string]any{{"text": "alpha", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke unknown file type: %v", err)
	}
	if logs.FilterMessage("GeneralChunker: unknown file_type; using text fallback").Len() != 1 {
		t.Fatalf("logs = %v, want unknown file_type fallback diagnostic", logs.All())
	}

	logs.TakeAll()
	_, err = component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.txt",
		"file_type":     "txt",
		"output_format": "json",
		"json":          []map[string]any{{"text": "alpha", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke canonical text file type: %v", err)
	}
	if logs.FilterMessage("GeneralChunker: unknown file_type; using text fallback").Len() != 0 {
		t.Fatalf("canonical text fallback emitted unknown-file diagnostic: %v", logs.All())
	}
}

func TestGeneralChunkerInfersFileTypeFromSourceName(t *testing.T) {
	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	_, err = component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.txt",
		"output_format": "json",
		"json":          []map[string]any{{"text": "alpha", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke inferred file type: %v", err)
	}
}

func TestGeneralChunkerRequiresFileTypeWhenSourceHasNoExtension(t *testing.T) {
	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	_, err = component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document",
		"output_format": "json",
		"json":          []map[string]any{{"text": "alpha", "doc_type_kwd": "text"}},
	})
	if err == nil || !strings.Contains(err.Error(), "file_type") {
		t.Fatalf("Invoke error = %v, want missing file_type error", err)
	}
}

func TestGeneralChunkerPreservesSingleParserUnit(t *testing.T) {
	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{{
			"text":          "alpha",
			"doc_type_kwd":  "text",
			"source_order":  3,
			"heading_level": 2,
		}},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks, ok := schema.ChunkCarrierToMaps(out["chunks"])
	if !ok || len(chunks) != 1 {
		t.Fatalf("chunks = %#v, want one chunk", out["chunks"])
	}
	if chunks[0]["text"] != "alpha" || chunks[0]["source_order"] != float64(3) || chunks[0]["heading_level"] != float64(2) {
		t.Errorf("single parser unit was not preserved: %#v", chunks[0])
	}
}

func TestGeneralChunkerMarkdownShortHeadingForcesNextUnit(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "Title", "doc_type_kwd": "text", "layout": "heading"},
			{"text": "body", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("chunks = %#v, want one forced heading/body chunk", chunks)
	}
	if text, _ := chunks[0]["text"].(string); text != "Title\nbody" {
		t.Errorf("text = %q, want %q", text, "Title\nbody")
	}
}

func TestGeneralChunkerMarkdownLongHeadingUsesNormalCap(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	longHeading := strings.Repeat("heading ", 60)
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": longHeading, "doc_type_kwd": "text", "layout": "heading"},
			{"text": "body", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 2 {
		t.Fatalf("chunks = %#v, want separate long heading and body chunks", chunks)
	}
	if text, _ := chunks[0]["text"].(string); text != strings.TrimSpace(longHeading) {
		t.Errorf("first text = %q, want long heading", text)
	}
	if text, _ := chunks[1]["text"].(string); text != "body" {
		t.Errorf("second text = %q, want body", text)
	}
}

func TestGeneralChunkerMarkdownImageMergesWithTextAndPreservesPayload(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "Title", "doc_type_kwd": "text", "layout": "heading"},
			{"text": "figure caption", "doc_type_kwd": "image", "image": "data:image/png;base64,AAAA"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("chunks = %#v, want one heading/image chunk", chunks)
	}
	if text, _ := chunks[0]["text"].(string); text != "Title\nfigure caption" {
		t.Errorf("text = %q, want %q", text, "Title\nfigure caption")
	}
	if image, _ := chunks[0]["image"].(string); image != "data:image/png;base64,AAAA" {
		t.Errorf("image = %q, want original image payload", image)
	}
}

func TestMergeMarkdownImagesStacksRasterPayloads(t *testing.T) {
	const pixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
	const secondPixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYPj/HwADAgH/5ncLrgAAAABJRU5ErkJggg=="
	got, ok := mergeMarkdownImagesChecked("data:image/png;base64,"+pixel, "data:image/png;base64,"+secondPixel)
	if !ok {
		t.Fatal("mergeMarkdownImagesChecked rejected valid PNG payloads")
	}
	decoded, ok := decodeMarkdownImage(got)
	if !ok {
		t.Fatalf("merged image is not decodable: %q", got)
	}
	if got := decoded.Bounds(); got.Dx() != 1 || got.Dy() != 2 {
		t.Fatalf("merged image bounds = %v, want 1x2", got)
	}
}

func TestDecodeMarkdownImageSupportsJPEGAndGIF(t *testing.T) {
	var jpegData bytes.Buffer
	img := image.NewRGBA(image.Rect(0, 0, 1, 1))
	img.Set(0, 0, color.RGBA{R: 255, A: 255})
	if err := jpeg.Encode(&jpegData, img, nil); err != nil {
		t.Fatalf("jpeg.Encode: %v", err)
	}
	cases := []struct {
		name string
		mime string
		data []byte
	}{
		{
			name: "jpeg",
			mime: "image/jpeg",
			data: jpegData.Bytes(),
		},
		{
			name: "gif",
			mime: "image/gif",
			data: mustDecodeBase64(t, "R0lGODdhAgACAIEAAP8AAAAAAAAAAAAAACwAAAAAAgACAAAIBgABCAQQEAA7"),
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			value := "data:" + tc.mime + ";base64," + base64.StdEncoding.EncodeToString(tc.data)
			if _, ok := decodeMarkdownImage(value); !ok {
				t.Fatalf("decodeMarkdownImage rejected %s payload", tc.mime)
			}
		})
	}
}

func mustDecodeBase64(t *testing.T, value string) []byte {
	t.Helper()
	decoded, err := base64.StdEncoding.DecodeString(value)
	if err != nil {
		t.Fatalf("DecodeString: %v", err)
	}
	return decoded
}

func TestMergeMarkdownImagesAcceptsBareBase64Payloads(t *testing.T) {
	const pixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
	const secondPixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYPj/HwADAgH/5ncLrgAAAABJRU5ErkJggg=="
	got, ok := mergeMarkdownImagesChecked(pixel, secondPixel)
	if !ok {
		t.Fatal("mergeMarkdownImagesChecked rejected bare base64 payloads")
	}
	decoded, ok := decodeMarkdownImage(got)
	if !ok {
		t.Fatalf("merged bare-base64 image is not decodable: %q", got)
	}
	if got := decoded.Bounds(); got.Dx() != 1 || got.Dy() != 2 {
		t.Fatalf("merged image bounds = %v, want 1x2", got)
	}
}

func TestMergeMarkdownImagesRejectsOversizedCanvas(t *testing.T) {
	if markdownImageWithinLimits(maxMarkdownImageDimension, maxMarkdownImageDimension) {
		t.Fatal("maximum-dimension canvas should exceed the pixel safety limit")
	}
	if !markdownImageWithinLimits(1024, 1024) {
		t.Fatal("normal image dimensions should remain mergeable")
	}
	if got, ok := mergeMarkdownImagesChecked("s3://bucket/first.png", "s3://bucket/second.png"); ok || got != "s3://bucket/first.png" {
		t.Fatalf("opaque image references were changed: %q", got)
	}
}

func TestGeneralChunkerMarkdownDoesNotDropUnmergeableImages(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 512})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "first", "doc_type_kwd": "image", "image": "s3://bucket/first.png"},
			{"text": "second", "doc_type_kwd": "image", "image": "s3://bucket/second.png"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 2 {
		t.Fatalf("chunks = %#v, want two chunks so neither image reference is lost", chunks)
	}
	if chunks[0]["image"] != "s3://bucket/first.png" || chunks[1]["image"] != "s3://bucket/second.png" {
		t.Fatalf("image references = %#v, want both source references", chunks)
	}
}

func TestGeneralChunkerMarkdownShortHeadingKeepsFollowingTableAtomic(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 1})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "Title", "doc_type_kwd": "text", "layout": "heading"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "body", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 2 {
		t.Fatalf("chunks = %#v, want table and body", chunks)
	}
	if text, _ := chunks[0]["text"].(string); text != "Title\n<table><tr><td>A</td></tr></table>" {
		t.Errorf("table text = %q", text)
	}
	if got := chunks[0]["doc_type_kwd"]; got != "table" {
		t.Errorf("table doc_type_kwd = %v, want table", got)
	}
}

func TestGeneralChunkerDOCXMediaDoesNotBreakTextMerge(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 10})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "", "doc_type_kwd": "image", "image": "figure"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 2 {
		t.Fatalf("chunks = %#v, want merged text and image", chunks)
	}
	if chunks[0]["text"] != "before\nafter" {
		t.Errorf("merged text = %q, want before\\nafter", chunks[0]["text"])
	}
	if chunks[1]["doc_type_kwd"] != "image" || chunks[1]["image"] != "figure" {
		t.Errorf("image chunk = %+v", chunks[1])
	}
}

// assertMaterializedMediaContext pins the chunker output contract for media
// chunks: the surrounding context is folded into the chunk body and the
// retrieval-only context fields are gone — the shape Python's chunker emits
// (rag/flow/chunker/token_chunker.py:343-359) and the shape the persisted
// content_with_weight and the chunk id are built from.
func assertMaterializedMediaContext(t *testing.T, chunk map[string]any, wantText string) {
	t.Helper()
	if got := chunk["text"]; got != wantText {
		t.Errorf("media chunk text = %q, want %q", got, wantText)
	}
	for _, key := range []string{"context_above", "context_below"} {
		if _, exists := chunk[key]; exists {
			t.Errorf("media chunk must not carry %s after materialization: %+v", key, chunk)
		}
	}
	// The folded body and its token count must agree: a media chunk is never
	// merged, so TKNums is a count of exactly this text.
	if count, ok := chunk["tk_nums"].(float64); !ok || count != float64(tokenizeStr(wantText)) {
		t.Errorf("media chunk tk_nums = %v, want %d (its own text)", chunk["tk_nums"], tokenizeStr(wantText))
	}
}

func TestGeneralChunkerMarkdownAttachesMediaContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	var table map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "table" {
			table = ck
			break
		}
	}
	if table == nil {
		t.Fatalf("table chunk missing: %#v", chunks)
	}
	assertMaterializedMediaContext(t, table, "before<table><tr><td>A</td></tr></table>after")
}

func TestGeneralChunkerMarkdownTableDoesNotDuplicateShortHeadingInContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "## Section", "doc_type_kwd": "text", "layout": "heading"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	var table map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "table" {
			table = ck
			break
		}
	}
	if table == nil {
		t.Fatalf("table chunk missing: %#v", chunks)
	}
	want := "## Section\n<table><tr><td>A</td></tr></table>"
	assertMaterializedMediaContext(t, table, want)
	if strings.Count(table["text"].(string), "## Section") != 1 {
		t.Fatalf("heading repeated in table chunk: %q", table["text"])
	}
}

func TestGeneralChunkerMarkdownTableKeepsEarlierContextWhenHeadingFolds(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 3,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "intro", "doc_type_kwd": "text"},
			{"text": "## Section", "doc_type_kwd": "text", "layout": "heading"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	var table map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "table" {
			table = ck
			break
		}
	}
	if table == nil {
		t.Fatalf("table chunk missing: %#v", chunks)
	}
	want := "intro## Section\n<table><tr><td>A</td></tr></table>"
	assertMaterializedMediaContext(t, table, want)
}

func TestGeneralChunkerMarkdownImageKeepsMediaContextWhenConfigured(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"image_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.md",
		"file_type":     "md",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "figure", "doc_type_kwd": "image", "image": "data:image/png;base64,AAAA"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	var image map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "image" {
			image = ck
			break
		}
	}
	if image == nil {
		t.Fatalf("image chunk missing: %#v", chunks)
	}
	assertMaterializedMediaContext(t, image, "beforefigureafter")
}

func TestGeneralChunkerHTMLAttachesMediaContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "page.html",
		"file_type":     "html",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	var table map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "table" {
			table = ck
			break
		}
	}
	if table == nil {
		t.Fatalf("table chunk missing: %#v", chunks)
	}
	assertMaterializedMediaContext(t, table, "before<table><tr><td>A</td></tr></table>after")
}

func TestGeneralChunkerDOCXAttachesMediaContextBeforeTextMerge(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 2 {
		t.Fatalf("chunks = %#v, want merged text and table", chunks)
	}
	if chunks[1]["doc_type_kwd"] != "table" {
		t.Fatalf("table chunk = %+v", chunks[1])
	}
	assertMaterializedMediaContext(t, chunks[1], "before<table><tr><td>A</td></tr></table>after")
}

func TestGeneralMediaContextSeparatesAdjacentSourceUnits(t *testing.T) {
	units := []schema.ChunkDoc{
		{Text: "before one", DocType: "text", TKNums: intPtr(1)},
		{Text: "before two", DocType: "text", TKNums: intPtr(1)},
		{Text: "", DocType: "table"},
		{Text: "after one", DocType: "text", TKNums: intPtr(1)},
		{Text: "after two", DocType: "text", TKNums: intPtr(1)},
	}

	if got, want := collectGeneralMediaContext(units, 2, 10, true, contextSentencePattern), "before one\nbefore two"; got != want {
		t.Fatalf("above context = %q, want %q", got, want)
	}
	if got, want := collectGeneralMediaContext(units, 2, 10, false, contextSentencePattern), "after one\nafter two"; got != want {
		t.Fatalf("below context = %q, want %q", got, want)
	}
}

func TestGeneralChunkerDOCXCustomDelimiterGroupsMultiParagraphRecords(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size": 512,
		"delimiters":       []string{"\n", "`问:`"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "问:first question", "doc_type_kwd": "text"},
			{"text": "名  称:item one", "doc_type_kwd": "text"},
			{"text": "答:first answer", "doc_type_kwd": "text"},
			{"text": "问:second question", "doc_type_kwd": "text"},
			{"text": "答:second answer", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	texts := outputTexts(t, out)
	if len(texts) != 2 {
		t.Fatalf("texts = %q, want two record chunks", texts)
	}
	// A custom delimiter is a split instruction, not content: the leading
	// record prefix is dropped (Python naive_merge_docx/_build_cks parity).
	if strings.Contains(texts[0], "问:") || !strings.Contains(texts[0], "first question") || !strings.Contains(texts[0], "名  称:item one") || !strings.Contains(texts[0], "答:first answer") {
		t.Fatalf("first record = %q", texts[0])
	}
	if strings.Contains(texts[1], "问:") || !strings.Contains(texts[1], "second question") || !strings.Contains(texts[1], "答:second answer") {
		t.Fatalf("second record = %q", texts[1])
	}
}

func TestGeneralChunkerDOCXDropsCustomDelimiterRecordPrefix(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size": 512,
		"delimiters":       []string{"`AAA`"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "first section", "doc_type_kwd": "text"},
			{"text": "AAA", "doc_type_kwd": "text"},
			{"text": "second section", "doc_type_kwd": "text"},
			{"text": "AAA", "doc_type_kwd": "text"},
			{"text": "before AAA after", "doc_type_kwd": "text"},
			{"text": "AAA", "doc_type_kwd": "text"},
			{"text": "third section", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	texts := outputTexts(t, out)
	for _, text := range texts {
		if strings.Contains(text, "AAA") {
			t.Fatalf("custom delimiter survived: %q", text)
		}
	}
	if !reflect.DeepEqual(texts, []string{"first section", "second section", "before", "after", "third section"}) {
		t.Fatalf("texts = %q", texts)
	}
}

func TestGeneralChunkerDOCXDropsTrailingDelimiterOnlyRecord(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   512,
		"overlapped_percent": 50,
		"delimiters":         []string{"`AAA`"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "AAAfirst", "doc_type_kwd": "text"},
			{"text": "AAA", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	// The delimiter-only record must not survive as an empty unit: overlap
	// would otherwise synthesize a spurious chunk from the previous tail.
	if texts := outputTexts(t, out); !reflect.DeepEqual(texts, []string{"first"}) {
		t.Fatalf("texts = %q, want [first]", texts)
	}
}

func TestGeneralChunkerDOCXPrefersDelimiterMatchBeforeTrimming(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size": 512,
		"delimiters":       []string{"`  A`", "`A123`"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json":          []map[string]any{{"text": "  A123hello", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	// The delimiter that includes the leading whitespace matches the original
	// text first, so "123" stays in the indexed content.
	if texts := outputTexts(t, out); !reflect.DeepEqual(texts, []string{"123hello"}) {
		t.Fatalf("texts = %q, want [123hello]", texts)
	}
}

func TestGroupDOCXUnitsByRecordBoundaryInactiveWithoutBoundary(t *testing.T) {
	units := []schema.ChunkDoc{
		{Text: "plain paragraph one", DocType: "text"},
		{Text: "plain paragraph two", DocType: "text"},
	}
	got, grouped := groupDOCXUnitsByRecordBoundary(units, []string{"问:"})
	if grouped {
		t.Fatal("grouping should stay inactive without a record boundary")
	}
	if !reflect.DeepEqual(got, units) {
		t.Fatalf("units = %#v, want unchanged %#v", got, units)
	}
}

func TestGeneralChunkerDOCXCustomDelimiterDisablesTextMerge(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size": 10,
		"delimiters":       []string{"`|`"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before|after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	if texts := outputTexts(t, out); !reflect.DeepEqual(texts, []string{"before", "after"}) {
		t.Fatalf("texts = %q, want custom-delimiter units", texts)
	}
}

func TestGeneralChunkerDOCXAppliesTextOverlap(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   2,
		"overlapped_percent": 50,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "alpha beta", "doc_type_kwd": "text"},
			{"text": "gamma delta", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	texts := outputTexts(t, out)
	if len(texts) != 2 {
		t.Fatalf("texts = %q, want two overlapped chunks", texts)
	}
	if texts[1] == "gamma delta" || !strings.HasSuffix(texts[1], "\ngamma delta") {
		t.Fatalf("DOCX overlap = %q, want previous tail plus current paragraph", texts[1])
	}
}

func TestGeneralChunkerChildrenDelimiterKeepsDelimiter(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"children_delimiters": []string{";"},
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.txt",
		"file_type":     "txt",
		"output_format": "json",
		"json":          []map[string]any{{"text": "part A;part B", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	if texts := outputTexts(t, out); !reflect.DeepEqual(texts, []string{"part A;", "part B"}) {
		t.Fatalf("children delimiter texts = %q, want [part A; part B]", texts)
	}
}

func TestGeneralChunkerPDFPreservesPhysicalOrderAroundMedia(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 10})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.pdf",
		"file_type":     "pdf",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want text, media, text in physical order", chunks)
	}
	if chunks[0]["doc_type_kwd"] != "text" || chunks[0]["text"] != "before" {
		t.Errorf("first chunk = %+v", chunks[0])
	}
	if chunks[1]["doc_type_kwd"] != "table" || chunks[1]["text"] != "<table><tr><td>A</td></tr></table>" {
		t.Errorf("media chunk = %+v", chunks[1])
	}
	if chunks[2]["doc_type_kwd"] != "text" || chunks[2]["text"] != "after" {
		t.Errorf("last chunk = %+v", chunks[2])
	}
}

func TestGeneralChunkerPDFUsesPositionOrderForMediaContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 1,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	position := func(top float64) []any {
		return []any{[]any{1.0, 0.0, 10.0, top, top + 5}}
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.pdf",
		"file_type":     "pdf",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "after", "doc_type_kwd": "text", "positions": position(30)},
			{"text": "<table>A</table>", "doc_type_kwd": "table", "positions": position(20)},
			{"text": "before", "doc_type_kwd": "text", "positions": position(10)},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want text, media, text", chunks)
	}
	assertMaterializedMediaContext(t, chunks[1], "before<table>A</table>after")
	if chunks[0]["text"] != "before" || chunks[2]["text"] != "after" {
		t.Errorf("position-ordered text = [%v, %v]", chunks[0]["text"], chunks[2]["text"])
	}
}

func TestSortPDFUnitsKeepsUnpositionedMediaInInputOrder(t *testing.T) {
	position := func(top float64) json.RawMessage {
		return json.RawMessage(fmt.Sprintf("[[1,0,10,%g,%g]]", top, top+5))
	}
	units := []schema.ChunkDoc{
		{Text: "before", DocType: "text", Positions: position(10)},
		{Text: "figure", DocType: "image"},
		{Text: "after", DocType: "text", Positions: position(30)},
	}

	got := sortPDFUnits(units)
	if texts := generalChunkTexts(got); !reflect.DeepEqual(texts, []string{"before", "figure", "after"}) {
		t.Fatalf("PDF units = %q, want unpositioned media to keep its input position", texts)
	}
}

func TestGeneralChunkerSpreadsheetHeaderOnlyPreservesHeaderChunk(t *testing.T) {
	component, err := NewGeneralChunker(nil)
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	item := spreadsheetSegmentItem("Sheet1", []string{"Name", "Amount"}, nil, 1, 1)
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "headers.xlsx",
		"file_type":     "xlsx",
		"output_format": "json",
		"json":          []map[string]any{item},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("chunks = %#v, want one header-only chunk", chunks)
	}
	text, _ := chunks[0]["text"].(string)
	if chunks[0]["doc_type_kwd"] != "table" || text == "" || !strings.Contains(text, "Name") || !strings.Contains(text, "Amount") {
		t.Fatalf("header-only chunk = %#v", chunks[0])
	}
}

func TestGeneralChunkerSpreadsheetAttachesImageContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   100,
		"image_context_size": 10,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "figures.xlsx",
		"file_type":     "xlsx",
		"output_format": "json",
		"json": []map[string]any{
			spreadsheetSegmentItem("Sheet1", []string{"Name"}, [][]string{{"Revenue"}}, 1, 2),
			{"text": "B2", "doc_type_kwd": "image", "image": "figure", "sheet_index": 1},
			spreadsheetSegmentItem("Sheet1", []string{"Name"}, [][]string{{"Growth"}}, 1, 3),
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want segment, image, segment", chunks)
	}
	if chunks[1]["doc_type_kwd"] != "image" {
		t.Fatalf("image chunk = %#v", chunks[1])
	}
	assertMaterializedMediaContext(t, chunks[1], "RevenueB2Growth")
}

func TestGeneralChunkerSpreadsheetImageContextStopsAtSheetBoundary(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 100, "image_context_size": 10})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "figures.xlsx",
		"file_type":     "xlsx",
		"output_format": "json",
		"json": []map[string]any{
			spreadsheetSegmentItem("Sheet1", []string{"Name"}, [][]string{{"Sheet one"}}, 1, 2),
			{"text": "B2", "doc_type_kwd": "image", "image": "figure", "sheet_index": 1},
			spreadsheetSegmentItem("Sheet2", []string{"Name"}, [][]string{{"Sheet two"}}, 2, 2),
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want segment, image, segment", chunks)
	}
	assertMaterializedMediaContext(t, chunks[1], "Sheet oneB2")
}

// TestGeneralChunkerSpreadsheetSplitsLargeSegmentIntoBoundedChunks pins the
// chunker-side size budget: a segment over ChunkTokenSize is cut into
// sub-tables that each replicate the header row and carry only their own
// rows' position tuples (R11). Without the cut a wide/long row runs past the
// embedding truncation point and its tail rows silently disappear.
func TestGeneralChunkerSpreadsheetSplitsLargeSegmentIntoBoundedChunks(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 20})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	var rows [][]string
	for i := 0; i < 6; i++ {
		rows = append(rows, []string{fmt.Sprintf("value-%d-with-some-padding", i)})
	}
	item := spreadsheetSegmentItem("Sheet1", []string{"Name"}, rows, 1, 2)
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "long.xlsx",
		"file_type":     "xlsx",
		"output_format": "json",
		"json":          []map[string]any{item},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) < 2 {
		t.Fatalf("chunks = %d, want the segment split under the token budget", len(chunks))
	}
	covered := 0
	for i, chunk := range chunks {
		// New contract: Text is the sub-table rendered as HTML (replicated
		// header + this part's data rows); the structured TableData is dropped
		// and never indexed; positions are sliced to this sub-table when the
		// matrix is row-aligned.
		if _, ok := chunk["table"]; ok {
			t.Fatalf("chunk %d still carries structured table", i)
		}
		text, _ := chunk["text"].(string)
		if !strings.Contains(text, "<table>") || !strings.Contains(text, "<th>Name</th>") {
			t.Fatalf("chunk %d text lost the header cell: %q", i, text)
		}
		// Single-column table: each data row is one <td>value-…</td> cell.
		dataRows := strings.Count(text, "<td>value-")
		if dataRows == 0 {
			t.Fatalf("chunk %d has no data rows: %q", i, text)
		}
		var matrix [][]float64
		raw, _ := json.Marshal(chunk["positions"])
		if err := json.Unmarshal(raw, &matrix); err != nil {
			t.Fatalf("chunk %d positions = %v, want a position matrix", i, chunk["positions"])
		}
		// One header tuple + this sub-table's own data tuples, never the
		// full segment matrix.
		if len(matrix) < 2 {
			t.Fatalf("chunk %d matrix = %v, want header plus data rows", i, matrix)
		}
		if matrix[1][1] != 1 {
			t.Errorf("chunk %d header tuple = %v, want sheet 1 row 1", i, matrix[1])
		}
		if dataRows != len(matrix)-1 {
			t.Errorf("chunk %d data rows %d != position tuples %d", i, dataRows, len(matrix)-1)
		}
		if _, err := indexdoc.ProcessChunksForPipeline([]map[string]any{chunk}, "doc", "long.xlsx", time.Now()); err != nil {
			t.Fatal(err)
		}
		indexed := chunk["position_int"].([][]int)
		if indexed[0][1] != covered+2 || indexed[1][1] != 1 {
			t.Fatalf("chunk %d indexed positions = %v, want first data row %d then header", i, indexed, covered+2)
		}
		covered += dataRows
	}
	if covered != len(rows) {
		t.Errorf("sub-tables cover %d data rows, want %d", covered, len(rows))
	}
}

// TestGeneralChunkerSpreadsheetDropsMisalignedPositionsOnSplit: when the
// matrix cannot be aligned one tuple per row, a split drops positions
// entirely rather than pointing every sub-table row at the full matrix (R1).
func TestGeneralChunkerSpreadsheetDropsMisalignedPositionsOnSplit(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 20})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	var rows [][]string
	for i := 0; i < 6; i++ {
		rows = append(rows, []string{fmt.Sprintf("value-%d-with-some-padding", i)})
	}
	item := spreadsheetSegmentItem("Sheet1", []string{"Name"}, rows, 1, 2)
	// One whole-segment tuple instead of the per-row matrix.
	item["positions"] = [][]float64{{1, 1, 7, 1, 1}}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "long.xlsx",
		"file_type":     "xlsx",
		"output_format": "json",
		"json":          []map[string]any{item},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) < 2 {
		t.Fatalf("chunks = %d, want the segment split under the token budget", len(chunks))
	}
	for i, chunk := range chunks {
		if _, exists := chunk["positions"]; exists {
			t.Errorf("chunk %d keeps a misaligned positions payload: %v", i, chunk["positions"])
		}
	}
}

// TestGeneralChunkerMediaContextReachesChunkIDAndIndexContent pins the
// downstream half of the fold: once the context is part of the chunk body, it
// is also part of the persisted content_with_weight and of the chunk id
// (ChunkID hashes the body). Python's chunker emits the merged body, so its
// id and stored content already carry the context; before the fold Go hashed
// and stored the bare media payload instead, which made the configured window
// invisible to both the chunk list and the index.
func TestGeneralChunkerMediaContextReachesChunkIDAndIndexContent(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   10,
		"table_context_size": 2,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before", "doc_type_kwd": "text"},
			{"text": "<table><tr><td>A</td></tr></table>", "doc_type_kwd": "table"},
			{"text": "after", "doc_type_kwd": "text"},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := indexdoc.NormalizeChunks(out)
	if _, err := indexdoc.ProcessChunksForPipeline(chunks, "doc-1", "document.docx", time.Now()); err != nil {
		t.Fatalf("ProcessChunksForPipeline: %v", err)
	}

	const wantText = "before<table><tr><td>A</td></tr></table>after"
	// The table chunk is selected by the STORED type column: doc_type_kwd is
	// the content-type contract and the index boundary keeps it.
	var table map[string]any
	for _, ck := range chunks {
		if ck["doc_type_kwd"] == "table" {
			table = ck
			break
		}
	}
	if table == nil {
		t.Fatalf("no table chunk in %#v", chunks)
	}
	if got := table["content_with_weight"]; got != wantText {
		t.Errorf("persisted content_with_weight = %q, want %q", got, wantText)
	}
	if got, want := table["id"], common.ChunkID("doc-1", wantText); got != want {
		t.Errorf("chunk id = %v, want %v (context must drive chunk identity)", got, want)
	}
}

// TestGeneralChunkerMediaContextStripsPositionTags pins the tag-stripping
// order Python uses: remove_tag runs on the merged body, so a position tag
// carried by a neighbouring text unit never reaches the stored media chunk.
// (The parser keeps boxes in the positions field, so this is a guard, not a
// re-strip of the media payload.)
func TestGeneralChunkerMediaContextStripsPositionTags(t *testing.T) {
	position := func(top float64) []any {
		return []any{[]any{1.0, 0.0, 10.0, top, top + 5}}
	}
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   512,
		"table_context_size": 20,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.pdf",
		"file_type":     "pdf",
		"output_format": "json",
		"json": []map[string]any{
			{"text": "before@@1\t0.0\t10.0\t10.0\t20.0##", "doc_type_kwd": "text", "positions": position(10)},
			{"text": "<table>A</table>", "doc_type_kwd": "table", "positions": position(20)},
			{"text": "after@@1\t0.0\t10.0\t10.0\t30.0\t35.0##", "doc_type_kwd": "text", "positions": position(30)},
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want text, media, text", chunks)
	}
	assertMaterializedMediaContext(t, chunks[1], "before<table>A</table>after")
}

func TestGeneralChunkerPDFAttachesOutlineOnce(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 10})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.pdf",
		"file_type":     "pdf",
		"output_format": "json",
		"file": map[string]any{
			"outline": []map[string]any{{"title": "Chapter 1", "level": 0}},
		},
		"json": []map[string]any{{"text": "body", "doc_type_kwd": "text"}},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 1 {
		t.Fatalf("chunks = %#v, want one chunk", chunks)
	}
	outline, ok := chunks[0]["__outline__"].([]any)
	if !ok || len(outline) != 1 {
		t.Fatalf("outline = %#v, want one entry", chunks[0]["__outline__"])
	}
	entry, _ := outline[0].(map[string]any)
	if entry["title"] != "Chapter 1" || entry["depth"] != float64(0) {
		t.Errorf("outline entry = %#v", entry)
	}
}

// TestGeneralChunkerNonSpreadsheetTableNotMediaContext: a table item without
// spreadsheet identity must not become a media-context source. The DOCX and
// PDF strategies share the collector, so reading their tables as context would
// change those documents' image chunks (and their chunk ids) as a side effect
// of the spreadsheet wire switch.
func TestGeneralChunkerNonSpreadsheetTableNotMediaContext(t *testing.T) {
	component, err := NewGeneralChunker(map[string]any{
		"chunk_token_size":   100,
		"image_context_size": 10,
	})
	if err != nil {
		t.Fatalf("NewGeneralChunker: %v", err)
	}
	table := map[string]any{
		"text":         "<table><caption>Doc</caption>\n<tr><th>Name</th></tr>\n<tr><td>Revenue</td></tr>\n</table>\n",
		"doc_type_kwd": "table",
	}
	out, err := component.Invoke(t.Context(), nil, map[string]any{
		"name":          "document.docx",
		"file_type":     "docx",
		"output_format": "json",
		"json": []map[string]any{
			table,
			{"text": "B2", "doc_type_kwd": "image", "image": "figure"},
			table,
		},
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) != 3 {
		t.Fatalf("chunks = %#v, want table, image, table", chunks)
	}
	if chunks[1]["doc_type_kwd"] != "image" {
		t.Fatalf("image chunk = %#v", chunks[1])
	}
	if got, _ := chunks[1]["text"].(string); got != "B2" {
		t.Errorf("image chunk text = %q, want B2 with no table text folded in", got)
	}
	for _, key := range []string{"context_above", "context_below"} {
		if _, exists := chunks[1][key]; exists {
			t.Errorf("image chunk must not carry %s: %v", key, chunks[1][key])
		}
	}
}

// TestGeneralChunkerSpreadsheetSplitDropsNonSpreadsheetPositions: sub-tables
// only receive sliced positions when the item carries spreadsheet identity and
// the matrix is five-field tuples aligned to the splitter's rows; a PDF-style
// matrix or a short tuple is dropped rather than misattributed.
func TestGeneralChunkerSpreadsheetSplitDropsNonSpreadsheetPositions(t *testing.T) {
	rows := [][]string{{"v0", "p0"}, {"v1", "p1"}, {"v2", "p2"}, {"v3", "p3"}, {"v4", "p4"}, {"v5", "p5"}}
	cases := []struct {
		name   string
		mutate func(item map[string]any)
	}{
		{"no spreadsheet identity", func(item map[string]any) { delete(item, "sheet_index") }},
		{"short tuples", func(item map[string]any) {
			item["positions"] = [][]float64{{1}, {1}, {1}, {1}, {1}, {1}, {1}}
		}},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			component, err := NewGeneralChunker(map[string]any{"chunk_token_size": 20})
			if err != nil {
				t.Fatalf("NewGeneralChunker: %v", err)
			}
			item := spreadsheetSegmentItem("Sheet1", []string{"name", "price"}, rows, 1, 2)
			tc.mutate(item)
			out, err := component.Invoke(t.Context(), nil, map[string]any{
				"name":          "long.xlsx",
				"file_type":     "xlsx",
				"output_format": "json",
				"json":          []map[string]any{item},
			})
			if err != nil {
				t.Fatalf("Invoke: %v", err)
			}
			chunks := outputChunks(t, out)
			if len(chunks) < 2 {
				t.Fatalf("expected the segment to be split, got %d chunks", len(chunks))
			}
			for i, chunk := range chunks {
				if p, ok := chunk["positions"]; ok && p != nil && fmt.Sprintf("%v", p) != "[]" && fmt.Sprintf("%v", p) != "<nil>" {
					t.Errorf("chunk %d kept positions without a usable spreadsheet matrix: %v", i, p)
				}
			}
		})
	}
}

// TestGeneralContextSourceTextProjectsMergedRows pins the general-context
// projection: data-origin row spans stay visible, header-origin spans do not
// leak into data rows, and a colspan is not duplicated.
func TestGeneralContextSourceTextProjectsMergedRows(t *testing.T) {
	cases := []struct {
		name string
		td   *entity.TableData
		want string
	}{
		{
			name: "data rowspan",
			td: &entity.TableData{HeaderRows: 1, Grid: [][]entity.TableCell{
				{{Text: "Group"}, {Text: "Item"}},
				{{Text: "G1", RowSpan: 2}, {Text: "x"}},
				{{Covered: true}, {Text: "y"}},
			}},
			want: "G1 x\nG1 y",
		},
		{
			name: "header-origin rowspan",
			td: &entity.TableData{HeaderRows: 1, Grid: [][]entity.TableCell{
				{{Text: "H", RowSpan: 2}, {Text: "Name"}},
				{{Covered: true}, {Text: "Alice"}},
			}},
			want: "Alice",
		},
		{
			name: "data colspan",
			td: &entity.TableData{HeaderRows: 1, Grid: [][]entity.TableCell{
				{{Text: "A"}, {Text: "B"}, {Text: "C"}},
				{{Text: "Wide", ColSpan: 2}, {Covered: true}, {Text: "z"}},
			}},
			want: "Wide z",
		},
		{
			name: "rowspan and colspan block",
			td: &entity.TableData{HeaderRows: 1, Grid: [][]entity.TableCell{
				{{Text: "A"}, {Text: "B"}, {Text: "C"}},
				{{Text: "Wide", RowSpan: 2, ColSpan: 2}, {Covered: true}, {Text: "x"}},
				{{Covered: true}, {Covered: true}, {Text: "y"}},
			}},
			want: "Wide x\nWide y",
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got, ok := generalContextSourceText(schema.ChunkDoc{
				DocType:   "table",
				Sheet:     "Sheet1",
				TableData: tc.td,
			})
			if !ok {
				t.Fatal("generalContextSourceText did not accept the spreadsheet table")
			}
			if got != tc.want {
				t.Fatalf("context = %q, want %q", got, tc.want)
			}
		})
	}
}

func TestGeneralChunkerMarkdownPreservesUnresolvedImageReferences(t *testing.T) {
	markdown, err := parserlib.NewMarkdownParser(parserlib.GoMarkdown)
	if err != nil {
		t.Fatal(err)
	}
	source := "# Title\n\n![figure](images/fig-1.png)\n\n![](images/bare.png)\n\n" +
		"| A | B |\n|---|---|\n| x | ![table](images/table.png) |\n"
	parsed := markdown.ParseWithResult(t.Context(), "doc.md", []byte(source))
	if parsed.Err != nil {
		t.Fatalf("ParseWithResult: %v", parsed.Err)
	}
	comp, err := NewGeneralChunker(map[string]any{"chunk_token_size": 512})
	if err != nil {
		t.Fatal(err)
	}
	out, err := comp.Invoke(t.Context(), nil, map[string]any{
		"name": "doc.md", "file_type": "md", "output_format": "json", "json": parsed.JSON,
	})
	if err != nil {
		t.Fatalf("Invoke: %v", err)
	}
	chunks := outputChunks(t, out)
	if len(chunks) == 0 {
		t.Fatal("chunks are empty")
	}
	var text strings.Builder
	for _, chunk := range chunks {
		body, _ := chunk["text"].(string)
		text.WriteString(body)
		text.WriteByte('\n')
	}
	for _, want := range []string{
		"![figure](images/fig-1.png)",
		"![](images/bare.png)",
		"![table](images/table.png)",
	} {
		if !strings.Contains(text.String(), want) {
			t.Errorf("chunk text = %q, want it to contain %q", text.String(), want)
		}
	}
}