File size: 57,753 Bytes
97ee7cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
/**
 * Wave-loading state machine integration tests (PR 2).
 *
 * Covers the mutations + queries directly. Actions (pickWaveAction,
 * pushBatchAction, finalizeWaveAction) integrate Resend HTTP calls and
 * the Convex scheduler β€” those are exercised end-to-end on a test fork
 * with mocked Resend, not in this unit suite.
 *
 * Acceptance criteria mapped to tests in this file:
 *   - lease conflict (second claim refused)
 *   - underfill flag preserved through pick β†’ finalize
 *   - empty pool β†’ terminal no-op + lease cleared
 *   - CAS idempotency (_markContactPushed twice = +1 pushedCount once)
 *   - failure-rate threshold flips whole run
 *   - operator recovery routing (resumeStalled / resumeFinalize / discard)
 *   - confirmedNotSent gate on send-failure recovery
 *   - cleanup chunked deletion
 */

import { convexTest } from "convex-test";
import { describe, expect, test } from "vitest";
import schema from "../schema";
import { internal } from "../_generated/api";

const modules = import.meta.glob("../**/*.ts");

// convex-test 0.0.43 emits an unhandled rejection of shape
// `Error: Write outside of transaction <id>;_scheduled_functions` when a
// mutation under test calls `ctx.scheduler.runAfter(...)` and the framework
// later attempts to dispatch the scheduled action. This is a framework
// artifact (the scheduled action would touch `_scheduled_functions` outside
// the test's transactional fake) β€” not a bug in our code. Filter only this
// specific rejection so genuine errors still surface.
process.on("unhandledRejection", (err) => {
  if (err instanceof Error && /Write outside of transaction.*_scheduled_functions/.test(err.message)) {
    return; // swallow the convex-test scheduler-dispatch artifact
  }
  throw err;
});

// ───────────────────────────────────────────────────────────────────────────
// Helpers
// ───────────────────────────────────────────────────────────────────────────

const RAMP_KEY = "current";

async function seedRampConfig(t: ReturnType<typeof convexTest>): Promise<void> {
  await t.run(async (ctx) => {
    await ctx.db.insert("broadcastRampConfig", {
      key: RAMP_KEY,
      active: true,
      rampCurve: [1500, 5000, 15000, 25000],
      currentTier: 0,
      waveLabelPrefix: "pro-launch-wave",
      waveLabelOffset: 3,
      bounceKillThreshold: 0.04,
      complaintKillThreshold: 0.0008,
      killGateTripped: false,
    });
  });
}

async function seedRegistrations(
  t: ReturnType<typeof convexTest>,
  emails: string[],
): Promise<void> {
  await t.run(async (ctx) => {
    const now = Date.now();
    for (const email of emails) {
      await ctx.db.insert("registrations", {
        email,
        normalizedEmail: email.toLowerCase().trim(),
        registeredAt: now,
        appVersion: "test",
      });
    }
  });
}

async function readConfig(t: ReturnType<typeof convexTest>) {
  return t.run(async (ctx) =>
    ctx.db
      .query("broadcastRampConfig")
      .withIndex("by_key", (q) => q.eq("key", RAMP_KEY))
      .unique(),
  );
}

async function readWaveRun(t: ReturnType<typeof convexTest>, runId: string) {
  return t.run(async (ctx) =>
    ctx.db
      .query("waveRuns")
      .withIndex("by_runId", (q) => q.eq("runId", runId))
      .unique(),
  );
}

async function readContacts(t: ReturnType<typeof convexTest>, runId: string) {
  return t.run(async (ctx) =>
    ctx.db
      .query("wavePickedContacts")
      .withIndex("by_runId", (q) => q.eq("runId", runId))
      .collect(),
  );
}

/** Helper: find a contact's _id by (runId, normalizedEmail). Tests call
 *  the mark-mutations by `contactId` after PR2 review-fix 9 (avoid the
 *  Convex 8192-doc-read scan limit). */
async function findContactId(
  t: ReturnType<typeof convexTest>,
  runId: string,
  normalizedEmail: string,
): Promise<string> {
  const all = await readContacts(t, runId);
  const match = all.find((c) => c.normalizedEmail === normalizedEmail);
  if (!match) throw new Error(`findContactId: no contact (${runId}, ${normalizedEmail})`);
  return match._id;
}

// ───────────────────────────────────────────────────────────────────────────
// _claimWaveRunLease
// ───────────────────────────────────────────────────────────────────────────

