deepline 0.3.531 → 0.3.533

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  2. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +129 -62
  3. package/dist/bundling-sources/shared_libs/play-runtime/deployment/commands/roll-execution-relay.ts +139 -35
  4. package/dist/bundling-sources/shared_libs/play-runtime/deployment/commands/roll-receipt-gateway.ts +438 -38
  5. package/dist/bundling-sources/shared_libs/play-runtime/deployment/commands/runtime-topology.ts +17 -0
  6. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-machine-lifecycle.ts +2 -0
  7. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-transient-retry.ts +279 -20
  8. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/attempts/engine-suspension.ts +1 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/attempts/ports.ts +2 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/attempts/postgres-fence-adapter.ts +2 -1
  11. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +1 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +6 -0
  13. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +8 -0
  14. package/dist/cli/{auth-33B3OEM4.mjs → auth-2TZNPIJQ.mjs} +5 -5
  15. package/dist/cli/auth-KE6RFHUE.js +43 -0
  16. package/dist/cli/{billing-Y2M2ABLW.js → billing-HQYTRIV3.js} +79 -79
  17. package/dist/cli/{billing-X4OQRH6D.mjs → billing-LR4WJIHO.mjs} +6 -6
  18. package/dist/cli/{chunk-NXEQMKSM.js → chunk-274Y66HP.js} +2 -2
  19. package/dist/cli/{chunk-CVOFP6BU.mjs → chunk-2TMNRF5R.mjs} +1 -1
  20. package/dist/cli/{chunk-VWOOOU6G.mjs → chunk-2UYERVXF.mjs} +2 -2
  21. package/dist/cli/{chunk-3PMVNMG4.js → chunk-33SNTG5F.js} +16 -16
  22. package/dist/cli/{chunk-IXOEKHOY.js → chunk-352XVCGE.js} +5 -5
  23. package/dist/cli/{chunk-XOXKVLJZ.mjs → chunk-3KQBV2CG.mjs} +3 -3
  24. package/dist/cli/{chunk-O7EFJR6Y.mjs → chunk-3O3AL5RI.mjs} +4 -4
  25. package/dist/cli/{chunk-4O7UET74.js → chunk-425ERNBL.js} +44 -44
  26. package/dist/cli/{chunk-5M24K577.js → chunk-4CYNH47Y.js} +53 -53
  27. package/dist/cli/{chunk-PTKSHGUM.js → chunk-4UADZTU5.js} +22 -22
  28. package/dist/cli/{chunk-RZXSCWEB.js → chunk-4YP2YAIZ.js} +26 -26
  29. package/dist/cli/{chunk-DWYX5DFJ.js → chunk-5XTXC45Z.js} +41 -41
  30. package/dist/cli/{chunk-RBPCXQBE.js → chunk-735ZOYQN.js} +11 -11
  31. package/dist/cli/{chunk-IOOWKPF7.js → chunk-A4JP6RPX.js} +2 -2
  32. package/dist/cli/{chunk-L4XVL4LW.js → chunk-B4ZNWXUW.js} +9 -9
  33. package/dist/cli/{chunk-HYPLMUMA.mjs → chunk-BSI7UHQZ.mjs} +5 -5
  34. package/dist/cli/{chunk-O267YGUV.js → chunk-BWZHMWM5.js} +6 -6
  35. package/dist/cli/{chunk-YVOFNLGN.mjs → chunk-CANHB6DH.mjs} +2 -2
  36. package/dist/cli/{chunk-ZJQITGPV.mjs → chunk-CWIGRIIX.mjs} +3 -3
  37. package/dist/cli/{chunk-O4NTPEQV.js → chunk-E4VWBU2E.js} +16 -16
  38. package/dist/cli/{chunk-RLRPEHQ3.js → chunk-EYWES7F5.js} +3 -3
  39. package/dist/cli/{chunk-YMGQP7WI.mjs → chunk-G3GJ3IGU.mjs} +5 -5
  40. package/dist/cli/{chunk-VHIHGMZD.mjs → chunk-G3RVDRYL.mjs} +1 -1
  41. package/dist/cli/{chunk-TDJCNVDE.js → chunk-HOTJSXLY.js} +5 -5
  42. package/dist/cli/{chunk-XWQI4TMS.mjs → chunk-HPOVAUQF.mjs} +1 -1
  43. package/dist/cli/{chunk-UNTFERUX.mjs → chunk-IETLUG4C.mjs} +1 -1
  44. package/dist/cli/{chunk-SPODXGBZ.mjs → chunk-JZ7LJS3P.mjs} +6 -6
  45. package/dist/cli/{chunk-EURLINZT.mjs → chunk-KKUOIVQO.mjs} +1 -1
  46. package/dist/cli/{chunk-WHAMLN6B.js → chunk-LTF2J3JM.js} +2 -2
  47. package/dist/cli/{chunk-TU7HU5K2.mjs → chunk-LZ3PBEQH.mjs} +2 -2
  48. package/dist/cli/{chunk-U5YBINPF.mjs → chunk-LZMRCUVD.mjs} +2 -2
  49. package/dist/cli/{chunk-MGWYYTZN.mjs → chunk-MKUYZ7LR.mjs} +1 -1
  50. package/dist/cli/{chunk-2WWTIR2G.js → chunk-MNAEALPG.js} +98 -98
  51. package/dist/cli/{chunk-MYTA37IL.mjs → chunk-NFDYVMGC.mjs} +10 -10
  52. package/dist/cli/{chunk-VGWUCBNA.mjs → chunk-NKVW552R.mjs} +1 -1
  53. package/dist/cli/{chunk-XQGLHKDI.mjs → chunk-NW736SOD.mjs} +2 -2
  54. package/dist/cli/{chunk-BUK6WHY2.js → chunk-O7RSUW75.js} +4 -4
  55. package/dist/cli/{chunk-6W73VXMK.mjs → chunk-PIACHLYY.mjs} +2 -2
  56. package/dist/cli/{chunk-JFTO33FK.js → chunk-QZWURUBP.js} +7 -7
  57. package/dist/cli/{chunk-ZBL4CP75.js → chunk-R7YDZSN7.js} +3 -3
  58. package/dist/cli/{chunk-4WPHK2R3.js → chunk-SVVUC3B4.js} +7 -7
  59. package/dist/cli/{chunk-4M4AASO3.js → chunk-TU56J4OV.js} +13 -13
  60. package/dist/cli/{chunk-2CUPFDW5.mjs → chunk-USAQ42OG.mjs} +5 -5
  61. package/dist/cli/{chunk-623FFVZU.mjs → chunk-VKGNQC2S.mjs} +5 -5
  62. package/dist/cli/{chunk-WDLY4HST.js → chunk-VPQDKL5O.js} +6 -6
  63. package/dist/cli/{chunk-H26ZSNLX.js → chunk-WF652G74.js} +14 -14
  64. package/dist/cli/{chunk-57PPAYDB.mjs → chunk-XUX5KGCQ.mjs} +2 -2
  65. package/dist/cli/{chunk-567HD6G6.mjs → chunk-XZN3DBTP.mjs} +1 -1
  66. package/dist/cli/{chunk-PTOPMO22.mjs → chunk-YZK5RSUL.mjs} +1 -1
  67. package/dist/cli/{chunk-D5BLTX5L.js → chunk-ZH5HCAN3.js} +1 -1
  68. package/dist/cli/{csv-CMUWCM46.mjs → csv-CJKKHGNQ.mjs} +4 -4
  69. package/dist/cli/{csv-N4P2XOKP.js → csv-MBSCHS4H.js} +13 -13
  70. package/dist/cli/{db-GFI45WV5.js → db-45HNPCY3.js} +27 -27
  71. package/dist/cli/{db-J5HFGOUO.mjs → db-EAFR6N45.mjs} +6 -6
  72. package/dist/cli/{describe-NKHH3VVI.mjs → describe-IXW3LDGC.mjs} +18 -18
  73. package/dist/cli/describe-PYLZAVRI.js +50 -0
  74. package/dist/cli/{executions-FMWHU72C.js → executions-SZAES2S4.js} +8 -8
  75. package/dist/cli/{executions-54QEYYE6.mjs → executions-ZATZV7O6.mjs} +6 -6
  76. package/dist/cli/{feedback-R7C3AZKN.js → feedback-KXLF4GR4.js} +14 -14
  77. package/dist/cli/{feedback-HA4QUWMU.mjs → feedback-NY63KEK2.mjs} +6 -6
  78. package/dist/cli/{git-OVG63PJV.mjs → git-BSSSTR6N.mjs} +5 -5
  79. package/dist/cli/git-T5JTVBYZ.js +25 -0
  80. package/dist/cli/index.js +141 -141
  81. package/dist/cli/index.mjs +43 -43
  82. package/dist/cli/{legacy-noops-PLQWYZ7A.mjs → legacy-noops-CYF6DJBF.mjs} +6 -6
  83. package/dist/cli/{legacy-noops-GM2F7GMV.js → legacy-noops-XQANGML3.js} +9 -9
  84. package/dist/cli/{monitors-QXK7JTRG.mjs → monitors-ABJVLWIP.mjs} +7 -7
  85. package/dist/cli/{monitors-SJBIPV4K.js → monitors-F3PTNP45.js} +100 -100
  86. package/dist/cli/{org-OFMMMVYT.mjs → org-BHF6Y5R7.mjs} +6 -6
  87. package/dist/cli/{org-XKO7BBT4.js → org-WQAPZI5Q.js} +86 -86
  88. package/dist/cli/{pages-ZGXRON5S.js → pages-U3EJ2NPL.js} +18 -18
  89. package/dist/cli/{pages-NDI2K34M.mjs → pages-W4HWVJUG.mjs} +6 -6
  90. package/dist/cli/{play-2YD5NTH6.js → play-2UHKONON.js} +317 -317
  91. package/dist/cli/{play-SMKNTBRK.mjs → play-3T4X3ZKH.mjs} +18 -18
  92. package/dist/cli/{providers-6SKF5W4Y.mjs → providers-2G2VTNDG.mjs} +6 -6
  93. package/dist/cli/{providers-52PIA36O.js → providers-LUK5LIUA.js} +9 -9
  94. package/dist/cli/{quickstart-4Z22WVLK.js → quickstart-76P6PGID.js} +6 -6
  95. package/dist/cli/{quickstart-RVA335ED.mjs → quickstart-XP4PJZ7N.mjs} +4 -4
  96. package/dist/cli/{run-GMN4TCVV.mjs → run-ACIHA53A.mjs} +23 -23
  97. package/dist/cli/{run-FDTSTMDM.js → run-S2KHGBCM.js} +41 -41
  98. package/dist/cli/search-5MD65V43.js +33 -0
  99. package/dist/cli/{search-2FG2USCF.mjs → search-VFIJCUZL.mjs} +8 -8
  100. package/dist/cli/{search-output-AC3AAV6E.mjs → search-output-2KFLZS5F.mjs} +4 -4
  101. package/dist/cli/{search-output-5FKQYLFW.js → search-output-GV7NNB4X.js} +6 -6
  102. package/dist/cli/{secrets-5A7AY2YU.js → secrets-KJSFEW2F.js} +15 -15
  103. package/dist/cli/{secrets-MA4ZTNVG.mjs → secrets-MAQLBVC4.mjs} +6 -6
  104. package/dist/cli/sessions-FDMO7PAA.js +22 -0
  105. package/dist/cli/{sessions-LBYKV5O4.mjs → sessions-G5MWNJ75.mjs} +6 -6
  106. package/dist/cli/{settings-6MQVNROV.mjs → settings-MR6UFOK5.mjs} +13 -13
  107. package/dist/cli/{settings-HA3D4GNZ.js → settings-VXGRPFXP.js} +86 -86
  108. package/dist/cli/{setup-3JWTNSOK.js → setup-C74BRK7N.js} +50 -50
  109. package/dist/cli/{setup-BXCUZOZH.mjs → setup-ZOBXMONM.mjs} +10 -10
  110. package/dist/cli/{skills-7ASML2WZ.mjs → skills-4CG3MHOY.mjs} +8 -8
  111. package/dist/cli/skills-KRUL7QCT.js +37 -0
  112. package/dist/cli/tools-CGHOSCPS.js +57 -0
  113. package/dist/cli/{tools-7IJWJXZ3.mjs → tools-YXCXZ4ZD.mjs} +17 -17
  114. package/dist/cli/update-S2TILEHZ.js +35 -0
  115. package/dist/cli/{update-JFKH4SVK.mjs → update-Z3C5W3I4.mjs} +10 -10
  116. package/dist/cli/{views-2EURG3P5.mjs → views-45B2FZQT.mjs} +6 -6
  117. package/dist/cli/{views-XTAIIX2Y.js → views-XGP2GZ52.js} +18 -18
  118. package/dist/cli/{workflow-AXOF74HO.js → workflow-DWO35XHZ.js} +17 -17
  119. package/dist/cli/{workflow-7FCQ34QD.mjs → workflow-KQRWSNBH.mjs} +7 -7
  120. package/dist/index.js +9 -9
  121. package/dist/index.mjs +6 -6
  122. package/dist/install-integrity.json +104 -104
  123. package/dist/release.d.mts +1 -1
  124. package/dist/release.d.ts +1 -1
  125. package/dist/release.js +2 -2
  126. package/dist/release.mjs +1 -1
  127. package/dist/server.js +5 -5
  128. package/dist/server.mjs +3 -3
  129. package/package.json +1 -1
  130. package/dist/cli/auth-3UDRBF5D.js +0 -43
  131. package/dist/cli/describe-HFUWQN3A.js +0 -50
  132. package/dist/cli/git-ETBABM6D.js +0 -25
  133. package/dist/cli/search-63X5FPDM.js +0 -33
  134. package/dist/cli/sessions-SMWWKKD4.js +0 -22
  135. package/dist/cli/skills-OJ7NZL6S.js +0 -37
  136. package/dist/cli/tools-Y2VMPUSI.js +0 -57
  137. package/dist/cli/update-JURCS2FE.js +0 -35
