@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.
@@ -1,6 +1,7 @@
1
1
  import type { TaskEnvironmentHandle } from "./task-environment/types";
2
2
  import { isEnvironmentTransportProvider } from "./task-environment/types";
3
3
  import { MACHINE_GATEWAY_TUNNEL_PORT } from "./machine-gateway-tunnel";
4
+ import { MACHINE_SSH_CONNECT_TIMEOUT_SECONDS } from "./machine-exec";
4
5
  import {
5
6
  installMachineProjectEnvLoader,
6
7
  installMachineTaskForwarderAsset,
@@ -23,16 +24,51 @@ type TaskForwarderNodePath =
23
24
  | "/usr/local/bin/node"
24
25
  | typeof APPLE_FORWARDER_NODE_PATH;
25
26
 
27
+ /**
28
+ * How long the launcher waits for the forwarder's READY (F5, test 6.2: 2 of 5
29
+ * AWS-host starts failed at the old 5 s). It must outlast the child's own
30
+ * verdict, so a slow child reports its own failure instead of being cut off:
31
+ * node start-up, then up to SECONDS of SECRET_INPUT_TIMEOUT_MS (5 s,
32
+ * uai-task-forwarder.mjs) reading the secret from stdin, then a loopback
33
+ * listen. The old 5 s deadline equalled that stdin budget alone.
34
+ */
35
+ export const TASK_FORWARDER_READY_SECONDS = 20;
36
+ /** Bound on stopping a previous forwarder before the new one starts. */
37
+ export const OLD_FORWARDER_STOP_SECONDS = 5;
38
+ /**
39
+ * The exec budget, built from what may happen before the launcher answers
40
+ * (review #tgxadc: an 8 s connect, a 5 s old-forwarder stop and a child
41
+ * ready at 18 s exceeded the old 30 s, and the kill took the diagnostics):
42
+ * ssh's connect and handshake (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS, 10 s),
43
+ * the old-forwarder stop (5 s) and the READY wait (20 s), each measured on
44
+ * a whole-second clock (+1 s each), and 4 s for the remaining shell steps
45
+ * and the answer: 41 s. On a direct exec (no ssh) the connect term only
46
+ * adds slack. The launcher thus always answers, with its report, before
47
+ * the exec is killed.
48
+ */
49
+ export const LAUNCH_EXEC_TIMEOUT_MS =
50
+ (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS + OLD_FORWARDER_STOP_SECONDS + 1 + TASK_FORWARDER_READY_SECONDS + 1 + 4) * 1_000;
51
+ /** The whole thrown message, in UTF-8 bytes. */
52
+ export const MAX_LAUNCH_ERROR_BYTES = 2_048;
53
+ const ERROR_LOG_TAIL_BYTES = 1_024;
54
+
26
55
  // Shared by initial machine provisioning and every recovery topology. Keep
27
56
  // the ownership/process proof in lockstep with task-up.sh's container
28
57
  // launcher. The generation secret arrives on stdin; no task file, argv entry,
29
58
  // or environment variable ever contains it.
30
- const START_TASK_FORWARDER = String.raw`set -eu
59
+ //
60
+ // On failure it names which one (the child exited, with its status, or was
61
+ // not ready in time) and appends the tail of the child's error.log, so the
62
+ // thrown error carries the real cause before any cleanup removes the machine.
63
+ export const START_TASK_FORWARDER = String.raw`set -eu
31
64
  task_id=$1
32
65
  generation=$2
33
66
  gateway_host=$3
34
67
  gateway_port=$4
35
68
  node_path=$5
69
+ ready_seconds=$6
70
+ case "$ready_seconds" in ''|*[!0-9]*) exit 1 ;; esac
71
+ [ "$ready_seconds" -ge 1 ] && [ "$ready_seconds" -le 25 ] || exit 1
36
72
  case "$node_path" in
37
73
  /usr/bin/node | /usr/local/bin/node) ;;
38
74
  ${APPLE_FORWARDER_NODE_PATH})
@@ -66,10 +102,11 @@ if [ -f "$pid_file" ] && [ ! -L "$pid_file" ]; then
66
102
  && printf '%s\n' "$old_args" | /bin/grep -Fxq '/usr/local/share/uai/uai-task-forwarder.mjs' \
67
103
  && printf '%s\n' "$old_args" | /bin/grep -Fxq "$task_id"; then
68
104
  /bin/kill -TERM "$old_pid"