describe("_claimWaveRunLease", () => {
  test("claims lease when no holder + no active waveRun + no label collision", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    const result = await t.mutation(
      internal.broadcast.waveRuns._claimWaveRunLease,
      { waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50 },
    );
    expect(result).toEqual({ ok: true, runId: "run-1" });
    const config = await readConfig(t);
    expect(config!.pendingRunId).toBe("run-1");
    expect(config!.pendingWaveLabel).toBe("pro-launch-wave-4");
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("picking");
    expect(run!.requestedCount).toBe(100);
    expect(run!.batchSize).toBe(50);
  });

  test("refuses second claim while first lease is held", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    const second = await t.mutation(
      internal.broadcast.waveRuns._claimWaveRunLease,
      { waveLabel: "pro-launch-wave-5", runId: "run-2", requestedCount: 100, batchSize: 50 },
    );
    expect(second).toMatchObject({ ok: false, reason: "lease-held", current: "run-1" });
  });

  test("refuses claim when waveLabel already has a stamped registration", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.run(async (ctx) => {
      await ctx.db.insert("registrations", {
        email: "stamped@example.com",
        normalizedEmail: "stamped@example.com",
        registeredAt: Date.now(),
        appVersion: "test",
        proLaunchWave: "pro-launch-wave-4",
      });
    });
    const result = await t.mutation(
      internal.broadcast.waveRuns._claimWaveRunLease,
      { waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50 },
    );
    expect(result).toMatchObject({ ok: false, reason: "label-collides" });
  });

  test("refuses claim when no broadcastRampConfig row exists", async () => {
    const t = convexTest(schema, modules);
    const result = await t.mutation(
      internal.broadcast.waveRuns._claimWaveRunLease,
      { waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50 },
    );
    expect(result).toMatchObject({ ok: false, reason: "no-config" });
  });
});

// ───────────────────────────────────────────────────────────────────────────
// _persistPickedBatch + _markPickComplete + _markPickFailed
// ───────────────────────────────────────────────────────────────────────────

describe("pick-phase mutations", () => {
  test("_persistPickedBatch inserts contacts as pending + bumps updatedAt", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 3, batchSize: 50,
    });
    const r = await t.mutation(
      internal.broadcast.waveRuns._persistPickedBatch,
      { runId: "run-1", contacts: ["a@test", "b@test", "c@test"] },
    );
    expect(r.inserted).toBe(3);
    const contacts = await readContacts(t, "run-1");
    expect(contacts).toHaveLength(3);
    expect(contacts.every((c) => c.status === "pending")).toBe(true);
  });

  test("_markPickComplete transitions picking β†’ segment-created with totalCount/underfilled", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 80, underfilled: true,
    });
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("segment-created");
    expect(run!.segmentId).toBe("seg_abc");
    expect(run!.totalCount).toBe(80);
    expect(run!.underfilled).toBe(true);
  });

  test("_markPickFailed empty-pool clears the lease (terminal no-op)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1", substatus: "empty-pool", error: "no unstamped registrations",
    });
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("empty-pool");
    const config = await readConfig(t);
    expect(config!.pendingRunId).toBeUndefined();
    // PR2 review-fix 3: empty-pool now also DEACTIVATES the ramp (not just
    // clears the lease) and uses a `ramp-complete-*` status to signal
    // terminal completion to the operator.
    expect(config!.active).toBe(false);
    expect(config!.lastRunStatus).toBe("ramp-complete-empty-pool");
  });

  test("_markPickFailed segment-create-failed KEEPS the lease (operator must discard)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1", substatus: "segment-create-failed", error: "Resend 500",
    });
    const config = await readConfig(t);
    expect(config!.pendingRunId).toBe("run-1");
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("segment-create-failed");
  });
});

// ───────────────────────────────────────────────────────────────────────────
// _markContactPushed / _markContactFailed (CAS guards)
// ───────────────────────────────────────────────────────────────────────────

