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
feat(parser): add per-method external DeepDoc analyzer dispatch (#21182)
xugangqiang5f1d452d6393
diff --git a/internal/parser/parser/pdf_analyzer_dispatch_entry_test.go b/internal/parser/parser/pdf_analyzer_dispatch_entry_test.gonew file mode 100644index 0000000000..a213f4dfdb--- /dev/null+++ b/internal/parser/parser/pdf_analyzer_dispatch_entry_test.go@@ -0,0 +1,108 @@+package parser++import (+ "context"+ "strings"+ "testing"++ deepdoctype "ragflow/internal/deepdoc/parser/type"+)++// These tests cover the PUBLIC entry path (validateParseMethod + ParseWithResult)+// that the lower-level dispatch tests in pdf_analyzer_dispatch_test.go bypass.+// They pin the previously-failing behavior: a parse method registered via+// RegisterAnalyzerFactory must be accepted by validation and must flow through+// ParseWithResult all the way to the DeepDoc dispatch — not be rejected by the+// supported-methods whitelist before dispatch ever runs.++func newStubFactory(tag string) func(baseURL string) (deepdoctype.DocAnalyzer, error) {+ return func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: tag}, nil+ }+}++// A method registered through the external analyzer factory must pass+// validation, instead of being rejected as "unsupported". This is the Blocker:+// before the fix, validateParseMethod only consulted supportedPDFParseMethods.+func TestValidateParseMethod_RegisteredExternalMethodAccepted(t *testing.T) {+ RegisterAnalyzerFactory("ext_entry_happy", newStubFactory("ext"))+ if err := (&PDFParser{ParseMethod: "ext_entry_happy"}).validateParseMethod(); err != nil {+ t.Fatalf("registered method should pass validation, got err: %v", err)+ }+}++// Registration and resolution both normalize the method token, so a differently+// cased registration must still be accepted for the canonical (lower-cased)+// method name.+func TestValidateParseMethod_RegisteredMethodNormalization(t *testing.T) {+ RegisterAnalyzerFactory("Ext_Entry_Case", newStubFactory("ext"))+ if err := (&PDFParser{ParseMethod: "ext_entry_case"}).validateParseMethod(); err != nil {+ t.Fatalf("mixed-case registered method should pass validation, got err: %v", err)+ }+}++// Leading/trailing whitespace in the configured method must not defeat the+// registered-method lookup, since both sides normalize with TrimSpace.+func TestValidateParseMethod_RegisteredMethodTrimsWhitespace(t *testing.T) {+ RegisterAnalyzerFactory("ext_entry_ws", newStubFactory("ext"))+ if err := (&PDFParser{ParseMethod: " EXT_ENTRY_WS "}).validateParseMethod(); err != nil {+ t.Fatalf("whitespace-padded registered method should pass validation, got err: %v", err)+ }+}++// Regression guard: a method that is neither built-in nor registered must still+// be rejected. The fix must not weaken the whitelist for unknown methods.+func TestValidateParseMethod_UnregisteredUnknownMethodStillRejected(t *testing.T) {+ err := (&PDFParser{ParseMethod: "totally_unknown_method_xyz"}).validateParseMethod()+ if err == nil {+ t.Fatal("unknown unregistered method should be rejected")+ }+ if !strings.Contains(err.Error(), "unsupported PDF parse_method") {+ t.Fatalf("expected unsupported-method error, got: %v", err)+ }+}++// Sanity guard: built-in methods continue to validate as before.+func TestValidateParseMethod_KnownBuiltinMethodAccepted(t *testing.T) {+ for _, m := range []string{"", "deepdoc", "plain_text", "mineru", "paddleocr", "docling", "opendataloader", "somark", "tcadp"} {+ if err := (&PDFParser{ParseMethod: m}).validateParseMethod(); err != nil {+ t.Fatalf("built-in method %q should pass validation, got err: %v", m, err)+ }+ }+}++// End-to-end through the public parser facade: a registered method must reach+// the DeepDoc dispatch path (not be bounced by validateParseMethod). The deepdoc+// engine is not exercised for real here (no models); what we assert is that the+// error, if any, is NOT the "unsupported PDF parse_method" validation error —+// that would mean the registered method never reached dispatch.+func TestParseWithResult_RegisteredExternalMethodReachesDispatch(t *testing.T) {+ const method = "ext_entry_e2e"+ RegisterAnalyzerFactory(method, newStubFactory("ext"))+ t.Setenv("EXT_ENTRY_E2E_URL", "http://ee.example:9380")++ res := (&PDFParser{ParseMethod: method}).ParseWithResult(+ context.Background(), "doc.pdf", []byte("%PDF-1.4 dummy content"))++ if res.Err == nil {+ // Under !cgo the engine reports ErrPDFEngineUnavailable; either way the+ // method must have cleared validation and entered the deepdoc path.+ return+ }+ if strings.Contains(res.Err.Error(), "unsupported PDF parse_method") {+ t.Fatalf("registered method was wrongly rejected at validation: %v", res.Err)+ }+}++// Regression guard at the facade level: an unknown, unregistered method must+// still be rejected by ParseWithResult with the unsupported-method error.+func TestParseWithResult_UnregisteredUnknownMethodRejected(t *testing.T) {+ res := (&PDFParser{ParseMethod: "bogus_method_zzz"}).ParseWithResult(+ context.Background(), "doc.pdf", []byte("%PDF-1.4 dummy content"))+ if res.Err == nil {+ t.Fatal("unknown unregistered method should be rejected by ParseWithResult")+ }+ if !strings.Contains(res.Err.Error(), "unsupported PDF parse_method") {+ t.Fatalf("expected unsupported-method error, got: %v", res.Err)+ }+}diff --git a/internal/parser/parser/pdf_analyzer_dispatch_register_test.go b/internal/parser/parser/pdf_analyzer_dispatch_register_test.gonew file mode 100644index 0000000000..8989e14ec3--- /dev/null+++ b/internal/parser/parser/pdf_analyzer_dispatch_register_test.go@@ -0,0 +1,69 @@+package parser++import (+ "testing"++ deepdoctype "ragflow/internal/deepdoc/parser/type"+)++// mustPanic runs f and fails the test unless f panics. Used to assert that+// RegisterAnalyzerFactory rejects mis-registrations (fail-loud) instead of+// silently ignoring them.+func mustPanic(t *testing.T, name string, f func()) {+ t.Helper()+ defer func() {+ if r := recover(); r == nil {+ t.Fatalf("%s: expected RegisterAnalyzerFactory to panic, but it did not", name)+ }+ }()+ f()+}++// Built-in methods that are dispatched by an internal engine (every switch case+// in ParseWithResult except the fall-through to DeepDoc) cannot be overridden by+// an external factory — the switch intercepts them before resolution runs, so a+// factory registered for them would be silently ignored. RegisterAnalyzerFactory+// must reject such registrations instead of letting them fail silently.+func TestRegisterAnalyzerFactory_RejectsBuiltinEngineMethods(t *testing.T) {+ for _, m := range []string{"plain_text", "mineru", "paddleocr", "docling", "opendataloader", "somark", "tcadp"} {+ mm := m+ mustPanic(t, mm, func() {+ RegisterAnalyzerFactory(mm, newStubFactory("reject"))+ })+ }+}++// Registering for the empty (default) method would hijack every caller that+// omits parse_method and route the default in-process path to an external+// service. That override is not allowed and must be rejected.+func TestRegisterAnalyzerFactory_RejectsEmptyMethod(t *testing.T) {+ mustPanic(t, "empty", func() {+ RegisterAnalyzerFactory("", newStubFactory("reject"))+ })+}++// The "deepdoc" method is the one built-in that falls through to the DeepDoc+// path, so it remains a valid external-override target (the DEEPDOC_URL+// convention). RegisterAnalyzerFactory must NOT reject it.+func TestRegisterAnalyzerFactory_AllowsDeepdoc(t *testing.T) {+ // Must not panic.+ RegisterAnalyzerFactory("deepdoc", newStubFactory("allow"))+ // And it must actually be registered so resolution can pick it up.+ if _, ok := analyzerFactories[normalizePDFParseMethod("deepdoc")]; !ok {+ t.Fatal("deepdoc should be a valid external-override target")+ }+ // Clean up: other tests rely on "deepdoc" being unregistered to exercise+ // the in-process fallback, and the global registry persists across tests.+ delete(analyzerFactories, normalizePDFParseMethod("deepdoc"))+}++// A non-built-in custom method name is the intended use case and must be+// accepted (not panicking).+func TestRegisterAnalyzerFactory_AllowsCustomMethod(t *testing.T) {+ RegisterAnalyzerFactory("ext_register_allowed", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: "ext"}, nil+ })+ if _, ok := analyzerFactories[normalizePDFParseMethod("ext_register_allowed")]; !ok {+ t.Fatal("custom method should be registered")+ }+}diff --git a/internal/parser/parser/pdf_analyzer_dispatch_test.go b/internal/parser/parser/pdf_analyzer_dispatch_test.gonew file mode 100644index 0000000000..0752f7f616--- /dev/null+++ b/internal/parser/parser/pdf_analyzer_dispatch_test.go@@ -0,0 +1,323 @@+package parser++import (+ "context"+ "errors"+ "fmt"+ "image"+ "strings"+ "sync"+ "testing"++ deepdoctype "ragflow/internal/deepdoc/parser/type"+)++// stubDispatchAnalyzer is a minimal DocAnalyzer used to prove the external+// factory dispatch routes to the registered factory without touching ONNX+// Runtime or the native backend.+type stubDispatchAnalyzer struct{ tag string }++func (s *stubDispatchAnalyzer) DLA(context.Context, image.Image) ([]deepdoctype.DLARegion, error) {+ return nil, nil+}+func (s *stubDispatchAnalyzer) TSR(context.Context, image.Image) ([]deepdoctype.TSRCell, error) {+ return nil, nil+}+func (s *stubDispatchAnalyzer) OCRDetect(context.Context, image.Image) ([]deepdoctype.OCRBox, error) {+ return nil, nil+}+func (s *stubDispatchAnalyzer) OCRRecognize(context.Context, image.Image) ([]deepdoctype.OCRText, error) {+ return nil, nil+}+func (s *stubDispatchAnalyzer) Health() bool { return true }++// --- Happy path ---------------------------------------------------------++// A registered external factory is selected for its method, and receives the+// endpoint from the generic <METHOD>_URL environment convention.+func TestResolveDocAnalyzerForMethod_RegisteredFactoryGetsEnvURL(t *testing.T) {+ var gotURL string+ RegisterAnalyzerFactory("ext_svc_happy", func(u string) (deepdoctype.DocAnalyzer, error) {+ gotURL = u+ return &stubDispatchAnalyzer{tag: "ext"}, nil+ })+ t.Setenv("EXT_SVC_HAPPY_URL", "http://ee.example:9380")++ a, err := resolveDocAnalyzerForMethod("ext_svc_happy", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if a == nil {+ t.Fatal("expected analyzer from the registered factory, got nil")+ }+ if gotURL != "http://ee.example:9380" {+ t.Errorf("factory received URL %q, want the EXT_SVC_HAPPY_URL value", gotURL)+ }+}++// --- Error paths --------------------------------------------------------++// A registered method with no configured URL must fail loudly (never silently+// degrade to empty results) and must not return a half-built analyzer.+func TestResolveDocAnalyzerForMethod_RegisteredFactoryNoURLFailsLoud(t *testing.T) {+ RegisterAnalyzerFactory("ext_svc_nourl", func(u string) (deepdoctype.DocAnalyzer, error) {+ t.Fatalf("factory must not be invoked when %s_URL is unset", "EXT_SVC_NOURL")+ return nil, nil+ })+ // Ensure the env var is genuinely unset for this method.+ t.Setenv("EXT_SVC_NOURL_URL", "")++ a, err := resolveDocAnalyzerForMethod("ext_svc_nourl", nil)+ if err == nil {+ t.Fatal("expected an error when the external URL is unset, got nil")+ }+ if a != nil {+ t.Errorf("expected nil analyzer on error, got %#v", a)+ }+ if !strings.Contains(err.Error(), "EXT_SVC_NOURL_URL") {+ t.Errorf("error %q should name the missing env var for operator diagnosability", err)+ }+}++// An error from the registered factory is propagated verbatim to the caller.+func TestResolveDocAnalyzerForMethod_RegisteredFactoryErrorPropagates(t *testing.T) {+ sentinel := errors.New("boom from factory")+ RegisterAnalyzerFactory("ext_svc_err", func(u string) (deepdoctype.DocAnalyzer, error) {+ return nil, sentinel+ })+ t.Setenv("EXT_SVC_ERR_URL", "http://ee.example:9380")++ a, err := resolveDocAnalyzerForMethod("ext_svc_err", nil)+ if !errors.Is(err, sentinel) {+ t.Fatalf("expected the factory error to propagate, got %v", err)+ }+ if a != nil {+ t.Errorf("expected nil analyzer when the factory errors, got %#v", a)+ }+}++// --- Fallback to in-process (behavior preserved) ------------------------++// A method with no registered factory falls back to the in-process native+// factory — this is the historical, unchanged OSS production path.+func TestResolveDocAnalyzerForMethod_UnregisteredMethodFallsBackToInProcess(t *testing.T) {+ native := func() (deepdoctype.DocAnalyzer, bool) {+ return &stubDispatchAnalyzer{tag: "native"}, true+ }+ a, err := resolveDocAnalyzerForMethod("deepdoc", native)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ got, ok := a.(*stubDispatchAnalyzer)+ if !ok || got.tag != "native" {+ t.Fatalf("expected the in-process native analyzer, got %#v", a)+ }+}++// No registered factory + unavailable native backend => error (fail loud).+func TestResolveDocAnalyzerForMethod_UnregisteredMethodNoNativeErrors(t *testing.T) {+ native := func() (deepdoctype.DocAnalyzer, bool) { return nil, false }+ a, err := resolveDocAnalyzerForMethod("deepdoc", native)+ if err == nil {+ t.Fatal("expected an error when no backend is available, got nil")+ }+ if a != nil {+ t.Errorf("expected nil analyzer, got %#v", a)+ }+}++// The empty method (callers that do not thread a parse method) must resolve to+// the in-process backend, preserving existing behavior.+func TestResolveDocAnalyzerForMethod_EmptyMethodFallsBackToInProcess(t *testing.T) {+ native := func() (deepdoctype.DocAnalyzer, bool) {+ return &stubDispatchAnalyzer{tag: "native"}, true+ }+ a, err := resolveDocAnalyzerForMethod("", native)+ if err != nil {+ t.Fatalf("unexpected error for empty method: %v", err)+ }+ if a == nil {+ t.Fatal("expected the in-process analyzer for the empty method, got nil")+ }+}++// --- Corner cases -------------------------------------------------------++// Registration and resolution agree after normalization: a canonical method+// registered once is found regardless of the spelling/case used to resolve.+func TestResolveDocAnalyzerForMethod_NormalizesMethodAndCase(t *testing.T) {+ RegisterAnalyzerFactory("ext_svc_norm", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: "ext"}, nil+ })+ t.Setenv("EXT_SVC_NORM_URL", "http://ee.example:9380")++ for _, q := range []string{"ext_svc_norm", "EXT_SVC_NORM", " ext_svc_norm "} {+ a, err := resolveDocAnalyzerForMethod(q, nil)+ if err != nil {+ t.Fatalf("query %q: unexpected error: %v", q, err)+ }+ if a == nil {+ t.Fatalf("query %q: expected the registered analyzer, got nil", q)+ }+ }+}++// Surrounding whitespace in the URL is trimmed before it reaches the factory.+func TestResolveDocAnalyzerForMethod_TrimsURLWhitespace(t *testing.T) {+ var gotURL string+ RegisterAnalyzerFactory("ext_svc_trim", func(u string) (deepdoctype.DocAnalyzer, error) {+ gotURL = u+ return &stubDispatchAnalyzer{}, nil+ })+ t.Setenv("EXT_SVC_TRIM_URL", " http://ee.example:9380\n")++ if _, err := resolveDocAnalyzerForMethod("ext_svc_trim", nil); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if gotURL != "http://ee.example:9380" {+ t.Errorf("factory received %q, want the trimmed URL", gotURL)+ }+}++// Re-registering the same method replaces the previous factory (last write+// wins), so a redeploy can swap the backend without a restart of the map.+func TestResolveDocAnalyzerForMethod_LatestRegistrationWins(t *testing.T) {+ RegisterAnalyzerFactory("ext_svc_swap", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: "first"}, nil+ })+ RegisterAnalyzerFactory("ext_svc_swap", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: "second"}, nil+ })+ t.Setenv("EXT_SVC_SWAP_URL", "http://ee.example:9380")++ a, err := resolveDocAnalyzerForMethod("ext_svc_swap", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got, _ := a.(*stubDispatchAnalyzer); got == nil || got.tag != "second" {+ t.Fatalf("expected the latest registration to win, got %#v", a)+ }+}++// --- Security -----------------------------------------------------------++// The URL is an opaque string handed to the factory; the dispatcher must not+// interpret it as a filesystem path or otherwise transform it beyond trimming.+// A traversal-looking value must reach the factory verbatim.+func TestResolveDocAnalyzerForMethod_URLNotInterpretedAsPath(t *testing.T) {+ const raw = "../../etc/passwd"+ var gotURL string+ RegisterAnalyzerFactory("ext_svc_path", func(u string) (deepdoctype.DocAnalyzer, error) {+ gotURL = u+ return &stubDispatchAnalyzer{}, nil+ })+ t.Setenv("EXT_SVC_PATH_URL", raw)++ if _, err := resolveDocAnalyzerForMethod("ext_svc_path", nil); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if gotURL != raw {+ t.Errorf("dispatcher altered the URL: got %q, want verbatim %q", gotURL, raw)+ }+}++// The method name is used only as a literal (upper-cased) env-var key; a name+// carrying separators or odd characters must not panic or inject — it simply+// yields a lookup and the documented fail-loud error.+func TestResolveDocAnalyzerForMethod_MethodCannotInjectEnvKey(t *testing.T) {+ RegisterAnalyzerFactory("weird method/../x", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{}, nil+ })+ // No matching env var for the upper-cased key; must fail loud, not panic.+ _, err := resolveDocAnalyzerForMethod("weird method/../x", nil)+ if err == nil {+ t.Fatal("expected fail-loud error for a registered method with no URL, got nil")+ }+}++// --- Wiring through the real entry point --------------------------------++// The parse method threaded through pdfPostProcessOptions must reach the+// dispatcher at the real parse entry point: a registered external method routes+// parsePDFWithDeepDocOptions to the factory's analyzer (handed to parseFn),+// proving the opts.parseMethod wiring is live end-to-end without ONNX Runtime.+func TestParsePDFWithDeepDocOptions_RoutesRegisteredMethodToFactory(t *testing.T) {+ want := &stubDispatchAnalyzer{tag: "ext-wire"}+ RegisterAnalyzerFactory("ext_wire", func(u string) (deepdoctype.DocAnalyzer, error) {+ return want, nil+ })+ t.Setenv("EXT_WIRE_URL", "http://ee.example:9380")++ var got deepdoctype.DocAnalyzer+ parseFn := func(_ context.Context, _ []byte, a deepdoctype.DocAnalyzer) (*deepdoctype.ParseResult, error) {+ got = a+ return &deepdoctype.ParseResult{}, nil+ }+ res := parsePDFWithDeepDocOptions(context.Background(), "f.pdf", []byte("dummy"),+ pdfPostProcessOptions{outputFormat: "json", parseMethod: "ext_wire"}, parseFn)+ if res.Err != nil {+ t.Fatalf("unexpected error: %v", res.Err)+ }+ if got != want {+ t.Fatalf("parseFn received %#v, want the registered factory analyzer %#v", got, want)+ }+}++// The default (empty) parse method keeps the historical in-process path: with+// no registered factory, the native factory is consulted at the entry point.+func TestParsePDFWithDeepDocOptions_EmptyMethodUsesInProcess(t *testing.T) {+ nativeCalled := false+ native := func() (deepdoctype.DocAnalyzer, bool) {+ nativeCalled = true+ return &stubDispatchAnalyzer{tag: "native"}, true+ }+ // Temporarily point the package-level native factory at our stub so the+ // entry point resolves in-process without ONNX Runtime.+ prev := deepdoctype.NativeDocAnalyzerFactory+ deepdoctype.NativeDocAnalyzerFactory = native+ defer func() { deepdoctype.NativeDocAnalyzerFactory = prev }()++ parseFn := func(_ context.Context, _ []byte, a deepdoctype.DocAnalyzer) (*deepdoctype.ParseResult, error) {+ return &deepdoctype.ParseResult{}, nil+ }+ res := parsePDFWithDeepDocOptions(context.Background(), "f.pdf", []byte("dummy"),+ pdfPostProcessOptions{outputFormat: "json"}, parseFn)+ if res.Err != nil {+ t.Fatalf("unexpected error: %v", res.Err)+ }+ if !nativeCalled {+ t.Fatal("expected the in-process native factory to be consulted for the empty method")+ }+}++// --- Concurrency (read-safety) ------------------------------------------+// Concurrent resolution against a pre-registered factory must be safe: the+// registry is populated at init/startup and only read during parsing.+func TestResolveDocAnalyzerForMethod_ConcurrentResolvesSafe(t *testing.T) {+ RegisterAnalyzerFactory("ext_svc_conc", func(u string) (deepdoctype.DocAnalyzer, error) {+ return &stubDispatchAnalyzer{tag: "ext"}, nil+ })+ t.Setenv("EXT_SVC_CONC_URL", "http://ee.example:9380")++ const n = 64+ var wg sync.WaitGroup+ errs := make([]error, n)+ wg.Add(n)+ for i := 0; i < n; i++ {+ go func(i int) {+ defer wg.Done()+ a, err := resolveDocAnalyzerForMethod("ext_svc_conc", nil)+ if err == nil && a == nil {+ errs[i] = fmt.Errorf("nil analyzer without error")+ } else {+ errs[i] = err+ }+ }(i)+ }+ wg.Wait()+ for i, err := range errs {+ if err != nil {+ t.Fatalf("goroutine %d: %v", i, err)+ }+ }+}diff --git a/internal/parser/parser/pdf_parser_common.go b/internal/parser/parser/pdf_parser_common.goindex af5f7576f3..3155d9b62f 100644--- a/internal/parser/parser/pdf_parser_common.go+++ b/internal/parser/parser/pdf_parser_common.go@@ -21,6 +21,7 @@ import ("errors""fmt""image"+ "os""sort""strings""time"@@ -342,10 +343,18 @@ func normalizePDFParseMethod(raw string) string {func (p *PDFParser) validateParseMethod() error {method := normalizePDFParseMethod(p.ParseMethod)+ // A method backed by a registered external analyzer factory (see+ // RegisterAnalyzerFactory) is a supported method even though it is not in+ // the built-in whitelist — it is routed to the DeepDoc dispatch path, which+ // selects the external factory. Without this, a registered method would be+ // rejected here before dispatch ever ran.+ if _, ok := analyzerFactories[method]; ok {+ return nil+ }if _, ok := supportedPDFParseMethods[method]; ok {return nil}- return fmt.Errorf("parser: unsupported PDF parse_method %q (Go currently supports: deepdoc, plain_text, mineru, paddleocr, docling, opendataloader, somark, tcadp; tenant-resolved custom IMAGE2TEXT/VLM model names are not supported in the Go parser layer)", p.ParseMethod)+ return fmt.Errorf("parser: unsupported PDF parse_method %q (Go currently supports: deepdoc, plain_text, mineru, paddleocr, docling, opendataloader, somark, tcadp; tenant-resolved custom IMAGE2TEXT/VLM model names are not supported in the Go parser layer — methods backed by a registered external analyzer factory are supported)", p.ParseMethod)}// ParseWithResult parses a PDF into a ParseResult, dispatching on the@@ -392,6 +401,7 @@ func (p *PDFParser) ParseWithResult(ctx context.Context, filename string, data [zoom: cfg.Zoom,enableMultiColumn: p.EnableMultiColumn,flattenMediaToText: p.FlattenMediaToText,+ parseMethod: p.ParseMethod,}, deepdocpdf.NewParser(cfg).Parse)if res.Err != nil {if errors.Is(res.Err, deepdocpdf.ErrNoPDFData) ||@@ -447,10 +457,84 @@ func resolveDocAnalyzer(factory func() (deepdoctype.DocAnalyzer, bool)) (deepdocreturn nil, fmt.Errorf("deepdoc: no in-process DeepDoc backend available: build with -tags cgo and provide ORT + models")}+// analyzerFactories maps a canonical PDF parse method to a factory that builds+// an out-of-process DocAnalyzer from a base URL. It is empty by default, so the+// OSS build stays in-process only (see resolveDocAnalyzer). A deployment that+// serves a parse method over an external inference service registers a factory+// for it via RegisterAnalyzerFactory; resolveDocAnalyzerForMethod then routes+// that method to the factory, reading the endpoint from the <METHOD>_URL+// environment variable — a generic convention, so no per-service name is baked+// into this package.+//+// Registration is expected at process start-up (init), before parsing begins;+// the map is only read while parsing, so concurrent resolution is safe.+var analyzerFactories = map[string]func(baseURL string) (deepdoctype.DocAnalyzer, error){}++// RegisterAnalyzerFactory registers an external DocAnalyzer backend for a+// canonical parse method. The method is normalized (aliases collapse to the+// canonical token) so registration and resolution agree; registering the same+// method again replaces the previous factory. It mirrors+// deepdoctype.SetNativeDocAnalyzerFactory, but for out-of-process backends+// selected per parse method.+//+// Two registrations are rejected (panic) because they would fail silently:+// - a built-in method that ParseWithResult dispatches to an internal engine+// (every switch case other than the fall-through to DeepDoc) — the switch+// intercepts it before resolution runs, so the factory would never be used;+// - the empty (default) method — routing it externally would hijack every+// caller that omits parse_method and divert the default in-process path.+//+// The only built-in that may be overridden externally is "deepdoc", which falls+// through to the DeepDoc path and is the DEEPDOC_URL convention. Any+// non-built-in custom method name is also accepted. Registration is expected at+// process start-up (init); the map is only read while parsing.+func RegisterAnalyzerFactory(method string, factory func(baseURL string) (deepdoctype.DocAnalyzer, error)) {+ m := normalizePDFParseMethod(method)+ if m == "" {+ panic("parser: RegisterAnalyzerFactory: cannot register an external analyzer for the empty (default) parse method; use an explicit method name")+ }+ if m != "deepdoc" {+ if _, builtin := supportedPDFParseMethods[m]; builtin {+ panic(fmt.Sprintf("parser: RegisterAnalyzerFactory: cannot register an external analyzer for built-in method %q; it is dispatched to an internal engine and the factory would be ignored", m))+ }+ }+ analyzerFactories[m] = factory+}++// externalAnalyzerURL derives the endpoint for a registered external method+// from the generic <METHOD>_URL environment convention (upper-cased canonical+// token). The value is trimmed and otherwise handed to the factory verbatim —+// the dispatcher never interprets it as a path.+func externalAnalyzerURL(method string) string {+ return strings.TrimSpace(os.Getenv(strings.ToUpper(method) + "_URL"))+}++// resolveDocAnalyzerForMethod selects the DeepDoc backend for a parse method:+// - a method with a registered external factory (RegisterAnalyzerFactory)+// routes to that factory with the <METHOD>_URL endpoint, failing loudly+// when the URL is unset rather than silently producing empty results;+// - every other method (including "") uses the in-process native factory,+// preserving the historical in-process-only production path.+//+// It takes the in-process factory explicitly (like resolveDocAnalyzer) so the+// policy is unit-testable without ONNX Runtime, and it never returns a mock.+func resolveDocAnalyzerForMethod(method string, nativeFactory func() (deepdoctype.DocAnalyzer, bool)) (deepdoctype.DocAnalyzer, error) {+ m := normalizePDFParseMethod(method)+ if factory, ok := analyzerFactories[m]; ok {+ url := externalAnalyzerURL(m)+ if url == "" {+ return nil, fmt.Errorf("parser: parse method %q is backed by an external analyzer but %s_URL is not set", m, strings.ToUpper(m))+ }+ return factory(url)+ }+ return resolveDocAnalyzer(nativeFactory)+}+// GetDocAnalyzer returns the configured in-process DeepDoc analyzer. It is the-// single production entry point now that the external HTTP service is no longer-// a backend. PDF and non-PDF image parsers use it instead of constructing a-// client.+// in-process entry point used by PDF (deepdoc method) and non-PDF image parsers.+// External, out-of-process backends are now available too, but only per parse+// method via RegisterAnalyzerFactory (resolved in resolveDocAnalyzerForMethod);+// GetDocAnalyzer itself stays in-process only and is never the external path.func GetDocAnalyzer() (deepdoctype.DocAnalyzer, error) {return deepDocAnalyzerFromEnv()}@@ -1016,7 +1100,7 @@ func parsePDFWithDeepDocOptions(ctx context.Context, filename string, data []bytif len(data) == 0 {return emptyPDFResult(filename)}- analyzer, aerr := deepDocAnalyzerFromEnv()+ analyzer, aerr := resolveDocAnalyzerForMethod(opts.parseMethod, deepdoctype.NativeDocAnalyzerFactory)if aerr != nil {return ParseResult{Err: aerr}}diff --git a/internal/parser/parser/pdf_postprocess.go b/internal/parser/parser/pdf_postprocess.goindex 4ca4297b32..2fe6d81daf 100644--- a/internal/parser/parser/pdf_postprocess.go+++ b/internal/parser/parser/pdf_postprocess.go@@ -19,6 +19,10 @@ type pdfPostProcessOptions struct {zoom float64enableMultiColumn boolflattenMediaToText bool+ // parseMethod carries the PDFParser.ParseMethod so the DeepDoc analyzer can+ // be resolved per request (in-process vs a registered external backend).+ // Empty means the historical in-process default.+ parseMethod string}func applyPDFPostProcess(result *deepdoctype.ParseResult, opts pdfPostProcessOptions) {