Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

bug: fix sequence number may be duplicated when multi-threads running the same workflow #21047 (#21153)

NeatGuyCoding918bb9a2f7de
diff --git a/api/core/repositories/sqlalchemy_workflow_execution_repository.py b/api/core/repositories/sqlalchemy_workflow_execution_repository.py
index e5ead9dc569..f82562a498d 100644
--- a/api/core/repositories/sqlalchemy_workflow_execution_repository.py
+++ b/api/core/repositories/sqlalchemy_workflow_execution_repository.py
@@ -151,12 +151,17 @@ class SQLAlchemyWorkflowExecutionRepository(WorkflowExecutionRepository):
existing = session.scalar(select(WorkflowRun).where(WorkflowRun.id == domain_model.id_))
if not existing:
# For new records, get the next sequence number
- stmt = select(func.max(WorkflowRun.sequence_number)).where(
- WorkflowRun.app_id == self._app_id,
- WorkflowRun.tenant_id == self._tenant_id,
+ # in case multiple executions are created concurrently, use for update
+ stmt = (
+ select(func.coalesce(func.max(WorkflowRun.sequence_number), 0) + 1)
+ .where(
+ WorkflowRun.app_id == self._app_id,
+ WorkflowRun.tenant_id == self._tenant_id,
+ )
+ .with_for_update()
)
- max_sequence = session.scalar(stmt)
- db_model.sequence_number = (max_sequence or 0) + 1
+ next_seq = session.scalar(stmt)
+ db_model.sequence_number = int(next_seq) if next_seq is not None else 1
else:
# For updates, keep the existing sequence number
db_model.sequence_number = existing.sequence_number