describe("push-phase CAS mutations", () => {
  async function setupPushing(t: ReturnType<typeof convexTest>, totalCount = 4) {
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: totalCount, batchSize: 50,
    });
    const emails = Array.from({ length: totalCount }, (_, i) => `c${i}@test`);
    await seedRegistrations(t, emails);
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: emails,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    return emails;
  }

  test("_markContactPushed: pushed=true + pushedCount++ + registration stamped", async () => {
    const t = convexTest(schema, modules);
    const [first] = await setupPushing(t);
    const r = await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId: await findContactId(t, "run-1", first!),
      runId: "run-1", normalizedEmail: first!, waveLabel: "pro-launch-wave-4",
    });
    expect(r).toMatchObject({ ok: true, stampResult: "stamped" });
    const run = await readWaveRun(t, "run-1");
    expect(run!.pushedCount).toBe(1);
    const contacts = await readContacts(t, "run-1");
    expect(contacts.find((c) => c.normalizedEmail === first)?.status).toBe("pushed");
  });

  test("_markContactPushed CAS: second call returns not-pending; pushedCount stays 1", async () => {
    const t = convexTest(schema, modules);
    const [first] = await setupPushing(t);
    const contactId = await findContactId(t, "run-1", first!);
    await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId,
      runId: "run-1", normalizedEmail: first!, waveLabel: "pro-launch-wave-4",
    });
    const second = await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId,
      runId: "run-1", normalizedEmail: first!, waveLabel: "pro-launch-wave-4",
    });
    expect(second).toMatchObject({ ok: false, reason: "not-pending" });
    const run = await readWaveRun(t, "run-1");
    expect(run!.pushedCount).toBe(1);
  });

  test("_markContactFailed: contact failed + failedCount++ (under threshold)", async () => {
    // 100 contacts: 1 failure = 1%, under the 5% threshold β†’ run does NOT flip.
    const t = convexTest(schema, modules);
    const emails = await setupPushing(t, 100);
    const first = emails[0]!;
    const r = await t.mutation(internal.broadcast.waveRuns._markContactFailed, {
      contactId: await findContactId(t, "run-1", first),
      runId: "run-1", normalizedEmail: first, failedReason: "Resend 422",
    });
    expect(r).toMatchObject({ ok: true, runFailed: false });
    const run = await readWaveRun(t, "run-1");
    expect(run!.failedCount).toBe(1);
    expect(run!.status).toBe("pushing"); // still pushing β€” under threshold
    const contacts = await readContacts(t, "run-1");
    const failed = contacts.find((c) => c.normalizedEmail === first);
    expect(failed?.status).toBe("failed");
    expect(failed?.failedReason).toBe("Resend 422");
  });

  test("_markContactFailed flips whole run when failure rate exceeds 5%", async () => {
    // 4 contacts; 1 fail = 25% which is >5% β†’ should flip.
    const t = convexTest(schema, modules);
    const [first] = await setupPushing(t, 4);
    const r = await t.mutation(internal.broadcast.waveRuns._markContactFailed, {
      contactId: await findContactId(t, "run-1", first!),
      runId: "run-1", normalizedEmail: first!, failedReason: "Resend 500",
    });
    expect(r).toMatchObject({ ok: true, runFailed: true });
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("batch-failure-rate-exceeded");
  });

  test("_markContactFailed CAS: second call on already-failed contact is no-op", async () => {
    const t = convexTest(schema, modules);
    // Use 100 contacts so a single failure is 1% β€” under threshold (won't flip the run)
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    const emails = Array.from({ length: 100 }, (_, i) => `c${i}@test`);
    await seedRegistrations(t, emails);
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: emails,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 100, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });

    const c0Id = await findContactId(t, "run-1", emails[0]!);
    await t.mutation(internal.broadcast.waveRuns._markContactFailed, {
      contactId: c0Id,
      runId: "run-1", normalizedEmail: emails[0]!, failedReason: "Resend 500",
    });
    const second = await t.mutation(internal.broadcast.waveRuns._markContactFailed, {
      contactId: c0Id,
      runId: "run-1", normalizedEmail: emails[0]!, failedReason: "Resend 500 again",
    });
    expect(second).toMatchObject({ ok: false, reason: "not-pending" });
    const run = await readWaveRun(t, "run-1");
    expect(run!.failedCount).toBe(1);
  });
});

// ───────────────────────────────────────────────────────────────────────────
// _finalizeWaveRun + _markBroadcastCreated
// ───────────────────────────────────────────────────────────────────────────

describe("finalize-phase mutations", () => {
  async function setupBroadcastCreated(t: ReturnType<typeof convexTest>) {
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
  }

  test("_markBroadcastCreated transitions pushing β†’ broadcast-created with broadcastId", async () => {
    const t = convexTest(schema, modules);
    await setupBroadcastCreated(t);
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("broadcast-created");
    expect(run!.broadcastId).toBe("bro_xyz");
  });

  test("_finalizeWaveRun atomically advances tier, sets lastWave*, clears lease, marks sent", async () => {
    const t = convexTest(schema, modules);
    await setupBroadcastCreated(t);
    const sentAt = Date.now();
    const r = await t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
      runId: "run-1", sentAt,
    });
    expect(r).toMatchObject({ ok: true, advancedToTier: 1 });
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(1);
    expect(config!.lastWaveLabel).toBe("pro-launch-wave-4");
    expect(config!.lastWaveBroadcastId).toBe("bro_xyz");
    expect(config!.lastWaveSegmentId).toBe("seg_abc");
    expect(config!.lastWaveSentAt).toBe(sentAt);
    expect(config!.lastRunStatus).toBe("succeeded");
    expect(config!.pendingRunId).toBeUndefined();
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("sent");
  });

  test("_markFinalizeFailed create-broadcast-failed flips status='failed' (no broadcast yet)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "create-broadcast-failed", error: "Resend 500",
    });
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("create-broadcast-failed");
  });

  test("_markFinalizeFailed send-broadcast-failed KEEPS status='broadcast-created' (broadcast exists)", async () => {
    const t = convexTest(schema, modules);
    await setupBroadcastCreated(t);
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "network timeout",
    });
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("broadcast-created"); // unchanged
    expect(run!.failureSubstatus).toBe("send-broadcast-failed");
  });
});

