@cnc-tools/storm 0.6.0 → 0.7.0

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 (80) hide show
  1. package/dist/build-info.js +1 -1
  2. package/dist/commands/exec/command.d.ts +26 -0
  3. package/dist/commands/exec/live-view.js +29 -13
  4. package/dist/commands/exec/metadata.d.ts +4 -1
  5. package/dist/commands/exec/outcomes.d.ts +50 -0
  6. package/dist/commands/exec/outcomes.js +9 -0
  7. package/dist/commands/exec/progress.d.ts +14 -2
  8. package/dist/commands/exec/progress.js +54 -9
  9. package/dist/commands/exec/run-command.d.ts +8 -2
  10. package/dist/commands/exec/run-command.js +41 -8
  11. package/dist/commands/exec/run-metadata.d.ts +5 -2
  12. package/dist/commands/exec/run-metadata.js +5 -2
  13. package/dist/commands/exec/run-record.d.ts +83 -4
  14. package/dist/commands/exec/run-record.js +49 -1
  15. package/dist/commands/exec/view.js +36 -4
  16. package/dist/commands/runs/facts.d.ts +25 -0
  17. package/dist/commands/runs/facts.js +36 -3
  18. package/dist/commands/runs/list/command.d.ts +25 -0
  19. package/dist/commands/runs/list/outcomes.d.ts +25 -0
  20. package/dist/commands/runs/show/command.d.ts +25 -0
  21. package/dist/commands/runs/show/metadata.js +1 -1
  22. package/dist/commands/runs/show/outcomes.d.ts +25 -0
  23. package/dist/commands/runs/show/outcomes.js +30 -1
  24. package/dist/commands/vitest/command.d.ts +26 -0
  25. package/dist/commands/vitest/metadata.d.ts +4 -1
  26. package/dist/commands/vitest/outcomes.d.ts +25 -0
  27. package/dist/core/events.d.ts +9 -7
  28. package/dist/core/run-state.d.ts +30 -6
  29. package/dist/core/run-state.js +19 -4
  30. package/dist/core/run.d.ts +17 -4
  31. package/dist/core/run.js +61 -25
  32. package/dist/runner/events.d.ts +64 -1
  33. package/dist/runner/gateways.d.ts +17 -6
  34. package/dist/runner/index.d.ts +5 -4
  35. package/dist/runner/index.js +4 -3
  36. package/dist/runner/live/snapshot-records.js +18 -4
  37. package/dist/runner/prepare.d.ts +23 -4
  38. package/dist/runner/prepare.js +13 -3
  39. package/dist/runner/ready.d.ts +7 -3
  40. package/dist/runner/ready.js +11 -5
  41. package/dist/runner/scope.d.ts +17 -1
  42. package/dist/runner/scope.js +4 -0
  43. package/dist/runner/snapshot-build.d.ts +3 -1
  44. package/dist/runner/snapshot-build.js +12 -2
  45. package/dist/runner/snapshot-cache.d.ts +46 -8
  46. package/dist/runner/snapshot-cache.js +60 -11
  47. package/dist/runner/snapshot-key.d.ts +12 -1
  48. package/dist/runner/snapshot-key.js +17 -1
  49. package/dist/runner/snapshot-save.d.ts +53 -0
  50. package/dist/runner/snapshot-save.js +148 -0
  51. package/dist/story/align.d.ts +1 -1
  52. package/dist/story/align.js +1 -1
  53. package/dist/story/definition.d.ts +22 -15
  54. package/dist/story/definition.js +2 -2
  55. package/dist/story/errors.js +1 -1
  56. package/dist/story/gateways.d.ts +45 -25
  57. package/dist/story/gateways.js +2 -2
  58. package/dist/story/host.d.ts +11 -8
  59. package/dist/story/host.js +37 -37
  60. package/dist/story/index.d.ts +1 -1
  61. package/dist/story/index.js +4 -4
  62. package/dist/story/json.d.ts +1 -1
  63. package/dist/story/json.js +2 -2
  64. package/dist/story/live/recording-gateway.d.ts +2 -0
  65. package/dist/story/live/{artifact-gateway.js → recording-gateway.js} +33 -12
  66. package/dist/story/mode.d.ts +2 -2
  67. package/dist/story/mode.js +1 -1
  68. package/dist/story/orphans.d.ts +23 -5
  69. package/dist/story/orphans.js +44 -8
  70. package/dist/story/recording.d.ts +62 -0
  71. package/dist/story/{artifact.js → recording.js} +31 -27
  72. package/dist/story/report.d.ts +21 -9
  73. package/dist/story/report.js +37 -25
  74. package/dist/story/settle.d.ts +23 -21
  75. package/dist/story/settle.js +17 -16
  76. package/dist/story/{run.d.ts → start.d.ts} +18 -17
  77. package/dist/story/{run.js → start.js} +66 -43
  78. package/package.json +1 -1
  79. package/dist/story/artifact.d.ts +0 -60
  80. package/dist/story/live/artifact-gateway.d.ts +0 -2
@@ -1,5 +1,5 @@
1
1
  import type { MintTarget } from "../credential/index.ts";
2
- import type { RunnerEvent, SnapshotCacheNote } from "../runner/index.ts";
2
+ import type { RunnerEvent, RunnerSandboxPlan, SnapshotCacheNote } from "../runner/index.ts";
3
3
  import type { Clock } from "../time/index.ts";
4
4
  import type { TestEvent } from "../sdk/index.ts";
5
5
  import type { AnyResources, ResourceEvent, ResourceFailures, ResourceHoldings, RunLane } from "./resource.ts";
@@ -15,7 +15,8 @@ export type LaneOutcome = "ready" | "failed" | "stopped";
15
15
  * provider order: none when it holds no resource with a lane, and `resources` the resources it holds, by name, in
16
16
  * provider order.
17
17
  * - `runner-prepared`: in a runner run, what the local checks found: the base, a full SHA, and the ref it is HEAD's
