RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(deepdoc): keep every inference call within one process CPU budget (#19695)
jay7772140041517202c
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.goindex 57ece4f2a6..b65f3b24f6 100644--- a/cmd/ragflow_server.go+++ b/cmd/ragflow_server.go@@ -31,6 +31,8 @@ import ("ragflow/internal/agent/runtime"agenttool "ragflow/internal/agent/tool""ragflow/internal/channels"+ native "ragflow/internal/deepdoc/native"+ pdf "ragflow/internal/deepdoc/parser/pdf"modelModule "ragflow/internal/entity/models""ragflow/internal/handler""ragflow/internal/ingestion/knowledge_compile"@@ -51,6 +53,7 @@ import ("ragflow/internal/storage""ragflow/internal/syncer""ragflow/internal/tokenizer"+ goruntime "runtime""strconv""strings""syscall"@@ -1544,6 +1547,16 @@ func registerNativeDeepDoc() {}common.Info("in-process DeepDoc backend registered (production backend)",zap.String("model_dir", modelDir))++ // DeepDoc sessions run single-threaded, so the process inference budget is a+ // plain concurrency cap. Register it with the native gate every inference+ // call passes through (internal/deepdoc/native/inference_limit.go); without+ // this the process would let every page worker call inference at once.+ limit := pdf.DeepDocConcurrency()+ native.SetInferenceLimit(limit)+ common.Info("in-process DeepDoc inference limit registered",+ zap.Int("max_concurrent_inference", limit),+ zap.Int("gomaxprocs", goruntime.GOMAXPROCS(0)))}// resolveDeepDocModelDir picks the model directory: the explicit DEEPDOC_MODEL_DIRdiff --git a/internal/deepdoc/native/det_core.go b/internal/deepdoc/native/det_core.goindex 0e6f716076..192272f093 100644--- a/internal/deepdoc/native/det_core.go+++ b/internal/deepdoc/native/det_core.go@@ -82,18 +82,12 @@ var detSessions = newSessionPool[detSessKey, *session](detMaxShapePools, detShap// shape plus a release func. The caller must call release exactly once. On a// pool miss a fresh session is created; creation errors are propagated and// nothing is cached.-func getDetSession(modelPath string, rh, rw int64) (*session, func(), error) {+func getDetSession(ctx context.Context, modelPath string, rh, rw int64) (*session, func(), error) {key := detSessKey{modelPath, rh, rw}- return detSessions.Get(key, func() (*session, error) {- // intraOpThreads=1 is preserved as-is for the verified det parity- // (mean|Δ|≈4e-5 vs the Python reference). The historical comment that- // this avoids competing OpenCV findContours worker threads does NOT- // apply to this pure-Go port, where the postprocess runs fully- // synchronously after RunWithOptions returns. Re-confirm parity on the- // det fixtures before switching to 0 (all cores) to match DLA/TSR.+ return detSessions.Get(ctx, key, func() (*session, error) {return NewSession(modelPath, "x",[]int64{1, 3, rh, rw}, "sigmoid_0.tmp_0",- []int64{1, 1, rh, rw}, 1)+ []int64{1, 1, rh, rw})})}@@ -102,7 +96,7 @@ func getDetSession(modelPath string, rh, rw int64) (*session, func(), error) {// extraction uses the pure-Go connected-components backend.func RunDet(ctx context.Context, modelDir string, img *Image) (DetResult, error) {blob, rh, rw, sh, sw := detPreprocess(img)- sess, release, e := getDetSession(filepath.Join(modelDir, "det.ort"), int64(rh), int64(rw))+ sess, release, e := getDetSession(ctx, filepath.Join(modelDir, "det.ort"), int64(rh), int64(rw))if e != nil {return DetResult{}, e}diff --git a/internal/deepdoc/native/dla.go b/internal/deepdoc/native/dla.goindex 856ff1f1dd..356f189bb1 100644--- a/internal/deepdoc/native/dla.go+++ b/internal/deepdoc/native/dla.go@@ -57,11 +57,9 @@ var (// RunDLA runs layout detection on a page image.func RunDLA(ctx context.Context, modelDir string, img *Image) (DLAResult, error) {blob, sf := dlaPreprocess(img)- // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable- // parity (no contour extraction in the DLA Run path).- sess, release, err := getModelSession(filepath.Join(modelDir, "layout.ort"), "images",+ sess, release, err := getModelSession(ctx, filepath.Join(modelDir, "layout.ort"), "images",[]int64{1, 3, dlaInputSize, dlaInputSize}, "output0",- []int64{1, dlaMaxBoxes, 6}, 0)+ []int64{1, dlaMaxBoxes, 6})if err != nil {return DLAResult{}, err}diff --git a/internal/deepdoc/native/inference_limit.go b/internal/deepdoc/native/inference_limit.gonew file mode 100644index 0000000000..1e50e8e719--- /dev/null+++ b/internal/deepdoc/native/inference_limit.go@@ -0,0 +1,99 @@+//go:build cgo++package native++// inference_limit.go — the process-wide DeepDoc inference budget.+//+// ONNX Runtime gives every session its own intra-op thread pool (the C API+// never switches a session onto a shared/global pool), so the threads DeepDoc+// inference occupies in this process are (threads per session) × (sessions+// running at once). Sessions are created single-threaded (see the intraOpThreads+// constant in session.go), which leaves exactly one lever: how many Runs may be+// in flight at once.+//+// That lever lives here — at the one boundary every inference call passes+// through — instead of at the call sites, so neither a new caller nor a new call+// site inside an existing caller can bypass the budget by forgetting to acquire+// a slot.+//+// The capacity is a process resource policy and is deliberately NOT decided+// here: the process owner registers it at startup (the server's backend wiring+// calls SetInferenceLimit with the parser's budget). A process that never+// registers one stays unlimited, which is what a one-shot CLI or a test process+// wants.++import (+ "context"+ "sync"+)++// inferenceLimiter caps how many inference calls may run at once. A nil+// *inferenceLimiter admits everything, so an unregistered process needs no+// separate code path.+type inferenceLimiter struct {+ slots chan struct{}+}++func newInferenceLimiter(capacity int) *inferenceLimiter {+ if capacity < 1 {+ return nil+ }+ return &inferenceLimiter{slots: make(chan struct{}, capacity)}+}++// acquire takes a slot, waiting until one frees up or ctx is done.+func (l *inferenceLimiter) acquire(ctx context.Context) error {+ if l == nil {+ return nil+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case l.slots <- struct{}{}:+ return nil+ }+}++// release returns a slot taken by acquire.+func (l *inferenceLimiter) release() {+ if l == nil {+ return+ }+ <-l.slots+}++var (+ inferenceLimitOnce sync.Once+ processLimiter *inferenceLimiter+)++// SetInferenceLimit caps how many DeepDoc inference calls this process may run+// at once. It is meant to be called once, at startup, by the process owner:+// later calls are ignored, so the capacity can never change under calls that are+// already holding slots. n < 1 leaves the gate open (unlimited), which is also+// the state of a process that never calls this.+func SetInferenceLimit(n int) {+ inferenceLimitOnce.Do(func() {+ processLimiter = newInferenceLimiter(n)+ })+}++// InferenceLimit returns the registered capacity, or 0 when the process never+// registered one (unlimited). Startup wiring logs it so an unlimited process is+// visible rather than silently unbounded.+func InferenceLimit() int {+ if processLimiter == nil {+ return 0+ }+ return cap(processLimiter.slots)+}++// acquireInference takes one process-wide inference slot; releaseInference+// returns it. Both are no-ops when no limit was registered.+func acquireInference(ctx context.Context) error {+ return processLimiter.acquire(ctx)+}++func releaseInference() {+ processLimiter.release()+}diff --git a/internal/deepdoc/native/inference_limit_test.go b/internal/deepdoc/native/inference_limit_test.gonew file mode 100644index 0000000000..ff2a542800--- /dev/null+++ b/internal/deepdoc/native/inference_limit_test.go@@ -0,0 +1,117 @@+//go:build cgo++package native++import (+ "context"+ "errors"+ "testing"+ "time"+)++// Unit tests for the process-wide inference gate (inference_limit.go). They are+// model-free: the gate is exercised on its own, and the pool wiring is checked+// with a local pool whose constructor never touches ONNX Runtime.++// swapProcessLimiter installs l as the process gate for the duration of a test.+// The package-level value is normally written once at startup (SetInferenceLimit)+// and only read afterwards, so a test may swap it as long as it restores the+// previous value before the next test runs.+func swapProcessLimiter(l *inferenceLimiter) func() {+ old := processLimiter+ processLimiter = l+ return func() { processLimiter = old }+}++func TestInferenceLimitUnregisteredAdmitsEverything(t *testing.T) {+ if got := InferenceLimit(); got != 0 {+ t.Fatalf("unregistered process reports limit %d, want 0 (unlimited)", got)+ }+ if err := acquireInference(context.Background()); err != nil {+ t.Fatalf("acquire with no limit registered: %v", err)+ }+ releaseInference()+}++func TestInferenceLimiterQueuesWhenExhausted(t *testing.T) {+ l := newInferenceLimiter(1)+ ctx := context.Background()++ if err := l.acquire(ctx); err != nil {+ t.Fatalf("first acquire: %v", err)+ }++ second := make(chan error, 1)+ go func() { second <- l.acquire(ctx) }()++ select {+ case err := <-second:+ t.Fatalf("second acquire returned (%v) while the only slot was held", err)+ case <-time.After(200 * time.Millisecond):+ }++ l.release()+ select {+ case err := <-second:+ if err != nil {+ t.Fatalf("second acquire after release: %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("second acquire did not proceed after the slot was released")+ }+ l.release()+}++func TestInferenceLimiterHonorsContextCancellation(t *testing.T) {+ l := newInferenceLimiter(1)+ if err := l.acquire(context.Background()); err != nil {+ t.Fatalf("first acquire: %v", err)+ }+ defer l.release()++ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if err := l.acquire(ctx); !errors.Is(err, context.Canceled) {+ t.Fatalf("acquire on a cancelled context returned %v, want context.Canceled", err)+ }+}++// TestSessionPoolGetTakesInferenceSlot pins the wiring: a pool hands out no+// session while the process budget is exhausted, and proceeds once a slot frees+// up. The local pool's constructor fails on purpose — it must not even be+// reached before the slot is available.+func TestSessionPoolGetTakesInferenceSlot(t *testing.T) {+ restore := swapProcessLimiter(newInferenceLimiter(1))+ defer restore()++ if err := acquireInference(context.Background()); err != nil {+ t.Fatalf("hold slot: %v", err)+ }++ pool := newSessionPool[sessKey, *session](0, 0)+ constructed := make(chan struct{})+ errs := make(chan error, 1)+ go func() {+ _, _, err := pool.Get(context.Background(), sessKey{modelPath: "test"}, func() (*session, error) {+ close(constructed)+ return nil, errors.New("constructor reached")+ })+ errs <- err+ }()++ select {+ case <-constructed:+ t.Fatal("pool reached the session constructor while the inference budget was exhausted")+ case <-time.After(200 * time.Millisecond):+ }++ releaseInference()+ select {+ case err := <-errs:+ if err == nil || err.Error() != "constructor reached" {+ t.Fatalf("Get returned %v, want the constructor error", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("Get did not proceed after the inference slot was released")+ }+}diff --git a/internal/deepdoc/native/ocr_rec.go b/internal/deepdoc/native/ocr_rec.goindex e2bb8083a0..05daa459d9 100644--- a/internal/deepdoc/native/ocr_rec.go+++ b/internal/deepdoc/native/ocr_rec.go@@ -116,10 +116,8 @@ func RunOCRRecBatchReal(ctx context.Context, modelDir string, imgs []*Image) ([]copy(batch[i*lineStride:(i+1)*lineStride], b)}- // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable- // parity (no contour extraction in the OCR-rec Run path).- sess, release, err := getRecSession(filepath.Join(modelDir, "rec.ort"), "x",- []int64{int64(n), 3, recH, int64(imgW)}, "softmax_11.tmp_0", 0)+ sess, release, err := getRecSession(ctx, filepath.Join(modelDir, "rec.ort"), "x",+ []int64{int64(n), 3, recH, int64(imgW)}, "softmax_11.tmp_0")if err != nil {return nil, err}@@ -159,10 +157,8 @@ func recognizeLine(ctx context.Context, modelDir string, img *Image, maxWhRatioresizedW = imgW}blob := ocrRecPreprocess(img, resizedW, imgW)- // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable- // parity (no contour extraction in the OCR-rec Run path).- sess, release, err := getRecSession(filepath.Join(modelDir, "rec.ort"), "x",- []int64{recMaxBatch, 3, recH, int64(imgW)}, "softmax_11.tmp_0", 0)+ sess, release, err := getRecSession(ctx, filepath.Join(modelDir, "rec.ort"), "x",+ []int64{recMaxBatch, 3, recH, int64(imgW)}, "softmax_11.tmp_0")if err != nil {return OCRRecResult{}, err}@@ -304,7 +300,7 @@ type recSession struct {poisoned bool}-func newRecSession(modelPath, inName string, inShape []int64, outName string, intraOpThreads int) (*recSession, error) {+func newRecSession(modelPath, inName string, inShape []int64, outName string) (*recSession, error) {in := make([]float32, prod(inShape))inT, err := ort.NewTensor(ort.NewShape(inShape...), in)if err != nil {@@ -315,9 +311,8 @@ func newRecSession(modelPath, inName string, inShape []int64, outName string, ininT.Destroy()return nil, err}- // 0 → all cores (mirrors Python's onnxruntime default); OCR-rec does no- // contour extraction in the Run path, so parallelism is safe and matches- // deepdoc's reduction order for bit-stable parity.+ // One intra-op thread per session, matching NewSession: see the+ // intraOpThreads constant in session.go.if err := opts.SetIntraOpNumThreads(intraOpThreads); err != nil {opts.Destroy()inT.Destroy()diff --git a/internal/deepdoc/native/session.go b/internal/deepdoc/native/session.goindex 7c65a25d07..c50e7057ee 100644--- a/internal/deepdoc/native/session.go+++ b/internal/deepdoc/native/session.go@@ -22,6 +22,17 @@ import (ort "github.com/infiniflow/onnxruntime_go")+// intraOpThreads is the intra-op thread count every session is opened with.+//+// ONNX Runtime gives each session its own intra-op thread pool (the C API+// never switches a session onto a shared/global pool), so the threads DeepDoc+// inference occupies in this process are intraOpThreads × the number of+// concurrently running sessions. Pinning it to 1 keeps every Run to a single+// thread, which is what makes the process ceiling a plain concurrency budget:+// the capacity registered in inference_limit.go bounds how many Runs may be in+// flight, and each of them costs exactly one thread.+const intraOpThreads = 1+var (ortOnce sync.OnceortInitErr error@@ -79,25 +90,12 @@ type session struct {}// NewSession opens modelPath. inShape/outShape describe the fixed tensor-// dimensions; outSize is the total element count of the output tensor.-// intraOpThreads controls ONNX Runtime's intra-op parallelism. DLA/TSR/OCR-rec-// pass 0 to use all cores — matching deepdoc's Python onnxruntime-// (intra_op_num_threads defaults to 0 = all cores); their Run path does no-// contour extraction, so the parallel reduction order matches Python for-// bit-stable parity.-//-// The DB text detector is currently pinned to 1 (single-threaded). NOTE: the-// historical rationale for this — that a multi-threaded Run would leave ONNX-// Runtime worker threads settling while the postprocess's OpenCV findContours-// ran its parallel_for_ and under-ran — does NOT apply to this pure-Go port.-// Here the postprocess (hand-rolled findContours / boxScoreFast / fillPoly) is-// fully synchronous and only runs after RunWithOptions returns, so there is no-// thread competition with the detector. The pin is preserved as-is because the-// det pred map was verified at intraOpThreads=1 (mean|Δ|≈4e-5 vs the Python-// reference); flipping it to 0 must be re-confirmed on the det integration-// fixtures before landing, since the reduction order differs.-// InitORT must have been called first.-func NewSession(modelPath, inName string, inShape []int64, outName string, outShape []int64, intraOpThreads int) (*session, error) {+// dimensions; outSize is the total element count of the output tensor. The+// session runs intraOpThreads intra-op threads (see the constant): one thread+// per Run, with the process-wide ceiling owned by the inference budget the+// process owner registers (see inference_limit.go). InitORT must have been+// called first.+func NewSession(modelPath, inName string, inShape []int64, outName string, outShape []int64) (*session, error) {in := make([]float32, prod(inShape))out := make([]float32, prod(outShape))inT, err := ort.NewTensor(ort.NewShape(inShape...), in)@@ -115,10 +113,9 @@ func NewSession(modelPath, inName string, inShape []int64, outName string, outShoutT.Destroy()return nil, err}- // intraOpThreads == 0 → all cores (mirrors Python's onnxruntime default);- // the DB detector passes 1, preserved as-is for verified det parity (see- // NewSession doc above — the old findContours/parallel_for_ rationale does- // not apply to this pure-Go port).+ // One intra-op thread per session: the session's Runs then cost one thread+ // each, so the process-wide inference ceiling is exactly the number of+ // concurrent Runs the caller admits (see the intraOpThreads constant).if err := opts.SetIntraOpNumThreads(intraOpThreads); err != nil {opts.Destroy()inT.Destroy()diff --git a/internal/deepdoc/native/session_pool.go b/internal/deepdoc/native/session_pool.goindex 0ea8d89509..5d3e23869f 100644--- a/internal/deepdoc/native/session_pool.go+++ b/internal/deepdoc/native/session_pool.go@@ -30,6 +30,7 @@ package native// degenerate case for the fixed-shape recognizers, whose key set is tiny.import (+ "context""reflect""strconv""strings"@@ -75,7 +76,25 @@ func newSessionPool[K comparable, V pooledSession](maxKeys, maxFree int) *sessio// miss, plus a release func. The caller must call release exactly once. A// poisoned session is Destroyed on release rather than pooled (ORT does not// guarantee reuse safety after a forced termination).-func (p *sessionPool[K, V]) Get(key K, newFn func() (V, error)) (V, func(), error) {+//+// Get takes a process-wide inference slot before it hands out a session and+// returns that slot from release, so the slot is held for the whole hold window+// (session construction on a miss, then the caller's Run). This is what makes+// the process inference budget real; see inference_limit.go.+func (p *sessionPool[K, V]) Get(ctx context.Context, key K, newFn func() (V, error)) (V, func(), error) {+ if err := acquireInference(ctx); err != nil {+ var zero V+ return zero, nil, err+ }+ slotReturned := false+ returnSlot := func() {+ if slotReturned {+ return+ }+ slotReturned = true+ releaseInference()+ }+p.mu.Lock()kp := p.pools[key]if kp == nil {@@ -102,12 +121,14 @@ func (p *sessionPool[K, V]) Get(key K, newFn func() (V, error)) (V, func(), errovar err errors, err = newFn()if err != nil {+ returnSlot()var zero Vreturn zero, nil, err}}release := func() {+ defer returnSlot()if s.isPoisoned() {s.Destroy()return@@ -181,17 +202,15 @@ func (p *sessionPool[K, V]) evictLRU() {type sessKey struct {modelPath, inName, outName stringinShape, outShape string- intraOpThreads int}-func sessKeyOf(modelPath, inName string, inShape []int64, outName string, outShape []int64, intraOpThreads int) sessKey {+func sessKeyOf(modelPath, inName string, inShape []int64, outName string, outShape []int64) sessKey {return sessKey{- modelPath: modelPath,- inName: inName,- outName: outName,- inShape: shapeKey(inShape),- outShape: shapeKey(outShape),- intraOpThreads: intraOpThreads,+ modelPath: modelPath,+ inName: inName,+ outName: outName,+ inShape: shapeKey(inShape),+ outShape: shapeKey(outShape),}}@@ -209,10 +228,10 @@ var modelSessions = newSessionPool[sessKey, *session](0, 0)// getModelSession returns a reusable session for the given model signature plus// a release func. The caller must call release exactly once.-func getModelSession(modelPath, inName string, inShape []int64, outName string, outShape []int64, intraOpThreads int) (*session, func(), error) {- key := sessKeyOf(modelPath, inName, inShape, outName, outShape, intraOpThreads)- return modelSessions.Get(key, func() (*session, error) {- return NewSession(modelPath, inName, inShape, outName, outShape, intraOpThreads)+func getModelSession(ctx context.Context, modelPath, inName string, inShape []int64, outName string, outShape []int64) (*session, func(), error) {+ key := sessKeyOf(modelPath, inName, inShape, outName, outShape)+ return modelSessions.Get(ctx, key, func() (*session, error) {+ return NewSession(modelPath, inName, inShape, outName, outShape)})}@@ -225,16 +244,14 @@ func getModelSession(modelPath, inName string, inShape []int64, outName string,type recKey struct {modelPath, inName, outName stringinShape string- intraOpThreads int}-func recKeyOf(modelPath, inName string, inShape []int64, outName string, intraOpThreads int) recKey {+func recKeyOf(modelPath, inName string, inShape []int64, outName string) recKey {return recKey{- modelPath: modelPath,- inName: inName,- outName: outName,- inShape: shapeKey(inShape),- intraOpThreads: intraOpThreads,+ modelPath: modelPath,+ inName: inName,+ outName: outName,+ inShape: shapeKey(inShape),}}@@ -257,9 +274,9 @@ var recSessions = newSessionPool[recKey, *recSession](recMaxShapePools, recShape// getRecSession returns a reusable dynamic-width OCR-rec session for the given// input width plus a release func. The caller must call release exactly once.-func getRecSession(modelPath, inName string, inShape []int64, outName string, intraOpThreads int) (*recSession, func(), error) {- key := recKeyOf(modelPath, inName, inShape, outName, intraOpThreads)- return recSessions.Get(key, func() (*recSession, error) {- return newRecSession(modelPath, inName, inShape, outName, intraOpThreads)+func getRecSession(ctx context.Context, modelPath, inName string, inShape []int64, outName string) (*recSession, func(), error) {+ key := recKeyOf(modelPath, inName, inShape, outName)+ return recSessions.Get(ctx, key, func() (*recSession, error) {+ return newRecSession(modelPath, inName, inShape, outName)})}diff --git a/internal/deepdoc/native/session_pool_stress_test.go b/internal/deepdoc/native/session_pool_stress_test.goindex da0dc38828..01cd75190c 100644--- a/internal/deepdoc/native/session_pool_stress_test.go+++ b/internal/deepdoc/native/session_pool_stress_test.go@@ -3,6 +3,7 @@package nativeimport (+ "context""sync""sync/atomic""testing"@@ -60,7 +61,7 @@ func TestSessionPoolConcurrentGetReleaseStress(t *testing.T) {// Rotate the key across more distinct values than maxKeys so the// LRU eviction path is exercised under contention.key := (g + i) % (maxKeys * 2)- s, release, err := p.Get(key, newFn)+ s, release, err := p.Get(context.Background(), key, newFn)if err != nil {t.Errorf("Get(%d): %v", key, err)returndiff --git a/internal/deepdoc/native/tsr.go b/internal/deepdoc/native/tsr.goindex 99f7d490e2..49fdee7a8d 100644--- a/internal/deepdoc/native/tsr.go+++ b/internal/deepdoc/native/tsr.go@@ -44,11 +44,9 @@ type TSRResult struct {// RunTSR runs table-structure recognition on a cropped table image.func RunTSR(ctx context.Context, modelDir string, img *Image) (TSRResult, error) {blob, sf := tsrPreprocess(img)- // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable- // parity (no contour extraction in the TSR Run path).- sess, release, err := getModelSession(filepath.Join(modelDir, "tsr.ort"), "images",+ sess, release, err := getModelSession(ctx, filepath.Join(modelDir, "tsr.ort"), "images",[]int64{1, 3, tsrInputSize, tsrInputSize}, "output0",- []int64{1, 11, tsrCandidates}, 0)+ []int64{1, 11, tsrCandidates})if err != nil {return TSRResult{}, err}diff --git a/internal/deepdoc/parser/pdf/parser.go b/internal/deepdoc/parser/pdf/parser.goindex 859d9407b2..69ea43f0c0 100644--- a/internal/deepdoc/parser/pdf/parser.go+++ b/internal/deepdoc/parser/pdf/parser.go@@ -7,7 +7,6 @@ import ("log/slog""math""sort"- "sync"lyt "ragflow/internal/deepdoc/parser/pdf/layout"tbl "ragflow/internal/deepdoc/parser/pdf/table"@@ -21,12 +20,6 @@ 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 worker-local artifacts produced bydiff --git a/internal/deepdoc/parser/pdf/parser_concurrency.go b/internal/deepdoc/parser/pdf/parser_concurrency.goindex 9a54479d18..a6a96ccc63 100644--- a/internal/deepdoc/parser/pdf/parser_concurrency.go+++ b/internal/deepdoc/parser/pdf/parser_concurrency.go@@ -10,14 +10,20 @@ import ("ragflow/internal/utility")-// ── Internal concurrency guards ──────────────────────────────────────────+// ── Process inference budget ─────────────────────────────────────────────//-// 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.+// Real page parallelism exposes the parser to multiplicative DeepDoc inference+// fan-out (DLA + TSR per table region + OCR per region). Every ONNX session runs+// single-threaded (see the intraOpThreads constant in the native package), so the+// threads DeepDoc inference occupies in this process are exactly the number of+// Runs in flight at once — one number to bound.+//+// That number is decided here, by the caller: DeepDocConcurrency() is this+// process's share of the CPUs, and it is (a) registered with the native gate+// every inference call passes through (native.SetInferenceLimit, called by the+// server's backend wiring) and (b) used to size the page worker pool. It is+// deliberately not user-configurable, so callers never 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@@ -26,56 +32,23 @@ import (// 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-)+// deepdocInferenceCPUShare is the share of the process's CPUs DeepDoc+// inference may occupy. The remainder is headroom for the Go runtime, PDFium,+// and I/O sharing the same cores.+const deepdocInferenceCPUShare = 0.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()+// DeepDocConcurrency returns how many DeepDoc ONNX Runs this process may have in+// flight at once — its inference budget. Sessions run single-threaded, so this+// is also the number of threads inference occupies.+//+// The share is taken from GOMAXPROCS, not runtime.NumCPU: GOMAXPROCS is what+// the process is actually allowed to use (it honours a cgroup CPU quota), while+// NumCPU reports the host's cores inside a container.+func DeepDocConcurrency() int {+ return max(1, int(deepdocInferenceCPUShare*float64(runtime.GOMAXPROCS(0))))}-// ── Parser-owned limiter accessors ────────────────────────────────────────+// ── Page worker pool ─────────────────────────────────────────────────────// pageTask holds the per-page work handed to the shared worker pool.type pageTask struct {@@ -93,9 +66,16 @@ var (pagePool *utility.WorkerPool[pageTask, pageResult])+// defaultPageWorkerCount sizes the shared page worker pool from the process+// inference budget: workers beyond that budget only queue rendered bitmaps in+// memory while they wait for an inference slot.+func defaultPageWorkerCount() int {+ return min(runtime.GOMAXPROCS(0), DeepDocConcurrency())+}+func parserPageWorkerPool() *utility.WorkerPool[pageTask, pageResult] {pagePoolOnce.Do(func() {- workers := runtime.GOMAXPROCS(0) * 2+ workers := defaultPageWorkerCount()if workers <= 0 {workers = 1}@@ -113,24 +93,24 @@ func PageWorkerPoolStats() utility.WorkerPoolStats {return parserPageWorkerPool().Stats()}-// SetPageWorkerPoolSize adjusts the process-wide PDF page worker pool size.+// SetPageWorkerPoolSize adjusts the process-wide PDF page worker pool size,+// clamped to the process inference budget. Workers beyond that budget have no+// throughput to gain — rendering is serialized by pdfsync.Mu and inference by+// the native gate — so they only add CPU contention and hold more rendered+// bitmaps while they wait. A size of zero or less still panics, as in Resize.func SetPageWorkerPoolSize(workers int) {+ if budget := DeepDocConcurrency(); workers > budget {+ workers = budget+ }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 ─────────────────────────────+//+// These wrappers guard health and shape, not the process inference budget: that+// budget is enforced inside the native backend, at the one boundary every ONNX+// Run passes through (see native.inference_limit.go), so a call site cannot+// escape it by not going through a wrapper.// renderPageToImage renders a page at the default DLA DPI. Native PDFium// access inside the engine is serialized by the process-wide pdfsync.Mu@@ -145,82 +125,40 @@ func (p *Parser) renderAtDPI(ctx context.Context, eng pdf.PDFEngine, pageNum intreturn 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.+// inferDLA invokes the per-page DLA call for a healthy analyzer. Page workers+// and enrichOnePageWithDeepDoc callers route through this wrapper so an+// unavailable analyzer degrades to "no regions" instead of an error.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+ return doc.DLA(ctx, pageImg)}-// 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.+// inferTSR invokes TSR for a single cropped table region.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+ return tb.DetectCells(ctx, cropped)}-// inferOCRDetect routes doc.OCRDetect through the inference limiter.-// ocrMergeChars and ocrDetectAndRecognize callers should funnel-// through this helper.+// inferOCRDetect invokes OCR detection for a healthy analyzer. ocrMergeChars and+// ocrDetectAndRecognize callers 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+ return doc.OCRDetect(ctx, pageImg)}-// inferOCRRecognize routes doc.OCRRecognize through the inference-// limiter. Per-region OCR fallback paths (buildTextBoxes) should use this-// wrapper so the per-region fan-out is bounded.+// inferOCRRecognize invokes OCR recognition for a healthy analyzer.+// Per-region OCR fallback paths (buildTextBoxes) use this wrapper.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+ return doc.OCRRecognize(ctx, cropped)}// batchRecognizer is an OPTIONAL capability a pdf.DocAnalyzer may implement to@@ -236,11 +174,11 @@ type batchRecognizer interface {OCRRecognizeBatch(ctx context.Context, imgs []image.Image) ([][]pdf.OCRText, error)}-// inferOCRRecognizeBatch routes a batch of crops through the inference limiter-// in a single slot. It is only safe to call after a type assertion confirms-// doc implements batchRecognizer. The whole batch consumes one limiter slot-// (instead of one per crop), which is both correct (one ONNX Run) and a-// throughput win. An empty slice returns nil without touching the analyzer.+// inferOCRRecognizeBatch recognizes a batch of crops in one call. It is only+// safe to call after a type assertion confirms doc implements batchRecognizer.+// The whole batch is a single ONNX Run, so it costs the process budget one+// inference slot rather than one per crop — a throughput win as well. An empty+// slice returns nil without touching the analyzer.func (p *Parser) inferOCRRecognizeBatch(ctx context.Context, doc pdf.DocAnalyzer, crops []image.Image) ([][]pdf.OCRText, error) {br, ok := doc.(batchRecognizer)if !ok || len(crops) == 0 {@@ -249,16 +187,7 @@ func (p *Parser) inferOCRRecognizeBatch(ctx context.Context, doc pdf.DocAnalyzerif doc == nil || !doc.Health() {return nil, nil}- var results [][]pdf.OCRText- err := p.limiters().withSlot(ctx, func() error {- r, callErr := br.OCRRecognizeBatch(ctx, crops)- if callErr != nil {- return callErr- }- results = r- return nil- })- return results, err+ return br.OCRRecognizeBatch(ctx, crops)}// docSupportsBatchOCR reports whether doc implements the optional batched OCRdiff --git a/internal/deepdoc/parser/pdf/parser_parallel_test.go b/internal/deepdoc/parser/pdf/parser_parallel_test.goindex cd7d598784..a6b9253fd0 100644--- a/internal/deepdoc/parser/pdf/parser_parallel_test.go+++ b/internal/deepdoc/parser/pdf/parser_parallel_test.go@@ -8,6 +8,7 @@ import ("image""image/png""reflect"+ "runtime""sync""testing"@@ -89,6 +90,38 @@ func TestParser_RunPageWorkers_DeterministicOrder(t *testing.T) {}}+func TestDefaultPageWorkersTrackInferenceCapacity(t *testing.T) {+ if got, budget := defaultPageWorkerCount(), DeepDocConcurrency(); got > budget {+ t.Fatalf("got %d page workers, want at most %d (process inference budget)", got, budget)+ }+}++// TestDeepDocConcurrencyShare pins the process budget rule: DeepDoc inference+// may have floor(80% of the CPUs available to the process) Runs in flight.+func TestDeepDocConcurrencyShare(t *testing.T) {+ want := int(deepdocInferenceCPUShare * float64(runtime.GOMAXPROCS(0)))+ if got := DeepDocConcurrency(); got != max(1, want) {+ t.Fatalf("got %d concurrent Runs, want %d (GOMAXPROCS=%d)",+ got, max(1, want), runtime.GOMAXPROCS(0))+ }+}++// TestSetPageWorkerPoolSizeClampsToBudget pins the setter's contract: the page+// worker pool never grows past the process inference budget, because workers+// beyond it cannot add throughput — rendering is serialized by pdfsync.Mu and+// inference by the native gate — and only contend for the CPUs the budget+// already accounts for.+func TestSetPageWorkerPoolSizeClampsToBudget(t *testing.T) {+ orig := PageWorkerPoolStats().DesiredWorkers+ t.Cleanup(func() { parserPageWorkerPool().Resize(orig) })++ budget := DeepDocConcurrency()+ SetPageWorkerPoolSize(budget + 8)+ if got := PageWorkerPoolStats().DesiredWorkers; got != budget {+ t.Fatalf("worker pool resized to %d, want the budget %d", got, budget)+ }+}+func TestParser_RunPageWorkers_PoolSize4_DeterministicOrder(t *testing.T) {mock := &MockDocAnalyzer{Healthy: true}eng := makeMultiPageEngine(8)@@ -485,13 +518,15 @@ func sortPages(pages []int) {}// 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.+// a test and restores the prior size afterwards. It drives the pool directly+// instead of going through SetPageWorkerPoolSize, whose public contract clamps+// the size to the process inference budget; tests need to exercise sizes on+// either side of that bound.func setPoolSize(t *testing.T, n int) {t.Helper()orig := PageWorkerPoolStats().DesiredWorkers- SetPageWorkerPoolSize(n)- t.Cleanup(func() { SetPageWorkerPoolSize(orig) })+ parserPageWorkerPool().Resize(n)+ t.Cleanup(func() { parserPageWorkerPool().Resize(orig) })}// imageHash produces a stable PNG-content fingerprint for an image sodiff --git a/internal/deepdoc/parser/pdf/pdf_benchmark_integration_test.go b/internal/deepdoc/parser/pdf/pdf_benchmark_integration_test.gonew file mode 100644index 0000000000..fa9497f6f6--- /dev/null+++ b/internal/deepdoc/parser/pdf/pdf_benchmark_integration_test.go@@ -0,0 +1,62 @@+//go:build cgo && integration++package pdf++import (+ "os"+ "runtime"+ "syscall"+ "testing"++ "ragflow/internal/deepdoc/native"+ infnative "ragflow/internal/deepdoc/parser/pdf/inference/native_analyzer"+ pdf "ragflow/internal/deepdoc/parser/pdf/type"+)++func BenchmarkNativePDFParse(b *testing.B) {+ path := os.Getenv("DEEPDOC_BENCH_PDF")+ if path == "" {+ b.Skip("set DEEPDOC_BENCH_PDF")+ }+ modelDir := os.Getenv("DEEPDOC_MODEL_DIR")+ if modelDir == "" {+ b.Skip("set DEEPDOC_MODEL_DIR")+ }+ data, err := os.ReadFile(path)+ if err != nil {+ b.Fatal(err)+ }+ if err := native.InitORT(); err != nil {+ b.Fatal(err)+ }+ analyzer, err := infnative.NewAnalyzer(modelDir, infnative.DefaultDropScore)+ if err != nil {+ b.Fatal(err)+ }+ parser := NewParser(pdf.DefaultParserConfig())++ b.ReportAllocs()+ b.SetBytes(int64(len(data)))+ b.ResetTimer()+ for range b.N {+ result, err := parser.Parse(b.Context(), data, analyzer)+ if err != nil {+ b.Fatal(err)+ }+ if len(result.Sections) == 0 {+ result.Close()+ b.Fatal("parser returned no sections")+ }+ result.Close()+ }+ b.StopTimer()+ var usage syscall.Rusage+ if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err != nil {+ b.Fatal(err)+ }+ maxrss := float64(usage.Maxrss)+ if runtime.GOOS == "darwin" {+ maxrss /= 1024+ }+ b.ReportMetric(maxrss/1024, "peak-RSS-MiB")+}