// ───────────────────────────────────────────────────────────────────────────
// Operator recovery β€” refuse-vs-route guards
// ───────────────────────────────────────────────────────────────────────────

describe("operator recovery", () => {
  test("resumeStalledWaveRun refuses broadcast-created (routes to resumeFinalizeWaveRun)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    await expect(
      t.mutation(internal.broadcast.waveRuns.resumeStalledWaveRun, { runId: "run-1" }),
    ).rejects.toThrow(/broadcast-created.*resumeFinalizeWaveRun/);
  });

  test("resumeFinalizeWaveRun refuses send-failure case without confirmedNotSent", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "network",
    });
    await expect(
      t.mutation(internal.broadcast.waveRuns.resumeFinalizeWaveRun, { runId: "run-1" }),
    ).rejects.toThrow(/verify in the Resend dashboard/);
  });

  test("resumeFinalizeWaveRun for create-broadcast-failed needs no confirmedNotSent (no broadcast exists)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "create-broadcast-failed", error: "Resend 500",
    });
    const r = await t.mutation(
      internal.broadcast.waveRuns.resumeFinalizeWaveRun,
      { runId: "run-1" },
    );
    expect(r).toMatchObject({ ok: true, scheduled: "finalizeWaveAction-create-and-send" });
    const run = await readWaveRun(t, "run-1");
    // Patched back to pushing so finalize action re-enters via create path.
    expect(run!.status).toBe("pushing");
    expect(run!.failureSubstatus).toBeUndefined();
    // Drain the scheduled finalizeWaveAction so it doesn't escape into an
    // unhandled rejection (the action would try Resend HTTP which fails in
    // the test env, but the scheduler-fail itself is fine).
    await t.finishInProgressScheduledFunctions().catch(() => {});
  });

  test("discardWaveRun marks failed + bumps waveLabelOffset + clears lease", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    const r = await t.mutation(internal.broadcast.waveRuns.discardWaveRun, {
      runId: "run-1", reason: "operator decision",
    });
    expect(r).toMatchObject({ ok: true, newWaveLabelOffset: 4 });
    const config = await readConfig(t);
    expect(config!.waveLabelOffset).toBe(4);
    expect(config!.pendingRunId).toBeUndefined();
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("discarded-by-operator");
  });

  test("markFinalizeRecovered finalizes the run when operator confirms send happened", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "timeout",
    });
    const sentAt = Date.now();
    const r = await t.mutation(internal.broadcast.waveRuns.markFinalizeRecovered, {
      runId: "run-1", sentAt, reason: "Resend dashboard confirmed sent at 10:19 UTC",
    });
    expect(r).toMatchObject({ ok: true, advancedToTier: 1 });
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(1);
    expect(config!.lastWaveSentAt).toBe(sentAt);
    expect(config!.pendingRunId).toBeUndefined();
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("sent");
  });
});

// ───────────────────────────────────────────────────────────────────────────
// In-flight guard query + cleanup
// ───────────────────────────────────────────────────────────────────────────

describe("_listInFlightWaveRuns + cleanup", () => {
  test("_listInFlightWaveRuns returns active runs with lastActivityAt fallback", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    const inFlight = await t.query(
      internal.broadcast.waveRuns._listInFlightWaveRuns,
      {},
    );
    expect(inFlight).toHaveLength(1);
    expect(inFlight[0]).toMatchObject({ runId: "run-1", status: "picking" });
    expect(inFlight[0]!.lastActivityAt).toBeGreaterThan(0);
  });

  test("_listInFlightWaveRuns excludes terminal-state runs (sent, failed)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 100, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1", substatus: "empty-pool", error: "no contacts",
    });
    const inFlight = await t.query(
      internal.broadcast.waveRuns._listInFlightWaveRuns,
      {},
    );
    expect(inFlight).toHaveLength(0);
  });

  test("_cleanupDiscardedWavePickedContacts deletes a chunk + reports hasMore", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 3, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: ["a@t", "b@t", "c@t"],
    });
    const r = await t.mutation(
      internal.broadcast.waveRuns._cleanupDiscardedWavePickedContacts,
      { runId: "run-1" },
    );
    expect(r.deleted).toBe(3);
    expect(r.hasMore).toBe(false);
    const remaining = await readContacts(t, "run-1");
    expect(remaining).toHaveLength(0);
  });
});

