@leitwerk-dev/worker-runners 0.3.1 → 0.4.1

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 (60) hide show
  1. package/dist/{chunk-YDYI3BD2.js → chunk-FEIZN5GL.js} +53 -9
  2. package/dist/chunk-FEIZN5GL.js.map +1 -0
  3. package/dist/{chunk-ZGFD76I6.js → chunk-GF3H4C3J.js} +1 -1
  4. package/dist/chunk-GF3H4C3J.js.map +1 -0
  5. package/dist/{chunk-V7TTFLGE.js → chunk-GMZOYHQD.js} +414 -82
  6. package/dist/chunk-GMZOYHQD.js.map +1 -0
  7. package/dist/{chunk-ISH4647R.js → chunk-LZOVBKHR.js} +89 -89
  8. package/dist/chunk-LZOVBKHR.js.map +1 -0
  9. package/dist/index.js +15 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/{kubernetes-api-client-CEe7pHC4.d.ts → kubernetes-api-client-BMWAgyfW.d.ts} +192 -103
  12. package/dist/kubernetes-api-client.d.ts +3 -0
  13. package/dist/kubernetes-api-client.d.ts.map +1 -1
  14. package/dist/kubernetes-client-public.js +2 -2
  15. package/dist/kubernetes-http-client.d.ts.map +1 -1
  16. package/dist/kubernetes-http-client.js +2 -2
  17. package/dist/kubernetes-image-preload-api.d.ts +69 -0
  18. package/dist/kubernetes-image-preload-api.d.ts.map +1 -0
  19. package/dist/kubernetes-image-preload.d.ts +48 -0
  20. package/dist/kubernetes-image-preload.d.ts.map +1 -0
  21. package/dist/kubernetes-manifests.d.ts +10 -1
  22. package/dist/kubernetes-manifests.d.ts.map +1 -1
  23. package/dist/kubernetes-preparation-api.d.ts +26 -0
  24. package/dist/kubernetes-preparation-api.d.ts.map +1 -0
  25. package/dist/kubernetes-preparation.d.ts +21 -0
  26. package/dist/kubernetes-preparation.d.ts.map +1 -0
  27. package/dist/kubernetes-public.js +3 -3
  28. package/dist/kubernetes-volume-pool-api.d.ts +17 -14
  29. package/dist/kubernetes-volume-pool-api.d.ts.map +1 -1
  30. package/dist/kubernetes-volume-pool.d.ts +5 -5
  31. package/dist/kubernetes-volume-pool.d.ts.map +1 -1
  32. package/dist/kubernetes-volume-retirement.d.ts +20 -0
  33. package/dist/kubernetes-volume-retirement.d.ts.map +1 -0
  34. package/dist/kubernetes-worker-runner.d.ts +13 -3
  35. package/dist/kubernetes-worker-runner.d.ts.map +1 -1
  36. package/dist/kubernetes-worker-runner.js +3 -3
  37. package/dist/process-volume-retention.d.ts +4 -0
  38. package/dist/process-volume-retention.d.ts.map +1 -1
  39. package/dist/types-public.js +1 -1
  40. package/dist/types.d.ts +11 -1
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/types.js +1 -1
  43. package/package.json +5 -5
  44. package/src/kubernetes-api-client.ts +3 -0
  45. package/src/kubernetes-http-client.ts +4 -0
  46. package/src/kubernetes-image-preload-api.ts +96 -0
  47. package/src/kubernetes-image-preload.ts +278 -0
  48. package/src/kubernetes-manifests.ts +75 -11
  49. package/src/kubernetes-preparation-api.ts +77 -0
  50. package/src/kubernetes-preparation.ts +100 -0
  51. package/src/kubernetes-volume-pool-api.ts +45 -105
  52. package/src/kubernetes-volume-pool.ts +28 -58
  53. package/src/kubernetes-volume-retirement.ts +139 -0
  54. package/src/kubernetes-worker-runner.ts +78 -28
  55. package/src/process-volume-retention.ts +27 -4
  56. package/src/types.ts +15 -1
  57. package/dist/chunk-ISH4647R.js.map +0 -1
  58. package/dist/chunk-V7TTFLGE.js.map +0 -1
  59. package/dist/chunk-YDYI3BD2.js.map +0 -1
  60. package/dist/chunk-ZGFD76I6.js.map +0 -1