18
- * merge-base with; the untracked nested Git repositories the upload leaves out; and what the cache read noticed.
18
+ * merge-base with; the untracked nested Git repositories the upload leaves out; what the cache read noticed; and
19
+ * whether `--save-snapshot` saves nothing because HEAD is detached (`saveSkipped`).
19
20
  * - `minting`, `minted` and `requesting-token`: a credential's events (`CredentialEvent`): the run's one mint, which a
20
21
  * runner run makes for its runner sandbox and a resource makes in a local run, and a GitHub Actions OIDC token
21
22
  * request.
@@ -29,9 +30,10 @@ export type LaneOutcome = "ready" | "failed" | "stopped";
29
30
  * - `command-started`: the command started, or in a runner run is about to start in the runner sandbox.
30
31
  * - `command-ended`: the command ended as `outcome` after `ms`; `command` is its executable's name. A command the
31
32
  * run killed reports the runner's `command-stopped` instead.
32
- * - `cleanup-started`: the run is cleaning up: in a runner run (`runner`) stopping and deleting the runner's
33
- * sandboxes, but for the runner sandbox it keeps running `keepSandboxMs` when that is above 0 (always 0 in a local
34
- * run), then releasing its resources, holding what `holdings` says of each.
33
+ * - `cleanup-started`: the run is cleaning up: in a runner run (`runnerSandbox`, null in a local run) stopping and
34
+ * deleting the runner's sandboxes, but for the runner sandbox, which it keeps running `ms` when that is above 0
35
+ * (`keep`) or saves as a branch snapshot of `branch` while it releases the resources (`save`, only when the save
36
+ * runs); and releasing its resources, holding what `holdings` says of each.
35
37
  * - `cleanup-finished`: it is done; `resourceFailures` counts, for each resource the run held, what releasing it
36
38
  * couldn't do, and in a runner run `notStopped` and `notDeleted` sandboxes couldn't be stopped or deleted.
37
39
  * - `test`: in a runner run, a test event the command appended to the run payload's `testEvents` file, as it
