Skip to content

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

fix(pipeline-log): record the pipeline Parser's parse_method, not document.parser_id (#18306) (#18763)

Taranum Wasu5231361db424
diff --git a/api/db/services/pipeline_operation_log_service.py b/api/db/services/pipeline_operation_log_service.py
index 14095d5886..3fdbc8a375 100644
--- a/api/db/services/pipeline_operation_log_service.py
+++ b/api/db/services/pipeline_operation_log_service.py
@@ -18,6 +18,7 @@ import logging
import os
import re
from datetime import datetime, timedelta
+from functools import lru_cache
from peewee import fn
@@ -29,10 +30,103 @@ from api.db.services.document_service import DocumentService
from api.db.services.knowledgebase_service import KnowledgebaseService
from api.db.services.task_service import GRAPH_RAPTOR_FAKE_DOC_ID, TaskService
from common.constants import PipelineTaskType, TaskStatus
+
+logger = logging.getLogger(__name__)
+
+
+@lru_cache(maxsize=1)
+def _parser_setup_key_by_suffix() -> dict[str, str]:
+ """Map document suffixes to the DSL "setups" key the flow Parser uses
+ to pick the per-type parser config (issue #18306).
+
+ Derived from ``ParserParam().setups`` (the source of truth used by
+ the runtime dispatch loop at rag/flow/parser/parser.py:1425-1426) so
+ the map can never diverge from the runtime — adding a new family or
+ suffix in ``ParserParam.setups`` flows through automatically.
+
+ Lazily evaluated on first call so importing this module does not pull
+ in ``rag.flow.parser.parser`` (which transitively imports deepdoc,
+ numpy, PIL) at API server startup. The first lookup happens only
+ when ``PipelineOperationLogService.create`` resolves a PARSE task's
+ pipeline parser.
+ """
+ from rag.flow.parser.parser import ParserParam
+
+ mapping: dict[str, str] = {}
+ for setup_key, conf in ParserParam().setups.items():
+ for suffix in conf.get("suffix", []):
+ mapping[suffix] = setup_key
+ return mapping
+
+
+def _load_dsl_mapping(dsl_str) -> dict | None:
+ """Decode + validate a pipeline DSL string into a mapping.
+
+ Returns None for missing, malformed, or non-mapping input so callers
+ can fall back to ``document.parser_id`` (issue #18306). An empty
+ mapping (``{}``) is a valid result and is returned as such so callers
+ can persist it on the log row. The PipelineOperationLog create path
+ decodes the DSL exactly once and reuses the parsed mapping for both
+ parser extraction and the persisted ``dsl`` column — avoids a
+ second ``json.loads`` that would re-raise on the same malformed
+ input.
+ """
+ if dsl_str is None or dsl_str == "":
+ return None
+ if isinstance(dsl_str, dict):
+ return dsl_str
+ try:
+ parsed = json.loads(dsl_str)
+ except (TypeError, ValueError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
+def _parser_for_document_from_dsl(dsl_mapping: dict | None, document_suffix: str) -> str | None:
+ """Return the parse_method the flow Parser would use for this document.
+
+ The Pipeline's Parser component configures ``parse_method`` per file
+ family (PDF, spreadsheet, slides, ...). For a dataflow task, the
+ PipelineOperationLog should record what the pipeline actually used,
+ not ``document.parser_id`` which may carry the KB default (e.g.
+ "DeepDOC") even when the Pipeline Parser component is set to
+ "Docling" — see issue #18306.
+
+ ``dsl_mapping`` must already be a decoded JSON object — callers
+ should run the raw DSL through :func:`_load_dsl_mapping` first so
+ malformed input is handled in one place.
+ """
+ if not isinstance(dsl_mapping, dict):
+ return None
+ components = dsl_mapping.get("components") or {}
+ if not isinstance(components, dict):
+ return None
+ setup_key = _parser_setup_key_by_suffix().get((document_suffix or "").lower())
+ if not setup_key:
+ return None
+ for cpn in components.values():
+ if not isinstance(cpn, dict):
+ continue
+ obj = cpn.get("obj")
+ if not isinstance(obj, dict) or obj.get("component_name") != "Parser":
+ continue
+ params = obj.get("params")
+ if not isinstance(params, dict):
+ continue
+ setups = params.get("setups")
+ if not isinstance(setups, dict):
+ continue
+ cfg = setups.get(setup_key)
+ if isinstance(cfg, dict):
+ method = cfg.get("parse_method")
+ if isinstance(method, str) and method:
+ return method
+ return None
+
+
from common.misc_utils import get_uuid
from common.time_utils import current_timestamp, datetime_format
-
# KB-level fan-out pipeline task types (task row carries a fake doc_id; the real
# participants live in task["doc_ids"]) → the KB ``<type>_task_finish_at`` column
# stamped when the task completes. Membership also marks a task as KB-scoped so
@@ -145,13 +239,13 @@ class PipelineOperationLogService(CommonService):
if task_type not in _PIPELINE_TASK_TYPE_TO_FINISH_FIELD:
ok, document = DocumentService.get_by_id(referred_document_id)
if not ok:
- logging.warning(f"Document for referred_document_id {referred_document_id} not found")
+ logger.warning(f"Document for referred_document_id {referred_document_id} not found")
return None
DocumentService.update_progress_immediately([document.to_dict()])
ok, document = DocumentService.get_by_id(referred_document_id)
if not ok:
- logging.warning(f"Document for referred_document_id {referred_document_id} not found")
+ logger.warning(f"Document for referred_document_id {referred_document_id} not found")
return None
# From document
@@ -163,6 +257,20 @@ class PipelineOperationLogService(CommonService):
progress_msg = document.progress_msg
process_begin_at = document.process_begin_at
process_duration = document.process_duration
+ parser_id = document.parser_id
+
+ # Closes #18306: decode the DSL exactly once and reuse the parsed
+ # mapping for both parser extraction and the persisted ``dsl``
+ # column — avoids a second ``json.loads`` that would re-raise on
+ # the same malformed input. If the DSL is malformed or missing we
+ # fall back to an empty mapping instead of crashing, and the
+ # warning below tells the operator why the parser resolution
+ # fell back to ``document.parser_id``.
+ dsl_mapping = _load_dsl_mapping(dsl)
+ if dsl_mapping is None:
+ dsl_for_log = {}
+ else:
+ dsl_for_log = _remove_embedding_vectors(dsl_mapping)
if pipeline_id:
ok, user_pipeline = UserCanvasService.get_by_id(pipeline_id)
@@ -171,6 +279,41 @@ class PipelineOperationLogService(CommonService):
tenant_id = user_pipeline.user_id
title = user_pipeline.title
avatar = user_pipeline.avatar
+ if task_type == PipelineTaskType.PARSE:
+ pipeline_parser = _parser_for_document_from_dsl(
+ dsl_mapping,
+ document.suffix or "",
+ )
+ if pipeline_parser:
+ parser_id = pipeline_parser
+ elif dsl_mapping is None:
+ # The pipeline's DSL is missing or malformed (None
+ # from _load_dsl_mapping for None/""/invalid JSON/
+ # non-mapping input). We can't recover the configured
+ # parser from the DSL, so log the gap explicitly
+ # before falling back to document.parser_id (which
+ # may carry the KB default like "DeepDOC" — see
+ # #18306).
+ logger.warning(
+ "[PipelineOperationLog] Pipeline DSL is missing or malformed for document_id=%s suffix=%s; falling back to document.parser_id=%s.",
+ document_id,
+ document.suffix,
+ parser_id,
+ )
+ elif dsl and dsl != "":
+ # This is not necessarily an error — many pipelines
+ # legitimately have no Parser component (e.g. they
+ # process already-chunked text from a prior stage).
+ # Demoted to DEBUG so the warning channel isn't noisy
+ # on every PARSE task where the pipeline just doesn't
+ # happen to configure a Parser component (issue #18306
+ # review follow-up).
+ logger.debug(
+ "[PipelineOperationLog] Could not resolve pipeline parser from DSL for document_id=%s suffix=%s; falling back to document.parser_id=%s.",
+ document_id,
+ document.suffix,
+ parser_id,
+ )
else:
ok, kb_info = KnowledgebaseService.get_by_id(document.kb_id)
if not ok:
@@ -194,7 +337,7 @@ class PipelineOperationLogService(CommonService):
process_duration = task.process_duration
if not cls._is_final_state(progress, operation_status):
- logging.info("Skip non-final dataset pipeline operation log task_id=%s task_type=%s progress=%s", task_id, task_type, progress)
+ logger.info("Skip non-final dataset pipeline operation log task_id=%s task_type=%s progress=%s", task_id, task_type, progress)
return None
finish_at = process_begin_at + timedelta(seconds=process_duration)
@@ -203,32 +346,32 @@ class PipelineOperationLogService(CommonService):
{_PIPELINE_TASK_TYPE_TO_FINISH_FIELD[task_type]: finish_at},
)
elif not cls._is_final_state(progress, operation_status):
- logging.info("Skip non-final file pipeline operation log document_id=%s task_type=%s progress=%s", document_id, task_type, progress)
+ logger.info("Skip non-final file pipeline operation log document_id=%s task_type=%s progress=%s", document_id, task_type, progress)
return None
- log = dict(
- id=get_uuid(),
- document_id=document_id, # GRAPH_RAPTOR_FAKE_DOC_ID or real document_id
- tenant_id=tenant_id,
- kb_id=document.kb_id,
- pipeline_id=pipeline_id,
- pipeline_title=title,
- parser_id=document.parser_id,
- document_name=document_name,
- document_suffix=document.suffix,
- document_type=document.type,
- source_from=document.source_type.split("/")[0],
- progress=progress,
- progress_msg=progress_msg,
- process_begin_at=process_begin_at,
- process_duration=process_duration,
- dsl=_remove_embedding_vectors(json.loads(dsl)),
- task_type=task_type,
- operation_status=operation_status,
- avatar=avatar,
- )
+ log = {
+ "id": get_uuid(),
+ "document_id": document_id, # GRAPH_RAPTOR_FAKE_DOC_ID or real document_id
+ "tenant_id": tenant_id,
+ "kb_id": document.kb_id,
+ "pipeline_id": pipeline_id,
+ "pipeline_title": title,
+ "parser_id": parser_id,
+ "document_name": document_name,
+ "document_suffix": document.suffix,
+ "document_type": document.type,
+ "source_from": document.source_type.split("/")[0],
+ "progress": progress,
+ "progress_msg": progress_msg,
+ "process_begin_at": process_begin_at,
+ "process_duration": process_duration,
+ "dsl": dsl_for_log,
+ "task_type": task_type,
+ "operation_status": operation_status,
+ "avatar": avatar,
+ }
timestamp = current_timestamp()
- datetime_now = datetime_format(datetime.now())
+ datetime_now = datetime_format(datetime.now()) # noqa: DTZ005
log["create_time"] = timestamp
log["create_date"] = datetime_now
log["update_time"] = timestamp
@@ -256,7 +399,7 @@ class PipelineOperationLogService(CommonService):
.first()
)
if existing:
- logging.debug(
+ logger.debug(
"Skip duplicate pipeline operation log document_id=%s pipeline_id=%s task_type=%s process_begin_at=%s existing_id=%s",
document_id,
pipeline_id,
@@ -268,14 +411,14 @@ class PipelineOperationLogService(CommonService):
obj = cls.save(**log)
- limit = int(os.getenv("PIPELINE_OPERATION_LOG_LIMIT", 1000))
+ limit = int(os.getenv("PIPELINE_OPERATION_LOG_LIMIT", "1000"))
total = cls.model.select().where(cls.model.kb_id == document.kb_id).count()
if total > limit:
keep_ids = [m.id for m in cls.model.select(cls.model.id).where(cls.model.kb_id == document.kb_id).order_by(cls.model.create_time.desc()).limit(limit)]
deleted = cls.model.delete().where(cls.model.kb_id == document.kb_id, cls.model.id.not_in(keep_ids)).execute()
- logging.info(f"[PipelineOperationLogService] Cleaned {deleted} old logs, kept latest {limit} for {document.kb_id}")
+ logger.info(f"[PipelineOperationLogService] Cleaned {deleted} old logs, kept latest {limit} for {document.kb_id}")
return obj
diff --git a/test/unit_test/api/db/services/test_pipeline_operation_log_parser.py b/test/unit_test/api/db/services/test_pipeline_operation_log_parser.py
new file mode 100644
index 0000000000..f1d41fa1ac
--- /dev/null
+++ b/test/unit_test/api/db/services/test_pipeline_operation_log_parser.py
@@ -0,0 +1,379 @@
+#
+# Copyright 2025 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.
+#
+
+"""Regression tests for the PipelineOperationLog parser extraction (issue #18306).
+
+When a Pipeline's Parser component is configured with ``parse_method =
+"Docling"`` (or any non-default parser) for PDFs, the resulting dataflow
+task should be logged with the actual pipeline parser, not the
+``document.parser_id`` which may carry the KB default (typically
+"DeepDOC"). These tests pin the helpers used to extract that value
+without re-decoding the DSL twice.
+"""
+
+import importlib
+import json
+
+from api.db.services import pipeline_operation_log_service as _pol_service
+from api.db.services.pipeline_operation_log_service import (
+ _load_dsl_mapping,
+ _parser_for_document_from_dsl,
+ _parser_setup_key_by_suffix,
+)
+
+
+def _dsl_with_parser(setup_key: str, parse_method: str) -> str:
+ return json.dumps(
+ {
+ "components": {
+ "parser-node": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {
+ "setups": {
+ setup_key: {"parse_method": parse_method},
+ },
+ },
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+
+
+# --------------------------------------------------------------------------- #
+# _load_dsl_mapping — decode + validate JSON DSL into a mapping
+# --------------------------------------------------------------------------- #
+
+
+def test_load_dsl_mapping_returns_mapping_for_valid_json():
+ dsl = _dsl_with_parser("pdf", "docling")
+ parsed = _load_dsl_mapping(dsl)
+ assert isinstance(parsed, dict)
+ assert "components" in parsed
+
+
+def test_load_dsl_mapping_returns_none_for_invalid_json():
+ """The PipelineOperationLog.create path used to crash on malformed DSL
+ by re-running json.loads — see CodeRabbit review for #18306."""
+ assert _load_dsl_mapping("not-json") is None
+
+
+def test_load_dsl_mapping_returns_none_for_empty_string():
+ assert _load_dsl_mapping("") is None
+
+
+def test_load_dsl_mapping_returns_none_for_none_input():
+ assert _load_dsl_mapping(None) is None # type: ignore[arg-type]
+
+
+def test_load_dsl_mapping_returns_dict_for_dict_input():
+ """The pipeline DSL column may be persisted as a dict (peewee
+ ``JSONField`` round-trips through Python objects). Decoding must
+ accept a dict passthrough instead of raising on ``json.loads`` — see
+ #19009 follow-up."""
+ dsl = {"components": {"p": {"obj": {"component_name": "Parser", "params": {"setups": {"pdf": {"parse_method": "docling"}}}}}}}
+ assert _load_dsl_mapping(dsl) == dsl
+
+
+def test_load_dsl_mapping_returns_dict_for_empty_dict_input():
+ """An empty dict is a valid mapping — same contract as ``{}`` JSON."""
+ assert _load_dsl_mapping({}) == {}
+
+
+def test_load_dsl_mapping_returns_none_for_json_array():
+ """JSON arrays are valid JSON but not mappings — must be rejected so
+ the caller falls back to document.parser_id instead of crashing
+ downstream on ``dsl.get("components")``."""
+ assert _load_dsl_mapping("[]") is None
+
+
+def test_load_dsl_mapping_returns_none_for_json_string():
+ assert _load_dsl_mapping('"just a string"') is None
+
+
+def test_load_dsl_mapping_returns_none_for_json_number():
+ assert _load_dsl_mapping("42") is None
+
+
+def test_load_dsl_mapping_returns_dict_for_empty_object():
+ """``{}`` is a valid mapping — should decode, even if it has no Parser
+ component for the helper to extract."""
+ assert _load_dsl_mapping("{}") == {}
+
+
+def test_load_dsl_mapping_returns_none_for_empty_components_dict():
+ """The create path falls back gracefully on ``{"components": []}``
+ because the helper can't find a Parser component — the test asserts
+ the mapping IS decoded (it's a valid mapping) but the parser lookup
+ returns None."""
+ parsed = _load_dsl_mapping(json.dumps({"components": []}))
+ assert parsed == {"components": []}
+ assert _parser_for_document_from_dsl(parsed, "pdf") is None
+
+
+# --------------------------------------------------------------------------- #
+# _parser_for_document_from_dsl — extract parse_method for the document family
+# --------------------------------------------------------------------------- #
+
+
+def test_extracts_docling_for_pdf_when_pipeline_parser_is_docling():
+ """Regression for #18306: PDF in a pipeline with Docling parser should
+ be logged as "docling", not "DeepDOC"."""
+ dsl = _load_dsl_mapping(_dsl_with_parser("pdf", "docling"))
+ assert _parser_for_document_from_dsl(dsl, "pdf") == "docling"
+
+
+def test_extracts_docling_case_insensitively_for_uppercase_suffix():
+ dsl = _load_dsl_mapping(_dsl_with_parser("pdf", "docling"))
+ assert _parser_for_document_from_dsl(dsl, "PDF") == "docling"
+
+
+def test_extracts_mineru_for_pdf_when_pipeline_parser_is_mineru():
+ dsl = _load_dsl_mapping(_dsl_with_parser("pdf", "MinerU"))
+ assert _parser_for_document_from_dsl(dsl, "pdf") == "MinerU"
+
+
+def test_extracts_deepdoc_for_spreadsheet_when_pipeline_parser_is_deepdoc():
+ """Non-PDF families fall back to their own setup key (issue #18306)."""
+ dsl = _load_dsl_mapping(_dsl_with_parser("spreadsheet", "deepdoc"))
+ assert _parser_for_document_from_dsl(dsl, "xlsx") == "deepdoc"
+
+
+def test_extracts_paddleocr_for_image_family():
+ dsl = _load_dsl_mapping(_dsl_with_parser("image", "paddleocr"))
+ assert _parser_for_document_from_dsl(dsl, "png") == "paddleocr"
+
+
+def test_extracts_deepdoc_when_pipeline_parser_is_deepdoc_for_pdf():
+ """If the operator explicitly chose DeepDOC in the pipeline, the log
+ should reflect that — not be silently overwritten."""
+ dsl = _load_dsl_mapping(_dsl_with_parser("pdf", "deepdoc"))
+ assert _parser_for_document_from_dsl(dsl, "pdf") == "deepdoc"
+
+
+def test_returns_none_when_dsl_is_none():
+ assert _parser_for_document_from_dsl(None, "pdf") is None
+
+
+def test_returns_none_when_dsl_is_empty_mapping():
+ assert _parser_for_document_from_dsl({}, "pdf") is None
+
+
+def test_returns_none_when_parser_component_is_missing():
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": {
+ "begin": {
+ "obj": {
+ "component_name": "Begin",
+ "params": {"setups": {"pdf": {"parse_method": "docling"}}},
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_returns_none_when_parser_setup_for_family_is_missing():
+ """If the pipeline's Parser component has no setup for the document's
+ file family, we don't guess — fall back to document.parser_id via
+ the caller."""
+ dsl = _load_dsl_mapping(_dsl_with_parser("image", "paddleocr"))
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_returns_none_when_suffix_is_unknown():
+ dsl = _load_dsl_mapping(_dsl_with_parser("pdf", "docling"))
+ assert _parser_for_document_from_dsl(dsl, "unknown-ext") is None
+ assert _parser_for_document_from_dsl(dsl, "") is None
+
+
+def test_returns_none_when_components_is_a_list():
+ """Robustness: if the DSL has a non-mapping ``components`` value
+ (e.g. a JSON array or a string), the helper must not crash."""
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": ["not", "a", "dict"],
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_returns_none_when_a_component_is_a_non_dict():
+ """Robustness: a non-mapping component entry must not crash."""
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": {"p": "not-a-dict"},
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_returns_none_when_params_is_non_dict():
+ """Robustness: a Parser component with non-mapping params must not
+ crash (defends against future DSL schema changes)."""
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": {
+ "p": {
+ "obj": {
+ "component_name": "Parser",
+ "params": "not-a-dict",
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_returns_none_when_setup_value_is_non_dict():
+ """Robustness: a Parser component whose setup entry for the family is
+ not a mapping (e.g. a string, number, or list) must not crash."""
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": {
+ "p": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {"setups": {"pdf": "not-a-dict"}},
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") is None
+
+
+def test_extracts_docling_when_multiple_components_present():
+ """Robustness: only the Parser component's setup matters, not Begin
+ or other components with the same family key."""
+ dsl = _load_dsl_mapping(
+ json.dumps(
+ {
+ "components": {
+ "begin": {
+ "obj": {
+ "component_name": "Begin",
+ "params": {"setups": {"pdf": {"parse_method": "docling"}}},
+ },
+ },
+ "parser": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {
+ "setups": {
+ "pdf": {"parse_method": "docling"},
+ },
+ },
+ },
+ },
+ "chunker": {
+ "obj": {
+ "component_name": "TokenChunker",
+ "params": {},
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+ )
+ assert _parser_for_document_from_dsl(dsl, "pdf") == "docling"
+
+
+# --------------------------------------------------------------------------- #
+# Setup-key exhaustive guard
+# --------------------------------------------------------------------------- #
+
+
+def test_setup_key_map_matches_parser_param_setups():
+ """The runtime source of truth is ``rag.flow.parser.parser.ParserParam().setups``.
+
+ This test iterates that source directly so it cannot diverge from
+ the runtime dispatch loop at rag/flow/parser/parser.py:1425-1426.
+ Each suffix listed in ParserParam.setups must appear in the map AND
+ must point to the correct setup key — a mismatch in either
+ direction silently regresses #18306 for that file family.
+ """
+ # Import inside the test so the parser module isn't required at
+ # collection time (the surrounding conftest pulls heavy deps).
+ from rag.flow.parser.parser import ParserParam
+
+ runtime_setups = ParserParam().setups
+ suffix_map = _parser_setup_key_by_suffix()
+
+ # Every runtime suffix must appear in the map with the correct setup key.
+ for setup_key, conf in runtime_setups.items():
+ for suffix in conf.get("suffix", []):
+ assert suffix_map[suffix] == setup_key, (
+ f"suffix {suffix!r} in ParserParam.setups[{setup_key!r}] is mapped to {suffix_map.get(suffix)!r}; the runtime dispatch at parser.py:1425-1426 will route {suffix!r} to {setup_key!r}."
+ )
+
+ # The map must contain ONLY suffixes that exist in ParserParam.setups.
+ # A stale map entry pointing at a setup that no longer lists the
+ # suffix would log the parser for a file family the runtime would
+ # reject — that would be a silent regression.
+ allowed = {suffix for conf in runtime_setups.values() for suffix in conf.get("suffix", [])}
+ stale = set(suffix_map.keys()) - allowed
+ assert not stale, f"_parser_setup_key_by_suffix has stale entries (not in ParserParam.setups): {sorted(stale)}. Remove them so we never log a parse_method for a suffix the runtime would reject."
+
+
+def test_setup_key_map_is_lazy():
+ """The suffix map must not be built at module import time. Importing
+ ``pipeline_operation_log_service`` must not pull in
+ ``rag.flow.parser.parser`` (which transitively imports deepdoc,
+ numpy, PIL) — the heavy import is deferred to first lookup.
+
+ Verified by ``lru_cache.cache_info()``: after a fresh module reload
+ ``currsize`` is zero, then 1 after the first call. A regression to
+ eager construction would have ``currsize`` already at 1 after the
+ reload completes.
+ """
+ # lru_cache lives across the whole test session — force a fresh
+ # module load so the cache state reflects the import-time behavior,
+ # not prior tests in this file.
+ importlib.reload(_pol_service)
+ fresh = _pol_service._parser_setup_key_by_suffix
+ fresh.cache_clear()
+ info_before = fresh.cache_info()
+ assert info_before.currsize == 0, (
+ f"suffix map was built at import time (cache has {info_before.currsize} entries); "
+ f"expected lazy construction so api.db.services.pipeline_operation_log_service "
+ f"can be imported in slim environments without deepdoc/numpy/PIL."
+ )
+
+ fresh() # first lookup
+ info_after = fresh.cache_info()
+ assert info_after.currsize == 1, "first lookup must populate the cache"
diff --git a/test/unit_test/api/db/services/test_pipeline_operation_log_service_create.py b/test/unit_test/api/db/services/test_pipeline_operation_log_service_create.py
new file mode 100644
index 0000000000..2badbb482d
--- /dev/null
+++ b/test/unit_test/api/db/services/test_pipeline_operation_log_service_create.py
@@ -0,0 +1,446 @@
+#
+# 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.
+#
+
+"""Integration tests for :func:`PipelineOperationLogService.create`.
+
+The actual bug fix from #18306 lives inside ``create()``: when a PARSE
+dataflow task has a valid pipeline DSL with a Parser component, the
+persisted ``parser_id`` should reflect the operator's chosen parser
+(e.g. "docling"), not the KB default the document inherited (typically
+"DeepDOC"). These tests mock the heavy service dependencies so the
+real ``create()`` method runs end-to-end and we assert on the captured
+log payload.
+"""
+
+import importlib.util
+import json
+import sys
+import types
+from contextlib import contextmanager
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# --------------------------------------------------------------------------- #
+# Module load: stub transitive imports the service module pulls in at top level
+# --------------------------------------------------------------------------- #
+#
+# ``create()`` reaches DocumentService, UserCanvasService,
+# KnowledgebaseService, and the peewee-backed DB. Stubbing those lets us
+# exercise the real create() flow without standing up the full stack.
+# Per-method behavior is patched with ``patch.object`` (and
+# ``monkeypatch.setattr`` where pytest's patcher is more ergonomic) so
+# the test stays close to ``unittest.mock`` conventions and avoids a
+# custom spec-loader dance.
+
+
+def _install_stubs(monkeypatch):
+ # peewee.fn is referenced at module import time.
+ peewee_mod = types.ModuleType("peewee")
+ peewee_mod.fn = lambda *a, **kw: None
+ monkeypatch.setitem(sys.modules, "peewee", peewee_mod)
+
+ # The service's transitive import chain pulls in api.db, common.*,
+ # and rag.flow.parser.parser — stub each module before exec so the
+ # real service module loads against synthetic bindings.
+ for mod in [
+ "common",
+ "common.constants",
+ "common.misc_utils",
+ "common.time_utils",
+ "api",
+ "api.db",
+ "api.db.db_models",
+ "api.db.services",
+ "api.db.services.common_service",
+ "api.db.services.document_service",
+ "api.db.services.knowledgebase_service",
+ "api.db.services.canvas_service",
+ "api.db.services.task_service",
+ ]:
+ monkeypatch.setitem(sys.modules, mod, types.ModuleType(mod))
+
+ @contextmanager
+ def _noop_connection_context(*a, **kw):
+ yield
+
+ DB = MagicMock()
+ DB.connection_context = _noop_connection_context
+ sys.modules["api.db.db_models"].DB = DB
+ sys.modules["api.db.db_models"].Document = object
+ # PipelineOperationLog needs concrete int returns on the count() chain
+ # so create()'s `if total > limit` branch is well-typed and the
+ # cleanup path doesn't blow up with `MagicMock > int`.
+ _PolModel = MagicMock()
+ _PolModel.select.return_value.where.return_value.count.return_value = 0
+ sys.modules["api.db.db_models"].PipelineOperationLog = _PolModel
+
+ # Build class stubs with the methods the service calls, so
+ # ``patch.object`` can target them without fighting ``object``'s
+ # read-only namespace.
+ def _class_stub(methods):
+ return type(
+ "_Stub",
+ (object,),
+ {m: classmethod(lambda cls, *a, **kw: None) for m in methods},
+ )
+
+ sys.modules["api.db.services.canvas_service"].UserCanvasService = _class_stub(["get_by_id"])
+ sys.modules["api.db.services.document_service"].DocumentService = _class_stub(["get_by_id", "update_progress_immediately"])
+ sys.modules["api.db.services.knowledgebase_service"].KnowledgebaseService = _class_stub(["get_by_id"])
+ sys.modules["api.db.services.task_service"].TaskService = _class_stub(["get_by_id"])
+ sys.modules["api.db.services.task_service"].GRAPH_RAPTOR_FAKE_DOC_ID = "fake"
+ sys.modules["api.db.services.common_service"].CommonService = _class_stub(["save"])
+ sys.modules["common.misc_utils"].get_uuid = lambda: "uuid"
+ sys.modules["common.time_utils"].current_timestamp = lambda: "ts"
+ sys.modules["common.time_utils"].datetime_format = lambda x: "dt"
+
+ # rag.flow.parser.parser is required for the suffix map derivation.
+ # Build a minimal ParserParam stub with the same shape the runtime
+ # uses for dispatch (issue #18306 review: tests must validate the
+ # helper, not a hand-maintained copy of the suffix list).
+ class _ParserParam:
+ def __init__(self):
+ self.setups = {
+ "pdf": {"suffix": ["pdf"]},
+ "markdown": {"suffix": ["md", "markdown", "mdx"]},
+ "image": {"suffix": ["jpg", "jpeg", "png", "gif"]},
+ "text&code": {"suffix": ["txt", "py", "js"]},
+ }
+
+ parser_pkg = types.ModuleType("rag.flow.parser")
+ parser_pkg.__path__ = ["/dev/null"]
+ parser_sub = types.ModuleType("rag.flow.parser.parser")
+ parser_sub.ParserParam = _ParserParam
+ monkeypatch.setitem(sys.modules, "rag", types.ModuleType("rag"))
+ monkeypatch.setitem(sys.modules, "rag.flow", types.ModuleType("rag.flow"))
+ monkeypatch.setitem(sys.modules, "rag.flow.parser", parser_pkg)
+ monkeypatch.setitem(sys.modules, "rag.flow.parser.parser", parser_sub)
+
+ # Stub PipelineTaskType/TaskStatus so the create() branching works.
+ import enum
+
+ class PipelineTaskType(str, enum.Enum):
+ PARSE = "Parse"
+ DOWNLOAD = "Download"
+ RAPTOR = "RAPTOR"
+ GRAPH_RAG = "GraphRAG"
+ MINDMAP = "Mindmap"
+ MEMORY = "Memory"
+ ARTIFACT = "Wiki"
+ SKILL = "Skill"
+ STRUCTURE_GRAPH = "StructureGraph"
+ STRUCTURE_MINDMAP = "StructureMindmap"
+ TIMELINE = "Timeline"
+ SESSION_GRAPH = "SessionGraph"
+ SESSION_ESSENCE = "SessionEssence"
+ STRUCTURE = "Structure"
+
+ class TaskStatus(str, enum.Enum):
+ CANCEL = "cancel"
+ DONE = "done"
+ FAIL = "fail"
+
+ sys.modules["common.constants"].PipelineTaskType = PipelineTaskType
+ sys.modules["common.constants"].TaskStatus = TaskStatus
+ sys.modules["api.db"].VALID_PIPELINE_TASK_TYPES = {
+ PipelineTaskType.PARSE,
+ PipelineTaskType.DOWNLOAD,
+ PipelineTaskType.RAPTOR,
+ PipelineTaskType.GRAPH_RAG,
+ PipelineTaskType.MINDMAP,
+ PipelineTaskType.ARTIFACT,
+ PipelineTaskType.SKILL,
+ }
+
+ # Load the module under test. Build the path from this test file's
+ # location so the test works regardless of the developer's checkout
+ # layout. Layout:
+ # <repo>/test/unit_test/api/db/services/<this_file>
+ # ^^^^^^^^ ^^^^^^ ^^^^^^
+ # parents[5] parents[4] parents[0]
+ service_path = Path(__file__).resolve().parents[5] / "api" / "db" / "services" / "pipeline_operation_log_service.py"
+ spec = importlib.util.spec_from_file_location("_pol_test", str(service_path))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module._parser_setup_key_by_suffix.cache_clear()
+ return module
+
+
+# --------------------------------------------------------------------------- #
+# Test helpers
+# --------------------------------------------------------------------------- #
+
+
+def _make_document(suffix: str = "pdf", parser_id: str = "DeepDOC"):
+ """Build a MagicMock that quacks like a Document ORM row."""
+ doc = MagicMock()
+ doc.parser_id = parser_id
+ doc.suffix = suffix
+ doc.name = f"sample.{suffix}"
+ doc.kb_id = "kb-1"
+ doc.run = "1"
+ doc.progress = 1.0
+ doc.progress_msg = ""
+ doc.process_begin_at = None
+ doc.process_duration = 0.0
+ doc.type = "pdf"
+ doc.source_type = "local/upload"
+ doc.to_dict = MagicMock(return_value={"id": "doc-1"})
+ return doc
+
+
+def _make_user_pipeline(pipeline_id: str = "pipe-1", title: str = "My pipeline"):
+ pipe = MagicMock()
+ pipe.id = pipeline_id
+ pipe.user_id = "tenant-1"
+ pipe.title = title
+ pipe.avatar = None
+ return pipe
+
+
+def _parse_dsl(setup_key: str, parse_method: str) -> str:
+ return json.dumps(
+ {
+ "components": {
+ "parser-node": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {"setups": {setup_key: {"parse_method": parse_method}}},
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Integration tests for create() (issue #18306 regression coverage)
+# --------------------------------------------------------------------------- #
+
+
+def pol_module(monkeypatch):
+ return _install_stubs(monkeypatch)
+
+
+def captured_log(monkeypatch, pol_module):
+ """Replace ``PipelineOperationLogService.save`` so we can capture the
+ log dict create() tries to persist, then return it without writing
+ to the DB."""
+ captured = {}
+
+ def _fake_save(cls, **kwargs):
+ captured["log"] = kwargs
+ return MagicMock()
+
+ monkeypatch.setattr(pol_module.PipelineOperationLogService, "save", classmethod(_fake_save))
+ return captured
+
+
+def test_create_prefers_pipeline_parser_for_parse_task(pol_module, captured_log, monkeypatch):
+ """Issue #18306: a PARSE task with a valid pipeline DSL must persist
+ the pipeline's Parser choice (e.g. "docling"), not the document's
+ inherited KB default ("DeepDOC")."""
+ document = _make_document(suffix="pdf", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ with patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)), patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl=_parse_dsl("pdf", "docling"),
+ )
+
+ assert captured_log["log"]["parser_id"] == "docling", f"create() must prefer the pipeline's Parser choice over document.parser_id; got parser_id={captured_log['log']['parser_id']!r}"
+
+
+def test_create_uses_document_parser_id_when_dsl_has_no_parser(pol_module, captured_log, monkeypatch):
+ """If the pipeline DSL has no Parser component, create() must fall
+ back to document.parser_id. The #18306 fix only changes the path
+ where a Parser is configured."""
+ document = _make_document(suffix="pdf", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ # DSL with no Parser component at all.
+ dsl = json.dumps({"components": {"some-other-node": {"obj": {"component_name": "Begin"}}}, "path": []})
+
+ with patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)), patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl=dsl,
+ )
+
+ log = captured_log["log"]
+ assert log["parser_id"] == "DeepDOC"
+ assert log["parser_id"] == document.parser_id
+
+
+def test_create_persists_sanitized_dsl(pol_module, captured_log, monkeypatch):
+ """create() must persist a sanitized copy of the DSL (without
+ q_<dim>_vec keys) in the dsl column — verified via the captured
+ log payload, not via a DB write."""
+ document = _make_document(suffix="md", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ dsl_with_vectors = json.dumps(
+ {
+ "components": {
+ "Tokenizer:0": {
+ "obj": {
+ "params": {
+ "outputs": {
+ "chunks": {"value": [{"text": "x", "q_1024_vec": [0.1, 0.2]}]},
+ },
+ },
+ },
+ },
+ "parser-node": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {"setups": {"markdown": {"parse_method": "docling"}}},
+ },
+ },
+ },
+ "path": [],
+ }
+ )
+
+ with patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)), patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl=dsl_with_vectors,
+ )
+
+ log = captured_log["log"]
+ persisted_dsl = log["dsl"]
+ chunk = persisted_dsl["components"]["Tokenizer:0"]["obj"]["params"]["outputs"]["chunks"]["value"][0]
+ assert "q_1024_vec" not in chunk
+ assert chunk == {"text": "x"}
+ assert log["parser_id"] == "docling"
+
+
+def test_create_accepts_dict_dsl(pol_module, captured_log, monkeypatch, caplog):
+ """A pipeline DSL stored as a dict (peewee JSONField round-trip)
+ must not crash create() and must still resolve the pipeline's
+ Parser choice. Before the dict-input fix, ``json.loads(dict)``
+ raised TypeError, the DSL was dropped, and the WARNING fired
+ spuriously on every PARSE task."""
+ document = _make_document(suffix="pdf", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ dsl_dict = {
+ "components": {
+ "parser-node": {
+ "obj": {
+ "component_name": "Parser",
+ "params": {"setups": {"pdf": {"parse_method": "docling"}}},
+ },
+ },
+ },
+ "path": [],
+ }
+
+ with (
+ caplog.at_level(pol_module.logging.WARNING, logger="root"),
+ patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)),
+ patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)),
+ ):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl=dsl_dict,
+ )
+
+ log = captured_log["log"]
+ assert log["parser_id"] == "docling", "dict DSL must still resolve the pipeline's parser"
+ # The "Pipeline DSL is missing or malformed" WARNING must NOT fire
+ # for a valid dict input.
+ assert not any("Pipeline DSL is missing or malformed" in rec.message for rec in caplog.records)
+
+
+def test_create_falls_back_to_empty_dsl_for_malformed_dsl(pol_module, captured_log, monkeypatch, caplog):
+ """Malformed DSL must not crash create() — it falls back to {} for
+ the dsl column, the WARNING fires (per CodeRabbit review), and the
+ parser_id falls back to document.parser_id."""
+ document = _make_document(suffix="pdf", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ with (
+ caplog.at_level(pol_module.logging.WARNING, logger="root"),
+ patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)),
+ patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)),
+ ):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl="not-json",
+ )
+
+ log = captured_log["log"]
+ assert log["dsl"] == {}
+ assert log["parser_id"] == "DeepDOC"
+ assert any("Pipeline DSL is missing or malformed" in rec.message for rec in caplog.records)
+
+
+def test_create_demotes_debug_log_when_dsl_has_no_parser(pol_module, captured_log, monkeypatch, caplog):
+ """Per the CodeRabbit review follow-up: when the pipeline DSL is valid
+ but has no Parser component (a common case for pipelines that don't
+ need text extraction), the message must NOT spam the warning
+ channel. Only the malformed-DSL warning is at WARNING; this one
+ is at DEBUG."""
+ document = _make_document(suffix="pdf", parser_id="DeepDOC")
+ user_pipeline = _make_user_pipeline()
+
+ dsl = json.dumps({"components": {"some-other-node": {"obj": {"component_name": "Begin"}}}, "path": []})
+
+ with (
+ caplog.at_level(pol_module.logging.DEBUG, logger="root"),
+ patch.object(pol_module.DocumentService, "get_by_id", return_value=(True, document)),
+ patch.object(pol_module.UserCanvasService, "get_by_id", return_value=(True, user_pipeline)),
+ ):
+ pol_module.PipelineOperationLogService.create(
+ document_id="doc-1",
+ pipeline_id="pipe-1",
+ task_type=pol_module.PipelineTaskType.PARSE,
+ task_id="task-1",
+ referred_document_id="doc-1",
+ dsl=dsl,
+ )
+
+ assert not any(rec.levelno >= pol_module.logging.WARNING and "Could not resolve pipeline parser from DSL" in rec.message for rec in caplog.records)
+ log = captured_log["log"]
+ assert log["parser_id"] == "DeepDOC"