// ───────────────────────────────────────────────────────────────────────────
// PR2 review-fix 1: _markBroadcastCreated + _finalizeWaveRun lease+status CAS
// ───────────────────────────────────────────────────────────────────────────

describe("review-fix 1: lease+status CAS", () => {
  async function setupPushing(t: ReturnType<typeof convexTest>) {
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
  }

  test("_markBroadcastCreated: idempotent on re-call with same broadcastId", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    const r1 = await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    expect(r1).toMatchObject({ ok: true, alreadyMarked: false });
    const r2 = await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    expect(r2).toMatchObject({ ok: true, alreadyMarked: true });
  });

  test("_markBroadcastCreated: refuses different broadcastId on already-marked run (duplicate detection)", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    const r = await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_OTHER",
    });
    expect(r).toMatchObject({
      ok: false,
      reason: "duplicate-broadcast-detected",
      existing: "bro_xyz",
    });
  });

  test("_markBroadcastCreated: refuses on lost lease", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    // Force-clear the lease (simulates operator forceReleaseLease).
    await t.run(async (ctx) => {
      const config = await ctx.db
        .query("broadcastRampConfig")
        .withIndex("by_key", (q) => q.eq("key", "current"))
        .unique();
      await ctx.db.patch(config!._id, { pendingRunId: undefined });
    });
    const r = await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    expect(r).toMatchObject({ ok: false, reason: "lost-lease" });
  });

  test("_markBroadcastCreated: refuses on wrong status (e.g. picking)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    // Status is still 'picking' β€” not allowed.
    const r = await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    expect(r).toMatchObject({ ok: false, reason: "wrong-status-picking" });
  });

  test("_finalizeWaveRun: idempotent on already-sent run (no-op, no double-advance)", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    const sentAt = Date.now();
    const r1 = await t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
      runId: "run-1", sentAt,
    });
    expect(r1).toMatchObject({ ok: true, advancedToTier: 1 });
    // Second call should NOT advance the tier again.
    const r2 = await t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
      runId: "run-1", sentAt: sentAt + 1000,
    });
    expect(r2).toMatchObject({ ok: true, alreadySent: true });
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(1); // NOT 2
  });

  test("_finalizeWaveRun: throws on lost lease (refuses to advance after operator force-release)", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    await t.run(async (ctx) => {
      const config = await ctx.db
        .query("broadcastRampConfig")
        .withIndex("by_key", (q) => q.eq("key", "current"))
        .unique();
      await ctx.db.patch(config!._id, { pendingRunId: undefined });
    });
    await expect(
      t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
        runId: "run-1", sentAt: Date.now(),
      }),
    ).rejects.toThrow(/lost lease/);
  });

  test("_finalizeWaveRun: throws on wrong status (e.g. pushing instead of broadcast-created)", async () => {
    const t = convexTest(schema, modules);
    await setupPushing(t);
    // Skip _markBroadcastCreated β€” try to finalize from 'pushing' directly.
    await expect(
      t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
        runId: "run-1", sentAt: Date.now(),
      }),
    ).rejects.toThrow(/expected broadcast-created/);
  });
});

// ───────────────────────────────────────────────────────────────────────────
// PR2 review-fix 2: discardWaveRun unstamps registrations
// ───────────────────────────────────────────────────────────────────────────