@@ -53,6 +55,7 @@ export type RunEvent<K> = {
53
55
  readonly baseRef: string;
54
56
  readonly nestedRepositories: readonly string[];
55
57
  readonly notes: readonly SnapshotCacheNote[];
58
+ readonly saveSkipped: boolean;
56
59
  } | CredentialEvent | {
57
60
  readonly kind: "lanes-started";
58
61
  } | {
@@ -72,8 +75,7 @@ export type RunEvent<K> = {
72
75
  readonly ms: number;
73
76
  } | {
74
77
  readonly kind: "cleanup-started";
75
- readonly runner: boolean;
76
- readonly keepSandboxMs: number;
78
+ readonly runnerSandbox: RunnerSandboxPlan | null;
77
79
  readonly holdings: ResourceHoldings<K>;
78
80
  } | {
79
81
  readonly kind: "cleanup-finished";
@@ -1,5 +1,5 @@
1
1
  import type { MintTarget } from "../credential/index.ts";
2
- import type { KeptSandbox } from "../runner/index.ts";
2
+ import type { KeptSandbox, RunnerSandboxPlan } from "../runner/index.ts";
3
3
  import type { TimedRunEvent } from "./events.ts";
4
4
  import type { LaneStates, ResourceLanes } from "./lane.ts";
5
5
  import type { ResourceHoldings, RunLane } from "./resource.ts";
@@ -30,15 +30,35 @@ export interface RunnerStepState {
30
30
  /** The last line the step printed, while it runs. */
31
31
  readonly latest: string | undefined;
32
32
  }
33
- /** What the runner did with its runner snapshot: reused or built one, of the base it holds, or is building one. */
33
+ /**
34
+ * What the runner did with its runner snapshot: reused or built one, of the base it holds, or is building one. A reused
35
+ * branch snapshot names the branch and HEAD commit of the run that saved it; each is null for a base snapshot.
36
+ */
34
37
  export type RunnerSnapshotState = {
35
38
  readonly kind: "reused" | "built";
36
39
  readonly id: string;
37
40
  readonly base: string;
41
+ readonly branch: string | null;
42
+ readonly head: string | null;
38
43
  } | {
39
44
  readonly kind: "building";
40
45
  readonly summary: string;
41
46
  };
47
+ /**
48
+ * Saving the runner sandbox as a branch snapshot of `branch` (`--save-snapshot`): under way, saved as runner snapshot
49
+ * `id` at HEAD commit `head`, or not saved.
50
+ */
51
+ export type BranchSnapshotSaveState = {
52
+ readonly kind: "saving";
53
+ readonly branch: string;
54
+ } | {
55
+ readonly kind: "saved";
56
+ readonly id: string;
57
+ readonly branch: string;
58
+ readonly head: string;
59
+ } | {
60
+ readonly kind: "not-saved";
61
+ };
42
62
  /** One vitest worker, as its test events show it. */
43
63
  export interface TestWorkerState {
44
64
  readonly worker: number;
@@ -73,6 +93,8 @@ export interface RunnerState extends Span {
73
93
  readonly activity: "saving-snapshot" | "waiting-for-snapshot" | undefined;
74
94
  /** The runner sandbox the run kept running once it ended, once closing kept it. */
75
95
  readonly kept: KeptSandbox | undefined;
96
+ /** Saving the runner sandbox as a branch snapshot, once it began. */
97
+ readonly save: BranchSnapshotSaveState | undefined;
76
98
  }
77
99
  /** The command: its argument list and how it ended; `stopped` when the run killed it. */
78
100
  export interface CommandState extends Span {
@@ -81,10 +103,12 @@ export interface CommandState extends Span {
81
103
  }
82
104
  /** The cleanup over the registry's kinds `K`: what it stops and releases, and what it couldn't. */
83
105
  export interface CleanupState<K> extends Span {
84
- /** Whether it stops and deletes the runner's sandboxes. */
85
- readonly runner: boolean;
86
- /** How long it keeps the runner sandbox running, in milliseconds; 0 when it stops and deletes it. */
87
- readonly keepSandboxMs: number;
106
+ /**
107
+ * In a runner run, what it does with the runner sandbox while it stops and deletes the runner's other sandboxes: keeps
108
+ * it running `ms` (`keep`, stopping and deleting it at 0) or saves it as a branch snapshot (`save`); null in a local
109
+ * run.
110
+ */
111
+ readonly runnerSandbox: RunnerSandboxPlan | null;
88
112
  /** What the run held of each resource as cleanup started, which each resource's presentation names. */
89
113
  readonly holdings: ResourceHoldings<K>;
90
114
  /** What releasing the resources the run held couldn't do, summed over them, such as leases not released. */
@@ -71,6 +71,7 @@ function applyEvent(lanes, state, event, at) {
71
71
  uploadBytes: undefined,
72
72
  activity: undefined,
73
73
  kept: undefined,
74
+ save: undefined,
74
75
  },
75
76
  };
76
77
  case "minting":
@@ -125,8 +126,7 @@ function applyEvent(lanes, state, event, at) {
125
126
  status: "running",
126
127
  startedAt: at,
127
128
  endedAt: undefined,
128
- runner: event.runner,
129
- keepSandboxMs: event.keepSandboxMs,
129
+ runnerSandbox: event.runnerSandbox,
130
130
  holdings: event.holdings,
131
131
  resourceFailures: 0,
132
132
  notStopped: 0,
@@ -210,11 +210,16 @@ function runnerEnded(state, outcome, at) {
210
210
  function applyRunnerEvent(state, event, at) {
211
211
  switch (event.kind) {
212
212
  case "snapshot-reused":
213
- return withRunner(withStep(state, "snapshot", () => ({ status: "done", startedAt: at, endedAt: at })), () => ({ snapshot: { kind: "reused", id: event.snapshotId, base: event.base } }));
213
+ return withRunner(withStep(state, "snapshot", () => ({ status: "done", startedAt: at, endedAt: at })), () => ({
214
+ snapshot: { kind: "reused", id: event.snapshotId, base: event.base, branch: event.branch, head: event.head },
215
+ }));
214
216
  case "snapshot-build-started":
215
217
  return withRunner(withStep(state, "snapshot", () => ({ status: "running", startedAt: at })), () => ({ snapshot: { kind: "building", summary: event.summary } }));
216
218
  case "snapshot-built":
217
- return withRunner(withStep(state, "snapshot", () => ({ status: "done", endedAt: at, latest: undefined })), () => ({ snapshot: { kind: "built", id: event.snapshotId, base: event.base }, activity: undefined }));
219
+ return withRunner(withStep(state, "snapshot", () => ({ status: "done", endedAt: at, latest: undefined })), () => ({
220
+ snapshot: { kind: "built", id: event.snapshotId, base: event.base, branch: null, head: null },
221
+ activity: undefined,
222
+ }));
218
223
  case "snapshot-saving":
219
224
  return withRunner(state, () => ({ activity: "saving-snapshot" }));
220
225
  case "runner-sandbox-starting":
@@ -248,11 +253,21 @@ function applyRunnerEvent(state, event, at) {
248
253
  return withRunner(state.cleanup === undefined ? state : { ...state, cleanup: { ...state.cleanup, waiting: true } }, () => ({ activity: "waiting-for-snapshot" }));
249
254
  case "sandbox-kept":
250
255
  return withRunner(state, () => ({ kept: { name: event.name, stopsAt: event.stopsAt } }));
256
+ case "branch-snapshot-saving":
257
+ return withRunner(state, () => ({ save: { kind: "saving", branch: event.branch } }));
258
+ case "branch-snapshot-saved":
259
+ return withRunner(state, () => ({
260
+ save: { kind: "saved", id: event.snapshotId, branch: event.branch, head: event.head },
261
+ }));
262
+ case "branch-snapshot-not-saved":
263
+ return withRunner(state, () => ({ save: { kind: "not-saved" } }));
251
264
  // A step's outcome comes from its lane's end, not from the end of its output.
252
265
  case "output-started":
253
266
  case "output-ended":
254
267
  case "snapshot-entry-not-written":
255
268
  case "command-output-started":
269
+ case "branch-snapshots-dropped":
270
+ case "branch-snapshots-not-dropped":
256
271
  return state;
257
272
  }
258
273
  }
@@ -1,5 +1,5 @@
1
1
  import { type CredentialGateway, type CredentialSourceChoice, type GitHubActionsTokenGateway, type MintFailure, type MintTarget } from "../credential/index.ts";
2
- import { type PreparedRunner, type RunnerContext, type RunnerFailure, type RunnerScopeReport, type RunnerSnapshotCacheFailure, type RunnerSnapshotEntry } from "../runner/index.ts";
2
+ import { type PreparedRunner, type RunnerContext, type RunnerFailure, type RunnerSandboxPlan, type RunnerSave, type RunnerScopeReport, type RunnerSnapshotCacheFailure, type RunnerSnapshotEntry } from "../runner/index.ts";
3
3
  import type { RunProgress } from "./events.ts";
4
4
  import type { CommandGateway } from "./gateways.ts";
5
5
  import type { CoreContext, RunProviders, ResourceCanceledFacts, ResourceCleanup, ResourceFacts, ResourceRefusal, ResourceRequests, ResourceUnprepared } from "./resource.ts";
@@ -23,8 +23,12 @@ export interface RunRunnerRequest {
23
23
  readonly target: MintTarget;
24
24
  /** The local user name, for each sandbox's `user` tag. */
25
25
  readonly user: string;
26
- /** How long the runner sandbox keeps running once the run ends, in milliseconds; 0 stops and deletes it. */
27
- readonly keepSandboxMs: number;
26
+ /**
27
+ * What the run does with the runner sandbox once it ends, decided before it starts: keep it running for the keep time
28
+ * (0 stops and deletes it), or, under `--save-snapshot` on a branch, save it as a branch snapshot once the command
29
+ * ends on its own (`saveBranchSnapshot`), never keeping it.
30
+ */
31
+ readonly sandbox: RunnerSandboxPlan;
28
32
  }
29
33
  /** What every run was asked to do, local or in a runner run. */
30
34
  interface RunRequestBase {
@@ -88,13 +92,21 @@ export type RunRunnerFailure = RunnerFailure | {
88
92
  };
89
93
  /** What a runner run got from the runner sandbox, once the command ran in it. */
90
94
  export interface RanRunner {
95
+ /** The runner snapshot it started from, and its base. */
91
96
  readonly snapshotId: string;
92
97
  readonly base: string;
98
+ /** For a branch snapshot it started from, the branch and HEAD commit of the run that saved it; null otherwise. */
99
+ readonly snapshotBranch: string | null;
100
+ readonly snapshotHead: string | null;
93
101
  /** Whether this run built the runner snapshot. */
94
102
  readonly built: boolean;
95
103
  readonly vcpus: number;
96
104
  readonly region: string;
97
105
  readonly runtime: string;
106
+ /** How long the build step took, in milliseconds. */
107
+ readonly buildMs: number;
108
+ /** How saving the runner sandbox as a branch snapshot ended; null without `--save-snapshot`. */
109
+ readonly save: RunnerSave | null;
98
110
  }
99
111
  /**
100
112
  * How a run ended, over the registry's kinds `K`.
@@ -181,7 +193,8 @@ export type RunStopped<K> = ResourceRefusal<K> | {
181
193
  *
182
194
  * Release happens in `finally`, however the run ended, a throw included: once the command has stopped and, in a
183
195
  * runner run, the runner's sandboxes are closed, each resource is released in reverse order, even when the
184
- * `cleanup-started` event can't be reported.
196
+ * `cleanup-started` event can't be reported. A runner run that saves the runner sandbox as a branch snapshot releases
197
+ * them while the save runs, since the command is done with them.
185
198
  */
186
199
  export declare function executeRun<K, C extends RunContext>(providers: RunProviders<K, C>, context: C, request: RunRequest<K>, control: RunControl, progress: RunProgress<K>): Promise<RunOutcome<K>>;
187
200
  export {};
package/dist/core/run.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { posix } from "node:path";
2
2
  import { credentialSourceFor, mintSource, } from "../credential/index.js";
3
- import { readyRunner, runnerSandboxScope, REMOTE_TEST_EVENTS_PATH, lineSplitter, runRemote, } from "../runner/index.js";
3
+ import { readyRunner, runnerSandboxScope, REMOTE_TEST_EVENTS_PATH, keptMs, lineSplitter, runRemote, saveBranchSnapshot, } from "../runner/index.js";
4
4
  import { parseTestEvent } from "../sdk/index.js";
5
5
  import { mintReported, mintSourceReported } from "./mint.js";
6
6
  import { colorEnvironment, commandEnvironment, runPayload } from "./payload.js";
@@ -17,7 +17,8 @@ import { acquireResources, canceledHolding, heldLanes, heldResources, prepareRes
17
17
  *
18
18
  * Release happens in `finally`, however the run ended, a throw included: once the command has stopped and, in a
19
19
  * runner run, the runner's sandboxes are closed, each resource is released in reverse order, even when the
20
- * `cleanup-started` event can't be reported.
20
+ * `cleanup-started` event can't be reported. A runner run that saves the runner sandbox as a branch snapshot releases
21
+ * them while the save runs, since the command is done with them.
21
22
  */
22
23
  export async function executeRun(providers, context, request, control, progress) {
23
24
  const slots = resourceSlots(providers, context, request.resources);
@@ -37,6 +38,7 @@ export async function executeRun(providers, context, request, control, progress)
37
38
  baseRef: prepared.baseRef,
38
39
  nestedRepositories: prepared.upload.nestedRepositories,
39
40
  notes: prepared.notes,
41
+ saveSkipped: prepared.save?.kind === "skipped",
40
42
  });
41
43
  }
42
44
  const unprepared = await prepareResources(slots, progress);
@@ -44,35 +46,38 @@ export async function executeRun(providers, context, request, control, progress)
44
46
  return unprepared;
45
47
  // Each slot keeps what its resource holds, pushed as it is acquired: the run releases all of it however it ends.
46
48
  let cleanupStarted = false;
47
- // Said once, before the runner's sandboxes are stopped in a runner run, else before the resources are released.
48
- const startCleanup = async () => {
49
+ // Said once, before the runner's sandboxes are stopped in a runner run, else before the resources are released, with
50
+ // what cleanup does with the runner sandbox (`runnerSandbox`). The first call's says it: a runner run that saves a
51
+ // branch snapshot calls `release` with its `save` before anything else starts cleanup.
52
+ const startCleanup = async (runnerSandbox) => {
49
53
  if (cleanupStarted)
50
54
  return;
51
55
  cleanupStarted = true;
52
- await progress.emit({
53
- kind: "cleanup-started",
54
- runner: request.runner !== undefined,
55
- keepSandboxMs: request.runner?.keepSandboxMs ?? 0,
56
- holdings: resourceHoldings(slots),
57
- });
56
+ await progress.emit({ kind: "cleanup-started", runnerSandbox, holdings: resourceHoldings(slots) });
58
57
  };
58
+ let resourceCleanup = {};
59
+ let releasing;
60
+ // Once: reporting cleanup's start can fail, and releasing what the run holds must not depend on it.
61
+ const release = (runnerSandbox) => (releasing ??= (async () => {
62
+ try {
63
+ await startCleanup(runnerSandbox);
64
+ }
65
+ finally {
66
+ resourceCleanup = await releaseResources(slots, progress);
67
+ }
68
+ })());
69
+ // What cleanup does with the runner sandbox when no save runs: the plan's keep time, 0 for a save that didn't run.
70
+ const unsaved = request.runner === undefined ? null : { kind: "keep", ms: keptMs(request.runner.sandbox) };
59
71
  let ended;
60
72
  let runnerCleanup = null;
61
- let resourceCleanup = {};
62
73
  try {
63
74
  ({ ended, runnerCleanup } =
64
75
  request.runner === undefined
65
76
  ? { ended: await provisionAndRun(context, request, slots, control, progress), runnerCleanup: null }
66
- : await provisionAndRunRemote(context, request, slots, control, progress, startCleanup));
77
+ : await provisionAndRunRemote(context, request, slots, control, progress, { startCleanup, release }));
67
78
  }
68
79
  finally {
69
- // Reporting cleanup's start can fail; releasing what the run holds must not depend on it.
70
- try {
71
- await startCleanup();
72
- }
73
- finally {
74
- resourceCleanup = await releaseResources(slots, progress);
75
- }
80
+ await release(unsaved);
76
81
  }
77
82
  await progress.emit({
78
83
  kind: "cleanup-finished",
@@ -179,10 +184,16 @@ function runnerStopped(outcome) {
179
184
  * for a create in flight and a snapshot still saving run while readying winds down; the close the run awaits later
180
185
  * gets that close's report, or its error. A runner run always mints, whatever resources it holds, so its request names
181
186
  * no credential source: the command layer refuses `--credential github-actions` with it.
187
+ *
188
+ * The run's plan (`request.runner.sandbox`) gives the scope its keep time, which is 0 for a `save` plan: such a run
189
+ * never keeps its runner sandbox, however it ends. Under a `save` plan, once the command ended on its own and no signal
190
+ * arrived, it saves the runner sandbox as a branch snapshot (`saveBranchSnapshot`) while the resources are released,
191
+ * and closes the scope once the save is done, even when releasing them threw.
182
192
  */
183
- async function provisionAndRunRemote(context, request, slots, control, progress, startCleanup) {
193
+ async function provisionAndRunRemote(context, request, slots, control, progress, cleanup) {
184
194
  const runnerProgress = { emit: (event) => progress.emit({ kind: "runner", event }) };
185
- const keepMs = request.runner.keepSandboxMs;
195
+ const plan = request.runner.sandbox;
196
+ const keepMs = keptMs(plan);
186
197
  const scope = runnerSandboxScope(context, runnerProgress, { keepMs });
187
198
  let commandRunning = false;
188
199
  // Said before the close starts, so the stopping line comes before any line the close's waits print.
@@ -202,9 +213,29 @@ async function provisionAndRunRemote(context, request, slots, control, progress,
202
213
  commandRunning = true;
203
214
  },
204
215
  }, progress, runnerProgress);
205
- await startCleanup();
216
+ commandRunning = false;
217
+ const unsaved = { kind: "keep", ms: keepMs };
218
+ if (ended.kind !== "command-ended") {
219
+ await cleanup.startCleanup(unsaved);
220
+ return { ended, runnerCleanup: { ...(await scope.close()), target: request.runner.target } };
221
+ }
222
+ const { ready, ...rest } = ended;
223
+ const { prepared } = request.runner;
224
+ let save = prepared.save?.kind === "skipped" ? prepared.save : null;
225
+ const action = plan.kind === "save" && !control.signal.aborted ? plan : unsaved;
226
+ if (action.kind === "save") {
227
+ const saving = saveBranchSnapshot(context, { ready, branch: action.branch, head: prepared.head.commit }, { scope, signal: control.signal }, runnerProgress);
228
+ // The save settles before the scope closes, even when releasing the resources threw.
229
+ try {
230
+ await cleanup.release(action);
231
+ }
232
+ finally {
233
+ save = await saving;
234
+ }
235
+ }
236
+ await cleanup.startCleanup(action);
206
237
  const runnerCleanup = { ...(await scope.close()), target: request.runner.target };
207
- return { ended, runnerCleanup };
238
+ return { ended: { ...rest, runner: { ...rest.runner, save } }, runnerCleanup };
208
239
  }
209
240
  finally {
210
241
  control.signal.removeEventListener("abort", stop);
@@ -290,13 +321,18 @@ async function mintAndRunRemote(context, request, slots, control, progress, runn
290
321
  resources: resourcesFacts(slots),
291
322
  command,
292
323
  runner: {
293
- snapshotId: ready.snapshotId,
294
- base: ready.base,
324
+ snapshotId: ready.startedFrom.snapshotId,
325
+ base: ready.startedFrom.base,
326
+ snapshotBranch: ready.startedFrom.branch ?? null,
327
+ snapshotHead: ready.startedFrom.head ?? null,
295
328
  built: ready.built,
296
329
  vcpus: ready.vcpus,
297
330
  region: ready.region,
298
331
  runtime: ready.runtime,
332
+ buildMs: ready.buildMs,
333
+ save: null,
299
334
  },
335
+ ready,
300
336
  };
301
337
  }
302
338
  /**
@@ -32,7 +32,8 @@ export interface NotKeptSandbox {
32
32
  /**
33
33
  * What the runner reports, in order.
34
34
  *
35
- * - `snapshot-reused`: the run starts from cached runner snapshot `snapshotId`, of `base`.
35
+ * - `snapshot-reused`: the run starts from cached runner snapshot `snapshotId`, of `base`; for a branch snapshot,
36
+ * saved by a run on `branch` at HEAD commit `head`, each null for a base snapshot.
36
37
  * - `snapshot-build-started`: the run builds a runner snapshot of `base`, because no cached one qualified or
37
38
  * `--rebuild-snapshot` asked; `summary` says what the build does.
38
39
  * - `runner-sandbox-starting`: the runner sandbox is starting from runner snapshot `snapshotId`.
@@ -52,11 +53,19 @@ export interface NotKeptSandbox {
52
53
  * and releasing the run's resources.
53
54
  * - `waiting-for-snapshot`: closing waits up to `settleMs` for a runner snapshot still saving.
54
55
  * - `sandbox-kept`: closing kept runner sandbox `name` running until `stopsAt`, an ISO time.
56
+ * - `branch-snapshot-saving`: the run saves the runner sandbox as a branch snapshot of `branch`, once the command
57
+ * ended (`--save-snapshot`).
58
+ * - `branch-snapshot-saved`: it did, as runner snapshot `snapshotId` of `branch` at HEAD commit `head`, in `ms`.
59
+ * - `branch-snapshot-not-saved`: it didn't, and `save` says why.
60
+ * - `branch-snapshots-dropped`: `--rebuild-snapshot` removed `branch`'s branch snapshot entries from the cache.
61
+ * - `branch-snapshots-not-dropped`: it couldn't list the cache or remove one of them.
55
62
  */
56
63
  export type RunnerEvent = {
57
64
  readonly kind: "snapshot-reused";
58
65
  readonly snapshotId: string;
59
66
  readonly base: string;
67
+ readonly branch: string | null;
68
+ readonly head: string | null;
60
69
  } | {
61
70
  readonly kind: "snapshot-build-started";
62
71
  readonly base: string;
@@ -130,6 +139,29 @@ export type RunnerEvent = {
130
139
  readonly kind: "sandbox-kept";
131
140
  readonly name: string;
132
141
  readonly stopsAt: string;
142
+ } | {
143
+ readonly kind: "branch-snapshot-saving";
144
+ readonly branch: string;
145
+ } | {
146
+ readonly kind: "branch-snapshot-saved";
147
+ readonly snapshotId: string;
148
+ readonly branch: string;
149
+ readonly head: string;
150
+ readonly ms: number;
151
+ readonly sizeBytes: number;
152
+ } | {
153
+ readonly kind: "branch-snapshot-not-saved";
154
+ readonly save: Exclude<RunnerSave, {
155
+ readonly kind: "saved" | "skipped";
156
+ }>;
157
+ } | {
158
+ readonly kind: "branch-snapshots-dropped";
159
+ readonly branch: string;
160
+ readonly snapshotIds: readonly string[];
161
+ } | {
162
+ readonly kind: "branch-snapshots-not-dropped";
163
+ readonly branch: string;
164
+ readonly failure: RunnerSnapshotCacheFailure;
133
165
  };
134
166
  /** Hears the runner's events as they happen. */
135
167
  export interface RunnerProgress {
@@ -159,6 +191,37 @@ export type RunnerFailure = {
159
191
  readonly kind: "checkout-failed";
160
192
  readonly failure: CheckoutFailure;
161
193
  };
194
+ /**
195
+ * How saving the runner sandbox as a branch snapshot ended (`--save-snapshot`).
196
+ *
197
+ * - `saved`: it is runner snapshot `snapshotId` of `base`, for `branch` at HEAD commit `head`, saved in `ms` from the
198
+ * save's start; `entryWritten` says whether the cache recorded it.
199
+ * - `skipped`: HEAD was detached as the run started, so there is no branch to save it for (`prepareRunner`); the run
200
+ * keeps its runner sandbox as without the flag.
201
+ * - `failed`: the scrub or the save failed with `message`.
202
+ * - `stopped`: a signal stopped it before it saved, or before the cache recorded the snapshot.
203
+ *
204
+ * A run on a branch never keeps its runner sandbox, whether the save ran or how it ended (`RunnerSandboxPlan`).
205
+ */
206
+ export type RunnerSave = {
207
+ readonly kind: "saved";
208
+ readonly snapshotId: string;
209
+ readonly base: string;
210
+ readonly branch: string;
211
+ readonly head: string;
212
+ readonly ms: number;
213
+ readonly sizeBytes: number;
214
+ readonly entryWritten: boolean;
215
+ } | {
216
+ readonly kind: "skipped";
217
+ readonly reason: "detached-head";
218
+ } | {
219
+ readonly kind: "failed";
220
+ readonly step: "scrub" | "save-snapshot";
221
+ readonly message: string;
222
+ } | {
223
+ readonly kind: "stopped";
224
+ };
162
225
  /** How one stage of readying the runner ended: its value, a failure, or a stop because the run was aborted. */
163
226
  export type RunnerStage<T> = {
164
227
  readonly kind: "ok";
@@ -122,7 +122,8 @@ export interface CheckoutGateway {
122
122
  }
123
123
  /**
124
124
  * One runner snapshot the cache records: who it belongs to, what it was built from, and when it expires. Times
125
- * are ISO strings.
125
+ * are ISO strings. An entry with `branch` and `head` records a branch snapshot, saved from a run on that branch; one
126
+ * without them records a base snapshot, built from its base. An entry has both or neither.
126
127
  */
127
128
  export interface RunnerSnapshotEntry {
128
129
  readonly teamId: string;
@@ -132,8 +133,17 @@ export interface RunnerSnapshotEntry {
132
133
  readonly recipeName: string;
133
134
  /** The snapshot key at `base` (`snapshotKey`). */
134
135
  readonly snapshotKey: string;
135
- /** The base commit's full SHA. */
136
+ /** The base commit's full SHA, whose tracked files the snapshot's repository commits first, in either kind. */
136
137
  readonly base: string;
138
+ /** For a branch snapshot, the local branch of the run that saved it. */
139
+ readonly branch?: string;
140
+ /** For a branch snapshot, the full SHA of the HEAD commit of the run that saved it. */
141
+ readonly head?: string;
142
+ /**
143
+ * For a branch snapshot, the root of the checkout the run that saved it ran from. Only a run from that checkout
144
+ * starts from it, so a branch of the same name in another checkout never inherits what this run left.
145
+ */
146
+ readonly repoRoot?: string;
137
147
  readonly snapshotId: string;
138
148
  readonly createdAt: string;
139
149
  readonly expiresAt: string;
@@ -170,8 +180,9 @@ export type RunnerSnapshotCacheOperation = {
170
180
  };
171
181
  /**
172
182
  * The per-machine runner snapshot cache: one record per runner snapshot, keyed by the entry's identity (team,
173
- * project, region, runtime, recipe name, snapshot key and base). Every method returns its expected failures and
174
- * never rejects. Which entries a run may use, and when one has expired, is the caller's.
183
+ * project, region, runtime, recipe name, snapshot key, base and, for a branch snapshot, branch and checkout root).
184
+ * Every method returns its expected failures and never rejects. Which entries a run may use, and when one has
185
+ * expired, is the caller's.
175
186
  */
176
187
  export interface RunnerSnapshotCacheGateway {
177
188
  /** Every readable entry, and the files it couldn't read. A cache never written is empty. */
@@ -260,7 +271,7 @@ export interface StagedFile {
260
271
  readonly name: string;
261
272
  readonly content: Uint8Array;
262
273
  }
263
- /** A runner snapshot a build sandbox was saved as. */
274
+ /** A runner snapshot a build sandbox or a runner sandbox was saved as. */
264
275
  export interface SavedSnapshot {
265
276
  readonly snapshotId: string;
266
277
  /** When the Sandbox API says it expires, as an ISO string, when it says. */
@@ -319,7 +330,7 @@ export interface RunnerSandboxGateway {
319
330
  readonly path: string;
320
331
  readonly fromLine: number;
321
332
  }, onOutput: (chunk: RemoteOutputChunk) => void, signal?: AbortSignal): Promise<RunnerSandboxOperation>;
322
- /** Saves a build sandbox as a runner snapshot that expires after `expirationMs`; that stops the sandbox. */
333
+ /** Saves a build or runner sandbox as a runner snapshot that expires after `expirationMs`; that stops the sandbox. */
323
334
  saveSnapshot(sandbox: RunnerSandbox, request: {
324
335
  readonly expirationMs: number;
325
336
  }): Promise<RunnerSandboxResult<SavedSnapshot>>;
@@ -1,6 +1,6 @@
1
1
  export { type BaseResolution, type RefusedBaseRef, resolveBase } from "./base.ts";
2
2
  export type { RunnerContext } from "./context.ts";
3
- export { type KeptSandbox, type NotDeletedSandbox, type NotKeptSandbox, type NotStoppedSandbox, type RunnerEvent, type RunnerFailure, type RunnerOutputSection, type RunnerProgress, type RunnerSandboxCall, type RunnerStage, type RunnerStepPhase, } from "./events.ts";
3
+ export { type KeptSandbox, type NotDeletedSandbox, type NotKeptSandbox, type NotStoppedSandbox, type RunnerEvent, type RunnerFailure, type RunnerOutputSection, type RunnerProgress, type RunnerSandboxCall, type RunnerSave, type RunnerStage, type RunnerStepPhase, } from "./events.ts";
4
4
  export type { BaseArchive, BaseCandidate, CheckoutFailure, CheckoutHead, CheckoutGateway, CheckoutResult, CheckoutUpload, FileAtCommit, RemoteExit, RemoteOutputChunk, RunnerKeepFailure, RunnerSandbox, RunnerSandboxFailure, RunnerSandboxGateway, RunnerSandboxOperation, RunnerSandboxPlacement, RunnerSandboxResult, RunnerSandboxRole, RunnerSnapshotCacheFailure, RunnerSnapshotCacheGateway, RunnerSnapshotCacheOperation, RunnerSnapshotCacheResult, RunnerSnapshotEntry, RunnerSnapshotListing, RunnerStartFailure, RunnerTerminal, SandboxAccess, SavedSnapshot, StagedFile, UnreadableSnapshotEntry, } from "./gateways.ts";
5
5
  export { liveCheckoutGateway } from "./live/checkout-gateway.ts";
6
6
  export { liveRunnerSandboxGateway } from "./live/sandbox-gateway.ts";
@@ -12,8 +12,9 @@ export { type PreparedRunner, prepareRunner, type PrepareRunnerOutcome, type Pre
12
12
  export { APPLY_LABEL, type ReadyRunner, readyRunner, type ReadyRunnerOutcome, type ReadyRunnerRequest, } from "./ready.ts";
13
13
  export { type CheckedRecipe, checkRecipe, type RecipeCheck, type RecipeProblem, resolveSteps, resolveVcpus, type RunnerRecipe, type RunnerResources, type RunnerStep, type RunnerStepContext, type RunnerSteps, } from "./recipe.ts";
14
14
  export { REMOTE_TEST_EVENTS_PATH, type RemoteCommandOutcome, remoteCommand, remoteEnvironment, type RemoteTestEvents, runRemote, } from "./remote-command.ts";
15
- export { CREATE_SETTLE_MS, type RunnerSandboxScope, runnerSandboxScope, type RunnerScopeReport, SNAPSHOT_SETTLE_MS, } from "./scope.ts";
15
+ export { CREATE_SETTLE_MS, keptMs, type RunnerSandboxPlan, type RunnerSandboxScope, runnerSandboxScope, type RunnerScopeReport, SNAPSHOT_SETTLE_MS, } from "./scope.ts";
16
16
  export { BASE_INDEX_LABEL, buildSnapshot, type BuildSnapshotRequest, type BuiltSnapshot } from "./snapshot-build.ts";
17
- export { findSnapshotCandidates, pickSnapshot, RUNNER_SNAPSHOTS_SUBPATH, type RunnerSnapshotCandidate, SNAPSHOT_EXPIRATION_MS, type SnapshotCacheContext, type SnapshotCacheNote, snapshotEntryFileName, snapshotEntryIdentity, } from "./snapshot-cache.ts";
18
- export { applyScript, baseIndexScript, snapshotKey, type SnapshotStepsAt, snapshotStepsAt } from "./snapshot-key.ts";
17
+ export { dropBranchSnapshots, type DroppedBranchSnapshots, findSnapshotCandidates, isBranchEntry, pickSnapshot, RUNNER_SNAPSHOTS_SUBPATH, type RunnerSnapshotCandidate, SNAPSHOT_EXPIRATION_MS, type SnapshotCacheContext, type SnapshotCacheNote, snapshotEntryFileName, snapshotEntryIdentity, } from "./snapshot-cache.ts";
18
+ export { applyScript, baseIndexScript, RESET_TO_BASE, snapshotKey, type SnapshotStepsAt, snapshotStepsAt, } from "./snapshot-key.ts";
19
+ export { saveBranchSnapshot, type SaveBranchSnapshotRequest, scrubGitScript, scrubTempScript, TEMP_DIRECTORIES, } from "./snapshot-save.ts";
19
20
  export { STEP_ENV, type StepOutcome } from "./steps.ts";
@@ -11,8 +11,9 @@ export { prepareRunner, } from "./prepare.js";
11
11
  export { APPLY_LABEL, readyRunner, } from "./ready.js";
12
12
  export { checkRecipe, resolveSteps, resolveVcpus, } from "./recipe.js";
13
13
  export { REMOTE_TEST_EVENTS_PATH, remoteCommand, remoteEnvironment, runRemote, } from "./remote-command.js";
14
- export { CREATE_SETTLE_MS, runnerSandboxScope, SNAPSHOT_SETTLE_MS, } from "./scope.js";
14
+ export { CREATE_SETTLE_MS, keptMs, runnerSandboxScope, SNAPSHOT_SETTLE_MS, } from "./scope.js";
15
15
  export { BASE_INDEX_LABEL, buildSnapshot } from "./snapshot-build.js";
16
- export { findSnapshotCandidates, pickSnapshot, RUNNER_SNAPSHOTS_SUBPATH, SNAPSHOT_EXPIRATION_MS, snapshotEntryFileName, snapshotEntryIdentity, } from "./snapshot-cache.js";
17
- export { applyScript, baseIndexScript, snapshotKey, snapshotStepsAt } from "./snapshot-key.js";
16
+ export { dropBranchSnapshots, findSnapshotCandidates, isBranchEntry, pickSnapshot, RUNNER_SNAPSHOTS_SUBPATH, SNAPSHOT_EXPIRATION_MS, snapshotEntryFileName, snapshotEntryIdentity, } from "./snapshot-cache.js";
17
+ export { applyScript, baseIndexScript, RESET_TO_BASE, snapshotKey, snapshotStepsAt, } from "./snapshot-key.js";
18
+ export { saveBranchSnapshot, scrubGitScript, scrubTempScript, TEMP_DIRECTORIES, } from "./snapshot-save.js";
18
19
  export { STEP_ENV } from "./steps.js";
@@ -1,9 +1,12 @@
1
1
  // The runner snapshot cache's file format: one JSON object per runner snapshot, carrying `version: 1`. A reader
2
- // rejects a version it doesn't know.
2
+ // rejects a version it doesn't know. A branch snapshot's record adds `branch`, `head` and `repoRoot`, all three or
3
+ // none; a storm that predates them drops them as it reads, so the file's name no longer matches the entry's identity,
4
+ // and that storm lists the file as unreadable and never starts from it.
3
5
  import { z } from "zod";
4
6
  const isoTime = z.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "not a time" });
5
7
  const nonEmpty = z.string().min(1);
6
- const entrySchema = z.object({
8
+ const entrySchema = z
9
+ .object({
7
10
  version: z.literal(1),
8
11
  teamId: nonEmpty,
9
12
  projectId: nonEmpty,
@@ -12,10 +15,17 @@ const entrySchema = z.object({
12
15
  recipeName: nonEmpty,
13
16
  snapshotKey: nonEmpty,
14
17
  base: nonEmpty,
18
+ branch: nonEmpty.exactOptional(),
19
+ head: nonEmpty.exactOptional(),
20
+ repoRoot: nonEmpty.exactOptional(),
15
21
  snapshotId: nonEmpty,
16
22
  createdAt: isoTime,
17
23
  expiresAt: isoTime,
18
- });
24
+ })
25
+ .refine((entry) => {
26
+ const present = [entry.branch, entry.head, entry.repoRoot].filter((value) => value !== undefined).length;
27
+ return present === 0 || present === 3;
28
+ }, { message: "has some of branch, head and repoRoot without the others" });
19
29
  /** The entry a cache file holds, or why it holds none. */
20
30
  export function parseSnapshotEntry(text) {
21
31
  let json;
@@ -39,7 +49,8 @@ export function parseSnapshotEntry(text) {
39
49
  }
40
50
  /** The text of the file that records `entry`. */
41
51
  export function snapshotEntryText(entry) {
42
- const { teamId, projectId, region, runtime, recipeName, snapshotKey, base, snapshotId, createdAt, expiresAt } = entry;
52
+ const { teamId, projectId, region, runtime, recipeName, snapshotKey, base, branch, head, repoRoot } = entry;
53
+ const { snapshotId, createdAt, expiresAt } = entry;
43
54
  const record = {
44
55
  version: 1,
45
56
  teamId,
@@ -49,6 +60,9 @@ export function snapshotEntryText(entry) {
49
60
  recipeName,
50
61
  snapshotKey,
51
62
  base,
63
+ ...(branch === undefined ? {} : { branch }),
64
+ ...(head === undefined ? {} : { head }),
65
+ ...(repoRoot === undefined ? {} : { repoRoot }),
52
66
  snapshotId,
53
67
  createdAt,
54
68
  expiresAt,