-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcancel-run.test.ts
More file actions
718 lines (649 loc) · 25.1 KB
/
Copy pathcancel-run.test.ts
File metadata and controls
718 lines (649 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActiveRunEntry, RunRegistryAdapter } from "../adapters/run-registry/types.js";
import type { IssueTrackerAdapter } from "../adapters/issue-tracker/types.js";
import type { Db } from "../db/client.js";
const state = vi.hoisted(() => ({
getRun: vi.fn(),
listSteps: vi.fn(),
stopSandboxes: vi.fn(),
tombstone: vi.fn(),
retireApproval: vi.fn(),
moveTicket: vi.fn(),
recordStatusReason: vi.fn(),
markBlockedOnCancel: vi.fn(),
markBlockedByOperator: vi.fn(),
findLiveClaim: vi.fn(),
findRunOutcome: vi.fn(),
settleOccurrence: vi.fn(),
warn: vi.fn(),
}));
vi.mock("../../env.js", () => ({
env: {
COLUMN_AI: "AI",
COLUMN_BACKLOG: "Backlog",
JIRA_BACKLOG_TRANSITION_ID: undefined,
},
}));
vi.mock("workflow/api", () => ({ getRun: state.getRun }));
vi.mock("workflow/runtime", () => ({
getWorld: () => ({ steps: { list: state.listSteps } }),
}));
vi.mock("../sandbox/stop-ticket-sandboxes.js", () => ({
stopSandboxesByIds: state.stopSandboxes,
}));
vi.mock("../db/client.js", () => ({ getDb: () => ({ db: true }) }));
vi.mock("../clarifications/store.js", () => ({
tombstoneClarificationCancellation: state.tombstone,
}));
vi.mock("../approvals/store.js", () => ({
retireApprovalCancellation: state.retireApproval,
}));
vi.mock("./ticket-transition.js", () => ({
moveTicketForRun: state.moveTicket,
withdrawTicketFromAiForRun: state.moveTicket,
}));
vi.mock("./telemetry/run-telemetry.js", () => ({
recordRunStatusReason: state.recordStatusReason,
markRunBlockedOnCancel: state.markBlockedOnCancel,
markRunBlockedByOperator: state.markBlockedByOperator,
}));
vi.mock("../db/queries/runs-read.js", () => ({
findLiveRunClaimByRunId: state.findLiveClaim,
findRunOutcomeByRunId: state.findRunOutcome,
}));
// cancelRunForOperator reaches the schedule ledger through a dynamic import, so this
// mock has to stand in for the whole module rather than one export of it.
vi.mock("../schedule-trigger/occurrence-store.js", () => ({
settleScheduleOccurrenceOnCancel: state.settleOccurrence,
}));
vi.mock("./logger.js", () => ({
logger: { warn: state.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import {
cancelRun,
cancelRunById,
cancelRunDetailed,
cancelRunForOperator,
} from "./cancel-run.js";
function active(overrides: Partial<ActiveRunEntry> = {}): ActiveRunEntry {
return {
subjectKey: "ticket:jira:PROJ-1",
ticketKey: "PROJ-1",
ownerToken: "owner-a",
runId: "run-1",
state: "bound",
kind: "ticket",
createdAt: Date.now(),
updatedAt: Date.now(),
...overrides,
};
}
function registry(entry: ActiveRunEntry | null = active()): RunRegistryAdapter {
return {
reserve: vi.fn(),
commitStartedRun: vi.fn(),
markRunEntryStarted: vi.fn(),
bindRun: vi.fn(),
beginParking: vi.fn(),
finishParking: vi.fn(),
handoff: vi.fn(),
get: vi.fn().mockResolvedValue(entry),
beginCancellation: vi.fn().mockResolvedValue(true),
releaseCancellation: vi.fn().mockResolvedValue(true),
releaseReservation: vi.fn(),
release: vi.fn(),
listAll: vi.fn(),
registerSandbox: vi.fn(),
listSandboxes: vi.fn().mockResolvedValue(["sandbox-1"]),
markFailed: vi.fn(),
isTicketFailed: vi.fn(),
listAllFailed: vi.fn(),
clearFailedMark: vi.fn(),
};
}
describe("cancelRun", () => {
beforeEach(() => {
vi.clearAllMocks();
state.getRun.mockReturnValue({ cancel: vi.fn().mockResolvedValue(undefined) });
state.listSteps.mockResolvedValue({ data: [], cursor: null, hasMore: false });
state.stopSandboxes.mockResolvedValue(undefined);
state.tombstone.mockResolvedValue({ matched: false, successorOwnerToken: null });
state.retireApproval.mockResolvedValue(0);
state.moveTicket.mockResolvedValue(undefined);
state.recordStatusReason.mockResolvedValue(undefined);
state.markBlockedOnCancel.mockResolvedValue(undefined);
});
it("closes, cancels, drains, cleans, and releases the exact owner", async () => {
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(true);
expect(runRegistry.beginCancellation).toHaveBeenCalledWith(
"ticket:jira:PROJ-1",
"owner-a",
"run-1",
);
expect(state.stopSandboxes).toHaveBeenCalledWith(["sandbox-1"]);
expect(runRegistry.releaseCancellation).toHaveBeenCalledWith(
"ticket:jira:PROJ-1",
"owner-a",
"run-1",
);
});
it("does not cancel a different owner", async () => {
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "foreign", runId: "run-1" },
runRegistry,
)).resolves.toBe(false);
expect(runRegistry.beginCancellation).not.toHaveBeenCalled();
});
it("retains ownership when Workflow cancellation cannot be confirmed", async () => {
state.getRun.mockReturnValue({
cancel: vi.fn().mockRejectedValue(new Error("unreachable")),
status: Promise.resolve("running"),
});
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(false);
expect(runRegistry.releaseCancellation).not.toHaveBeenCalled();
});
it("reports the already-terminal outcome and still releases the claim when the run had already failed", async () => {
state.getRun.mockReturnValue({
cancel: vi.fn().mockRejectedValue(new Error("run already terminal")),
status: Promise.resolve("failed"),
});
const runRegistry = registry();
await expect(cancelRunDetailed(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toEqual({
cancelled: true,
released: true,
alreadyTerminal: true,
tornDown: true,
});
expect(runRegistry.releaseCancellation).toHaveBeenCalledWith(
"ticket:jira:PROJ-1",
"owner-a",
"run-1",
);
});
it("performs a compatibility ticket move under the cancelling owner", async () => {
const runRegistry = registry();
const issueTracker = { moveTicket: vi.fn() } as unknown as IssueTrackerAdapter;
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
issueTracker,
"Backlog",
)).resolves.toBe(true);
expect(state.moveTicket).toHaveBeenCalledWith({
db: { db: true },
issueTracker,
ticketKey: "PROJ-1",
target: "Backlog",
owner: expect.objectContaining({
subjectKey: "ticket:jira:PROJ-1",
ownerToken: "owner-a",
runId: "run-1",
}),
requiredOwnerState: "cancelling",
});
});
it("records the cancellation reason best-effort after a confirmed cancel", async () => {
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
undefined,
undefined,
undefined,
"Cancelled via Slack /ai-workflow cancel",
)).resolves.toBe(true);
expect(state.recordStatusReason).toHaveBeenCalledWith(
{ db: true },
"run-1",
"Cancelled via Slack /ai-workflow cancel",
{ kind: "cancellation" },
);
});
it("skips the reason write when none is given", async () => {
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(true);
expect(state.recordStatusReason).not.toHaveBeenCalled();
});
it("still confirms cancellation when the reason write fails", async () => {
state.recordStatusReason.mockRejectedValue(new Error("db down"));
const runRegistry = registry();
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
undefined,
undefined,
undefined,
"reason",
)).resolves.toBe(true);
expect(runRegistry.releaseCancellation).toHaveBeenCalled();
});
// A run cancelled while it was parked on a clarification never resumes to
// clear the live "awaiting" the park wrote, so cancellation settles it.
it("settles a parked run as blocked after a confirmed cancel", async () => {
const runRegistry = registry({ ...active(), state: "parked" });
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(true);
expect(state.markBlockedOnCancel).toHaveBeenCalledWith({ db: true }, "run-1");
});
// Cancelling wakes the parked body, whose own error path flips the run back to
// "running". The settle has to land after the step drain proves that body can
// no longer write, or that flip wins and the cancelled run reads as in flight.
it("settles the park only after the step drain barrier", async () => {
const runRegistry = registry({ ...active(), state: "parked" });
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(true);
const drained = Math.max(...state.listSteps.mock.invocationCallOrder);
expect(state.markBlockedOnCancel.mock.invocationCallOrder[0]).toBeGreaterThan(
drained,
);
});
it("still confirms cancellation when the awaiting settle fails", async () => {
state.markBlockedOnCancel.mockRejectedValue(new Error("db down"));
const runRegistry = registry({ ...active(), state: "parked" });
await expect(cancelRun(
"PROJ-1",
{ ownerToken: "owner-a", runId: "run-1" },
runRegistry,
)).resolves.toBe(true);
expect(runRegistry.releaseCancellation).toHaveBeenCalled();
});
});
describe("cancelRunById", () => {
beforeEach(() => {
vi.clearAllMocks();
state.getRun.mockReturnValue({ cancel: vi.fn().mockResolvedValue(undefined) });
state.listSteps.mockResolvedValue({ data: [], cursor: null, hasMore: false });
state.stopSandboxes.mockResolvedValue(undefined);
state.tombstone.mockResolvedValue({ matched: false, successorOwnerToken: null });
state.retireApproval.mockResolvedValue(0);
state.recordStatusReason.mockResolvedValue(undefined);
state.markBlockedOnCancel.mockResolvedValue(undefined);
state.markBlockedByOperator.mockResolvedValue(undefined);
state.findLiveClaim.mockResolvedValue(null);
state.findRunOutcome.mockResolvedValue(null);
});
// A schedule/webhook run has no ticket, so it is addressed only by run id.
const scheduleClaim = (over: Partial<ActiveRunEntry> = {}): ActiveRunEntry =>
active({ subjectKey: "sched:demo:hourly", ticketKey: null, kind: "schedule", ...over });
// A distinct sentinel for the db passed straight into cancelRunById, so the
// markRunBlockedByOperator call it makes is distinguishable from the getDb()
// sentinel the reused subject cancel core drives internally.
const outerDb = { marker: "outer" } as unknown as Db;
it("cancels a live run: settles blocked with the operator reason and releases the subject", async () => {
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
const runRegistry = registry(scheduleClaim());
const db = outerDb;
await expect(
cancelRunById(db, "run-1", { actorLabel: "operator kate", runRegistry }),
).resolves.toEqual({ outcome: "cancelled", subjectKey: "sched:demo:hourly" });
// Reuses the subject cancel core against the exact owner from active_runs.
expect(runRegistry.beginCancellation).toHaveBeenCalledWith(
"sched:demo:hourly",
"owner-a",
"run-1",
);
// Releasing the subject is what lets a schedule/webhook blocked behind the
// run resume once the run is gone.
expect(runRegistry.releaseCancellation).toHaveBeenCalledWith(
"sched:demo:hourly",
"owner-a",
"run-1",
);
// Synchronous blocked + reason via the operator-only writer (the 3-arg call),
// never the park writer settleCancelledPark drives.
expect(state.markBlockedByOperator).toHaveBeenCalledWith(
db,
"run-1",
"cancelled by operator kate",
);
});
it("withdraws a cancelled manual ticket before releasing its claim", async () => {
state.findLiveClaim.mockResolvedValue({
subjectKey: "ticket:jira:PROJ-1",
ticketKey: "PROJ-1",
ownerToken: "owner-a",
kind: "manual_ticket",
});
const runRegistry = registry(active({ kind: "manual_ticket" }));
const issueTracker = {} as IssueTrackerAdapter;
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
issueTracker,
}),
).resolves.toEqual({
outcome: "cancelled",
subjectKey: "ticket:jira:PROJ-1",
});
expect(state.moveTicket).toHaveBeenCalledWith({
db: outerDb,
issueTracker,
ticketKey: "PROJ-1",
aiColumn: expect.any(String),
target: expect.any(String),
owner: expect.objectContaining({
subjectKey: "ticket:jira:PROJ-1",
ownerToken: "owner-a",
runId: "run-1",
}),
requiredOwnerState: "cancelling",
});
expect(state.moveTicket.mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(runRegistry.releaseCancellation).mock.invocationCallOrder[0]!,
);
});
// The irreversible cancel already landed and the claim is released, so a
// transient settle failure must never surface as a throw (E4 would map it to
// 500) or flip the outcome; the cron backstops the row, like the park sibling.
it("still reports cancelled when the operator settle write fails after the cancel", async () => {
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
state.markBlockedByOperator.mockRejectedValue(new Error("neon blip"));
const runRegistry = registry(scheduleClaim());
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({ outcome: "cancelled", subjectKey: "sched:demo:hourly" });
expect(state.markBlockedByOperator).toHaveBeenCalled();
expect(runRegistry.releaseCancellation).toHaveBeenCalled();
});
// Observed on prod: the Workflow run was cancelled mid-step, so the step drain
// never confirms. The run is dead, so "try again" is a lie and the schedule
// ledger (settled by the route on outcome "cancelled") would never flip.
it("reports cancelled when the run is torn down but the step drain cannot be confirmed", async () => {
state.listSteps.mockResolvedValue({
data: [{ status: "running" }],
cursor: null,
hasMore: false,
});
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
const runRegistry = registry(scheduleClaim());
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({ outcome: "cancelled", subjectKey: "sched:demo:hourly" });
expect(state.markBlockedByOperator).toHaveBeenCalledWith(
outerDb,
"run-1",
"cancelled by operator kate",
);
// This path deliberately leaves the claim in "cancelling" for reconcileRuns
// to converge on the poll cron (retryCancellingClaim); nothing here
// force-releases it.
expect(runRegistry.releaseCancellation).not.toHaveBeenCalled();
});
// Same shape one step earlier: the sandbox cleanup throws after the Workflow
// run is already gone. The teardown is still irreversible.
it("reports cancelled when sandbox cleanup fails after the run is torn down", async () => {
state.stopSandboxes.mockRejectedValue(new Error("sandbox api down"));
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
const runRegistry = registry(scheduleClaim());
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({ outcome: "cancelled", subjectKey: "sched:demo:hourly" });
expect(state.markBlockedByOperator).toHaveBeenCalled();
});
it("reports already_terminal without writing status when the run had already finished", async () => {
state.getRun.mockReturnValue({
cancel: vi.fn().mockRejectedValue(new Error("run already terminal")),
status: Promise.resolve("failed"),
});
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
state.findRunOutcome.mockResolvedValue({ status: "failed" });
const runRegistry = registry(scheduleClaim());
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({
outcome: "already_terminal",
subjectKey: "sched:demo:hourly",
status: "failed",
});
// Invariant 2: no status write for an already-terminal run.
expect(state.markBlockedByOperator).not.toHaveBeenCalled();
// The lingering claim is still released so a blocked schedule/webhook resumes.
expect(runRegistry.releaseCancellation).toHaveBeenCalled();
});
it("reports unconfirmed and keeps the claim when the live cancel cannot be confirmed", async () => {
state.getRun.mockReturnValue({
cancel: vi.fn().mockRejectedValue(new Error("unreachable")),
status: Promise.resolve("running"),
});
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
const runRegistry = registry(scheduleClaim());
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({ outcome: "unconfirmed", subjectKey: "sched:demo:hourly" });
expect(state.markBlockedByOperator).not.toHaveBeenCalled();
expect(runRegistry.releaseCancellation).not.toHaveBeenCalled();
});
// The other side of the discriminator: cancellation never began, so Workflow
// was never touched and the claim is untouched. Retrying is the correct advice.
it("reports unconfirmed and writes no status when the cancellation never began", async () => {
state.findLiveClaim.mockResolvedValue({
subjectKey: "sched:demo:hourly",
ownerToken: "owner-a",
});
const runRegistry = registry(scheduleClaim());
(runRegistry.beginCancellation as ReturnType<typeof vi.fn>).mockResolvedValue(false);
await expect(
cancelRunById(outerDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({ outcome: "unconfirmed", subjectKey: "sched:demo:hourly" });
expect(state.markBlockedByOperator).not.toHaveBeenCalled();
expect(runRegistry.releaseCancellation).not.toHaveBeenCalled();
});
it("reports already_terminal from workflow_runs for a run that already left the registry", async () => {
state.findLiveClaim.mockResolvedValue(null);
state.findRunOutcome.mockResolvedValue({ status: "success" });
const runRegistry = registry(null);
await expect(
cancelRunById(outerDb, "run-done", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({ outcome: "already_terminal", status: "success" });
// Not live: no cancellation is attempted.
expect(runRegistry.beginCancellation).not.toHaveBeenCalled();
expect(state.markBlockedByOperator).not.toHaveBeenCalled();
});
it("returns not_found when the run id is in neither table", async () => {
state.findLiveClaim.mockResolvedValue(null);
state.findRunOutcome.mockResolvedValue(null);
const runRegistry = registry(null);
await expect(
cancelRunById(outerDb, "ghost", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({ outcome: "not_found" });
expect(runRegistry.beginCancellation).not.toHaveBeenCalled();
});
});
/**
* The operator wrapper: cancelRunById plus the schedule-ledger settle that used to
* live inline in the dashboard route. It is asserted here rather than there because
* the settle is now shared by every operator-facing caller (the route and the MCP
* runs.cancel tool), and the thing worth locking down is that no caller can lose it
* and none can be broken by it.
*/
describe("cancelRunForOperator", () => {
const operatorDb = { marker: "operator" } as unknown as Db;
beforeEach(() => {
vi.clearAllMocks();
state.getRun.mockReturnValue({ cancel: vi.fn().mockResolvedValue(undefined) });
state.listSteps.mockResolvedValue({ data: [], cursor: null, hasMore: false });
state.stopSandboxes.mockResolvedValue(undefined);
state.tombstone.mockResolvedValue({ matched: false, successorOwnerToken: null });
state.retireApproval.mockResolvedValue(0);
state.moveTicket.mockResolvedValue(undefined);
state.recordStatusReason.mockResolvedValue(undefined);
state.markBlockedOnCancel.mockResolvedValue(undefined);
state.markBlockedByOperator.mockResolvedValue(undefined);
state.findLiveClaim.mockResolvedValue(null);
state.findRunOutcome.mockResolvedValue(null);
state.settleOccurrence.mockResolvedValue(true);
});
/**
* A live claim on the given subject, the shape cancelRunById resolves a run id to.
* The run id has to match the claim's, or the core refuses the cancel as
* unconfirmed and the settle under test never runs.
*/
function live(runId: string, subjectKey: string, kind: ActiveRunEntry["kind"]) {
state.findLiveClaim.mockResolvedValue({ subjectKey, ownerToken: "owner-a" });
return registry(
active({ subjectKey, ticketKey: null, kind, ownerToken: "owner-a", runId }),
);
}
it("settles the schedule ledger for a cancelled schedule run", async () => {
const runRegistry = live("run-1", "schedule:sch_1", "schedule");
await expect(
cancelRunForOperator(operatorDb, "run-1", {
actorLabel: "operator kate",
runRegistry,
}),
).resolves.toEqual({
outcome: "cancelled",
subjectKey: "schedule:sch_1",
scheduleOccurrenceSettled: true,
});
// The settle takes the db handed to the wrapper, not an internal one: the
// ledger row and the cancel have to be read in the same tenant's database.
expect(state.settleOccurrence).toHaveBeenCalledWith(operatorDb, "run-1");
expect(state.warn).not.toHaveBeenCalled();
});
it("reports an unsettled occurrence and warns, without weakening the cancel", async () => {
// The cancel landed in the bind-to-started window, so no started occurrence
// carries this run id. The run is still gone, which is what the caller asked for.
state.settleOccurrence.mockResolvedValue(false);
const runRegistry = live("run-2", "schedule:sch_2", "schedule");
await expect(
cancelRunForOperator(operatorDb, "run-2", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({
outcome: "cancelled",
subjectKey: "schedule:sch_2",
scheduleOccurrenceSettled: false,
});
expect(state.warn).toHaveBeenCalledWith(
{ runId: "run-2", subjectKey: "schedule:sch_2" },
"schedule_run_cancel_occurrence_unsettled",
);
});
it("swallows a throwing settle: the cancel already happened and cannot be undone", async () => {
state.settleOccurrence.mockRejectedValue(new Error("ledger write failed"));
const runRegistry = live("run-3", "schedule:sch_3", "schedule");
await expect(
cancelRunForOperator(operatorDb, "run-3", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({
outcome: "cancelled",
subjectKey: "schedule:sch_3",
scheduleOccurrenceSettled: false,
});
expect(state.warn).toHaveBeenCalledWith(
expect.objectContaining({ runId: "run-3", error: "ledger write failed" }),
"schedule_run_cancel_occurrence_unsettled",
);
});
it("reports null instead of false for a run that has no occurrence to settle", async () => {
// A webhook run owns no ledger row, so a settle that finds nothing is normal
// there. Reporting it as null rather than false keeps "nothing to settle"
// distinguishable from "should have settled and did not".
state.settleOccurrence.mockResolvedValue(false);
const runRegistry = live("run-4", "webhook:ep_1:delivery-9", "webhook_trigger");
await expect(
cancelRunForOperator(operatorDb, "run-4", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({
outcome: "cancelled",
subjectKey: "webhook:ep_1:delivery-9",
scheduleOccurrenceSettled: null,
});
expect(state.warn).not.toHaveBeenCalled();
});
it("never touches the ledger when nothing was cancelled", async () => {
state.findRunOutcome.mockResolvedValue({ status: "success" });
const runRegistry = registry(null);
await expect(
cancelRunForOperator(operatorDb, "run-done", {
actorLabel: "operator",
runRegistry,
}),
).resolves.toEqual({
outcome: "already_terminal",
status: "success",
scheduleOccurrenceSettled: null,
});
// Settling an occurrence for a run that ended on its own would close a row the
// run itself is responsible for closing.
expect(state.settleOccurrence).not.toHaveBeenCalled();
});
});