feat(docreader): speed up scanned-PDF parsing, stream image results, isolate heavy async queues

Large scanned PDFs (hundreds of pages) were slow and fragile end-to-end.
This change addresses the parse, transport, and task-scheduling layers:

docreader (parse + transport):
- Parallelize per-page scanned rendering across processes (forkserver/fork),
  with serial fallback. ~4-7x faster on large scanned PDFs; pdfium is not
  thread-safe so we fan out across processes. Configurable via
  DOCREADER_PDF_RENDER_PARALLELISM.
- Add server-streaming ReadStream RPC: emit one meta frame then one frame per
  image, so documents with many page images are no longer capped by the unary
  gRPC message-size limit (a 874-page PDF produced ~193MiB of images, far over
  the 50MB cap) and memory is bounded on both ends. Unary Read is kept for
  backward compatibility; the Go production reader switches to ReadStream.

VLM:
- Make the VLM HTTP timeout configurable (VLM_HTTP_TIMEOUT_SECONDS) and raise
  the default 90s -> 180s so dense scanned-page OCR does not time out with
  "context deadline exceeded".

Async task queues:
- Isolate high-volume, model-heavy fan-out tasks into dedicated asynq queues so
  a single large document cannot saturate the shared worker pool and block
  user-facing document parsing:
    image:multimodal  -> "multimodal"
    chunk:extract     -> "graph"
    question:generation -> "question"
- Register the new queues in the server weight map and the cancel inspector's
  scanned-queue set (so cancelling a knowledge still purges its pending tasks).
