@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 RefusedBaseRef } from "./base.ts";
2
- import type { CheckoutFailure, CheckoutUpload } from "./gateways.ts";
2
+ import type { CheckoutFailure, CheckoutHead, CheckoutUpload } from "./gateways.ts";
3
3
  import { type CheckedRecipe, type RunnerResources, type RunnerStep } from "./recipe.ts";
4
4
  import { type RunnerSnapshotCandidate, type SnapshotCacheContext, type SnapshotCacheNote } from "./snapshot-cache.ts";
5
5
  /** What `prepareRunner` needs: the checkout, the runner snapshot cache and the clock. */
@@ -12,11 +12,15 @@ export interface PrepareRunnerRequest {
12
12
  readonly resources: RunnerResources;
13
13
  /** `--rebuild-snapshot`: the run builds a runner snapshot whatever the cache holds, so the cache isn't read. */
14
14
  readonly rebuild: boolean;
15
+ /** `--save-snapshot`: the run saves the runner sandbox as a branch snapshot of HEAD's branch once the command ends. */
16
+ readonly saveSnapshot: boolean;
15
17
  }
16
18
  /** A runner run checked on this machine, ready for the remote side. */
17
19
  export interface PreparedRunner {
18
20
  readonly recipe: CheckedRecipe;
19
21
  readonly repoRoot: string;
22
+ /** Where HEAD is: the branch a run's branch snapshot is for, null when detached, and its commit. */
23
+ readonly head: CheckoutHead;
20
24
  /** The run's base, a full SHA, and the ref it is HEAD's merge-base with. */
21
25
  readonly base: string;
22
26
  readonly baseRef: string;
@@ -27,11 +31,25 @@ export interface PreparedRunner {
27
31
  /** The runner sandbox's vCPUs for the run's resources. */
28
32
  readonly vcpus: number;
29
33
  readonly upload: CheckoutUpload;
30
- /** The cached runner snapshots the run may start from, before the team and project filter (`pickSnapshot`). */
34
+ /**
35
+ * The cached runner snapshots the run may start from, base snapshots and HEAD's branch's branch snapshots, before
36
+ * the team and project filter (`pickSnapshot`).
37
+ */
31
38
  readonly candidates: readonly RunnerSnapshotCandidate[];
32
39
  readonly rebuild: boolean;
33
40
  /** What the cache read noticed, for the run to report. */
34
41
  readonly notes: readonly SnapshotCacheNote[];
42
+ /**
43
+ * `--save-snapshot`: the branch the run saves a branch snapshot of, or why it saves none (`skipped`, with a
44
+ * detached HEAD); null without the flag.
45
+ */
46
+ readonly save: {
47
+ readonly kind: "branch";
48
+ readonly branch: string;
49
+ } | {
50
+ readonly kind: "skipped";
51
+ readonly reason: "detached-head";
52
+ } | null;
35
53
  }
36
54
  /**
37
55
  * How the local checks ended.
@@ -61,7 +79,8 @@ export type PrepareRunnerOutcome = {
61
79
  readonly failure: CheckoutFailure;
62
80
  };
63
81
  /**
64
- * Runs the local checks in order: the repository's root, the base, the submodule refusal, the snapshot steps at the
65
- * base and their key, the runner's vCPUs, the upload, and the cache read. It never mints, leases or creates.
82
+ * Runs the local checks in order: the repository's root, HEAD, the base, the submodule refusal, the snapshot steps at
83
+ * the base and their key, the runner's vCPUs, the upload, and the cache read. It never mints, leases or creates. Under
84
+ * `--save-snapshot` it decides what the run saves: HEAD's branch, or nothing with a detached HEAD.
66
85
  */
67
86
  export declare function prepareRunner(context: RunnerPrepareContext, request: PrepareRunnerRequest): Promise<PrepareRunnerOutcome>;
@@ -6,8 +6,9 @@ import { resolveVcpus } from "./recipe.js";
6
6
  import { findSnapshotCandidates, } from "./snapshot-cache.js";
7
7
  import { snapshotStepsAt } from "./snapshot-key.js";
8
8
  /**
9
- * Runs the local checks in order: the repository's root, the base, the submodule refusal, the snapshot steps at the
10
- * base and their key, the runner's vCPUs, the upload, and the cache read. It never mints, leases or creates.
9
+ * Runs the local checks in order: the repository's root, HEAD, the base, the submodule refusal, the snapshot steps at
10
+ * the base and their key, the runner's vCPUs, the upload, and the cache read. It never mints, leases or creates. Under
11
+ * `--save-snapshot` it decides what the run saves: HEAD's branch, or nothing with a detached HEAD.
11
12
  */
12
13
  export async function prepareRunner(context, request) {
13
14
  const { checkout } = context;
@@ -16,6 +17,9 @@ export async function prepareRunner(context, request) {
16
17
  if (!root.ok)
17
18
  return { kind: "checkout-failed", failure: root.failure };
18
19
  const repoRoot = root.value;
20
+ const head = await checkout.head({ repoRoot });
21
+ if (!head.ok)
22
+ return { kind: "checkout-failed", failure: head.failure };
19
23
  const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
20
24
  if (resolved.kind === "failed")
21
25
  return { kind: "checkout-failed", failure: resolved.failure };
@@ -38,12 +42,13 @@ export async function prepareRunner(context, request) {
38
42
  return { kind: "checkout-failed", failure: upload.failure };
39
43
  const cache = request.rebuild
40
44
  ? { candidates: [], notes: [] }
41
- : await findSnapshotCandidates(context, { repoRoot, recipe });
45
+ : await findSnapshotCandidates(context, { repoRoot, recipe, branch: head.value.branch });
42
46
  return {
43
47
  kind: "ok",
44
48
  prepared: {
45
49
  recipe,
46
50
  repoRoot,
51
+ head: head.value,
47
52
  base,
48
53
  baseRef: resolved.ref,
49
54
  toolchains: steps.toolchains,
@@ -54,6 +59,11 @@ export async function prepareRunner(context, request) {
54
59
  candidates: cache.candidates,
55
60
  rebuild: request.rebuild,
56
61
  notes: cache.notes,
62
+ save: !request.saveSnapshot
63
+ ? null
64
+ : head.value.branch === null
65
+ ? { kind: "skipped", reason: "detached-head" }
66
+ : { kind: "branch", branch: head.value.branch },
57
67
  },
58
68
  };
59
69
  }
@@ -8,11 +8,15 @@ export declare const APPLY_LABEL = "Applying your changes";
8
8
  /** A runner sandbox ready for the command. */
9
9
  export interface ReadyRunner {
10
10
  readonly sandbox: RunnerSandbox;
11
- readonly snapshotId: string;
12
- /** The base of the runner snapshot it started from, which its repository holds as its first commit. */
13
- readonly base: string;
11
+ /**
12
+ * The cache entry of the runner snapshot it started from: a base snapshot or a branch snapshot, whose base its
13
+ * repository holds as its first commit.
14
+ */
15
+ readonly startedFrom: RunnerSnapshotEntry;
14
16
  /** Whether this run built the runner snapshot. */
15
17
  readonly built: boolean;
18
+ /** How long the build step took, in milliseconds. */
19
+ readonly buildMs: number;
16
20
  readonly vcpus: number;
17
21
  readonly region: string;
18
22
  readonly runtime: string;
@@ -24,7 +24,13 @@ export async function readyRunner(context, request, control, progress) {
24
24
  let entry;
25
25
  if (picked !== undefined) {
26
26
  entry = picked.entry;
27
- await progress.emit({ kind: "snapshot-reused", snapshotId: entry.snapshotId, base: entry.base });
27
+ await progress.emit({
28
+ kind: "snapshot-reused",
29
+ snapshotId: entry.snapshotId,
30
+ base: entry.base,
31
+ branch: entry.branch ?? null,
32
+ head: entry.head ?? null,
33
+ });
28
34
  }
29
35
  else {
30
36
  const built = await buildSnapshot(context, { prepared, access, user: request.user, reason: prepared.rebuild ? "rebuild" : "no-snapshot" }, control, progress);
@@ -83,9 +89,9 @@ export async function readyRunner(context, request, control, progress) {
83
89
  kind: "ready",
84
90
  runner: {
85
91
  sandbox,
86
- snapshotId: entry.snapshotId,
87
- base: entry.base,
92
+ startedFrom: entry,
88
93
  built: picked === undefined,
94
+ buildMs: built.value,
89
95
  vcpus: prepared.vcpus,
90
96
  region: recipe.region,
91
97
  runtime: recipe.runtime,
@@ -133,7 +139,7 @@ export function stagedChanges(upload) {
133
139
  : [{ name: STAGED_FILES.untrackedTarball, content: upload.untrackedTarball }]),
134
140
  ];
135
141
  }
136
- /** Runs the apply, install or build step; the install and build get rule lines. */
142
+ /** Runs the apply, install or build step, answering how long it took; the install and build get rule lines. */
137
143
  async function stage(context, request, signal, progress) {
138
144
  if (signal.aborted)
139
145
  return { kind: "aborted" };
@@ -145,7 +151,7 @@ async function stage(context, request, signal, progress) {
145
151
  if (ran.kind === "succeeded") {
146
152
  if (section !== undefined)
147
153
  await progress.emit({ kind: "output-ended", section, outcome: "finished" });
148
- return { kind: "ok", value: undefined };
154
+ return { kind: "ok", value: ran.ms };
149
155
  }
150
156
  const stop = ran.kind === "exited"
151
157
  ? {
@@ -5,6 +5,20 @@ import type { RunnerSandbox, RunnerSandboxGateway, RunnerSandboxPlacement, Runne
5
5
  export declare const CREATE_SETTLE_MS = 20000;
6
6
  /** How long closing waits for a runner snapshot still saving: 2 minutes. */
7
7
  export declare const SNAPSHOT_SETTLE_MS: number;
8
+ /**
9
+ * What a runner run does with its runner sandbox once it ends, decided before the run starts: keep it running `ms`
10
+ * (`keep`; 0 stops and deletes it), or save it as a branch snapshot of `branch` (`save`, `--save-snapshot` on a
11
+ * branch), which never keeps it, whether the save runs or not.
12
+ */
13
+ export type RunnerSandboxPlan = {
14
+ readonly kind: "keep";
15
+ readonly ms: number;
16
+ } | {
17
+ readonly kind: "save";
18
+ readonly branch: string;
19
+ };
20
+ /** How long `plan` keeps the runner sandbox running once the run ends, in milliseconds: 0 for a save. */
21
+ export declare function keptMs(plan: RunnerSandboxPlan): number;
8
22
  /**
9
23
  * What closing a scope left: the runner sandbox it kept running (`kept`), or couldn't keep running and so stopped and
10
24
  * deleted (`notKept`), each null otherwise, and the sandboxes it couldn't stop or delete.
@@ -30,7 +44,9 @@ export interface RunnerSandboxScope {
30
44
  startRunnerSandbox(access: SandboxAccess, request: RunnerSandboxPlacement & {
31
45
  readonly snapshotId: string;
32
46
  }): Promise<RunnerSandboxResult<RunnerSandbox, RunnerStartFailure>>;
33
- /** Saves a build sandbox as a runner snapshot, then deletes it at once; a failed save leaves it to `close`. */
47
+ /**
48
+ * Saves a build or runner sandbox as a runner snapshot, then deletes it at once; a failed save leaves it to `close`.
49
+ */
34
50
  saveSnapshot(sandbox: RunnerSandbox, request: {
35
51
  readonly expirationMs: number;
36
52
  }): Promise<RunnerSandboxResult<SavedSnapshot>>;
@@ -6,6 +6,10 @@
6
6
  export const CREATE_SETTLE_MS = 20_000;
7
7
  /** How long closing waits for a runner snapshot still saving: 2 minutes. */
8
8
  export const SNAPSHOT_SETTLE_MS = 2 * 60_000;
9
+ /** How long `plan` keeps the runner sandbox running once the run ends, in milliseconds: 0 for a save. */
10
+ export function keptMs(plan) {
11
+ return plan.kind === "keep" ? plan.ms : 0;
12
+ }
9
13
  /**
10
14
  * A scope over `context.runnerSandboxes`, waiting with `context.timer` and reporting to `progress`, which keeps the
11
15
  * runner sandbox running `keepMs` past closing (`context.clock` says when that is), or stops and deletes it with the
@@ -25,7 +25,9 @@ export interface BuildSnapshotRequest {
25
25
  /**
26
26
  * Builds a runner snapshot of `prepared.base`. The build sandbox starts while the base's files are packed, and is
27
27
  * deleted once saved; a build that fails leaves it to the scope to stop and delete. A cache entry that can't be
28
- * written is reported, and the build still succeeds.
28
+ * written is reported, and the build still succeeds. Under `--rebuild-snapshot` it then removes HEAD's branch's branch
29
+ * snapshot entries for the same owner and recipe, so the next run doesn't start from one the rebuild meant to replace;
30
+ * one it can't remove is reported.
29
31
  */
30
32
  export declare function buildSnapshot(context: Pick<RunnerContext, "checkout" | "runnerSnapshots" | "runnerSandboxes" | "clock">, request: BuildSnapshotRequest, control: {
31
33
  readonly scope: RunnerSandboxScope;
@@ -1,7 +1,7 @@
1
1
  // Building a runner snapshot of a run's base: a build sandbox runs the toolchain steps, commits exactly the base's
2
2
  // tracked files, runs the warm steps, and is saved as a snapshot, which the cache then records.
3
3
  import { runnerTags } from "./context.js";
4
- import { SNAPSHOT_EXPIRATION_MS } from "./snapshot-cache.js";
4
+ import { dropBranchSnapshots, SNAPSHOT_EXPIRATION_MS } from "./snapshot-cache.js";
5
5
  import { baseIndexScript, STAGED_FILES } from "./snapshot-key.js";
6
6
  import { runStep, sandboxStop } from "./steps.js";
7
7
  /** How long a build sandbox may live: 30 minutes. */
@@ -11,7 +11,9 @@ export const BASE_INDEX_LABEL = "Committing the base's files";
11
11
  /**
12
12
  * Builds a runner snapshot of `prepared.base`. The build sandbox starts while the base's files are packed, and is
13
13
  * deleted once saved; a build that fails leaves it to the scope to stop and delete. A cache entry that can't be
14
- * written is reported, and the build still succeeds.
14
+ * written is reported, and the build still succeeds. Under `--rebuild-snapshot` it then removes HEAD's branch's branch
15
+ * snapshot entries for the same owner and recipe, so the next run doesn't start from one the rebuild meant to replace;
16
+ * one it can't remove is reported.
15
17
  */
16
18
  export async function buildSnapshot(context, request, control, progress) {
17
19
  const { prepared, access } = request;
@@ -100,6 +102,14 @@ export async function buildSnapshot(context, request, control, progress) {
100
102
  const written = await context.runnerSnapshots.writeEntry(entry);
101
103
  if (!written.ok)
102
104
  await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
105
+ const { branch } = prepared.head;
106
+ if (request.reason === "rebuild" && branch !== null) {
107
+ const dropped = await dropBranchSnapshots(context.runnerSnapshots, { branch, repoRoot, owner: access, recipe });
108
+ if (dropped.snapshotIds.length > 0)
109
+ await progress.emit({ kind: "branch-snapshots-dropped", branch, snapshotIds: dropped.snapshotIds });
110
+ for (const failure of dropped.failures)
111
+ await progress.emit({ kind: "branch-snapshots-not-dropped", branch, failure });
112
+ }
103
113
  const ms = now() - startedAt;
104
114
  await progress.emit({
105
115
  kind: "snapshot-built",
@@ -9,9 +9,18 @@ export declare const SNAPSHOT_EXPIRATION_MS: number;
9
9
  export declare const SNAPSHOT_MIN_REMAINING_MS: number;
10
10
  /**
11
11
  * An entry's identity: the first 32 hex characters of sha256 over its team id, project id, region, runtime, recipe
12
- * name, snapshot key and base, joined with NUL. Entries with one identity replace each other.
12
+ * name, snapshot key, base and, for a branch snapshot only, branch and checkout root, joined with NUL. Entries with
13
+ * one identity replace each other: a base snapshot's entry replaces the base snapshot's at its base, and a branch
14
+ * snapshot's replaces that branch's in that checkout at its base. A base snapshot's identity is the one it had before
15
+ * branch snapshots existed.
13
16
  */
14
17
  export declare function snapshotEntryIdentity(entry: RunnerSnapshotEntry): string;
18
+ /** Whether `entry` records a branch snapshot, saved from a run on its branch, rather than a base snapshot. */
19
+ export declare function isBranchEntry(entry: RunnerSnapshotEntry): entry is RunnerSnapshotEntry & {
20
+ readonly branch: string;
21
+ readonly head: string;
22
+ readonly repoRoot: string;
23
+ };
15
24
  /** The name of the file that records `entry`: its identity and `.json`. */
16
25
  export declare function snapshotEntryFileName(entry: RunnerSnapshotEntry): string;
17
26
  /** Whether `entry`'s snapshot has expired at `now`. */
@@ -61,24 +70,53 @@ export interface SnapshotCacheContext {
61
70
  readonly clock: Clock;
62
71
  }
63
72
  /**
64
- * Reads the cache for the runner snapshots a run of `recipe` may start from. It removes expired entries' files, and
65
- * keeps the entries for the recipe's region, runtime and name with more than an hour left, whose base HEAD contains
66
- * (a base missing from the clone doesn't), and whose snapshot key, recomputed at that entry's base, is the one
67
- * recorded. A failure along the way is a note, never a refusal.
73
+ * Reads the cache for the runner snapshots a run of `recipe` on `branch` may start from. It removes expired entries'
74
+ * files, and keeps the entries for the recipe's region, runtime and name with more than an hour left, whose base HEAD
75
+ * contains (a base missing from the clone doesn't), and whose snapshot key, recomputed at that entry's base, is the
76
+ * one recorded. Of branch snapshots it keeps only `branch`'s saved from this checkout, `repoRoot`, whatever HEAD
77
+ * commit saved them; with `branch` null, a detached HEAD, it keeps none. A branch of the same name in another checkout
78
+ * may hold other code, so its snapshot never carries over. A failure along the way is a note, never a refusal.
68
79
  */
69
80
  export declare function findSnapshotCandidates(context: SnapshotCacheContext, request: {
70
81
  readonly repoRoot: string;
71
82
  readonly recipe: Pick<CheckedRecipe, "name" | "region" | "runtime" | "snapshot">;
83
+ /** HEAD's branch; null when detached. */
84
+ readonly branch: string | null;
72
85
  }): Promise<{
73
86
  readonly candidates: readonly RunnerSnapshotCandidate[];
74
87
  readonly notes: readonly SnapshotCacheNote[];
75
88
  }>;
76
89
  /**
77
- * Picks the runner snapshot a run starts from, once the credential names its team and project: of the candidates
78
- * for them, the one whose base is nearest HEAD, the one every other candidate's base is an ancestor of; when bases
79
- * are on separate lines of history, the newest commit. `undefined` when none is for them.
90
+ * Picks the runner snapshot a run starts from, once the credential names its team and project. Of the candidates for
91
+ * them it finds the base nearest HEAD, the one every other candidate's base is an ancestor of; when bases are on
92
+ * separate lines of history, the newest commit. Of the candidates at that base it picks a branch snapshot over the
93
+ * base snapshot, then the one that expires later, so a branch snapshot of an older base never beats a nearer base.
94
+ * `undefined` when none is for them.
80
95
  */
81
96
  export declare function pickSnapshot(candidates: readonly RunnerSnapshotCandidate[], owner: {
82
97
  readonly teamId: string;
83
98
  readonly projectId: string;
84
99
  }): RunnerSnapshotCandidate | undefined;
100
+ /**
101
+ * What dropping a branch's runner snapshots from the cache did: the snapshot ids of the entries it removed, and why
102
+ * it couldn't list the cache or remove an entry, if it couldn't.
103
+ */
104
+ export interface DroppedBranchSnapshots {
105
+ readonly snapshotIds: readonly string[];
106
+ readonly failures: readonly RunnerSnapshotCacheFailure[];
107
+ }
108
+ /**
109
+ * Removes every cached branch snapshot entry of `branch` in the checkout at `repoRoot` for `owner`'s team and project
110
+ * and the recipe's region, runtime and name, whatever its base, so a run after `--rebuild-snapshot` doesn't start
111
+ * from a branch snapshot the rebuild meant to replace. The snapshots themselves are left to expire. A failure is
112
+ * reported, never a refusal.
113
+ */
114
+ export declare function dropBranchSnapshots(runnerSnapshots: RunnerSnapshotCacheGateway, request: {
115
+ readonly branch: string;
116
+ readonly repoRoot: string;
117
+ readonly owner: {
118
+ readonly teamId: string;
119
+ readonly projectId: string;
120
+ };
121
+ readonly recipe: Pick<CheckedRecipe, "name" | "region" | "runtime">;
122
+ }): Promise<DroppedBranchSnapshots>;
@@ -10,7 +10,10 @@ export const SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000;
10
10
  export const SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1000;
11
11
  /**
12
12
  * An entry's identity: the first 32 hex characters of sha256 over its team id, project id, region, runtime, recipe
13
- * name, snapshot key and base, joined with NUL. Entries with one identity replace each other.
13
+ * name, snapshot key, base and, for a branch snapshot only, branch and checkout root, joined with NUL. Entries with
14
+ * one identity replace each other: a base snapshot's entry replaces the base snapshot's at its base, and a branch
15
+ * snapshot's replaces that branch's in that checkout at its base. A base snapshot's identity is the one it had before
16
+ * branch snapshots existed.
14
17
  */
15
18
  export function snapshotEntryIdentity(entry) {
16
19
  return createHash("sha256")
@@ -22,10 +25,15 @@ export function snapshotEntryIdentity(entry) {
22
25
  entry.recipeName,
23
26
  entry.snapshotKey,
24
27
  entry.base,
28
+ ...(isBranchEntry(entry) ? [entry.branch, entry.repoRoot] : []),
25
29
  ].join("\0"))
26
30
  .digest("hex")
27
31
  .slice(0, 32);
28
32
  }
33
+ /** Whether `entry` records a branch snapshot, saved from a run on its branch, rather than a base snapshot. */
34
+ export function isBranchEntry(entry) {
35
+ return entry.branch !== undefined && entry.head !== undefined && entry.repoRoot !== undefined;
36
+ }
29
37
  /** The name of the file that records `entry`: its identity and `.json`. */
30
38
  export function snapshotEntryFileName(entry) {
31
39
  return `${snapshotEntryIdentity(entry)}.json`;
@@ -39,14 +47,16 @@ export function hasTimeLeft(entry, now) {
39
47
  return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
40
48
  }
41
49
  /**
42
- * Reads the cache for the runner snapshots a run of `recipe` may start from. It removes expired entries' files, and
43
- * keeps the entries for the recipe's region, runtime and name with more than an hour left, whose base HEAD contains
44
- * (a base missing from the clone doesn't), and whose snapshot key, recomputed at that entry's base, is the one
45
- * recorded. A failure along the way is a note, never a refusal.
50
+ * Reads the cache for the runner snapshots a run of `recipe` on `branch` may start from. It removes expired entries'
51
+ * files, and keeps the entries for the recipe's region, runtime and name with more than an hour left, whose base HEAD
52
+ * contains (a base missing from the clone doesn't), and whose snapshot key, recomputed at that entry's base, is the
53
+ * one recorded. Of branch snapshots it keeps only `branch`'s saved from this checkout, `repoRoot`, whatever HEAD
54
+ * commit saved them; with `branch` null, a detached HEAD, it keeps none. A branch of the same name in another checkout
55
+ * may hold other code, so its snapshot never carries over. A failure along the way is a note, never a refusal.
46
56
  */
47
57
  export async function findSnapshotCandidates(context, request) {
48
58
  const { checkout, runnerSnapshots } = context;
49
- const { repoRoot, recipe } = request;
59
+ const { repoRoot, recipe, branch } = request;
50
60
  const notes = [];
51
61
  const listed = await runnerSnapshots.listEntries();
52
62
  if (!listed.ok)
@@ -63,6 +73,7 @@ export async function findSnapshotCandidates(context, request) {
63
73
  if (entry.region === recipe.region &&
64
74
  entry.runtime === recipe.runtime &&
65
75
  entry.recipeName === recipe.name &&
76
+ (isBranchEntry(entry) ? entry.branch === branch && entry.repoRoot === repoRoot : entry.branch === undefined) &&
66
77
  hasTimeLeft(entry, now))
67
78
  live.push(entry);
68
79
  }
@@ -113,14 +124,52 @@ export async function findSnapshotCandidates(context, request) {
113
124
  return { candidates, notes };
114
125
  }
115
126
  /**
116
- * Picks the runner snapshot a run starts from, once the credential names its team and project: of the candidates
117
- * for them, the one whose base is nearest HEAD, the one every other candidate's base is an ancestor of; when bases
118
- * are on separate lines of history, the newest commit. `undefined` when none is for them.
127
+ * Picks the runner snapshot a run starts from, once the credential names its team and project. Of the candidates for
128
+ * them it finds the base nearest HEAD, the one every other candidate's base is an ancestor of; when bases are on
129
+ * separate lines of history, the newest commit. Of the candidates at that base it picks a branch snapshot over the
130
+ * base snapshot, then the one that expires later, so a branch snapshot of an older base never beats a nearer base.
131
+ * `undefined` when none is for them.
119
132
  */
120
133
  export function pickSnapshot(candidates, owner) {
121
134
  const owned = candidates
122
135
  .filter(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId)
123
136
  .toSorted((a, b) => b.commitTime - a.commitTime || Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt));
124
- const nearest = owned.find((candidate) => owned.every((other) => other.entry.base === candidate.entry.base || candidate.ancestorBases.includes(other.entry.base)));
125
- return nearest ?? owned[0];
137
+ const nearest = owned.find((candidate) => owned.every((other) => other.entry.base === candidate.entry.base || candidate.ancestorBases.includes(other.entry.base))) ?? owned[0];
138
+ if (nearest === undefined)
139
+ return undefined;
140
+ return owned
141
+ .filter(({ entry }) => entry.base === nearest.entry.base)
142
+ .toSorted((a, b) => Number(isBranchEntry(b.entry)) - Number(isBranchEntry(a.entry)) ||
143
+ Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt))[0];
144
+ }
145
+ /**
146
+ * Removes every cached branch snapshot entry of `branch` in the checkout at `repoRoot` for `owner`'s team and project
147
+ * and the recipe's region, runtime and name, whatever its base, so a run after `--rebuild-snapshot` doesn't start
148
+ * from a branch snapshot the rebuild meant to replace. The snapshots themselves are left to expire. A failure is
149
+ * reported, never a refusal.
150
+ */
151
+ export async function dropBranchSnapshots(runnerSnapshots, request) {
152
+ const { branch, repoRoot, owner, recipe } = request;
153
+ const listed = await runnerSnapshots.listEntries();
154
+ if (!listed.ok)
155
+ return { snapshotIds: [], failures: [listed.failure] };
156
+ const snapshotIds = [];
157
+ const failures = [];
158
+ for (const entry of listed.value.entries) {
159
+ if (!isBranchEntry(entry) ||
160
+ entry.branch !== branch ||
161
+ entry.repoRoot !== repoRoot ||
162
+ entry.teamId !== owner.teamId ||
163
+ entry.projectId !== owner.projectId ||
164
+ entry.region !== recipe.region ||
165
+ entry.runtime !== recipe.runtime ||
166
+ entry.recipeName !== recipe.name)
167
+ continue;
168
+ const removed = await runnerSnapshots.removeEntry(entry);
169
+ if (removed.ok)
170
+ snapshotIds.push(entry.snapshotId);
171
+ else
172
+ failures.push(removed.failure);
173
+ }
174
+ return { snapshotIds, failures };
126
175
  }
@@ -15,6 +15,12 @@ export declare const STAGED_FILES: {
15
15
  readonly untrackedTarball: "untracked.tgz";
16
16
  readonly untrackedFileList: "untracked-files";
17
17
  };
18
+ /**
19
+ * Resets the repository to its root commit, which holds the base's tracked files (`baseIndexScript`): the real base
20
+ * commit isn't in a sandbox's repository. Then removes untracked files and directories, nested Git repositories
21
+ * included, keeping ignored ones such as `node_modules` and build outputs.
22
+ */
23
+ export declare const RESET_TO_BASE: readonly string[];
18
24
  /** A bash script that stops at the first failure and runs in the repository's root. */
19
25
  export declare function bashScript(lines: readonly string[]): string;
20
26
  /**
@@ -22,7 +28,12 @@ export declare function bashScript(lines: readonly string[]): string;
22
28
  * (`<staging>/base-files`), before the warm steps. `git add -A` would drop tracked files `.gitignore` matches.
23
29
  */
24
30
  export declare function baseIndexScript(base: string, staging: string): string;
25
- /** Applies and commits a run's patch and untracked files, uploaded to `staging`, in a runner sandbox. */
31
+ /**
32
+ * Applies and commits a run's patch and untracked files, uploaded to `staging`, in a runner sandbox. It first resets
33
+ * the repository to its root commit, the base's tracked files, and removes untracked files and nested Git
34
+ * repositories `.gitignore` doesn't match, so a branch snapshot applies as cleanly as a base snapshot even when its
35
+ * save left something behind.
36
+ */
26
37
  export declare function applyScript(staging: string): string;
27
38
  /**
28
39
  * The snapshot key: sha256 hex over `format=<SNAPSHOT_FORMAT>`, each toolchain step's label and script, the
@@ -20,6 +20,16 @@ export const STAGED_FILES = {
20
20
  };
21
21
  /** The identity of the commits the scripts make, with no hook or signing in the way. */
22
22
  const GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
23
+ /**
24
+ * Resets the repository to its root commit, which holds the base's tracked files (`baseIndexScript`): the real base
25
+ * commit isn't in a sandbox's repository. Then removes untracked files and directories, nested Git repositories
26
+ * included, keeping ignored ones such as `node_modules` and build outputs.
27
+ */
28
+ export const RESET_TO_BASE = [
29
+ "root=$(git rev-list --max-parents=0 HEAD)",
30
+ 'git reset -q --hard "$root"',
31
+ "git clean -ffdq",
32
+ ];
23
33
  /** A bash script that stops at the first failure and runs in the repository's root. */
24
34
  export function bashScript(lines) {
25
35
  return ["set -euo pipefail", `cd ${REMOTE_ROOT}`, ...lines].join("\n");
@@ -40,12 +50,18 @@ export function baseIndexScript(base, staging) {
40
50
  `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`,
41
51
  ]);
42
52
  }
43
- /** Applies and commits a run's patch and untracked files, uploaded to `staging`, in a runner sandbox. */
53
+ /**
54
+ * Applies and commits a run's patch and untracked files, uploaded to `staging`, in a runner sandbox. It first resets
55
+ * the repository to its root commit, the base's tracked files, and removes untracked files and nested Git
56
+ * repositories `.gitignore` doesn't match, so a branch snapshot applies as cleanly as a base snapshot even when its
57
+ * save left something behind.
58
+ */
44
59
  export function applyScript(staging) {
45
60
  const patch = `${staging}/${STAGED_FILES.patch}`;
46
61
  const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
47
62
  const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
48
63
  return bashScript([
64
+ ...RESET_TO_BASE,
49
65
  // A build may have rewritten tracked files with the same content.
50
66
  "git update-index -q --refresh || true",
51
67
  `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
@@ -0,0 +1,53 @@
1
+ import type { RunnerContext } from "./context.ts";
2
+ import type { RunnerProgress, RunnerSave } from "./events.ts";
3
+ import type { ReadyRunner } from "./ready.ts";
4
+ import type { RunnerSandboxScope } from "./scope.ts";
5
+ /** The directories the temp scrub empties: `/tmp`, `/var/tmp`, and `$TMPDIR` when it is set. */
6
+ export declare const TEMP_DIRECTORIES: readonly string[];
7
+ /**
8
+ * Resets the working tree in `root` to its root commit, the base's tracked files (`baseIndexScript`), and removes
9
+ * untracked files and nested Git repositories that `.gitignore` doesn't match: the same reset the next run's apply
10
+ * starts with (`RESET_TO_BASE`). Ignored files, such as `node_modules`, build outputs and the turbo cache, stay.
11
+ *
12
+ * It leaves `.git` alone, so the run's commit and anything else the command put in Git stay in the snapshot. Cleaning
13
+ * history adds no correctness: the next run resets before it applies. Nor does it hide the run's changes: the ignored
14
+ * files the snapshot keeps hold their build outputs. And `git prune` can't promise it either, since it removes only
15
+ * loose objects, not packed ones.
16
+ */
17
+ export declare function scrubGitScript(root?: string): string;
18
+ /**
19
+ * Empties each of `directories`, shell words that may expand to nothing: deletes what it holds, then, for anything
20
+ * left, tries again with `sudo -n`. Fails, naming the directory and what is left, when one still holds something.
21
+ */
22
+ export declare function scrubTempScript(directories?: readonly string[]): string;
23
+ /** What saving a branch snapshot is asked to save: the ready runner sandbox, and the branch and commit it is for. */
24
+ export interface SaveBranchSnapshotRequest {
25
+ /** The runner sandbox the command ran in, and the runner snapshot it started from. */
26
+ readonly ready: ReadyRunner;
27
+ /** HEAD's branch as the run started, which the snapshot is for. */
28
+ readonly branch: string;
29
+ /** HEAD's commit as the run started, a full SHA. */
30
+ readonly head: string;
31
+ }
32
+ /** How a save that ran ended: a detached HEAD's `skipped` is decided before the run (`prepareRunner`). */
33
+ type BranchSnapshotSave = Exclude<RunnerSave, {
34
+ readonly kind: "skipped";
35
+ }>;
36
+ /**
37
+ * Saves the runner sandbox, once the command ended, as a branch snapshot of the run's branch. The run's plan gave the
38
+ * scope no keep time (`RunnerSandboxPlan`), so however the save ends, closing stops and deletes the sandbox. It resets
39
+ * the working tree to the base the sandbox started from, leaving `.git` alone, empties the temp directories, saves the
40
+ * sandbox as a runner snapshot, which the scope then deletes, and records the entry: the started-from entry's owner,
41
+ * recipe, snapshot key and base, with the branch, the HEAD commit and the checkout's root. Its entry replaces the
42
+ * branch's entry in that checkout at that base; the snapshot it replaces is left to expire, since a run on this
43
+ * machine may be starting from it. Nothing here changes the run's outcome: each way it ends is a note.
44
+ *
45
+ * It searches nothing for the run's secrets: the snapshot keeps what the command wrote to `$HOME` and the ignored
46
+ * files, such as a resource's token, as a kept runner sandbox does. The token is limited to one test resource, and
47
+ * only a later run on the branch from this checkout, which gets the same token, starts from the snapshot.
48
+ */
49
+ export declare function saveBranchSnapshot(context: Pick<RunnerContext, "runnerSandboxes" | "runnerSnapshots" | "clock">, request: SaveBranchSnapshotRequest, control: {
50
+ readonly scope: RunnerSandboxScope;
51
+ readonly signal: AbortSignal;
52
+ }, progress: RunnerProgress): Promise<BranchSnapshotSave>;
53
+ export {};