Skip to content

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

refactor(config): nest DeepDoc inference config under ingestor; add cpu-cores budget + fail-fast (#20084)

xugangqiang52a0199c6e55
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go
index bd889a213a..f41a82e908 100644
--- a/cmd/ragflow_server.go
+++ b/cmd/ragflow_server.go
@@ -90,6 +90,9 @@ type serverArgs struct {
// deepdocInferenceConcurrency, when set, overrides the DeepDoc inference
// concurrency from env/config. nil means "unspecified".
deepdocInferenceConcurrency *int
+ // deepdocInferenceCPUCores, when set, overrides the DeepDoc inference CPU-core
+ // budget from env/config. nil means "unspecified" (0 means "all cores").
+ deepdocInferenceCPUCores *int
}
func parseArgs() (*serverArgs, error) {
@@ -118,6 +121,16 @@ func parseArgs() (*serverArgs, error) {
}
args.deepdocInferenceConcurrency = &n
continue
+ case "--deepdoc-inference-cpu-cores":
+ n, convErr := strconv.Atoi(value)
+ if convErr != nil {
+ return nil, fmt.Errorf("invalid --deepdoc-inference-cpu-cores: %w", convErr)
+ }
+ if n < 0 {
+ return nil, fmt.Errorf("invalid --deepdoc-inference-cpu-cores %d: must be >= 0 (0 means all cores)", n)
+ }
+ args.deepdocInferenceCPUCores = &n
+ continue
}
}
@@ -213,6 +226,19 @@ func parseArgs() (*serverArgs, error) {
return nil, fmt.Errorf("invalid --deepdoc-inference-concurrency %d: must be positive", n)
}
args.deepdocInferenceConcurrency = &n
+ case "--deepdoc-inference-cpu-cores":
+ if i+1 >= len(os.Args) {
+ return nil, errors.New("--deepdoc-inference-cpu-cores requires a value")
+ }
+ i++
+ n, convErr := strconv.Atoi(os.Args[i])
+ if convErr != nil {
+ return nil, fmt.Errorf("invalid --deepdoc-inference-cpu-cores: %w", convErr)
+ }
+ if n < 0 {
+ return nil, fmt.Errorf("invalid --deepdoc-inference-cpu-cores %d: must be >= 0 (0 means all cores)", n)
+ }
+ args.deepdocInferenceCPUCores = &n
default:
return nil, fmt.Errorf("unknown parameter: %s", arg)
}
@@ -242,28 +268,6 @@ func selectedLogLevel(args *serverArgs, configured string) string {
return configured
}
-// resolveDeepDocInferenceConcurrency applies the precedence
-// CLI flag > environment variable > config file > default(4) and returns the
-// resolved DeepDoc inference concurrency budget.
-func resolveDeepDocInferenceConcurrency(args *serverArgs, configured int) int {
- val := 4
- if configured > 0 {
- val = configured
- }
- if v := strings.TrimSpace(os.Getenv(common.EnvDeepDocInferenceConcurrency)); v != "" {
- if n, err := strconv.Atoi(v); err == nil && n > 0 {
- val = n
- }
- }
- // The CLI parser rejects a non-positive --deepdoc-inference-concurrency
- // up front (see TestParseArgsDeepDocInferenceConcurrency), so the parsed
- // value is already positive; no extra >0 guard is needed here.
- if args.deepdocInferenceConcurrency != nil {
- val = *args.deepdocInferenceConcurrency
- }
- return val
-}
-
func printHelp(args *serverArgs) {
switch {
case args.mode == nil || *args.mode == "migrate":
@@ -1433,6 +1437,23 @@ func configureTTSSynthesizer(modelProviderService *service.ModelProviderService)
common.Info("agent: TTS model-provider dispatch installed (audio.Synthesize → ModelProviderService.AudioSpeech)")
}
+// inferenceTotalCores returns the CPU budget the DeepDoc inference config is
+// validated against. It uses runtime.GOMAXPROCS(0) instead of runtime.NumCPU()
+// so the budget reflects the cgroup CPU quota inside containers: Go 1.25+ derives
+// GOMAXPROCS from the quota (CGroups v2 cpu.max / v1 cpu.cfs_quota_us), whereas
+// runtime.NumCPU() reports the host's affinity-mask core count and ignores a
+// container's CPU limit. Without this, a 2-CPU-limit pod on a 64-core host would
+// "resolve" inference_cpu_cores: 0 to 64 and let inference_concurrency: 16 pass
+// validation, oversubscribing the box the fail-fast guard in
+// native.ValidateInferenceConfig exists to prevent.
+func inferenceTotalCores() int {
+ n := goruntime.GOMAXPROCS(0)
+ if n < 1 {
+ return 1
+ }
+ return n
+}
+
// registerNativeDeepDoc wires the in-process (Go) DeepDoc backend as the local
// inference backend. The server is built with -tags cgo and links ONNX Runtime
// statically (libonnxruntime.a, resolved at runtime via dlopen(NULL) from the
@@ -1465,16 +1486,49 @@ func registerNativeDeepDoc(arguments *serverArgs) {
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. Resolve it from CLI > env > config > default(4)
- // and 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.
- budget := resolveDeepDocInferenceConcurrency(arguments, server.GetConfig().GetDeepDocConfig().InferenceConcurrency)
- pdf.SetDeepDocConcurrency(budget)
- native.SetInferenceLimit(budget)
+ // Resolve the DeepDoc in-process inference configuration: the concurrency
+ // budget K (max in-flight Runs) and the CPU-core budget N (max cores
+ // inference may occupy). Both resolve from CLI > env > config > default. K
+ // defaults to 1; N defaults to "unset", which is derived from K so each Run
+ // stays single-threaded by default (the prior behaviour). An explicit N = 0
+ // means "all cores". All values are fail-fast validated against the process's
+ // cgroup-aware CPU budget at startup (see native.ValidateInferenceConfig and
+ // inferenceTotalCores), so a misconfiguration aborts rather than silently
+ // oversubscribing the box.
+ cfg := server.GetConfig()
+ K, _, errK := cfg.ResolveDeepDocInferenceConcurrency(arguments.deepdocInferenceConcurrency)
+ if errK != nil {
+ common.Fatal("invalid deepdoc inference concurrency", zap.Error(errK))
+ }
+ rawN, explicitN, errN := cfg.ResolveDeepDocInferenceCPUCores(arguments.deepdocInferenceCPUCores)
+ if errN != nil {
+ common.Fatal("invalid deepdoc inference cpu cores", zap.Error(errN))
+ }
+ // When N is unset, derive it from K so each Run opens with a single intra-op
+ // thread (coresPerInference = max(1, K/K) = 1), preserving the prior
+ // single-core-per-run semantics. An explicit N (including 0 = all cores) is
+ // honoured as-is below.
+ resolvedN := rawN
+ if !explicitN {
+ resolvedN = K
+ }
+ totalCores := inferenceTotalCores()
+ // Validate K and N against the process's CPU budget (cgroup-aware) and
+ // derive the per-Run intra-op thread count (max(1, N/K)). N == 0 resolves to
+ // all cores here.
+ coresPerInference, totalCPUCores, errV := native.ValidateInferenceConfig(totalCores, resolvedN, K)
+ if errV != nil {
+ common.Fatal("invalid deepdoc inference configuration", zap.Error(errV))
+ }
+ // Register the per-session intra-op thread count before any model session is
+ // created (the native package reads it on every SessionOptions build).
+ native.SetIntraOpThreads(coresPerInference)
+ pdf.SetDeepDocConcurrency(K)
+ native.SetInferenceLimit(K)
common.Info("in-process DeepDoc inference limit registered",
- zap.Int("max_concurrent_inference", budget),
+ zap.Int("max_concurrent_inference", K),
+ zap.Int("cpu_cores_per_inference", coresPerInference),
+ zap.Int("total_cpu_cores_budget", totalCPUCores),
zap.Int("gomaxprocs", goruntime.GOMAXPROCS(0)))
}
diff --git a/cmd/ragflow_server_deepdoc_test.go b/cmd/ragflow_server_deepdoc_test.go
index 74deac3a19..91068e5db2 100644
--- a/cmd/ragflow_server_deepdoc_test.go
+++ b/cmd/ragflow_server_deepdoc_test.go
@@ -18,49 +18,18 @@ package main
import (
"os"
+ goruntime "runtime"
"testing"
- "ragflow/internal/common"
+ "github.com/spf13/viper"
+ native "ragflow/internal/deepdoc/native"
+ server "ragflow/internal/server/config"
)
-// TestResolveDeepDocInferenceConcurrency pins the precedence
-// CLI > environment > config file > default(4).
-func TestResolveDeepDocInferenceConcurrency(t *testing.T) {
- const envKey = common.EnvDeepDocInferenceConcurrency
-
- cases := []struct {
- name string
- configured int
- env string // "" means leave unset
- cli *int
- want int
- }{
- {"default", 0, "", nil, 4},
- {"config only", 6, "", nil, 6},
- {"env overrides config", 6, "8", nil, 8},
- {"cli overrides env and config", 6, "8", intPtr(12), 12},
- {"env invalid falls back to config", 6, "notanint", nil, 6},
- {"env only", 0, "9", nil, 9},
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- // t.Setenv restores the previous value after the subtest.
- t.Setenv(envKey, tc.env)
- args := &serverArgs{deepdocInferenceConcurrency: tc.cli}
- if got := resolveDeepDocInferenceConcurrency(args, tc.configured); got != tc.want {
- t.Fatalf("got %d, want %d (configured=%d env=%q cli=%v)",
- got, tc.want, tc.configured, tc.env, tc.cli)
- }
- })
- }
-}
-
-func intPtr(n int) *int { return &n }
-
// TestParseArgsDeepDocInferenceConcurrency pins the contract that the CLI parser
// rejects a non-positive or non-integer --deepdoc-inference-concurrency up front
// (both the "--flag=value" and "--flag value" forms), and accepts a positive
-// value. Because the parser guarantees a positive value, resolveDeepDocInference
+// value. Because the parser guarantees a positive value, ResolveDeepDocInference
// Concurrency can trust the parsed pointer and needs no extra >0 guard.
func TestParseArgsDeepDocInferenceConcurrency(t *testing.T) {
cases := []struct {
@@ -100,3 +69,119 @@ func TestParseArgsDeepDocInferenceConcurrency(t *testing.T) {
})
}
}
+
+// TestParseArgsDeepDocInferenceCPUCores pins the contract that the CLI parser
+// accepts a non-negative --deepdoc-inference-cpu-cores (0 means "all cores"),
+// and rejects a negative or non-integer value (both forms).
+func TestParseArgsDeepDocInferenceCPUCores(t *testing.T) {
+ cases := []struct {
+ name string
+ args []string
+ wantErr bool
+ want int
+ }{
+ {"equals zero valid", []string{"prog", "--deepdoc-inference-cpu-cores=0"}, false, 0},
+ {"equals positive", []string{"prog", "--deepdoc-inference-cpu-cores=4"}, false, 4},
+ {"space positive", []string{"prog", "--deepdoc-inference-cpu-cores", "4"}, false, 4},
+ {"equals negative", []string{"prog", "--deepdoc-inference-cpu-cores=-1"}, true, 0},
+ {"equals nonint", []string{"prog", "--deepdoc-inference-cpu-cores=abc"}, true, 0},
+ {"space nonint", []string{"prog", "--deepdoc-inference-cpu-cores", "abc"}, true, 0},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ old := os.Args
+ defer func() { os.Args = old }()
+ os.Args = tc.args
+
+ got, err := parseArgs()
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("parseArgs() = nil error, want rejection for %v", tc.args)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("parseArgs() error = %v, want nil for %v", err, tc.args)
+ }
+ if got.deepdocInferenceCPUCores == nil || *got.deepdocInferenceCPUCores != tc.want {
+ t.Fatalf("deepdocInferenceCPUCores = %v, want %d for %v", got.deepdocInferenceCPUCores, tc.want, tc.args)
+ }
+ })
+ }
+}
+
+// TestValidateInferenceConfigKNExceedsBudget pins the CPU-core budget N as a hard
+// ceiling via the same exported function the server calls at startup. When K > N,
+// max(1, N/K) floors at 1 so total occupancy would be K, oversubscribing the box
+// beyond N.
+func TestValidateInferenceConfigKNExceedsBudget(t *testing.T) {
+ if _, _, err := native.ValidateInferenceConfig(8, 2, 8); err == nil {
+ t.Fatal("expected error when concurrency K=8 exceeds cpu-core budget N=2")
+ }
+ if c, total, err := native.ValidateInferenceConfig(8, 4, 2); err != nil {
+ t.Fatalf("unexpected error for K<=N: %v", err)
+ } else if c != 2 || total != 4 {
+ t.Fatalf("coresPerInference=%d totalCPUCores=%d, want 2/4", c, total)
+ }
+}
+
+// TestRegisterNativeDeepDocDefaultBootsOnSmallMachine pins the startup contract
+// that the shipped default configuration (both deepdoc keys unset, so K defaults
+// to 1 and N is derived from K) still boots on a host with fewer than the
+// nominal core count: the derived N equals K, ValidateInferenceConfig accepts
+// them, and registerNativeDeepDoc must not call common.Fatal. This mirrors the
+// resolution order in registerNativeDeepDoc and guards against a regression
+// where an explicit default larger than the host core count would fatally reject
+// startup.
+func TestRegisterNativeDeepDocDefaultBootsOnSmallMachine(t *testing.T) {
+ const totalCores = 2
+ cfg := &server.Config{}
+ if err := cfg.ParseIngestorConfig(viper.New()); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ // No CLI override; both config keys unset.
+ K, explicitK, errK := cfg.ResolveDeepDocInferenceConcurrency(nil)
+ if errK != nil {
+ t.Fatalf("ResolveDeepDocInferenceConcurrency: %v", errK)
+ }
+ rawN, explicitN, errN := cfg.ResolveDeepDocInferenceCPUCores(nil)
+ if errN != nil {
+ t.Fatalf("ResolveDeepDocInferenceCPUCores: %v", errN)
+ }
+ if explicitK || explicitN {
+ t.Fatal("default config must report both K and N as not-explicit")
+ }
+ // Unset N is derived from K, preserving single-threaded-per-run semantics.
+ resolvedN := rawN
+ if !explicitN {
+ resolvedN = K
+ }
+ if K != 1 {
+ t.Fatalf("default K = %d, want 1", K)
+ }
+ if resolvedN != K {
+ t.Fatalf("derived N = %d, want K=%d", resolvedN, K)
+ }
+ if _, _, err := native.ValidateInferenceConfig(totalCores, resolvedN, K); err != nil {
+ t.Fatalf("default config on %d-core host must validate, got: %v", totalCores, err)
+ }
+}
+
+// TestInferenceTotalCoresIsCgroupAware pins that the DeepDoc inference core
+// budget passed to native.ValidateInferenceConfig is derived from
+// runtime.GOMAXPROCS(0) (cgroup-quota aware in Go 1.25+) rather than
+// runtime.NumCPU() (host affinity mask, which ignores a container's CPU limit).
+// This keeps the fail-fast oversubscription guard effective under container CPU
+// quotas: with NumCPU(), a 2-CPU-limit pod on a 64-core host would "resolve"
+// inference_cpu_cores: 0 to 64 and let inference_concurrency: 16 pass validation,
+// oversubscribing the box the check exists to prevent.
+func TestInferenceTotalCoresIsCgroupAware(t *testing.T) {
+ got := inferenceTotalCores()
+ want := goruntime.GOMAXPROCS(0)
+ if got != want {
+ t.Fatalf("inferenceTotalCores() = %d, want runtime.GOMAXPROCS(0) = %d (cgroup-aware budget)", got, want)
+ }
+ if got < 1 {
+ t.Fatalf("inferenceTotalCores() = %d, want >= 1", got)
+ }
+}
diff --git a/conf/service_conf.yaml b/conf/service_conf.yaml
index 45aefef45a..820e9b3536 100644
--- a/conf/service_conf.yaml
+++ b/conf/service_conf.yaml
@@ -10,14 +10,6 @@ ragflow:
# or CIDR of a further proxy in front of nginx; an empty list trusts none.
# trusted_proxies: ['127.0.0.0/8', '::1/128']
-# DeepDoc in-process (Go) ONNX inference settings.
-deepdoc:
- # Max concurrent DeepDoc ONNX inference Runs in this process; each Run uses
- # exactly one CPU core (intraOpThreads is pinned to 1 in the native package).
- # Override with the env var RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY, or the CLI
- # flag --deepdoc-inference-concurrency (highest precedence). Default 4.
- inference_concurrency: 4
-
# Optional standalone MCP listener for the Go API server. Uncomment to enable.
# RAGFLOW_MCP_* environment variables override these settings.
# mcp:
@@ -99,6 +91,22 @@ ingestor:
mq_type: 'nats'
max_concurrent_workers: 2
compiler_pool_size: 0
+ # DeepDoc in-process (Go) ONNX inference settings.
+ # Max concurrent in-process DeepDoc ONNX inference Runs in this process (K).
+ # Each Run opens with max(1, inference_cpu_cores / K) intra-op threads, so the
+ # total CPU cores inference may occupy is bounded by inference_cpu_cores.
+ # Override with env RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY or the CLI flag
+ # --deepdoc-inference-concurrency (highest precedence). Default 1. K must be
+ # a positive integer and must not exceed the machine's CPU core count.
+ inference_concurrency: 1
+ # CPU-core budget (N) for DeepDoc in-process inference. A value of 0 means
+ # "use all available cores" (runtime.NumCPU()). The per-Run intra-op thread
+ # count is max(1, N/K); N may not exceed the machine's CPU core count.
+ # Override with env RAGFLOW_DEEPDOC_INFERENCE_CPU_CORES or the CLI flag
+ # --deepdoc-inference-cpu-cores (highest precedence). When this key is left
+ # unset (recommended), N is derived from K so each Run stays single-threaded
+ # by default (the prior behaviour); an explicit 0 opts into "all cores".
+ # inference_cpu_cores: 0
file_syncer:
max_concurrent_syncs: 5
user_default_llm:
diff --git a/internal/common/environments.go b/internal/common/environments.go
index d161c36f4a..1516c568ea 100644
--- a/internal/common/environments.go
+++ b/internal/common/environments.go
@@ -257,10 +257,17 @@ const (
// recognizer drop_score, so recognized text is blanked consistently.
EnvDeepDocDropScore = "DEEPDOC_DROP_SCORE"
// EnvDeepDocInferenceConcurrency bounds how many DeepDoc ONNX inference
- // Runs may be in flight at once (each uses one core). It overrides the
- // deepdoc.inference_concurrency config key and is itself overridden by the
+ // Runs may be in flight at once. Each Run opens with max(1, N/K) intra-op
+ // threads (N = EnvDeepDocInferenceCPUCores budget, K = this value), so the
+ // total cores inference may occupy is at most N. It overrides the
+ // ingestor.inference_concurrency config key and is itself overridden by the
// --deepdoc-inference-concurrency CLI flag.
EnvDeepDocInferenceConcurrency = "RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY"
+ // EnvDeepDocInferenceCPUCores bounds the CPU-core budget N for DeepDoc
+ // in-process inference (0 = all cores). It overrides the
+ // ingestor.inference_cpu_cores config key and is itself overridden by the
+ // --deepdoc-inference-cpu-cores CLI flag.
+ EnvDeepDocInferenceCPUCores = "RAGFLOW_DEEPDOC_INFERENCE_CPU_CORES"
)
// DeepDocModelFiles is the single source of truth for the weights the
diff --git a/internal/deepdoc/native/inference_config.go b/internal/deepdoc/native/inference_config.go
new file mode 100644
index 0000000000..fa6d38b3e4
--- /dev/null
+++ b/internal/deepdoc/native/inference_config.go
@@ -0,0 +1,88 @@
+//go:build cgo
+
+package native
+
+import (
+ "fmt"
+ "sync/atomic"
+)
+
+// intraOpThreads is the intra-op thread count every ONNX session is opened
+// with. It is process-global policy registered once at startup (see
+// SetIntraOpThreads) and read on every session creation.
+//
+// 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 a single DeepDoc
+// inference Run occupies equal intraOpThreads. The process-wide inference budget
+// (see inference_limit.go) bounds how many Runs may be in flight at once, so the
+// total cores inference may occupy is intraOpThreads × concurrency.
+//
+// Historically this was pinned to 1 (each Run cost exactly one core, making the
+// concurrency budget a plain core count). It is now configurable: the process
+// owner computes intraOpThreads = max(1, N/K) from the configured CPU-core
+// budget N and inference concurrency K, and registers it once at startup before
+// any session is created.
+var intraOpThreads int32 = 1
+
+// SetIntraOpThreads sets the intra-op thread count every subsequently created
+// session opens with. It is meant to be called exactly once at startup, before
+// any model session is created. Non-positive values are clamped to 1: ORT needs
+// at least one thread per session, and a zero/negative request is a caller bug.
+func SetIntraOpThreads(n int) {
+ if n < 1 {
+ n = 1
+ }
+ atomic.StoreInt32(&intraOpThreads, int32(n))
+}
+
+// intraOpThreadCount returns the currently configured intra-op thread count.
+// Sessions call it at creation time; after startup registration it is stable.
+func intraOpThreadCount() int {
+ return int(atomic.LoadInt32(&intraOpThreads))
+}
+
+// ValidateInferenceConfig computes the per-inference core budget from the
+// requested configuration and the machine's available core count, failing fast
+// on any invalid combination.
+//
+// - totalCores is the process's available CPU budget (callers pass
+// runtime.GOMAXPROCS(0), which is cgroup-quota aware in Go 1.25+, rather than
+// runtime.NumCPU(), which ignores a container's CPU limit). It bounds both the
+// "all cores" resolution of rawCPUCores == 0 and every validation ceiling below.
+// - rawCPUCores is the requested CPU-core budget N. A value of 0 means "use
+// all cores" and is resolved to totalCores.
+// - concurrency is the requested inference concurrency K (max in-flight Runs).
+//
+// It returns coresPerInference (max(1, N/K), the intra-op thread count per Run)
+// and totalCPUCores (the resolved N). The following are rejected:
+// - concurrency < 1 (not a valid integer / below the minimum),
+// - concurrency > totalCores (cannot run more parallel Runs than cores),
+// - rawCPUCores > totalCores (cannot allocate more cores than the machine has),
+// - concurrency > resolvedN (the CPU-core budget N is a hard ceiling: when
+// K > N, max(1, N/K) floors at 1 so total occupancy would be K, oversubscribing
+// the box beyond the budget N).
+//
+// totalCPUCores is returned as the resolved N so callers can log the effective
+// budget; it equals totalCores when rawCPUCores == 0.
+func ValidateInferenceConfig(totalCores, rawCPUCores, concurrency int) (coresPerInference, totalCPUCores int, err error) {
+ if concurrency < 1 {
+ return 0, 0, fmt.Errorf("deepdoc inference_concurrency %d invalid: must be a positive integer", concurrency)
+ }
+ if concurrency > totalCores {
+ return 0, 0, fmt.Errorf("deepdoc inference_concurrency %d exceeds available CPU cores %d", concurrency, totalCores)
+ }
+ resolved := rawCPUCores
+ if resolved == 0 {
+ resolved = totalCores
+ }
+ if resolved < 0 {
+ return 0, 0, fmt.Errorf("deepdoc inference_cpu_cores %d invalid: must be >= 0 (0 means all cores)", resolved)
+ }
+ if resolved > totalCores {
+ return 0, 0, fmt.Errorf("deepdoc inference_cpu_cores %d exceeds available CPU cores %d", resolved, totalCores)
+ }
+ if concurrency > resolved {
+ return 0, 0, fmt.Errorf("deepdoc inference_concurrency %d exceeds cpu-core budget %d (inference_cpu_cores)", concurrency, resolved)
+ }
+ return max(1, resolved/concurrency), resolved, nil
+}
diff --git a/internal/deepdoc/native/session.go b/internal/deepdoc/native/session.go
index fed1df7d27..036adbed97 100644
--- a/internal/deepdoc/native/session.go
+++ b/internal/deepdoc/native/session.go
@@ -24,16 +24,15 @@ 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
+// intraOpThreads is the intra-op thread count every session is opened with. It
+// is a process-global policy registered once at startup via SetIntraOpThreads
+// (see inference_config.go) and read here on every session creation. 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
+// concurrently running sessions. The capacity registered in inference_limit.go
+// bounds how many Runs may be in flight; together with intraOpThreads this is
+// the process inference budget (see ValidateInferenceConfig).
var (
ortOnce sync.Once
@@ -242,10 +241,12 @@ func newSessionOptions(weights *weightSet) (*ort.SessionOptions, error) {
if err != nil {
return nil, err
}
- // 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 {
+ // One intra-op thread per session by default; the startup path may raise it
+ // via SetIntraOpThreads to share N cores across K Runs (see
+ // ValidateInferenceConfig). The session's Runs then cost intraOpThreadCount()
+ // threads each, and the process-wide inference ceiling (inference_limit.go)
+ // bounds how many Runs may be in flight.
+ if err := opts.SetIntraOpNumThreads(intraOpThreadCount()); err != nil {
opts.Destroy()
return nil, err
}
diff --git a/internal/deepdoc/parser/pdf/parser_concurrency.go b/internal/deepdoc/parser/pdf/parser_concurrency.go
index c95f649fbf..ae7415f14d 100644
--- a/internal/deepdoc/parser/pdf/parser_concurrency.go
+++ b/internal/deepdoc/parser/pdf/parser_concurrency.go
@@ -26,7 +26,7 @@ import (
// called by the server's backend wiring) and (b) used to size the page worker
// pool. It is configurable: the server resolves it once at start from
// CLI > env (RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY) > config
-// (deepdoc.inference_concurrency) > default 4, then injects it with
+// (ingestor.inference_concurrency) > default 1, then injects it with
// SetDeepDocConcurrency. Callers read it via DeepDocConcurrency(); they never
// have to reason about the precedence themselves.
//
@@ -41,7 +41,9 @@ import (
// set once at server start via SetDeepDocConcurrency. It is the maximum number
// of Runs in flight; each Run is single-threaded (intraOpThreads = 1 in the
// native package), so it is also the number of cores inference may occupy.
-var deepDocInferenceConcurrency = 4
+// The default (1) is the conservative floor; the server overrides it from
+// CLI/env/config at boot via SetDeepDocConcurrency.
+var deepDocInferenceConcurrency = 1
// SetDeepDocConcurrency sets the process inference budget. It is called exactly
// once at server boot after CLI/env/config resolution. Non-positive values are
diff --git a/internal/deepdoc/parser/pdf/parser_concurrency_test.go b/internal/deepdoc/parser/pdf/parser_concurrency_test.go
index d04ad090eb..d2a17ce32d 100644
--- a/internal/deepdoc/parser/pdf/parser_concurrency_test.go
+++ b/internal/deepdoc/parser/pdf/parser_concurrency_test.go
@@ -18,15 +18,19 @@ package pdf
import "testing"
-// TestDeepDocConcurrencyDefaultsToFour pins the process inference budget
-// default: when nothing configures it, DeepDocConcurrency() returns 4.
-func TestDeepDocConcurrencyDefaultsToFour(t *testing.T) {
+// TestDeepDocConcurrencyDefaultOne pins the process inference budget default:
+// when nothing configures it, DeepDocConcurrency() returns 1.
+func TestDeepDocConcurrencyDefaultOne(t *testing.T) {
+ if got := DeepDocConcurrency(); got != 1 {
+ t.Fatalf("initial DeepDocConcurrency() = %d, want 1", got)
+ }
+
orig := DeepDocConcurrency()
t.Cleanup(func() { SetDeepDocConcurrency(orig) })
- SetDeepDocConcurrency(4)
- if got := DeepDocConcurrency(); got != 4 {
- t.Fatalf("DeepDocConcurrency() = %d, want 4", got)
+ SetDeepDocConcurrency(7)
+ if got := DeepDocConcurrency(); got != 7 {
+ t.Fatalf("DeepDocConcurrency() after SetDeepDocConcurrency(7) = %d, want 7", got)
}
}
diff --git a/internal/server/config.go b/internal/server/config.go
index 2f82df806a..701cc79091 100644
--- a/internal/server/config.go
+++ b/internal/server/config.go
@@ -136,11 +136,6 @@ func Init(configPath string) error {
return fmt.Errorf("parse log config error: %w", err)
}
- err = globalConfig.ParseDeepDocConfig(v)
- if err != nil {
- return fmt.Errorf("parse deepdoc config error: %w", err)
- }
-
err = globalConfig.ParseSMTPConfig(v)
if err != nil {
return fmt.Errorf("parse SMTP config error: %w", err)
diff --git a/internal/server/config/base.go b/internal/server/config/base.go
index 73a5db5ad4..dfbb624240 100644
--- a/internal/server/config/base.go
+++ b/internal/server/config/base.go
@@ -32,7 +32,6 @@ type Config struct {
apiServer APIServerConfig
syncer SyncerConfig
ingestor IngestorConfig
- deepdoc DeepDocConfig
log LogConfig
smtp common.SMTPConfig
diff --git a/internal/server/config/deepdoc_config.go b/internal/server/config/deepdoc_config.go
deleted file mode 100644
index 129c6e8845..0000000000
--- a/internal/server/config/deepdoc_config.go
+++ /dev/null
@@ -1,52 +0,0 @@
-//
-// 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 config
-
-import (
- "github.com/spf13/viper"
-)
-
-// DeepDocConfig holds DeepDoc (in-process ONNX) inference settings.
-type DeepDocConfig struct {
- // InferenceConcurrency bounds how many DeepDoc ONNX Runs this process may
- // have in flight at once. Each Run is single-threaded (intraOpThreads = 1
- // in the native package), so this is also the number of cores inference may
- // occupy. Default 4.
- InferenceConcurrency int `mapstructure:"inference_concurrency"`
-}
-
-// ParseDeepDocConfig populates DeepDocConfig from the viper instance. It reads
-// only the deepdoc.inference_concurrency YAML key (default 4). The environment
-// variable RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY does NOT override it here:
-// v.Sub("deepdoc") does not inherit viper's AutomaticEnv settings (env prefix,
-// replacer, AutomaticEnv are all dropped by Sub), so the env override would be
-// missed if applied only through viper. The env override is therefore resolved
-// later in the server boot path by cmd.resolveDeepDocInferenceConcurrency via
-// os.Getenv, which also applies the --deepdoc-inference-concurrency CLI flag
-// (highest precedence) over both.
-func (c *Config) ParseDeepDocConfig(v *viper.Viper) error {
- c.deepdoc.InferenceConcurrency = 4
- if sub := v.Sub("deepdoc"); sub != nil && sub.IsSet("inference_concurrency") {
- c.deepdoc.InferenceConcurrency = sub.GetInt("inference_concurrency")
- }
- return nil
-}
-
-// GetDeepDocConfig returns the parsed DeepDoc configuration.
-func (c *Config) GetDeepDocConfig() *DeepDocConfig {
- return &c.deepdoc
-}
diff --git a/internal/server/config/deepdoc_config_test.go b/internal/server/config/deepdoc_config_test.go
index ad7e0bf60c..859e5e65fc 100644
--- a/internal/server/config/deepdoc_config_test.go
+++ b/internal/server/config/deepdoc_config_test.go
@@ -25,53 +25,243 @@ import (
"github.com/spf13/viper"
)
-// TestParseDeepDocConfigDefaultsToFour pins the default inference concurrency.
-func TestParseDeepDocConfigDefaultsToFour(t *testing.T) {
+// TestParseIngestorConfigDeepDocDefaultsToOne pins the default inference
+// concurrency when the ingestor.inference_concurrency key is absent.
+func TestParseIngestorConfigDeepDocDefaultsToOne(t *testing.T) {
v := viper.New()
c := &Config{}
- if err := c.ParseDeepDocConfig(v); err != nil {
- t.Fatalf("ParseDeepDocConfig: %v", err)
+ if err := c.ParseIngestorConfig(v); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
}
- if got := c.GetDeepDocConfig().InferenceConcurrency; got != 4 {
- t.Fatalf("default inference concurrency = %d, want 4", got)
+ if got := c.ingestor.deepDocInferenceConcurrency; got != 1 {
+ t.Fatalf("default inference concurrency = %d, want 1", got)
}
}
-// TestParseDeepDocConfigReadsYAML pins that the deepdoc.inference_concurrency
-// key is honoured when present.
-func TestParseDeepDocConfigReadsYAML(t *testing.T) {
+// TestParseIngestorConfigReadsDeepDocYAML pins that the
+// ingestor.inference_concurrency key is honoured when present.
+func TestParseIngestorConfigReadsDeepDocYAML(t *testing.T) {
v := viper.New()
- v.Set("deepdoc", map[string]any{"inference_concurrency": 6})
+ v.Set("ingestor", map[string]any{
+ "inference_concurrency": 6,
+ })
c := &Config{}
- if err := c.ParseDeepDocConfig(v); err != nil {
- t.Fatalf("ParseDeepDocConfig: %v", err)
+ if err := c.ParseIngestorConfig(v); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
}
- if got := c.GetDeepDocConfig().InferenceConcurrency; got != 6 {
+ if got := c.ingestor.deepDocInferenceConcurrency; got != 6 {
t.Fatalf("inference concurrency = %d, want 6", got)
}
}
-// TestParseDeepDocConfigIgnoresEnvVar pins the provenance of the env override:
-// ParseDeepDocConfig reads ONLY the deepdoc.inference_concurrency YAML key and
-// does not apply the RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY environment variable.
-// This holds even with viper's AutomaticEnv configured exactly as server.Init
-// does, because v.Sub("deepdoc") does not inherit the parent's env (prefix /
-// replacer / AutomaticEnv). The env override is resolved later in the server
-// boot path by cmd.resolveDeepDocInferenceConcurrency (via os.Getenv), so the
-// configured value returned here must stay at the YAML/default value.
-func TestParseDeepDocConfigIgnoresEnvVar(t *testing.T) {
+// TestParseIngestorConfigDeepDocIgnoresEnvVar pins the provenance of the env
+// override: ParseIngestorConfig reads ONLY the ingestor.inference_concurrency
+// YAML key and does not apply RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY. The env
+// override is resolved separately by Config.ResolveDeepDocInferenceConcurrency.
+func TestParseIngestorConfigDeepDocIgnoresEnvVar(t *testing.T) {
t.Setenv(common.EnvDeepDocInferenceConcurrency, "9")
+ v := viper.New()
+ c := &Config{}
+ if err := c.ParseIngestorConfig(v); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ if got := c.ingestor.deepDocInferenceConcurrency; got != 1 {
+ t.Fatalf("inference concurrency with only env set = %d, want default 1 (env applied later)", got)
+ }
+}
+
+// TestParseIngestorConfigDeepDocIgnoresAutoEnvVar pins that the auto-derived
+// (undocumented) env var RAGFLOW_INGESTOR_INFERENCE_CONCURRENCY does NOT
+// override the YAML ingestor.inference_concurrency. viper's Sub() inherits
+// AutomaticEnv, so a plain GetInt would consult that variable before the file
+// value. The config parse must be file-only; env precedence is applied later by
+// ResolveDeepDocInferenceConcurrency via os.Getenv. This test uses the
+// production Viper settings (env prefix + replacer + AutomaticEnv) to reproduce
+// the real precedence resolution path.
+func TestParseIngestorConfigDeepDocIgnoresAutoEnvVar(t *testing.T) {
+ t.Setenv("RAGFLOW_INGESTOR_INFERENCE_CONCURRENCY", "bad")
+
v := viper.New()
v.SetEnvPrefix("RAGFLOW")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
+ v.Set("ingestor", map[string]any{
+ "inference_concurrency": 6,
+ })
+
+ c := &Config{}
+ if err := c.ParseIngestorConfig(v); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ if got := c.ingestor.deepDocInferenceConcurrency; got != 6 {
+ t.Fatalf("inference concurrency = %d, want 6 (auto-env must not override YAML)", got)
+ }
+}
+
+// TestResolveDeepDocInferenceConcurrency pins the precedence
+// CLI > environment > config file > default(1) and the fail-fast contract: any
+// non-integer, non-positive, or otherwise invalid value is an error, never a
+// silent fallback. The second return reports whether K was explicitly set by any
+// layer (as opposed to the built-in default of 1).
+func TestResolveDeepDocInferenceConcurrency(t *testing.T) {
+ const envKey = common.EnvDeepDocInferenceConcurrency
+
+ cases := []struct {
+ name string
+ configured int
+ configuredSet bool
+ env string // "" means leave unset
+ cli *int
+ want int
+ wantExplicit bool
+ wantErr bool
+ }{
+ {"default", 0, false, "", nil, 1, false, false},
+ {"config only", 6, true, "", nil, 6, true, false},
+ {"env overrides config", 6, true, "8", nil, 8, true, false},
+ {"cli overrides env and config", 6, true, "8", intPtr(12), 12, true, false},
+ {"env only", 0, false, "9", nil, 9, true, false},
+ // Invalid values are rejected, not silently ignored.
+ {"env invalid -> error", 6, true, "notanint", nil, 0, false, true},
+ {"config zero -> error", 0, true, "", nil, 0, false, true},
+ {"config negative -> error", -3, true, "", nil, 0, false, true},
+ {"env negative -> error", 6, true, "-2", nil, 0, false, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv(envKey, tc.env)
+
+ c := &Config{}
+ if err := c.ParseIngestorConfig(viper.New()); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ c.ingestor.deepDocInferenceConcurrency = tc.configured
+ c.ingestor.deepDocInferenceConcurrencySet = tc.configuredSet
+ got, explicit, err := c.ResolveDeepDocInferenceConcurrency(tc.cli)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("expected error, got %d (explicit=%v)", got, explicit)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != tc.want {
+ t.Fatalf("got %d, want %d (configured=%d configuredSet=%v env=%q cli=%v)",
+ got, tc.want, tc.configured, tc.configuredSet, tc.env, tc.cli)
+ }
+ if explicit != tc.wantExplicit {
+ t.Fatalf("explicit = %v, want %v", explicit, tc.wantExplicit)
+ }
+ })
+ }
+}
+
+// TestResolveDeepDocInferenceCPUCores pins the precedence
+// CLI > environment > config file > default(0, "derive from K") for the CPU-core
+// budget N, and that the second return reports whether N was explicitly set by
+// any layer. An explicit 0 means "use all cores" and is returned as 0 (resolved
+// against runtime.NumCPU() by the caller); only non-integer or negative values
+// error.
+func TestResolveDeepDocInferenceCPUCores(t *testing.T) {
+ const envKey = common.EnvDeepDocInferenceCPUCores
+ cases := []struct {
+ name string
+ configured int
+ configuredSet bool
+ env string
+ cli *int
+ want int
+ wantExplicit bool
+ wantErr bool
+ }{
+ {"default unset", 0, false, "", nil, 0, false, false},
+ {"config zero -> all cores sentinel", 0, true, "", nil, 0, true, false},
+ {"config only", 8, true, "", nil, 8, true, false},
+ {"env overrides config", 8, true, "16", nil, 16, true, false},
+ {"cli overrides env and config", 8, true, "16", intPtr(32), 32, true, false},
+ {"env only", 0, false, "12", nil, 12, true, false},
+ {"cli zero valid -> all cores sentinel", 0, true, "", intPtr(0), 0, true, false},
+ // Invalid values are rejected.
+ {"env invalid -> error", 8, true, "notanint", nil, 0, false, true},
+ {"env negative -> error", 8, true, "-1", nil, 0, false, true},
+ {"config negative -> error", -1, true, "", nil, 0, false, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv(envKey, tc.env)
+
+ c := &Config{}
+ if err := c.ParseIngestorConfig(viper.New()); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ c.ingestor.deepDocInferenceCPUCores = tc.configured
+ c.ingestor.deepDocInferenceCPUCoresSet = tc.configuredSet
+ got, explicit, err := c.ResolveDeepDocInferenceCPUCores(tc.cli)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("expected error, got %d (explicit=%v)", got, explicit)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != tc.want {
+ t.Fatalf("got %d, want %d (configured=%d configuredSet=%v env=%q cli=%v)",
+ got, tc.want, tc.configured, tc.configuredSet, tc.env, tc.cli)
+ }
+ if explicit != tc.wantExplicit {
+ t.Fatalf("explicit = %v, want %v", explicit, tc.wantExplicit)
+ }
+ })
+ }
+}
+
+// TestParseIngestorConfigDeepDocRejectsNonInteger pins the fail-fast contract:
+// a present-but-non-integer ingestor.inference_concurrency / inference_cpu_cores
+// value must surface as an error rather than being silently coerced to 0 by
+// viper/cast.
+func TestParseIngestorConfigDeepDocRejectsNonInteger(t *testing.T) {
+ v := viper.New()
+ v.Set("ingestor", map[string]any{
+ "inference_concurrency": "four",
+ })
c := &Config{}
- if err := c.ParseDeepDocConfig(v); err != nil {
- t.Fatalf("ParseDeepDocConfig: %v", err)
+ if err := c.ParseIngestorConfig(v); err == nil {
+ t.Fatal("expected error for non-integer inference_concurrency, got nil (silently coerced to 0)")
}
- if got := c.GetDeepDocConfig().InferenceConcurrency; got != 4 {
- t.Fatalf("inference concurrency with only env set = %d, want default 4 (env must not be applied here)", got)
+
+ v2 := viper.New()
+ v2.Set("ingestor", map[string]any{
+ "inference_cpu_cores": "alsobad",
+ })
+ c2 := &Config{}
+ if err := c2.ParseIngestorConfig(v2); err == nil {
+ t.Fatal("expected error for non-integer inference_cpu_cores, got nil (silently coerced to 0)")
}
}
+
+// TestParseIngestorConfigReadsDeepDocCPUCoresYAML pins that the
+// ingestor.inference_cpu_cores key is honoured when present.
+func TestParseIngestorConfigReadsDeepDocCPUCoresYAML(t *testing.T) {
+ v := viper.New()
+ v.Set("ingestor", map[string]any{
+ "inference_cpu_cores": 8,
+ })
+ c := &Config{}
+ if err := c.ParseIngestorConfig(v); err != nil {
+ t.Fatalf("ParseIngestorConfig: %v", err)
+ }
+ if got := c.ingestor.deepDocInferenceCPUCores; got != 8 {
+ t.Fatalf("inference cpu cores = %d, want 8", got)
+ }
+ if !c.ingestor.deepDocInferenceCPUCoresSet {
+ t.Fatal("deepDocInferenceCPUCoresSet should be true when key present")
+ }
+}
+
+func intPtr(n int) *int { return &n }
diff --git a/internal/server/config/ingestor_config.go b/internal/server/config/ingestor_config.go
index 9b5a2b8646..43554da170 100644
--- a/internal/server/config/ingestor_config.go
+++ b/internal/server/config/ingestor_config.go
@@ -12,10 +12,19 @@
// 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 config
import (
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "ragflow/internal/common"
+
+ "github.com/spf13/cast"
"github.com/spf13/viper"
)
@@ -28,12 +37,40 @@ type IngestorConfig struct {
// pool that drives the cross-doc KNN / LLM-merge / write stages. 0/negative
// falls back to runtime.NumCPU() (or KC_COMPILE_CONCURRENCY if set).
CompilerPoolSize int `mapstructure:"compiler_pool_size"`
+ // deepDocInferenceConcurrency bounds how many DeepDoc ONNX Runs this process
+ // may have in flight at once (K). Each Run opens with
+ // max(1, deepDocInferenceCPUCores / deepDocInferenceConcurrency) intra-op
+ // threads (see internal/deepdoc/native/inference_config.go), so the total
+ // cores inference may occupy is at most deepDocInferenceCPUCores. K must be a
+ // positive integer and may not exceed the machine's CPU core count. Default
+ // 1. Read from the file-only ingestor.inference_concurrency key; env/CLI
+ // precedence is applied later by ResolveDeepDocInferenceConcurrency.
+ deepDocInferenceConcurrency int
+ // deepDocInferenceConcurrencySet is true when inference_concurrency was
+ // explicitly present in the config file. It lets the server distinguish
+ // "unset" (fall back to the default of 1) from an explicit value such as 0
+ // (which is invalid for K and must be rejected).
+ deepDocInferenceConcurrencySet bool
+ // deepDocInferenceCPUCores is the CPU-core budget N for DeepDoc in-process
+ // inference. A value of 0 means "use all available cores" (resolved to
+ // runtime.NumCPU() at startup). The per-Run intra-op thread count is
+ // max(1, N/K); N may not exceed the machine's CPU core count. Default 0,
+ // which (when unset) is derived from K so each Run stays single-threaded by
+ // default, preserving the prior single-core-per-run behaviour; an explicit
+ // 0 opts into "all cores".
+ deepDocInferenceCPUCores int
+ // deepDocInferenceCPUCoresSet is true when inference_cpu_cores was present.
+ deepDocInferenceCPUCoresSet bool
}
func (c *Config) ParseIngestorConfig(v *viper.Viper) error {
// Default Ingestor config
c.ingestor.MaxConcurrentWorkers = 2
c.ingestor.CompilerPoolSize = 0
+ c.ingestor.deepDocInferenceConcurrency = 1
+ c.ingestor.deepDocInferenceConcurrencySet = false
+ c.ingestor.deepDocInferenceCPUCores = 0
+ c.ingestor.deepDocInferenceCPUCoresSet = false
if !v.IsSet("ingestor") {
return nil
@@ -51,9 +88,107 @@ func (c *Config) ParseIngestorConfig(v *viper.Viper) error {
c.ingestor.CompilerPoolSize = sub.GetInt("compiler_pool_size")
}
+ // Read the DeepDoc inference keys from FILE-ONLY data. sub inherits
+ // AutomaticEnv (viper's Sub copies the parent's env settings), so a plain
+ // sub.GetInt would also consult the auto-derived env vars
+ // RAGFLOW_INGESTOR_INFERENCE_CONCURRENCY / RAGFLOW_INGESTOR_INFERENCE_CPU_CORES
+ // and could override or (on a non-integer value) clobber the YAML setting.
+ // Env precedence belongs exclusively to ResolveDeepDocInferenceConcurrency /
+ // ResolveDeepDocInferenceCPUCores (os.Getenv), so the config tier must be
+ // the raw file value. Repoint the env prefix at an impossible token to
+ // deterministically disable AutomaticEnv for this read. A present-but
+ // non-integer value is a hard error (cast.ToIntE) rather than a silent 0.
+ sub.SetEnvPrefix("__DISABLED__")
+ if sub.IsSet("inference_concurrency") {
+ n, err := cast.ToIntE(sub.Get("inference_concurrency"))
+ if err != nil {
+ return fmt.Errorf("invalid ingestor.inference_concurrency: %w", err)
+ }
+ c.ingestor.deepDocInferenceConcurrency = n
+ c.ingestor.deepDocInferenceConcurrencySet = true
+ }
+ if sub.IsSet("inference_cpu_cores") {
+ n, err := cast.ToIntE(sub.Get("inference_cpu_cores"))
+ if err != nil {
+ return fmt.Errorf("invalid ingestor.inference_cpu_cores: %w", err)
+ }
+ c.ingestor.deepDocInferenceCPUCores = n
+ c.ingestor.deepDocInferenceCPUCoresSet = true
+ }
+
return nil
}
+// ResolveDeepDocInferenceConcurrency resolves the effective DeepDoc inference
+// concurrency K. Precedence (highest wins): CLI flag > environment variable
+// RAGFLOW_DEEPDOC_INFERENCE_CONCURRENCY > ingestor.inference_concurrency
+// (config file) > default (1). It returns the resolved value, whether it was
+// explicitly set by any layer (config, env, or CLI) as opposed to the built-in
+// default, and any error. An explicit value that is non-integer, non-positive,
+// or otherwise invalid is reported as an error rather than silently ignored.
+func (c *Config) ResolveDeepDocInferenceConcurrency(cli *int) (int, bool, error) {
+ val := c.ingestor.deepDocInferenceConcurrency
+ explicit := c.ingestor.deepDocInferenceConcurrencySet
+ if explicit && val <= 0 {
+ return 0, false, fmt.Errorf("invalid ingestor.inference_concurrency %d: must be a positive integer", val)
+ }
+ if val <= 0 {
+ val = 1
+ explicit = false
+ }
+ if v := strings.TrimSpace(os.Getenv(common.EnvDeepDocInferenceConcurrency)); v != "" {
+ n, err := strconv.Atoi(v)
+ if err != nil {
+ return 0, false, fmt.Errorf("invalid %s %q: %w", common.EnvDeepDocInferenceConcurrency, v, err)
+ }
+ if n < 1 {
+ return 0, false, fmt.Errorf("invalid %s %d: must be a positive integer", common.EnvDeepDocInferenceConcurrency, n)
+ }
+ val = n
+ explicit = true
+ }
+ // The CLI parser rejects a non-positive --deepdoc-inference-concurrency up
+ // front, so the parsed value is already positive; no extra >0 guard needed.
+ if cli != nil && *cli > 0 {
+ val = *cli
+ explicit = true
+ }
+ return val, explicit, nil
+}
+
+// ResolveDeepDocInferenceCPUCores resolves the requested CPU-core budget N for
+// DeepDoc in-process inference. Precedence (highest wins): CLI flag > environment
+// variable RAGFLOW_DEEPDOC_INFERENCE_CPU_CORES > ingestor.inference_cpu_cores
+// (config file) > default (0, meaning "derive from K"). It returns the raw value
+// (0 still means "all cores" when explicit), whether N was explicitly set by any
+// layer, and any error. A non-integer or negative value is reported as an error;
+// an explicit 0 is valid and means "use all available cores".
+func (c *Config) ResolveDeepDocInferenceCPUCores(cli *int) (int, bool, error) {
+ val := c.ingestor.deepDocInferenceCPUCores
+ explicit := c.ingestor.deepDocInferenceCPUCoresSet
+ if explicit && val < 0 {
+ return 0, false, fmt.Errorf("invalid ingestor.inference_cpu_cores %d: must be >= 0 (0 means all cores)", val)
+ }
+ if v := strings.TrimSpace(os.Getenv(common.EnvDeepDocInferenceCPUCores)); v != "" {
+ n, err := strconv.Atoi(v)
+ if err != nil {
+ return 0, false, fmt.Errorf("invalid %s %q: %w", common.EnvDeepDocInferenceCPUCores, v, err)
+ }
+ if n < 0 {
+ return 0, false, fmt.Errorf("invalid %s %d: must be >= 0 (0 means all cores)", common.EnvDeepDocInferenceCPUCores, n)
+ }
+ val = n
+ explicit = true
+ }
+ // The CLI parser accepts a non-negative --deepdoc-inference-cpu-cores (0 =
+ // all cores), so the parsed value is already >= 0.
+ if cli != nil {
+ val = *cli
+ explicit = true
+ }
+ return val, explicit, nil
+}
+
func (c *Config) GetIngestorConfig() *IngestorConfig {
return &c.ingestor
}