From 2705e9570f7f96db761a58f3a3bd74a042f7077e Mon Sep 17 00:00:00 2001 From: Ehsan Barkhordar Date: Thu, 24 Sep 2026 08:01:26 +0000 Subject: [PATCH] fix(api): do not reuse task chunks the doc store no longer has Changing a document's chunk method deletes its chunks and leaves the task rows that name them. Parsing again with the original method reproduces the original digest, so reuse_prev_task_chunks adopts chunk ids that no longer resolve, sets progress to 1.0 so nothing is queued, and queue_tasks writes chunk_num as the count of the missing ids. Ask the doc store whether the document still has a chunk before reusing. Fixes #8542 --- api/db/services/task_service.py | 24 ++++++- .../services/test_task_service_queue_tasks.py | 71 +++++++++++++++++++ 2 files changed, 93 insertions(+), 2 deletions(-) diff --git a/api/db/services/task_service.py b/api/db/services/task_service.py index 6c0743dafe2..e1e53af0b78 100644 --- a/api/db/services/task_service.py +++ b/api/db/services/task_service.py @@ -32,6 +32,7 @@ from common.time_utils import current_timestamp, get_format_time from common.constants import StatusEnum, TaskStatus, MAXIMUM_PAGE_NUMBER, MAXIMUM_TASK_PAGE_NUMBER from common.parser_config_utils import normalize_layout_recognizer +from common.doc_store.doc_store_base import OrderByExpr from common.llm_request_context import normalize_llm_user_id from deepdoc.parser.excel_parser import RAGFlowExcelParser from rag.utils.redis_conn import REDIS_CONN @@ -444,6 +445,22 @@ def delete_by_doc_ids(cls, doc_ids): return cls.model.delete().where(cls.model.doc_id.in_(doc_ids)).execute() +def doc_has_chunks(doc_id: str, chunking_config: dict) -> bool: + """Whether the document still has at least one chunk in the doc store.""" + res = settings.docStoreConn.search( + ["id"], + [], + {"doc_id": [doc_id]}, + [], + OrderByExpr(), + 0, + 1, + search.index_name(chunking_config["tenant_id"]), + [chunking_config["kb_id"]], + ) + return settings.docStoreConn.get_total(res) > 0 + + def queue_tasks(doc: dict, bucket: str, name: str, priority: int, user_id: str | None = None): """Create and queue document processing tasks. @@ -564,8 +581,11 @@ def new_task(): prev_tasks = TaskService.get_tasks(doc["id"]) ck_num = 0 if prev_tasks: - for task in parse_task_array: - ck_num += reuse_prev_task_chunks(task, prev_tasks, chunking_config) + # A task row outlives the chunks it names: changing the chunk method deletes the + # document's chunks and leaves the rows behind, still naming the deleted ids. + if doc_has_chunks(doc["id"], chunking_config): + for task in parse_task_array: + ck_num += reuse_prev_task_chunks(task, prev_tasks, chunking_config) TaskService.filter_delete([Task.doc_id == doc["id"]]) pre_chunk_ids = [] for pre_task in prev_tasks: diff --git a/test/unit_test/api/db/services/test_task_service_queue_tasks.py b/test/unit_test/api/db/services/test_task_service_queue_tasks.py index 7cf573ceb2c..f8a0327d854 100644 --- a/test/unit_test/api/db/services/test_task_service_queue_tasks.py +++ b/test/unit_test/api/db/services/test_task_service_queue_tasks.py @@ -79,3 +79,74 @@ def test_queue_tasks_does_not_log_the_resume_collapse_for_naive(monkeypatch, cap _queue_tasks(monkeypatch, "naive", {"pages": [[1, 5], [10, 15]], "task_page_size": 12}) assert "uses the resume parser" not in caplog.text + + +def _reparse(monkeypatch, prev_tasks, chunks_in_store): + """Drive queue_tasks over a non-PDF document that already has task rows.""" + inserted_tasks = [] + queued_messages = [] + doc_updates = {} + doc_store = SimpleNamespace( + search=lambda *_args, **_kwargs: chunks_in_store, + get_total=lambda hits: hits, + delete=lambda *_args: None, + ) + monkeypatch.setattr(task_service.settings, "docStoreConn", doc_store) + monkeypatch.setattr(task_service.settings, "STORAGE_IMPL", SimpleNamespace(get=lambda *_args: b"")) + monkeypatch.setattr( + task_service.DocumentService, + "get_chunking_config", + lambda *_args: {"id": "doc-id", "kb_id": "kb-id", "tenant_id": "tenant-id", "parser_id": "naive", "parser_config": {}}, + ) + monkeypatch.setattr(task_service.TaskService, "get_tasks", lambda *_args: prev_tasks) + monkeypatch.setattr(task_service.TaskService, "filter_delete", lambda *_args: None) + monkeypatch.setattr(task_service.DocumentService, "update_by_id", lambda _doc_id, fields: doc_updates.update(fields)) + monkeypatch.setattr(task_service, "bulk_insert_into_db", lambda _model, tasks, _replace: inserted_tasks.extend(tasks)) + monkeypatch.setattr(task_service.DocumentService, "begin2parse", lambda *_args: None) + monkeypatch.setattr(task_service, "seed_doc_chunking_counter", lambda *_args: True) + monkeypatch.setattr(task_service.REDIS_CONN, "queue_product", lambda *_args, **kwargs: queued_messages.append(kwargs["message"]) or True) + + task_service.queue_tasks( + { + "id": "doc-id", + "name": "handbook.txt", + "type": FileType.DOC.value, + "parser_id": "naive", + "parser_config": {}, + }, + "bucket", + "handbook.txt", + 0, + ) + return inserted_tasks, queued_messages, doc_updates + + +def _finished_task_owning(chunk_id, monkeypatch): + """A completed task row for this document, as the previous parse left it.""" + first_parse, _, _ = _reparse(monkeypatch, prev_tasks=None, chunks_in_store=1) + row = dict(first_parse[0]) + row["progress"] = 1.0 + row["chunk_ids"] = chunk_id + return row + + +@pytest.mark.p2 +def test_queue_tasks_reparses_when_the_doc_store_lost_the_chunks(monkeypatch): + prev_tasks = [_finished_task_owning("chunk-a", monkeypatch)] + + inserted_tasks, queued_messages, doc_updates = _reparse(monkeypatch, prev_tasks, chunks_in_store=0) + + assert doc_updates["chunk_num"] == 0 + assert inserted_tasks[0].get("chunk_ids", "") == "" + assert len(queued_messages) == 1 + + +@pytest.mark.p2 +def test_queue_tasks_reuses_chunks_the_doc_store_still_has(monkeypatch): + prev_tasks = [_finished_task_owning("chunk-a", monkeypatch)] + + inserted_tasks, queued_messages, doc_updates = _reparse(monkeypatch, prev_tasks, chunks_in_store=1) + + assert doc_updates["chunk_num"] == 1 + assert inserted_tasks[0]["chunk_ids"] == "chunk-a" + assert queued_messages == []