describe("review-fix 2: unstamp on discard", () => {
  test("_cleanupDiscardedWavePickedContacts unstamps registrations matching the run's waveLabel", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 3, batchSize: 50,
    });
    const emails = ["a@t", "b@t", "c@t"];
    await seedRegistrations(t, emails);
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: emails,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 3, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    // Push two of three (third stays pending). All three were seeded with
    // matching registrations by seedRegistrations.
    await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId: await findContactId(t, "run-1", "a@t"),
      runId: "run-1", normalizedEmail: "a@t", waveLabel: "pro-launch-wave-4",
    });
    await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId: await findContactId(t, "run-1", "b@t"),
      runId: "run-1", normalizedEmail: "b@t", waveLabel: "pro-launch-wave-4",
    });
    // Verify a + b are stamped before cleanup.
    const stampedBefore = await t.run(async (ctx) =>
      ctx.db.query("registrations").collect(),
    );
    expect(stampedBefore.filter((r) => r.proLaunchWave === "pro-launch-wave-4")).toHaveLength(2);

    // Cleanup should unstamp the 2 pushed contacts and delete all 3 wavePickedContacts rows.
    const r = await t.mutation(
      internal.broadcast.waveRuns._cleanupDiscardedWavePickedContacts,
      { runId: "run-1" },
    );
    expect(r).toMatchObject({ deleted: 3, unstamped: 2, hasMore: false });

    const stampedAfter = await t.run(async (ctx) =>
      ctx.db.query("registrations").collect(),
    );
    expect(stampedAfter.filter((r) => r.proLaunchWave === "pro-launch-wave-4")).toHaveLength(0);
    const remainingContacts = await readContacts(t, "run-1");
    expect(remainingContacts).toHaveLength(0);
  });

  test("_cleanupDiscardedWavePickedContacts does NOT unstamp a contact re-picked into a later wave", async () => {
    // Defensive: if the operator discards run-1, then a later run-2 picks
    // and stamps the same email with a different waveLabel, the cleanup of
    // run-1 must NOT clear run-2's stamp.
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await seedRegistrations(t, ["a@t"]);
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: ["a@t"],
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId: await findContactId(t, "run-1", "a@t"),
      runId: "run-1", normalizedEmail: "a@t", waveLabel: "pro-launch-wave-4",
    });
    // Manually re-stamp the registration as if it were re-picked into wave-5.
    await t.run(async (ctx) => {
      const reg = await ctx.db
        .query("registrations")
        .withIndex("by_normalized_email", (q) => q.eq("normalizedEmail", "a@t"))
        .first();
      await ctx.db.patch(reg!._id, { proLaunchWave: "pro-launch-wave-5" });
    });
    // Cleanup run-1 β€” must leave the wave-5 stamp alone.
    const r = await t.mutation(
      internal.broadcast.waveRuns._cleanupDiscardedWavePickedContacts,
      { runId: "run-1" },
    );
    expect(r.unstamped).toBe(0);
    const reg = await t.run(async (ctx) =>
      ctx.db
        .query("registrations")
        .withIndex("by_normalized_email", (q) => q.eq("normalizedEmail", "a@t"))
        .first(),
    );
    expect(reg!.proLaunchWave).toBe("pro-launch-wave-5");
  });

  test("discardWaveRun + cleanup unstamps the registration (action runs after discard)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await seedRegistrations(t, ["a@t"]);
    await t.mutation(internal.broadcast.waveRuns._persistPickedBatch, {
      runId: "run-1", contacts: ["a@t"],
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markContactPushed, {
      contactId: await findContactId(t, "run-1", "a@t"),
      runId: "run-1", normalizedEmail: "a@t", waveLabel: "pro-launch-wave-4",
    });
    // Operator discard β€” flips the run to failed/discarded-by-operator and
    // schedules cleanup (we exercise the cleanup mutation directly here
    // since convex-test's action-dispatch path emits a benign "Write outside
    // of transaction" rejection on schedule.runAfter; the BEHAVIOR we want
    // to verify is that cleanup unstamps).
    await t.mutation(internal.broadcast.waveRuns.discardWaveRun, {
      runId: "run-1", reason: "operator decision",
    });
    // Run the cleanup mutation directly (same one the eager scheduler call
    // would invoke). Verifies the unstamp behavior on a discarded run.
    const r = await t.mutation(
      internal.broadcast.waveRuns._cleanupDiscardedWavePickedContacts,
      { runId: "run-1" },
    );
    expect(r.unstamped).toBe(1);
    const reg = await t.run(async (ctx) =>
      ctx.db
        .query("registrations")
        .withIndex("by_normalized_email", (q) => q.eq("normalizedEmail", "a@t"))
        .first(),
    );
    expect(reg!.proLaunchWave).toBeUndefined();
    // Drain the action that discardWaveRun also scheduled (it's a no-op
    // by this point since cleanup is already done; just suppress the
    // convex-test scheduler artifact).
    await t.finishInProgressScheduledFunctions().catch(() => {});
  });
});

// ───────────────────────────────────────────────────────────────────────────
// PR2 review-fix 3: pool-too-small terminates ramp
// ───────────────────────────────────────────────────────────────────────────

describe("review-fix 3: pool-too-small terminates ramp", () => {
  test("_markPickFailed pool-too-small clears lease + DEACTIVATES the ramp", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1500, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1",
      substatus: "pool-too-small",
      error: "picked 50 contacts < threshold",
    });
    const config = await readConfig(t);
    expect(config!.active).toBe(false);
    expect(config!.pendingRunId).toBeUndefined();
    expect(config!.lastRunStatus).toBe("ramp-complete-pool-too-small");
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("failed");
    expect(run!.failureSubstatus).toBe("pool-too-small");
  });

  test("_markPickFailed empty-pool also DEACTIVATES the ramp (terminal completion)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1500, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1", substatus: "empty-pool", error: "no contacts",
    });
    const config = await readConfig(t);
    expect(config!.active).toBe(false);
    expect(config!.lastRunStatus).toBe("ramp-complete-empty-pool");
  });

  test("_markPickFailed segment-create-failed does NOT deactivate (operator must triage)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1500, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickFailed, {
      runId: "run-1", substatus: "segment-create-failed", error: "Resend 500",
    });
    const config = await readConfig(t);
    // Ramp stays active β€” operator inspects + discards. Lease stays held.
    expect(config!.active).toBe(true);
    expect(config!.pendingRunId).toBe("run-1");
  });
});

