@moondeck/station 1.0.5 → 1.0.6

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.
package/lib/agent.ts CHANGED
@@ -150,6 +150,9 @@ const TaskUpData = z.object({
150
150
  worktreePath: z.string(),
151
151
  codeServerPort: z.number().int().positive().optional(),
152
152
  previewPorts: PreviewPortRuntimesSchema.optional(),
153
+ /** F6: the task's machine had been terminated, and this start launched a
154
+ * fresh one; work only on the old machine is gone. A feed system note. */
155
+ environmentReplaced: z.literal(true).optional(),
153
156
  /** Degraded start: uai-init failed twice; surfaced as a feed system note. */
154
157
  initWarning: z.string().optional(),
155
158
  /** ADR-153: whether this start put the secrets proxy's CA, and its pins,
@@ -22,6 +22,10 @@ import { spawn } from "node:child_process";
22
22
  import type { DockerResult } from "./docker-exec";
23
23
 
24
24
  const DEFAULT_TIMEOUT_MS = 60_000;
25
+ /** ssh's ConnectTimeout for every machine exec: it bounds the TCP connect
26
+ * and the SSH handshake and key exchange (ssh_config(5)). Exec budgets that
27
+ * must leave room for a slow connect count it in (task-env-forwarder.ts). */
28
+ export const MACHINE_SSH_CONNECT_TIMEOUT_SECONDS = 10;
25
29
  const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
26
30
  /** SIGKILLed ssh normally closes at once; an unreapable child must not hold
27
31
  * the promise open past the caller's own deadline. */
@@ -123,7 +127,7 @@ export function machineSshArgs(
123
127
  "-o",
124
128
  "StrictHostKeyChecking=accept-new",
125
129
  "-o",
126
- "ConnectTimeout=10",
130
+ `ConnectTimeout=${MACHINE_SSH_CONNECT_TIMEOUT_SECONDS}`,
127
131
  "-i",
128
132
  target.keyPath,
129
133
  "-p",
@@ -166,7 +170,7 @@ export function machineEnvironmentSshArgs(
166
170
  "-o",
167
171
  "StrictHostKeyChecking=accept-new",
168
172
  "-o",
169
- "ConnectTimeout=10",
173
+ `ConnectTimeout=${MACHINE_SSH_CONNECT_TIMEOUT_SECONDS}`,
170
174
  "-i",
171
175
  target.keyPath,
172
176
  "-p",
@@ -24,11 +24,14 @@ import { spawn } from "node:child_process";
24
24
  import type { DockerResult } from "./docker-exec";
25
25
  import { createHash } from "node:crypto";
26
26
 
27
- import type {
28
- MachineInfo,
29
- MachineProvider,
30
- MachineSpec,
31
- MachineState,
27
+ import {
28
+ MachineLaunchTokenSpentError,
29
+ type MachineInfo,
30
+ type MachineLaunchIntent,
31
+ type MachineLaunchIntentStore,
32
+ type MachineProvider,
33
+ type MachineSpec,
34
+ type MachineState,
32
35
  } from "./machine-provider";
33
36
  import {
34
37
  noApprovedImageMessage,
@@ -79,12 +82,12 @@ export interface AwsMachineConfig {
79
82
 
80
83
  const DEFAULT_DISK_GIB = 50;
81
84
 
82
- type Runner = (args: string[]) => Promise<DockerResult>;
85
+ type Runner = (args: string[], options?: { env?: Record<string, string> }) => Promise<DockerResult>;
83
86
 
84
87
  const DEFAULT_TIMEOUT_MS = 60_000;
85
88
 
86
89
  function defaultRunner(region: string): Runner {
87
- return (args) =>
90
+ return (args, options = {}) =>
88
91
  new Promise<DockerResult>((resolve) => {
89
92
  let stdout = "";
90
93
  let stderr = "";
@@ -92,7 +95,10 @@ function defaultRunner(region: string): Runner {
92
95
  const child = spawn(
93
96
  "aws",
94
97
  ["--region", region, "--output", "json", ...args],
95
- { stdio: ["ignore", "pipe", "pipe"] },
98
+ {
99
+ stdio: ["ignore", "pipe", "pipe"],
100
+ ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
101
+ },
96
102
  );
97
103
  const settle = (status: number | null): void => {
98
104
  if (settled) return;
@@ -236,6 +242,81 @@ type LiveInstance = {
236
242
  payloadValidation: "pending" | "ok" | null;
237
243
  };
238
244
 
245
+ interface LaunchSubnet {
246
+ id: string;
247
+ /** Its availability zone, when describe-subnets named it. */
248
+ az: string | null;
249
+ /** UAI_AWS_SUBNET_ID: never replaced by another subnet. */
250
+ pinned: boolean;
251
+ }
252
+
253
+ function azLabel(subnet: LaunchSubnet): string {
254
+ return subnet.az ?? subnet.id;
255
+ }
256
+
257
+ /**
258
+ * EC2 error codes that reject a launch in THIS availability zone or subnet
259
+ * and provably launched nothing, so another AZ is safe to try (F3):
260
+ *
261
+ * - InsufficientInstanceCapacity: AWS has no On-Demand capacity for the type
262
+ * in the requested AZ; AWS's own advice is to try another AZ
263
+ * (docs.aws.amazon.com/AWSEC2/latest/UserGuide/troubleshooting-launch.html).
264
+ * - Unsupported, only in its instance-type/AZ form (AZ_UNSUPPORTED): the type
265
+ * is not offered in the requested AZ ("Please retry your request by ...
266
+ * choosing <other AZs>", same page). Any other Unsupported stops.
267
+ * - InsufficientFreeAddressesInSubnet: the subnet has no free private
268
+ * address (EC2 API error codes reference); another default subnet has its
269
+ * own range.
270
+ *
271
+ * Each launch asks for exactly one instance (--count 1, so MinCount 1), and
272
+ * RunInstances launches nothing when it cannot launch MinCount
273
+ * (RunInstances API reference). With AWS_MAX_ATTEMPTS=1 every answer is one
274
+ * request. So a definite rejection is no instance.
275
+ * Everything else (no exit status, RequestLimitExceeded, InternalError,
276
+ * Unavailable, an unrecognised code or message) is ambiguous and stops.
277
+ */
278
+ /** The AZ-specific `Unsupported` answer, as EC2 words it: "Your requested
279
+ * instance type (m7g.xlarge) is not supported in your requested
280
+ * Availability Zone (us-west-2d)." */
281
+ const AZ_UNSUPPORTED = /instance type \([^)]+\) is not supported in your requested Availability Zone \([^)]+\)/;
282
+
283
+ const AZ_REJECTION_CODES = new Set([
284
+ "InsufficientInstanceCapacity",
285
+ "Unsupported",
286
+ "InsufficientFreeAddressesInSubnet",
287
+ ]);
288
+
289
+ function definiteCapacityRejection(res: DockerResult): { code: string; message: string } | null {
290
+ if (res.status === null || res.status === 0) return null;
291
+ const match = /An error occurred \(([A-Za-z]+)\) when calling the RunInstances operation(?: \(reached max retries: (\d+)\))?: ([^\n]*)/.exec(res.stderr);
292
+ if (!match || !AZ_REJECTION_CODES.has(match[1]!)) return null;
293
+ // `Unsupported` covers many unsupported requests; only the instance-type
294
+ // and AZ one is about this AZ (review #mta79m).
295
+ if (match[1] === "Unsupported" && !AZ_UNSUPPORTED.test(match[3]!)) return null;
296
+ // Only a single answered request is a clean rejection. With
297
+ // AWS_MAX_ATTEMPTS=1, botocore's standard retry mode still marks a
298
+ // retryable error as max-attempts-reached on the first attempt
299
+ // (botocore/retries/standard.py, MaxAttemptsChecker sets
300
+ // MaxAttemptsReached), and ClientError then appends "(reached max
301
+ // retries: <RetryAttempts>)" (botocore/exceptions.py, _get_retry_info):
302
+ // 0 there is one attempt. A positive count means earlier attempts whose
303
+ // outcome is unknown: stop.
304
+ if (match[2] !== undefined && Number(match[2]) !== 0) return null;
305
+ return { code: match[1]!, message: match[3]!.trim() };
306
+ }
307
+
308
+ /** The one instance id a run-instances answer names; null otherwise. */
309
+ function runInstancesInstanceId(stdout: string): string | null {
310
+ try {
311
+ const instances = (JSON.parse(stdout) as { Instances?: unknown }).Instances;
312
+ if (!Array.isArray(instances) || instances.length !== 1) return null;
313
+ const id = (instances[0] as { InstanceId?: unknown } | null)?.InstanceId;
314
+ return typeof id === "string" && /^i-[0-9a-f]{8,32}$/.test(id) ? id : null;
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+
239
320
  /** Strict reservations parse. Any malformed instance voids the answer. */
240
321
  function parseReservations(stdout: string): LiveInstance[] | null {
241
322
  let parsed: unknown;
@@ -495,19 +576,23 @@ export function createAwsMachineProvider(
495
576
  return selected.id;
496
577
  }
497
578
 
498
- let resolvedSubnet: string | null = null;
499
- async function resolveSubnet(): Promise<string> {
500
- if (config.subnetId) return config.subnetId;
501
- if (resolvedSubnet) return resolvedSubnet;
579
+ let resolvedSubnets: LaunchSubnet[] | null = null;
580
+ /** Where a launch may go, in order. An explicit UAI_AWS_SUBNET_ID is the
581
+ * only candidate and is never overridden. Otherwise every default-VPC
582
+ * subnet (one per AZ, sorted by AZ), the public ones only when any is
583
+ * public: the Station dials the machine's public address. */
584
+ async function resolveSubnets(): Promise<LaunchSubnet[]> {
585
+ if (config.subnetId) return [{ id: config.subnetId, az: null, pinned: true }];
586
+ if (resolvedSubnets) return resolvedSubnets;
502
587
  const res = await runner([
503
588
  "ec2",
504
589
  "describe-subnets",
505
590
  "--filters",
506
591
  "Name=default-for-az,Values=true",
507
592
  "--query",
508
- "sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId}",
593
+ "sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId, az: AvailabilityZone}",
509
594
  ]);
510
- let subnets: Array<{ id?: unknown; public?: unknown }> = [];
595
+ let subnets: Array<{ id?: unknown; public?: unknown; az?: unknown }> = [];
511
596
  if (res.status === 0) {
512
597
  try {
513
598
  const parsed = JSON.parse(res.stdout);
@@ -516,19 +601,32 @@ export function createAwsMachineProvider(
516
601
  subnets = [];
517
602
  }
518
603
  }
519
- const chosen =
520
- subnets.find((s) => s.public === true && typeof s.id === "string") ??
521
- subnets.find((s) => typeof s.id === "string");
522
- if (!chosen || typeof chosen.id !== "string") {
604
+ const named = subnets.filter((s): s is { id: string; public?: unknown; az?: unknown } => typeof s.id === "string");
605
+ const publicOnes = named.filter((s) => s.public === true);
606
+ const eligible = publicOnes.length > 0 ? publicOnes : named;
607
+ if (eligible.length === 0) {
523
608
  throw new Error(
524
609
  `no default-VPC subnet found in ${config.region} — set ` +
525
610
  "UAI_AWS_SUBNET_ID to a public subnet",
526
611
  );
527
612
  }
528
- resolvedSubnet = chosen.id;
529
- return chosen.id;
613
+ resolvedSubnets = eligible.map((s) => ({
614
+ id: s.id,
615
+ az: typeof s.az === "string" ? s.az : null,
616
+ pinned: false,
617
+ }));
618
+ return resolvedSubnets;
530
619
  }
531
620
 
621
+ /** Launch intents for callers that bring no durable store (tests, the
622
+ * smoke scripts): per task, in-process only. */
623
+ const memoryIntents = new Map<string, MachineLaunchIntent>();
624
+ const intentStoreFor = (spec: MachineSpec): MachineLaunchIntentStore =>
625
+ spec.launchIntent ?? {
626
+ read: () => memoryIntents.get(spec.taskId) ?? null,
627
+ write: (intent) => void memoryIntents.set(spec.taskId, intent),
628
+ };
629
+
532
630
  let resolvedSecurityGroup: string | null = null;
533
631
  async function resolveSecurityGroup(subnetId: string): Promise<string> {
534
632
  if (config.securityGroupId) return config.securityGroupId;
@@ -743,78 +841,158 @@ export function createAwsMachineProvider(
743
841
  // Only an auto-selected image is subject to the payload-marker probe.
744
842
  const autoSelected = !spec.image.startsWith("ami-");
745
843
  const image = await resolveImage(spec.image);
746
- const subnetId = await resolveSubnet();
747
- const securityGroupId = await resolveSecurityGroup(subnetId);
844
+ const subnets = await resolveSubnets();
845
+ // Default-VPC subnets share the default VPC, so one group serves all.
846
+ const securityGroupId = await resolveSecurityGroup(subnets[0]!.id);
748
847
  const rootDevice = await rootDeviceName(image);
749
- // a live machine.
750
- const launchFingerprint = createHash("sha256")
751
- .update(
848
+ // F3 (review #mta79m): the persisted intent's subnet goes first, an
849
+ // attempt whose outcome is unknown included. Its token replays: a
850
+ // machine it made comes back (no second one in another AZ, whatever the
851
+ // tag query shows), and only a definite rejection there moves on. A
852
+ // launched intent also makes the AZ that worked the task's first choice.
853
+ const intents = intentStoreFor(spec);
854
+ const intent = intents.read();
855
+ const remembered: LaunchSubnet | null =
856
+ intent === null || subnets[0]!.pinned
857
+ ? null
858
+ : subnets.find((s) => s.id === intent.subnetId) ?? { id: intent.subnetId, az: null, pinned: false };
859
+ const order = remembered === null
860
+ ? subnets
861
+ : [remembered, ...subnets.filter((s) => s.id !== remembered.id)];
862
+ // F3: one attempt per subnet, moving on ONLY after a definite
863
+ // per-AZ rejection that launched nothing. Each subnet's token differs
864
+ // (the subnet is in the fingerprint), and is the same on every retry of
865
+ // that subnet, so a later attempt there replays rather than doubles.
866
+ const rejected: Array<{ subnet: LaunchSubnet; code: string; message: string }> = [];
867
+ let launchedIn: LaunchSubnet | null = null;
868
+ for (const subnet of order) {
869
+ const subnetId = subnet.id;
870
+ // a live machine.
871
+ const launchFingerprint = createHash("sha256")
872
+ .update(
873
+ JSON.stringify([
874
+ image,
875
+ type,
876
+ spec.authorizedPublicKey ?? null,
877
+ subnetId,
878
+ securityGroupId,
879
+ config.iamInstanceProfileArn ?? null,
880
+ diskGiB,
881
+ // The tag spec depends on the validation mode (an auto-selected
882
+ // image gets the `pending` tag, a pinned one none), so the mode
883
+ // is part of the token: the same AMI pinned and auto-selected
884
+ // must never share one (IdempotentParameterMismatch). The "v1"
885
+ // also keeps the tokens of 1.0.4 and earlier from meeting the new tag spec.
886
+ // describe-first above still prevents a double launch.
887
+ ["payload-validation-v1", autoSelected ? "pending" : null],
888
+ // F6: the task's Nth machine after N-1 proven terminations,
889
+ // appended only when N > 0, so generation 0 keeps exactly the
890
+ // 1.0.5 token (payload-validation-v1 included).
891
+ ...((spec.launchGeneration ?? 0) > 0
892
+ ? [["launch-generation", spec.launchGeneration]]
893
+ : []),
894
+ ]),
895
+ )
896
+ .digest("hex")
897
+ .slice(0, 16);
898
+ const args = [
899
+ "ec2",
900
+ "run-instances",
901
+ "--image-id",
902
+ image,
903
+ "--instance-type",
904
+ type,
905
+ "--count",
906
+ "1",
907
+ // Idempotency across crashed/retried provisions: the same token can
908
+ // never mint a second instance.
909
+ "--client-token",
910
+ `${machineId}-${launchFingerprint}`.slice(0, 64),
911
+ "--tag-specifications",
912
+ `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
913
+ autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
914
+ }]`,
915
+ "--block-device-mappings",
752
916
  JSON.stringify([
753
- image,
754
- type,
755
- spec.authorizedPublicKey ?? null,
756
- subnetId,
757
- securityGroupId,
758
- config.iamInstanceProfileArn ?? null,
759
- diskGiB,
760
- // The tag spec depends on the validation mode (an auto-selected
761
- // image gets the `pending` tag, a pinned one none), so the mode
762
- // is part of the token: the same AMI pinned and auto-selected
763
- // must never share one (IdempotentParameterMismatch). The "v1"
764
- // also keeps the tokens of 1.0.4 and earlier from meeting the new tag spec.
765
- // describe-first above still prevents a double launch.
766
- ["payload-validation-v1", autoSelected ? "pending" : null],
767
- ]),
768
- )
769
- .digest("hex")
770
- .slice(0, 16);
771
- const args = [
772
- "ec2",
773
- "run-instances",
774
- "--image-id",
775
- image,
776
- "--instance-type",
777
- type,
778
- "--count",
779
- "1",
780
- // Idempotency across crashed/retried provisions: the same token can
781
- // never mint a second instance.
782
- "--client-token",
783
- `${machineId}-${launchFingerprint}`.slice(0, 64),
784
- "--tag-specifications",
785
- `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
786
- autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
787
- }]`,
788
- "--block-device-mappings",
789
- JSON.stringify([
790
- {
791
- DeviceName: rootDevice,
792
- Ebs: {
793
- VolumeSize: diskGiB,
794
- VolumeType: "gp3",
795
- DeleteOnTermination: true,
917
+ {
918
+ DeviceName: rootDevice,
919
+ Ebs: {
920
+ VolumeSize: diskGiB,
921
+ VolumeType: "gp3",
922
+ DeleteOnTermination: true,
923
+ },
796
924
  },
797
- },
798
- ]),
799
- ...(spec.authorizedPublicKey
800
- ? ["--user-data", awsUserData(spec.authorizedPublicKey)]
801
- : []),
802
- "--subnet-id",
803
- subnetId,
804
- "--security-group-ids",
805
- securityGroupId,
806
- ...(config.iamInstanceProfileArn
807
- ? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
808
- : []),
809
- ];
810
- const res = await runner(args);
811
- if (res.status !== 0) {
925
+ ]),
926
+ ...(spec.authorizedPublicKey
927
+ ? ["--user-data", awsUserData(spec.authorizedPublicKey)]
928
+ : []),
929
+ "--subnet-id",
930
+ subnetId,
931
+ "--security-group-ids",
932
+ securityGroupId,
933
+ ...(config.iamInstanceProfileArn
934
+ ? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
935
+ : []),
936
+ ];
937
+ // Durable BEFORE the request: a crash or an unknown answer from here
938
+ // on leaves this subnet to be replayed first. A failed write launches
939
+ // nothing.
940
+ intents.write({ subnetId, state: "attempting" });
941
+ // One attempt per answer (review #mta79m): the CLI's own retries
942
+ // could hide an earlier attempt's unknown outcome behind a final
943
+ // capacity error. AWS_MAX_ATTEMPTS counts the initial call, so 1
944
+ // disables retries; the environment overrides the config file
945
+ // (AWS CLI "AWS CLI retries" and environment-variable docs).
946
+ const res = await runner(args, { env: { AWS_MAX_ATTEMPTS: "1" } });
947
+ if (res.status === 0) {
948
+ // F6 (test 6.3): a repeated client token is answered with the
949
+ // instance it first launched, even once that instance is terminated
950
+ // (its root volume deleted with it). The tag query below never lists
951
+ // a terminated instance, so look the answered instance up by id: only
952
+ // a definite terminated / shutting-down answer is proof the token is
953
+ // spent. A brand-new id that is not yet visible proves nothing.
954
+ const answeredId = runInstancesInstanceId(res.stdout);
955
+ if (answeredId !== null) {
956
+ const byId = await runner([
957
+ "ec2",
958
+ "describe-instances",
959
+ "--instance-ids",
960
+ answeredId,
961
+ ]);
962
+ const answered = byId.status === 0 ? parseReservations(byId.stdout) : null;
963
+ const gone = answered?.length === 1 &&
964
+ answered[0]!.instanceId === answeredId &&
965
+ (answered[0]!.state === "terminated" || answered[0]!.state === "shutting-down");
966
+ if (gone) {
967
+ throw new MachineLaunchTokenSpentError(machineId, answeredId, answered[0]!.state);
968
+ }
969
+ }
970
+ launchedIn = subnet;
971
+ break;
972
+ }
973
+ const rejection = subnet.pinned ? null : definiteCapacityRejection(res);
974
+ if (rejection === null) {
975
+ // Ambiguous (a timeout, throttling, a 5xx, anything unrecognised) or
976
+ // a pinned subnet: no other AZ, since this attempt may have launched.
977
+ throw new Error(
978
+ `machine launch failed for ${machineId}${
979
+ rejected.length > 0 ? ` (after no capacity in ${rejected.map((r) => azLabel(r.subnet)).join(", ")})` : ""
980
+ }: ${res.stderr.trim() || `exit ${res.status ?? "killed"}`}`,
981
+ );
982
+ }
983
+ rejected.push({ subnet, ...rejection });
984
+ console.warn(
985
+ `[machine-aws] ${machineId}: ${rejection.code} in ${azLabel(subnet)}; trying the next availability zone`,
986
+ );
987
+ }
988
+ if (launchedIn === null) {
812
989
  throw new Error(
813
- `machine launch failed for ${machineId}: ${
814
- res.stderr.trim() || `exit ${res.status ?? "killed"}`
815
- }`,
990
+ `machine launch failed for ${machineId}: no ${type} capacity in ${config.region} ` +
991
+ `(${rejected.map((r) => `${azLabel(r.subnet)}: ${r.code}`).join("; ")}). ` +
992
+ "Try again later, choose another instance type, or launch the host in another region.",
816
993
  );
817
994
  }
995
+ intents.write({ subnetId: launchedIn.id, state: "launched" });
818
996
  // DescribeInstances TAG FILTERS are eventually consistent: the query
819
997
  // can miss an instance RunInstances just created (live 2026-08-28 —
820
998
  // the machine was running the whole time while launch reported
@@ -43,6 +43,49 @@ export interface MachineSpec {
43
43
  * host-routable there, so SSH must ride a loopback-published port. The
44
44
  * Linux guinea pig and cloud backends dial the address directly. */
45
45
  publishSsh?: boolean;
46
+ /** F3: where the task's launch intent is kept (its control dir), so a
47
+ * retry after a restart replays the subnet an earlier attempt used before
48
+ * trying any other. Backends without placement choices ignore it. */
49
+ launchIntent?: MachineLaunchIntentStore;
50
+ /** Which launch of this task's machine this is (F6). A cloud backend's
51
+ * launch idempotency is keyed on it: 0 (or absent) is the task's first
52
+ * machine, with the token every earlier release used. The caller bumps it
53
+ * only after the backend proved the previous generation's machine
54
+ * terminated (MachineLaunchTokenSpentError), so a retry of a launch still
55
+ * in flight keeps its token and can never mint a second machine. */
56
+ launchGeneration?: number;
57
+ }
58
+
59
+ /** The subnet a launch is attempting or launched in; `attempting` means its
60
+ * outcome is not yet known. */
61
+ export interface MachineLaunchIntent {
62
+ subnetId: string;
63
+ state: "attempting" | "launched";
64
+ }
65
+
66
+ export interface MachineLaunchIntentStore {
67
+ read(): MachineLaunchIntent | null;
68
+ /** Atomic and durable before it returns; throws rather than pretend. */
69
+ write(intent: MachineLaunchIntent): void;
70
+ }
71
+
72
+ /**
73
+ * The backend's launch idempotency resolved to a machine that is already
74
+ * terminated (F6, test 6.3): EC2 remembers a client token for a while past
75
+ * termination and answers a repeat with the old, gone instance. Proof that
76
+ * this launch generation is spent; the caller may launch the next one.
77
+ */
78
+ export class MachineLaunchTokenSpentError extends Error {
79
+ override readonly name = "MachineLaunchTokenSpentError";
80
+ constructor(
81
+ readonly machineId: string,
82
+ readonly instanceId: string,
83
+ readonly instanceState: string,
84
+ ) {
85
+ super(
86
+ `machine ${machineId}: its launch token resolved to instance ${instanceId}, which is ${instanceState}`,
87
+ );
88
+ }
46
89
  }
47
90
 
48
91
  export interface MachineInfo {
@@ -142,6 +142,7 @@ import {
142
142
  ensureMachineGatewayTunnel,
143
143
  ensureMachineGatewayTunnelReady,
144
144
  MACHINE_GATEWAY_TUNNEL_PORT,
145
+ stopMachineGatewayTunnel,
145
146
  } from "./machine-gateway-tunnel";
146
147
  import { ensureContainerTaskEnvForwarder } from "./task-env-forwarder";
147
148
  import { STATION_AGENT_CLI } from "../src/station-identity";
@@ -8246,6 +8247,27 @@ function finishAllTaskRecovery(): void {
8246
8247
  for (const taskId of [...taskRecoveryBarriers.keys()]) {
8247
8248
  finishTaskRecovery(taskId);
8248
8249
  }
8250
+ abandonedTaskRecoveries.clear();
8251
+ }
8252
+
8253
+ /** Boot-recovery attempts under way, by task: a barrier is never released
8254
+ * under one (the attempt may be starting the task's runtime). */
8255
+ const recoveringTaskIds = new Set<string>();
8256
+ /** Tasks whose boot recovery a terminal command ended (F4): never retried. */
8257
+ const abandonedTaskRecoveries = new Set<string>();
8258
+
8259
+ /**
8260
+ * Terminal intent (task deletion / teardown of the current run): end this
8261
+ * task's boot recovery. Its barrier opens now, or as soon as an attempt
8262
+ * under way returns, and no later pass retries it, so the teardown queued
8263
+ * behind the barrier runs instead of waiting out every retry (F4, test 6.2:
8264
+ * a deleted task whose machine was never launched kept recovery retrying
8265
+ * until the next restart). A no-op once the task's recovery is over.
8266
+ */
8267
+ export function abandonTaskRecovery(taskId: string): void {
8268
+ if (!taskRecoveryBarriers.has(taskId)) return;
8269
+ abandonedTaskRecoveries.add(taskId);
8270
+ if (!recoveringTaskIds.has(taskId)) finishTaskRecovery(taskId);
8249
8271
  }
8250
8272
 
8251
8273
  export function taskRecoveryComplete(taskId: string): Promise<void> {
@@ -9725,6 +9747,12 @@ async function recoveryPass(
9725
9747
  );
9726
9748
  for (const task of rows) {
9727
9749
  if (!isCurrent()) break;
9750
+ if (!lifecycle && abandonedTaskRecoveries.has(task.taskId)) {
9751
+ abandonedTaskRecoveries.delete(task.taskId);
9752
+ finishTaskRecovery(task.taskId);
9753
+ continue;
9754
+ }
9755
+ if (!lifecycle) recoveringTaskIds.add(task.taskId);
9728
9756
  try {
9729
9757
  const recovered = lifecycle
9730
9758
  ? await lifecycle.runTaskLifecycle(task.taskId, async () => {
@@ -9753,7 +9781,10 @@ async function recoveryPass(
9753
9781
  isCurrent,
9754
9782
  consumerLifecycle,
9755
9783
  );
9756
- if (recovered) {
9784
+ if (!lifecycle && abandonedTaskRecoveries.delete(task.taskId)) {
9785
+ // Ended by a terminal command while this attempt ran.
9786
+ finishTaskRecovery(task.taskId);
9787
+ } else if (recovered) {
9757
9788
  if (!lifecycle) finishTaskRecovery(task.taskId);
9758
9789
  } else {
9759
9790
  deferred.add(task.taskId);
@@ -9765,6 +9796,8 @@ async function recoveryPass(
9765
9796
  `[orchestrator] recovery: ${task.taskId} failed:`,
9766
9797
  err instanceof Error ? err.message : err,
9767
9798
  );
9799
+ } finally {
9800
+ if (!lifecycle) recoveringTaskIds.delete(task.taskId);
9768
9801
  }
9769
9802
  }
9770
9803
  } catch (err) {
@@ -10086,6 +10119,18 @@ async function recoverPersistedTaskEnvironment(
10086
10119
  : {}),
10087
10120
  });
10088
10121
  if (result.outcome === "recovered" && !consumersPrepared && isCurrent()) {
10122
+ const settled = result.status?.state;
10123
+ if (settled === "absent" || settled === "stopped") {
10124
+ // F4 (test 6.2): the provider proved nothing runs, so there is no
10125
+ // consumer to prepare. Preparing them anyway waited on a gateway
10126
+ // tunnel to a machine that does not exist, deferred recovery every
10127
+ // pass, and held Resume and deletion behind the task's barrier.
10128
+ // Settle the row as stopped instead, like Docker and Apple recovery:
10129
+ // Resume provisions it (starting a stopped machine, launching an
10130
+ // absent one), and deletion tears it down.
10131
+ settleRecoveredWithoutRuntime(task.taskId, settled);
10132
+ return true;
10133
+ }
10089
10134
  const current = getHostTask(task.taskId);
10090
10135
  if (current?.statusMirror && isActive(current.statusMirror)) {
10091
10136
  await prepareConsumers();
@@ -10101,6 +10146,22 @@ async function recoverPersistedTaskEnvironment(
10101
10146
  }
10102
10147
  }
10103
10148
 
10149
+ /** A recovered environment with nothing running: drop the gateway tunnel the
10150
+ * recovery armed, mark an active row stopped, and revoke its gateway token. */
10151
+ function settleRecoveredWithoutRuntime(
10152
+ taskId: string,
10153
+ state: "absent" | "stopped",
10154
+ ): void {
10155
+ stopMachineGatewayTunnel(taskId);
10156
+ const current = getHostTask(taskId);
10157
+ if (!current?.statusMirror || !isActive(current.statusMirror)) return;
10158
+ db_setStatus(taskId, "stopped", { codeServerPort: null, previewPorts: "[]" });
10159
+ clearTaskGatewayAcl(taskId);
10160
+ console.log(
10161
+ `[orchestrator] recovery: ${taskId} has no running environment (${state}); marked stopped until Resume`,
10162
+ );
10163
+ }
10164
+
10104
10165
  /** A durable row the provider can never reconcile with its locator. Retrying
10105
10166
  * cannot change the verdict, so the sweep must not treat it as an unknown
10106
10167
  * runtime state: that kept the whole runtime in checking, retrying every