This commit is contained in:
wizardchen
2026-06-02 09:50:09 +08:00
committed by lyingbug
parent 2ba1237598
commit 7b1bb1054f
26 changed files with 1994 additions and 188 deletions
+1 -1
View File
@@ -113,7 +113,7 @@ func NewChunkExtractTask(
if err != nil {
return false, err
}
task := asynq.NewTask(types.TypeChunkExtract, payload, asynq.MaxRetry(3))
task := asynq.NewTask(types.TypeChunkExtract, payload, asynq.Queue(types.QueueGraph), asynq.MaxRetry(3))
info, err := client.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "failed to enqueue task: %v", err)
@@ -525,7 +525,7 @@ func (s *KnowledgePostProcessService) enqueueQuestionGenerationTasks(
continue
}
task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue(types.QueueQuestion), asynq.MaxRetry(3))
if _, err := s.taskEnqueuer.Enqueue(task); err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to enqueue question generation batch %d for %s: %v", batchIndex-1, payload.KnowledgeID, err)
continue
@@ -3343,7 +3343,7 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
continue
}
task := asynq.NewTask(types.TypeImageMultimodal, payloadBytes)
task := asynq.NewTask(types.TypeImageMultimodal, payloadBytes, asynq.Queue(types.QueueMultimodal))
if _, err := s.task.Enqueue(task); err != nil {
logger.Warnf(ctx, "Failed to enqueue image multimodal task for %s: %v", img.ServingURL, err)
} else {
@@ -3,6 +3,7 @@ package docparser
import (
"context"
"fmt"
"io"
"os"
"strconv"
"sync"
@@ -125,11 +126,52 @@ func (p *GRPCDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (
},
}
resp, err := client.Read(ctx, protoReq)
// Use the streaming RPC so documents with many page images (large scanned
// PDFs) are not capped by the unary message-size limit. The meta frame
// arrives first, followed by one frame per image.
stream, err := client.ReadStream(ctx, protoReq)
if err != nil {
return nil, fmt.Errorf("gRPC Read failed: %w", err)
return nil, fmt.Errorf("gRPC ReadStream failed: %w", err)
}
return fromProtoReadResponse(resp), nil
result := &types.ReadResult{}
gotMeta := false
for {
frame, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
return nil, fmt.Errorf("gRPC ReadStream recv failed: %w", recvErr)
}
if meta := frame.GetMeta(); meta != nil {
gotMeta = true
result.MarkdownContent = meta.GetMarkdownContent()
result.ImageDirPath = meta.GetImageDirPath()
result.Metadata = meta.GetMetadata()
result.Error = meta.GetError()
if n := meta.GetImageCount(); n > 0 {
result.ImageRefs = make([]types.ImageRef, 0, n)
}
continue
}
if img := frame.GetImage(); img != nil {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: img.GetFilename(),
OriginalRef: img.GetOriginalRef(),
MimeType: img.GetMimeType(),
StorageKey: img.GetStorageKey(),
ImageData: img.GetImageData(),
})
}
}
if !gotMeta {
return nil, fmt.Errorf("gRPC ReadStream returned no metadata frame")
}
return result, nil
}
func (p *GRPCDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
@@ -157,24 +199,3 @@ func (p *GRPCDocumentReader) ListEngines(ctx context.Context, overrides map[stri
}
return result, nil
}
func fromProtoReadResponse(resp *proto.ReadResponse) *types.ReadResult {
result := &types.ReadResult{
MarkdownContent: resp.GetMarkdownContent(),
ImageDirPath: resp.GetImageDirPath(),
Metadata: resp.GetMetadata(),
Error: resp.GetError(),
}
for _, ref := range resp.GetImageRefs() {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: ref.GetFilename(),
OriginalRef: ref.GetOriginalRef(),
MimeType: ref.GetMimeType(),
StorageKey: ref.GetStorageKey(),
ImageData: ref.GetImageData(),
})
}
return result
}
+20 -2
View File
@@ -5,6 +5,8 @@ import (
"encoding/base64"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
@@ -15,11 +17,27 @@ import (
)
const (
defaultTimeout = 90 * time.Second
// defaultTimeout is the fallback HTTP timeout for a single VLM request.
// Dense scanned-PDF OCR (full-page text + layout extraction) can take well
// over a minute on slow endpoints, so this is intentionally generous and
// can be raised further via VLM_HTTP_TIMEOUT_SECONDS.
defaultTimeout = 180 * time.Second
defaultMaxToks = 5000
defaultTemp = float32(0.1)
)
// vlmHTTPTimeout returns the HTTP client timeout for VLM requests, read from
// the VLM_HTTP_TIMEOUT_SECONDS env var when set (and positive), falling back to
// defaultTimeout otherwise. Shared by all OpenAI-compatible VLM backends.
func vlmHTTPTimeout() time.Duration {
if v := strings.TrimSpace(os.Getenv("VLM_HTTP_TIMEOUT_SECONDS")); v != "" {
if secs, err := strconv.Atoi(v); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
}
return defaultTimeout
}
// RemoteAPIVLM implements VLM via an OpenAI-compatible chat completions API.
type RemoteAPIVLM struct {
modelName string
@@ -54,7 +72,7 @@ func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) {
apiCfg.BaseURL = config.BaseURL
}
}
httpClient := &http.Client{Timeout: defaultTimeout}
httpClient := &http.Client{Timeout: vlmHTTPTimeout()}
// 注入用户自定义 HTTP header(类似 OpenAI Python SDK 的 extra_headers)
if len(config.CustomHeaders) > 0 {
+1 -1
View File
@@ -51,7 +51,7 @@ func NewWeKnoraCloudVLM(config *Config) (*WeKnoraCloudVLM, error) {
appID: config.AppID,
apiKey: config.AppSecret,
baseURL: strings.TrimRight(config.BaseURL, "/"),
client: &http.Client{Timeout: defaultTimeout},
client: &http.Client{Timeout: vlmHTTPTimeout()},
}, nil
}
+6 -3
View File
@@ -139,9 +139,12 @@ func NewAsynqServer() *asynq.Server {
asynq.Config{
Concurrency: concurrency,
Queues: map[string]int{
"critical": 6, // Highest priority queue
"default": 3, // Default priority queue
"low": 1, // Lowest priority queue
types.QueueCritical: 6, // Highest priority queue
types.QueueDefault: 3, // Default priority queue
types.QueueLow: 1, // Lowest priority queue
types.QueueMultimodal: 1, // Isolated lane for high-volume slow VLM image tasks
types.QueueGraph: 1, // Isolated lane for high-volume slow graph-extraction tasks
types.QueueQuestion: 1, // Isolated lane for high-volume slow question-generation tasks
},
RetryDelayFunc: asynqRetryDelayFunc,
},
+11 -1
View File
@@ -47,7 +47,17 @@ type knowledgeIDProbe struct {
// queuesScanned is the fixed set of queue names this codebase enqueues
// into. Kept tight on purpose — we never scan user-defined queues.
var queuesScanned = []string{"default", "critical", "low"}
// MUST include every queue any cancelable task type can land in; the
// multimodal queue is required here so cancelling a knowledge also purges
// its (potentially hundreds of) pending image:multimodal tasks.
var queuesScanned = []string{
types.QueueDefault,
types.QueueCritical,
types.QueueLow,
types.QueueMultimodal,
types.QueueGraph,
types.QueueQuestion,
}
// taskTypesForKnowledgeCancel lists every asynq task type that carries
// a knowledge_id in its payload and should be cancelable. The set is
+23
View File
@@ -1,5 +1,28 @@
package types
// Asynq queue names. MUST stay in sync with the Queues weight map in
// router.NewAsynqServer — a task enqueued to a queue that the server does not
// list will never be consumed.
const (
QueueCritical = "critical"
QueueDefault = "default"
QueueLow = "low"
// QueueMultimodal isolates high-volume, slow VLM image tasks (OCR + caption)
// so a single large scanned PDF (hundreds–thousands of page images) cannot
// saturate the shared worker pool and block user-facing document parsing in
// the default queue.
QueueMultimodal = "multimodal"
// QueueGraph isolates high-volume, slow graph-extraction tasks (one per
// chunk, LLM-backed, only when Neo4j is enabled). Same rationale as
// QueueMultimodal: a large document must not flood the default queue.
QueueGraph = "graph"
// QueueQuestion isolates high-volume, slow question-generation tasks (one
// per 20-chunk batch, LLM-backed). Keeps a large document's hundreds of
// question batches from starving the lightweight tasks in the low queue
// (summary, deletes, wiki ingest).
QueueQuestion = "question"
)
const (
TypeChunkExtract = "chunk:extract"
TypeDocumentProcess = "document:process" // 文档处理任务