mirror of
https://github.com/langgenius/dify.git
synced 2026-11-29 16:18:01 +08:00
- Segment enable/disable/delete tasks wait for a busy document index lock instead of giving up after five retries. - Tasks that exhaust retries resolve documents left in a transitional state so users can retry them, and clear indexing cache flags. - Hand off the duplicate-indexing tenant queue slot only on a final attempt. - Document cleanup bounds non-lock retries and falls back to relational cleanup when index cleanup fails terminally. - App removal continues past failing records and reports them once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
340 lines
14 KiB
Python
340 lines
14 KiB
Python
import logging
|
|
import time
|
|
from collections.abc import Callable, Sequence
|
|
from contextlib import ExitStack
|
|
|
|
import click
|
|
from celery import Task, shared_task
|
|
from redis.exceptions import RedisError
|
|
from sqlalchemy import delete, select
|
|
|
|
from configs import dify_config
|
|
from core.db.session_factory import session_factory
|
|
from core.entities.document_task import DocumentTask
|
|
from core.rag.index_processor.index_processor import IndexProcessorFactory
|
|
from core.rag.pipeline.queue import TenantIsolatedTaskQueue
|
|
from enums import CloudPlan, DeploymentEdition
|
|
from extensions.ext_redis import redis_client
|
|
from libs.datetime_utils import naive_utc_now
|
|
from models.dataset import Dataset, Document, DocumentSegment
|
|
from models.enums import IndexingStatus
|
|
from services.feature_service import FeatureService
|
|
from services.knowledge.entities.resource_scope import DatasetRef
|
|
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
|
|
from services.knowledge.indexing.adapters.redis_lock import RedisKnowledgeIndexingLock
|
|
from services.knowledge.indexing.errors import DocumentIsPausedError
|
|
from services.knowledge.indexing.locks import (
|
|
KnowledgeIndexingLease,
|
|
KnowledgeIndexingLeaseLostError,
|
|
KnowledgeIndexingLockBusyError,
|
|
document_index_lock_name,
|
|
)
|
|
from tasks.indexing_task_retry import (
|
|
is_final_attempt,
|
|
mark_document_indexing_error,
|
|
resolve_documents_after_terminal_failure,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
_RETRYABLE_ERRORS = (KnowledgeIndexingLockBusyError, KnowledgeIndexingLeaseLostError, RedisError)
|
|
|
|
|
|
def _fail_unstarted_duplicates(document_ids: Sequence[str], error: Exception) -> None:
|
|
"""Fail duplicate-indexing documents that never left the ``waiting`` state their request persisted.
|
|
|
|
Called only once the batch will not be attempted again, so a document that
|
|
no worker advanced becomes retryable by the user instead of waiting forever.
|
|
"""
|
|
|
|
message = f"Document could not be indexed: {error}"
|
|
resolve_documents_after_terminal_failure(
|
|
document_ids,
|
|
still_owned=lambda document: document.indexing_status == IndexingStatus.WAITING,
|
|
resolve=lambda document: mark_document_indexing_error(document, message),
|
|
)
|
|
|
|
|
|
@shared_task(
|
|
bind=True,
|
|
queue="dataset",
|
|
autoretry_for=_RETRYABLE_ERRORS,
|
|
retry_backoff=True,
|
|
max_retries=10,
|
|
)
|
|
def duplicate_document_indexing_task(self: Task, dataset_id: str, document_ids: list):
|
|
"""
|
|
Async process document
|
|
:param dataset_id:
|
|
:param document_ids:
|
|
|
|
.. warning:: TO BE DEPRECATED
|
|
This function will be deprecated and removed in a future version.
|
|
Use normal_duplicate_document_indexing_task or priority_duplicate_document_indexing_task instead.
|
|
|
|
Usage: duplicate_document_indexing_task.delay(dataset_id, document_ids)
|
|
"""
|
|
logger.warning("duplicate document indexing task received: %s - %s", dataset_id, document_ids)
|
|
try:
|
|
_duplicate_document_indexing_task(dataset_id, document_ids)
|
|
except _RETRYABLE_ERRORS as error:
|
|
if is_final_attempt(self, max_retries=self.max_retries):
|
|
_fail_unstarted_duplicates(document_ids, error)
|
|
raise
|
|
|
|
|
|
def _duplicate_document_indexing_task_with_tenant_queue(
|
|
tenant_id: str,
|
|
dataset_id: str,
|
|
document_ids: Sequence[str],
|
|
task_func: Callable[[str, str, Sequence[str]], None],
|
|
*,
|
|
final_attempt: bool,
|
|
) -> None:
|
|
"""Run one duplicate-indexing batch and release its tenant queue slot once.
|
|
|
|
Precondition: ``final_attempt`` is ``True`` exactly when Celery will not
|
|
retry this attempt after a lock-busy, lease-lost, or Redis error.
|
|
Postcondition: the tenant-isolated queue hand-off runs on success and on
|
|
terminal failure, and never on an attempt that will be retried, so one
|
|
batch occupies exactly one concurrency slot across all of its retries.
|
|
On terminal failure, documents still ``waiting`` are moved to ``error``.
|
|
Failure behavior: retryable errors always propagate to Celery.
|
|
"""
|
|
try:
|
|
_duplicate_document_indexing_task(dataset_id, document_ids)
|
|
except _RETRYABLE_ERRORS as error:
|
|
if not final_attempt:
|
|
# Retain the tenant's queue slot until this batch has actually finished.
|
|
raise
|
|
logger.exception(
|
|
"Duplicate document indexing exhausted its retries: tenant_id=%s dataset_id=%s document_ids=%s",
|
|
tenant_id,
|
|
dataset_id,
|
|
document_ids,
|
|
)
|
|
_fail_unstarted_duplicates(document_ids, error)
|
|
_hand_off_tenant_queue_slot(tenant_id, task_func)
|
|
raise
|
|
except Exception:
|
|
logger.exception(
|
|
"Error processing duplicate document indexing %s for tenant %s: %s",
|
|
dataset_id,
|
|
tenant_id,
|
|
document_ids,
|
|
exc_info=True,
|
|
)
|
|
_hand_off_tenant_queue_slot(tenant_id, task_func)
|
|
|
|
|
|
def _hand_off_tenant_queue_slot(
|
|
tenant_id: str,
|
|
task_func: Callable[[str, str, Sequence[str]], None],
|
|
) -> None:
|
|
"""Dispatch the tenant's next waiting batches, or clear the running flag when none wait."""
|
|
tenant_isolated_task_queue = TenantIsolatedTaskQueue(tenant_id, "duplicate_document_indexing")
|
|
|
|
# Check if there are waiting tasks in the queue
|
|
# Use rpop to get the next task from the queue (FIFO order)
|
|
next_tasks = tenant_isolated_task_queue.pull_tasks(count=dify_config.TENANT_ISOLATED_TASK_CONCURRENCY)
|
|
|
|
logger.info("duplicate document indexing tenant isolation queue %s next tasks: %s", tenant_id, next_tasks)
|
|
|
|
if next_tasks:
|
|
for next_task in next_tasks:
|
|
document_task = DocumentTask(**next_task)
|
|
# Process the next waiting task
|
|
# Keep the flag set to indicate a task is running
|
|
tenant_isolated_task_queue.set_task_waiting_time()
|
|
task_func.delay( # type: ignore
|
|
tenant_id=document_task.tenant_id,
|
|
dataset_id=document_task.dataset_id,
|
|
document_ids=document_task.document_ids,
|
|
)
|
|
else:
|
|
# No more waiting tasks, clear the flag
|
|
tenant_isolated_task_queue.delete_task_key()
|
|
|
|
|
|
def _duplicate_document_indexing_task(dataset_id: str, document_ids: Sequence[str]):
|
|
locks = RedisKnowledgeIndexingLock(redis=redis_client)
|
|
with ExitStack() as stack:
|
|
leases = {
|
|
document_id: stack.enter_context(
|
|
locks.hold(
|
|
document_index_lock_name(document_id),
|
|
timeout=600,
|
|
blocking_timeout=5,
|
|
)
|
|
)
|
|
for document_id in sorted(set(document_ids))
|
|
}
|
|
_run_duplicate_document_indexing_task(dataset_id, document_ids, leases=leases)
|
|
|
|
|
|
def _run_duplicate_document_indexing_task(
|
|
dataset_id: str,
|
|
document_ids: Sequence[str],
|
|
*,
|
|
leases: dict[str, KnowledgeIndexingLease],
|
|
) -> None:
|
|
documents: list[Document] = []
|
|
start_at = time.perf_counter()
|
|
|
|
with session_factory.create_session() as session:
|
|
try:
|
|
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
|
|
if dataset is None:
|
|
logger.info(click.style(f"Dataset not found: {dataset_id}", fg="red"))
|
|
return
|
|
|
|
# check document limit
|
|
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
|
|
features = FeatureService.get_features(dataset.tenant_id)
|
|
try:
|
|
vector_space = features.vector_space
|
|
assert vector_space is not None
|
|
count = len(document_ids)
|
|
if features.billing.subscription.plan == CloudPlan.SANDBOX and count > 1:
|
|
raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
|
|
batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
|
|
if count > batch_upload_limit:
|
|
raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
|
|
current = int(getattr(vector_space, "size", 0) or 0)
|
|
limit = int(getattr(vector_space, "limit", 0) or 0)
|
|
if limit > 0 and (current + count) > limit:
|
|
raise ValueError(
|
|
"Your total number of documents plus the number of uploads have exceeded the limit of "
|
|
"your subscription."
|
|
)
|
|
except Exception as e:
|
|
documents = list(
|
|
session.scalars(
|
|
select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id)
|
|
).all()
|
|
)
|
|
for document in documents:
|
|
if document is not None:
|
|
document.indexing_status = IndexingStatus.ERROR
|
|
document.error = str(e)
|
|
document.stopped_at = naive_utc_now()
|
|
session.add(document)
|
|
session.commit()
|
|
return
|
|
|
|
documents = list(
|
|
session.scalars(
|
|
select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id)
|
|
).all()
|
|
)
|
|
|
|
for document in documents:
|
|
lease = leases[document.id]
|
|
lease.assert_owned()
|
|
logger.info(click.style(f"Start process document: {document.id}", fg="green"))
|
|
|
|
# clean old data
|
|
index_type = document.doc_form
|
|
index_processor = IndexProcessorFactory(index_type).init_index_processor()
|
|
|
|
segments = session.scalars(
|
|
select(DocumentSegment).where(DocumentSegment.document_id == document.id)
|
|
).all()
|
|
if segments:
|
|
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
|
|
|
|
# delete from vector index
|
|
index_processor.clean(
|
|
dataset,
|
|
index_node_ids,
|
|
with_keywords=True,
|
|
delete_child_chunks=True,
|
|
session=session,
|
|
)
|
|
lease.assert_owned()
|
|
|
|
segment_ids = [segment.id for segment in segments]
|
|
if segment_ids:
|
|
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.id.in_(segment_ids))
|
|
session.execute(segment_delete_stmt)
|
|
lease.assert_owned()
|
|
session.commit()
|
|
|
|
document.indexing_status = IndexingStatus.PARSING
|
|
document.processing_started_at = naive_utc_now()
|
|
session.add(document)
|
|
indexing_service = build_document_indexing_service(session_factory=session_factory.get_session_maker())
|
|
document_refs = [DatasetRef(doc.tenant_id, doc.dataset_id).document(doc.id) for doc in documents]
|
|
# Do not keep segment deletions or parsing status changes open during extraction.
|
|
session.commit()
|
|
for document in documents:
|
|
leases[document.id].assert_owned()
|
|
indexing_service.run(
|
|
document_refs,
|
|
owned_leases={document.id: leases[document.id] for document in documents},
|
|
)
|
|
end_at = time.perf_counter()
|
|
logger.info(click.style(f"Processed dataset: {dataset_id} latency: {end_at - start_at}", fg="green"))
|
|
except DocumentIsPausedError as ex:
|
|
session.rollback()
|
|
logger.info(click.style(str(ex), fg="yellow"))
|
|
except KnowledgeIndexingLeaseLostError:
|
|
session.rollback()
|
|
raise
|
|
except Exception:
|
|
session.rollback()
|
|
logger.exception("duplicate_document_indexing_task failed, dataset_id: %s", dataset_id)
|
|
|
|
|
|
@shared_task(
|
|
bind=True,
|
|
queue="dataset",
|
|
autoretry_for=_RETRYABLE_ERRORS,
|
|
retry_backoff=True,
|
|
max_retries=10,
|
|
)
|
|
def normal_duplicate_document_indexing_task(self: Task, tenant_id: str, dataset_id: str, document_ids: Sequence[str]):
|
|
"""
|
|
Async process duplicate documents
|
|
:param tenant_id:
|
|
:param dataset_id:
|
|
:param document_ids:
|
|
|
|
Usage: normal_duplicate_document_indexing_task.delay(tenant_id, dataset_id, document_ids)
|
|
"""
|
|
logger.info("normal duplicate document indexing task received: %s - %s - %s", tenant_id, dataset_id, document_ids)
|
|
_duplicate_document_indexing_task_with_tenant_queue(
|
|
tenant_id,
|
|
dataset_id,
|
|
document_ids,
|
|
normal_duplicate_document_indexing_task,
|
|
final_attempt=is_final_attempt(self, max_retries=self.max_retries),
|
|
)
|
|
|
|
|
|
@shared_task(
|
|
bind=True,
|
|
queue="priority_dataset",
|
|
autoretry_for=_RETRYABLE_ERRORS,
|
|
retry_backoff=True,
|
|
max_retries=10,
|
|
)
|
|
def priority_duplicate_document_indexing_task(self: Task, tenant_id: str, dataset_id: str, document_ids: Sequence[str]):
|
|
"""
|
|
Async process duplicate documents
|
|
:param tenant_id:
|
|
:param dataset_id:
|
|
:param document_ids:
|
|
|
|
Usage: priority_duplicate_document_indexing_task.delay(tenant_id, dataset_id, document_ids)
|
|
"""
|
|
logger.info("priority duplicate document indexing task received: %s - %s - %s", tenant_id, dataset_id, document_ids)
|
|
_duplicate_document_indexing_task_with_tenant_queue(
|
|
tenant_id,
|
|
dataset_id,
|
|
document_ids,
|
|
priority_duplicate_document_indexing_task,
|
|
final_attempt=is_final_attempt(self, max_retries=self.max_retries),
|
|
)
|