@@ -1,3 +1,5 @@
1
+ import { createPreparationApi, type PreparationRequest } from "./kubernetes-preparation-api.js";
2
+
1
3
  /** Kubernetes objects used for native PVC provisioning and safe PV rebinding. @internal */
2
4
  export interface PoolObject {
3
5
  /** @internal */
@@ -17,6 +19,8 @@ export interface PoolObject {
17
19
  /** @internal */
18
20
  deletionTimestamp?: string;
19
21
  /** @internal */
22
+ creationTimestamp?: string;
23
+ /** @internal */
20
24
  labels?: Record<string, string>;
21
25
  /** @internal */
22
26
  annotations?: Record<string, string>;
@@ -52,6 +56,17 @@ export interface PoolObject {
52
56
  status?: {
53
57
  /** @internal */
54
58
  phase?: string;
59
+ /** @internal */
60
+ reason?: string;
61
+ /** @internal */
62
+ conditions?: Array<{
63
+ /** @internal */
64
+ type?: string;
65
+ /** @internal */
66
+ status?: string;
67
+ /** @internal */
68
+ reason?: string;
69
+ }>;
55
70
  };
56
71
  }
57
72
 
@@ -91,7 +106,7 @@ export interface VolumePoolApi {
91
106
  deleteStorageClass(value: PoolStorageClass, signal: AbortSignal): Promise<void>;
92
107
  /** @internal */
93
108
  list(
94
- kind: "persistentvolumes" | "persistentvolumeclaims",
109
+ kind: "persistentvolumes" | "persistentvolumeclaims" | "pods",
95
110
  namespace: string,
96
111
  selector: string,
97
112
  signal: AbortSignal,
@@ -115,102 +130,34 @@ export interface VolumePoolApi {
115
130
  delete(kind: string, namespace: string, object: PoolObject, signal: AbortSignal): Promise<void>;
116
131
  }
117
132
 
118
- type Request = <T>(input: {
119
- method: string;
120
- path: string;
121
- body?: unknown;
122
- contentType?: string;
123
- ok?: readonly number[];
124
- signal?: AbortSignal;
125
- }) => Promise<{ status: number; body: T | null }>;
126
-
127
- export function createVolumePoolApi(request: Request): VolumePoolApi {
133
+ /** @internal */
134
+ export function createVolumePoolApi(request: PreparationRequest): VolumePoolApi {
135
+ const api = createPreparationApi(request, "volume-pool");
128
136
  const path = (kind: string, namespace: string, name?: string) =>
129
137
  `/api/v1/${namespace ? `namespaces/${encodeURIComponent(namespace)}/` : ""}${kind}${name ? `/${encodeURIComponent(name)}` : ""}`;
130
- const bounded = (signal: AbortSignal) => AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
131
138
  const classes = "/apis/storage.k8s.io/v1/storageclasses";
132
- async function list<T>(collection: string, selector: string, signal: AbortSignal): Promise<T[]> {
133
- const items: T[] = [];
134
- let cursor = "";
135
- do {
136
- const query = new URLSearchParams({
137
- labelSelector: selector,
138
- limit: "100",
139
- ...(cursor ? { continue: cursor } : {}),
140
- });
141
- const response = await request<{ items: T[]; metadata?: { continue?: string } }>({
142
- method: "GET",
143
- path: `${collection}?${query}`,
144
- signal: bounded(signal),
145
- });
146
- if (!response.body) throw new Error("Missing volume-pool list response");
147
- items.push(...response.body.items);
148
- cursor = response.body.metadata?.continue ?? "";
149
- } while (cursor);
150
- return items;
151
- }
152
139
 
153
140
  return {
154
- async getStorageClass(name, signal) {
155
- const response = await request<PoolStorageClass>({
156
- method: "GET",
157
- path: `${classes}/${encodeURIComponent(name)}`,
158
- ok: [200, 404],
159
- signal: bounded(signal),
160
- });
161
- return response.status === 404 ? null : response.body;
162
- },
163
- listStorageClasses(selector, signal) {
164
- return list<PoolStorageClass>(classes, selector, signal);
165
- },
166
- async createStorageClass(value, signal) {
167
- await request({
168
- method: "POST",
169
- path: classes,
170
- body: value,
171
- ok: [201, 409],
172
- signal: bounded(signal),
173
- });
174
- },
175
- async deleteStorageClass(value, signal) {
176
- if (!value.metadata.uid) throw new Error("Staging StorageClass identity is missing");
177
- await request({
178
- method: "DELETE",
179
- path: `${classes}/${encodeURIComponent(value.metadata.name)}`,
180
- body: {
181
- apiVersion: "v1",
182
- kind: "DeleteOptions",
183
- preconditions: { uid: value.metadata.uid },
184
- },
185
- ok: [200, 202, 404],
186
- signal: bounded(signal),
187
- });
188
- },
189
- list(kind, namespace, selector, signal) {
190
- return list<PoolObject>(path(kind, namespace), selector, signal);
191
- },
192
- async get(kind, namespace, name, signal) {
193
- const result = await request<PoolObject>({
194
- method: "GET",
195
- path: path(kind, namespace, name),
196
- ok: [200, 404],
197
- signal: bounded(signal),
198
- });
199
- return result.status === 404 ? null : result.body;
200
- },
201
- async create(kind, namespace, object, signal) {
202
- await request({
203
- method: "POST",
204
- path: path(kind, namespace),
205
- body: object,
206
- ok: [201, 409],
207
- signal: bounded(signal),
208
- });
209
- },
141
+ getStorageClass: (name, signal) =>
142
+ api.get<PoolStorageClass>(`${classes}/${encodeURIComponent(name)}`, signal),
143
+ listStorageClasses: (selector, signal) => api.list<PoolStorageClass>(classes, selector, signal),
144
+ createStorageClass: (value, signal) => api.create(classes, value, signal),
145
+ deleteStorageClass: (value, signal) =>
146
+ api.delete(
147
+ `${classes}/${encodeURIComponent(value.metadata.name)}`,
148
+ value.metadata.uid,
149
+ signal,
150
+ "Staging StorageClass",
151
+ ),
152
+ list: (kind, namespace, selector, signal) =>
153
+ api.list<PoolObject>(path(kind, namespace), selector, signal),
154
+ get: (kind, namespace, name, signal) =>
155
+ api.get<PoolObject>(path(kind, namespace, name), signal),
156
+ create: (kind, namespace, object, signal) => api.create(path(kind, namespace), object, signal),
210
157
  async patchVolume(volume, operations, signal) {
211
158
  if (!volume.metadata.uid || !volume.metadata.resourceVersion)
212
159
  throw new Error("PV identity is missing");
213
- await request({
160
+ await api.request({
214
161
  method: "PATCH",
215
162
  path: path("persistentvolumes", "", volume.metadata.name),
216
163
  contentType: "application/json-patch+json",
@@ -219,23 +166,16 @@ export function createVolumePoolApi(request: Request): VolumePoolApi {
219
166
  { op: "test", path: "/metadata/resourceVersion", value: volume.metadata.resourceVersion },
220
167
  ...operations,
221
168
  ],
222
- signal: bounded(signal),
223
- });
224
- },
225
- async delete(kind, namespace, object, signal) {
226
- if (!object.metadata.uid) throw new Error("Preparation resource identity is missing");
227
- await request({
228
- method: "DELETE",
229
- path: path(kind, namespace, object.metadata.name),
230
- body: {
231
- apiVersion: "v1",
232
- kind: "DeleteOptions",
233
- preconditions: { uid: object.metadata.uid },
234
- gracePeriodSeconds: 1,
235
- },
236
- ok: [200, 202, 404],
237
- signal: bounded(signal),
169
+ signal,
238
170
  });
239
171
  },
172
+ delete: (kind, namespace, object, signal) =>
173
+ api.delete(
174
+ path(kind, namespace, object.metadata.name),
175
+ object.metadata.uid,
176
+ signal,
177
+ "Preparation resource",
178
+ 1,
179
+ ),
240
180
  };
241
181
  }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { setTimeout as delay } from "node:timers/promises";
2
+ import { buildPreparationPodSpec, createPreparationController } from "./kubernetes-preparation.js";
3
3
  import type { PoolObject, VolumePoolApi } from "./kubernetes-volume-pool-api.js";
4
4
 
5
5
  export const POOL_LABEL = "leitwerk.dev/volume-pool";
@@ -36,7 +36,9 @@ export interface VolumePoolOptions {
36
36
  /** @internal */
37
37
  tolerations?: unknown[];
38
38
  /** @internal */
39
- onError?: () => void;
39
+ onError?: (error?: unknown) => void;
40
+ /** Clock seam; Kubernetes creation times survive controller restarts. @internal */
41
+ now?: () => number;
40
42
  }
41
43
 
42
44
  /** Only the staging claim's UID authorizes rebinding; process claims are never recycled. @internal */
@@ -54,8 +56,6 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
54
56
  [POOL_LABEL]: poolId,
55
57
  "leitwerk.dev/component": "volume-preparation",
56
58
  };
57
- let controller: AbortController | undefined;
58
- let running: Promise<void> | undefined;
59
59
 
60
60
  function preparationPod(claim: PoolObject): PoolObject {
61
61
  return {
@@ -75,30 +75,8 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
75
75
  ],
76
76
  },
77
77
  spec: {
78
- restartPolicy: "Never",
79
- serviceAccountName: "default",
80
- automountServiceAccountToken: false,
81
- nodeSelector: options.nodeSelector ?? {},
82
- tolerations: options.tolerations ?? [],
83
- imagePullSecrets: (options.imagePullSecrets ?? []).map((name) => ({ name })),
84
- containers: [
85
- {
86
- name: "prepare",
87
- image: options.image,
88
- imagePullPolicy: options.imagePullPolicy ?? "IfNotPresent",
89
- command: ["node", "-e", "process.exit(0)"],
90
- resources: {
91
- requests: { cpu: "1m", memory: "32Mi" },
92
- limits: { cpu: "100m", memory: "64Mi" },
93
- },
94
- securityContext: {
95
- allowPrivilegeEscalation: false,
96
- readOnlyRootFilesystem: true,
97
- capabilities: { drop: ["ALL"] },
98
- },
99
- volumeMounts: [{ name: "volume", mountPath: "/volume" }],
100
- },
101
- ],
78
+ ...buildPreparationPodSpec(options, [{ name: "volume", mountPath: "/volume" }]),
79
+ activeDeadlineSeconds: 900,
102
80
  volumes: [{ name: "volume", persistentVolumeClaim: { claimName: claim.metadata.name } }],
103
81
  },
104
82
  };
@@ -194,6 +172,7 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
194
172
  for (const pv of volumes) {
195
173
  if (await advanceVolume(pv, signal)) active.add(pv.metadata.annotations?.[CLAIM_NAME] ?? "");
196
174
  }
175
+ const failures: string[] = [];
197
176
  const claims = await api.list("persistentvolumeclaims", namespace, selector, signal);
198
177
  for (const claim of claims) {
199
178
  active.add(claim.metadata.name);
@@ -214,8 +193,20 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
214
193
  !pod.metadata.ownerReferences?.some((owner) => owner.uid === claim.metadata.uid)
215
194
  )
216
195
  throw new Error("Preparation Pod ownership mismatch");
217
- if (pod.status?.phase === "Failed") {
218
- await api.delete("pods", namespace, pod, signal);
196
+ const created = Date.parse(claim.metadata.creationTimestamp ?? "");
197
+ const ageSeconds = Number.isFinite(created)
198
+ ? Math.max(0, Math.floor(((options.now?.() ?? Date.now()) - created) / 1_000))
199
+ : undefined;
200
+ if (
201
+ pod.status?.phase === "Failed" ||
202
+ (pod.status?.phase !== "Succeeded" && ageSeconds !== undefined && ageSeconds >= 900)
203
+ ) {
204
+ // Keep the failed receipt and reservation across restarts. An operator retries
205
+ // the same PVC by deleting its Pod only after fixing storage; never allocate
206
+ // another volume to work around replica scheduling or attach failures.
207
+ failures.push(
208
+ `${namespace}/${pod.metadata.name}: age=${ageSeconds ?? "unknown"}s phase=${pod.status?.phase ?? "unknown"} reason=${pod.status?.reason ?? pod.status?.conditions?.find((condition) => condition.status === "False")?.reason ?? "inspect Pod events and CSI/Longhorn scheduling conditions"}`,
209
+ );
219
210
  continue;
220
211
  }
221
212
  if (pod.status?.phase !== "Succeeded" || !claim.spec.volumeName) continue;
@@ -248,6 +239,11 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
248
239
  [CLAIM_NAME]: claim.metadata.name,
249
240
  [POLICY]: policy,
250
241
  [STATE]: "preparing",
242
+ "leitwerk.dev/preparation-pod-uid": pod.metadata.uid ?? "",
243
+ "leitwerk.dev/preparation-image": options.image,
244
+ "leitwerk.dev/preparation-completed-at": new Date(
245
+ options.now?.() ?? Date.now(),
246
+ ).toISOString(),
251
247
  [TARGET_CLASS]: options.storageClassName,
252
248
  [SIZE]: claim.metadata.annotations?.[SIZE],
253
249
  [MODES]: claim.metadata.annotations?.[MODES],
@@ -336,6 +332,7 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
336
332
  );
337
333
  }
338
334
  }
335
+ if (failures.length) throw new Error(`Volume pool preparation blocked: ${failures.join("; ")}`);
339
336
  }
340
337
 
341
338
  return {
@@ -343,33 +340,6 @@ export function createKubernetesVolumePool(options: VolumePoolOptions) {
343
340
  poolId,
344
341
  /** @internal */
345
342
  reconcile,
346
- /** @internal */
347
- start() {
348
- if (controller) return;
349
- controller = new AbortController();
350
- const { signal } = controller;
351
- running = (async () => {
352
- while (!signal.aborted) {
353
- let interval = 2_000;
354
- try {
355
- await reconcile(signal);
356
- } catch {
357
- interval = 30_000;
358
- if (!signal.aborted) options.onError?.();
359
- }
360
- try {
361
- await delay(interval, undefined, { signal });
362
- } catch {
363
- break;
364
- }
365
- }
366
- })();
367
- },
368
- /** @internal */
369
- async stop() {
370
- controller?.abort();
371
- await running;
372
- controller = undefined;
373
- },
343
+ ...createPreparationController(reconcile, 2_000, options.onError, 30_000),
374
344
  };
375
345
  }
@@ -0,0 +1,139 @@
1
+ import { POOL_LABEL } from "./kubernetes-volume-pool.js";
2
+ import type { VolumePoolApi } from "./kubernetes-volume-pool-api.js";
3
+ import type { ProcessVolumeReclamation } from "./types.js";
4
+
5
+ /** Persist ownership and any terminal disposal authorization before PVC deletion. @internal */
6
+ export async function retireKubernetesProcessVolume(input: {
7
+ /** @internal */
8
+ api: VolumePoolApi;
9
+ /** @internal */
10
+ namespace: string;
11
+ /** @internal */
12
+ name: string;
13
+ /** @internal */
14
+ instanceId: string;
15
+ /** @internal */
16
+ signal: AbortSignal;
17
+ /** @internal */
18
+ reason?: "retention-expired" | "process-deleted";
19
+ /** @internal */
20
+ reclaimBackingStorage?: ProcessVolumeReclamation | "process-deleted";
21
+ }): Promise<void> {
22
+ const { api, namespace, name, instanceId, signal } = input;
23
+ const reclamation = input.reclaimBackingStorage;
24
+ if (
25
+ typeof reclamation === "object" &&
26
+ (!["completed", "aborted"].includes(reclamation.lifecycleStatus) ||
27
+ !Number.isFinite(Date.parse(reclamation.closedAt)) ||
28
+ Date.parse(reclamation.closedAt) > Date.now())
29
+ )
30
+ throw new Error("Backing-storage reclamation requires a closed terminal process");
31
+ if (reclamation === "process-deleted" && input.reason !== "process-deleted")
32
+ throw new Error("Explicit storage deletion requires a process deletion request");
33
+ const pvc = await api.get("persistentvolumeclaims", namespace, name, signal);
34
+ if (!pvc) return;
35
+ const labels = pvc.metadata.labels;
36
+ if (
37
+ !pvc.metadata.uid ||
38
+ labels?.["leitwerk.dev/managed-by"] !== "leitwerk" ||
39
+ labels["leitwerk.dev/component"] !== "process-volume" ||
40
+ labels["leitwerk.dev/instance-id"] !== instanceId ||
41
+ pvc.metadata.ownerReferences?.length
42
+ )
43
+ throw new Error("Cannot retire a foreign or ambiguous process PVC");
44
+ if (reclamation && !pvc.spec.volumeName)
45
+ throw new Error(
46
+ "PVC is still provisioning; preserve its identity until the backing PV can be audited",
47
+ );
48
+ const pods = await api.list("pods", namespace, "", signal);
49
+ if (
50
+ pods.some(
51
+ (pod) =>
52
+ !["Succeeded", "Failed"].includes(pod.status?.phase ?? "") &&
53
+ Array.isArray(pod.spec.volumes) &&
54
+ pod.spec.volumes.some(
55
+ (volume) =>
56
+ (volume as { persistentVolumeClaim?: { claimName?: string } }).persistentVolumeClaim
57
+ ?.claimName === name,
58
+ ),
59
+ )
60
+ )
61
+ throw new Error("Cannot retire a process volume referenced by a live Pod");
62
+ if (pvc.spec.volumeName) {
63
+ const pv = await api.get("persistentvolumes", "", pvc.spec.volumeName, signal);
64
+ if (
65
+ !pv ||
66
+ (pv.metadata.labels?.["leitwerk.dev/managed-by"] !== undefined &&
67
+ pv.metadata.labels["leitwerk.dev/managed-by"] !== "leitwerk") ||
68
+ (pv.metadata.labels?.["leitwerk.dev/instance-id"] !== undefined &&
69
+ pv.metadata.labels["leitwerk.dev/instance-id"] !== instanceId) ||
70
+ pv.metadata.ownerReferences?.length ||
71
+ pv.metadata.deletionTimestamp ||
72
+ pv.spec.claimRef?.uid !== pvc.metadata.uid ||
73
+ pv.spec.claimRef?.name !== name ||
74
+ pv.spec.claimRef?.namespace !== namespace
75
+ )
76
+ throw new Error("Cannot retire a volume with ambiguous claim ownership");
77
+ const csi = pv.spec.csi as { driver?: string; volumeHandle?: string } | undefined;
78
+ if (
79
+ reclamation &&
80
+ (!csi?.driver ||
81
+ !csi.volumeHandle ||
82
+ pv.metadata.annotations?.["pv.kubernetes.io/provisioned-by"] !== csi.driver ||
83
+ !["Retain", "Delete"].includes(pv.spec.persistentVolumeReclaimPolicy ?? ""))
84
+ )
85
+ throw new Error(
86
+ "Backing-storage reclamation requires an owned dynamically provisioned CSI volume",
87
+ );
88
+ const volumeLabels: Record<string, string> = {
89
+ ...pv.metadata.labels,
90
+ "leitwerk.dev/managed-by": "leitwerk",
91
+ "leitwerk.dev/component": "process-volume",
92
+ "leitwerk.dev/instance-id": instanceId,
93
+ ...(reclamation ? { "leitwerk.dev/reclamation": "terminal" } : {}),
94
+ };
95
+ // End pool ownership atomically: a stale pool reconciler must not restore
96
+ // Retain after a fast process closes. Both writers use resourceVersion tests.
97
+ delete volumeLabels[POOL_LABEL];
98
+ await api.patchVolume(
99
+ pv,
100
+ [
101
+ {
102
+ op: "add",
103
+ path: "/metadata/labels",
104
+ value: volumeLabels,
105
+ },
106
+ {
107
+ op: "add",
108
+ path: "/metadata/annotations",
109
+ value: {
110
+ ...pv.metadata.annotations,
111
+ "leitwerk.dev/retirement": JSON.stringify({
112
+ instanceId,
113
+ namespace,
114
+ claimName: name,
115
+ claimUid: pvc.metadata.uid,
116
+ volumeUid: pv.metadata.uid,
117
+ reason: input.reason ?? "retention-expired",
118
+ ...(reclamation
119
+ ? {
120
+ reclamation:
121
+ typeof reclamation === "object"
122
+ ? { policy: "terminal-process", ...reclamation }
123
+ : { policy: "process-deletion" },
124
+ }
125
+ : {}),
126
+ }),
127
+ },
128
+ },
129
+ // Arm CSI reclamation before deleting the claim. A crash after this
130
+ // patch is safe: retry either repeats it or CSI completes independently.
131
+ ...(reclamation
132
+ ? [{ op: "add", path: "/spec/persistentVolumeReclaimPolicy", value: "Delete" }]
133
+ : []),
134
+ ],
135
+ signal,
136
+ );
137
+ }
138
+ await api.delete("persistentvolumeclaims", namespace, pvc, signal);
139
+ }
@@ -4,6 +4,10 @@ import {
4
4
  exportHelperEnvironment,
5
5
  } from "./helper-process-state-exporter.js";
6
6
  import type { KubernetesApiClient } from "./kubernetes-api-client.js";
7
+ import {
8
+ createKubernetesImagePreload,
9
+ type ImagePreparationEvent,
10
+ } from "./kubernetes-image-preload.js";
7
11
  import {
8
12
  buildKubernetesDockerConfigJsonSecretManifest,
9
13
  buildKubernetesExportHelperPodManifest,
@@ -23,8 +27,10 @@ import {
23
27
  redactKubernetesDiagnostic,
24
28
  volumeRefFromPvc,
25
29
  } from "./kubernetes-manifests.js";
30
+ import { createKubernetesPreparation } from "./kubernetes-preparation.js";
26
31
  import { sampleKubernetesStartup, startupReceipt } from "./kubernetes-startup-sampler.js";
27
32
  import { createKubernetesVolumePool } from "./kubernetes-volume-pool.js";
33
+ import { retireKubernetesProcessVolume } from "./kubernetes-volume-retirement.js";
28
34
  import { UnitExitNotifier } from "./runner-utils.js";
29
35
  import {
30
36
  SESSION_TRANSFER_HELPER_ENTRY_PATH,
@@ -68,12 +74,21 @@ function boundedKubernetesStartDiagnostic(
68
74
 
69
75
  /** @internal */
70
76
  export interface KubernetesWorkerRunnerOptions {
77
+ /** Enable CSI backing reclamation for explicit process deletion. @internal */
78
+ reclaimOnClose?: boolean;
79
+ /** @internal */
80
+ imagePreload?: {
81
+ /** @internal */
82
+ images: string[];
83
+ /** @internal */
84
+ onEvent?: (event: ImagePreparationEvent) => void;
85
+ };
71
86
  /** @internal */
72
87
  preProvision?: {
73
88
  /** @internal */
74
89
  count: number;
75
90
  /** @internal */
76
- onError?: () => void;
91
+ onError?: (error?: unknown) => void;
77
92
  };
78
93
  /** @internal */
79
94
  client: KubernetesApiClient;
@@ -124,7 +139,7 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
124
139
  /** @internal */
125
140
  exporter: ProcessStateExporter;
126
141
  /** @internal */
127
- volumePool?: ReturnType<typeof createKubernetesVolumePool>;
142
+ preparation?: ReturnType<typeof createKubernetesPreparation>;
128
143
  } {
129
144
  if (!options.serverUrl || !options.exporterImage || !options.helperRelays) {
130
145
  throw new Error("Kubernetes transfer exporter is not configured");
@@ -134,6 +149,15 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
134
149
  const exporterImage = options.exporterImage;
135
150
  const helperRelays = options.helperRelays;
136
151
  const serverCaFile = options.serverCaFile?.trim();
152
+ const serverCaConfig = serverCaFile
153
+ ? {
154
+ serverCaConfigMap: {
155
+ name: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,
156
+ key: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,
157
+ mountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,
158
+ },
159
+ }
160
+ : {};
137
161
  const namespaceForProcess = (instanceId: string) =>
138
162
  kubernetesProcessNamespaceName(instanceId, options.processNamespacePrefix);
139
163
  const delay =
@@ -147,7 +171,7 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
147
171
  const namespaceManifest = buildKubernetesProcessNamespaceManifest({
148
172
  instanceId,
149
173
  processNamespacePrefix: options.processNamespacePrefix,
150
- ...(requirements?.docker && options.docker?.gvisor
174
+ ...(requirements?.docker && options.docker?.isolation
151
175
  ? { extraLabels: { "pod-security.kubernetes.io/enforce": "privileged" } }
152
176
  : {}),
153
177
  });
@@ -242,7 +266,20 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
242
266
  namespace: manifest.metadata.namespace,
243
267
  });
244
268
  },
245
- async release(instanceId) {
269
+ async release(instanceId, releaseOptions) {
270
+ if (client.volumePool) {
271
+ await retireKubernetesProcessVolume({
272
+ api: client.volumePool,
273
+ namespace: namespaceForProcess(instanceId),
274
+ name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
275
+ instanceId,
276
+ signal: AbortSignal.timeout(30_000),
277
+ reclaimBackingStorage: releaseOptions?.reclaimBackingStorage,
278
+ });
279
+ return;
280
+ }
281
+ if (releaseOptions?.reclaimBackingStorage)
282
+ throw new Error("Backing-storage reclamation requires Kubernetes volume inspection");
246
283
  await client.deletePersistentVolumeClaim(
247
284
  kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
248
285
  namespaceForProcess(instanceId),
@@ -251,6 +288,17 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
251
288
  async deleteProcessResources(instanceId) {
252
289
  samplers.get(instanceId)?.stop();
253
290
  samplers.delete(instanceId);
291
+ if (client.volumePool) {
292
+ await retireKubernetesProcessVolume({
293
+ api: client.volumePool,
294
+ namespace: namespaceForProcess(instanceId),
295
+ name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
296
+ instanceId,
297
+ reason: "process-deleted",
298
+ reclaimBackingStorage: options.reclaimOnClose ? "process-deleted" : undefined,
299
+ signal: AbortSignal.timeout(30_000),
300
+ });
301
+ }
254
302
  await client.deleteNamespace(namespaceForProcess(instanceId));
255
303
  },
256
304
  };
@@ -348,15 +396,7 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
348
396
  namespace: processNamespace,
349
397
  ...(options.pod ?? {}),
350
398
  ...(input.docker && options.docker ? { docker: options.docker } : {}),
351
- ...(serverCaFile
352
- ? {
353
- serverCaConfigMap: {
354
- name: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,
355
- key: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,
356
- mountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,
357
- },
358
- }
359
- : {}),
399
+ ...serverCaConfig,
360
400
  });
361
401
  observer?.report("allocating_runtime");
362
402
  try {
@@ -483,15 +523,7 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
483
523
  namespace,
484
524
  ...(options.pod ?? {}),
485
525
  imagePullPolicy: options.exporterImagePullPolicy,
486
- ...(serverCaFile
487
- ? {
488
- serverCaConfigMap: {
489
- name: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,
490
- key: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,
491
- mountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,
492
- },
493
- }
494
- : {}),
526
+ ...serverCaConfig,
495
527
  },
496
528
  );
497
529
  await client.createPod(manifest);
@@ -518,6 +550,10 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
518
550
  },
519
551
  });
520
552
 
553
+ const preparationPullSecrets = (options.pod?.imagePullSecrets ?? []).map(
554
+ (name) =>
555
+ options.imagePullSecretCopies?.find((copy) => copy.targetName === name)?.sourceName ?? name,
556
+ );
521
557
  let volumePool: ReturnType<typeof createKubernetesVolumePool> | undefined;
522
558
  if (options.preProvision) {
523
559
  if (!client.volumePool || !options.volume.storageClassName || !options.serverNamespace) {
@@ -532,14 +568,28 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
532
568
  ...options.preProvision,
533
569
  image: exporterImage,
534
570
  imagePullPolicy: options.exporterImagePullPolicy,
535
- imagePullSecrets: (options.pod?.imagePullSecrets ?? []).map(
536
- (name) =>
537
- options.imagePullSecretCopies?.find((copy) => copy.targetName === name)?.sourceName ??
538
- name,
539
- ),
571
+ imagePullSecrets: preparationPullSecrets,
572
+ nodeSelector: options.pod?.nodeSelector,
573
+ tolerations: options.pod?.tolerations,
574
+ });
575
+ }
576
+ let imagePreload: ReturnType<typeof createKubernetesImagePreload> | undefined;
577
+ if (options.imagePreload) {
578
+ if (!client.imagePreload || !options.serverNamespace)
579
+ throw new Error("Image preloading requires an API and server namespace");
580
+ imagePreload = createKubernetesImagePreload({
581
+ api: client.imagePreload,
582
+ namespace: options.serverNamespace,
583
+ ...options.imagePreload,
584
+ imagePullSecrets: preparationPullSecrets,
540
585
  nodeSelector: options.pod?.nodeSelector,
586
+ additionalNodeSelectors: options.docker
587
+ ? [{ ...options.pod?.nodeSelector, ...options.docker.nodeSelector }]
588
+ : undefined,
541
589
  tolerations: options.pod?.tolerations,
542
590
  });
543
591
  }
544
- return { runner, volume, exporter, volumePool };
592
+ const controllers = [volumePool, imagePreload].filter((value) => value !== undefined);
593
+ const preparation = controllers.length ? createKubernetesPreparation(controllers) : undefined;
594
+ return { runner, volume, exporter, preparation };
545
595
  }