chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,152 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.doc_type import DocType
from core.rag.index_processor.constant.index_type import IndexStructureType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import DatasetAutoDisableLog, DocumentSegment
from models.dataset import Document as DatasetDocument
from models.enums import IndexingStatus, SegmentStatus
from repositories.knowledge.dataset_read_repository import (
get_dataset_doc_form,
get_document_dataset,
get_segment_child_chunks,
)
from repositories.knowledge.segment_read_adapter import get_segment_attachments
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def add_document_to_index_task(dataset_document_id: str):
"""
Async Add document to index
:param dataset_document_id:
Usage: add_document_to_index_task.delay(dataset_document_id)
"""
logger.info(click.style(f"Start add document to index: {dataset_document_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
dataset_document = session.scalar(
select(DatasetDocument).where(DatasetDocument.id == dataset_document_id).limit(1)
)
if not dataset_document:
logger.info(click.style(f"Document not found: {dataset_document_id}", fg="red"))
return
if dataset_document.indexing_status != IndexingStatus.COMPLETED:
return
indexing_cache_key = f"document_{dataset_document.id}_indexing"
try:
dataset = get_document_dataset(dataset_document, session=session)
if not dataset:
raise Exception(f"Document {dataset_document.id} dataset {dataset_document.dataset_id} doesn't exist.")
segments = session.scalars(
select(DocumentSegment)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.status == SegmentStatus.COMPLETED,
)
.order_by(DocumentSegment.position.asc())
).all()
documents = []
multimodal_documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
if dataset_document.doc_form == IndexStructureType.PARENT_CHILD_INDEX:
child_chunks = get_segment_child_chunks(segment, session=session)
if child_chunks:
child_documents = []
for child_chunk in child_chunks:
child_document = ChildDocument(
page_content=child_chunk.content,
metadata={
"doc_id": child_chunk.index_node_id,
"doc_hash": child_chunk.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
child_documents.append(child_document)
document.children = child_documents
if dataset.is_multimodal:
for attachment in get_segment_attachments(segment, session=session):
multimodal_documents.append(
AttachmentDocument(
page_content=attachment["name"],
metadata={
"doc_id": attachment["id"],
"doc_hash": "",
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
"doc_type": DocType.IMAGE,
},
)
)
documents.append(document)
index_type = get_dataset_doc_form(dataset, session=session)
index_processor = IndexProcessorFactory(index_type).init_index_processor()
index_processor.load(dataset, documents, multimodal_documents=multimodal_documents, session=session)
# delete auto disable log
session.execute(
delete(DatasetAutoDisableLog).where(DatasetAutoDisableLog.document_id == dataset_document.id)
)
# update segment to enable
session.execute(
update(DocumentSegment)
.where(DocumentSegment.document_id == dataset_document.id)
.values(enabled=True, disabled_at=None, disabled_by=None, updated_at=naive_utc_now())
)
session.commit()
# Enable summary indexes for all segments in this document
from services.knowledge.summaries.adapters import SummaryIndexAdapter
segment_ids_list = [segment.id for segment in segments]
if segment_ids_list:
try:
SummaryIndexAdapter.enable_summaries_for_segments(
dataset=dataset,
segment_ids=segment_ids_list,
)
except Exception:
logger.warning("Failed to enable summaries for document %s", dataset_document.id, exc_info=True)
end_at = time.perf_counter()
logger.info(
click.style(f"Document added to index: {dataset_document.id} latency: {end_at - start_at}", fg="green")
)
except Exception as e:
logger.exception("add document to index failed")
dataset_document.enabled = False
dataset_document.disabled_at = naive_utc_now()
dataset_document.indexing_status = IndexingStatus.ERROR
dataset_document.error = str(e)
session.commit()
finally:
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,63 @@
import logging
import time
import click
from celery import shared_task
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from core.rag.models.document import Document
from models.dataset import Dataset
from services.knowledge.dataset_service import DatasetCollectionBindingService
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def add_annotation_to_index_task(
annotation_id: str, question: str, tenant_id: str, app_id: str, collection_binding_id: str
):
"""
Add annotation to index.
:param annotation_id: annotation id
:param question: question
:param tenant_id: tenant id
:param app_id: app id
:param collection_binding_id: embedding binding id
Usage: clean_dataset_task.delay(dataset_id, tenant_id, indexing_technique, index_struct)
"""
logger.info(click.style(f"Start build index for annotation: {annotation_id}", fg="green"))
start_at = time.perf_counter()
try:
with session_factory.create_session() as session:
dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
collection_binding_id, session, "annotation"
)
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider=dataset_collection_binding.provider_name,
embedding_model=dataset_collection_binding.model_name,
collection_binding_id=dataset_collection_binding.id,
)
document = Document(
page_content=question, metadata={"annotation_id": annotation_id, "app_id": app_id, "doc_id": annotation_id}
)
with session_factory.create_session() as session:
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
vector.create([document], duplicate_check=True)
end_at = time.perf_counter()
logger.info(
click.style(
f"Build index successful for annotation: {annotation_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("Build index for annotation failed")
@@ -0,0 +1,111 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select
from werkzeug.exceptions import NotFound
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from core.rag.models.document import Document
from extensions.ext_redis import redis_client
from models.dataset import Dataset
from models.model import App, AppAnnotationSetting, MessageAnnotation
from repositories.annotation_import_job_repository import annotation_import_job_owner_key
from services.annotation_import_service import AnnotationImportRecord
from services.knowledge.dataset_service import DatasetCollectionBindingService
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def batch_import_annotations_task(
job_id: str, content_list: list[AnnotationImportRecord], app_id: str, tenant_id: str, user_id: str
) -> None:
"""
Add annotation to index.
:param job_id: job_id
:param content_list: content list
:param app_id: app id
:param tenant_id: tenant id
:param user_id: user_id
"""
logger.info(click.style(f"Start batch import annotation: {job_id}", fg="green"))
start_at = time.perf_counter()
indexing_cache_key = f"app_annotation_batch_import_{job_id}"
active_jobs_key = f"annotation_import_active:{tenant_id}"
with session_factory.create_session() as session:
# get app info
app = session.scalar(
select(App).where(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal").limit(1)
)
if app:
try:
documents = []
for content in content_list:
annotation = MessageAnnotation(
app_id=app.id, content=content["answer"], question=content["question"], account_id=user_id
)
session.add(annotation)
session.flush()
document = Document(
page_content=content["question"],
metadata={"annotation_id": annotation.id, "app_id": app_id, "doc_id": annotation.id},
)
documents.append(document)
# if annotation reply is enabled , batch add annotations' index
app_annotation_setting = session.scalar(
select(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app_id).limit(1)
)
if app_annotation_setting:
dataset_collection_binding = (
DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
app_annotation_setting.collection_binding_id, session, "annotation"
)
)
if not dataset_collection_binding:
raise NotFound("App annotation setting not found")
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider=dataset_collection_binding.provider_name,
embedding_model=dataset_collection_binding.model_name,
collection_binding_id=dataset_collection_binding.id,
)
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
vector.create(documents, duplicate_check=True)
session.commit()
redis_client.setex(indexing_cache_key, 600, "completed")
redis_client.expire(annotation_import_job_owner_key(job_id=job_id), 600)
end_at = time.perf_counter()
logger.info(
click.style(
f"Build index successful for batch import annotation: {job_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception as e:
session.rollback()
redis_client.setex(indexing_cache_key, 600, "error")
redis_client.expire(annotation_import_job_owner_key(job_id=job_id), 600)
indexing_error_msg_key = f"app_annotation_batch_import_error_msg_{job_id}"
redis_client.setex(indexing_error_msg_key, 600, str(e))
logger.exception("Build index for batch import annotations failed")
finally:
# Clean up active job tracking to release concurrency slot
try:
redis_client.zrem(active_jobs_key, job_id)
logger.debug("Released concurrency slot for job: %s", job_id)
except Exception as cleanup_error:
# Log but don't fail if cleanup fails - the job will be auto-expired
logger.warning("Failed to clean up active job tracking for %s: %s", job_id, cleanup_error)
@@ -0,0 +1,45 @@
import logging
import time
import click
from celery import shared_task
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from models.dataset import Dataset
from services.knowledge.dataset_service import DatasetCollectionBindingService
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def delete_annotation_index_task(annotation_id: str, app_id: str, tenant_id: str, collection_binding_id: str):
"""
Async delete annotation index task
"""
logger.info(click.style(f"Start delete app annotation index: {app_id}", fg="green"))
start_at = time.perf_counter()
try:
with session_factory.create_session() as session:
dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
collection_binding_id, session, "annotation"
)
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
collection_binding_id=dataset_collection_binding.id,
)
try:
with session_factory.create_session() as session:
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
vector.delete_by_metadata_field("annotation_id", annotation_id)
except Exception:
logger.exception("Delete annotation index failed when annotation deleted.")
end_at = time.perf_counter()
logger.info(click.style(f"App annotations index deleted : {app_id} latency: {end_at - start_at}", fg="green"))
except Exception:
logger.exception("Annotation deleted index failed")
@@ -0,0 +1,86 @@
import logging
import time
from contextlib import ExitStack
import click
from celery import shared_task
from sqlalchemy import exists, select
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from extensions.ext_redis import redis_client
from models.dataset import Dataset
from models.model import App, AppAnnotationSetting, MessageAnnotation
from repositories.annotation_reply_job_repository import (
RedisAnnotationReplyJobRepository,
annotation_reply_job_owner_key,
)
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def disable_annotation_reply_task(job_id: str, app_id: str, tenant_id: str):
"""
Async enable annotation reply task
"""
logger.info(click.style(f"Start delete app annotations index: {app_id}", fg="green"))
start_at = time.perf_counter()
jobs = RedisAnnotationReplyJobRepository(redis=redis_client)
# get app info
with ExitStack() as cleanup:
cleanup.callback(jobs.release_processing, app_id=app_id, action="disable", job_id=job_id)
session = cleanup.enter_context(session_factory.create_session())
app = session.scalar(
select(App).where(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal").limit(1)
)
annotations_exists = session.scalar(select(exists().where(MessageAnnotation.app_id == app_id)))
if not app:
logger.info(click.style(f"App not found: {app_id}", fg="red"))
return
app_annotation_setting = session.scalar(
select(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app_id).limit(1)
)
if not app_annotation_setting:
logger.info(click.style(f"App annotation setting not found: {app_id}", fg="red"))
return
disable_app_annotation_job_key = f"disable_app_annotation_job_{job_id}"
try:
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
collection_binding_id=app_annotation_setting.collection_binding_id,
)
try:
if annotations_exists:
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
vector.delete()
except Exception:
logger.exception("Delete annotation index failed when annotation deleted.")
redis_client.setex(disable_app_annotation_job_key, 600, "completed")
redis_client.expire(annotation_reply_job_owner_key(action="disable", job_id=job_id), 600)
# delete annotation setting
session.delete(app_annotation_setting)
session.commit()
end_at = time.perf_counter()
logger.info(
click.style(
f"App annotations index deleted : {app_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception as e:
logger.exception("Annotation batch deleted index failed")
redis_client.setex(disable_app_annotation_job_key, 600, "error")
redis_client.expire(annotation_reply_job_owner_key(action="disable", job_id=job_id), 600)
disable_app_annotation_error_key = f"disable_app_annotation_error_{job_id}"
redis_client.setex(disable_app_annotation_error_key, 600, str(e))
@@ -0,0 +1,145 @@
import logging
import time
from contextlib import ExitStack
import click
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from core.rag.models.document import Document
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset
from models.enums import CollectionBindingType
from models.model import App, AppAnnotationSetting, MessageAnnotation
from repositories.annotation_reply_job_repository import (
RedisAnnotationReplyJobRepository,
annotation_reply_job_owner_key,
)
from services.knowledge.dataset_service import DatasetCollectionBindingService
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def enable_annotation_reply_task(
job_id: str,
app_id: str,
user_id: str,
tenant_id: str,
score_threshold: float,
embedding_provider_name: str,
embedding_model_name: str,
):
"""
Async enable annotation reply task
"""
logger.info(click.style(f"Start add app annotation to index: {app_id}", fg="green"))
start_at = time.perf_counter()
jobs = RedisAnnotationReplyJobRepository(redis=redis_client)
# get app info
with ExitStack() as cleanup:
cleanup.callback(jobs.release_processing, app_id=app_id, action="enable", job_id=job_id)
session = cleanup.enter_context(session_factory.create_session())
app = session.scalar(
select(App).where(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal").limit(1)
)
if not app:
logger.info(click.style(f"App not found: {app_id}", fg="red"))
return
annotations = session.scalars(select(MessageAnnotation).where(MessageAnnotation.app_id == app_id)).all()
enable_app_annotation_job_key = f"enable_app_annotation_job_{job_id}"
try:
documents = []
dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
embedding_provider_name, embedding_model_name, session, CollectionBindingType.ANNOTATION
)
annotation_setting = session.scalar(
select(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app_id).limit(1)
)
if annotation_setting:
if dataset_collection_binding.id != annotation_setting.collection_binding_id:
old_dataset_collection_binding = (
DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
annotation_setting.collection_binding_id, session, CollectionBindingType.ANNOTATION
)
)
if old_dataset_collection_binding and annotations:
old_dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider=old_dataset_collection_binding.provider_name,
embedding_model=old_dataset_collection_binding.model_name,
collection_binding_id=old_dataset_collection_binding.id,
)
old_vector = Vector(
old_dataset,
attributes=["doc_id", "annotation_id", "app_id"],
session=session,
)
try:
old_vector.delete()
except Exception:
logger.info("Delete annotation index error", exc_info=True)
annotation_setting.score_threshold = score_threshold
annotation_setting.collection_binding_id = dataset_collection_binding.id
annotation_setting.updated_user_id = user_id
annotation_setting.updated_at = naive_utc_now()
session.add(annotation_setting)
else:
new_app_annotation_setting = AppAnnotationSetting(
app_id=app_id,
score_threshold=score_threshold,
collection_binding_id=dataset_collection_binding.id,
created_user_id=user_id,
updated_user_id=user_id,
)
session.add(new_app_annotation_setting)
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider=embedding_provider_name,
embedding_model=embedding_model_name,
collection_binding_id=dataset_collection_binding.id,
)
if annotations:
for annotation in annotations:
document = Document(
page_content=annotation.question_text,
metadata={"annotation_id": annotation.id, "app_id": app_id, "doc_id": annotation.id},
)
documents.append(document)
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
try:
vector.delete_by_metadata_field("app_id", app_id)
except Exception:
logger.info("Delete annotation index error", exc_info=True)
vector.create(documents)
session.commit()
redis_client.setex(enable_app_annotation_job_key, 600, "completed")
redis_client.expire(annotation_reply_job_owner_key(action="enable", job_id=job_id), 600)
end_at = time.perf_counter()
logger.info(
click.style(
f"App annotations added to index: {app_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception as e:
logger.exception("Annotation batch created index failed")
redis_client.setex(enable_app_annotation_job_key, 600, "error")
redis_client.expire(annotation_reply_job_owner_key(action="enable", job_id=job_id), 600)
enable_app_annotation_error_key = f"enable_app_annotation_error_{job_id}"
redis_client.setex(enable_app_annotation_error_key, 600, str(e))
session.rollback()
@@ -0,0 +1,64 @@
import logging
import time
import click
from celery import shared_task
from core.db.session_factory import session_factory
from core.rag.datasource.vdb.vector_factory import Vector
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from core.rag.models.document import Document
from models.dataset import Dataset
from services.knowledge.dataset_service import DatasetCollectionBindingService
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def update_annotation_to_index_task(
annotation_id: str, question: str, tenant_id: str, app_id: str, collection_binding_id: str
):
"""
Update annotation to index.
:param annotation_id: annotation id
:param question: question
:param tenant_id: tenant id
:param app_id: app id
:param collection_binding_id: embedding binding id
Usage: clean_dataset_task.delay(dataset_id, tenant_id, indexing_technique, index_struct)
"""
logger.info(click.style(f"Start update index for annotation: {annotation_id}", fg="green"))
start_at = time.perf_counter()
try:
with session_factory.create_session() as session:
dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
collection_binding_id, session, "annotation"
)
dataset = Dataset(
id=app_id,
tenant_id=tenant_id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider=dataset_collection_binding.provider_name,
embedding_model=dataset_collection_binding.model_name,
collection_binding_id=dataset_collection_binding.id,
)
document = Document(
page_content=question, metadata={"annotation_id": annotation_id, "app_id": app_id, "doc_id": annotation_id}
)
with session_factory.create_session() as session:
vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"], session=session)
vector.delete_by_metadata_field("annotation_id", annotation_id)
vector.add_texts([document])
end_at = time.perf_counter()
logger.info(
click.style(
f"Build index successful for annotation: {annotation_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("Build index for annotation failed")
@@ -0,0 +1,3 @@
from .workflow_execute_task import AppExecutionParams, resume_app_execution, workflow_based_app_execution_task
__all__ = ["AppExecutionParams", "resume_app_execution", "workflow_based_app_execution_task"]
@@ -0,0 +1,795 @@
import contextlib
import logging
import uuid
from collections.abc import Generator, Mapping
from enum import StrEnum
from functools import partial
from typing import Annotated, Any
from celery import shared_task
from flask import current_app, json
from pydantic import BaseModel, Discriminator, Field, Tag
from sqlalchemy import Engine, select
from sqlalchemy.orm import Session, sessionmaker
from core.app.apps.advanced_chat.app_generator import AdvancedChatAppGenerator
from core.app.apps.execution_coordinator import clear_app_task_cancellation_signals
from core.app.apps.message_based_app_generator import MessageBasedAppGenerator
from core.app.apps.workflow.app_generator import WorkflowAppGenerator
from core.app.entities.app_invoke_entities import (
AdvancedChatAppGenerateEntity,
InvokeFrom,
WorkflowAppGenerateEntity,
)
from core.app.entities.task_entities import WorkflowFinishStreamResponse, WorkflowStartStreamResponse
from core.app.layers.pause_state_persist_layer import PauseStateLayerConfig, WorkflowResumptionContext
from core.repositories import DifyCoreRepositoryFactory
from extensions.ext_database import db
from graphon.engine.filter import ResponseStreamFilter
from graphon.entities import WorkflowStartReason
from graphon.enums import WorkflowExecutionStatus
from graphon.runtime import RuntimeState
from libs.datetime_utils import naive_utc_now
from libs.flask_utils import set_login_user
from libs.helper import to_timestamp
from models.account import Account
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.model import App, AppMode, Conversation, EndUser, Message
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom, WorkflowRun
from repositories.factory import DifyAPIRepositoryFactory
from repositories.sqlalchemy_api_workflow_run_repository import WorkflowRunNotPausedError
from services.app_task_service import AppTaskService
from services.workflow_execution_identity import build_workflow_execution_identity
from services.workflow_run_agg import WorkflowRunAgg
logger = logging.getLogger(__name__)
WORKFLOW_BASED_APP_EXECUTION_QUEUE = "workflow_based_app_execution"
class _UserType(StrEnum):
ACCOUNT = "account"
END_USER = "end_user"
class _Account(BaseModel):
TYPE: _UserType = _UserType.ACCOUNT
user_id: str
class _EndUser(BaseModel):
TYPE: _UserType = _UserType.END_USER
end_user_id: str
def _get_user_type_descriminator(value: Any):
match value:
case _Account() | _EndUser():
return value.TYPE
case dict():
user_type_str = value.get("TYPE")
if user_type_str is None:
return None
try:
user_type = _UserType(user_type_str)
except ValueError:
return None
return user_type
case _:
# return None if the discriminator value isn't found
return None
type User = Annotated[
(Annotated[_Account, Tag(_UserType.ACCOUNT)] | Annotated[_EndUser, Tag(_UserType.END_USER)]),
Discriminator(_get_user_type_descriminator),
]
class AppExecutionParams(BaseModel):
app_id: str
workflow_id: str
tenant_id: str
app_mode: AppMode = AppMode.ADVANCED_CHAT
user: User
args: Mapping[str, Any]
invoke_from: InvokeFrom
streaming: bool = True
call_depth: int = 0
root_node_id: str | None = None
workflow_run_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
@classmethod
def new(
cls,
app_model: App,
workflow: Workflow,
user: Account | EndUser,
args: Mapping[str, Any],
invoke_from: InvokeFrom,
streaming: bool = True,
call_depth: int = 0,
root_node_id: str | None = None,
workflow_run_id: str | None = None,
):
user_params: _Account | _EndUser
match user:
case Account():
user_params = _Account(user_id=user.id)
case EndUser():
user_params = _EndUser(end_user_id=user.id)
case _:
raise AssertionError("this statement should be unreachable.")
return cls(
app_id=app_model.id,
workflow_id=workflow.id,
tenant_id=app_model.tenant_id,
app_mode=AppMode.value_of(app_model.mode),
user=user_params,
args=args,
invoke_from=invoke_from,
streaming=streaming,
call_depth=call_depth,
root_node_id=root_node_id,
workflow_run_id=workflow_run_id or str(uuid.uuid4()),
)
class _AppRunner:
def __init__(self, session_factory: sessionmaker | Engine, exec_params: AppExecutionParams):
if isinstance(session_factory, Engine):
session_factory = sessionmaker(bind=session_factory)
self._session_factory = session_factory
self._exec_params = exec_params
@contextlib.contextmanager
def _session(self):
with self._session_factory(expire_on_commit=False) as session, session.begin():
yield session
@contextlib.contextmanager
def _setup_flask_context(self, user: Account | EndUser):
flask_app = current_app._get_current_object() # type: ignore
with flask_app.app_context():
set_login_user(user)
yield
def run(self):
exec_params = self._exec_params
with self._session() as session:
workflow = session.get(Workflow, exec_params.workflow_id)
if workflow is None:
logger.warning("Workflow %s not found for execution", exec_params.workflow_id)
return None
app = session.get(App, workflow.app_id)
if app is None:
logger.warning("App %s not found for workflow %s", workflow.app_id, exec_params.workflow_id)
return None
pause_config = PauseStateLayerConfig(
session_factory=self._session_factory,
state_owner_user_id=workflow.created_by,
)
user = self._resolve_user()
with self._setup_flask_context(user), self._session_factory(expire_on_commit=False) as session:
try:
response = self._run_app(
app=app,
workflow=workflow,
user=user,
pause_state_config=pause_config,
session=session,
)
except Exception as exc:
if exec_params.streaming:
_publish_failed_workflow_terminal_events(
exc=exc,
exec_params=exec_params,
)
raise
if not exec_params.streaming:
return response
assert isinstance(response, Generator)
_publish_streaming_response(
response,
exec_params.workflow_run_id,
exec_params.app_mode,
exec_params.workflow_id,
exec_params.args.get("inputs", {}),
WorkflowStartReason.INITIAL,
)
def _run_app(
self,
*,
app: App,
workflow: Workflow,
user: Account | EndUser,
pause_state_config: PauseStateLayerConfig,
session: Session,
):
exec_params = self._exec_params
if exec_params.app_mode == AppMode.ADVANCED_CHAT:
return AdvancedChatAppGenerator(execution_driver=WorkflowRunAgg.run).generate(
app_model=app,
workflow=workflow,
user=user,
args=exec_params.args,
invoke_from=exec_params.invoke_from,
streaming=exec_params.streaming,
workflow_run_id=exec_params.workflow_run_id,
pause_state_config=pause_state_config,
session=session,
)
if exec_params.app_mode == AppMode.WORKFLOW:
return WorkflowAppGenerator(execution_driver=WorkflowRunAgg.run).generate(
app_model=app,
workflow=workflow,
user=user,
execution_identity=build_workflow_execution_identity(user),
args=exec_params.args,
invoke_from=exec_params.invoke_from,
streaming=exec_params.streaming,
call_depth=exec_params.call_depth,
root_node_id=exec_params.root_node_id,
workflow_run_id=exec_params.workflow_run_id,
pause_state_config=pause_state_config,
)
logger.error("Unsupported app mode for execution: %s", exec_params.app_mode)
return None
def _resolve_user(self) -> Account | EndUser:
user_params = self._exec_params.user
match user_params:
case _EndUser():
with self._session() as session:
return session.get(EndUser, user_params.end_user_id)
case _Account():
with self._session() as session:
user: Account = session.get(Account, user_params.user_id)
return user
case _:
raise AssertionError(f"user should only be _Account or _EndUser, got {type(user_params)}")
def _resolve_user_for_run(session: Session, workflow_run: WorkflowRun) -> Account | EndUser | None:
role = CreatorUserRole(workflow_run.created_by_role)
if role == CreatorUserRole.ACCOUNT:
return session.get(Account, workflow_run.created_by)
return session.get(EndUser, workflow_run.created_by)
def _publish_failed_workflow_terminal_events(exc: Exception, exec_params: AppExecutionParams) -> None:
"""Publish synthetic workflow lifecycle events for pre-runtime failures.
Early failures can happen before the app generator creates a task entity or
emits any workflow queue events. In that window SSE consumers still need a
normal terminal event to close their state machines, so we synthesize a
minimal `workflow_started -> workflow_finished(failed)` sequence here.
`workflow_run_id` is reused as a synthetic `task_id` because no application
task id exists yet on this failure path.
"""
timestamp = to_timestamp(naive_utc_now())
assert timestamp is not None
topic = MessageBasedAppGenerator.get_response_topic(exec_params.app_mode, exec_params.workflow_run_id)
started_payload = WorkflowStartStreamResponse(
task_id=exec_params.workflow_run_id,
workflow_run_id=exec_params.workflow_run_id,
data=WorkflowStartStreamResponse.Data(
id=exec_params.workflow_run_id,
workflow_id=exec_params.workflow_id,
inputs=exec_params.args.get("inputs", {}),
created_at=timestamp,
reason=WorkflowStartReason.INITIAL,
),
)
topic.publish(json.dumps(started_payload.model_dump(mode="json"), ensure_ascii=False).encode())
finished_payload = WorkflowFinishStreamResponse(
task_id=exec_params.workflow_run_id,
workflow_run_id=exec_params.workflow_run_id,
data=WorkflowFinishStreamResponse.Data(
id=exec_params.workflow_run_id,
workflow_id=exec_params.workflow_id,
status=WorkflowExecutionStatus.FAILED,
outputs=None,
error=str(exc),
elapsed_time=0.0,
total_tokens=0,
total_steps=0,
created_by={},
created_at=timestamp,
finished_at=timestamp,
exceptions_count=1,
files=[],
),
)
topic.publish(json.dumps(finished_payload.model_dump(mode="json"), ensure_ascii=False).encode())
def _get_event_data(event: str | Mapping[str, Any] | BaseModel) -> Mapping[str, Any] | None:
if isinstance(event, BaseModel):
# Temporary compatibility for legacy BaseModel stream events; remove after confirming generators always emit
# str / Mapping responses.
return event.model_dump()
if isinstance(event, Mapping):
return event
return None
def _get_event_name(event: str | Mapping[str, Any] | BaseModel) -> str | None:
event_data = _get_event_data(event)
if event_data is None:
return None
event_name = event_data.get("event")
if event_name is None:
return None
return str(event_name)
def _get_task_id(event: str | Mapping[str, Any] | BaseModel) -> str | None:
event_data = _get_event_data(event)
if event_data is None:
return None
task_id = event_data.get("task_id")
return task_id if isinstance(task_id, str) and task_id else None
def _get_error_message(event: str | Mapping[str, Any] | BaseModel) -> str | None:
event_data = _get_event_data(event)
if event_data is None:
return None
message = event_data.get("message")
return message if isinstance(message, str) and message else None
def _publish_streaming_response(
response_stream: Generator[str | Mapping[str, Any] | BaseModel],
workflow_run_id: str | uuid.UUID,
app_mode: AppMode,
workflow_id: str,
inputs: Mapping[str, Any],
started_reason: WorkflowStartReason,
) -> None:
"""Publish workflow stream events and close broken streams with a failed terminal event.
`_AppRunner.run()` only handles failures before the generator is returned.
Once we start iterating the runtime stream, this helper becomes the last
place that can guarantee SSE consumers eventually see a terminal workflow
lifecycle event.
"""
normalized_workflow_run_id = str(workflow_run_id)
def _publish_failed_terminal_event(error_message: str, task_id: str, publish_started: bool) -> None:
timestamp = to_timestamp(naive_utc_now())
assert timestamp is not None
if publish_started:
started_payload = WorkflowStartStreamResponse(
task_id=task_id,
workflow_run_id=normalized_workflow_run_id,
data=WorkflowStartStreamResponse.Data(
id=normalized_workflow_run_id,
workflow_id=workflow_id,
inputs=inputs,
created_at=timestamp,
reason=started_reason,
),
)
topic.publish(
json.dumps(
started_payload.model_dump(mode="json", fallback=str),
ensure_ascii=False,
).encode()
)
finished_payload = WorkflowFinishStreamResponse(
task_id=task_id,
workflow_run_id=normalized_workflow_run_id,
data=WorkflowFinishStreamResponse.Data(
id=normalized_workflow_run_id,
workflow_id=workflow_id,
status=WorkflowExecutionStatus.FAILED,
outputs=None,
error=error_message,
elapsed_time=0.0,
total_tokens=0,
total_steps=0,
created_by={},
created_at=timestamp,
finished_at=timestamp,
exceptions_count=1,
files=[],
),
)
topic.publish(json.dumps(finished_payload.model_dump(mode="json"), ensure_ascii=False).encode())
terminal_events = {"workflow_finished", "workflow_paused"}
unexpected_stream_end_message = "Workflow stream ended without a terminal event"
topic = MessageBasedAppGenerator.get_response_topic(app_mode, normalized_workflow_run_id)
started_published = False
terminal_published = False
last_task_id = normalized_workflow_run_id
stream_error_message: str | None = None
try:
for event in response_stream:
event_name = _get_event_name(event)
task_id = _get_task_id(event)
if task_id is not None:
last_task_id = task_id
try:
if isinstance(event, BaseModel):
payload = json.dumps(event.model_dump(mode="json"), ensure_ascii=False)
else:
payload = json.dumps(event, ensure_ascii=False, default=str)
except (TypeError, ValueError):
logger.exception("error while encoding event")
continue
topic.publish(payload.encode())
if event_name == "workflow_started":
started_published = True
elif event_name in terminal_events:
terminal_published = True
elif event_name == "error":
stream_error_message = _get_error_message(event) or stream_error_message
except Exception as exc:
if not terminal_published:
logger.exception(
"Workflow stream for run %s failed before terminal event; publishing fallback terminal event",
normalized_workflow_run_id,
)
_publish_failed_terminal_event(
error_message=str(exc) or exc.__class__.__name__,
task_id=last_task_id,
publish_started=not started_published,
)
raise
if not terminal_published:
logger.warning(
"Workflow stream for run %s ended without a terminal event; publishing fallback terminal event",
normalized_workflow_run_id,
)
_publish_failed_terminal_event(
error_message=stream_error_message or unexpected_stream_end_message,
task_id=last_task_id,
publish_started=not started_published,
)
@shared_task(queue=WORKFLOW_BASED_APP_EXECUTION_QUEUE)
def workflow_based_app_execution_task(
payload: str,
) -> Mapping[str, Any] | None:
exec_params = AppExecutionParams.model_validate_json(payload)
logger.info("workflow_based_app_execution_task run with params: %s", exec_params)
runner = _AppRunner(db.engine, exec_params=exec_params)
return runner.run()
def _resume_app_execution(payload: dict[str, Any]) -> None:
workflow_run_id = payload["workflow_run_id"]
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker=session_factory)
pause_entity = workflow_run_repo.get_workflow_pause(workflow_run_id)
if pause_entity is None:
logger.warning("No pause entity found for workflow run %s", workflow_run_id)
return
try:
resumption_context = WorkflowResumptionContext.loads(pause_entity.get_state().decode())
except Exception:
logger.exception("Failed to load resumption context for workflow run %s", workflow_run_id)
return
generate_entity = resumption_context.get_generate_entity()
graph_runtime_state = RuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
response_stream_filter = resumption_context.get_response_stream_filter()
conversation = None
message = None
with Session(db.engine, expire_on_commit=False) as session:
workflow_run = session.get(WorkflowRun, workflow_run_id)
if workflow_run is None:
logger.warning("Workflow run %s not found during resume", workflow_run_id)
return
workflow = session.get(Workflow, workflow_run.workflow_id)
if workflow is None:
logger.warning("Workflow %s not found during resume", workflow_run.workflow_id)
return
app_model = session.get(App, workflow_run.app_id)
if app_model is None:
logger.warning("App %s not found during resume", workflow_run.app_id)
return
user = _resolve_user_for_run(session, workflow_run)
if user is None:
logger.warning("User %s not found for workflow run %s", workflow_run.created_by, workflow_run_id)
return
if isinstance(generate_entity, AdvancedChatAppGenerateEntity):
if generate_entity.conversation_id is None:
logger.warning("Conversation id missing in resumption context for workflow run %s", workflow_run_id)
return
conversation = session.get(Conversation, generate_entity.conversation_id)
if conversation is None:
logger.warning(
"Conversation %s not found for workflow run %s", generate_entity.conversation_id, workflow_run_id
)
return
message = session.scalar(
select(Message)
.where(
Message.conversation_id == conversation.id,
Message.workflow_run_id == workflow_run_id,
)
.order_by(Message.created_at.desc())
.limit(1)
)
if message is None:
logger.warning("Message not found for workflow run %s", workflow_run_id)
return
if not isinstance(generate_entity, (AdvancedChatAppGenerateEntity, WorkflowAppGenerateEntity)):
logger.error(
"Unsupported resumption entity for workflow run %s (found %s)",
workflow_run_id,
type(generate_entity),
)
return
# TODO: Remove legacy task recovery 30 days after the last legacy writer is retired.
task_id = workflow_run.task_id
if task_id is None:
try:
task_id = str(uuid.UUID(generate_entity.task_id))
except ValueError:
logger.warning("Invalid saved task ID for workflow run %s", workflow_run_id)
return
AppTaskService.index_workflow_pause_task(
workflow_run=workflow_run,
pause_entity=pause_entity,
resumption_context=resumption_context,
workflow_run_repo=workflow_run_repo,
)
indexed_run = workflow_run_repo.get_workflow_run_by_id(
workflow_run.tenant_id, workflow_run.app_id, workflow_run.id
)
if indexed_run is None or indexed_run.task_id != task_id:
logger.warning("Cannot recover saved task ownership for workflow run %s", workflow_run_id)
return
workflow_run.task_id = task_id
generate_entity.task_id = task_id
# The resumed attempt reuses the paused run's task ID, so cancellation
# signals armed against that ID before or during the pause would abort it
# immediately and report it as stopped by the user. This attempt is starting
# deliberately, so drop them before any engine can observe them.
try:
workflow_run_repo.resume_workflow_pause(
workflow_run_id,
pause_entity,
before_resume=partial(clear_app_task_cancellation_signals, generate_entity.task_id),
)
except WorkflowRunNotPausedError:
logger.info("Workflow run %s was stopped or resumed by another request", workflow_run_id)
return
pause_config = PauseStateLayerConfig(
session_factory=session_factory,
state_owner_user_id=workflow.created_by,
)
match generate_entity:
case AdvancedChatAppGenerateEntity():
assert conversation is not None
assert message is not None
with session_factory() as session:
_resume_advanced_chat(
app_model=app_model,
workflow=workflow,
user=user,
conversation=conversation,
message=message,
generate_entity=generate_entity,
graph_runtime_state=graph_runtime_state,
response_stream_filter=response_stream_filter,
session_factory=session_factory,
pause_state_config=pause_config,
workflow_run_id=workflow_run_id,
workflow_run=workflow_run,
session=session,
)
case WorkflowAppGenerateEntity():
_resume_workflow(
app_model=app_model,
workflow=workflow,
user=user,
generate_entity=generate_entity,
graph_runtime_state=graph_runtime_state,
response_stream_filter=response_stream_filter,
session_factory=session_factory,
pause_state_config=pause_config,
workflow_run_id=workflow_run_id,
workflow_run=workflow_run,
workflow_run_repo=workflow_run_repo,
pause_entity=pause_entity,
)
def _resume_advanced_chat(
*,
app_model: App,
workflow: Workflow,
user: Account | EndUser,
conversation: Conversation,
message: Message,
generate_entity: AdvancedChatAppGenerateEntity,
graph_runtime_state: RuntimeState,
response_stream_filter: ResponseStreamFilter,
session_factory: sessionmaker,
pause_state_config: PauseStateLayerConfig,
workflow_run_id: str,
workflow_run: WorkflowRun,
session: Session,
) -> None:
resumed_generate_entity = generate_entity.model_copy(update={"stream": True})
try:
triggered_from = WorkflowRunTriggeredFrom(workflow_run.triggered_from)
except ValueError:
triggered_from = WorkflowRunTriggeredFrom.APP_RUN
workflow_execution_repository = DifyCoreRepositoryFactory.create_workflow_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=app_model.id,
triggered_from=triggered_from,
)
workflow_node_execution_repository = DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=app_model.id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
)
generator = AdvancedChatAppGenerator(execution_driver=WorkflowRunAgg.run)
try:
response = generator.resume(
app_model=app_model,
workflow=workflow,
user=user,
conversation=conversation,
message=message,
application_generate_entity=resumed_generate_entity,
workflow_execution_repository=workflow_execution_repository,
workflow_node_execution_repository=workflow_node_execution_repository,
graph_runtime_state=graph_runtime_state,
pause_state_config=pause_state_config,
response_stream_filter=response_stream_filter,
session=session,
)
except Exception:
logger.exception("Failed to resume chatflow execution for workflow run %s", workflow_run_id)
raise
assert isinstance(response, Generator)
_publish_streaming_response(
response,
workflow_run_id,
AppMode.ADVANCED_CHAT,
workflow.id,
generate_entity.inputs,
WorkflowStartReason.RESUMPTION,
)
def _resume_workflow(
*,
app_model: App,
workflow: Workflow,
user: Account | EndUser,
generate_entity: WorkflowAppGenerateEntity,
graph_runtime_state: RuntimeState,
response_stream_filter: ResponseStreamFilter,
session_factory: sessionmaker,
pause_state_config: PauseStateLayerConfig,
workflow_run_id: str,
workflow_run: WorkflowRun,
workflow_run_repo,
pause_entity,
) -> None:
resumed_generate_entity = generate_entity.model_copy(update={"stream": True})
try:
triggered_from = WorkflowRunTriggeredFrom(workflow_run.triggered_from)
except ValueError:
triggered_from = WorkflowRunTriggeredFrom.APP_RUN
workflow_execution_repository = DifyCoreRepositoryFactory.create_workflow_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=app_model.id,
triggered_from=triggered_from,
)
workflow_node_execution_repository = DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=app_model.id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
)
generator = WorkflowAppGenerator(execution_driver=WorkflowRunAgg.run)
try:
response = generator.resume(
app_model=app_model,
workflow=workflow,
user=user,
application_generate_entity=resumed_generate_entity,
graph_runtime_state=graph_runtime_state,
workflow_execution_repository=workflow_execution_repository,
workflow_node_execution_repository=workflow_node_execution_repository,
pause_state_config=pause_state_config,
response_stream_filter=response_stream_filter,
)
except Exception:
logger.exception("Failed to resume workflow execution for workflow run %s", workflow_run_id)
raise
assert isinstance(response, Generator)
_publish_streaming_response(
response,
workflow_run_id,
AppMode.WORKFLOW,
workflow.id,
generate_entity.inputs,
WorkflowStartReason.RESUMPTION,
)
try:
workflow_run_repo.delete_workflow_pause(pause_entity)
except Exception as exc:
if exc.__class__.__name__ != "_WorkflowRunError" or "WorkflowPause not found" not in str(exc):
raise
logger.info(
"Skipped deleting workflow pause %s after resume because it was already replaced or removed",
pause_entity.id,
)
@shared_task(queue=WORKFLOW_BASED_APP_EXECUTION_QUEUE, name="resume_app_execution")
def resume_app_execution(payload: dict[str, Any]) -> None:
_resume_app_execution(payload)
@@ -0,0 +1,15 @@
"""Durable application trace delivery routed by ``OPS_TRACE_QUEUE``."""
from celery import shared_task
from extensions.ext_application_services import application_services
@shared_task
def export_application_trace(run_id: str) -> None:
application_services().tracing.agent_traces.deliver(run_id)
@shared_task
def reconcile_application_traces() -> None:
application_services().tracing.agent_traces.reconcile()
@@ -0,0 +1,375 @@
"""
Celery tasks for async workflow execution.
These tasks handle workflow execution for different subscription tiers
with appropriate retry policies and error handling.
"""
import logging
from datetime import UTC, datetime
from typing import Any
from uuid import UUID
from celery import shared_task
from sqlalchemy import select
from sqlalchemy.orm import Session, sessionmaker
from typing_extensions import TypedDict
from configs import dify_config
from core.app.apps.workflow.app_generator import WorkflowAppGenerator
from core.app.entities.app_invoke_entities import InvokeFrom, WorkflowAppGenerateEntity
from core.app.layers.pause_state_persist_layer import PauseStateLayerConfig, WorkflowResumptionContext
from core.app.layers.timeslice_layer import TimeSliceLayer
from core.app.layers.trigger_post_layer import TriggerPostLayer
from core.db.session_factory import session_factory
from core.repositories import DifyCoreRepositoryFactory
from extensions.ext_database import db
from graphon.runtime import RuntimeState
from models.account import Account
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom, WorkflowTriggerStatus
from models.model import App, EndUser, Tenant
from models.trigger import WorkflowTriggerLog
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom, WorkflowRun
from repositories.factory import DifyAPIRepositoryFactory
from repositories.sqlalchemy_workflow_trigger_log_repository import SQLAlchemyWorkflowTriggerLogRepository
from services.app_task_service import AppTaskService
from services.errors.app import WorkflowNotFoundError
from services.workflow.entities import (
TriggerData,
WorkflowResumeTaskData,
WorkflowTaskData,
)
from services.workflow_execution_identity import build_workflow_execution_identity
from services.workflow_run_agg import WorkflowRunAgg
from tasks.workflow_cfs_scheduler.cfs_scheduler import AsyncWorkflowCFSPlanEntity, AsyncWorkflowCFSPlanScheduler
from tasks.workflow_cfs_scheduler.entities import AsyncWorkflowQueue, AsyncWorkflowSystemStrategy
logger = logging.getLogger(__name__)
class WorkflowGeneratorArgsDict(TypedDict):
inputs: dict[str, Any]
files: list[Any]
@shared_task(queue=AsyncWorkflowQueue.PROFESSIONAL_QUEUE)
def execute_workflow_professional(task_data_dict: dict[str, Any]):
"""Execute workflow for professional tier with highest priority"""
task_data = WorkflowTaskData.model_validate(task_data_dict)
cfs_plan_scheduler_entity = AsyncWorkflowCFSPlanEntity(
queue=AsyncWorkflowQueue.PROFESSIONAL_QUEUE,
schedule_strategy=AsyncWorkflowSystemStrategy,
granularity=dify_config.ASYNC_WORKFLOW_SCHEDULER_GRANULARITY,
)
_execute_workflow_common(
task_data,
AsyncWorkflowCFSPlanScheduler(plan=cfs_plan_scheduler_entity),
cfs_plan_scheduler_entity,
)
@shared_task(queue=AsyncWorkflowQueue.TEAM_QUEUE)
def execute_workflow_team(task_data_dict: dict[str, Any]):
"""Execute workflow for team tier"""
task_data = WorkflowTaskData.model_validate(task_data_dict)
cfs_plan_scheduler_entity = AsyncWorkflowCFSPlanEntity(
queue=AsyncWorkflowQueue.TEAM_QUEUE,
schedule_strategy=AsyncWorkflowSystemStrategy,
granularity=dify_config.ASYNC_WORKFLOW_SCHEDULER_GRANULARITY,
)
_execute_workflow_common(
task_data,
AsyncWorkflowCFSPlanScheduler(plan=cfs_plan_scheduler_entity),
cfs_plan_scheduler_entity,
)
@shared_task(queue=AsyncWorkflowQueue.SANDBOX_QUEUE)
def execute_workflow_sandbox(task_data_dict: dict[str, Any]):
"""Execute workflow for free tier with lower retry limit"""
task_data = WorkflowTaskData.model_validate(task_data_dict)
cfs_plan_scheduler_entity = AsyncWorkflowCFSPlanEntity(
queue=AsyncWorkflowQueue.SANDBOX_QUEUE,
schedule_strategy=AsyncWorkflowSystemStrategy,
granularity=dify_config.ASYNC_WORKFLOW_SCHEDULER_GRANULARITY,
)
_execute_workflow_common(
task_data,
AsyncWorkflowCFSPlanScheduler(plan=cfs_plan_scheduler_entity),
cfs_plan_scheduler_entity,
)
def _build_generator_args(trigger_data: TriggerData) -> WorkflowGeneratorArgsDict:
"""Build args passed into WorkflowAppGenerator.generate for Celery executions."""
return {
"inputs": dict(trigger_data.inputs),
"files": list(trigger_data.files),
}
def _execute_workflow_common(
task_data: WorkflowTaskData,
cfs_plan_scheduler: AsyncWorkflowCFSPlanScheduler,
cfs_plan_scheduler_entity: AsyncWorkflowCFSPlanEntity,
):
"""Execute workflow with common logic and trigger log updates."""
with session_factory.create_session() as session:
trigger_log_repo = SQLAlchemyWorkflowTriggerLogRepository(session)
# Get trigger log
trigger_log = trigger_log_repo.get_by_id(task_data.workflow_trigger_log_id)
if not trigger_log:
# This should not happen, but handle gracefully
return
# Reconstruct execution data from trigger log
trigger_data = TriggerData.model_validate_json(trigger_log.trigger_data)
# Update status to running
trigger_log.status = WorkflowTriggerStatus.RUNNING
trigger_log_repo.update(trigger_log)
session.commit()
start_time = datetime.now(UTC)
try:
# Get app and workflow models
app_model = session.scalar(select(App).where(App.id == trigger_log.app_id))
if not app_model:
raise WorkflowNotFoundError(f"App not found: {trigger_log.app_id}")
workflow = session.scalar(select(Workflow).where(Workflow.id == trigger_log.workflow_id))
if not workflow:
raise WorkflowNotFoundError(f"Workflow not found: {trigger_log.workflow_id}")
user = _get_user(session, trigger_log)
# Execute workflow using WorkflowAppGenerator
generator = WorkflowAppGenerator(execution_driver=WorkflowRunAgg.run)
# Adapt trigger inputs and files for the generator.
args = _build_generator_args(trigger_data)
pause_config = PauseStateLayerConfig(
session_factory=session_factory.get_session_maker(),
state_owner_user_id=workflow.created_by,
)
# NOTE (hj24)
# Release the transaction before the blocking generate() call,
# otherwise the connection stays "idle in transaction" for hours.
session.commit()
# NOTE END
generator.generate(
app_model=app_model,
workflow=workflow,
user=user,
execution_identity=build_workflow_execution_identity(user),
args=args,
invoke_from=InvokeFrom.SERVICE_API,
streaming=False,
call_depth=0,
triggered_from=trigger_data.trigger_from,
root_node_id=trigger_data.root_node_id,
graph_engine_layers=[
# TODO: Re-enable TimeSliceLayer after the HITL release.
TriggerPostLayer(cfs_plan_scheduler_entity, start_time, trigger_log.id),
],
pause_state_config=pause_config,
)
except Exception as e:
# Calculate elapsed time for failed execution
elapsed_time = (datetime.now(UTC) - start_time).total_seconds()
# Update trigger log with failure
trigger_log.status = WorkflowTriggerStatus.FAILED
trigger_log.error = str(e)
trigger_log.finished_at = datetime.now(UTC)
trigger_log.elapsed_time = elapsed_time
trigger_log_repo.update(trigger_log)
# Final failure - no retry logic (simplified like RAG tasks)
session.commit()
@shared_task(name="resume_workflow_execution")
def resume_workflow_execution(task_data_dict: dict[str, Any]) -> None:
"""Resume a paused workflow run via Celery."""
task_data = WorkflowResumeTaskData.model_validate(task_data_dict)
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory)
pause_entity = workflow_run_repo.get_workflow_pause(task_data.workflow_run_id)
if pause_entity is None:
logger.warning("No pause state for workflow run %s", task_data.workflow_run_id)
return
workflow_run = workflow_run_repo.get_workflow_run_by_id_without_tenant(pause_entity.workflow_execution_id)
if workflow_run is None:
logger.warning("Workflow run not found for pause entity: pause_entity_id=%s", pause_entity.id)
return
try:
resumption_context = WorkflowResumptionContext.loads(pause_entity.get_state().decode())
except Exception as exc:
logger.exception("Failed to load resumption context for workflow run %s", task_data.workflow_run_id)
raise exc
generate_entity = resumption_context.get_generate_entity()
if not isinstance(generate_entity, WorkflowAppGenerateEntity):
logger.error(
"Unsupported resumption entity for workflow run %s: %s",
task_data.workflow_run_id,
type(generate_entity),
)
return
# TODO: Remove legacy task recovery 30 days after the last legacy writer is retired.
task_id = workflow_run.task_id
if task_id is None:
try:
task_id = str(UUID(generate_entity.task_id))
except ValueError:
logger.warning("Invalid saved task ID for workflow run %s", task_data.workflow_run_id)
return
AppTaskService.index_workflow_pause_task(
workflow_run=workflow_run,
pause_entity=pause_entity,
resumption_context=resumption_context,
workflow_run_repo=workflow_run_repo,
)
indexed_run = workflow_run_repo.get_workflow_run_by_id(
workflow_run.tenant_id, workflow_run.app_id, workflow_run.id
)
if indexed_run is None or indexed_run.task_id != task_id:
logger.warning("Cannot recover saved task ownership for workflow run %s", task_data.workflow_run_id)
return
workflow_run.task_id = task_id
generate_entity.task_id = task_id
graph_runtime_state = RuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
response_stream_filter = resumption_context.get_response_stream_filter()
with session_factory() as session:
workflow = session.scalar(select(Workflow).where(Workflow.id == workflow_run.workflow_id))
if workflow is None:
raise WorkflowNotFoundError(
f"Workflow not found: workflow_run_id={workflow_run.id}, workflow_id={workflow_run.workflow_id}"
)
user = _get_user(session, workflow_run)
app_model = session.scalar(select(App).where(App.id == workflow_run.app_id))
if app_model is None:
raise _AppNotFoundError(f"App not found: app_id={workflow_run.app_id}, workflow_run_id={workflow_run.id}")
workflow_execution_repository = DifyCoreRepositoryFactory.create_workflow_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=generate_entity.app_config.app_id,
triggered_from=WorkflowRunTriggeredFrom(workflow_run.triggered_from),
)
workflow_node_execution_repository = DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
session_factory=session_factory,
tenant_id=app_model.tenant_id,
user=user,
app_id=generate_entity.app_config.app_id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
)
pause_config = PauseStateLayerConfig(
session_factory=session_factory,
state_owner_user_id=workflow.created_by,
)
generator = WorkflowAppGenerator(execution_driver=WorkflowRunAgg.run)
start_time = datetime.now(UTC)
graph_engine_layers = []
trigger_log = _query_trigger_log_info(session_factory, task_data.workflow_run_id)
if trigger_log:
cfs_plan_scheduler_entity = AsyncWorkflowCFSPlanEntity(
queue=AsyncWorkflowQueue(trigger_log.queue_name),
schedule_strategy=AsyncWorkflowSystemStrategy,
granularity=dify_config.ASYNC_WORKFLOW_SCHEDULER_GRANULARITY,
)
cfs_plan_scheduler = AsyncWorkflowCFSPlanScheduler(plan=cfs_plan_scheduler_entity)
graph_engine_layers.extend(
[
TimeSliceLayer(cfs_plan_scheduler),
TriggerPostLayer(cfs_plan_scheduler_entity, start_time, trigger_log.id),
]
)
workflow_run_repo.resume_workflow_pause(task_data.workflow_run_id, pause_entity)
generator.resume(
app_model=app_model,
workflow=workflow,
user=user,
application_generate_entity=generate_entity,
graph_runtime_state=graph_runtime_state,
workflow_execution_repository=workflow_execution_repository,
workflow_node_execution_repository=workflow_node_execution_repository,
graph_engine_layers=graph_engine_layers,
pause_state_config=pause_config,
response_stream_filter=response_stream_filter,
)
workflow_run_repo.delete_workflow_pause(pause_entity)
def _get_user(session: Session, workflow_run: WorkflowRun | WorkflowTriggerLog) -> Account | EndUser:
"""Compose user from trigger log"""
tenant = session.scalar(select(Tenant).where(Tenant.id == workflow_run.tenant_id))
if not tenant:
raise _TenantNotFoundError(
"Tenant not found for WorkflowRun: tenant_id=%s, workflow_run_id=%s",
workflow_run.tenant_id,
workflow_run.id,
)
# Get user from trigger log
if workflow_run.created_by_role == CreatorUserRole.ACCOUNT:
user = session.scalar(select(Account).where(Account.id == workflow_run.created_by))
if user:
user.set_current_tenant_with_session(tenant, session=session)
else: # CreatorUserRole.END_USER
user = session.scalar(select(EndUser).where(EndUser.id == workflow_run.created_by))
if not user:
raise _UserNotFoundError(
"User not found: user_id=%s, created_by_role=%s, workflow_run_id=%s",
workflow_run.created_by,
workflow_run.created_by_role,
workflow_run.id,
)
return user
def _query_trigger_log_info(session_factory: sessionmaker[Session], workflow_run_id) -> WorkflowTriggerLog | None:
with session_factory() as session, session.begin():
trigger_log_repo = SQLAlchemyWorkflowTriggerLogRepository(session)
trigger_log = trigger_log_repo.get_by_workflow_run_id(workflow_run_id)
if not trigger_log:
logger.debug("Trigger log not found for workflow_run: workflow_run_id=%s", workflow_run_id)
return None
return trigger_log
class _TenantNotFoundError(Exception):
pass
class _UserNotFoundError(Exception):
pass
class _AppNotFoundError(Exception):
pass
@@ -0,0 +1,249 @@
import logging
import time
from typing import cast
import click
from celery import shared_task
from sqlalchemy import delete, select
from sqlalchemy.engine import CursorResult
from core.db.session_factory import session_factory
from core.tools.utils.web_reader_tool import get_image_upload_file_ids
from extensions.ext_storage import storage
from models.dataset import DatasetMetadataBinding, DocumentSegment, SegmentAttachmentBinding
from models.model import UploadFile
from services.dataset_knowledge_fs_upgrade_file_lease import reserve_upgrade_file_cleanup
from services.knowledge.indexing.adapters.cleanup import clean_document_indexes
from tasks.refresh_billing_vector_space_task import schedule_billing_vector_space_refresh
logger = logging.getLogger(__name__)
# Batch size for database operations to keep transactions short
BATCH_SIZE = 1000
@shared_task(queue="dataset")
def batch_clean_document_task(
document_ids: list[str],
dataset_id: str,
doc_form: str | None,
file_ids: list[str],
) -> None:
"""
Clean document when document deleted.
:param document_ids: document ids
:param dataset_id: dataset id
:param doc_form: doc_form
:param file_ids: file ids
Usage: batch_clean_document_task.delay(document_ids, dataset_id)
"""
logger.info(click.style("Start batch clean documents when documents deleted", fg="green"))
start_at = time.perf_counter()
if not doc_form:
raise ValueError("doc_form is required")
storage_keys_to_delete: list[str] = []
index_node_ids: list[str] = []
segment_ids: list[str] = []
total_image_upload_file_ids: list[str] = []
dataset_tenant_id: str | None = None
deletable_file_ids = list(file_ids)
try:
# ============ Step 1: Query segment and file data (short read-only transaction) ============
with session_factory.create_session() as session, session.begin():
# Get segments info
segments = session.scalars(
select(DocumentSegment).where(DocumentSegment.document_id.in_(document_ids))
).all()
if segments:
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
segment_ids = [segment.id for segment in segments]
# Collect image file IDs from segment content
for segment in segments:
image_upload_file_ids = get_image_upload_file_ids(segment.content)
total_image_upload_file_ids.extend(image_upload_file_ids)
total_image_upload_file_ids.extend(
session.scalars(
select(SegmentAttachmentBinding.attachment_id).where(
SegmentAttachmentBinding.tenant_id == segments[0].tenant_id,
SegmentAttachmentBinding.dataset_id == dataset_id,
SegmentAttachmentBinding.document_id.in_(document_ids),
SegmentAttachmentBinding.segment_id.in_(segment_ids),
)
).all()
)
# Query storage keys for image files
if total_image_upload_file_ids:
image_files = session.scalars(
select(UploadFile).where(UploadFile.id.in_(total_image_upload_file_ids))
).all()
storage_keys_to_delete.extend([f.key for f in image_files if f and f.key])
# Query storage keys for document files
if file_ids:
leased_file_ids = reserve_upgrade_file_cleanup(session, file_ids)
deletable_file_ids = [file_id for file_id in file_ids if file_id not in leased_file_ids]
if leased_file_ids:
logger.info(
"Keep %d source files while KnowledgeFS upgrade leases are active, dataset_id=%s",
len(leased_file_ids),
dataset_id,
)
files = session.scalars(select(UploadFile).where(UploadFile.id.in_(deletable_file_ids))).all()
storage_keys_to_delete.extend([f.key for f in files if f and f.key])
# A retry can still have summaries even after its segments were deleted.
try:
dataset_tenant_id = clean_document_indexes(
dataset_id=dataset_id,
document_ids=document_ids,
doc_form=doc_form,
new_session=session_factory.create_session,
)
except Exception:
logger.exception(
"Failed to clean vector index for dataset_id: %s, document_ids: %s, index_node_ids count: %d",
dataset_id,
document_ids,
len(index_node_ids),
)
# ============ Step 3: Delete metadata binding (separate short transaction) ============
try:
with session_factory.create_session() as session:
result = cast(
CursorResult,
session.execute(
delete(DatasetMetadataBinding).where(
DatasetMetadataBinding.dataset_id == dataset_id,
DatasetMetadataBinding.document_id.in_(document_ids),
)
),
)
deleted_count = result.rowcount
session.commit()
logger.debug("Deleted %d metadata bindings for dataset_id: %s", deleted_count, dataset_id)
except Exception:
logger.exception(
"Failed to delete metadata bindings for dataset_id: %s, document_ids: %s",
dataset_id,
document_ids,
)
# ============ Step 4: Batch delete UploadFile records (multiple short transactions) ============
if total_image_upload_file_ids:
failed_batches = 0
total_batches = (len(total_image_upload_file_ids) + BATCH_SIZE - 1) // BATCH_SIZE
for i in range(0, len(total_image_upload_file_ids), BATCH_SIZE):
batch = total_image_upload_file_ids[i : i + BATCH_SIZE]
try:
with session_factory.create_session() as session:
stmt = delete(UploadFile).where(UploadFile.id.in_(batch))
session.execute(stmt)
session.commit()
except Exception:
failed_batches += 1
logger.exception(
"Failed to delete image UploadFile batch %d-%d for dataset_id: %s",
i,
i + len(batch),
dataset_id,
)
if failed_batches > 0:
logger.warning(
"Image UploadFile deletion: %d/%d batches failed for dataset_id: %s",
failed_batches,
total_batches,
dataset_id,
)
# ============ Step 5: Batch delete DocumentSegment records (multiple short transactions) ============
if segment_ids:
failed_batches = 0
total_batches = (len(segment_ids) + BATCH_SIZE - 1) // BATCH_SIZE
for i in range(0, len(segment_ids), BATCH_SIZE):
batch = segment_ids[i : i + BATCH_SIZE]
try:
with session_factory.create_session() as session:
binding_delete_stmt = delete(SegmentAttachmentBinding).where(
SegmentAttachmentBinding.tenant_id == segments[0].tenant_id,
SegmentAttachmentBinding.dataset_id == dataset_id,
SegmentAttachmentBinding.document_id.in_(document_ids),
SegmentAttachmentBinding.segment_id.in_(batch),
)
session.execute(binding_delete_stmt)
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.id.in_(batch))
session.execute(segment_delete_stmt)
session.commit()
except Exception:
failed_batches += 1
logger.exception(
"Failed to delete DocumentSegment batch %d-%d for dataset_id: %s, document_ids: %s",
i,
i + len(batch),
dataset_id,
document_ids,
)
if failed_batches > 0:
logger.warning(
"DocumentSegment deletion: %d/%d batches failed, document_ids: %s",
failed_batches,
total_batches,
document_ids,
)
# ============ Step 6: Delete document-associated files (separate short transaction) ============
if deletable_file_ids:
try:
with session_factory.create_session() as session:
stmt = delete(UploadFile).where(UploadFile.id.in_(deletable_file_ids))
session.execute(stmt)
session.commit()
except Exception:
logger.exception(
"Failed to delete document UploadFile records for dataset_id: %s, file_ids: %s",
dataset_id,
deletable_file_ids,
)
# ============ Step 7: Delete storage files (I/O operations, no DB transaction) ============
storage_delete_failures = 0
for storage_key in storage_keys_to_delete:
try:
storage.delete(storage_key)
except Exception:
storage_delete_failures += 1
logger.exception("Failed to delete file from storage, key: %s", storage_key)
if storage_delete_failures > 0:
logger.warning(
"Storage file deletion completed with %d failures out of %d total files for dataset_id: %s",
storage_delete_failures,
len(storage_keys_to_delete),
dataset_id,
)
if dataset_tenant_id is not None:
schedule_billing_vector_space_refresh(dataset_tenant_id)
end_at = time.perf_counter()
logger.info(
click.style(
f"Cleaned documents when documents deleted latency: {end_at - start_at:.2f}s, "
f"dataset_id: {dataset_id}, document_ids: {document_ids}, "
f"segments: {len(segment_ids)}, image_files: {len(total_image_upload_file_ids)}, "
f"storage_files: {len(storage_keys_to_delete)}",
fg="green",
)
)
except Exception:
logger.exception(
"Batch clean documents failed for dataset_id: %s, document_ids: %s",
dataset_id,
document_ids,
)
@@ -0,0 +1,215 @@
import logging
import tempfile
import time
import uuid
from pathlib import Path
from typing import Any
import click
import pandas as pd
from celery import shared_task
from sqlalchemy import func, select
from core.credit_usage import CreditUsageCreatedBy
from core.db.session_factory import session_factory
from core.model_context import with_credit_usage_created_by
from core.model_manager import ModelManager
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from extensions.ext_redis import redis_client
from extensions.ext_storage import storage
from graphon.model_runtime.entities.model_entities import ModelType
from libs import helper
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import SegmentStatus
from models.model import UploadFile
from services.knowledge.resource_scope import DatasetRef
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
def batch_create_segment_to_index_task(
job_id: str,
upload_file_id: str,
dataset_id: str,
document_id: str,
tenant_id: str,
user_id: str,
):
"""
Async batch create segment to index
:param job_id:
:param upload_file_id:
:param dataset_id:
:param document_id:
:param tenant_id:
:param user_id:
Usage: batch_create_segment_to_index_task.delay(job_id, upload_file_id, dataset_id, document_id, tenant_id, user_id)
"""
logger.info(click.style(f"Start batch create segment jobId: {job_id}", fg="green"))
start_at = time.perf_counter()
indexing_cache_key = f"segment_batch_import_{job_id}"
# Initialize variables with default values
upload_file_key: str | None = None
dataset_config: dict[str, Any] | None = None
document_config: dict[str, Any] | None = None
with session_factory.create_session() as session:
try:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id, Dataset.tenant_id == tenant_id))
if not dataset:
raise ValueError("Dataset not exist.")
dataset_document = session.scalar(
select(Document).where(
Document.id == document_id, Document.dataset_id == dataset_id, Document.tenant_id == tenant_id
)
)
if not dataset_document:
raise ValueError("Document not exist.")
if (
not dataset_document.enabled
or dataset_document.archived
or dataset_document.indexing_status != "completed"
):
raise ValueError("Document is not available.")
upload_file = session.scalar(
select(UploadFile).where(UploadFile.id == upload_file_id, UploadFile.tenant_id == tenant_id)
)
if not upload_file:
raise ValueError("UploadFile not found.")
dataset_config = {
"id": dataset.id,
"indexing_technique": dataset.indexing_technique,
"tenant_id": dataset.tenant_id,
"embedding_model_provider": dataset.embedding_model_provider,
"embedding_model": dataset.embedding_model,
}
document_config = {
"id": dataset_document.id,
"doc_form": dataset_document.doc_form,
"word_count": dataset_document.word_count or 0,
}
upload_file_key = upload_file.key
except Exception:
logger.exception("Segments batch created index failed")
redis_client.setex(indexing_cache_key, 600, "error")
return
# Ensure required variables are set before proceeding
if upload_file_key is None or dataset_config is None or document_config is None:
logger.error("Required configuration not set due to session error")
redis_client.setex(indexing_cache_key, 600, "error")
return
with tempfile.TemporaryDirectory() as temp_dir:
suffix = Path(upload_file_key).suffix
file_path = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}" # type: ignore
storage.download(upload_file_key, file_path)
df = pd.read_csv(file_path, dtype=str, keep_default_na=False)
content = []
for _, row in df.iterrows():
if document_config["doc_form"] == IndexStructureType.QA_INDEX:
data = {"content": row.iloc[0], "answer": row.iloc[1]}
else:
data = {"content": row.iloc[0]}
content.append(data)
if len(content) == 0:
raise ValueError("The CSV file is empty.")
segment_ids: list[str] = []
embedding_model = None
if dataset_config["indexing_technique"] == IndexTechniqueType.HIGH_QUALITY:
model_manager = ModelManager.for_tenant(tenant_id=dataset_config["tenant_id"])
embedding_model = model_manager.get_model_instance(
tenant_id=dataset_config["tenant_id"],
provider=dataset_config["embedding_model_provider"],
model_type=ModelType.TEXT_EMBEDDING,
model=dataset_config["embedding_model"],
)
word_count_change = 0
if embedding_model:
tokens_list = embedding_model.get_text_embedding_num_tokens(texts=[segment["content"] for segment in content])
else:
tokens_list = [0] * len(content)
with session_factory.create_session() as session, session.begin():
max_position = (
session.scalar(
select(func.max(DocumentSegment.position)).where(
DocumentSegment.tenant_id == tenant_id,
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
)
)
or 0
)
for segment, tokens in zip(content, tokens_list, strict=False):
content = segment["content"]
doc_id = str(uuid.uuid4())
segment_hash = helper.generate_text_hash(content)
max_position += 1
segment_document = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset_id,
document_id=document_id,
index_node_id=doc_id,
index_node_hash=segment_hash,
position=max_position,
content=content,
word_count=len(content),
tokens=tokens,
created_by=user_id,
indexing_at=naive_utc_now(),
status=SegmentStatus.COMPLETED,
completed_at=naive_utc_now(),
)
if document_config["doc_form"] == IndexStructureType.QA_INDEX:
segment_document.answer = segment["answer"]
segment_document.word_count += len(segment["answer"])
word_count_change += segment_document.word_count
session.add(segment_document)
segment_ids.append(segment_document.id)
dataset_document = session.scalar(
select(Document).where(
Document.id == document_id, Document.dataset_id == dataset_id, Document.tenant_id == tenant_id
)
)
if dataset_document is None:
raise ValueError("Document no longer exists.")
dataset_document.word_count = (dataset_document.word_count or 0) + word_count_change
session.add(dataset_document)
# The registry imports this task while assembling the batch dispatcher.
from extensions.ext_application_services import application_services
try:
application_services().knowledge.segments.mutations.index_segments(
DatasetRef(tenant_id, dataset_id).document(document_id), segment_ids=segment_ids
)
except Exception:
redis_client.setex(indexing_cache_key, 600, "error")
raise
redis_client.setex(indexing_cache_key, 600, "completed")
end_at = time.perf_counter()
logger.info(
click.style(
f"Segment batch created job: {job_id} latency: {end_at - start_at}",
fg="green",
)
)
@@ -0,0 +1,276 @@
import logging
import time
from collections.abc import Callable, Sequence
import click
from celery import shared_task
from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.tools.utils.web_reader_tool import get_image_upload_file_ids
from extensions.ext_storage import storage
from models import WorkflowType
from models.dataset import (
AppDatasetJoin,
Dataset,
DatasetMetadata,
DatasetMetadataBinding,
DatasetProcessRule,
DatasetQuery,
Document,
DocumentSegment,
Pipeline,
SegmentAttachmentBinding,
)
from models.model import UploadFile
from models.workflow import Workflow
from services.dataset_knowledge_fs_upgrade_file_lease import reserve_upgrade_file_cleanup
from services.dataset_storage_cleanup_service import cleanup_dataset_crawl_cache
from tasks.refresh_billing_vector_space_task import schedule_billing_vector_space_refresh
logger = logging.getLogger(__name__)
# Keep committed batches on failure, but preserve dependent rows until a retry
# finishes their prerequisite cleanup.
_DELETE_BATCH_SIZE = 1000
_MAX_RETRIES = 3
_RETRY_DELAY_SECONDS = 30
@shared_task(queue="dataset", bind=True, max_retries=_MAX_RETRIES, default_retry_delay=_RETRY_DELAY_SECONDS)
def clean_dataset_task(
self,
dataset_id: str,
tenant_id: str,
indexing_technique: str | None,
index_struct: str | None,
collection_binding_id: str | None,
doc_form: str,
pipeline_id: str | None = None,
*,
index_cleanup_done: bool = False,
) -> None:
"""
Clean dataset when dataset deleted.
:param dataset_id: dataset id
:param tenant_id: tenant id
:param indexing_technique: indexing technique
:param index_struct: index struct dict
:param collection_binding_id: collection binding id
:param doc_form: dataset form
:param index_cleanup_done: preserve successful index cleanup across explicit retries
Usage: clean_dataset_task.delay(dataset_id, tenant_id, indexing_technique, index_struct)
"""
logger.info(click.style(f"Start clean dataset when dataset deleted: {dataset_id}", fg="green"))
start_at = time.perf_counter()
# Enhanced validation: Check if doc_form is None, empty string, or contains only whitespace.
# Treating all invalid values as the default paragraph index type keeps the vector
# database cleanup reachable for empty/broken datasets.
if doc_form is None or (isinstance(doc_form, str) and not doc_form.strip()):
from core.rag.index_processor.constant.index_type import IndexStructureType
doc_form = IndexStructureType.PARAGRAPH_INDEX
logger.info(
click.style(f"Invalid doc_form detected, using default index type for cleanup: {doc_form}", fg="yellow")
)
dataset = Dataset(
id=dataset_id,
tenant_id=tenant_id,
indexing_technique=indexing_technique,
index_struct=index_struct,
collection_binding_id=collection_binding_id,
)
try:
cleanup_dataset_crawl_cache(tenant_id, dataset_id)
with session_factory.create_session() as session:
if not index_cleanup_done:
# Index processors also delete relational child rows, so the whole step must succeed first.
_run_step(session, dataset_id, "dataset index", lambda: _clean_index(session, dataset, doc_form))
index_cleanup_done = True
schedule_billing_vector_space_refresh(dataset.tenant_id)
# Stop on failure so documents and their resources outlive any remaining segments.
_run_step(session, dataset_id, "segments", lambda: _delete_segments(session, dataset_id))
_run_step(session, dataset_id, "documents", lambda: _delete_documents(session, dataset_id))
_run_step(session, dataset_id, "attachments", lambda: _delete_attachments(session, tenant_id, dataset_id))
_run_step(
session,
dataset_id,
"dataset metadata",
lambda: _delete_dataset_scoped_rows(session, tenant_id, dataset_id, pipeline_id),
)
except Exception as exc:
if self.request.retries >= _MAX_RETRIES:
logger.exception("Dataset cleanup retry budget exhausted, dataset_id=%s", dataset_id)
raise
logger.warning(
"Dataset cleanup failed, scheduling retry %d/%d, dataset_id=%s",
self.request.retries + 1,
_MAX_RETRIES,
dataset_id,
exc_info=True,
)
# The session is closed before retrying. Normalize arguments for positional callers too.
raise self.retry(
exc=exc,
args=(),
kwargs={
"dataset_id": dataset_id,
"tenant_id": tenant_id,
"indexing_technique": indexing_technique,
"index_struct": index_struct,
"collection_binding_id": collection_binding_id,
"doc_form": doc_form,
"pipeline_id": pipeline_id,
"index_cleanup_done": index_cleanup_done,
},
countdown=_RETRY_DELAY_SECONDS * (2**self.request.retries),
) from exc
end_at = time.perf_counter()
logger.info(
click.style(
f"Cleaned dataset when dataset deleted: {dataset_id} latency: {end_at - start_at}",
fg="green",
)
)
def _run_step(session: Session, dataset_id: str, name: str, step: Callable[[], None]) -> None:
"""Roll back uncommitted work on failure and stop dependent steps until retry."""
try:
step()
except Exception:
logger.exception(click.style(f"Failed to clean {name} for dataset {dataset_id}", fg="red"))
try:
session.rollback()
except Exception:
logger.exception("Failed to rollback database session")
raise
def _clean_index(session: Session, dataset: Dataset, doc_form: str) -> None:
"""Clean the dataset index and commit any relational rows removed by its processor."""
index_processor = IndexProcessorFactory(doc_form).init_index_processor()
index_processor.clean(dataset, None, with_keywords=True, delete_child_chunks=True, session=session)
session.commit()
logger.info(click.style(f"Successfully cleaned vector database for dataset: {dataset.id}", fg="green"))
def _delete_segments(session: Session, dataset_id: str) -> None:
"""Delete document segments in batches, removing their inline image files first."""
while True:
segments = session.scalars(
select(DocumentSegment).where(DocumentSegment.dataset_id == dataset_id).limit(_DELETE_BATCH_SIZE)
).all()
if not segments:
break
image_upload_file_ids: list[str] = []
for segment in segments:
image_upload_file_ids.extend(get_image_upload_file_ids(segment.content))
_delete_upload_files(session, image_upload_file_ids)
session.execute(delete(DocumentSegment).where(DocumentSegment.id.in_([segment.id for segment in segments])))
session.commit()
def _delete_documents(session: Session, dataset_id: str) -> None:
"""Delete documents in batches, removing their uploaded source files first."""
while True:
documents = session.scalars(
select(Document).where(Document.dataset_id == dataset_id).limit(_DELETE_BATCH_SIZE)
).all()
if not documents:
break
file_ids: list[str] = []
for document in documents:
if document.data_source_type == "upload_file" and document.data_source_info:
data_source_info = document.data_source_info_dict
if data_source_info and "upload_file_id" in data_source_info:
file_ids.append(data_source_info["upload_file_id"])
# Active KnowledgeFS upgrades still read these sources; their leases record the cleanup instead.
leased_file_ids = reserve_upgrade_file_cleanup(session, file_ids)
if leased_file_ids:
logger.info(
"Keep %d source files while KnowledgeFS upgrade leases are active, dataset_id=%s",
len(leased_file_ids),
dataset_id,
)
_delete_upload_files(session, [file_id for file_id in file_ids if file_id not in leased_file_ids])
session.execute(delete(Document).where(Document.id.in_([document.id for document in documents])))
session.commit()
def _delete_upload_files(session: Session, file_ids: Sequence[str]) -> None:
"""Delete blobs before their lookup rows so failures retain storage keys for retry."""
if not file_ids:
return
files = session.scalars(select(UploadFile).where(UploadFile.id.in_(file_ids))).all()
for file in files:
try:
storage.delete(file.key)
except FileNotFoundError:
logger.debug("Upload file already absent from storage, upload_file_id: %s", file.id)
session.execute(delete(UploadFile).where(UploadFile.id.in_(file_ids)))
def _delete_attachments(session: Session, tenant_id: str, dataset_id: str) -> None:
"""Delete segment attachments (upload files + bindings) for the dataset."""
# Inline-image cleanup may already have deleted the file; its binding still needs cleanup.
attachments_with_bindings = session.execute(
select(SegmentAttachmentBinding, UploadFile)
.outerjoin(UploadFile, UploadFile.id == SegmentAttachmentBinding.attachment_id)
.where(
SegmentAttachmentBinding.tenant_id == tenant_id,
SegmentAttachmentBinding.dataset_id == dataset_id,
)
).all()
if not attachments_with_bindings:
return
attachment_ids = [
attachment_file.id for _, attachment_file in attachments_with_bindings if attachment_file is not None
]
binding_ids = [binding.id for binding, _ in attachments_with_bindings]
for binding, attachment_file in attachments_with_bindings:
if attachment_file is None:
continue
try:
storage.delete(attachment_file.key)
except Exception:
logger.exception(
"Delete attachment_file failed when storage deleted, attachment_file_id: %s",
binding.attachment_id,
)
if attachment_ids:
session.execute(delete(UploadFile).where(UploadFile.id.in_(attachment_ids)))
session.execute(delete(SegmentAttachmentBinding).where(SegmentAttachmentBinding.id.in_(binding_ids)))
session.commit()
def _delete_dataset_scoped_rows(session: Session, tenant_id: str, dataset_id: str, pipeline_id: str | None) -> None:
"""Delete the remaining small dataset-scoped tables (and the pipeline/workflow)."""
session.execute(delete(DatasetProcessRule).where(DatasetProcessRule.dataset_id == dataset_id))
session.execute(delete(DatasetQuery).where(DatasetQuery.dataset_id == dataset_id))
session.execute(delete(AppDatasetJoin).where(AppDatasetJoin.dataset_id == dataset_id))
# delete dataset metadata
session.execute(delete(DatasetMetadata).where(DatasetMetadata.dataset_id == dataset_id))
session.execute(delete(DatasetMetadataBinding).where(DatasetMetadataBinding.dataset_id == dataset_id))
# delete pipeline and workflow
if pipeline_id:
session.execute(delete(Pipeline).where(Pipeline.id == pipeline_id))
session.execute(
delete(Workflow).where(
Workflow.tenant_id == tenant_id,
Workflow.app_id == pipeline_id,
Workflow.type == WorkflowType.RAG_PIPELINE,
)
)
session.commit()
@@ -0,0 +1,172 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from core.db.session_factory import session_factory
from core.tools.utils.web_reader_tool import get_image_upload_file_ids
from extensions.ext_storage import storage
from models.dataset import Dataset, DatasetMetadataBinding, DocumentSegment, SegmentAttachmentBinding
from models.model import UploadFile
from services.dataset_knowledge_fs_upgrade_file_lease import reserve_upgrade_file_cleanup
from services.knowledge.indexing.adapters.cleanup import clean_document_indexes
from tasks.refresh_billing_vector_space_task import schedule_billing_vector_space_refresh
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def clean_document_task(
document_id: str,
dataset_id: str,
doc_form: str,
file_id: str | None,
) -> None:
"""
Clean document when document deleted.
:param document_id: document id
:param dataset_id: dataset id
:param doc_form: doc_form
:param file_id: file id
Usage: clean_document_task.delay(document_id, dataset_id)
"""
logger.info(click.style(f"Start clean document when document deleted: {document_id}", fg="green"))
start_at = time.perf_counter()
total_attachment_files = []
vector_cleanup_succeeded = False
with session_factory.create_session() as session:
try:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
raise Exception("Document has no dataset")
dataset_tenant_id = dataset.tenant_id
segments = session.scalars(select(DocumentSegment).where(DocumentSegment.document_id == document_id)).all()
# Use JOIN to fetch attachments with bindings in a single query
attachments_with_bindings = session.execute(
select(SegmentAttachmentBinding, UploadFile)
.join(UploadFile, UploadFile.id == SegmentAttachmentBinding.attachment_id)
.where(
SegmentAttachmentBinding.tenant_id == dataset.tenant_id,
SegmentAttachmentBinding.dataset_id == dataset_id,
SegmentAttachmentBinding.document_id == document_id,
)
).all()
attachment_ids = [attachment_file.id for _, attachment_file in attachments_with_bindings]
binding_ids = [binding.id for binding, _ in attachments_with_bindings]
total_attachment_files.extend([attachment_file.key for _, attachment_file in attachments_with_bindings])
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
segment_contents = [segment.content for segment in segments]
except Exception:
logger.exception("Cleaned document when document deleted failed")
return
# A retry must also find summaries whose segments were already removed.
# Preserve relational cleanup if the external index is temporarily unavailable.
try:
vector_cleanup_succeeded = (
clean_document_indexes(
dataset_id=dataset_id,
document_ids=[document_id],
doc_form=doc_form,
new_session=session_factory.create_session,
)
is not None
)
except Exception:
logger.exception(
"Failed to clean vector / keyword index in clean_document_task, "
"document_id=%s, dataset_id=%s, index_node_ids_count=%d. "
"Continuing with PG / storage cleanup; vector orphans can be reaped later.",
document_id,
dataset_id,
len(index_node_ids),
)
total_image_files = []
with session_factory.create_session() as session, session.begin():
for segment_content in segment_contents:
image_upload_file_ids = get_image_upload_file_ids(segment_content)
image_files = session.scalars(select(UploadFile).where(UploadFile.id.in_(image_upload_file_ids))).all()
total_image_files.extend([image_file.key for image_file in image_files])
image_file_delete_stmt = delete(UploadFile).where(UploadFile.id.in_(image_upload_file_ids))
session.execute(image_file_delete_stmt)
with session_factory.create_session() as session, session.begin():
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.document_id == document_id)
session.execute(segment_delete_stmt)
for image_file_key in total_image_files:
try:
storage.delete(image_file_key)
except Exception:
logger.exception(
"Delete image_files failed when storage deleted, \
image_upload_file_is: %s",
image_file_key,
)
with session_factory.create_session() as session, session.begin():
if file_id:
if file_id in reserve_upgrade_file_cleanup(session, [file_id]):
logger.info(
"Keep source file while KnowledgeFS upgrade lease is active, file_id=%s, document_id=%s",
file_id,
document_id,
)
file_id = None
if file_id:
file = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1))
if file:
try:
storage.delete(file.key)
except Exception:
logger.exception("Delete file failed when document deleted, file_id: %s", file_id)
session.delete(file)
with session_factory.create_session() as session, session.begin():
# delete segment attachments
if attachment_ids:
attachment_file_delete_stmt = delete(UploadFile).where(UploadFile.id.in_(attachment_ids))
session.execute(attachment_file_delete_stmt)
if binding_ids:
binding_delete_stmt = delete(SegmentAttachmentBinding).where(SegmentAttachmentBinding.id.in_(binding_ids))
session.execute(binding_delete_stmt)
for attachment_file_key in total_attachment_files:
try:
storage.delete(attachment_file_key)
except Exception:
logger.exception(
"Delete attachment_file failed when storage deleted, \
attachment_file_id: %s",
attachment_file_key,
)
with session_factory.create_session() as session, session.begin():
# delete dataset metadata binding
session.execute(
delete(DatasetMetadataBinding).where(
DatasetMetadataBinding.dataset_id == dataset_id,
DatasetMetadataBinding.document_id == document_id,
)
)
if vector_cleanup_succeeded:
schedule_billing_vector_space_refresh(dataset_tenant_id)
end_at = time.perf_counter()
logger.info(
click.style(
f"Cleaned document when document deleted: {document_id} latency: {end_at - start_at}",
fg="green",
)
)
@@ -0,0 +1,77 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from core.db.session_factory import session_factory
from models.dataset import Dataset, Document, DocumentSegment
from repositories.knowledge.dataset_read_repository import get_dataset_doc_form
from services.knowledge.indexing.adapters.cleanup import clean_document_indexes
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def clean_notion_document_task(document_ids: list[str], dataset_id: str):
"""
Clean document when document deleted.
:param document_ids: document ids
:param dataset_id: dataset id
Usage: clean_notion_document_task.delay(document_ids, dataset_id)
"""
logger.info(click.style(f"Start clean document when import form notion document deleted: {dataset_id}", fg="green"))
start_at = time.perf_counter()
total_index_node_ids = []
with session_factory.create_session() as session, session.begin():
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
raise Exception("Document has no dataset")
index_type = get_dataset_doc_form(dataset, session=session)
document_delete_stmt = delete(Document).where(Document.id.in_(document_ids))
session.execute(document_delete_stmt)
for document_id in document_ids:
segments = session.scalars(select(DocumentSegment).where(DocumentSegment.document_id == document_id)).all()
total_index_node_ids.extend([segment.index_node_id for segment in segments if segment.index_node_id])
# Wrap vector / keyword index cleanup in try/except so that a transient
# failure here (e.g. billing API hiccup propagated via FeatureService when
# ``ModelManager`` is initialized inside ``Vector(dataset)``) does not abort
# the task and leave the already-deleted documents' segments stranded in PG.
# The Document rows are hard-deleted in the previous session block, so any
# exception escaping this task would produce orphans that no later request
# can reference back. Mirrors the pattern in ``clean_dataset_task``.
try:
clean_document_indexes(
dataset_id=dataset_id,
document_ids=document_ids,
doc_form=index_type,
new_session=session_factory.create_session,
)
except Exception:
logger.exception(
"Failed to clean vector / keyword index in clean_notion_document_task, "
"dataset_id=%s, document_ids=%s, index_node_ids_count=%d. "
"Continuing with segment deletion; vector orphans can be reaped later.",
dataset_id,
document_ids,
len(total_index_node_ids),
)
with session_factory.create_session() as session, session.begin():
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.document_id.in_(document_ids))
session.execute(segment_delete_stmt)
end_at = time.perf_counter()
logger.info(
click.style(
f"Clean document when import form notion document deleted end :: {dataset_id} latency: {end_at - start_at}",
fg="green",
)
)
@@ -0,0 +1,102 @@
"""Collect retired Agent data under a two-phase task contract.
Phase one attempts every explicitly identified RETIRED working resource. Phase
two purges the requested archived Agent aggregates only after the whole first
phase succeeds. Any collection failure skips aggregate purge and is included in
the error raised after all explicit resources have been attempted.
"""
from __future__ import annotations
import logging
from collections.abc import Iterable
from celery import shared_task
from services.agent.deletion_service import AgentDeletionService
from services.agent.home_snapshot_service import AgentHomeSnapshotService
from services.agent.workspace_service import AgentWorkspaceService
logger = logging.getLogger(__name__)
@shared_task(queue="retention")
def collect_agent_resources(
*,
tenant_id: str,
binding_ids: list[str],
workspace_ids: list[str],
home_snapshot_ids: list[str],
purge_agent_ids: list[str] | None = None,
) -> None:
"""Collect the explicit RETIRED batch, then purge Agents only on full success.
Collection is best-effort across the complete explicit batch so one failed
resource does not hide later failures. If any resource fails, aggregate
purge is skipped and one summary error is raised after all attempts.
"""
collectors = (
(workspace_ids, "workspace_id", AgentWorkspaceService.collect_retired_workspace),
(binding_ids, "binding_id", AgentWorkspaceService.collect_retired_binding),
(
home_snapshot_ids,
"home_snapshot_id",
AgentHomeSnapshotService.collect_retired_home_snapshot,
),
)
failures: list[str] = []
first_error: Exception | None = None
for resource_ids, argument_name, collector in collectors:
for resource_id in resource_ids:
try:
collector(tenant_id=tenant_id, **{argument_name: resource_id})
except Exception as exc:
resource_type = argument_name.removesuffix("_id")
failures.append(f"{resource_type}:{resource_id}")
if first_error is None:
first_error = exc
logger.exception(
"Failed to collect retired Agent resource",
extra={
"tenant_id": tenant_id,
"resource_type": resource_type,
"resource_id": resource_id,
},
)
if failures:
raise RuntimeError(
f"Failed to collect {len(failures)} retired Agent resource(s): {', '.join(failures)}"
) from first_error
AgentDeletionService.purge_archived_agents(tenant_id=tenant_id, agent_ids=purge_agent_ids or ())
def enqueue_agent_resource_collection(
*,
tenant_id: str,
binding_ids: Iterable[str] = (),
workspace_ids: Iterable[str] = (),
home_snapshot_ids: Iterable[str] = (),
purge_agent_ids: Iterable[str] = (),
) -> None:
"""Enqueue physical collection after retirement has committed."""
payload = {
"binding_ids": sorted({resource_id for resource_id in binding_ids if resource_id}),
"workspace_ids": sorted({resource_id for resource_id in workspace_ids if resource_id}),
"home_snapshot_ids": sorted({resource_id for resource_id in home_snapshot_ids if resource_id}),
"purge_agent_ids": sorted({agent_id for agent_id in purge_agent_ids if agent_id}),
}
if not any(payload.values()):
return
try:
collect_agent_resources.delay(tenant_id=tenant_id, **payload)
except Exception:
logger.exception(
"Failed to enqueue retired Agent resource collection",
extra={"tenant_id": tenant_id, **payload},
)
raise
__all__ = ["collect_agent_resources", "enqueue_agent_resource_collection"]
@@ -0,0 +1,19 @@
import logging
from celery import shared_task
from sqlalchemy.orm import sessionmaker
from extensions.ext_database import db
from services.telemetry_service import CommunityTelemetryService
logger = logging.getLogger(__name__)
@shared_task(name="community_telemetry.send_heartbeat", queue="schedule_executor")
def send_community_telemetry_heartbeat() -> None:
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
with session_factory() as session:
try:
CommunityTelemetryService.report_heartbeat(session=session)
except Exception:
logger.debug("Failed to process community telemetry heartbeat", exc_info=True)
@@ -0,0 +1,106 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import Document
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import DocumentSegment
from models.enums import IndexingStatus, SegmentStatus
from repositories.knowledge.dataset_read_repository import (
get_dataset_doc_form,
get_segment_dataset,
get_segment_document,
)
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def create_segment_to_index_task(segment_id: str, keywords: list[str] | None = None):
"""
Async create segment to index
:param segment_id:
:param keywords:
Usage: create_segment_to_index_task.delay(segment_id)
"""
logger.info(click.style(f"Start create segment to index: {segment_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
segment = session.scalar(select(DocumentSegment).where(DocumentSegment.id == segment_id).limit(1))
if not segment:
logger.info(click.style(f"Segment not found: {segment_id}", fg="red"))
return
if segment.status != SegmentStatus.WAITING:
return
indexing_cache_key = f"segment_{segment.id}_indexing"
try:
# update segment status to indexing
session.execute(
update(DocumentSegment)
.where(DocumentSegment.id == segment.id)
.values(status=SegmentStatus.INDEXING, indexing_at=naive_utc_now())
)
session.commit()
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
dataset = get_segment_dataset(segment, session=session)
if not dataset:
logger.info(click.style(f"Segment {segment.id} has no dataset, pass.", fg="cyan"))
return
dataset_document = get_segment_document(segment, session=session)
if not dataset_document:
logger.info(click.style(f"Segment {segment.id} has no document, pass.", fg="cyan"))
return
if (
not dataset_document.enabled
or dataset_document.archived
or dataset_document.indexing_status != IndexingStatus.COMPLETED
):
logger.info(click.style(f"Segment {segment.id} document status is invalid, pass.", fg="cyan"))
return
index_type = get_dataset_doc_form(dataset, session=session)
index_processor = IndexProcessorFactory(index_type).init_index_processor()
index_processor.load(dataset, [document], session=session)
# update segment to completed
session.execute(
update(DocumentSegment)
.where(DocumentSegment.id == segment.id)
.values(status=SegmentStatus.COMPLETED, completed_at=naive_utc_now())
)
session.commit()
end_at = time.perf_counter()
logger.info(click.style(f"Segment created to index: {segment.id} latency: {end_at - start_at}", fg="green"))
except Exception as e:
logger.exception("create segment to index failed")
segment.enabled = False
segment.disabled_at = naive_utc_now()
segment.status = SegmentStatus.ERROR
segment.error = str(e)
session.commit()
finally:
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,220 @@
import logging
import time
import click
from celery import shared_task # type: ignore
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.doc_type import DocType
from core.rag.index_processor.constant.index_type import IndexStructureType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from models.dataset import Dataset, DocumentSegment
from models.dataset import Document as DatasetDocument
from repositories.knowledge.dataset_read_repository import get_dataset_doc_form, get_segment_child_chunks
from repositories.knowledge.segment_read_adapter import get_segment_attachments
@shared_task(queue="dataset")
def deal_dataset_index_update_task(dataset_id: str, action: str):
"""
Async deal dataset from index
:param dataset_id: dataset_id
:param action: action
Usage: deal_dataset_index_update_task.delay(dataset_id, action)
"""
logging.info(click.style(f"Start deal dataset index update: {dataset_id}", fg="green"))
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 not dataset:
raise Exception("Dataset not found")
index_type = get_dataset_doc_form(dataset, session=session) or IndexStructureType.PARAGRAPH_INDEX
index_processor = IndexProcessorFactory(index_type).init_index_processor()
if action == "upgrade":
dataset_documents = session.scalars(
select(DatasetDocument).where(
DatasetDocument.dataset_id == dataset_id,
DatasetDocument.indexing_status == "completed",
DatasetDocument.enabled.is_(True),
DatasetDocument.archived.is_(False),
)
).all()
if dataset_documents:
dataset_documents_ids = [doc.id for doc in dataset_documents]
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id.in_(dataset_documents_ids))
.values({DatasetDocument.indexing_status: "indexing"})
)
session.commit()
for dataset_document in dataset_documents:
try:
# add from vector index
segments = session.scalars(
select(DocumentSegment)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.enabled.is_(True),
)
.order_by(DocumentSegment.position.asc())
).all()
if segments:
documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
documents.append(document)
# save vector index
# clean keywords
index_processor.clean(
dataset,
None,
with_keywords=True,
delete_child_chunks=False,
session=session,
)
index_processor.load(dataset, documents, with_keywords=False, session=session)
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "completed"})
)
session.commit()
except Exception as e:
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "error", DatasetDocument.error: str(e)})
)
session.commit()
elif action == "update":
dataset_documents = session.scalars(
select(DatasetDocument).where(
DatasetDocument.dataset_id == dataset_id,
DatasetDocument.indexing_status == "completed",
DatasetDocument.enabled.is_(True),
DatasetDocument.archived.is_(False),
)
).all()
# add new index
if dataset_documents:
# update document status
dataset_documents_ids = [doc.id for doc in dataset_documents]
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id.in_(dataset_documents_ids))
.values({DatasetDocument.indexing_status: "indexing"})
)
session.commit()
# clean index
index_processor.clean(
dataset, None, with_keywords=False, delete_child_chunks=False, session=session
)
for dataset_document in dataset_documents:
# update from vector index
try:
segments = session.scalars(
select(DocumentSegment)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.enabled.is_(True),
)
.order_by(DocumentSegment.position.asc())
).all()
if segments:
documents = []
multimodal_documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
if dataset_document.doc_form == IndexStructureType.PARENT_CHILD_INDEX:
child_chunks = get_segment_child_chunks(segment, session=session)
if child_chunks:
child_documents = []
for child_chunk in child_chunks:
child_document = ChildDocument(
page_content=child_chunk.content,
metadata={
"doc_id": child_chunk.index_node_id,
"doc_hash": child_chunk.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
child_documents.append(child_document)
document.children = child_documents
if dataset.is_multimodal:
for attachment in get_segment_attachments(segment, session=session):
multimodal_documents.append(
AttachmentDocument(
page_content=attachment["name"],
metadata={
"doc_id": attachment["id"],
"doc_hash": "",
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
"doc_type": DocType.IMAGE,
},
)
)
documents.append(document)
# save vector index
index_processor.load(
dataset,
documents,
multimodal_documents=multimodal_documents,
with_keywords=False,
session=session,
)
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "completed"})
)
session.commit()
except Exception as e:
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "error", DatasetDocument.error: str(e)})
)
session.commit()
else:
# clean collection
index_processor.clean(
dataset, None, with_keywords=False, delete_child_chunks=False, session=session
)
end_at = time.perf_counter()
logging.info(
click.style(
f"Deal dataset vector index: {dataset_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logging.exception("Deal dataset vector index failed")
@@ -0,0 +1,216 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.doc_type import DocType
from core.rag.index_processor.constant.index_type import IndexStructureType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from models.dataset import Dataset, DocumentSegment
from models.dataset import Document as DatasetDocument
from repositories.knowledge.dataset_read_repository import get_dataset_doc_form, get_segment_child_chunks
from repositories.knowledge.segment_read_adapter import get_segment_attachments
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def deal_dataset_vector_index_task(dataset_id: str, action: str):
"""
Async deal dataset from index
:param dataset_id: dataset_id
:param action: action
Usage: deal_dataset_vector_index_task.delay(dataset_id, action)
"""
logger.info(click.style(f"Start deal dataset vector index: {dataset_id}", fg="green"))
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 not dataset:
raise Exception("Dataset not found")
index_type = get_dataset_doc_form(dataset, session=session) or IndexStructureType.PARAGRAPH_INDEX
index_processor = IndexProcessorFactory(index_type).init_index_processor()
if action == "remove":
index_processor.clean(dataset, None, with_keywords=False, session=session)
elif action == "add":
dataset_documents = session.scalars(
select(DatasetDocument).where(
DatasetDocument.dataset_id == dataset_id,
DatasetDocument.indexing_status == "completed",
DatasetDocument.enabled.is_(True),
DatasetDocument.archived.is_(False),
)
).all()
if dataset_documents:
dataset_documents_ids = [doc.id for doc in dataset_documents]
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id.in_(dataset_documents_ids))
.values({DatasetDocument.indexing_status: "indexing"})
)
session.commit()
for dataset_document in dataset_documents:
try:
# add from vector index
segments = session.scalars(
select(DocumentSegment)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.enabled.is_(True),
)
.order_by(DocumentSegment.position.asc())
).all()
if segments:
documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
documents.append(document)
# save vector index
index_processor.load(dataset, documents, with_keywords=False, session=session)
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "completed"})
)
session.commit()
except Exception as e:
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "error", DatasetDocument.error: str(e)})
)
session.commit()
elif action == "update":
dataset_documents = session.scalars(
select(DatasetDocument).where(
DatasetDocument.dataset_id == dataset_id,
DatasetDocument.indexing_status == "completed",
DatasetDocument.enabled.is_(True),
DatasetDocument.archived.is_(False),
)
).all()
# add new index
if dataset_documents:
# update document status
dataset_documents_ids = [doc.id for doc in dataset_documents]
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id.in_(dataset_documents_ids))
.values({DatasetDocument.indexing_status: "indexing"})
)
session.commit()
# clean index
index_processor.clean(
dataset, None, with_keywords=False, delete_child_chunks=False, session=session
)
for dataset_document in dataset_documents:
# update from vector index
try:
segments = session.scalars(
select(DocumentSegment)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.enabled.is_(True),
)
.order_by(DocumentSegment.position.asc())
).all()
if segments:
documents = []
multimodal_documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
if dataset_document.doc_form == IndexStructureType.PARENT_CHILD_INDEX:
child_chunks = get_segment_child_chunks(segment, session=session)
if child_chunks:
child_documents = []
for child_chunk in child_chunks:
child_document = ChildDocument(
page_content=child_chunk.content,
metadata={
"doc_id": child_chunk.index_node_id,
"doc_hash": child_chunk.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
child_documents.append(child_document)
document.children = child_documents
if dataset.is_multimodal:
for attachment in get_segment_attachments(segment, session=session):
multimodal_documents.append(
AttachmentDocument(
page_content=attachment["name"],
metadata={
"doc_id": attachment["id"],
"doc_hash": "",
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
"doc_type": DocType.IMAGE,
},
)
)
documents.append(document)
# save vector index
index_processor.load(
dataset,
documents,
multimodal_documents=multimodal_documents,
with_keywords=False,
session=session,
)
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "completed"})
)
session.commit()
except Exception as e:
session.execute(
update(DatasetDocument)
.where(DatasetDocument.id == dataset_document.id)
.values({DatasetDocument.indexing_status: "error", DatasetDocument.error: str(e)})
)
session.commit()
else:
# clean collection
index_processor.clean(
dataset, None, with_keywords=False, delete_child_chunks=False, session=session
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Deal dataset vector index: {dataset_id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("Deal dataset vector index failed")
@@ -0,0 +1,31 @@
import logging
from celery import shared_task
from sqlalchemy import select
from configs import dify_config
from core.db.session_factory import session_factory
from enums import DeploymentEdition
from models import Account
from services.billing_service import BillingService
from tasks.mail_account_deletion_task import send_deletion_success_task
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def delete_account_task(account_id):
with session_factory.create_session() as session:
account = session.scalar(select(Account).where(Account.id == account_id).limit(1))
try:
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
BillingService.delete_account(account_id)
except Exception:
logger.exception("Failed to delete account %s from billing service.", account_id)
raise
if not account:
logger.error("Account %s not found.", account_id)
return
# send success email
send_deletion_success_task.delay(account.email)
@@ -0,0 +1,158 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from configs import dify_config
from core.db.session_factory import session_factory
from extensions.ext_storage import storage
from models import (
AgentDebugConversation,
Conversation,
ConversationVariable,
HumanInputForm,
HumanInputFormUploadFile,
HumanInputFormUploadToken,
Message,
MessageAgentThought,
MessageAnnotation,
MessageChain,
MessageFeedback,
MessageFile,
PinnedConversation,
SavedMessage,
)
from models.human_input import HumanInputDelivery, HumanInputFormRecipient
from models.tools import ToolConversationVariables, ToolFile
logger = logging.getLogger(__name__)
_MAX_RETRIES = 5
_RETRY_DELAY_SECONDS = 30
def _delete_storage_object(file_key: str) -> None:
try:
storage.delete(file_key)
except Exception:
# A prior attempt may have deleted the object before its DB transaction
# rolled back. Only suppress the retry when the backend confirms absence.
if storage.exists(file_key):
raise
logger.info("Storage object %s was already absent", file_key)
def _cleanup_conversation_related_data(conversation_id: str) -> bool:
"""Physically remove a soft-deleted conversation and its owned resources.
The storage object is deleted before its ``ToolFile`` row so a failed attempt
retains the durable ``file_key`` needed by the next retry.
"""
with session_factory.create_session() as session:
conversation = session.scalar(select(Conversation).where(Conversation.id == conversation_id).with_for_update())
if conversation is not None and not conversation.is_deleted:
logger.warning("Skipped cleanup for active conversation %s", conversation_id)
return False
tool_files = list(
session.scalars(
select(ToolFile)
.where(ToolFile.conversation_id == conversation_id)
.order_by(ToolFile.id)
.with_for_update()
)
)
for tool_file in tool_files:
_delete_storage_object(tool_file.file_key)
session.delete(tool_file)
message_ids = select(Message.id).where(Message.conversation_id == conversation_id)
session.execute(delete(MessageAgentThought).where(MessageAgentThought.message_id.in_(message_ids)))
session.execute(delete(MessageChain).where(MessageChain.message_id.in_(message_ids)))
session.execute(delete(MessageFile).where(MessageFile.message_id.in_(message_ids)))
session.execute(delete(SavedMessage).where(SavedMessage.message_id.in_(message_ids)))
session.execute(delete(MessageAnnotation).where(MessageAnnotation.conversation_id == conversation_id))
session.execute(delete(MessageFeedback).where(MessageFeedback.conversation_id == conversation_id))
session.execute(
delete(ToolConversationVariables).where(ToolConversationVariables.conversation_id == conversation_id)
)
session.execute(delete(ConversationVariable).where(ConversationVariable.conversation_id == conversation_id))
form_ids = select(HumanInputForm.id).where(HumanInputForm.conversation_id == conversation_id)
session.execute(delete(HumanInputFormUploadFile).where(HumanInputFormUploadFile.form_id.in_(form_ids)))
session.execute(delete(HumanInputFormUploadToken).where(HumanInputFormUploadToken.form_id.in_(form_ids)))
session.execute(delete(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id.in_(form_ids)))
session.execute(delete(HumanInputDelivery).where(HumanInputDelivery.form_id.in_(form_ids)))
session.execute(delete(HumanInputForm).where(HumanInputForm.conversation_id == conversation_id))
session.execute(delete(Message).where(Message.conversation_id == conversation_id))
session.execute(delete(PinnedConversation).where(PinnedConversation.conversation_id == conversation_id))
session.execute(delete(AgentDebugConversation).where(AgentDebugConversation.conversation_id == conversation_id))
session.execute(
delete(Conversation).where(
Conversation.id == conversation_id,
Conversation.is_deleted.is_(True),
)
)
session.commit()
return True
@shared_task(queue="conversation", bind=True, max_retries=_MAX_RETRIES, default_retry_delay=_RETRY_DELAY_SECONDS)
def delete_conversation_related_data(self, conversation_id: str) -> None:
"""
Delete related data conversation in correct order from database to respect foreign key constraints
Args:
conversation_id: conversation Id
"""
logger.info(
click.style(f"Starting to delete conversation data from db for conversation_id {conversation_id}", fg="green")
)
start_at = time.perf_counter()
try:
cleaned = _cleanup_conversation_related_data(conversation_id)
except Exception as exc:
logger.exception("Failed to delete data for conversation_id: %s", conversation_id)
countdown = min(_RETRY_DELAY_SECONDS * (2**self.request.retries), 10 * 60)
raise self.retry(exc=exc, countdown=countdown) from exc
end_at = time.perf_counter()
logger.info(
click.style(
(
f"Finished cleaning data for conversation_id {conversation_id}, "
f"cleaned={cleaned}, latency: {end_at - start_at}"
),
fg="green",
)
)
@shared_task(queue="conversation")
def sweep_deleted_conversations() -> int:
"""Re-enqueue soft-deleted conversations whose immediate dispatch was lost."""
with session_factory.create_session() as session:
conversation_ids = list(
session.scalars(
select(Conversation.id)
.where(Conversation.is_deleted.is_(True))
.order_by(Conversation.updated_at, Conversation.id)
.limit(dify_config.CONVERSATION_CLEANUP_BATCH_SIZE)
)
)
dispatched = 0
for conversation_id in conversation_ids:
try:
delete_conversation_related_data.delay(conversation_id)
dispatched += 1
except Exception:
logger.exception("Failed to dispatch cleanup for conversation %s", conversation_id)
return dispatched
@@ -0,0 +1,138 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.ext_storage import storage
from models.dataset import Dataset, Document, SegmentAttachmentBinding
from models.model import UploadFile
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def delete_segment_from_index_task(
index_node_ids: list, dataset_id: str, document_id: str, segment_ids: list, child_node_ids: list | None = None
):
"""
Async Remove segment from index
:param index_node_ids:
:param dataset_id:
:param document_id:
Usage: delete_segment_from_index_task.delay(index_node_ids, dataset_id, document_id)
"""
logger.info(click.style("Start delete segment from index", fg="green"))
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 not dataset:
logging.warning("Dataset %s not found, skipping index cleanup", dataset_id)
return
dataset_document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if not dataset_document:
return
if (
not dataset_document.enabled
or dataset_document.archived
or dataset_document.indexing_status != "completed"
):
logging.info("Document not in valid state for index operations, skipping")
return
doc_form = dataset_document.doc_form
# Proceed with index cleanup using the index_node_ids directly
# For actual deletion, we should delete summaries (not just disable them)
index_processor = IndexProcessorFactory(doc_form).init_index_processor()
index_processor.clean(
dataset,
index_node_ids,
with_keywords=True,
delete_child_chunks=True,
precomputed_child_node_ids=child_node_ids,
delete_summaries=True, # Actually delete summaries when segment is deleted,
session=session,
)
session.commit()
if dataset.is_multimodal:
# delete segment attachment binding
segment_attachment_bindings = session.scalars(
select(SegmentAttachmentBinding).where(
SegmentAttachmentBinding.tenant_id == dataset.tenant_id,
SegmentAttachmentBinding.dataset_id == dataset.id,
SegmentAttachmentBinding.document_id == document_id,
SegmentAttachmentBinding.segment_id.in_(segment_ids),
)
).all()
if segment_attachment_bindings:
segment_attachment_bind_ids = [i.id for i in segment_attachment_bindings]
attachment_ids = list(
dict.fromkeys(binding.attachment_id for binding in segment_attachment_bindings)
)
for i in range(0, len(segment_attachment_bind_ids), 1000):
segment_attachment_bind_delete_stmt = delete(SegmentAttachmentBinding).where(
SegmentAttachmentBinding.tenant_id == dataset.tenant_id,
SegmentAttachmentBinding.dataset_id == dataset.id,
SegmentAttachmentBinding.document_id == document_id,
SegmentAttachmentBinding.id.in_(segment_attachment_bind_ids[i : i + 1000]),
)
session.execute(segment_attachment_bind_delete_stmt)
session.flush()
remaining_attachment_ids = set(
session.scalars(
select(SegmentAttachmentBinding.attachment_id).where(
SegmentAttachmentBinding.attachment_id.in_(attachment_ids)
)
).all()
)
orphan_attachment_ids = [
attachment_id
for attachment_id in attachment_ids
if attachment_id not in remaining_attachment_ids
]
if orphan_attachment_ids:
attachment_storage_keys = list(
dict.fromkeys(
session.scalars(
select(UploadFile.key).where(
UploadFile.tenant_id == dataset.tenant_id,
UploadFile.id.in_(orphan_attachment_ids),
)
).all()
)
)
index_processor.clean(
session=session, dataset=dataset, node_ids=orphan_attachment_ids, with_keywords=False
)
session.execute(
delete(UploadFile).where(
UploadFile.tenant_id == dataset.tenant_id,
UploadFile.id.in_(orphan_attachment_ids),
)
)
else:
attachment_storage_keys = []
session.commit()
for storage_key in attachment_storage_keys:
try:
storage.delete(storage_key)
except Exception:
logger.exception("Failed to delete segment attachment from storage, key: %s", storage_key)
end_at = time.perf_counter()
logger.info(click.style(f"Segment deleted from index latency: {end_at - start_at}", fg="green"))
except Exception:
session.rollback()
logger.exception("delete segment from index failed")
@@ -0,0 +1,93 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.ext_redis import redis_client
from models.dataset import DocumentSegment
from models.enums import SegmentStatus
from repositories.knowledge.dataset_read_repository import get_segment_dataset, get_segment_document
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def disable_segment_from_index_task(segment_id: str):
"""
Async disable segment from index
:param segment_id:
Usage: disable_segment_from_index_task.delay(segment_id)
"""
logger.info(click.style(f"Start disable segment from index: {segment_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
segment = session.scalar(select(DocumentSegment).where(DocumentSegment.id == segment_id).limit(1))
if not segment:
logger.info(click.style(f"Segment not found: {segment_id}", fg="red"))
return
if segment.status != SegmentStatus.COMPLETED:
logger.info(click.style(f"Segment is not completed, disable is not allowed: {segment_id}", fg="red"))
return
indexing_cache_key = f"segment_{segment.id}_indexing"
try:
dataset = get_segment_dataset(segment, session=session)
if not dataset:
logger.info(click.style(f"Segment {segment.id} has no dataset, pass.", fg="cyan"))
return
dataset_document = get_segment_document(segment, session=session)
if not dataset_document:
logger.info(click.style(f"Segment {segment.id} has no document, pass.", fg="cyan"))
return
if (
not dataset_document.enabled
or dataset_document.archived
or dataset_document.indexing_status != "completed"
):
logger.info(click.style(f"Segment {segment.id} document status is invalid, pass.", fg="cyan"))
return
index_type = dataset_document.doc_form
index_processor = IndexProcessorFactory(index_type).init_index_processor()
assert segment.index_node_id
index_processor.clean(dataset, [segment.index_node_id], session=session)
session.commit()
# Disable summary index for this segment
from services.knowledge.summaries.adapters import SummaryIndexAdapter
try:
SummaryIndexAdapter.disable_summaries_for_segments(
dataset=dataset,
segment_ids=[segment.id],
disabled_by=segment.disabled_by,
)
except Exception:
logger.warning("Failed to disable summary for segment %s", segment.id, exc_info=True)
end_at = time.perf_counter()
logger.info(
click.style(
f"Segment removed from index: {segment.id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("remove segment from index failed")
session.rollback()
segment.enabled = True
session.commit()
finally:
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,105 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.ext_redis import redis_client
from models.dataset import Dataset, DocumentSegment, SegmentAttachmentBinding
from models.dataset import Document as DatasetDocument
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def disable_segments_from_index_task(segment_ids: list, dataset_id: str, document_id: str):
"""
Async disable segments from index
:param segment_ids: list of segment ids
:param dataset_id: dataset id
:param document_id: document id
Usage: disable_segments_from_index_task.delay(segment_ids, dataset_id, document_id)
"""
start_at = time.perf_counter()
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.info(click.style(f"Dataset {dataset_id} not found, pass.", fg="cyan"))
return
dataset_document = session.scalar(select(DatasetDocument).where(DatasetDocument.id == document_id).limit(1))
if not dataset_document:
logger.info(click.style(f"Document {document_id} not found, pass.", fg="cyan"))
return
if not dataset_document.enabled or dataset_document.archived or dataset_document.indexing_status != "completed":
logger.info(click.style(f"Document {document_id} status is invalid, pass.", fg="cyan"))
return
# sync index processor
index_processor = IndexProcessorFactory(dataset_document.doc_form).init_index_processor()
segments = session.scalars(
select(DocumentSegment).where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
)
).all()
if not segments:
return
try:
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
if dataset.is_multimodal:
segment_ids = [segment.id for segment in segments]
segment_attachment_bindings = session.scalars(
select(SegmentAttachmentBinding).where(SegmentAttachmentBinding.segment_id.in_(segment_ids))
).all()
if segment_attachment_bindings:
attachment_ids = [binding.attachment_id for binding in segment_attachment_bindings]
index_node_ids.extend(attachment_ids)
index_processor.clean(
dataset, index_node_ids, with_keywords=True, delete_child_chunks=False, session=session
)
session.commit()
# Disable summary indexes for these segments
from services.knowledge.summaries.adapters import SummaryIndexAdapter
segment_ids_list = [segment.id for segment in segments]
try:
# Get disabled_by from first segment (they should all have the same disabled_by)
disabled_by = segments[0].disabled_by if segments else None
SummaryIndexAdapter.disable_summaries_for_segments(
dataset=dataset,
segment_ids=segment_ids_list,
disabled_by=disabled_by,
)
except Exception:
logger.warning("Failed to disable summaries for segments", exc_info=True)
end_at = time.perf_counter()
logger.info(click.style(f"Segments removed from index latency: {end_at - start_at}", fg="green"))
except Exception:
# update segment error msg
session.rollback()
session.execute(
update(DocumentSegment)
.where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
)
.values(disabled_at=None, disabled_by=None, enabled=True)
)
session.commit()
finally:
for segment in segments:
indexing_cache_key = f"segment_{segment.id}_indexing"
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,178 @@
import json
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from core.db.session_factory import get_session_maker, session_factory
from core.rag.extractor.notion_extractor import NotionExtractor
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.application_services.data_sources import build_data_source_credentials
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import IndexingStatus
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.indexing.errors import DocumentIsPausedError
from services.knowledge.resource_scope import DatasetRef
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def document_indexing_sync_task(dataset_id: str, document_id: str):
"""
Async update document
:param dataset_id:
:param document_id:
Usage: document_indexing_sync_task.delay(dataset_id, document_id)
"""
logger.info(click.style(f"Start sync document: {document_id}", fg="green"))
start_at = time.perf_counter()
tenant_id = None
with session_factory.create_session() as session, session.begin():
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="red"))
return
if document.indexing_status == IndexingStatus.PARSING:
logger.info(click.style(f"Document {document_id} is already being processed, skipping", fg="yellow"))
return
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
raise Exception("Dataset not found")
data_source_info = document.data_source_info_dict
if document.data_source_type != "notion_import":
logger.info(click.style(f"Document {document_id} is not a notion_import, skipping", fg="yellow"))
return
if (
not data_source_info
or "notion_page_id" not in data_source_info
or "notion_workspace_id" not in data_source_info
):
raise ValueError("no notion page found")
workspace_id = data_source_info["notion_workspace_id"]
page_id = data_source_info["notion_page_id"]
page_type = data_source_info["type"]
page_edited_time = data_source_info["last_edited_time"]
credential_id = data_source_info.get("credential_id")
tenant_id = document.tenant_id
index_type = document.doc_form
segments = session.scalars(select(DocumentSegment).where(DocumentSegment.document_id == document_id)).all()
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
# Get credentials from datasource provider
datasource_provider_service = build_data_source_credentials(database_client=get_session_maker()).providers
credential = datasource_provider_service.get_datasource_credentials(
tenant_id=tenant_id,
credential_id=credential_id,
provider="notion_datasource",
plugin_id="langgenius/notion_datasource",
)
if not credential:
logger.error(
"Datasource credential not found for document %s, tenant_id: %s, credential_id: %s",
document_id,
tenant_id,
credential_id,
)
with session_factory.create_session() as session, session.begin():
document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = "Datasource credential not found. Please reconnect your Notion workspace."
document.stopped_at = naive_utc_now()
return
loader = NotionExtractor(
notion_token_loader=lambda: datasource_provider_service.get_stored_notion_access_token(
tenant_id=tenant_id, credential_id=credential_id
),
notion_workspace_id=workspace_id,
notion_obj_id=page_id,
notion_page_type=page_type,
notion_access_token=credential.get("integration_secret"),
tenant_id=tenant_id,
)
last_edited_time = loader.get_notion_last_edited_time()
if last_edited_time == page_edited_time:
logger.info(click.style(f"Document {document_id} content unchanged, skipping sync", fg="yellow"))
return
logger.info(click.style(f"Document {document_id} content changed, starting sync", fg="green"))
try:
indexing_service = build_document_indexing_service(session_factory=session_factory.get_session_maker())
with session_factory.create_session() as session:
document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if not document:
logger.warning(click.style(f"Document {document_id} not found during sync", fg="yellow"))
return
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
# End the read transaction before the external vector cleanup.
session.commit()
if dataset:
try:
index_processor = IndexProcessorFactory(index_type).init_index_processor()
index_processor.clean(
dataset,
index_node_ids,
with_keywords=True,
delete_child_chunks=True,
session=session,
)
session.commit()
logger.info(click.style(f"Cleaned vector index for document {document_id}", fg="green"))
except Exception:
logger.exception("Failed to clean vector index for document %s", document_id)
session.rollback()
document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if not document:
logger.warning(click.style(f"Document {document_id} not found during sync", fg="yellow"))
return
data_source_info = document.data_source_info_dict
data_source_info["last_edited_time"] = last_edited_time
document.data_source_info = json.dumps(data_source_info)
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.document_id == document_id)
session.execute(segment_delete_stmt)
document_refs = [DatasetRef(document.tenant_id, document.dataset_id).document(document.id)]
# Make the source update and segment deletion visible before extraction.
session.commit()
logger.info(click.style(f"Deleted segments for document {document_id}", fg="green"))
indexing_service.run(document_refs)
end_at = time.perf_counter()
logger.info(click.style(f"Sync completed for document {document_id} latency: {end_at - start_at}", fg="green"))
except DocumentIsPausedError as ex:
logger.info(click.style(str(ex), fg="yellow"))
except Exception as e:
logger.exception("document_indexing_sync_task failed for document_id: %s", document_id)
with session_factory.create_session() as session:
document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = str(e)
document.stopped_at = naive_utc_now()
session.commit()
@@ -0,0 +1,272 @@
import logging
import time
from collections.abc import Sequence
from typing import Any, Protocol
import click
from celery import current_app, shared_task
from sqlalchemy import 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.constant.index_type import IndexStructureType, IndexTechniqueType
from core.rag.pipeline.queue import TenantIsolatedTaskQueue
from enums import CloudPlan, DeploymentEdition
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, Document
from models.enums import IndexingStatus
from services.feature_service import FeatureService
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.indexing.errors import DocumentIsPausedError
from services.knowledge.resource_scope import DatasetRef
from tasks.generate_summary_index_task import generate_summary_index_task
logger = logging.getLogger(__name__)
class CeleryTaskLike(Protocol):
def delay(self, *args: Any, **kwargs: Any) -> Any: ...
def apply_async(self, *args: Any, **kwargs: Any) -> Any: ...
@shared_task(queue="dataset")
def document_indexing_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_document_indexing_task or priority_document_indexing_task instead.
Usage: document_indexing_task.delay(dataset_id, document_ids)
"""
logger.warning("document indexing legacy mode received: %s - %s", dataset_id, document_ids)
_document_indexing(dataset_id, document_ids)
def _document_indexing(dataset_id: str, document_ids: Sequence[str]):
"""
Process document for tasks
:param dataset_id:
:param document_ids:
Usage: _document_indexing(dataset_id, document_ids)
"""
start_at = time.perf_counter()
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.info(click.style(f"Dataset is not found: {dataset_id}", fg="yellow"))
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)
batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
if features.billing.subscription.plan == CloudPlan.SANDBOX and count > 1:
raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
if count > batch_upload_limit:
raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
if 0 < vector_space.limit <= vector_space.size:
raise ValueError(
"Your total number of documents plus the number of uploads have over the limit of "
"your subscription."
)
except Exception as e:
for document_id in document_ids:
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = str(e)
document.stopped_at = naive_utc_now()
session.add(document)
session.commit()
return
# Phase 1: Persist parsing status before slow extraction and vector operations.
with session_factory.create_session() as session, session.begin():
documents: list[Document] = list(
session.scalars(
select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id)
).all()
)
for document in documents:
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
session.add(document)
# Phase 2: Execute indexing without holding locks from the parsing-status update.
has_error = False
try:
indexing_service = build_document_indexing_service(
session_factory=session_factory.get_session_maker(), enforce_vector_space_admission=True
)
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.info(click.style(f"Dataset is not found: {dataset_id}", fg="yellow"))
return
documents = list(
session.scalars(
select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id)
).all()
)
document_refs = [DatasetRef(doc.tenant_id, doc.dataset_id).document(doc.id) for doc in documents]
session.commit()
indexing_service.run(document_refs)
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:
logger.info(click.style(str(ex), fg="yellow"))
has_error = True
except Exception:
logger.exception("Document indexing task failed, dataset_id: %s", dataset_id)
has_error = True
if not has_error:
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.warning("Dataset %s not found after indexing", dataset_id)
return
if dataset.indexing_technique == IndexTechniqueType.HIGH_QUALITY:
summary_index_setting = dataset.summary_index_setting
if summary_index_setting and summary_index_setting.get("enable"):
# Check each document's indexing status and trigger summary generation if completed
documents = list(
session.scalars(
select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id)
).all()
)
for document in documents:
if document:
logger.info(
"Checking document %s for summary generation: status=%s, doc_form=%s, need_summary=%s",
document.id,
document.indexing_status,
document.doc_form,
document.need_summary,
)
if (
document.indexing_status == IndexingStatus.COMPLETED
and document.doc_form != IndexStructureType.QA_INDEX
and document.need_summary is True
):
try:
generate_summary_index_task.delay(dataset.id, document.id, None)
logger.info(
"Queued summary index generation task for document %s in dataset %s "
"after indexing completed",
document.id,
dataset.id,
)
except Exception:
logger.exception(
"Failed to queue summary index generation task for document %s",
document.id,
)
# Don't fail the entire indexing process if summary task queuing fails
else:
logger.info(
"Skipping summary generation for document %s: "
"status=%s, doc_form=%s, need_summary=%s",
document.id,
document.indexing_status,
document.doc_form,
document.need_summary,
)
else:
logger.warning("Document %s not found after indexing", document.id)
else:
logger.info(
"Summary index generation skipped for dataset %s: indexing_technique=%s (not 'high_quality')",
dataset.id,
dataset.indexing_technique,
)
def _document_indexing_with_tenant_queue(
tenant_id: str, dataset_id: str, document_ids: Sequence[str], task_func: CeleryTaskLike
) -> None:
try:
_document_indexing(dataset_id, document_ids)
except Exception:
logger.exception(
"Error processing document indexing %s for tenant %s: %s",
dataset_id,
tenant_id,
document_ids,
exc_info=True,
)
finally:
tenant_isolated_task_queue = TenantIsolatedTaskQueue(tenant_id, "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("document indexing tenant isolation queue %s next tasks: %s", tenant_id, next_tasks)
if next_tasks:
with current_app.producer_or_acquire() as producer: # type: ignore
for next_task in next_tasks:
document_task = DocumentTask(**next_task)
# Keep the flag set to indicate a task is running
tenant_isolated_task_queue.set_task_waiting_time()
task_func.apply_async(
kwargs={
"tenant_id": document_task.tenant_id,
"dataset_id": document_task.dataset_id,
"document_ids": document_task.document_ids,
},
producer=producer,
)
else:
# No more waiting tasks, clear the flag
tenant_isolated_task_queue.delete_task_key()
@shared_task(queue="dataset")
def normal_document_indexing_task(tenant_id: str, dataset_id: str, document_ids: Sequence[str]):
"""
Async process document
:param tenant_id:
:param dataset_id:
:param document_ids:
Usage: normal_document_indexing_task.delay(tenant_id, dataset_id, document_ids)
"""
logger.info("normal document indexing task received: %s - %s - %s", tenant_id, dataset_id, document_ids)
_document_indexing_with_tenant_queue(tenant_id, dataset_id, document_ids, normal_document_indexing_task)
@shared_task(queue="priority_dataset")
def priority_document_indexing_task(tenant_id: str, dataset_id: str, document_ids: Sequence[str]):
"""
Priority async process document
:param tenant_id:
:param dataset_id:
:param document_ids:
Usage: priority_document_indexing_task.delay(tenant_id, dataset_id, document_ids)
"""
logger.info("priority document indexing task received: %s - %s - %s", tenant_id, dataset_id, document_ids)
_document_indexing_with_tenant_queue(tenant_id, dataset_id, document_ids, priority_document_indexing_task)
@@ -0,0 +1,217 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.ext_storage import storage
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, Document, DocumentSegment, SegmentAttachmentBinding
from models.enums import IndexingStatus
from models.model import UploadFile
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.indexing.errors import DocumentIsPausedError
from services.knowledge.resource_scope import DatasetRef
from tasks.generate_summary_index_task import generate_summary_index_task
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def document_indexing_update_task(dataset_id: str, document_id: str):
"""
Async update document
:param dataset_id:
:param document_id:
Usage: document_indexing_update_task.delay(dataset_id, document_id)
"""
logger.info(click.style(f"Start update document: {document_id}", fg="green"))
start_at = time.perf_counter()
has_error = False
try:
with session_factory.create_session() as session:
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="red"))
return
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
return
index_type = document.doc_form
segments = session.scalars(select(DocumentSegment).where(DocumentSegment.document_id == document_id)).all()
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
# Persist the parsing status before vector cleanup and extraction.
session.commit()
clean_success = False
index_processor = None
try:
index_processor = IndexProcessorFactory(index_type).init_index_processor()
if index_node_ids:
index_processor.clean(
dataset,
index_node_ids,
with_keywords=True,
delete_child_chunks=True,
session=session,
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Cleaned document when document update data source or process rule: {document_id} "
f"latency: {end_at - start_at}",
fg="green",
)
)
clean_success = True
except Exception:
logger.exception("Failed to clean document index during update, document_id: %s", document_id)
session.rollback()
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="red"))
return
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
session.commit()
if clean_success and index_processor is not None:
attachment_storage_keys: list[str] = []
if dataset.is_multimodal:
segment_attachment_bindings = session.scalars(
select(SegmentAttachmentBinding).where(
SegmentAttachmentBinding.tenant_id == dataset.tenant_id,
SegmentAttachmentBinding.dataset_id == dataset.id,
SegmentAttachmentBinding.document_id == document_id,
)
).all()
attachment_ids = list(
dict.fromkeys(binding.attachment_id for binding in segment_attachment_bindings)
)
if segment_attachment_bindings:
session.execute(
delete(SegmentAttachmentBinding).where(
SegmentAttachmentBinding.tenant_id == dataset.tenant_id,
SegmentAttachmentBinding.dataset_id == dataset.id,
SegmentAttachmentBinding.document_id == document_id,
)
)
session.flush()
remaining_attachment_ids = set(
session.scalars(
select(SegmentAttachmentBinding.attachment_id).where(
SegmentAttachmentBinding.attachment_id.in_(attachment_ids)
)
).all()
)
orphan_attachment_ids = [
attachment_id
for attachment_id in attachment_ids
if attachment_id not in remaining_attachment_ids
]
if orphan_attachment_ids:
attachment_storage_keys = list(
dict.fromkeys(
session.scalars(
select(UploadFile.key).where(
UploadFile.tenant_id == dataset.tenant_id,
UploadFile.id.in_(orphan_attachment_ids),
)
).all()
)
)
index_processor.clean(
session=session,
dataset=dataset,
node_ids=orphan_attachment_ids,
with_keywords=False,
)
session.execute(
delete(UploadFile).where(
UploadFile.tenant_id == dataset.tenant_id,
UploadFile.id.in_(orphan_attachment_ids),
)
)
segment_delete_stmt = delete(DocumentSegment).where(DocumentSegment.document_id == document_id)
session.execute(segment_delete_stmt)
session.commit()
for storage_key in attachment_storage_keys:
try:
storage.delete(storage_key)
except Exception:
logger.exception(
"Failed to delete document attachment from storage during re-indexing, key: %s",
storage_key,
)
indexing_service = build_document_indexing_service(session_factory=session_factory.get_session_maker())
document_refs = [DatasetRef(document.tenant_id, document.dataset_id).document(document.id)]
session.commit()
indexing_service.run(document_refs)
end_at = time.perf_counter()
logger.info(click.style(f"update document: {document.id} latency: {end_at - start_at}", fg="green"))
except DocumentIsPausedError as ex:
logger.info(click.style(str(ex), fg="yellow"))
has_error = True
except Exception:
logger.exception("document_indexing_update_task failed, document_id: %s", document_id)
has_error = True
if has_error:
return
# Trigger summary index generation for the updated document if enabled.
# Only generate for high_quality indexing technique and when summary_index_setting is enabled.
with session_factory.create_session() as session:
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.warning("Dataset %s not found after update indexing", dataset_id)
return
if dataset.indexing_technique == IndexTechniqueType.HIGH_QUALITY:
summary_index_setting = dataset.summary_index_setting
if summary_index_setting and summary_index_setting.get("enable"):
if (
document
and document.indexing_status == IndexingStatus.COMPLETED
and document.doc_form != IndexStructureType.QA_INDEX
and document.need_summary is True
):
try:
generate_summary_index_task.delay(dataset.id, document.id, None)
logger.info(
"Queued summary index generation task for document %s in dataset %s "
"after update indexing completed",
document.id,
dataset.id,
)
except Exception:
logger.exception(
"Failed to queue summary index generation task for document %s after update",
document.id,
)
@@ -0,0 +1,207 @@
import logging
import time
from collections.abc import Callable, Sequence
import click
from celery import shared_task
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 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.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.indexing.errors import DocumentIsPausedError
from services.knowledge.resource_scope import DatasetRef
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def duplicate_document_indexing_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)
_duplicate_document_indexing_task(dataset_id, document_ids)
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]
):
try:
_duplicate_document_indexing_task(dataset_id, document_ids)
except Exception:
logger.exception(
"Error processing duplicate document indexing %s for tenant %s: %s",
dataset_id,
tenant_id,
document_ids,
exc_info=True,
)
finally:
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]):
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:
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,
)
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)
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()
indexing_service.run(document_refs)
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 Exception:
session.rollback()
logger.exception("duplicate_document_indexing_task failed, dataset_id: %s", dataset_id)
@shared_task(queue="dataset")
def normal_duplicate_document_indexing_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
)
@shared_task(queue="priority_dataset")
def priority_duplicate_document_indexing_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
)
@@ -0,0 +1,140 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.doc_type import DocType
from core.rag.index_processor.constant.index_type import IndexStructureType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import DocumentSegment
from models.enums import IndexingStatus, SegmentStatus
from repositories.knowledge.dataset_read_repository import (
get_segment_child_chunks,
get_segment_dataset,
get_segment_document,
)
from repositories.knowledge.segment_read_adapter import get_segment_attachments
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def enable_segment_to_index_task(segment_id: str):
"""
Async enable segment to index
:param segment_id:
Usage: enable_segment_to_index_task.delay(segment_id)
"""
logger.info(click.style(f"Start enable segment to index: {segment_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
segment = session.scalar(select(DocumentSegment).where(DocumentSegment.id == segment_id).limit(1))
if not segment:
logger.info(click.style(f"Segment not found: {segment_id}", fg="red"))
return
if segment.status != SegmentStatus.COMPLETED:
logger.info(click.style(f"Segment is not completed, enable is not allowed: {segment_id}", fg="red"))
return
indexing_cache_key = f"segment_{segment.id}_indexing"
try:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
dataset = get_segment_dataset(segment, session=session)
if not dataset:
logger.info(click.style(f"Segment {segment.id} has no dataset, pass.", fg="cyan"))
return
dataset_document = get_segment_document(segment, session=session)
if not dataset_document:
logger.info(click.style(f"Segment {segment.id} has no document, pass.", fg="cyan"))
return
if (
not dataset_document.enabled
or dataset_document.archived
or dataset_document.indexing_status != IndexingStatus.COMPLETED
):
logger.info(click.style(f"Segment {segment.id} document status is invalid, pass.", fg="cyan"))
return
index_processor = IndexProcessorFactory(dataset_document.doc_form).init_index_processor()
if dataset_document.doc_form == IndexStructureType.PARENT_CHILD_INDEX:
child_chunks = get_segment_child_chunks(segment, session=session)
if child_chunks:
child_documents = []
for child_chunk in child_chunks:
child_document = ChildDocument(
page_content=child_chunk.content,
metadata={
"doc_id": child_chunk.index_node_id,
"doc_hash": child_chunk.index_node_hash,
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
},
)
child_documents.append(child_document)
document.children = child_documents
multimodel_documents = []
if dataset.is_multimodal:
for attachment in get_segment_attachments(segment, session=session):
multimodel_documents.append(
AttachmentDocument(
page_content=attachment["name"],
metadata={
"doc_id": attachment["id"],
"doc_hash": "",
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
"doc_type": DocType.IMAGE,
},
)
)
# save vector index
index_processor.load(dataset, [document], multimodal_documents=multimodel_documents, session=session)
session.commit()
# Enable summary index for this segment
from services.knowledge.summaries.adapters import SummaryIndexAdapter
try:
SummaryIndexAdapter.enable_summaries_for_segments(
dataset=dataset,
segment_ids=[segment.id],
)
except Exception:
logger.warning("Failed to enable summary for segment %s", segment.id, exc_info=True)
end_at = time.perf_counter()
logger.info(click.style(f"Segment enabled to index: {segment.id} latency: {end_at - start_at}", fg="green"))
except Exception as e:
logger.exception("enable segment to index failed")
session.rollback()
segment.enabled = False
segment.disabled_at = naive_utc_now()
segment.status = SegmentStatus.ERROR
segment.error = str(e)
session.commit()
finally:
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,152 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.doc_type import DocType
from core.rag.index_processor.constant.index_type import IndexStructureType
from core.rag.index_processor.index_processor import IndexProcessorFactory
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, DocumentSegment
from models.dataset import Document as DatasetDocument
from models.enums import SegmentStatus
from repositories.knowledge.dataset_read_repository import get_segment_child_chunks
from repositories.knowledge.segment_read_adapter import get_segment_attachments
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def enable_segments_to_index_task(segment_ids: list, dataset_id: str, document_id: str):
"""
Async enable segments to index
:param segment_ids: list of segment ids
:param dataset_id: dataset id
:param document_id: document id
Usage: enable_segments_to_index_task.delay(segment_ids, dataset_id, document_id)
"""
start_at = time.perf_counter()
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.info(click.style(f"Dataset {dataset_id} not found, pass.", fg="cyan"))
return
dataset_document = session.scalar(select(DatasetDocument).where(DatasetDocument.id == document_id).limit(1))
if not dataset_document:
logger.info(click.style(f"Document {document_id} not found, pass.", fg="cyan"))
return
if not dataset_document.enabled or dataset_document.archived or dataset_document.indexing_status != "completed":
logger.info(click.style(f"Document {document_id} status is invalid, pass.", fg="cyan"))
return
# sync index processor
index_processor = IndexProcessorFactory(dataset_document.doc_form).init_index_processor()
segments = session.scalars(
select(DocumentSegment).where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
# A segment that never finished indexing has no trustworthy index
# payload (its ``index_node_id`` may still be NULL), so it must not
# be pushed into the vector index. This mirrors the guard in
# ``enable_segment_to_index_task`` ("Segment is not completed,
# enable is not allowed") and in
# ``disable_segment_from_index_task``.
DocumentSegment.status == SegmentStatus.COMPLETED,
)
).all()
if not segments:
logger.info(click.style(f"Segments not found: {segment_ids}", fg="cyan"))
return
try:
documents = []
multimodal_documents = []
for segment in segments:
document = Document(
page_content=segment.content,
metadata={
"doc_id": segment.index_node_id,
"doc_hash": segment.index_node_hash,
"document_id": document_id,
"dataset_id": dataset_id,
},
)
if dataset_document.doc_form == IndexStructureType.PARENT_CHILD_INDEX:
child_chunks = get_segment_child_chunks(segment, session=session)
if child_chunks:
child_documents = []
for child_chunk in child_chunks:
child_document = ChildDocument(
page_content=child_chunk.content,
metadata={
"doc_id": child_chunk.index_node_id,
"doc_hash": child_chunk.index_node_hash,
"document_id": document_id,
"dataset_id": dataset_id,
},
)
child_documents.append(child_document)
document.children = child_documents
if dataset.is_multimodal:
for attachment in get_segment_attachments(segment, session=session):
multimodal_documents.append(
AttachmentDocument(
page_content=attachment["name"],
metadata={
"doc_id": attachment["id"],
"doc_hash": "",
"document_id": segment.document_id,
"dataset_id": segment.dataset_id,
"doc_type": DocType.IMAGE,
},
)
)
documents.append(document)
# save vector index
index_processor.load(dataset, documents, multimodal_documents=multimodal_documents, session=session)
session.commit()
# Enable summary indexes for these segments
from services.knowledge.summaries.adapters import SummaryIndexAdapter
segment_ids_list = [segment.id for segment in segments]
try:
SummaryIndexAdapter.enable_summaries_for_segments(
dataset=dataset,
segment_ids=segment_ids_list,
)
except Exception:
logger.warning("Failed to enable summaries for segments", exc_info=True)
end_at = time.perf_counter()
logger.info(click.style(f"Segments enabled to index latency: {end_at - start_at}", fg="green"))
except Exception as e:
logger.exception("enable segments to index failed")
# update segment error msg
session.rollback()
session.execute(
update(DocumentSegment)
.where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
)
.values(error=str(e), status=SegmentStatus.ERROR, disabled_at=naive_utc_now(), enabled=False)
)
session.commit()
finally:
for segment in segments:
indexing_cache_key = f"segment_{segment.id}_indexing"
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,50 @@
"""Celery worker for enterprise metric/log telemetry events.
This module defines the Celery task that processes telemetry envelopes
from the enterprise_telemetry queue. It deserializes envelopes and
dispatches them to the EnterpriseMetricHandler.
"""
import logging
from celery import shared_task
from enterprise.telemetry.contracts import TelemetryEnvelope
from enterprise.telemetry.metric_handler import EnterpriseMetricHandler
logger = logging.getLogger(__name__)
@shared_task(queue="enterprise_telemetry")
def process_enterprise_telemetry(envelope_json: str) -> None:
"""Process enterprise metric/log telemetry envelope.
This task is enqueued by the TelemetryGateway for metric/log-only
events. It deserializes the envelope and dispatches to the handler.
Best-effort processing: logs errors but never raises, to avoid
failing user requests due to telemetry issues.
Args:
envelope_json: JSON-serialized TelemetryEnvelope.
"""
try:
# Deserialize envelope
envelope = TelemetryEnvelope.model_validate_json(envelope_json)
# Process through handler
handler = EnterpriseMetricHandler()
handler.handle(envelope)
logger.debug(
"Successfully processed telemetry envelope: tenant_id=%s, event_id=%s, case=%s",
envelope.tenant_id,
envelope.event_id,
envelope.case,
)
except Exception:
# Best-effort: log and drop on error, never fail user request
logger.warning(
"Failed to process enterprise telemetry envelope, dropping event",
exc_info=True,
)
@@ -0,0 +1,127 @@
"""Async task for generating summary indexes."""
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from models.dataset import Dataset, DocumentSegment
from models.dataset import Document as DatasetDocument
from services.knowledge.summaries.adapters import SummaryIndexAdapter
logger = logging.getLogger(__name__)
@shared_task(queue="dataset_summary")
def generate_summary_index_task(dataset_id: str, document_id: str, segment_ids: list[str] | None = None):
"""
Async generate summary index for document segments.
Args:
dataset_id: Dataset ID
document_id: Document ID
segment_ids: Optional list of specific segment IDs to process. If None, process all segments.
Usage:
generate_summary_index_task.delay(dataset_id, document_id)
generate_summary_index_task.delay(dataset_id, document_id, segment_ids)
"""
logger.info(
click.style(
f"Start generating summary index for document {document_id} in dataset {dataset_id}",
fg="green",
)
)
start_at = time.perf_counter()
try:
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.error(click.style(f"Dataset not found: {dataset_id}", fg="red"))
return
document = session.scalar(
select(DatasetDocument).where(
DatasetDocument.id == document_id,
DatasetDocument.dataset_id == dataset.id,
DatasetDocument.tenant_id == dataset.tenant_id,
)
)
if not document:
logger.error(click.style(f"Document not found: {document_id}", fg="red"))
return
# Check if document needs summary
if not document.need_summary:
logger.info(
click.style(
f"Skipping summary generation for document {document_id}: need_summary is False",
fg="cyan",
)
)
return
# Only generate summary index for high_quality indexing technique
if dataset.indexing_technique != IndexTechniqueType.HIGH_QUALITY:
logger.info(
click.style(
f"Skipping summary generation for dataset {dataset_id}: "
f"indexing_technique is {dataset.indexing_technique}, not 'high_quality'",
fg="cyan",
)
)
return
# Check if summary index is enabled
summary_index_setting = dataset.summary_index_setting
if not summary_index_setting or not summary_index_setting.get("enable"):
logger.info(
click.style(
f"Summary index is disabled for dataset {dataset_id}",
fg="cyan",
)
)
return
# Determine if only parent chunks should be processed
only_parent_chunks = dataset.chunk_structure == "parent_child_index"
# Release the task's read transaction before the adapter invokes models.
session.commit()
summary_records = SummaryIndexAdapter.generate_summaries_for_document(
dataset=dataset,
document=document,
summary_index_setting=summary_index_setting,
segment_ids=segment_ids,
only_parent_chunks=only_parent_chunks,
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Summary index generation completed for document {document_id}: "
f"{len(summary_records)} summaries generated, latency: {end_at - start_at}",
fg="green",
)
)
except Exception as e:
logger.exception("Failed to generate summary index for document %s", document_id)
# Update document segments with error status if needed
if segment_ids:
error_message = f"Summary generation failed: {str(e)}"
with session_factory.create_session() as session:
session.execute(
update(DocumentSegment)
.where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.dataset_id == dataset_id,
)
.values(error=error_message)
)
session.commit()
@@ -0,0 +1,31 @@
"""Independent Celery follow-up for one committed Human Input card delivery."""
import logging
from celery import shared_task
from sqlalchemy.exc import SQLAlchemyError
from core.db.session_factory import session_factory
from core.human_input_v2.shared.values import TenantId
from services.human_input_v2.im_card_service import HumanInputIMCardService, IMCardUpdateRetryableError
from services.human_input_v2.im_credential_codec import IMCredentialError
logger = logging.getLogger(__name__)
_MAX_RETRIES = 5
@shared_task(
queue="human_input_delivery",
autoretry_for=(IMCardUpdateRetryableError, IMCredentialError, SQLAlchemyError, OSError),
retry_backoff=True,
retry_kwargs={"max_retries": _MAX_RETRIES},
acks_late=True,
reject_on_worker_lost=True,
)
def update_human_input_im_card_task(tenant_id: str, form_id: str, delivery_id: str) -> None:
logger.info(
"Human Input IM card update received tenant_id=%s form_id=%s delivery_id=%s", tenant_id, form_id, delivery_id
)
HumanInputIMCardService(session_factory=session_factory.get_session_maker()).update_card(
tenant_id=TenantId(tenant_id), form_id=form_id, delivery_id=delivery_id
)
@@ -0,0 +1,165 @@
import logging
from datetime import timedelta
from celery import shared_task
from kombu.exceptions import OperationalError as BrokerOperationalError
from sqlalchemy import or_, select
from sqlalchemy.orm import sessionmaker
from configs import dify_config
from core.db.session_factory import session_factory as v2_session_factory
from core.human_input_v2.shared.values import TenantId
from core.repositories.human_input_repository import HumanInputFormSubmissionRepository
from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
from extensions.ext_database import db
from extensions.ext_storage import storage
from graphon.enums import WorkflowExecutionStatus
from libs.datetime_utils import ensure_naive_utc, naive_utc_now
from models.human_input import HumanInputForm
from models.workflow import WorkflowPause, WorkflowRun
from repositories.human_input_v2.sqlalchemy_form_repository import SQLAlchemyFormExpirationRepository
from services.human_input_service import HumanInputService
from services.human_input_v2.form_service import handle_form_timeouts
from tasks.app_generate.workflow_execute_task import WORKFLOW_BASED_APP_EXECUTION_QUEUE
logger = logging.getLogger(__name__)
@shared_task(name="human_input_form_timeout.check_and_resume", queue="schedule_executor")
def check_and_handle_human_input_timeouts(limit: int = 100) -> None:
"""Keep legacy expiration handling and fan out independent v2 timeout tasks."""
_handle_legacy_human_input_timeouts(limit)
_enqueue_human_input_v2_timeouts(limit)
def _enqueue_human_input_v2_timeouts(limit: int) -> None:
"""Discover candidate runs without settling forms in the periodic task."""
now = naive_utc_now()
with v2_session_factory.create_session() as session:
runs = SQLAlchemyFormExpirationRepository(session).list_expired_runs(now=now, limit=limit)
for run in runs:
try:
handle_human_input_v2_timeout.apply_async(
kwargs={"tenant_id": run.tenant_id, "app_id": run.app_id, "workflow_run_id": run.workflow_run_id}
)
except BrokerOperationalError:
logger.exception(
"Failed to enqueue v2 timeout: tenant_id=%s app_id=%s workflow_run_id=%s",
run.tenant_id,
run.app_id,
run.workflow_run_id,
)
@shared_task(name="human_input_v2_form_timeout.handle", queue=WORKFLOW_BASED_APP_EXECUTION_QUEUE)
def handle_human_input_v2_timeout(tenant_id: str, app_id: str, workflow_run_id: str) -> None:
"""Settle one run using current persisted state, then enqueue resume if due."""
logger.info("Handling v2 timeout: tenant_id=%s app_id=%s workflow_run_id=%s", tenant_id, app_id, workflow_run_id)
handle_form_timeouts(
session_factory=v2_session_factory.get_session_maker(),
tenant_id=TenantId(tenant_id),
app_id=app_id,
workflow_run_id=workflow_run_id,
)
def _is_global_timeout(form_model: HumanInputForm, global_timeout_seconds: int, *, now) -> bool:
if global_timeout_seconds <= 0:
return False
if form_model.workflow_run_id is None:
return False
created_at = ensure_naive_utc(form_model.created_at)
global_deadline = created_at + timedelta(seconds=global_timeout_seconds)
return global_deadline <= now
def _handle_global_timeout(*, form_id: str, workflow_run_id: str, node_id: str, session_factory: sessionmaker) -> None:
now = naive_utc_now()
with session_factory() as session, session.begin():
workflow_run = session.get(WorkflowRun, workflow_run_id)
if workflow_run is not None:
workflow_run.status = WorkflowExecutionStatus.STOPPED
workflow_run.error = f"Human input global timeout at node {node_id}"
workflow_run.finished_at = now
session.add(workflow_run)
pause_model = session.scalar(select(WorkflowPause).where(WorkflowPause.workflow_run_id == workflow_run_id))
if pause_model is not None:
try:
storage.delete(pause_model.state_object_key)
except Exception:
logger.exception(
"Failed to delete pause state object for workflow_run_id=%s, pause_id=%s",
workflow_run_id,
pause_model.id,
)
pause_model.resumed_at = now
session.add(pause_model)
def _handle_legacy_human_input_timeouts(limit: int) -> None:
"""Scan for expired human input forms and resume or end workflows."""
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
form_repo = HumanInputFormSubmissionRepository()
service = HumanInputService(session_factory, form_repository=form_repo)
now = naive_utc_now()
global_timeout_seconds = dify_config.HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS
with session_factory() as session:
global_deadline = now - timedelta(seconds=global_timeout_seconds) if global_timeout_seconds > 0 else None
timeout_filter = HumanInputForm.expiration_time <= now
if global_deadline is not None:
timeout_filter = or_(timeout_filter, HumanInputForm.created_at <= global_deadline)
stmt = (
select(HumanInputForm)
.where(
HumanInputForm.status == HumanInputFormStatus.WAITING,
timeout_filter,
)
.order_by(HumanInputForm.id.asc())
.limit(limit)
)
expired_forms = session.scalars(stmt).all()
for form_model in expired_forms:
try:
if form_model.form_kind == HumanInputFormKind.DELIVERY_TEST:
form_repo.mark_timeout(
form_id=form_model.id,
timeout_status=HumanInputFormStatus.TIMEOUT,
reason="delivery_test_timeout",
)
continue
is_global = _is_global_timeout(form_model, global_timeout_seconds, now=now)
record = form_repo.mark_timeout(
form_id=form_model.id,
timeout_status=HumanInputFormStatus.EXPIRED if is_global else HumanInputFormStatus.TIMEOUT,
reason="global_timeout" if is_global else "node_timeout",
)
if is_global:
# Global timeout applies only to workflow-owned forms
# (_is_global_timeout requires a workflow_run_id): end the run.
assert record.workflow_run_id is not None, "global timeout requires a workflow_run_id"
_handle_global_timeout(
form_id=record.form_id,
workflow_run_id=record.workflow_run_id,
node_id=record.node_id,
session_factory=session_factory,
)
elif record.workflow_run_id is not None:
# Human Input node form: resume the workflow.
service.enqueue_resume(record.workflow_run_id)
else:
logger.warning(
"Timed-out form %s has no workflow_run_id; skipping resume",
record.form_id,
)
except Exception:
logger.exception(
"Failed to handle timeout for form_id=%s workflow_run_id=%s",
form_model.id,
form_model.workflow_run_id,
)
@@ -0,0 +1,56 @@
"""Celery entrypoint for durable IM Contact synchronization runs."""
from __future__ import annotations
import logging
from celery import shared_task
from core.human_input_v2.shared import DeploymentScope, DirectoryScope, IMSyncRunId, TenantId, WorkspaceScope
from services.human_input_v2.im_contact_sync.coordinator import IMSyncRetryableError
from services.human_input_v2.im_contact_sync.worker import IMContactSyncWorker
logger = logging.getLogger(__name__)
_WORKSPACE_SCOPE_KIND = "workspace"
_DEPLOYMENT_SCOPE_KIND = "deployment"
def build_im_contact_sync_worker() -> IMContactSyncWorker:
"""Defer production composition until a worker delivery is actually claimed."""
from services.human_input_v2.im_contact_sync.composition import build_im_contact_sync_worker as build_worker
return build_worker()
@shared_task(
queue="human_input_contact_sync",
autoretry_for=(IMSyncRetryableError,),
retry_backoff=True,
retry_kwargs={"max_retries": 5},
)
def reconcile_im_contacts_task(sync_run_id: str, scope_kind: str, tenant_id: str | None) -> str:
"""Accept durable identifiers and return the persisted terminal run status."""
scope = _scope_from_payload(scope_kind, tenant_id)
logger.info("IM Contact sync task received, sync_run_id=%s", sync_run_id)
terminal_run = build_im_contact_sync_worker().execute(IMSyncRunId(sync_run_id), scope)
logger.info(
"IM Contact sync task completed, sync_run_id=%s, channel_id=%s, status=%s",
terminal_run.id,
terminal_run.channel_revision.channel_id,
terminal_run.status.value,
)
return terminal_run.status.value
def _scope_from_payload(scope_kind: str, tenant_id: str | None) -> DirectoryScope:
if scope_kind == _WORKSPACE_SCOPE_KIND and tenant_id is not None:
return WorkspaceScope(id=TenantId(tenant_id))
if scope_kind == _DEPLOYMENT_SCOPE_KIND and tenant_id is None:
return DeploymentScope()
raise ValueError("invalid Organization scope payload")
__all__ = ["reconcile_im_contacts_task"]
@@ -0,0 +1,91 @@
"""Celery execution boundary for durable IM callbacks."""
from __future__ import annotations
import logging
from collections.abc import Callable
from dataclasses import dataclass
from traceback import extract_tb
from typing import Protocol
from celery import shared_task
from flask import current_app
from core.human_input_v2.im_message_inbox import IMInboxRecordId
from dify_app import DifyApp
logger = logging.getLogger(__name__)
_RUNTIME_EXTENSION_KEY = "im_message_inbox_task_runtime"
_MAX_RETRIES = 5
class IMInboxRecordProcessor(Protocol):
"""Process one callback record without owning task retry policy."""
def process(self, record_id: IMInboxRecordId) -> None:
"""Process one durable callback record."""
@dataclass(frozen=True, slots=True)
class IMInboxTaskRuntime:
"""Application-composed factory for callback processing."""
processor_factory: Callable[[], IMInboxRecordProcessor]
class IMInboxRuntimeNotConfiguredError(Exception):
"""Application composition has not installed callback processing."""
class IMInboxTaskRetryError(Exception):
"""Sanitized callback processing failure retried by Celery."""
def configure_im_inbox_task_runtime(
app: DifyApp,
*,
processor_factory: Callable[[], IMInboxRecordProcessor],
) -> None:
"""Install the application-composed callback processor factory."""
app.extensions[_RUNTIME_EXTENSION_KEY] = IMInboxTaskRuntime(processor_factory=processor_factory)
def _task_runtime() -> IMInboxTaskRuntime:
runtime = current_app.extensions.get(_RUNTIME_EXTENSION_KEY)
if not isinstance(runtime, IMInboxTaskRuntime):
raise IMInboxRuntimeNotConfiguredError("IM callback processor is not configured")
return runtime
@shared_task(
name="im_message_inbox.process_record",
queue="human_input_delivery",
autoretry_for=(IMInboxTaskRetryError,),
retry_backoff=True,
retry_kwargs={"max_retries": _MAX_RETRIES},
acks_late=True,
reject_on_worker_lost=True,
)
def process_im_message_inbox_record(record_id: str) -> None:
"""Process one committed callback and let Celery own retry lifecycle."""
runtime = _task_runtime()
try:
processor = runtime.processor_factory()
processor.process(IMInboxRecordId(record_id))
except Exception as error:
# Exception messages and chained SQL parameters may contain callback
# tokens. Source frames still identify the failure without those values.
logger.exception(
"IM callback processing will be retried record_id=%s error_type=%s\n%s",
record_id,
type(error).__name__,
"".join(
f' File "{frame.filename}", line {frame.lineno}, in {frame.name}\n'
for frame in extract_tb(error.__traceback__)
),
exc_info=False,
)
raise IMInboxTaskRetryError(f"failed to process IM callback record {record_id}") from None
@@ -0,0 +1,248 @@
"""Initialize default RBAC access for existing workspace members after app creation."""
import logging
from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass
from celery import shared_task
from sqlalchemy import select
from configs import dify_config
from extensions.ext_database import db
from models import Agent, App, Dataset, TenantAccountJoin, TenantAccountRole
from services.enterprise import rbac_service as enterprise_rbac_service
from services.rbac import contracts as rbac_contracts
logger = logging.getLogger(__name__)
APP_RBAC_ACCOUNT_POLICY_BATCH_SIZE = 500
APP_RBAC_DEFAULT_ACCESS_POLICY_ID = "default"
APP_RBAC_QUEUE = "app_rbac"
APP_RBAC_RESOURCE_CONFIG_BATCH_SIZE = 500
APP_RBAC_MEMBER_APPEND_BATCH_SIZE = 500
def _owner_account_id(tenant_id: str) -> str | None:
return db.session().scalar(
select(TenantAccountJoin.account_id)
.where(TenantAccountJoin.tenant_id == tenant_id, TenantAccountJoin.role == TenantAccountRole.OWNER)
.order_by(TenantAccountJoin.id.asc())
.limit(1)
)
@dataclass(frozen=True)
class _WhitelistResourceKind[ItemT]:
resource_type: rbac_contracts.RBACResourceType
model: type[App] | type[Dataset] | type[Agent]
build_item: Callable[[str, Sequence[str]], ItemT]
append_members: Callable[[str, str | None, Sequence[ItemT]], None]
def iter_id_batches(self, tenant_id: str, batch_size: int) -> Iterator[list[str]]:
last_id: str | None = None
while True:
stmt = (
select(self.model.id)
.where(self.model.tenant_id == tenant_id)
.order_by(self.model.id.asc())
.limit(batch_size)
)
if last_id:
stmt = stmt.where(self.model.id > last_id)
ids = list(db.session().scalars(stmt).all())
if not ids:
return
yield ids
last_id = ids[-1]
def append_member(self, tenant_id: str, actor_account_id: str, resource_ids: list[str], member_account_id: str):
self.append_members(
tenant_id,
actor_account_id,
[self.build_item(resource_id, [member_account_id]) for resource_id in resource_ids],
)
def append_member_batch(
self,
tenant_id: str,
actor_account_id: str,
resource_id: str,
member_account_ids: Sequence[str],
) -> None:
self.append_members(
tenant_id,
actor_account_id,
[self.build_item(resource_id, member_account_ids)],
)
_WHITELIST_RESOURCE_KINDS = (
_WhitelistResourceKind(
resource_type=rbac_contracts.RBACResourceType.APP,
model=App,
build_item=lambda app_id, account_ids: rbac_contracts.AppendAppWhitelistMembersBatchItem(
app_id=app_id, account_ids=list(account_ids), policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID
),
append_members=lambda tenant_id, account_id, data: (
enterprise_rbac_service.RBACService.AppAccess.append_whitelist_members_batch(
tenant_id=tenant_id, account_id=account_id, data=data
)
),
),
_WhitelistResourceKind(
resource_type=rbac_contracts.RBACResourceType.DATASET,
model=Dataset,
build_item=lambda dataset_id, account_ids: rbac_contracts.AppendDatasetWhitelistMembersBatchItem(
dataset_id=dataset_id, account_ids=list(account_ids), policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID
),
append_members=lambda tenant_id, account_id, data: (
enterprise_rbac_service.RBACService.DatasetAccess.append_whitelist_members_batch(
tenant_id=tenant_id, account_id=account_id, data=data
)
),
),
_WhitelistResourceKind(
resource_type=rbac_contracts.RBACResourceType.AGENT,
model=Agent,
build_item=lambda agent_id, account_ids: rbac_contracts.AppendAgentWhitelistMembersBatchItem(
agent_id=agent_id, account_ids=list(account_ids), policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID
),
append_members=lambda tenant_id, account_id, data: (
enterprise_rbac_service.RBACService.AgentAccess.append_whitelist_members_batch(
tenant_id=tenant_id, account_id=account_id, data=data
)
),
),
)
_WHITELIST_RESOURCE_KIND_BY_TYPE = {kind.resource_type: kind for kind in _WHITELIST_RESOURCE_KINDS}
def _iter_resource_config_batches(
tenant_id: str,
batch_size: int,
) -> Iterator[list[rbac_contracts.ResourceWhitelistConfigResource]]:
for kind in _WHITELIST_RESOURCE_KINDS:
for ids in kind.iter_id_batches(tenant_id, batch_size):
yield [
rbac_contracts.ResourceWhitelistConfigResource(
resource_type=kind.resource_type, resource_id=resource_id
)
for resource_id in ids
]
def _chunks[T](items: list[T], chunk_size: int) -> Iterator[list[T]]:
for index in range(0, len(items), chunk_size):
yield items[index : index + chunk_size]
def _resolve_target_resource(
resource_ids: dict[rbac_contracts.RBACResourceType, str | None],
) -> tuple[_WhitelistResourceKind, str]:
provided = [(resource_type, rid) for resource_type, rid in resource_ids.items() if rid is not None]
if len(provided) != 1:
given = ", ".join(sorted(resource_type.value for resource_type, _ in provided)) or "none"
raise ValueError(f"exactly one of app_id, dataset_id, agent_id must be given, got: {given}")
resource_type, resource_id = provided[0]
return _WHITELIST_RESOURCE_KIND_BY_TYPE[resource_type], resource_id
@shared_task(queue=APP_RBAC_QUEUE, bind=True, max_retries=3, default_retry_delay=60)
def initialize_created_app_rbac_access_task(
self,
tenant_id: str,
account_id: str,
app_id: str | None = None,
dataset_id: str | None = None,
agent_id: str | None = None,
) -> None:
"""Grant the default policy on one app, dataset or agent to current workspace members.
The resource scope is persisted synchronously before this task is queued. Member
bindings are appended through the whitelist batch endpoint so locked default
access-policy bindings remain immutable.
"""
if not dify_config.RBAC_ENABLED:
return
kind, resource_id = _resolve_target_resource(
{
rbac_contracts.RBACResourceType.APP: app_id,
rbac_contracts.RBACResourceType.DATASET: dataset_id,
rbac_contracts.RBACResourceType.AGENT: agent_id,
}
)
from extensions.ext_application_services import application_services
try:
for account_ids in application_services().workspaces.management.iter_member_account_id_batches(
tenant_id,
APP_RBAC_ACCOUNT_POLICY_BATCH_SIZE,
):
kind.append_member_batch(
tenant_id,
account_id,
resource_id,
account_ids,
)
except Exception as exc:
logger.exception(
"Failed to initialize RBAC access; retrying: tenant_id=%s resource_type=%s resource_id=%s attempt=%s",
tenant_id,
kind.resource_type.value,
resource_id,
self.request.retries + 1,
)
raise self.retry(exc=exc) from exc
@shared_task(queue=APP_RBAC_QUEUE, bind=True, max_retries=3, default_retry_delay=60)
def sync_joined_workspace_member_rbac_access_task(
self,
tenant_id: str,
member_account_id: str,
operator_account_id: str | None = None,
) -> None:
"""Grant a newly joined member default access to resources that auto-include workspace members."""
if not dify_config.RBAC_ENABLED:
return
try:
actor_account_id = operator_account_id or _owner_account_id(tenant_id)
if actor_account_id is None:
logger.warning(
"Skipping joined member RBAC access sync because workspace owner was not found: tenant_id=%s member=%s",
tenant_id,
member_account_id,
)
return
auto_included: dict[rbac_contracts.RBACResourceType, list[str]] = {
kind.resource_type: [] for kind in _WHITELIST_RESOURCE_KINDS
}
for resources in _iter_resource_config_batches(tenant_id, APP_RBAC_RESOURCE_CONFIG_BATCH_SIZE):
configs = enterprise_rbac_service.RBACService.ResourceWhitelistConfigs.batch_get(
tenant_id=tenant_id,
account_id=actor_account_id,
resources=resources,
)
for config in configs.data:
if not config.automatic_include_workspace_members:
continue
ids = auto_included.get(config.resource_type)
if ids is not None:
ids.append(config.resource_id)
for resource_type, resource_ids in auto_included.items():
kind = _WHITELIST_RESOURCE_KIND_BY_TYPE[resource_type]
for id_batch in _chunks(resource_ids, APP_RBAC_MEMBER_APPEND_BATCH_SIZE):
kind.append_member(tenant_id, actor_account_id, id_batch, member_account_id)
except Exception as exc:
logger.exception(
"Failed to sync joined member RBAC access; retrying: tenant_id=%s member=%s attempt=%s",
tenant_id,
member_account_id,
self.request.retries + 1,
)
raise self.retry(exc=exc) from exc
@@ -0,0 +1,104 @@
"""Install configured marketplace plugins for a newly created tenant."""
import logging
from celery import shared_task
from configs import dify_config
from core.helper import marketplace
from core.plugin.entities.plugin_daemon import PluginInstallTaskStatus
from core.plugin.plugin_service import PluginService
from graphon.model_runtime.entities.model_entities import ModelType
from services.model_provider.service import ModelProviderService
logger = logging.getLogger(__name__)
@shared_task(queue="plugin", bind=True, max_retries=60, default_retry_delay=5)
def configure_default_models_task(self, tenant_id: str, plugin_install_task_id: str | None) -> None:
"""Apply explicit defaults and initialize an unset LLM after default plugins finish installing."""
plugin_install_failed = False
if plugin_install_task_id:
try:
install_task = PluginService.fetch_install_task(tenant_id, plugin_install_task_id)
except Exception as exc:
logger.warning(
"Failed to fetch default plugin installation task for tenant %s; retrying",
tenant_id,
)
raise self.retry(exc=exc) from exc
if install_task.status in (PluginInstallTaskStatus.Pending, PluginInstallTaskStatus.Running):
raise self.retry()
plugin_install_failed = install_task.status == PluginInstallTaskStatus.Failed
if plugin_install_failed:
failed_plugin_ids = [
plugin.plugin_id for plugin in install_task.plugins if plugin.status == PluginInstallTaskStatus.Failed
]
logger.error(
"Default plugin installation failed for tenant %s: %s",
tenant_id,
", ".join(failed_plugin_ids),
)
model_provider_service = ModelProviderService()
failed_model_types: list[str] = []
model_settings = dify_config.NEW_USER_DEFAULT_MODEL_LIST
for model_type, provider, model in model_settings:
try:
model_provider_service.update_default_model_of_model_type(
tenant_id=tenant_id,
model_type=model_type,
provider=provider,
model=model,
)
except Exception:
failed_model_types.append(model_type)
logger.exception(
"Failed to configure default model for tenant %s: model_type=%s provider=%s model=%s",
tenant_id,
model_type,
provider,
model,
)
if not any(model_type == ModelType.LLM for model_type, _, _ in model_settings):
try:
model_provider_service.initialize_default_llm(tenant_id)
except Exception:
failed_model_types.append(ModelType.LLM.value)
logger.exception("Failed to initialize default LLM for tenant %s", tenant_id)
if plugin_install_failed or failed_model_types:
raise RuntimeError(
f"Failed to initialize defaults for tenant {tenant_id}; "
f"model types: {', '.join(failed_model_types) or 'none'}"
)
@shared_task(queue="plugin")
def install_default_plugins_task(tenant_id: str, plugin_ids: list[str]) -> None:
"""Install the latest marketplace versions of the configured plugins."""
if not plugin_ids:
return
try:
manifests = {manifest.plugin_id: manifest for manifest in marketplace.batch_fetch_plugin_manifests(plugin_ids)}
plugin_identifiers = [
manifests[plugin_id].latest_package_identifier for plugin_id in plugin_ids if plugin_id in manifests
]
missing_plugin_ids = [plugin_id for plugin_id in plugin_ids if plugin_id not in manifests]
if missing_plugin_ids:
logger.warning("Default plugins not found in marketplace: %s", ", ".join(missing_plugin_ids))
if not plugin_identifiers:
return
response = PluginService.install_from_marketplace_pkg(tenant_id, plugin_identifiers)
configure_default_models_task.delay(
tenant_id,
None if response.all_installed else response.task_id,
)
except Exception:
logger.exception("Failed to install default plugins for tenant %s", tenant_id)
raise
@@ -0,0 +1,43 @@
"""Classify a completed Agent knowledge investigation outside the Agent hot path."""
import logging
from celery import shared_task
from dify_agent.protocol.knowledge_fs import KnowledgeFsError
from dify_agent.protocol.knowledge_investigation import KnowledgeInvestigationPayload
from pydantic import ValidationError
from services.agent.knowledge_gateway import AgentKnowledgeGateway
from services.agent_config_service import AgentConfigServiceError
from services.knowledge_fs.app_admission_service import KnowledgeFSAppAdmissionError
from services.knowledge_fs.product_remote import KnowledgeFSProductRequestRejectedError
from services.knowledge_fs_capability import KnowledgeFSCapabilityPolicyError
logger = logging.getLogger(__name__)
@shared_task(queue="dataset", bind=True, max_retries=3, default_retry_delay=30)
def capture_agent_knowledge_investigation_task(self, *, report: dict, control_space_id: str) -> None:
"""Reconstruct authorization on every attempt; report IDs survive queue redelivery."""
context = {"control_space_id": control_space_id, "investigation_id": str(report.get("investigation_id", ""))[:36]}
try:
payload = KnowledgeInvestigationPayload.model_validate(report)
AgentKnowledgeGateway().capture_investigation(payload, control_space_id)
except (
KnowledgeFsError,
AgentConfigServiceError,
KnowledgeFSAppAdmissionError,
KnowledgeFSCapabilityPolicyError,
ValidationError,
PermissionError,
):
logger.warning("Agent knowledge investigation rejected", extra=context)
except KnowledgeFSProductRequestRejectedError as exc:
if exc.status_code not in {429, 503}:
logger.warning("Agent knowledge investigation rejected", extra=context)
return
logger.warning("Agent knowledge investigation retry scheduled", extra=context)
raise self.retry(exc=exc, countdown=30 * (2**self.request.retries)) from exc
except Exception as exc:
logger.warning("Agent knowledge investigation retry scheduled", extra=context)
raise self.retry(exc=exc, countdown=30 * (2**self.request.retries)) from exc
@@ -0,0 +1,78 @@
"""Celery owns execution; durable KnowledgeFS leases own resource state and retry policy."""
import logging
import time
from celery import shared_task
from celery.exceptions import Reject
from celery.signals import worker_process_shutdown
from configs import dify_config
from services.knowledge_fs.background_contract import (
DELIVERY_TASK,
DOCUMENT_QUEUE,
MAINTENANCE_QUEUE,
OPERATION_QUEUES,
OPERATION_TASK,
BackgroundJobPayload,
)
from services.knowledge_fs.background_engine import background_engine
logger = logging.getLogger(__name__)
@worker_process_shutdown.connect
def close_background_engine(**_: object) -> None:
background_engine.close()
@shared_task(
name=DELIVERY_TASK,
bind=True,
queue=DOCUMENT_QUEUE,
acks_late=True,
reject_on_worker_lost=True,
max_retries=None,
soft_time_limit=dify_config.KNOWLEDGE_FS_BACKGROUND_TASK_TIMEOUT_SECONDS,
time_limit=dify_config.KNOWLEDGE_FS_BACKGROUND_TASK_TIMEOUT_SECONDS + 30,
)
def execute_delivery(self, *, delivery: dict[str, object]) -> dict[str, object]:
try:
locator = BackgroundJobPayload.model_validate(delivery)
except ValueError as error:
raise Reject("Invalid KnowledgeFS background locator", requeue=False) from error
if str(locator.id) != self.request.id:
raise Reject("KnowledgeFS broker delivery identity mismatch", requeue=False)
envelope = locator.model_dump(mode="json", exclude={"runAfter"})
envelope["attempts"] = self.request.retries + 1
logger.info("KnowledgeFS Celery delivery type=%s delivery_id=%s", locator.type, locator.id)
try:
result = background_engine.execute("delivery", envelope)
except Exception as error:
raise self.retry(exc=error, countdown=min(300, 5 * 2 ** min(self.request.retries, 6))) from error
if result.get("outcome") == "retry":
run_after = result.get("runAfter")
delay = max(1.0, (float(run_after) / 1000 - time.time()) if isinstance(run_after, (int, float)) else 5.0)
raise self.retry(countdown=min(delay, 86_400))
if result.get("outcome") == "failed":
raise Reject("KnowledgeFS rejected the background delivery", requeue=False)
return result
@shared_task(
name=OPERATION_TASK,
bind=True,
queue=MAINTENANCE_QUEUE,
acks_late=True,
reject_on_worker_lost=True,
max_retries=5,
soft_time_limit=dify_config.KNOWLEDGE_FS_BACKGROUND_TASK_TIMEOUT_SECONDS,
time_limit=dify_config.KNOWLEDGE_FS_BACKGROUND_TASK_TIMEOUT_SECONDS + 30,
)
def execute_operation(self, *, operation: str) -> dict[str, object]:
if not isinstance(operation, str) or operation not in OPERATION_QUEUES:
raise Reject("Unknown KnowledgeFS background operation", requeue=False)
try:
return background_engine.execute(operation)
except Exception as error:
raise self.retry(exc=error, countdown=min(300, 5 * 2 ** min(self.request.retries, 6))) from error
@@ -0,0 +1,159 @@
"""Asynchronously classify empty KnowledgeFS Workflow retrievals for quality follow-up."""
from __future__ import annotations
import logging
import uuid
from typing import Literal
from celery import shared_task
from pydantic import ValidationError
from core.db.session_factory import session_factory
from services.knowledge_fs.app_admission_service import KnowledgeFSAppAdmissionError
from services.knowledge_fs.app_execution_capability import KnowledgeResourceRef
from services.knowledge_fs.product_dto import KnowledgeFSWorkflowFailedRetrievalCapturePayload
from services.knowledge_fs.product_remote import (
KnowledgeFSOperationUnavailableError,
KnowledgeFSProductRequestRejectedError,
KnowledgeFSProductResourceNotFoundError,
)
from services.knowledge_fs.runtime import get_knowledge_fs_runtime
logger = logging.getLogger(__name__)
_MAX_RETRIES = 3
_RETRY_DELAY_SECONDS = 30
@shared_task(queue="dataset", bind=True, max_retries=_MAX_RETRIES, default_retry_delay=_RETRY_DELAY_SECONDS)
def capture_workflow_failed_retrieval_task(
self,
*,
event_id: str,
tenant_id: str,
app_id: str,
control_space_id: str,
query: str,
mode: Literal["deep", "fast", "research"],
retrieval_trace_id: str,
) -> None:
"""Re-authorize a Workflow app and ask KnowledgeFS to classify one empty retrieval.
``event_id`` is the stable business idempotency key across Celery retries. Capability transport
traces are minted independently on every attempt so uncertain delivery can be retried safely.
"""
context = {
"app_id": app_id,
"control_space_id": control_space_id,
"event_id": event_id,
"tenant_id": tenant_id,
}
try:
payload = KnowledgeFSWorkflowFailedRetrievalCapturePayload.model_validate(
{
"eventId": event_id,
"query": query,
"mode": mode,
"retrievalTraceId": retrieval_trace_id,
}
)
capability = get_knowledge_fs_runtime(session_factory.get_session_maker()).app_capabilities
result = capability.capture_workflow_failed_retrieval(
tenant_id=tenant_id,
app_id=app_id,
resource=KnowledgeResourceRef(kind="knowledge_fs", control_space_id=control_space_id),
payload=payload,
)
except (
KnowledgeFSAppAdmissionError,
KnowledgeFSOperationUnavailableError,
KnowledgeFSProductResourceNotFoundError,
ValidationError,
):
logger.exception("KnowledgeFS Workflow failed-retrieval capture was rejected", extra=context)
return
except KnowledgeFSProductRequestRejectedError as exc:
if exc.status_code != 429:
logger.exception("KnowledgeFS Workflow failed-retrieval capture was rejected", extra=context)
return
_retry_capture(self, exc=exc, context=context)
except Exception as exc:
_retry_capture(self, exc=exc, context=context)
else:
logger.info(
"KnowledgeFS Workflow failed-retrieval capture completed",
extra={
**context,
"bad_case_id": str(result.bad_case_id) if result.bad_case_id else None,
"failed_query_id": str(result.failed_query_id),
"verdict": result.verdict,
},
)
def enqueue_workflow_failed_retrieval_capture(
*,
tenant_id: str,
app_id: str,
control_space_id: str,
query: str,
mode: Literal["deep", "fast", "research"],
retrieval_trace_id: str,
event_id: str | None = None,
) -> None:
"""Best-effort dispatch that never changes the completed Workflow node outcome."""
capture_event_id = event_id or str(uuid.uuid4())
try:
payload = KnowledgeFSWorkflowFailedRetrievalCapturePayload.model_validate(
{
"eventId": capture_event_id,
"query": query,
"mode": mode,
"retrievalTraceId": retrieval_trace_id,
}
)
capture_workflow_failed_retrieval_task.delay(
event_id=str(payload.event_id),
tenant_id=tenant_id,
app_id=app_id,
control_space_id=control_space_id,
query=payload.query,
mode=payload.mode,
retrieval_trace_id=payload.retrieval_trace_id,
)
except Exception:
logger.exception(
"Failed to enqueue KnowledgeFS Workflow failed-retrieval capture",
extra={
"app_id": app_id,
"control_space_id": control_space_id,
"event_id": capture_event_id,
"tenant_id": tenant_id,
},
)
def _retry_capture(self, *, exc: Exception, context: dict[str, str]) -> None:
if self.request.retries >= _MAX_RETRIES:
logger.exception(
"KnowledgeFS Workflow failed-retrieval capture retry budget exhausted",
extra=context,
)
raise exc
logger.warning(
"KnowledgeFS Workflow failed-retrieval capture failed; scheduling retry %d/%d",
self.request.retries + 1,
_MAX_RETRIES,
extra=context,
exc_info=True,
)
raise self.retry(exc=exc, countdown=_RETRY_DELAY_SECONDS * (2**self.request.retries))
__all__ = [
"capture_workflow_failed_retrieval_task",
"enqueue_workflow_failed_retrieval_capture",
]
@@ -0,0 +1,132 @@
"""Runs website datasource preview jobs outside Console request workers."""
from __future__ import annotations
import logging
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from models.account import Account, AccountStatus, TenantAccountJoin
from services.knowledge_fs.initial_source_preview import (
KnowledgeFSInitialSourcePreviewCanceledError,
KnowledgeFSInitialSourcePreviewService,
)
from services.knowledge_fs.initial_source_preview_job import (
KnowledgeFSInitialSourcePreviewJobNotFoundError,
KnowledgeFSInitialSourcePreviewJobService,
)
from services.knowledge_fs.product_dto import (
KnowledgeFSInitialWebsiteSourcePreviewPayload,
knowledge_fs_initial_preview_configuration_fingerprint,
)
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def run_knowledge_fs_initial_source_preview(
*,
tenant_id: str,
account_id: str,
job_id: str,
payload: dict[str, object],
) -> None:
job_service = KnowledgeFSInitialSourcePreviewJobService(session_factory.get_session_maker())
try:
if not job_service.transition_status(
tenant_id=tenant_id,
account_id=account_id,
job_id=job_id,
status="running",
allowed_from=("pending",),
):
return
with session_factory.create_session() as session:
account = session.get(Account, account_id)
if account is None or account.status != AccountStatus.ACTIVE:
raise LookupError("Datasource preview account is unavailable")
membership = session.scalar(
select(TenantAccountJoin.id).where(
TenantAccountJoin.tenant_id == tenant_id,
TenantAccountJoin.account_id == account_id,
)
)
if membership is None:
raise PermissionError("Datasource preview account is not a tenant member")
account.set_tenant_id_with_session(tenant_id, session=session)
if account.current_tenant_id != tenant_id:
raise PermissionError("Datasource preview account is not a tenant member")
session.expunge(account)
preview_payload = KnowledgeFSInitialWebsiteSourcePreviewPayload.model_validate(payload)
result = KnowledgeFSInitialSourcePreviewService(session_factory.get_session_maker()).preview(
tenant_id=tenant_id,
account=account,
payload=preview_payload,
is_canceled=lambda: _preview_was_canceled(
job_service=job_service,
tenant_id=tenant_id,
account_id=account_id,
job_id=job_id,
),
)
result.configuration_fingerprint = knowledge_fs_initial_preview_configuration_fingerprint(preview_payload)
job_service.store_content(tenant_id=tenant_id, account_id=account_id, job_id=job_id, result=result)
completed = job_service.transition_status(
tenant_id=tenant_id,
account_id=account_id,
job_id=job_id,
status="completed",
allowed_from=("running",),
result=result,
)
if completed:
cleanup_knowledge_fs_initial_source_preview.apply_async(
kwargs={"account_id": account_id, "job_id": job_id, "tenant_id": tenant_id},
countdown=60 * 60,
)
except KnowledgeFSInitialSourcePreviewCanceledError:
logger.info(
"KnowledgeFS initial source preview canceled",
extra={"account_id": account_id, "job_id": job_id, "tenant_id": tenant_id},
)
except Exception:
logger.exception(
"KnowledgeFS initial source preview failed",
extra={"account_id": account_id, "job_id": job_id, "tenant_id": tenant_id},
)
job_service.transition_status(
tenant_id=tenant_id,
account_id=account_id,
job_id=job_id,
status="failed",
allowed_from=("pending", "running"),
)
finally:
job_service.release_active_job(
tenant_id=tenant_id,
account_id=account_id,
job_id=job_id,
)
def _preview_was_canceled(
*,
job_service: KnowledgeFSInitialSourcePreviewJobService,
tenant_id: str,
account_id: str,
job_id: str,
) -> bool:
try:
return job_service.get(tenant_id=tenant_id, account_id=account_id, job_id=job_id).status == "canceled"
except KnowledgeFSInitialSourcePreviewJobNotFoundError:
return True
@shared_task(queue="dataset")
def cleanup_knowledge_fs_initial_source_preview(*, tenant_id: str, account_id: str, job_id: str) -> None:
KnowledgeFSInitialSourcePreviewJobService.cleanup_content(tenant_id=tenant_id, account_id=account_id, job_id=job_id)
__all__ = ["cleanup_knowledge_fs_initial_source_preview", "run_knowledge_fs_initial_source_preview"]
@@ -0,0 +1,136 @@
"""Durable follow-up that imports the first Source after Space provisioning."""
from __future__ import annotations
from celery import shared_task
from pydantic import TypeAdapter
from services.knowledge_fs.initial_source_import import (
KnowledgeFSInitialSourceNotReadyError,
start_initial_source_import,
start_initial_website_source_import,
)
from services.knowledge_fs.product_dto import (
KnowledgeFSInitialSourcePayload,
KnowledgeFSInitialWebsiteSourcePayload,
)
from services.knowledge_fs.product_remote import (
KnowledgeFSProductRemoteError,
KnowledgeFSProductRequestRejectedError,
KnowledgeFSProductResourceNotFoundError,
)
_INITIAL_SOURCE_ADAPTER: TypeAdapter[KnowledgeFSInitialSourcePayload] = TypeAdapter(KnowledgeFSInitialSourcePayload)
def _run_initial_source_task(
task,
*,
tenant_id: str,
account_id: str,
control_space_id: str,
operation_id: str,
payload: dict[str, object],
workflow_id: str | None,
) -> str:
try:
return start_initial_source_import(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
operation_id=operation_id,
payload=_INITIAL_SOURCE_ADAPTER.validate_python(payload),
workflow_id=workflow_id,
)
except KnowledgeFSInitialSourceNotReadyError as exc:
if exc.workflow_id is not None:
raise task.retry(
exc=exc,
kwargs={
"tenant_id": tenant_id,
"account_id": account_id,
"control_space_id": control_space_id,
"operation_id": operation_id,
"payload": payload,
"workflow_id": exc.workflow_id,
},
) from exc
raise task.retry(exc=exc) from exc
except KnowledgeFSProductResourceNotFoundError:
raise
except KnowledgeFSProductRequestRejectedError as exc:
if exc.status_code == 429:
raise task.retry(exc=exc) from exc
raise
except KnowledgeFSProductRemoteError as exc:
raise task.retry(exc=exc) from exc
@shared_task(bind=True, queue="knowledge_fs_lifecycle", max_retries=180, default_retry_delay=2)
def import_initial_source(
self,
*,
tenant_id: str,
account_id: str,
control_space_id: str,
operation_id: str,
payload: dict[str, object],
workflow_id: str | None = None,
) -> str:
return _run_initial_source_task(
self,
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
operation_id=operation_id,
payload=payload,
workflow_id=workflow_id,
)
@shared_task(bind=True, queue="knowledge_fs_lifecycle", max_retries=180, default_retry_delay=2)
def import_initial_website_source(
self,
*,
tenant_id: str,
account_id: str,
control_space_id: str,
operation_id: str,
payload: dict[str, object],
workflow_id: str | None = None,
) -> str:
"""Compatibility task for already-enqueued website-only messages."""
try:
return start_initial_website_source_import(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
operation_id=operation_id,
payload=KnowledgeFSInitialWebsiteSourcePayload.model_validate(payload),
workflow_id=workflow_id,
)
except KnowledgeFSInitialSourceNotReadyError as exc:
if exc.workflow_id is not None:
raise self.retry(
exc=exc,
kwargs={
"tenant_id": tenant_id,
"account_id": account_id,
"control_space_id": control_space_id,
"operation_id": operation_id,
"payload": payload,
"workflow_id": exc.workflow_id,
},
) from exc
raise self.retry(exc=exc) from exc
except KnowledgeFSProductResourceNotFoundError:
raise
except KnowledgeFSProductRemoteError as exc:
raise self.retry(exc=exc) from exc
__all__ = [
"import_initial_source",
"import_initial_website_source",
]
@@ -0,0 +1,72 @@
"""Gated poller for KnowledgeFS lifecycle outbox delivery and reconciliation."""
from __future__ import annotations
import socket
from datetime import timedelta
from typing import TypedDict
from celery import shared_task
from configs import dify_config
from core.db.session_factory import session_factory
from libs.datetime_utils import naive_utc_now
from services.knowledge_fs.lifecycle_readiness import get_configured_knowledge_fs_lifecycle_worker_readiness
from services.knowledge_fs.lifecycle_saga import KnowledgeFSLifecycleSagaRunner
from services.knowledge_fs.orphan_reconciler import KnowledgeFSOrphanReconciler
from services.knowledge_fs.remote_registry import get_knowledge_fs_lifecycle_remote
from services.knowledge_fs.runtime import get_knowledge_fs_runtime
from services.knowledge_fs.staged_upload_service import KnowledgeFSStagedUploadService
class KnowledgeFSLifecycleWorkerResult(TypedDict):
status: str
dispatched: int
completed: int
reconciled: int
@shared_task(queue="knowledge_fs_lifecycle")
def run_knowledge_fs_lifecycle_worker() -> KnowledgeFSLifecycleWorkerResult:
readiness = get_configured_knowledge_fs_lifecycle_worker_readiness()
if not readiness.ready:
return {"status": "disabled", "dispatched": 0, "completed": 0, "reconciled": 0}
remote = get_knowledge_fs_lifecycle_remote()
session_maker = session_factory.get_session_maker()
runner = KnowledgeFSLifecycleSagaRunner(session_maker, remote)
worker_id = f"{socket.gethostname()}:{run_knowledge_fs_lifecycle_worker.request.id or 'manual'}"
dispatched = 0
completed = 0
for _ in range(dify_config.KNOWLEDGE_FS_LIFECYCLE_BATCH_SIZE):
result = runner.dispatch_one(
worker_id=worker_id,
now=naive_utc_now(),
lease_duration=timedelta(seconds=dify_config.KNOWLEDGE_FS_LIFECYCLE_LEASE_SECONDS),
product_enabled=dify_config.KNOWLEDGE_FS_ENABLED,
)
if not result.claimed:
break
dispatched += 1
completed += result.completed
report = KnowledgeFSOrphanReconciler(session_maker, remote).reconcile(
limit=dify_config.KNOWLEDGE_FS_LIFECYCLE_BATCH_SIZE,
apply_repairs=True,
)
reconciled = len(report.repaired_control_space_ids) + len(report.cleanup_control_space_ids)
return {"status": "ok", "dispatched": dispatched, "completed": completed, "reconciled": reconciled}
@shared_task(queue="knowledge_fs_lifecycle")
def cleanup_knowledge_fs_staged_uploads() -> int:
readiness = get_configured_knowledge_fs_lifecycle_worker_readiness()
if not readiness.ready:
return 0
session_maker = session_factory.get_session_maker()
runtime = get_knowledge_fs_runtime(session_maker)
return KnowledgeFSStagedUploadService(session_maker, facade=runtime.facade).cleanup_expired(
limit=dify_config.KNOWLEDGE_FS_LIFECYCLE_BATCH_SIZE
)
__all__ = ["cleanup_knowledge_fs_staged_uploads", "run_knowledge_fs_lifecycle_worker"]
@@ -0,0 +1,178 @@
"""Durable reconciliation for Add source imports submitted from preview."""
from __future__ import annotations
from celery import shared_task
from core.db.session_factory import session_factory
from services.knowledge_fs.product_dto import (
KnowledgeFSDeferredSyncPolicyPayload,
KnowledgeFSSourceSyncPolicyPayload,
KnowledgeFSSourceUpdatePayload,
)
from services.knowledge_fs.product_remote import (
KnowledgeFSProductRemoteError,
KnowledgeFSProductRequestRejectedError,
KnowledgeFSProductResourceNotFoundError,
)
from services.knowledge_fs.runtime import get_knowledge_fs_runtime
_ACTIVE_STATES = {"queued", "running", "crawling", "importing", "syncing"}
_ASYNC_IMPORT_KINDS = {
"crawl-preview-selection",
"website-crawl-import",
"online-document-import",
"online-drive-import",
}
_PENDING_IMPORT_KEY = "pendingImport"
class KnowledgeFSSourceImportNotReadyError(RuntimeError):
pass
def finalize_source_import_once(
*, tenant_id: str, account_id: str, control_space_id: str, source_id: str, workflow_id: str
) -> str:
facade = get_knowledge_fs_runtime(session_factory.get_session_maker()).facade
workflow = facade.get_source_workflow(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
run_id=workflow_id,
)
if workflow.state in _ACTIVE_STATES:
raise KnowledgeFSSourceImportNotReadyError("KnowledgeFS Source import is still running")
source = facade.get_source(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
)
pending = _matching_import_marker(source.metadata.get(_PENDING_IMPORT_KEY), workflow_id)
last_import = _matching_import_marker(source.metadata.get("lastImport"), workflow_id)
completed_import = last_import if last_import is not None and last_import.get("state") == "completed" else None
if pending is None and last_import is None:
return workflow_id
if workflow.state != "completed":
if pending is None:
return workflow_id
# updateSource applies a metadata merge patch, so omission preserves the old marker.
# An explicit null is the tombstone consumed by Dify/UI readers.
failure = {
"errorCode": workflow.last_error_code,
"errorMessage": workflow.failure.message if workflow.failure is not None else None,
"kind": pending.get("kind"),
"previewWorkflowId": pending.get("previewWorkflowId"),
"state": workflow.state,
"syncPolicy": pending.get("syncPolicy"),
"workflowId": workflow.id,
}
facade.update_source(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
payload=KnowledgeFSSourceUpdatePayload(
expectedVersion=source.version,
metadata={_PENDING_IMPORT_KEY: None, "lastImport": failure, "preview": False},
status="error",
),
)
return workflow_id
import_metadata = completed_import or pending or last_import
if import_metadata is None:
return workflow_id
if completed_import is None:
completion = {
"kind": import_metadata.get("kind"),
**(
{"previewWorkflowId": import_metadata.get("previewWorkflowId")}
if import_metadata.get("previewWorkflowId") is not None
else {}
),
"state": "completed",
"syncPolicy": import_metadata.get("syncPolicy"),
"workflowId": workflow.id,
}
source = facade.update_source(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
payload=KnowledgeFSSourceUpdatePayload(
expectedVersion=source.version,
metadata={_PENDING_IMPORT_KEY: None, "lastImport": completion, "preview": False},
status="active",
),
)
import_metadata = completion
desired_policy = KnowledgeFSDeferredSyncPolicyPayload.model_validate(import_metadata.get("syncPolicy"))
try:
current_policy = facade.get_source_sync_policy(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
)
expected_revision = current_policy.revision
except KnowledgeFSProductResourceNotFoundError:
expected_revision = 0
try:
facade.update_source_sync_policy(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
payload=KnowledgeFSSourceSyncPolicyPayload(
enabled=desired_policy.enabled,
mode=desired_policy.mode,
customIntervalSeconds=desired_policy.custom_interval_seconds,
expectedRevision=expected_revision,
expectedSourceVersion=source.version,
),
)
except KnowledgeFSProductRequestRejectedError as exc:
# A website selection replacement can still be draining its child document deletions after
# the parent workflow completes. KnowledgeFS reports that temporary policy-write fence as 400.
if exc.status_code != 400 or import_metadata.get("kind") != "website-crawl-import":
raise
raise KnowledgeFSSourceImportNotReadyError("Website source import cleanup is still running") from exc
return workflow_id
def _matching_import_marker(value: object, workflow_id: str) -> dict[str, object] | None:
if (
not isinstance(value, dict)
or value.get("kind") not in _ASYNC_IMPORT_KINDS
or value.get("workflowId") != workflow_id
):
return None
return value
@shared_task(bind=True, queue="knowledge_fs_lifecycle", max_retries=300, default_retry_delay=2)
def finalize_source_import(
self, *, tenant_id: str, account_id: str, control_space_id: str, source_id: str, workflow_id: str
) -> str:
try:
return finalize_source_import_once(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
source_id=source_id,
workflow_id=workflow_id,
)
except (KnowledgeFSSourceImportNotReadyError, KnowledgeFSProductRemoteError) as exc:
raise self.retry(exc=exc) from exc
except KnowledgeFSProductRequestRejectedError as exc:
if exc.status_code != 409:
raise
raise self.retry(exc=exc) from exc
__all__ = ["finalize_source_import", "finalize_source_import_once"]
@@ -0,0 +1,150 @@
"""Dedicated-queue execution for legacy Dataset upgrades."""
from __future__ import annotations
import logging
from celery import shared_task
from core.db.session_factory import session_factory
from services.dataset_knowledge_fs_upgrade_file_lease import cleanup_deferred_upgrade_files
from services.dataset_knowledge_fs_upgrade_service import (
UPGRADE_CHECKPOINT_TIME_LIMIT_SECONDS,
KnowledgeFSUpgradeBusyError,
KnowledgeFSUpgradeDocumentReconciler,
KnowledgeFSUpgradeNotReadyError,
KnowledgeFSUpgradeRunner,
KnowledgeFSUpgradeSnapshotService,
)
KNOWLEDGE_FS_UPGRADE_QUEUE = "knowledge_fs_upgrade"
logger = logging.getLogger(__name__)
@shared_task(
bind=True,
queue=KNOWLEDGE_FS_UPGRADE_QUEUE,
max_retries=360,
default_retry_delay=5,
acks_late=True,
reject_on_worker_lost=True,
soft_time_limit=UPGRADE_CHECKPOINT_TIME_LIMIT_SECONDS - 30,
time_limit=UPGRADE_CHECKPOINT_TIME_LIMIT_SECONDS,
)
def run_knowledge_fs_upgrade(self, *, job_id: str) -> None:
"""Run one checkpoint and enqueue the next only after it is committed."""
runner = KnowledgeFSUpgradeRunner(session_factory.get_session_maker())
try:
has_more = runner.run_next(job_id=job_id, celery_task_id=self.request.id)
except KnowledgeFSUpgradeBusyError as error:
# A redelivery can precede expiry of the lost child's execution window.
# It must never fail or steal the currently running checkpoint.
raise self.retry(exc=error, countdown=30) from error
except KnowledgeFSUpgradeNotReadyError as error:
if self.request.retries >= self.max_retries:
runner.fail(job_id=job_id, celery_task_id=self.request.id, error=error)
logger.exception(
"KnowledgeFS Dataset upgrade exhausted provisioning retries",
extra={"upgrade_job_id": job_id},
)
raise
runner.release_for_retry(job_id=job_id, celery_task_id=self.request.id)
raise self.retry(exc=error) from error
except Exception as error:
runner.fail(job_id=job_id, celery_task_id=self.request.id, error=error)
logger.exception("KnowledgeFS Dataset upgrade failed", extra={"upgrade_job_id": job_id})
raise
if has_more is None:
return
if has_more:
_dispatch_next_checkpoint(runner, job_id=job_id, celery_task_id=self.request.id)
else:
_dispatch_reconciliations(job_id=job_id)
def _dispatch_next_checkpoint(runner: KnowledgeFSUpgradeRunner, *, job_id: str, celery_task_id: str | None) -> None:
from services.knowledge.datasets.upgrades import enqueue_upgrade_job
tenant_id = runner.release_for_dispatch(job_id=job_id, celery_task_id=celery_task_id)
if tenant_id is None:
return
enqueue_upgrade_job(KnowledgeFSUpgradeSnapshotService(session_factory.get_session_maker()), tenant_id, job_id)
@shared_task(
bind=True,
queue=KNOWLEDGE_FS_UPGRADE_QUEUE,
acks_late=True,
reject_on_worker_lost=True,
soft_time_limit=UPGRADE_CHECKPOINT_TIME_LIMIT_SECONDS - 30,
time_limit=UPGRADE_CHECKPOINT_TIME_LIMIT_SECONDS,
)
def reconcile_knowledge_fs_upgrade_documents(self, *, job_id: str) -> None:
"""Apply document checkpoints under a recoverable lease, independent of parent success."""
reconciler = KnowledgeFSUpgradeDocumentReconciler(session_factory.get_session_maker())
task_id = self.request.id
if not reconciler.start_delivery(job_id=job_id, task_id=task_id):
return
try:
reconciler.reconcile(job_id=job_id)
except Exception:
logger.warning(
"KnowledgeFS Dataset upgrade document reconciliation is not ready",
extra={"upgrade_job_id": job_id},
exc_info=True,
)
finally:
# Beat retries unfinished checkpoints, including failures to persist this release.
reconciler.finish_delivery(job_id=job_id, task_id=task_id)
def _dispatch_reconciliations(*, job_id: str | None = None) -> int:
reconciler = KnowledgeFSUpgradeDocumentReconciler(session_factory.get_session_maker())
deliveries = reconciler.claim_deliveries(job_id=job_id)
for tenant_id, pending_job_id, task_id in deliveries:
try:
reconcile_knowledge_fs_upgrade_documents.apply_async(kwargs={"job_id": pending_job_id}, task_id=task_id)
except Exception:
# Retain the lease after ambiguous publication: a delivered message may already be
# executing. Beat reclaims it after the bounded worker must have stopped.
logger.exception(
"KnowledgeFS upgrade reconciliation dispatch failed tenant_id=%s job_id=%s",
tenant_id,
pending_job_id,
)
return len(deliveries)
@shared_task(queue=KNOWLEDGE_FS_UPGRADE_QUEUE)
def cleanup_deferred_knowledge_fs_upgrade_files() -> int:
"""Delete orphaned source files after abandoned upgrade leases expire."""
return cleanup_deferred_upgrade_files(session_factory.get_session_maker())
@shared_task(queue=KNOWLEDGE_FS_UPGRADE_QUEUE)
def recover_stalled_knowledge_fs_upgrades() -> int:
"""Redispatch abandoned checkpoints and publisher claims from durable state."""
from services.knowledge.datasets.upgrades import enqueue_upgrade_job
snapshots = KnowledgeFSUpgradeSnapshotService(session_factory.get_session_maker())
recovered = snapshots.recover_stalled_jobs()
for tenant_id, job_id in recovered:
try:
enqueue_upgrade_job(snapshots, tenant_id, job_id)
logger.info("Recovered KnowledgeFS upgrade tenant_id=%s job_id=%s", tenant_id, job_id)
except Exception:
# The next sweep recovers this unclaimed job even if the broker is down.
logger.exception("KnowledgeFS upgrade recovery dispatch failed tenant_id=%s job_id=%s", tenant_id, job_id)
return len(recovered) + _dispatch_reconciliations()
__all__ = [
"KNOWLEDGE_FS_UPGRADE_QUEUE",
"cleanup_deferred_knowledge_fs_upgrade_files",
"reconcile_knowledge_fs_upgrade_documents",
"recover_stalled_knowledge_fs_upgrades",
"run_knowledge_fs_upgrade",
]
@@ -0,0 +1,84 @@
import logging
import time
import click
from celery import shared_task
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_deletion_success_task(to: str, language: str = "en-US"):
"""
Send account deletion success email with internationalization support.
Args:
to: Recipient email address
language: Language code for email localization
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start send account deletion success email to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.ACCOUNT_DELETION_SUCCESS,
language_code=language,
to=to,
template_context={
"to": to,
"email": to,
},
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send account deletion success email to {to}: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send account deletion success email to %s failed", to)
@shared_task(queue="mail")
def send_account_deletion_verification_code(to: str, code: str, language: str = "en-US"):
"""
Send account deletion verification code email with internationalization support.
Args:
to: Recipient email address
code: Verification code
language: Language code for email localization
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start send account deletion verification code email to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.ACCOUNT_DELETION_VERIFICATION,
language_code=language,
to=to,
template_context={
"to": to,
"code": code,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send account deletion verification code email to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("Send account deletion verification code email to %s failed", to)
@@ -0,0 +1,80 @@
import logging
import time
import click
from celery import shared_task
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_change_mail_task(language: str, to: str, code: str, phase: str):
"""
Send change email notification with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
code: Email verification code
phase: Change email phase ('old_email' or 'new_email')
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start change email mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_change_email(
language_code=language,
to=to,
code=code,
phase=phase,
)
end_at = time.perf_counter()
logger.info(click.style(f"Send change email mail to {to} succeeded: latency: {end_at - start_at}", fg="green"))
except Exception:
logger.exception("Send change email mail to %s failed", to)
@shared_task(queue="mail")
def send_change_mail_completed_notification_task(language: str, to: str):
"""
Send change email completed notification with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start change email completed notify mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.CHANGE_EMAIL_COMPLETED,
language_code=language,
to=to,
template_context={
"to": to,
"email": to,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send change email completed mail to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("Send change email completed mail to %s failed", to)
@@ -0,0 +1,46 @@
import logging
import time
import click
from celery import shared_task
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_email_code_login_mail_task(language: str, to: str, code: str):
"""
Send email code login email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
code: Email verification code
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start email code login mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.EMAIL_CODE_LOGIN,
language_code=language,
to=to,
template_context={
"to": to,
"code": code,
},
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send email code login mail to {to} succeeded: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send email code login mail to %s failed", to)
@@ -0,0 +1,197 @@
"""Celery entrypoints for delivering persisted human input forms.
The generic form-delivery task must stay independent from email availability so
non-email providers can run even when mail is not configured. The legacy email
task keeps its historical mail and feature gates for callers that still need
email-only semantics. The generic task only checks email availability after
loading persisted delivery contexts and only when an email context is present.
"""
import logging
import time
from collections.abc import Sequence
import click
from celery import shared_task
from sqlalchemy.orm import Session, sessionmaker
from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext
from core.workflow.human_input_adapter import DeliveryMethodType
from extensions.ext_database import db
from extensions.ext_mail import mail
from graphon.runtime import RuntimeState, VariablePool
from models.human_input import HumanInputForm
from repositories.factory import DifyAPIRepositoryFactory
from services.feature_service import FeatureService
from services.human_input_form_delivery_provider import (
HumanInputFormDeliveryContext,
HumanInputFormDeliveryDispatcher,
HumanInputFormDeliveryProviderRegistry,
)
logger = logging.getLogger(__name__)
FORM_DELIVERY_METHOD_TYPES = (DeliveryMethodType.EMAIL, DeliveryMethodType.IM)
def _has_email_context(contexts: Sequence[HumanInputFormDeliveryContext]) -> bool:
return any(context.delivery_method_type == DeliveryMethodType.EMAIL for context in contexts)
def _load_variable_pool(workflow_run_id: str | None) -> VariablePool | None:
if not workflow_run_id:
return None
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory)
pause_entity = workflow_run_repo.get_workflow_pause(workflow_run_id)
if pause_entity is None:
logger.info("No pause state found for workflow run %s", workflow_run_id)
return None
try:
resumption_context = WorkflowResumptionContext.loads(pause_entity.get_state().decode())
except Exception:
logger.exception("Failed to load resumption context for workflow run %s", workflow_run_id)
return None
graph_runtime_state = RuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
return graph_runtime_state.variable_pool
def _open_session(session_factory: sessionmaker | Session | None):
if session_factory is None:
return Session(db.engine)
if isinstance(session_factory, Session):
return session_factory
return session_factory()
def _filter_unavailable_email_contexts(
*,
contexts: Sequence[HumanInputFormDeliveryContext],
tenant_id: str,
form_id: str,
) -> tuple[HumanInputFormDeliveryContext, ...]:
contexts_tuple = tuple(contexts)
if not _has_email_context(contexts_tuple):
return contexts_tuple
email_delivery_enabled = False
if mail.is_inited():
try:
features = FeatureService.get_features(tenant_id, exclude_vector_space=True)
email_delivery_enabled = features.human_input_email_delivery_enabled
except Exception:
logger.exception(
"Failed to check human input email delivery availability; skipping email contexts, "
"tenant=%s, form_id=%s",
tenant_id,
form_id,
)
if email_delivery_enabled:
return contexts_tuple
return tuple(context for context in contexts_tuple if context.delivery_method_type != DeliveryMethodType.EMAIL)
def _is_email_delivery_enabled(*, tenant_id: str, form_id: str) -> bool:
features = FeatureService.get_features(tenant_id, exclude_vector_space=True)
email_delivery_enabled = features.human_input_email_delivery_enabled
if not email_delivery_enabled:
logger.info(
"Human input email delivery is not available for tenant=%s, form_id=%s",
tenant_id,
form_id,
)
return email_delivery_enabled
def _load_and_dispatch_form_delivery(
*,
form_id: str,
node_title: str | None,
session_factory,
delivery_method_types: Sequence[DeliveryMethodType] | None,
require_mail_inited: bool,
require_email_feature: bool,
filter_unavailable_email: bool,
log_label: str,
) -> None:
if require_mail_inited and not mail.is_inited():
return
logger.info(click.style(f"Start human input {log_label} delivery for form {form_id}", fg="green"))
start_at = time.perf_counter()
try:
with _open_session(session_factory) as session:
form = session.get(HumanInputForm, form_id)
if form is None:
logger.warning("Human input form not found, form_id=%s", form_id)
return
if require_email_feature and not _is_email_delivery_enabled(tenant_id=form.tenant_id, form_id=form_id):
return
variable_pool = _load_variable_pool(form.workflow_run_id)
registry = HumanInputFormDeliveryProviderRegistry.default(mail_client=mail)
dispatcher = HumanInputFormDeliveryDispatcher(registry=registry)
contexts = dispatcher.load_form_contexts(
session=session,
form=form,
variable_pool=variable_pool,
delivery_method_types=delivery_method_types,
)
if filter_unavailable_email:
contexts = _filter_unavailable_email_contexts(
contexts=contexts,
tenant_id=form.tenant_id,
form_id=form_id,
)
dispatcher.dispatch_contexts(contexts)
end_at = time.perf_counter()
logger.info(
click.style(
f"Human input {log_label} delivery succeeded for form {form_id}: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception(
"Dispatch human input %s delivery failed, form_id=%s, node_title=%s",
log_label,
form_id,
node_title,
)
@shared_task(queue="mail")
def dispatch_human_input_form_delivery_task(form_id: str, node_title: str | None = None, session_factory=None):
_load_and_dispatch_form_delivery(
form_id=form_id,
node_title=node_title,
session_factory=session_factory,
delivery_method_types=FORM_DELIVERY_METHOD_TYPES,
require_mail_inited=False,
require_email_feature=False,
filter_unavailable_email=True,
log_label="form",
)
@shared_task(queue="mail")
def dispatch_human_input_email_task(form_id: str, node_title: str | None = None, session_factory=None):
_load_and_dispatch_form_delivery(
form_id=form_id,
node_title=node_title,
session_factory=session_factory,
delivery_method_types=(DeliveryMethodType.EMAIL,),
require_mail_inited=True,
require_email_feature=True,
filter_unavailable_email=False,
log_label="email",
)
@@ -0,0 +1,72 @@
import logging
import time
from collections.abc import Mapping
from typing import Any, override
import click
from celery import shared_task
from flask import render_template_string
from jinja2.runtime import Context
from jinja2.sandbox import ImmutableSandboxedEnvironment
from configs import dify_config
from configs.feature import TemplateMode
from extensions.ext_mail import mail
from libs.email_i18n import get_email_i18n_service
from services.entities.mail_entities import InnerMailMessage
logger = logging.getLogger(__name__)
class SandboxedEnvironment(ImmutableSandboxedEnvironment):
def __init__(self, timeout: int, *args: Any, **kwargs: Any):
self._timeout_time = time.time() + timeout
super().__init__(*args, **kwargs)
@override
def call(self, context: Context, obj: Any, *args: Any, **kwargs: Any) -> Any:
if time.time() > self._timeout_time:
raise TimeoutError("Template rendering timeout")
return super().call(context, obj, *args, **kwargs)
def _render_template_with_strategy(body: str, substitutions: Mapping[str, Any]) -> str:
mode = dify_config.MAIL_TEMPLATING_MODE
timeout = dify_config.MAIL_TEMPLATING_TIMEOUT
if mode == TemplateMode.UNSAFE:
return render_template_string(body, **substitutions)
if mode == TemplateMode.SANDBOX:
tmpl = SandboxedEnvironment(timeout=timeout).from_string(body)
return tmpl.render(substitutions)
if mode == TemplateMode.DISABLED:
return body
raise ValueError(f"Unsupported mail templating mode: {mode}")
@shared_task(queue="mail")
def send_inner_email_task(to: list[str], subject: str, body: str, substitutions: Mapping[str, Any]):
if not mail.is_inited():
return
logger.info(click.style(f"Start enterprise mail to {to} with subject {subject}", fg="green"))
start_at = time.perf_counter()
try:
html_content = _render_template_with_strategy(body, substitutions)
email_service = get_email_i18n_service()
email_service.send_raw_email(to=to, subject=subject, html_content=html_content)
end_at = time.perf_counter()
logger.info(click.style(f"Send enterprise mail to {to} succeeded: latency: {end_at - start_at}", fg="green"))
except Exception:
logger.exception("Send enterprise mail to %s failed", to)
def enqueue_inner_mail(message: InnerMailMessage) -> None:
send_inner_email_task.delay(
to=list(message.recipients),
subject=message.subject,
body=message.body,
substitutions=message.substitutions or {},
)
@@ -0,0 +1,50 @@
import logging
import time
import click
from celery import shared_task
from configs import dify_config
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_invite_member_mail_task(language: str, to: str, token: str, inviter_name: str, workspace_name: str):
"""
Send invite member email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
token: Invitation token
inviter_name: Name of the person sending the invitation
workspace_name: Name of the workspace
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start send invite member mail to {to} in workspace {workspace_name}", fg="green"))
start_at = time.perf_counter()
try:
url = f"{dify_config.CONSOLE_WEB_URL}/activate?token={token}"
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.INVITE_MEMBER,
language_code=language,
to=to,
template_context={
"to": to,
"inviter_name": inviter_name,
"workspace_name": workspace_name,
"url": url,
},
)
end_at = time.perf_counter()
logger.info(click.style(f"Send invite member mail to {to} succeeded: latency: {end_at - start_at}", fg="green"))
except Exception:
logger.exception("Send invite member mail to %s failed", to)
@@ -0,0 +1,131 @@
import logging
import time
import click
from celery import shared_task
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_owner_transfer_confirm_task(language: str, to: str, code: str, workspace: str):
"""
Send owner transfer confirmation email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
code: Verification code
workspace: Workspace name
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start owner transfer confirm mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.OWNER_TRANSFER_CONFIRM,
language_code=language,
to=to,
template_context={
"to": to,
"code": code,
"WorkspaceName": workspace,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send owner transfer confirm mail to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("owner transfer confirm email mail to %s failed", to)
@shared_task(queue="mail")
def send_old_owner_transfer_notify_email_task(language: str, to: str, workspace: str, new_owner_email: str):
"""
Send old owner transfer notification email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
workspace: Workspace name
new_owner_email: New owner email address
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start old owner transfer notify mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.OWNER_TRANSFER_OLD_NOTIFY,
language_code=language,
to=to,
template_context={
"to": to,
"WorkspaceName": workspace,
"NewOwnerEmail": new_owner_email,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send old owner transfer notify mail to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("old owner transfer notify email mail to %s failed", to)
@shared_task(queue="mail")
def send_new_owner_transfer_notify_email_task(language: str, to: str, workspace: str):
"""
Send new owner transfer notification email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
workspace: Workspace name
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start new owner transfer notify mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.OWNER_TRANSFER_NEW_NOTIFY,
language_code=language,
to=to,
template_context={
"to": to,
"WorkspaceName": workspace,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send new owner transfer notify mail to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("new owner transfer notify email mail to %s failed", to)
@@ -0,0 +1,87 @@
import logging
import time
import click
from celery import shared_task
from configs import dify_config
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_email_register_mail_task(language: str, to: str, code: str) -> None:
"""
Send email register email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
code: Email register code
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start email register mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.EMAIL_REGISTER,
language_code=language,
to=to,
template_context={
"to": to,
"code": code,
},
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send email register mail to {to} succeeded: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send email register mail to %s failed", to)
@shared_task(queue="mail")
def send_email_register_mail_task_when_account_exist(language: str, to: str, account_name: str) -> None:
"""
Send email register email with internationalization support when account exist.
Args:
language: Language code for email localization
to: Recipient email address
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start email register mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
login_url = f"{dify_config.CONSOLE_WEB_URL}/signin"
reset_password_url = f"{dify_config.CONSOLE_WEB_URL}/reset-password"
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.EMAIL_REGISTER_WHEN_ACCOUNT_EXIST,
language_code=language,
to=to,
template_context={
"to": to,
"login_url": login_url,
"reset_password_url": reset_password_url,
"account_name": account_name,
},
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send email register mail to {to} succeeded: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send email register mail to %s failed", to)
@@ -0,0 +1,91 @@
import logging
import time
import click
from celery import shared_task
from configs import dify_config
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_reset_password_mail_task(language: str, to: str, code: str):
"""
Send reset password email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
code: Reset password code
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start password reset mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.RESET_PASSWORD,
language_code=language,
to=to,
template_context={
"to": to,
"code": code,
},
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send password reset mail to {to} succeeded: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send password reset mail to %s failed", to)
@shared_task(queue="mail")
def send_reset_password_mail_task_when_account_not_exist(language: str, to: str, is_allow_register: bool) -> None:
"""
Send reset password email with internationalization support when account not exist.
Args:
language: Language code for email localization
to: Recipient email address
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start password reset mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
if is_allow_register:
sign_up_url = f"{dify_config.CONSOLE_WEB_URL}/signup"
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.RESET_PASSWORD_WHEN_ACCOUNT_NOT_EXIST,
language_code=language,
to=to,
template_context={
"to": to,
"sign_up_url": sign_up_url,
},
)
else:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.RESET_PASSWORD_WHEN_ACCOUNT_NOT_EXIST_NO_REGISTER,
language_code=language,
to=to,
)
end_at = time.perf_counter()
logger.info(
click.style(f"Send password reset mail to {to} succeeded: latency: {end_at - start_at}", fg="green")
)
except Exception:
logger.exception("Send password reset mail to %s failed", to)
@@ -0,0 +1,65 @@
import logging
import time
import click
from celery import shared_task
from extensions.ext_mail import mail
from libs.email_i18n import EmailType, get_email_i18n_service
logger = logging.getLogger(__name__)
@shared_task(queue="mail")
def send_workflow_comment_mention_email_task(
language: str,
to: str,
mentioned_name: str,
commenter_name: str,
app_name: str,
comment_content: str,
app_url: str,
):
"""
Send workflow comment mention email with internationalization support.
Args:
language: Language code for email localization
to: Recipient email address
mentioned_name: Name of the mentioned user
commenter_name: Name of the comment author
app_name: Name of the app where the comment was made
comment_content: Comment content excerpt
app_url: Link to the app workflow page
"""
if not mail.is_inited():
return
logger.info(click.style(f"Start workflow comment mention mail to {to}", fg="green"))
start_at = time.perf_counter()
try:
email_service = get_email_i18n_service()
email_service.send_email(
email_type=EmailType.WORKFLOW_COMMENT_MENTION,
language_code=language,
to=to,
template_context={
"to": to,
"mentioned_name": mentioned_name,
"commenter_name": commenter_name,
"app_name": app_name,
"comment_content": comment_content,
"app_url": app_url,
},
)
end_at = time.perf_counter()
logger.info(
click.style(
f"Send workflow comment mention mail to {to} succeeded: latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("workflow comment mention email to %s failed", to)
@@ -0,0 +1,30 @@
"""Retired entry point of the previous trace pipeline.
Producers from before an upgrade may still enqueue this task. Its payload uses
the previous record format, so the message is dropped and its payload deleted;
only old workers can export it. Keep new workers off the old queue until it has
drained. The new pipeline's sweeper leaves legacy payloads alone.
"""
import logging
import re
from celery import shared_task
from extensions.ext_storage import storage
logger = logging.getLogger(__name__)
_PAYLOAD_SEGMENT = re.compile(r"[A-Za-z0-9-]+")
@shared_task(queue="ops_trace")
def process_trace_tasks(file_info: dict[str, object]) -> None:
app_id, file_id = file_info.get("app_id"), file_info.get("file_id")
if isinstance(app_id, str) and isinstance(file_id, str):
if _PAYLOAD_SEGMENT.fullmatch(app_id) and _PAYLOAD_SEGMENT.fullmatch(file_id):
try:
storage.delete(f"ops_trace/{app_id}/{file_id}.json")
except Exception:
logger.warning("Legacy trace payload cleanup failed: app_id=%s", app_id, exc_info=True)
logger.info("Dropped a trace task enqueued before the trace pipeline upgrade: app_id=%s", app_id)
@@ -0,0 +1,285 @@
import json
import logging
import operator
import click
from celery import shared_task
from pydantic import TypeAdapter
from core.helper.marketplace import batch_fetch_plugin_manifests, get_plugin_pkg_url
from core.plugin.entities.marketplace import MarketplacePluginDeclaration, MarketplacePluginSnapshot
from core.plugin.entities.plugin import PluginInstallation, PluginInstallationSource
from core.plugin.impl.plugin import PluginInstaller
from core.plugin.plugin_service import PluginService
from extensions.ext_redis import redis_client
from models.account import (
TenantPluginAutoUpgradeCategory,
TenantPluginAutoUpgradeMode,
TenantPluginAutoUpgradeStrategySetting,
)
logger = logging.getLogger(__name__)
PluginCategory = TenantPluginAutoUpgradeCategory
RETRY_TIMES_OF_ONE_PLUGIN_IN_ONE_TENANT = 3
CACHE_REDIS_KEY_PREFIX = "plugin_autoupgrade_check_task:cached_plugin_snapshot:"
CACHE_REDIS_TTL = 60 * 60 # 1 hour
# A cached miss is stored as JSON null, so None has to stay a valid payload.
_CACHED_MANIFEST_ADAPTER = TypeAdapter(MarketplacePluginSnapshot | None)
def _get_redis_cache_key(plugin_id: str) -> str:
"""Generate Redis cache key for plugin manifest."""
return f"{CACHE_REDIS_KEY_PREFIX}{plugin_id}"
def _get_cached_manifest(plugin_id: str) -> MarketplacePluginSnapshot | None | bool:
"""
Get cached plugin manifest from Redis.
Returns:
- MarketplacePluginSnapshot: if found in cache
- None: if cached as not found (marketplace returned no result)
- False: if not in cache at all
"""
try:
key = _get_redis_cache_key(plugin_id)
cached_data = redis_client.get(key)
if cached_data is None:
return False
return _CACHED_MANIFEST_ADAPTER.validate_json(cached_data)
except Exception:
logger.exception("Failed to get cached manifest for plugin %s", plugin_id)
return False
def _set_cached_manifest(plugin_id: str, snapshot: MarketplacePluginSnapshot | None) -> None:
"""
Cache a plugin snapshot in Redis, or record that the marketplace has no such plugin.
Caching misses as well as hits keeps the fallback cheap: a plugin that the marketplace
does not know about is looked up once per TTL instead of once per check cycle.
"""
try:
key = _get_redis_cache_key(plugin_id)
if snapshot is None:
redis_client.setex(key, CACHE_REDIS_TTL, json.dumps(None))
else:
redis_client.setex(key, CACHE_REDIS_TTL, snapshot.model_dump_json())
except Exception:
# If Redis fails, continue without caching
logger.exception("Failed to set cached manifest for plugin %s", plugin_id)
def _snapshot_from_declaration(declaration: MarketplacePluginDeclaration) -> MarketplacePluginSnapshot:
"""Adapt a batch-API declaration to the snapshot shape used by the upgrade check."""
return MarketplacePluginSnapshot(
org=declaration.org,
name=declaration.name,
latest_version=declaration.latest_version,
latest_package_identifier=declaration.latest_package_identifier,
latest_package_url=get_plugin_pkg_url(declaration.latest_package_identifier),
)
def marketplace_batch_fetch_plugin_manifests(
plugin_ids_plain_list: list[str],
) -> list[MarketplacePluginSnapshot]:
"""
Fetch plugin manifests, preferring the pre-populated Redis cache.
fetch_global_plugin_manifest() normally warms the cache with the whole marketplace.
When that snapshot is unavailable or incomplete, fall back to the per-plugin batch API
so upgrades still happen instead of being silently skipped.
"""
result: list[MarketplacePluginSnapshot] = []
uncached_plugin_ids: list[str] = []
# Check Redis cache for each plugin
for plugin_id in plugin_ids_plain_list:
cached_result = _get_cached_manifest(plugin_id)
if isinstance(cached_result, MarketplacePluginSnapshot):
result.append(cached_result)
elif cached_result is None:
# Cached as not found in the marketplace; nothing to upgrade to.
continue
else:
uncached_plugin_ids.append(plugin_id)
if not uncached_plugin_ids:
return result
logger.info(
"%d plugin manifests missing from the global snapshot, fetching them from the marketplace",
len(uncached_plugin_ids),
)
try:
declarations = batch_fetch_plugin_manifests(uncached_plugin_ids)
except Exception:
logger.exception(
"failed to fetch plugin manifests from marketplace, skipping %d plugins", len(uncached_plugin_ids)
)
return result
fetched_plugin_ids = set()
for declaration in declarations:
snapshot = _snapshot_from_declaration(declaration)
fetched_plugin_ids.add(declaration.plugin_id)
_set_cached_manifest(declaration.plugin_id, snapshot)
result.append(snapshot)
# Remember which plugins the marketplace does not serve, so we stop asking every cycle.
for plugin_id in uncached_plugin_ids:
if plugin_id not in fetched_plugin_ids:
_set_cached_manifest(plugin_id, None)
return result
def _normalize_category(category: PluginCategory | str | None) -> str | None:
if category is None:
return None
if isinstance(category, PluginCategory):
return category.value
return str(category)
def _plugin_matches_category(plugin: PluginInstallation, category: str | None) -> bool:
"""Return whether an installed plugin should be checked by a category strategy."""
if category is None:
return True
declaration = getattr(plugin, "declaration", None)
plugin_category = getattr(declaration, "category", None)
plugin_category_value = getattr(plugin_category, "value", plugin_category)
return plugin_category_value == category
@shared_task(queue="plugin")
def process_tenant_plugin_autoupgrade_check_task(
tenant_id: str,
strategy_setting: TenantPluginAutoUpgradeStrategySetting,
upgrade_time_of_day: int,
upgrade_mode: TenantPluginAutoUpgradeMode,
exclude_plugins: list[str],
include_plugins: list[str],
category: PluginCategory | str | None = None,
):
try:
manager = PluginInstaller()
category_value = _normalize_category(category)
click.echo(
click.style(
f"Checking upgradable plugin for tenant: {tenant_id}, category: {category_value or 'all'}",
fg="green",
)
)
if strategy_setting == TenantPluginAutoUpgradeStrategySetting.DISABLED:
return
# get plugin_ids to check
plugin_ids: list[tuple[str, str, str]] = [] # plugin_id, version, unique_identifier
click.echo(click.style(f"Upgrade mode: {upgrade_mode}", fg="green"))
if upgrade_mode == TenantPluginAutoUpgradeMode.PARTIAL and include_plugins:
all_plugins = manager.list_plugins(tenant_id)
for plugin in all_plugins:
if (
plugin.source == PluginInstallationSource.Marketplace
and plugin.plugin_id in include_plugins
and _plugin_matches_category(plugin, category_value)
):
plugin_ids.append(
(
plugin.plugin_id,
plugin.version,
plugin.plugin_unique_identifier,
)
)
elif upgrade_mode == TenantPluginAutoUpgradeMode.EXCLUDE:
# get all plugins and remove excluded plugins
all_plugins = manager.list_plugins(tenant_id)
plugin_ids = [
(plugin.plugin_id, plugin.version, plugin.plugin_unique_identifier)
for plugin in all_plugins
if plugin.source == PluginInstallationSource.Marketplace
and plugin.plugin_id not in exclude_plugins
and _plugin_matches_category(plugin, category_value)
]
elif upgrade_mode == TenantPluginAutoUpgradeMode.ALL:
all_plugins = manager.list_plugins(tenant_id)
plugin_ids = [
(plugin.plugin_id, plugin.version, plugin.plugin_unique_identifier)
for plugin in all_plugins
if plugin.source == PluginInstallationSource.Marketplace
and _plugin_matches_category(plugin, category_value)
]
if not plugin_ids:
return
plugin_ids_plain_list = [plugin_id for plugin_id, _, _ in plugin_ids]
manifests = marketplace_batch_fetch_plugin_manifests(plugin_ids_plain_list)
if not manifests:
return
for manifest in manifests:
for plugin_id, version, original_unique_identifier in plugin_ids:
if manifest.plugin_id != plugin_id:
continue
try:
current_version = version
latest_version = manifest.latest_version
def fix_only_checker(latest_version: str, current_version: str):
latest_version_tuple = tuple(int(val) for val in latest_version.split("."))
current_version_tuple = tuple(int(val) for val in current_version.split("."))
if (
latest_version_tuple[0] == current_version_tuple[0]
and latest_version_tuple[1] == current_version_tuple[1]
):
return latest_version_tuple[2] != current_version_tuple[2]
return False
version_checker = {
TenantPluginAutoUpgradeStrategySetting.LATEST: operator.ne,
TenantPluginAutoUpgradeStrategySetting.FIX_ONLY: fix_only_checker,
}
if version_checker[strategy_setting](latest_version, current_version):
# execute upgrade
new_unique_identifier = manifest.latest_package_identifier
click.echo(
click.style(
f"Upgrade plugin: {original_unique_identifier} -> {new_unique_identifier}",
fg="green",
)
)
# Use the service that downloads and uploads the package to the daemon
# first; calling manager.upgrade_plugin directly skips that step and the
# daemon fails because the package never reaches its local bucket.
_ = PluginService.upgrade_plugin_with_marketplace(
tenant_id,
original_unique_identifier,
new_unique_identifier,
)
except Exception as e:
click.echo(click.style(f"Error when upgrading plugin: {e}", fg="red"))
# traceback.print_exc()
break
except Exception as e:
click.echo(click.style(f"Error when checking upgradable plugin: {e}", fg="red"))
# traceback.print_exc()
return
@@ -0,0 +1,205 @@
import contextvars
import logging
import time
import uuid
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import click
from celery import shared_task # type: ignore
from flask import current_app, g
from pydantic import TypeAdapter
from sqlalchemy import select
from sqlalchemy.orm import Session, sessionmaker
from configs import dify_config
from core.app.apps.pipeline.pipeline_generator import PipelineGenerator
from core.app.entities.app_invoke_entities import InvokeFrom, RagPipelineGenerateEntity
from core.app.entities.rag_pipeline_invoke_entities import RagPipelineInvokeEntity
from core.db.session_factory import get_session_maker
from core.rag.pipeline.queue import TenantIsolatedTaskQueue
from core.repositories.factory import DifyCoreRepositoryFactory
from extensions.application_services.data_sources import build_data_source_credentials
from extensions.ext_database import db
from models import Account, Tenant
from models.dataset import Pipeline
from models.enums import WorkflowRunTriggeredFrom
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
from services.file_service import FileService
from services.workflow_run_agg import WorkflowRunAgg
logger = logging.getLogger(__name__)
# Each entry is validated into RagPipelineInvokeEntity inside the worker.
_INVOKE_ENTITIES_ADAPTER = TypeAdapter(list[dict[str, Any]])
@shared_task(queue="priority_pipeline")
def priority_rag_pipeline_run_task(
rag_pipeline_invoke_entities_file_id: str,
tenant_id: str,
):
"""
Async Run rag pipeline task using high priority queue.
:param rag_pipeline_invoke_entities_file_id: File ID containing serialized RAG pipeline invoke entities
:param tenant_id: Tenant ID for the pipeline execution
"""
# run with threading, thread pool size is 10
try:
start_at = time.perf_counter()
rag_pipeline_invoke_entities_content = FileService(db.engine).get_file_content(
rag_pipeline_invoke_entities_file_id
)
rag_pipeline_invoke_entities = _INVOKE_ENTITIES_ADAPTER.validate_json(rag_pipeline_invoke_entities_content)
logger.info("tenant %s received %d rag pipeline invoke entities", tenant_id, len(rag_pipeline_invoke_entities))
# Get Flask app object for thread context
flask_app = current_app._get_current_object() # type: ignore
with ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for rag_pipeline_invoke_entity in rag_pipeline_invoke_entities:
# Submit task to thread pool with Flask app
future = executor.submit(run_single_rag_pipeline_task, rag_pipeline_invoke_entity, flask_app)
futures.append(future)
# Wait for all tasks to complete
for future in futures:
try:
future.result() # This will raise any exceptions that occurred in the thread
except Exception:
logging.exception("Error in pipeline task")
end_at = time.perf_counter()
logging.info(
click.style(
f"tenant_id: {tenant_id}, Rag pipeline run completed. Latency: {end_at - start_at}s", fg="green"
)
)
except Exception:
logging.exception(click.style(f"Error running rag pipeline, tenant_id: {tenant_id}", fg="red"))
raise
finally:
tenant_isolated_task_queue = TenantIsolatedTaskQueue(tenant_id, "pipeline")
# Check if there are waiting tasks in the queue
# Use rpop to get the next task from the queue (FIFO order)
next_file_ids = tenant_isolated_task_queue.pull_tasks(count=dify_config.TENANT_ISOLATED_TASK_CONCURRENCY)
logger.info("priority rag pipeline tenant isolation queue %s next files: %s", tenant_id, next_file_ids)
if next_file_ids:
for next_file_id in next_file_ids:
# Process the next waiting task
# Keep the flag set to indicate a task is running
tenant_isolated_task_queue.set_task_waiting_time()
priority_rag_pipeline_run_task.delay( # type: ignore
rag_pipeline_invoke_entities_file_id=next_file_id.decode("utf-8")
if isinstance(next_file_id, bytes)
else next_file_id,
tenant_id=tenant_id,
)
else:
# No more waiting tasks, clear the flag
tenant_isolated_task_queue.delete_task_key()
file_service = FileService(db.engine)
file_service.delete_file(rag_pipeline_invoke_entities_file_id)
db.session.close()
def run_single_rag_pipeline_task(rag_pipeline_invoke_entity: Mapping[str, Any], flask_app):
"""Run a single RAG pipeline task within Flask app context."""
# Create Flask application context for this thread
with flask_app.app_context():
try:
rag_pipeline_invoke_entity_model = RagPipelineInvokeEntity.model_validate(rag_pipeline_invoke_entity)
user_id = rag_pipeline_invoke_entity_model.user_id
tenant_id = rag_pipeline_invoke_entity_model.tenant_id
pipeline_id = rag_pipeline_invoke_entity_model.pipeline_id
workflow_id = rag_pipeline_invoke_entity_model.workflow_id
streaming = rag_pipeline_invoke_entity_model.streaming
workflow_execution_id = rag_pipeline_invoke_entity_model.workflow_execution_id
workflow_thread_pool_id = rag_pipeline_invoke_entity_model.workflow_thread_pool_id
application_generate_entity = rag_pipeline_invoke_entity_model.application_generate_entity
with Session(db.engine, expire_on_commit=False) as session:
# Load required entities
account = session.scalar(select(Account).where(Account.id == user_id).limit(1))
if not account:
raise ValueError(f"Account {user_id} not found")
tenant = session.scalar(select(Tenant).where(Tenant.id == tenant_id).limit(1))
if not tenant:
raise ValueError(f"Tenant {tenant_id} not found")
account.set_current_tenant_with_session(tenant, session=session)
pipeline = session.scalar(select(Pipeline).where(Pipeline.id == pipeline_id).limit(1))
if not pipeline:
raise ValueError(f"Pipeline {pipeline_id} not found")
workflow = session.scalar(select(Workflow).where(Workflow.id == pipeline.workflow_id).limit(1))
if not workflow:
raise ValueError(f"Workflow {pipeline.workflow_id} not found")
if workflow_execution_id is None:
workflow_execution_id = str(uuid.uuid4())
# Create application generate entity from dict
entity = RagPipelineGenerateEntity.model_validate(application_generate_entity)
# Create workflow repositories
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_execution_repository = DifyCoreRepositoryFactory.create_workflow_execution_repository(
session_factory=session_factory,
tenant_id=pipeline.tenant_id,
user=account,
app_id=entity.app_config.app_id,
triggered_from=WorkflowRunTriggeredFrom.RAG_PIPELINE_RUN,
)
workflow_node_execution_repository = (
DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
session_factory=session_factory,
tenant_id=pipeline.tenant_id,
user=account,
app_id=entity.app_config.app_id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.RAG_PIPELINE_RUN,
)
)
# Set the user directly in g for preserve_flask_contexts
g._login_user = account
# Copy context for passing to pipeline generator
context = contextvars.copy_context()
# Direct execution without creating another thread
# Since we're already in a thread pool, no need for nested threading
pipeline_generator = PipelineGenerator(
execution_driver=WorkflowRunAgg.run,
documents=SQLAlchemyDocumentRepository(session_factory=session_factory),
datasource_providers=build_data_source_credentials(database_client=get_session_maker()).providers,
)
# Using protected method intentionally for async execution
with Session(db.engine, expire_on_commit=False) as session:
pipeline_generator._generate( # type: ignore[attr-defined]
session=session,
flask_app=flask_app,
context=context,
pipeline=pipeline,
workflow_id=workflow_id,
user=account,
application_generate_entity=entity,
invoke_from=InvokeFrom.PUBLISHED_PIPELINE,
workflow_execution_repository=workflow_execution_repository,
workflow_node_execution_repository=workflow_node_execution_repository,
streaming=streaming,
workflow_thread_pool_id=workflow_thread_pool_id,
)
except Exception:
logging.exception("Error in priority pipeline task")
raise
@@ -0,0 +1,218 @@
import contextvars
import logging
import time
import uuid
from collections.abc import Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from itertools import islice
from typing import Any
import click
from celery import shared_task
from flask import current_app, g
from pydantic import TypeAdapter
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
from configs import dify_config
from core.app.apps.pipeline.pipeline_generator import PipelineGenerator
from core.app.entities.app_invoke_entities import InvokeFrom, RagPipelineGenerateEntity
from core.app.entities.rag_pipeline_invoke_entities import RagPipelineInvokeEntity
from core.db.session_factory import get_session_maker
from core.rag.pipeline.queue import TenantIsolatedTaskQueue
from core.repositories.factory import DifyCoreRepositoryFactory
from extensions.application_services.data_sources import build_data_source_credentials
from extensions.ext_database import db
from models import Account, Tenant
from models.dataset import Pipeline
from models.enums import WorkflowRunTriggeredFrom
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
from services.file_service import FileService
from services.workflow_run_agg import WorkflowRunAgg
logger = logging.getLogger(__name__)
# Each entry is validated into RagPipelineInvokeEntity inside the worker.
_INVOKE_ENTITIES_ADAPTER = TypeAdapter(list[dict[str, Any]])
def chunked(iterable: Sequence, size: int):
it = iter(iterable)
return iter(lambda: list(islice(it, size)), [])
@shared_task(queue="pipeline")
def rag_pipeline_run_task(
rag_pipeline_invoke_entities_file_id: str,
tenant_id: str,
):
"""
Async Run rag pipeline task using regular priority queue.
:param rag_pipeline_invoke_entities_file_id: File ID containing serialized RAG pipeline invoke entities
:param tenant_id: Tenant ID for the pipeline execution
"""
# run with threading, thread pool size is 10
try:
start_at = time.perf_counter()
rag_pipeline_invoke_entities_content = FileService(db.engine).get_file_content(
rag_pipeline_invoke_entities_file_id
)
rag_pipeline_invoke_entities = _INVOKE_ENTITIES_ADAPTER.validate_json(rag_pipeline_invoke_entities_content)
logger.info("tenant %s received %d rag pipeline invoke entities", tenant_id, len(rag_pipeline_invoke_entities))
# Get Flask app object for thread context
flask_app = current_app._get_current_object() # type: ignore
with ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for rag_pipeline_invoke_entity in rag_pipeline_invoke_entities:
# Submit task to thread pool with Flask app
future = executor.submit(run_single_rag_pipeline_task, rag_pipeline_invoke_entity, flask_app)
futures.append(future)
# Wait for all tasks to complete
for future in futures:
try:
future.result() # This will raise any exceptions that occurred in the thread
except Exception:
logging.exception("Error in pipeline task")
end_at = time.perf_counter()
logging.info(
click.style(
f"tenant_id: {tenant_id}, Rag pipeline run completed. Latency: {end_at - start_at}s", fg="green"
)
)
except Exception:
logging.exception(click.style(f"Error running rag pipeline, tenant_id: {tenant_id}", fg="red"))
raise
finally:
tenant_isolated_task_queue = TenantIsolatedTaskQueue(tenant_id, "pipeline")
# Check if there are waiting tasks in the queue
# Use rpop to get the next task from the queue (FIFO order)
next_file_ids = tenant_isolated_task_queue.pull_tasks(count=dify_config.TENANT_ISOLATED_TASK_CONCURRENCY)
logger.info("rag pipeline tenant isolation queue %s next files: %s", tenant_id, next_file_ids)
if next_file_ids:
for batch in chunked(next_file_ids, 100):
jobs = []
for next_file_id in batch:
tenant_isolated_task_queue.set_task_waiting_time()
file_id = (
next_file_id.decode("utf-8") if isinstance(next_file_id, (bytes, bytearray)) else next_file_id
)
jobs.append(
rag_pipeline_run_task.s(
rag_pipeline_invoke_entities_file_id=file_id,
tenant_id=tenant_id,
)
)
for job in jobs:
job.apply_async()
else:
# No more waiting tasks, clear the flag
tenant_isolated_task_queue.delete_task_key()
file_service = FileService(db.engine)
file_service.delete_file(rag_pipeline_invoke_entities_file_id)
db.session.close()
def run_single_rag_pipeline_task(rag_pipeline_invoke_entity: Mapping[str, Any], flask_app):
"""Run a single RAG pipeline task within Flask app context."""
# Create Flask application context for this thread
with flask_app.app_context():
try:
rag_pipeline_invoke_entity_model = RagPipelineInvokeEntity.model_validate(rag_pipeline_invoke_entity)
user_id = rag_pipeline_invoke_entity_model.user_id
tenant_id = rag_pipeline_invoke_entity_model.tenant_id
pipeline_id = rag_pipeline_invoke_entity_model.pipeline_id
workflow_id = rag_pipeline_invoke_entity_model.workflow_id
streaming = rag_pipeline_invoke_entity_model.streaming
workflow_execution_id = rag_pipeline_invoke_entity_model.workflow_execution_id
workflow_thread_pool_id = rag_pipeline_invoke_entity_model.workflow_thread_pool_id
application_generate_entity = rag_pipeline_invoke_entity_model.application_generate_entity
with sessionmaker(db.engine, expire_on_commit=False).begin() as session:
# Load required entities
account = session.scalar(select(Account).where(Account.id == user_id).limit(1))
if not account:
raise ValueError(f"Account {user_id} not found")
tenant = session.scalar(select(Tenant).where(Tenant.id == tenant_id).limit(1))
if not tenant:
raise ValueError(f"Tenant {tenant_id} not found")
account.set_current_tenant_with_session(tenant, session=session)
pipeline = session.scalar(select(Pipeline).where(Pipeline.id == pipeline_id).limit(1))
if not pipeline:
raise ValueError(f"Pipeline {pipeline_id} not found")
workflow = session.scalar(select(Workflow).where(Workflow.id == pipeline.workflow_id).limit(1))
if not workflow:
raise ValueError(f"Workflow {pipeline.workflow_id} not found")
if workflow_execution_id is None:
workflow_execution_id = str(uuid.uuid4())
# Create application generate entity from dict
entity = RagPipelineGenerateEntity.model_validate(application_generate_entity)
# Create workflow repositories
session_factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_execution_repository = DifyCoreRepositoryFactory.create_workflow_execution_repository(
session_factory=session_factory,
tenant_id=pipeline.tenant_id,
user=account,
app_id=entity.app_config.app_id,
triggered_from=WorkflowRunTriggeredFrom.RAG_PIPELINE_RUN,
)
workflow_node_execution_repository = (
DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
session_factory=session_factory,
tenant_id=pipeline.tenant_id,
user=account,
app_id=entity.app_config.app_id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.RAG_PIPELINE_RUN,
)
)
# Set the user directly in g for preserve_flask_contexts
g._login_user = account
# Copy context for passing to pipeline generator
context = contextvars.copy_context()
# Direct execution without creating another thread
# Since we're already in a thread pool, no need for nested threading
pipeline_generator = PipelineGenerator(
execution_driver=WorkflowRunAgg.run,
documents=SQLAlchemyDocumentRepository(session_factory=session_factory),
datasource_providers=build_data_source_credentials(database_client=get_session_maker()).providers,
)
# Using protected method intentionally for async execution
pipeline_generator._generate( # type: ignore[attr-defined]
session=session,
flask_app=flask_app,
context=context,
pipeline=pipeline,
workflow_id=workflow_id,
user=account,
application_generate_entity=entity,
invoke_from=InvokeFrom.PUBLISHED_PIPELINE,
workflow_execution_repository=workflow_execution_repository,
workflow_node_execution_repository=workflow_node_execution_repository,
streaming=streaming,
workflow_thread_pool_id=workflow_thread_pool_id,
)
except Exception:
logging.exception("Error in pipeline task")
raise
@@ -0,0 +1,54 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from models.dataset import Document
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.indexing.errors import DocumentIsPausedError
from services.knowledge.resource_scope import DatasetRef
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def recover_document_indexing_task(dataset_id: str, document_id: str):
"""
Async recover document
:param dataset_id:
:param document_id:
Usage: recover_document_indexing_task.delay(dataset_id, document_id)
"""
logger.info(click.style(f"Recover document: {document_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="red"))
return
try:
indexing_service = build_document_indexing_service(session_factory=session_factory.get_session_maker())
document_ref = DatasetRef(document.tenant_id, document.dataset_id).document(document.id)
status = document.indexing_status
session.commit()
if status in {"waiting", "parsing", "cleaning"}:
indexing_service.run([document_ref])
elif status == "splitting":
indexing_service.run_in_splitting_status(document_ref)
elif status == "indexing":
indexing_service.run_in_indexing_status(document_ref)
end_at = time.perf_counter()
logger.info(click.style(f"Processed document: {document.id} latency: {end_at - start_at}", fg="green"))
except DocumentIsPausedError as ex:
logger.info(click.style(str(ex), fg="yellow"))
except Exception:
logger.exception("recover_document_indexing_task failed, document_id: %s", document_id)
@@ -0,0 +1,60 @@
import logging
from celery import shared_task
from opentelemetry import metrics
from configs import dify_config
from enums import DeploymentEdition
from services.billing_service import BillingService
logger = logging.getLogger(__name__)
_MAX_RETRIES = 3
_RETRY_DELAY_SECONDS = 30
_refresh_counter = metrics.get_meter(__name__).create_counter(
"billing.vector_space_cache_refresh.count",
description="Number of billing vector-space cache refresh outcomes",
)
@shared_task(queue="dataset", bind=True, max_retries=_MAX_RETRIES, default_retry_delay=_RETRY_DELAY_SECONDS)
def refresh_billing_vector_space_task(self, tenant_id: str) -> None:
"""Refresh billing vector-space usage after vector cleanup has completed."""
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
return
try:
BillingService.invalidate_vector_space_cache(tenant_id)
except Exception as exc:
if self.request.retries >= _MAX_RETRIES:
_refresh_counter.add(1, {"outcome": "exhausted"})
logger.exception(
"Billing vector-space cache refresh retry budget exhausted, tenant_id=%s",
tenant_id,
)
raise
_refresh_counter.add(1, {"outcome": "retry"})
logger.warning(
"Billing vector-space cache refresh failed, scheduling retry %d/%d, tenant_id=%s",
self.request.retries + 1,
_MAX_RETRIES,
tenant_id,
exc_info=True,
)
raise self.retry(exc=exc, countdown=_RETRY_DELAY_SECONDS * (2**self.request.retries)) from exc
_refresh_counter.add(1, {"outcome": "success"})
logger.info("Billing vector-space cache refreshed, tenant_id=%s", tenant_id)
def schedule_billing_vector_space_refresh(tenant_id: str) -> None:
"""Dispatch a best-effort billing refresh without changing cleanup status."""
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
return
try:
refresh_billing_vector_space_task.delay(tenant_id)
except Exception:
_refresh_counter.add(1, {"outcome": "dispatch_failure"})
logger.exception("Failed to dispatch billing vector-space cache refresh, tenant_id=%s", tenant_id)
@@ -0,0 +1,303 @@
"""Task for regenerating summary indexes when dataset settings change."""
import logging
import time
from collections import defaultdict
import click
from celery import shared_task
from sqlalchemy import or_, select
from core.credit_usage import CreditUsageCreatedBy
from core.db.session_factory import session_factory
from core.model_context import with_credit_usage_created_by
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from models.dataset import Dataset, DocumentSegment, DocumentSegmentSummary
from models.dataset import Document as DatasetDocument
from models.enums import SummaryStatus
from services.knowledge.summaries.adapters import SummaryIndexAdapter
logger = logging.getLogger(__name__)
@shared_task(queue="dataset_summary")
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
def regenerate_summary_index_task(
dataset_id: str,
regenerate_reason: str = "summary_model_changed",
regenerate_vectors_only: bool = False,
):
"""
Regenerate summary indexes for all documents in a dataset.
This task is triggered when:
1. summary_index_setting model changes (regenerate_reason="summary_model_changed")
- Regenerates summary content and vectors for all existing summaries
2. embedding_model changes (regenerate_reason="embedding_model_changed")
- Only regenerates vectors for existing summaries (keeps summary content)
Args:
dataset_id: Dataset ID
regenerate_reason: Reason for regeneration ("summary_model_changed" or "embedding_model_changed")
regenerate_vectors_only: If True, only regenerate vectors without regenerating summary content
"""
logger.info(
click.style(
f"Start regenerate summary index for dataset {dataset_id}, reason: {regenerate_reason}",
fg="green",
)
)
start_at = time.perf_counter()
try:
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if not dataset:
logger.error(click.style(f"Dataset not found: {dataset_id}", fg="red"))
return
# Only regenerate summary index for high_quality indexing technique
if dataset.indexing_technique != IndexTechniqueType.HIGH_QUALITY:
logger.info(
click.style(
f"Skipping summary regeneration for dataset {dataset_id}: "
f"indexing_technique is {dataset.indexing_technique}, not 'high_quality'",
fg="cyan",
)
)
return
# Check if summary index is enabled (only for summary_model change)
# For embedding_model change, we still re-vectorize existing summaries even if setting is disabled
summary_index_setting = dataset.summary_index_setting
if not regenerate_vectors_only:
# For summary_model change, require summary_index_setting to be enabled
if not summary_index_setting or not summary_index_setting.get("enable"):
logger.info(
click.style(
f"Summary index is disabled for dataset {dataset_id}",
fg="cyan",
)
)
return
total_segments_processed = 0
total_segments_failed = 0
if regenerate_vectors_only:
# For embedding_model change: directly query all segments with existing summaries
# Don't require document indexing_status == "completed"
# Include summaries with status "completed" or "error" (if they have content)
segments_with_summaries = session.execute(
select(DocumentSegment, DocumentSegmentSummary)
.join(
DocumentSegmentSummary,
DocumentSegment.id == DocumentSegmentSummary.chunk_id,
)
.join(
DatasetDocument,
DocumentSegment.document_id == DatasetDocument.id,
)
.where(
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.status == "completed", # Segment must be completed
DocumentSegment.enabled.is_(True),
DocumentSegmentSummary.dataset_id == dataset_id,
DocumentSegmentSummary.summary_content.isnot(None), # Must have summary content
# Include completed summaries or error summaries (with content)
or_(
DocumentSegmentSummary.status == SummaryStatus.COMPLETED,
DocumentSegmentSummary.status == SummaryStatus.ERROR,
),
DatasetDocument.enabled.is_(True), # Document must be enabled
DatasetDocument.archived.is_(False), # Document must not be archived
DatasetDocument.doc_form != IndexStructureType.QA_INDEX, # Skip qa_model documents
)
.order_by(DocumentSegment.document_id.asc(), DocumentSegment.position.asc())
).all()
if not segments_with_summaries:
logger.info(
click.style(
f"No segments with summaries found for re-vectorization in dataset {dataset_id}",
fg="cyan",
)
)
return
logger.info(
"Found %s segments with summaries for re-vectorization in dataset %s",
len(segments_with_summaries),
dataset_id,
)
# Group by document for logging
segments_by_document = defaultdict(list)
for segment, summary_record in segments_with_summaries:
segments_by_document[segment.document_id].append((segment, summary_record))
logger.info(
"Segments grouped into %s documents for re-vectorization",
len(segments_by_document),
)
for document_id, segment_summary_pairs in segments_by_document.items():
logger.info(
"Re-vectorizing summaries for %s segments in document %s",
len(segment_summary_pairs),
document_id,
)
for segment, summary_record in segment_summary_pairs:
try:
# The summary use case replaces the old vector after releasing this transaction.
SummaryIndexAdapter.vectorize_summary(summary_record, segment, dataset, session=session)
session.commit()
total_segments_processed += 1
except Exception as e:
logger.error(
"Failed to re-vectorize summary for segment %s: %s",
segment.id,
str(e),
exc_info=True,
)
total_segments_failed += 1
# Update summary record with error status
summary_record.status = SummaryStatus.ERROR
summary_record.error = f"Re-vectorization failed: {str(e)}"
session.add(summary_record)
session.commit()
continue
else:
# For summary_model change: require document indexing_status == "completed"
# Get all documents with completed indexing status
dataset_documents = session.scalars(
select(DatasetDocument).where(
DatasetDocument.dataset_id == dataset_id,
DatasetDocument.indexing_status == "completed",
DatasetDocument.enabled.is_(True),
DatasetDocument.archived.is_(False),
)
).all()
if not dataset_documents:
logger.info(
click.style(
f"No documents found for summary regeneration in dataset {dataset_id}",
fg="cyan",
)
)
return
logger.info(
"Found %s documents for summary regeneration in dataset %s",
len(dataset_documents),
dataset_id,
)
for dataset_document in dataset_documents:
# Skip qa_model documents
if dataset_document.doc_form == IndexStructureType.QA_INDEX:
continue
try:
# Get all segments with existing summaries
segments = session.scalars(
select(DocumentSegment)
.join(
DocumentSegmentSummary,
DocumentSegment.id == DocumentSegmentSummary.chunk_id,
)
.where(
DocumentSegment.document_id == dataset_document.id,
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.status == "completed",
DocumentSegment.enabled.is_(True),
DocumentSegmentSummary.dataset_id == dataset_id,
)
.order_by(DocumentSegment.position.asc())
).all()
if not segments:
continue
logger.info(
"Regenerating summaries for %s segments in document %s",
len(segments),
dataset_document.id,
)
for segment in segments:
existing_summary_record: DocumentSegmentSummary | None = None
try:
# Get existing summary record
existing_summary_record = session.scalar(
select(DocumentSegmentSummary)
.where(
DocumentSegmentSummary.chunk_id == segment.id,
DocumentSegmentSummary.dataset_id == dataset_id,
)
.limit(1)
)
if not existing_summary_record:
logger.warning("Summary record not found for segment %s, skipping", segment.id)
continue
# Regenerate both summary content and vectors (for summary_model change)
SummaryIndexAdapter.generate_and_vectorize_summary(
segment, dataset, summary_index_setting, session=session
)
total_segments_processed += 1
except Exception as e:
logger.error(
"Failed to regenerate summary for segment %s: %s",
segment.id,
str(e),
exc_info=True,
)
total_segments_failed += 1
# Update summary record with error status
if existing_summary_record is not None:
existing_summary_record.status = SummaryStatus.ERROR
existing_summary_record.error = f"Regeneration failed: {str(e)}"
session.add(existing_summary_record)
session.commit()
continue
except Exception as e:
logger.error(
"Failed to process document %s for summary regeneration: %s",
dataset_document.id,
str(e),
exc_info=True,
)
continue
end_at = time.perf_counter()
if regenerate_vectors_only:
logger.info(
click.style(
f"Summary re-vectorization completed for dataset {dataset_id}: "
f"{total_segments_processed} segments processed successfully, "
f"{total_segments_failed} segments failed, "
f"latency: {end_at - start_at:.2f}s",
fg="green",
)
)
else:
logger.info(
click.style(
f"Summary index regeneration completed for dataset {dataset_id}: "
f"{total_segments_processed} segments processed successfully, "
f"{total_segments_failed} segments failed, "
f"latency: {end_at - start_at:.2f}s",
fg="green",
)
)
except Exception:
logger.exception("Regenerate summary index failed for dataset %s", dataset_id)
@@ -0,0 +1,822 @@
import logging
import time
from collections.abc import Callable
from typing import Any, cast
import click
import sqlalchemy as sa
from celery import shared_task
from sqlalchemy import delete, select
from sqlalchemy.engine import CursorResult
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session, sessionmaker
from configs import dify_config
from constants.resource_access_token import ResourceAccessTokenResourceType
from core.db.session_factory import session_factory
from enums import DeploymentEdition
from extensions.application_services.resource_access_token import build_resource_access_token_cleanup_service
from extensions.ext_database import db
from libs.archive_storage import ArchiveStorageNotConfiguredError, get_archive_storage
from models import (
ApiToken,
AppAnnotationHitHistory,
AppAnnotationSetting,
AppDatasetJoin,
AppMCPServer,
AppModelConfig,
AppStar,
AppTrigger,
Conversation,
EndUser,
InstalledApp,
Message,
MessageAgentThought,
MessageAnnotation,
MessageChain,
MessageFeedback,
MessageFile,
RecommendedApp,
Site,
TagBinding,
TraceAppConfig,
WorkflowSchedulePlan,
)
from models.agent import WorkflowAgentNodeBinding
from models.tools import WorkflowToolProvider
from models.trigger import WorkflowPluginTrigger, WorkflowTriggerLog, WorkflowWebhookTrigger
from models.web import PinnedConversation, SavedMessage
from models.workflow import (
ConversationVariable,
Workflow,
WorkflowAppLog,
WorkflowArchiveLog,
)
from repositories.factory import DifyAPIRepositoryFactory
from services.api_token_service import ApiTokenCache
from services.app_storage_cleanup_service import cleanup_app_storage
logger = logging.getLogger(__name__)
NETWORK_ACCESS_BINDING_CLEANUP_DELAY_SECONDS = 10
NETWORK_ACCESS_BINDING_CLEANUP_RETRY_BASE_SECONDS = 15
NETWORK_ACCESS_BINDING_CLEANUP_RETRY_MAX_SECONDS = 10 * 60
def _network_access_binding_cleanup_retry_delay(retries: int) -> int:
exponent = min(max(retries, 0), 6)
return min(
NETWORK_ACCESS_BINDING_CLEANUP_RETRY_BASE_SECONDS * (2**exponent),
NETWORK_ACCESS_BINDING_CLEANUP_RETRY_MAX_SECONDS,
)
@shared_task(queue="app_deletion", bind=True, max_retries=24)
def cleanup_app_network_access_group_binding_task(self, tenant_id: str, app_id: str) -> None:
"""Reliably remove a SaaS binding after its owning App was committed deleted."""
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
return
try:
# Import lazily because AppService imports this task module while the
# application-service composition root imports AppService dependencies.
from extensions.ext_application_services import application_services
application_services().network_access_groups.cleanup_app_binding(
workspace_id=tenant_id,
app_id=app_id,
)
except Exception as e:
countdown = _network_access_binding_cleanup_retry_delay(self.request.retries)
logger.exception(
"Failed to clean up App network access group binding",
extra={"tenant_id": tenant_id, "app_id": app_id, "retry_countdown": countdown},
)
raise self.retry(exc=e, countdown=countdown) from e
def _schedule_app_network_access_group_binding_cleanup(tenant_id: str, app_id: str) -> None:
"""Schedule only from App lifecycle cleanup, never account/member deletion."""
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
return
cleanup_app_network_access_group_binding_task.apply_async(
kwargs={"tenant_id": tenant_id, "app_id": app_id},
countdown=NETWORK_ACCESS_BINDING_CLEANUP_DELAY_SECONDS,
)
@shared_task(queue="app_deletion", bind=True, max_retries=3)
def remove_app_and_related_data_task(self, tenant_id: str, app_id: str):
logger.info(click.style(f"Start deleting app and related data: {tenant_id}:{app_id}", fg="green"))
start_at = time.perf_counter()
try:
# AppService publishes this task after the App transaction commits.
# Schedule the independent high-retry SaaS cleanup before legacy local
# cleanup so a later local failure cannot strand the binding.
_schedule_app_network_access_group_binding_cleanup(tenant_id, app_id)
# Preserve ownership records until storage cleanup succeeds, so retries
# can still locate files. External I/O runs outside DB transactions.
cleanup_app_storage(tenant_id, app_id)
# Delete related data
_delete_app_model_configs(tenant_id, app_id)
_delete_app_site(tenant_id, app_id)
_delete_app_mcp_servers(tenant_id, app_id)
_delete_app_api_tokens(tenant_id, app_id)
_delete_app_resource_access_token_relations(tenant_id, app_id)
_delete_installed_apps(tenant_id, app_id)
_delete_app_stars(tenant_id, app_id)
_delete_recommended_apps(tenant_id, app_id)
_delete_app_annotation_data(tenant_id, app_id)
_delete_app_dataset_joins(tenant_id, app_id)
_delete_workflow_agent_node_bindings(tenant_id, app_id)
_delete_app_workflows(tenant_id, app_id)
_delete_app_workflow_node_executions(tenant_id, app_id)
_delete_app_workflow_runs(tenant_id, app_id)
_delete_app_workflow_app_logs(tenant_id, app_id)
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.ARCHIVE_STORAGE_ENABLED:
_delete_app_workflow_archive_logs(tenant_id, app_id)
_delete_archived_workflow_run_files(tenant_id, app_id)
_delete_app_conversations(tenant_id, app_id)
_delete_app_messages(tenant_id, app_id)
_delete_workflow_tool_providers(tenant_id, app_id)
_delete_app_tag_bindings(tenant_id, app_id)
_delete_end_users(tenant_id, app_id)
_delete_trace_app_configs(tenant_id, app_id)
_delete_conversation_variables(app_id=app_id)
_delete_draft_variables(app_id)
_delete_app_triggers(tenant_id, app_id)
_delete_workflow_plugin_triggers(tenant_id, app_id)
_delete_workflow_webhook_triggers(tenant_id, app_id)
_delete_workflow_schedule_plans(tenant_id, app_id)
_delete_workflow_trigger_logs(tenant_id, app_id)
end_at = time.perf_counter()
logger.info(click.style(f"App and related data deleted: {app_id} latency: {end_at - start_at}", fg="green"))
except SQLAlchemyError as e:
logger.exception(click.style(f"Database error occurred while deleting app {app_id} and related data", fg="red"))
raise self.retry(exc=e, countdown=60) from e # Retry after 60 seconds
except Exception as e:
logger.exception(click.style(f"Error occurred while deleting app {app_id} and related data", fg="red"))
raise self.retry(exc=e, countdown=60) from e # Retry after 60 seconds
def _delete_app_model_configs(tenant_id: str, app_id: str):
def del_model_config(session: Session, model_config_id: str):
session.execute(
delete(AppModelConfig)
.where(AppModelConfig.id == model_config_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_model_configs where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_model_config,
"app model config",
)
def _delete_app_site(tenant_id: str, app_id: str):
def del_site(session: Session, site_id: str):
session.execute(delete(Site).where(Site.id == site_id).execution_options(synchronize_session=False))
_delete_records(
"""select id from sites where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_site,
"site",
)
def _delete_app_mcp_servers(tenant_id: str, app_id: str):
def del_mcp_server(session: Session, mcp_server_id: str):
session.execute(
delete(AppMCPServer).where(AppMCPServer.id == mcp_server_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_mcp_servers where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_mcp_server,
"app mcp server",
)
def _delete_app_api_tokens(tenant_id: str, app_id: str):
def del_api_token(session: Session, api_token_id: str):
# Fetch token details for cache invalidation
token_obj = session.scalar(select(ApiToken).where(ApiToken.id == api_token_id).limit(1))
if token_obj:
# Invalidate cache before deletion
ApiTokenCache.delete(token_obj.token, token_obj.type)
session.execute(
delete(ApiToken).where(ApiToken.id == api_token_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from api_tokens where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_api_token,
"api token",
)
def _delete_app_resource_access_token_relations(tenant_id: str, app_id: str):
with session_factory.get_session_maker()() as session:
build_resource_access_token_cleanup_service(session=session).delete_resource_relations(
tenant_id=tenant_id, resource_type=ResourceAccessTokenResourceType.APP, resource_id=app_id
)
session.commit()
def _delete_installed_apps(tenant_id: str, app_id: str):
def del_installed_app(session: Session, installed_app_id: str):
session.execute(
delete(InstalledApp).where(InstalledApp.id == installed_app_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from installed_apps where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_installed_app,
"installed app",
)
def _delete_app_stars(tenant_id: str, app_id: str):
def del_app_star(session, app_star_id: str):
session.execute(delete(AppStar).where(AppStar.id == app_star_id).execution_options(synchronize_session=False))
_delete_records(
"""select id from app_stars where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_app_star,
"app star",
)
def _delete_recommended_apps(tenant_id: str, app_id: str):
def del_recommended_app(session: Session, recommended_app_id: str):
session.execute(
delete(RecommendedApp)
.where(RecommendedApp.id == recommended_app_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from recommended_apps where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_recommended_app,
"recommended app",
)
def _delete_app_annotation_data(tenant_id: str, app_id: str):
def del_annotation_hit_history(session: Session, annotation_hit_history_id: str):
session.execute(
delete(AppAnnotationHitHistory)
.where(AppAnnotationHitHistory.id == annotation_hit_history_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_annotation_hit_histories where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_annotation_hit_history,
"annotation hit history",
)
def del_annotation_setting(session: Session, annotation_setting_id: str):
session.execute(
delete(AppAnnotationSetting)
.where(AppAnnotationSetting.id == annotation_setting_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_annotation_settings where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_annotation_setting,
"annotation setting",
)
def _delete_app_dataset_joins(tenant_id: str, app_id: str):
def del_dataset_join(session: Session, dataset_join_id: str):
session.execute(
delete(AppDatasetJoin)
.where(AppDatasetJoin.id == dataset_join_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_dataset_joins where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_dataset_join,
"dataset join",
)
def _delete_app_workflows(tenant_id: str, app_id: str):
def del_workflow(session: Session, workflow_id: str):
session.execute(delete(Workflow).where(Workflow.id == workflow_id).execution_options(synchronize_session=False))
_delete_records(
"""select id from workflows where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_workflow,
"workflow",
)
def _delete_workflow_agent_node_bindings(tenant_id: str, app_id: str) -> None:
with session_factory.create_session() as session:
session.execute(
delete(WorkflowAgentNodeBinding).where(
WorkflowAgentNodeBinding.tenant_id == tenant_id,
WorkflowAgentNodeBinding.app_id == app_id,
)
)
session.commit()
def _delete_app_workflow_runs(tenant_id: str, app_id: str):
"""Delete all workflow runs for an app using the service repository."""
session_maker = sessionmaker(bind=db.engine)
workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker)
deleted_count = workflow_run_repo.delete_runs_by_app(
tenant_id=tenant_id,
app_id=app_id,
batch_size=1000,
)
logger.info("Deleted %s workflow runs for app %s", deleted_count, app_id)
def _delete_app_workflow_node_executions(tenant_id: str, app_id: str):
"""Delete all workflow node executions for an app using the service repository."""
session_maker = sessionmaker(bind=db.engine)
node_execution_repo = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(session_maker)
deleted_count = node_execution_repo.delete_executions_by_app(
tenant_id=tenant_id,
app_id=app_id,
batch_size=1000,
)
logger.info("Deleted %s workflow node executions for app %s", deleted_count, app_id)
def _delete_app_workflow_app_logs(tenant_id: str, app_id: str):
def del_workflow_app_log(session: Session, workflow_app_log_id: str):
session.execute(
delete(WorkflowAppLog)
.where(WorkflowAppLog.id == workflow_app_log_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_app_logs where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_workflow_app_log,
"workflow app log",
)
def _delete_app_workflow_archive_logs(tenant_id: str, app_id: str):
def del_workflow_archive_log(session: Session, workflow_archive_log_id: str):
session.execute(
delete(WorkflowArchiveLog)
.where(WorkflowArchiveLog.id == workflow_archive_log_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_archive_logs where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_workflow_archive_log,
"workflow archive log",
)
def _delete_archived_workflow_run_files(tenant_id: str, app_id: str):
prefix = f"{tenant_id}/app_id={app_id}/"
try:
archive_storage = get_archive_storage()
except ArchiveStorageNotConfiguredError as e:
logger.info("Archive storage not configured, skipping archive file cleanup: %s", e)
return
try:
keys = archive_storage.list_objects(prefix)
except Exception:
logger.exception("Failed to list archive files for app %s", app_id)
return
deleted = 0
for key in keys:
try:
archive_storage.delete_object(key)
deleted += 1
except Exception:
logger.exception("Failed to delete archive object %s", key)
logger.info("Deleted %s archive objects for app %s", deleted, app_id)
def _delete_app_conversations(tenant_id: str, app_id: str):
def del_conversation(session: Session, conversation_id: str):
session.execute(
delete(PinnedConversation)
.where(PinnedConversation.conversation_id == conversation_id)
.execution_options(synchronize_session=False)
)
session.execute(
delete(Conversation).where(Conversation.id == conversation_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from conversations where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_conversation,
"conversation",
)
def _delete_conversation_variables(*, app_id: str):
with session_factory.create_session() as session:
stmt = delete(ConversationVariable).where(ConversationVariable.app_id == app_id)
session.execute(stmt)
session.commit()
logger.info(click.style(f"Deleted conversation variables for app {app_id}", fg="green"))
def _delete_app_messages(tenant_id: str, app_id: str):
def del_message(session: Session, message_id: str):
session.execute(
delete(MessageFeedback)
.where(MessageFeedback.message_id == message_id)
.execution_options(synchronize_session=False)
)
session.execute(
delete(MessageAnnotation)
.where(MessageAnnotation.message_id == message_id)
.execution_options(synchronize_session=False)
)
session.execute(
delete(MessageChain)
.where(MessageChain.message_id == message_id)
.execution_options(synchronize_session=False)
)
session.execute(
delete(MessageAgentThought)
.where(MessageAgentThought.message_id == message_id)
.execution_options(synchronize_session=False)
)
session.execute(
delete(MessageFile).where(MessageFile.message_id == message_id).execution_options(synchronize_session=False)
)
session.execute(
delete(SavedMessage)
.where(SavedMessage.message_id == message_id)
.execution_options(synchronize_session=False)
)
session.execute(delete(Message).where(Message.id == message_id).execution_options(synchronize_session=False))
_delete_records(
"""select id from messages where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_message,
"message",
)
def _delete_workflow_tool_providers(tenant_id: str, app_id: str):
def del_tool_provider(session: Session, tool_provider_id: str):
session.execute(
delete(WorkflowToolProvider)
.where(WorkflowToolProvider.id == tool_provider_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from tool_workflow_providers where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_tool_provider,
"tool workflow provider",
)
def _delete_app_tag_bindings(tenant_id: str, app_id: str):
def del_tag_binding(session: Session, tag_binding_id: str):
session.execute(
delete(TagBinding).where(TagBinding.id == tag_binding_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from tag_bindings where tenant_id=:tenant_id and target_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_tag_binding,
"tag binding",
)
def _delete_end_users(tenant_id: str, app_id: str):
def del_end_user(session: Session, end_user_id: str):
session.execute(delete(EndUser).where(EndUser.id == end_user_id).execution_options(synchronize_session=False))
_delete_records(
"""select id from end_users where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_end_user,
"end user",
)
def _delete_trace_app_configs(tenant_id: str, app_id: str):
def del_trace_app_config(session: Session, trace_app_config_id: str):
session.execute(
delete(TraceAppConfig)
.where(TraceAppConfig.id == trace_app_config_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from trace_app_config where app_id=:app_id limit 1000""",
{"app_id": app_id},
del_trace_app_config,
"trace app config",
)
def _delete_draft_variables(app_id: str):
"""Delete all workflow draft variables for an app in batches."""
return delete_draft_variables_batch(app_id, batch_size=1000)
def delete_draft_variables_batch(app_id: str, batch_size: int = 1000) -> int:
"""
Delete draft variables for an app in batches.
This function now handles cleanup of associated Offload data including:
- WorkflowDraftVariableFile records
- UploadFile records
- Object storage files
Args:
app_id: The ID of the app whose draft variables should be deleted
batch_size: Number of records to delete per batch
Returns:
Total number of records deleted
"""
if batch_size <= 0:
raise ValueError("batch_size must be positive")
total_deleted = 0
total_files_deleted = 0
while True:
# Read the batch in a transaction of its own: the offload cleanup in between
# must run with no transaction open.
with session_factory.create_session() as session:
# Get a batch of draft variable IDs along with their file_ids
query_sql = """
SELECT id, file_id FROM workflow_draft_variables
WHERE app_id = :app_id
LIMIT :batch_size
"""
result = session.execute(sa.text(query_sql), {"app_id": app_id, "batch_size": batch_size})
rows = list(result)
if not rows:
break
draft_var_ids = [row[0] for row in rows]
file_ids = [row[1] for row in rows if row[1] is not None]
# Clean up associated Offload data first, outside any transaction, so the rows
# remain visible if the storage cleanup has to be retried.
if file_ids:
files_deleted = _delete_draft_variable_offload_data(file_ids)
total_files_deleted += files_deleted
# Delete the draft variables
with session_factory.create_session() as session, session.begin():
delete_sql = """
DELETE FROM workflow_draft_variables
WHERE id IN :ids
"""
deleted_result = cast(
CursorResult[Any],
session.execute(
sa.text(delete_sql).bindparams(sa.bindparam("ids", expanding=True)), {"ids": draft_var_ids}
),
)
batch_deleted: int = int(getattr(deleted_result, "rowcount", 0) or 0)
total_deleted += batch_deleted
logger.info(click.style(f"Deleted {batch_deleted} draft variables (batch) for app {app_id}", fg="green"))
logger.info(
click.style(
f"Deleted {total_deleted} total draft variables for app {app_id}. "
f"Cleaned up {total_files_deleted} total associated files.",
fg="green",
)
)
return total_deleted
def _delete_draft_variable_offload_data(file_ids: list[str]) -> int:
"""
Delete Offload data associated with WorkflowDraftVariable file_ids.
This function:
1. Finds WorkflowDraftVariableFile records by file_ids
2. Deletes associated files from object storage
3. Deletes UploadFile records
4. Deletes WorkflowDraftVariableFile records
Object storage is external: the storage deletes below run outside any database
transaction (see api/AGENTS.md).
Args:
file_ids: List of WorkflowDraftVariableFile IDs
Returns:
Number of files cleaned up
"""
from extensions.ext_storage import storage
if not file_ids:
return 0
files_deleted = 0
try:
# Get WorkflowDraftVariableFile records and their associated UploadFile keys
query_sql = """
SELECT wdvf.id, uf.key, uf.id as upload_file_id
FROM workflow_draft_variable_files wdvf
JOIN upload_files uf ON wdvf.upload_file_id = uf.id
WHERE wdvf.id IN :file_ids \
"""
with session_factory.create_session() as session:
result = session.execute(sa.text(query_sql), {"file_ids": tuple(file_ids)})
file_records = [(row[0], row[1], row[2]) for row in result]
# Delete from object storage and collect upload file IDs
upload_file_ids = []
for _, storage_key, upload_file_id in file_records:
try:
storage.delete(storage_key)
upload_file_ids.append(upload_file_id)
files_deleted += 1
except Exception:
logging.exception("Failed to delete storage object %s", storage_key)
# Continue with database cleanup even if storage deletion fails
upload_file_ids.append(upload_file_id)
with session_factory.create_session() as session, session.begin():
# Delete UploadFile records
if upload_file_ids:
delete_upload_files_sql = """
DELETE \
FROM upload_files
WHERE id IN :upload_file_ids \
"""
session.execute(sa.text(delete_upload_files_sql), {"upload_file_ids": tuple(upload_file_ids)})
# Delete WorkflowDraftVariableFile records
delete_variable_files_sql = """
DELETE \
FROM workflow_draft_variable_files
WHERE id IN :file_ids \
"""
session.execute(sa.text(delete_variable_files_sql), {"file_ids": tuple(file_ids)})
except Exception:
logging.exception("Error deleting draft variable offload data:")
# Don't raise, as we want to continue with the main deletion process
return files_deleted
def _delete_app_triggers(tenant_id: str, app_id: str):
def del_app_trigger(session: Session, trigger_id: str):
session.execute(
delete(AppTrigger).where(AppTrigger.id == trigger_id).execution_options(synchronize_session=False)
)
_delete_records(
"""select id from app_triggers where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_app_trigger,
"app trigger",
)
def _delete_workflow_plugin_triggers(tenant_id: str, app_id: str):
def del_plugin_trigger(session: Session, trigger_id: str):
session.execute(
delete(WorkflowPluginTrigger)
.where(WorkflowPluginTrigger.id == trigger_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_plugin_triggers where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_plugin_trigger,
"workflow plugin trigger",
)
def _delete_workflow_webhook_triggers(tenant_id: str, app_id: str):
def del_webhook_trigger(session: Session, trigger_id: str):
session.execute(
delete(WorkflowWebhookTrigger)
.where(WorkflowWebhookTrigger.id == trigger_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_webhook_triggers where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_webhook_trigger,
"workflow webhook trigger",
)
def _delete_workflow_schedule_plans(tenant_id: str, app_id: str):
def del_schedule_plan(session: Session, plan_id: str):
session.execute(
delete(WorkflowSchedulePlan)
.where(WorkflowSchedulePlan.id == plan_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_schedule_plans where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_schedule_plan,
"workflow schedule plan",
)
def _delete_workflow_trigger_logs(tenant_id: str, app_id: str):
def del_trigger_log(session: Session, log_id: str):
session.execute(
delete(WorkflowTriggerLog)
.where(WorkflowTriggerLog.id == log_id)
.execution_options(synchronize_session=False)
)
_delete_records(
"""select id from workflow_trigger_logs where tenant_id=:tenant_id and app_id=:app_id limit 1000""",
{"tenant_id": tenant_id, "app_id": app_id},
del_trigger_log,
"workflow trigger log",
)
def _delete_records(
query_sql: str, params: dict[str, Any], delete_func: Callable[[Session, str], None], name: str
) -> None:
while True:
with session_factory.create_session() as session:
rs = session.execute(sa.text(query_sql), params)
rows = rs.fetchall()
if not rows:
break
success_count = 0
for i in rows:
record_id = str(i.id)
try:
delete_func(session, record_id)
logger.info(click.style(f"Deleted {name} {record_id}", fg="green"))
session.commit()
success_count += 1
except Exception:
logger.exception("Error occurred while deleting %s %s", name, record_id)
# continue with next record even if one deletion fails
session.rollback()
continue
rs.close()
# If we couldn't delete ANY records in this batch, we must break out of the while loop
# to prevent an infinite loop where we keep fetching the same failing records.
if success_count == 0:
logger.warning(
click.style(
f"Failed to delete any {name} in the current batch. Stopping to prevent infinite loop.",
fg="yellow",
)
)
break
@@ -0,0 +1,104 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import select, update
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import Document, DocumentSegment
from models.enums import IndexingStatus
from repositories.knowledge.dataset_read_repository import get_document_dataset
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def remove_document_from_index_task(document_id: str):
"""
Async Remove document from index
:param document_id: document id
Usage: remove_document_from_index.delay(document_id)
"""
logger.info(click.style(f"Start remove document segments from index: {document_id}", fg="green"))
start_at = time.perf_counter()
with session_factory.create_session() as session:
document = session.scalar(select(Document).where(Document.id == document_id).limit(1))
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="red"))
return
if document.indexing_status != IndexingStatus.COMPLETED:
logger.info(click.style(f"Document is not completed, remove is not allowed: {document_id}", fg="red"))
return
indexing_cache_key = f"document_{document.id}_indexing"
try:
dataset = get_document_dataset(document, session=session)
if not dataset:
raise Exception("Document has no dataset")
index_processor = IndexProcessorFactory(document.doc_form).init_index_processor()
segments = session.scalars(select(DocumentSegment).where(DocumentSegment.document_id == document.id)).all()
# Disable summary indexes for all segments in this document
from services.knowledge.summaries.adapters import SummaryIndexAdapter
segment_ids_list = [segment.id for segment in segments]
if segment_ids_list:
try:
SummaryIndexAdapter.disable_summaries_for_segments(
dataset=dataset,
segment_ids=segment_ids_list,
disabled_by=document.disabled_by,
)
except Exception:
logger.warning("Failed to disable summaries for document %s", document.id, exc_info=True)
index_node_ids = [segment.index_node_id for segment in segments if segment.index_node_id]
if index_node_ids:
try:
index_processor.clean(
dataset,
index_node_ids,
with_keywords=True,
delete_child_chunks=False,
session=session,
)
except Exception:
logger.exception("clean dataset %s from index failed", dataset.id)
# update segment to disable
session.execute(
update(DocumentSegment)
.where(DocumentSegment.document_id == document.id)
.values(
enabled=False,
disabled_at=naive_utc_now(),
disabled_by=document.disabled_by,
updated_at=naive_utc_now(),
)
)
session.commit()
end_at = time.perf_counter()
logger.info(
click.style(
f"Document removed from index: {document.id} latency: {end_at - start_at}",
fg="green",
)
)
except Exception:
logger.exception("remove document from index failed")
if not document.archived:
document.enabled = True
session.commit()
finally:
redis_client.delete(indexing_cache_key)
@@ -0,0 +1,165 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from configs import dify_config
from core.app.apps.pipeline.pipeline_generator import PipelineGenerator
from core.db.session_factory import get_session_maker, session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from enums import DeploymentEdition
from extensions.application_services.data_sources import build_data_source_credentials
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models import Account, Tenant
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import IndexingStatus
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
from services.feature_service import FeatureService
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.resource_scope import DatasetRef
from services.rag_pipeline.rag_pipeline import RagPipelineService
from services.workflow_run_agg import WorkflowRunAgg
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def retry_document_indexing_task(dataset_id: str, document_ids: list[str], user_id: str):
"""
Async process document
:param dataset_id:
:param document_ids:
:param user_id:
Usage: retry_document_indexing_task.delay(dataset_id, document_ids, user_id)
"""
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 not dataset:
logger.info(click.style(f"Dataset not found: {dataset_id}", fg="red"))
return
user = session.scalar(select(Account).where(Account.id == user_id).limit(1))
if not user:
logger.info(click.style(f"User not found: {user_id}", fg="red"))
return
tenant = session.scalar(select(Tenant).where(Tenant.id == dataset.tenant_id).limit(1))
if not tenant:
raise ValueError("Tenant not found")
user.set_current_tenant_with_session(tenant, session=session)
for document_id in document_ids:
retry_indexing_cache_key = f"document_{document_id}_is_retried"
# check document limit
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
features = FeatureService.get_features(tenant.id)
try:
vector_space = features.vector_space
assert vector_space is not None
if 0 < vector_space.limit <= vector_space.size:
raise ValueError(
"Your total number of documents plus the number of uploads have over the limit of "
"your subscription."
)
except Exception as e:
document = session.scalar(
select(Document)
.where(Document.id == document_id, Document.dataset_id == dataset_id)
.limit(1)
)
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = str(e)
document.stopped_at = naive_utc_now()
session.add(document)
session.commit()
redis_client.delete(retry_indexing_cache_key)
return
logger.info(click.style(f"Start retry document: {document_id}", fg="green"))
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if not document:
logger.info(click.style(f"Document not found: {document_id}", fg="yellow"))
return
try:
# clean old data
index_processor = IndexProcessorFactory(document.doc_form).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,
)
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)
session.commit()
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
session.add(document)
document_ref = DatasetRef(document.tenant_id, document.dataset_id).document(document.id)
runtime_mode = dataset.runtime_mode
# Persist preparation before handing off to the selected execution service.
session.commit()
if runtime_mode == "rag_pipeline":
with session_factory.create_session() as rag_session:
rag_pipeline_service = RagPipelineService(rag_session)
rag_pipeline_service.retry_error_document(
dataset,
document,
user,
generator=PipelineGenerator(
execution_driver=WorkflowRunAgg.run,
documents=SQLAlchemyDocumentRepository(
session_factory=session_factory.get_session_maker()
),
datasource_providers=build_data_source_credentials(
database_client=get_session_maker()
).providers,
),
)
else:
indexing_service = build_document_indexing_service(
session_factory=session_factory.get_session_maker(), enforce_vector_space_admission=True
)
indexing_service.run([document_ref])
redis_client.delete(retry_indexing_cache_key)
except Exception as ex:
session.rollback()
document = session.scalar(
select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1)
)
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = str(ex)
document.stopped_at = naive_utc_now()
session.add(document)
session.commit()
logger.info(click.style(str(ex), fg="yellow"))
redis_client.delete(retry_indexing_cache_key)
logger.exception("retry_document_indexing_task failed, document_id: %s", document_id)
end_at = time.perf_counter()
logger.info(click.style(f"Retry dataset: {dataset_id} latency: {end_at - start_at}", fg="green"))
except Exception as e:
logger.exception(
"retry_document_indexing_task failed, dataset_id: %s, document_ids: %s", dataset_id, document_ids
)
raise e
@@ -0,0 +1,122 @@
import logging
import time
import click
from celery import shared_task
from sqlalchemy import delete, select
from configs import dify_config
from core.db.session_factory import session_factory
from core.rag.index_processor.index_processor import IndexProcessorFactory
from enums import DeploymentEdition
from extensions.ext_redis import redis_client
from libs.datetime_utils import naive_utc_now
from models.dataset import Dataset, DocumentSegment
from models.enums import DataSourceType, IndexingStatus
from repositories.knowledge.document_repository import _get_document
from services.feature_service import FeatureService
from services.knowledge.indexing.adapters.execution import build_document_indexing_service
from services.knowledge.resource_scope import DatasetRef
logger = logging.getLogger(__name__)
@shared_task(queue="dataset")
def sync_website_document_indexing_task(dataset_id: str, document_id: str):
"""
Async process document
:param dataset_id:
:param document_id:
Usage: sync_website_document_indexing_task.delay(dataset_id, document_id)
"""
start_at = time.perf_counter()
with session_factory.create_session() as session:
dataset = session.scalar(select(Dataset).where(Dataset.id == dataset_id).limit(1))
if dataset is None:
raise ValueError("Dataset not found")
tenant_id = dataset.tenant_id
dataset_ref = DatasetRef(tenant_id=dataset.tenant_id, dataset_id=dataset.id)
document_ref = dataset_ref.document(document_id)
document = _get_document(session, document_ref)
if document is None:
logger.info(click.style(f"Document not found: {document_id}", fg="yellow"))
return
if document.data_source_type != DataSourceType.WEBSITE_CRAWL:
raise ValueError("Document is not a website document")
sync_indexing_cache_key = f"document_{document_id}_is_sync"
# 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
if 0 < vector_space.limit <= vector_space.size:
raise ValueError(
"Your total number of documents plus the number of uploads have over the limit of "
"your subscription."
)
except Exception as e:
document.indexing_status = IndexingStatus.ERROR
document.error = str(e)
document.stopped_at = naive_utc_now()
session.add(document)
session.commit()
redis_client.delete(sync_indexing_cache_key)
return
logger.info(click.style(f"Start sync website document: {document_id}", fg="green"))
try:
# clean old data
index_processor = IndexProcessorFactory(document.doc_form).init_index_processor()
segments = session.scalars(
select(DocumentSegment).where(
DocumentSegment.tenant_id == tenant_id,
DocumentSegment.dataset_id == dataset_id,
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
if index_node_ids:
index_processor.clean(
dataset, index_node_ids, with_keywords=True, delete_child_chunks=True, session=session
)
segment_ids = [segment.id for segment in segments]
if segment_ids:
segment_delete_stmt = delete(DocumentSegment).where(
DocumentSegment.id.in_(segment_ids),
DocumentSegment.tenant_id == tenant_id,
DocumentSegment.dataset_id == dataset_id,
DocumentSegment.document_id == document_id,
)
session.execute(segment_delete_stmt)
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())
# Release document/segment locks before extraction starts.
session.commit()
indexing_service.run([document_ref])
redis_client.delete(sync_indexing_cache_key)
except Exception as ex:
session.rollback()
document = _get_document(session, document_ref)
if document:
document.indexing_status = IndexingStatus.ERROR
document.error = str(ex)
document.stopped_at = naive_utc_now()
session.add(document)
session.commit()
logger.info(click.style(str(ex), fg="yellow"))
redis_client.delete(sync_indexing_cache_key)
logger.exception("sync_website_document_indexing_task failed, document_id: %s", document_id)
end_at = time.perf_counter()
logger.info(click.style(f"Sync document: {document_id} latency: {end_at - start_at}", fg="green"))
@@ -0,0 +1,112 @@
"""Celery entry points of the trace pipeline, routed by ``OPS_TRACE_QUEUE``.
Delivery is at most once per sink: an event is redelivered only while its
records are not persisted yet, or when the Agent collector could not decide
ownership (enterprise telemetry is then skipped, it already ran).
"""
import logging
import re
from datetime import UTC, date, datetime, timedelta
from typing import Any
from celery import shared_task
from dify_trace_sdk.events import TraceEvent
from extensions.ext_application_services import application_services
from extensions.ext_storage import storage
from services.tracing.adapters import PAYLOAD_PREFIX
from services.tracing.delivery import ExportJob
from services.tracing.errors import SourceNotFoundError, SourceNotReadyError, TraceCollectorUnavailableError
logger = logging.getLogger(__name__)
REDELIVERY_LIMIT = 10
PAYLOAD_RETENTION = timedelta(days=2)
_PAYLOAD_DAY = re.compile(rf"{PAYLOAD_PREFIX}/(\d{{4}}-\d{{2}}-\d{{2}})/")
def _expired(key: str, cutoff: date) -> bool:
match = _PAYLOAD_DAY.match(key)
if match is None:
return False
try:
return date.fromisoformat(match.group(1)) < cutoff
except ValueError:
return False
def _redelivery_delay(retries: int) -> int:
return min(60, 5 * 2**retries)
def _delete_quietly(key: str) -> None:
try:
storage.delete(key)
except Exception:
logger.warning("Trace payload cleanup failed: key=%s", key, exc_info=True)
@shared_task(bind=True, max_retries=REDELIVERY_LIMIT)
def deliver_trace_event(self, envelope: dict[str, Any]) -> None:
payload_key = envelope.get("payload_key")
redelivering = False
try:
raw = storage.load(payload_key) if isinstance(payload_key, str) else envelope["event"]
event = TraceEvent.model_validate_json(raw)
except Exception:
logger.warning("Trace event unreadable; dropped", exc_info=True)
if isinstance(payload_key, str):
_delete_quietly(payload_key)
return
try:
application_services().tracing.delivery.deliver(
event, enterprise_delivered=envelope.get("enterprise_delivered") is True
)
except SourceNotFoundError:
logger.info("Trace event source not found; dropped: kind=%s app_id=%s", event.payload.kind, event.app_id)
except SourceNotReadyError:
if self.request.retries < REDELIVERY_LIMIT:
redelivering = True
raise self.retry(args=(envelope,), countdown=_redelivery_delay(self.request.retries)) from None
logger.warning("Trace event source never became ready; dropped: kind=%s", event.payload.kind)
except TraceCollectorUnavailableError:
if self.request.retries < REDELIVERY_LIMIT:
redelivering = True
raise self.retry(
args=({**envelope, "enterprise_delivered": True},),
countdown=_redelivery_delay(self.request.retries),
) from None
logger.warning("Agent trace collector unavailable; dropped: kind=%s", event.payload.kind)
finally:
if isinstance(payload_key, str) and not redelivering:
_delete_quietly(payload_key)
@shared_task
def retry_trace_export(job_key: str) -> None:
try:
job = ExportJob.model_validate_json(storage.load(job_key))
except Exception:
logger.warning("Trace export job unreadable; dropped: key=%s", job_key, exc_info=True)
_delete_quietly(job_key)
return
try:
application_services().tracing.delivery.retry(job)
finally:
_delete_quietly(job_key)
@shared_task
def sweep_trace_payloads() -> None:
"""Delete expired new-pipeline payloads; legacy workers still own their payloads during an upgrade."""
cutoff = (datetime.now(UTC) - PAYLOAD_RETENTION).date()
# Directory listings need the trailing slash on some storage backends.
prefix = f"{PAYLOAD_PREFIX}/"
try:
keys = storage.scan(prefix, files=True)
except (FileNotFoundError, NotImplementedError):
return
for key in keys:
if key.startswith(prefix) and _expired(key, cutoff):
_delete_quietly(key)
@@ -0,0 +1,543 @@
"""
Celery tasks for async trigger processing.
These tasks handle trigger workflow execution asynchronously
to avoid blocking the main request thread.
"""
import json
import logging
from collections.abc import Mapping, Sequence
from datetime import UTC, datetime
from typing import Any, Protocol
from celery import shared_task
from sqlalchemy import select
from sqlalchemy.orm import Session
from core.db.session_factory import session_factory
from core.plugin.entities.plugin_daemon import CredentialType
from core.plugin.entities.request import TriggerInvokeEventResponse
from core.plugin.impl.exc import PluginInvokeError
from core.trigger.constants import TRIGGER_PLUGIN_NODE_TYPE
from core.trigger.debug.event_bus import TriggerDebugEventBus
from core.trigger.debug.events import PluginTriggerDebugEvent, build_plugin_pool_key
from core.trigger.entities.entities import TriggerProviderEntity
from core.trigger.provider import PluginTriggerProviderController
from core.trigger.trigger_manager import TriggerManager
from core.workflow.nodes.trigger_plugin.entities import TriggerEventNodeData
from enums import QuotaType
from extensions.ext_application_services import application_services
from graphon.enums import WorkflowExecutionStatus
from models.enums import (
AppTriggerType,
CreatorUserRole,
EndUserType,
WorkflowRunTriggeredFrom,
WorkflowTriggerStatus,
)
from models.model import App, EndUser
from models.provider_ids import TriggerProviderID
from models.trigger import TriggerSubscription, WorkflowPluginTrigger, WorkflowTriggerLog
from models.workflow import Workflow, WorkflowAppLog, WorkflowAppLogCreatedFrom, WorkflowRun
from services.async_workflow_service import AsyncWorkflowService
from services.errors.app import QuotaExceededError
from services.quota_service import QuotaService, unlimited
from services.trigger.app_trigger_service import AppTriggerService
from services.trigger.trigger_provider_service import TriggerProviderService
from services.trigger.trigger_request_service import TriggerHttpRequestCachingService
from services.trigger.trigger_subscription_operator_service import TriggerSubscriptionOperatorService
from services.workflow.entities import PluginTriggerData, PluginTriggerDispatchData, PluginTriggerMetadata
from services.workflow.queue_dispatcher import QueueDispatcherManager
logger = logging.getLogger(__name__)
# Use workflow queue for trigger processing
TRIGGER_QUEUE = "triggered_workflow_dispatcher"
class TriggerEndUserProvisioner(Protocol):
def create_end_user_batch(
self,
type: EndUserType,
tenant_id: str,
app_ids: list[str],
user_id: str,
) -> Mapping[str, EndUser]: ...
def dispatch_trigger_debug_event(
events: list[str],
user_id: str,
timestamp: int,
request_id: str,
subscription: TriggerSubscription,
) -> int:
debug_dispatched = 0
try:
for event_name in events:
pool_key: str = build_plugin_pool_key(
name=event_name,
tenant_id=subscription.tenant_id,
subscription_id=subscription.id,
provider_id=subscription.provider_id,
)
trigger_debug_event: PluginTriggerDebugEvent = PluginTriggerDebugEvent(
timestamp=timestamp,
user_id=user_id,
name=event_name,
request_id=request_id,
subscription_id=subscription.id,
provider_id=subscription.provider_id,
)
debug_dispatched += TriggerDebugEventBus.dispatch(
tenant_id=subscription.tenant_id,
event=trigger_debug_event,
pool_key=pool_key,
)
logger.debug(
"Trigger debug dispatched %d sessions to pool %s for event %s for subscription %s provider %s",
debug_dispatched,
pool_key,
event_name,
subscription.id,
subscription.provider_id,
)
return debug_dispatched
except Exception:
logger.exception("Failed to dispatch to debug sessions")
return 0
def _get_published_workflows_by_app_ids(
session: Session, subscribers: Sequence[WorkflowPluginTrigger]
) -> Mapping[str, Workflow]:
"""Get current published workflows through apps.workflow_id."""
app_ids = {trigger.app_id for trigger in subscribers}
tenant_ids = {trigger.tenant_id for trigger in subscribers}
if not app_ids or not tenant_ids:
return {}
workflows = session.scalars(
select(Workflow)
.join(App, App.workflow_id == Workflow.id)
.where(
App.id.in_(app_ids),
App.tenant_id.in_(tenant_ids),
App.workflow_id.isnot(None),
Workflow.app_id == App.id,
Workflow.tenant_id == App.tenant_id,
Workflow.version != Workflow.VERSION_DRAFT,
)
).all()
return {w.app_id: w for w in workflows}
def _record_trigger_failure_log(
*,
session: Session,
workflow: Workflow,
plugin_trigger: WorkflowPluginTrigger,
subscription: TriggerSubscription,
trigger_metadata: PluginTriggerMetadata,
end_user: EndUser | None,
error_message: str,
event_name: str,
request_id: str,
) -> None:
"""
Persist a workflow run, workflow app log, and trigger log entry for failed trigger invocations.
"""
now = datetime.now(UTC)
if end_user:
created_by_role = CreatorUserRole.END_USER
created_by = end_user.id
else:
created_by_role = CreatorUserRole.ACCOUNT
created_by = subscription.user_id
failure_inputs = {
"event_name": event_name,
"subscription_id": subscription.id,
"request_id": request_id,
"plugin_trigger_id": plugin_trigger.id,
}
workflow_run = WorkflowRun(
tenant_id=workflow.tenant_id,
app_id=workflow.app_id,
workflow_id=workflow.id,
type=workflow.type,
triggered_from=WorkflowRunTriggeredFrom.PLUGIN,
version=workflow.version,
graph=workflow.graph,
inputs=json.dumps(failure_inputs),
status=WorkflowExecutionStatus.FAILED,
outputs="{}",
error=error_message,
elapsed_time=0.0,
total_tokens=0,
total_steps=0,
created_by_role=created_by_role,
created_by=created_by,
finished_at=now,
exceptions_count=0,
)
workflow_run.created_at = now
session.add(workflow_run)
session.flush()
workflow_app_log = WorkflowAppLog(
tenant_id=workflow.tenant_id,
app_id=workflow.app_id,
workflow_id=workflow.id,
workflow_run_id=workflow_run.id,
created_from=WorkflowAppLogCreatedFrom.SERVICE_API,
created_by_role=created_by_role,
created_by=created_by,
)
session.add(workflow_app_log)
dispatcher = QueueDispatcherManager.get_dispatcher(subscription.tenant_id)
queue_name = dispatcher.get_queue_name()
trigger_data = PluginTriggerData(
app_id=plugin_trigger.app_id,
tenant_id=subscription.tenant_id,
workflow_id=workflow.id,
root_node_id=plugin_trigger.node_id,
inputs={},
trigger_metadata=trigger_metadata,
plugin_id=subscription.provider_id,
endpoint_id=subscription.endpoint_id,
)
trigger_log = WorkflowTriggerLog(
tenant_id=workflow.tenant_id,
app_id=workflow.app_id,
workflow_id=workflow.id,
workflow_run_id=workflow_run.id,
root_node_id=plugin_trigger.node_id,
trigger_metadata=trigger_metadata.model_dump_json(),
trigger_type=AppTriggerType.TRIGGER_PLUGIN,
trigger_data=trigger_data.model_dump_json(),
inputs=json.dumps({}),
status=WorkflowTriggerStatus.FAILED,
error=error_message,
queue_name=queue_name,
retry_count=0,
created_by_role=created_by_role,
created_by=created_by,
triggered_at=now,
finished_at=now,
elapsed_time=0.0,
total_tokens=0,
outputs=None,
celery_task_id=None,
)
session.add(trigger_log)
session.commit()
def dispatch_triggered_workflow(
user_id: str,
subscription: TriggerSubscription,
event_name: str,
request_id: str,
*,
end_users: TriggerEndUserProvisioner,
) -> int:
"""Process triggered workflows.
Args:
user_id: The ID of the user who activated the trigger
subscription: The trigger subscription
event_name: The name of the trigger event that was activated
request_id: The ID of the stored request in storage system
end_users: Provisioner that resolves or creates the end users for each app
Returns:
The number of workflows dispatched for the event
"""
request = TriggerHttpRequestCachingService.get_request(request_id)
payload = TriggerHttpRequestCachingService.get_payload(request_id)
subscribers: list[WorkflowPluginTrigger] = TriggerSubscriptionOperatorService.get_subscriber_triggers(
tenant_id=subscription.tenant_id, subscription_id=subscription.id, event_name=event_name
)
if not subscribers:
logger.warning(
"No workflows found for trigger event '%s' in subscription '%s'",
event_name,
subscription.id,
)
return 0
dispatched_count = 0
provider_controller: PluginTriggerProviderController = TriggerManager.get_trigger_provider(
tenant_id=subscription.tenant_id, provider_id=TriggerProviderID(subscription.provider_id)
)
trigger_entity: TriggerProviderEntity = provider_controller.entity
# Ensure expire_on_commit is set to False to remain workflows available
with session_factory.create_session() as session:
workflows: Mapping[str, Workflow] = _get_published_workflows_by_app_ids(session, subscribers)
end_users_by_app: Mapping[str, EndUser] = end_users.create_end_user_batch(
type=EndUserType.TRIGGER,
tenant_id=subscription.tenant_id,
app_ids=[plugin_trigger.app_id for plugin_trigger in subscribers],
user_id=user_id,
)
for plugin_trigger in subscribers:
workflow: Workflow | None = workflows.get(plugin_trigger.app_id)
if not workflow:
logger.error(
"Workflow not found for app %s",
plugin_trigger.app_id,
)
continue
event_node = None
for node_id, node_config in workflow.walk_nodes(TRIGGER_PLUGIN_NODE_TYPE):
if node_id == plugin_trigger.node_id:
event_node = node_config
break
if not event_node:
logger.error("Trigger event node not found for app %s", plugin_trigger.app_id)
continue
trigger_metadata = PluginTriggerMetadata(
plugin_unique_identifier=provider_controller.plugin_unique_identifier or "",
endpoint_id=subscription.endpoint_id,
provider_id=subscription.provider_id,
event_name=event_name,
icon_filename=trigger_entity.identity.icon or "",
icon_dark_filename=trigger_entity.identity.icon_dark or "",
)
quota_charge = unlimited()
try:
quota_charge = QuotaService.reserve(QuotaType.TRIGGER, subscription.tenant_id)
except QuotaExceededError:
AppTriggerService.mark_tenant_triggers_rate_limited(subscription.tenant_id)
logger.info("Tenant %s rate limited, skipping plugin trigger %s", subscription.tenant_id, plugin_trigger.id)
return dispatched_count
node_data: TriggerEventNodeData = TriggerEventNodeData.model_validate(event_node)
invoke_response: TriggerInvokeEventResponse | None = None
with session_factory.create_session() as session:
try:
invoke_response = TriggerManager.invoke_trigger_event(
tenant_id=subscription.tenant_id,
user_id=user_id,
provider_id=TriggerProviderID(subscription.provider_id),
event_name=event_name,
parameters=node_data.resolve_parameters(
parameter_schemas=provider_controller.get_event_parameters(event_name=event_name)
),
credentials=subscription.credentials,
credential_type=CredentialType.of(subscription.credential_type),
subscription=subscription.to_entity(),
request=request,
payload=payload,
)
except PluginInvokeError as e:
quota_charge.refund()
error_message = e.to_user_friendly_error(plugin_name=trigger_entity.identity.name)
try:
end_user = end_users_by_app.get(plugin_trigger.app_id)
_record_trigger_failure_log(
session=session,
workflow=workflow,
plugin_trigger=plugin_trigger,
subscription=subscription,
trigger_metadata=trigger_metadata,
end_user=end_user,
error_message=error_message,
event_name=event_name,
request_id=request_id,
)
except Exception:
logger.exception(
"Failed to record trigger failure log for app %s",
plugin_trigger.app_id,
)
continue
except Exception:
quota_charge.refund()
logger.exception(
"Failed to invoke trigger event for app %s",
plugin_trigger.app_id,
)
continue
if invoke_response is not None and invoke_response.cancelled:
quota_charge.refund()
logger.info(
"Trigger ignored for app %s with trigger event %s",
plugin_trigger.app_id,
event_name,
)
continue
# Create trigger data for async execution
trigger_data = PluginTriggerData(
app_id=plugin_trigger.app_id,
tenant_id=subscription.tenant_id,
workflow_id=workflow.id,
root_node_id=plugin_trigger.node_id,
plugin_id=subscription.provider_id,
endpoint_id=subscription.endpoint_id,
inputs=invoke_response.variables,
trigger_metadata=trigger_metadata,
)
# Trigger async workflow
try:
end_user = end_users_by_app.get(plugin_trigger.app_id)
if not end_user:
raise ValueError(f"End user not found for app {plugin_trigger.app_id}")
AsyncWorkflowService.trigger_workflow_async(session=session, user=end_user, trigger_data=trigger_data)
quota_charge.commit()
dispatched_count += 1
logger.info(
"Triggered workflow for app %s with trigger event %s",
plugin_trigger.app_id,
event_name,
)
except Exception:
quota_charge.refund()
logger.exception(
"Failed to trigger workflow for app %s",
plugin_trigger.app_id,
)
return dispatched_count
def dispatch_triggered_workflows(
user_id: str,
events: list[str],
subscription: TriggerSubscription,
request_id: str,
*,
end_users: TriggerEndUserProvisioner,
) -> int:
dispatched_count = 0
for event_name in events:
try:
dispatched_count += dispatch_triggered_workflow(
user_id=user_id,
subscription=subscription,
event_name=event_name,
request_id=request_id,
end_users=end_users,
)
except Exception:
logger.exception(
"Failed to dispatch trigger '%s' for subscription %s and provider %s. Continuing...",
event_name,
subscription.id,
subscription.provider_id,
)
# Continue processing other triggers even if one fails
continue
logger.info(
"Completed async trigger dispatching: processed %d/%d triggers for subscription %s and provider %s",
dispatched_count,
len(events),
subscription.id,
subscription.provider_id,
)
return dispatched_count
@shared_task(queue=TRIGGER_QUEUE)
def dispatch_triggered_workflows_async(
dispatch_data: Mapping[str, Any],
) -> Mapping[str, Any]:
"""
Dispatch triggers asynchronously.
Args:
dispatch_data: Dispatch payload validated into PluginTriggerDispatchData,
carrying user_id, tenant_id, endpoint_id, provider_id,
subscription_id, timestamp, events, and request_id
Returns:
dict: Execution result with status and dispatched trigger count
"""
dispatch_params: PluginTriggerDispatchData = PluginTriggerDispatchData.model_validate(dispatch_data)
user_id = dispatch_params.user_id
tenant_id = dispatch_params.tenant_id
endpoint_id = dispatch_params.endpoint_id
provider_id = dispatch_params.provider_id
subscription_id = dispatch_params.subscription_id
timestamp = dispatch_params.timestamp
events = dispatch_params.events
request_id = dispatch_params.request_id
try:
logger.info(
"Starting trigger dispatching uid=%s, endpoint=%s, events=%s, req_id=%s, sub_id=%s, provider_id=%s",
user_id,
endpoint_id,
events,
request_id,
subscription_id,
provider_id,
)
subscription: TriggerSubscription | None = TriggerProviderService.get_subscription_by_id(
tenant_id=tenant_id,
subscription_id=subscription_id,
)
if not subscription:
logger.error("Subscription not found: %s", subscription_id)
return {"status": "failed", "error": "Subscription not found"}
workflow_dispatched = dispatch_triggered_workflows(
user_id=user_id,
events=events,
subscription=subscription,
request_id=request_id,
end_users=application_services().app_scoped_end_users.commands,
)
debug_dispatched = dispatch_trigger_debug_event(
events=events,
user_id=user_id,
timestamp=timestamp,
request_id=request_id,
subscription=subscription,
)
return {
"status": "completed",
"total_count": len(events),
"workflows": workflow_dispatched,
"debug_events": debug_dispatched,
}
except Exception as e:
logger.exception(
"Error in async trigger dispatching for endpoint %s data %s for subscription %s and provider %s",
endpoint_id,
dispatch_data,
subscription_id,
provider_id,
)
return {
"status": "failed",
"error": str(e),
}
@@ -0,0 +1,120 @@
import logging
from collections.abc import Mapping
from typing import Any
from celery import shared_task
from sqlalchemy import select
from sqlalchemy.orm import Session
from configs import dify_config
from core.db.session_factory import session_factory
from core.plugin.entities.plugin_daemon import CredentialType
from core.trigger.utils.locks import build_trigger_refresh_lock_key
from extensions.ext_redis import redis_client
from libs.helper import current_timestamp
from models.trigger import TriggerSubscription
from services.trigger.trigger_provider_service import TriggerProviderService
logger = logging.getLogger(__name__)
def _load_subscription(session: Session, tenant_id: str, subscription_id: str) -> TriggerSubscription | None:
return session.scalar(
select(TriggerSubscription)
.where(TriggerSubscription.tenant_id == tenant_id, TriggerSubscription.id == subscription_id)
.limit(1)
)
def _refresh_oauth_if_expired(tenant_id: str, subscription: TriggerSubscription, now: int) -> None:
threshold_seconds: int = int(dify_config.TRIGGER_PROVIDER_CREDENTIAL_THRESHOLD_SECONDS)
if (
subscription.credential_expires_at != -1
and int(subscription.credential_expires_at) <= now + threshold_seconds
and CredentialType.of(subscription.credential_type) == CredentialType.OAUTH2
):
logger.info(
"Refreshing OAuth token: tenant=%s subscription_id=%s expires_at=%s now=%s",
tenant_id,
subscription.id,
subscription.credential_expires_at,
now,
)
try:
result: Mapping[str, Any] = TriggerProviderService.refresh_oauth_token(
tenant_id=tenant_id, subscription_id=subscription.id
)
logger.info(
"OAuth token refreshed: tenant=%s subscription_id=%s result=%s", tenant_id, subscription.id, result
)
except Exception:
logger.exception("OAuth refresh failed: tenant=%s subscription_id=%s", tenant_id, subscription.id)
def _refresh_subscription_if_expired(
tenant_id: str,
subscription: TriggerSubscription,
now: int,
) -> None:
threshold_seconds: int = int(dify_config.TRIGGER_PROVIDER_SUBSCRIPTION_THRESHOLD_SECONDS)
if subscription.expires_at == -1 or int(subscription.expires_at) > now + threshold_seconds:
logger.debug(
"Subscription not due: tenant=%s subscription_id=%s expires_at=%s now=%s threshold=%s",
tenant_id,
subscription.id,
subscription.expires_at,
now,
threshold_seconds,
)
return
try:
result: Mapping[str, Any] = TriggerProviderService.refresh_subscription(
tenant_id=tenant_id, subscription_id=subscription.id, now=now
)
logger.info(
"Subscription refreshed: tenant=%s subscription_id=%s result=%s",
tenant_id,
subscription.id,
result.get("result"),
)
except Exception:
logger.exception("Subscription refresh failed: tenant=%s id=%s", tenant_id, subscription.id)
@shared_task(queue="trigger_refresh_executor")
def trigger_subscription_refresh(tenant_id: str, subscription_id: str) -> None:
"""Refresh a trigger subscription if needed, guarded by a Redis in-flight lock."""
lock_key: str = build_trigger_refresh_lock_key(tenant_id, subscription_id)
if not redis_client.get(lock_key):
logger.debug("Refresh lock missing, skip: %s", lock_key)
return
logger.info("Begin subscription refresh: tenant=%s id=%s", tenant_id, subscription_id)
try:
now: int = current_timestamp()
with session_factory.create_session() as session:
subscription: TriggerSubscription | None = _load_subscription(session, tenant_id, subscription_id)
if not subscription:
logger.warning("Subscription not found: tenant=%s id=%s", tenant_id, subscription_id)
return
logger.debug(
"Loaded subscription: tenant=%s id=%s cred_exp=%s sub_exp=%s now=%s",
tenant_id,
subscription.id,
subscription.credential_expires_at,
subscription.expires_at,
now,
)
_refresh_oauth_if_expired(tenant_id=tenant_id, subscription=subscription, now=now)
_refresh_subscription_if_expired(tenant_id=tenant_id, subscription=subscription, now=now)
finally:
try:
redis_client.delete(lock_key)
logger.debug("Lock released: %s", lock_key)
except Exception:
# Best-effort lock cleanup
logger.warning("Failed to release lock: %s", lock_key, exc_info=True)
@@ -0,0 +1,33 @@
from typing import override
from services.workflow.entities import WorkflowScheduleCFSPlanEntity
from services.workflow.scheduler import CFSPlanScheduler, SchedulerCommand
from tasks.workflow_cfs_scheduler.entities import AsyncWorkflowQueue
class AsyncWorkflowCFSPlanEntity(WorkflowScheduleCFSPlanEntity):
"""
Trigger workflow CFS plan entity.
"""
queue: AsyncWorkflowQueue
class AsyncWorkflowCFSPlanScheduler(CFSPlanScheduler[AsyncWorkflowCFSPlanEntity]):
"""
Trigger workflow CFS plan scheduler.
"""
@override
def can_schedule(self) -> SchedulerCommand:
"""
Check if the workflow can be scheduled.
"""
if self.plan.queue in [AsyncWorkflowQueue.PROFESSIONAL_QUEUE, AsyncWorkflowQueue.TEAM_QUEUE]:
"""
permitted all paid users to schedule the workflow any time
"""
return SchedulerCommand.NONE
# FIXME: avoid the sandbox user's workflow at a running state for ever
return SchedulerCommand.RESOURCE_LIMIT_REACHED
@@ -0,0 +1,26 @@
from enum import StrEnum
from configs import dify_config
from enums import DeploymentEdition
from services.workflow.entities import WorkflowScheduleCFSPlanEntity
# Determine queue names based on edition
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
# Cloud edition: separate queues for different tiers
_professional_queue = "workflow_professional"
_team_queue = "workflow_team"
_sandbox_queue = "workflow_sandbox"
AsyncWorkflowSystemStrategy = WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice
else:
# Community edition: single workflow queue (not dataset)
_professional_queue = "workflow"
_team_queue = "workflow"
_sandbox_queue = "workflow"
AsyncWorkflowSystemStrategy = WorkflowScheduleCFSPlanEntity.Strategy.Nop
class AsyncWorkflowQueue(StrEnum):
# Define constants
PROFESSIONAL_QUEUE = _professional_queue
TEAM_QUEUE = _team_queue
SANDBOX_QUEUE = _sandbox_queue
@@ -0,0 +1,21 @@
"""
Celery tasks for asynchronous workflow execution storage operations.
These tasks provide asynchronous storage capabilities for workflow execution data,
improving performance by offloading storage operations to background workers.
"""
from celery import shared_task # type: ignore[import-untyped]
from core.db.session_factory import session_factory
from services.workflow_draft_variable_service import DraftVarFileDeletion, WorkflowDraftVariableService
@shared_task(queue="workflow_draft_var", bind=True, max_retries=3, default_retry_delay=60)
def save_workflow_execution_task(
self,
deletions: list[DraftVarFileDeletion],
):
with session_factory.create_session() as session, session.begin():
srv = WorkflowDraftVariableService(session=session)
srv.delete_workflow_draft_variable_file(deletions=deletions)
@@ -0,0 +1,140 @@
"""
Celery tasks for asynchronous workflow execution storage operations.
These tasks provide asynchronous storage capabilities for workflow execution data,
improving performance by offloading storage operations to background workers.
"""
import json
import logging
from typing import Any
from celery import shared_task
from sqlalchemy import select
from core.db.session_factory import session_factory
from graphon.enums import WorkflowExecutionStatus
from graphon.workflow_type_encoder import WorkflowRuntimeTypeConverter
from models import CreatorUserRole, WorkflowRun
from models.enums import WorkflowRunTriggeredFrom
from repositories.entities.workflow_execution import WorkflowExecution
logger = logging.getLogger(__name__)
@shared_task(queue="workflow_storage", bind=True, max_retries=3, default_retry_delay=60)
def save_workflow_execution_task(
self,
execution_data: dict[str, Any],
tenant_id: str,
app_id: str,
triggered_from: str,
creator_user_id: str,
creator_user_role: str,
) -> bool:
"""
Asynchronously save or update a workflow execution to the database.
Args:
execution_data: Serialized WorkflowExecution data
tenant_id: Tenant ID for multi-tenancy
app_id: Application ID
triggered_from: Source of the execution trigger
creator_user_id: ID of the user who created the execution
creator_user_role: Role of the user who created the execution
Returns:
True if successful, False otherwise
"""
try:
with session_factory.create_session() as session:
# Deserialize execution data
execution = WorkflowExecution.model_validate(execution_data)
# Check if workflow run already exists
existing_run = session.scalar(select(WorkflowRun).where(WorkflowRun.id == execution.id_).with_for_update())
if existing_run:
# Update existing workflow run
_update_workflow_run_from_execution(existing_run, execution)
logger.debug("Updated existing workflow run: %s", execution.id_)
else:
# Create new workflow run
workflow_run = _create_workflow_run_from_execution(
execution=execution,
tenant_id=tenant_id,
app_id=app_id,
triggered_from=WorkflowRunTriggeredFrom(triggered_from),
creator_user_id=creator_user_id,
creator_user_role=CreatorUserRole(creator_user_role),
)
session.add(workflow_run)
logger.debug("Created new workflow run: %s", execution.id_)
session.commit()
return True
except Exception as e:
logger.exception("Failed to save workflow execution %s", execution_data.get("id_", "unknown"))
# Retry the task with exponential backoff
raise self.retry(exc=e, countdown=60 * (2**self.request.retries)) from e
def _create_workflow_run_from_execution(
execution: WorkflowExecution,
tenant_id: str,
app_id: str,
triggered_from: WorkflowRunTriggeredFrom,
creator_user_id: str,
creator_user_role: CreatorUserRole,
) -> WorkflowRun:
"""
Create a WorkflowRun database model from a WorkflowExecution domain entity.
"""
workflow_run = WorkflowRun()
workflow_run.id = execution.id_
workflow_run.tenant_id = tenant_id
workflow_run.app_id = app_id
workflow_run.workflow_id = execution.workflow_id
from models.workflow import WorkflowType as ModelWorkflowType
workflow_run.type = ModelWorkflowType(execution.workflow_type.value)
workflow_run.triggered_from = triggered_from
workflow_run.version = execution.workflow_version
json_converter = WorkflowRuntimeTypeConverter()
workflow_run.graph = json.dumps(json_converter.to_json_encodable(execution.graph), ensure_ascii=False)
workflow_run.inputs = json.dumps(json_converter.to_json_encodable(execution.inputs), ensure_ascii=False)
workflow_run.status = execution.status
workflow_run.outputs = (
json.dumps(json_converter.to_json_encodable(execution.outputs), ensure_ascii=False)
if execution.outputs
else "{}"
)
workflow_run.error = execution.error_message
workflow_run.elapsed_time = execution.elapsed_time
workflow_run.total_tokens = execution.total_tokens
workflow_run.total_steps = execution.total_steps
workflow_run.created_by_role = creator_user_role
workflow_run.created_by = creator_user_id
workflow_run.created_at = execution.started_at
workflow_run.finished_at = execution.finished_at
return workflow_run
def _update_workflow_run_from_execution(workflow_run: WorkflowRun, execution: WorkflowExecution):
"""
Update a WorkflowRun database model from a WorkflowExecution domain entity.
"""
if workflow_run.stop_requested_at is not None and workflow_run.status == WorkflowExecutionStatus.STOPPED:
return
json_converter = WorkflowRuntimeTypeConverter()
workflow_run.status = execution.status
workflow_run.outputs = (
json.dumps(json_converter.to_json_encodable(execution.outputs)) if execution.outputs else "{}"
)
workflow_run.error = execution.error_message
workflow_run.elapsed_time = execution.elapsed_time
workflow_run.total_tokens = execution.total_tokens
workflow_run.total_steps = execution.total_steps
workflow_run.finished_at = execution.finished_at
@@ -0,0 +1,283 @@
"""
Celery tasks for asynchronous workflow node execution storage operations.
These tasks provide asynchronous storage capabilities for workflow node execution data,
improving performance by offloading storage operations to background workers.
"""
import json
import logging
from typing import Any
from celery import shared_task
from sqlalchemy import and_, or_, select
from core.db.session_factory import session_factory
from core.workflow.node_execution import WorkflowNodeExecution as DifyWorkflowNodeExecution
from core.workflow.node_execution_process_data import keep_agent_and_tool_ids
from graphon.entities.workflow_node_execution import (
WorkflowNodeExecution,
)
from graphon.enums import WorkflowNodeExecutionStatus
from graphon.workflow_type_encoder import WorkflowRuntimeTypeConverter
from models import CreatorUserRole, WorkflowNodeExecutionModel
from models.workflow import WorkflowNodeExecutionTriggeredFrom
from repositories.workflow_run_control import apply_workflow_stop_to_node, get_stopped_workflow_run
logger = logging.getLogger(__name__)
@shared_task(queue="workflow_storage", bind=True, max_retries=3, default_retry_delay=60)
def save_workflow_node_executions_task(
self,
executions_data: list[dict[str, Any]],
tenant_id: str,
app_id: str,
triggered_from: str,
creator_user_id: str,
creator_user_role: str,
) -> bool:
"""Upsert an owner-scoped cleanup batch atomically, including missing start rows."""
try:
executions = [DifyWorkflowNodeExecution.model_validate(data) for data in executions_data]
if not executions:
return True
with session_factory.create_session() as session, session.begin():
for execution in executions:
if execution.status in (
WorkflowNodeExecutionStatus.RUNNING,
WorkflowNodeExecutionStatus.PAUSED,
WorkflowNodeExecutionStatus.RETRY,
):
apply_workflow_stop_to_node(
execution,
get_stopped_workflow_run(
session, tenant_id=tenant_id, workflow_run_id=execution.workflow_execution_id, lock=True
),
)
query = WorkflowNodeExecutionModel.preload_offload_data(select(WorkflowNodeExecutionModel)).where(
WorkflowNodeExecutionModel.tenant_id == tenant_id,
WorkflowNodeExecutionModel.app_id == app_id,
WorkflowNodeExecutionModel.triggered_from == triggered_from,
or_(
*(
and_(
WorkflowNodeExecutionModel.id == execution.id,
WorkflowNodeExecutionModel.workflow_id == execution.workflow_id,
WorkflowNodeExecutionModel.workflow_run_id == execution.workflow_execution_id,
)
for execution in executions
)
),
)
existing_models = {model.id: model for model in session.scalars(query)}
for execution in executions:
existing = existing_models.get(execution.id)
if existing is None:
session.add(
_create_node_execution_from_domain(
execution,
tenant_id,
app_id,
WorkflowNodeExecutionTriggeredFrom(triggered_from),
creator_user_id,
CreatorUserRole(creator_user_role),
)
)
continue
inputs, process_data, outputs = existing.inputs, existing.process_data, existing.outputs
_update_node_execution_from_domain(existing, execution)
if existing.inputs_truncated:
existing.inputs = inputs
if existing.process_data_truncated:
existing.process_data = process_data
if existing.outputs_truncated:
existing.outputs = outputs
return True
except Exception as error:
logger.exception(
"Failed to save workflow node execution batch: %s", [data.get("id") for data in executions_data]
)
raise self.retry(exc=error, countdown=60 * (2**self.request.retries)) from error
@shared_task(queue="workflow_storage", bind=True, max_retries=3, default_retry_delay=60)
def save_workflow_node_execution_task(
self,
execution_data: dict[str, Any],
tenant_id: str,
app_id: str,
triggered_from: str,
creator_user_id: str,
creator_user_role: str,
) -> bool:
"""
Asynchronously save or update a workflow node execution to the database.
Args:
execution_data: Serialized WorkflowNodeExecution data
tenant_id: Tenant ID for multi-tenancy
app_id: Application ID
triggered_from: Source of the execution trigger
creator_user_id: ID of the user who created the execution
creator_user_role: Role of the user who created the execution
Returns:
True if successful, False otherwise
"""
try:
with session_factory.create_session() as session:
# Deserialize execution data
execution = DifyWorkflowNodeExecution.model_validate(execution_data)
if execution.status in (
WorkflowNodeExecutionStatus.RUNNING,
WorkflowNodeExecutionStatus.PAUSED,
WorkflowNodeExecutionStatus.RETRY,
):
apply_workflow_stop_to_node(
execution,
get_stopped_workflow_run(
session, tenant_id=tenant_id, workflow_run_id=execution.workflow_execution_id, lock=True
),
)
# Check if node execution already exists
existing_execution = session.scalar(
select(WorkflowNodeExecutionModel).where(
WorkflowNodeExecutionModel.id == execution.id,
WorkflowNodeExecutionModel.tenant_id == tenant_id,
WorkflowNodeExecutionModel.app_id == app_id,
WorkflowNodeExecutionModel.workflow_id == execution.workflow_id,
)
)
if existing_execution:
# Update existing node execution
_update_node_execution_from_domain(existing_execution, execution)
logger.debug("Updated existing workflow node execution: %s", execution.id)
else:
# Create new node execution
node_execution = _create_node_execution_from_domain(
execution=execution,
tenant_id=tenant_id,
app_id=app_id,
triggered_from=WorkflowNodeExecutionTriggeredFrom(triggered_from),
creator_user_id=creator_user_id,
creator_user_role=CreatorUserRole(creator_user_role),
)
session.add(node_execution)
logger.debug("Created new workflow node execution: %s", execution.id)
session.commit()
return True
except Exception as e:
logger.exception("Failed to save workflow node execution %s", execution_data.get("id", "unknown"))
# Retry the task with exponential backoff
raise self.retry(exc=e, countdown=60 * (2**self.request.retries)) from e
def _create_node_execution_from_domain(
execution: WorkflowNodeExecution,
tenant_id: str,
app_id: str,
triggered_from: WorkflowNodeExecutionTriggeredFrom,
creator_user_id: str,
creator_user_role: CreatorUserRole,
) -> WorkflowNodeExecutionModel:
"""
Create a WorkflowNodeExecutionModel database model from a WorkflowNodeExecution domain entity.
"""
node_execution = WorkflowNodeExecutionModel()
node_execution.id = execution.id
node_execution.tenant_id = tenant_id
node_execution.app_id = app_id
node_execution.workflow_id = execution.workflow_id
if isinstance(execution, DifyWorkflowNodeExecution):
node_execution.triggered_from_workflow_id = execution.triggered_from_workflow_id
node_execution.triggered_from_node_execution_id = execution.triggered_from_node_execution_id
node_execution.triggered_from = triggered_from
node_execution.workflow_run_id = execution.workflow_execution_id
node_execution.index = execution.index
node_execution.predecessor_node_id = execution.predecessor_node_id
node_execution.node_id = execution.node_id
node_execution.node_type = execution.node_type
node_execution.title = execution.title
node_execution.node_execution_id = execution.node_execution_id
# Serialize complex data as JSON
json_converter = WorkflowRuntimeTypeConverter()
node_execution.inputs = json.dumps(json_converter.to_json_encodable(execution.inputs)) if execution.inputs else "{}"
node_execution.process_data = (
json.dumps(json_converter.to_json_encodable(execution.process_data)) if execution.process_data else "{}"
)
node_execution.outputs = (
json.dumps(json_converter.to_json_encodable(execution.outputs)) if execution.outputs else "{}"
)
# Convert metadata enum keys to strings for JSON serialization
if execution.metadata:
metadata_for_json = {
key.value if hasattr(key, "value") else str(key): value for key, value in execution.metadata.items()
}
node_execution.execution_metadata = json.dumps(json_converter.to_json_encodable(metadata_for_json))
else:
node_execution.execution_metadata = "{}"
node_execution.status = execution.status
node_execution.error = execution.error
node_execution.elapsed_time = execution.elapsed_time
node_execution.created_by_role = creator_user_role
node_execution.created_by = creator_user_id
node_execution.created_at = execution.created_at
node_execution.finished_at = execution.finished_at
return node_execution
def _update_node_execution_from_domain(node_execution: WorkflowNodeExecutionModel, execution: WorkflowNodeExecution):
"""
Update a WorkflowNodeExecutionModel database model from a WorkflowNodeExecution domain entity.
"""
# Cleanup can insert the terminal row before its queued start is delivered.
if (
node_execution.status == WorkflowNodeExecutionStatus.FAILED
and node_execution.finished_at is not None
and execution.status
in (
WorkflowNodeExecutionStatus.RUNNING,
WorkflowNodeExecutionStatus.PAUSED,
WorkflowNodeExecutionStatus.RETRY,
)
):
return
if isinstance(execution, DifyWorkflowNodeExecution):
if execution.triggered_from_workflow_id is not None:
node_execution.triggered_from_workflow_id = execution.triggered_from_workflow_id
if execution.triggered_from_node_execution_id is not None:
node_execution.triggered_from_node_execution_id = execution.triggered_from_node_execution_id
# Update serialized data
json_converter = WorkflowRuntimeTypeConverter()
node_execution.inputs = json.dumps(json_converter.to_json_encodable(execution.inputs)) if execution.inputs else "{}"
process_data = keep_agent_and_tool_ids(node_execution.process_data_dict, execution.process_data)
node_execution.process_data = (
json.dumps(json_converter.to_json_encodable(process_data)) if process_data is not None else "{}"
)
node_execution.outputs = (
json.dumps(json_converter.to_json_encodable(execution.outputs)) if execution.outputs else "{}"
)
# Convert metadata enum keys to strings for JSON serialization
if execution.metadata:
metadata_for_json = {
key.value if hasattr(key, "value") else str(key): value for key, value in execution.metadata.items()
}
node_execution.execution_metadata = json.dumps(json_converter.to_json_encodable(metadata_for_json))
else:
node_execution.execution_metadata = "{}"
# Update other fields
node_execution.status = execution.status
node_execution.error = execution.error
node_execution.elapsed_time = execution.elapsed_time
node_execution.finished_at = execution.finished_at
@@ -0,0 +1,44 @@
"""Archive-only deletion jobs on the existing workflow archive queue."""
import logging
from celery import shared_task
from core.db.session_factory import get_session_maker
from extensions.ext_redis import redis_client
from libs.archive_storage import ArchiveStorageError, get_archive_storage, get_export_storage
from repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository
from services.retention.workflow_run.archive_deletion import WorkflowRunArchiveDeleter
from services.retention.workflow_run.archive_deletion_task import WorkflowRunArchiveDeletionStatus
from services.retention.workflow_run.archive_month_lock import (
RedisWorkflowRunArchiveMonthLock,
)
from tasks.workflow_run_archive_download_tasks import WORKFLOW_RUN_ARCHIVE_DOWNLOAD_QUEUE
logger = logging.getLogger(__name__)
@shared_task(
queue=WORKFLOW_RUN_ARCHIVE_DOWNLOAD_QUEUE,
acks_late=True,
reject_on_worker_lost=True,
autoretry_for=(Exception,),
retry_backoff=30,
retry_backoff_max=120,
retry_kwargs={"max_retries": 5},
)
def delete_workflow_run_archive_task(tenant_id: str, year: int, month: int) -> None:
"""Redelivery is safe because only DB rows with durable deletion requests are selected."""
logger.info("Deleting workflow run archive month: tenant=%s year=%s month=%s", tenant_id, year, month)
result = WorkflowRunArchiveDeleter(
bundles=WorkflowRunArchiveBundleQueryRepository(session_factory=get_session_maker()),
archive_storage_provider=get_archive_storage,
download_storage_provider=get_export_storage,
month_lock=RedisWorkflowRunArchiveMonthLock(redis=redis_client),
).delete(tenant_id=tenant_id, year=year, month=month)
if result.status is WorkflowRunArchiveDeletionStatus.FAILED:
# The deleter persists FAILED durably but swallows the fault: without
# raising, Celery reports SUCCESS and the configured autoretry/backoff
# never engages (#44059). Exhausting the retry budget then surfaces as
# a task failure instead of silent success.
raise ArchiveStorageError(result.error or "Failed to delete archive files. Please retry.")
@@ -0,0 +1,30 @@
"""Celery tasks for preparing workflow-run archive downloads."""
import logging
from celery import shared_task
from core.db.session_factory import get_session_maker
from extensions.ext_redis import redis_client
from libs.archive_storage import get_archive_storage, get_export_storage
from repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository
from services.retention.workflow_run.archive_download_preparation import WorkflowRunArchiveDownloadPreparer
from services.retention.workflow_run.archive_download_task_cache import WorkflowRunArchiveDownloadTaskCache
from services.retention.workflow_run.archive_month_lock import RedisWorkflowRunArchiveMonthLock
logger = logging.getLogger(__name__)
WORKFLOW_RUN_ARCHIVE_DOWNLOAD_QUEUE = "workflow_archive"
@shared_task(queue=WORKFLOW_RUN_ARCHIVE_DOWNLOAD_QUEUE)
def prepare_workflow_run_archive_download_task(tenant_id: str, download_id: str) -> None:
"""Prepare a cached workflow-run archive download in the background."""
logger.info("Preparing workflow run archive download: tenant=%s download_id=%s", tenant_id, download_id)
WorkflowRunArchiveDownloadPreparer(
archive_storage_provider=get_archive_storage,
bundles=WorkflowRunArchiveBundleQueryRepository(session_factory=get_session_maker()),
cache=WorkflowRunArchiveDownloadTaskCache(redis=redis_client),
download_storage_provider=get_export_storage,
month_lock=RedisWorkflowRunArchiveMonthLock(redis=redis_client),
).prepare(tenant_id=tenant_id, download_id=download_id)
@@ -0,0 +1,72 @@
import logging
from celery import shared_task
from core.db.session_factory import session_factory
from core.workflow.nodes.trigger_schedule.exc import (
ScheduleExecutionError,
ScheduleNotFoundError,
TenantOwnerNotFoundError,
)
from enums import QuotaType
from models.trigger import WorkflowSchedulePlan
from services.async_workflow_service import AsyncWorkflowService
from services.errors.app import QuotaExceededError
from services.quota_service import QuotaService, unlimited
from services.trigger.app_trigger_service import AppTriggerService
from services.trigger.schedule_service import ScheduleService
from services.workflow.entities import ScheduleTriggerData
logger = logging.getLogger(__name__)
@shared_task(queue="schedule_executor")
def run_schedule_trigger(schedule_id: str) -> None:
"""
Execute a scheduled workflow trigger.
Note: No retry logic needed as schedules will run again at next interval.
The execution result is tracked via WorkflowTriggerLog.
Raises:
ScheduleNotFoundError: If schedule doesn't exist
TenantOwnerNotFoundError: If no owner/admin for tenant
ScheduleExecutionError: If workflow trigger fails
"""
# Ensure expire_on_commit is set to False to remain schedule/tenant_owner available
with session_factory.create_session() as session:
schedule = session.get(WorkflowSchedulePlan, schedule_id)
if not schedule:
raise ScheduleNotFoundError(f"Schedule {schedule_id} not found")
tenant_owner = ScheduleService.get_tenant_owner(schedule.tenant_id, session=session)
if not tenant_owner:
raise TenantOwnerNotFoundError(f"No owner or admin found for tenant {schedule.tenant_id}")
quota_charge = unlimited()
try:
quota_charge = QuotaService.reserve(QuotaType.TRIGGER, schedule.tenant_id)
except QuotaExceededError:
AppTriggerService.mark_tenant_triggers_rate_limited(schedule.tenant_id)
logger.info("Tenant %s rate limited, skipping schedule trigger %s", schedule.tenant_id, schedule_id)
return
try:
with session_factory.create_session() as session:
response = AsyncWorkflowService.trigger_workflow_async(
session=session,
user=tenant_owner,
trigger_data=ScheduleTriggerData(
app_id=schedule.app_id,
root_node_id=schedule.node_id,
inputs={},
tenant_id=schedule.tenant_id,
),
)
quota_charge.commit()
logger.info("Schedule %s triggered workflow: %s", schedule_id, response.workflow_trigger_log_id)
except Exception as e:
quota_charge.refund()
raise ScheduleExecutionError(
f"Failed to trigger workflow for schedule {schedule_id}, app {schedule.app_id}"
) from e