// ───────────────────────────────────────────────────────────────────────────
// PR2 review-fix 5: cleanup excludes recoverable finalize failures
// ───────────────────────────────────────────────────────────────────────────

describe("review-fix 5: cleanup excludes recoverable failures", () => {
  async function setupOldFailedRun(
    t: ReturnType<typeof convexTest>,
    substatus: string,
  ) {
    // Seed a failed run with updatedAt 25h ago so it passes the age cutoff.
    const oldTime = Date.now() - 25 * 60 * 60 * 1000;
    await seedRampConfig(t);
    await t.run(async (ctx) => {
      await ctx.db.insert("waveRuns", {
        runId: `run-${substatus}`,
        waveLabel: `pro-launch-wave-${substatus}`,
        status: "failed",
        failureSubstatus: substatus,
        requestedCount: 100,
        totalCount: 100,
        underfilled: false,
        pushedCount: 50,
        failedCount: 0,
        batchSize: 50,
        createdAt: oldTime,
        updatedAt: oldTime,
      });
    });
  }

  test("auto-cleanup INCLUDES discarded-by-operator runs", async () => {
    const t = convexTest(schema, modules);
    await setupOldFailedRun(t, "discarded-by-operator");
    const candidates = await t.query(
      internal.broadcast.waveRuns._listFailedWaveRunsForCleanup,
      {},
    );
    expect(candidates).toContain("run-discarded-by-operator");
  });

  test("auto-cleanup INCLUDES batch-failure-rate-exceeded (24h safety net)", async () => {
    const t = convexTest(schema, modules);
    await setupOldFailedRun(t, "batch-failure-rate-exceeded");
    const candidates = await t.query(
      internal.broadcast.waveRuns._listFailedWaveRunsForCleanup,
      {},
    );
    expect(candidates).toContain("run-batch-failure-rate-exceeded");
  });

  test("auto-cleanup EXCLUDES recoverable create-broadcast-failed", async () => {
    const t = convexTest(schema, modules);
    await setupOldFailedRun(t, "create-broadcast-failed");
    const candidates = await t.query(
      internal.broadcast.waveRuns._listFailedWaveRunsForCleanup,
      {},
    );
    // Operator may yet run resumeFinalizeWaveRun; cleanup would unstamp
    // pushed contacts and a subsequent successful send would re-stamp them
    // β€” risking duplicate outreach. Skip these in auto-cleanup.
    expect(candidates).not.toContain("run-create-broadcast-failed");
  });

  test("auto-cleanup EXCLUDES recoverable send-broadcast-failed", async () => {
    const t = convexTest(schema, modules);
    await setupOldFailedRun(t, "send-broadcast-failed");
    const candidates = await t.query(
      internal.broadcast.waveRuns._listFailedWaveRunsForCleanup,
      {},
    );
    expect(candidates).not.toContain("run-send-broadcast-failed");
  });

  test("auto-cleanup EXCLUDES failed runs with no substatus (defensive)", async () => {
    const t = convexTest(schema, modules);
    const oldTime = Date.now() - 25 * 60 * 60 * 1000;
    await seedRampConfig(t);
    await t.run(async (ctx) => {
      await ctx.db.insert("waveRuns", {
        runId: "run-no-substatus",
        waveLabel: "pro-launch-wave-x",
        status: "failed", // status='failed' but no failureSubstatus set
        requestedCount: 100, totalCount: 100, underfilled: false,
        pushedCount: 0, failedCount: 0, batchSize: 50,
        createdAt: oldTime, updatedAt: oldTime,
      });
    });
    const candidates = await t.query(
      internal.broadcast.waveRuns._listFailedWaveRunsForCleanup,
      {},
    );
    expect(candidates).not.toContain("run-no-substatus");
  });
});

// ───────────────────────────────────────────────────────────────────────────
// PR2 review-fix 6: _markFinalizeFailed terminal CAS + markFinalizeRecovered strict
// ───────────────────────────────────────────────────────────────────────────

