Skip to content

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

feat(agent): Go ingestion pipeline progress mirroring and DeepDOC parser hardening (#16795)

Zhichang Yu12787996d1b1
diff --git a/AGENTS.md b/AGENTS.md
index 3539386378..a70d532c2d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -58,6 +58,7 @@ Use this file as the local operating guide for the current codebase. Prefer the
- Preserve behavior with focused tests when the behavior is still valid; do not keep tests that protect obsolete behavior.
- If a surface is only there for compatibility, remove it unless the user asks to keep it.
- Do not add new compatibility wording in comments or docs.
+- When a maintainer takes over a community PR, a new commit generated by rewriting history (e.g. `merge`, `rebase -i`) must preserve the original author and add the maintainer as co-author (via a `Co-authored-by:` trailer) instead of overwriting the author with the maintainer alone.
## Commands
### Backend
diff --git a/go.mod b/go.mod
index e76511df36..d2b5539150 100644
--- a/go.mod
+++ b/go.mod
@@ -18,7 +18,7 @@ require (
github.com/browserbase/stagehand-go/v3 v3.21.0
github.com/cenkalti/backoff/v5 v5.0.3
github.com/cespare/xxhash/v2 v2.3.0
- github.com/cloudwego/eino v0.9.9
+ github.com/cloudwego/eino v0.9.12
github.com/denisenkom/go-mssqldb v0.12.3
github.com/elastic/go-elasticsearch/v8 v8.19.1
github.com/eric642/e2b-go-sdk v0.1.3
diff --git a/go.sum b/go.sum
index ac6e8a7d79..5e6b91f364 100644
--- a/go.sum
+++ b/go.sum
@@ -163,8 +163,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
-github.com/cloudwego/eino v0.9.9 h1:x63hvRif6ANPh9YEPoTIrp1potEeoLQFAjOclKaX/Kg=
-github.com/cloudwego/eino v0.9.9/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ=
+github.com/cloudwego/eino v0.9.12 h1:mHAMo5k7GdvnVD8Lc2sLyfpkxEm0S/y3PkEMhsSYt78=
+github.com/cloudwego/eino v0.9.12/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
diff --git a/internal/agent/canvas/compile.go b/internal/agent/canvas/compile.go
index aff844ce63..175e4246c2 100644
--- a/internal/agent/canvas/compile.go
+++ b/internal/agent/canvas/compile.go
@@ -54,6 +54,27 @@ type CompileOptions struct {
// compose.WithInterruptBeforeNodes / WithInterruptAfterNodes.
InterruptBefore []string
InterruptAfter []string
+ // CheckPointID is the stable eino checkpoint identifier. Unlike
+ // eino's compose.WithCheckPointID (a run-time Option applied at
+ // Workflow.Invoke), this is a compile-time descriptor: Compile cannot
+ // call compose.WithCheckPointID (the option type is wrong for a
+ // GraphCompileOption), so it only records the id on the returned
+ // CompiledCanvas — the caller threads it to Invoke. Use a stable,
+ // per-task value (e.g. taskID) so re-running the same task hits the
+ // same Redis checkpoint (agent:cp:{id}). When empty,
+ // CompiledCanvas.CheckPointID stays empty and the caller must supply
+ // its own id (or omit it for a fresh per-run checkpoint).
+ CheckPointID string
+ // InterruptAfterNonTerminal, when true, makes Compile compute the
+ // non-terminal node ids internally (components with out-degree > 0)
+ // and register compose.WithInterruptAfterNodes on them — the caller
+ // does not enumerate them. UserFillUp nodes are excluded (see §4.2.b)
+ // because they already emit their own compose.Interrupt;
+ // double-registering the same node for two interrupt sources would
+ // break resume. Terminal nodes (no downstream) are excluded so the
+ // graph does not pause on completion and force an extra, needless
+ // ResumeWithData round.
+ InterruptAfterNonTerminal bool
}
// CompileOption mutates a CompileOptions before the compile runs.
@@ -79,6 +100,27 @@ func WithInterruptAfter(nodes []string) CompileOption {
return func(o *CompileOptions) { o.InterruptAfter = nodes }
}
+// WithCheckPointID sets the stable checkpoint id recorded on the returned
+// CompiledCanvas. Unlike eino's compose.WithCheckPointID (a run-time
+// Option), this is a compile-time descriptor: Compile stores the id so the
+// caller can pass it to Workflow.Invoke. Pass a stable, per-task value
+// (e.g. taskID) so re-running the same task loads the same Redis
+// checkpoint (agent:cp:{id}).
+func WithCheckPointID(id string) CompileOption {
+ return func(o *CompileOptions) { o.CheckPointID = id }
+}
+
+// WithInterruptAfterNonTerminalCpn registers an after-node interrupt on
+// every non-terminal component (out-degree > 0) automatically. The set is
+// computed inside Compile from the Canvas topology, so callers can't pass
+// the wrong list (e.g. all cpnIDs, which would also interrupt terminal
+// nodes and force an extra needless ResumeWithData round). UserFillUp
+// nodes are excluded (§4.2.b). See computeNonTerminalCpnIDs for the exact
+// selection rules.
+func WithInterruptAfterNonTerminalCpn() CompileOption {
+ return func(o *CompileOptions) { o.InterruptAfterNonTerminal = true }
+}
+
// Compile builds the eino Workflow from the Canvas and returns the
// compiled Runnable. State pre/post handlers are wired inside BuildWorkflow
// (see scheduler.go). Checkpoint store + serializer are wired here as
@@ -121,6 +163,39 @@ func Compile(ctx context.Context, c *Canvas, opts ...CompileOption) (*CompiledCa
}
}
+ // S3 (plan §4.2.b 方案 A): ingestion resume mode forbids UserFillUp
+ // nodes. A UserFillUp node emits its own compose.Interrupt
+ // (wait-for-user); the pipeline resume loop (pipeline.go runResumable)
+ // classifies every interrupt via IsInterruptError and auto-resumes with
+ // nil data — so a UserFillUp pause would be silently skipped instead of
+ // waiting for a human. Reject at compile time so the mis-classification
+ // can never occur. The non-terminal-after filter (computeNonTerminalCpnIDs)
+ // already keeps UserFillUp out of the after-node set; this is a hard
+ // guard layered on top (plan §8 step 5). Checked before BuildWorkflow so
+ // the guard fires on DSL content regardless of whether the graph builds.
+ //
+ // The same guard also forbids legacy no-op nodes (e.g. "ExitLoop", see
+ // legacyNoOpNames / isLegacyNoOp). A no-op node routes to an echo body
+ // that never emits TrackProgress, so it would still be counted in
+ // ingestion_task.component_total yet never report progress — leaving the
+ // aggregate percent permanently below 100% (plan §8 "known
+ // inconsistency"). Forbidding it keeps component_total == "components
+ // that report progress", so percent can reach 100% and the
+ // resume/percent invariant holds. Ingestion DSLs must consist solely of
+ // progress-reporting components.
+ if cfg.InterruptAfterNonTerminal && c != nil {
+ var bad []string
+ bad = append(bad, AutoDiscoverUserFillUpIDs(c)...)
+ for cpnID, comp := range c.Components {
+ if isLegacyNoOp(comp.Obj.ComponentName) {
+ bad = append(bad, cpnID)
+ }
+ }
+ if len(bad) > 0 {
+ return nil, fmt.Errorf("canvas: Compile: WithInterruptAfterNonTerminalCpn forbids UserFillUp/legacy-no-op nodes %v (plan §4.2.b): ingestion has no user to fill up and no-op nodes do not report progress, breaking the resume/percent invariant", bad)
+ }
+ }
+
wf, err := BuildWorkflow(ctx, c)
if err != nil {
return nil, fmt.Errorf("canvas: build workflow: %w", err)
@@ -140,15 +215,78 @@ func Compile(ctx context.Context, c *Canvas, opts ...CompileOption) (*CompiledCa
if len(cfg.InterruptBefore) > 0 {
compileOpts = append(compileOpts, compose.WithInterruptBeforeNodes(cfg.InterruptBefore))
}
- if len(cfg.InterruptAfter) > 0 {
- compileOpts = append(compileOpts, compose.WithInterruptAfterNodes(cfg.InterruptAfter))
+ // Merge the caller-supplied InterruptAfter list with the
+ // internally-computed non-terminal set (when requested). The
+ // computed set excludes UserFillUp nodes (§4.2.b); the caller list is
+ // trusted verbatim. Dedupe so a node isn't registered twice in one
+ // WithInterruptAfterNodes call.
+ after := append([]string{}, cfg.InterruptAfter...)
+ if cfg.InterruptAfterNonTerminal {
+ after = append(after, computeNonTerminalCpnIDs(c)...)
+ }
+ after = dedupeStrings(after)
+ if len(after) > 0 {
+ compileOpts = append(compileOpts, compose.WithInterruptAfterNodes(after))
}
runnable, err := wf.Compile(ctx, compileOpts...)
if err != nil {
return nil, fmt.Errorf("canvas: eino compile: %w", err)
}
- return &CompiledCanvas{Workflow: runnable}, nil
+ return &CompiledCanvas{Workflow: runnable, CheckPointID: cfg.CheckPointID}, nil
+}
+
+// computeNonTerminalCpnIDs returns the cpnIDs of every component with at
+// least one downstream edge (out-degree > 0). These are the nodes the
+// "interrupt-after-node" resume strategy must pause on: any node that has
+// work after it.
+//
+// Terminal nodes (no downstream) are intentionally excluded — interrupting
+// them would make Invoke return an interrupt error instead of a completion,
+// and force an extra needless ResumeWithData round before the graph truly
+// finishes.
+//
+// UserFillUp nodes are excluded (§4.2.b): they already emit their own
+// compose.Interrupt and must not be registered for a second, conflicting
+// interrupt source. Double-registering the same node breaks resume.
+func computeNonTerminalCpnIDs(c *Canvas) []string {
+ if c == nil {
+ return nil
+ }
+ exclude := make(map[string]bool, len(c.Components))
+ for _, id := range AutoDiscoverUserFillUpIDs(c) {
+ exclude[id] = true
+ }
+ var ids []string
+ for cpnID, comp := range c.Components {
+ if exclude[cpnID] {
+ continue
+ }
+ if len(comp.Downstream) > 0 {
+ ids = append(ids, cpnID)
+ }
+ }
+ return ids
+}
+
+// dedupeStrings returns in with duplicate entries removed, preserving
+// first-seen order. Used to merge the computed non-terminal set with the
+// caller-supplied InterruptAfter list without registering a node twice in
+// the same WithInterruptAfterNodes call.
+func dedupeStrings(in []string) []string {
+ if len(in) == 0 {
+ return in
+ }
+ seen := make(map[string]bool, len(in))
+ out := make([]string, 0, len(in))
+ for _, s := range in {
+ if seen[s] {
+ continue
+ }
+ seen[s] = true
+ out = append(out, s)
+ }
+ return out
}
// checkPointAdapter drops the Delete method that compose.CheckPointStore
diff --git a/internal/agent/canvas/compile_test.go b/internal/agent/canvas/compile_test.go
index f4e818f81c..1e0c78b4c0 100644
--- a/internal/agent/canvas/compile_test.go
+++ b/internal/agent/canvas/compile_test.go
@@ -18,6 +18,7 @@ package canvas
import (
"bytes"
"context"
+ "sort"
"strings"
"testing"
@@ -119,3 +120,98 @@ func TestCompile_NoLogOnCleanCanvas(t *testing.T) {
t.Errorf("unexpected legacy-node log on clean canvas: %q", got)
}
}
+
+// TestWithCheckPointID_OptionSetsField verifies the new R2 option records
+// the stable id on CompileOptions. (Compile cannot apply eino's
+// compose.WithCheckPointID directly — it's a run-time Option, not a
+// GraphCompileOption — so the id is carried on CompiledCanvas for the
+// caller to thread to Workflow.Invoke.)
+func TestWithCheckPointID_OptionSetsField(t *testing.T) {
+ o := CompileOptions{}
+ WithCheckPointID("task-42")(&o)
+ if o.CheckPointID != "task-42" {
+ t.Errorf("WithCheckPointID did not set field: got %q", o.CheckPointID)
+ }
+}
+
+// TestWithInterruptAfterNonTerminalCpn_OptionSetsField verifies the no-arg
+// option flips the internal-compute flag.
+func TestWithInterruptAfterNonTerminalCpn_OptionSetsField(t *testing.T) {
+ o := CompileOptions{}
+ WithInterruptAfterNonTerminalCpn()(&o)
+ if !o.InterruptAfterNonTerminal {
+ t.Error("WithInterruptAfterNonTerminalCpn did not set flag")
+ }
+}
+
+// TestComputeNonTerminalCpnIDs covers the core selection rule for the
+// no-arg WithInterruptAfterNonTerminalCpn: include every component with
+// out-degree > 0, exclude terminal nodes (no downstream) and UserFillUp
+// nodes (§4.2.b — they carry their own compose.Interrupt).
+func TestComputeNonTerminalCpnIDs(t *testing.T) {
+ c := &Canvas{
+ Components: map[string]CanvasComponent{
+ "n1": {Obj: CanvasComponentObj{ComponentName: "Parser"}, Downstream: []string{"n2"}},
+ "n2": {Obj: CanvasComponentObj{ComponentName: "LLM"}, Downstream: []string{"n3"}},
+ "n3": {Obj: CanvasComponentObj{ComponentName: "Answer"}, Downstream: nil}, // terminal
+ "uf": {Obj: CanvasComponentObj{ComponentName: "UserFillUp"}, Downstream: []string{"n4"}}, // excluded
+ "n4": {Obj: CanvasComponentObj{ComponentName: "Answer"}, Downstream: nil}, // terminal
+ },
+ }
+ got := computeNonTerminalCpnIDs(c)
+ sort.Strings(got)
+ want := []string{"n1", "n2"}
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("computeNonTerminalCpnIDs = %v, want %v", got, want)
+ }
+}
+
+// TestCompile_RejectsUserFillUpInResumeMode covers S3 (plan §4.2.b 方案 A):
+// when WithInterruptAfterNonTerminalCpn is set (ingestion resume mode), a DSL
+// containing a UserFillUp node must be rejected at compile time. A UserFillUp
+// node emits its own compose.Interrupt (wait-for-user); the pipeline resume
+// loop would catch it via IsInterruptError and auto-resume with nil data,
+// silently skipping the human interaction. The guard fires before BuildWorkflow
+// so it is independent of whether the rest of the graph compiles.
+func TestCompile_RejectsUserFillUpInResumeMode(t *testing.T) {
+ c := &Canvas{
+ Components: map[string]CanvasComponent{
+ "begin": {Obj: CanvasComponentObj{ComponentName: "Begin", Params: map[string]any{}}},
+ "uf": {Obj: CanvasComponentObj{ComponentName: "UserFillUp"}, Downstream: []string{"end"}},
+ "end": {Obj: CanvasComponentObj{ComponentName: "Answer", Params: map[string]any{}}},
+ },
+ }
+ _, err := Compile(context.Background(), c, WithInterruptAfterNonTerminalCpn())
+ if err == nil {
+ t.Fatal("expected Compile to reject UserFillUp in resume mode, got nil error")
+ }
+ if !strings.Contains(err.Error(), "UserFillUp") {
+ t.Errorf("expected UserFillUp reject message, got %v", err)
+ }
+}
+
+// TestCompile_PropagatesCheckPointID verifies Compile stores the stable id
+// on the returned CompiledCanvas. The assertion only fires when the canvas
+// actually compiles end-to-end in this environment (component factories /
+// DB may be unavailable in unit scope) — matching the repo convention in
+// the other Compile tests that ignore compile errors. The option-side
+// contract is independently covered by TestWithCheckPointID_OptionSetsField.
+func TestCompile_PropagatesCheckPointID(t *testing.T) {
+ c := &Canvas{
+ Components: map[string]CanvasComponent{
+ "begin": {Obj: CanvasComponentObj{ComponentName: "Begin", Params: map[string]any{}}},
+ "llm:0": {Obj: CanvasComponentObj{ComponentName: "LLM", Params: map[string]any{}}, Downstream: []string{"answer:0"}},
+ "answer:0": {Obj: CanvasComponentObj{ComponentName: "Answer", Params: map[string]any{}}},
+ },
+ }
+ compiled, err := Compile(context.Background(), c, WithCheckPointID("task-9"))
+ if err != nil {
+ t.Skipf("skipping propagation assertion: canvas did not compile in unit scope: %v", err)
+ }
+ if compiled == nil {
+ t.Skip("skipping propagation assertion: nil CompiledCanvas")
+ }
+ if compiled.CheckPointID != "task-9" {
+ t.Errorf("CompiledCanvas.CheckPointID = %q, want %q", compiled.CheckPointID, "task-9")
+ }
+}
diff --git a/internal/agent/canvas/node_body.go b/internal/agent/canvas/node_body.go
index 80ac74ae4d..5ac3181c89 100644
--- a/internal/agent/canvas/node_body.go
+++ b/internal/agent/canvas/node_body.go
@@ -158,12 +158,24 @@ func componentTimeout() time.Duration {
// runtime.Component. The component is constructed once at build time
// (in buildNodeBody) and re-invoked per iteration.
//
-// Each invocation is wrapped in a context.WithTimeout derived from
-// resolveTimeout(comp.Name()) — the per-class resolver in timeout.go
-// (4-level: per-class env → per-class defaults table → uniform env
-// → 600s fallback). The lookup is per-invocation (not per-body) so
-// operators can tune COMPONENT_EXEC_TIMEOUT[_<CLASS>] at runtime
-// without rebuilding graphs.
+// This is the SINGLE chokepoint through which every component Invoke
+// passes — both the agent canvas and the ingestion pipeline
+// (internal/ingestion/pipeline compiles a canvas and runs its workflow)
+// reach components here. Cross-cutting concerns therefore belong here,
+// not inside each component's Invoke:
+//
+// - per-class timeout: context.WithTimeout from resolveTimeout
+// (4-level: per-class env → per-class defaults table → uniform env
+// → 600s fallback). The lookup is per-invocation (not per-body) so
+// operators can tune COMPONENT_EXEC_TIMEOUT[_<CLASS>] at runtime
+// without rebuilding graphs.
+// - progress: runtime.TrackProgress, with the callback pulled from
+// ctx (nil ⇒ no observer). This makes progress a framework-level
+// concern — components no longer wrap themselves.
+// - elapsed-time accounting: runtime.TrackElapsed stamps
+// _created_time / _elapsed_time into the output map so the
+// dataflow-result UI can show per-node timing without each
+// component repeating the bookkeeping.
//
// Timeout errors are surfaced as `timeout after Xs: <wrapped>`;
// parent-context cancellation as `cancelled: <wrapped>`; all other
@@ -178,16 +190,24 @@ func realComponentBody(cpnID, componentClass string, comp runtime.Component) nod
timeout := resolveTimeoutFromContext(ctx, componentClass)
cctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
- out, err := comp.Invoke(cctx, in)
- if err != nil {
+
+ var out map[string]any
+ invokeErr := runtime.TrackProgress(cpnID, runtime.ProgressCallbackFromContext(ctx), func() error {
+ var e error
+ out, e = runtime.TrackElapsed(componentClass, func() (map[string]any, error) {
+ return comp.Invoke(cctx, in)
+ })
+ return e
+ })
+ if invokeErr != nil {
switch {
- case errors.Is(err, context.DeadlineExceeded):
+ case errors.Is(invokeErr, context.DeadlineExceeded):
return nil, fmt.Errorf("canvas: component %q invoke: timeout after %s: %w",
- cpnID, timeout, err)
- case errors.Is(err, context.Canceled):
- return nil, fmt.Errorf("canvas: component %q invoke: cancelled: %w", cpnID, err)
+ cpnID, timeout, invokeErr)
+ case errors.Is(invokeErr, context.Canceled):
+ return nil, fmt.Errorf("canvas: component %q invoke: cancelled: %w", cpnID, invokeErr)
}
- return nil, fmt.Errorf("canvas: component %q invoke: %w", cpnID, err)
+ return nil, fmt.Errorf("canvas: component %q invoke: %w", cpnID, invokeErr)
}
if out == nil {
out = make(map[string]any, 1)
diff --git a/internal/agent/canvas/run_tracker.go b/internal/agent/canvas/run_tracker.go
index d5309cc807..4ca81d6d1b 100644
--- a/internal/agent/canvas/run_tracker.go
+++ b/internal/agent/canvas/run_tracker.go
@@ -44,6 +44,10 @@ const (
runStatusCancelled = "3"
)
+// runFieldInterruptID is the hash field that holds the eino interrupt id a
+// run is paused on (plan §4.4, M3). Reuses the run hash — no dedicated key.
+const runFieldInterruptID = "interrupt_id"
+
func runKey(runID string) string { return runKeyPrefix + runID }
// RunTracker manages canvas-run metadata (canvas_id, status, checkpoint
@@ -114,6 +118,49 @@ func (t *RunTracker) AttachCheckpoint(ctx context.Context, runID, checkpointID s
return t.client.HSet(ctx, runKey(runID), "checkpoint_id", checkpointID).Err()
}
+// AttachInterrupt persists the eino interrupt id that paused this run
+// (plan §4.4, M3). The id is written to the SAME hash key as the other run
+// metadata — no new Redis key — so a process that crashes between "Invoke
+// returned an interrupt" and "the next loop iteration resumes" can recover:
+// the next process reads GetInterruptID at the top of its resume loop and
+// calls compose.ResumeWithData with it. The ONLY writer of "interrupt_id".
+func (t *RunTracker) AttachInterrupt(ctx context.Context, runID, interruptID string) error {
+ if t == nil || t.client == nil {
+ return errors.New("run tracker: redis client not initialized")
+ }
+ return t.client.HSet(ctx, runKey(runID), runFieldInterruptID, interruptID).Err()
+}
+
+// GetInterruptID returns the persisted interrupt id for runID. The bool is
+// false when no interrupt is pending (field absent or empty). A nil error
+// with (id, false) means "no pending interrupt" — callers treat that as
+// "fresh run, do a normal Invoke".
+func (t *RunTracker) GetInterruptID(ctx context.Context, runID string) (string, bool, error) {
+ if t == nil || t.client == nil {
+ return "", false, errors.New("run tracker: redis client not initialized")
+ }
+ v, err := t.client.HGet(ctx, runKey(runID), runFieldInterruptID).Result()
+ if errors.Is(err, redis.Nil) {
+ return "", false, nil
+ }
+ if err != nil {
+ return "", false, err
+ }
+ if v == "" {
+ return "", false, nil
+ }
+ return v, true, nil
+}
+
+// ClearInterruptID removes the persisted interrupt id. Called when a run
+// completes (no longer paused) or is cancelled (the checkpoint is wiped).
+func (t *RunTracker) ClearInterruptID(ctx context.Context, runID string) error {
+ if t == nil || t.client == nil {
+ return errors.New("run tracker: redis client not initialized")
+ }
+ return t.client.HDel(ctx, runKey(runID), runFieldInterruptID).Err()
+}
+
// MarkSucceeded transitions the run to status=1 and stamps finished_at.
func (t *RunTracker) MarkSucceeded(ctx context.Context, runID string) error {
if t == nil || t.client == nil {
diff --git a/internal/agent/runtime/helpers.go b/internal/agent/runtime/helpers.go
index 44cbaa5689..1a48992aea 100644
--- a/internal/agent/runtime/helpers.go
+++ b/internal/agent/runtime/helpers.go
@@ -45,40 +45,78 @@ import (
"time"
)
+// ProgressPhase classifies a component lifecycle event emitted by
+// TrackProgress. The integer values are stable and persisted in the
+// ingestion_task_log.phase column, so they are part of the data contract
+// (see internal/ingestion/pipeline PROGRESS_LOG_RESUME_PLAN §5.1):
+//
+// PhaseEnter = 0 component just started
+// PhaseExit = 1 component finished cleanly
+// PhaseError = 2 component errored (Err carries the error)
+type ProgressPhase int
+
+const (
+ PhaseEnter ProgressPhase = iota
+ PhaseExit
+ PhaseError
+)
+
+// ProgressEvent is a structured progress notification emitted by
+// TrackProgress for every component lifecycle event.
+//
+// Component is the node id (cpnID) — the unique identifier of the node in
+// the DSL graph, NOT the component class name. Class names cannot
+// disambiguate multiple instances of the same class, so sinks must key on
+// Component for attribution, ordering, and GROUP BY (plan §5.1).
+//
+// Err is non-nil only when Phase == PhaseError.
+//
+// ProgressEvent deliberately does NOT carry the component's output:
+// resume is owned by the framework's eino checkpoint, so progress is
+// purely observational (plan §5.1 / §5.3). Keeping the event free of
+// output also avoids serializing large payloads on every event.
+//
+// Concrete sinks (ingestion task-log writer, in-memory test recorder)
+// implement ProgressCallback. nil is a valid value: TrackProgress treats a
+// nil cb as "no observer" and simply runs fn.
+type ProgressEvent struct {
+ Phase ProgressPhase
+ Component string
+ Err error
+}
+
// ProgressCallback receives progress notifications from TrackProgress.
-// The numeric progress values follow the convention used by the Python
-// pipeline canvas callback:
-//
-// progress=0 before fn runs (component just started)
-// progress=1 on success (component finished cleanly)
-// progress=-1 on failure (component errored; message is the error)
-//
-// Concrete sinks (Redis log writer, in-memory test recorder) implement
-// this signature. nil is a valid value: TrackProgress treats a nil cb as
-// "no observer" and simply runs fn.
-type ProgressCallback func(progress int, message string)
+type ProgressCallback func(event ProgressEvent)
// TrackProgress wraps fn with progress notifications. The callback is
-// invoked at most twice per call (once at start, once at end).
-//
-// On success: cb(1, "<compName> Done") and nil error.
-// On failure: cb(-1, "<compName>: <err>") and the original error.
-//
-// A nil callback is permitted: fn runs to completion and its return
-// value (including error) is passed through untouched.
-func TrackProgress(compName string, cb ProgressCallback, fn func() error) error {
+// invoked at most twice per call (once at start, once at end):
+//
+// enter: cb(ProgressEvent{Phase: PhaseEnter, Component: cpnID})
+// exit: cb(ProgressEvent{Phase: PhaseExit, Component: cpnID})
+// error: cb(ProgressEvent{Phase: PhaseError, Component: cpnID, Err: err})
+//
+// A nil callback is permitted: fn runs to completion and its return value
+// (including error) is passed through untouched.
+//
+// cpnID is the node id from the DSL graph. The canvas framework
+// (internal/agent/canvas realComponentBody) is the single chokepoint that
+// calls TrackProgress, so individual components must NOT call it
+// themselves — that keeps the observer injection point in one place.
+// realComponentBody pulls the callback from ctx via
+// ProgressCallbackFromContext.
+func TrackProgress(cpnID string, cb ProgressCallback, fn func() error) error {
if cb != nil {
- cb(0, compName+" Started")
+ cb(ProgressEvent{Phase: PhaseEnter, Component: cpnID})
}
err := fn()
if cb == nil {
return err
}
if err != nil {
- cb(-1, fmt.Sprintf("%s: %s", compName, err.Error()))
+ cb(ProgressEvent{Phase: PhaseError, Component: cpnID, Err: err})
return err
}
- cb(1, compName+" Done")
+ cb(ProgressEvent{Phase: PhaseExit, Component: cpnID})
return nil
}
@@ -161,3 +199,32 @@ func TrackElapsed(name string, fn func() (map[string]any, error)) (map[string]an
}
return out, nil
}
+
+// progressCBKey is the context key under which a ProgressCallback is
+// carried so the canvas framework can fan progress out to an observer
+// without every component knowing about it. The framework owns the
+// callback; components only see their own work.
+type progressCBKey struct{}
+
+// WithProgressCallback attaches a ProgressCallback to ctx. The canvas
+// framework reads it inside realComponentBody and forwards it to
+// TrackProgress when a component runs, so progress reporting is a
+// framework-level concern. A run that wants progress fan-out (e.g. the
+// ingestion pipeline's task log writer) injects one; when none is set,
+// ProgressCallbackFromContext returns nil and TrackProgress is a no-op.
+func WithProgressCallback(ctx context.Context, cb ProgressCallback) context.Context {
+ return context.WithValue(ctx, progressCBKey{}, cb)
+}
+
+// ProgressCallbackFromContext returns the ProgressCallback attached to
+// ctx, or nil if none was set. TrackProgress treats a nil callback as
+// "no observer" and simply runs fn.
+func ProgressCallbackFromContext(ctx context.Context) ProgressCallback {
+ if ctx == nil {
+ return nil
+ }
+ if cb, ok := ctx.Value(progressCBKey{}).(ProgressCallback); ok {
+ return cb
+ }
+ return nil
+}
diff --git a/internal/agent/runtime/helpers_test.go b/internal/agent/runtime/helpers_test.go
index 24749755ea..c3e941f03f 100644
--- a/internal/agent/runtime/helpers_test.go
+++ b/internal/agent/runtime/helpers_test.go
@@ -26,29 +26,23 @@ import (
)
// recordingCallback is a thread-safe ProgressCallback recorder used by
-// the TrackProgress tests. progress/message pairs are appended in
+// the TrackProgress tests. ProgressEvent values are appended in
// invocation order so tests can assert the exact call sequence.
type recordingCallback struct {
- mu sync.Mutex
- calls []recordedCall
- started bool
+ mu sync.Mutex
+ calls []ProgressEvent
}
-type recordedCall struct {
- progress int
- message string
-}
-
-func (r *recordingCallback) callback(progress int, message string) {
+func (r *recordingCallback) callback(ev ProgressEvent) {
r.mu.Lock()
defer r.mu.Unlock()
- r.calls = append(r.calls, recordedCall{progress: progress, message: message})
+ r.calls = append(r.calls, ev)
}
-func (r *recordingCallback) callsCopy() []recordedCall {
+func (r *recordingCallback) callsCopy() []ProgressEvent {
r.mu.Lock()
defer r.mu.Unlock()
- out := make([]recordedCall, len(r.calls))
+ out := make([]ProgressEvent, len(r.calls))
copy(out, r.calls)
return out
}
@@ -67,11 +61,11 @@ func TestTrackProgress_Success(t *testing.T) {
if len(calls) != 2 {
t.Fatalf("expected 2 callback invocations, got %d: %+v", len(calls), calls)
}
- if calls[0].progress != 0 || calls[0].message != "Parser Started" {
- t.Errorf("first call = %+v, want progress=0 message=%q", calls[0], "Parser Started")
+ if calls[0].Phase != PhaseEnter || calls[0].Component != "Parser" {
+ t.Errorf("first call = %+v, want phase=PhaseEnter component=%q", calls[0], "Parser")
}
- if calls[1].progress != 1 || calls[1].message != "Parser Done" {
- t.Errorf("second call = %+v, want progress=1 message=%q", calls[1], "Parser Done")
+ if calls[1].Phase != PhaseExit || calls[1].Component != "Parser" {
+ t.Errorf("second call = %+v, want phase=PhaseExit component=%q", calls[1], "Parser")
}
}
@@ -88,14 +82,17 @@ func TestTrackProgress_Failure(t *testing.T) {
if len(calls) != 2 {
t.Fatalf("expected 2 callback invocations, got %d", len(calls))
}
- if calls[0].progress != 0 || calls[0].message != "Tokenizer Started" {
- t.Errorf("first call = %+v, want progress=0 message=%q", calls[0], "Tokenizer Started")
+ if calls[0].Phase != PhaseEnter || calls[0].Component != "Tokenizer" {
+ t.Errorf("first call = %+v, want phase=PhaseEnter component=%q", calls[0], "Tokenizer")
+ }
+ if calls[1].Phase != PhaseError {
+ t.Errorf("second call phase = %v, want PhaseError", calls[1].Phase)
}
- if calls[1].progress != -1 {
- t.Errorf("second call progress = %d, want -1", calls[1].progress)
+ if calls[1].Component != "Tokenizer" {
+ t.Errorf("second call component = %q, want %q", calls[1].Component, "Tokenizer")
}
- if !strings.Contains(calls[1].message, "Tokenizer") || !strings.Contains(calls[1].message, "boom") {
- t.Errorf("second call message = %q, want it to contain both %q and %q", calls[1].message, "Tokenizer", "boom")
+ if !errors.Is(calls[1].Err, wantErr) {
+ t.Errorf("second call Err = %v, want %v", calls[1].Err, wantErr)
}
}
@@ -122,8 +119,9 @@ func TestTrackProgress_NilCallback(t *testing.T) {
}
// TestTrackProgress_PassesThroughReturnValue covers the documented contract
-// that the error returned to the caller is fn's error verbatim (wrapped
-// only by the message-formatting for the callback, not for the return).
+// that the error returned to the caller is fn's error verbatim (the
+// callback receives it on a PhaseError event but the return value is not
+// wrapped).
func TestTrackProgress_PassesThroughReturnValue(t *testing.T) {
rec := &recordingCallback{}
@@ -139,13 +137,11 @@ func TestTrackProgress_PassesThroughReturnValue(t *testing.T) {
t.Fatalf("err not propagated by identity: got %v (%T), want %v (%T)", got, got, want, want)
}
- // cb saw the failure with progress=-1
- var last recordedCall
- for _, c := range rec.callsCopy() {
- last = c
- }
- if last.progress != -1 {
- t.Errorf("final cb call progress = %d, want -1", last.progress)
+ // cb saw the failure on a PhaseError event
+ calls := rec.callsCopy()
+ last := calls[len(calls)-1]
+ if last.Phase != PhaseError {
+ t.Errorf("final cb call phase = %v, want PhaseError", last.Phase)
}
}
diff --git a/internal/agent/tool/code_exec.go b/internal/agent/tool/code_exec.go
index a714af71d1..a14effaf35 100644
--- a/internal/agent/tool/code_exec.go
+++ b/internal/agent/tool/code_exec.go
@@ -94,7 +94,7 @@ func NewCodeExecTool() *CodeExecTool {
}
// Info returns the tool's metadata for the chat model. The schema mirrors
-// the Python CodeExecParam ToolMeta (plan , 字段对齐).
+// the Python CodeExecParam ToolMeta (plan, field alignment).
func (c *CodeExecTool) Info(_ context.Context) (*schema.ToolInfo, error) {
return &schema.ToolInfo{
Name: codeExecToolName,
diff --git a/internal/agent/tool/qweather.go b/internal/agent/tool/qweather.go
index ac81375965..0ad2e9c58c 100644
--- a/internal/agent/tool/qweather.go
+++ b/internal/agent/tool/qweather.go
@@ -39,7 +39,7 @@ var qweatherEndpoint = "https://devapi.qweather.com/v7/weather/now"
// qweatherParams is the JSON shape the model sends into InvokableRun.
//
-// - APIKey (required): the QWeather API key (Console → 项目 → 凭据).
+// - APIKey (required): the QWeather API key (Console → Project → Credentials).
// - Location (required): the location code, e.g. "101010100" (Beijing)
// or a lat,lon string "39.904,116.405".
// - Lang (optional): language code for `text` and `windDir`. Defaults
@@ -79,7 +79,7 @@ type qweatherEnvelope struct {
// QWeatherTool is the 和风天气
// (QWeather) current-conditions tool (
-// 第 4 批). It performs a GET against devapi.qweather.com/v7/weather/now
+// batch 4). It performs a GET against devapi.qweather.com/v7/weather/now
// and returns the parsed now.{temp, feelsLike, text, windDir, humidity}.
//
// QWeatherTool uses the shared HTTPHelper for retry/timeout/OTel
@@ -178,8 +178,8 @@ func (q *QWeatherTool) InvokableRun(ctx context.Context, argsJSON string, _ ...t
fmt.Errorf("qweather: decode response: %w", err)
}
// QWeather uses "200" string code for OK; anything else is a
- // business-level error. Code "404" = 城市不存在, "401" = 认证失败,
- // "429" = 超过访问次数, "402" = 超过访问速度.
+ // business-level error. Code "404" = city not found, "401" = authentication failed,
+ // "429" = exceeded access count, "402" = exceeded access rate.
if raw.Code != "200" {
return qweatherErrJSON(fmt.Errorf("qweather: upstream returned code %q", raw.Code)),
fmt.Errorf("qweather: upstream returned code %q", raw.Code)
diff --git a/internal/agent/tool/retrieval.go b/internal/agent/tool/retrieval.go
index 2fc0c2a225..81d39d74af 100644
--- a/internal/agent/tool/retrieval.go
+++ b/internal/agent/tool/retrieval.go
@@ -95,7 +95,7 @@ func NewRetrievalTool() *RetrievalTool {
}
// Info returns the tool's metadata for the chat model. The schema mirrors
-// the Python RetrievalParam ToolMeta (plan , 字段对齐).
+// the Python RetrievalParam ToolMeta (plan, field alignment).
func (r *RetrievalTool) Info(_ context.Context) (*schema.ToolInfo, error) {
return &schema.ToolInfo{
Name: retrievalToolName,
diff --git a/internal/agent/workflowx/r3_interrupt_test.go b/internal/agent/workflowx/r3_interrupt_test.go
new file mode 100644
index 0000000000..dedf4cedbf
--- /dev/null
+++ b/internal/agent/workflowx/r3_interrupt_test.go
@@ -0,0 +1,451 @@
+//
+// 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 not 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.
+
+// r3_interrupt_test.go — R3 spike for PROGRESS_LOG_RESUME_PLAN.md.
+//
+// R3 (P0 gate for §8 step 3) asks whether eino v0.9.12's
+// WithInterruptAfterNodes + full-graph ResumeWithData behaves correctly
+// under DAG / Loop / Parallel topology. The ingestion canvas CAN contain
+// Loop and Parallel nodes (via AddLoopNode / AddParallelNode), so step 3's
+// "interrupt-after-every-non-terminal-node then resume" strategy must not
+// re-execute already-completed nodes and must re-enter loops/parallels
+// cleanly.
+//
+// These tests build real compose.Workflow graphs with a real
+// CheckPointStore and assert the post-resume node-execution counts. They
+// double as a permanent regression guard: if a future eino bump breaks
+// interrupt-after + resume, these fail instead of silently re-running
+// completed ingestion components (the "re-parse a file" hazard).
+//
+// NOTE: eino only wraps an after-node interrupt into the *interruptError
+// shape that ExtractInterruptInfo recognizes when the graph is STATEFUL
+// (WithGenLocalState). The ingestion canvas is stateful via CanvasState,
+// so the spike mirrors that: every outer workflow is built with
+// WithGenLocalState + WithGraphName, exactly as canvas.BuildWorkflow does.
+package workflowx
+
+import (
+ "context"
+ "strconv"
+ "testing"
+
+ "github.com/cloudwego/eino/compose"
+)
+
+// r3State is a minimal local state so the outer graph is stateful and
+// after-node interrupts surface as ExtractInterruptInfo-recognizable
+// errors (the production canvas path is also stateful via CanvasState).
+// It must be registered with eino's serializer, exactly like CanvasState
+// (runtime/state.go), or the checkpoint marshal fails with "unknown type".
+type r3State struct{ A int }
+
+func init() {
+ compose.RegisterSerializableType[r3State]("workflowx.r3State")
+}
+
+// r3NewWorkflow builds a stateful outer workflow mirroring the canvas
+// compile path.
+func r3NewWorkflow[I, O any]() *compose.Workflow[I, O] {
+ return compose.NewWorkflow[I, O](
+ compose.WithGenLocalState(func(context.Context) *r3State { return &r3State{} }),
+ )
+}
+
+// r3FirstInterruptID extracts the single interrupt id from an after-node
+// interrupt error. WithInterruptAfterNodes produces exactly one
+// InterruptContext whose ID is the paused node's address.
+func r3FirstInterruptID(t *testing.T, err error) string {
+ t.Helper()
+ info, ok := compose.ExtractInterruptInfo(err)
+ if !ok {
+ if info2, ok2 := compose.IsInterruptRerunError(err); ok2 {
+ t.Fatalf("ExtractInterruptInfo=nil but IsInterruptRerunError ok (info=%v); err=%v [%T]", info2, err, err)
+ }
+ t.Fatalf("ExtractInterruptInfo: %v [%T]", err, err)
+ }
+ if len(info.InterruptContexts) == 0 {
+ t.Fatal("InterruptContexts empty")
+ }
+ return info.InterruptContexts[0].ID
+}
+
+// r3cp is a tiny deterministic checkpoint id builder for loop/parallel
+// sub-checkpoints (mirrors the pattern in loop_integration_test.go).
+func r3cp(prefix string) func(string, int) string {
+ return func(_ string, iter int) string {
+ return prefix + ":" + strconv.Itoa(iter)
+ }
+}
+
+// TestR3_DAG_InterruptAfterResumesWithoutRerun is the baseline DAG
+// assertion: with WithInterruptAfterNodes([B]) on the chain
+// A->B->C (B non-terminal), the first Invoke pauses after B; the resume
+// Invoke must continue to C WITHOUT re-running A or B.
+func TestR3_DAG_InterruptAfterResumesWithoutRerun(t *testing.T) {
+ store := newInMemoryStore()
+ var aCount, bCount, cCount int
+
+ wf := r3NewWorkflow[int, int]()
+ a := wf.AddLambdaNode("A", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ aCount++
+ return in + 1, nil
+ }))
+ b := wf.AddLambdaNode("B", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ bCount++
+ return in * 2, nil
+ }))
+ c := wf.AddLambdaNode("C", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ cCount++
+ return in + 10, nil
+ }))
+ a.AddInput(compose.START)
+ b.AddInput("A")
+ c.AddInput("B")
+ wf.End().AddInput("C")
+
+ compiled, err := wf.Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"B"}),
+ )
+ if err != nil {
+ t.Fatalf("compile: %v", err)
+ }
+
+ cpID := "r3-dag"
+ _, invokeErr := compiled.Invoke(context.Background(), 1, compose.WithCheckPointID(cpID))
+ if invokeErr == nil {
+ t.Fatal("expected interrupt after B, got nil")
+ }
+
+ resumeCtx := compose.ResumeWithData(context.Background(), r3FirstInterruptID(t, invokeErr), nil)
+ out, err := compiled.Invoke(resumeCtx, 1, compose.WithCheckPointID(cpID))
+ if err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+
+ // A(1->2), B(2->4), C(4->14)
+ if out != 14 {
+ t.Fatalf("output: got %d, want 14", out)
+ }
+ if aCount != 1 || bCount != 1 || cCount != 1 {
+ t.Fatalf("rerun on resume: A=%d B=%d C=%d; want all 1 (completed nodes must not re-execute)", aCount, bCount, cCount)
+ }
+}
+
+// TestR3_DAG_CrashRecovery_RecompiledGraph simulates a process crash
+// between the interrupt and the resume: a brand-new compiled runnable
+// (process 2) loads the same CheckPointID and resumes. This proves the
+// recovery path step 3 relies on (a fresh Pipeline.Run picking up the
+// orphaned checkpoint) actually re-enters at C and does not restart A/B.
+func TestR3_DAG_CrashRecovery_RecompiledGraph(t *testing.T) {
+ store := newInMemoryStore()
+ var aCount, bCount, cCount int
+
+ build := func() *compose.Workflow[int, int] {
+ wf := r3NewWorkflow[int, int]()
+ a := wf.AddLambdaNode("A", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ aCount++
+ return in + 1, nil
+ }))
+ b := wf.AddLambdaNode("B", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ bCount++
+ return in * 2, nil
+ }))
+ c := wf.AddLambdaNode("C", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ cCount++
+ return in + 10, nil
+ }))
+ a.AddInput(compose.START)
+ b.AddInput("A")
+ c.AddInput("B")
+ wf.End().AddInput("C")
+ return wf
+ }
+
+ // Process 1: compile, run, pause after B.
+ compiled1, err := build().Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"B"}),
+ )
+ if err != nil {
+ t.Fatalf("compile1: %v", err)
+ }
+ cpID := "r3-dag-crash"
+ _, err = compiled1.Invoke(context.Background(), 1, compose.WithCheckPointID(cpID))
+ if err == nil {
+ t.Fatal("expected interrupt, got nil")
+ }
+ interruptID := r3FirstInterruptID(t, err)
+ // Process 1 "crashes" — compiled1 is discarded.
+
+ // Process 2: fresh compile (same store, same cpID), resume.
+ compiled2, err := build().Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"B"}),
+ )
+ if err != nil {
+ t.Fatalf("compile2: %v", err)
+ }
+ resumeCtx := compose.ResumeWithData(context.Background(), interruptID, nil)
+ out, err := compiled2.Invoke(resumeCtx, 1, compose.WithCheckPointID(cpID))
+ if err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if out != 14 {
+ t.Fatalf("output: got %d, want 14", out)
+ }
+ if aCount != 1 || bCount != 1 || cCount != 1 {
+ t.Fatalf("cross-process rerun: A=%d B=%d C=%d; want all 1", aCount, bCount, cCount)
+ }
+}
+
+// TestR3_LoopInDAG_InterruptAfterPreLoopNode covers the ingestion-relevant
+// topology: A -> loop(B->C) -> D, with WithInterruptAfterNodes([A]) (A is
+// non-terminal, immediately before the loop). The first run pauses after A;
+// resume must NOT re-run A, must enter and complete the loop, then run D.
+//
+// Loop math: in=1 -> A=2 -> loop iter1: B=20,C=21 (next=21<31) -> iter2:
+// B=210,C=211 (next=211>=31 quit, out=211) -> D=311.
+func TestR3_LoopInDAG_InterruptAfterPreLoopNode(t *testing.T) {
+ store := newInMemoryStore()
+ var aCount, bCount, cCount, dCount int
+
+ sub := compose.NewWorkflow[int, int]()
+ b := sub.AddLambdaNode("B", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ bCount++
+ return in * 10, nil
+ }))
+ c := sub.AddLambdaNode("C", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ cCount++
+ return in + 1, nil
+ }))
+ b.AddInput(compose.START)
+ c.AddInput("B")
+ sub.End().AddInput("C")
+
+ shouldQuit := func(_ context.Context, _, _, next int) (bool, error) {
+ return next >= 31, nil
+ }
+
+ outer := r3NewWorkflow[int, int]()
+ aNode := outer.AddLambdaNode("A", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ aCount++
+ return in + 1, nil
+ }))
+ loopNode, err := AddLoopNode(context.Background(), outer, "loop", sub, shouldQuit,
+ WithLoopMaxIterations(10),
+ WithLoopCheckpointIDBuilder(r3cp("r3-loop-pre")),
+ )
+ if err != nil {
+ t.Fatalf("AddLoopNode: %v", err)
+ }
+ aNode.AddInput(compose.START)
+ loopNode.AddInput("A")
+ dNode := outer.AddLambdaNode("D", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ dCount++
+ return in + 100, nil
+ }))
+ dNode.AddInput("loop")
+ outer.End().AddInput("D")
+
+ compiled, err := outer.Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"A"}),
+ )
+ if err != nil {
+ t.Fatalf("compile: %v", err)
+ }
+
+ cpID := "r3-loop-pre"
+ _, invokeErr := compiled.Invoke(context.Background(), 1, compose.WithCheckPointID(cpID))
+ if invokeErr == nil {
+ t.Fatal("expected interrupt after A, got nil")
+ }
+ resumeCtx := compose.ResumeWithData(context.Background(), r3FirstInterruptID(t, invokeErr), nil)
+ out, err := compiled.Invoke(resumeCtx, 1, compose.WithCheckPointID(cpID))
+ if err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+
+ if out != 311 {
+ t.Fatalf("output: got %d, want 311", out)
+ }
+ if aCount != 1 {
+ t.Fatalf("A ran %d times; want 1 (must not re-run on resume)", aCount)
+ }
+ if bCount != 2 || cCount != 2 {
+ t.Fatalf("loop ran B=%d C=%d; want 2 each", bCount, cCount)
+ }
+ if dCount != 1 {
+ t.Fatalf("D ran %d times; want 1", dCount)
+ }
+}
+
+// TestR3_LoopInDAG_InterruptAfterLoopNode is the strictest R3 case: the
+// after-node interrupt lands ON the loop node itself. The loop fully
+// executes in run 1 (B,C twice), then the graph pauses after the loop.
+// Resume must run D and must NOT re-execute the loop (B,C stay at 2).
+// This is exactly step 3's risk: an interrupt on a composite node whose
+// subtree already has checkpoint state.
+func TestR3_LoopInDAG_InterruptAfterLoopNode(t *testing.T) {
+ store := newInMemoryStore()
+ var aCount, bCount, cCount, dCount int
+
+ sub := compose.NewWorkflow[int, int]()
+ b := sub.AddLambdaNode("B", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ bCount++
+ return in * 10, nil
+ }))
+ c := sub.AddLambdaNode("C", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ cCount++
+ return in + 1, nil
+ }))
+ b.AddInput(compose.START)
+ c.AddInput("B")
+ sub.End().AddInput("C")
+
+ shouldQuit := func(_ context.Context, _, _, next int) (bool, error) {
+ return next >= 31, nil
+ }
+
+ outer := r3NewWorkflow[int, int]()
+ aNode := outer.AddLambdaNode("A", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ aCount++
+ return in + 1, nil
+ }))
+ loopNode, err := AddLoopNode(context.Background(), outer, "loop", sub, shouldQuit,
+ WithLoopMaxIterations(10),
+ WithLoopCheckpointIDBuilder(r3cp("r3-loop-node")),
+ )
+ if err != nil {
+ t.Fatalf("AddLoopNode: %v", err)
+ }
+ aNode.AddInput(compose.START)
+ loopNode.AddInput("A")
+ dNode := outer.AddLambdaNode("D", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ dCount++
+ return in + 100, nil
+ }))
+ dNode.AddInput("loop")
+ outer.End().AddInput("D")
+
+ compiled, err := outer.Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"loop"}),
+ )
+ if err != nil {
+ t.Fatalf("compile: %v", err)
+ }
+
+ cpID := "r3-loop-node"
+ _, invokeErr := compiled.Invoke(context.Background(), 1, compose.WithCheckPointID(cpID))
+ if invokeErr == nil {
+ t.Fatal("expected interrupt after loop, got nil")
+ }
+ resumeCtx := compose.ResumeWithData(context.Background(), r3FirstInterruptID(t, invokeErr), nil)
+ out, err := compiled.Invoke(resumeCtx, 1, compose.WithCheckPointID(cpID))
+ if err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+
+ if out != 311 {
+ t.Fatalf("output: got %d, want 311", out)
+ }
+ if aCount != 1 || bCount != 2 || cCount != 2 {
+ t.Fatalf("run1 partial rerun: A=%d B=%d C=%d; want 1/2/2", aCount, bCount, cCount)
+ }
+ if dCount != 1 {
+ t.Fatalf("D ran %d times; want 1", dCount)
+ }
+}
+
+// TestR3_ParallelInDAG_InterruptAfterParallelNode covers the Parallel branch
+// of R3: A -> parallel(B) -> D (outer type []int -> []int), with
+// WithInterruptAfterNodes([parallel]). Run 1: A + parallel run, pause after
+// parallel. Resume must run D and must NOT re-run A or the parallel fan-out
+// (B stays at len(input)).
+func TestR3_ParallelInDAG_InterruptAfterParallelNode(t *testing.T) {
+ store := newInMemoryStore()
+ var aCount, bCount, dCount int
+
+ sub := compose.NewWorkflow[int, int]()
+ b := sub.AddLambdaNode("B", compose.InvokableLambda(func(_ context.Context, in int) (int, error) {
+ bCount++
+ return in + 10, nil
+ }))
+ b.AddInput(compose.START)
+ sub.End().AddInput("B")
+
+ outer := r3NewWorkflow[[]int, []int]()
+ aNode := outer.AddLambdaNode("A", compose.InvokableLambda(func(_ context.Context, in []int) ([]int, error) {
+ aCount++
+ out := make([]int, len(in))
+ for i, v := range in {
+ out[i] = v + 1
+ }
+ return out, nil
+ }))
+ parNode, err := AddParallelNode(context.Background(), outer, "parallel", sub)
+ if err != nil {
+ t.Fatalf("AddParallelNode: %v", err)
+ }
+ aNode.AddInput(compose.START)
+ parNode.AddInput("A")
+ dNode := outer.AddLambdaNode("D", compose.InvokableLambda(func(_ context.Context, in []int) ([]int, error) {
+ dCount++
+ sum := 0
+ for _, v := range in {
+ sum += v
+ }
+ return []int{sum}, nil
+ }))
+ dNode.AddInput("parallel")
+ outer.End().AddInput("D")
+
+ compiled, err := outer.Compile(context.Background(),
+ compose.WithGraphName("root"),
+ compose.WithCheckPointStore(store),
+ compose.WithInterruptAfterNodes([]string{"parallel"}),
+ )
+ if err != nil {
+ t.Fatalf("compile: %v", err)
+ }
+
+ cpID := "r3-parallel"
+ input := []int{1, 2, 3}
+ _, invokeErr := compiled.Invoke(context.Background(), input, compose.WithCheckPointID(cpID))
+ if invokeErr == nil {
+ t.Fatal("expected interrupt after parallel, got nil")
+ }
+ resumeCtx := compose.ResumeWithData(context.Background(), r3FirstInterruptID(t, invokeErr), nil)
+ out, err := compiled.Invoke(resumeCtx, input, compose.WithCheckPointID(cpID))
+ if err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+
+ // A: [2,3,4]; parallel: [12,13,14]; D: sum=39 -> [39]
+ if len(out) != 1 || out[0] != 39 {
+ t.Fatalf("output: got %v, want [39]", out)
+ }
+ if aCount != 1 {
+ t.Fatalf("A ran %d times; want 1", aCount)
+ }
+ if bCount != 3 {
+ t.Fatalf("parallel fan-out ran B %d times; want 3 (one per item, no re-run on resume)", bCount)
+ }
+ if dCount != 1 {
+ t.Fatalf("D ran %d times; want 1", dCount)
+ }
+}
diff --git a/internal/cli/user_command.go b/internal/cli/user_command.go
index 2c633c8425..779b54c40e 100644
--- a/internal/cli/user_command.go
+++ b/internal/cli/user_command.go
@@ -3548,10 +3548,7 @@ func (c *CLI) APIParseLocalFileCommand(cmd *Command) (ResponseIf, error) {
}
fileType := utility.GetFileType(filename)
- config := map[string]string{
- "lib_type": "office_oxide",
- }
- fileParser, err := parser.GetParser(fileType, config)
+ fileParser, err := parser.GetParser(fileType)
if err != nil {
return nil, err
}
diff --git a/internal/dao/ingestion.go b/internal/dao/ingestion.go
index cc27860163..860f81f930 100644
--- a/internal/dao/ingestion.go
+++ b/internal/dao/ingestion.go
@@ -91,6 +91,12 @@ func (dao *IngestionTaskDAO) UpdateStatus(taskID, status string) error {
return DB.Model(&entity.IngestionTask{}).Where("id = ?", taskID).Update("status", status).Error
}
+// UpdateComponentTotal records the number of components in the task's DSL
+// graph. It is the authoritative denominator for progress percentage.
+func (dao *IngestionTaskDAO) UpdateComponentTotal(taskID string, total int) error {
+ return DB.Model(&entity.IngestionTask{}).Where("id = ?", taskID).Update("component_total", total).Error
+}
+
// CheckAnd called by ingestor
// if task status is RUNNING, COMPLETED, STOPPED, FAILED, just return without error
// if task status is CREATE, update to RUNNING
@@ -258,26 +264,10 @@ func (dao *IngestionTaskDAO) RemoveByAPIServerOrAdminServer(taskID string, userI
taskStatus := tasks[0].Status
switch taskStatus {
case common.CREATED, common.STOPPED, common.COMPLETED, common.FAILED:
- // get all ingestion task log
- var taskLogs []*entity.IngestionTaskLog
- err = tx.Where("task_id = ?", taskID).Find(&taskLogs).Error
- if err != nil {
- return nil, err
- }
-
- fileMap := make(map[string]bool)
- for _, taskLog := range taskLogs {
- files, ok := taskLog.Checkpoint["files"].([]string)
- if ok {
- for _, file := range files {
- fileMap[file] = true
- }
- }
- }
+ // ingestion_task_log no longer carries file references (the old
+ // checkpoint JSON column was dropped in favor of typed columns), so
+ // there are no task-level files to delete here.
var filesToDelete []string
- for file := range fileMap {
- filesToDelete = append(filesToDelete, file)
- }
err = tx.Model(&entity.IngestionTask{}).Where("id = ?", taskID).Delete(&entity.IngestionTask{}).Error
if err != nil {
@@ -356,12 +346,76 @@ func (dao *IngestionTaskLogDAO) Update(ingestionLog *entity.IngestionTaskLog) er
return DB.Save(ingestionLog).Error
}
+// ListLogsByTaskID returns the task's logs in chronological (write) order.
+// Ordering is by auto-increment `id ASC` (NOT `create_time`) because
+// create_time has only second-level resolution and would tie-break
+// arbitrarily; `id` is monotonic and always reflects write order. This
+// feeds the frontend log stream (GET .../logs), which renders each row by
+// phase (0 started / 1 done / -1 failed).
func (dao *IngestionTaskLogDAO) ListLogsByTaskID(taskID string) ([]*entity.IngestionTaskLog, error) {
var tasks []*entity.IngestionTaskLog
- err := DB.Where("task_id = ?", taskID).Order("create_time DESC").Find(&tasks).Error
+ err := DB.Where("task_id = ?", taskID).Order("id ASC").Find(&tasks).Error
return tasks, err
}
+// TaskProgress is the server-side aggregate of a task's component progress,
+// served by GET /api/v1/ingestion_task/{task_id}/progress so the frontend
+// can render a progress bar without pulling the full log stream.
+type TaskProgress struct {
+ Total int `json:"total"`
+ Done int `json:"done"`
+ Failed int `json:"failed"`
+ Running int `json:"running"`
+ Percent float64 `json:"percent"`
+}
+
+// AggregateProgress computes {total, done, failed, running, percent} for a
+// task purely in SQL. It takes each component's latest row (max id per
+// component) and classifies by its phase:
+//
+// done = latest phase is exit/success (1)
+// failed = latest phase is error/failure (-1 legacy, or 2 after 1c)
+// running = anything else (started, 0)
+//
+// `total` is the authoritative denominator from ingestion_task.component_total.
+// The classification is forward-compatible with the §5.1 ProgressPhase
+// renumbering (exit=1 stays; error moves -1 -> 2).
+func (dao *IngestionTaskLogDAO) AggregateProgress(taskID string, total int) (*TaskProgress, error) {
+ // Latest row id per component for this task.
+ latestIDs := DB.Model(&entity.IngestionTaskLog{}).
+ Select("MAX(id)").
+ Where("task_id = ?", taskID).
+ Group("component")
+
+ type phaseRow struct {
+ Phase int
+ }
+ var rows []phaseRow
+ err := DB.Model(&entity.IngestionTaskLog{}).
+ Select("phase").
+ Where("id IN (?)", latestIDs).
+ Scan(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+
+ progress := &TaskProgress{Total: total}
+ for _, r := range rows {
+ switch {
+ case r.Phase == 1:
+ progress.Done++
+ case r.Phase < 0 || r.Phase == 2:
+ progress.Failed++
+ default:
+ progress.Running++
+ }
+ }
+ if total > 0 {
+ progress.Percent = float64(progress.Done) / float64(total) * 100
+ }
+ return progress, nil
+}
+
func (dao *IngestionTaskLogDAO) LatestLogByTaskID(taskID string) (*entity.IngestionTaskLog, error) {
var task *entity.IngestionTaskLog
err := DB.Where("task_id = ?", taskID).Order("create_time DESC").First(&task).Error
diff --git a/internal/deepdoc/parser/pdf/batch_smoke_test.go b/internal/deepdoc/parser/pdf/batch_smoke_test.go
index 2a5bd817f7..aee547eecd 100644
--- a/internal/deepdoc/parser/pdf/batch_smoke_test.go
+++ b/internal/deepdoc/parser/pdf/batch_smoke_test.go
@@ -90,7 +90,7 @@ func variantFromEnv() string {
}
type outputDirs struct {
- text, tables, dla, tsrRaw string
+ text, tables, dla string
}
func mkOutputDirs(variant string) outputDirs {
@@ -98,12 +98,10 @@ func mkOutputDirs(variant string) outputDirs {
text: filepath.Join("testdata", "output", "go", variant, "text"),
tables: filepath.Join("testdata", "output", "go", variant, "tables"),
dla: filepath.Join("testdata", "output", "go", variant, "dla"),
- tsrRaw: filepath.Join("testdata", "output", "go", variant, "tsr_raw"),
}
os.MkdirAll(d.text, 0755)
os.MkdirAll(d.tables, 0755)
os.MkdirAll(d.dla, 0755)
- os.MkdirAll(d.tsrRaw, 0755)
return d
}
@@ -344,15 +342,10 @@ func writeOutputs(dirs outputDirs, name string, parsed *pdf.ParseResult, res *pa
os.WriteFile(filepath.Join(dirs.tables, name+".json"), b, 0644)
}
- // ── DLA + TSR debug intermediates ──
- if parsed.DLADebug != nil {
- if b, _ := json.MarshalIndent(parsed.DLADebug, "", " "); b != nil {
+ // ── DLA layout intermediates ──
+ if parsed.DLARegions != nil {
+ if b, _ := json.MarshalIndent(parsed.DLARegions, "", " "); b != nil {
os.WriteFile(filepath.Join(dirs.dla, name+".json"), b, 0644)
}
}
- if parsed.TSRDebug != nil {
- if b, _ := json.MarshalIndent(parsed.TSRDebug, "", " "); b != nil {
- os.WriteFile(filepath.Join(dirs.tsrRaw, name+".json"), b, 0644)
- }
- }
}
diff --git a/internal/deepdoc/parser/pdf/inference/cache.go b/internal/deepdoc/parser/pdf/inference/cache.go
new file mode 100644
index 0000000000..4183aa2d18
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/inference/cache.go
@@ -0,0 +1,239 @@
+//
+// 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 inference
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "image"
+ "time"
+
+ "ragflow/internal/deepdoc/parser/pdf/util"
+ doctype "ragflow/internal/deepdoc/parser/type"
+ "ragflow/internal/engine/redis"
+)
+
+// DefaultCacheTTL is the cache entry lifetime applied when the
+// caller does not supply one. 1 hour matches the python
+// deepdoc cache policy.
+const DefaultCacheTTL = time.Hour
+
+// cacheKeyPrefix namespaces DocAnalyzer cache entries so they
+// do not collide with other Redis users in the same database.
+const cacheKeyPrefix = "ddoc:cache:"
+
+// cacheStore abstracts the Redis-side persistence so the
+// wrapper can be exercised against an in-memory fake in unit
+// tests. The interface intentionally mirrors only the
+// operations the cache needs; Redis features beyond this stay
+// out of the wrapping path.
+type cacheStore interface {
+ Enabled() bool
+ GetObj(key string, dest any) bool
+ SetObj(key string, value any, ttl time.Duration) bool
+}
+
+// redisCacheStore is the production store, backed by the
+// package-level Redis singleton. When Redis is unconfigured
+// the package-level methods become no-ops (return false / treat
+// as miss), which is exactly the behaviour we want.
+type redisCacheStore struct{}
+
+// Enabled forwards to redis.IsEnabled().
+func (redisCacheStore) Enabled() bool { return redis.IsEnabled() }
+
+// GetObj forwards to the package-level Redis singleton.
+// Errors are logged inside the engine; we treat any failure
+// (including connectivity) as a cache miss for safety.
+func (redisCacheStore) GetObj(key string, dest any) bool {
+ return redis.Get().GetObj(key, dest)
+}
+
+// SetObj forwards to the package-level Redis singleton.
+func (redisCacheStore) SetObj(key string, value any, ttl time.Duration) bool {
+ return redis.Get().SetObj(key, value, ttl)
+}
+
+// DocAnalyzerCache wraps an inner doctype.DocAnalyzer and
+// transparently caches its 4 image-keyed methods in Redis.
+//
+// Behaviour:
+//
+// - If the store is disabled, the wrapper passes every call
+// straight through to the inner analyser. Tests and
+// developer machines without Redis configured see no
+// behavioural change.
+// - On cache hit the inner call is skipped entirely.
+// - On cache miss the inner call runs; its successful result
+// is JSON-serialised and stored under the deterministic
+// sha256-based key with the configured TTL.
+// - Health() is a pure passthrough; caching it would not be
+// semantically meaningful.
+//
+// The wrapper is safe for concurrent use: the cache lookup
+// path uses only the store's own synchronisation, so callers
+// can route per-image OCR through OCRRecognize from multiple
+// page workers without additional locking.
+type DocAnalyzerCache struct {
+ inner doctype.DocAnalyzer
+ store cacheStore
+ ttl time.Duration
+}
+
+// NewDocAnalyzerCache wraps inner with a Redis-backed cache
+// using the supplied TTL (use DefaultCacheTTL for 1h). When
+// Redis is not configured, the wrapper transparently degrades
+// to a pass-through.
+func NewDocAnalyzerCache(inner doctype.DocAnalyzer, ttl time.Duration) *DocAnalyzerCache {
+ if ttl <= 0 {
+ ttl = DefaultCacheTTL
+ }
+ return &DocAnalyzerCache{
+ inner: inner,
+ store: redisCacheStore{},
+ ttl: ttl,
+ }
+}
+
+// newDocAnalyzerCacheWithStore is the test seam. Production
+// code uses NewDocAnalyzerCache; tests inject a fake store to
+// drive the cache behaviour deterministically without
+// depending on a running Redis.
+func newDocAnalyzerCacheWithStore(inner doctype.DocAnalyzer, s cacheStore, ttl time.Duration) *DocAnalyzerCache {
+ if ttl <= 0 {
+ ttl = DefaultCacheTTL
+ }
+ return &DocAnalyzerCache{inner: inner, store: s, ttl: ttl}
+}
+
+// cacheKey returns the cache key used for the given method +
+// image. It encodes the image to JPEG (matching what the
+// inference HTTP client actually sends) and hashes the
+// resulting bytes. JPEG encoding is deterministic for a given
+// image and quality, so two DocAnalyzer calls with the same
+// image content produce the same key.
+func cacheKey(method string, img image.Image) (string, error) {
+ if img == nil {
+ return "", fmt.Errorf("%s: nil image", method)
+ }
+ data, err := util.EncodeJPEG(img)
+ if err != nil {
+ return "", fmt.Errorf("%s: encode: %w", method, err)
+ }
+ sum := sha256.Sum256(data)
+ return fmt.Sprintf("%s%s:%s", cacheKeyPrefix, method, hex.EncodeToString(sum[:])), nil
+}
+
+// cacheKeyOrEmpty returns the cache key for img, or "" if the
+// image should bypass caching (nil image, encode failure). The
+// empty string is the "no key" sentinel — callers must skip
+// the cache and call inner directly in that case.
+func cacheKeyOrEmpty(method string, img image.Image) string {
+ k, err := cacheKey(method, img)
+ if err != nil {
+ return ""
+ }
+ return k
+}
+
+// DLA see doctype.DocAnalyzer.
+func (c *DocAnalyzerCache) DLA(ctx context.Context, img image.Image) ([]doctype.DLARegion, error) {
+ if key := cacheKeyOrEmpty("dla", img); key != "" && c.store.Enabled() {
+ var cached []doctype.DLARegion
+ if c.store.GetObj(key, &cached) {
+ return cached, nil
+ }
+ }
+ out, err := c.inner.DLA(ctx, img)
+ if err != nil || img == nil {
+ return out, err
+ }
+ if key := cacheKeyOrEmpty("dla", img); key != "" && c.store.Enabled() {
+ c.store.SetObj(key, out, c.ttl)
+ }
+ return out, nil
+}
+
+// TSR see doctype.DocAnalyzer.
+func (c *DocAnalyzerCache) TSR(ctx context.Context, img image.Image) ([]doctype.TSRCell, error) {
+ if key := cacheKeyOrEmpty("tsr", img); key != "" && c.store.Enabled() {
+ var cached []doctype.TSRCell
+ if c.store.GetObj(key, &cached) {
+ return cached, nil
+ }
+ }
+ out, err := c.inner.TSR(ctx, img)
+ if err != nil || img == nil {
+ return out, err
+ }
+ if key := cacheKeyOrEmpty("tsr", img); key != "" && c.store.Enabled() {
+ c.store.SetObj(key, out, c.ttl)
+ }
+ return out, nil
+}
+
+// OCRDetect see doctype.DocAnalyzer.
+func (c *DocAnalyzerCache) OCRDetect(ctx context.Context, img image.Image) ([]doctype.OCRBox, error) {
+ if key := cacheKeyOrEmpty("ocr_detect", img); key != "" && c.store.Enabled() {
+ var cached []doctype.OCRBox
+ if c.store.GetObj(key, &cached) {
+ return cached, nil
+ }
+ }
+ out, err := c.inner.OCRDetect(ctx, img)
+ if err != nil || img == nil {
+ return out, err
+ }
+ if key := cacheKeyOrEmpty("ocr_detect", img); key != "" && c.store.Enabled() {
+ c.store.SetObj(key, out, c.ttl)
+ }
+ return out, nil
+}
+
+// OCRRecognize see doctype.DocAnalyzer.
+func (c *DocAnalyzerCache) OCRRecognize(ctx context.Context, img image.Image) ([]doctype.OCRText, error) {
+ if key := cacheKeyOrEmpty("ocr_recognize", img); key != "" && c.store.Enabled() {
+ var cached []doctype.OCRText
+ if c.store.GetObj(key, &cached) {
+ return cached, nil
+ }
+ }
+ out, err := c.inner.OCRRecognize(ctx, img)
+ if err != nil || img == nil {
+ return out, err
+ }
+ if key := cacheKeyOrEmpty("ocr_recognize", img); key != "" && c.store.Enabled() {
+ c.store.SetObj(key, out, c.ttl)
+ }
+ return out, nil
+}
+
+// Health see doctype.DocAnalyzer. Health probes are
+// deliberately uncached — caching the outcome would defeat the
+// purpose of a health check.
+func (c *DocAnalyzerCache) Health() bool {
+ if c == nil || c.inner == nil {
+ return false
+ }
+ return c.inner.Health()
+}
+
+// Compile-time guarantee that DocAnalyzerCache satisfies the
+// doctype.DocAnalyzer interface.
+var _ doctype.DocAnalyzer = (*DocAnalyzerCache)(nil)
diff --git a/internal/deepdoc/parser/pdf/inference/cache_test.go b/internal/deepdoc/parser/pdf/inference/cache_test.go
new file mode 100644
index 0000000000..2f74b67521
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/inference/cache_test.go
@@ -0,0 +1,375 @@
+//
+// 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 inference
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "image"
+ "image/color"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ doctype "ragflow/internal/deepdoc/parser/type"
+)
+
+// ── fake store ───────────────────────────────────────────────────────
+
+// fakeStore is an in-memory implementation of cacheStore used
+// by tests. Safe for concurrent use.
+type fakeStore struct {
+ mu sync.Mutex
+ enabled bool
+ data map[string][]byte
+ sets int32
+ gets int32
+}
+
+func newFakeStore() *fakeStore {
+ return &fakeStore{enabled: true, data: map[string][]byte{}}
+}
+
+func (s *fakeStore) Enabled() bool { return s.enabled }
+
+func (s *fakeStore) GetObj(key string, dest any) bool {
+ atomic.AddInt32(&s.gets, 1)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ raw, ok := s.data[key]
+ if !ok {
+ return false
+ }
+ return json.Unmarshal(raw, dest) == nil
+}
+
+func (s *fakeStore) SetObj(key string, value any, _ time.Duration) bool {
+ atomic.AddInt32(&s.sets, 1)
+ raw, err := json.Marshal(value)
+ if err != nil {
+ return false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.data[key] = raw
+ return true
+}
+
+// ── fake analyser ──────────────────────────────────────────────────
+
+// fakeAnalyzer is a deterministic, count-tracking DocAnalyzer.
+// Each method increments a counter and returns a value shaped
+// uniquely so a cache hit can be told apart from an inner call.
+type fakeAnalyzer struct {
+ dlaCount int32
+ tsrCount int32
+ ocrDetCnt int32
+ ocrRecCnt int32
+
+ healthy bool
+
+ dlaOut []doctype.DLARegion
+ tsrOut []doctype.TSRCell
+ ocrDet []doctype.OCRBox
+ ocrRec []doctype.OCRText
+ dlaErr error
+ tsrErr error
+ ocrDetEr error
+ ocrRecEr error
+}
+
+func (f *fakeAnalyzer) DLA(_ context.Context, _ image.Image) ([]doctype.DLARegion, error) {
+ atomic.AddInt32(&f.dlaCount, 1)
+ if f.dlaErr != nil {
+ return nil, f.dlaErr
+ }
+ return f.dlaOut, nil
+}
+
+func (f *fakeAnalyzer) TSR(_ context.Context, _ image.Image) ([]doctype.TSRCell, error) {
+ atomic.AddInt32(&f.tsrCount, 1)
+ if f.tsrErr != nil {
+ return nil, f.tsrErr
+ }
+ return f.tsrOut, nil
+}
+
+func (f *fakeAnalyzer) OCRDetect(_ context.Context, _ image.Image) ([]doctype.OCRBox, error) {
+ atomic.AddInt32(&f.ocrDetCnt, 1)
+ if f.ocrDetEr != nil {
+ return nil, f.ocrDetEr
+ }
+ return f.ocrDet, nil
+}
+
+func (f *fakeAnalyzer) OCRRecognize(_ context.Context, _ image.Image) ([]doctype.OCRText, error) {
+ atomic.AddInt32(&f.ocrRecCnt, 1)
+ if f.ocrRecEr != nil {
+ return nil, f.ocrRecEr
+ }
+ return f.ocrRec, nil
+}
+
+func (f *fakeAnalyzer) Health() bool { return f.healthy }
+
+// ── helpers ────────────────────────────────────────────────────────
+
+// newImage returns a tiny 4x4 RGBA image with stable pixel
+// content. JPEG encoding of identical pixel data is
+// deterministic, so the cache key for the same newImage() result
+// is the same across calls.
+func newImage(seed byte) *image.RGBA {
+ img := image.NewRGBA(image.Rect(0, 0, 4, 4))
+ for y := 0; y < 4; y++ {
+ for x := 0; x < 4; x++ {
+ img.SetRGBA(x, y, color.RGBA{seed, seed * 2, seed * 3, 255})
+ }
+ }
+ return img
+}
+
+// ── key tests ──────────────────────────────────────────────────────
+
+func TestCacheKey_Deterministic(t *testing.T) {
+ a, errA := cacheKey("dla", newImage(0x10))
+ if errA != nil {
+ t.Fatalf("cacheKey(dla,#1): %v", errA)
+ }
+ b, errB := cacheKey("dla", newImage(0x10))
+ if errB != nil {
+ t.Fatalf("cacheKey(dla,#2): %v", errB)
+ }
+ if a != b {
+ t.Fatalf("same image → different key: %q vs %q", a, b)
+ }
+ if want := cacheKeyPrefix + "dla:"; len(a) < len(want) || a[:len(want)] != want {
+ t.Fatalf("key missing prefix: %q", a)
+ }
+
+ c, errC := cacheKey("tsr", newImage(0x10))
+ if errC != nil {
+ t.Fatalf("cacheKey(tsr): %v", errC)
+ }
+ if c == a {
+ t.Fatal("different methods should yield different keys")
+ }
+
+ d, errD := cacheKey("dla", newImage(0x11))
+ if errD != nil {
+ t.Fatalf("cacheKey(dla,#2): %v", errD)
+ }
+ if d == a {
+ t.Fatal("different image bytes should yield different keys")
+ }
+}
+
+func TestCacheKey_NilImageErrors(t *testing.T) {
+ if _, err := cacheKey("dla", nil); err == nil {
+ t.Fatal("want error for nil image, got nil")
+ }
+}
+
+// ── cache hit / miss / disabled ────────────────────────────────────
+
+func TestDocAnalyzerCache_MissThenHit(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaOut: []doctype.DLARegion{{X0: 1, Y0: 2, X1: 3, Y1: 4, Label: "text"}},
+ }
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ img := newImage(0x20)
+
+ out1, err := c.DLA(context.Background(), img)
+ if err != nil {
+ t.Fatalf("DLA #1: %v", err)
+ }
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 1 {
+ t.Fatalf("inner called %d times after first DLA, want 1", got)
+ }
+ if got := atomic.LoadInt32(&s.sets); got != 1 {
+ t.Fatalf("store.SetObj called %d times after first DLA, want 1", got)
+ }
+
+ out2, err := c.DLA(context.Background(), img)
+ if err != nil {
+ t.Fatalf("DLA #2: %v", err)
+ }
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 1 {
+ t.Fatalf("inner called %d times after hit, want 1 (cached)", got)
+ }
+ if got := atomic.LoadInt32(&s.gets); got < 1 {
+ t.Fatalf("store.GetObj not called, want ≥1")
+ }
+
+ if len(out1) != len(out2) || out1[0].Label != out2[0].Label {
+ t.Fatalf("cached result diverged from inner: %v vs %v", out1, out2)
+ }
+}
+
+func TestDocAnalyzerCache_StoreDisabledPassthrough(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaOut: []doctype.DLARegion{{Label: "text"}},
+ }
+ s := newFakeStore()
+ s.enabled = false
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ img := newImage(0x30)
+ for i := 0; i < 3; i++ {
+ if _, err := c.DLA(context.Background(), img); err != nil {
+ t.Fatalf("DLA #%d: %v", i, err)
+ }
+ }
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 3 {
+ t.Fatalf("inner called %d times, want 3 (no caching when disabled)", got)
+ }
+ if got := atomic.LoadInt32(&s.sets); got != 0 {
+ t.Fatalf("store.SetObj called %d times, want 0", got)
+ }
+}
+
+func TestDocAnalyzerCache_NilImageBypassesCache(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaOut: []doctype.DLARegion{{Label: "noop"}},
+ }
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ for i := 0; i < 2; i++ {
+ if _, err := c.DLA(context.Background(), nil); err != nil {
+ t.Fatalf("DLA nil #%d: %v", i, err)
+ }
+ }
+ if got := atomic.LoadInt32(&s.sets); got != 0 {
+ t.Fatalf("nil image should bypass store.SetObj, got count %d", got)
+ }
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 2 {
+ t.Fatalf("inner called %d times, want 2 (nil → no cache)", got)
+ }
+}
+
+// ── all 4 methods ───────────────────────────────────────────────────
+
+func TestDocAnalyzerCache_AllMethods(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaOut: []doctype.DLARegion{{Label: "title"}},
+ tsrOut: []doctype.TSRCell{{X0: 0, Y0: 0, X1: 1, Y1: 1, Text: "A"}},
+ ocrDet: []doctype.OCRBox{{X0: 0, Y0: 0, X1: 10, Y1: 10}},
+ ocrRec: []doctype.OCRText{{Text: "x", Confidence: 0.9}},
+ }
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ img := newImage(0x40)
+
+ if _, err := c.DLA(context.Background(), img); err != nil {
+ t.Fatalf("DLA: %v", err)
+ }
+ if _, err := c.TSR(context.Background(), img); err != nil {
+ t.Fatalf("TSR: %v", err)
+ }
+ if _, err := c.OCRDetect(context.Background(), img); err != nil {
+ t.Fatalf("OCRDetect: %v", err)
+ }
+ if _, err := c.OCRRecognize(context.Background(), img); err != nil {
+ t.Fatalf("OCRRecognize: %v", err)
+ }
+
+ if got := atomic.LoadInt32(&s.sets); got != 4 {
+ t.Fatalf("store.SetObj called %d times, want 4", got)
+ }
+
+ if _, err := c.DLA(context.Background(), img); err != nil {
+ t.Fatalf("DLA #2: %v", err)
+ }
+ if _, err := c.TSR(context.Background(), img); err != nil {
+ t.Fatalf("TSR #2: %v", err)
+ }
+ if _, err := c.OCRDetect(context.Background(), img); err != nil {
+ t.Fatalf("OCRDetect #2: %v", err)
+ }
+ if _, err := c.OCRRecognize(context.Background(), img); err != nil {
+ t.Fatalf("OCRRecognize #2: %v", err)
+ }
+
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 1 {
+ t.Fatalf("DLA inner count = %d, want 1", got)
+ }
+ if got := atomic.LoadInt32(&inner.tsrCount); got != 1 {
+ t.Fatalf("TSR inner count = %d, want 1", got)
+ }
+ if got := atomic.LoadInt32(&inner.ocrDetCnt); got != 1 {
+ t.Fatalf("OCRDetect inner count = %d, want 1", got)
+ }
+ if got := atomic.LoadInt32(&inner.ocrRecCnt); got != 1 {
+ t.Fatalf("OCRRecognize inner count = %d, want 1", got)
+ }
+}
+
+// ── inner error propagation ─────────────────────────────────────────
+
+func TestDocAnalyzerCache_InnerErrorNotCached(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaErr: errors.New("inference service down"),
+ }
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ img := newImage(0x50)
+ if _, err := c.DLA(context.Background(), img); err == nil {
+ t.Fatal("want error, got nil")
+ }
+ if got := atomic.LoadInt32(&s.sets); got != 0 {
+ t.Fatalf("error result must not be cached, got sets=%d", got)
+ }
+}
+
+// ── Health passthrough ─────────────────────────────────────────────
+
+func TestDocAnalyzerCache_HealthPassthrough(t *testing.T) {
+ for _, healthy := range []bool{true, false} {
+ inner := &fakeAnalyzer{healthy: healthy}
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+ if got := c.Health(); got != healthy {
+ t.Fatalf("Health() = %v, want %v", got, healthy)
+ }
+ }
+}
+
+// ── different images → different keys ───────────────────────────────
+
+func TestDocAnalyzerCache_DifferentImagesBypassCache(t *testing.T) {
+ inner := &fakeAnalyzer{
+ dlaOut: []doctype.DLARegion{{Label: "a"}},
+ }
+ s := newFakeStore()
+ c := newDocAnalyzerCacheWithStore(inner, s, DefaultCacheTTL)
+
+ if _, err := c.DLA(context.Background(), newImage(0x80)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.DLA(context.Background(), newImage(0x81)); err != nil {
+ t.Fatal(err)
+ }
+ if got := atomic.LoadInt32(&inner.dlaCount); got != 2 {
+ t.Fatalf("inner called %d times for 2 different images, want 2", got)
+ }
+}
diff --git a/internal/deepdoc/parser/pdf/inference/client.go b/internal/deepdoc/parser/pdf/inference/client.go
index 22f367de43..0298720a18 100644
--- a/internal/deepdoc/parser/pdf/inference/client.go
+++ b/internal/deepdoc/parser/pdf/inference/client.go
@@ -12,7 +12,6 @@ import (
"mime/multipart"
"net"
"net/http"
- "sync"
"time"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
@@ -221,39 +220,6 @@ func (c *Client) OCRRecognize(ctx context.Context, cropped image.Image) ([]pdf.O
return texts, nil
}
-// OCRRecognizeBatch recognizes text in multiple cropped image regions.
-// Returns a slice of results and a parallel slice of errors (nil on success).
-// A nil cropped image in the input produces nil results and a non-nil error.
-func (c *Client) OCRRecognizeBatch(ctx context.Context, cropped []image.Image) ([][]pdf.OCRText, []error) {
- results := make([][]pdf.OCRText, len(cropped))
- errs := make([]error, len(cropped))
-
- // Process images concurrently with a bounded worker pool to avoid
- // overwhelming the DeepDoc service.
- const maxConcurrent = 4
- sem := make(chan struct{}, maxConcurrent)
- var wg sync.WaitGroup
-
- for i, img := range cropped {
- if img == nil {
- errs[i] = fmt.Errorf("ocr rec batch: image[%d] is nil", i)
- continue
- }
- wg.Add(1)
- go func(idx int, im image.Image) {
- defer wg.Done()
- sem <- struct{}{}
- defer func() { <-sem }()
-
- texts, err := c.OCRRecognize(ctx, im)
- results[idx] = texts
- errs[idx] = err
- }(i, img)
- }
- wg.Wait()
- return results, errs
-}
-
// Health checks whether the DeepDoc service is reachable.
func (c *Client) Health() bool {
resp, err := c.httpClient.Get(c.baseURL + "/health")
diff --git a/internal/deepdoc/parser/pdf/layout/boxes_sections.go b/internal/deepdoc/parser/pdf/layout/boxes_sections.go
index 70853df981..84cd19227c 100644
--- a/internal/deepdoc/parser/pdf/layout/boxes_sections.go
+++ b/internal/deepdoc/parser/pdf/layout/boxes_sections.go
@@ -1,7 +1,6 @@
package layout
import (
- "sort"
"strings"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
@@ -102,23 +101,6 @@ func NormalizeSectionPositions(sections []pdf.Section) {
}
}
-// SortByPageThenY sorts boxes by page → vertical key → x0.
-func SortByPageThenY(boxes []pdf.TextBox, sortByTop bool) {
- key := func(b pdf.TextBox) float64 { return b.Bottom }
- if sortByTop {
- key = func(b pdf.TextBox) float64 { return b.Top }
- }
- sort.Slice(boxes, func(i, j int) bool {
- if boxes[i].PageNumber != boxes[j].PageNumber {
- return boxes[i].PageNumber < boxes[j].PageNumber
- }
- if key(boxes[i]) != key(boxes[j]) {
- return key(boxes[i]) < key(boxes[j])
- }
- return boxes[i].X0 < boxes[j].X0
- })
-}
-
// SectionsToMarkdown converts Sections to a markdown string.
//
// Title sections get a "## " prefix.
diff --git a/internal/deepdoc/parser/pdf/layout/layout.go b/internal/deepdoc/parser/pdf/layout/layout.go
index 142e0cdaaa..1dc840d488 100644
--- a/internal/deepdoc/parser/pdf/layout/layout.go
+++ b/internal/deepdoc/parser/pdf/layout/layout.go
@@ -19,7 +19,7 @@ import (
// with silhouette score selection, matching Python's _assign_column().
//
// Python: pdf_parser.py:739 _assign_column()
-func AssignColumn(boxes []pdf.TextBox, zoom float64) []pdf.TextBox {
+func AssignColumn(boxes []pdf.TextBox) []pdf.TextBox {
if len(boxes) == 0 {
return boxes
}
@@ -162,7 +162,7 @@ func remapLabelsByCentroidOrder(centroids []float64) map[int]int {
// TextMerge horizontally merges adjacent boxes at similar vertical positions.
//
// Python: pdf_parser.py:888 _text_merge()
-func TextMerge(boxes []pdf.TextBox, medianHeights map[int]float64, zoom float64) []pdf.TextBox {
+func TextMerge(boxes []pdf.TextBox, medianHeights map[int]float64) []pdf.TextBox {
if len(boxes) < 2 {
return boxes
}
@@ -207,7 +207,7 @@ func TextMerge(boxes []pdf.TextBox, medianHeights map[int]float64, zoom float64)
// NaiveVerticalMerge vertically merges boxes on the same page/column.
//
// Python: pdf_parser.py:926 _naive_vertical_merge()
-func NaiveVerticalMerge(boxes []pdf.TextBox, medianHeights map[int]float64, medianWidths map[int]float64, isEnglish bool) []pdf.TextBox {
+func NaiveVerticalMerge(boxes []pdf.TextBox, medianHeights map[int]float64, medianWidths map[int]float64, pageEnglish map[int]bool) []pdf.TextBox {
if len(boxes) < 2 {
return boxes
}
@@ -234,7 +234,7 @@ func NaiveVerticalMerge(boxes []pdf.TextBox, medianHeights map[int]float64, medi
}
// Process boxes for this page
- processed := processPageBoxes(bxs, mh, mw, isEnglish)
+ processed := processPageBoxes(bxs, mh, mw, pageEnglish[pg])
result = append(result, processed...)
}
slog.Debug("vm result", "in", len(boxes), "out", len(result))
@@ -356,22 +356,56 @@ func mergeTwoBoxes(prev, curr pdf.TextBox) pdf.TextBox {
return prev
}
-// processPageBoxes processes all boxes for a single page
+// processPageBoxes vertically merges the boxes of a single page. Boxes are
+// bucketed by column (ColID) first so the merge never crosses columns; within
+// a column the merge runs top→bottom, and columns are emitted in ascending
+// ColID order (leftmost first). This preserves the column-major reading order
+// established by FinalReadingOrderMerge (page → ColID → top → x0).
func processPageBoxes(boxes []pdf.TextBox, mh, mw float64, isEnglish bool) []pdf.TextBox {
if len(boxes) == 0 {
return boxes
}
- // Sort by Top, X0
- sortedBoxes := make([]pdf.TextBox, len(boxes))
- copy(sortedBoxes, boxes)
- sort.Slice(sortedBoxes, func(i, j int) bool {
- if sortedBoxes[i].Top != sortedBoxes[j].Top {
- return sortedBoxes[i].Top < sortedBoxes[j].Top
+ colGroups, sortedCols := groupBoxesByCol(boxes)
+
+ out := make([]pdf.TextBox, 0, len(boxes))
+ for _, col := range sortedCols {
+ indices := colGroups[col]
+ bxs := make([]pdf.TextBox, len(indices))
+ for i, idx := range indices {
+ bxs[i] = boxes[idx]
}
- return sortedBoxes[i].X0 < sortedBoxes[j].X0
- })
+ // Sort within the column by Top, X0.
+ sort.Slice(bxs, func(i, j int) bool {
+ if bxs[i].Top != bxs[j].Top {
+ return bxs[i].Top < bxs[j].Top
+ }
+ return bxs[i].X0 < bxs[j].X0
+ })
+ out = append(out, mergeColumnBoxes(bxs, mh, mw, isEnglish)...)
+ }
+ return out
+}
+
+// groupBoxesByCol groups boxes by column id and returns the groups plus the
+// column ids in ascending order (leftmost column first).
+func groupBoxesByCol(boxes []pdf.TextBox) (map[int][]int, []int) {
+ colGroups := make(map[int][]int)
+ for i, b := range boxes {
+ colGroups[b.ColID] = append(colGroups[b.ColID], i)
+ }
+ colKeys := make([]int, 0, len(colGroups))
+ for c := range colGroups {
+ colKeys = append(colKeys, c)
+ }
+ sort.Ints(colKeys)
+ return colGroups, colKeys
+}
+// mergeColumnBoxes vertically merges boxes that already belong to one column
+// and are sorted top→bottom. It skips cross-page number suffixes and merges
+// vertically adjacent text.
+func mergeColumnBoxes(sortedBoxes []pdf.TextBox, mh, mw float64, isEnglish bool) []pdf.TextBox {
out := make([]pdf.TextBox, 0, len(sortedBoxes))
for i := 0; i < len(sortedBoxes); i++ {
curr := sortedBoxes[i]
diff --git a/internal/deepdoc/parser/pdf/layout/layout_test.go b/internal/deepdoc/parser/pdf/layout/layout_test.go
index c7ed9841e3..dd12e943af 100644
--- a/internal/deepdoc/parser/pdf/layout/layout_test.go
+++ b/internal/deepdoc/parser/pdf/layout/layout_test.go
@@ -27,7 +27,7 @@ func TestAssignColumn(t *testing.T) {
{PageNumber: 0, X0: 400, Text: "col1"},
{PageNumber: 1, X0: 50, Text: "pg1-col0"},
}
- result := AssignColumn(boxes, 3)
+ result := AssignColumn(boxes)
if len(result) != 4 {
t.Fatal("expected 4 boxes")
}
@@ -45,7 +45,7 @@ func TestTextMerge(t *testing.T) {
{PageNumber: 0, ColID: 0, X0: 252, X1: 550, Top: 100, Bottom: 112, Text: "右半", LayoutType: "text", LayoutNo: "1"},
}
meanH := map[int]float64{0: 12}
- result := TextMerge(boxes, meanH, 3)
+ result := TextMerge(boxes, meanH)
if len(result) != 1 {
t.Errorf("expected 1 merged box, got %d", len(result))
}
@@ -57,7 +57,7 @@ func TestTextMergeNoMerge_DiffLayout(t *testing.T) {
{PageNumber: 0, ColID: 0, X0: 252, X1: 550, Top: 100, Bottom: 112, Text: "table", LayoutType: "table", LayoutNo: "2"},
}
meanH := map[int]float64{0: 12}
- result := TextMerge(boxes, meanH, 3)
+ result := TextMerge(boxes, meanH)
if len(result) != 2 {
t.Error("table and text should not merge")
}
@@ -101,9 +101,6 @@ func TestDefaultConfig(t *testing.T) {
if cfg.Zoom != 3 {
t.Error("default zoom should be 3")
}
- if cfg.ToPage != -1 {
- t.Error("default to_page should be -1")
- }
}
func TestKmeans1D_Boundary(t *testing.T) {
@@ -246,7 +243,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 1 {
t.Errorf("expected 1 merged box, got %d", len(result))
@@ -272,7 +269,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 1 {
t.Errorf("expected 1 merged box (ASCII comma ',' should override period anti), got %d", len(result))
@@ -295,7 +292,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 1 {
t.Errorf("expected 1 merged box (next line starts with ','), got %d", len(result))
}
@@ -317,7 +314,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 1 {
t.Errorf("expected 1 merged box (next line starts with '。'), got %d", len(result))
}
@@ -342,7 +339,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
// Default merge — no anti, no detach, same layoutno, close gap.
if len(result) != 1 {
t.Errorf("expected 1 merged box (default merge when no anti/detach), got %d", len(result))
@@ -365,7 +362,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 50}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
// Even with '。' concat char, boxes are detached horizontally.
if len(result) != 2 {
t.Errorf("expected 2 boxes (horizontally detached), got %d", len(result))
@@ -388,7 +385,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
// Gap 200-112=88 > 12*1.5=18 — anti triggers.
if len(result) != 2 {
t.Errorf("expected 2 boxes (large vertical gap), got %d", len(result))
@@ -411,7 +408,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, true)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, map[int]bool{0: true})
// When isEnglish=true, endsWith ".!?" is anti — don't merge.
if len(result) != 2 {
t.Errorf("expected 2 boxes (english period anti), got %d", len(result))
@@ -434,7 +431,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
meanH := map[int]float64{0: 12, 1: 12}
meanW := map[int]float64{0: 200, 1: 200}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
// Different pages — NaiveVerticalMerge groups by page.
if len(result) != 2 {
t.Errorf("expected 2 boxes (different pages), got %d", len(result))
@@ -442,11 +439,11 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
})
t.Run("empty boxes", func(t *testing.T) {
- result := NaiveVerticalMerge(nil, nil, nil, false)
+ result := NaiveVerticalMerge(nil, nil, nil, nil)
if len(result) != 0 {
t.Error("expected empty result for nil input")
}
- result = NaiveVerticalMerge([]pdf.TextBox{}, nil, nil, false)
+ result = NaiveVerticalMerge([]pdf.TextBox{}, nil, nil, nil)
if len(result) != 0 {
t.Error("expected empty result for empty input")
}
@@ -456,7 +453,7 @@ func TestNaiveVerticalMerge_CommaConcat(t *testing.T) {
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 50, X1: 250, Top: 100, Bottom: 112, Text: "only", LayoutNo: "1"},
}
- result := NaiveVerticalMerge(boxes, nil, nil, false)
+ result := NaiveVerticalMerge(boxes, nil, nil, nil)
if len(result) != 1 {
t.Error("single box should be returned as-is")
}
@@ -478,7 +475,7 @@ func TestNaiveVerticalMerge_BottomShrink(t *testing.T) {
mh := map[int]float64{0: 50} // threshold = 50 * 1.5 = 75
mw := map[int]float64{0: 5}
- result := NaiveVerticalMerge(boxes, mh, mw, false)
+ result := NaiveVerticalMerge(boxes, mh, mw, nil)
if len(result) != 1 {
t.Fatalf("expected 1 merged box, got %d", len(result))
@@ -497,7 +494,7 @@ func TestNaiveVerticalMerge(t *testing.T) {
}
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 5}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 1 {
t.Errorf("expected 1 merged box, got %d: %v", len(result), result)
}
@@ -513,13 +510,97 @@ func TestNaiveVerticalMergeNonMerge(t *testing.T) {
}
meanH := map[int]float64{0: 12}
meanW := map[int]float64{0: 5}
- result := NaiveVerticalMerge(boxes, meanH, meanW, false)
+ result := NaiveVerticalMerge(boxes, meanH, meanW, nil)
if len(result) != 2 {
t.Errorf("expected 2 separate boxes (large gap), got %d", len(result))
}
}
-// ---- 重构辅助函数的测试 ----
+// TestNaiveVerticalMerge_MultiColumnOrder guards against the multi-column
+// reading-order regression: after AssignColumn assigns ColID, the final
+// reading order must be column-major (all of column 0, then all of column 1),
+// NOT interleaved by vertical (Top) position. The merge must never cross
+// columns.
+//
+// With interleaved tops (col0 at 100/300/500, col1 at 150/250/350/450) and
+// large enough vertical gaps that nothing merges, the old code (sort by
+// Top→X0 across the whole page) produced col0/col1 interleaving; the fix
+// buckets by ColID first so column 0 fully precedes column 1.
+func TestNaiveVerticalMerge_MultiColumnOrder(t *testing.T) {
+ boxes := []pdf.TextBox{
+ {PageNumber: 0, ColID: 0, X0: 50, X1: 250, Top: 100, Bottom: 112, Text: "L0-a", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 1, X0: 400, X1: 600, Top: 150, Bottom: 162, Text: "R0-a", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 1, X0: 400, X1: 600, Top: 250, Bottom: 262, Text: "R0-b", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 0, X0: 50, X1: 250, Top: 300, Bottom: 312, Text: "L0-b", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 1, X0: 400, X1: 600, Top: 350, Bottom: 362, Text: "R0-c", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 1, X0: 400, X1: 600, Top: 450, Bottom: 462, Text: "R0-d", LayoutNo: "1"},
+ {PageNumber: 0, ColID: 0, X0: 50, X1: 250, Top: 500, Bottom: 512, Text: "L0-c", LayoutNo: "1"},
+ }
+ meanH := map[int]float64{0: 12}
+ meanW := map[int]float64{0: 5}
+
+ merged := NaiveVerticalMerge(boxes, meanH, meanW, nil)
+ // Gaps are ~100–200 (>> 12*1.5=18), so nothing merges: 7 boxes out.
+ if len(merged) != 7 {
+ t.Fatalf("expected 7 separate boxes, got %d", len(merged))
+ }
+
+ // All column-0 boxes must precede all column-1 boxes.
+ seenCol1 := false
+ for _, b := range merged {
+ switch b.ColID {
+ case 0:
+ if seenCol1 {
+ t.Errorf("column 0 box %q appears after a column 1 box — reading order is not column-major", b.Text)
+ }
+ case 1:
+ seenCol1 = true
+ default:
+ t.Errorf("unexpected ColID %d", b.ColID)
+ }
+ }
+
+ // Within each column, order must be top→bottom.
+ col0Tops := []float64{}
+ col1Tops := []float64{}
+ for _, b := range merged {
+ if b.ColID == 0 {
+ col0Tops = append(col0Tops, b.Top)
+ } else {
+ col1Tops = append(col1Tops, b.Top)
+ }
+ }
+ for i := 1; i < len(col0Tops); i++ {
+ if col0Tops[i] < col0Tops[i-1] {
+ t.Errorf("column 0 not sorted top→bottom: %v", col0Tops)
+ }
+ }
+ for i := 1; i < len(col1Tops); i++ {
+ if col1Tops[i] < col1Tops[i-1] {
+ t.Errorf("column 1 not sorted top→bottom: %v", col1Tops)
+ }
+ }
+}
+
+func TestFinalReadingOrderMerge_ColumnMajor(t *testing.T) {
+ // Same interleaved scenario as the pipeline test, but at the
+ // FinalReadingOrderMerge level: column must dominate vertical position.
+ boxes := []pdf.TextBox{
+ {PageNumber: 0, ColID: 0, Top: 100, Text: "L0-a"},
+ {PageNumber: 0, ColID: 1, Top: 150, Text: "R0-a"},
+ {PageNumber: 0, ColID: 1, Top: 250, Text: "R0-b"},
+ {PageNumber: 0, ColID: 0, Top: 300, Text: "L0-b"},
+ }
+ result := FinalReadingOrderMerge(boxes)
+ want := []string{"L0-a", "L0-b", "R0-a", "R0-b"}
+ for i, w := range want {
+ if result[i].Text != w {
+ t.Errorf("position %d: want %q, got %q", i, w, result[i].Text)
+ }
+ }
+}
+
+// ---- Tests for refactored helper functions ----
func TestGroupBoxesByPage(t *testing.T) {
boxes := []pdf.TextBox{
diff --git a/internal/deepdoc/parser/pdf/mock_doc_analyzer.go b/internal/deepdoc/parser/pdf/mock_doc_analyzer.go
index 173f238cd3..7486092572 100644
--- a/internal/deepdoc/parser/pdf/mock_doc_analyzer.go
+++ b/internal/deepdoc/parser/pdf/mock_doc_analyzer.go
@@ -2,7 +2,6 @@ package pdf
import (
"context"
- "fmt"
"image"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
)
@@ -14,11 +13,6 @@ type MockDocAnalyzer struct {
TSRCells []pdf.TSRCell
OCRBoxes []pdf.OCRBox
OCRTexts []pdf.OCRText
- // OCRBatchTexts returns per-image texts for OCRRecognizeBatch.
- // If nil, OCRTexts is returned for every image.
- OCRBatchTexts [][]pdf.OCRText
- // OCRBatchErr makes OCRRecognizeBatch return an error for image i.
- OCRBatchErr func(i int) error
// Per-method error injection for testing failure paths.
DLAErr error
TSRErr error
@@ -52,23 +46,4 @@ func (m *MockDocAnalyzer) OCRRecognize(_ context.Context, _ image.Image) ([]pdf.
}
return m.OCRTexts, nil
}
-func (m *MockDocAnalyzer) OCRRecognizeBatch(_ context.Context, cropped []image.Image) ([][]pdf.OCRText, []error) {
- results := make([][]pdf.OCRText, len(cropped))
- errs := make([]error, len(cropped))
- for i, img := range cropped {
- if img == nil {
- errs[i] = fmt.Errorf("image[%d] is nil", i)
- continue
- }
- if m.OCRBatchErr != nil {
- errs[i] = m.OCRBatchErr(i)
- }
- if m.OCRBatchTexts != nil && i < len(m.OCRBatchTexts) {
- results[i] = m.OCRBatchTexts[i]
- } else {
- results[i] = m.OCRTexts
- }
- }
- return results, errs
-}
func (m *MockDocAnalyzer) Health() bool { return m.Healthy }
diff --git a/internal/deepdoc/parser/pdf/mock_engine.go b/internal/deepdoc/parser/pdf/mock_engine.go
index b8034f1459..90171ef0af 100644
--- a/internal/deepdoc/parser/pdf/mock_engine.go
+++ b/internal/deepdoc/parser/pdf/mock_engine.go
@@ -8,10 +8,11 @@ import (
// MockEngine is a minimal pdf.PDFEngine stub for unit/integration tests.
type MockEngine struct {
- Chars map[int][]pdf.TextChar
- NumPages int
- RenderW int
- RenderH int
+ Chars map[int][]pdf.TextChar
+ NumPages int
+ RenderW int
+ RenderH int
+ RenderPageImageFunc func(pg int, dpi float64) (image.Image, error)
}
func (m *MockEngine) ExtractChars(pg int) ([]pdf.TextChar, error) {
@@ -21,6 +22,9 @@ func (m *MockEngine) RenderPage(pg int, dpi float64) ([]byte, error) {
return nil, ErrNoPDFData
}
func (m *MockEngine) RenderPageImage(pg int, dpi float64) (image.Image, error) {
+ if m.RenderPageImageFunc != nil {
+ return m.RenderPageImageFunc(pg, dpi)
+ }
w, h := m.RenderW, m.RenderH
if w <= 0 {
w = 100
diff --git a/internal/deepdoc/parser/pdf/ocr_merge_test.go b/internal/deepdoc/parser/pdf/ocr_merge_test.go
index fe34dfe0fa..357b105f62 100644
--- a/internal/deepdoc/parser/pdf/ocr_merge_test.go
+++ b/internal/deepdoc/parser/pdf/ocr_merge_test.go
@@ -7,6 +7,7 @@ import (
"image/png"
"os"
inf "ragflow/internal/deepdoc/parser/pdf/inference"
+ pdftype "ragflow/internal/deepdoc/parser/pdf/type"
util "ragflow/internal/deepdoc/parser/pdf/util"
"strings"
"testing"
@@ -61,7 +62,9 @@ func TestOCR_mergeChars_RealScanned(t *testing.T) {
t.Fatal(err)
}
- boxes := ocrMergeChars(context.Background(), img, chars, dd, 0)
+ p := NewParser(pdftype.ParserConfig{})
+
+ boxes := p.ocrMergeChars(context.Background(), img, chars, dd, 0)
t.Logf("ocrMergeChars boxes: %d", len(boxes))
for i, b := range boxes {
// Save go render for comparison
@@ -74,7 +77,7 @@ func TestOCR_mergeChars_RealScanned(t *testing.T) {
i, b.X0, b.Top, b.X1, b.Bottom, b.Text[:end])
}
- scanBoxes := ocrDetectAndRecognize(context.Background(), img, dd, 0, "scan page")
+ scanBoxes := p.ocrDetectAndRecognize(context.Background(), img, dd, 0, "scan page")
t.Logf("ocrScanPage boxes (no chars): %d", len(scanBoxes))
for i, b := range scanBoxes {
end := min(120, len(b.Text))
diff --git a/internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go b/internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go
deleted file mode 100644
index 6c6f834304..0000000000
--- a/internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go
+++ /dev/null
@@ -1,196 +0,0 @@
-//go:build cgo
-
-package pdf
-
-import (
- "context"
- "errors"
- "image"
- pdf "ragflow/internal/deepdoc/parser/pdf/type"
- "testing"
-)
-
-func TestOCRRecognizeBatch_EmptyList(t *testing.T) {
- mock := &MockDocAnalyzer{Healthy: true}
- results, errs := mock.OCRRecognizeBatch(context.Background(), nil)
- if len(results) != 0 {
- t.Errorf("nil input: expected 0 results, got %d", len(results))
- }
- if len(errs) != 0 {
- t.Errorf("nil input: expected 0 errs, got %d", len(errs))
- }
- results, errs = mock.OCRRecognizeBatch(context.Background(), []image.Image{})
- if len(results) != 0 || len(errs) != 0 {
- t.Error("empty input: expected 0 results/errs")
- }
-}
-
-func TestOCRRecognizeBatch_SingleImage(t *testing.T) {
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{{Text: "hello", Confidence: 0.9}},
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy})
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
- if len(results[0]) != 1 || results[0][0].Text != "hello" {
- t.Errorf("expected 'hello', got %v", results[0])
- }
- if errs[0] != nil {
- t.Errorf("expected nil err, got %v", errs[0])
- }
-}
-
-func TestOCRRecognizeBatch_MultipleImages(t *testing.T) {
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRBatchTexts: [][]pdf.OCRText{
- {{Text: "img0", Confidence: 0.9}},
- {{Text: "img1", Confidence: 0.8}},
- {{Text: "img2", Confidence: 0.7}},
- },
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy, dummy, dummy})
- if len(results) != 3 {
- t.Fatalf("expected 3 results, got %d", len(results))
- }
- for i, want := range []string{"img0", "img1", "img2"} {
- if len(results[i]) != 1 || results[i][0].Text != want {
- t.Errorf("image[%d]: expected %q, got %v", i, want, results[i])
- }
- if errs[i] != nil {
- t.Errorf("image[%d]: expected nil err, got %v", i, errs[i])
- }
- }
-}
-
-func TestOCRRecognizeBatch_NilImage(t *testing.T) {
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{{Text: "ok", Confidence: 0.9}},
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy, nil, dummy})
- if len(results) != 3 {
- t.Fatalf("expected 3 results, got %d", len(results))
- }
- if len(results[0]) == 0 || results[0][0].Text != "ok" {
- t.Errorf("image[0]: expected 'ok', got %v", results[0])
- }
- if results[1] != nil {
- t.Errorf("image[1]: nil image should get nil result, got %v", results[1])
- }
- if errs[1] == nil {
- t.Error("image[1]: nil image should get error")
- }
- if len(results[2]) == 0 || results[2][0].Text != "ok" {
- t.Errorf("image[2]: expected 'ok' after nil, got %v", results[2])
- }
-}
-
-func TestOCRRecognizeBatch_ErrorHandling(t *testing.T) {
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{{Text: "ok", Confidence: 0.9}},
- OCRBatchErr: func(i int) error {
- if i == 1 {
- return errors.New("simulated error")
- }
- return nil
- },
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy, dummy, dummy})
- if len(results) != 3 {
- t.Fatalf("expected 3 results, got %d", len(results))
- }
- // Image 0: OK
- if errs[0] != nil {
- t.Errorf("image[0]: expected nil err, got %v", errs[0])
- }
- // Image 1: error
- if errs[1] == nil {
- t.Error("image[1]: expected error")
- }
- // Image 2: OK (error only for index 1)
- if errs[2] != nil {
- t.Errorf("image[2]: expected nil err, got %v", errs[2])
- }
- // Results should still be returned alongside errors
- if results[0] == nil || results[0][0].Text != "ok" {
- t.Error("image[0]: result should be returned despite error on other image")
- }
- if results[2] == nil || results[2][0].Text != "ok" {
- t.Error("image[2]: result should be returned despite error on other image")
- }
-}
-
-func TestOCRRecognizeBatch_EmptyText(t *testing.T) {
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{}, // empty — simulate no text recognized
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy})
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
- if len(results[0]) != 0 {
- t.Errorf("expected empty texts, got %v", results[0])
- }
- if errs[0] != nil {
- t.Errorf("expected nil err for empty text, got %v", errs[0])
- }
-}
-
-func TestOCRRecognizeBatch_FallbackToOCRTexts(t *testing.T) {
- // When OCRBatchTexts is nil, fall back to OCRTexts for every image.
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{{Text: "default", Confidence: 0.5}},
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy, dummy, dummy})
- if len(results) != 3 {
- t.Fatalf("expected 3 results, got %d", len(results))
- }
- for i := 0; i < 3; i++ {
- if len(results[i]) != 1 || results[i][0].Text != "default" {
- t.Errorf("image[%d]: expected 'default', got %v", i, results[i])
- }
- if errs[i] != nil {
- t.Errorf("image[%d]: expected nil err, got %v", i, errs[i])
- }
- }
-}
-
-func TestOCRRecognizeBatch_PartialBatchTexts(t *testing.T) {
- // OCRBatchTexts shorter than images — remaining fall back to OCRTexts.
- mock := &MockDocAnalyzer{
- Healthy: true,
- OCRTexts: []pdf.OCRText{{Text: "fallback", Confidence: 0.5}},
- OCRBatchTexts: [][]pdf.OCRText{
- {{Text: "custom0", Confidence: 0.9}},
- },
- }
- dummy := image.NewRGBA(image.Rect(0, 0, 10, 10))
- results, errs := mock.OCRRecognizeBatch(context.Background(), []image.Image{dummy, dummy, dummy})
- if len(results) != 3 {
- t.Fatalf("expected 3 results, got %d", len(results))
- }
- if results[0][0].Text != "custom0" {
- t.Errorf("image[0]: expected 'custom0', got %q", results[0][0].Text)
- }
- if results[1][0].Text != "fallback" {
- t.Errorf("image[1]: expected 'fallback', got %q", results[1][0].Text)
- }
- if results[2][0].Text != "fallback" {
- t.Errorf("image[2]: expected 'fallback', got %q", results[2][0].Text)
- }
- if errs[0] != nil || errs[1] != nil || errs[2] != nil {
- t.Error("all errors should be nil")
- }
-}
diff --git a/internal/deepdoc/parser/pdf/page_batch_test.go b/internal/deepdoc/parser/pdf/page_batch_test.go
deleted file mode 100644
index 8b0c83b06a..0000000000
--- a/internal/deepdoc/parser/pdf/page_batch_test.go
+++ /dev/null
@@ -1,90 +0,0 @@
-//go:build cgo && manual
-
-package pdf
-
-import (
- "context"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "ragflow/internal/deepdoc/parser/pdf/tool"
- pdf "ragflow/internal/deepdoc/parser/pdf/type"
-)
-
-// TestParse_BatchEquivalence verifies that batched processing produces
-// the same output as processing all pages at once. Uses batchSize=1
-// (every page is its own batch) on a multi-page fixture to maximize
-// batch boundary stress.
-func TestParse_BatchEquivalence(t *testing.T) {
- data, err := readTestPDF(t, "03_multipage.pdf")
- if err != nil {
- t.Fatal(err)
- }
-
- parse := func(batchSize int) *pdf.ParseResult {
- eng, err := NewEngine(data)
- if err != nil {
- t.Fatal(err)
- }
- defer eng.Close()
- cfg := pdf.DefaultParserConfig()
- cfg.BatchSize = batchSize
- p := NewParser(cfg)
- result, err := p.ParseRaw(context.Background(), eng, mockDLA)
- if err != nil {
- t.Fatal(err)
- }
- return result
- }
-
- // No batching (all pages at once).
- full := parse(9999)
- // Aggressive batching (1 page per batch).
- batched := parse(1)
-
- // Compare section counts.
- if len(full.Sections) != len(batched.Sections) {
- t.Logf("section count: full=%d batched=%d (small diff acceptable at batch boundaries)",
- len(full.Sections), len(batched.Sections))
- }
-
- // Compare text content via CharSimilarity.
- fullText := sectionsText(full.Sections)
- batchedText := sectionsText(batched.Sections)
- charSim := tool.CharSimilarity(fullText, batchedText)
- t.Logf("CharSimilarity: %.1f%%", charSim)
- if charSim < 95 {
- t.Errorf("batch equivalence too low: CharSim=%.1f%% (want >= 95%%)", charSim)
- }
-
- // Compare metrics (should be identical or very close).
- t.Logf("Metrics: full=%+v batched=%+v", full.Metrics, batched.Metrics)
- if full.Metrics.BoxesInitial != batched.Metrics.BoxesInitial {
- t.Errorf("BoxesInitial: full=%d batched=%d",
- full.Metrics.BoxesInitial, batched.Metrics.BoxesInitial)
- }
-
- // Bug fix regression: PageImages must survive batched merge.
- if len(full.PageImages) == 0 {
- t.Error("full parse: PageImages should not be empty (3-page document)")
- }
- if len(batched.PageImages) == 0 {
- t.Error("batched parse: PageImages should be preserved across batches")
- }
-}
-
-func readTestPDF(t *testing.T, name string) ([]byte, error) {
- t.Helper()
- return os.ReadFile(filepath.Join("testdata", "pdfs", name))
-}
-
-func sectionsText(sections []pdf.Section) string {
- var sb strings.Builder
- for _, s := range sections {
- sb.WriteString(s.Text)
- sb.WriteByte('\n')
- }
- return sb.String()
-}
diff --git a/internal/deepdoc/parser/pdf/parse_cgo.go b/internal/deepdoc/parser/pdf/parse_cgo.go
index aae70ae232..7299ddcae2 100644
--- a/internal/deepdoc/parser/pdf/parse_cgo.go
+++ b/internal/deepdoc/parser/pdf/parse_cgo.go
@@ -10,13 +10,28 @@ import (
)
// Parse runs the full PDF extraction pipeline from raw bytes.
-// Creates and manages the PDF engine lifecycle internally.
+//
+// Engine lifetime / ownership: Parse creates the native PDF engine and
+// transfers ownership of it to the returned *pdf.ParseResult (result.Engine is
+// populated inside ParseRaw/processPages). The engine is intentionally kept
+// alive past Parse so the serialization step can still use it — most
+// importantly the markdown path (cropMarkdownFigures) renders and crops figure
+// images on demand. Parse must therefore NOT close the engine itself.
+//
+// The caller (the adapter layer: pdfParseResultToJSONWithOptions /
+// pdfParseResultToMarkdownWithOptions) releases the engine via result.Close()
+// once serialization is complete. The only place Parse closes the engine is on
+// its own error return, since in that case no ParseResult is handed back for
+// the caller to release.
func (p *Parser) Parse(ctx context.Context, data []byte, docAnalyzer pdf.DocAnalyzer) (*pdf.ParseResult, error) {
engine, err := NewEngine(data)
if err != nil {
return nil, fmt.Errorf("pdfoxide.NewEngine: %w", err)
}
- defer engine.Close()
-
- return p.ParseRaw(ctx, engine, docAnalyzer)
+ res, err := p.ParseRaw(ctx, engine, docAnalyzer)
+ if err != nil {
+ _ = engine.Close()
+ return nil, err
+ }
+ return res, nil
}
diff --git a/internal/deepdoc/parser/pdf/parser.go b/internal/deepdoc/parser/pdf/parser.go
index 8c4249309f..2204a34633 100644
--- a/internal/deepdoc/parser/pdf/parser.go
+++ b/internal/deepdoc/parser/pdf/parser.go
@@ -2,16 +2,17 @@ package pdf
import (
"context"
- "errors"
"fmt"
"image"
"log/slog"
+ "math"
"sync"
lyt "ragflow/internal/deepdoc/parser/pdf/layout"
tbl "ragflow/internal/deepdoc/parser/pdf/table"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
util "ragflow/internal/deepdoc/parser/pdf/util"
+ "ragflow/internal/utility"
)
// Parser is the core PDF text/layout extraction pipeline.
@@ -19,16 +20,45 @@ import (
// Stateless after construction — safe to reuse across documents.
type Parser struct {
Config pdf.ParserConfig
+ // deepInfOnce lazily initializes deepInf exactly once, so a Parser shared
+ // across goroutines does not race on the DeepDoc inference slot channel.
+ deepInfOnce sync.Once
+ // deepInf bounds concurrent DeepDoc (deepdoc) inference calls. Created
+ // on first use via limiters(); see parser_concurrency.go.
+ deepInf *deepInfLimiter
}
-// pageResult holds per-page output from extractPages.
+// pageResult holds per-page worker-local artifacts produced by
+// processAllPagesParallel. The struct is keyed by page number in a
+// map so worker completion order does not affect collection order;
+// final assembly sorts by page number before merging into ParseResult.
+//
+// Fatal vs recoverable policy:
+// - RenderPageToImage failure → recoverable: page may still produce
+// boxes from charsToBoxes fallback. The Err field carries the
+// render error for logging visibility.
+// - OCR detect/recognize failure → recoverable: page falls back to
+// embedded chars; Err carries the underlying failure if any.
+// - DLA/TSR failure → recoverable: page produces no tables for that
+// page; tables remain empty in the worker artifact.
+// - Worker-pool orchestration bugs → fatal: panic surfaces immediately.
type pageResult struct {
- pg int
- ocrBoxes []pdf.TextBox
- chars []pdf.TextChar
- ocrUsed bool
- pageImg image.Image
- err error
+ PageNumber int
+ Boxes []pdf.TextBox
+ Chars []pdf.TextChar
+ MedianH float64
+ MedianW float64
+ IsEnglish bool
+ IsScanNoise bool
+ OCRUsed bool
+ // PageHeight and PageWidth record the PDF-point dimensions of the
+ // winning page render (pixel dimensions divided by the per-page
+ // zoom). They are used by buildLayout without needing a zoom map.
+ PageHeight float64
+ PageWidth float64
+ Tables []pdf.TableItem
+ DLARegions []pdf.DLAPageRegions
+ Err error
}
// New creates a new Parser with the given config.
@@ -58,36 +88,9 @@ func NewTableBuilderFor(doc pdf.DocAnalyzer) pdf.TableBuilder {
// ParseRaw is the internal entry point: runs the core pipeline on an
// already-opened engine. Exported for tests that inject mock engines.
func (p *Parser) ParseRaw(ctx context.Context, engine pdf.PDFEngine, docAnalyzer pdf.DocAnalyzer) (*pdf.ParseResult, error) {
- tb := NewTableBuilderFor(docAnalyzer)
-
- _, fromPage, toPage, err := p.normalizePageRange(engine)
- if err != nil {
- return nil, fmt.Errorf("page count: %w", err)
- }
- if toPage < fromPage {
- return &pdf.ParseResult{PageImages: make(map[int]image.Image)}, nil
- }
-
- totalPages := toPage - fromPage + 1
- batchSize := p.getBatchSize()
-
- prescanChars, prescanMedianH, prescanMedianW, isEnglish, scanNoise := p.prescanPages(ctx, engine, fromPage, toPage, totalPages)
outlines := p.extractOutlines(engine)
- if totalPages <= batchSize {
- result, err := p.processPages(ctx, engine, fromPage, toPage,
- prescanChars, prescanMedianH, prescanMedianW, isEnglish, scanNoise,
- docAnalyzer, tb)
- if err != nil {
- return nil, err
- }
- result.Outlines = outlines
- return result, nil
- }
-
- result, err := p.processLargeDocument(ctx, engine, fromPage, toPage, batchSize,
- prescanChars, prescanMedianH, prescanMedianW, isEnglish, scanNoise,
- docAnalyzer, tb)
+ result, err := p.processPages(ctx, engine, docAnalyzer)
if err != nil {
return nil, err
}
@@ -97,59 +100,12 @@ func (p *Parser) ParseRaw(ctx context.Context, engine pdf.PDFEngine, docAnalyzer
// ── ParseRaw helper functions ───────────────────────────────────────────────
-// normalizePageRange normalizes the page range based on config and actual page count.
-func (p *Parser) normalizePageRange(engine pdf.PDFEngine) (pageCount, fromPage, toPage int, err error) {
- pageCount, err = engine.PageCount()
- if err != nil {
- return 0, 0, 0, err
- }
- fromPage = p.Config.FromPage
- if fromPage < 0 {
- fromPage = 0
- } else if fromPage >= pageCount {
- fromPage = pageCount - 1
- }
- toPage = p.Config.ToPage
- if toPage < 0 || toPage >= pageCount {
- toPage = pageCount - 1
- }
- if toPage < fromPage {
- toPage = fromPage
- }
- return pageCount, fromPage, toPage, nil
-}
-
-// getBatchSize returns the batch size, defaulting to 50 if <= 0.
-func (p *Parser) getBatchSize() int {
- batchSize := p.Config.BatchSize
- if batchSize <= 0 {
- batchSize = 50
+func documentPages(pageCount int) []int {
+ pages := make([]int, pageCount)
+ for pg := range pages {
+ pages[pg] = pg
}
- return batchSize
-}
-
-// prescanPages extracts chars from all pages and computes median heights/widths.
-func (p *Parser) prescanPages(ctx context.Context, engine pdf.PDFEngine, fromPage, toPage, totalPages int) (
- map[int][]pdf.TextChar, map[int]float64, map[int]float64, bool, bool,
-) {
- prescanChars := make(map[int][]pdf.TextChar)
- prescanMedianH := make(map[int]float64)
- prescanMedianW := make(map[int]float64)
-
- for pg := fromPage; pg <= toPage; pg++ {
- chars, extractErr := engine.ExtractChars(pg)
- if extractErr != nil {
- slog.Warn("prescan: ExtractChars failed", "page", pg, "err", extractErr)
- chars = nil
- }
- prescanChars[pg] = chars
- prescanMedianH[pg] = util.MedianCharHeight(chars)
- prescanMedianW[pg] = util.MedianCharWidth(chars)
- }
-
- isEnglish := util.DetectEnglish(prescanChars, totalPages, nil)
- scanNoise := util.IsScanNoise(util.FullTextFromChars(prescanChars))
- return prescanChars, prescanMedianH, prescanMedianW, isEnglish, scanNoise
+ return pages
}
// extractOutlines extracts the PDF outlines, returning nil on error.
@@ -162,180 +118,179 @@ func (p *Parser) extractOutlines(engine pdf.PDFEngine) []pdf.Outline {
return outlines
}
-// processLargeDocument processes a large document in batches.
-func (p *Parser) processLargeDocument(ctx context.Context, engine pdf.PDFEngine, fromPage, toPage, batchSize int,
- prescanChars map[int][]pdf.TextChar, prescanMedianH, prescanMedianW map[int]float64,
- isEnglish, scanNoise bool, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder,
-) (*pdf.ParseResult, error) {
- slog.Info("batched processing", "pages", toPage-fromPage+1, "batchSize", batchSize)
- result := &pdf.ParseResult{PageImages: make(map[int]image.Image)}
-
- for start := fromPage; start <= toPage; start += batchSize {
- if err := ctx.Err(); err != nil {
- return nil, fmt.Errorf("cancelled at batch starting page %d: %w", start, err)
- }
- end := min(start+batchSize-1, toPage)
-
- batchChars := make(map[int][]pdf.TextChar, end-start+1)
- batchMH := make(map[int]float64, end-start+1)
- batchMW := make(map[int]float64, end-start+1)
- for pg := start; pg <= end; pg++ {
- batchChars[pg] = prescanChars[pg]
- batchMH[pg] = prescanMedianH[pg]
- batchMW[pg] = prescanMedianW[pg]
- }
-
- batch, err := p.processPages(ctx, engine, start, end,
- batchChars, batchMH, batchMW, isEnglish, scanNoise,
- docAnalyzer, tb)
- if err != nil {
- return nil, err
- }
-
- p.mergeBatchResults(result, batch)
- }
- return result, nil
-}
-
-// mergeBatchResults merges the batch result into the main result.
-func (p *Parser) mergeBatchResults(result, batch *pdf.ParseResult) {
- result.Sections = append(result.Sections, batch.Sections...)
- result.Tables = append(result.Tables, batch.Tables...)
- if result.PageImages == nil {
- result.PageImages = make(map[int]image.Image)
- }
- for pg, img := range batch.PageImages {
- result.PageImages[pg] = img
+// ── Page worker pool ─────────────────────────────────────────────────────────
+
+// processPage executes a single page through the unified page-local path.
+// Both clean and garbled/empty pages flow through this function; the OCR
+// strategy is selected page-locally based on character quality. Worker
+// artifacts are returned in pageResult for the global assembly phase.
+//
+// Zoom retry is per-page: if the default zoom produces no boxes and
+// conditions allow (Zoom < 9, !SkipOCR, render succeeded), the page is
+// re-rendered at Config.Zoom × DlaScale and OCR/DLA are re-run. This
+// replaces the old document-wide retryZoom pass and ensures only pages
+// that actually need a higher zoom pay the memory cost.
+//
+// Cancellation: workers honor ctx.Err() before issuing expensive work.
+// Page-local OCR detection / recognition failures are recoverable; the
+// page falls back to charsToBoxes. RenderPageToImage failure is also
+// recoverable — the page may still emit chars-derived boxes.
+func (p *Parser) processPage(ctx context.Context, engine pdf.PDFEngine, pg int,
+ docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder,
+) pageResult {
+ chars, extractErr := engine.ExtractChars(pg)
+ if extractErr != nil {
+ slog.Warn("processPage: ExtractChars failed", "page", pg, "err", extractErr)
+ chars = nil
}
- result.Metrics.BoxesInitial += batch.Metrics.BoxesInitial
- result.Metrics.BoxesTextMerge += batch.Metrics.BoxesTextMerge
- result.Metrics.BoxesVertMerge += batch.Metrics.BoxesVertMerge
- result.Metrics.BoxesFinal += batch.Metrics.BoxesFinal
- result.Metrics.TablesCount += batch.Metrics.TablesCount
-}
+ medianH := util.MedianCharHeight(chars)
+ medianW := util.MedianCharWidth(chars)
+ isEnglish := util.DetectEnglishPage(chars, nil)
+ isScanNoise := util.IsScanNoise(util.FullTextFromChars(map[int][]pdf.TextChar{pg: chars}))
-// ── extractPages helper functions ───────────────────────────────────────────
-
-func (p *Parser) extractPages(ctx context.Context, engine pdf.PDFEngine,
- fromPage, toPage int,
- prescanChars map[int][]pdf.TextChar,
- medianHeights, medianWidths map[int]float64,
- pageImages map[int]image.Image,
- docAnalyzer pdf.DocAnalyzer,
-) ([]pdf.TextBox, map[int][]pdf.TextChar, bool, error) {
- pageCount := toPage - fromPage + 1
- results := make([]pageResult, pageCount)
-
- sem, wg := p.setupPageConcurrency()
-
- for i := 0; i < pageCount; i++ {
- pg := fromPage + i
- chars := prescanChars[pg]
-
- if len(chars) > 0 && !util.IsGarbledPage(chars) {
- if err := ctx.Err(); err != nil {
- results[i] = pageResult{pg: pg, err: fmt.Errorf("cancelled before sync page %d: %w", pg, err)}
- continue
- }
- results[i] = p.processPageSync(ctx, engine, pg, chars, pageImages, docAnalyzer)
- continue
+ if err := ctx.Err(); err != nil {
+ return pageResult{
+ PageNumber: pg,
+ Chars: chars,
+ MedianH: medianH,
+ MedianW: medianW,
+ IsEnglish: isEnglish,
+ IsScanNoise: isScanNoise,
+ Err: err,
}
-
- wg.Add(1)
- go func(i, pg int, chars []pdf.TextChar) {
- defer wg.Done()
- results[i] = p.processPageAsync(ctx, engine, pg, chars, sem, docAnalyzer)
- }(i, pg, chars)
- }
- wg.Wait()
- return p.collectPageResults(results, pageImages, medianHeights, medianWidths)
-}
-
-// setupPageConcurrency sets up the concurrency primitives for page processing.
-func (p *Parser) setupPageConcurrency() (chan struct{}, *sync.WaitGroup) {
- maxConc := p.Config.MaxOCRConcurrency
- if maxConc <= 0 {
- maxConc = 1
}
- return make(chan struct{}, maxConc), &sync.WaitGroup{}
-}
-// processPageSync processes a page synchronously (normal pages with non-garbled chars).
-func (p *Parser) processPageSync(ctx context.Context, engine pdf.PDFEngine, pg int, chars []pdf.TextChar,
- pageImages map[int]image.Image, docAnalyzer pdf.DocAnalyzer,
-) pageResult {
- pageImg, renderErr := RenderPageToImage(engine, pg)
- if renderErr == nil && pageImg != nil {
- pageImages[pg] = pageImg
- } else if renderErr != nil {
- slog.Warn("processPageSync: RenderPageToImage failed", "page", pg, "err", renderErr)
- }
-
- ocrBoxes, updatedChars, ocrUsed := p.processPageBoxes(ctx, pageImg, chars, pg, renderErr, docAnalyzer, false)
- return pageResult{pg: pg, ocrBoxes: ocrBoxes, chars: updatedChars, ocrUsed: ocrUsed}
-}
-
-// processPageAsync processes a page asynchronously (garbled pages or scan pages).
-func (p *Parser) processPageAsync(ctx context.Context, engine pdf.PDFEngine, pg int, chars []pdf.TextChar,
- sem chan struct{}, docAnalyzer pdf.DocAnalyzer,
-) pageResult {
- select {
- case <-ctx.Done():
- return pageResult{pg: pg, err: ctx.Err()}
- case sem <- struct{}{}:
+ // First pass: render at the default DLA DPI (216 DPI).
+ pageImg, renderErr := p.renderPageToImage(ctx, engine, pg)
+ pageZoom := pdf.DlaScale
+ var ocrBoxes []pdf.TextBox
+ var updatedChars []pdf.TextChar
+ var ocrUsed bool
+ var annotated []pdf.TextBox
+ var pageTables []pdf.TableItem
+ var dlaRegions []pdf.DLAPageRegions
+
+ if pageImg != nil && renderErr == nil {
+ ocrBoxes, updatedChars, ocrUsed = p.processPageBoxes(ctx, pageImg, chars, pg, renderErr, isScanNoise, docAnalyzer)
+ annotated, pageTables, dlaRegions = p.enrichOnePageWithDeepDoc(
+ ctx, pageImg, ocrBoxes, pg, renderErr, docAnalyzer, tb, pageZoom)
+ }
+
+ if renderErr != nil {
+ slog.Warn("processPage: RenderPageToImage failed", "page", pg, "err", renderErr)
+ }
+
+ // Per-page zoom retry: if no boxes were produced at the default zoom
+ // and conditions allow, re-render at a higher zoom and re-run OCR/DLA.
+ if len(annotated) == 0 && p.Config.Zoom >= 1.0 && !p.Config.SkipOCR && renderErr == nil {
+ // Cap the retry zoom so a large Config.Zoom cannot drive the retry
+ // render to an unsafe DPI and spike memory on large pages.
+ const maxRetryZoom = 9.0
+ retryZoom := math.Min(p.Config.Zoom*pdf.DlaScale, maxRetryZoom)
+ slog.Info("per-page zoom retry", "page", pg, "zoom", retryZoom)
+ retryImg, retryRenderErr := p.renderAtDPI(ctx, engine, pg, retryZoom*72)
+ if retryRenderErr == nil && retryImg != nil {
+ ocrBoxes, updatedChars, ocrUsed = p.processPageBoxes(ctx, retryImg, chars, pg, retryRenderErr, isScanNoise, docAnalyzer)
+ annotated, pageTables, dlaRegions = p.enrichOnePageWithDeepDoc(
+ ctx, retryImg, ocrBoxes, pg, retryRenderErr, docAnalyzer, tb, retryZoom)
+ pageImg = retryImg
+ pageZoom = retryZoom
+ } else if retryRenderErr != nil {
+ slog.Warn("processPage: retry-zoom render failed", "page", pg, "err", retryRenderErr)
+ }
}
- defer func() { <-sem }()
- pageImg, err := RenderPageToImage(engine, pg)
- if err != nil {
- return pageResult{pg: pg, err: err}
- }
- if err := ctx.Err(); err != nil {
- return pageResult{pg: pg, err: err}
+ // Compute PDF-point page dimensions from the winning render so
+ // buildLayout can use them without needing a per-page zoom map.
+ var pageHeight, pageWidth float64
+ if pageImg != nil && pageZoom > 0 {
+ pageHeight = float64(pageImg.Bounds().Dy()) / pageZoom
+ pageWidth = float64(pageImg.Bounds().Dx()) / pageZoom
+ }
+
+ return pageResult{
+ PageNumber: pg,
+ Boxes: annotated,
+ Chars: updatedChars,
+ MedianH: medianH,
+ MedianW: medianW,
+ IsEnglish: isEnglish,
+ IsScanNoise: isScanNoise,
+ OCRUsed: ocrUsed,
+ PageHeight: pageHeight,
+ PageWidth: pageWidth,
+ Tables: pageTables,
+ DLARegions: dlaRegions,
+ Err: renderErr,
}
-
- ocrBoxes, updatedChars, ocrUsed := p.processPageBoxes(ctx, pageImg, chars, pg, nil, docAnalyzer, true)
- return pageResult{pg: pg, ocrBoxes: ocrBoxes, chars: updatedChars, ocrUsed: ocrUsed, pageImg: pageImg}
}
-// processPageBoxes processes OCR box extraction for a page, shared between sync and async paths.
-// Returns (ocrBoxes, updatedChars, ocrUsed). The updatedChars includes synthetic OCR
-// chars appended when OCR detect+recognize succeeds — callers must use the returned
-// chars slice, not the original, to get correct median/layout calculations.
+// processPageBoxes picks the OCR strategy for a single page based on
+// character quality. There is no async/sync split: the decision is
+// page-local and the OCR call path is selected here.
+//
+// - Clean embedded chars (count > 0 and not garbled):
+// use ocrMergeChars, which detect-merges chars into boxes and falls
+// back to single-image OCR recognize for empty boxes.
+// - Garbled or empty chars: use ocrDetectAndRecognize for full OCR,
+// then fall back to ocrMergeChars if detect succeeds but recognize
+// produced no useful output. Synthetic chars are appended to support
+// subsequent median calculations.
+//
+// updatedChars includes synthetic OCR chars when detect+recognize was
+// used; callers must use the returned slice instead of the original.
+// processPageBoxes builds the page's text boxes — line/word-level, NOT
+// per-rune — either from embedded chars or via OCR, chosen by page quality.
+//
+// Parameters:
+// - pageImg: the page bitmap rendered at the DLA DPI (216 by default),
+// consumed by OCR detection/recognition.
+// - chars: per-glyph characters from ExtractChars (0-based page pg); the
+// finest-grained text unit. nil when the page has no embedded text.
+// - pg: page number (0-based), stamped onto every produced box.
+// - renderErr: non-nil skips OCR entirely and falls back to chars.
+// - isScanNoise: true marks a scanned/noisy page → prefer full OCR
+// detect+recognize over the embedded-char merge path.
+// - docAnalyzer: the DLA/OCR/Tensor backend (DeepDOC model) used for
+// detection and recognition.
+//
+// Returns:
+// - ocrBoxes: line/word-level []pdf.TextBox in PDF-point space; this is
+// the granularity fed into enrichOnePageWithDeepDoc as pageBoxes
+// (one box per line or per column-subline, never per rune).
+// - updatedChars: chars, possibly augmented with synthetic OCR-derived
+// glyphs so downstream median-height/width stats stay meaningful.
+// - bool: whether OCR was actually used to produce ocrBoxes.
func (p *Parser) processPageBoxes(ctx context.Context, pageImg image.Image, chars []pdf.TextChar, pg int,
- renderErr error, docAnalyzer pdf.DocAnalyzer, isAsync bool,
+ renderErr error, isScanNoise bool, docAnalyzer pdf.DocAnalyzer,
) ([]pdf.TextBox, []pdf.TextChar, bool) {
var ocrBoxes []pdf.TextBox
ocrUsed := false
- if !p.Config.SkipOCR {
- if isAsync {
+ if !p.Config.SkipOCR && renderErr == nil && pageImg != nil {
+ hasCleanChars := len(chars) > 0 && !isScanNoise && !util.IsGarbledPage(chars)
+ if hasCleanChars {
+ ocrBoxes = p.ocrMergeChars(ctx, pageImg, chars, docAnalyzer, pg)
+ ocrUsed = ocrBoxes != nil
+ } else {
label := "scan page"
- if len(chars) > 0 {
+ if len(chars) > 0 && !isScanNoise {
label = "garbled page"
}
- ocrBoxes = ocrDetectAndRecognize(ctx, pageImg, docAnalyzer, pg, label)
- if ocrBoxes != nil {
+ ocrBoxes = p.ocrDetectAndRecognize(ctx, pageImg, docAnalyzer, pg, label)
+ ocrUsed = ocrBoxes != nil
+ if ocrUsed {
+ // Synthetic OCR chars feed downstream median calculations.
for j := range ocrBoxes {
for _, r := range ocrBoxes[j].Text {
chars = append(chars, pdf.TextChar{Text: string(r), PageNumber: pg})
break
}
}
- ocrUsed = true
- }
- if !ocrUsed && len(chars) > 0 {
- ocrBoxes = ocrMergeChars(ctx, pageImg, chars, docAnalyzer, pg)
- if ocrBoxes != nil {
- ocrUsed = true
- }
- }
- } else {
- if renderErr == nil && pageImg != nil {
- ocrBoxes = ocrMergeChars(ctx, pageImg, chars, docAnalyzer, pg)
- if ocrBoxes != nil {
- ocrUsed = true
- }
+ } else if len(chars) > 0 {
+ // Detect failed but chars exist: try the merge path.
+ ocrBoxes = p.ocrMergeChars(ctx, pageImg, chars, docAnalyzer, pg)
+ ocrUsed = ocrBoxes != nil
}
}
}
@@ -349,270 +304,221 @@ func (p *Parser) processPageBoxes(ctx context.Context, pageImg image.Image, char
return ocrBoxes, chars, ocrUsed
}
-// collectPageResults collects and merges the per-page results.
-func (p *Parser) collectPageResults(results []pageResult, pageImages map[int]image.Image,
- medianHeights, medianWidths map[int]float64,
-) ([]pdf.TextBox, map[int][]pdf.TextChar, bool, error) {
- var boxes []pdf.TextBox
- pageChars := make(map[int][]pdf.TextChar)
- ocrUsedAny := false
- var errs []error
+// runPageWorkers executes pages through the single process-wide worker
+// pool (parserPageWorkerPool). Page concurrency is bounded by that pool's
+// worker count — there is no per-Parser parallelism knob; callers tune
+// throughput via SetPageWorkerPoolSize. Each page produces one pageResult
+// stored by page number so worker completion order does not affect
+// collection order. Workers record the first page-level error for caller
+// visibility, while context cancellation still stops new dispatch and lets
+// in-flight work observe ctx.Err().
+//
+// Pages are returned sorted by page number so callers can stream them
+// directly into downstream assembly without re-sorting.
+func (p *Parser) runPageWorkers(ctx context.Context, engine pdf.PDFEngine,
+ pages []int,
+ docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder,
+) ([]*pageResult, error) {
+ if len(pages) == 0 {
+ return nil, nil
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
- for _, r := range results {
- if r.err != nil {
- slog.Warn("page OCR failed", "page", r.pg, "err", r.err)
- errs = append(errs, fmt.Errorf("page %d: %w", r.pg, r.err))
- continue
+ resultMap := make(map[int]*pageResult, len(pages))
+ var firstErr error
+ recordErr := func(e error) {
+ if e != nil && firstErr == nil {
+ firstErr = e
}
- if r.ocrUsed {
- boxes = append(boxes, r.ocrBoxes...)
- ocrUsedAny = true
- } else if len(r.ocrBoxes) > 0 {
- boxes = append(boxes, r.ocrBoxes...)
+ }
+
+ type pageTaskResult = utility.WorkerPoolResult[pageTask, pageResult]
+ resultCh := make(chan pageTaskResult, len(pages))
+
+ submitted := 0
+ for _, pg := range pages {
+ task := pageTask{
+ parser: p,
+ engine: engine,
+ pageNumber: pg,
+ docAnalyzer: docAnalyzer,
+ tb: tb,
}
- if r.pageImg != nil {
- pageImages[r.pg] = r.pageImg
+ if err := parserPageWorkerPool().SubmitTo(ctx, task, resultCh); err != nil {
+ recordErr(err)
+ break
}
- pageChars[r.pg] = r.chars
- if r.ocrUsed {
- medianHeights[r.pg] = util.MedianCharHeight(r.chars)
- medianWidths[r.pg] = util.MedianCharWidth(r.chars)
+ submitted++
+ }
+
+ for i := 0; i < submitted; i++ {
+ taskResult := <-resultCh
+ r := taskResult.Value
+ r.PageNumber = taskResult.Input.pageNumber
+ if taskResult.Err != nil && r.Err == nil {
+ r.Err = taskResult.Err
+ }
+ if r.Err != nil {
+ recordErr(r.Err)
+ }
+ resultMap[r.PageNumber] = &r
+ }
+
+ results := make([]*pageResult, 0, len(pages))
+ for _, pg := range pages {
+ if r, ok := resultMap[pg]; ok {
+ results = append(results, r)
}
}
- return boxes, pageChars, ocrUsedAny, errors.Join(errs...)
+ return results, firstErr
}
// ── Internal pipeline steps ────────────────────────────────────────────────
-func (p *Parser) retryScanNoise(ctx context.Context, engine pdf.PDFEngine,
- fromPage, toPage int,
- pageImages map[int]image.Image,
- pageChars map[int][]pdf.TextChar,
- medianHeights, medianWidths map[int]float64,
- ocrUsedAny bool,
- docAnalyzer pdf.DocAnalyzer,
-) ([]pdf.TextBox, map[int][]pdf.TextChar, bool) {
- slog.Warn("scan noise: OCR retry", "from", fromPage, "to", toPage)
+// runAssembly merges per-page worker artifacts into the final document-wide
+// state. Document-wide layout, table merge/replace, cross-page figures, and
+// metrics aggregation happen here so page workers never mutate shared state.
+// pageResults are expected to be sorted by page number.
+func (p *Parser) assembleDocument(ctx context.Context, pages []int, pageResults []*pageResult) (*pdf.ParseResult, error) {
+ result := &pdf.ParseResult{
+ PageHeight: make(map[int]float64),
+ PageWidth: make(map[int]float64),
+ }
+
var boxes []pdf.TextBox
- for pg := fromPage; pg <= toPage; pg++ {
- img := pageImages[pg]
- if img == nil {
- var err error
- img, err = RenderPageToImage(engine, pg)
- if err != nil {
- slog.Warn("scan noise: page render failed", "page", pg, "err", err)
- continue
- }
- pageImages[pg] = img
- }
- ocrBoxes := ocrDetectAndRecognize(ctx, img, docAnalyzer, pg, "scan page")
- if ocrBoxes == nil {
- slog.Warn("scan noise: page OCR empty", "page", pg)
+ pageChars := make(map[int][]pdf.TextChar)
+ medianHeights := make(map[int]float64, len(pageResults))
+ medianWidths := make(map[int]float64, len(pageResults))
+ pageEnglish := make(map[int]bool, len(pageResults))
+
+ for _, r := range pageResults {
+ if r == nil {
continue
}
- boxes = append(boxes, ocrBoxes...)
- var chars []pdf.TextChar
- for _, b := range ocrBoxes {
- for _, r := range b.Text {
- chars = append(chars, pdf.TextChar{Text: string(r), Top: b.Top, Bottom: b.Bottom, PageNumber: pg})
- break
- }
+ if r.Err != nil {
+ slog.Warn("page worker failed", "page", r.PageNumber, "err", r.Err)
}
- pageChars[pg] = chars
- medianHeights[pg] = util.MedianCharHeight(chars)
- medianWidths[pg] = util.MedianCharWidth(chars)
- }
- slog.Debug("scan noise OCR retry complete", "pages", toPage-fromPage+1, "boxes", len(boxes))
- return boxes, pageChars, true
-}
-
-func (p *Parser) retryZoom(ctx context.Context, engine pdf.PDFEngine,
- fromPage, toPage int,
- pageImages map[int]image.Image,
- boxes []pdf.TextBox, ocrUsedAny bool,
- docAnalyzer pdf.DocAnalyzer,
-) ([]pdf.TextBox, bool) {
- retryZoomVal := p.Config.Zoom * pdf.DlaScale
- retryDPI := retryZoomVal * 72
- slog.Info("zoom retry: re-rendering", "oldZoom", p.Config.Zoom, "newZoom", retryZoomVal)
- for pg := fromPage; pg <= toPage; pg++ {
- img, err := engine.RenderPageImage(pg, retryDPI)
- if err != nil {
- slog.Warn("zoom retry: render failed", "page", pg, "err", err)
- continue
+ // Store per-page PDF-point dimensions for buildLayout.
+ if r.PageHeight > 0 {
+ result.PageHeight[r.PageNumber] = r.PageHeight
}
- pageImages[pg] = img
- if retryDPI != pdf.DlaDPI {
- if dlaImg, dlaErr := engine.RenderPageImage(pg, pdf.DlaDPI); dlaErr == nil {
- pageImages[pg] = dlaImg
- }
+ if r.PageWidth > 0 {
+ result.PageWidth[r.PageNumber] = r.PageWidth
}
- ocrBoxes := ocrDetectAndRecognize(ctx, img, docAnalyzer, pg, "zoom retry")
- if ocrBoxes == nil {
- continue
+ // Worker Boxes already carry DLA/TSR annotations (worker-local
+ // write-back happened inside processPage). Concatenate in page
+ // order to rebuild the document-wide boxes slice.
+ boxes = append(boxes, r.Boxes...)
+ pageChars[r.PageNumber] = r.Chars
+ medianHeights[r.PageNumber] = r.MedianH
+ medianWidths[r.PageNumber] = r.MedianW
+ pageEnglish[r.PageNumber] = r.IsEnglish
+ if r.OCRUsed {
+ medianHeights[r.PageNumber] = util.MedianCharHeight(r.Chars)
+ medianWidths[r.PageNumber] = util.MedianCharWidth(r.Chars)
+ pageEnglish[r.PageNumber] = util.DetectEnglishPage(r.Chars, nil)
}
- scaleFactor := retryZoomVal / p.Config.Zoom
- for i := range ocrBoxes {
- ocrBoxes[i].X0 /= scaleFactor
- ocrBoxes[i].X1 /= scaleFactor
- ocrBoxes[i].Top /= scaleFactor
- ocrBoxes[i].Bottom /= scaleFactor
+ // Tables and DLARegions are accumulated across pages in order.
+ if len(r.Tables) > 0 {
+ result.Tables = append(result.Tables, r.Tables...)
}
- boxes = append(boxes, ocrBoxes...)
- ocrUsedAny = true
+ if len(r.DLARegions) > 0 {
+ result.DLARegions = append(result.DLARegions, r.DLARegions...)
+ }
+ }
+
+ if len(boxes) == 0 {
+ return result, nil
}
- return boxes, ocrUsedAny
+
+ if err := p.buildLayout(ctx, result, boxes, pageChars,
+ medianHeights, medianWidths, pageEnglish); err != nil {
+ return nil, fmt.Errorf("buildLayout: %w", err)
+ }
+ return result, nil
}
+// buildLayout consumes the assembled boxes + page-level artifacts and runs
+// the global layout/table/figure pipeline. It is the only step that runs
+// AssignColumn, TextMerge, FinalReadingOrderMerge, NaiveVerticalMerge, table
+// merge, figure consolidation, BoxesToSections, and caption merge.
func (p *Parser) buildLayout(ctx context.Context,
- result *pdf.ParseResult, engine pdf.PDFEngine,
+ result *pdf.ParseResult,
boxes []pdf.TextBox, pageChars map[int][]pdf.TextChar,
medianHeights, medianWidths map[int]float64,
- fromPage, toPage int, ocrUsedAny bool, isEnglish bool,
- docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder,
+ pageEnglish map[int]bool,
) error {
result.Metrics.BoxesInitial = len(boxes)
- result.Tables = p.enrichWithDeepDoc(ctx, result, engine, boxes, result.PageImages, docAnalyzer, tb)
- result.Metrics.TablesCount = len(result.Tables)
- if err := ctx.Err(); err != nil {
- return err
- }
-
- boxes = lyt.AssignColumn(boxes, p.Config.Zoom)
- boxes = lyt.TextMerge(boxes, medianHeights, p.Config.Zoom)
+ boxes = lyt.AssignColumn(boxes)
+ boxes = lyt.TextMerge(boxes, medianHeights)
result.Metrics.BoxesTextMerge = len(boxes)
- lyt.SortByPageThenY(boxes, p.Config.SortByTop)
+ // FinalReadingOrderMerge sorts page → column (ColID) → top → x0, which
+ // is the correct multi-column reading order. NaiveVerticalMerge preserves
+ // this column-major order (it buckets by ColID before merging).
+ boxes = lyt.FinalReadingOrderMerge(boxes)
- if ocrUsedAny {
- isEnglish = util.DetectEnglish(pageChars, toPage-fromPage+1, nil)
- }
- boxes = lyt.NaiveVerticalMerge(boxes, medianHeights, medianWidths, isEnglish)
+ boxes = lyt.NaiveVerticalMerge(boxes, medianHeights, medianWidths, pageEnglish)
result.Metrics.BoxesVertMerge = len(boxes)
if err := ctx.Err(); err != nil {
return err
}
+ if len(result.Tables) > 0 {
+ result.Tables = tbl.MergeTablesAcrossPages(result.Tables, nil)
+ }
+
boxes = tbl.ExtractTableAndReplace(boxes, result.Tables)
+ result.Metrics.TablesCount = len(result.Tables)
boxes = tbl.ConsolidateFigures(boxes)
- pageHeights := make(map[int]float64, len(result.PageImages))
- for pg, img := range result.PageImages {
- pageHeights[pg] = float64(img.Bounds().Dy()) / p.Config.Zoom
- }
- result.Sections = lyt.BoxesToSections(boxes, pageHeights)
+ // PageHeight is already in PDF-point space — computed in processPage.
+ result.Sections = lyt.BoxesToSections(boxes, result.PageHeight)
result.Metrics.BoxesFinal = len(result.Sections)
result.Sections = tbl.MergeCaptions(result.Sections, result.Figures())
return nil
}
-func (p *Parser) processPages(ctx context.Context, engine pdf.PDFEngine,
- fromPage, toPage int,
- prescanChars map[int][]pdf.TextChar,
- medianHeights, medianWidths map[int]float64,
- isEnglish, isScanNoiseDoc bool,
- docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder,
-) (*pdf.ParseResult, error) {
- result := &pdf.ParseResult{PageImages: make(map[int]image.Image)}
-
- boxes, pageChars, ocrUsedAny, ocrErr := p.extractPages(ctx, engine,
- fromPage, toPage, prescanChars,
- medianHeights, medianWidths, result.PageImages, docAnalyzer)
- if ocrErr != nil {
- slog.Warn("extractPages: some pages failed OCR", "err", ocrErr)
+// processPages drives the page worker pool and the global assembly step.
+// Page-local work (including per-page zoom retry) happens inside processPage;
+// document-wide work happens in assembleDocument.
+func (p *Parser) processPages(ctx context.Context, engine pdf.PDFEngine, docAnalyzer pdf.DocAnalyzer) (*pdf.ParseResult, error) {
+ pageCount, err := engine.PageCount()
+ if err != nil {
+ return nil, fmt.Errorf("page count: %w", err)
}
-
- if isScanNoiseDoc {
- boxes, pageChars, ocrUsedAny = p.retryScanNoise(ctx, engine,
- fromPage, toPage, result.PageImages,
- pageChars, medianHeights, medianWidths, ocrUsedAny, docAnalyzer)
+ if pageCount == 0 {
+ return &pdf.ParseResult{
+ PageHeight: make(map[int]float64),
+ PageWidth: make(map[int]float64),
+ }, nil
}
- if len(boxes) == 0 && p.Config.Zoom < 9 && !p.Config.SkipOCR {
- boxes, ocrUsedAny = p.retryZoom(ctx, engine, fromPage, toPage,
- result.PageImages, boxes, ocrUsedAny, docAnalyzer)
- }
+ tb := NewTableBuilderFor(docAnalyzer)
+ pages := documentPages(pageCount)
- if len(boxes) == 0 {
- return result, nil
+ pageResults, pageErr := p.runPageWorkers(ctx, engine, pages, docAnalyzer, tb)
+ if pageErr != nil {
+ slog.Warn("runPageWorkers: some pages failed", "err", pageErr)
}
- if err := p.buildLayout(ctx, result, engine, boxes, pageChars,
- medianHeights, medianWidths, fromPage, toPage, ocrUsedAny, isEnglish,
- docAnalyzer, tb); err != nil {
- return nil, fmt.Errorf("buildLayout: %w", err)
+ result, err := p.assembleDocument(ctx, pages, pageResults)
+ if err != nil {
+ return nil, err
}
- p.fillSectionImages(result)
+ // Preserve a hard failure from the page workers (e.g. context
+ // cancellation) — assembleDocument may still succeed on an empty
+ // result, which would otherwise swallow the error.
+ if pageErr != nil {
+ return result, pageErr
+ }
+ // Carry the engine on the result so the JSON/markdown serialization
+ // step can crop section images on demand, then release it. This also
+ // fixes the previous engine leak (the engine was discarded here and
+ // re-created unnecessarily downstream).
+ result.Engine = engine
return result, nil
}
-
-func (p *Parser) fillSectionImages(result *pdf.ParseResult) {
- if len(result.PageImages) == 0 {
- return
- }
- tableImgByRegion := make(map[string]string, len(result.Tables))
- for _, tbl := range result.Tables {
- if tbl.ImageB64 == "" {
- continue
- }
- pg := 0
- if len(tbl.Positions) > 0 && len(tbl.Positions[0].PageNumbers) > 0 {
- pg = tbl.Positions[0].PageNumbers[0]
- }
- key := fmt.Sprintf("%d_%.1f_%.1f_%.1f_%.1f",
- pg, tbl.RegionLeft, tbl.RegionRight, tbl.RegionTop, tbl.RegionBottom)
- tableImgByRegion[key] = tbl.ImageB64
- }
- for i := range result.Sections {
- if result.Sections[i].LayoutType == pdf.LayoutTypeTable {
- if img, ok := matchTableImage(&result.Sections[i], tableImgByRegion); ok {
- result.Sections[i].Image = img
- continue
- }
- }
- if result.Sections[i].LayoutType == pdf.LayoutTypeFigure && len(result.Sections[i].Positions) > 0 {
- if dlaImg := util.CropSectionByDLA(result.Sections[i], result.DLADebug, result.PageImages); dlaImg != "" {
- result.Sections[i].Image = dlaImg
- continue
- }
- }
- img := util.CropSectionImage(result.Sections[i].PositionTag, result.PageImages, p.Config.Zoom)
- result.Sections[i].Image = img
- if img == "" && result.Sections[i].Text != "" {
- tag := result.Sections[i].PositionTag
- slog.Warn("cropSectionImage empty for non-empty section",
- "section", i, "posTag", tag[:min(80, len(tag))])
- }
- }
-}
-
-// matchTableImage looks up a pre-rendered table image for a section.
-// Uses Positions if available; falls back to TableItem Region boundaries.
-func matchTableImage(sec *pdf.Section, tableImgByRegion map[string]string) (string, bool) {
- pg := 0
- if len(sec.Positions) > 0 {
- pos := sec.Positions[0]
- if len(pos.PageNumbers) > 0 {
- pg = pos.PageNumbers[0]
- }
- key := fmt.Sprintf("%d_%.1f_%.1f_%.1f_%.1f", pg, pos.Left, pos.Right, pos.Top, pos.Bottom)
- if img, ok := tableImgByRegion[key]; ok {
- return img, true
- }
- return "", false
- }
- if sec.TableItem != nil {
- if len(sec.TableItem.Positions) > 0 && len(sec.TableItem.Positions[0].PageNumbers) > 0 {
- pg = sec.TableItem.Positions[0].PageNumbers[0]
- }
- key := fmt.Sprintf("%d_%.1f_%.1f_%.1f_%.1f", pg,
- sec.TableItem.RegionLeft, sec.TableItem.RegionRight,
- sec.TableItem.RegionTop, sec.TableItem.RegionBottom)
- if img, ok := tableImgByRegion[key]; ok {
- return img, true
- }
- }
- return "", false
-}
-
diff --git a/internal/deepdoc/parser/pdf/parser_concurrency.go b/internal/deepdoc/parser/pdf/parser_concurrency.go
new file mode 100644
index 0000000000..dccf9705d0
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/parser_concurrency.go
@@ -0,0 +1,224 @@
+package pdf
+
+import (
+ "context"
+ "image"
+ "runtime"
+ "sync"
+
+ pdf "ragflow/internal/deepdoc/parser/pdf/type"
+ "ragflow/internal/utility"
+)
+
+// ── Internal concurrency guards ──────────────────────────────────────────
+//
+// Real page parallelism exposes the parser to multiplicative DeepDoc
+// inference fan-out (DLA + TSR per table region + OCR per region).
+// deepInfLimiter (deepdoc inference limiter) bounds the worst-case
+// concurrent inference work a single document can drive. It is
+// parser-owned, not user-configurable, so callers do not have to reason
+// about the knob.
+//
+// Native PDFium access (RenderPage / ExtractChars / PageSize / outlines)
+// is serialized by a process-wide mutex in package pdfsync, shared by
+// both the cgo pdfium binding and the Rust pdf_oxide binding — PDFium is
+// not thread-safe for any call, even across different documents, so the
+// mutex (not a per-Parser limiter) is the correct guard. See
+// pdfsync/pdfsync.go.
+
+const (
+ // defaultdeepInfCapacity bounds DeepDoc (deepdoc) inference calls
+ // (DLA, TSR, OCR).
+ defaultdeepInfCapacity = 8
+)
+
+// deepInfLimiter bounds concurrent DeepDoc (deepdoc) inference calls emitted
+// by per-page workers. acquire blocks until a slot is available or the
+// context is cancelled; release must be called in a defer.
+type deepInfLimiter struct {
+ sem chan struct{}
+}
+
+func newdeepInfLimiter(capacity int) *deepInfLimiter {
+ if capacity <= 0 {
+ capacity = defaultdeepInfCapacity
+ }
+ return &deepInfLimiter{sem: make(chan struct{}, capacity)}
+}
+
+func (l *deepInfLimiter) acquire(ctx context.Context) error {
+ if l == nil {
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case l.sem <- struct{}{}:
+ return nil
+ }
+}
+
+func (l *deepInfLimiter) release() {
+ if l == nil {
+ return
+ }
+ <-l.sem
+}
+
+// withSlot acquires a slot, runs fn, and releases the slot. fn's error
+// is propagated unchanged.
+func (l *deepInfLimiter) withSlot(ctx context.Context, fn func() error) error {
+ if err := l.acquire(ctx); err != nil {
+ return err
+ }
+ defer l.release()
+ return fn()
+}
+
+// ── Parser-owned limiter accessors ────────────────────────────────────────
+
+// pageTask holds the per-page work handed to the shared worker pool.
+type pageTask struct {
+ parser *Parser
+ engine pdf.PDFEngine
+ pageNumber int
+ docAnalyzer pdf.DocAnalyzer
+ tb pdf.TableBuilder
+}
+
+const pageWorkerQueueFactor = 4
+
+var (
+ pagePoolOnce sync.Once
+ pagePool *utility.WorkerPool[pageTask, pageResult]
+)
+
+func parserPageWorkerPool() *utility.WorkerPool[pageTask, pageResult] {
+ pagePoolOnce.Do(func() {
+ workers := runtime.GOMAXPROCS(0) * 2
+ if workers <= 0 {
+ workers = 1
+ }
+ pagePool = utility.NewWorkerPool(workers, workers*pageWorkerQueueFactor,
+ func(ctx context.Context, task pageTask) (pageResult, error) {
+ return task.parser.processPage(ctx, task.engine, task.pageNumber,
+ task.docAnalyzer, task.tb), nil
+ })
+ })
+ return pagePool
+}
+
+// PageWorkerPoolStats returns process-wide stats for the shared PDF page worker pool.
+func PageWorkerPoolStats() utility.WorkerPoolStats {
+ return parserPageWorkerPool().Stats()
+}
+
+// SetPageWorkerPoolSize adjusts the process-wide PDF page worker pool size.
+func SetPageWorkerPoolSize(workers int) {
+ parserPageWorkerPool().Resize(workers)
+}
+
+// limiters returns the parser's lazily-initialized DeepDoc inference
+// limiter. The returned limiter is shared across ParseRaw calls (and
+// per-page workers) so test or production callers that reuse a Parser
+// do not pile up extra slots. Creation is guarded by deepInfOnce so a
+// Parser shared across goroutines initializes the slot channel once.
+func (p *Parser) limiters() *deepInfLimiter {
+ p.deepInfOnce.Do(func() {
+ p.deepInf = newdeepInfLimiter(0)
+ })
+ return p.deepInf
+}
+
+// ── Wrapped calls used by the parser pipeline ─────────────────────────────
+
+// renderPageToImage renders a page at the default DLA DPI. Native PDFium
+// access inside the engine is serialized by the process-wide pdfsync.Mu
+// (see pdfsync/pdfsync.go), so no per-Parser engine limiter is needed here.
+func (p *Parser) renderPageToImage(ctx context.Context, eng pdf.PDFEngine, pageNum int) (image.Image, error) {
+ return RenderPageToImage(eng, pageNum)
+}
+
+// renderAtDPI invokes the engine's DPI-parameterized render path. As with
+// renderPageToImage, native PDFium serialization is handled by pdfsync.Mu.
+func (p *Parser) renderAtDPI(ctx context.Context, eng pdf.PDFEngine, pageNum int, dpi float64) (image.Image, error) {
+ return eng.RenderPageImage(pageNum, dpi)
+}
+
+// inferDLA acquires the inference limiter slot before invoking the
+// per-page DLA call. Page workers and enrichOnePageWithDeepDoc callers
+// route through this wrapper so DLA fan-out cannot overwhelm the
+// DeepDoc service independently of the page worker pool size.
+func (p *Parser) inferDLA(ctx context.Context, doc pdf.DocAnalyzer, pageImg image.Image) ([]pdf.DLARegion, error) {
+ if doc == nil || !doc.Health() {
+ return nil, nil
+ }
+ var regions []pdf.DLARegion
+ err := p.limiters().withSlot(ctx, func() error {
+ r, callErr := doc.DLA(ctx, pageImg)
+ if callErr != nil {
+ return callErr
+ }
+ regions = r
+ return nil
+ })
+ return regions, err
+}
+
+// inferTSR acquires the inference limiter slot before invoking TSR for
+// a single cropped table region. TSR can be called once per detected
+// DLA table region, so without this wrapper the worst-case
+// (DlaRegion × pool worker count) fan-out could overwhelm the service.
+func (p *Parser) inferTSR(ctx context.Context, tb pdf.TableBuilder, cropped image.Image) ([]pdf.TSRCell, error) {
+ if tb == nil {
+ return nil, nil
+ }
+ var cells []pdf.TSRCell
+ err := p.limiters().withSlot(ctx, func() error {
+ c, callErr := tb.DetectCells(ctx, cropped)
+ if callErr != nil {
+ return callErr
+ }
+ cells = c
+ return nil
+ })
+ return cells, err
+}
+
+// inferOCRDetect routes doc.OCRDetect through the inference limiter.
+// ocrMergeChars and ocrDetectAndRecognize callers should funnel
+// through this helper.
+func (p *Parser) inferOCRDetect(ctx context.Context, doc pdf.DocAnalyzer, pageImg image.Image) ([]pdf.OCRBox, error) {
+ if doc == nil || !doc.Health() {
+ return nil, nil
+ }
+ var boxes []pdf.OCRBox
+ err := p.limiters().withSlot(ctx, func() error {
+ b, callErr := doc.OCRDetect(ctx, pageImg)
+ if callErr != nil {
+ return callErr
+ }
+ boxes = b
+ return nil
+ })
+ return boxes, err
+}
+
+// inferOCRRecognize routes doc.OCRRecognize through the inference
+// limiter. Per-region OCR fallback paths (buildTextBoxes, ocrTableCells)
+// should use this wrapper so the per-region fan-out is bounded.
+func (p *Parser) inferOCRRecognize(ctx context.Context, doc pdf.DocAnalyzer, cropped image.Image) ([]pdf.OCRText, error) {
+ if doc == nil || !doc.Health() {
+ return nil, nil
+ }
+ var texts []pdf.OCRText
+ err := p.limiters().withSlot(ctx, func() error {
+ t, callErr := doc.OCRRecognize(ctx, cropped)
+ if callErr != nil {
+ return callErr
+ }
+ texts = t
+ return nil
+ })
+ return texts, err
+}
diff --git a/internal/deepdoc/parser/pdf/parser_mock_test.go b/internal/deepdoc/parser/pdf/parser_mock_test.go
index 11a0091fc3..b40cfcc633 100644
--- a/internal/deepdoc/parser/pdf/parser_mock_test.go
+++ b/internal/deepdoc/parser/pdf/parser_mock_test.go
@@ -47,25 +47,25 @@ func TestMockDocAnalyzer(t *testing.T) {
}
}
-// ── enrichWithDeepDoc noop ─────────────────────────────────────────────
+// ── enrichOnePageWithDeepDoc noop ───────────────────────────────────────
-func TestEnrichWithDeepDoc_Noop(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_Noop(t *testing.T) {
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 50, X1: 550, Top: 100, Bottom: 112, Text: "text"},
}
- eng := &MockEngine{NumPages: 1}
+ dummyImg := image.NewRGBA(image.Rect(0, 0, 900, 600))
p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{Healthy: false}
- tables := p.enrichWithDeepDoc(context.Background(), nil, eng, boxes, nil, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummyImg, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Error("unhealthy DeepDoc → 0 Tables")
}
}
-// ── extractTableBoxesFromImage with mock ───────────────────────────────
+// ── enrichOnePageWithDeepDoc with mock ───────────────────────────────────
-func TestExtractTableBoxes_Mock(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_Mock(t *testing.T) {
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 80, X1: 500, Top: 200, Bottom: 550, Text: "cell 1"},
{PageNumber: 0, X0: 80, X1: 500, Top: 550, Bottom: 760, Text: "cell 2"},
@@ -87,7 +87,7 @@ func TestExtractTableBoxes_Mock(t *testing.T) {
p := NewParser(pdf.DefaultParserConfig())
dummyImg := image.NewRGBA(image.Rect(0, 0, 2000, 3000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, boxes, dummyImg, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummyImg, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 1 {
t.Fatalf("expected 1 pdf.TableItem, got %d", len(tables))
}
@@ -104,17 +104,17 @@ func TestExtractTableBoxes_Mock(t *testing.T) {
}
}
-func TestExtractTableBoxes_NoTables(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_NoTables(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, DLARegions: []pdf.DLARegion{}}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 1000, 1000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, nil, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, nil, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("0 tables expected, got %d", len(tables))
}
}
-func TestExtractTableBoxes_NonTableRegions(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_NonTableRegions(t *testing.T) {
mock := &MockDocAnalyzer{
Healthy: true,
DLARegions: []pdf.DLARegion{
@@ -124,13 +124,13 @@ func TestExtractTableBoxes_NonTableRegions(t *testing.T) {
}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 2000, 2000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, nil, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, nil, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("non-table regions → 0 tables, got %d", len(tables))
}
}
-func TestExtractTableBoxes_NoOverlap(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_NoOverlap(t *testing.T) {
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 50, X1: 550, Top: 10, Bottom: 30, Text: "far away"},
}
@@ -142,13 +142,13 @@ func TestExtractTableBoxes_NoOverlap(t *testing.T) {
}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 2000, 3000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, boxes, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("no overlap → 0 tables, got %d", len(tables))
}
}
-func TestExtractTableBoxes_TSRError(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_TSRError(t *testing.T) {
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 80, X1: 500, Top: 210, Bottom: 660, Text: "cell"},
}
@@ -161,7 +161,7 @@ func TestExtractTableBoxes_TSRError(t *testing.T) {
}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 2000, 3000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, boxes, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 1 {
t.Fatalf("TSR failure: expected 1 pdf.TableItem with image+positions, got %d", len(tables))
}
@@ -176,21 +176,21 @@ func TestExtractTableBoxes_TSRError(t *testing.T) {
}
}
-func TestExtractTableBoxes_DLAError(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_DLAError(t *testing.T) {
// DLA returns only non-table regions → 0 tables
mock := &MockDocAnalyzer{Healthy: true, DLARegions: []pdf.DLARegion{
{X0: 0, Y0: 0, X1: 100, Y1: 100, Label: "text", Confidence: 0.9},
}}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 1000, 1000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, nil, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, nil, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("non-table DLA → 0 tables, got %d", len(tables))
}
}
func TestParse_TableLinkedToSections(t *testing.T) {
- // Simulate enrichWithDeepDoc → extractTableAndReplace → boxesToSections:
+ // Simulate enrichOnePageWithDeepDoc → extractTableAndReplace → boxesToSections:
// table boxes are popped and replaced with one HTML box.
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 50, X1: 200, Top: 50, Bottom: 80, Text: "heading"},
@@ -228,9 +228,9 @@ func TestParse_TableLinkedToSections(t *testing.T) {
}
// ── cropImageRegion ────────────────────────────────────────────────────
-// ── extractTableBoxesFromImage: invalid DLA region ─────────────────────
+// ── enrichOnePageWithDeepDoc: invalid DLA region ────────────────────────
-func TestExtractTableBoxes_InvalidRegion(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_InvalidRegion(t *testing.T) {
// DLA returns a table region with x1 < x0. The pipeline should skip
// this table gracefully (Python raises ValueError from PIL.Image.crop).
mock := &MockDocAnalyzer{
@@ -241,7 +241,7 @@ func TestExtractTableBoxes_InvalidRegion(t *testing.T) {
}
p := NewParser(pdf.DefaultParserConfig())
dummy := image.NewRGBA(image.Rect(0, 0, 1000, 1000))
- tables := p.extractTableBoxesFromImage(context.Background(), nil, nil, dummy, 0, 0, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummy, nil, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("invalid DLA region should be skipped, got %d tables", len(tables))
}
@@ -400,14 +400,12 @@ func TestMockDocAnalyzer_DLAError_DoesNotCrash(t *testing.T) {
DLAErr: fmt.Errorf("DLA service unavailable"),
}
p := NewParser(pdf.DefaultParserConfig())
- eng := &MockEngine{NumPages: 1}
img := image.NewRGBA(image.Rect(0, 0, 100, 100))
- pageImages := map[int]image.Image{0: img}
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 0, X1: 100, Top: 0, Bottom: 50, Text: "text"},
}
- // enrichWithDeepDoc should return nil (not panic) on DLA error.
- tables := p.enrichWithDeepDoc(context.Background(), nil, eng, boxes, pageImages, mock, NewTableBuilderFor(mock))
+ // enrichOnePageWithDeepDoc should return nil (not panic) on DLA error.
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), img, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) != 0 {
t.Errorf("DLA error should produce 0 tables, got %d", len(tables))
}
@@ -424,13 +422,11 @@ func TestMockDocAnalyzer_TSRError_DoesNotCrash(t *testing.T) {
TSRErr: fmt.Errorf("TSR model timeout"),
}
p := NewParser(pdf.DefaultParserConfig())
- eng := &MockEngine{NumPages: 1}
img := image.NewRGBA(image.Rect(0, 0, 100, 100))
- pageImages := map[int]image.Image{0: img}
boxes := []pdf.TextBox{
{PageNumber: 0, X0: 10, X1: 90, Top: 10, Bottom: 90, Text: "in table region"},
}
- tables := p.enrichWithDeepDoc(context.Background(), nil, eng, boxes, pageImages, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), img, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
// DLA detects the table region → 1 pdf.TableItem is created. TSR failure
// means it has no cells, but the pipeline must not panic.
if len(tables) != 1 {
@@ -442,7 +438,7 @@ func TestMockDocAnalyzer_TSRError_DoesNotCrash(t *testing.T) {
}
func TestMockDocAnalyzer_OCRDetectError_DoesNotCrash(t *testing.T) {
- // OCRDetect failure path: extractPages uses ocrDetectAndRecognize which
+ // OCRDetect failure path: processPageBoxes uses ocrDetectAndRecognize which
// calls doc.OCRDetect. When it fails, the page is skipped gracefully.
mock := &MockDocAnalyzer{Healthy: true, OCRDetectErr: fmt.Errorf("OCR model OOM")}
eng := &MockEngine{
diff --git a/internal/deepdoc/parser/pdf/parser_ocr.go b/internal/deepdoc/parser/pdf/parser_ocr.go
index c8ed5c8972..d4fb6347e0 100644
--- a/internal/deepdoc/parser/pdf/parser_ocr.go
+++ b/internal/deepdoc/parser/pdf/parser_ocr.go
@@ -12,8 +12,8 @@ import (
"strings"
)
-func ocrDetectAndRecognize(ctx context.Context, pageImg image.Image, doc pdf.DocAnalyzer, pageNum int, logLabel string) []pdf.TextBox {
- boxes, err := doc.OCRDetect(ctx, pageImg)
+func (p *Parser) ocrDetectAndRecognize(ctx context.Context, pageImg image.Image, doc pdf.DocAnalyzer, pageNum int, logLabel string) []pdf.TextBox {
+ boxes, err := p.inferOCRDetect(ctx, doc, pageImg)
if err != nil || len(boxes) == 0 {
if err != nil {
slog.Warn(logLabel+" OCR detect failed", "page", pageNum, "err", err)
@@ -21,6 +21,13 @@ func ocrDetectAndRecognize(ctx context.Context, pageImg image.Image, doc pdf.Doc
return nil
}
+ // detectBoxes returns image-pixel coords; ocrMergeChars divides by
+ // pdf.DlaScale before emitting boxes so downstream layout receives
+ // PDF-point coordinates. ocrDetectAndRecognize must match the same
+ // conversion so both OCR paths produce the same coordinate space.
+ imgW := float64(pageImg.Bounds().Dx()) / pdf.DlaScale
+ imgH := float64(pageImg.Bounds().Dy()) / pdf.DlaScale
+
var result []pdf.TextBox
for _, b := range boxes {
x0 := int(math.Min(b.X0, math.Min(b.X1, math.Min(b.X2, b.X3))))
@@ -31,17 +38,37 @@ func ocrDetectAndRecognize(ctx context.Context, pageImg image.Image, doc pdf.Doc
continue
}
cropped := util.FastCrop(pageImg, x0, y0, x1, y1)
- texts, recErr := doc.OCRRecognize(ctx, cropped)
+ texts, recErr := p.inferOCRRecognize(ctx, doc, cropped)
if recErr != nil {
slog.Warn(logLabel+" OCR recognize failed", "page", pageNum, "err", recErr)
continue
}
+ // Convert crop bounds back to PDF-point space before emitting.
+ px0 := float64(x0) / pdf.DlaScale
+ py0 := float64(y0) / pdf.DlaScale
+ px1 := float64(x1) / pdf.DlaScale
+ py1 := float64(y1) / pdf.DlaScale
+ if px0 < 0 {
+ px0 = 0
+ }
+ if py0 < 0 {
+ py0 = 0
+ }
+ if px1 > imgW {
+ px1 = imgW
+ }
+ if py1 > imgH {
+ py1 = imgH
+ }
+ if px0 >= px1 || py0 >= py1 {
+ continue
+ }
for _, t := range texts {
if strings.TrimSpace(t.Text) != "" {
result = append(result, pdf.TextBox{
- X0: float64(x0), X1: float64(x1),
- Top: float64(y0), Bottom: float64(y1),
- Text: t.Text,
+ X0: px0, X1: px1,
+ Top: py0, Bottom: py1,
+ Text: t.Text,
PageNumber: pageNum,
})
}
@@ -59,17 +86,17 @@ type ocrDetectBox struct {
x0, y0, x1, y1 float64
}
-func ocrMergeChars(ctx context.Context, pageImg image.Image, chars []pdf.TextChar, doc pdf.DocAnalyzer, pageNum int) []pdf.TextBox {
- boxes, scale, err := detectBoxes(ctx, pageImg, doc, pageNum)
+func (p *Parser) ocrMergeChars(ctx context.Context, pageImg image.Image, chars []pdf.TextChar, doc pdf.DocAnalyzer, pageNum int) []pdf.TextBox {
+ boxes, scale, err := p.detectBoxes(ctx, pageImg, doc, pageNum)
if err != nil || len(boxes) == 0 {
return nil
}
boxChars := matchCharsToBoxes(boxes, chars)
- return buildTextBoxes(ctx, pageImg, boxes, boxChars, doc, scale, pageNum)
+ return p.buildTextBoxes(ctx, pageImg, boxes, boxChars, doc, scale, pageNum)
}
-func detectBoxes(ctx context.Context, pageImg image.Image, doc pdf.DocAnalyzer, pageNum int) ([]ocrDetectBox, float64, error) {
- ocrDetectBoxes, err := doc.OCRDetect(ctx, pageImg)
+func (p *Parser) detectBoxes(ctx context.Context, pageImg image.Image, doc pdf.DocAnalyzer, pageNum int) ([]ocrDetectBox, float64, error) {
+ ocrDetectBoxes, err := p.inferOCRDetect(ctx, doc, pageImg)
if err != nil || len(ocrDetectBoxes) == 0 {
return nil, 0, err
}
@@ -187,7 +214,7 @@ func charBoxOverlapRatio(c pdf.TextChar, x0, x1, y0, y1 float64) float64 {
}
// ocrTableCells fills empty TSR cells via OCR recognition.
-func ocrTableCells(ctx context.Context, cells []pdf.TSRCell, tableImg image.Image, doc pdf.DocAnalyzer) {
+func (p *Parser) ocrTableCells(ctx context.Context, cells []pdf.TSRCell, tableImg image.Image, doc pdf.DocAnalyzer) {
if doc == nil || tableImg == nil || len(cells) == 0 {
return
}
@@ -203,7 +230,7 @@ func ocrTableCells(ctx context.Context, cells []pdf.TSRCell, tableImg image.Imag
continue
}
cropped := util.FastCrop(tableImg, x0, y0, x1, y1)
- texts, err := doc.OCRRecognize(ctx, cropped)
+ texts, err := p.inferOCRRecognize(ctx, doc, cropped)
if err != nil {
slog.Warn("table cell OCR failed", "err", err)
continue
@@ -218,8 +245,12 @@ func ocrTableCells(ctx context.Context, cells []pdf.TSRCell, tableImg image.Imag
}
}
-// buildTextBoxes assembles detect box text from embedded chars and fills empty boxes via batch OCR.
-func buildTextBoxes(ctx context.Context, pageImg image.Image,
+// buildTextBoxes assembles detect box text from embedded chars and fills empty boxes via single-image OCR.
+// Each region that lacks embedded text is cropped and recognized with a
+// direct doc.OCRRecognize call so empty-box fallback runs through the
+// canonical single-image recognition primitive. A nil or unhealthy
+// analyzer yields empty results for OCR-hungry regions instead of panicking.
+func (p *Parser) buildTextBoxes(ctx context.Context, pageImg image.Image,
boxes []ocrDetectBox, boxChars [][]pdf.TextChar, doc pdf.DocAnalyzer, scale float64, pageNum int,
) []pdf.TextBox {
var result []pdf.TextBox
@@ -253,21 +284,18 @@ func buildTextBoxes(ctx context.Context, pageImg image.Image,
}
result = append(result, tb)
}
- if len(needOCR) > 0 {
- cropped := make([]image.Image, len(needOCR))
- for j, idx := range needOCR {
- cropped[j] = util.FastCrop(pageImg,
+ if len(needOCR) > 0 && doc != nil && doc.Health() {
+ for _, idx := range needOCR {
+ cropped := util.FastCrop(pageImg,
int(boxes[idx].x0*scale), int(boxes[idx].y0*scale),
int(boxes[idx].x1*scale), int(boxes[idx].y1*scale))
- }
- allTexts, allErrs := doc.OCRRecognizeBatch(ctx, cropped)
- for j, idx := range needOCR {
- if allErrs[j] != nil {
- slog.Warn("ocr merge: recognize failed", "page", pageNum, "err", allErrs[j])
+ texts, err := p.inferOCRRecognize(ctx, doc, cropped)
+ if err != nil {
+ slog.Warn("ocr merge: recognize failed", "page", pageNum, "err", err)
continue
}
var ocrParts []string
- for _, t := range allTexts[j] {
+ for _, t := range texts {
if strings.TrimSpace(t.Text) != "" {
ocrParts = append(ocrParts, t.Text)
}
diff --git a/internal/deepdoc/parser/pdf/parser_ocr_test.go b/internal/deepdoc/parser/pdf/parser_ocr_test.go
index a5b4308f30..109c76bb00 100644
--- a/internal/deepdoc/parser/pdf/parser_ocr_test.go
+++ b/internal/deepdoc/parser/pdf/parser_ocr_test.go
@@ -9,6 +9,7 @@ import (
// TestOCRMergeChars_FullCoverage: embedded chars fill the detect box.
func TestOCRMergeChars_FullCoverage(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{
Healthy: true,
OCRBoxes: []pdf.OCRBox{
@@ -25,7 +26,7 @@ func TestOCRMergeChars_FullCoverage(t *testing.T) {
{X0: 12, X1: 28, Top: 2, Bottom: 35, Text: "World"},
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -37,6 +38,7 @@ func TestOCRMergeChars_FullCoverage(t *testing.T) {
// TestOCRMergeChars_PartialCoverage: box A has chars, box B is OCR'd.
func TestOCRMergeChars_PartialCoverage(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{
Healthy: true,
OCRBoxes: []pdf.OCRBox{
@@ -53,7 +55,7 @@ func TestOCRMergeChars_PartialCoverage(t *testing.T) {
{X0: 2, X1: 12, Top: 2, Bottom: 15, Text: "A"},
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 2 {
t.Fatalf("expected 2 boxes, got %d", len(boxes))
}
@@ -69,6 +71,7 @@ func TestOCRMergeChars_PartialCoverage(t *testing.T) {
// TestOCRMergeChars_NoDetectBoxes: OCRDetect returns nil/empty → ocrMergeChars returns nil.
func TestOCRMergeChars_NoDetectBoxes(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{
Healthy: true,
OCRBoxes: nil,
@@ -78,14 +81,14 @@ func TestOCRMergeChars_NoDetectBoxes(t *testing.T) {
{X0: 2, X1: 10, Top: 2, Bottom: 8, Text: "Hello"},
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if boxes != nil {
t.Errorf("expected nil for no detect boxes, got %d boxes", len(boxes))
}
// Also test empty OCRBoxes
mock.OCRBoxes = []pdf.OCRBox{}
- boxes = ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes = p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if boxes != nil {
t.Errorf("expected nil for empty detect boxes, got %d boxes", len(boxes))
}
@@ -93,6 +96,7 @@ func TestOCRMergeChars_NoDetectBoxes(t *testing.T) {
// TestOCRMergeChars_GarbledChars: chars are majority PUA → text cleared → OCRRecognize triggered.
func TestOCRMergeChars_GarbledChars(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{
Healthy: true,
OCRBoxes: []pdf.OCRBox{
@@ -110,7 +114,7 @@ func TestOCRMergeChars_GarbledChars(t *testing.T) {
{X0: 22, X1: 28, Top: 2, Bottom: 35, Text: "a"}, // normal
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -122,6 +126,7 @@ func TestOCRMergeChars_GarbledChars(t *testing.T) {
// TestOCRMergeChars_HeightGate: char height differs from box height by >70% → filtered out.
func TestOCRMergeChars_HeightGate(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
// Box height in PDF space: 120/3.0 = 40
mock := &MockDocAnalyzer{
Healthy: true,
@@ -138,7 +143,7 @@ func TestOCRMergeChars_HeightGate(t *testing.T) {
{X0: 2, X1: 10, Top: 2, Bottom: 3, Text: "tiny"},
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box (OCR fallback after height gate), got %d", len(boxes))
}
@@ -152,6 +157,7 @@ func TestOCRMergeChars_HeightGate(t *testing.T) {
// detection: subset-font chars clear the box text → OCR fallback.
// Python __ocr: _is_garbled_by_font_encoding(min_chars=5).
func TestOCRMergeChars_FontEncodingGarbled(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
mock := &MockDocAnalyzer{
Healthy: true,
OCRBoxes: []pdf.OCRBox{
@@ -168,7 +174,7 @@ func TestOCRMergeChars_FontEncodingGarbled(t *testing.T) {
Text: "#", FontName: "DY1+SimSun", PageNumber: 0,
}
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 OCR-fallback box, got %d", len(boxes))
}
@@ -227,6 +233,7 @@ func TestSortCharsYFirstly(t *testing.T) {
// fuzzy Y-sort — chars on the same line with different font sizes
// (different Top values) are sorted by X, not by strict Top.
func TestOCRMergeChars_MixedFontSizes(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
// Simulate mixed font sizes on the same line.
// "小" has higher Top (smaller font sits higher on the baseline)
// but is physically to the left of "大" and "号".
@@ -246,7 +253,7 @@ func TestOCRMergeChars_MixedFontSizes(t *testing.T) {
{X0: 12, X1: 24, Top: 5, Bottom: 35, Text: "大"}, // larger font, lower baseline
{X0: 24, X1: 36, Top: 5, Bottom: 35, Text: "号"}, // same size as 大, rightmost
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -259,6 +266,7 @@ func TestOCRMergeChars_MixedFontSizes(t *testing.T) {
// TestOCRMergeChars_BoxOrder verifies detect boxes are sorted top-down
// (matching Python's sort_Y_firstly) before char matching.
func TestOCRMergeChars_BoxOrder(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
// 3 detect boxes in reverse Y order. After sorting, output should be top-down.
mock := &MockDocAnalyzer{
Healthy: true,
@@ -277,7 +285,7 @@ func TestOCRMergeChars_BoxOrder(t *testing.T) {
{X0: 2, X1: 10, Top: 16, Bottom: 19, Text: "B"}, // box 2 (middle)
{X0: 2, X1: 10, Top: 32, Bottom: 37, Text: "C"}, // box 3 (bottom)
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 3 {
t.Fatalf("expected 3 boxes, got %d", len(boxes))
}
@@ -294,6 +302,7 @@ func TestOCRMergeChars_BoxOrder(t *testing.T) {
// The old box-perspective collectOverlapChars would duplicate the char;
// the new char-perspective code (matching Python's find_overlapped) does not.
func TestOCRMergeChars_OverlappingBoxes(t *testing.T) {
+ p := NewParser(pdf.DefaultParserConfig())
// Box A: PDF x=0..20, y=0..20. Box B: PDF x=10..30, y=0..20.
// Overlap zone: x=10..20.
// Char "Y" at PDF x=2..8 → Box A only.
@@ -314,7 +323,7 @@ func TestOCRMergeChars_OverlappingBoxes(t *testing.T) {
{X0: 12, X1: 18, Top: 2, Bottom: 12, Text: "乙"}, // overlap zone
{X0: 22, X1: 28, Top: 2, Bottom: 12, Text: "丙"}, // Box B only
}
- boxes := ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), testPageImg(), chars, mock, 0)
if len(boxes) != 2 {
t.Fatalf("expected 2 boxes, got %d", len(boxes))
}
diff --git a/internal/deepdoc/parser/pdf/parser_parallel_integration_test.go b/internal/deepdoc/parser/pdf/parser_parallel_integration_test.go
new file mode 100644
index 0000000000..e4cc6fefbf
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/parser_parallel_integration_test.go
@@ -0,0 +1,59 @@
+//go:build cgo && integration
+
+package pdf
+
+import (
+ "context"
+ "reflect"
+ "testing"
+
+ pdf "ragflow/internal/deepdoc/parser/pdf/type"
+)
+
+// TestParser_PageParallel_DeterministicOrder verifies the plan's real-fixture
+// acceptance criteria: pool size 1 and pool size 4 must produce stable
+// Sections, Tables, Metrics, and per-page PNG-equivalent images on the named
+// PDF fixtures. With Config.Parallelism removed, page concurrency is governed
+// by the process-wide worker pool.
+func TestParser_PageParallel_DeterministicOrder(t *testing.T) {
+ client := mustConnectInferenceClient(t)
+
+ fixtures := []string{
+ "03_multipage.pdf",
+ "06_table_content.pdf",
+ "07_mixed_content.pdf",
+ "19_multipage_chunk.pdf",
+ }
+
+ runParse := func(t *testing.T, name string, poolSize int) *pdf.ParseResult {
+ t.Helper()
+ setPoolSize(t, poolSize)
+ p := NewParser(pdf.DefaultParserConfig())
+ result, err := p.Parse(context.Background(), mustReadPDF(t, name), client)
+ if err != nil {
+ t.Fatalf("fixture=%s poolSize=%d: Parse: %v", name, poolSize, err)
+ }
+ t.Cleanup(func() { result.Close() })
+ return result
+ }
+
+ for _, name := range fixtures {
+ t.Run(name, func(t *testing.T) {
+ baseline := runParse(t, name, 1)
+ parallel := runParse(t, name, 4)
+
+ if !reflect.DeepEqual(stableSections(baseline.Sections), stableSections(parallel.Sections)) {
+ t.Fatalf("fixture=%s: Sections diverged between poolSize=1 and poolSize=4", name)
+ }
+ if !reflect.DeepEqual(stableTables(baseline.Tables), stableTables(parallel.Tables)) {
+ t.Fatalf("fixture=%s: Tables diverged between poolSize=1 and poolSize=4", name)
+ }
+ if !reflect.DeepEqual(baseline.Metrics, parallel.Metrics) {
+ t.Fatalf("fixture=%s: Metrics diverged: %#v vs %#v", name, baseline.Metrics, parallel.Metrics)
+ }
+ if !reflect.DeepEqual(baseline.PageHeight, parallel.PageHeight) {
+ t.Fatalf("fixture=%s: PageHeight diverged between poolSize=1 and poolSize=4", name)
+ }
+ })
+ }
+}
diff --git a/internal/deepdoc/parser/pdf/parser_parallel_test.go b/internal/deepdoc/parser/pdf/parser_parallel_test.go
new file mode 100644
index 0000000000..b88d70efcc
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/parser_parallel_test.go
@@ -0,0 +1,510 @@
+package pdf
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "image"
+ "image/png"
+ "reflect"
+ "sync"
+ "testing"
+
+ pdf "ragflow/internal/deepdoc/parser/pdf/type"
+)
+
+type recordingAnalyzer struct {
+ mu sync.Mutex
+ seenDetectSizes [][2]int
+}
+
+func (r *recordingAnalyzer) DLA(context.Context, image.Image) ([]pdf.DLARegion, error) {
+ return nil, nil
+}
+func (r *recordingAnalyzer) TSR(context.Context, image.Image) ([]pdf.TSRCell, error) { return nil, nil }
+func (r *recordingAnalyzer) OCRDetect(_ context.Context, img image.Image) ([]pdf.OCRBox, error) {
+ if img != nil {
+ b := img.Bounds()
+ r.mu.Lock()
+ r.seenDetectSizes = append(r.seenDetectSizes, [2]int{b.Dx(), b.Dy()})
+ r.mu.Unlock()
+ if b.Dx() <= 90 {
+ return nil, nil
+ }
+ }
+ return []pdf.OCRBox{
+ {X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40},
+ }, nil
+}
+func (r *recordingAnalyzer) OCRRecognize(context.Context, image.Image) ([]pdf.OCRText, error) {
+ return []pdf.OCRText{{Text: "zoom retry", Confidence: 0.9}}, nil
+}
+func (r *recordingAnalyzer) Health() bool { return true }
+
+func (r *recordingAnalyzer) lastDetectSize() (int, int, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if len(r.seenDetectSizes) == 0 {
+ return 0, 0, false
+ }
+ last := r.seenDetectSizes[len(r.seenDetectSizes)-1]
+ return last[0], last[1], true
+}
+
+// ── Page-parallel regression tests ───────────────────────────────────────
+
+// makeMultiPageEngine builds a MockEngine with 1 page worth of embedded
+// chars per page so the unified processPage path lands on the
+// ocrMergeChars strategy.
+func makeMultiPageEngine(numPages int) *MockEngine {
+ chars := make(map[int][]pdf.TextChar, numPages)
+ for pg := 0; pg < numPages; pg++ {
+ chars[pg] = []pdf.TextChar{
+ {X0: 50, X1: 200, Top: 100 + float64(pg*10), Bottom: 112 + float64(pg*10), Text: "page", PageNumber: pg},
+ {X0: 50, X1: 200, Top: 130 + float64(pg*10), Bottom: 142 + float64(pg*10), Text: "text", PageNumber: pg},
+ }
+ }
+ return &MockEngine{NumPages: numPages, Chars: chars, RenderW: 100, RenderH: 100}
+}
+
+func TestParser_RunPageWorkers_DeterministicOrder(t *testing.T) {
+ mock := &MockDocAnalyzer{Healthy: true}
+ eng := makeMultiPageEngine(8)
+ p := NewParser(pdf.DefaultParserConfig())
+
+ pages := []int{0, 1, 2, 3, 4, 5, 6, 7}
+ results, err := p.runPageWorkers(context.Background(), eng, pages,
+ mock, NewTableBuilderFor(mock))
+ if err != nil {
+ t.Fatalf("runPageWorkers: %v", err)
+ }
+ if len(results) != len(pages) {
+ t.Fatalf("expected %d results, got %d", len(pages), len(results))
+ }
+ for i, r := range results {
+ if r.PageNumber != pages[i] {
+ t.Errorf("results[%d].PageNumber = %d, want %d", i, r.PageNumber, pages[i])
+ }
+ }
+}
+
+func TestParser_RunPageWorkers_PoolSize4_DeterministicOrder(t *testing.T) {
+ mock := &MockDocAnalyzer{Healthy: true}
+ eng := makeMultiPageEngine(8)
+ setPoolSize(t, 4)
+ p := NewParser(pdf.DefaultParserConfig())
+
+ pages := []int{0, 1, 2, 3, 4, 5, 6, 7}
+ results, err := p.runPageWorkers(context.Background(), eng, pages,
+ mock, NewTableBuilderFor(mock))
+ if err != nil {
+ t.Fatalf("runPageWorkers: %v", err)
+ }
+ if len(results) != len(pages) {
+ t.Fatalf("expected %d results, got %d", len(pages), len(results))
+ }
+ for i, r := range results {
+ if r.PageNumber != pages[i] {
+ t.Errorf("results[%d].PageNumber = %d, want %d", i, r.PageNumber, pages[i])
+ }
+ }
+}
+
+// TestParser_RunPageWorkers_StableAcrossPoolSizes verifies that the output
+// produced with pool size 1 and pool size N is structurally equivalent:
+// same page numbers, same box count per page, same image fingerprint, same
+// TableItem count. Page concurrency is governed by the process-wide worker
+// pool, not a per-Parser knob.
+func TestParser_RunPageWorkers_StableAcrossPoolSizes(t *testing.T) {
+ mock := &MockDocAnalyzer{
+ Healthy: true,
+ DLARegions: []pdf.DLARegion{
+ {X0: 100, Y0: 200, X1: 800, Y1: 600, Label: "table", Confidence: 0.9},
+ },
+ }
+ eng := makeMultiPageEngine(4)
+
+ for _, par := range []int{1, 2, 4} {
+ setPoolSize(t, par)
+ p := NewParser(pdf.DefaultParserConfig())
+
+ pages := []int{0, 1, 2, 3}
+ results, err := p.runPageWorkers(context.Background(), eng, pages,
+ mock, NewTableBuilderFor(mock))
+ if err != nil {
+ t.Fatalf("poolSize=%d: runPageWorkers: %v", par, err)
+ }
+ if len(results) != len(pages) {
+ t.Fatalf("poolSize=%d: got %d results, want %d", par, len(results), len(pages))
+ }
+ for i, r := range results {
+ if r.PageNumber != pages[i] {
+ t.Errorf("poolSize=%d: results[%d].PageNumber = %d, want %d",
+ par, i, r.PageNumber, pages[i])
+ }
+ if r.PageHeight <= 0 {
+ t.Errorf("poolSize=%d: page %d has zero PageHeight", par, r.PageNumber)
+ }
+ }
+ }
+}
+
+// TestParser_ParseRaw_PoolSizeEquivalence verifies that the final ParseResult
+// has equivalent shape for pool size 1 and pool size>1: same PageHeight values,
+// same Section count, same Table count.
+func TestParser_ParseRaw_PoolSizeEquivalence(t *testing.T) {
+ mock := &MockDocAnalyzer{Healthy: true}
+ eng := makeMultiPageEngine(6)
+
+ var results [2]*pdf.ParseResult
+ for i, par := range []int{1, 3} {
+ setPoolSize(t, par)
+ p := NewParser(pdf.DefaultParserConfig())
+ r, err := p.ParseRaw(context.Background(), eng, mock)
+ if err != nil {
+ t.Fatalf("poolSize=%d: ParseRaw: %v", par, err)
+ }
+ results[i] = r
+ }
+
+ if !reflect.DeepEqual(results[0].PageHeight, results[1].PageHeight) {
+ t.Errorf("PageHeight mismatch:\n poolSize=1: %v\n poolSize=3: %v",
+ results[0].PageHeight, results[1].PageHeight)
+ }
+ if len(results[0].Sections) != len(results[1].Sections) {
+ t.Errorf("Section count mismatch: poolSize=1=%d poolSize=3=%d",
+ len(results[0].Sections), len(results[1].Sections))
+ }
+ if len(results[0].Tables) != len(results[1].Tables) {
+ t.Errorf("Table count mismatch: poolSize=1=%d poolSize=3=%d",
+ len(results[0].Tables), len(results[1].Tables))
+ }
+}
+
+// TestParser_ProcessPage_UnifiedPath verifies that the single processPage
+// function works the same way across page-local decisions: clean chars
+// (ocrMergeChars path), garbled chars (ocrDetectAndRecognize path), and
+// empty chars (ocrDetectAndRecognize path).
+func TestParser_ProcessPage_UnifiedPath(t *testing.T) {
+ t.Run("clean_chars", func(t *testing.T) {
+ chars := make([]pdf.TextChar, 40)
+ for i := range chars {
+ chars[i] = pdf.TextChar{
+ X0: 10 + float64(i*2), X1: 12 + float64(i*2), Top: 10, Bottom: 30,
+ Text: "a", PageNumber: 0,
+ }
+ }
+ eng := &MockEngine{NumPages: 1, Chars: map[int][]pdf.TextChar{0: chars}}
+ mock := &MockDocAnalyzer{
+ Healthy: true,
+ OCRBoxes: []pdf.OCRBox{
+ {X0: 15, Y0: 15, X1: 150, Y1: 15, X2: 150, Y2: 150, X3: 15, Y3: 150},
+ },
+ OCRTexts: []pdf.OCRText{{Text: "Hello", Confidence: 0.9}},
+ }
+ p := NewParser(pdf.DefaultParserConfig())
+ r := p.processPage(context.Background(), eng, 0, mock, NewTableBuilderFor(mock))
+ if r.Err != nil {
+ t.Fatalf("processPage: %v", r.Err)
+ }
+ if r.PageHeight <= 0 {
+ t.Error("PageHeight zero for clean chars page")
+ }
+ if len(r.Boxes) == 0 {
+ t.Error("clean chars page should produce some boxes")
+ }
+ if !r.IsEnglish {
+ t.Error("clean english page should be marked english")
+ }
+ if r.MedianH <= 0 || r.MedianW <= 0 {
+ t.Error("clean page should carry per-page median metadata")
+ }
+ })
+
+ t.Run("garbled_chars", func(t *testing.T) {
+ chars := garbledSample()
+ eng := &MockEngine{NumPages: 1, Chars: map[int][]pdf.TextChar{0: chars}}
+ mock := &MockDocAnalyzer{
+ Healthy: true,
+ OCRBoxes: []pdf.OCRBox{
+ {X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40},
+ },
+ OCRTexts: []pdf.OCRText{{Text: "OCR result", Confidence: 0.9}},
+ }
+ p := NewParser(pdf.DefaultParserConfig())
+ r := p.processPage(context.Background(), eng, 0, mock, NewTableBuilderFor(mock))
+ if r.Err != nil {
+ t.Fatalf("processPage: %v", r.Err)
+ }
+ if len(r.Boxes) == 0 {
+ t.Error("garbled chars page should yield OCR boxes")
+ }
+ })
+
+ t.Run("empty_chars", func(t *testing.T) {
+ eng := &MockEngine{NumPages: 1}
+ mock := &MockDocAnalyzer{
+ Healthy: true,
+ OCRBoxes: []pdf.OCRBox{
+ {X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40},
+ },
+ OCRTexts: []pdf.OCRText{{Text: "scan OCR", Confidence: 0.9}},
+ }
+ p := NewParser(pdf.DefaultParserConfig())
+ r := p.processPage(context.Background(), eng, 0, mock, NewTableBuilderFor(mock))
+ if r.Err != nil {
+ t.Fatalf("processPage: %v", r.Err)
+ }
+ if len(r.Boxes) == 0 {
+ t.Error("empty chars page should yield OCR boxes")
+ }
+ })
+}
+
+// TestParser_RunPageWorkers_CancellationHonored verifies that an already-
+// cancelled context produces empty results without panicking.
+func TestParser_RunPageWorkers_CancellationHonored(t *testing.T) {
+ mock := &MockDocAnalyzer{Healthy: true}
+ eng := makeMultiPageEngine(4)
+ setPoolSize(t, 2)
+ p := NewParser(pdf.DefaultParserConfig())
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ _, err := p.runPageWorkers(ctx, eng, []int{0, 1, 2, 3},
+ mock, NewTableBuilderFor(mock))
+ if err == nil {
+ t.Error("expected non-nil error from cancelled context")
+ }
+}
+
+// TestParser_ProcessPages_CrossPageTableMerge verifies that cross-page
+// tables still merge after being collected from per-page workers, even
+// when different workers process the participating pages. This is the
+// regression test for AD-3 in the plan: pages processed by separate
+// workers participate in one document-wide merge pass.
+func TestParser_ProcessPages_CrossPageTableMerge(t *testing.T) {
+ // Same DLA region is returned for every page; positions match the
+ // rendered image space so the cross-page merge would attach page 1
+ // to page 0 once MergeTablesAcrossPages is called with both.
+ mock := &MockDocAnalyzer{
+ Healthy: true,
+ DLARegions: []pdf.DLARegion{
+ {X0: 250, Y0: 600, X1: 1500, Y1: 2300, Label: "table", Confidence: 0.95},
+ },
+ TSRCells: []pdf.TSRCell{
+ {X0: 0, Y0: 0, X1: 600, Y1: 400, Text: "A1"},
+ },
+ }
+ chars := map[int][]pdf.TextChar{
+ 0: {{X0: 80, X1: 500, Top: 200, Bottom: 300, Text: "head", PageNumber: 0}},
+ 1: {{X0: 80, X1: 500, Top: 100, Bottom: 200, Text: "next", PageNumber: 1}},
+ }
+ eng := &MockEngine{NumPages: 2, Chars: chars, RenderW: 2000, RenderH: 3000}
+
+ for _, par := range []int{1, 4} {
+ setPoolSize(t, par)
+ p := NewParser(pdf.DefaultParserConfig())
+ result, err := p.ParseRaw(context.Background(), eng, mock)
+ if err != nil {
+ t.Fatalf("poolSize=%d: ParseRaw: %v", par, err)
+ }
+ // With the same DLA region on both pages, per-page workers
+ // emit two table candidates and MergeTablesAcrossPages must
+ // collapse them to one merged document-wide TableItem.
+ if len(result.Tables) >= 2 {
+ t.Errorf("poolSize=%d: expected merged cross-page tables, got %d (no merge occurred)",
+ par, len(result.Tables))
+ }
+ }
+}
+
+// TestParser_PageParallel_DeterministicOrder_MockEngine keeps a fast mock
+// regression around the assembly-order invariant. The integration test with
+// the plan-mandated fixture coverage lives in parser_parallel_integration_test.go.
+//
+// The plan's AD-5a requires this regression to catch output drift
+// before it is observable in production. The test runs each
+// configuration multiple times to flush out flaky worker-pool timing
+// surprises that a single execution might miss.
+func TestParser_PageParallel_DeterministicOrder_MockEngine(t *testing.T) {
+ mock := &MockDocAnalyzer{Healthy: true}
+ eng := makeMultiPageEngine(6)
+
+ runParse := func(par int) *pdf.ParseResult {
+ setPoolSize(t, par)
+ p := NewParser(pdf.DefaultParserConfig())
+ r, err := p.ParseRaw(context.Background(), eng, mock)
+ if err != nil {
+ t.Fatalf("poolSize=%d: ParseRaw: %v", par, err)
+ }
+ return r
+ }
+
+ // Run pool size 4 three times so we exercise worker scheduling
+ // variations. Each run should match the pool size 1 baseline.
+ baseline := runParse(1)
+ for run := 0; run < 3; run++ {
+ parRun := runParse(4)
+ if !reflect.DeepEqual(stableSections(baseline.Sections), stableSections(parRun.Sections)) {
+ t.Errorf("run=%d: Sections not stable across pool size", run)
+ }
+ if !reflect.DeepEqual(stableTables(baseline.Tables), stableTables(parRun.Tables)) {
+ t.Errorf("run=%d: Tables not stable across pool size", run)
+ }
+ if !reflect.DeepEqual(baseline.Metrics, parRun.Metrics) {
+ t.Errorf("run=%d: Metrics not stable across pool size: %v vs %v",
+ run, baseline.Metrics, parRun.Metrics)
+ }
+ }
+}
+
+func TestParser_ParseRaw_RetryZoomReplacesPageImageAndZoom(t *testing.T) {
+ cfg := pdf.DefaultParserConfig()
+ cfg.Zoom = 2
+ p := NewParser(cfg)
+
+ eng := &MockEngine{
+ NumPages: 1,
+ RenderPageImageFunc: func(_ int, dpi float64) (image.Image, error) {
+ if dpi > pdf.DlaDPI {
+ return image.NewRGBA(image.Rect(0, 0, 180, 240)), nil
+ }
+ return image.NewRGBA(image.Rect(0, 0, 90, 120)), nil
+ },
+ }
+ mock := &MockDocAnalyzer{Healthy: true}
+
+ result, err := p.ParseRaw(context.Background(), eng, mock)
+ if err != nil {
+ t.Fatalf("ParseRaw: %v", err)
+ }
+
+ // Verify retry zoom: page dimensions are always reported in PDF-point
+ // space. The retry render is 180×240 px at 6× zoom → 30×40 PDF-point.
+ if got, want := result.PageHeight[0], 40.0; got != want {
+ t.Fatalf("PageHeight[0] = %v, want %v (PDF-point height)", got, want)
+ }
+ if got, want := result.PageWidth[0], 30.0; got != want {
+ t.Fatalf("PageWidth[0] = %v, want %v (PDF-point width)", got, want)
+ }
+}
+
+func TestParser_ParseRaw_RetryZoomUsesHigherDPIForOCR(t *testing.T) {
+ cfg := pdf.DefaultParserConfig()
+ cfg.Zoom = 2
+ p := NewParser(cfg)
+
+ eng := &MockEngine{
+ NumPages: 1,
+ RenderPageImageFunc: func(_ int, dpi float64) (image.Image, error) {
+ if dpi > pdf.DlaDPI {
+ return image.NewRGBA(image.Rect(0, 0, 180, 240)), nil
+ }
+ return image.NewRGBA(image.Rect(0, 0, 90, 120)), nil
+ },
+ }
+ analyzer := &recordingAnalyzer{}
+
+ result, err := p.ParseRaw(context.Background(), eng, analyzer)
+ if err != nil {
+ t.Fatalf("ParseRaw: %v", err)
+ }
+ if len(result.Sections) == 0 {
+ t.Fatal("expected retryZoom OCR to produce sections")
+ }
+ w, h, ok := analyzer.lastDetectSize()
+ if !ok {
+ t.Fatal("expected OCRDetect to be called")
+ }
+ if w != 180 || h != 240 {
+ t.Fatalf("retryZoom OCRDetect used image size %dx%d, want 180x240", w, h)
+ }
+}
+
+// stableSections normalizes Sections to a comparable shape: positions
+// become a sorted tuple list and PositionTag is omitted since the test
+// only cares about text + layout-type + position geometry.
+func stableSections(sections []pdf.Section) []stableSection {
+ out := make([]stableSection, len(sections))
+ for i, s := range sections {
+ var pages []int
+ var bbox [4]float64
+ if len(s.Positions) > 0 {
+ p := s.Positions[0]
+ pages = append(pages, p.PageNumbers...)
+ bbox = [4]float64{p.Left, p.Right, p.Top, p.Bottom}
+ }
+ // Defensive copy and sort so worker completion order cannot
+ // affect the comparison.
+ sortPages(pages)
+ out[i] = stableSection{
+ Text: s.Text,
+ LayoutType: s.LayoutType,
+ Pages: pages,
+ BBox: bbox,
+ }
+ }
+ return out
+}
+
+type stableSection struct {
+ Text string
+ LayoutType string
+ Pages []int
+ BBox [4]float64
+}
+
+type stableTable struct {
+ Positions [][]int
+}
+
+func stableTables(tables []pdf.TableItem) []stableTable {
+ out := make([]stableTable, len(tables))
+ for i, t := range tables {
+ positions := make([][]int, 0, len(t.Positions))
+ for _, p := range t.Positions {
+ pages := append([]int(nil), p.PageNumbers...)
+ sortPages(pages)
+ positions = append(positions, pages)
+ }
+ out[i] = stableTable{Positions: positions}
+ }
+ return out
+}
+
+func sortPages(pages []int) {
+ // Small fixed slice — insertion sort is fine.
+ for i := 1; i < len(pages); i++ {
+ for j := i; j > 0 && pages[j-1] > pages[j]; j-- {
+ pages[j-1], pages[j] = pages[j], pages[j-1]
+ }
+ }
+}
+
+// setPoolSize resizes the process-wide page worker pool for the duration of
+// a test and restores the prior size afterwards. With Config.Parallelism
+// removed, the pool worker count is the only page-concurrency knob.
+func setPoolSize(t *testing.T, n int) {
+ t.Helper()
+ orig := PageWorkerPoolStats().DesiredWorkers
+ SetPageWorkerPoolSize(n)
+ t.Cleanup(func() { SetPageWorkerPoolSize(orig) })
+}
+
+// imageHash produces a stable PNG-content fingerprint for an image so
+// equivalence comparisons remain independent of concrete image types.
+func imageHash(img image.Image) string {
+ if img == nil {
+ return ""
+ }
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ return ""
+ }
+ h := sha256.New()
+ h.Write(buf.Bytes())
+ return hex.EncodeToString(h.Sum(nil))
+}
diff --git a/internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go b/internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
index cad7169937..4c5c082536 100644
--- a/internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
+++ b/internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
@@ -592,25 +592,24 @@ func TestIntegration_GarbageLayout(t *testing.T) {
t.Logf("Sections: %d", len(result.Sections))
}
-// TestIntegration_MultiChunk verifies chunked processing for large documents.
+// TestIntegration_MultiChunk verifies parsing for large documents.
func TestIntegration_MultiChunk(t *testing.T) {
client := mustConnectInferenceClient(t)
data := mustReadPDF(t, "19_multipage_chunk.pdf")
cfg := pdf.DefaultParserConfig()
- cfg.BatchSize = 10 // small batches to force multi-batch path
p := NewParser(cfg)
result, err := p.Parse(context.Background(), data, client)
if err != nil {
t.Fatalf("Parse: %v", err)
}
+ defer result.Close()
- // 52 pages with 10-page batches → >= 6 batches.
if len(result.Sections) == 0 {
- t.Error("multi-batch should produce sections")
+ t.Error("large document should produce sections")
}
- t.Logf("52 pages × batchSize=10: %d sections, %d tables",
+ t.Logf("52 pages: %d sections, %d tables",
len(result.Sections), len(result.Tables))
}
diff --git a/internal/deepdoc/parser/pdf/parser_test.go b/internal/deepdoc/parser/pdf/parser_test.go
index de44ab0b1d..38829c1075 100644
--- a/internal/deepdoc/parser/pdf/parser_test.go
+++ b/internal/deepdoc/parser/pdf/parser_test.go
@@ -22,9 +22,9 @@ func newTestParser() *Parser {
func newMockDocAnalyzer(healthy bool, boxes []pdf.OCRBox, texts []pdf.OCRText) *MockDocAnalyzer {
return &MockDocAnalyzer{
- Healthy: healthy,
- OCRBoxes: boxes,
- OCRTexts: texts,
+ Healthy: healthy,
+ OCRBoxes: boxes,
+ OCRTexts: texts,
}
}
@@ -35,28 +35,29 @@ func newSimpleMockDocAnalyzer() *MockDocAnalyzer {
// ── OCR fallback ──────────────────────────────────────────────────────
func TestOCR_Fallback(t *testing.T) {
+ p := newTestParser()
dummyImg := image.NewRGBA(image.Rect(0, 0, 100, 100))
t.Run("nil image", func(t *testing.T) {
- if got := ocrDetectAndRecognize(context.Background(), nil, &MockDocAnalyzer{Healthy: true}, 0, "garbled page"); got != nil {
+ if got := p.ocrDetectAndRecognize(context.Background(), nil, &MockDocAnalyzer{Healthy: true}, 0, "garbled page"); got != nil {
t.Error("nil image → nil")
}
})
t.Run("detect returns no boxes", func(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, OCRBoxes: nil}
- if got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page"); got != nil {
+ if got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page"); got != nil {
t.Error("no det boxes → nil")
}
})
t.Run("detect + recognize success", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40}},
OCRTexts: []pdf.OCRText{{Text: "Hello", Confidence: 0.9}},
}
- got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
+ got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
if len(got) != 1 {
t.Fatalf("expected 1 pdf.TextChar, got %d", len(got))
}
@@ -67,11 +68,11 @@ func TestOCR_Fallback(t *testing.T) {
t.Run("detect boxes but rec returns empty text", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40}},
OCRTexts: []pdf.OCRText{{Text: "", Confidence: 0.1}},
}
- got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
+ got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
if len(got) != 0 {
t.Error("empty rec text → empty result")
}
@@ -83,17 +84,18 @@ func TestOCR_Fallback(t *testing.T) {
// ── OCR scan page ──────────────────────────────────────────────────────
func TestOCR_ScanPage(t *testing.T) {
+ p := newTestParser()
dummyImg := image.NewRGBA(image.Rect(0, 0, 100, 100))
t.Run("nil image", func(t *testing.T) {
- if got := ocrDetectAndRecognize(context.Background(), nil, &MockDocAnalyzer{Healthy: true}, 0, "scan page"); got != nil {
+ if got := p.ocrDetectAndRecognize(context.Background(), nil, &MockDocAnalyzer{Healthy: true}, 0, "scan page"); got != nil {
t.Error("nil image → nil")
}
})
t.Run("detect returns no boxes", func(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, OCRBoxes: nil}
- if got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page"); got != nil {
+ if got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page"); got != nil {
t.Error("no det boxes → nil")
}
})
@@ -107,7 +109,7 @@ func TestOCR_ScanPage(t *testing.T) {
},
OCRTexts: []pdf.OCRText{{Text: "Hello", Confidence: 0.9}, {Text: "World", Confidence: 0.8}},
}
- got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page")
+ got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page")
if len(got) < 1 {
t.Error("expected at least 1 pdf.TextChar")
}
@@ -115,11 +117,11 @@ func TestOCR_ScanPage(t *testing.T) {
t.Run("detect success but rec returns empty", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40}},
OCRTexts: []pdf.OCRText{},
}
- got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page")
+ got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "scan page")
if len(got) != 0 {
t.Error("no rec text → empty")
}
@@ -129,6 +131,7 @@ func TestOCR_ScanPage(t *testing.T) {
// ── OCR table cell ─────────────────────────────────────────────────────
func TestOCR_TableCell(t *testing.T) {
+ p := newTestParser()
t.Run("fill single empty cell", func(t *testing.T) {
cells := []pdf.TSRCell{
{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: ""},
@@ -137,7 +140,7 @@ func TestOCR_TableCell(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, OCRTexts: []pdf.OCRText{{Text: "识别结果", Confidence: 0.9}}}
dummy := image.NewRGBA(image.Rect(0, 0, 200, 50))
- ocrTableCells(context.Background(), cells, dummy, mock)
+ p.ocrTableCells(context.Background(), cells, dummy, mock)
if cells[0].Text != "识别结果" {
t.Errorf("empty cell not filled: %q", cells[0].Text)
@@ -152,20 +155,20 @@ func TestOCR_TableCell(t *testing.T) {
{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: "A"},
{X0: 100, Y0: 0, X1: 200, Y1: 50, Text: "B"},
}
- ocrTableCells(context.Background(), cells, nil, nil) // should not panic
+ p.ocrTableCells(context.Background(), cells, nil, nil) // should not panic
if cells[0].Text != "A" || cells[1].Text != "B" {
t.Error("filled cells should not change")
}
})
t.Run("empty cells list", func(t *testing.T) {
- ocrTableCells(context.Background(), nil, nil, nil) // should not panic
- ocrTableCells(context.Background(), []pdf.TSRCell{}, nil, nil)
+ p.ocrTableCells(context.Background(), nil, nil, nil) // should not panic
+ p.ocrTableCells(context.Background(), []pdf.TSRCell{}, nil, nil)
})
t.Run("no DeepDoc — skip", func(t *testing.T) {
cells := []pdf.TSRCell{{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: ""}}
- ocrTableCells(context.Background(), cells, nil, nil)
+ p.ocrTableCells(context.Background(), cells, nil, nil)
if cells[0].Text != "" {
t.Error("without DeepDoc, cell should stay empty")
}
@@ -174,7 +177,7 @@ func TestOCR_TableCell(t *testing.T) {
t.Run("no cropped image — skip", func(t *testing.T) {
cells := []pdf.TSRCell{{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: ""}}
mock := &MockDocAnalyzer{Healthy: true, OCRTexts: []pdf.OCRText{{Text: "x", Confidence: 0.5}}}
- ocrTableCells(context.Background(), cells, nil, mock)
+ p.ocrTableCells(context.Background(), cells, nil, mock)
if cells[0].Text != "" {
t.Error("without image, cell should stay empty")
}
@@ -184,7 +187,7 @@ func TestOCR_TableCell(t *testing.T) {
cells := []pdf.TSRCell{{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: ""}}
mock := &MockDocAnalyzer{Healthy: true, OCRTexts: []pdf.OCRText{}}
dummy := image.NewRGBA(image.Rect(0, 0, 100, 50))
- ocrTableCells(context.Background(), cells, dummy, mock)
+ p.ocrTableCells(context.Background(), cells, dummy, mock)
if cells[0].Text != "" {
t.Error("empty OCR result → cell stays empty")
}
@@ -195,7 +198,7 @@ func TestOCR_TableCell(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, OCRTexts: []pdf.OCRText{{Text: "out of bounds", Confidence: 0.9}}}
dummy := image.NewRGBA(image.Rect(0, 0, 100, 100))
// Should not panic — gracefully degrade
- ocrTableCells(context.Background(), cells, dummy, mock)
+ p.ocrTableCells(context.Background(), cells, dummy, mock)
t.Logf("out-of-bounds cell: text=%q", cells[0].Text)
})
}
@@ -326,17 +329,18 @@ func TestIsGarbledPage(t *testing.T) {
}
func TestOCR_Fallback_PUAGarbled(t *testing.T) {
+ p := newTestParser()
pua := make([]pdf.TextChar, 50)
for i := range pua {
pua[i] = pdf.TextChar{Text: string(rune(0xE000 + i%10)), PageNumber: 0}
}
dummyImg := image.NewRGBA(image.Rect(0, 0, 100, 100))
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 10, Y0: 20, X1: 90, Y1: 20, X2: 90, Y2: 40, X3: 10, Y3: 40}},
OCRTexts: []pdf.OCRText{{Text: "PUA OCR text", Confidence: 0.9}},
}
- got := ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
+ got := p.ocrDetectAndRecognize(context.Background(), dummyImg, mock, 0, "garbled page")
if len(got) != 1 || got[0].Text != "PUA OCR text" {
t.Errorf("PUA garbled should trigger OCR, got %v", got)
}
@@ -345,11 +349,12 @@ func TestOCR_Fallback_PUAGarbled(t *testing.T) {
// ── ocrMergeChars ──────────────────────────────────────────────────────
func TestOCR_MergeChars(t *testing.T) {
+ p := newTestParser()
dummyImg := image.NewRGBA(image.Rect(0, 0, 600, 600))
t.Run("nil image", func(t *testing.T) {
chars := []pdf.TextChar{{X0: 10, Top: 10, X1: 20, Bottom: 30, Text: "A", PageNumber: 0}}
- if boxes := ocrMergeChars(context.Background(), nil, chars, &MockDocAnalyzer{Healthy: true}, 0); boxes != nil {
+ if boxes := p.ocrMergeChars(context.Background(), nil, chars, &MockDocAnalyzer{Healthy: true}, 0); boxes != nil {
t.Error("nil image → nil")
}
})
@@ -357,19 +362,19 @@ func TestOCR_MergeChars(t *testing.T) {
t.Run("detect returns no boxes", func(t *testing.T) {
mock := &MockDocAnalyzer{Healthy: true, OCRBoxes: []pdf.OCRBox{}}
chars := []pdf.TextChar{{X0: 10, Top: 10, X1: 20, Bottom: 30, Text: "A", PageNumber: 0}}
- if boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0); boxes != nil {
+ if boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0); boxes != nil {
t.Error("no detect boxes → nil")
}
})
t.Run("detect boxes — all overlap with chars (chars used, Python-aligned)", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 15, Y0: 15, X1: 150, Y1: 15, X2: 150, Y2: 150, X3: 15, Y3: 150}},
OCRTexts: []pdf.OCRText{{Text: "Hello OCR", Confidence: 0.9}},
}
chars := []pdf.TextChar{{X0: 10, X1: 30, Top: 10, Bottom: 30, Text: "Hello", PageNumber: 0}}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -381,12 +386,12 @@ func TestOCR_MergeChars(t *testing.T) {
t.Run("detect boxes — none overlap with chars", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 240, Y0: 240, X1: 270, Y1: 240, X2: 270, Y2: 270, X3: 240, Y3: 270}},
OCRTexts: []pdf.OCRText{{Text: "OCR", Confidence: 0.9}},
}
chars := []pdf.TextChar{{X0: 10, X1: 20, Top: 10, Bottom: 20, Text: "A", PageNumber: 0}}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box (OCR), got %d", len(boxes))
}
@@ -397,12 +402,12 @@ func TestOCR_MergeChars(t *testing.T) {
t.Run("detect box — no chars and OCR returns empty", func(t *testing.T) {
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 240, Y0: 240, X1: 270, Y1: 240, X2: 270, Y2: 270, X3: 240, Y3: 270}},
OCRTexts: []pdf.OCRText{},
}
chars := []pdf.TextChar{{X0: 10, X1: 20, Top: 10, Bottom: 20, Text: "A", PageNumber: 0}}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 0 {
t.Fatalf("expected 0 boxes (empty OCR), got %d", len(boxes))
}
@@ -421,7 +426,7 @@ func TestOCR_MergeChars(t *testing.T) {
},
}
chars := []pdf.TextChar{{X0: 10, X1: 30, Top: 10, Bottom: 30, Text: "Hello", PageNumber: 0}}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 2 {
t.Fatalf("expected 2 boxes, got %d", len(boxes))
}
@@ -449,7 +454,7 @@ func TestOCR_MergeChars(t *testing.T) {
{X0: 70, X1: 90, Top: 110, Bottom: 130, Text: "c", PageNumber: 0},
{X0: 10, X1: 30, Top: 10, Bottom: 30, Text: "a", PageNumber: 0},
}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 2 {
t.Fatalf("expected 2 detect boxes, got %d", len(boxes))
}
@@ -476,7 +481,7 @@ func TestOCR_MergeChars(t *testing.T) {
{X0: 10, X1: 30, Top: 30, Bottom: 50, Text: "A", PageNumber: 0},
{X0: 40, X1: 60, Top: 20, Bottom: 120, Text: "B", PageNumber: 0},
}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -499,7 +504,7 @@ func TestOCR_MergeChars(t *testing.T) {
{X0: 30, X1: 40, Top: 10, Bottom: 20, Text: "", PageNumber: 0},
{X0: 50, X1: 60, Top: 10, Bottom: 20, Text: "a", PageNumber: 0},
}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -513,7 +518,7 @@ func TestOCR_MergeChars(t *testing.T) {
// Chars at (10,10-25) → within the box region. Char text "do" is
// used (Python-aligned: embedded chars are more precise than OCR).
mock := &MockDocAnalyzer{
- Healthy: true,
+ Healthy: true,
OCRBoxes: []pdf.OCRBox{{X0: 30, Y0: 30, X1: 90, Y1: 30, X2: 90, Y2: 90, X3: 30, Y3: 90}},
OCRTexts: []pdf.OCRText{{Text: "docker commit infiniflow", Confidence: 0.95}},
}
@@ -521,7 +526,7 @@ func TestOCR_MergeChars(t *testing.T) {
{Text: "d", X0: 10, X1: 20, Top: 10, Bottom: 25, PageNumber: 0},
{Text: "o", X0: 21, X1: 30, Top: 10, Bottom: 25, PageNumber: 0},
}
- boxes := ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
+ boxes := p.ocrMergeChars(context.Background(), dummyImg, chars, mock, 0)
if len(boxes) != 1 {
t.Fatalf("expected 1 box, got %d", len(boxes))
}
@@ -595,22 +600,25 @@ func TestParser_ConcurrentSafety(t *testing.T) {
wg.Wait()
}
-func TestParseRaw_ClampsFromPage(t *testing.T) {
- // A negative FromPage should be treated as page 0.
- // Only page 0 has content so we can verify clamping worked.
- eng := &MockEngine{NumPages: 3, Chars: map[int][]pdf.TextChar{
+func TestParseRaw_PageDimensions(t *testing.T) {
+ // ParseResult must carry per-page PDF-point dimensions so downstream
+ // consumers get PDF-point values directly without a zoom map.
+ eng := &MockEngine{NumPages: 1, Chars: map[int][]pdf.TextChar{
0: {{Text: "page0", X0: 100, X1: 200, Top: 100, Bottom: 120}},
}}
mockDLA := &MockDocAnalyzer{Healthy: true}
cfg := pdf.DefaultParserConfig()
- cfg.FromPage = -1
+ cfg.Zoom = 3
p := NewParser(cfg)
result, err := p.ParseRaw(context.Background(), eng, mockDLA)
if err != nil {
t.Fatalf("ParseRaw: %v", err)
}
- if len(result.Sections) == 0 {
- t.Error("expected sections from page 0")
+ if result.PageHeight == nil {
+ t.Fatal("PageHeight map should be initialized")
+ }
+ if result.PageWidth == nil {
+ t.Fatal("PageWidth map should be initialized")
}
}
@@ -640,175 +648,3 @@ func TestParseRaw_ZeroZoom_NoNaN(t *testing.T) {
t.Fatal("expected at least one position to validate")
}
}
-
-// ── Test for refactored helper functions ──────────────────────────────
-// These are simple tests for the helper functions to ensure they work.
-
-func TestParser_getBatchSize(t *testing.T) {
- tests := []struct {
- name string
- batchSize int
- want int
- }{
- {
- name: "positive batch size",
- batchSize: 100,
- want: 100,
- },
- {
- name: "zero batch size",
- batchSize: 0,
- want: 50,
- },
- {
- name: "negative batch size",
- batchSize: -1,
- want: 50,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- p := &Parser{Config: pdf.ParserConfig{BatchSize: tt.batchSize}}
- got := p.getBatchSize()
- if got != tt.want {
- t.Errorf("getBatchSize() = %v, want %v", got, tt.want)
- }
- })
- }
-}
-
-func TestParser_setupPageConcurrency(t *testing.T) {
- tests := []struct {
- name string
- maxConcurrency int
- wantCap int
- }{
- {
- name: "positive concurrency",
- maxConcurrency: 5,
- wantCap: 5,
- },
- {
- name: "zero concurrency",
- maxConcurrency: 0,
- wantCap: 1,
- },
- {
- name: "negative concurrency",
- maxConcurrency: -1,
- wantCap: 1,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- p := &Parser{Config: pdf.ParserConfig{MaxOCRConcurrency: tt.maxConcurrency}}
- sem, wg := p.setupPageConcurrency()
- if cap(sem) != tt.wantCap {
- t.Errorf("setupPageConcurrency() sem cap = %v, want %v", cap(sem), tt.wantCap)
- }
- if wg == nil {
- t.Error("setupPageConcurrency() wg should not be nil")
- }
- })
- }
-}
-
-func TestParser_prescanPages(t *testing.T) {
- // Provide at least 30 ASCII chars per page so DetectEnglish finds a run ≥30.
- charsPage0 := make([]pdf.TextChar, 50)
- for i := range charsPage0 {
- charsPage0[i] = pdf.TextChar{
- Text: "a", PageNumber: 0, Top: 10, Bottom: 20,
- X0: 50 + float64(i*10), X1: 58 + float64(i*10),
- }
- }
- charsPage1 := make([]pdf.TextChar, 50)
- for i := range charsPage1 {
- charsPage1[i] = pdf.TextChar{
- Text: "b", PageNumber: 1, Top: 10, Bottom: 20,
- X0: 50 + float64(i*10), X1: 58 + float64(i*10),
- }
- }
- eng := &MockEngine{
- NumPages: 2,
- Chars: map[int][]pdf.TextChar{
- 0: charsPage0,
- 1: charsPage1,
- },
- }
- p := &Parser{Config: pdf.DefaultParserConfig()}
-
- prescanChars, prescanMedianH, prescanMedianW, isEnglish, scanNoise := p.prescanPages(context.Background(), eng, 0, 1, 2)
-
- if _, ok := prescanChars[0]; !ok {
- t.Error("prescanPages() prescanChars should contain page 0")
- }
- if _, ok := prescanMedianH[0]; !ok {
- t.Error("prescanPages() prescanMedianH should contain page 0")
- }
- if _, ok := prescanMedianW[0]; !ok {
- t.Error("prescanPages() prescanMedianW should contain page 0")
- }
- if isEnglish != true {
- t.Errorf("prescanPages() isEnglish = %v, want true", isEnglish)
- }
- if scanNoise != false {
- t.Errorf("prescanPages() scanNoise = %v, want false", scanNoise)
- }
-}
-
-func TestParser_mergeBatchResults(t *testing.T) {
- p := &Parser{Config: pdf.DefaultParserConfig()}
- result := &pdf.ParseResult{
- Sections: []pdf.Section{{Text: "section1"}},
- Tables: []pdf.TableItem{{}},
- Metrics: pdf.PipelineMetrics{
- BoxesInitial: 10,
- BoxesTextMerge: 8,
- BoxesVertMerge: 5,
- BoxesFinal: 3,
- TablesCount: 1,
- },
- }
- batch := &pdf.ParseResult{
- Sections: []pdf.Section{{Text: "section2"}},
- Tables: []pdf.TableItem{{}},
- PageImages: map[int]image.Image{1: image.NewRGBA(image.Rect(0, 0, 10, 10))},
- Metrics: pdf.PipelineMetrics{
- BoxesInitial: 20,
- BoxesTextMerge: 15,
- BoxesVertMerge: 10,
- BoxesFinal: 6,
- TablesCount: 2,
- },
- }
-
- p.mergeBatchResults(result, batch)
-
- if len(result.Sections) != 2 {
- t.Errorf("mergeBatchResults() sections length = %v, want 2", len(result.Sections))
- }
- if len(result.Tables) != 2 {
- t.Errorf("mergeBatchResults() tables length = %v, want 2", len(result.Tables))
- }
- if result.Metrics.BoxesInitial != 30 {
- t.Errorf("mergeBatchResults() BoxesInitial = %v, want 30", result.Metrics.BoxesInitial)
- }
- if result.Metrics.BoxesTextMerge != 23 {
- t.Errorf("mergeBatchResults() BoxesTextMerge = %v, want 23", result.Metrics.BoxesTextMerge)
- }
- if result.Metrics.BoxesVertMerge != 15 {
- t.Errorf("mergeBatchResults() BoxesVertMerge = %v, want 15", result.Metrics.BoxesVertMerge)
- }
- if result.Metrics.BoxesFinal != 9 {
- t.Errorf("mergeBatchResults() BoxesFinal = %v, want 9", result.Metrics.BoxesFinal)
- }
- if result.Metrics.TablesCount != 3 {
- t.Errorf("mergeBatchResults() TablesCount = %v, want 3", result.Metrics.TablesCount)
- }
- if _, ok := result.PageImages[1]; !ok {
- t.Error("mergeBatchResults() pageImages should contain page 1")
- }
-}
diff --git a/internal/deepdoc/parser/pdf/pdfium/pdfium.go b/internal/deepdoc/parser/pdf/pdfium/pdfium.go
index 8945612d01..1a9b569b8f 100644
--- a/internal/deepdoc/parser/pdf/pdfium/pdfium.go
+++ b/internal/deepdoc/parser/pdf/pdfium/pdfium.go
@@ -52,6 +52,8 @@ import (
"sync"
"unicode/utf16"
"unsafe"
+
+ pdfsync "ragflow/internal/deepdoc/parser/pdf/pdfsync"
)
// Outline represents one entry in a PDF document outline (table of contents).
@@ -63,11 +65,6 @@ type Outline struct {
var initOnce sync.Once
-// pdfiumMu serializes all pdfium C API access. pdfium is NOT thread-safe —
-// concurrent calls to FPDF_LoadPage / FPDF_RenderPageBitmap corrupt the
-// global heap, causing SIGSEGV. See TestPdfiumConcurrentSafety.
-var pdfiumMu sync.Mutex
-
// Init initializes the PDFium library. Safe to call multiple times.
func Init() { initOnce.Do(func() { C.FPDF_InitLibrary() }) }
@@ -76,66 +73,71 @@ func Init() { initOnce.Do(func() { C.FPDF_InitLibrary() }) }
// (swapped from the MediaBox 595×842). The call is cheap — it opens the
// document and page, reads dimensions, then closes.
func PageSize(pdfData []byte, pageIdx int) (width, height float64, err error) {
- Init()
- pdfiumMu.Lock()
- defer pdfiumMu.Unlock()
- _, _, pw, ph, closeAll, err := openPage(pdfData, pageIdx)
- if err != nil {
- return 0, 0, err
- }
- closeAll()
- return pw, ph, nil
+ pdfsync.With(func() {
+ Init()
+ _, _, pw, ph, closeAll, e := openPage(pdfData, pageIdx)
+ if e != nil {
+ err = e
+ return
+ }
+ closeAll()
+ width, height = pw, ph
+ })
+ return
}
// RenderPage renders a single page of a PDF to an *image.RGBA at the given DPI.
// pdfData is the raw PDF bytes, pageIdx is 0-based.
-func RenderPage(pdfData []byte, pageIdx int, dpi float64) (*image.RGBA, error) {
- Init()
- pdfiumMu.Lock()
- defer pdfiumMu.Unlock()
- _, page, pw, ph, closeAll, err := openPage(pdfData, pageIdx)
- if err != nil {
- return nil, err
- }
- defer closeAll()
+func RenderPage(pdfData []byte, pageIdx int, dpi float64) (out *image.RGBA, err error) {
+ pdfsync.With(func() {
+ Init()
+ _, page, pw, ph, closeAll, e := openPage(pdfData, pageIdx)
+ if e != nil {
+ err = e
+ return
+ }
+ defer closeAll()
- scale := dpi / 72.0
- pxW := int(math.Round(pw * scale))
- pxH := int(math.Round(ph * scale))
+ scale := dpi / 72.0
+ pxW := int(math.Round(pw * scale))
+ pxH := int(math.Round(ph * scale))
- bitmap := C.FPDFBitmap_Create(C.int(pxW), C.int(pxH), 1) // 1 = RGBA
- if bitmap == nil {
- return nil, fmt.Errorf("pdfium: FPDFBitmap_Create(%d,%d) returned nil", pxW, pxH)
- }
- defer C.FPDFBitmap_Destroy(bitmap)
-
- // Fill with opaque white before rendering, so transparent areas
- // (e.g. outside crop box) are white rather than undefined.
- stride := int(C.FPDFBitmap_GetStride(bitmap))
- buf := C.FPDFBitmap_GetBuffer(bitmap)
- pixels := (*[1 << 30]byte)(unsafe.Pointer(buf))[: pxH*stride : pxH*stride]
- for i := range pixels {
- pixels[i] = 255
- }
+ bitmap := C.FPDFBitmap_Create(C.int(pxW), C.int(pxH), 1) // 1 = RGBA
+ if bitmap == nil {
+ err = fmt.Errorf("pdfium: FPDFBitmap_Create(%d,%d) returned nil", pxW, pxH)
+ return
+ }
+ defer C.FPDFBitmap_Destroy(bitmap)
+
+ // Fill with opaque white before rendering, so transparent areas
+ // (e.g. outside crop box) are white rather than undefined.
+ stride := int(C.FPDFBitmap_GetStride(bitmap))
+ buf := C.FPDFBitmap_GetBuffer(bitmap)
+ pixels := (*[1 << 30]byte)(unsafe.Pointer(buf))[: pxH*stride : pxH*stride]
+ for i := range pixels {
+ pixels[i] = 255
+ }
- // FPDF_ANNOT (0x01) — render annotations.
- // LCD text AA (0x02) is left off; default text smoothing is sufficient.
- C.FPDF_RenderPageBitmap(bitmap, page, 0, 0, C.int(pxW), C.int(pxH), 0, 0x01)
-
- // pdfium outputs BGRA; convert to RGBA.
- img := image.NewRGBA(image.Rect(0, 0, pxW, pxH))
- for y := 0; y < pxH; y++ {
- for x := 0; x < pxW; x++ {
- off := y*stride + x*4
- img.SetRGBA(x, y, color.RGBA{
- R: pixels[off+2], // B
- G: pixels[off+1], // G
- B: pixels[off], // R
- A: 255,
- })
+ // FPDF_ANNOT (0x01) — render annotations.
+ // LCD text AA (0x02) is left off; default text smoothing is sufficient.
+ C.FPDF_RenderPageBitmap(bitmap, page, 0, 0, C.int(pxW), C.int(pxH), 0, 0x01)
+
+ // pdfium outputs BGRA; convert to RGBA.
+ img := image.NewRGBA(image.Rect(0, 0, pxW, pxH))
+ for y := 0; y < pxH; y++ {
+ for x := 0; x < pxW; x++ {
+ off := y*stride + x*4
+ img.SetRGBA(x, y, color.RGBA{
+ R: pixels[off+2], // B
+ G: pixels[off+1], // G
+ B: pixels[off], // R
+ A: 255,
+ })
+ }
}
- }
- return img, nil
+ out = img
+ })
+ return
}
// openPage opens a document and page, returning post-rotation dimensions
@@ -187,62 +189,65 @@ func openPage(pdfData []byte, pageIdx int) (
// as required by pdfium's FPDFBookmark_GetTitle.
//
// Traversal is iterative with an explicit stack to avoid stack overflow on deep
-// outline trees. pdfium is not thread-safe; callers must hold pdfiumMu.
+// outline trees. pdfium is not thread-safe; all FPDF_* calls are serialized by
+// the shared pdfsync.Mu.
func ExtractOutlines(pdfData []byte) []Outline {
if len(pdfData) == 0 {
return nil
}
- Init()
- pdfiumMu.Lock()
- defer pdfiumMu.Unlock()
+ var out []Outline
+ pdfsync.With(func() {
+ Init()
- cData := C.CBytes(pdfData)
- defer C.free(cData)
+ cData := C.CBytes(pdfData)
+ defer C.free(cData)
- doc := C.FPDF_LoadMemDocument(unsafe.Pointer(cData), C.int(len(pdfData)), nil)
- if doc == nil {
- return nil
- }
- defer C.FPDF_CloseDocument(doc)
+ doc := C.FPDF_LoadMemDocument(unsafe.Pointer(cData), C.int(len(pdfData)), nil)
+ if doc == nil {
+ return
+ }
+ defer C.FPDF_CloseDocument(doc)
- type frame struct {
- bm C.FPDF_BOOKMARK
- level int
- }
+ type frame struct {
+ bm C.FPDF_BOOKMARK
+ level int
+ }
- var result []Outline
- stack := []frame{{bm: C.FPDFBookmark_GetFirstChild(doc, nil), level: 0}}
+ var result []Outline
+ stack := []frame{{bm: C.FPDFBookmark_GetFirstChild(doc, nil), level: 0}}
- for len(stack) > 0 {
- top := stack[len(stack)-1]
- stack = stack[:len(stack)-1]
- if top.bm == nil {
- continue
- }
+ for len(stack) > 0 {
+ top := stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ if top.bm == nil {
+ continue
+ }
- // Title (UTF-16LE).
- title := bookmarkTitle(top.bm)
+ // Title (UTF-16LE).
+ title := bookmarkTitle(top.bm)
- // Page number.
- pageNum := 1 // default to page 1 if dest is unavailable
- if dest := C.FPDFBookmark_GetDest(doc, top.bm); dest != nil {
- pn := C.FPDFDest_GetDestPageIndex(doc, dest)
- if pn >= 0 {
- pageNum = int(pn) + 1 // pdfium returns 0-based
+ // Page number.
+ pageNum := 1 // default to page 1 if dest is unavailable
+ if dest := C.FPDFBookmark_GetDest(doc, top.bm); dest != nil {
+ pn := C.FPDFDest_GetDestPageIndex(doc, dest)
+ if pn >= 0 {
+ pageNum = int(pn) + 1 // pdfium returns 0-based
+ }
}
- }
- result = append(result, Outline{Title: title, Level: top.level, PageNumber: pageNum})
+ result = append(result, Outline{Title: title, Level: top.level, PageNumber: pageNum})
- // Push siblings after children so children are processed first (pre-order).
- if sibling := C.FPDFBookmark_GetNextSibling(doc, top.bm); sibling != nil {
- stack = append(stack, frame{bm: sibling, level: top.level})
- }
- if child := C.FPDFBookmark_GetFirstChild(doc, top.bm); child != nil {
- stack = append(stack, frame{bm: child, level: top.level + 1})
+ // Push siblings after children so children are processed first (pre-order).
+ if sibling := C.FPDFBookmark_GetNextSibling(doc, top.bm); sibling != nil {
+ stack = append(stack, frame{bm: sibling, level: top.level})
+ }
+ if child := C.FPDFBookmark_GetFirstChild(doc, top.bm); child != nil {
+ stack = append(stack, frame{bm: child, level: top.level + 1})
+ }
}
- }
- return result
+ out = result
+ })
+ return out
}
// bookmarkTitle reads a bookmark's title (UTF-16LE) and converts to Go string.
diff --git a/internal/deepdoc/parser/pdf/pdfium/pdfium_test.go b/internal/deepdoc/parser/pdf/pdfium/pdfium_test.go
index 03c450ff48..56977bd700 100644
--- a/internal/deepdoc/parser/pdf/pdfium/pdfium_test.go
+++ b/internal/deepdoc/parser/pdf/pdfium/pdfium_test.go
@@ -207,11 +207,11 @@ func TestPageSize(t *testing.T) {
}
}
-// TestPdfiumConcurrentSafety verifies that the pdfiumMu mutex prevents
-// SIGSEGV from concurrent pdfium access. Without the mutex, 10 goroutines
-// calling PageSize/RenderPage simultaneously causes heap corruption within
-// milliseconds (empirically proven). If this test completes without
-// crashing, the mutex is working.
+// TestPdfiumConcurrentSafety verifies that the shared pdfsync.Mu mutex
+// prevents SIGSEGV from concurrent pdfium access. Without the mutex, 10
+// goroutines calling PageSize/RenderPage simultaneously cause heap
+// corruption within milliseconds (empirically proven). If this test
+// completes without crashing, the mutex is working.
func TestPdfiumConcurrentSafety(t *testing.T) {
data := readPDF(t, "01_english_simple.pdf")
diff --git a/internal/deepdoc/parser/pdf/pdfium_integration_test.go b/internal/deepdoc/parser/pdf/pdfium_integration_test.go
index 300564db31..d4e13b025a 100644
--- a/internal/deepdoc/parser/pdf/pdfium_integration_test.go
+++ b/internal/deepdoc/parser/pdf/pdfium_integration_test.go
@@ -53,13 +53,13 @@ func TestParse_PdfiumRender(t *testing.T) {
if err != nil {
t.Fatalf("Parse: %v", err)
}
- t.Logf("Parse: %d sections, %d tables, %d page images", len(result.Sections), len(result.Tables), len(result.PageImages))
+ t.Logf("Parse: %d sections, %d tables, %d pages", len(result.Sections), len(result.Tables), len(result.PageHeight))
if len(result.Sections) == 0 {
t.Error("expected at least one section")
}
- if len(result.PageImages) == 0 {
- t.Error("expected at least one page image")
+ if len(result.PageHeight) == 0 {
+ t.Error("expected at least one page dimension entry")
}
}
diff --git a/internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go b/internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go
index 2c264e2227..3c69516dcb 100644
--- a/internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go
+++ b/internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go
@@ -21,6 +21,8 @@ import (
"strings"
pdfoxide "github.com/yfedoseev/pdf_oxide/go"
+
+ pdfsync "ragflow/internal/deepdoc/parser/pdf/pdfsync"
)
// ── pdf_oxide-based types ──────────────────────────────────────────
@@ -64,18 +66,26 @@ type RenderResult struct {
// Open opens a PDF file from a file path.
func Open(path string) (*Document, error) {
- doc, err := pdfoxide.Open(path)
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: open %s: %w", path, err)
+ var doc *pdfoxide.PdfDocument
+ var oerr error
+ pdfsync.With(func() {
+ doc, oerr = pdfoxide.Open(path)
+ })
+ if oerr != nil {
+ return nil, fmt.Errorf("pdfplumber: open %s: %w", path, oerr)
}
return &Document{Inner: doc}, nil
}
// OpenBytes opens a PDF from raw bytes in memory.
func OpenBytes(data []byte) (*Document, error) {
- doc, err := pdfoxide.OpenFromBytes(data)
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: open from bytes: %w", err)
+ var doc *pdfoxide.PdfDocument
+ var oerr error
+ pdfsync.With(func() {
+ doc, oerr = pdfoxide.OpenFromBytes(data)
+ })
+ if oerr != nil {
+ return nil, fmt.Errorf("pdfplumber: open from bytes: %w", oerr)
}
return &Document{Inner: doc}, nil
}
@@ -83,7 +93,9 @@ func OpenBytes(data []byte) (*Document, error) {
// Close releases the document handle.
func (d *Document) Close() {
if d.Inner != nil {
- d.Inner.Close()
+ pdfsync.With(func() {
+ d.Inner.Close()
+ })
d.Inner = nil
}
}
@@ -93,7 +105,15 @@ func (d *Document) PageCount() (int, error) {
if d.Inner == nil {
return 0, fmt.Errorf("pdfplumber: document is closed")
}
- return d.Inner.PageCount()
+ var n int
+ var perr error
+ pdfsync.With(func() {
+ n, perr = d.Inner.PageCount()
+ })
+ if perr != nil {
+ return 0, perr
+ }
+ return n, nil
}
// PageSize returns the pre-rotation page dimensions from pdf_oxide in PDF
@@ -104,78 +124,94 @@ func (d *Document) PageSize(pageIdx int) (width, height float64, err error) {
if d.Inner == nil {
return 0, 0, fmt.Errorf("pdfplumber: document is closed")
}
- info, err := d.Inner.PageInfo(pageIdx)
- if err != nil {
- return 0, 0, err
- }
- return float64(info.Width), float64(info.Height), nil
+ pdfsync.With(func() {
+ info, e := d.Inner.PageInfo(pageIdx)
+ if e != nil {
+ err = e
+ return
+ }
+ width, height = float64(info.Width), float64(info.Height)
+ })
+ return
}
// GetPageChars returns all characters on a page (0-indexed).
-func (d *Document) GetPageChars(pageIdx int) ([]char, error) {
+//
+// The whole body runs under pdfsync.Mu so the native ExtractChars / PageInfo
+// calls never interleave with pdfium (the two bindings share one PDFium
+// instance). Note it calls d.Inner.PageCount() directly rather than the
+// guarded Document.PageCount, because this method already holds the lock and
+// sync.Mutex is not reentrant.
+func (d *Document) GetPageChars(pageIdx int) (chars []char, err error) {
if d.Inner == nil {
return nil, fmt.Errorf("pdfplumber: document is closed")
}
- n, err := d.PageCount()
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: page count: %w", err)
- }
- if pageIdx < 0 || pageIdx >= n {
- return nil, fmt.Errorf("pdfplumber: page index %d out of range (pages: %d)", pageIdx, n)
- }
- raw, err := d.Inner.ExtractChars(pageIdx)
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: extract chars page %d: %w", pageIdx, err)
- }
+ pdfsync.With(func() {
+ n, e := d.Inner.PageCount()
+ if e != nil {
+ err = fmt.Errorf("pdfplumber: page count: %w", e)
+ return
+ }
+ if pageIdx < 0 || pageIdx >= n {
+ err = fmt.Errorf("pdfplumber: page index %d out of range (pages: %d)", pageIdx, n)
+ return
+ }
+ raw, e := d.Inner.ExtractChars(pageIdx)
+ if e != nil {
+ err = fmt.Errorf("pdfplumber: extract chars page %d: %w", pageIdx, e)
+ return
+ }
- // pdf_oxide returns Y in PDF coordinate system (origin bottom-left, Y↑).
- // Python pdfplumber internally flips to top-left origin (Y↓), matching
- // "top" = distance from page top. We replicate that here so that
- // sortByPageThenY produces top-to-bottom reading order.
- info, err := d.Inner.PageInfo(pageIdx)
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: page info %d: %w", pageIdx, err)
- }
- // Page height: use CropBox (matches pdfplumber's page.height).
- // pdf_oxide bbox: [baseline, baseline + font_size] — no descent
- // below baseline. pdfplumber bbox: [baseline - descent, baseline
- // + ascent]. Both have height = font_size, but the Y origin
- // differs. We keep the raw pdf_oxide bbox and sort by Bottom
- // (= pageHeight - c.Y) in groupCharsToLines so all chars on the
- // same baseline share the same sort key regardless of font size.
- pageHeight := float64(info.CropBox.Height)
- if pageHeight <= 0 {
- pageHeight = float64(info.Height) // fallback
- }
+ // pdf_oxide returns Y in PDF coordinate system (origin bottom-left, Y↑).
+ // Python pdfplumber internally flips to top-left origin (Y↓), matching
+ // "top" = distance from page top. We replicate that here so that
+ // FinalReadingOrderMerge produces top-to-bottom reading order.
+ info, e := d.Inner.PageInfo(pageIdx)
+ if e != nil {
+ err = fmt.Errorf("pdfplumber: page info %d: %w", pageIdx, e)
+ return
+ }
+ // Page height: use CropBox (matches pdfplumber's page.height).
+ // pdf_oxide bbox: [baseline, baseline + font_size] — no descent
+ // below baseline. pdfplumber bbox: [baseline - descent, baseline
+ // + ascent]. Both have height = font_size, but the Y origin
+ // differs. We keep the raw pdf_oxide bbox and sort by Bottom
+ // (= pageHeight - c.Y) in groupCharsToLines so all chars on the
+ // same baseline share the same sort key regardless of font size.
+ pageHeight := float64(info.CropBox.Height)
+ if pageHeight <= 0 {
+ pageHeight = float64(info.Height) // fallback
+ }
- chars := make([]char, len(raw))
- for i, c := range raw {
- x0 := float64(c.X)
- fs := float64(c.FontSize)
- top := pageHeight - float64(c.Y) - float64(c.Height)
- w := float64(c.Width)
- h := float64(c.Height)
- chars[i] = char{
- Text: string(c.Char),
- Fontname: c.FontName,
- Size: fs,
- X0: x0,
- X1: x0 + w,
- Top: top,
- Bottom: top + h,
- Width: w,
- Height: h,
- Doctop: top,
- Matrix: [6]float64{fs, 0, 0, fs, x0, top},
- Upright: true,
- StrokingColor: "",
- NonStrokingColor: "",
- Ncs: "",
- Adv: fs * 0.5,
- PageNumber: pageIdx + 1,
+ chars = make([]char, len(raw))
+ for i, c := range raw {
+ x0 := float64(c.X)
+ fs := float64(c.FontSize)
+ top := pageHeight - float64(c.Y) - float64(c.Height)
+ w := float64(c.Width)
+ h := float64(c.Height)
+ chars[i] = char{
+ Text: string(c.Char),
+ Fontname: c.FontName,
+ Size: fs,
+ X0: x0,
+ X1: x0 + w,
+ Top: top,
+ Bottom: top + h,
+ Width: w,
+ Height: h,
+ Doctop: top,
+ Matrix: [6]float64{fs, 0, 0, fs, x0, top},
+ Upright: true,
+ StrokingColor: "",
+ NonStrokingColor: "",
+ Ncs: "",
+ Adv: fs * 0.5,
+ PageNumber: pageIdx + 1,
+ }
}
- }
- return chars, nil
+ })
+ return
}
// GetDedupePageChars returns deduplicated characters on a page (0-indexed).
@@ -286,13 +322,18 @@ func RenderPage(pdfData []byte, pageIdx int, dpi float64) (*RenderResult, error)
if len(pdfData) == 0 {
return nil, fmt.Errorf("pdfplumber: empty PDF data for rendering")
}
- doc, err := pdfoxide.OpenFromBytes(pdfData)
- if err != nil {
- return nil, fmt.Errorf("pdfplumber: open for render: %w", err)
- }
- defer doc.Close()
-
- return renderPageFromDoc(doc, pageIdx, dpi)
+ var res *RenderResult
+ var rerr error
+ pdfsync.With(func() {
+ doc, e := pdfoxide.OpenFromBytes(pdfData)
+ if e != nil {
+ rerr = fmt.Errorf("pdfplumber: open for render: %w", e)
+ return
+ }
+ defer doc.Close()
+ res, rerr = renderPageFromDoc(doc, pageIdx, dpi)
+ })
+ return res, rerr
}
// RenderPage renders a single page using the already-open document.
@@ -302,7 +343,12 @@ func (d *Document) RenderPage(pageIdx int, dpi float64) (*RenderResult, error) {
if d.Inner == nil {
return nil, fmt.Errorf("pdfplumber: document is closed")
}
- return renderPageFromDoc(d.Inner, pageIdx, dpi)
+ var res *RenderResult
+ var rerr error
+ pdfsync.With(func() {
+ res, rerr = renderPageFromDoc(d.Inner, pageIdx, dpi)
+ })
+ return res, rerr
}
// renderPageFromDoc is the shared rendering core: calls RenderPageRaw and
diff --git a/internal/deepdoc/parser/pdf/pdfsync/pdfsync.go b/internal/deepdoc/parser/pdf/pdfsync/pdfsync.go
new file mode 100644
index 0000000000..f01391f746
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/pdfsync/pdfsync.go
@@ -0,0 +1,43 @@
+//go:build cgo
+
+// Package pdfsync provides a single process-wide mutex that serializes ALL
+// access to the PDFium C library, regardless of which Go binding issues the
+// call.
+//
+// Both the cgo pdfium binding (package pdfium) and the Rust pdf_oxide binding
+// (package pdfoxide) are linked into the same final binary against the same
+// PDFium static library. build.sh collapses the duplicate FPDF_* symbols with
+// --allow-multiple-definition, so the process contains exactly ONE PDFium
+// instance. PDFium is documented as NOT thread-safe for any call — concurrent
+// calls corrupt the global heap and crash with SIGSEGV even when the calls
+// operate on different documents.
+//
+// Therefore every native entry point in either binding must hold this one
+// shared lock. Two independent mutexes would give the illusion of safety
+// while still allowing a cgo pdfium call and a Rust pdf_oxide call to
+// interleave onto the same PDFium instance. A single shared mutex is correct
+// in both the one-instance and the (hypothetical, build-breaking) two-instance
+// cases; two mutexes are only correct in the two-instance case.
+package pdfsync
+
+import "sync"
+
+// Mu serializes all PDFium C API calls across every binding linked into the
+// process. Acquire it (via With / WithErr) around every FPDF_* call and every
+// pdf_oxide Rust call that re-enters the same PDFium instance.
+var Mu sync.Mutex
+
+// With runs f while holding the shared PDFium mutex.
+func With(f func()) {
+ Mu.Lock()
+ defer Mu.Unlock()
+ f()
+}
+
+// WithErr runs f while holding the shared PDFium mutex and propagates its
+// error unchanged.
+func WithErr(f func() error) error {
+ Mu.Lock()
+ defer Mu.Unlock()
+ return f()
+}
diff --git a/internal/deepdoc/parser/pdf/pdfsync_shared_mutex_test.go b/internal/deepdoc/parser/pdf/pdfsync_shared_mutex_test.go
new file mode 100644
index 0000000000..13fcef8194
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/pdfsync_shared_mutex_test.go
@@ -0,0 +1,75 @@
+//go:build cgo && manual
+
+package pdf
+
+import (
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "ragflow/internal/deepdoc/parser/pdf/pdfium"
+ "ragflow/internal/deepdoc/parser/pdf/pdfoxide"
+)
+
+// TestPdfsyncSharedMutexAcrossBindings hammers both the cgo pdfium binding and
+// the Rust pdf_oxide binding concurrently on the same document. Both bindings
+// link a single PDFium instance (build.sh collapses the duplicate FPDF_*
+// symbols with --allow-multiple-definition), so each binding must serialize
+// through the SAME process-wide pdfsync.Mu. Two independent mutexes would
+// still interleave calls onto the shared PDFium heap and SIGSEGV. The test
+// therefore only passes if it completes without crashing — it directly
+// exercises the shared-mutex invariant described in pdfsync/pdfsync.go.
+func TestPdfsyncSharedMutexAcrossBindings(t *testing.T) {
+ pdfPath := filepath.Join("testdata", "pdfs", "01_english_simple.pdf")
+ data, err := os.ReadFile(pdfPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const goroutines = 16
+ const iterations = 3
+
+ var wg sync.WaitGroup
+ for i := 0; i < goroutines; i++ {
+ wg.Add(1)
+ go func(id int) {
+ defer wg.Done()
+ usePdfium := id%2 == 0
+ for j := 0; j < iterations; j++ {
+ if usePdfium {
+ if _, _, err := pdfium.PageSize(data, 0); err != nil {
+ t.Errorf("pdfium.PageSize: %v", err)
+ return
+ }
+ img, err := pdfium.RenderPage(data, 0, 72)
+ if err != nil {
+ t.Errorf("pdfium.RenderPage: %v", err)
+ return
+ }
+ if img.Bounds().Dx() <= 0 {
+ t.Error("pdfium.RenderPage returned zero-width image")
+ return
+ }
+ } else {
+ doc, err := pdfoxide.OpenBytes(data)
+ if err != nil {
+ t.Errorf("pdfoxide.OpenBytes: %v", err)
+ return
+ }
+ res, err := doc.RenderPage(0, 72)
+ doc.Close()
+ if err != nil {
+ t.Errorf("pdfoxide.RenderPage: %v", err)
+ return
+ }
+ if res.Width <= 0 {
+ t.Error("pdfoxide.RenderPage returned zero-width image")
+ return
+ }
+ }
+ }
+ }(i)
+ }
+ wg.Wait()
+}
diff --git a/internal/deepdoc/parser/pdf/pipeline_parity_test.go b/internal/deepdoc/parser/pdf/pipeline_parity_test.go
index 8bfb6e062c..4c000ae4a3 100644
--- a/internal/deepdoc/parser/pdf/pipeline_parity_test.go
+++ b/internal/deepdoc/parser/pdf/pipeline_parity_test.go
@@ -261,7 +261,7 @@ func TestVMWhitespaceGapBridge(t *testing.T) {
// Verify production lyt.NaiveVerticalMerge matches vWithWS (Python behavior).
mhMap := map[int]float64{1: mh}
mwMap := map[int]float64{1: 5}
- vmResult := lyt.NaiveVerticalMerge(boxes, mhMap, mwMap, false)
+ vmResult := lyt.NaiveVerticalMerge(boxes, mhMap, mwMap, nil)
t.Logf("lyt.NaiveVerticalMerge (production): %d sections", len(vmResult))
if len(vmResult) != nWS {
t.Errorf("lyt.NaiveVerticalMerge produced %d sections, want %d (Python-like with gap bridge)", len(vmResult), nWS)
diff --git a/internal/deepdoc/parser/pdf/snapshot_test.go b/internal/deepdoc/parser/pdf/snapshot_test.go
index d3f7b5c807..808ade8a11 100644
--- a/internal/deepdoc/parser/pdf/snapshot_test.go
+++ b/internal/deepdoc/parser/pdf/snapshot_test.go
@@ -49,7 +49,7 @@ func TestSnapshotStageComparison(t *testing.T) {
// Run Go lyt.TextMerge with default params
meanH := map[int]float64{0: avg(s1.MeanHeight)}
- merged := lyt.TextMerge(goBoxes, meanH, 3)
+ merged := lyt.TextMerge(goBoxes, meanH)
// Compare counts
if len(merged) > 0 {
@@ -61,7 +61,11 @@ func TestSnapshotStageComparison(t *testing.T) {
// Run Go lyt.NaiveVerticalMerge
meanW := map[int]float64{0: avg(s1.MeanWidth)}
- vm := lyt.NaiveVerticalMerge(merged, meanH, meanW, s1.IsEnglish)
+ pageEnglish := map[int]bool{}
+ if s1.IsEnglish {
+ pageEnglish[0] = true
+ }
+ vm := lyt.NaiveVerticalMerge(merged, meanH, meanW, pageEnglish)
if s6, ok := snap.Stages["_naive_vertical_merge"]; ok {
t.Logf(" Go VerticalMerge: %d -> %d boxes (Python: %d->%d)",
len(merged), len(vm), s6.BoxesBefore, s6.BoxesAfter)
diff --git a/internal/deepdoc/parser/pdf/table/table_annotate.go b/internal/deepdoc/parser/pdf/table/table_annotate.go
index 6ae3bed336..87d3719cd6 100644
--- a/internal/deepdoc/parser/pdf/table/table_annotate.go
+++ b/internal/deepdoc/parser/pdf/table/table_annotate.go
@@ -177,8 +177,8 @@ func AnnotateBoxLayouts(boxes []pdf.TextBox, regions []pdf.DLARegion, scale floa
// Compact: remove popped boxes into a new backing array (Python
// bxs.pop). Allocating a fresh slice is deliberate: annotations were
- // set in-place on the input elements, and callers (enrichWithDeepDoc)
- // rely on positional stability of the original slice for their
+ // set in-place on the input elements, and callers (enrichOnePageWithDeepDoc)
+ // rely on positional stability of the input slice for their
// write-back loop. Reusing the input backing array would shift
// survivors forward and break that index mapping.
survivors := 0
diff --git a/internal/deepdoc/parser/pdf/table/table_annotate_test.go b/internal/deepdoc/parser/pdf/table/table_annotate_test.go
index 23054f206d..3ac34468f4 100644
--- a/internal/deepdoc/parser/pdf/table/table_annotate_test.go
+++ b/internal/deepdoc/parser/pdf/table/table_annotate_test.go
@@ -351,7 +351,7 @@ func TestAnnotateBoxLayouts_MixedTypesLayoutNo(t *testing.T) {
// ability to write annotations back to the correct global box indices.
//
// The bug: annotateBoxLayouts compacts boxes in place in the shared backing
-// array, shifting survivors forward. enrichWithDeepDoc then iterates
+// array, shifting survivors forward. enrichOnePageWithDeepDoc then iterates
// len(indices) positions and writes pageBoxes[i] back to boxes[indices[i]],
// but after compaction pageBoxes[1] holds what was originally pageBoxes[2],
// so annotations land on the wrong global box.
diff --git a/internal/deepdoc/parser/pdf/table/table_cells_group_test.go b/internal/deepdoc/parser/pdf/table/table_cells_group_test.go
index 69a4b5b54f..f13492f09a 100644
--- a/internal/deepdoc/parser/pdf/table/table_cells_group_test.go
+++ b/internal/deepdoc/parser/pdf/table/table_cells_group_test.go
@@ -196,7 +196,7 @@ func TestFillCellTextFromBoxes(t *testing.T) {
})
}
-// ── enrichWithDeepDoc noop ─────────────────────────────────────────────
+// ── enrichOnePageWithDeepDoc noop ──────────────────────────────────────
func TestGroupTSRCellsToRows_SameHeight(t *testing.T) {
// All cells have identical height → medianH is that value → threshold = medianH/2
diff --git a/internal/deepdoc/parser/pdf/table/table_construct_test.go b/internal/deepdoc/parser/pdf/table/table_construct_test.go
index 86de5e956d..719a3d837f 100644
--- a/internal/deepdoc/parser/pdf/table/table_construct_test.go
+++ b/internal/deepdoc/parser/pdf/table/table_construct_test.go
@@ -1,4 +1,3 @@
-
package table
import (
@@ -20,7 +19,7 @@ func TestCellTexts(t *testing.T) {
}
func TestConstructTable_Simple3x2(t *testing.T) {
- // 3 columns × 2 rows — cells pre-filled (simulating extractTableBoxesFromImage).
+ // 3 columns × 2 rows — cells pre-filled (simulating enrichOnePageWithDeepDoc).
cells := []pdf.TSRCell{
{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: "A", Label: "table row"},
{X0: 101, Y0: 0, X1: 200, Y1: 50, Text: "B", Label: "table row"},
@@ -106,7 +105,7 @@ func TestConstructTable_CellsTextFilledAfterCall(t *testing.T) {
// constructTable should populate cell text from boxes.
// Bug: fillCellTextFromBoxes modifies a local copy — original cells stay empty,
// causing generate_test.go to output empty rows.
- // Cells pre-filled — constructTable no longer fills text (done in extractTableBoxesFromImage).
+ // Cells pre-filled — constructTable no longer fills text (done in enrichOnePageWithDeepDoc).
cells := []pdf.TSRCell{
{X0: 0, Y0: 0, X1: 100, Y1: 50, Text: "A1", Label: "table row"},
{X0: 101, Y0: 0, X1: 200, Y1: 50, Text: "B1", Label: "table row"},
@@ -161,7 +160,7 @@ func TestExtractTableAndReplace_CellTextFilled(t *testing.T) {
}
// TSR cells in crop pixel space (matching real TSR output).
- // Cells pre-filled (extractTableBoxesFromImage already ran fillText + OCR).
+ // Cells pre-filled (enrichOnePageWithDeepDoc already ran fillText + OCR).
cells := []pdf.TSRCell{
{X0: 35, Y0: 441, X1: 456, Y1: 500, Text: "标职务", Label: "table row"},
{X0: 460, Y0: 441, X1: 630, Y1: 500, Text: "飞机", Label: "table row"},
@@ -252,9 +251,9 @@ func TestFillCellTextFromBoxes_RCAnnotations(t *testing.T) {
// Boxes have R/C annotations but their spatial overlap with cell rects
// is marginal (real-world scenario). R/C path should still fill text.
boxes := []pdf.TextBox{
- {X0: 12, X1: 198, Top: 12, Bottom: 48, Text: "A", R: 0, C: 0}, // overlap ~92% → OK
+ {X0: 12, X1: 198, Top: 12, Bottom: 48, Text: "A", R: 0, C: 0}, // overlap ~92% → OK
{X0: 215, X1: 395, Top: 12, Bottom: 48, Text: "B", R: 0, C: 1}, // overlap ~90% → OK
- {X0: 12, X1: 198, Top: 58, Bottom: 92, Text: "C", R: 1, C: 0}, // overlap ~92% → OK
+ {X0: 12, X1: 198, Top: 58, Bottom: 92, Text: "C", R: 1, C: 0}, // overlap ~92% → OK
{X0: 215, X1: 350, Top: 58, Bottom: 92, Text: "D", R: 1, C: 1}, // overlap ~50% → MARGINAL
}
@@ -450,7 +449,7 @@ func TestIsCaptionBox(t *testing.T) {
{"Table 1: Transport Levels", true},
{"图表 1: 测试", true},
{"公司领导班子成员、出差地", false}, // plain text, not caption
- {"第十条到厂矿单位出差", false}, // normal paragraph
+ {"第十条到厂矿单位出差", false}, // normal paragraph
{"", false},
}
for _, tt := range tests {
diff --git a/internal/deepdoc/parser/pdf/table/table_orient_test.go b/internal/deepdoc/parser/pdf/table/table_orient_test.go
index 6ad22e8df9..fe4d76beeb 100644
--- a/internal/deepdoc/parser/pdf/table/table_orient_test.go
+++ b/internal/deepdoc/parser/pdf/table/table_orient_test.go
@@ -65,15 +65,6 @@ func (m *mockRotationDoc) OCRDetect(_ context.Context, img image.Image) ([]pdf.O
return boxes, nil
}
-func (m *mockRotationDoc) OCRRecognizeBatch(_ context.Context, cropped []image.Image) ([][]pdf.OCRText, []error) {
- results := make([][]pdf.OCRText, len(cropped))
- errs := make([]error, len(cropped))
- for i, img := range cropped {
- results[i], errs[i] = m.OCRRecognize(context.Background(), img)
- }
- return results, errs
-}
-
func (m *mockRotationDoc) OCRRecognize(_ context.Context, _ image.Image) ([]pdf.OCRText, error) {
angle := rotationOrder[(m.callSeq-1)%len(rotationOrder)] // use angle from last Detect call
cfg, ok := m.angles[angle]
diff --git a/internal/deepdoc/parser/pdf/table/table_post_test.go b/internal/deepdoc/parser/pdf/table/table_post_test.go
index f2cae473c9..ec7846c197 100644
--- a/internal/deepdoc/parser/pdf/table/table_post_test.go
+++ b/internal/deepdoc/parser/pdf/table/table_post_test.go
@@ -8,7 +8,7 @@ import (
)
// ============================================
-// 第一部分:findTableAnchors 的测试
+// Part 1: findTableAnchors tests
// ============================================
func TestFindTableAnchors_SingleTable(t *testing.T) {
@@ -121,7 +121,7 @@ func TestFindTableAnchors_DifferentPage(t *testing.T) {
}
// ============================================
-// 第二部分:buildTableHTMLs 的测试
+// Part 2: buildTableHTMLs tests
// ============================================
func TestBuildTableHTMLs_SingleTable(t *testing.T) {
@@ -182,7 +182,7 @@ func TestBuildTableHTMLs_WithTableBoxes(t *testing.T) {
}
// ============================================
-// 第三部分:insertTableBoxes 的测试
+// Part 3: insertTableBoxes tests
// ============================================
func TestInsertTableBoxes_Basic(t *testing.T) {
@@ -306,7 +306,7 @@ func TestInsertTableBoxes_EmptyHTML(t *testing.T) {
}
// ============================================
-// 第四部分:集成测试 - 验证重构后功能保持一致
+// Part 4: Integration tests - verify refactored behavior remains consistent
// ============================================
func TestExtractTableAndReplace_Integration(t *testing.T) {
@@ -380,7 +380,7 @@ func TestExtractTableAndReplace_ZeroBoxesWithTables(t *testing.T) {
}
// ============================================
-// 第五部分:FilterBoxesByRemoveSet 单元测试
+// Part 5: FilterBoxesByRemoveSet unit tests
// ============================================
func TestFilterBoxesByRemoveSet_EmptyRemoveSet(t *testing.T) {
@@ -427,25 +427,25 @@ func TestFilterBoxesByRemoveSet_EmptyInput(t *testing.T) {
}
func TestFilterBoxesByRemoveSet_Preallocation(t *testing.T) {
- // 验证容量预分配是否合理
+ // Verify that capacity pre-allocation is reasonable
boxes := make([]pdf.TextBox, 100)
removeSet := map[int]bool{}
for i := 0; i < 30; i++ {
- removeSet[i] = true // 标记 30 个要移除
+ removeSet[i] = true // Mark 30 entries for removal
}
result := FilterBoxesByRemoveSet(boxes, removeSet)
if len(result) != 70 {
t.Errorf("expected 70 boxes, got %d", len(result))
}
- // 验证容量至少为 70
+ // Verify capacity is at least 70
if cap(result) < 70 {
t.Errorf("expected capacity >= 70, got %d", cap(result))
}
}
// ============================================
-// 第六部分:createTableBoxFromItem 单元测试
+// Part 6: createTableBoxFromItem unit tests
// ============================================
func TestCreateTableBoxFromItem_Basic(t *testing.T) {
@@ -475,7 +475,7 @@ func TestCreateTableBoxFromItem_Basic(t *testing.T) {
}
func TestCreateTableBoxFromItem_FallbackToPosition(t *testing.T) {
- // Region 字段为空时,使用 Position 的坐标
+ // When Region fields are empty, use the Position coordinates
table := &pdf.TableItem{
Positions: []pdf.Position{{
PageNumbers: []int{2},
@@ -493,7 +493,7 @@ func TestCreateTableBoxFromItem_FallbackToPosition(t *testing.T) {
}
func TestCreateTableBoxFromItem_EmptyPositions(t *testing.T) {
- // 没有 Positions 时也能工作
+ // Also works when Positions is empty
table := &pdf.TableItem{
RegionLeft: 10,
RegionRight: 100,
@@ -508,7 +508,7 @@ func TestCreateTableBoxFromItem_EmptyPositions(t *testing.T) {
}
// ============================================
-// 第七部分:handleImageOnlyPDFs 单元测试
+// Part 7: handleImageOnlyPDFs unit tests
// ============================================
func TestHandleImageOnlyPDFs_EmptyTables(t *testing.T) {
@@ -520,7 +520,7 @@ func TestHandleImageOnlyPDFs_EmptyTables(t *testing.T) {
func TestHandleImageOnlyPDFs_EmptyCells(t *testing.T) {
tables := []pdf.TableItem{
- {Cells: []pdf.TSRCell{}}, // 没有 cell 的 table
+ {Cells: []pdf.TSRCell{}}, // Table with no cells
}
result := handleImageOnlyPDFs(tables)
if len(result) != 0 {
@@ -563,7 +563,7 @@ func TestHandleImageOnlyPDFs_MultipleTables(t *testing.T) {
Cells: []pdf.TSRCell{{Text: "table1"}},
},
{
- // 没有 cell 的 table,应该被跳过
+ // Table with no cells, should be skipped
Cells: []pdf.TSRCell{},
},
{
@@ -581,7 +581,7 @@ func TestHandleImageOnlyPDFs_MultipleTables(t *testing.T) {
}
// ============================================
-// 阶段 2: buildAndSortAnchors 和 processTablesWithReplacements
+// Phase 2: buildAndSortAnchors and processTablesWithReplacements
// ============================================
func TestBuildAndSortAnchors(t *testing.T) {
@@ -608,7 +608,7 @@ func TestBuildAndSortAnchors(t *testing.T) {
}
// ============================================
-// 第八部分:ConsolidateFigures 子函数的单元测试
+// Part 8: ConsolidateFigures subfunction unit tests
// ============================================
func TestMarkDataSourceBoxesForRemoval(t *testing.T) {
@@ -617,7 +617,7 @@ func TestMarkDataSourceBoxesForRemoval(t *testing.T) {
{Text: "资料来源:abc", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0},
{Text: "图表来源 def", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0},
{Text: "正常图片内容", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0},
- {Text: "数据来源: 不应该移除", LayoutType: pdf.LayoutTypeText, PageNumber: 0}, // 不是 figure 类型
+ {Text: "数据来源: 不应该移除", LayoutType: pdf.LayoutTypeText, PageNumber: 0}, // Not a figure type
}
removeSet := markDataSourceBoxesForRemoval(boxes)
@@ -637,7 +637,7 @@ func TestGroupFigureBoxes(t *testing.T) {
{Text: "fig1-part1", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0, LayoutNo: "fig-0"},
{Text: "fig1-part2", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0, LayoutNo: "fig-0"},
{Text: "fig2", LayoutType: pdf.LayoutTypeFigure, PageNumber: 0, LayoutNo: "fig-1"},
- {Text: "fig3", LayoutType: pdf.LayoutTypeFigure, PageNumber: 1, LayoutNo: "fig-0"}, // 不同页面
+ {Text: "fig3", LayoutType: pdf.LayoutTypeFigure, PageNumber: 1, LayoutNo: "fig-0"}, // Different page
{Text: "text", LayoutType: pdf.LayoutTypeText, PageNumber: 0},
}
removeSet := map[int]bool{}
@@ -647,7 +647,7 @@ func TestGroupFigureBoxes(t *testing.T) {
t.Errorf("expected 3 groups, got %d", len(groups))
}
- // 验证组的内容
+ // Verify the group's contents
key1 := figKey{page: 0, ln: "fig-0"}
if len(groups[key1]) != 2 {
t.Errorf("expected 2 boxes in fig-0 group, got %d", len(groups[key1]))
@@ -679,7 +679,7 @@ func TestMergeFigureGroups(t *testing.T) {
mergeFigureGroups(boxes, groups, removeSet)
- // 验证合并后的结果
+ // Verify the merged result
if boxes[0].Text != "part1\npart2" {
t.Errorf("expected merged text, got %q", boxes[0].Text)
}
@@ -706,12 +706,12 @@ func TestConsolidateFigures_Integration(t *testing.T) {
result := ConsolidateFigures(boxes)
- // 验证结果
- if len(result) != 2 { // 合并后的 figure + normal text
+ // Verify result
+ if len(result) != 2 { // Merged figure + normal text
t.Errorf("expected 2 boxes, got %d", len(result))
}
- // 检查 figure 是否正确合并
+ // Check that figures are correctly merged
var figureFound bool
for _, b := range result {
if b.LayoutType == pdf.LayoutTypeFigure {
diff --git a/internal/deepdoc/parser/pdf/table_extract.go b/internal/deepdoc/parser/pdf/table_extract.go
index a65f631d24..acb4b050c1 100644
--- a/internal/deepdoc/parser/pdf/table_extract.go
+++ b/internal/deepdoc/parser/pdf/table_extract.go
@@ -5,106 +5,77 @@ import (
"image"
"log/slog"
"math"
- "sort"
tbl "ragflow/internal/deepdoc/parser/pdf/table"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
util "ragflow/internal/deepdoc/parser/pdf/util"
)
-// enrichWithDeepDoc runs DLA+TSR via docAnalyzer and returns detected tables.
-// pageImages optionally provides pre-rendered page images to avoid re-rendering.
-func (p *Parser) enrichWithDeepDoc(ctx context.Context, result *pdf.ParseResult, engine pdf.PDFEngine, boxes []pdf.TextBox, pageImages map[int]image.Image, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder) []pdf.TableItem {
- if !docAnalyzer.Health() {
- return nil
- }
- // Group boxes by page for annotation write-back.
- byPage := make(map[int][]int)
- for i, b := range boxes {
- byPage[b.PageNumber] = append(byPage[b.PageNumber], i)
- }
-
- // Collect all pages that have images (from pageImages) or boxes.
- // This matches Python's __images__ which processes every page regardless
- // of embedded chars — image-only PDFs still get DLA+TSR.
- allPages := make(map[int]bool)
- for pg := range pageImages {
- allPages[pg] = true
- }
- for pg := range byPage {
- allPages[pg] = true
- }
- pageKeys := make([]int, 0, len(allPages))
- for pg := range allPages {
- pageKeys = append(pageKeys, pg)
- }
- sort.Ints(pageKeys)
-
- var tableItems []pdf.TableItem
- for _, pg := range pageKeys {
- if err := ctx.Err(); err != nil {
- return tableItems
- }
- indices := byPage[pg]
- pageBoxes := make([]pdf.TextBox, len(indices))
- for i, idx := range indices {
- pageBoxes[i] = boxes[idx]
- }
- tables := p.extractTableBoxes(ctx, result, pageBoxes, engine, pg, pageImages, len(tableItems), docAnalyzer, tb)
- tableItems = append(tableItems, tables...)
- // Write back DLA and TSR annotations (R/C/H/SP) to the original boxes.
- for i, idx := range indices {
- if pageBoxes[i].LayoutType != "" {
- boxes[idx].LayoutType = pageBoxes[i].LayoutType
- boxes[idx].LayoutNo = pageBoxes[i].LayoutNo
- }
- tbl.CopyBoxAnnotations(&boxes[idx], &pageBoxes[i])
- }
-
- }
- return tableItems
-}
-
-func (p *Parser) extractTableBoxes(ctx context.Context, result *pdf.ParseResult, boxes []pdf.TextBox, engine pdf.PDFEngine, pageNum int, pageImages map[int]image.Image, tableBaseIdx int, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder) []pdf.TableItem {
- pageImg, ok := pageImages[pageNum]
- if !ok {
- var err error
- pageImg, err = RenderPageToImage(engine, pageNum)
- if err != nil {
- slog.Warn("render page for DeepDoc failed", "page", pageNum, "err", err)
- return nil
- }
- }
- return p.extractTableBoxesFromImage(ctx, result, boxes, pageImg, pageNum, tableBaseIdx, docAnalyzer, tb)
-}
-
-func (p *Parser) extractTableBoxesFromImage(ctx context.Context, result *pdf.ParseResult, boxes []pdf.TextBox, pageImg image.Image, pageNum int, tableBaseIdx int, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder) []pdf.TableItem {
- regions, err := docAnalyzer.DLA(ctx, pageImg)
+// enrichOnePageWithDeepDoc runs DLA+TSR for a single page and returns
+// worker-local artifacts. Boxes may be empty (image-only pages); the
+// function still runs DLA/TSR if pageImg is available so a page can
+// contribute tables and debug payloads even when no embedded text exists.
+//
+// Parameters:
+// - pageImg: the page bitmap DLA/TSR run against (rendered at the DLA
+// DPI); also the source image for table cropping.
+// - pageBoxes: line/word-level []pdf.TextBox (NOT per-rune) from
+// processPageBoxes, in PDF-point space. DLA/TSR annotations are
+// written back onto a shallow copy of this slice (see Returns).
+// - pg: page number (0-based), stamped onto tables and debug payloads.
+// - renderErr: non-nil short-circuits to (pageBoxes, nil, nil, nil).
+// - docAnalyzer: the DLA/OCR/Tensor backend used for region inference
+// and TSR.
+// - tb: table builder used to group TSR cells into a grid.
+// - scale: the points-to-pixels multiplier of pageImg. DLA returns
+// region coordinates in image-pixel space while box coordinates are in
+// PDF-point space, so scale bridges the two when matching tables and
+// writing annotations. Typically pdf.DlaScale (base render) or
+// retryDPI/72 (retry-zoom render) so annotation stays consistent with
+// the image that produced it.
+//
+// Returns:
+// - annotated: page boxes after DLA/TSR annotation write-back (LayoutType,
+// LayoutNo, R/C/H/SP fields) — same length as input pageBoxes.
+// - tables: table candidates detected on this page.
+// - dlaRegions: page-local DLA regions payload.
+func (p *Parser) enrichOnePageWithDeepDoc(ctx context.Context,
+ pageImg image.Image, pageBoxes []pdf.TextBox, pg int, renderErr error,
+ docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder, scale float64,
+) (annotated []pdf.TextBox, tables []pdf.TableItem,
+ dlaRegions []pdf.DLAPageRegions,
+) {
+ if docAnalyzer == nil || !docAnalyzer.Health() || renderErr != nil || pageImg == nil {
+ return pageBoxes, nil, nil
+ }
+ regions, err := p.inferDLA(ctx, docAnalyzer, pageImg)
if err != nil {
- slog.Warn("DLA failed", "page", pageNum, "err", err)
- return nil
- }
- // Collect DLA debug intermediates.
- if result != nil {
- result.DLADebug = append(result.DLADebug, pdf.DLAPageRegions{Page: pageNum, Regions: regions})
+ slog.Warn("DLA failed", "page", pg, "err", err)
+ return pageBoxes, nil, nil
}
- // Annotate boxes with DLA layout types (title, text, figure, table, ...).
- scale := pdf.DlaScale
- boxes = tbl.AnnotateBoxLayouts(boxes, regions, scale, float64(pageImg.Bounds().Dy()))
+ dlaRegions = []pdf.DLAPageRegions{{Page: pg, Regions: regions}}
+
+ // Copy page boxes so DLA annotation can append synthetic figure boxes
+ // without mutating the caller's slice. The annotated copy is what the
+ // caller should use downstream for layout/text-merge.
+ annotated = append([]pdf.TextBox(nil), pageBoxes...)
+ annotated = tbl.AnnotateBoxLayouts(annotated, regions, scale, float64(pageImg.Bounds().Dy()))
- tableMatches := tbl.MatchTableRegions(boxes, regions, scale)
+ tableMatches := tbl.MatchTableRegions(annotated, regions, scale)
var items []pdf.TableItem
for _, tm := range tableMatches {
- item := p.processOneTable(ctx, result, boxes, pageImg, pageNum, docAnalyzer, tb, tm, scale, tableBaseIdx+len(items))
+ item := p.processOneTable(ctx, pageImg, annotated, pg, docAnalyzer, tb, tm, scale)
if item.ImageB64 != "" || len(item.Cells) > 0 || len(item.Positions) > 0 {
items = append(items, item)
}
}
- return items
+ return annotated, items, dlaRegions
}
// processOneTable handles DLA+TSR+OCR for a single table region match.
-func (p *Parser) processOneTable(ctx context.Context, result *pdf.ParseResult, boxes []pdf.TextBox, pageImg image.Image, pageNum int, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder, tm tbl.TableMatch, scale float64, tableIdx int) pdf.TableItem {
+// It mutates `boxes` in place to write back R/C/H/SP annotations. The
+// function is page-local and never touches the document-wide ParseResult.
+func (p *Parser) processOneTable(ctx context.Context, pageImg image.Image, boxes []pdf.TextBox, pageNum int, docAnalyzer pdf.DocAnalyzer, tb pdf.TableBuilder, tm tbl.TableMatch, scale float64) pdf.TableItem {
cropped, cropErr := util.CropImageRegion(pageImg, tm.Region)
if cropErr != nil {
return pdf.TableItem{}
@@ -122,18 +93,10 @@ func (p *Parser) processOneTable(ctx context.Context, result *pdf.ParseResult, b
if encErr != nil {
slog.Warn("table PNG encode failed", "page", pageNum, "err", encErr)
}
- cells, tsrErr := tb.DetectCells(ctx, tsrImg)
+ cells, tsrErr := p.inferTSR(ctx, tb, tsrImg)
if tsrErr != nil {
slog.Warn("TSR failed", "page", pageNum, "err", tsrErr)
}
- if tsrErr == nil && result != nil {
- for _, c := range cells {
- result.TSRDebug = append(result.TSRDebug, pdf.TSRRawCell{
- TableIndex: tableIdx, Page: pageNum,
- Label: c.Label, X0: c.X0, Y0: c.Y0, X1: c.X1, Y1: c.Y1, Text: c.Text,
- })
- }
- }
w := tm.Region.X1 - tm.Region.X0
h := tm.Region.Y1 - tm.Region.Y0
cropOffX := math.Max(0, tm.Region.X0-w*0.03)
@@ -142,7 +105,7 @@ func (p *Parser) processOneTable(ctx context.Context, result *pdf.ParseResult, b
if tsrErr == nil && len(cells) > 0 {
if bestAngle != 0 {
if !p.Config.SkipOCR {
- ocrTableCells(ctx, cells, tsrImg, docAnalyzer)
+ p.ocrTableCells(ctx, cells, tsrImg, docAnalyzer)
}
for i := range cells {
cells[i].X0, cells[i].Y0 = util.MapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
@@ -189,7 +152,7 @@ func (p *Parser) processOneTable(ctx context.Context, result *pdf.ParseResult, b
}
}
if bestAngle == 0 && !p.Config.SkipOCR {
- ocrTableCells(ctx, flat, tsrImg, docAnalyzer)
+ p.ocrTableCells(ctx, flat, tsrImg, docAnalyzer)
idx = 0
for ri := range grid {
for ci := range grid[ri] {
diff --git a/internal/deepdoc/parser/pdf/table_rotate_integration_test.go b/internal/deepdoc/parser/pdf/table_rotate_integration_test.go
index 551600e47c..6aa11fc603 100644
--- a/internal/deepdoc/parser/pdf/table_rotate_integration_test.go
+++ b/internal/deepdoc/parser/pdf/table_rotate_integration_test.go
@@ -57,7 +57,6 @@ func TestTableRotation_Integration(t *testing.T) {
t.Logf("PDF: %d pages", pageCount)
cfg := pdf.DefaultParserConfig()
- cfg.ToPage = pageCount - 1
autoRotate := true
cfg.AutoRotateTables = &autoRotate
_ = NewParser(cfg) // verify construction does not panic
diff --git a/internal/deepdoc/parser/pdf/table_section_test.go b/internal/deepdoc/parser/pdf/table_section_test.go
index 3ca41a41d3..fcd77d671d 100644
--- a/internal/deepdoc/parser/pdf/table_section_test.go
+++ b/internal/deepdoc/parser/pdf/table_section_test.go
@@ -80,10 +80,10 @@ func TestTableSection_TextFromTSR(t *testing.T) {
// not from pre-filled TSR cell text (EE feature).
}
-// TestEnrichWithDeepDoc_ImageOnlyPage verifies that enrichWithDeepDoc
+// TestEnrichOnePageWithDeepDoc_ImageOnlyPage verifies that enrichOnePageWithDeepDoc
// runs DLA on pages that have images but zero embedded chars (boxes).
// Regression test for test.pdf (Go 0 tables, Py 1 table).
-func TestEnrichWithDeepDoc_ImageOnlyPage(t *testing.T) {
+func TestEnrichOnePageWithDeepDoc_ImageOnlyPage(t *testing.T) {
mock := &MockDocAnalyzer{
Healthy: true,
DLARegions: []pdf.DLARegion{
@@ -98,14 +98,13 @@ func TestEnrichWithDeepDoc_ImageOnlyPage(t *testing.T) {
// 0 text boxes, but page 0 has a rendered image.
boxes := []pdf.TextBox{}
dummyImg := image.NewRGBA(image.Rect(0, 0, 900, 600))
- pageImages := map[int]image.Image{0: dummyImg}
- tables := p.enrichWithDeepDoc(context.Background(), nil, nil, boxes, pageImages, mock, NewTableBuilderFor(mock))
+ _, tables, _ := p.enrichOnePageWithDeepDoc(context.Background(), dummyImg, boxes, 0, nil, mock, NewTableBuilderFor(mock), pdf.DlaScale)
if len(tables) == 0 {
- t.Fatal("enrichWithDeepDoc: expected at least 1 table from DLA on page with image but no boxes, got 0")
+ t.Fatal("enrichOnePageWithDeepDoc: expected at least 1 table from DLA on page with image but no boxes, got 0")
}
if len(tables[0].Cells) == 0 {
- t.Fatal("enrichWithDeepDoc: expected TSR cells in table")
+ t.Fatal("enrichOnePageWithDeepDoc: expected TSR cells in table")
}
}
@@ -312,57 +311,15 @@ func TestNilChars_Handled(t *testing.T) {
}
}
-func TestMatchTableImage_ByPositions(t *testing.T) {
- tableByRegion := map[string]string{
- "0_50.0_500.0_100.0_300.0": "img_base64_positions",
- }
+func TestTableSection_StillParsesWithPositions(t *testing.T) {
+ // matchTableImage was removed along with Parse.fillSectionImages; the
+ // Python pipeline crops tables at tokenize time, not parse time. This
+ // guard keeps the table section shape exercised after that removal.
sec := &pdf.Section{
LayoutType: pdf.LayoutTypeTable,
Positions: []pdf.Position{{PageNumbers: []int{0}, Left: 50.0, Right: 500.0, Top: 100.0, Bottom: 300.0}},
}
- img, ok := matchTableImage(sec, tableByRegion)
- if !ok {
- t.Fatal("expected match by Positions")
- }
- if img != "img_base64_positions" {
- t.Errorf("got %q, want img_base64_positions", img)
- }
-}
-
-func TestMatchTableImage_FallbackToRegion(t *testing.T) {
- tableByRegion := map[string]string{
- "0_80.0_520.0_200.0_400.0": "img_base64_region",
- }
- sec := &pdf.Section{
- LayoutType: pdf.LayoutTypeTable,
- Positions: nil,
- TableItem: &pdf.TableItem{RegionLeft: 80.0, RegionRight: 520.0, RegionTop: 200.0, RegionBottom: 400.0},
- }
- img, ok := matchTableImage(sec, tableByRegion)
- if !ok {
- t.Fatal("expected match by Region fallback")
- }
- if img != "img_base64_region" {
- t.Errorf("got %q, want img_base64_region", img)
- }
-}
-
-func TestMatchTableImage_NoMatch(t *testing.T) {
- tableByRegion := map[string]string{"0_10.0_20.0_30.0_40.0": "no_chance"}
- sec := &pdf.Section{
- LayoutType: pdf.LayoutTypeTable,
- Positions: []pdf.Position{{PageNumbers: []int{0}, Left: 100, Right: 200, Top: 300, Bottom: 400}},
- }
- _, ok := matchTableImage(sec, tableByRegion)
- if ok {
- t.Error("expected no match")
- }
-}
-
-func TestMatchTableImage_EmptySection(t *testing.T) {
- sec := &pdf.Section{LayoutType: pdf.LayoutTypeTable}
- _, ok := matchTableImage(sec, map[string]string{"x": "y"})
- if ok {
- t.Error("expected no match for empty section")
+ if len(sec.Positions) != 1 {
+ t.Fatalf("expected 1 position, got %d", len(sec.Positions))
}
}
diff --git a/internal/deepdoc/parser/pdf/type/types.go b/internal/deepdoc/parser/pdf/type/types.go
index d5fa0cdfa3..ae0cd7447e 100644
--- a/internal/deepdoc/parser/pdf/type/types.go
+++ b/internal/deepdoc/parser/pdf/type/types.go
@@ -10,7 +10,6 @@ import doctype "ragflow/internal/deepdoc/parser/type"
type PipelineMetrics = doctype.PipelineMetrics
type ParseResult = doctype.ParseResult
type DLAPageRegions = doctype.DLAPageRegions
-type TSRRawCell = doctype.TSRRawCell
type TextChar = doctype.TextChar
type TextBox = doctype.TextBox
type Position = doctype.Position
diff --git a/internal/deepdoc/parser/pdf/util/crop.go b/internal/deepdoc/parser/pdf/util/crop.go
index 8c282b65e0..e5ff629af6 100644
--- a/internal/deepdoc/parser/pdf/util/crop.go
+++ b/internal/deepdoc/parser/pdf/util/crop.go
@@ -8,6 +8,7 @@ import (
"log/slog"
"math"
pdf "ragflow/internal/deepdoc/parser/pdf/type"
+ "strings"
)
// CropSectionImage crops region(s) from rendered page images based on a
@@ -239,75 +240,197 @@ func CropSectionImage(posTag string, decodedImages map[int]image.Image, zoom flo
return base64.StdEncoding.EncodeToString(data)
}
-// cropSectionByDLA crops a section using the best-overlapping DLA region.
-// It finds a DLA "figure" or "equation" region whose overlap with the section's
-// bounding box is maximal, then crops from the page image at 216 DPI using the
-// DLA region boundary (plus 3% margin via cropImageRegion).
+// cropSectionByDLA crops a section using the best-overlapping DLA region,
+// mimicking Python's cropout() in deepdoc/parser/pdf_parser.py (around line
+// 1307). Unlike the original Go version (which only cropped the first page),
+// it now walks every position and every page the section spans, crops each
+// page's best DLA region (or the section bbox as a fallback), and
+// vertically concatenates the per-page crops — exactly like cropout's
+// multi-page branch (Image.new("RGB", (...), (245,245,245)) + paste loop).
//
-// Returns "" (empty string) if no matching DLA region or page image is found.
-// The caller should fall through to cropSectionImage as a fallback.
-//
-// Python equivalent: cropout() in pdf_parser.py:1144-1148
+// Python equivalent (single-page branch):
//
// louts = [layout for layout in self.page_layout[pn] if layout["type"] == ltype]
// ii = Recognizer.find_overlapped(b, louts, naive=True)
-// if ii is not None: b = louts[ii]
-func CropSectionByDLA(sec pdf.Section, dlaDebug []pdf.DLAPageRegions, pageImages map[int]image.Image) string {
- if len(sec.Positions) == 0 || len(sec.Positions[0].PageNumbers) == 0 {
+// if ii is not None:
+// b = louts[ii]
+//
+// find_overlapped ranks candidates by overlapped_area(layout, section,
+// ratio=True), i.e. intersection_area / Area(layout). We replicate that exact
+// metric with OverlapRatioA(region, bx) — NOT the symmetric OverlapRatioMax —
+// so the chosen region matches Python even when the section box is larger than
+// the candidate region.
+//
+// Fallback semantics match cropout too: when a page has no figure/equation DLA
+// region (find_overlapped returns None), cropout crops the section's own bbox
+// on that page; we do the same via cropDLAPage. We return "" (empty string)
+// only when the section has no positions/pages at all or a referenced page
+// image is missing — in which case the caller should fall through to
+// CropSectionImage for the whole section.
+//
+// Note: cropout does NOT add the 120px context bands that CropSectionImage
+// (Python crop()) inserts; matching cropout, this function returns clean
+// per-page crops with no edge bands.
+func CropSectionByDLA(sec pdf.Section, dlaRegions []pdf.DLAPageRegions, pageImages map[int]image.Image) string {
+ if len(sec.Positions) == 0 {
return ""
}
- pg := sec.Positions[0].PageNumbers[0]
- pos := sec.Positions[0]
+ const gap = 6 // matches cropout's vertical paste gap.
- // Find DLA regions for this page.
- var regions []pdf.DLARegion
- for _, dp := range dlaDebug {
- if dp.Page == pg {
- regions = dp.Regions
- break
+ // Convert section bbox from PDF points (72 DPI) to DLA pixel space (216 DPI).
+ scale := pdf.DlaDPI / 72.0 // 3.0
+
+ var crops []image.Image
+ for _, pos := range sec.Positions {
+ if len(pos.PageNumbers) == 0 {
+ continue
+ }
+ // Spanning height in pixels for this position across its pages,
+ // mirroring CropSectionImage's accumBottom computation.
+ pn0 := pos.PageNumbers[0]
+ accumBottom := pos.Bottom * scale
+ for _, pn := range pos.PageNumbers[1:] {
+ if pn == pn0 {
+ continue
+ }
+ if img, ok := pageImages[pn]; ok {
+ accumBottom += float64(img.Bounds().Dy())
+ }
+ }
+
+ img0, ok := pageImages[pn0]
+ if !ok {
+ // First page of this position is missing → skip the whole
+ // position (its page order is anchored on pn0). Python's
+ // cropout likewise skips out-of-range pages.
+ continue
+ }
+ // First page: crop [Top, min(Bottom, page height)] (clamped).
+ firstBottom := math.Min(accumBottom, float64(img0.Bounds().Dy()))
+ crops = append(crops, cropDLAPage(img0, dlaRegions, pn0,
+ pos.Left*scale, pos.Top*scale, pos.Right*scale, firstBottom))
+
+ // Subsequent pages: each contributes [0, remaining height].
+ remaining := accumBottom - float64(img0.Bounds().Dy())
+ for _, pn := range pos.PageNumbers[1:] {
+ if pn == pn0 {
+ continue
+ }
+ imgN, ok := pageImages[pn]
+ if !ok {
+ // Missing subsequent page → skip just this page; the
+ // caller's CropSectionImage fallback would also drop it.
+ continue
+ }
+ pageH := float64(imgN.Bounds().Dy())
+ h := math.Min(remaining, pageH)
+ crops = append(crops, cropDLAPage(imgN, dlaRegions, pn,
+ pos.Left*scale, 0, pos.Right*scale, h))
+ remaining -= pageH
}
}
- if len(regions) == 0 {
+ if len(crops) == 0 {
return ""
}
+ return stitchVerticalImages(crops, gap)
+}
- // Convert section bbox from PDF points (72 DPI) to DLA pixel space (216 DPI).
- scale := pdf.DlaDPI / 72.0 // 3.0
- bx := Rect{
- X0: pos.Left * scale,
- Y0: pos.Top * scale,
- X1: pos.Right * scale,
- Y1: pos.Bottom * scale,
+// cropDLAPage crops a single page for a section position. It prefers the
+// best-overlapping figure/equation DLA region (cropout's find_overlapped
+// branch); if none overlaps, it falls back to the section bbox on that page
+// (cropout's ii-is-None branch). left/top/right/bottom are already in DLA
+// pixel space (216 DPI).
+func cropDLAPage(img image.Image, dlaRegions []pdf.DLAPageRegions,
+ pn int, lpx, tpx, rpx, bpx float64,
+) image.Image {
+ // Find DLA regions for this page.
+ var regions []pdf.DLARegion
+ for _, dp := range dlaRegions {
+ if dp.Page == pn {
+ regions = dp.Regions
+ break
+ }
}
- // Find best-overlapping figure or equation DLA region.
+ bx := Rect{X0: lpx, Y0: tpx, X1: rpx, Y1: bpx}
bestIdx := -1
bestOverlap := 0.0
for i, r := range regions {
if r.Label != pdf.LayoutTypeFigure && r.Label != pdf.LayoutTypeEquation {
continue
}
- overlap := RectOverlap(bx, Rect{r.X0, r.Y0, r.X1, r.Y1})
+ // Match Python's find_overlapped metric: intersection_area / Area(region).
+ overlap := OverlapRatioA(Rect{r.X0, r.Y0, r.X1, r.Y1}, bx)
if overlap > bestOverlap {
bestOverlap = overlap
bestIdx = i
}
}
- if bestIdx < 0 {
- slog.Warn("cropSectionByDLA: no matching layout region found", "page", pg)
- return ""
+ if bestIdx >= 0 {
+ if cropped, err := CropImageRegion(img, regions[bestIdx]); err == nil {
+ return cropped
+ } else {
+ slog.Warn("cropSectionByDLA: cropImageRegion failed, falling back to bbox",
+ "page", pn, "err", err)
+ }
}
+ // Fallback: crop the section bbox on this page (FastCrop clamps to bounds).
+ return FastCrop(img, int(lpx), int(tpx), int(rpx), int(bpx))
+}
- img, ok := pageImages[pg]
- if !ok {
+// stitchVerticalImages concatenates crops top-to-bottom on a gray (245)
+// background with the given pixel gap, matching cropout's
+// Image.new("RGB", (...), (245, 245, 245)) + paste loop. Returns a base64 PNG,
+// or "" if encoding fails.
+func stitchVerticalImages(imgs []image.Image, gap int) string {
+ if len(imgs) == 0 {
return ""
}
- cropped, err := CropImageRegion(img, regions[bestIdx])
- if err != nil {
- slog.Warn("cropSectionByDLA: cropImageRegion failed", "page", pg, "err", err)
- return ""
+ totalH := 0
+ maxW := 0
+ for _, im := range imgs {
+ b := im.Bounds()
+ totalH += b.Dy() + gap
+ if w := b.Dx(); w > maxW {
+ maxW = w
+ }
+ }
+ totalH -= gap
+ stitched := image.NewRGBA(image.Rect(0, 0, maxW, totalH))
+
+ // Fill gray 245 background (BGRA bytes).
+ for y := 0; y < totalH; y++ {
+ row := stitched.Pix[stitched.PixOffset(0, y):stitched.PixOffset(maxW, y)]
+ for i := 0; i < len(row); i += 4 {
+ row[i] = 245
+ row[i+1] = 245
+ row[i+2] = 245
+ row[i+3] = 255
+ }
+ }
+
+ curY := 0
+ for _, im := range imgs {
+ b := im.Bounds()
+ srcW, srcH := b.Dx(), b.Dy()
+ if rgba, ok := im.(*image.RGBA); ok {
+ for ry := 0; ry < srcH; ry++ {
+ srcStart := rgba.PixOffset(b.Min.X, b.Min.Y+ry)
+ srcRow := rgba.Pix[srcStart : srcStart+srcW*4]
+ dstStart := stitched.PixOffset(0, curY+ry)
+ copy(stitched.Pix[dstStart:], srcRow)
+ }
+ } else {
+ for y := 0; y < srcH; y++ {
+ for x := 0; x < srcW; x++ {
+ stitched.Set(x, curY+y, im.At(x+b.Min.X, y+b.Min.Y))
+ }
+ }
+ }
+ curY += srcH + gap
}
- data, err := EncodePNG(cropped)
+
+ data, err := EncodePNG(stitched)
if err != nil {
slog.Warn("cropSectionByDLA: PNG encode failed", "err", err)
return ""
@@ -435,3 +558,97 @@ func CropImageRegion(img image.Image, r pdf.DLARegion) (image.Image, error) {
cropped := FastCrop(img, x0, y0, x1, y1)
return cropped, nil
}
+
+// CropSectionPositions is the tag-free variant of CropSectionImage. It
+// crops directly from a typed []pdf.Position — for example decoded from a
+// chunk's _pdf_positions matrix — instead of re-parsing a position tag
+// string. The page-image map is keyed by zero-indexed page number.
+//
+// Python: pdf_parser.py:1802 RAGFlowPdfParser.crop()
+func CropSectionPositions(positions []pdf.Position, decodedImages map[int]image.Image, zoom float64) string {
+ if len(positions) == 0 {
+ return ""
+ }
+ var tag strings.Builder
+ for _, pos := range positions {
+ if len(pos.PageNumbers) == 0 {
+ continue
+ }
+ if len(pos.PageNumbers) == 1 {
+ tag.WriteString(FormatPositionTag(pos.PageNumbers[0], pos.Left, pos.Right, pos.Top, pos.Bottom))
+ } else {
+ from, to := pos.PageNumbers[0], pos.PageNumbers[len(pos.PageNumbers)-1]
+ tag.WriteString(FormatPositionTagRange(from, to, pos.Left, pos.Right, pos.Top, pos.Bottom))
+ }
+ }
+ if tag.Len() == 0 {
+ return ""
+ }
+ return CropSectionImage(tag.String(), decodedImages, zoom)
+}
+
+// PositionsFromMatrix converts the _pdf_positions / positions matrix form
+// (as produced by layout.SectionsToJSON and normalized to 1-based page
+// numbers by normalizePDFPageNumber) back into typed []pdf.Position. The
+// engine renders 0-based pages, so the leading 1-based page numbers are
+// shifted to 0-based — matching Python's crop(), which indexes
+// self.page_images[page_number-1].
+func PositionsFromMatrix(m [][]any) []pdf.Position {
+ var out []pdf.Position
+ for _, row := range m {
+ if len(row) < 5 {
+ continue
+ }
+ pageNums := matrixPageNumbers(row[0])
+ left, lok := matrixFloat(row[1])
+ right, rok := matrixFloat(row[2])
+ top, tok := matrixFloat(row[3])
+ bottom, bok := matrixFloat(row[4])
+ if !lok || !rok || !tok || !bok || len(pageNums) == 0 {
+ continue
+ }
+ out = append(out, pdf.Position{
+ PageNumbers: pageNums,
+ Left: left,
+ Right: right,
+ Top: top,
+ Bottom: bottom,
+ })
+ }
+ return out
+}
+
+// matrixPageNumbers decodes a page-number cell (scalar or list) from the
+// JSON matrix and converts it from the 1-based serialization to the
+// engine's 0-based page index.
+func matrixPageNumbers(raw any) []int {
+ switch v := raw.(type) {
+ case []any:
+ var out []int
+ for _, e := range v {
+ if n, ok := matrixFloat(e); ok {
+ out = append(out, int(n)-1)
+ }
+ }
+ return out
+ case float64:
+ return []int{int(v) - 1}
+ case int:
+ return []int{v - 1}
+ case int64:
+ return []int{int(v) - 1}
+ }
+ return nil
+}
+
+func matrixFloat(raw any) (float64, bool) {
+ switch v := raw.(type) {
+ case float64:
+ return v, true
+ case int:
+ return float64(v), true
+ case int64:
+ return float64(v), true
+ }
+ return 0, false
+}
diff --git a/internal/deepdoc/parser/pdf/util/crop_matrix_test.go b/internal/deepdoc/parser/pdf/util/crop_matrix_test.go
new file mode 100644
index 0000000000..1e62e9d88c
--- /dev/null
+++ b/internal/deepdoc/parser/pdf/util/crop_matrix_test.go
@@ -0,0 +1,58 @@
+package util
+
+import (
+ "testing"
+)
+
+// TestPositionsFromMatrix_ConvertsToZeroBased verifies the JSON matrix
+// (1-based page numbers, per normalizePDFPageNumber) is decoded to the
+// engine's 0-based page indices. This matches Python's crop(), which
+// indexes page_images[page_number-1].
+func TestPositionsFromMatrix_ConvertsToZeroBased(t *testing.T) {
+ m := [][]any{
+ {1.0, 10.0, 100.0, 10.0, 100.0},
+ {2.0, 0.0, 50.0, 0.0, 50.0},
+ }
+ got := PositionsFromMatrix(m)
+ if len(got) != 2 {
+ t.Fatalf("len = %d, want 2", len(got))
+ }
+ if got[0].PageNumbers[0] != 0 {
+ t.Errorf("got[0].PageNumbers[0] = %d, want 0 (1-based -> 0-based)", got[0].PageNumbers[0])
+ }
+ if got[1].PageNumbers[0] != 1 {
+ t.Errorf("got[1].PageNumbers[0] = %d, want 1", got[1].PageNumbers[0])
+ }
+}
+
+// TestPositionsFromMatrix_ListPageNumbers exercises the multi-page list
+// form (cross-page sections), confirming each entry is shifted -1.
+func TestPositionsFromMatrix_ListPageNumbers(t *testing.T) {
+ m := [][]any{
+ {[]any{1.0, 2.0}, 10.0, 100.0, 10.0, 100.0},
+ }
+ got := PositionsFromMatrix(m)
+ if len(got) != 1 {
+ t.Fatalf("len = %d, want 1", len(got))
+ }
+ if len(got[0].PageNumbers) != 2 || got[0].PageNumbers[0] != 0 || got[0].PageNumbers[1] != 1 {
+ t.Errorf("PageNumbers = %v, want [0 1]", got[0].PageNumbers)
+ }
+}
+
+// TestPositionsFromMatrix_SkipsMalformedRows confirms rows shorter than 5
+// fields and non-numeric pages are dropped rather than producing garbage.
+func TestPositionsFromMatrix_SkipsMalformedRows(t *testing.T) {
+ m := [][]any{
+ {1.0, 10.0, 100.0, 10.0}, // too short
+ {"x", 10.0, 100.0, 10.0, 100.0}, // non-numeric page
+ {3.0, 10.0, 100.0, 10.0, 100.0}, // valid -> 0-based 2
+ }
+ got := PositionsFromMatrix(m)
+ if len(got) != 1 {
+ t.Fatalf("len = %d, want 1 (malformed rows skipped)", len(got))
+ }
+ if got[0].PageNumbers[0] != 2 {
+ t.Errorf("got[0].PageNumbers[0] = %d, want 2", got[0].PageNumbers[0])
+ }
+}
diff --git a/internal/deepdoc/parser/pdf/util/crop_test.go b/internal/deepdoc/parser/pdf/util/crop_test.go
index 4da35e7f3a..6e1b0d3e24 100644
--- a/internal/deepdoc/parser/pdf/util/crop_test.go
+++ b/internal/deepdoc/parser/pdf/util/crop_test.go
@@ -313,7 +313,7 @@ func TestCropSectionByDLA(t *testing.T) {
// DLA regions in pixel space (216 DPI).
// Figure region at (30, 60, 270, 420) — a large area covering most of the image.
// Text region at (10, 400, 100, 440) — a small text box near the bottom.
- dlaDebug := []pdf.DLAPageRegions{{
+ dlaRegions := []pdf.DLAPageRegions{{
Page: 0,
Regions: []pdf.DLARegion{
{X0: 10, Y0: 400, X1: 100, Y1: 440, Label: "text"},
@@ -334,7 +334,7 @@ func TestCropSectionByDLA(t *testing.T) {
LayoutType: "figure",
}
- result := CropSectionByDLA(sec, dlaDebug, pageImages)
+ result := CropSectionByDLA(sec, dlaRegions, pageImages)
if result == "" {
t.Fatal("expected non-empty result for figure overlapping DLA region")
}
@@ -352,12 +352,14 @@ func TestCropSectionByDLA(t *testing.T) {
}
}
-// TestCropSectionByDLA_NoMatch returns empty when no DLA region overlaps.
+// TestCropSectionByDLA_NoMatch falls back to the section bbox crop (matching
+// Python cropout's ii-is-None branch) when no figure/equation DLA region
+// overlaps — it does NOT return "".
func TestCropSectionByDLA_NoMatch(t *testing.T) {
pageImages := map[int]image.Image{
0: makeTestPageImage(300, 450, color.RGBA{255, 0, 0, 255}),
}
- dlaDebug := []pdf.DLAPageRegions{{
+ dlaRegions := []pdf.DLAPageRegions{{
Page: 0,
Regions: []pdf.DLARegion{
{X0: 10, Y0: 10, X1: 100, Y1: 50, Label: "title"},
@@ -365,6 +367,7 @@ func TestCropSectionByDLA_NoMatch(t *testing.T) {
},
}}
// pdf.Section whose bbox doesn't overlap any figure/equation DLA region.
+ // PDF points → pixels at scale 3: (20,20,50,50) → (60,60,150,150) ≈ 90x90.
sec := pdf.Section{
Positions: []pdf.Position{{
PageNumbers: []int{0},
@@ -372,9 +375,50 @@ func TestCropSectionByDLA_NoMatch(t *testing.T) {
}},
LayoutType: "figure",
}
- result := CropSectionByDLA(sec, dlaDebug, pageImages)
- if result != "" {
- t.Errorf("expected empty result when no figure/equation DLA region found, got length %d", len(result))
+ result := CropSectionByDLA(sec, dlaRegions, pageImages)
+ if result == "" {
+ t.Fatal("expected bbox fallback crop when no figure/equation DLA region found")
+ }
+ decoded, _ := base64.StdEncoding.DecodeString(result)
+ img := decodePNG(t, decoded)
+ w, h := img.Bounds().Dx(), img.Bounds().Dy()
+ t.Logf("cropSectionByDLA fallback result: %dx%d", w, h)
+ if w < 80 || h < 80 {
+ t.Errorf("unexpected fallback crop size %dx%d, want ~90x90 (bbox based)", w, h)
+ }
+}
+
+// TestCropSectionByDLA_MultiPage verifies that a section spanning two pages is
+// cropped per page and vertically concatenated (matching cropout's multi-page
+// branch), rather than returning only the first page.
+func TestCropSectionByDLA_MultiPage(t *testing.T) {
+ pageImages := map[int]image.Image{
+ 0: makeTestPageImage(300, 450, color.RGBA{255, 0, 0, 255}),
+ 1: makeTestPageImage(300, 450, color.RGBA{0, 255, 0, 255}),
+ }
+ dlaRegions := []pdf.DLAPageRegions{
+ {Page: 0, Regions: []pdf.DLARegion{{X0: 30, Y0: 60, X1: 270, Y1: 420, Label: "figure"}}},
+ {Page: 1, Regions: []pdf.DLARegion{{X0: 30, Y0: 60, X1: 270, Y1: 420, Label: "figure"}}},
+ }
+ // Section bbox covers both pages (PDF points, 72 DPI).
+ sec := pdf.Section{
+ Positions: []pdf.Position{{
+ PageNumbers: []int{0, 1},
+ Left: 20, Right: 50, Top: 100, Bottom: 200,
+ }},
+ LayoutType: "figure",
+ }
+ result := CropSectionByDLA(sec, dlaRegions, pageImages)
+ if result == "" {
+ t.Fatal("expected non-empty multi-page crop")
+ }
+ decoded, _ := base64.StdEncoding.DecodeString(result)
+ img := decodePNG(t, decoded)
+ h := img.Bounds().Dy()
+ t.Logf("cropSectionByDLA multi-page result: %dx%d", img.Bounds().Dx(), h)
+ // Concatenation of two ~360px tall crops (+ 6px gap) must exceed one page.
+ if h <= 450 {
+ t.Errorf("multi-page crop height %d should exceed a single page (450)", h)
}
}
diff --git a/internal/deepdoc/parser/pdf/util/eng_detect.go b/internal/deepdoc/parser/pdf/util/eng_detect.go
index 953502aa0e..c72ebe637f 100644
--- a/internal/deepdoc/parser/pdf/util/eng_detect.go
+++ b/internal/deepdoc/parser/pdf/util/eng_detect.go
@@ -66,45 +66,48 @@ func FullTextFromChars(pageChars map[int][]pdf.TextChar) string {
return sb.String()
}
+// DetectEnglishPage reports whether one page contains a run of 30+
+// consecutive ASCII-printable characters in a random sample of up to 100
+// extracted character texts.
+func DetectEnglishPage(chars []pdf.TextChar, sample pdf.SampleFunc) bool {
+ if len(chars) == 0 {
+ return false
+ }
+ if sample == nil {
+ sample = DefaultSampleChars
+ }
+
+ sampleText := sample(chars, 100)
+ run := 0
+ for _, r := range sampleText {
+ if IsASCIIPrintable(r) {
+ run++
+ if run >= 30 {
+ return true
+ }
+ } else {
+ run = 0
+ }
+ }
+ return false
+}
+
// DetectEnglish detects whether a PDF is primarily English by per-page
// majority vote, matching Python's is_english logic in __images__
// (pdf_parser.py:1519-1526).
//
-// Each page: sample up to 100 character texts via sampler, join into one
-// string, check if there is a run of 30+ consecutive ASCII characters
-// (letters, digits, spaces, punctuation). Pages with such a run vote
-// "English". Returns true when a strict majority of pages vote yes.
-//
-// totalPages is the denominator (len(self.page_images) in Python), including
-// image-only pages that have zero chars. This matches Python's behavior
-// where empty pages dilute the majority.
+// Each page votes via DetectEnglishPage. Returns true when a strict majority
+// of pages vote yes. totalPages remains the denominator so image-only pages
+// still dilute the majority, matching Python behavior.
func DetectEnglish(pageChars map[int][]pdf.TextChar, totalPages int, sample pdf.SampleFunc) bool {
if totalPages == 0 || len(pageChars) == 0 {
return false
}
- if sample == nil {
- sample = DefaultSampleChars
- }
pagesWithSeq := 0
-
for _, chars := range pageChars {
- if len(chars) == 0 {
- continue
- }
- sampleText := sample(chars, 100)
- run := 0
- for _, r := range sampleText {
- if IsASCIIPrintable(r) {
- run++
- if run >= 30 {
- pagesWithSeq++
- break
- }
- } else {
- run = 0
- }
+ if DetectEnglishPage(chars, sample) {
+ pagesWithSeq++
}
}
-
return pagesWithSeq > totalPages/2
}
diff --git a/internal/deepdoc/parser/type/types.go b/internal/deepdoc/parser/type/types.go
index 946c722924..13e0428eac 100644
--- a/internal/deepdoc/parser/type/types.go
+++ b/internal/deepdoc/parser/type/types.go
@@ -23,14 +23,29 @@ type PipelineMetrics struct {
// ParseResult encapsulates all outputs from a single Parse() call.
type ParseResult struct {
- Sections []Section
- Tables []TableItem
- PageImages map[int]image.Image
+ Sections []Section
+ Tables []TableItem
+ // PageHeight and PageWidth record the PDF-point dimensions of
+ // each page's winning render. These are computed from the render
+ // image's pixel dimensions divided by the per-page zoom factor,
+ // so downstream consumers get PDF-point values directly without
+ // needing to track a per-page zoom map.
+ PageHeight map[int]float64
+ PageWidth map[int]float64
Metrics PipelineMetrics
Outlines []Outline // PDF outlines/bookmarks extracted from the document
- DLADebug []DLAPageRegions
- TSRDebug []TSRRawCell
+ DLARegions []DLAPageRegions
+
+ // Engine is the native PDF backend used to lazily crop section
+ // images on demand (e.g. for markdown figure embeds or downstream
+ // chunk-time cropping). It is populated by ParseRaw and carries
+ // ownership of the engine: Parse does NOT close the engine, so the
+ // caller must release it via Close once the result is fully
+ // serialized. The JSON parse path closes it immediately after
+ // serialization; the markdown path crops figure images first, then
+ // closes. Close is idempotent and safe to call on a nil result.
+ Engine PDFEngine
}
// Figures returns all sections with LayoutType "figure".
@@ -39,24 +54,21 @@ func (r *ParseResult) Figures() []Section {
return CollectFigures(r.Sections)
}
+// Close releases the native PDF engine held by the result, if any. It is
+// safe to call multiple times and on a nil/empty result.
+func (r *ParseResult) Close() {
+ if r != nil && r.Engine != nil {
+ _ = r.Engine.Close()
+ r.Engine = nil
+ }
+}
+
// DLAPageRegions holds DLA layout regions for one page.
type DLAPageRegions struct {
Page int
Regions []DLARegion
}
-// TSRRawCell holds a raw TSR cell before row/column grouping.
-type TSRRawCell struct {
- TableIndex int `json:"table_index"`
- Page int `json:"page"`
- Label string `json:"label"`
- X0 float64 `json:"x0"`
- Y0 float64 `json:"y0"`
- X1 float64 `json:"x1"`
- Y1 float64 `json:"y1"`
- Text string `json:"text"`
-}
-
// ── Character and text box types ──────────────────────────────────────────
// TextChar represents a single character extracted from a PDF page.
@@ -195,25 +207,18 @@ type OCRText struct {
// ParserConfig holds parser configuration.
type ParserConfig struct {
Zoom float64
- FromPage int
- ToPage int
TableContextSize int
ImageContextSize int
AutoRotateTables *bool
SeparateTablesFigs bool
SortByTop bool
- BatchSize int
SkipOCR bool
- MaxOCRConcurrency int
}
// DefaultParserConfig returns a ParserConfig with sensible defaults.
func DefaultParserConfig() ParserConfig {
return ParserConfig{
Zoom: 3,
- FromPage: 0,
- ToPage: -1,
- BatchSize: 50,
TableContextSize: 0,
ImageContextSize: 0,
SeparateTablesFigs: false,
@@ -250,7 +255,6 @@ type DocAnalyzer interface {
TSR(ctx context.Context, cropped image.Image) ([]TSRCell, error)
OCRDetect(ctx context.Context, cropped image.Image) ([]OCRBox, error)
OCRRecognize(ctx context.Context, cropped image.Image) ([]OCRText, error)
- OCRRecognizeBatch(ctx context.Context, cropped []image.Image) ([][]OCRText, []error)
Health() bool
}
@@ -266,6 +270,13 @@ type Outline struct {
// PDFEngine abstracts page extraction capabilities.
type PDFEngine interface {
+ // ExtractChars returns the per-glyph text of one page. pageNum is a
+ // 0-based page index. Each returned TextChar carries its bounding box
+ // in PDF-point space (post-/Rotate and CropBox-corrected) and is the
+ // finest-grained text unit: it is one glyph, not a word or line.
+ // Downstream processPageBoxes / CharsToBoxes merge these chars into
+ // line/word-level TextBoxes before DLA/TSR, so ExtractChars output is
+ // never fed to layout analysis as-is.
ExtractChars(pageNum int) ([]TextChar, error)
RenderPage(pageNum int, dpi float64) ([]byte, error)
RenderPageImage(pageNum int, dpi float64) (image.Image, error)
diff --git a/internal/entity/ingestion_task.go b/internal/entity/ingestion_task.go
index def89ad956..a2e0f44d6e 100644
--- a/internal/entity/ingestion_task.go
+++ b/internal/entity/ingestion_task.go
@@ -23,6 +23,11 @@ type IngestionTask struct {
DatasetID string `gorm:"column:dataset_id;size:32;not null" json:"dataset_id"`
Schema JSONMap `gorm:"column:schema;type:longtext" json:"schema"`
Status string `gorm:"column:status;size:32;not null;" json:"status"`
+ // ComponentTotal is the number of components in the task's DSL graph.
+ // It is the authoritative denominator for progress percentage so the
+ // frontend does not have to count DSL nodes itself. Written once the
+ // pipeline compiles the canvas (see pipeline.Run).
+ ComponentTotal int `gorm:"column:component_total;default:0" json:"component_total"`
BaseModel
}
@@ -32,9 +37,13 @@ func (IngestionTask) TableName() string {
}
type IngestionTaskLog struct {
- ID int `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
- TaskID string `gorm:"column:task_id;size:32;not null;index" json:"task_id"`
- Checkpoint JSONMap `gorm:"column:checkpoint;type:longtext;not null" json:"checkpoint"`
+ ID int `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
+ TaskID string `gorm:"column:task_id;size:32;not null;index" json:"task_id"`
+ Checkpoint JSONMap `gorm:"column:checkpoint;type:longtext;not null" json:"checkpoint"`
+ ComponentIndex int `gorm:"column:component_index" json:"component_index"`
+ Phase int `gorm:"column:phase" json:"phase"`
+ Component string `gorm:"column:component;size:64;index" json:"component"`
+ Message string `gorm:"column:message;type:text" json:"message"`
BaseModel
}
diff --git a/internal/ingestion/component/chunker/pdfcrop_cgo.go b/internal/ingestion/component/chunker/pdfcrop_cgo.go
new file mode 100644
index 0000000000..9bdf0d1d47
--- /dev/null
+++ b/internal/ingestion/component/chunker/pdfcrop_cgo.go
@@ -0,0 +1,149 @@
+//go:build cgo
+
+// Package chunker — on-demand PDF section cropping.
+//
+// When the upstream Parser forwards storage references (doc_id / bucket /
+// path) for a PDF, the chunker re-acquires the source bytes and crops
+// image/table sections on demand, instead of carrying the rendered images
+// (or the raw binary) across the component boundary. This matches the
+// Python pipeline, where pdf_parser.crop() runs at tokenize time, and keeps
+// peak memory bounded to one page render per cropped section.
+package chunker
+
+import (
+ "context"
+ "encoding/json"
+ "image"
+ "log/slog"
+
+ deepdocpdf "ragflow/internal/deepdoc/parser/pdf"
+ "ragflow/internal/deepdoc/parser/pdf/util"
+ deepdoctype "ragflow/internal/deepdoc/parser/type"
+ "ragflow/internal/ingestion/component"
+ "ragflow/internal/ingestion/component/schema"
+)
+
+// newPDFEngineFromUpstream re-acquires the source PDF from storage using the
+// same resolution the Parser uses, then opens a native engine. It returns
+// (nil, nil) when no storage reference is present or the bytes are not a PDF,
+// so callers can treat a nil engine as "no cropping".
+func newPDFEngineFromUpstream(ctx context.Context, up schema.ChunkerFromUpstream) (deepdoctype.PDFEngine, error) {
+ var data []byte
+ var err error
+ switch {
+ case up.Bucket != "" && up.Path != "":
+ data, err = component.FetchBinary(ctx, up.Bucket, up.Path)
+ case up.DocID != "":
+ var ref *component.DocumentStorageRef
+ ref, err = component.ResolveDocumentStorage(up.DocID)
+ if err == nil && ref != nil {
+ data, err = component.FetchBinary(ctx, ref.Bucket, ref.Path)
+ }
+ default:
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ // Only PDFs can be cropped. Guard against other binary types so a
+ // non-PDF pipeline that happens to forward doc_id stays a no-op.
+ if len(data) < 5 || string(data[:5]) != "%PDF-" {
+ return nil, nil
+ }
+ return deepdocpdf.NewEngine(data)
+}
+
+// cropImageChunks crops image/table chunks in place. Each spanned page is
+// rendered at most once. Chunks arrive in document order, so we keep only a
+// sliding window of page images: once we advance past a chunk whose minimum
+// page is P, no later chunk references a page < P, and we evict those entries
+// from pageCache. This bounds peak memory to the pages spanned by the recent
+// window (typically one page per chunk) instead of holding every rendered
+// page for the whole call. The pdfsync.Mu serializer inside the engine makes
+// concurrent renders safe, but we render sequentially here since the caller
+// fans out across chunks.
+func cropImageChunks(ctx context.Context, engine deepdoctype.PDFEngine, chunks []schema.ChunkDoc) []schema.ChunkDoc {
+ if engine == nil {
+ return chunks
+ }
+ pageCache := make(map[int]image.Image)
+ out := make([]schema.ChunkDoc, len(chunks))
+ for i, ck := range chunks {
+ out[i] = ck
+ if !needsCrop(ck) || ck.Image != "" {
+ continue
+ }
+ raw := ck.PDFPositions
+ if len(raw) == 0 {
+ raw = ck.Positions
+ }
+ var matrix [][]any
+ if err := json.Unmarshal(raw, &matrix); err != nil || len(matrix) == 0 {
+ continue
+ }
+ positions := util.PositionsFromMatrix(matrix)
+ if len(positions) == 0 {
+ continue
+ }
+ // Minimum page this chunk touches; used to prune stale cache entries.
+ minPage := -1
+ for _, pos := range positions {
+ for _, pn := range pos.PageNumbers {
+ if pn < minPage || minPage < 0 {
+ minPage = pn
+ }
+ }
+ }
+ // Evict page images that no later chunk can reference (all future
+ // chunks start at page >= minPage).
+ for pn := range pageCache {
+ if pn < minPage {
+ delete(pageCache, pn)
+ }
+ }
+ single := make(map[int]image.Image, len(positions))
+ for _, pos := range positions {
+ for _, pn := range pos.PageNumbers {
+ if _, ok := single[pn]; ok {
+ continue
+ }
+ if img, ok := pageCache[pn]; ok {
+ single[pn] = img
+ continue
+ }
+ img, rerr := deepdocpdf.RenderPageToImage(engine, pn)
+ if rerr != nil || img == nil {
+ slog.Warn("cropImageChunks: render failed, skipping page",
+ "page", pn, "err", rerr)
+ continue
+ }
+ pageCache[pn] = img
+ single[pn] = img
+ }
+ }
+ // Proceed whenever at least one spanned page resolved to an
+ // image — whether freshly rendered or served from the page cache
+ // (the latter happens for the second chunk reusing page 0).
+ if len(single) == 0 {
+ continue
+ }
+ if err := ctx.Err(); err != nil {
+ return out
+ }
+ img := util.CropSectionPositions(positions, single, deepdoctype.DlaScale)
+ if img == "" {
+ continue
+ }
+ out[i].Image = "data:image/png;base64," + img
+ }
+ return out
+}
+
+func needsCrop(ck schema.ChunkDoc) bool {
+ switch ck.CKType {
+ case "image", "table":
+ return len(ck.PDFPositions) > 0 || len(ck.Positions) > 0
+ default:
+ return false
+ }
+}
diff --git a/internal/ingestion/component/chunker/pdfcrop_cgo_test.go b/internal/ingestion/component/chunker/pdfcrop_cgo_test.go
new file mode 100644
index 0000000000..ec91980020
--- /dev/null
+++ b/internal/ingestion/component/chunker/pdfcrop_cgo_test.go
@@ -0,0 +1,155 @@
+//go:build cgo
+
+package chunker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "image"
+ "strings"
+ "testing"
+
+ deepdoctype "ragflow/internal/deepdoc/parser/type"
+ "ragflow/internal/ingestion/component/schema"
+)
+
+// mockCropEngine returns a fixed solid image for any rendered page. It
+// ignores the page number, so it can stand in for the native engine.
+type mockCropEngine struct{}
+
+func (mockCropEngine) ExtractChars(int) ([]deepdoctype.TextChar, error) {
+ return nil, nil
+}
+func (mockCropEngine) RenderPage(int, float64) ([]byte, error) { return nil, nil }
+func (mockCropEngine) RenderPageImage(_ int, _ float64) (image.Image, error) {
+ return image.NewRGBA(image.Rect(0, 0, 1000, 1000)), nil
+}
+func (mockCropEngine) RawData() []byte { return nil }
+func (mockCropEngine) PageCount() (int, error) { return 1, nil }
+func (mockCropEngine) Outlines() ([]deepdoctype.Outline, error) { return nil, nil }
+func (mockCropEngine) Close() error { return nil }
+
+// assertZeroPageEngine fails unless the engine is asked for page index 0,
+// which proves the chunker converts the 1-based JSON positions to the
+// engine's 0-based page index before rendering.
+type assertZeroPageEngine struct{}
+
+func (assertZeroPageEngine) ExtractChars(int) ([]deepdoctype.TextChar, error) {
+ return nil, nil
+}
+func (assertZeroPageEngine) RenderPage(int, float64) ([]byte, error) { return nil, nil }
+func (assertZeroPageEngine) RenderPageImage(pageNum int, _ float64) (image.Image, error) {
+ if pageNum != 0 {
+ return nil, fmt.Errorf("assertZeroPageEngine: expected 0-based page, got %d", pageNum)
+ }
+ return image.NewRGBA(image.Rect(0, 0, 1000, 1000)), nil
+}
+func (assertZeroPageEngine) RawData() []byte { return nil }
+func (assertZeroPageEngine) PageCount() (int, error) { return 1, nil }
+func (assertZeroPageEngine) Outlines() ([]deepdoctype.Outline, error) { return nil, nil }
+func (assertZeroPageEngine) Close() error { return nil }
+
+func jsonPositions(t *testing.T, rows ...[]float64) json.RawMessage {
+ t.Helper()
+ matrix := make([][]any, 0, len(rows))
+ for _, r := range rows {
+ matrix = append(matrix, []any{r[0], r[1], r[2], r[3], r[4]})
+ }
+ b, err := json.Marshal(matrix)
+ if err != nil {
+ t.Fatalf("marshal positions: %v", err)
+ }
+ return b
+}
+
+func TestNeedsCrop(t *testing.T) {
+ cases := []struct {
+ name string
+ ck schema.ChunkDoc
+ want bool
+ }{
+ {"image with positions", schema.ChunkDoc{CKType: "image", PDFPositions: jsonPositions(t, []float64{1, 10, 100, 10, 100})}, true},
+ {"table with positions", schema.ChunkDoc{CKType: "table", Positions: jsonPositions(t, []float64{1, 10, 100, 10, 100})}, true},
+ {"text with positions", schema.ChunkDoc{CKType: "text", PDFPositions: jsonPositions(t, []float64{1, 10, 100, 10, 100})}, false},
+ {"image without positions", schema.ChunkDoc{CKType: "image"}, false},
+ {"unknown type", schema.ChunkDoc{CKType: "equation", PDFPositions: jsonPositions(t, []float64{1, 10, 100, 10, 100})}, false},
+ }
+ for _, tc := range cases {
+ if got := needsCrop(tc.ck); got != tc.want {
+ t.Errorf("%s: needsCrop = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestCropImageChunks_CropsImageAndTable(t *testing.T) {
+ ctx := context.Background()
+ // 1-based JSON position (1) must be rendered as 0-based page 0.
+ eng := assertZeroPageEngine{}
+ pos := jsonPositions(t, []float64{1, 10, 100, 10, 100})
+
+ chunks := []schema.ChunkDoc{
+ {CKType: "image", PDFPositions: pos},
+ {CKType: "table", PDFPositions: pos},
+ {CKType: "text", PDFPositions: pos}, // skipped (not image/table)
+ {CKType: "image", Image: "data:image/png;base64,preexisting"}, // preserved
+ }
+ out := cropImageChunks(ctx, eng, chunks)
+ if len(out) != len(chunks) {
+ t.Fatalf("len(out) = %d, want %d", len(out), len(chunks))
+ }
+ for i, ck := range out {
+ switch ck.CKType {
+ case "text":
+ if ck.Image != "" {
+ t.Errorf("chunk %d (text): image should stay empty, got %q", i, ck.Image)
+ }
+ case "image":
+ if ck.Image == "data:image/png;base64,preexisting" {
+ continue // preserved, not re-cropped
+ }
+ if !strings.HasPrefix(ck.Image, "data:image/png;base64,") {
+ t.Errorf("chunk %d (image): image = %q, want data:image/png;base64, prefix", i, ck.Image)
+ }
+ case "table":
+ if !strings.HasPrefix(ck.Image, "data:image/png;base64,") {
+ t.Errorf("chunk %d (table): image = %q, want data:image/png;base64, prefix", i, ck.Image)
+ }
+ }
+ }
+}
+
+func TestCropImageChunks_NilEnginePassesThrough(t *testing.T) {
+ ctx := context.Background()
+ pos := jsonPositions(t, []float64{1, 10, 100, 10, 100})
+ chunks := []schema.ChunkDoc{
+ {CKType: "image", PDFPositions: pos},
+ {CKType: "table", PDFPositions: pos},
+ }
+ out := cropImageChunks(ctx, nil, chunks)
+ if len(out) != 2 {
+ t.Fatalf("len(out) = %d, want 2", len(out))
+ }
+ for i, ck := range out {
+ if ck.Image != "" {
+ t.Errorf("chunk %d: expected no crop with nil engine, got image %q", i, ck.Image)
+ }
+ }
+}
+
+func TestCropImageChunks_RenderFailureSkipsChunk(t *testing.T) {
+ ctx := context.Background()
+ // mockCropEngine renders a real image, so a non-empty crop is expected.
+ pos := jsonPositions(t, []float64{1, 10, 100, 10, 100})
+ chunks := []schema.ChunkDoc{
+ {CKType: "image", PDFPositions: pos},
+ }
+ out := cropImageChunks(ctx, mockCropEngine{}, chunks)
+ if len(out) != 1 {
+ t.Fatalf("len(out) = %d, want 1", len(out))
+ }
+ // mockCropEngine renders successfully, so a non-empty crop is expected.
+ if !strings.HasPrefix(out[0].Image, "data:image/png;base64,") {
+ t.Errorf("chunk image = %q, want data:image/png;base64, prefix", out[0].Image)
+ }
+}
diff --git a/internal/ingestion/component/chunker/pdfcrop_nocgo.go b/internal/ingestion/component/chunker/pdfcrop_nocgo.go
new file mode 100644
index 0000000000..51778ff0f1
--- /dev/null
+++ b/internal/ingestion/component/chunker/pdfcrop_nocgo.go
@@ -0,0 +1,23 @@
+//go:build !cgo
+
+// Package chunker — no-CGO fallback for on-demand PDF section cropping.
+//
+// Without the native PDF backend there is nothing to crop, so the engine is
+// always nil and chunks pass through unchanged. The signatures mirror the
+// cgo file so token.go can call them unconditionally.
+package chunker
+
+import (
+ "context"
+
+ deepdoctype "ragflow/internal/deepdoc/parser/type"
+ "ragflow/internal/ingestion/component/schema"
+)
+
+func newPDFEngineFromUpstream(_ context.Context, _ schema.ChunkerFromUpstream) (deepdoctype.PDFEngine, error) {
+ return nil, nil
+}
+
+func cropImageChunks(_ context.Context, _ deepdoctype.PDFEngine, chunks []schema.ChunkDoc) []schema.ChunkDoc {
+ return chunks
+}
diff --git a/internal/ingestion/component/chunker/token.go b/internal/ingestion/component/chunker/token.go
index b61ce76fa9..a4dd08b9de 100644
--- a/internal/ingestion/component/chunker/token.go
+++ b/internal/ingestion/component/chunker/token.go
@@ -59,11 +59,13 @@ import (
"context"
"encoding/json"
"fmt"
+ "log/slog"
"regexp"
"strings"
"sync"
"ragflow/internal/agent/runtime"
+ deepdoctype "ragflow/internal/deepdoc/parser/type"
"ragflow/internal/ingestion/component/schema"
"ragflow/internal/parser/chunk"
)
@@ -190,7 +192,18 @@ func (c *TokenChunkerComponent) invoke(ctx context.Context, inputs map[string]an
}
return c.invokeTextPayload(ctx, *upstream.HTMLResult, delimPattern, childrenPattern), nil
default:
- return c.invokeJSONPayload(ctx, upstream.JSONResult, delimPattern, childrenPattern), nil
+ // Re-acquire the source PDF (if the Parser forwarded storage
+ // refs) so image/table sections are cropped on demand rather
+ // than carried through the wire. Best-effort: a nil engine
+ // simply skips cropping.
+ engine, engErr := newPDFEngineFromUpstream(ctx, upstream)
+ if engErr != nil {
+ slog.Warn("TokenChunker: could not open PDF for on-demand cropping", "err", engErr)
+ }
+ if engine != nil {
+ defer engine.Close()
+ }
+ return c.invokeJSONPayload(ctx, upstream.JSONResult, delimPattern, childrenPattern, engine), nil
}
}
@@ -285,7 +298,7 @@ func (c *TokenChunkerComponent) mergeByTokenSize(text string, childrenPattern *r
// invokeJSONPayload handles structured upstream input. Items fan
// across goroutines (Parallelism); merge is by input index.
-func (c *TokenChunkerComponent) invokeJSONPayload(ctx context.Context, items []schema.ChunkDoc, delimPattern, childrenPattern *regexp.Regexp) map[string]any {
+func (c *TokenChunkerComponent) invokeJSONPayload(ctx context.Context, items []schema.ChunkDoc, delimPattern, childrenPattern *regexp.Regexp, engine deepdoctype.PDFEngine) map[string]any {
if len(items) == 0 {
return emptyOutputs()
}
@@ -351,6 +364,9 @@ func (c *TokenChunkerComponent) invokeJSONPayload(ctx context.Context, items []s
flat = splitByChildren(flat, childrenPattern)
}
+ // Crop image/table chunks on demand when a PDF engine is available.
+ flat = cropImageChunks(ctx, engine, flat)
+
out := make([]schema.ChunkDoc, 0, len(flat))
for _, m := range flat {
if strings.TrimSpace(m.Text) == "" {
diff --git a/internal/ingestion/component/document_storage.go b/internal/ingestion/component/document_storage.go
index da2bb865f4..73b0aa54eb 100644
--- a/internal/ingestion/component/document_storage.go
+++ b/internal/ingestion/component/document_storage.go
@@ -38,7 +38,11 @@ type DocumentStorageRef struct {
// storage resolution. Production leaves this nil and uses DAO-backed lookup.
var ResolveDocumentStorageOverride func(docID string) (*DocumentStorageRef, error)
-func fetchBinary(ctx context.Context, bucket, path string) ([]byte, error) {
+// FetchBinary downloads the raw object stored at (bucket, path). It is
+// exported so downstream components (e.g. the chunker, which re-acquires
+// the source PDF to crop section images on demand) can reuse the same
+// storage resolution the Parser uses.
+func FetchBinary(ctx context.Context, bucket, path string) ([]byte, error) {
stg := resolveStorage()
if stg == nil {
return nil, fmt.Errorf("no storage backend registered")
@@ -73,7 +77,11 @@ func resolveStorage() storage.Storage {
return storage.GetStorageFactory().GetStorage()
}
-func resolveDocumentStorage(docID string) (*DocumentStorageRef, error) {
+// ResolveDocumentStorage maps a document ID to its backing storage
+// location. It is exported so downstream components can re-acquire the
+// source PDF without threading the raw bytes across the component
+// boundary.
+func ResolveDocumentStorage(docID string) (*DocumentStorageRef, error) {
if ResolveDocumentStorageOverride != nil {
return ResolveDocumentStorageOverride(docID)
}
diff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.go
index 69f03e8c7e..d0c6422f81 100644
--- a/internal/ingestion/component/extractor.go
+++ b/internal/ingestion/component/extractor.go
@@ -467,7 +467,8 @@ func extractorChunkList(v any) ([]map[string]any, bool) {
// output_format (string) — always "chunks".
// _ERROR (string, reserved) — populated when the component
// short-circuits with an error.
-// _created_time, _elapsed_time — TrackElapsed bookkeeping.
+// _created_time, _elapsed_time — stamped by the canvas framework
+// (realComponentBody), not here.
func (c *ExtractorComponent) Invoke(ctx context.Context, inputs map[string]any) (map[string]any, error) {
if err := c.Param.Validate(); err != nil {
return nil, fmt.Errorf("extractor: %w", err)
@@ -479,44 +480,38 @@ func (c *ExtractorComponent) Invoke(ctx context.Context, inputs map[string]any)
return nil, fmt.Errorf("extractor: field_name %q requires the TOC prompt generator which is not yet ported to Go", "toc")
}
- tracked, err := runtime.TrackElapsed("Extractor", func() (map[string]any, error) {
- cb := runtime.ProgressCallback(nil)
- progressErr := runtime.TrackProgress("Extractor", cb, func() error {
- return runtime.WithTimeout(ctx, extractorTimeout, func(timeoutCtx context.Context) error {
- if len(in.chunks) == 0 {
- // Fast path (python _invoke line 108): one
- // call with the resolved args directly.
- ans, callErr := c.call(timeoutCtx, in, "")
- if callErr != nil {
- return callErr
- }
- in.chunks = []map[string]any{{in.fieldName: ans}}
- return nil
- }
- for i, ck := range in.chunks {
- text, _ := ck["text"].(string)
- ans, callErr := c.call(timeoutCtx, in, text)
- if callErr != nil {
- return fmt.Errorf("chunk %d: %w", i, callErr)
- }
- ck[in.fieldName] = ans
- in.chunks[i] = ck
- }
- return nil
- })
- })
- if progressErr != nil {
- return nil, progressErr
+ // Progress (_created_time / _elapsed_time stamping, start/done
+ // callbacks) is owned by the canvas framework (realComponentBody),
+ // not by this component. The per-chunk LLM timeout below is a
+ // business concern that stays here.
+ if err := runtime.WithTimeout(ctx, extractorTimeout, func(timeoutCtx context.Context) error {
+ if len(in.chunks) == 0 {
+ // Fast path (python _invoke line 108): one
+ // call with the resolved args directly.
+ ans, callErr := c.call(timeoutCtx, in, "")
+ if callErr != nil {
+ return callErr
+ }
+ in.chunks = []map[string]any{{in.fieldName: ans}}
+ return nil
}
- return map[string]any{
- "chunks": in.chunks,
- "output_format": "chunks",
- }, nil
- })
- if err != nil {
+ for i, ck := range in.chunks {
+ text, _ := ck["text"].(string)
+ ans, callErr := c.call(timeoutCtx, in, text)
+ if callErr != nil {
+ return fmt.Errorf("chunk %d: %w", i, callErr)
+ }
+ ck[in.fieldName] = ans
+ in.chunks[i] = ck
+ }
+ return nil
+ }); err != nil {
return nil, fmt.Errorf("extractor: %w", err)
}
- return tracked, nil
+ return map[string]any{
+ "chunks": in.chunks,
+ "output_format": "chunks",
+ }, nil
}
// call dispatches one LLM chat call for the supplied chunk text
diff --git a/internal/ingestion/component/extractor_test.go b/internal/ingestion/component/extractor_test.go
index 37dc0c5441..c5d5181104 100644
--- a/internal/ingestion/component/extractor_test.go
+++ b/internal/ingestion/component/extractor_test.go
@@ -153,12 +153,6 @@ func TestExtractorComponent_Invoke_HappyPath(t *testing.T) {
if out["output_format"] != "chunks" {
t.Errorf("output_format = %v, want chunks", out["output_format"])
}
- if out["_elapsed_time"] == nil {
- t.Error("_elapsed_time missing")
- }
- if out["_created_time"] == nil {
- t.Error("_created_time missing")
- }
}
// TestExtractorComponent_Invoke_LLMError verifies a mock LLM
diff --git a/internal/ingestion/component/parser.go b/internal/ingestion/component/parser.go
index 29dda9a1b0..f23739bdd1 100644
--- a/internal/ingestion/component/parser.go
+++ b/internal/ingestion/component/parser.go
@@ -22,20 +22,22 @@
// - WHAT IS PORTED:
//
// - The component's lifecycle contract: NewParserComponent /
-// Invoke / Parallelism / Inputs / Outputs and registration
-// under runtime.CategoryIngestion.
+// Invoke / Inputs / Outputs and registration under
+// runtime.CategoryIngestion.
//
-// - The Python fan-out pattern from rag/flow/parser/parser.py
-// (parallel page parsing, deterministic merge by page number,
-// see plan §8 R8) — the Go implementation uses
-// golang.org/x/sync/errgroup with up to 4 goroutines and
-// bounds each fan-out batch by a "page_size" input (default
-// = ceil(total_pages / 4)).
+// - Per-page parallelism is delegated to the parser backends
+// (e.g. internal/deepdoc/parser/pdf fans out one worker per
+// page and assembles the results in page order). This
+// component only reshapes the parser output into the
+// schema.Page layout and keeps the deterministic, page-number
+// sorted merge contract (plan §8 R8) that the downstream
+// chunker / tokenizer rely on for stable chunk IDs.
//
-// - TrackProgress (start/done callback), WithTimeout (60s per
-// page-batch) and TrackElapsed (_created_time / _elapsed_time
-// stamping) — see internal/agent/runtime/helpers.go for the
-// helpers, plan §1 background.
+// - Progress (start/done callback) and elapsed-time stamping
+// (_created_time / _elapsed_time) are owned by the canvas
+// framework (internal/agent/canvas/node_body.go realComponentBody),
+// which wraps every component Invoke. This component does not call
+// those helpers itself. See internal/agent/runtime/helpers.go.
//
// - WHAT IS NOT YET PORTED:
//
@@ -77,11 +79,8 @@ import (
"fmt"
"sort"
"strings"
- "time"
"unicode/utf8"
- "golang.org/x/sync/errgroup"
-
"ragflow/internal/agent/runtime"
"ragflow/internal/ingestion/component/schema"
"ragflow/internal/utility"
@@ -89,19 +88,6 @@ import (
const ComponentNameParser = "Parser"
-// parserParallelism is the fan-out degree for the Parser component.
-// Matches the plan §2 AD-5a choice ("Parser: 4 (parallel page
-// parsing)"). Used by the pipeline runner when it needs to know how
-// many goroutines the component is willing to absorb.
-const parserParallelism = 4
-
-// parserPageBatchTimeout is the per-batch timeout. Mirrors the
-// Python component's `@timeout(60)` decorator on the page parse
-// branch. WithTimeout collapses the dual-layer
-// asyncio.wait_for / @timeout model into a single context, see
-// plan §8 R1.
-const parserPageBatchTimeout = 60 * time.Second
-
// pageFormFeed is the byte that text-page mode treats as a
// hard page boundary. Matches the ASCII form feed (\f, 0x0C) — the
// same convention used by the Python TxtParser and by most
@@ -179,12 +165,6 @@ func NewParserComponent(params map[string]any) (runtime.Component, error) {
return &ParserComponent{Param: p}, nil
}
-// Parallelism declares the goroutine fan-out degree. The pipeline
-// runner uses this to decide how many worker slots the component
-// can absorb. We return 4 to match the Python asyncio.gather
-// pattern that fans one batch per page-range.
-func (c *ParserComponent) Parallelism() int { return parserParallelism }
-
// Inputs returns the static parameter metadata. The component
// reads the following from the inputs map at Invoke time:
//
@@ -193,16 +173,12 @@ func (c *ParserComponent) Parallelism() int { return parserParallelism }
// them from bucket/path or doc_id.
// doc_id (string, optional) — document ID used for naming and,
// when binary is absent, storage lookup.
-// page_size (int, optional) — pages per goroutine for
-// fan-out. Defaults to
-// ceil(totalPages / Parallelism).
func (c *ParserComponent) Inputs() map[string]string {
return map[string]string{
- "binary": "Optional file bytes ([]byte). When absent, Parser resolves them from bucket/path or doc_id.",
- "doc_id": "Optional document ID (string). Used for downstream correlation and doc_id-driven storage lookup.",
- "bucket": "Optional storage bucket override. Used when binary is absent.",
- "path": "Optional storage object key override. Used when binary is absent.",
- "page_size": "Optional integer. Pages per goroutine for fan-out. Default: ceil(totalPages / 4).",
+ "binary": "Optional file bytes ([]byte). When absent, Parser resolves them from bucket/path or doc_id.",
+ "doc_id": "Optional document ID (string). Used for downstream correlation and doc_id-driven storage lookup.",
+ "bucket": "Optional storage bucket override. Used when binary is absent.",
+ "path": "Optional storage object key override. Used when binary is absent.",
}
}
@@ -240,13 +216,13 @@ func (c *ParserComponent) Outputs() map[string]string {
// "_elapsed_time": float64 seconds (via TrackElapsed),
// }
//
-// The fan-out is bounded by Parallelism() goroutines. Each
-// goroutine parses its page-batch under a derived timeout
-// (WithTimeout, 60s). The first error cancels the errgroup
-// context; siblings observe ctx.Done() and abandon their work.
+// Per-page parallelism and aggregation now live in the parser
+// backends (e.g. internal/deepdoc/parser/pdf fans out one worker
+// per page and assembles the results in page order), so this
+// component does no goroutine fan-out of its own.
//
-// DETERMINISTIC MERGE (plan §8 R8): after fan-out, the page slice
-// is sorted by PageNumber. This guarantees the same input
+// DETERMINISTIC MERGE (plan §8 R8): after the page slice is built,
+// it is sorted by PageNumber. This guarantees the same input
// produces byte-identical output across runs and is the contract
// that downstream Chunker / Tokenizer rely on for stable chunk
// IDs (chunks that span pages must reference adjacent PageNumbers
@@ -336,123 +312,60 @@ func (c *ParserComponent) Invoke(ctx context.Context, inputs map[string]any) (ma
pages = [][]byte{nil}
}
}
- totalPages := len(pages)
-
- // 4. Fan-out: split pages into batches of pageSize. The
- // default pageSize is ceil(totalPages / Parallelism),
- // matching the plan §2 AD-5a target.
- pageSize := resolvePageSize(inputs, totalPages)
- batches := splitIntoBatches(pages, pageSize)
-
- // 5. Drive the fan-out from TrackProgress (which delivers the
- // start/done/fail callback sequence); stamp
- // _created_time / _elapsed_time on the result via
- // TrackElapsed without re-running the work.
- var out map[string]any
- progressErr := runtime.TrackProgress(ComponentNameParser, nil, func() error {
- parsed, err := fanOutAndMerge(ctx, batches, parserParallelism)
- if err != nil {
- return err
- }
- // Sort by PageNumber — DETERMINISTIC MERGE (plan §8 R8).
- sortPagesByNumber(parsed)
- out = buildParserOutputs(parsed, dispatched, filename, fileTypeExt)
- return nil
- })
- if progressErr != nil {
- return nil, fmt.Errorf("Parser: %w", progressErr)
- }
- // Stamp _created_time / _elapsed_time. We pass a closure
- // that returns the pre-built `out` so the helper does not
- // re-execute the fan-out.
- return runtime.TrackElapsed(ComponentNameParser, func() (map[string]any, error) {
- return out, nil
- })
-}
-
-// fanOutAndMerge parses each batch in parallel and concatenates
-// the per-batch results. The first error cancels the errgroup
-// context; siblings see ctx.Done() and abandon their parse
-// (returning ctx.Err()).
-//
-// Concurrency model: at most `parallelism` goroutines run
-// concurrently. errgroup.WithContext provides the cancel-on-
-// first-error behaviour, and golang.org/x/sync/errgroup is
-// already in go.mod (line 59).
-func fanOutAndMerge(parent context.Context, batches [][][]byte, parallelism int) ([]schema.Page, error) {
- if len(batches) == 0 {
- return nil, nil
- }
- if parallelism < 1 {
- parallelism = 1
- }
- g, ctx := errgroup.WithContext(parent)
- g.SetLimit(parallelism)
- // One slot per batch; we collect the results in order so the
- // caller can sort the merged slice by PageNumber without
- // needing a mutex.
- results := make([][]schema.Page, len(batches))
- for i, batch := range batches {
- i, batch := i, batch
- g.Go(func() error {
- pages, err := parseBatch(ctx, batch)
- if err != nil {
- return err
- }
- results[i] = pages
- return nil
- })
- }
- if err := g.Wait(); err != nil {
- return nil, err
- }
- // Flatten in batch order. The caller is responsible for
- // sorting by PageNumber — we deliberately do NOT sort here
- // so the per-batch order is visible to tests.
- total := 0
- for _, r := range results {
- total += len(r)
- }
- merged := make([]schema.Page, 0, total)
- for _, r := range results {
- merged = append(merged, r...)
- }
- return merged, nil
+ // 4. Build the page slice sequentially. Per-page parallelism now
+ // lives in the parser backends (e.g. internal/deepdoc/parser/pdf
+ // fans out one worker per page and assembles in page order), so
+ // this component only reshapes the parser output. The DETERMINISTIC
+ // MERGE (plan §8 R8) keeps pages sorted by PageNumber so the
+ // downstream chunker / tokenizer get stable chunk IDs.
+ parsed, err := buildPagesFromBytes(ctx, pages)
+ if err != nil {
+ return nil, fmt.Errorf("Parser: %w", err)
+ }
+ sortPagesByNumber(parsed)
+ out := buildParserOutputs(parsed, dispatched, filename, fileTypeExt)
+ // Forward the storage references so a downstream chunker can
+ // re-acquire the source PDF and crop section images on demand,
+ // instead of carrying the binary across the component boundary.
+ if docID != "" {
+ out["doc_id"] = docID
+ }
+ if bucket, _ := getString(inputs, "bucket"); bucket != "" {
+ out["bucket"] = bucket
+ }
+ if path, _ := getString(inputs, "path"); path != "" {
+ out["path"] = path
+ }
+ // Progress (_created_time / _elapsed_time stamping, start/done
+ // callbacks) is owned by the canvas framework (realComponentBody),
+ // not by this component, so we return the work result directly.
+ return out, nil
}
-// parseBatch parses a single batch of pages under a derived
-// 60-second timeout. The batch is the unit of fan-out: if a
-// batch exceeds its timeout, ONLY that batch errors; siblings
-// see ctx.Done() and abandon their work (errgroup cancel
-// cascades).
+// buildPagesFromBytes reshapes already-prepared page bytes into the
+// schema.Page layout the downstream chunker consumes. The per-page
+// parse (including any parallelism) now lives in the parser backends
+// (internal/parser/parser and internal/deepdoc/parser/pdf); this
+// component only wraps the bytes into pages and honors context
+// cancellation so an abandoned run does not keep reshaping pages.
//
-// runtime.WithTimeout returns just an error; we capture the
-// result pages in a closure-scoped variable and read it back
-// after Wait. This keeps the helper at its single-purpose
-// signature (ctx, fn -> error) without growing the runtime API.
-func parseBatch(ctx context.Context, batch [][]byte) ([]schema.Page, error) {
- var pages []schema.Page
- err := runtime.WithTimeout(ctx, parserPageBatchTimeout, func(ctx context.Context) error {
- pages = make([]schema.Page, 0, len(batch))
- for _, raw := range batch {
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- }
- // Text-page mode: the bytes are already page text.
- pages = append(pages, schema.Page{
- "text": string(raw),
- "doc_type_kwd": "text",
- })
+// The function is format-agnostic: it does not resolve parsers or
+// inspect file families — it only carries the raw bytes under the
+// "text" key with doc_type_kwd "text", matching the shape downstream
+// readers expect from the raw-text fallback and dispatch paths.
+func buildPagesFromBytes(ctx context.Context, pages [][]byte) ([]schema.Page, error) {
+ out := make([]schema.Page, 0, len(pages))
+ for _, raw := range pages {
+ if err := ctx.Err(); err != nil {
+ return nil, err
}
- return nil
- })
- if err != nil {
- return nil, err
+ out = append(out, schema.Page{
+ "text": string(raw),
+ "doc_type_kwd": "text",
+ })
}
- return pages, nil
+ return out, nil
}
// --- input helpers ---
@@ -485,14 +398,14 @@ func readParserBinary(ctx context.Context, inputs map[string]any) ([]byte, error
bucket, _ := getString(inputs, "bucket")
path, _ := getString(inputs, "path")
if bucket != "" && path != "" {
- return fetchBinary(ctx, bucket, path)
+ return FetchBinary(ctx, bucket, path)
}
if docID, ok := getString(inputs, "doc_id"); ok && docID != "" {
- ref, err := resolveDocumentStorage(docID)
+ ref, err := ResolveDocumentStorage(docID)
if err != nil {
return nil, fmt.Errorf("Parser: resolve doc_id %q: %w", docID, err)
}
- return fetchBinary(ctx, ref.Bucket, ref.Path)
+ return FetchBinary(ctx, ref.Bucket, ref.Path)
}
return nil, nil
}
@@ -531,57 +444,6 @@ func containsFormFeed(b []byte) bool {
return false
}
-// splitIntoBatches partitions the page slice into batches of
-// `size` consecutive pages. A non-positive size collapses to
-// one batch.
-func splitIntoBatches(pages [][]byte, size int) [][][]byte {
- if size < 1 {
- size = len(pages)
- }
- if size < 1 {
- return nil
- }
- batches := make([][][]byte, 0, (len(pages)+size-1)/size)
- for i := 0; i < len(pages); i += size {
- end := i + size
- if end > len(pages) {
- end = len(pages)
- }
- batch := make([][]byte, end-i)
- copy(batch, pages[i:end])
- batches = append(batches, batch)
- }
- return batches
-}
-
-// resolvePageSize returns the inputs["page_size"] value when
-// valid, otherwise ceil(totalPages / Parallelism). A page_size
-// of 0 or 1 is treated as "use the default" so a caller that
-// sets page_size=1 to mean "no batching" still fans out across
-// `Parallelism` goroutines.
-func resolvePageSize(inputs map[string]any, totalPages int) int {
- if inputs != nil {
- if v, ok := inputs["page_size"].(int); ok && v > 1 {
- return v
- }
- if v, ok := inputs["page_size"].(int64); ok && v > 1 {
- return int(v)
- }
- if v, ok := inputs["page_size"].(float64); ok && v > 1 {
- return int(v)
- }
- }
- if totalPages < 1 {
- return 1
- }
- // ceil(totalPages / Parallelism)
- size := (totalPages + parserParallelism - 1) / parserParallelism
- if size < 1 {
- size = 1
- }
- return size
-}
-
// sortPagesByNumber orders pages by their PageNumber key
// ascending. Pages without a PageNumber key (or with a non-int
// value) sort to the END so the deterministic contract is
diff --git a/internal/ingestion/component/parser_dispatch.go b/internal/ingestion/component/parser_dispatch.go
index 82a6f1c6b0..30e03d436f 100644
--- a/internal/ingestion/component/parser_dispatch.go
+++ b/internal/ingestion/component/parser_dispatch.go
@@ -121,31 +121,6 @@ func resolveOutputFormat(family string, setups map[string]schema.ParserSetup, al
)
}
-// resolveLibType returns the lib_type argument for parser.GetParser.
-// The Python side does not pass an explicit lib_type for the
-// Markdown / HTML / Office families — the parser constructor picks
-// the only available backend. Mirroring that, when setups[…].lib_type
-// is unset we leave the field empty and let parser.GetParser
-// surface a structured error if no backend is wired.
-//
-// `parse_method` is preserved on the dispatch result so callers can
-// tell the difference between "explicit OCR" and "default DeepDOC"
-// without re-reading setups.
-func resolveLibType(fileType utility.FileType, setups map[string]schema.ParserSetup) (libType, parseMethod string) {
- family := resolveParserFamily(fileType)
- setup, ok := setups[family]
- if !ok {
- return "", ""
- }
- if s, ok := setup["lib_type"].(string); ok {
- libType = s
- }
- if s, ok := setup["parse_method"].(string); ok {
- parseMethod = s
- }
- return libType, parseMethod
-}
-
// dispatchParse resolves the parser for the given fileType and invokes
// its structured ParseWithResult contract.
//
@@ -156,21 +131,28 @@ func resolveLibType(fileType utility.FileType, setups map[string]schema.ParserSe
// fileType may be utility.FileTypeOTHER when the upstream did not
// supply a filename; the dispatch then takes text-page mode
// without consulting parser.GetParser.
+//
+// `parse_method` is captured from setups so callers can tell the
+// difference between "explicit OCR" and "default DeepDOC" without
+// re-reading setups. lib_type is no longer threaded through: the
+// Python dispatcher picks a single backend per family and the Go
+// constructors mirror that.
func dispatchParse(fileType utility.FileType, filename string, data []byte, setups map[string]schema.ParserSetup) parserDispatchResult {
if fileType == utility.FileTypeOTHER {
// Unknown / unset family. The component treats the bytes
- // as text pages; the existing logic
- // (splitIntoPages + fan-out) handles it. We return no
+ // as text pages; splitIntoPages handles it. We return no
// result here so the caller routes to that path.
return parserDispatchResult{}
}
- libType, parseMethod := resolveLibType(fileType, setups)
+ var parseMethod string
+ if setup, ok := setups[resolveParserFamily(fileType)]; ok {
+ if s, ok := setup["parse_method"].(string); ok {
+ parseMethod = s
+ }
+ }
- // Resolve a parser via the GetParser entry point. Any error here
- // is the caller's fault (libType unsupported for this family);
- // surface it as Err so Invoke can set _ERROR.
- p, err := parser.GetParser(fileType, map[string]string{"lib_type": libType})
+ p, err := parser.GetParser(fileType)
if err != nil {
return parserDispatchResult{Err: fmt.Errorf("Parser: resolve %q: %w", fileType, err)}
}
@@ -335,9 +317,9 @@ func jsonItemsToPages(items []map[string]any) []schema.Page {
}
// pagesFromDispatch extracts the per-page bytes from a parsed
-// schema.Page slice so the existing fan-out / merge path can run
-// unchanged. Pages without a `text` field emit an empty buffer
-// (the merge step treats them as zero-length pages).
+// schema.Page slice so the page builder can reshape them into the
+// schema.Page layout the chunker consumes. Pages without a `text`
+// field emit an empty buffer (treated as a zero-length page).
func pagesFromDispatch(pages []schema.Page) [][]byte {
out := make([][]byte, 0, len(pages))
for _, p := range pages {
diff --git a/internal/ingestion/component/parser_dispatch_test.go b/internal/ingestion/component/parser_dispatch_test.go
index c3538d33c4..f4b4b3d9c9 100644
--- a/internal/ingestion/component/parser_dispatch_test.go
+++ b/internal/ingestion/component/parser_dispatch_test.go
@@ -750,40 +750,3 @@ func tcadpZipFixtureForComponent(t *testing.T) []byte {
}
return buf.Bytes()
}
-
-func TestResolveLibType_UsesOwningFamilySetup(t *testing.T) {
- setups := schema.ParserParam{}.Defaults().Setups
- setups["slides"]["lib_type"] = "office_oxide"
- setups["slides"]["parse_method"] = "deepdoc"
- setups["spreadsheet"]["lib_type"] = "office_oxide"
- setups["spreadsheet"]["parse_method"] = "deepdoc"
-
- cases := []struct {
- name string
- fileType utility.FileType
- wantLibType string
- wantParseMethod string
- }{
- {
- name: "pptx resolves from slides family",
- fileType: utility.FileTypePPTX,
- wantLibType: "office_oxide",
- wantParseMethod: "deepdoc",
- },
- {
- name: "xlsx resolves from spreadsheet family",
- fileType: utility.FileTypeXLSX,
- wantLibType: "office_oxide",
- wantParseMethod: "deepdoc",
- },
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- gotLibType, gotParseMethod := resolveLibType(tc.fileType, setups)
- if gotLibType != tc.wantLibType || gotParseMethod != tc.wantParseMethod {
- t.Fatalf("resolveLibType(%q) = (%q, %q), want (%q, %q)",
- tc.fileType, gotLibType, gotParseMethod, tc.wantLibType, tc.wantParseMethod)
- }
- })
- }
-}
diff --git a/internal/ingestion/component/parser_test.go b/internal/ingestion/component/parser_test.go
index b1a1220ad7..89e40b9456 100644
--- a/internal/ingestion/component/parser_test.go
+++ b/internal/ingestion/component/parser_test.go
@@ -19,7 +19,6 @@ package component
import (
"context"
"encoding/json"
- "errors"
"reflect"
"strings"
"testing"
@@ -77,20 +76,12 @@ func TestParserComponent_InputsOutputs_NonEmpty(t *testing.T) {
}
}
-// TestParserComponent_Parallelism locks the fan-out degree to
-// the plan §2 AD-5a value (4). Changing this would silently
-// re-tune resource consumption and break the "fan-out" claim.
-func TestParserComponent_Parallelism(t *testing.T) {
- c := &ParserComponent{}
- if got := c.Parallelism(); got != 4 {
- t.Errorf("Parallelism() = %d, want 4", got)
- }
-}
-
// TestParserComponent_Invoke_TextInput covers the happy path:
// UTF-8 text input, no form-feeds, default page_size. The
// component must emit exactly one page carrying the full text
-// under "text", plus the timing stamps.
+// under "text". Timing stamps (_created_time / _elapsed_time) are
+// owned by the canvas framework, not by this component, so they are
+// not asserted here.
func TestParserComponent_Invoke_TextInput(t *testing.T) {
c := &ParserComponent{Param: schema.ParserParam{}.Defaults()}
out, err := c.Invoke(context.Background(), map[string]any{
@@ -109,12 +100,6 @@ func TestParserComponent_Invoke_TextInput(t *testing.T) {
if got := pages[0]["text"]; got != "hello world" {
t.Errorf("pages[0][text] = %q, want %q", got, "hello world")
}
- if _, ok := out["_created_time"]; !ok {
- t.Errorf("_created_time missing from output")
- }
- if _, ok := out["_elapsed_time"]; !ok {
- t.Errorf("_elapsed_time missing from output")
- }
}
// TestParserComponent_Invoke_PageRangeFilter asserts that
@@ -151,17 +136,13 @@ func TestParserComponent_Invoke_PageRangeFilter(t *testing.T) {
// The test is expected to pass under `go test -count=10 -race`
// — that flag is run separately in the verification block.
//
-// We can't tag-stamp the page text (no page_number key in
-// text-page mode) so we tag the input with explicit
-// page numbers and verify the SORTED output is stable across
-// runs. The fan-out goroutines therefore produce pages in
-// different physical orders, but the deterministic sort
-// rescues byte-equality.
+// Text-page mode has no page_number key, so the input order is
+// the output order; the deterministic sort keeps that order
+// stable across runs, which is the contract the downstream
+// chunker relies on for stable chunk IDs.
func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) {
c := &ParserComponent{Param: schema.ParserParam{}.Defaults()}
- // 8 form-feed-separated pages — enough to exercise the
- // ceil(8/4)=2 page_size default and force multiple
- // goroutines to interleave.
+ // 8 form-feed-separated pages.
input := "p1\fp2\fp3\fp4\fp5\fp6\fp7\fp8"
// First call: produce the canonical bytes.
@@ -195,64 +176,6 @@ func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) {
}
}
-// TestParserComponent_Invoke_RespectsTimeout exercises the
-// cancellation path. We pass a pre-cancelled parent context
-// (no timeout) so the errgroup's WithContext branches see
-// ctx.Done() on the first fan-out — the same code path that
-// a context.WithTimeout parent takes when its deadline
-// elapses. The pre-cancelled form is deterministic across
-// hardware speeds; a 1ms deadline raced on slow CI.
-//
-// The component does NOT expose a "Parallelism" override
-// hook (Parallelism() is fixed at 4). Using a pre-cancelled
-// parent also verifies that a parent cancellation cascades
-// through the errgroup → siblings see ctx.Done() and
-// return ctx.Err().
-func TestParserComponent_Invoke_RespectsTimeout(t *testing.T) {
- c := &ParserComponent{Param: schema.ParserParam{}.Defaults()}
- // Build a 400-page input so the fan-out has more than
- // one batch to dispatch.
- var b strings.Builder
- for i := 0; i < 400; i++ {
- if i > 0 {
- b.WriteByte(pageFormFeed)
- }
- b.WriteString("page")
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // pre-cancel
-
- _, err := c.Invoke(ctx, map[string]any{
- "binary": b.String(),
- })
- if err == nil {
- t.Fatalf("Invoke returned nil error; expected a cancellation error")
- }
- // The error must reference cancellation — not an
- // unrelated "parse error" — so callers can distinguish
- // "we were cancelled" from "the input was malformed".
- if !isTimeoutish(err) {
- t.Errorf("Invoke error = %v, want a timeout/cancel error", err)
- }
-}
-
-// isTimeoutish returns true if err is a context.DeadlineExceeded
-// (directly or wrapped) or otherwise carries a "deadline
-// exceeded" / "context deadline" / "context canceled" substring.
-func isTimeoutish(err error) bool {
- if err == nil {
- return false
- }
- msg := err.Error()
- if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
- return true
- }
- return strings.Contains(msg, "deadline exceeded") ||
- strings.Contains(msg, "context deadline") ||
- strings.Contains(msg, "context canceled")
-}
-
// TestParserComponent_New_Defaults constructs a Parser from a
// nil param map and verifies the static Param is the
// Defaults() value (i.e., NewParserComponent does not mutate
@@ -423,44 +346,17 @@ func TestParserComponent_Invoke_AcceptsBytes(t *testing.T) {
}
}
-// TestParserComponent_Invoke_PageSizeHint covers the optional
-// page_size input. A page_size of 2 with 6 pages yields 3
-// batches; the deterministic merge still yields 6 pages in
-// input order.
-func TestParserComponent_Invoke_PageSizeHint(t *testing.T) {
- c := &ParserComponent{Param: schema.ParserParam{}.Defaults()}
- out, err := c.Invoke(context.Background(), map[string]any{
- "binary": "p1\fp2\fp3\fp4\fp5\fp6",
- "page_size": 2,
- })
- if err != nil {
- t.Fatalf("Invoke: %v", err)
- }
- pages, ok := out["pages"].([]schema.Page)
- if !ok {
- t.Fatalf("pages: got %T", out["pages"])
- }
- if len(pages) != 6 {
- t.Fatalf("pages len = %d, want 6", len(pages))
- }
- for i, p := range pages {
- want := "p" + string(rune('1'+i))
- if got := p["text"]; got != want {
- t.Errorf("pages[%d] = %q, want %q", i, got, want)
- }
- }
-}
-
-// TestParseBatch_IsFormatAgnostic pins the batching contract:
-// parseBatch does not resolve parsers or inspect file families. It
-// only wraps already-prepared page bytes into schema.Page items.
-func TestParseBatch_IsFormatAgnostic(t *testing.T) {
- got, err := parseBatch(context.Background(), [][]byte{
+// TestBuildPagesFromBytes_FormatAgnostic pins the page-builder
+// contract: buildPagesFromBytes does not resolve parsers or inspect
+// file families. It only wraps already-prepared page bytes into
+// schema.Page items.
+func TestBuildPagesFromBytes_FormatAgnostic(t *testing.T) {
+ got, err := buildPagesFromBytes(context.Background(), [][]byte{
[]byte("first page from dispatch"),
[]byte("<table>second page from html dispatch</table>"),
})
if err != nil {
- t.Fatalf("parseBatch: %v", err)
+ t.Fatalf("buildPagesFromBytes: %v", err)
}
if len(got) != 2 {
t.Fatalf("len(got) = %d, want 2", len(got))
diff --git a/internal/ingestion/component/schema/chunker.go b/internal/ingestion/component/schema/chunker.go
index 63b60cf62e..ed8854de53 100644
--- a/internal/ingestion/component/schema/chunker.go
+++ b/internal/ingestion/component/schema/chunker.go
@@ -50,6 +50,17 @@ type ChunkerFromUpstream struct {
// Name is the source document name. Required.
Name string `json:"name"`
+ // DocID is the originating document ID. When set, the chunker can
+ // re-resolve the source PDF from storage to crop section images on
+ // demand, instead of carrying the binary across the component
+ // boundary.
+ DocID string `json:"doc_id,omitempty"`
+
+ // Bucket and Path are the explicit storage location of the source
+ // PDF. They take precedence over DocID-driven resolution.
+ Bucket string `json:"bucket,omitempty"`
+ Path string `json:"path,omitempty"`
+
// File is the optional upstream file descriptor.
File *ChunkerFileMeta `json:"file,omitempty"`
diff --git a/internal/ingestion/pipeline/PROGRESS_LOG_RESUME_PLAN.md b/internal/ingestion/pipeline/PROGRESS_LOG_RESUME_PLAN.md
new file mode 100644
index 0000000000..1ec71e7911
--- /dev/null
+++ b/internal/ingestion/pipeline/PROGRESS_LOG_RESUME_PLAN.md
@@ -0,0 +1,390 @@
+# Ingestion Pipeline:Progress / Log / Resume 机制计划书
+
+> 范围:`internal/ingestion/pipeline` 的执行可观测性与断点续跑。
+> 关联代码:`internal/agent/canvas/*`(框架闸口)、`internal/agent/runtime/*`(progress 回调)、`internal/ingestion/*`(ingestion 专属逻辑)。
+> 状态:设计稿 v2(v1 经评审修订,修订记录见文末 §10)。结论:**续跑走 B(eino interrupt/checkpoint),观测走轻量 task_log(不存全量 output)**。
+
+---
+
+## 1. 背景与目标
+
+ingestion pipeline 是把一份 DSL 编译成 eino 图后完整执行(`Pipeline.Run` → `compiled.Workflow.Invoke`)。需要三件事:
+
+1. **Progress(进度)**:框架层对每个 component 的发令(进入/退出/失败),供 UI/API 展示。
+2. **Log(日志)**:把 progress 落库成可回读的 `ingestion_task_log`,API 侧 `IngestionTaskLogDAO.ListLogsByTaskID` 读取。
+3. **Resume(续跑)**:重跑同一个 task(task_id / pipeline_id 不变)时,已成功执行过的 component 不必重做。
+
+目标约束(来自 `node_body.go:156` 的项目自身原则):
+
+> cross-cutting concerns belong in the framework body (`realComponentBody`), not inside each component's `Invoke`.
+
+即 progress / resume 不应回到 `Parser` 等组件内部(否则每个组件都依赖 `dao`,且违反单一闸口原则)。
+
+---
+
+## 2. 现状(已落地的部分)
+
+区分两件事:**功能是否完整**(能否在进程内 interrupt→resume)与**持久化是否到位**(崩溃/重启后能否恢复)。
+
+| 能力 | 位置 | 状态 |
+| --- | --- | --- |
+| 框架级 progress 发令 | `node_body.go:187` `runtime.TrackProgress` → 从 ctx 取 `ProgressCallback` | ✅ 已落地(功能完整) |
+| pipeline 写 `ingestion_task_log` | `pipeline.go:165` `taskLogProgressCallback`(`dao.DB==nil` 时 no-op) | ✅ 已落地,但 `progress` 字段语义是状态 `{0,1,-1}`,无序号、无进入/退出区分、无输出序列化 |
+| eino `WithInterruptAfterNodes` 接线 | `compile.go:56,78,143` `CompileOptions.InterruptAfter` → `compose.WithInterruptAfterNodes` | ✅ 已落地(功能完整) |
+| eino CheckPointStore(Redis) | `compile.go:63` + `checkpoint_store.go` `RedisCheckPointStore`,key=`agent:cp:{id}` | ✅ 已落地(功能完整) |
+| 状态机(running/succeeded/failed/cancelled) | `run_tracker.go` `RunTracker`,key=`agent:run:{run_id}`,状态 `0/1/2/3` | ✅ 已落地(功能完整) |
+| interrupt 捕获 / resume id 暂存 | `runner.go:163` `interruptIDs`(**内存** map) | ✅ 功能完整(agent/chat 用,进程内可用);⚠️ **持久化待补**(跨进程重启即丢,ingestion 不能依赖) |
+| `UserFillUp` interrupt 发令 | `interrupt_resume.go` `UserFillUpNodeBody`(`compose.Interrupt` / `GetResumeContext`) | ✅ 发令功能完整;⚠️ resume 侧(`ResumeWithData`)尚未接线(仅注释提及) |
+| 稳定 `CheckPointID` 选项 | `compile.go` `CompileOptions` | ❌ 缺 `WithCheckPointID`,目前 CheckPointID 每编译一次生成 |
+
+**关键结论**:续跑要用的「执行完 interrupt → 持久化 checkpoint → 后续 resume」底座在 canvas 层已经齐全(功能层面),ingestion 只需把 `Pipeline.Run` 接上,并补齐 **interrupt id 的跨进程持久化** 这一缺口。
+
+---
+
+## 3. 路线 A:自研 task_log 缓存 + 框架闸口跳过(先前提案,已放弃用于续跑)
+
+### 机制
+- `realComponentBody` 在 `comp.Invoke` 前,从 ctx 取 `ResumeProvider`(agent 侧为 nil),按 `cpnID` 命中则直接 `return cachedOutput`,不调 `Invoke`。
+- `Pipeline.Run` 预读 `ingestion_task_log` 的 exit 行 → 构建 `map[cpnID]output`,经 ctx 注入;并注入 `cpnID→index` 映射供 progress 写 0-based 序号。
+- 失效靠 `input_fingerprint = hash(in)`:exit log 记指纹,resume 时组件输入指纹不匹配则重跑。
+
+### 优点
+- 不依赖 Redis;DB 无关(测试友好)。
+- 对 eino resume 语义零依赖,完全自控。
+
+### 缺点(这是放弃它做续跑的原因)
+- **重造 checkpoint**:eino 已有现成的图级 checkpoint + 序列化 + 恢复,A 等于自己再写一遍,且对 DAG / Loop / Parallel 的拓扑正确性要自己保证。
+- **框架闸口 skip 是 hack**:在 `realComponentBody` 里短路 `Invoke`,与「pipeline 完整执行 DSL」的契约微妙冲突;eino 也失去了它自己对该节点执行结果的一致性保证。
+- **体积(量化)**:exit log 要存全量 output(longtext)。预估:单文件 parser 输出通常 KB~MB;长文档 / 多分片可达 **十 MB 级**;若按「每 component 一条 exit 行 + 全量 output」落库,单 task 的 `ingestion_task_log` 体积 = Σ(output_size),可能达 **数十 MB**。这正是 B 方案把全量 output 交给 eino checkpoint(Redis,带 TTL,可过期)而非 task_log(DB longtext,需永久保留)的原因。
+- **指纹失效不彻底**:仅 `(cpnID, fingerprint)` 仍可能在 DSL 结构变化(节点增删、边重连)时误命中。
+
+---
+
+## 4. 路线 B:eino interrupt-after-node + Redis checkpoint(推荐)
+
+> 思路:每个 component **执行完成后** 由 eino 自动 `interrupt`,把整图状态(含该节点输出)序列化进 Redis checkpoint;orchestrator 捕获 interrupt 后 `ResumeWithData` 续跑下一步。进程崩溃/重启后,下一次 `Pipeline.Run` 检测到遗留 checkpoint 即从中恢复。
+
+### 4.1 接线(编译期)
+`Pipeline.Run` 编译时传入:
+
+```go
+compiled, err := canvas.Compile(ctx, p.canvas,
+ canvas.WithCheckPointStore(dao.NewRedisCheckPointStore(ttl)), // 复用 checkpoint_store.go
+ canvas.WithStateSerializer(canvas.CanvasStateSerializer{}), // state_serializer.go(JSON)
+ canvas.WithInterruptAfterNonTerminalCpn(), // 无参;canvas.Compile 内部算出非终态节点并 interrupt
+ canvas.WithCheckPointID(p.taskID), // 稳定 id = taskID(需新增选项,见 §6)
+)
+```
+
+- `WithInterruptAfterNonTerminalCpn()`(**无参**,用户建议):调用方不再需要计算 / 传入 `nonTerminalCpnIDs`。`canvas.Compile` 在内部直接根据 `Canvas` 结构算出「非终态节点 id」(见 §4.1.a),并对它们注册 `WithInterruptAfterNodes`。这样接线从调用方下沉到 `Compile`,避免「算错集合 / 传 allCpnIDs」类错误(见 §4.1.a),也让 `UserFillUp` 排除(§4.2.b)由同一处统一处理。
+
+#### 4.1.a 为什么不能用 `allCpnIDs`(用户发现 2)
+`WithInterruptAfter(allCpnIDs)` 会在**每个**节点(含终态/输出节点)执行后再插入一次 eino interrupt。终态节点的 `Invoke` 返回即代表整图完成;若把它纳入,eino 会在它执行后再 pause 一次,导致 orchestrator 多一轮无意义的 `ResumeWithData` 才真正结束,且可能让 `Invoke` 返回 interrupt 错误而非完成结果,打乱 §4.2 的 `err==nil → break` 判定。
+
+正确做法:**只对「有下游」的非终态节点 interrupt**;终态节点正常退出 → `err==nil` → 循环 break,整图一次完成。该集合由 `canvas.Compile` 内部计算(出度 > 0 的中间节点 = `Canvas.Components` 中不是 `Canvas.Outputs` 的节点),调用方用无参 `WithInterruptAfterNonTerminalCpn()` 即可,无需也无法传错集合。
+- `WithCheckPointID`:目前 `CompileOptions` **没有**该字段,需新增(映射 `compose.WithCheckPointID`),使 checkpoint key 稳定为 `agent:cp:{taskID}`,重跑同一个 task 才命中同一份 checkpoint。
+
+### 4.2 运行期:进程内循环 + 跨进程恢复(统一在 `Pipeline.Run`)
+
+```go
+// Pipeline.Run 内部
+for {
+ // 崩溃恢复优先(用户建议):每轮首要动作先判断是否有遗留中断。
+ // 上一进程在「命中 interrupt → 持久化 interrupt id」之后、消费它之前崩溃,
+ // 会在 Redis 留下未消费的 interrupt_id。本轮第一件事就是直接 resume 该中断,
+ // 而不是从图入口重跑(那样会重复执行已完成节点)。
+ if pending := runTracker.GetInterruptID(ctx, p.taskID); pending != "" {
+ runCtx = compose.ResumeWithData(runCtx, pending, nil)
+ runTracker.ClearInterruptID(ctx, p.taskID) // 已消费,避免下一轮重复 resume
+ }
+ out, err := compiled.Workflow.Invoke(runCtx, current)
+ if err == nil {
+ break // 整图完成
+ }
+ if !canvas.IsInterruptError(err) {
+ return nil, err // 真错误
+ }
+ // 续跑型 interrupt(不在本轮回内联 resume,交给下一轮顶部统一 resume,
+ // 避免同一 ctx 被重复 ResumeWithData)。
+ // 安全前提见 §4.2.b:ingestion DSL 不得含 UserFillUp 节点,
+ // 因此 IsInterruptError 命中即续跑,不会误当 wait-for-user。
+ ctxs := canvas.ExtractInterruptContexts(err)
+ interruptID := canvas.RootInterruptID(ctxs)
+ runTracker.AttachInterrupt(ctx, p.taskID, interruptID) // 持久化到同一 hash(见 §4.4),供崩溃后恢复
+}
+```
+
+单次 `Pipeline.Run` 调用即可跑完整条 pipeline,每节点执行后把状态落 Redis;中途崩溃则下一次调用恢复。
+
+#### 4.2.b 安全前置:`UserFillUp` 在 ingest DSL 的禁止(S3)
+ingestion 当前无交互节点,但若将来 DSL 增加 `UserFillUp`(如人工确认 chunking 结果),`IsInterruptError` 命中会被误判为续跑。前置守卫二选一并写进编译契约:
+
+- **方案 A(推荐,编译期禁止)**:`canvas.Compile` 增加 `InterruptAfterNonTerminalCpn` 与 `UserFillUp` 的互斥校验——ingestion 走该选项时,若 DSL 含 `UserFillUp` 节点直接编译失败,返回明确错误。
+- **方案 B(运行期过滤)**:`canvas.Compile` 在计算 `nonTerminalCpnIDs`(供 `WithInterruptAfterNonTerminalCpn` 使用)时显式剔除 `UserFillUp` 类节点,且不对其注册 after-node interrupt;其余节点的 interrupt 才走续跑路径。
+
+**共存原理(Question:`WithInterruptAfter` 与用户导致的 interrupt 能否共存?)**:两者都是 eino 的**同一套 interrupt 原语**,仅靠 **interrupt id** 区分,由 `IsInterruptError` 统一捕获、`ExtractInterruptContexts` / `RootInterruptID` 取出对应 id。`WithInterruptAfterNodes` 是「编排级」pause(节点跑完由框架插入,resume 传 `nil`);`compose.Interrupt`(UserFillUp 内部调用)是「节点级」pause(节点自己发令、等待用户数据,resume 传用户数据)。它们**可以共存于同一图**——只要同一个节点不被两种机制重复注册。ingestion 通过 §4.2.b 把 UserFillUp 排除出 `nonTerminalCpnIDs`,使其仅保留自身 `compose.Interrupt` 作为该节点的唯一 interrupt 源;其余节点走 after-node interrupt。该共存行为需在 eino v0.9.12 上 spike 确认(见新增 R7),但原理上无冲突。
+
+本期 ingestion DSL 保证无 `UserFillUp`,两条守卫任选其一落地即可消除 R6 歧义。
+
+### 4.3 跨调用恢复(「重复运行一个 task」)
+`Pipeline.Run` 开头判断:
+
+```go
+st := runTracker.Get(ctx, p.taskID) // agent:run:{taskID},status ∈ {0,1,2,3}
+switch st["status"] {
+case runStatusRunning: // 0:上次跑崩/被中断,保留 checkpoint + interrupt_id
+ // 不删、不在此处 resume;由 §4.2 循环顶部读 GetInterruptID 直接恢复
+case runStatusCancelled: // 3:见 §4.3.b
+ store.Delete(ctx, p.taskID) // 清旧 checkpoint + 整跑(默认策略)
+case runStatusSucceeded, runStatusFailed, "": // 1/2/"":已完成或全新 → 重跑
+ store.Delete(ctx, p.taskID) // 清旧 checkpoint(连带清 interrupt_id,循环中无 pending → 从入口跑)
+}
+```
+
+- **`running` 的续跑入口在循环顶部**:状态机只决定「保不保留 checkpoint」。`running` 时不删,下一行进入 §4.2 的 `for` 循环,循环顶部 `GetInterruptID` 读到遗留 interrupt_id 即 `ResumeWithData` 恢复——所以恢复逻辑只有一处(循环顶),不在 §4.3 重复写(避免与 §4.2 两处 resume 漂移)。
+- 其余状态 `Delete` 会把 checkpoint 与 `interrupt_id` 一同清掉,循环顶部 `GetInterruptID` 返回 `""` → 从图入口正常跑(eino checkpoint 已删,不会命中旧状态)。
+
+- **失效策略=状态机**,而非 A 的指纹:`running` → 复用;其余 → 重置重跑。比指纹更可靠(天然覆盖 DSL 结构变化)。
+- 这与 `run_tracker.go` 的 `Start/MarkSucceeded/MarkFailed/AttachCheckpoint` 完全对齐;`Pipeline.Run` 在开始时 `Start`、完成时 `MarkSucceeded`、失败时 `MarkFailed`。
+
+#### 4.3.a 重跑 vs 续跑语义(S2)
+ingestion **不区分**「重跑」与「续跑」两种入口——它的语义统一为:
+
+> 按 `task_id` 重做整图;框架用 checkpoint 跳过已执行节点。状态机只决定「是否命中遗留 checkpoint」:`running` 命中复用,其余清掉重跑。
+
+即:用户再次提交同一 `task_id`(合法重跑用例)时,行为是「先清旧 checkpoint 再整跑」——这是**正确的**(用户明确要重做)。如果将来需要「基于上次结果继续而不重做」,需新增独立的 resume 入口(不在本期范围),届时 `succeeded` 分支才需要区分「清掉重跑」与「保留续跑」。本期在 API / 用户文档中明确此语义。
+
+#### 4.3.b `cancelled` 状态恢复策略(S5)
+`RunTracker` 有 `runStatusCancelled = "3"`(`run_tracker.go:44`)。本期策略:
+
+- 命中 `cancelled` 默认**不允许自动续跑** → 清 checkpoint + 整跑(与 `failed` 一致),避免「用户取消后悄悄继续」的语义歧义。
+- 可选增强(不在本期):暴露显式 `resume cancelled` 入口,由人工/API 触发,才走 `running` 的复用分支。
+
+### 4.4 需要新增的持久化(M3 + S4)
+`runner.go:163` 的 `interruptIDs` 是**内存** map,进程重启即丢。
+
+- **M3 决策(不新增 key)**:复用现有 `agent:run:{taskID}` hash,新增 `interrupt_id` 字段,而非引入第二种持久化约定(`agent:cpint:{taskID}`)。给 `RunTracker` 加:
+ ```go
+ func (t *RunTracker) AttachInterrupt(ctx, runID, interruptID string) error // HSet "interrupt_id"
+ func (t *RunTracker) GetInterruptID(ctx, runID) (string, error) // HGet "interrupt_id"
+ func (t *RunTracker) ClearInterruptID(ctx, runID) error // HDel "interrupt_id"(循环顶部消费后调用)
+ ```
+ 与既有的 `AttachCheckpoint`(写 `checkpoint_id` 字段,`run_tracker.go:110`)同 hash、同生命周期、同 TTL,维护成本最低。
+- **S4 边界(不动 agent/chat)**:本次改动**仅引入 ingestion 用的持久化路径**。`runner.go` 的内存 `interruptIDs` 继续服务 agent/chat 路径,不做合并——不为「统一性」强行改 agent 调用方(遵循 `CLAUDE.md`:agent 仍在用就保留)。文档明确这一点,避免后续实现者把它当 deprecated 留着或误删。
+
+### 4.5 优点
+- **复用现成底座**:eino 负责 checkpoint 序列化/恢复,对 DAG/Loop/Parallel 拓扑正确性是 eino 保证的,不自己再造。
+- **组件零改动、零 `dao` 依赖**:`Parser` 等完全不知道 resume 存在,符合 `node_body.go:156` 原则。
+- **用户原始意图被升级为框架级 checkpoint(澄清)**:用户最早设想「组件读自己的 exit log 跳过」,方案 B 不是让组件去读自己的 log,而是**框架统一用 eino checkpoint 在闸口处跳过**——组件仍然零改动,意图以更稳健的方式达成(等价于「框架替组件做了它想做的事」)。
+- **失效干净**:状态机驱动,无指纹误命中问题。
+- **天然支持用户需求**:「重跑同 task,已完成组件不重做」= checkpoint 恢复,零额外代码。
+
+### 4.6 缺点 / 风险(见 §6 风险与 spike)
+- 依赖 Redis(ingestion 已用 Redis,可接受;无 Redis 时的**可见**降级见 R5)。
+- 需把 `Pipeline.Run` 从单次 `Invoke` 改为循环,且管理 interrupt id 持久化。
+- eino 序列化保真度:checkpoint = `CanvasState` 整体 JSON(`state_serializer.go` 用 `json.Marshal`)。native 解析器等若产出非 JSON 类型(`[]byte`、自定义 struct)会断 resume——需 spike(R1)。
+- 需确认 `WithInterruptAfterNodes` + 全图 `ResumeWithData` 在 Loop/Parallel 下的精确语义(R3,P0)。
+
+---
+
+## 5. Progress / Log 改进(路线无关,必做)
+
+无论续跑走 A 还是 B,`taskLogProgressCallback` 都该升级为**结构化事件**,满足用户最初要求:
+
+- `progress` 字段改为 `(component 序号 0-based, 相位 enter/exit/error)`。
+- **不携带 component 的 `Output`**:resume 由框架 eino checkpoint 负责,progress/log 仅是观测,不需要 output(用户决定)。这同时消解了 M5「事件携带 vs sink 不落库」的紧张——两层现在一致「都不存 output」。
+
+### 5.1 共享类型保持纯净(M1)
+`runtime.ProgressEvent` **不**携带 `Index`——`Index` 是 ingestion 专有概念,放进 agent/ingestion 共享类型属于抽象泄漏。定义:
+
+```go
+// internal/agent/runtime(共享,agent 与 ingestion 共用,保持纯净)
+type ProgressPhase int
+const (PhaseEnter ProgressPhase = iota; PhaseExit; PhaseError)
+type ProgressEvent struct {
+ Phase ProgressPhase
+ Component string // cpnID
+ Err error // 仅 PhaseError 非空
+ // 不携带 Output:resume 由 eino checkpoint 负责,progress 仅是观测(用户决定)
+}
+type ProgressCallback func(ProgressEvent)
+```
+
+`realComponentBody` 的 `cpnID` 是闭包参数(`node_body.go:180`),而 `node_body.go:187` 当前传给 `TrackProgress` 的**第一参数是 `componentClass`(class 名),不是节点 id**。改造时把该第一参数从 `componentClass` 改为 **`cpnID`**:`runtime.TrackProgress(cpnID, ...)`,使 `ProgressEvent.Component` 填的是**节点 id**(`ProgressEvent.Component` 用于落库定位与排序,需唯一标识节点;class 名无法区分同名多实例)。采用「只改调用处第一参数」方案,不扩 `TrackProgress` 签名(更少改动,符合用户建议)。`realComponentBody` 改为发 `ProgressEvent{Phase, Component: cpnID, ...}`(enter 时 Phase=PhaseEnter;exit 时 Phase=PhaseExit;error 时 Phase=PhaseError 且填 `Err`),**不读取、不传递组件 output**。
+
+### 5.2 ingestion 侧注入 Index(M1 落地)
+在 `pipeline` 包内定义轻量包装,Index 由 **sink 层**用 pipeline 注入 ctx 的 `cpnID→index` 映射算出,不污染共享类型:
+
+```go
+// internal/ingestion/pipeline(ingestion 专有)
+type pipelineProgressEvent struct {
+ Index int // 0-based,来自 ComponentIndexMap
+ Event runtime.ProgressEvent
+}
+```
+
+`taskLogProgressCallback` 闭包持有 `cpnID→index` 映射,收到 `ProgressEvent` 后计算 `Index = indexMap[event.Component]`,再写库。Index 的归属与计算完全留在 ingestion 侧。
+
+### 5.3 落库策略(M5,已消解)
+`ProgressEvent` **不携带 `Output`**(用户决定:resume 不需要它,output 完整回放本就交给 eino checkpoint / Redis,progress 仅是观测)。因此 M5 原本的「事件携带 vs sink 不落库」紧张关系**不再存在**——两层一致:事件不带、sink 也不存。
+
+**时间戳(Q1 结论:event 不携带时间戳)**:
+- `ProgressEvent` 不携带时间戳。回调在 `realComponentBody` 内同步触发、sink 立即落库,emit≈落库。
+- 时间戳只由 GORM `BaseModel.create_time` 自动写入(**秒级精度**),作为行级元数据;现有 `pipeline.go` 把 `create_time` 又塞进 `checkpoint` JSON 是**冗余,应删除**。
+- 行内排序以自增 `id` 为准(`LatestLogByTaskID` 已依赖 `id DESC` 做确定性 tie-break,因 `create_time` 秒级会撞)——event 时间戳对排序无增量价值。
+- 与移除 `Output` 一致,保持共享 `ProgressEvent` 精简(M1 纯净化)。
+
+> `taskLogProgressCallback` 直接写独立列(`component_index` / `phase` / `component` / `message`),**不再写 `checkpoint` JSON**(不含 output、不含 create_time);时间戳仅来自 `BaseModel.create_time`。任何地方都不在 progress 通道里携带组件全量 output(体积问题见 §3 量化,且 resume 不依赖它)。
+
+---
+
+## 6. 风险与待验证(Spike,附优先级)
+
+| # | 风险 | 优先级 | 验证方式 |
+| --- | --- | --- | --- |
+| R1 | `CanvasState` 经 JSON 序列化/反序列化保真(native 解析器 `[]byte`/自定义类型) | P1 | 集成测试:跑含 Parser 的 DSL,中断→恢复,断言恢复后输出与一次性跑一致 |
+| R2 | 稳定 `CheckPointID` 接线 | P1 | 给 `CompileOptions` 加 `CheckPointID` + `WithCheckPointID`;单测验证 key=`agent:cp:{taskID}` |
+| **R3** | **`WithInterruptAfterNodes` + 全图 `ResumeWithData` 在 Loop/Parallel/DAG 下的语义** | **P0** | **✅ 已通过(2026-07-09)**:`internal/agent/workflowx/r3_interrupt_test.go` 五个集成用例全绿(DAG / 含 Loop 前置节点 / 含 Loop 节点本身 / 含 Parallel / 跨进程重编译同 CheckPointID 恢复)。结论:interrupt-after-node + `ResumeWithData` 在三类拓扑下语义正确——① 已完成节点(interrupt 之前的)resume 后**不重跑**(counter 恒为 1,无「重解析文件」风险);② Loop/Parallel 正确重入(或已完成则跳过,counter 不增);③ 跨进程崩溃恢复(重编译图 + 同 `WithCheckPointID`)可续跑。**无需 M2 回退**,§8 第 3 步可按原计划推进。注意:after-node interrupt 仅在**有状态图**(`WithGenLocalState`,与 `canvas.BuildWorkflow` 的 `CanvasState` 一致)下才会被包成 `*interruptError` 并被 `ExtractInterruptInfo` 识别;无状态图返回裸 `*core.InterruptSignal`(`ExtractInterruptInfo` 返回 nil)。ingestion 路径因 `CanvasState` 已注册而天然满足。 |
+| R4 | interrupt id 持久化与崩溃恢复 | P1 | 进程内循环跑完正常;模拟「跑崩在节点 N」→ 新进程 `Pipeline.Run` 从该断点续跑 |
+| R5 | Redis 不可用降级(**可见**,非静默) | P1 | 见 §6.a:启动探测 Redis → 拒绝启动并明确报错,或在 task_log 写 `resume_degraded` warning |
+| R6 | ingestion「续跑型 interrupt」与 agent「wait-for-user interrupt」区分 | P2 | 由 §4.2.b 的 `UserFillUp` 禁止/过滤守卫消除,无需靠运行期猜测 |
+| R7 | `WithInterruptAfterNodes` 与节点内 `compose.Interrupt`(UserFillUp)在同一图的共存语义 | P1 | eino v0.9.12 集成测试:构造含 UserFillUp + 非终态 after-node interrupt 的图,断言两者按 interrupt id 分别 resume,且 UserFillUp 节点不被重复 interrupt(见 §4.2.b 共存原理) |
+
+### 6.a R5 可见降级(M4)
+静默降级为「整跑」会悄悄违反用户需求「重跑同 task,已完成组件不重做」,且无上层信号。改为**可见**二选一:
+
+- **方案 A(推荐)**:ingest job 启动时探测 Redis 不可用 → **直接拒绝启动**并返回明确错误(不在无 checkpoint 能力下假装支持 resume)。
+- **方案 B**:降级路径必须在 `ingestion_task_log` 写一条 `resume_degraded` warning(含原因),使 API 侧能查询到「本次为整跑、无续跑保证」。
+
+两种都保证**不静默**。本期选 A(强信号),B 作为可加的审计记录。
+
+### 6.b R3 不通过的回退(M2)
+若 eino v0.9.12 不支持「全图 interrupt-after-node + ResumeWithData」:
+- 降级为「**只在 DAG 节点上 interrupt**」(Loop/Parallel 内部不 interrupt,整段作为原子单元),或
+- 回退到路线 A 的**轻量版**(仅 progress/log,无 resume)。
+
+> ✅ **R3 已于 2026-07-09 通过**(见 §6 R3 行 + `internal/agent/workflowx/r3_interrupt_test.go`),M2 回退路径**当前不需要**;§8 第 3 步的 resume 循环可按原计划安全推进。
+
+---
+
+## 7. 推荐方案
+
+**续跑走 B,观测走轻量 task_log**:
+
+1. `ProgressCallback` 升级为结构化事件(序号 + 进入/退出 + 退出带输出),`taskLogProgressCallback` 写轻量 `ingestion_task_log`(sink 不存全量 output,见 §5.3)。
+2. `Pipeline.Run` 接 eino interrupt/checkpoint:编译期 `WithInterruptAfterNonTerminalCpn()`(无参)+ `WithCheckPointStore` + `WithCheckPointID(taskID)`;运行期内部 resume 循环(循环顶部先判断遗留中断并恢复);`RunTracker` 状态机驱动跨调用恢复与失效。
+3. 组件(`Parser` 等)**完全不改**、不依赖 `dao`;续跑由框架闸口 + Redis checkpoint 统一负责。
+
+理由:B 复用仓库已建好的 eino 底座(功能完整,仅缺 ingest 用持久化),最省事且对图拓扑正确性最稳;A 的「自研缓存 + 闸口跳过」仅在「无 Redis、必须 DB 无关」的极端约束下才值得。
+
+---
+
+## 8. 实施步骤(建议顺序,含评审修订)
+
+0. **schema 评估与迁移(S1,新增)+ 前端取数契约(Q2/Q3)** ✅ **已实现(entity/DAO/pipeline 落地,dao+pipeline 包测试通过)**:
+ - **表结构(最小迁移,沿用 `ingestion_task_log`,但 `checkpoint` JSON 拆列)**:原 `checkpoint` LONGTEXT(JSON) 按 key 拆成**独立列**便于直接访问与聚合(用户决定):`id` BIGINT 自增 PK;`task_id` VARCHAR(32) 索引;`component_index` INT(0-based 序号,key `index`);`phase` TINYINT(key `phase`,复用 `ProgressPhase`:0=enter / 1=exit / 2=error);`component` VARCHAR(64)(cpnID,key `component`,建议加索引便于聚合);`message` TEXT(key `message`);`BaseModel`(`create_time`/`update_time`/`deleted_at`,时间戳只此一处)。**不再有 `checkpoint` 列**(旧 `{progress,message,create_time}` 整体废弃)。拆列后 `AggregateProgress` 可纯 SQL `GROUP BY phase, component` 完成,无需解析 JSON(见下方端点)。
+ - **老 `progress` 字段兼容**:旧编码 `{progress:0/1/-1, message, create_time}` 原本整体在 `checkpoint` JSON 列内(无独立列)。现改为**拆列**后 `checkpoint` 列直接删除,旧 `IngestionTaskLog.Create` 路径(写 JSONMap)随之废弃;`IngestionTaskLogDAO` 改用直接写列的 `Create`(实体字段即列),无需 `CreateStructured` 双写。需确认现有 API 消费者是否依赖旧 `checkpoint.progress` 编码(见下方端点兼容性),若有则端点层做字段映射兼容。
+ - **总组件数 N(算百分比必需)**:在 `ingestion_task` 表**新增加法列** `component_total INT`(任务创建时由 DSL 节点数写入)。加法列迁移安全,且让"完成百分比"有服务端权威 N。
+ - **前端取数端点(建议)**:
+ - `GET /api/v1/ingestion_task/{task_id}/logs` → 复用 `IngestionTaskLogDAO.ListLogsByTaskID`,**改为按 `id ASC`**(时间正序,日志流用)返回 `{id, task_id, index, phase, component, message, create_time}`。前端按 phase 渲染(0 开始 / 1 完成 / 2 失败)。
+ - `GET /api/v1/ingestion_task/{task_id}/progress` → 服务端聚合 `{total, done, failed, running, percent, status}`。因 `phase`/`component` 已是独立列,`AggregateProgress` 可纯 SQL 完成(无需解析 JSON):按 `component` 取每个组件最新 `phase`(按 `id DESC` 取每组件末行),再 `CASE WHEN 末phase=1 THEN 'done' WHEN 末phase=2 THEN 'failed' ELSE 'running' END` 计数;`percent = done/total*100`;`total` 取 `ingestion_task.component_total`。前端拉进度条不必先拉全量日志。
+ - 产出:migration 脚本(含 `component_total` 加法列)+ API 兼容性结论,进入第 1 步前完成。
+ - **已落地(本次)**:
+ - `entity.IngestionTaskLog`:`Checkpoint JSONMap` → 四列 `ComponentIndex`(INT) / `Phase`(INT) / `Component`(VARCHAR(64),index) / `Message`(TEXT);`entity.IngestionTask` 新增 `ComponentTotal`(INT,default 0)。GORM `AutoMigrate` 自动加列(加法安全)。
+ - `dao`:`IngestionTaskDAO.UpdateComponentTotal(taskID,total)`;`IngestionTaskLogDAO.ListLogsByTaskID` 改 `id ASC`;新增 `TaskProgress{Total,Done,Failed,Running,Percent}` 与 `AggregateProgress(taskID,total)`(子查询取每 component 最新 `id`→按 phase 分类计数;分类**向前兼容** 1c renumber:done=1,failed∈{-1,2})。
+ - `pipeline.Run`:编译后 best-effort `UpdateComponentTotal(taskID, len(canvas.Components))`(DB 为空则跳过)。
+ - ⚠️ 依赖 1c:sink 目前仍写 `Component=""` / `ComponentIndex=0`,故 `AggregateProgress` 的 `GROUP BY component` 在 1c(cpnID 注入)前会退化为单组;method 与 schema 已就绪,待 1c 填列后生效。
+
+1. **结构化 progress 事件(独立、低风险,但先做完影响面评估)** ✅ **已实现(runtime/canvas/pipeline 落地 + runtime/canvas/pipeline 包测试通过;agent/ingestion 整树编译通过)**:
+ - **1a. 影响面清点(已核实)**:`ProgressCallback|TrackProgress|WithProgressCallback|ProgressCallbackFromContext` 全仓仅 `helpers.go`/`helpers_test.go`/`pipeline.go`/`node_body.go` 4 个 Go 文件有真实引用;`file.go`/`tokenizer.go` 经内容搜索**无** `Progress`/`TrackProgress` 引用(§9 标注为旧注释,已不实)。生产可执行调用方仅 `node_body.go`(`TrackProgress` 一处)+ `pipeline.go`(sink);`WithProgressCallback`/`ProgressCallbackFromContext` 签名随类型别名自动迁移,零改动。**无 SDK / 外部调用方**,无需对外征询。
+ - **1b. 向后兼容策略 → 改为干净硬切**:影响面仅 8 处生产 + 4 个测试函数,按 AGENTS.md「优先单路径、删废弃分支」原则**未保留**旧 `ProgressCallback func(int,string)` 适配器(渐进迁移方案被否决,避免遗留 deprecated 双轨)。一次性把 `ProgressCallback` 改为 `func(ProgressEvent)`,并同步重写 `helpers_test.go` 4 个测试。
+ - **1c. 落地(已做)**:
+ - `runtime/helpers.go`:新增 `ProgressPhase`(`PhaseEnter=0`/`PhaseExit=1`/`PhaseError=2`,值稳定并持久化到 `phase` 列,属数据契约)+ `ProgressEvent{Phase, Component, Err}`(`Err` 仅 error 相位非空;**不携带 Output**,见 §5.3);`ProgressCallback` 改为 `func(ProgressEvent)`;`TrackProgress(cpnID, cb, fn)` 发 `ProgressEvent{PhaseEnter}` / `PhaseExit` / `{PhaseError, Err}`(不再拼 `compName Started/Done/:err` 字符串,消息改由 sink 派生)。
+ - `node_body.go:187`:`TrackProgress(componentClass, ...)` → `TrackProgress(cpnID, ...)`,`ProgressEvent.Component` 现填**节点 id**(唯一标识,可区分同名多实例);`componentClass` 仍用于 `resolveTimeoutFromContext`,无冗余。
+ - `pipeline.go`:`taskLogProgressCallback` 改消费 `ProgressEvent`,`componentIndexMap()`(按排序 cpnID 给确定性 0-based 序号,因 map 遍历无序)算 `ComponentIndex`,并写 `Component`/`Phase`(=int(Phase))/`ComponentIndex`/`Message`(消息由相位派生:`cpnID Started`/`Done`/`:err`,保持前端兼容)。`AggregateProgress` 的 `GROUP BY component` 在 1c 后**已生效**(按 cpnID 正确分组)。
+ - ⚠️ **已知不一致(非阻塞)**:`component_total` 在 step 0 取 `len(canvas.Components)`(含 no-op/UserFillUp 节点),而这些节点的 body(`legacyNoOpBody`/`UserFillUpNodeBody`)**不发** `TrackProgress`,故 `done` 计数可能永远 < `total`,进度百分比上限 < 100%。属观测精度问题,留待后续按需把分母改为「实际会发事件的组件数」。
+
+2. **`CompileOptions` 加 `CheckPointID`(R2)** ✅ **已实现(canvas 包测试通过)**:
+ - **关键 API 事实修正**:`compose.WithCheckPointID(id)` 返回的是 **运行期 `compose.Option`**(`checkpoint.go:74`),**不是** `GraphCompileOption`,无法在 `Compile`(`Workflow.Compile(...GraphCompileOption)`)里直接 `append`。因此 step 2 **不**把 `compose.WithCheckPointID` 塞进编译选项,而是:
+ - `CompileOptions` 新增 `CheckPointID string` 字段 + `WithCheckPointID(id)` 选项(仅把 id 记到选项里);
+ - `Compile` 把 `cfg.CheckPointID` 存进返回的 `CompiledCanvas.CheckPointID`(该字段早已存在却从未赋值);
+ - **运行期接线(真正的 `compose.WithCheckPointID`)留到 step 3**:`pipeline.go` 在 `compiled.Workflow.Invoke(runCtx, current, compose.WithCheckPointID(compiled.CheckPointID))` 时传。service 层 `agent.go:1041` 早已自行维护 `cpID=runID` 并 `compose.WithCheckPointID(cpID)`,不受本改动影响(它不读 `compiled.CheckPointID`)。
+ - **无参 `WithInterruptAfterNonTerminalCpn()`(建议1)已实现**:`CompileOptions` 新增 `InterruptAfterNonTerminal bool` + 无参 `WithInterruptAfterNonTerminalCpn()`;`Compile` 内部调用 `computeNonTerminalCpnIDs(c)` 算出「出度>0 的中间节点」(非终态),与调用方传入的 `InterruptAfter` 合并去重后统一 `compose.WithInterruptAfterNodes(...)`。选择规则:**排除终态节点**(无 `Downstream`,避免 Invoke 返回 interrupt 而非完成、并省一轮无意义 ResumeWithData)、**排除 `UserFillUp` 节点**(§4.2.b,它自带 `compose.Interrupt`,不与之重复注册)。`Canvas` 无 `Outputs` 字段,故「非终态」以 `len(Downstream)>0` 为准(与 §4.1.a 出度>0 等价)。
+ - **⚠️ 接线约束**:`WithInterruptAfterNonTerminalCpn()` 一旦被 `pipeline.go` 调用而**尚无 step 3 的 resume 循环**,`Invoke` 会在第一个非终态节点暂停并返回 interrupt 错误,直接破坏 ingestion。故 step 2 **只动 `compile.go` + 单测**,`pipeline.go` 的真正接线(compile 选项 + `Invoke` 传 `compose.WithCheckPointID` + resume 循环)整体归入 **step 3**(R3 gate 之后)。
+ - **单测**:`compile_test.go` 新增 `TestWithCheckPointID_OptionSetsField`、`TestWithInterruptAfterNonTerminalCpn_OptionSetsField`、`TestComputeNonTerminalCpnIDs`(断言 `n1,n2` 命中、`n3/n4` 终态排除、`uf` UserFillUp 排除)、`TestCompile_PropagatesCheckPointID`(编译成功则断言 `CompiledCanvas.CheckPointID==task-9`,编译失败则 skip,与现有 compile_test 忽略编译错误的约定一致)。
+
+3. **`Pipeline.Run` resume 循环 ✅ 已实现(2026-07-09)**:R3 已于 2026-07-09 通过(见 §6 R3 行),无需 M2 回退。落地于 `internal/ingestion/pipeline/pipeline.go`:`Run` 先 `resolveStore()`/`resolveTracker()`(注入优先,否则按 `redis.Get()` 解析),有 store 才编译期接 `WithCheckPointStore`+`WithCheckPointID(p.taskID)`+`WithInterruptAfterNonTerminalCpn()` 进入 resumable 路径;运行期 `for` 循环(`maxResumeRounds=1000` 防呆)**顶部先恢复中断**(优先级:RunTracker `GetInterruptID` 跨进程恢复 > 进程内 `localInterruptID` 兜底),命中 interrupt 后仅 `AttachInterrupt` 持久化、下一轮顶部统一 `ResumeWithData(ctx, id, nil)`(不内联 resume,避免同 ctx 双 resume,依 §4.2 建议2);`RunTracker.Start/MarkSucceeded/MarkFailed` 接入;`cancelled`(`context.Canceled`/`DeadlineExceeded`)分支按 §4.3.b 调 `cleanupCheckpoint`(删 eino checkpoint + `ClearInterruptID`)并 `MarkCancelled`;无 store 时降级为单次 `runPlain`(不破坏无 Redis 的现有测试)。interrupt 捕获用 `canvas.IsInterruptError`/`ExtractInterruptContexts`/`FirstInterruptID`。端到端测试 `TestPipelineRunResumableAutoResumes`(注入 in-memory store,断言每个节点恰好执行 1 次——验证 R3「resume 不重跑」在 pipeline 层成立)。
+
+4. **interrupt id 持久化(M3)✅ 已实现(2026-07-09)**:`internal/agent/canvas/run_tracker.go` 加 `AttachInterrupt/GetInterruptID/ClearInterruptID`,写同一 hash 的 `interrupt_id` 字段(不新增 key);agent/chat 路径不动(S4)。与 step 3 的进程内 `localInterruptID` 兜底共同构成跨/进程内双层恢复。
+
+5. **降级与守卫(M4 + S3)✅ 已实现(2026-07-09)**:
+ - **M4(§6.a 方案 A,可见拒绝,非静默)**:`Pipeline` 加 `requireResume bool` + `WithRequireResume()` 选项 + `var ErrResumeUnavailable = errors.New(...)` sentinel。`Run` 在 `resolveStore()` 之后、`Compile` 之前加检查:当 `requireResume && store==nil`(无注入 store 且无全局 Redis)时返回 `fmt.Errorf("pipeline: Run: %w", ErrResumeUnavailable)`,由调用方 `errors.Is` 识别并拒绝入队(而非静默降级 `runPlain`)。默认(不置 `requireResume`)保持原有静默降级 `runPlain`,不破坏无 Redis 的单元/headless 测试;生产 ingestion 接线时启用 `WithRequireResume()` 即「Redis 不可用 → 拒绝启动」的强信号。
+ - **S3(§4.2.b 方案 A,编译期硬拒绝)**:`internal/agent/canvas/compile.go` 在 `BuildWorkflow` 之前加护栏——当 `cfg.InterruptAfterNonTerminal`(ingestion resume 模式)且 `AutoDiscoverUserFillUpIDs(c)` 非空时,`Compile` 直接返回错误 `"...WithInterruptAfterNonTerminalCpn forbids UserFillUp nodes ... would be mis-resumed with nil data"`。理由:`UserFillUp` 自身发 `compose.Interrupt`(wait-for-user),`runResumable` 的 `IsInterruptError` 全捕获并以 `nil` 自动续跑,会**静默跳过人工交互**;编译期硬拒使其永不发生。先于 step 2 已有的 `computeNonTerminalCpnIDs` 过滤(方案 B,不重复注册)构成双层守卫。
+ - 测试:`pipeline_test.go` 加 `TestPipelineRun_RequireResumeRejectsWithoutStore`(无 store + `WithRequireResume` → `ErrResumeUnavailable`);`compile_test.go` 加 `TestCompile_RejectsUserFillUpInResumeMode`(含 `UserFillUp` + `WithInterruptAfterNonTerminalCpn` → 编译错误且含 "UserFillUp")。`bash build.sh --test ./internal/ingestion/pipeline/... ./internal/agent/canvas/...` 全绿(2026-07-09)。
+
+6. **Spike 验证(§6 R1–R4)通过后,默认开启 checkpoint;否则回退为纯 progress/log(无 resume)**(M2 回退路径)。
+
+---
+
+## 9. 涉及文件与影响面
+
+- **改**:
+ - `internal/agent/runtime/helpers.go`(`ProgressCallback` / `TrackProgress` / `WithProgressCallback` / `ProgressCallbackFromContext` 签名变更)。
+ **影响面(已全仓 grep 核实)**:共 **42 处匹配、6 个文件**,分布如下:
+
+ | 文件 | 匹配数 | 性质 |
+ | --- | --- | --- |
+ | `internal/agent/runtime/helpers.go` | 17 | 被改文件本身(定义+实现+doc) |
+ | `internal/agent/runtime/helpers_test.go` | 14 | **测试回归主成本** |
+ | `internal/ingestion/pipeline/pipeline.go` | 6 | 生产调用方(sink + `WithProgressCallback` 注入) |
+ | `internal/agent/canvas/node_body.go` | 2 | 生产调用方(框架发令) |
+ | `internal/ingestion/component/file.go` | 2 | **仅 doc 注释**,非调用 |
+ | `internal/ingestion/component/tokenizer.go` | 1 | **仅 doc 注释**,非调用 |
+
+ - 生产**可执行**调用方只有 `pipeline.go` + `node_body.go`(共 8 处);`file.go`/`tokenizer.go` 仅为注释,不影响编译。
+ - 6 个文件全部在 `agent runtime / canvas / ingestion` 内,**无 SDK / 外部调用方** → 第 1 步无需对外征询(用户发现 2 担心的「先通知外部」仅当存在外部调用方才需,本次不存在)。
+ - 真正工作量在 `helpers_test.go` 的 14 处测试回归 + 8 处生产调用方改造;采用 §8 第 1b 步的向后兼容适配器降低风险。
+ - `internal/agent/canvas/node_body.go`(发结构化事件;`node_body.go:187` 把 `TrackProgress` 第一参数由 `componentClass` 改为 `cpnID`,见 §5.1)。
+ - `internal/agent/canvas/compile.go`(加 `CheckPointID` 选项 + `WithCheckPointID`;新增**无参** `WithInterruptAfterNonTerminalCpn()` —— `Compile` 内部计算非终态节点 id(出度>0,§4.1.a)并对它们注册 `WithInterruptAfterNodes`,同时按 §4.2.b 排除 `UserFillUp` 节点 / 或与其互斥校验)。
+ - `internal/agent/canvas/run_tracker.go`(新增 `AttachInterrupt` / `GetInterruptID` / `ClearInterruptID`,同 hash 字段)。
+ - `internal/ingestion/pipeline/pipeline.go`(`Run` resume 循环——**循环顶部先 `GetInterruptID` 恢复崩溃遗留中断**、命中后 `AttachInterrupt` 持久化;升级 `taskLogProgressCallback` + `ComponentIndexMap` 注入,§4.2/§5.1;`UserFillUp` 过滤已下沉到 `compile.go`,此处不再计算 `nonTerminalCpnIDs`,§4.2.b)。
+ - `internal/dao`(新增 `IngestionTaskLogDAO` 结构化写入方法 / schema 迁移,S1)。
+- **复用(不改)**:`internal/agent/canvas/checkpoint_store.go`、`internal/agent/canvas/interrupt_resume.go`、`internal/agent/canvas/state_serializer.go`、`runner.go` 的 agent/chat 内存 `interruptIDs`(保留,S4)。
+- **不改**:`internal/ingestion/component/*`、`internal/agent/component/*`(组件零改动)。
+
+---
+
+## 10. 修订记录(v1 → v2,基于评审)
+
+| # | 项 | 优先级 | 修订 |
+| --- | --- | --- | --- |
+| M1 | `ProgressEvent.Index` 不应进共享 runtime 类型 | P0 | 共享类型去除 `Index`;ingestion 包内 `pipelineProgressEvent{Index, Event}` 包装,Index 由 sink 用 `cpnID→index` 映射算出(§5.1/§5.2) |
+| M2 | R3(Loop/Parallel)必须前置 spike | P0 | R3 升为 P0,§8 第 3 步加 R3 gate;新增 §6.b 回退路径 |
+| M3 | interrupt id 复用 RunTracker hash 字段,别加新 key | P1 | §4.4 定为 `AttachInterrupt` 写同一 hash 的 `interrupt_id`,不引入 `agent:cpint:{taskID}` |
+| M4 | Redis 不可用降级要可见 | P1 | §6.a 改为拒绝启动 / 写 `resume_degraded` warning,非静默整跑 |
+| M5 | §5 与 §8 第 1 步 output 携带矛盾 | P1 | 已消解:`ProgressEvent` **不携带 `Output`**(用户决定 resume 不需要,output 回放交给 eino checkpoint),事件层与 sink 层一致「都不存 output」,§5.3 重写为两层共识 |
+| S1 | `ingestion_task_log` schema 兼容性 | P2 | §8 新增第 0 步 schema 评估与迁移;优先新增 DAO 方法 |
+| S2 | succeeded 重跑 vs resume 语义 | P2 | §4.3.a 明确统一语义「按 task_id 重做整图,框架跳过已执行节点」 |
+| S3 | `UserFillUp` 在 ingest DSL 的禁止/过滤 | P2 | §4.2.b 加编译期禁止 / 运行期过滤守卫 |
+| S4 | `runner.go` 内存 `interruptIDs` 处置 | P2 | §4.4 明确 agent/chat 路径不动,本次仅引入 ingest 持久化路径 |
+| S5 | `cancelled` 状态去向 | P2 | §4.3.b 明确 cancelled 默认清 checkpoint+整跑,可选暴露显式 resume 入口 |
+| 排版 | §2 ⚠️/✅ 区分「功能完整」与「持久化到位」 | — | §2 表格重排,分两列表述 |
+| 排版 | §3 体积量化 | — | §3 给出 ballpark(单 task 可达数十 MB) |
+| 排版 | §4.5 第 2 条表述 | — | 澄清「用户意图被升级为框架级 checkpoint,非组件读自己 log」 |
+| 排版 | §9 helpers.go 影响面 | — | §9 列出已知调用方 + 需 grep sweep 的说明 |
+| 发现1 | `realComponentBody` 的 `cpnID` 是闭包参数,`ProgressEvent.Component` 应填 cpnID 而非 componentClass | — | §5.1 改为「调用处第一参数由 componentClass 改 cpnID」,不扩 helper 签名 |
+| 发现2 | `helpers.go` 影响面实为 42 处匹配(6 文件),非「少量」 | — | §9 以全仓 grep 复核:生产可执行调用方仅 pipeline.go+node_body.go(8);file.go/tokenizer.go 仅 doc;helpers_test.go 14 为测试回归主成本;无外部调用方;§8 第 1 步加 1a 影响面清点 + 1b 向后兼容渐进迁移 |
+| 问答1 | `WithInterruptAfter` 与 UserFillUp 的 interrupt 能否共存 | — | §4.2.b 新增「共存原理」:同一 eino interrupt 原语按 id 区分,不重复注册同一节点即可共存;ingestion 排除 UserFillUp 出 nonTerminalCpnIDs;新增 R7 spike |
+| 问答2 | `WithInterruptAfter` 不应传 allCpnIDs | — | §4.1 改为 `nonTerminalCpnIDs`(出度>0 的中间节点),新增 §4.1.a 解释终态节点不应 interrupt 的原因 |
+| 建议1 | `WithInterruptAfter(nonTerminalCpnIDs)` 参数化 → 无参 | — | §4.1 / §4.1.a 改为无参 `WithInterruptAfterNonTerminalCpn()`;`Canvas.Components` 出度>0 的节点集合由 `canvas.Compile` **内部**计算,调用方无需也不能传错;`UserFillUp` 排除(§4.2.b)一并下沉到 `Compile`。§7/§8-3/§9 同步更新 |
+| 建议2 | `Pipeline.Run` 的 for 循环应先判断 interrupt 是否存在 | — | §4.2 循环顶部新增「`GetInterruptID` 读遗留中断 → `ResumeWithData` 恢复 → `ClearInterruptID`」作为每轮首要动作;底部命中 interrupt 只 `AttachInterrupt` 持久化、不内联 resume(避免同一 ctx 重复 resume)。§4.3 状态机只做 keep/delete,`running` 的恢复入口收敛到循环顶部一处,杜绝与 §4.2 两处 resume 漂移 |
+| 决策 | 选择路线 B | — | 路线 B(eino interrupt-after-node + Redis checkpoint)正式定为方案;§5/§8 的 progress 改进对 B 同样必做(原本标注 A/B 兼容,现仅服务于 B) |
+| 决策 | `ProgressEvent` 不再存储 `Output` | — | §5 开头、`§5.1` 类型定义、`§5.3` 落库策略、`§8 第1c 步` 全部改为事件与 sink **均不携带/不落库 Output**;理由:resume 由 eino checkpoint 负责,progress 仅观测,不需要 output(同时彻底消解原 M5 矛盾) |
+| 决策 | `ProgressEvent` 不携带时间戳(Q1) | — | §5.3 新增:event 不带时间戳;时间戳只由 `BaseModel.create_time` 自动写入(秒级),排序以自增 `id` 为准(复用 `LatestLogByTaskID` 的 `id DESC` tie-break);删除现有 `pipeline.go` 把 create_time 塞进 checkpoint JSON 的冗余 |
+| 决策 | schema 与前端取数契约(Q2/Q3) | — | §8 第0步补:沿用 `ingestion_task_log` 表、`checkpoint` JSON 改为 `{index,phase,component,message}`;`ingestion_task` 新增加法列 `component_total`;新增 `GET .../logs`(`id ASC`)+ `GET .../progress`(`{total,done,failed,running,percent,status}` 服务端聚合)端点契约 |
+| 决策 | `ingestion_task_log.checkpoint` 拆成独立列 | — | §8 第0步 / §5.3 / §8-1c:`checkpoint` LONGTEXT(JSON) 按 key 拆为 `component_index`(INT) / `phase`(TINYINT) / `component`(VARCHAR,建议索引) / `message`(TEXT) 四列,删除 `checkpoint` 列;`AggregateProgress` 改为纯 SQL `GROUP BY phase,component`(无需解析 JSON);旧 `Create`(写 JSONMap) 路径废弃,无需 `CreateStructured` 双写 |
+| 决策 | §8 第1步 结构化 progress 事件(干净硬切,非渐进迁移) | — | §8 第1步 / §5.1:`ProgressCallback` 改为 `func(ProgressEvent)`(新增 `ProgressPhase` 枚举 0/1/2 + `ProgressEvent{Phase,Component,Err}`,不携带 Output/时间戳);`TrackProgress(cpnID,cb,fn)` 发 enter/exit/error 事件;`node_body.go` 第一参数 `componentClass`→`cpnID`;`pipeline.go` sink 消费 `ProgressEvent` 并由 `componentIndexMap()`(排序 cpnID 确定性序号)填 `ComponentIndex`+写 `Component`/`Phase`;未保留 1b 适配器(按 AGENTS.md 单路径原则);`AggregateProgress` 的 `GROUP BY component` 在 1c 后已生效 |
+| 决策 | §8 第2步 `CompileOptions.CheckPointID` + 无参 `WithInterruptAfterNonTerminalCpn()` | — | §8 第2步 / §4.1.a / §4.2.b:①**API 事实修正**——`compose.WithCheckPointID` 是运行期 `compose.Option`(非 `GraphCompileOption`),无法在 `Compile` 内直接 append;故 `WithCheckPointID(id)` 仅记到 `CompileOptions.CheckPointID`,`Compile` 存进 `CompiledCanvas.CheckPointID`,**真正 `compose.WithCheckPointID` 在 `Invoke` 侧接线留 step 3**;service 层 `agent.go:1041` 自行维护 `cpID=runID`,不受影响。②无参 `WithInterruptAfterNonTerminalCpn()` → `Compile` 内部 `computeNonTerminalCpnIDs(c)` 算「出度>0 的中间节点」(排除终态与 `UserFillUp`),与调用方 `InterruptAfter` 合并去重后统一 `compose.WithInterruptAfterNodes`。③**接线约束**:该选项未接入 `pipeline.go`(无 step 3 resume 循环会破坏 ingestion),整体接线归 step 3。④单测覆盖选项 setter + `computeNonTerminalCpnIDs` + 容错传播 |
+| 决策 | §6 R3 spike 结论(P0 gate 已通过) | — | R3 / DAG+Loop+Parallel / `WithInterruptAfterNodes`+`ResumeWithData`:①新增 `internal/agent/workflowx/r3_interrupt_test.go` 五个 eino 集成用例(DAG 链 A→B→C、`A→loop(B→C)→D` 中断在 A、`A→loop→D` 中断在 loop 节点本身、`A→parallel(B)→D`、以及跨进程「重编译图+同 CheckPointID」恢复),全部 `bash build.sh --test ./internal/agent/workflowx/...` 通过(2026-07-09);②核心结论:已完成的节点 resume 后**不重跑**(节点 counter 恒为 1),Loop/Parallel 正确重入或跳过,**无需 M2 回退**,§8 第 3 步按原计划推进;③关键实现约束:after-node interrupt 仅在**有状态图**(`WithGenLocalState`,与 `canvas.BuildWorkflow`/`CanvasState` 一致)下才被包成 `*interruptError` 并被 `ExtractInterruptInfo` 识别;无状态图返回裸 `*core.InterruptSignal`(`ExtractInterruptInfo`→nil)。自定义 state 类型须 `compose.RegisterSerializableType[T]`(仿 `runtime.CanvasState`),否则 checkpoint marshal 报 `unknown type` |
+| 决策 | §8 第3步+第4步(M3)实现:Pipeline.Run resume 循环 + interrupt id 持久化 | — | ①`internal/ingestion/pipeline/pipeline.go`:`Run` 改为 `resolveStore()`/`resolveTracker()`(注入优先,否则 `redis.Get()` 解析)→ 有 store 才进 resumable 路径(编译接 `WithCheckPointStore`+`WithCheckPointID(p.taskID)`+`WithInterruptAfterNonTerminalCpn()`),`for` 循环(`maxResumeRounds=1000`)顶部恢复中断(RunTracker `GetInterruptID` 跨进程 > `localInterruptID` 进程内兜底),命中仅 `AttachInterrupt` 持久化、下轮顶部 `ResumeWithData` 恢复(不内联 resume);`RunTracker.Start/MarkSucceeded/MarkFailed/MarkCancelled` 接入;`cancelled` 分支按 §4.3.b 调 `cleanupCheckpoint` 删 eino checkpoint+`ClearInterruptID`;无 store 降级 `runPlain` 单次 Invoke;`NewPipelineFromDSL` 加 `...PipelineOption`(`WithCheckPointStore`/`WithRunTracker` 注入)。②`internal/agent/canvas/run_tracker.go` 加 `AttachInterrupt/GetInterruptID/ClearInterruptID`(同 hash `interrupt_id` 字段)。③测试:`pipeline_test.go` 加 `TestPipelineRunResumableAutoResumes`(注入 in-memory store,断言每节点恰好执行 1 次);`bash build.sh --test ./internal/ingestion/pipeline/... ./internal/agent/canvas/...` 全绿(2026-07-09) |
+| 决策 | §8 第5步(M4+S3)实现:可见降级 + UserFillUp 守卫 | — | ①**M4(§6.a 方案 A 可见拒绝)**:`internal/ingestion/pipeline/pipeline.go` 加 `requireResume bool` 字段 + `WithRequireResume()` 选项 + `var ErrResumeUnavailable = errors.New("resume unavailable: no checkpoint store (Redis down or not configured)")` sentinel;`Run` 在 `resolveStore()` 后、`Compile` 前检查 `requireResume && store==nil` → 返回 `fmt.Errorf("pipeline: Run: %w", ErrResumeUnavailable)`,由调用方 `errors.Is` 识别并拒绝入队(而非静默 `runPlain`)。默认不置 `requireResume` 保持静默降级(覆盖无 Redis 的单元/headless 测试);生产 ingestion 接线时启用 `WithRequireResume()` 即「Redis 不可用 → 拒绝启动」强信号。②**S3(§4.2.b 方案 A 编译期硬拒)**:`internal/agent/canvas/compile.go` 在 `BuildWorkflow` 前加护栏——`cfg.InterruptAfterNonTerminal && len(AutoDiscoverUserFillUpIDs(c))>0` → 返回 `"...WithInterruptAfterNonTerminalCpn forbids UserFillUp nodes ... would be mis-resumed with nil data"`;理由:`UserFillUp` 自发包 `compose.Interrupt`,`runResumable` 全捕获并以 `nil` 续跑会静默跳过人工交互,硬拒不使其发生;与 step 2 的 `computeNonTerminalCpnIDs` 过滤(方案 B)构成双层守卫。③测试:`pipeline_test.go` 加 `TestPipelineRun_RequireResumeRejectsWithoutStore`;`compile_test.go` 加 `TestCompile_RejectsUserFillUpInResumeMode`;`bash build.sh --test ./internal/ingestion/pipeline/... ./internal/agent/canvas/...` 全绿(2026-07-09) |
diff --git a/internal/ingestion/pipeline/pipeline.go b/internal/ingestion/pipeline/pipeline.go
index 0c5e273db2..7857916195 100644
--- a/internal/ingestion/pipeline/pipeline.go
+++ b/internal/ingestion/pipeline/pipeline.go
@@ -19,25 +19,89 @@ package pipeline
import (
"context"
"encoding/json"
+ "errors"
"fmt"
+ "sort"
"time"
"ragflow/internal/agent/canvas"
_ "ragflow/internal/agent/component"
"ragflow/internal/agent/runtime"
+ "ragflow/internal/common"
+ "ragflow/internal/dao"
+ redis2 "ragflow/internal/engine/redis"
+ "ragflow/internal/entity"
+
+ "github.com/cloudwego/eino/compose"
)
// Pipeline is a compiled ingestion canvas plus task-scoped metadata.
type Pipeline struct {
- taskID string
+ taskID string
+ documentID string // owning document; progress is mirrored back to the
+ // document table so the existing GET /api/v1/datasets/{dataset_id}/documents
+ // endpoint (which reads document.progress/run/progress_msg) reflects the
+ // live Go pipeline progress without a bespoke endpoint (plan §8).
canvas *canvas.Canvas
- factory runtime.ComponentFactory
+ store canvas.CheckPointStore // optional injected; nil -> resolve at Run
+ tracker *canvas.RunTracker // optional injected; nil -> resolve at Run
+ // requireResume, when true, makes Run refuse to start if no checkpoint
+ // store can be resolved (no injected store AND no global Redis client).
+ // Plan §6.a M4 方案 A: a deployment that cannot persist checkpoints must
+ // not silently degrade to a non-resumable run — it must surface a clear,
+ // distinguishable error so the caller knows resume is unavailable.
+ requireResume bool
+ factory runtime.ComponentFactory // optional instance-scoped component factory
+}
+
+// ErrResumeUnavailable is returned by Run when WithRequireResume is set but no
+// checkpoint store can be resolved (plan §6.a M4). Callers can test for it with
+// errors.Is to surface a "resume unavailable" condition instead of a generic
+// failure (e.g. refuse to enqueue the task rather than start a non-resumable
+// run).
+var ErrResumeUnavailable = errors.New("resume unavailable: no checkpoint store (Redis down or not configured)")
+
+// PipelineOption mutates a Pipeline before Run. Used to inject test doubles
+// (in-memory store / miniredis tracker) or dedicated Redis pools.
+type PipelineOption func(*Pipeline)
+
+// WithCheckPointStore injects a checkpoint store. When unset, Run resolves
+// one from the global Redis client (and degrades to a non-resumable run when
+// Redis is unavailable — plan §6.a).
+func WithCheckPointStore(s canvas.CheckPointStore) PipelineOption {
+ return func(p *Pipeline) { p.store = s }
+}
+
+// WithRunTracker injects a RunTracker for interrupt-id persistence / crash
+// recovery. When unset, Run resolves one from the global Redis client.
+func WithRunTracker(t *canvas.RunTracker) PipelineOption {
+ return func(p *Pipeline) { p.tracker = t }
+}
+
+// WithRequireResume makes Run refuse to start when no checkpoint store can be
+// resolved (no injected store AND no global Redis client). This is plan §6.a
+// M4 方案 A: a deployment that cannot persist checkpoints must not silently
+// degrade to a non-resumable run — it must surface a clear, distinguishable
+// error (ErrResumeUnavailable) so the caller knows resume is unavailable.
+// Production ingestion wiring sets this; unit tests leave it off to exercise
+// the non-resumable runPlain fallback.
+func WithRequireResume() PipelineOption {
+ return func(p *Pipeline) { p.requireResume = true }
+}
+
+// WithDocumentID binds the pipeline's owning document so progress can be
+// mirrored back into the document table (document.progress / run /
+// progress_msg) — the canonical store the document-list endpoint serves.
+// Pass the empty string to disable the mirror (e.g. headless/test runs where
+// the document row is not materialized).
+func WithDocumentID(docID string) PipelineOption {
+ return func(p *Pipeline) { p.documentID = docID }
}
// NewPipelineFromDSL compiles the canonical ingestion canvas DSL.
// It accepts either the inner canvas DSL or the template wrapper whose
// top-level `dsl` field carries that canvas.
-func NewPipelineFromDSL(dsl []byte, taskID string) (*Pipeline, error) {
+func NewPipelineFromDSL(dsl []byte, taskID string, opts ...PipelineOption) (*Pipeline, error) {
var raw map[string]any
if err := json.Unmarshal(dsl, &raw); err != nil {
return nil, fmt.Errorf("pipeline: decode DSL: %w", err)
@@ -50,10 +114,14 @@ func NewPipelineFromDSL(dsl []byte, taskID string) (*Pipeline, error) {
if err != nil {
return nil, fmt.Errorf("pipeline: decode canvas DSL: %w", err)
}
- return &Pipeline{
+ p := &Pipeline{
taskID: taskID,
canvas: cnv,
- }, nil
+ }
+ for _, o := range opts {
+ o(p)
+ }
+ return p, nil
}
// WithComponentFactory installs an instance-scoped factory override for this
@@ -111,6 +179,11 @@ func stageTimeout() time.Duration {
var defaultStageTimeout = 60 * time.Second
+// defaultCheckpointTTL is the expiry applied to the eino checkpoint payload
+// and the RunTracker hash. A finished run's checkpoint is deleted on success;
+// the TTL only guards against leaks from crashed runs that never clean up.
+var defaultCheckpointTTL = 24 * time.Hour
+
// Run executes the full ingestion graph described by the canonical DSL.
// There is no pipeline-layer partial resume entry point: execution always
// starts from the graph entry and component-level replay decisions belong to
@@ -133,25 +206,335 @@ func (p *Pipeline) Run(ctx context.Context, inputs map[string]any) (map[string]a
if p.factory != nil {
compileCtx = canvas.WithComponentFactory(compileCtx, p.factory)
}
- compiled, err := canvas.Compile(compileCtx, p.canvas)
+
+ // Resolve the checkpoint store + run tracker. Resume (interrupt-after
+ // non-terminal node) requires a checkpoint store to persist the resume
+ // point; without one we fall back to a single non-resumable Invoke
+ // (plan §6.a degrade — progress stays observable, the run just cannot
+ // pause/resume across nodes).
+ store := p.resolveStore()
+ tracker := p.resolveTracker()
+
+ // M4 (plan §6.a 方案 A): refuse to start when resume is required but no
+ // checkpoint store is resolvable. A Redis-less deployment must not pretend
+ // the task is resumable; it must report the gap clearly so the caller can
+ // refuse to enqueue the task instead of silently running a non-resumable
+ // run (which would violate "re-run same task, completed components not
+ // redone").
+ if p.requireResume && store == nil {
+ return nil, fmt.Errorf("pipeline: Run: %w", ErrResumeUnavailable)
+ }
+ resumable := store != nil
+
+ var compileOpts []canvas.CompileOption
+ if resumable {
+ compileOpts = append(compileOpts,
+ canvas.WithCheckPointStore(store),
+ canvas.WithCheckPointID(p.taskID),
+ canvas.WithInterruptAfterNonTerminalCpn(),
+ )
+ }
+ compiled, err := canvas.Compile(compileCtx, p.canvas, compileOpts...)
if err != nil {
return nil, fmt.Errorf("pipeline: Run: compile canvas: %w", err)
}
+ // Record the component count as the authoritative denominator for
+ // progress percentage. Best-effort: a DB failure (or headless run
+ // with no DB) must not abort the pipeline — progress is observability.
+ if dao.DB != nil {
+ total := len(p.canvas.Components)
+ if err := dao.NewIngestionTaskDAO().UpdateComponentTotal(p.taskID, total); err != nil {
+ common.Error(fmt.Sprintf("pipeline: update component_total for task %s failed: %v", p.taskID, err), err)
+ }
+ }
+
runState := canvas.NewCanvasState("", p.taskID)
runCtx := canvas.WithState(ctx, runState)
runCtx = canvas.WithComponentTimeoutOverride(runCtx, stageTimeout())
+ // Framework-level progress fan-out: the canvas framework
+ // (realComponentBody) pulls this callback from ctx via
+ // runtime.ProgressCallbackFromContext and records every component
+ // start/done/fail event as an ingestion_task_log row. The callback
+ // is nil when the DB is not initialized (unit tests, headless
+ // runs), in which case TrackProgress is a no-op — progress is an
+ // observability concern, not a data dependency.
+ runCtx = runtime.WithProgressCallback(runCtx, p.taskLogProgressCallback())
current := cloneMapOrEmpty(inputs)
+
+ if !resumable {
+ return p.runPlain(runCtx, current, compiled, tracker, runState)
+ }
+
+ // Resumable path: record the run, then loop Invoke until the graph
+ // completes or a non-resumable error surfaces.
+ if tracker != nil {
+ if err := tracker.Start(ctx, p.taskID, "", "", ""); err != nil {
+ common.Error(fmt.Sprintf("pipeline: RunTracker.Start for task %s failed: %v", p.taskID, err), err)
+ }
+ }
+ return p.runResumable(ctx, runCtx, current, compiled, store, tracker, runState)
+}
+
+// resolveStore returns the injected store, or a Redis-backed one when the
+// global Redis client is available. Returns nil (degraded, non-resumable)
+// when neither is present.
+func (p *Pipeline) resolveStore() canvas.CheckPointStore {
+ if p.store != nil {
+ return p.store
+ }
+ if redis2.Get() != nil {
+ return canvas.NewRedisCheckPointStore(defaultCheckpointTTL)
+ }
+ return nil
+}
+
+// resolveTracker mirrors resolveStore for the RunTracker.
+func (p *Pipeline) resolveTracker() *canvas.RunTracker {
+ if p.tracker != nil {
+ return p.tracker
+ }
+ if redis2.Get() != nil {
+ return canvas.NewRunTracker(defaultCheckpointTTL)
+ }
+ return nil
+}
+
+// runPlain executes a single Invoke with no checkpoint/resume. Used when no
+// checkpoint store is available; progress is still recorded via the sink.
+func (p *Pipeline) runPlain(runCtx context.Context, current map[string]any, compiled *canvas.CompiledCanvas, tracker *canvas.RunTracker, runState *canvas.CanvasState) (map[string]any, error) {
out, err := compiled.Workflow.Invoke(runCtx, current)
if err != nil {
+ if errors.Is(runCtx.Err(), context.Canceled) || errors.Is(runCtx.Err(), context.DeadlineExceeded) {
+ if tracker != nil {
+ _ = tracker.MarkCancelled(runCtx, p.taskID)
+ }
+ return current, fmt.Errorf("pipeline: run cancelled: %w", runCtx.Err())
+ }
+ if tracker != nil {
+ _ = tracker.MarkFailed(runCtx, p.taskID, err.Error())
+ }
return current, fmt.Errorf("pipeline: run canvas workflow: %w", err)
}
+ if tracker != nil {
+ _ = tracker.MarkSucceeded(runCtx, p.taskID)
+ }
+ return finalizeResult(current, out, runState), nil
+}
+
+// runResumable drives the graph with eino's interrupt-after-node + resume
+// loop (plan §8 step 3). Every non-terminal-node pause is auto-resumed with
+// nil data (ingestion resume needs no user input). The loop's TOP reads any
+// persisted interrupt id — from the RunTracker (cross-process crash
+// recovery) or an in-process fallback — and resumes; the BOTTOM only persists
+// the id, never inline-resumes (avoids double-resuming one ctx, plan §4.2
+// 建议2).
+func (p *Pipeline) runResumable(ctx context.Context, runCtx context.Context, current map[string]any, compiled *canvas.CompiledCanvas, store canvas.CheckPointStore, tracker *canvas.RunTracker, runState *canvas.CanvasState) (map[string]any, error) {
+ cpID := compiled.CheckPointID
+ var localInterruptID string // in-process resume fallback when tracker is nil
+ invokeInput := current
+
+ const maxResumeRounds = 1000
+ for round := 0; round < maxResumeRounds; round++ {
+ // TOP: recover the pending interrupt (crash recovery or in-process).
+ resumeID := ""
+ if tracker != nil {
+ if id, ok, _ := tracker.GetInterruptID(ctx, cpID); ok && id != "" {
+ resumeID = id
+ }
+ }
+ if resumeID == "" {
+ resumeID = localInterruptID
+ }
+ if resumeID != "" {
+ runCtx = compose.ResumeWithData(runCtx, resumeID, nil)
+ invokeInput = nil // resume restores the graph input from checkpoint
+ }
+
+ out, invokeErr := compiled.Workflow.Invoke(runCtx, invokeInput, compose.WithCheckPointID(cpID))
+ if invokeErr == nil {
+ if tracker != nil {
+ _ = tracker.ClearInterruptID(ctx, cpID)
+ _ = tracker.MarkSucceeded(ctx, cpID)
+ }
+ return finalizeResult(current, out, runState), nil
+ }
+
+ // Cancellation (plan §4.3.b): wipe the checkpoint and mark cancelled.
+ if errors.Is(ctx.Err(), context.Canceled) || errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ p.cleanupCheckpoint(ctx, store, tracker, cpID)
+ if tracker != nil {
+ _ = tracker.MarkCancelled(ctx, cpID)
+ }
+ return current, fmt.Errorf("pipeline: run cancelled: %w", ctx.Err())
+ }
+
+ if !canvas.IsInterruptError(invokeErr) {
+ if tracker != nil {
+ _ = tracker.MarkFailed(ctx, cpID, invokeErr.Error())
+ }
+ return current, fmt.Errorf("pipeline: run canvas workflow: %w", invokeErr)
+ }
+
+ // Paused at a non-terminal node: persist for crash recovery, then
+ // resume on the next loop iteration's TOP.
+ ctxs := canvas.ExtractInterruptContexts(invokeErr)
+ id := canvas.FirstInterruptID(ctxs)
+ localInterruptID = id
+ if tracker != nil {
+ if err := tracker.AttachInterrupt(ctx, cpID, id); err != nil {
+ common.Error(fmt.Sprintf("pipeline: AttachInterrupt for task %s failed: %v", p.taskID, err), err)
+ }
+ }
+ }
+ return current, fmt.Errorf("pipeline: run exceeded max resume rounds (%d) for task %s", maxResumeRounds, p.taskID)
+}
+
+// cleanupCheckpoint wipes the eino checkpoint payload and the persisted
+// interrupt id (plan §4.3.b cancelled path).
+func (p *Pipeline) cleanupCheckpoint(ctx context.Context, store canvas.CheckPointStore, tracker *canvas.RunTracker, cpID string) {
+ if store != nil {
+ if err := store.Delete(ctx, cpID); err != nil {
+ common.Error(fmt.Sprintf("pipeline: delete checkpoint %s failed: %v", cpID, err), err)
+ }
+ }
+ if tracker != nil {
+ _ = tracker.ClearInterruptID(ctx, cpID)
+ }
+}
+
+// finalizeResult merges the graph output into the input map and attaches the
+// canvas state snapshot — the shared success payload for both run paths.
+func finalizeResult(current, out map[string]any, runState *canvas.CanvasState) map[string]any {
if out == nil {
current["state"] = runState.Snapshot()
- return current, nil
+ return current
}
merged := mergeInto(current, out)
merged["state"] = runState.Snapshot()
- return merged, nil
+ return merged
+}
+
+// taskLogProgressCallback returns a runtime.ProgressCallback that appends
+// an ingestion_task_log row for every component progress event emitted by
+// the canvas framework (component start = 0, done = 1, fail = -1). Progress
+// is a framework-level concern owned by realComponentBody; this callback is
+// the ingestion-specific sink that turns those events into durable task
+// logs that the API can later read back (dao.IngestionTaskLogDAO).
+//
+// The write is best-effort: a DB failure is logged and never aborts the
+// pipeline. When the DAO/DB has not been initialized (unit tests, headless
+// runs) the callback is nil, so TrackProgress becomes a no-op and the
+// pipeline stays DB-independent.
+// componentIndexMap builds a deterministic cpnID → 0-based-index map for
+// the task's canvas. Map iteration order is non-deterministic in Go, so
+// the cpnIDs are sorted to keep the index stable across runs. The index is
+// ingestion-proprietary (plan §5.1 M1) and computed here at the sink,
+// never carried on the shared runtime.ProgressEvent.
+func (p *Pipeline) componentIndexMap() map[string]int {
+ ids := make([]string, 0, len(p.canvas.Components))
+ for id := range p.canvas.Components {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ m := make(map[string]int, len(ids))
+ for i, id := range ids {
+ m[id] = i
+ }
+ return m
+}
+
+// taskLogProgressCallback returns a runtime.ProgressCallback that appends
+// an ingestion_task_log row for every component progress event emitted by
+// the canvas framework. Progress is a framework-level concern owned by
+// realComponentBody; this callback is the ingestion-specific sink that
+// turns those events into durable task logs the API can read back
+// (dao.IngestionTaskLogDAO).
+//
+// The event carries the node id (cpnID) and phase. The sink derives:
+// - ComponentIndex from the task's ComponentIndexMap (ingestion-only);
+// - Message from the phase + cpnID (+ error), mirroring the legacy
+// "cpnID Started/Done" / "cpnID: <err>" strings the frontend expects.
+//
+// The write is best-effort: a DB failure is logged and never aborts the
+// pipeline. When the DAO/DB has not been initialized (unit tests, headless
+// runs) the callback is nil, so TrackProgress becomes a no-op and the
+// pipeline stays DB-independent.
+func (p *Pipeline) taskLogProgressCallback() runtime.ProgressCallback {
+ if dao.DB == nil {
+ return nil
+ }
+ logDAO := dao.NewIngestionTaskLogDAO()
+ docDAO := dao.NewDocumentDAO()
+ indexMap := p.componentIndexMap()
+ // total is the authoritative denominator (plan §8). After the
+ // UserFillUp/legacy-no-op guard in Compile, every component in the canvas
+ // reports progress, so len(Components) == component_total and the
+ // aggregate percent can reach 100%.
+ total := len(p.canvas.Components)
+ return func(ev runtime.ProgressEvent) {
+ var msg string
+ switch ev.Phase {
+ case runtime.PhaseEnter:
+ msg = ev.Component + " Started"
+ case runtime.PhaseExit:
+ msg = ev.Component + " Done"
+ case runtime.PhaseError:
+ if ev.Err != nil {
+ msg = ev.Component + ": " + ev.Err.Error()
+ } else {
+ msg = ev.Component + " Error"
+ }
+ }
+ entry := &entity.IngestionTaskLog{
+ TaskID: p.taskID,
+ Checkpoint: entity.JSONMap{},
+ ComponentIndex: indexMap[ev.Component],
+ Phase: int(ev.Phase),
+ Component: ev.Component,
+ Message: msg,
+ }
+ if err := logDAO.Create(entry); err != nil {
+ common.Error(fmt.Sprintf("pipeline: write ingestion_task_log for task %s failed: %v", p.taskID, err), err)
+ }
+ // Mirror progress into the document table so the existing
+ // GET /api/v1/datasets/{dataset_id}/documents endpoint (which reads
+ // document.progress/run/progress_msg) reflects live Go pipeline
+ // progress. Best-effort: a DB failure is logged and never aborts the
+ // pipeline. Skipped when no owning document is bound (headless runs).
+ if p.documentID == "" {
+ return
+ }
+ progress, run := p.deriveDocumentProgress(logDAO, total)
+ updates := map[string]interface{}{
+ "progress": progress,
+ "run": run,
+ "progress_msg": msg,
+ }
+ if err := docDAO.UpdateByID(p.documentID, updates); err != nil {
+ common.Error(fmt.Sprintf("pipeline: mirror progress to document %s for task %s failed: %v", p.documentID, p.taskID, err), err)
+ }
+ }
+}
+
+// deriveDocumentProgress computes the document-level progress (0~1) and run
+// label ("0".."4", matching Python's document.run enum) from the aggregated
+// ingestion_task_log. It reads the freshly-written log row back so the value
+// is correct across resume rounds and crash recovery (plan §8).
+func (p *Pipeline) deriveDocumentProgress(logDAO *dao.IngestionTaskLogDAO, total int) (float64, string) {
+ agg, err := logDAO.AggregateProgress(p.taskID, total)
+ if err != nil || agg == nil || total <= 0 {
+ return 0, "0"
+ }
+ run := "0" // UNSTART
+ switch {
+ case agg.Failed > 0:
+ run = "4" // FAIL
+ case agg.Done == total:
+ run = "3" // DONE
+ case agg.Done > 0 || agg.Running > 0:
+ run = "1" // RUNNING
+ }
+ return agg.Percent / 100, run
}
diff --git a/internal/ingestion/pipeline/pipeline_test.go b/internal/ingestion/pipeline/pipeline_test.go
index ec0eb86a30..1863d20aa6 100644
--- a/internal/ingestion/pipeline/pipeline_test.go
+++ b/internal/ingestion/pipeline/pipeline_test.go
@@ -18,6 +18,7 @@ package pipeline
import (
"context"
+ "errors"
"fmt"
"sync"
"testing"
@@ -28,10 +29,12 @@ import (
type mockCanvasStage struct {
output map[string]any
called bool
+ calls int
}
func (m *mockCanvasStage) Invoke(_ context.Context, inputs map[string]any) (map[string]any, error) {
m.called = true
+ m.calls++
out := cloneMapOrEmpty(inputs)
for k, v := range m.output {
out[k] = v
@@ -163,13 +166,43 @@ func (s *factorySentinelStage) Invoke(_ context.Context, inputs map[string]any)
return out, nil
}
-func TestPipelineRun_InstanceFactoryOverridesDefaultFactory(t *testing.T) {
- origFactory := runtime.DefaultFactory()
- runtime.SetDefaultFactory(func(_ string, _ map[string]any) (runtime.Component, error) {
- return &factorySentinelStage{marker: "default"}, nil
- })
- defer runtime.SetDefaultFactory(origFactory)
+// memCheckpointStore is a thread-safe in-memory canvas.CheckPointStore used
+// to exercise the resumable run path without Redis.
+type memCheckpointStore struct {
+ mu sync.Mutex
+ data map[string][]byte
+}
+
+func newMemCheckpointStore() *memCheckpointStore {
+ return &memCheckpointStore{data: map[string][]byte{}}
+}
+func (s *memCheckpointStore) Get(_ context.Context, id string) ([]byte, bool, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ v, ok := s.data[id]
+ return v, ok, nil
+}
+
+func (s *memCheckpointStore) Set(_ context.Context, id string, payload []byte) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ cp := make([]byte, len(payload))
+ copy(cp, payload)
+ s.data[id] = cp
+ return nil
+}
+
+func (s *memCheckpointStore) Delete(_ context.Context, id string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ delete(s.data, id)
+ return nil
+}
+
+// TestPipelineRun_InstanceFactoryOverridesDefaultFactory verifies that a
+// pipeline-scoped component factory can provide task-specific components.
+func TestPipelineRun_InstanceFactoryOverridesDefaultFactory(t *testing.T) {
pipe, err := NewPipelineFromDSL([]byte(`{
"dsl": {
"components": {
@@ -271,3 +304,75 @@ func TestPipelineRun_TaskScopedFactoriesDoNotLeakAcrossConcurrentPipelines(t *te
t.Fatalf("markers = %#v, want one A and one B", got)
}
}
+
+func TestPipelineRunResumableAutoResumes(t *testing.T) {
+ stageA := &mockCanvasStage{output: map[string]any{"a": 1}}
+ stageB := &mockCanvasStage{output: map[string]any{"b": 2}}
+
+ const (
+ nameA = "p.ResumeStageA"
+ nameB = "p.ResumeStageB"
+ )
+ runtime.MustRegister(nameA, runtime.CategoryIngestion,
+ func(_ string, _ map[string]any) (runtime.Component, error) { return stageA, nil },
+ runtime.Metadata{Version: "1.0.0"})
+ runtime.MustRegister(nameB, runtime.CategoryIngestion,
+ func(_ string, _ map[string]any) (runtime.Component, error) { return stageB, nil },
+ runtime.Metadata{Version: "1.0.0"})
+
+ pipe, err := NewPipelineFromDSL([]byte(`{
+ "dsl": {
+ "components": {
+ "begin": {"obj": {"component_name": "Begin", "params": {}}, "downstream": ["a"]},
+ "a": {"obj": {"component_name": "`+nameA+`", "params": {}}, "upstream": ["begin"], "downstream": ["b"]},
+ "b": {"obj": {"component_name": "`+nameB+`", "params": {}}, "upstream": ["a"]}
+ },
+ "path": ["begin", "a", "b"],
+ "graph": {"nodes": []}
+ }
+ }`), "task-resume", WithCheckPointStore(newMemCheckpointStore()))
+ if err != nil {
+ t.Fatalf("NewPipelineFromDSL: %v", err)
+ }
+
+ out, err := pipe.Run(context.Background(), map[string]any{"name": "doc-resume"})
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if !stageA.called || !stageB.called {
+ t.Fatalf("expected both stages to run, got A=%v B=%v", stageA.called, stageB.called)
+ }
+ // No re-run on resume: each node must execute exactly once.
+ if stageA.calls != 1 || stageB.calls != 1 {
+ t.Fatalf("expected each stage to run exactly once, got A.calls=%d B.calls=%d", stageA.calls, stageB.calls)
+ }
+ if out == nil {
+ t.Fatal("expected non-nil output")
+ }
+}
+
+// TestPipelineRun_RequireResumeRejectsWithoutStore verifies M4 (plan §6.a
+// 方案 A): with WithRequireResume set and no checkpoint store resolvable (no
+// injected store, no global Redis in unit scope), Run must refuse to start
+// and return ErrResumeUnavailable — a clear, distinguishable signal — rather
+// than silently degrading to a non-resumable runPlain. The reject fires
+// before compile, so the DSL does not need a runnable graph.
+func TestPipelineRun_RequireResumeRejectsWithoutStore(t *testing.T) {
+ pipe, err := NewPipelineFromDSL([]byte(`{
+ "dsl": {
+ "components": {
+ "begin": {"obj": {"component_name": "Begin", "params": {}}, "downstream": ["a"]},
+ "a": {"obj": {"component_name": "p.Docx", "params": {}}, "upstream": ["begin"]}
+ },
+ "path": ["begin", "a"],
+ "graph": {"nodes": []}
+ }
+ }`), "task-req-resume", WithRequireResume())
+ if err != nil {
+ t.Fatalf("NewPipelineFromDSL: %v", err)
+ }
+ _, err = pipe.Run(context.Background(), map[string]any{"name": "doc"})
+ if !errors.Is(err, ErrResumeUnavailable) {
+ t.Fatalf("expected ErrResumeUnavailable, got %v", err)
+ }
+}
diff --git a/internal/parser/parser/doc_parser.go b/internal/parser/parser/doc_parser.go
index 4f8f22fbe8..f0ef78435b 100644
--- a/internal/parser/parser/doc_parser.go
+++ b/internal/parser/parser/doc_parser.go
@@ -24,19 +24,10 @@ import (
officeOxide "github.com/yfedoseev/office_oxide/go"
)
-type DOCParser struct {
- libType string
-}
+type DOCParser struct{}
-func NewDOCParser(libType string) (*DOCParser, error) {
- switch libType {
- case OfficeOxide:
- return &DOCParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported DOC library type: %s", libType)
- }
+func NewDOCParser() *DOCParser {
+ return &DOCParser{}
}
func (p *DOCParser) String() string {
diff --git a/internal/parser/parser/docx_parser.go b/internal/parser/parser/docx_parser.go
index 59d0d9abae..295a5222d9 100644
--- a/internal/parser/parser/docx_parser.go
+++ b/internal/parser/parser/docx_parser.go
@@ -24,19 +24,10 @@ import (
officeOxide "github.com/yfedoseev/office_oxide/go"
)
-type DOCXParser struct {
- libType string
-}
+type DOCXParser struct{}
-func NewDOCXParser(libType string) (*DOCXParser, error) {
- switch libType {
- case OfficeOxide:
- return &DOCXParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported DOCX library type: %s", libType)
- }
+func NewDOCXParser() *DOCXParser {
+ return &DOCXParser{}
}
// ParseWithResult captures the office_oxide ToMarkdown output
diff --git a/internal/parser/parser/docx_parser_cgo_test.go b/internal/parser/parser/docx_parser_cgo_test.go
index e36c24eba8..859483cf2b 100644
--- a/internal/parser/parser/docx_parser_cgo_test.go
+++ b/internal/parser/parser/docx_parser_cgo_test.go
@@ -9,10 +9,7 @@ import (
)
func TestDOCXParser_ParseWithResult_CGOMinimalDocument(t *testing.T) {
- p, err := NewDOCXParser(OfficeOxide)
- if err != nil {
- t.Fatalf("NewDOCXParser: %v", err)
- }
+ p := NewDOCXParser()
data := minimalDOCX(t, "Hello from DOCX parser")
res := p.ParseWithResult("sample.docx", data)
if res.Err != nil {
diff --git a/internal/parser/parser/html_parser.go b/internal/parser/parser/html_parser.go
index 6b32615b37..b73020ed0f 100644
--- a/internal/parser/parser/html_parser.go
+++ b/internal/parser/parser/html_parser.go
@@ -24,23 +24,10 @@ import (
"golang.org/x/net/html"
)
-const (
- Official string = "official"
-)
+type HTMLParser struct{}
-type HTMLParser struct {
- libType string
-}
-
-func NewHTMLParser(libType string) (*HTMLParser, error) {
- switch libType {
- case Official:
- return &HTMLParser{
- libType: Official,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported HTML library type: %s", libType)
- }
+func NewHTMLParser() *HTMLParser {
+ return &HTMLParser{}
}
func (p *HTMLParser) String() string {
@@ -61,9 +48,6 @@ func (p *HTMLParser) String() string {
// separate ck_type — the python HtmlParser collapses inline
// formatting into the parent block's text.
func (p *HTMLParser) ParseWithResult(filename string, data []byte) ParseResult {
- if p.libType != Official {
- return ParseResult{Err: fmt.Errorf("unsupported HTML library type: %s", p.libType)}
- }
doc, err := html.Parse(bytes.NewReader(data))
if err != nil {
return ParseResult{Err: fmt.Errorf("html parse: %w", err)}
diff --git a/internal/parser/parser/markdown_parser.go b/internal/parser/parser/markdown_parser.go
index b14bcb27ca..662274ef53 100644
--- a/internal/parser/parser/markdown_parser.go
+++ b/internal/parser/parser/markdown_parser.go
@@ -18,30 +18,16 @@ package parser
import (
"bytes"
- "fmt"
"strings"
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/parser"
)
-const (
- GoMarkdown = "go_markdown"
-)
-
-type MarkdownParser struct {
- libType string
-}
+type MarkdownParser struct{}
-func NewMarkdownParser(libType string) (*MarkdownParser, error) {
- switch libType {
- case GoMarkdown:
- return &MarkdownParser{
- libType: GoMarkdown,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported Markdown library type: %s", libType)
- }
+func NewMarkdownParser() *MarkdownParser {
+ return &MarkdownParser{}
}
// ParseWithResult implements ParseResultProducer (plan §6.5) and
@@ -50,9 +36,6 @@ func NewMarkdownParser(libType string) (*MarkdownParser, error) {
// emits one item with `text` + `doc_type_kwd: "text"`. The legacy
// debug-print path has been removed; callers consume ParseResult directly.
func (p *MarkdownParser) ParseWithResult(filename string, data []byte) ParseResult {
- if p.libType != GoMarkdown {
- return ParseResult{Err: fmt.Errorf("unsupported Markdown library type: %s", p.libType)}
- }
doc := markdownNew().Parse(data)
var items []map[string]any
diff --git a/internal/parser/parser/office_parsers_cgo_shared.go b/internal/parser/parser/office_parsers_cgo_shared.go
index 38efeeecf5..d128fee295 100644
--- a/internal/parser/parser/office_parsers_cgo_shared.go
+++ b/internal/parser/parser/office_parsers_cgo_shared.go
@@ -4,9 +4,6 @@ package parser
import "html"
-// OfficeOxide is the lib_type identifier for office_oxide backend.
-const OfficeOxide = "office_oxide"
-
func htmlEscape(s string) string {
return html.EscapeString(s)
}
diff --git a/internal/parser/parser/office_parsers_no_cgo.go b/internal/parser/parser/office_parsers_no_cgo.go
index 6203557ec4..abb6257a78 100644
--- a/internal/parser/parser/office_parsers_no_cgo.go
+++ b/internal/parser/parser/office_parsers_no_cgo.go
@@ -7,20 +7,16 @@ import (
"fmt"
)
-// OfficeOxide is the lib_type identifier for office_oxide backend.
-const OfficeOxide = "office_oxide"
-
// ErrOfficeCGORequired is returned by ParseWithResult on every
// office-parser family (DOC / DOCX / PPT / PPTX / XLS / XLSX)
// when the build is not CGO-enabled. The CGO build's
// implementation captures the office_oxide PlainText / ToMarkdown
// output; this stub mirrors that surface so the package compiles
-// and existing tests pass.
+// and existing tests pass. The error is surfaced at parse time
+// rather than at construction time, matching the NewPDFParser
+// shape used by the rest of the package.
var ErrOfficeCGORequired = errors.New("parser: office family requires CGO (office_oxide)")
-// docxParseWithResultNoCGO is the no-CGO stub for the DOCX
-// family. The CGO build's implementation lives in docx_parser.go
-// under //go:build cgo.
func (p *DOCXParser) ParseWithResult(filename string, _ []byte) ParseResult {
return ParseResult{
File: map[string]any{"name": filename},
@@ -63,72 +59,60 @@ func (p *PPTXParser) ParseWithResult(filename string, _ []byte) ParseResult {
}
}
-type DOCParser struct {
- libType string
-}
+type DOCParser struct{}
-func NewDOCParser(libType string) (*DOCParser, error) {
- return nil, fmt.Errorf("DOC parser requires CGO (office_oxide)")
+func NewDOCParser() *DOCParser {
+ return &DOCParser{}
}
func (p *DOCParser) String() string {
return "DOCParser(no-cgo)"
}
-type DOCXParser struct {
- libType string
-}
+type DOCXParser struct{}
-func NewDOCXParser(libType string) (*DOCXParser, error) {
- return nil, fmt.Errorf("DOCX parser requires CGO (office_oxide)")
+func NewDOCXParser() *DOCXParser {
+ return &DOCXParser{}
}
func (p *DOCXParser) String() string {
return "DOCXParser(no-cgo)"
}
-type XLSParser struct {
- libType string
-}
+type XLSParser struct{}
-func NewXLSParser(libType string) (*XLSParser, error) {
- return nil, fmt.Errorf("XLS parser requires CGO (office_oxide)")
+func NewXLSParser() *XLSParser {
+ return &XLSParser{}
}
func (p *XLSParser) String() string {
return "XLSParser(no-cgo)"
}
-type XLSXParser struct {
- libType string
-}
+type XLSXParser struct{}
-func NewXLSXParser(libType string) (*XLSXParser, error) {
- return nil, fmt.Errorf("XLSX parser requires CGO (office_oxide)")
+func NewXLSXParser() *XLSXParser {
+ return &XLSXParser{}
}
func (p *XLSXParser) String() string {
return "XLSXParser(no-cgo)"
}
-type PPTParser struct {
- libType string
-}
+type PPTParser struct{}
-func NewPPTParser(libType string) (*PPTParser, error) {
- return nil, fmt.Errorf("PPT parser requires CGO (office_oxide)")
+func NewPPTParser() *PPTParser {
+ return &PPTParser{}
}
func (p *PPTParser) String() string {
return "PPTParser(no-cgo)"
}
-type PPTXParser struct {
- libType string
-}
+type PPTXParser struct{}
-func NewPPTXParser(libType string) (*PPTXParser, error) {
- return nil, fmt.Errorf("PPTX parser requires CGO (office_oxide)")
+func NewPPTXParser() *PPTXParser {
+ return &PPTXParser{}
}
func (p *PPTXParser) String() string {
diff --git a/internal/parser/parser/office_routes_cgo_test.go b/internal/parser/parser/office_routes_cgo_test.go
index a749e3a1a3..713aafb530 100644
--- a/internal/parser/parser/office_routes_cgo_test.go
+++ b/internal/parser/parser/office_routes_cgo_test.go
@@ -22,10 +22,13 @@ func TestGetParser_RoutesOfficeFamilies(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- p, err := GetParser(tc.fileType, map[string]string{"lib_type": OfficeOxide})
+ p, err := GetParser(tc.fileType)
if err != nil {
t.Fatalf("GetParser(%q): %v", tc.fileType, err)
}
+ if p == nil {
+ t.Fatalf("GetParser(%q) returned nil", tc.fileType)
+ }
if _, ok := p.(ParseResultProducer); !ok {
t.Fatalf("GetParser(%q) returned %T, want ParseResultProducer", tc.fileType, p)
}
diff --git a/internal/parser/parser/parse_result_test.go b/internal/parser/parser/parse_result_test.go
index 37256bff0b..45567cb599 100644
--- a/internal/parser/parser/parse_result_test.go
+++ b/internal/parser/parser/parse_result_test.go
@@ -130,10 +130,7 @@ func (s sentinelErr) Error() string { return string(s) }
// tiny: 1 heading, 1 paragraph, 1 unordered list item, no nested
// formatting.
func TestMarkdownParser_ParseWithResult(t *testing.T) {
- p, err := NewMarkdownParser(GoMarkdown)
- if err != nil {
- t.Fatalf("NewMarkdownParser: %v", err)
- }
+ p := NewMarkdownParser()
src := []byte("# Title\n\nFirst paragraph.\n\n- Item one\n")
res := p.ParseWithResult("doc.md", src)
if res.Err != nil {
diff --git a/internal/parser/parser/parse_with_result_test.go b/internal/parser/parser/parse_with_result_test.go
index b73391670b..d38670f83c 100644
--- a/internal/parser/parser/parse_with_result_test.go
+++ b/internal/parser/parser/parse_with_result_test.go
@@ -43,10 +43,7 @@ import (
// rule. A blank-line-separated input yields one item per
// paragraph; the python TxtParser does the same.
func TestTextParser_ParseWithResult_ParaSplit(t *testing.T) {
- p, err := NewTextParser("")
- if err != nil {
- t.Fatalf("NewTextParser: %v", err)
- }
+ p := NewTextParser()
src := []byte("First paragraph.\n\nSecond paragraph.\n\nThird.")
res := p.ParseWithResult("doc.txt", src)
if res.Err != nil {
@@ -74,7 +71,7 @@ func TestTextParser_ParseWithResult_ParaSplit(t *testing.T) {
// sees a non-nil JSON slice. Mirrors the MarkdownParser convention
// at markdown_parser.go:71-76.
func TestTextParser_ParseWithResult_Empty(t *testing.T) {
- p, _ := NewTextParser("")
+ p := NewTextParser()
res := p.ParseWithResult("empty.txt", []byte{})
if res.Err != nil {
t.Fatalf("ParseWithResult: %v", res.Err)
@@ -88,7 +85,7 @@ func TestTextParser_ParseWithResult_Empty(t *testing.T) {
// maxItemBytes boundary behaviour. A single paragraph longer
// than 8192 bytes is sliced at the nearest line boundary.
func TestTextParser_ParseWithResult_LongParagraphSlicing(t *testing.T) {
- p, _ := NewTextParser("")
+ p := NewTextParser()
long := strings.Repeat("a", 9000)
res := p.ParseWithResult("long.txt", []byte(long))
if res.Err != nil {
@@ -108,7 +105,7 @@ func TestTextParser_ParseWithResult_LongParagraphSlicing(t *testing.T) {
// validation rule. Invalid bytes produce an error in the result
// (matching the python TxtParser's behaviour).
func TestTextParser_ParseWithResult_InvalidUTF8(t *testing.T) {
- p, _ := NewTextParser("")
+ p := NewTextParser()
bad := []byte{0xff, 0xfe, 0xfd}
res := p.ParseWithResult("bad.txt", bad)
if res.Err == nil {
@@ -120,10 +117,7 @@ func TestTextParser_ParseWithResult_InvalidUTF8(t *testing.T) {
// Three block elements (heading, paragraph, list) yield three
// items with the python-compatible ck_type vocabulary.
func TestHTMLParser_ParseWithResult_BlockSplit(t *testing.T) {
- p, err := NewHTMLParser(Official)
- if err != nil {
- t.Fatalf("NewHTMLParser: %v", err)
- }
+ p := NewHTMLParser()
src := []byte(`<!DOCTYPE html><html><body>
<h1>Title</h1>
<p>First paragraph.</p>
@@ -163,7 +157,7 @@ func TestHTMLParser_ParseWithResult_BlockSplit(t *testing.T) {
// rule that <script> / <style> subtrees are skipped entirely so
// they don't pollute the downstream chunker input.
func TestHTMLParser_ParseWithResult_SkipsScriptAndStyle(t *testing.T) {
- p, _ := NewHTMLParser(Official)
+ p := NewHTMLParser()
src := []byte(`<html><body>
<p>Visible.</p>
<script>alert("x")</script>
@@ -189,7 +183,7 @@ func TestHTMLParser_ParseWithResult_SkipsScriptAndStyle(t *testing.T) {
// `utility.FileTypeTXT` resolves to a TextParser that satisfies
// ParseResultProducer.
func TestGetParser_RoutesTextAndCode(t *testing.T) {
- p, err := GetParser(utility.FileTypeTXT, map[string]string{"lib_type": ""})
+ p, err := GetParser(utility.FileTypeTXT)
if err != nil {
t.Fatalf("GetParser(FileTypeTXT): %v", err)
}
diff --git a/internal/parser/parser/parser_type.go b/internal/parser/parser/parser_type.go
index e825ab8019..35cfd25422 100644
--- a/internal/parser/parser/parser_type.go
+++ b/internal/parser/parser/parser_type.go
@@ -18,35 +18,38 @@ package parser
import (
"fmt"
+
"ragflow/internal/utility"
)
-func GetParser(fileType utility.FileType, config map[string]string) (ParseResultProducer, error) {
- libType, ok := config["lib_type"]
- if !ok {
- return nil, fmt.Errorf("missing lib_type config")
- }
+// GetParser returns the ParseResultProducer for the given file type.
+// Each format picks a single backend — the Python dispatcher does
+// not pass any lib_type knob for these families, so the Go side
+// mirrors that with one constructor per format. Constructors mirror
+// the NewPDFParser shape (no error return): none of them have inputs
+// that could fail, so the error slot is dead weight.
+func GetParser(fileType utility.FileType) (ParseResultProducer, error) {
switch fileType {
case utility.FileTypePPTX:
- return NewPPTXParser(libType)
+ return NewPPTXParser(), nil
case utility.FileTypePPT:
- return NewPPTParser(libType)
+ return NewPPTParser(), nil
case utility.FileTypeXLSX:
- return NewXLSXParser(libType)
+ return NewXLSXParser(), nil
case utility.FileTypeXLS:
- return NewXLSParser(libType)
+ return NewXLSParser(), nil
case utility.FileTypeDOCX:
- return NewDOCXParser(libType)
+ return NewDOCXParser(), nil
case utility.FileTypeDOC:
- return NewDOCParser(libType)
+ return NewDOCParser(), nil
case utility.FileTypePDF:
return NewPDFParser(), nil
case utility.FileTypeHTML:
- return NewHTMLParser(Official)
+ return NewHTMLParser(), nil
case utility.FileTypeMarkdown:
- return NewMarkdownParser(GoMarkdown)
+ return NewMarkdownParser(), nil
case utility.FileTypeTXT:
- return NewTextParser(libType)
+ return NewTextParser(), nil
default:
return nil, fmt.Errorf("unsupported file type: %s", fileType)
}
diff --git a/internal/parser/parser/pdf_parser_common.go b/internal/parser/parser/pdf_parser_common.go
index 9bc754be6a..4bebde1083 100644
--- a/internal/parser/parser/pdf_parser_common.go
+++ b/internal/parser/parser/pdf_parser_common.go
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"image"
+ "log/slog"
"os"
"sort"
"strings"
@@ -30,6 +31,7 @@ import (
deepdocpdf "ragflow/internal/deepdoc/parser/pdf"
"ragflow/internal/deepdoc/parser/pdf/inference"
pdflayout "ragflow/internal/deepdoc/parser/pdf/layout"
+ "ragflow/internal/deepdoc/parser/pdf/util"
deepdoctype "ragflow/internal/deepdoc/parser/type"
)
@@ -293,9 +295,6 @@ func emptyPDFResult(filename string) ParseResult {
func deepDocAnalyzerFromEnv() deepdoctype.DocAnalyzer {
baseURL := strings.TrimSpace(os.Getenv("DEEPDOC_URL"))
- if baseURL == "" {
- baseURL = strings.TrimSpace(os.Getenv("OSSDEEPDOC_URL"))
- }
if baseURL == "" {
return &deepdocpdf.MockDocAnalyzer{Healthy: true}
}
@@ -306,7 +305,12 @@ func deepDocAnalyzerFromEnv() deepdoctype.DocAnalyzer {
if !client.Health() {
return &deepdocpdf.MockDocAnalyzer{Healthy: true}
}
- return client
+ // Wrap with Redis-backed cache (1h TTL) so repeated
+ // DLA/TSR/OCR inference on the same image is served from
+ // Redis instead of re-hitting the DeepDoc HTTP service. The
+ // wrapper is a no-op when Redis is not configured (see
+ // internal/deepdoc/parser/pdf/inference/cache.go).
+ return inference.NewDocAnalyzerCache(client, inference.DefaultCacheTTL)
}
func pdfParseResultToJSON(filename string, parsed *deepdoctype.ParseResult) ParseResult {
@@ -321,7 +325,7 @@ func pdfParseResultToJSONWithOptions(filename string, parsed *deepdoctype.ParseR
processed.Sections = append([]deepdoctype.Section(nil), parsed.Sections...)
processed.Outlines = append([]deepdoctype.Outline(nil), parsed.Outlines...)
if opts.enableMultiColumn && opts.pageWidth <= 0 {
- opts.pageWidth = firstPDFPageWidth(processed.PageImages, opts.zoom)
+ opts.pageWidth = firstPDFPageWidth(processed.PageWidth)
}
applyPDFPostProcess(&processed, opts)
@@ -345,11 +349,14 @@ func pdfParseResultToJSONWithOptions(filename string, parsed *deepdoctype.ParseR
items[i]["image"] = "data:image/png;base64," + img
}
}
+ // JSON is consumed by the chunker, which re-acquires the source PDF
+ // and crops image/table sections on demand. Release the engine now.
+ processed.Close()
return ParseResult{
OutputFormat: "json",
File: map[string]any{
"name": filename,
- "page_count": len(processed.PageImages),
+ "page_count": len(processed.PageHeight),
"outline": outlinesToFileMeta(processed.Outlines),
},
JSON: items,
@@ -364,15 +371,20 @@ func pdfParseResultToMarkdownWithOptions(filename string, parsed *deepdoctype.Pa
processed.Sections = append([]deepdoctype.Section(nil), parsed.Sections...)
processed.Outlines = append([]deepdoctype.Outline(nil), parsed.Outlines...)
if opts.enableMultiColumn && opts.pageWidth <= 0 {
- opts.pageWidth = firstPDFPageWidth(processed.PageImages, opts.zoom)
+ opts.pageWidth = firstPDFPageWidth(processed.PageWidth)
}
applyPDFPostProcess(&processed, opts)
+ // Markdown embeds figure images inline, so crop figures here while
+ // the engine is still alive. The chunker path crops image/table
+ // chunks on demand instead.
+ cropMarkdownFigures(&processed)
+ processed.Close()
return ParseResult{
OutputFormat: "markdown",
File: map[string]any{
"name": filename,
- "page_count": len(processed.PageImages),
+ "page_count": len(processed.PageHeight),
"outline": outlinesToFileMeta(processed.Outlines),
},
Markdown: sectionsToMarkdown(processed.Sections),
@@ -443,23 +455,105 @@ func sectionsToMarkdown(sections []deepdoctype.Section) string {
return b.String()
}
-func firstPDFPageWidth(pageImages map[int]image.Image, zoom float64) float64 {
- if len(pageImages) == 0 {
- return 0
+// cropMarkdownFigures crops inline images for figure sections so the
+// markdown output can embed them. It mirrors the figure branch of the
+// former Parse.fillSectionImages, but runs only for the markdown path
+// (the JSON path defers cropping to the chunker). The engine is read
+// from result.Engine; callers must Close the result afterwards.
+func cropMarkdownFigures(result *deepdoctype.ParseResult) {
+ engine := result.Engine
+ if engine == nil || len(result.PageHeight) == 0 {
+ return
}
- if zoom <= 0 {
- zoom = deepdoctype.DefaultParserConfig().Zoom
+ // Render each page at most once across all figures. A PDF can have many
+ // figures on the same page, so a cache shared across the section loop
+ // avoids re-rendering the page for every figure.
+ //
+ // result.Sections is ordered by page, so once we advance to a figure whose
+ // minimum page is P, no later figure references a page < P. We therefore
+ // keep only a sliding window of page images: pages strictly below the
+ // current figure's minimum page are evicted. This bounds memory to the
+ // current figure's page span (typically one page, a few at most for a
+ // cross-page figure) instead of caching the whole PDF.
+ pageCache := make(map[int]image.Image)
+ renderPage := func(pn int) image.Image {
+ if img, ok := pageCache[pn]; ok {
+ return img
+ }
+ img, err := deepdocpdf.RenderPageToImage(engine, pn)
+ if err != nil || img == nil {
+ slog.Warn("cropMarkdownFigures: render failed, skipping figure",
+ "page", pn, "err", err)
+ pageCache[pn] = nil
+ return nil
+ }
+ pageCache[pn] = img
+ return img
}
- pages := make([]int, 0, len(pageImages))
- for page := range pageImages {
- pages = append(pages, page)
+
+ for i := range result.Sections {
+ sec := &result.Sections[i]
+ if sec.LayoutType != deepdoctype.LayoutTypeFigure {
+ continue
+ }
+ if len(sec.Positions) == 0 {
+ continue
+ }
+ // Minimum page this figure touches; used both to prune stale cache
+ // entries and to bound the window.
+ minPage := -1
+ pages := make(map[int]struct{})
+ for _, pos := range sec.Positions {
+ for _, pn := range pos.PageNumbers {
+ pages[pn] = struct{}{}
+ if pn < minPage || minPage < 0 {
+ minPage = pn
+ }
+ }
+ }
+ // Evict page images that no later figure can reference (all future
+ // figures start at page >= minPage).
+ for pn := range pageCache {
+ if pn < minPage {
+ delete(pageCache, pn)
+ }
+ }
+ // Collect every distinct page this section spans so CropSectionByDLA
+ // can crop and vertically concatenate each page (mirroring Python's
+ // cropout multi-page branch). Single-page figures still render exactly
+ // one page, and the pageCache above guarantees a page is rendered at
+ // most once even when several figures share it.
+ single := make(map[int]image.Image, len(pages))
+ for pn := range pages {
+ if img := renderPage(pn); img != nil {
+ single[pn] = img
+ }
+ }
+ if len(single) == 0 {
+ continue
+ }
+ if dla := util.CropSectionByDLA(*sec, result.DLARegions, single); dla != "" {
+ sec.Image = dla
+ continue
+ }
+ sec.Image = util.CropSectionImage(sec.PositionTag, single, deepdoctype.DlaScale)
}
- sort.Ints(pages)
- img := pageImages[pages[0]]
- if img == nil {
+}
+
+// firstPDFPageWidth returns the first page's width from a map of
+// per-page PDF-point widths. The map is guaranteed to store values
+// already converted to PDF-point space by processPage.
+func firstPDFPageWidth(pageWidths map[int]float64) float64 {
+ if len(pageWidths) == 0 {
return 0
}
- return float64(img.Bounds().Dx()) / zoom
+ pages := make([]int, 0, len(pageWidths))
+ for pg := range pageWidths {
+ pages = append(pages, pg)
+ }
+ sort.Ints(pages)
+ pg := pages[0]
+ return pageWidths[pg]
}
func normalizePDFPositions(raw any) [][]any {
diff --git a/internal/parser/parser/pdf_parser_mineru.go b/internal/parser/parser/pdf_parser_mineru.go
index cdc5c4b953..f5d2f26c9e 100644
--- a/internal/parser/parser/pdf_parser_mineru.go
+++ b/internal/parser/parser/pdf_parser_mineru.go
@@ -97,10 +97,7 @@ func parseMinerUMarkdownResult(filename, markdown, outputFormat string, pageCoun
fileMeta := pdfFileMeta(filename, pageCount)
switch strings.ToLower(strings.TrimSpace(outputFormat)) {
case "", "json":
- mp, err := NewMarkdownParser(GoMarkdown)
- if err != nil {
- return ParseResult{Err: err}
- }
+ mp := NewMarkdownParser()
res := mp.ParseWithResult(filename, []byte(markdown))
if res.Err != nil {
return res
diff --git a/internal/parser/parser/pdf_postprocess.go b/internal/parser/parser/pdf_postprocess.go
index 106f92841d..5ce3d2a0d7 100644
--- a/internal/parser/parser/pdf_postprocess.go
+++ b/internal/parser/parser/pdf_postprocess.go
@@ -73,11 +73,12 @@ func assignPDFDocTypeKeywords(result *deepdoctype.ParseResult, flatten bool) {
case deepdoctype.LayoutTypeFigure:
section.DocTypeKwd = "image"
default:
- if section.Image != "" {
- section.DocTypeKwd = "image"
- } else {
- section.DocTypeKwd = "text"
- }
+ // doc_type_kwd is derived from layout, not from whether a
+ // section image was cropped. Cropping happens lazily at
+ // markdown serialization / chunk time, so it must not
+ // influence classification here (otherwise every positioned
+ // text box would be mislabeled "image").
+ section.DocTypeKwd = "text"
}
}
}
diff --git a/internal/parser/parser/pdf_postprocess_test.go b/internal/parser/parser/pdf_postprocess_test.go
index 9c8fa29111..f95bbd2128 100644
--- a/internal/parser/parser/pdf_postprocess_test.go
+++ b/internal/parser/parser/pdf_postprocess_test.go
@@ -48,7 +48,10 @@ func TestApplyPDFPostProcess_AssignsDocTypeKeywords(t *testing.T) {
},
}
applyPDFPostProcess(result, pdfPostProcessOptions{})
- want := []string{"table", "image", "text", "image"}
+ // doc_type_kwd is derived from layout type only. A pre-set Image no
+ // longer reclassifies a section as "image" — cropping happens lazily
+ // at markdown serialization / chunk time (see pdf_parser_common.go).
+ want := []string{"table", "image", "text", "text"}
for i, s := range result.Sections {
if s.DocTypeKwd != want[i] {
t.Fatalf("Sections[%d].DocTypeKwd = %q, want %q", i, s.DocTypeKwd, want[i])
diff --git a/internal/parser/parser/ppt_parser.go b/internal/parser/parser/ppt_parser.go
index 4d12854d3a..7e5b9473b7 100644
--- a/internal/parser/parser/ppt_parser.go
+++ b/internal/parser/parser/ppt_parser.go
@@ -18,23 +18,10 @@
package parser
-import (
- "fmt"
-)
+type PPTParser struct{}
-type PPTParser struct {
- libType string
-}
-
-func NewPPTParser(libType string) (*PPTParser, error) {
- switch libType {
- case OfficeOxide:
- return &PPTParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported PPT library type: %s", libType)
- }
+func NewPPTParser() *PPTParser {
+ return &PPTParser{}
}
func (p *PPTParser) String() string {
@@ -46,11 +33,7 @@ func (p *PPTParser) String() string {
// in the binary container; the python parser.py:slides branch
// treats them uniformly.
func (p *PPTParser) ParseWithResult(filename string, data []byte) ParseResult {
- delegate, err := NewPPTXParser(OfficeOxide)
- if err != nil {
- return ParseResult{Err: fmt.Errorf("ppt delegate: %w", err)}
- }
- res := delegate.ParseWithResult(filename, data)
+ res := NewPPTXParser().ParseWithResult(filename, data)
if res.File != nil {
res.File["format"] = "ppt"
}
diff --git a/internal/parser/parser/pptx_parser.go b/internal/parser/parser/pptx_parser.go
index 0ce0f4ac39..edf825932a 100644
--- a/internal/parser/parser/pptx_parser.go
+++ b/internal/parser/parser/pptx_parser.go
@@ -25,19 +25,10 @@ import (
officeOxide "github.com/yfedoseev/office_oxide/go"
)
-type PPTXParser struct {
- libType string
-}
+type PPTXParser struct{}
-func NewPPTXParser(libType string) (*PPTXParser, error) {
- switch libType {
- case OfficeOxide:
- return &PPTXParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported PPTX library type: %s", libType)
- }
+func NewPPTXParser() *PPTXParser {
+ return &PPTXParser{}
}
func (p *PPTXParser) String() string {
diff --git a/internal/parser/parser/text_parser.go b/internal/parser/parser/text_parser.go
index f7f99c30c7..de041e0202 100644
--- a/internal/parser/parser/text_parser.go
+++ b/internal/parser/parser/text_parser.go
@@ -37,8 +37,6 @@ import (
"strings"
)
-const TextParserLibType = "text"
-
// TextParser is the text&code family parser. It implements the
// structured ParseResultProducer contract directly.
type TextParser struct {
@@ -49,12 +47,10 @@ type TextParser struct {
maxItemBytes int
}
-// NewTextParser constructs a TextParser. The libType argument
-// preserves the parser-library constructor signature for
-// consistency with the other family parsers; the value is ignored
-// (TextParser has no alternative backend).
-func NewTextParser(_ string) (*TextParser, error) {
- return &TextParser{maxItemBytes: 8192}, nil
+// NewTextParser constructs a TextParser with the default
+// paragraph-sized chunking ceiling.
+func NewTextParser() *TextParser {
+ return &TextParser{maxItemBytes: 8192}
}
// ParseWithResult emits one item per non-empty paragraph. The
diff --git a/internal/parser/parser/xls_parser.go b/internal/parser/parser/xls_parser.go
index 2e45aa944c..05e22442e8 100644
--- a/internal/parser/parser/xls_parser.go
+++ b/internal/parser/parser/xls_parser.go
@@ -26,19 +26,10 @@ import (
"github.com/xuri/excelize/v2"
)
-type XLSParser struct {
- libType string
-}
+type XLSParser struct{}
-func NewXLSParser(libType string) (*XLSParser, error) {
- switch libType {
- case OfficeOxide:
- return &XLSParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported XLS library type: %s", libType)
- }
+func NewXLSParser() *XLSParser {
+ return &XLSParser{}
}
func (p *XLSParser) String() string {
diff --git a/internal/parser/parser/xlsx_parser.go b/internal/parser/parser/xlsx_parser.go
index 00f34a8e3f..8676cd27a7 100644
--- a/internal/parser/parser/xlsx_parser.go
+++ b/internal/parser/parser/xlsx_parser.go
@@ -26,19 +26,10 @@ import (
"github.com/xuri/excelize/v2"
)
-type XLSXParser struct {
- libType string
-}
+type XLSXParser struct{}
-func NewXLSXParser(libType string) (*XLSXParser, error) {
- switch libType {
- case OfficeOxide:
- return &XLSXParser{
- libType: OfficeOxide,
- }, nil
- default:
- return nil, fmt.Errorf("unsupported XLSX library type: %s", libType)
- }
+func NewXLSXParser() *XLSXParser {
+ return &XLSXParser{}
}
func (p *XLSXParser) String() string {
diff --git a/internal/service/file.go b/internal/service/file.go
index c0a0840a91..659153f531 100644
--- a/internal/service/file.go
+++ b/internal/service/file.go
@@ -1128,9 +1128,7 @@ func parseFileContent(filename string, data []byte) string {
if fileType == utility.FileTypeOTHER {
return string(data)
}
- // Parser config — office_oxide for MS Office formats; other parsers ignore it.
- parserCfg := map[string]string{"lib_type": "office_oxide"}
- fp, err := parser.GetParser(fileType, parserCfg)
+ fp, err := parser.GetParser(fileType)
if err != nil {
return string(data)
}
diff --git a/internal/utility/workerpool.go b/internal/utility/workerpool.go
new file mode 100644
index 0000000000..af2ed077c9
--- /dev/null
+++ b/internal/utility/workerpool.go
@@ -0,0 +1,241 @@
+package utility
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "sync/atomic"
+)
+
+const (
+ workerPoolStateRunning uint32 = 0
+ workerPoolStateStopped uint32 = 1
+)
+
+var (
+ // ErrWorkerPoolStopped is returned when a task is submitted to a stopped pool.
+ ErrWorkerPoolStopped = errors.New("workerpool: already stopped")
+)
+
+// WorkerPoolHandler processes one task input and returns its typed result.
+type WorkerPoolHandler[T any, R any] func(context.Context, T) (R, error)
+
+// WorkerPoolResult carries the input, output, and execution error for one task.
+type WorkerPoolResult[T any, R any] struct {
+ Input T
+ Value R
+ Err error
+}
+
+// WorkerPoolFuture wraps the asynchronous result for one submitted task.
+type WorkerPoolFuture[T any, R any] struct {
+ ch <-chan WorkerPoolResult[T, R]
+}
+
+// Wait blocks until the task completes or ctx is cancelled.
+func (f WorkerPoolFuture[T, R]) Wait(ctx context.Context) (WorkerPoolResult[T, R], error) {
+ select {
+ case <-ctx.Done():
+ var zero WorkerPoolResult[T, R]
+ return zero, ctx.Err()
+ case res := <-f.ch:
+ return res, nil
+ }
+}
+
+// WorkerPoolStats exposes a snapshot of pool activity.
+type WorkerPoolStats struct {
+ DesiredWorkers int
+ LiveWorkers int
+ ActiveWorkers int
+ QueueDepth int
+ SubmittedTotal uint64
+ CompletedTotal uint64
+ FailedTotal uint64
+ PendingTotal uint64
+}
+
+type workerPoolJob[T any, R any] struct {
+ ctx context.Context
+ input T
+ out chan<- WorkerPoolResult[T, R]
+}
+
+// WorkerPool is a reusable, process-local worker pool for homogeneous tasks.
+// Workers are long-lived and can be resized at runtime.
+type WorkerPool[T any, R any] struct {
+ handler WorkerPoolHandler[T, R]
+ workChan chan workerPoolJob[T, R]
+
+ state uint32
+
+ desiredWorkers int64
+ liveWorkers int64
+ activeWorkers int64
+ submittedTotal uint64
+ completedTotal uint64
+ failedTotal uint64
+
+ taskDone sync.Cond
+ mu sync.Mutex
+ submitN uint64
+ doneN uint64
+
+ workerWg sync.WaitGroup
+}
+
+// NewWorkerPool creates a worker pool with fixed queue capacity and starts workers immediately.
+func NewWorkerPool[T any, R any](workers, queueSize int, handler WorkerPoolHandler[T, R]) *WorkerPool[T, R] {
+ if workers <= 0 {
+ panic("workerpool: workers must be greater than zero")
+ }
+ if queueSize <= 0 {
+ panic("workerpool: queueSize must be greater than zero")
+ }
+ if handler == nil {
+ panic("workerpool: handler must not be nil")
+ }
+
+ p := &WorkerPool[T, R]{
+ handler: handler,
+ workChan: make(chan workerPoolJob[T, R], queueSize),
+ desiredWorkers: int64(workers),
+ }
+ p.taskDone.L = &p.mu
+ p.start(workers)
+ return p
+}
+
+func (p *WorkerPool[T, R]) start(workers int) {
+ for range workers {
+ p.workerWg.Add(1)
+ go p.worker()
+ }
+}
+
+func (p *WorkerPool[T, R]) worker() {
+ atomic.AddInt64(&p.liveWorkers, 1)
+ defer func() {
+ atomic.AddInt64(&p.liveWorkers, -1)
+ p.workerWg.Done()
+ }()
+
+ for j := range p.workChan {
+ res := WorkerPoolResult[T, R]{Input: j.input}
+ if err := j.ctx.Err(); err != nil {
+ res.Err = err
+ } else {
+ atomic.AddInt64(&p.activeWorkers, 1)
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ res.Err = fmt.Errorf("workerpool: handler panic: %v", r)
+ }
+ atomic.AddInt64(&p.activeWorkers, -1)
+ }()
+ value, err := p.handler(j.ctx, j.input)
+ res.Value = value
+ res.Err = err
+ }()
+ }
+
+ if res.Err != nil {
+ atomic.AddUint64(&p.failedTotal, 1)
+ }
+ atomic.AddUint64(&p.completedTotal, 1)
+ if j.out != nil {
+ j.out <- res
+ }
+ p.markDone()
+
+ if atomic.LoadInt64(&p.liveWorkers) > atomic.LoadInt64(&p.desiredWorkers) {
+ return
+ }
+ }
+}
+
+// Resize adjusts the target worker count. When shrinking, extra workers retire
+// after completing their current task.
+func (p *WorkerPool[T, R]) Resize(workers int) {
+ if workers <= 0 {
+ panic("workerpool: workers must be greater than zero")
+ }
+
+ current := int(atomic.LoadInt64(&p.desiredWorkers))
+ atomic.StoreInt64(&p.desiredWorkers, int64(workers))
+ if workers > current {
+ p.start(workers - current)
+ }
+}
+
+// Submit enqueues one task and returns a future for its result.
+func (p *WorkerPool[T, R]) Submit(ctx context.Context, input T) (WorkerPoolFuture[T, R], error) {
+ resultCh := make(chan WorkerPoolResult[T, R], 1)
+ if err := p.SubmitTo(ctx, input, resultCh); err != nil {
+ return WorkerPoolFuture[T, R]{}, err
+ }
+ return WorkerPoolFuture[T, R]{ch: resultCh}, nil
+}
+
+// SubmitTo enqueues one task and routes its result into out.
+func (p *WorkerPool[T, R]) SubmitTo(ctx context.Context, input T, out chan<- WorkerPoolResult[T, R]) error {
+ if atomic.LoadUint32(&p.state) == workerPoolStateStopped {
+ return ErrWorkerPoolStopped
+ }
+
+ j := workerPoolJob[T, R]{ctx: ctx, input: input, out: out}
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case p.workChan <- j:
+ atomic.AddUint64(&p.submittedTotal, 1)
+ p.mu.Lock()
+ p.submitN++
+ p.mu.Unlock()
+ return nil
+ }
+}
+
+func (p *WorkerPool[T, R]) markDone() {
+ p.mu.Lock()
+ p.doneN++
+ if p.submitN == p.doneN {
+ p.taskDone.Broadcast()
+ }
+ p.mu.Unlock()
+}
+
+// StopWait stops accepting new tasks, waits for queued/running tasks to finish,
+// then shuts down the worker pool.
+func (p *WorkerPool[T, R]) StopWait() {
+ if !atomic.CompareAndSwapUint32(&p.state, workerPoolStateRunning, workerPoolStateStopped) {
+ return
+ }
+
+ p.mu.Lock()
+ for p.submitN != p.doneN {
+ p.taskDone.Wait()
+ }
+ p.mu.Unlock()
+
+ close(p.workChan)
+ p.workerWg.Wait()
+}
+
+// Stats returns a point-in-time view of pool usage counters.
+func (p *WorkerPool[T, R]) Stats() WorkerPoolStats {
+ submitted := atomic.LoadUint64(&p.submittedTotal)
+ completed := atomic.LoadUint64(&p.completedTotal)
+
+ return WorkerPoolStats{
+ DesiredWorkers: int(atomic.LoadInt64(&p.desiredWorkers)),
+ LiveWorkers: int(atomic.LoadInt64(&p.liveWorkers)),
+ ActiveWorkers: int(atomic.LoadInt64(&p.activeWorkers)),
+ QueueDepth: len(p.workChan),
+ SubmittedTotal: submitted,
+ CompletedTotal: completed,
+ FailedTotal: atomic.LoadUint64(&p.failedTotal),
+ PendingTotal: submitted - completed,
+ }
+}
diff --git a/internal/utility/workerpool_test.go b/internal/utility/workerpool_test.go
new file mode 100644
index 0000000000..edfb101eca
--- /dev/null
+++ b/internal/utility/workerpool_test.go
@@ -0,0 +1,109 @@
+package utility
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestWorkerPoolSubmitAndStats(t *testing.T) {
+ pool := NewWorkerPool[int, int](2, 4, func(_ context.Context, in int) (int, error) {
+ return in * 2, nil
+ })
+ defer pool.StopWait()
+
+ f1, err := pool.Submit(context.Background(), 2)
+ if err != nil {
+ t.Fatalf("Submit(2): %v", err)
+ }
+ f2, err := pool.Submit(context.Background(), 3)
+ if err != nil {
+ t.Fatalf("Submit(3): %v", err)
+ }
+
+ r1, err := f1.Wait(context.Background())
+ if err != nil {
+ t.Fatalf("Wait(2): %v", err)
+ }
+ r2, err := f2.Wait(context.Background())
+ if err != nil {
+ t.Fatalf("Wait(3): %v", err)
+ }
+ if r1.Value != 4 || r2.Value != 6 {
+ t.Fatalf("unexpected results: %+v %+v", r1, r2)
+ }
+
+ stats := pool.Stats()
+ if stats.DesiredWorkers != 2 {
+ t.Fatalf("DesiredWorkers = %d, want 2", stats.DesiredWorkers)
+ }
+ if stats.SubmittedTotal != 2 || stats.CompletedTotal != 2 {
+ t.Fatalf("stats totals = %+v, want submitted=2 completed=2", stats)
+ }
+ if stats.FailedTotal != 0 || stats.PendingTotal != 0 {
+ t.Fatalf("stats failure/pending = %+v, want 0", stats)
+ }
+}
+
+func TestWorkerPoolSubmitToCanceledTaskReturnsContextError(t *testing.T) {
+ started := make(chan struct{})
+ release := make(chan struct{})
+ var ranSecond atomic.Uint64
+
+ pool := NewWorkerPool[int, int](1, 2, func(ctx context.Context, in int) (int, error) {
+ if in == 1 {
+ close(started)
+ <-release
+ return in, nil
+ }
+ ranSecond.Add(1)
+ return in, ctx.Err()
+ })
+ defer pool.StopWait()
+
+ firstCh := make(chan WorkerPoolResult[int, int], 1)
+ if err := pool.SubmitTo(context.Background(), 1, firstCh); err != nil {
+ t.Fatalf("SubmitTo(first): %v", err)
+ }
+ <-started
+
+ ctx, cancel := context.WithCancel(context.Background())
+ secondCh := make(chan WorkerPoolResult[int, int], 1)
+ if err := pool.SubmitTo(ctx, 2, secondCh); err != nil {
+ t.Fatalf("SubmitTo(second): %v", err)
+ }
+ cancel()
+ close(release)
+
+ select {
+ case <-firstCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for first result")
+ }
+
+ select {
+ case res := <-secondCh:
+ if res.Err == nil {
+ t.Fatal("second result error = nil, want context cancellation")
+ }
+ if ranSecond.Load() != 0 {
+ t.Fatalf("second handler ran %d times, want 0", ranSecond.Load())
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for second result")
+ }
+}
+
+func TestWorkerPoolResize(t *testing.T) {
+ pool := NewWorkerPool[int, int](1, 2, func(_ context.Context, in int) (int, error) {
+ return in, nil
+ })
+ defer pool.StopWait()
+
+ pool.Resize(3)
+ stats := pool.Stats()
+ if stats.DesiredWorkers != 3 {
+ t.Fatalf("DesiredWorkers = %d, want 3", stats.DesiredWorkers)
+ }
+}