69
- attempts=0
70
- while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$attempts" -lt 50 ]; do
105
+ # Wall clock, so the stop stays within the exec budget however slow
106
+ # each fork is on a cold machine.
107
+ stop_deadline=$((SECONDS + ${OLD_FORWARDER_STOP_SECONDS}))
108
+ while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$SECONDS" -lt "$stop_deadline" ]; do
71
109
  /bin/sleep 0.1
72
- attempts=$((attempts + 1))
73
110
  done
74
111
  if /bin/kill -0 "$old_pid" 2>/dev/null; then
75
112
  /bin/kill -KILL "$old_pid"
@@ -102,22 +139,91 @@ forwarder_pid=$!
102
139
  exec 3<&-
103
140
  printf '%s\n' "$forwarder_pid" > "$pid_file"
104
141
 
105
- attempts=0
106
- while [ "$attempts" -lt 50 ]; do
107
- /bin/kill -0 "$forwarder_pid" 2>/dev/null || exit 1
142
+ report_log() {
143
+ if [ -s "$error_file" ] && [ ! -L "$error_file" ]; then
144
+ printf '%s\n' "forwarder error.log (last ${ERROR_LOG_TAIL_BYTES} bytes):" >&2
145
+ /usr/bin/tail -c ${ERROR_LOG_TAIL_BYTES} "$error_file" >&2 || true
146
+ else
147
+ printf '%s\n' "forwarder error.log is empty" >&2
148
+ fi
149
+ }
150
+
151
+ # Wall clock, not an iteration count: on a cold machine each /bin/sleep fork
152
+ # is slow too, and the deadline must hold inside the exec budget.
153
+ deadline=$((SECONDS + ready_seconds))
154
+ while :; do
155
+ if ! /bin/kill -0 "$forwarder_pid" 2>/dev/null; then
156
+ status=0
157
+ wait "$forwarder_pid" || status=$?
158
+ printf '%s\n' "task env forwarder exited with status $status before it was ready" >&2
159
+ report_log
160
+ exit 1
161
+ fi
108
162
  if [ -f "$ready_file" ] \
109
163
  && [ "$(/bin/cat "$ready_file" 2>/dev/null || true)" = READY ]; then
110
164
  exit 0
111
165
  fi
166
+ # SECONDS counts whole seconds: -gt waits at least ready_seconds, at most
167
+ # one more.
168
+ if [ "$SECONDS" -gt "$deadline" ]; then
169
+ printf '%s\n' "task env forwarder was not ready within $ready_seconds s (pid $forwarder_pid still running)" >&2
170
+ report_log
171
+ exit 1
172
+ fi
112
173
  /bin/sleep 0.1
113
- attempts=$((attempts + 1))
114
- done
115
- exit 1`;
174
+ done`;
116
175
 