describe("review-fix 6: terminal-CAS on finalize failure / recovery", () => {
  async function setupSent(t: ReturnType<typeof convexTest>) {
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    await t.mutation(internal.broadcast.waveRuns._finalizeWaveRun, {
      runId: "run-1", sentAt: Date.now(),
    });
  }

  test("_markFinalizeFailed: refuses to overwrite status='sent' (duplicate-finalize loser)", async () => {
    const t = convexTest(schema, modules);
    await setupSent(t);
    // Loser of a finalize race calls _markFinalizeFailed after Resend
    // returns 422 already-sent.
    const r = await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1",
      substatus: "send-broadcast-failed",
      error: "Resend 422 already sent",
    });
    expect(r).toMatchObject({ ok: false, reason: "already-sent" });
    // Run state unchanged β€” sent stays sent.
    const run = await readWaveRun(t, "run-1");
    expect(run!.status).toBe("sent");
    expect(run!.failureSubstatus).toBeUndefined();
  });

  test("_markFinalizeFailed: refuses to overwrite a different existing substatus", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    // First failure β€” create-broadcast-failed.
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "create-broadcast-failed", error: "Resend 500",
    });
    // Second mutation tries to relabel β€” refuses.
    const r = await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "different reason",
    });
    expect(r).toMatchObject({
      ok: false,
      reason: "already-failed-different-substatus",
      existing: "create-broadcast-failed",
    });
  });

  test("markFinalizeRecovered: throws on status='sent' (no double-advance)", async () => {
    const t = convexTest(schema, modules);
    await setupSent(t);
    // Even if a stale failureSubstatus was somehow set, status='sent' must block recovery.
    await t.run(async (ctx) => {
      const run = await ctx.db
        .query("waveRuns")
        .withIndex("by_runId", (q) => q.eq("runId", "run-1"))
        .unique();
      // Force a malformed state (won't happen in practice now that
      // _markFinalizeFailed CAS-rejects, but tests defense in depth).
      await ctx.db.patch(run!._id, { failureSubstatus: "send-broadcast-failed" });
    });
    await expect(
      t.mutation(internal.broadcast.waveRuns.markFinalizeRecovered, {
        runId: "run-1", sentAt: Date.now(), reason: "stale state recovery",
      }),
    ).rejects.toThrow(/already finalized|requires status/);
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(1); // NOT advanced again
  });

  test("markFinalizeRecovered: throws on lost lease (refuses to advance from stale runId)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    // PR2 review-fix 10: substatus required for the recovery to be reachable.
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "timeout",
    });
    // Force-clear the lease (operator did forceReleaseLease).
    await t.run(async (ctx) => {
      const config = await ctx.db
        .query("broadcastRampConfig")
        .withIndex("by_key", (q) => q.eq("key", "current"))
        .unique();
      await ctx.db.patch(config!._id, { pendingRunId: undefined });
    });
    await expect(
      t.mutation(internal.broadcast.waveRuns.markFinalizeRecovered, {
        runId: "run-1", sentAt: Date.now(), reason: "operator verified",
      }),
    ).rejects.toThrow(/lost lease/);
  });

  test("markFinalizeRecovered: succeeds on broadcast-created + send-broadcast-failed substatus + held lease", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    // PR2 review-fix 10: markFinalizeRecovered now requires the substatus
    // signal. Without it, status='broadcast-created' alone is also the
    // mid-flight pre-send state and would race-advance the tier.
    await t.mutation(internal.broadcast.waveRuns._markFinalizeFailed, {
      runId: "run-1", substatus: "send-broadcast-failed", error: "network timeout",
    });
    const sentAt = Date.now();
    const r = await t.mutation(internal.broadcast.waveRuns.markFinalizeRecovered, {
      runId: "run-1", sentAt, reason: "Resend dashboard confirmed sent",
    });
    expect(r).toMatchObject({ ok: true, advancedToTier: 1 });
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(1);
    expect(config!.lastWaveSentAt).toBe(sentAt);
  });

  test("markFinalizeRecovered: REFUSES on broadcast-created without send-broadcast-failed substatus (mid-flight protection)", async () => {
    const t = convexTest(schema, modules);
    await seedRampConfig(t);
    await t.mutation(internal.broadcast.waveRuns._claimWaveRunLease, {
      waveLabel: "pro-launch-wave-4", runId: "run-1", requestedCount: 1, batchSize: 50,
    });
    await t.mutation(internal.broadcast.waveRuns._markPickComplete, {
      runId: "run-1", segmentId: "seg_abc", totalCount: 1, underfilled: false,
    });
    await t.mutation(internal.broadcast.waveRuns._markPushingStarted, { runId: "run-1" });
    await t.mutation(internal.broadcast.waveRuns._markBroadcastCreated, {
      runId: "run-1", broadcastId: "bro_xyz",
    });
    // status='broadcast-created' but no failureSubstatus β€” this is the
    // active mid-flight state between create and send. Operator MUST
    // NOT be able to short-circuit here.
    await expect(
      t.mutation(internal.broadcast.waveRuns.markFinalizeRecovered, {
        runId: "run-1", sentAt: Date.now(), reason: "operator confused",
      }),
    ).rejects.toThrow(/failureSubstatus.*<none>|only applies to send-broadcast-failed/);
    const config = await readConfig(t);
    expect(config!.currentTier).toBe(0); // NOT advanced
  });
});