@@ -26,8 +26,11 @@ import {
26
26
  classifyFlyRequestError,
27
27
  createWithReadBeforeRetry,
28
28
  describeMachineFailures,
29
+ FLY_CREATE_NONCE_METADATA_KEY,
29
30
  runFlyctlWithTransientRetry,
30
31
  runFlyctlWithTransientRetrySync,
32
+ type FlyCreateReadBackOptions,
33
+ type FlyCreateResult,
31
34
  } from '../fly-transient-retry';
32
35
  import {
33
36
  RECEIPT_GATEWAY_DRAIN_TIMEOUT,
@@ -581,6 +584,300 @@ function assertCandidateFleet(input: {
581
584
  return 'ready';
582
585
  }
583
586
 
587
+ /**
588
+ * More candidates than the serving fleet has Machines exist for one operation
589
+ * and the tool will not remove any of them by itself. Waiting cannot fix
590
+ * this, so it fails at once and names every Machine.
591
+ */
592
+ export class ReceiptGatewayCandidateSurplusError extends Error {
593
+ readonly machineIds: readonly string[];
594
+ constructor(input: {
595
+ operationId: string;
596
+ count: number;
597
+ candidates: readonly FlyMachine[];
598
+ reason: string;
599
+ }) {
600
+ super(
601
+ `Receipt rollout ${input.operationId} has ${input.candidates.length} candidate Machine(s) where ${input.count} are expected, and the surplus is not removed automatically: ${input.reason}. Candidates: ${formatReceiptGatewayInventory(input.candidates).join(' | ')}. The rollout's cleanup command for this SHA removes only its still-cordoned candidates; run it, then prepare again.`,
602
+ );
603
+ this.name = 'ReceiptGatewayCandidateSurplusError';
604
+ this.machineIds = input.candidates.map(
605
+ (machine) => machine.id ?? '<no-id>',
606
+ );
607
+ }
608
+ }
609
+
610
+ function createdAtMs(machine: FlyMachine): number {
611
+ const parsed = Date.parse(machine.created_at ?? '');
612
+ return Number.isFinite(parsed) ? parsed : Number.POSITIVE_INFINITY;
613
+ }
614
+
615
+ /** Oldest first; an unknown creation time sorts last; the id breaks ties. */
616
+ function byCandidateAge(left: FlyMachine, right: FlyMachine): number {
617
+ const leftMs = createdAtMs(left);
618
+ const rightMs = createdAtMs(right);
619
+ if (leftMs < rightMs) return -1;
620
+ if (leftMs > rightMs) return 1;
621
+ return (left.id ?? '').localeCompare(right.id ?? '');
622
+ }
623
+
624
+ function candidatesByName(
625
+ candidates: readonly FlyMachine[],
626
+ ): Map<string, FlyMachine[]> {
627
+ const groups = new Map<string, FlyMachine[]>();
628
+ for (const machine of candidates) {
629
+ const name = machine.name ?? '';
630
+ groups.set(name, [...(groups.get(name) ?? []), machine]);
631
+ }
632
+ return groups;
633
+ }
634
+
635
+ /**
636
+ * One Machine per candidate name: the oldest. Duplicates of a name are the
637
+ * same logical candidate (`planReceiptGatewayCandidateSurplus` refuses any
638
+ * that disagree on their source), so fleet-level checks read one of them.
639
+ */
640
+ export function oneReceiptCandidatePerName(
641
+ candidates: readonly FlyMachine[],
642
+ ): FlyMachine[] {
643
+ return [...candidatesByName(candidates).values()].map(
644
+ (members) => [...members].sort(byCandidateAge)[0]!,
645
+ );
646
+ }
647
+
648
+ export type ReceiptGatewaySurplusMode =
649
+ /** Log exactly what would be destroyed, destroy nothing, then fail. */
650
+ | 'observe'
651
+ /** Destroy the planned surplus and confirm it by read-back. */
652
+ | 'destroy';
653
+
654
+ /**
655
+ * What prepare does with duplicate candidates it has a plan for. This path
656
+ * has no staging and runs only on a Production release, so it ships in
657
+ * `observe`: every decision is logged with its Machine ids and the release
658
+ * fails at once, naming them; cleanup for the SHA then removes the candidates
659
+ * as before. Switch to `destroy` only after a Production release has logged
660
+ * a correct "would destroy" decision, or after a staged proof.
661
+ */
662
+ export const RECEIPT_GATEWAY_SURPLUS_MODE =
663
+ 'observe' as ReceiptGatewaySurplusMode;
664
+
665
+ const TERMINAL_CANDIDATE_STATES = [
666
+ 'failed',
667
+ 'stopped',
668
+ 'suspended',
669
+ 'destroying',
670
+ 'destroyed',
671
+ ];
672
+
673
+ export type ReceiptGatewaySurplusDecision = Readonly<{
674
+ name: string;
675
+ keepMachineId: string;
676
+ destroyMachineIds: readonly string[];
677
+ }>;
678
+
679
+ export type ReceiptGatewaySurplusPlan = Readonly<{
680
+ decisions: readonly ReceiptGatewaySurplusDecision[];
681
+ /** Duplicated names with no healthy Machine to keep yet. */
682
+ waitingNames: readonly string[];
683
+ }>;
684
+
685
+ /**
686
+ * Decide what to do about duplicate candidates of one operation. Pure.
687
+ *
688
+ * `POST /machines` cannot be made idempotent (see
689
+ * `createWithReadBeforeRetry`), so an ambiguous create can still leave two
690
+ * Machines with one deterministic candidate name. For each duplicated name
691
+ * the oldest healthy Machine is kept and the others are destroyed. A name
692
+ * whose duplicates are all still starting is left alone until one is
693
+ * healthy: keeping a Machine that never starts would fail the release.
694
+ *
695
+ * Nothing is planned for destruction unless every candidate of the operation
696
+ * proves this is still an unadmitted preparation of this release:
697
+ * - each carries this operation id and the receipt role in Fly metadata, and
698
+ * one of this operation's deterministic names;
699
+ * - each is cordoned;
700
+ * - their durable phases still mean `Prepare`. `Activating` is written
701
+ * before the first uncordon and never cleared, so its absence proves no
702
+ * candidate was ever admitted. A fleet that was public and then rolled
703
+ * back is cordoned again but keeps `Activating`, and is refused here;
704
+ * - duplicates of a name share one source Machine.
705
+ * Anything else throws `ReceiptGatewayCandidateSurplusError`.
706
+ */
707
+ export function planReceiptGatewayCandidateSurplus(input: {
708
+ candidates: readonly FlyMachine[];
709
+ operationId: string;
710
+ count: number;
711
+ }): ReceiptGatewaySurplusPlan {
712
+ const refuse: (reason: string) => never = (reason) => {
713
+ throw new ReceiptGatewayCandidateSurplusError({ ...input, reason });
714
+ };
715
+ const duplicated = [...candidatesByName(input.candidates)].filter(
716
+ ([, members]) => members.length > 1,
717
+ );
718
+ if (duplicated.length === 0) return { decisions: [], waitingNames: [] };
719
+
720
+ const expectedNames = new Set(
721
+ Array.from({ length: input.count }, (_, index) =>
722
+ candidateName(input.operationId, index),
723
+ ),
724
+ );
725
+ for (const machine of input.candidates) {
726
+ const identity = `${machine.id ?? '<no-id>'} (${machine.name ?? '<no-name>'})`;
727
+ if (!machine.id) refuse(`${identity} has no Fly Machine identity`);
728
+ if (
729
+ machine.config?.metadata?.deepline_gateway_role !== 'receipt' ||
730
+ machine.config.metadata.deepline_gateway_rollout !== input.operationId
731
+ ) {
732
+ refuse(`${identity} does not carry this operation in its Fly metadata`);
733
+ }
734
+ if (machine.cordoned !== true) refuse(`${identity} is not cordoned`);
735
+ if (!expectedNames.has(machine.name ?? '')) {
736
+ refuse(
737
+ `${identity} is not one of this operation's ${input.count} deterministic candidate names`,
738
+ );
739
+ }
740
+ }
741
+ let action: ReceiptGatewayPreparationAction | undefined;
742
+ try {
743
+ action = receiptGatewayPreparationAction(input.candidates);
744
+ } catch (error) {
745
+ refuse(error instanceof Error ? error.message : String(error));
746
+ }
747
+ if (action !== ReceiptGatewayPreparationAction.Prepare) {
748
+ refuse(
749
+ 'the candidates carry durable activation intent, so one of them may have been admitted',
750
+ );
751
+ }
752
+
753
+ const decisions: ReceiptGatewaySurplusDecision[] = [];
754
+ const waitingNames: string[] = [];
755
+ for (const [name, members] of duplicated) {
756
+ const sources = new Set(
757
+ members.map(
758
+ (machine) => machine.config?.metadata?.deepline_gateway_source_machine,
759
+ ),
760
+ );
761
+ if (sources.size !== 1 || sources.has(undefined)) {
762
+ refuse(`the duplicates of ${name} do not share one source Machine`);
763
+ }
764
+ const keeper = members.filter(healthy).sort(byCandidateAge)[0];
765
+ if (!keeper) {
766
+ if (
767
+ members.every((machine) =>
768
+ TERMINAL_CANDIDATE_STATES.includes(machine.state ?? ''),
769
+ )
770
+ ) {
771
+ refuse(
772
+ `every duplicate of ${name} is in a terminal state (${members
773
+ .map((machine) => `${machine.id}=${machine.state}`)
774
+ .join(', ')}), so none can become healthy`,
775
+ );
776
+ }
777
+ waitingNames.push(name);
778
+ continue;
779
+ }
780
+ decisions.push({
781
+ name,
782
+ keepMachineId: keeper.id!,
783
+ destroyMachineIds: members
784
+ .filter((machine) => machine !== keeper)
785
+ .map((machine) => machine.id!)
786
+ .sort(),
787
+ });
788
+ }
789
+ return { decisions, waitingNames };
790
+ }
791
+
792
+ export type ReceiptGatewaySurplusOutcome =
793
+ /** No candidate name is duplicated. */
794
+ | 'none'
795
+ /** Duplicates exist, but none of them is healthy yet; nothing was removed. */
796
+ | 'waiting'
797
+ /** At least one duplicate was destroyed and its deletion read back. */
798
+ | 'reconciled';
799
+
800
+ /**
801
+ * Apply `planReceiptGatewayCandidateSurplus` and log every decision with its
802
+ * Machine ids.
803
+ *
804
+ * In `observe` mode (the shipped default, `RECEIPT_GATEWAY_SURPLUS_MODE`)
805
+ * nothing is destroyed: the decisions are logged as what would happen and
806
+ * the call throws `ReceiptGatewayCandidateSurplusError`.
807
+ *
808
+ * In `destroy` mode the surplus goes through the provider-confirmed cordoned
809
+ * delete that candidate cleanup already uses, then the fleet is read back
810
+ * and the call refuses to continue unless the destroyed Machines are gone
811
+ * and the kept ones remain.
812
+ */
813
+ export async function reconcileReceiptGatewayCandidateSurplus(input: {
814
+ operationId: string;
815
+ count: number;
816
+ candidates: readonly FlyMachine[];
817
+ /** Must re-check the cordon and confirm deletion with the provider. */
818
+ destroyCordoned: (machineIds: string[]) => Promise<void>;
819
+ readCandidates: () => FlyMachine[] | Promise<FlyMachine[]>;
820
+ mode?: ReceiptGatewaySurplusMode;
821
+ log?: (line: string) => void;
822
+ }): Promise<ReceiptGatewaySurplusOutcome> {
823
+ const mode = input.mode ?? RECEIPT_GATEWAY_SURPLUS_MODE;
824
+ const destroying = mode === 'destroy';
825
+ const plan = planReceiptGatewayCandidateSurplus(input);
826
+ if (plan.decisions.length === 0) {
827
+ return plan.waitingNames.length > 0 ? 'waiting' : 'none';
828
+ }
829
+ const log = input.log ?? ((line: string) => console.info(line));
830
+ const describe = (machineId: string): string => {
831
+ const machine = input.candidates.find(
832
+ (candidate) => candidate.id === machineId,
833
+ )!;
834
+ return `${formatReceiptGatewayInventory([machine])[0]} phase=${candidatePhase(machine)} created_at=${machine.created_at ?? '<unknown>'}`;
835
+ };
836
+ for (const decision of plan.decisions) {
837
+ log(
838
+ `[receipt-gateway] surplus candidate: operation=${input.operationId} mode=${mode} name=${decision.name} decision=${destroying ? 'keep' : 'would-keep'} reason="oldest healthy cordoned candidate with this name" machine=${JSON.stringify(describe(decision.keepMachineId))}`,
839
+ );
840
+ for (const machineId of decision.destroyMachineIds) {
841
+ log(
842
+ `[receipt-gateway] surplus candidate: operation=${input.operationId} mode=${mode} name=${decision.name} decision=${destroying ? 'destroy' : 'would-destroy'} reason="duplicate of ${decision.keepMachineId}; cordoned and never admitted" machine=${JSON.stringify(describe(machineId))}`,
843
+ );
844
+ }
845
+ }
846
+ const destroyed = plan.decisions.flatMap(
847
+ (decision) => decision.destroyMachineIds,
848
+ );
849
+ const kept = plan.decisions.map((decision) => decision.keepMachineId);
850
+ if (!destroying) {
851
+ throw new ReceiptGatewayCandidateSurplusError({
852
+ operationId: input.operationId,
853
+ count: input.count,
854
+ candidates: input.candidates,
855
+ reason: `automatic removal is in observe mode; it would destroy [${destroyed.join(', ')}] and keep [${kept.join(', ')}]`,
856
+ });
857
+ }
858
+ await input.destroyCordoned([...destroyed]);
859
+ const after = await input.readCandidates();
860
+ const afterIds = after.map((machine) => machine.id);
861
+ const stillListed = destroyed.filter((machineId) =>
862
+ afterIds.includes(machineId),
863
+ );
864
+ if (stillListed.length > 0) {
865
+ throw new Error(
866
+ `Receipt rollout ${input.operationId} surplus candidate(s) [${stillListed.join(', ')}] are still listed after their deletion was confirmed.`,
867
+ );
868
+ }
869
+ const missing = kept.filter((machineId) => !afterIds.includes(machineId));
870
+ if (missing.length > 0) {
871
+ throw new Error(
872
+ `Receipt rollout ${input.operationId} kept candidate(s) [${missing.join(', ')}] disappeared while their duplicates [${destroyed.join(', ')}] were destroyed.`,
873
+ );
874
+ }
875
+ log(
876
+ `[receipt-gateway] surplus reconciled: operation=${input.operationId} destroyed=[${destroyed.join(', ')}] kept=[${kept.join(', ')}] candidates=${after.length}/${input.count}`,
877
+ );
878
+ return 'reconciled';
879
+ }
880
+
584
881
  /**
585
882
  * "not healthy" alone cannot be acted on. Name every serving Machine that is
586
883
  * unhealthy and the exact check that says so, so the release log answers
@@ -694,6 +991,14 @@ export async function waitForReceiptGatewayCandidates(input: {
694
991
  progressIntervalMs?: number;
695
992
  reportProgress?: (message: string) => void;
696
993
  shouldFailImmediately?: (failure: string) => boolean;
994
+ /**
995
+ * Called when more candidates exist than `count`. A surplus never resolves
996
+ * by waiting: without this, or when it reports `none`, the wait fails at
997
+ * once with every Machine id. Its own errors are never retried.
998
+ */
999
+ reconcileSurplus?: (
1000
+ candidates: FlyMachine[],
1001
+ ) => Promise<ReceiptGatewaySurplusOutcome>;
697
1002
  }): Promise<FlyMachine[]> {
698
1003
  const now = input.now ?? Date.now;
699
1004
  const timeoutMs = input.timeoutMs ?? HEALTH_TIMEOUT_MS;
@@ -701,19 +1006,21 @@ export async function waitForReceiptGatewayCandidates(input: {
701
1006
  const progressIntervalMs =
702
1007
  input.progressIntervalMs ?? CANDIDATE_WAIT_PROGRESS_INTERVAL_MS;
703
1008
  const startedAt = now();
704
- const deadline = startedAt + timeoutMs;
1009
+ let deadline = startedAt + timeoutMs;
705
1010
  let lastProgressAt: number | undefined;
706
1011
  let observedCandidates: FlyMachine[] = [];
707
1012
  let observedCount = 0;
708
1013
  let failure = 'starting';
709
1014
 
710
1015
  while (now() < deadline) {
1016
+ let surplus: FlyMachine[] | undefined;
711
1017
  try {
712
1018
  const candidates = input.candidates();
713
1019
  observedCandidates = candidates;
714
1020
  observedCount = candidates.length;
715
1021
  if (candidates.length !== input.count) {
716
1022
  failure = `expected ${input.count} candidates; found ${candidates.length}`;
1023
+ if (candidates.length > input.count) surplus = candidates;
717
1024
  } else if (input.readiness(candidates) === 'starting') {
718
1025
  failure = 'receipt candidate is still starting';
719
1026
  } else {
@@ -723,6 +1030,31 @@ export async function waitForReceiptGatewayCandidates(input: {
723
1030
  failure = error instanceof Error ? error.message : String(error);
724
1031
  if (input.shouldFailImmediately?.(failure)) throw error;
725
1032
  }
1033
+ if (surplus) {
1034
+ // Outside the retry above on purpose: neither a refusal nor a failed
1035
+ // deletion is something another poll can fix.
1036
+ const reconcileStartedAt = now();
1037
+ const outcome = input.reconcileSurplus
1038
+ ? await input.reconcileSurplus(surplus)
1039
+ : 'none';
1040
+ if (outcome === 'reconciled') {
1041
+ // The health budget is for candidates to start, not for a confirmed
1042
+ // delete. Give back what the reconciliation spent and read again.
1043
+ deadline += now() - reconcileStartedAt;
1044
+ continue;
1045
+ }
1046
+ if (outcome === 'none') {
1047
+ throw new ReceiptGatewayCandidateSurplusError({
1048
+ operationId: input.operationId,
1049
+ count: input.count,
1050
+ candidates: surplus,
1051
+ reason: input.reconcileSurplus
1052
+ ? 'no candidate name is duplicated, so no Machine is a known duplicate'
1053
+ : 'this step only waits for an existing fleet',
1054
+ });
1055
+ }
1056
+ failure = `${failure}; its duplicates have no healthy Machine to keep yet`;
1057
+ }
726
1058
 
727
1059
  const current = now();
728
1060
  if (
@@ -750,10 +1082,14 @@ export async function waitForReceiptGatewayCandidates(input: {
750
1082
  async function waitForCandidates(
751
1083
  operationId: string,
752
1084
  count: number,
1085
+ reconcileSurplus?: (
1086
+ candidates: FlyMachine[],
1087
+ ) => Promise<ReceiptGatewaySurplusOutcome>,
753
1088
  ): Promise<FlyMachine[]> {
754
1089
  return waitForReceiptGatewayCandidates({
755
1090
  operationId,
756
1091
  count,
1092
+ ...(reconcileSurplus ? { reconcileSurplus } : {}),
757
1093
  candidates: () => candidatesFor(operationId),
758
1094
  readiness: (candidates) =>
759
1095
  readinessOfCordonedCandidates({
@@ -857,9 +1193,19 @@ async function removeCordoned(operationId: string): Promise<void> {
857
1193
  'Refusing to remove a receipt candidate that received public traffic.',
858
1194
  );
859
1195
  }
1196
+ await destroyCordonedMachines(
1197
+ targets.map((machine) => machine.id!).filter(Boolean),
1198
+ );
1199
+ }
1200
+
1201
+ /**
1202
+ * Stop and delete exact Machines, refusing any that is not cordoned on every
1203
+ * read, and return only after Fly's own list no longer contains them.
1204
+ */
1205
+ async function destroyCordonedMachines(machineIds: string[]): Promise<void> {
860
1206
  const client = releaseFlyClient();
861
1207
  await stopAndDestroyCordonedMachines({
862
- machineIds: targets.map((machine) => machine.id!).filter(Boolean),
1208
+ machineIds,
863
1209
  readMachines: machines,
864
1210
  listProviderMachineIds: async () =>
865
1211
  (await client.listMachines()).map((machine) => machine.id),
@@ -896,11 +1242,64 @@ async function drain(operationId: string): Promise<void> {
896
1242
  console.info(JSON.stringify({ operationId, ...outcome }));
897
1243
  }
898
1244
 
1245
+ /** The two Machines API calls a candidate create needs; a fake in tests. */
1246
+ export type ReceiptGatewayCandidateFlyClient = Readonly<{
1247
+ createMachine: (config: Record<string, unknown>) => Promise<FlyMachine>;
1248
+ listMachines: () => Promise<FlyMachine[]>;
1249
+ }>;
1250
+
1251
+ /**
1252
+ * Create one cordoned candidate, or adopt the Machine that already carries
1253
+ * its identity. The identity is the deterministic name plus this operation's
1254
+ * id in Fly metadata; each create request also stamps its own nonce there.
1255
+ * See `createWithReadBeforeRetry` for what happens when Fly does not answer.
1256
+ */
1257
+ export async function createReceiptGatewayCandidate(input: {
1258
+ client: ReceiptGatewayCandidateFlyClient;
1259
+ operationId: string;
1260
+ name: string;
1261
+ sourceId: string;
1262
+ options?: FlyCreateReadBackOptions;
1263
+ }): Promise<FlyCreateResult<FlyMachine>> {
1264
+ return await createWithReadBeforeRetry<FlyMachine>({
1265
+ identity: `receipt gateway candidate ${input.name} (operation ${input.operationId})`,
1266
+ create: ({ nonce }) =>
1267
+ input.client.createMachine({
1268
+ name: input.name,
1269
+ region: fleet.primaryRegion,
1270
+ skip_service_registration: true,
1271
+ config: gatewayMachineConfig({
1272
+ profile: 'production',
1273
+ role: 'receipt',
1274
+ image: receiptGatewayImage(input.operationId),
1275
+ metadata: {
1276
+ deepline_gateway_role: 'receipt',
1277
+ deepline_gateway_rollout: input.operationId,
1278
+ deepline_gateway_source_machine: input.sourceId,
1279
+ [RECEIPT_GATEWAY_OPERATION_PHASE_METADATA_KEY]:
1280
+ ReceiptGatewayOperationPhase.Prepared,
1281
+ [FLY_CREATE_NONCE_METADATA_KEY]: nonce,
1282
+ fly_process_group: fleet.processGroup,
1283
+ },
1284
+ }),
1285
+ }),
1286
+ findExisting: async () =>
1287
+ candidatesFor(
1288
+ input.operationId,
1289
+ await input.client.listMachines(),
1290
+ ).filter((machine) => machine.name === input.name),
1291
+ describe: (machine) =>
1292
+ `${machine.id ?? '<no-id>'} (create nonce ${machine.config?.metadata?.[FLY_CREATE_NONCE_METADATA_KEY] ?? '<none>'})`,
1293
+ classify: classifyFlyRequestError,
1294
+ ...(input.options ? { options: input.options } : {}),
1295
+ });
1296
+ }
1297
+
899
1298
  async function prepare(operationId: string): Promise<void> {
900
1299
  // Different immutable releases may prepare cordoned candidates in parallel.
901
1300
  // Never let one release delete another release's fenced evidence; the
902
1301
  // topology cleanup command owns that exact-SHA operation explicitly.
903
- const existing = candidatesFor(operationId);
1302
+ let existing = candidatesFor(operationId);
904
1303
  if (existing.length > 0) {
905
1304
  const action = receiptGatewayPreparationAction(existing);
906
1305
  if (action !== ReceiptGatewayPreparationAction.Prepare) {
@@ -929,49 +1328,50 @@ async function prepare(operationId: string): Promise<void> {
929
1328
  }
930
1329
  run('bun', productionGatewayImageEnsureArgs('receiptGateway', operationId));
931
1330
  const blue = serving();
932
- if (existing.length > 0) {
933
- assertCandidateSourceGeneration({ candidates: existing, serving: blue });
934
- }
935
1331
  const client = releaseFlyClient();
936
- const createCandidate = (name: string, sourceId: string) =>
937
- client.createMachine({
938
- name,
939
- region: fleet.primaryRegion,
940
- skip_service_registration: true,
941
- config: gatewayMachineConfig({
942
- profile: 'production',
943
- role: 'receipt',
944
- image: receiptGatewayImage(operationId),
945
- metadata: {
946
- deepline_gateway_role: 'receipt',
947
- deepline_gateway_rollout: operationId,
948
- deepline_gateway_source_machine: sourceId,
949
- [RECEIPT_GATEWAY_OPERATION_PHASE_METADATA_KEY]:
950
- ReceiptGatewayOperationPhase.Prepared,
951
- fly_process_group: fleet.processGroup,
952
- },
953
- }),
1332
+ const reconcileSurplus = (
1333
+ candidates: readonly FlyMachine[],
1334
+ ): Promise<ReceiptGatewaySurplusOutcome> =>
1335
+ reconcileReceiptGatewayCandidateSurplus({
1336
+ operationId,
1337
+ count: blue.length,
1338
+ candidates,
1339
+ destroyCordoned: destroyCordonedMachines,
1340
+ // The delete is confirmed against the Machines API list, so read the
1341
+ // result back through the same API rather than a second source.
1342
+ readCandidates: async () =>
1343
+ candidatesFor(operationId, await client.listMachines()),
954
1344
  });
1345
+ if (existing.length > 0) {
1346
+ // An earlier attempt for this SHA may have left a duplicate behind.
1347
+ // Settle it before anything reads this fleet as one Machine per name.
1348
+ // The image step above can take minutes, so decide on a fresh read: a
1349
+ // stale one could keep a Machine that has since stopped being healthy.
1350
+ existing = candidatesFor(operationId);
1351
+ if ((await reconcileSurplus(existing)) === 'reconciled') {
1352
+ existing = candidatesFor(operationId);
1353
+ }
1354
+ assertCandidateSourceGeneration({
1355
+ candidates: oneReceiptCandidatePerName(existing),
1356
+ serving: blue,
1357
+ });
1358
+ }
955
1359
  for (const [index, source] of blue.entries()) {
956
1360
  const name = candidateName(operationId, index);
957
1361
  if (existing.some((machine) => machine.name === name)) continue;
958
1362
  if (!source.id) throw new Error('Serving Machine has no identity.');
959
- const sourceId = source.id;
960
- // A transient create failure is ambiguous; re-read before any retry so a
961
- // candidate Fly already created is adopted, never duplicated. The result
962
- // is unused (waitForCandidates re-reads), and the create response and the
963
- // inventory entry are different FlyMachine shapes, so neither narrows T.
964
- await createWithReadBeforeRetry<unknown>({
965
- create: () => createCandidate(name, sourceId),
966
- findExisting: async () =>
967
- candidatesFor(operationId, await client.listMachines()).find(
968
- (machine) => machine.name === name,
969
- ),
970
- classify: classifyFlyRequestError,
971
- options: { label: `Create receipt gateway candidate ${name}` },
1363
+ await createReceiptGatewayCandidate({
1364
+ client,
1365
+ operationId,
1366
+ name,
1367
+ sourceId: source.id,
972
1368
  });
973
1369
  }
974
- const ready = await waitForCandidates(operationId, blue.length);
1370
+ const ready = await waitForCandidates(
1371
+ operationId,
1372
+ blue.length,
1373
+ reconcileSurplus,
1374
+ );
975
1375
  await assertPublic(blue.map((machine) => machine.id!));
976
1376
  console.info(
977
1377
  JSON.stringify({
@@ -784,6 +784,23 @@ export async function commitProductionTopologyPlan(input: {
784
784
  ...input.environment,
785
785
  GITHUB_SHA: input.proven.plan.releaseSha,
786
786
  };
787
+ // Relay activation runs after the receipt cutover and refuses a duplicate
788
+ // relay candidate. Find one here, while both gateways still serve the old
789
+ // generation, so it cannot leave receipt on new and relay on old.
790
+ await input.command({
791
+ command: 'bun',
792
+ args: [
793
+ 'scripts/roll-execution-relay.ts',
794
+ 'assert-no-surplus',
795
+ '--environment',
796
+ 'production',
797
+ '--sha',
798
+ input.proven.plan.releaseSha,
799
+ '--apply',
800
+ ],
801
+ environment,
802
+ description: 'Refuse surplus execution relay candidates before cutover',
803
+ });
787
804
  await input.command({
788
805
  command: 'bun',
789
806
  args: [
@@ -4,6 +4,8 @@ export type FlyMachine = {
4
4
  name?: string;
5
5
  state?: string;
6
6
  cordoned?: boolean;
7
+ /** Fly's immutable Machine creation timestamp (RFC 3339). */
8
+ created_at?: string;
7
9
  region?: string;
8
10
  /**
9
11
  * `name` and `output` are what make a failing check actionable in a release