117
176
  export interface TaskEnvForwarderLaunchOptions {
118
177
  gatewayHost: string;
119
178
  gatewayPort: number;
120
179
  nodePath: TaskForwarderNodePath;
180
+ /** Test seam; production always uses TASK_FORWARDER_READY_SECONDS. */
181
+ readySeconds?: number;
182
+ }
183
+
184
+ /**
185
+ * The thrown message, at most MAX_LAUNCH_ERROR_BYTES of UTF-8 (review
186
+ * #tgxadc: the detail alone was bounded, and invalid bytes from the child's
187
+ * log grow threefold as U+FFFD). Keeps the launcher's verdict line (which
188
+ * failure, the child's status) and as much of the log's END as fits, the
189
+ * newest lines, cut between characters, never inside one.
190
+ */
191
+ export function launchFailureMessage(outcome: string, detail: string): string {
192
+ const head = `task env forwarder failed to start (${outcome})`;
193
+ const whole = detail ? `${head}: ${detail}` : head;
194
+ if (Buffer.byteLength(whole) <= MAX_LAUNCH_ERROR_BYTES) return whole;
195
+ const newline = detail.indexOf("\n");
196
+ const verdict = newline === -1 ? "" : detail.slice(0, newline);
197
+ const rest = newline === -1 ? detail : detail.slice(newline + 1);
198
+ const lead = `${head}: ${utf8Prefix(verdict, 512)}${verdict ? "\n" : ""}…`;
199
+ return lead + utf8Suffix(rest, MAX_LAUNCH_ERROR_BYTES - Buffer.byteLength(lead));
200
+ }
201
+
202
+ /** The longest prefix of `text` within `bytes` UTF-8 bytes, whole code points. */
203
+ function utf8Prefix(text: string, bytes: number): string {
204
+ let used = 0;
205
+ let out = "";
206
+ for (const char of text) {
207
+ const size = Buffer.byteLength(char);
208
+ if (used + size > bytes) break;
209
+ used += size;
210
+ out += char;
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /** The longest suffix of `text` within `bytes` UTF-8 bytes, whole code points. */
216
+ function utf8Suffix(text: string, bytes: number): string {
217
+ const chars = Array.from(text);
218
+ let used = 0;
219
+ let start = chars.length;
220
+ while (start > 0) {
221
+ const size = Buffer.byteLength(chars[start - 1]!);
222
+ if (used + size > bytes) break;
223
+ used += size;
224
+ start -= 1;
225
+ }
226
+ return chars.slice(start).join("");
121
227
  }
122
228
 
123
229
  /** Launch or replace one authenticated task forwarder. Consumes and wipes
@@ -149,11 +255,12 @@ export async function launchTaskEnvForwarder(
149
255
  options.gatewayHost,
150
256
  String(options.gatewayPort),
151
257
  options.nodePath,
258
+ String(options.readySeconds ?? TASK_FORWARDER_READY_SECONDS),
152
259
  ],
153
260
  user: "root",
154
261
  projectEnvProfile: "maintenance",
155
262
  stdin: secret,
156
- timeoutMs: 30_000,
263
+ timeoutMs: LAUNCH_EXEC_TIMEOUT_MS,
157
264
  maxOutputBytes: STEP_OUTPUT_BYTES,
158
265
  });
159
266
  if (
@@ -162,12 +269,11 @@ export async function launchTaskEnvForwarder(
162
269
  result.stdoutTruncated ||
163
270
  result.stderrTruncated
164
271
  ) {
165
- throw new Error(
166
- `task env forwarder failed to start: ${Buffer.from(result.stderr)
167
- .toString("utf8")
168
- .trim()
169
- .slice(-512) || `exit ${String(result.exitCode)}`}`,
170
- );
272
+ const detail = Buffer.from(result.stderr).toString("utf8").trim();
273
+ const outcome = result.signal !== null
274
+ ? `killed by ${result.signal} (the ${LAUNCH_EXEC_TIMEOUT_MS / 1000} s launch budget ran out)`
275
+ : `exit ${String(result.exitCode)}`;
276
+ throw new Error(launchFailureMessage(outcome, detail));
171
277
  }
172
278
  } finally {
173
279
  secret.fill(0);
@@ -1230,6 +1230,9 @@ export function createMachineHostTaskEnvironmentProvider(
1230
1230
  throw error;
1231
1231
  }
1232
1232
  return {
1233
+ // The Station posts the replacement note and, once the cloud has it,
1234
+ // clears the notice (src/index.ts): never before.
1235
+ ...(provisioned.lossNotices?.length ? { lossNotices: provisioned.lossNotices } : {}),
1233
1236
  handle: withTaskDownResult(handle),
1234
1237
  result: {
1235
1238
  // Recorded as the task's runtime identity (the compose-project
@@ -1241,6 +1244,7 @@ export function createMachineHostTaskEnvironmentProvider(
1241
1244
  ...(warnings.length > 0
1242
1245
  ? { initWarning: warnings.join("\n") }
1243
1246
  : {}),
1247
+ ...(provisioned.replacedLostEnvironment ? { environmentReplaced: true as const } : {}),
1244
1248
  },
1245
1249
  };
1246
1250
  },
@@ -15,15 +15,20 @@
15
15
  */
16
16
 
17
17
  import { execFile, spawn as nodeSpawn } from "node:child_process";
18
- import { readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
19
+ import { join } from "node:path";
19
20
  import { promisify } from "node:util";
20
21
 
21
- import type {
22
- MachineInfo,
23
- MachineProvider,
22
+ import {
23
+ MachineLaunchTokenSpentError,
24
+ type MachineInfo,
25
+ type MachineLaunchIntent,
26
+ type MachineLaunchIntentStore,
27
+ type MachineProvider,
24
28
  } from "../machine-provider";
25
29
  import { machineEnvironmentSshArgs } from "../machine-exec";
26
30
  import { STATION_MACHINE_PAYLOAD_MARKER } from "../machine-payload-image";
31
+ import type { EnvironmentLossNotice } from "./types";
27
32
  import { applyProjectEnvProfile } from "../runtime-authority";
28
33
  import { rootAnchoredRequest } from "./anchor";
29
34
  import {
@@ -121,6 +126,283 @@ export interface MachineTaskEnvironmentDeps {
121
126
  readyTimeoutMs?: number;
122
127
  }
123
128
 
129
+ /**
130
+ * F6: which launch of a task's machine is current, kept beside its SSH
131
+ * identity in the task control dir so it survives a Station restart. The
132
+ * generation feeds the backend's launch idempotency (MachineSpec), and is
133
+ * bumped only after the backend proves the current generation's machine
134
+ * terminated. `launched` records that this generation's launch succeeded, and
135
+ * `instanceId` which instance it made: a later launch answered by a DIFFERENT
136
+ * instance means the old one, and its disk, went away. The same instance
137
+ * means a retry found it again (a lagging describe), and nothing was lost.
138
+ *
139
+ * `pendingLossNotices` holds those proofs, one per lost machine, until the
140
+ * user has been told (reviews #w3qdsr, #4ndq0w): each is added when its loss
141
+ * is proven, carried across a crash before the relaunch and across failed
142
+ * starts after it, and removed (by its id) only once the cloud has its note.
143
+ * A queue, not one slot: every lost machine is its own fact with its own id,
144
+ * so a second loss can never be folded into, or hidden behind, the first.
145
+ */
146
+ export interface MachineLaunchRecord {
147
+ generation: number;
148
+ launched: boolean;
149
+ instanceId?: string;
150
+ pendingLossNotices?: PendingLossNotice[];
151
+ /** F3: the subnet the latest launch attempt used, written BEFORE its
152
+ * run-instances; `attempting` means its outcome is not yet known. The
153
+ * next launch replays this subnet first (fileLaunchIntentStore). One
154
+ * record, so the generation and the subnet always move together; every
155
+ * write re-reads the file and keeps the fields it does not own. */
156
+ launchIntent?: MachineLaunchIntent;
157
+ }
158
+
159
+ export interface PendingLossNotice {
160
+ lostInstanceId: string | null;
161
+ /** The generation that replaced it: with the instance, the loss's id. */
162
+ generation: number;
163
+ /** Handed to a publisher at least once (review #2cp6r4). Set before the
164
+ * first publish and never cleared: the cloud may hold this id already, so
165
+ * the entry is immutable (never folded, grown or dropped) until its id is
166
+ * acknowledged, and every retry resends the identical id and text. */
167
+ attempted?: true;
168
+ /** A summary of several losses folded together when the queue overflowed
169
+ * (review #d0p42f). `lostInstanceId` and `generation` are the FIRST folded
170
+ * loss's, so the summary's id never changes as more fold in. */
171
+ folded?: { count: number; instanceIds: string[] };
172
+ }
173
+
174
+ /**
175
+ * The most entries the queue keeps (review #d0p42f). Each one needs a real
176
+ * EC2 machine of this task proven terminated, whose note the cloud has not
177
+ * yet confirmed. Even a handful between two successful starts is far beyond
178
+ * what happens, so 16 never folds in practice and still bounds a broken
179
+ * delivery path. With at most MAX_FOLDED_INSTANCE_IDS ids in a summary, the
180
+ * whole record stays under 4 KiB.
181
+ *
182
+ * It is never exceeded (review #2cp6r4): the Station delivers one entry per
183
+ * task at a time, oldest first, and attempts the next only once the current
184
+ * one is acknowledged, so at most one entry is attempted at any time and at
185
+ * least 15 of 16 are always foldable.
186
+ */
187
+ export const MAX_PENDING_LOSS_NOTICES = 16;
188
+ export const MAX_FOLDED_INSTANCE_IDS = 8;
189
+
190
+ function isPendingLossNotice(value: unknown): value is PendingLossNotice {
191
+ if (typeof value !== "object" || value === null) return false;
192
+ const notice = value as { lostInstanceId?: unknown; generation?: unknown; attempted?: unknown; folded?: unknown };
193
+ const folded = notice.folded as { count?: unknown; instanceIds?: unknown } | undefined;
194
+ return (
195
+ (notice.lostInstanceId === null || typeof notice.lostInstanceId === "string") &&
196
+ typeof notice.generation === "number" &&
197
+ Number.isSafeInteger(notice.generation) &&
198
+ (notice.attempted === undefined || notice.attempted === true) &&
199
+ (folded === undefined ||
200
+ (typeof folded === "object" &&
201
+ folded !== null &&
202
+ typeof folded.count === "number" &&
203
+ Number.isSafeInteger(folded.count) &&
204
+ folded.count >= 1 &&
205
+ Array.isArray(folded.instanceIds) &&
206
+ folded.instanceIds.length <= MAX_FOLDED_INSTANCE_IDS &&
207
+ folded.instanceIds.every((id) => typeof id === "string" && id.length <= 64)))
208
+ );
209
+ }
210
+
211
+ /** `into` (a summary, or a single loss that becomes one) with `next` folded in. */
212
+ function foldLossNotices(into: PendingLossNotice, next: PendingLossNotice): PendingLossNotice {
213
+ const idsOf = (notice: PendingLossNotice): string[] =>
214
+ notice.folded?.instanceIds ?? (notice.lostInstanceId === null ? [] : [notice.lostInstanceId]);
215
+ const countOf = (notice: PendingLossNotice): number => notice.folded?.count ?? 1;
216
+ return {
217
+ lostInstanceId: into.lostInstanceId,
218
+ generation: into.generation,
219
+ folded: {
220
+ count: countOf(into) + countOf(next),
221
+ instanceIds: [...idsOf(into), ...idsOf(next)].slice(0, MAX_FOLDED_INSTANCE_IDS),
222
+ },
223
+ };
224
+ }
225
+
226
+ /** The record's queue with `notice` added, unless one with its id is there. */
227
+ export function withLossNotice(current: MachineLaunchRecord, notice: PendingLossNotice): PendingLossNotice[] {
228
+ const existing = current.pendingLossNotices ?? [];
229
+ if (existing.some((pending) => lossNoticeId(pending) === lossNoticeId(notice))) return existing;
230
+ const queue = [...existing, notice];
231
+ // Reviews #d0p42f, #2cp6r4: at most MAX_PENDING_LOSS_NOTICES entries.
232
+ while (queue.length > MAX_PENDING_LOSS_NOTICES) {
233
+ // The two oldest entries never attempted fold into one. An attempted
234
+ // entry is never touched: the cloud may already hold its id. A summary
235
+ // never attempted may grow (the cloud never saw its id) and keeps it;
236
+ // two singles make a new summary, whose id is its own first loss's.
237
+ const first = queue.findIndex((pending) => pending.attempted !== true);
238
+ const second = first === -1 ? -1 : queue.findIndex((pending, index) => index > first && pending.attempted !== true);
239
+ if (second === -1) {
240
+ // Only reachable with two or more attempted entries, which one-at-a-time
241
+ // delivery never leaves: refuse rather than drop a proof or grow past
242
+ // the bound.
243
+ throw new Error(
244
+ `machine-loss notice queue invariant broken: ${String(queue.filter((pending) => pending.attempted === true).length)} attempted entries`,
245
+ );
246
+ }
247
+ const folded = foldLossNotices(queue[first]!, queue[second]!);
248
+ queue.splice(second, 1);
249
+ queue.splice(first, 1, folded);
250
+ }
251
+ return queue;
252
+ }
253
+
254
+ export function lossNoticeId(notice: PendingLossNotice): string {
255
+ const single = `${notice.lostInstanceId ?? "unknown-instance"}@generation-${notice.generation}`;
256
+ return notice.folded ? `folded:${single}` : single;
257
+ }
258
+
259
+ export const MACHINE_LAUNCH_RECORD = "machine-launch.json";
260
+
261
+ /** The task's launch record; a task from before F6 has none (generation 0,
262
+ * never recorded as launched). A record that does not parse is refused, not
263
+ * guessed at: a wrong generation could reuse a spent token or double-launch. */
264
+ export function readMachineLaunchRecord(controlDir: string): MachineLaunchRecord {
265
+ let raw: string;
266
+ try {
267
+ raw = readFileSync(join(controlDir, MACHINE_LAUNCH_RECORD), "utf8");
268
+ } catch (error) {
269
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { generation: 0, launched: false };
270
+ throw error;
271
+ }
272
+ const parsed = JSON.parse(raw) as {
273
+ schemaVersion?: unknown;
274
+ generation?: unknown;
275
+ launched?: unknown;
276
+ instanceId?: unknown;
277
+ pendingLossNotices?: unknown;
278
+ launchIntent?: { subnetId?: unknown; state?: unknown } | null;
279
+ };
280
+ if (
281
+ parsed?.schemaVersion !== 1 ||
282
+ typeof parsed.generation !== "number" ||
283
+ !Number.isSafeInteger(parsed.generation) ||
284
+ parsed.generation < 0 ||
285
+ typeof parsed.launched !== "boolean" ||
286
+ (parsed.instanceId !== undefined && typeof parsed.instanceId !== "string") ||
287
+ (parsed.pendingLossNotices !== undefined &&
288
+ (!Array.isArray(parsed.pendingLossNotices) || !parsed.pendingLossNotices.every(isPendingLossNotice))) ||
289
+ (parsed.launchIntent !== undefined &&
290
+ (typeof parsed.launchIntent !== "object" ||
291
+ parsed.launchIntent === null ||
292
+ typeof parsed.launchIntent.subnetId !== "string" ||
293
+ // Refused, not guessed at: a wrong subnet could launch a second machine.
294
+ !/^subnet-[0-9a-f]{8,32}$/.test(parsed.launchIntent.subnetId) ||
295
+ (parsed.launchIntent.state !== "attempting" && parsed.launchIntent.state !== "launched")))
296
+ ) {
297
+ throw new Error(`machine launch record in ${controlDir} is invalid`);
298
+ }
299
+ return {
300
+ generation: parsed.generation,
301
+ launched: parsed.launched,
302
+ ...(typeof parsed.instanceId === "string" ? { instanceId: parsed.instanceId } : {}),
303
+ ...(Array.isArray(parsed.pendingLossNotices) && parsed.pendingLossNotices.length > 0
304
+ ? {
305
+ pendingLossNotices: (parsed.pendingLossNotices as PendingLossNotice[]).map((notice) => ({
306
+ lostInstanceId: notice.lostInstanceId,
307
+ generation: notice.generation,
308
+ ...(notice.attempted === true ? { attempted: true as const } : {}),
309
+ ...(notice.folded
310
+ ? { folded: { count: notice.folded.count, instanceIds: [...notice.folded.instanceIds] } }
311
+ : {}),
312
+ })),
313
+ }
314
+ : {}),
315
+ ...(parsed.launchIntent !== undefined
316
+ ? {
317
+ launchIntent: {
318
+ subnetId: parsed.launchIntent.subnetId as string,
319
+ state: parsed.launchIntent.state as MachineLaunchIntent["state"],
320
+ },
321
+ }
322
+ : {}),
323
+ };
324
+ }
325
+
326
+ /** Read the record afresh, change it, write it: a writer never drops a field
327
+ * another one owns (the launch intent, the loss notice). */
328
+ export function updateMachineLaunchRecord(
329
+ controlDir: string,
330
+ change: (current: MachineLaunchRecord) => MachineLaunchRecord,
331
+ ): void {
332
+ writeMachineLaunchRecord(controlDir, change(readMachineLaunchRecord(controlDir)));
333
+ }
334
+
335
+ /** F3's launch-intent store over the task's machine-launch.json. */
336
+ export function fileLaunchIntentStore(controlDir: string): MachineLaunchIntentStore {
337
+ return {
338
+ read: () => readMachineLaunchRecord(controlDir).launchIntent ?? null,
339
+ write: (intent) => updateMachineLaunchRecord(controlDir, (current) => ({ ...current, launchIntent: { ...intent } })),
340
+ };
341
+ }
342
+
343
+ /** The pending notice as the Station delivers it. Both steps touch only the
344
+ * notice they were handed (by id) and throw on a failed write. */
345
+ export function machineLossNotice(controlDir: string, pending: PendingLossNotice): EnvironmentLossNotice {
346
+ const id = lossNoticeId(pending);
347
+ // Each step re-reads the record and touches only this notice, by id.
348
+ const update = (change: (notice: PendingLossNotice) => PendingLossNotice | null): void =>
349
+ updateMachineLaunchRecord(controlDir, (current) => {
350
+ const queue: PendingLossNotice[] = [];
351
+ for (const notice of current.pendingLossNotices ?? []) {
352
+ if (lossNoticeId(notice) !== id) {
353
+ queue.push(notice);
354
+ continue;
355
+ }
356
+ const next = change(notice);
357
+ if (next !== null) queue.push(next);
358
+ }
359
+ const { pendingLossNotices: _old, ...rest } = current;
360
+ return queue.length > 0 ? { ...rest, pendingLossNotices: queue } : rest;
361
+ });
362
+ return {
363
+ id,
364
+ attempted: pending.attempted === true,
365
+ lostEnvironments: pending.folded?.count ?? 1,
366
+ markAttempted: () => {
367
+ // Persist the mark first and read what the entry carries from that same
368
+ // write: from here on it never changes, so the text sent now is the
369
+ // text every retry sends.
370
+ let count: number | null = null;
371
+ update((notice) => {
372
+ count = notice.folded?.count ?? 1;
373
+ return { ...notice, attempted: true };
374
+ });
375
+ return count;
376
+ },
377
+ acknowledge: () => update(() => null),
378
+ };
379
+ }
380
+
381
+ export function writeMachineLaunchRecord(controlDir: string, record: MachineLaunchRecord): void {
382
+ const path = join(controlDir, MACHINE_LAUNCH_RECORD);
383
+ const temporary = `${path}.${process.pid}.tmp`;
384
+ writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, ...record })}\n`, { mode: 0o600 });
385
+ renameSync(temporary, path);
386
+ }
387
+
388
+ /** Best-effort: never blocks resuming a machine that exists. */
389
+ function noteMachineSeen(controlDir: string, taskId: string, instanceId: string | undefined): void {
390
+ try {
391
+ const record = readMachineLaunchRecord(controlDir);
392
+ if (!record.launched || (instanceId !== undefined && record.instanceId !== instanceId)) {
393
+ writeMachineLaunchRecord(controlDir, {
394
+ ...record,
395
+ launched: true,
396
+ ...(instanceId !== undefined ? { instanceId } : {}),
397
+ });
398
+ }
399
+ } catch (error) {
400
+ console.warn(
401
+ `[machine] task ${taskId}: could not update its launch record: ${error instanceof Error ? error.message : String(error)}`,
402
+ );
403
+ }
404
+ }
405
+
124
406
  export function machineTaskEnvironmentLocator(
125
407
  value: MachineTaskEnvironmentLocatorValue,
126
408
  ): TaskEnvironmentLocator {
@@ -1050,14 +1332,70 @@ export function createMachineTaskEnvironmentProvider(
1050
1332
  // or a restarted Station sees the same answer: an unconfirmed machine
1051
1333
  // is probed whether it is fresh or reused.
1052
1334
  let payloadValidation = existing.payloadValidation ?? null;
1335
+ const controlDir = deps.taskControlDir(taskId);
1053
1336
  if (existing.state === "absent") {
1054
- const launched = await deps.machines.launch({
1337
+ // Read once for what this start knows of the task's last machine.
1338
+ // Every write below re-reads the record (updateMachineLaunchRecord)
1339
+ // and changes only its own fields: a delivery may acknowledge a
1340
+ // notice while this start awaits a launch, and a snapshot taken
1341
+ // before that await must never be written back (review #4ndq0w).
1342
+ const record = readMachineLaunchRecord(controlDir);
1343
+ let generation = record.generation;
1344
+ const launchSpec = {
1055
1345
  taskId,
1056
1346
  image: input.image,
1057
1347
  cpus: input.cpus,
1058
1348
  memoryMiB: input.memoryMiB,
1059
1349
  authorizedPublicKey: keys.publicKey,
1060
1350
  ...(input.publishSsh ? { publishSsh: true } : {}),
1351
+ launchIntent: fileLaunchIntentStore(deps.taskControlDir(taskId)),
1352
+ };
1353
+ let launched: MachineInfo;
1354
+ try {
1355
+ launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
1356
+ } catch (error) {
1357
+ if (!(error instanceof MachineLaunchTokenSpentError)) throw error;
1358
+ // F6: the backend proved this generation's machine terminated, so
1359
+ // its token can only ever answer with that machine. Persist the
1360
+ // next generation BEFORE launching it: a crash mid-launch retries
1361
+ // with the new token, never the spent one, and never mints twice.
1362
+ generation += 1;
1363
+ const loss: PendingLossNotice = { lostInstanceId: error.instanceId, generation };
1364
+ const nextGeneration = generation;
1365
+ updateMachineLaunchRecord(controlDir, (current) => {
1366
+ // The lost instance is no longer the task's: drop its id, so a
1367
+ // retry after a crash cannot prove the same loss again.
1368
+ const { instanceId: _lost, ...rest } = current;
1369
+ return { ...rest, generation: nextGeneration, launched: false, pendingLossNotices: withLossNotice(current, loss) };
1370
+ });
1371
+ console.warn(
1372
+ `[machine] task ${taskId}: ${error.message}; launching generation ${generation} with a new launch token`,
1373
+ );
1374
+ launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
1375
+ }
1376
+ // Lost only on proof: the token was spent on a terminated instance
1377
+ // (above), or a launch this record knows answered with a different
1378
+ // instance than before.
1379
+ const replacedInstance =
1380
+ record.instanceId !== undefined &&
1381
+ launched.instanceId !== undefined &&
1382
+ launched.instanceId !== record.instanceId
1383
+ ? record.instanceId
1384
+ : null;
1385
+ const launchedGeneration = generation;
1386
+ updateMachineLaunchRecord(controlDir, (current) => {
1387
+ const { instanceId: _previous, ...rest } = current;
1388
+ return {
1389
+ // The current record: the launch intent the launch just wrote,
1390
+ // and the notice queue as deliveries left it.
1391
+ ...rest,
1392
+ generation: launchedGeneration,
1393
+ launched: true,
1394
+ ...(launched.instanceId !== undefined ? { instanceId: launched.instanceId } : {}),
1395
+ ...(replacedInstance !== null
1396
+ ? { pendingLossNotices: withLossNotice(current, { lostInstanceId: replacedInstance, generation: launchedGeneration }) }
1397
+ : {}),
1398
+ };
1061
1399
  });
1062
1400
  if (launched.id !== machineId) {
1063
1401
  // The backend named the machine something other than what the
@@ -1069,8 +1407,11 @@ export function createMachineTaskEnvironmentProvider(
1069
1407
  );
1070
1408
  }
1071
1409
  payloadValidation = launched.payloadValidation ?? null;
1072
- } else if (existing.state === "stopped") {
1073
- await deps.machines.start(machineId);
1410
+ } else {
1411
+ // A machine seen for this task (one a pre-F6 Station launched has no
1412
+ // record yet): once it is gone, a later Resume must say so.
1413
+ noteMachineSeen(controlDir, taskId, existing.instanceId);
1414
+ if (existing.state === "stopped") await deps.machines.start(machineId);
1074
1415
  }
1075
1416
  // running/pending: fall through to the ssh-readiness proof below.
1076
1417
 
@@ -1131,7 +1472,23 @@ export function createMachineTaskEnvironmentProvider(
1131
1472
  );
1132
1473
  }
1133
1474
  }
1134
- return { handle, result: handle.descriptor, reused };
1475
+ // Reported by every start until one succeeds, a retry that found the
1476
+ // replacement already running included.
1477
+ let pending: PendingLossNotice[] = [];
1478
+ try {
1479
+ pending = readMachineLaunchRecord(controlDir).pendingLossNotices ?? [];
1480
+ } catch {
1481
+ // An unreadable record was refused above for a launch; for a reused
1482
+ // machine it only costs the notice.
1483
+ }
1484
+ return {
1485
+ handle,
1486
+ result: handle.descriptor,
1487
+ reused,
1488
+ ...(pending.length > 0
1489
+ ? { replacedLostEnvironment: true, lossNotices: pending.map((notice) => machineLossNotice(controlDir, notice)) }
1490
+ : {}),
1491
+ };
1135
1492
  },
1136
1493
 
1137
1494
  async reconstruct(
@@ -378,6 +378,34 @@ export interface TaskEnvironmentProvisioned<TResult, TTeardownResult = void> {
378
378
  * stopped machine, whose disk holds the task's work — rather than creating
379
379
  * it. A failed start stops such an environment; it never destroys it. */
380
380
  reused?: boolean;
381
+ /** F6: the task had an environment before, it is gone (a terminated
382
+ * machine and its disk), and this provision created a fresh one. Work
383
+ * that lived only on the old one is lost; the start says so. */
384
+ replacedLostEnvironment?: boolean;
385
+ /** The proof behind replacedLostEnvironment, until the user is told. */
386
+ /** One per lost environment not yet told, oldest first (review #4ndq0w). */
387
+ lossNotices?: EnvironmentLossNotice[];
388
+ }
389
+
390
+ /**
391
+ * A lost environment the user has not yet been told about (F6, reviews
392
+ * #tgxadc, #2cp6r4). The Station delivers a task's notices one at a time,
393
+ * oldest first: markAttempted (persisted, never undone) before the first
394
+ * publish, the same id and text on every retry, and acknowledge only once the
395
+ * cloud has the note. The next notice is attempted only after that.
396
+ */
397
+ export interface EnvironmentLossNotice {
398
+ readonly id: string;
399
+ /** Handed to a publisher before: resend exactly this. */
400
+ readonly attempted: boolean;
401
+ /** How many lost environments this notice speaks for: 1, or more for a
402
+ * summary folded from an overflowing queue (review #d0p42f). */
403
+ readonly lostEnvironments?: number;
404
+ /** Before publishing: mark the notice attempted (persisted; from then on it
405
+ * is immutable) and return how many lost environments it carries, or
406
+ * null when it is already gone. */
407
+ markAttempted(): number | null;
408
+ acknowledge(): void;
381
409
  }
382
410
 
383
411
  export interface TaskEnvironmentProvider<