mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 01:58:18 +00:00
feat(workflow): use atomic updateMany CAS locking to prevent multi-replica polling race conditions
This commit is contained in:
@@ -122,6 +122,37 @@ describe('LocalExecutor Integration Tests', () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('should atomically claim tasks using CAS updateMany to prevent double-execution when tick() runs concurrently', async () => {
|
||||
mocks.agentChat.mockResolvedValue(undefined)
|
||||
|
||||
// Mock submit to prevent automatic execution by the Prisma Client Extension
|
||||
const submitSpy = vi.spyOn(workflowService, 'submit').mockResolvedValue('dummy-id')
|
||||
|
||||
// Create a single pending task (will NOT be run automatically because submit is mocked)
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-concurrent-test',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// We trigger two ticks concurrently to simulate overlapping polling cycles or multi-replica triggers.
|
||||
// Both ticks will query the database at approximately the same time.
|
||||
const tick1 = executor.tick()
|
||||
const tick2 = executor.tick()
|
||||
|
||||
const [promises1, promises2] = await Promise.all([tick1, tick2])
|
||||
await Promise.all([...promises1, ...promises2])
|
||||
|
||||
// Verify that the mock workflow is called EXACTLY ONCE for this task ID,
|
||||
// proving that one tick successfully claimed the task and the other was atomically blocked.
|
||||
expect(mocks.agentChat).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: task.id }))
|
||||
|
||||
submitSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should query and retry stale tasks in tick() but ignore non-stale processing tasks', async () => {
|
||||
mocks.agentChat.mockResolvedValue(undefined)
|
||||
|
||||
|
||||
@@ -73,14 +73,22 @@ export class LocalExecutor implements Executor {
|
||||
this.processingTasks.add(task.id)
|
||||
|
||||
// 1. Immediately mark task as processing and set initial heartbeat in DB
|
||||
// atomically, only if the task is still pending.
|
||||
try {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
const affected = await prisma.workflowTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
data: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(),
|
||||
},
|
||||
})
|
||||
if (affected.count === 0) {
|
||||
this.processingTasks.delete(task.id)
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[LocalExecutor] Failed to mark task ${task.id} as processing in submit:`,
|
||||
@@ -159,14 +167,28 @@ export class LocalExecutor implements Executor {
|
||||
|
||||
// 1. Immediately mark task as processing and set initial heartbeat in DB
|
||||
// to guarantee no other ticks/replicas can double-query it.
|
||||
// We use updateMany to atomically claim it only if it is still pending or stale.
|
||||
try {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
const affected = await prisma.workflowTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
OR: [
|
||||
{ status: WorkflowTaskStatus.pending },
|
||||
{
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: { lt: staleTime },
|
||||
},
|
||||
],
|
||||
},
|
||||
data: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(),
|
||||
},
|
||||
})
|
||||
if (affected.count === 0) {
|
||||
this.processingTasks.delete(task.id)
|
||||
continue
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[LocalExecutor] Failed to mark task ${task.id} as processing:`, err)
|
||||
this.processingTasks.delete(task.id)
|
||||
|
||||
Reference in New Issue
Block a user