@catamorphic/work-server 0.1.0-alpha.39 → 0.1.0-alpha.42

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 (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
@@ -0,0 +1,1065 @@
1
+ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
2
+ import {
3
+ isProjectPrincipal,
4
+ PLACEMENT_WAIT_FRESH_SECONDS,
5
+ type WorkerNode,
6
+ type WorkerNodesService,
7
+ } from "@catamorphic/core";
8
+ import type { DB } from "@catamorphic/db";
9
+ import { parseSignInCapability } from "@catamorphic/sandbox";
10
+ import {
11
+ type Kysely,
12
+ type Selectable,
13
+ sql,
14
+ type Transaction,
15
+ type UpdateObject,
16
+ } from "kysely";
17
+ import { z } from "zod";
18
+ import {
19
+ DEFAULT_LOST_AFTER_MINUTES,
20
+ type MachineFacts,
21
+ type MachinePrincipal,
22
+ type MachineState,
23
+ type MachineVerb,
24
+ normalizePrincipals,
25
+ type WaitingWork,
26
+ } from "../machines/contract.js";
27
+ import {
28
+ lostAfterMsOf,
29
+ type MachinePhase,
30
+ type MachineRecord,
31
+ machineStateOf,
32
+ type PlannedMachine,
33
+ } from "../machines/sequencer.js";
34
+ import {
35
+ type ScheduledPlacement,
36
+ storedPlacement,
37
+ type WorkerPlacement,
38
+ } from "./placement.js";
39
+
40
+ export const WORKER_NODE_PREFIX = "worker.";
41
+
42
+ /** Minutes an enrollment code works; a machine still starting keeps its code. */
43
+ const ENROLLMENT_MINUTES = 60;
44
+
45
+ type MachineRow = Selectable<DB["work_machines"]>;
46
+
47
+ const PHASES: readonly MachinePhase[] = [
48
+ "starting",
49
+ "running",
50
+ "stopping",
51
+ "stopped",
52
+ "resuming",
53
+ "destroying",
54
+ ];
55
+
56
+ function phaseOf(value: string): MachinePhase {
57
+ return PHASES.find((phase) => phase === value) ?? "starting";
58
+ }
59
+
60
+ const VERBS: readonly MachineVerb[] = [
61
+ "create",
62
+ "destroy",
63
+ "stop",
64
+ "start",
65
+ "describe",
66
+ ];
67
+
68
+ const OptionsSchema = z.record(z.string(), z.unknown());
69
+
70
+ const WaitPool = z.record(z.string(), z.string());
71
+ const WaitRequirements = z.object({
72
+ resources: z
73
+ .object({
74
+ cpuMillis: z.number().optional(),
75
+ memoryMb: z.number().optional(),
76
+ storageMb: z.number().optional(),
77
+ gpu: z.boolean().optional(),
78
+ })
79
+ .default({}),
80
+ capabilities: z.array(z.string()).default([]),
81
+ isolation: z.enum(["none", "process", "sandbox"]).optional(),
82
+ });
83
+
84
+ /**
85
+ * The machines Work knows (ADR 0349), in Postgres: one row per name from
86
+ * the moment its intent is recorded until its platform confirmed it gone.
87
+ * Nothing about a machine lives in a replica's memory.
88
+ */
89
+ export class MachineStore {
90
+ constructor(
91
+ private readonly deps: {
92
+ db: Kysely<DB>;
93
+ nodes: WorkerNodesService;
94
+ tenantId: string;
95
+ authorityId: string;
96
+ /**
97
+ * Derives the enrollment code of a machine the hook makes, so every
98
+ * replica repeats its create with one code and none is stored.
99
+ */
100
+ enrollmentSecret: string;
101
+ /** Minutes unseen that make a machine lost when its plan gives none. */
102
+ lostMinutes?: number;
103
+ },
104
+ ) {}
105
+
106
+ get defaultLostMinutes(): number {
107
+ return this.deps.lostMinutes ?? DEFAULT_LOST_AFTER_MINUTES;
108
+ }
109
+
110
+ /** A machine's row, if Work knows it. */
111
+ async row(args: {
112
+ name: string;
113
+ transaction?: Transaction<DB>;
114
+ }): Promise<MachineRow | undefined> {
115
+ return (args.transaction ?? this.deps.db)
116
+ .selectFrom("work_machines")
117
+ .selectAll()
118
+ .where("tenant_id", "=", this.deps.tenantId)
119
+ .where("name", "=", args.name)
120
+ .executeTakeFirst();
121
+ }
122
+
123
+ /**
124
+ * The enrollment code of a machine the hook makes: derived from the
125
+ * server's secret, its name and a nonce, so it is the same wherever it
126
+ * is asked for and only its hash is stored.
127
+ */
128
+ private code(args: { name: string; nonce: string }): string {
129
+ const mac = createHmac("sha256", this.deps.enrollmentSecret)
130
+ .update(
131
+ `work-machine-enrollment\0${this.deps.tenantId}\0${args.name}\0${args.nonce}`,
132
+ )
133
+ .digest("base64url");
134
+ return `wke_${mac.slice(0, 32)}`;
135
+ }
136
+
137
+ /**
138
+ * Record the intent to make a machine (ADR 0349): its row and a new
139
+ * enrollment, under the name's lock, so replicas asking at once record
140
+ * one. False when the name is known already.
141
+ */
142
+ async intend(args: { machine: PlannedMachine }): Promise<boolean> {
143
+ const { machine } = args;
144
+ return this.deps.db.transaction().execute(async (trx) => {
145
+ await this.lockName({ name: machine.name, transaction: trx });
146
+ if (await this.row({ name: machine.name, transaction: trx }))
147
+ return false;
148
+ const enrolled = await trx
149
+ .selectFrom("work_workers")
150
+ .select("node_id")
151
+ .where("tenant_id", "=", this.deps.tenantId)
152
+ .where("name", "=", machine.name)
153
+ .where("revoked_at", "is", null)
154
+ .executeTakeFirst();
155
+ if (enrolled) return false;
156
+ const nonce = randomBytes(16).toString("hex");
157
+ const key = hash(this.code({ name: machine.name, nonce }));
158
+ await trx
159
+ .insertInto("work_machines")
160
+ .values({
161
+ tenant_id: this.deps.tenantId,
162
+ name: machine.name,
163
+ managed: true,
164
+ enrollment_nonce: nonce,
165
+ idempotency_key: key,
166
+ labels: JSON.stringify(machine.labels),
167
+ serves: machine.for === null ? null : JSON.stringify(machine.for),
168
+ trusted: machine.trusted,
169
+ options: JSON.stringify(machine.options),
170
+ lost_after_minutes: machine.lostAfterMinutes,
171
+ reason: machine.reason,
172
+ phase: "starting",
173
+ })
174
+ .execute();
175
+ await this.insertEnrollment({
176
+ name: machine.name,
177
+ key,
178
+ transaction: trx,
179
+ });
180
+ return true;
181
+ });
182
+ }
183
+
184
+ /**
185
+ * The enrollment a machine's create is asked with, the same on every
186
+ * pass; its code keeps working while the machine is still starting.
187
+ */
188
+ async enrollment(args: {
189
+ name: string;
190
+ }): Promise<{ code: string; idempotencyKey: string } | null> {
191
+ const row = await this.row(args);
192
+ if (!row?.enrollment_nonce || !row.idempotency_key) return null;
193
+ await this.deps.db
194
+ .updateTable("work_worker_enrollments")
195
+ .set({
196
+ expires_at: sql`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`,
197
+ })
198
+ .where("tenant_id", "=", this.deps.tenantId)
199
+ .where("code_hash", "=", row.idempotency_key)
200
+ .where("used_at", "is", null)
201
+ .execute();
202
+ return {
203
+ code: this.code({ name: args.name, nonce: row.enrollment_nonce }),
204
+ idempotencyKey: row.idempotency_key,
205
+ };
206
+ }
207
+
208
+ /** A new enrollment, and so a new idempotency key, after a refusal. */
209
+ async reissue(args: { name: string }): Promise<void> {
210
+ await this.deps.db.transaction().execute(async (trx) => {
211
+ await this.lockName({ name: args.name, transaction: trx });
212
+ const row = await this.row({ name: args.name, transaction: trx });
213
+ if (!row?.managed || row.enrollment_nonce || row.phase !== "starting")
214
+ return;
215
+ const nonce = randomBytes(16).toString("hex");
216
+ const key = hash(this.code({ name: args.name, nonce }));
217
+ await trx
218
+ .updateTable("work_machines")
219
+ .set({
220
+ enrollment_nonce: nonce,
221
+ idempotency_key: key,
222
+ updated_at: sql`now()`,
223
+ })
224
+ .where("tenant_id", "=", this.deps.tenantId)
225
+ .where("name", "=", args.name)
226
+ .execute();
227
+ await this.insertEnrollment({ name: args.name, key, transaction: trx });
228
+ });
229
+ }
230
+
231
+ private async insertEnrollment(args: {
232
+ name: string;
233
+ key: string;
234
+ transaction: Transaction<DB>;
235
+ }): Promise<void> {
236
+ await args.transaction
237
+ .deleteFrom("work_worker_enrollments")
238
+ .where("tenant_id", "=", this.deps.tenantId)
239
+ .where("name", "=", args.name)
240
+ .where("used_at", "is", null)
241
+ .execute();
242
+ await args.transaction
243
+ .insertInto("work_worker_enrollments")
244
+ .values({
245
+ code_hash: args.key,
246
+ tenant_id: this.deps.tenantId,
247
+ name: args.name,
248
+ expires_at: sql<Date>`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`,
249
+ })
250
+ .execute();
251
+ }
252
+
253
+ /** One issuer or enroller per name at a time, across replicas, until commit. */
254
+ async lockName(args: {
255
+ name: string;
256
+ transaction: Transaction<DB>;
257
+ }): Promise<void> {
258
+ await sql`SELECT pg_advisory_xact_lock(hashtext(${`work-worker-name:${this.deps.tenantId}:${args.name}`}))`.execute(
259
+ args.transaction,
260
+ );
261
+ }
262
+
263
+ async created(args: { name: string; ref: string }): Promise<void> {
264
+ await this.update(args.name, {
265
+ ref: args.ref,
266
+ refused_count: 0,
267
+ refused_at: null,
268
+ });
269
+ }
270
+
271
+ /**
272
+ * The platform made nothing: the code is withdrawn, and a later pass
273
+ * asks again with a new one. A machine that enrolled anyway keeps its
274
+ * code; only the failure is recorded.
275
+ */
276
+ async refused(args: { name: string; reason: string }): Promise<void> {
277
+ await this.deps.db.transaction().execute(async (trx) => {
278
+ await this.lockName({ name: args.name, transaction: trx });
279
+ const row = await this.row({ name: args.name, transaction: trx });
280
+ if (!row) return;
281
+ const failure = {
282
+ last_error: `Its platform refused: ${args.reason}`.slice(0, 4_000),
283
+ last_error_verb: "create",
284
+ last_error_at: sql<Date>`now()`,
285
+ updated_at: sql<Date>`now()`,
286
+ };
287
+ const withdrawn = row.idempotency_key
288
+ ? await trx
289
+ .deleteFrom("work_worker_enrollments")
290
+ .where("tenant_id", "=", this.deps.tenantId)
291
+ .where("code_hash", "=", row.idempotency_key)
292
+ .where("used_at", "is", null)
293
+ .returning("code_hash")
294
+ .executeTakeFirst()
295
+ : undefined;
296
+ await trx
297
+ .updateTable("work_machines")
298
+ .set(
299
+ withdrawn
300
+ ? {
301
+ ...failure,
302
+ enrollment_nonce: null,
303
+ idempotency_key: null,
304
+ refused_count: sql<number>`refused_count + 1`,
305
+ refused_at: sql<Date>`now()`,
306
+ }
307
+ : failure,
308
+ )
309
+ .where("tenant_id", "=", this.deps.tenantId)
310
+ .where("name", "=", args.name)
311
+ .execute();
312
+ });
313
+ }
314
+
315
+ async configure(args: {
316
+ name: string;
317
+ labels: Readonly<Record<string, string>>;
318
+ trusted: boolean;
319
+ reason: string | null;
320
+ lostAfterMinutes: number | null;
321
+ }): Promise<void> {
322
+ await this.updatePlacement(args.name, {
323
+ labels: JSON.stringify(args.labels),
324
+ trusted: args.trusted,
325
+ reason: args.reason,
326
+ lost_after_minutes: args.lostAfterMinutes,
327
+ });
328
+ }
329
+
330
+ /** Whom a machine is for from now on; ends a reset no longer wanted. */
331
+ async setFor(args: {
332
+ name: string;
333
+ for: readonly MachinePrincipal[] | null;
334
+ }): Promise<void> {
335
+ await this.updatePlacement(args.name, {
336
+ serves: principalsJson(args.for),
337
+ reset_pending: false,
338
+ reset_serves: null,
339
+ });
340
+ }
341
+
342
+ async beginReset(args: {
343
+ name: string;
344
+ for: readonly MachinePrincipal[] | null;
345
+ }): Promise<void> {
346
+ await this.updatePlacement(args.name, {
347
+ reset_pending: true,
348
+ reset_serves: principalsJson(args.for),
349
+ });
350
+ }
351
+
352
+ /** A reset machine is for whom it was being reset for. */
353
+ async finishReset(args: { name: string }): Promise<void> {
354
+ await this.updatePlacement(args.name, {
355
+ serves: sql`CASE WHEN reset_pending THEN reset_serves ELSE serves END`,
356
+ reset_pending: false,
357
+ reset_serves: null,
358
+ });
359
+ }
360
+
361
+ async setDropped(args: { name: string; dropped: boolean }): Promise<void> {
362
+ await this.updatePlacement(args.name, {
363
+ dropped_at: args.dropped ? sql<Date>`coalesce(dropped_at, now())` : null,
364
+ });
365
+ }
366
+
367
+ async openPlacement({ name }: { name: string }): Promise<void> {
368
+ await this.updatePlacement(name, {}, { onlyWhenUnopened: true });
369
+ }
370
+
371
+ /** Move a machine to a phase, in the caller's transaction when given. */
372
+ async setPhase(args: {
373
+ name: string;
374
+ phase: MachinePhase;
375
+ from?: readonly MachinePhase[];
376
+ lost?: boolean;
377
+ at?: string;
378
+ transaction?: Transaction<DB>;
379
+ }): Promise<boolean> {
380
+ const moved = await (args.transaction ?? this.deps.db)
381
+ .updateTable("work_machines")
382
+ .set({
383
+ phase: args.phase,
384
+ phase_since: args.at === undefined ? sql`now()` : new Date(args.at),
385
+ verb_done_at: null,
386
+ updated_at: sql`now()`,
387
+ ...(args.phase === "destroying"
388
+ ? {
389
+ destroy_requested_at: sql<Date>`coalesce(destroy_requested_at, now())`,
390
+ }
391
+ : {}),
392
+ ...(args.lost ? { lost_at: sql<Date>`coalesce(lost_at, now())` } : {}),
393
+ ...(args.phase === "running" ? { lost_at: null } : {}),
394
+ })
395
+ .where("tenant_id", "=", this.deps.tenantId)
396
+ .where("name", "=", args.name)
397
+ .where("phase", "!=", args.phase)
398
+ .$if(args.from !== undefined, (query) =>
399
+ query.where("phase", "in", [...(args.from ?? [])]),
400
+ )
401
+ .returning("name")
402
+ .executeTakeFirst();
403
+ return Boolean(moved);
404
+ }
405
+
406
+ async startAsked(args: { name: string }): Promise<void> {
407
+ await this.deps.db
408
+ .updateTable("work_machines")
409
+ .set({ verb_done_at: sql`now()`, updated_at: sql`now()` })
410
+ .where("tenant_id", "=", this.deps.tenantId)
411
+ .where("name", "=", args.name)
412
+ .where("phase", "=", "resuming")
413
+ .execute();
414
+ }
415
+
416
+ /** Its platform confirmed it gone: Work knows it no more. */
417
+ async forget(args: {
418
+ name: string;
419
+ transaction?: Transaction<DB>;
420
+ }): Promise<void> {
421
+ const db = args.transaction ?? this.deps.db;
422
+ await db
423
+ .deleteFrom("work_machines")
424
+ .where("tenant_id", "=", this.deps.tenantId)
425
+ .where("name", "=", args.name)
426
+ .execute();
427
+ await db
428
+ .deleteFrom("work_worker_enrollments")
429
+ .where("tenant_id", "=", this.deps.tenantId)
430
+ .where("name", "=", args.name)
431
+ .where("used_at", "is", null)
432
+ .execute();
433
+ }
434
+
435
+ async note(args: { name: string; notice: string | null }): Promise<void> {
436
+ await this.update(args.name, { notice: args.notice });
437
+ }
438
+
439
+ async failed(args: {
440
+ name: string;
441
+ verb: MachineVerb;
442
+ message: string;
443
+ }): Promise<void> {
444
+ await this.update(args.name, {
445
+ last_error: args.message.slice(0, 4_000),
446
+ last_error_verb: args.verb,
447
+ last_error_at: sql<Date>`now()`,
448
+ });
449
+ }
450
+
451
+ async succeeded(args: { name: string; verb: MachineVerb }): Promise<void> {
452
+ await this.deps.db
453
+ .updateTable("work_machines")
454
+ .set({ last_error: null, last_error_verb: null, last_error_at: null })
455
+ .where("tenant_id", "=", this.deps.tenantId)
456
+ .where("name", "=", args.name)
457
+ .where("last_error_verb", "=", args.verb)
458
+ .execute();
459
+ }
460
+
461
+ /** What the latest plan said, for the machines listing on every replica. */
462
+ async planned(args: { error: string | null }): Promise<void> {
463
+ const values = args.error
464
+ ? { error: args.error.slice(0, 4_000), error_at: sql<Date>`now()` }
465
+ : { planned_at: sql<Date>`now()`, error: null, error_at: null };
466
+ await this.deps.db
467
+ .insertInto("work_machine_plans")
468
+ .values({ tenant_id: this.deps.tenantId, ...values })
469
+ .onConflict((conflict) =>
470
+ conflict.column("tenant_id").doUpdateSet(values),
471
+ )
472
+ .execute();
473
+ }
474
+
475
+ async plan(): Promise<{
476
+ plannedAt: string | null;
477
+ error: { message: string; at: string } | null;
478
+ }> {
479
+ const row = await this.deps.db
480
+ .selectFrom("work_machine_plans")
481
+ .selectAll()
482
+ .where("tenant_id", "=", this.deps.tenantId)
483
+ .executeTakeFirst();
484
+ return {
485
+ plannedAt: row?.planned_at?.toISOString() ?? null,
486
+ error:
487
+ row?.error && row.error_at
488
+ ? { message: row.error, at: row.error_at.toISOString() }
489
+ : null,
490
+ };
491
+ }
492
+
493
+ /** Fence placement decisions under the same node lock as an Allocation. */
494
+ private async updatePlacement(
495
+ name: string,
496
+ values: UpdateObject<DB, "work_machines">,
497
+ options: { onlyWhenUnopened?: boolean } = {},
498
+ ): Promise<void> {
499
+ const { db, tenantId } = this.deps;
500
+ const nodeId = `${WORKER_NODE_PREFIX}${name}`;
501
+ await db.transaction().execute(async (trx) => {
502
+ const node = await trx
503
+ .selectFrom("worker_nodes")
504
+ .select(["id", "admission_revision"])
505
+ .where("id", "=", nodeId)
506
+ .where("tenant_id", "=", tenantId)
507
+ .forUpdate()
508
+ .executeTakeFirst();
509
+ if (options.onlyWhenUnopened && (!node || node.admission_revision))
510
+ return;
511
+ const updated = await trx
512
+ .updateTable("work_machines")
513
+ .set({ ...values, updated_at: sql`now()` })
514
+ .where("tenant_id", "=", tenantId)
515
+ .where("name", "=", name)
516
+ .returning(["reset_pending", "dropped_at", "phase"])
517
+ .executeTakeFirst();
518
+ if (node && updated)
519
+ await trx
520
+ .updateTable("worker_nodes")
521
+ .set({
522
+ admission_revision:
523
+ updated.reset_pending ||
524
+ updated.dropped_at ||
525
+ updated.phase !== "running"
526
+ ? null
527
+ : randomUUID(),
528
+ })
529
+ .where("id", "=", node.id)
530
+ .execute();
531
+ });
532
+ }
533
+
534
+ private async update(
535
+ name: string,
536
+ values: UpdateObject<DB, "work_machines">,
537
+ ): Promise<void> {
538
+ await this.deps.db
539
+ .updateTable("work_machines")
540
+ .set({ ...values, updated_at: sql`now()` })
541
+ .where("tenant_id", "=", this.deps.tenantId)
542
+ .where("name", "=", name)
543
+ .execute();
544
+ }
545
+
546
+ /** One machine's placement, as its worker's connection is checked against. */
547
+ async placementOf(args: { name: string }): Promise<WorkerPlacement> {
548
+ const row = await this.row(args);
549
+ if (!row) throw new Error(`Work knows no machine named '${args.name}'`);
550
+ return storedPlacement(row);
551
+ }
552
+
553
+ /**
554
+ * Placement of every machine, by node, for the scheduler. A machine the
555
+ * plan dropped, one stopping, stopped or resuming, and one waiting for
556
+ * its reset take no new work; the Allocations one already holds keep
557
+ * reaching it.
558
+ */
559
+ async placements(): Promise<Map<string, ScheduledPlacement>> {
560
+ const rows = await this.deps.db
561
+ .selectFrom("work_machines as machine")
562
+ .innerJoin("worker_nodes as node", (join) =>
563
+ join
564
+ .onRef("node.tenant_id", "=", "machine.tenant_id")
565
+ .on(
566
+ "node.id",
567
+ "=",
568
+ sql<string>`${WORKER_NODE_PREFIX} || machine.name`,
569
+ ),
570
+ )
571
+ .select([
572
+ "machine.name",
573
+ "machine.labels",
574
+ "machine.serves",
575
+ "machine.trusted",
576
+ "machine.phase",
577
+ "machine.dropped_at",
578
+ "machine.reset_pending",
579
+ "node.admission_revision",
580
+ ])
581
+ .where("machine.tenant_id", "=", this.deps.tenantId)
582
+ .execute();
583
+ return new Map(
584
+ rows.map((row) => [
585
+ `${WORKER_NODE_PREFIX}${row.name}`,
586
+ {
587
+ ...storedPlacement(row),
588
+ admissionRevision: row.admission_revision,
589
+ accepting:
590
+ row.phase === "running" &&
591
+ row.admission_revision !== null &&
592
+ row.dropped_at === null &&
593
+ !row.reset_pending,
594
+ },
595
+ ]),
596
+ );
597
+ }
598
+
599
+ /**
600
+ * Every machine with its facts (ADR 0349): what Work stores, its
601
+ * worker's lease and report, and what it holds, read by the database's
602
+ * clock so every replica and listing agree.
603
+ */
604
+ async records(): Promise<MachineRecord[]> {
605
+ const { db, tenantId } = this.deps;
606
+ const [rows, workers, nodes, holdings, loads, clock] = await Promise.all([
607
+ db
608
+ .selectFrom("work_machines")
609
+ .selectAll()
610
+ .where("tenant_id", "=", tenantId)
611
+ .orderBy("name")
612
+ .execute(),
613
+ db
614
+ .selectFrom("work_workers")
615
+ .select(["name", "enrolled_at", "last_seen_at", "revoked_at"])
616
+ .where("tenant_id", "=", tenantId)
617
+ .execute(),
618
+ this.deps.nodes.list({ tenantId, authorityId: this.deps.authorityId }),
619
+ db
620
+ .selectFrom("execution_allocations as allocation")
621
+ .leftJoin("agent_sessions as session", (join) =>
622
+ join
623
+ .onRef("session.id", "=", "allocation.root_workload_id")
624
+ .on("allocation.workload_kind", "=", "agent"),
625
+ )
626
+ .select([
627
+ "allocation.worker_node_id",
628
+ "allocation.project_id",
629
+ "session.external_user_id",
630
+ "session.chat_key",
631
+ ])
632
+ .where("allocation.tenant_id", "=", tenantId)
633
+ .where("allocation.status", "=", "active")
634
+ .where("allocation.worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
635
+ .execute(),
636
+ db
637
+ .selectFrom("execution_allocations")
638
+ .select([
639
+ "worker_node_id",
640
+ sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as(
641
+ "holding",
642
+ ),
643
+ sql<Date | null>`max(capacity_released_at)`.as("last_released"),
644
+ ])
645
+ .where("tenant_id", "=", tenantId)
646
+ .where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
647
+ .groupBy("worker_node_id")
648
+ .execute(),
649
+ sql<{ now: Date }>`SELECT now() AS now`.execute(db),
650
+ ]);
651
+ const now = clock.rows[0]?.now ?? new Date();
652
+ const workerOf = new Map(workers.map((worker) => [worker.name, worker]));
653
+ const nodeOf = new Map(nodes.map((node) => [node.id, node]));
654
+ const loadOf = new Map(loads.map((load) => [load.worker_node_id, load]));
655
+ return rows.map((row) => {
656
+ const nodeId = `${WORKER_NODE_PREFIX}${row.name}`;
657
+ const worker = workerOf.get(row.name);
658
+ const node = nodeOf.get(nodeId);
659
+ const load = loadOf.get(nodeId);
660
+ const held = holdings.filter((entry) => entry.worker_node_id === nodeId);
661
+ const phase = phaseOf(row.phase);
662
+ const seen =
663
+ worker?.last_seen_at ?? worker?.enrolled_at ?? row.phase_since;
664
+ const lostAfterMs = lostAfterMsOf({
665
+ lostAfterMinutes: row.lost_after_minutes,
666
+ defaultMinutes: this.defaultLostMinutes,
667
+ });
668
+ const state = machineStateOf({
669
+ phase,
670
+ dropped: row.dropped_at !== null || row.reset_pending,
671
+ disabled: row.disabled_at !== null,
672
+ live: Boolean(node?.available) && !worker?.revoked_at,
673
+ unseenForMs: now.getTime() - seen.getTime(),
674
+ lostAfterMs,
675
+ startAskedForMs: row.verb_done_at
676
+ ? now.getTime() - row.verb_done_at.getTime()
677
+ : null,
678
+ });
679
+ const placement = storedPlacement(row);
680
+ const everConnected = phase !== "starting";
681
+ const facts: MachineFacts = {
682
+ name: row.name,
683
+ ref: row.ref,
684
+ managed: row.managed,
685
+ state,
686
+ since: sinceOf({ row, state, seen }).toISOString(),
687
+ labels: placement.labels,
688
+ for: placement.for,
689
+ trusted: placement.trusted,
690
+ options: OptionsSchema.parse(row.options),
691
+ reason: row.reason,
692
+ holding: {
693
+ workspaces: held.length,
694
+ for: normalizePrincipals(
695
+ held.map((entry) =>
696
+ entry.external_user_id &&
697
+ !isProjectPrincipal(entry.external_user_id)
698
+ ? { user: entry.external_user_id }
699
+ : entry.chat_key
700
+ ? { project: entry.project_id, key: entry.chat_key }
701
+ : { project: entry.project_id },
702
+ ),
703
+ ),
704
+ },
705
+ idleSince:
706
+ (state === "serving" || state === "draining") &&
707
+ Number(load?.holding ?? 0) === 0
708
+ ? latest([
709
+ row.phase_since,
710
+ load?.last_released ?? null,
711
+ worker?.enrolled_at ?? null,
712
+ ]).toISOString()
713
+ : null,
714
+ lastSeenAt: worker?.last_seen_at?.toISOString() ?? null,
715
+ capacity: everConnected && node?.capacity ? node.capacity : null,
716
+ usage: everConnected && node ? node.usage : null,
717
+ disk: everConnected && node?.disk ? diskFacts(node) : null,
718
+ isolation: everConnected ? isolationOf(node) : null,
719
+ signedIn: signedInOf(node),
720
+ notice: row.notice,
721
+ lastError:
722
+ row.last_error && row.last_error_at
723
+ ? {
724
+ verb:
725
+ VERBS.find((verb) => verb === row.last_error_verb) ??
726
+ "create",
727
+ message: row.last_error,
728
+ at: row.last_error_at.toISOString(),
729
+ }
730
+ : null,
731
+ };
732
+ return {
733
+ facts,
734
+ phase,
735
+ phaseSince: row.phase_since.toISOString(),
736
+ idempotencyKey: row.idempotency_key,
737
+ dropped: row.dropped_at !== null,
738
+ refused:
739
+ row.refused_count > 0 && row.refused_at
740
+ ? { count: row.refused_count, at: row.refused_at.toISOString() }
741
+ : null,
742
+ reset: row.reset_pending
743
+ ? { for: storedPlacement({ ...row, serves: row.reset_serves }).for }
744
+ : null,
745
+ startAsked: row.verb_done_at !== null,
746
+ destroyRequestedAt: row.destroy_requested_at?.toISOString() ?? null,
747
+ lostAfterMinutes: row.lost_after_minutes,
748
+ revoked: Boolean(worker?.revoked_at),
749
+ };
750
+ });
751
+ }
752
+
753
+ /** The database's clock, which every time in the facts is read by. */
754
+ async now(): Promise<string> {
755
+ const clock = await sql<{ now: Date }>`SELECT now() AS now`.execute(
756
+ this.deps.db,
757
+ );
758
+ return (clock.rows[0]?.now ?? new Date()).toISOString();
759
+ }
760
+
761
+ /**
762
+ * Work that has no machine yet (ADR 0258): waits tried recently with
763
+ * something still queued, oldest first. A disabled member's work is no
764
+ * reason for a machine.
765
+ */
766
+ async work(): Promise<WaitingWork[]> {
767
+ const rows = await this.deps.db
768
+ .selectFrom("placement_waits")
769
+ .leftJoin(
770
+ "work_accounts",
771
+ "work_accounts.user_id",
772
+ "placement_waits.owner",
773
+ )
774
+ .select([
775
+ "placement_waits.root_workload_id",
776
+ "placement_waits.workload_kind",
777
+ "placement_waits.project_id",
778
+ "placement_waits.owner",
779
+ "placement_waits.chat_key",
780
+ "placement_waits.environment_name",
781
+ "placement_waits.pool",
782
+ "placement_waits.requirements",
783
+ "placement_waits.reason",
784
+ "placement_waits.waiting_since",
785
+ "work_accounts.disabled_at",
786
+ sql<boolean>`EXISTS (SELECT 1 FROM environment_cache_fills WHERE id = placement_waits.root_workload_id)`.as(
787
+ "fill",
788
+ ),
789
+ ])
790
+ .where("placement_waits.tenant_id", "=", this.deps.tenantId)
791
+ .where("placement_waits.last_tried_at", ">", waitFresh())
792
+ .where(queuedPlacementWait(this.deps.db))
793
+ .orderBy("placement_waits.waiting_since")
794
+ .execute();
795
+ const work: WaitingWork[] = [];
796
+ for (const row of rows) {
797
+ const pool = WaitPool.safeParse(row.pool);
798
+ const requirements = WaitRequirements.safeParse(row.requirements);
799
+ if (!pool.success || !requirements.success) continue;
800
+ if (row.owner !== null && row.disabled_at !== null) continue;
801
+ work.push({
802
+ id: row.root_workload_id,
803
+ kind: row.fill
804
+ ? "fill"
805
+ : row.workload_kind === "agent"
806
+ ? "chat"
807
+ : "run",
808
+ project: row.project_id,
809
+ user: row.owner,
810
+ key: row.chat_key,
811
+ environment: row.environment_name,
812
+ pool: pool.data,
813
+ requirements: requirements.data,
814
+ reason: row.reason === "unavailable" ? "unavailable" : "capacity",
815
+ waitingSince: row.waiting_since.toISOString(),
816
+ });
817
+ }
818
+ return work;
819
+ }
820
+
821
+ /**
822
+ * What a pass would act on, in one cheap statement, so a replica looks
823
+ * every few seconds and plans only when it changed: the work waiting,
824
+ * what machines hold, and where each machine stands.
825
+ */
826
+ async signature(): Promise<string> {
827
+ const row = await this.deps.db
828
+ .selectNoFrom((eb) => [
829
+ eb
830
+ .selectFrom("placement_waits")
831
+ .select(
832
+ sql<string>`count(*)::text || '/' || coalesce(max(waiting_since)::text, '')`.as(
833
+ "waits",
834
+ ),
835
+ )
836
+ .where("tenant_id", "=", this.deps.tenantId)
837
+ .where("last_tried_at", ">", waitFresh())
838
+ .where(queuedPlacementWait(this.deps.db))
839
+ .as("waits"),
840
+ eb
841
+ .selectFrom("execution_allocations")
842
+ .select(
843
+ sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as(
844
+ "work",
845
+ ),
846
+ )
847
+ .where("tenant_id", "=", this.deps.tenantId)
848
+ .where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
849
+ .as("work"),
850
+ eb
851
+ .selectFrom("work_machines")
852
+ .select(
853
+ sql<string>`coalesce(string_agg(name || ':' || phase || ':' || (dropped_at IS NOT NULL)::text || ':' || (disabled_at IS NOT NULL)::text, ',' ORDER BY name), '')`.as(
854
+ "machines",
855
+ ),
856
+ )
857
+ .where("tenant_id", "=", this.deps.tenantId)
858
+ .as("machines"),
859
+ eb
860
+ .selectFrom("work_accounts")
861
+ .select(
862
+ sql<string>`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as(
863
+ "accounts",
864
+ ),
865
+ )
866
+ .as("accounts"),
867
+ eb
868
+ .selectFrom("memberships")
869
+ .select(
870
+ sql<string>`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as(
871
+ "roles",
872
+ ),
873
+ )
874
+ .as("roles"),
875
+ ])
876
+ .executeTakeFirst();
877
+ const reach = [...(await this.reach())]
878
+ .map(([name, entry]) => `${name}:${entry.state}`)
879
+ .join(",");
880
+ return [
881
+ row?.waits ?? "",
882
+ row?.work ?? "",
883
+ row?.machines ?? "",
884
+ row?.accounts ?? "",
885
+ row?.roles ?? "",
886
+ reach,
887
+ ].join("|");
888
+ }
889
+
890
+ /**
891
+ * Every machine's state by name, from its row and its worker's lease
892
+ * alone: what maintenance and the pass trigger read every few seconds.
893
+ */
894
+ async reach(): Promise<
895
+ Map<
896
+ string,
897
+ {
898
+ nodeId: string;
899
+ state: MachineState;
900
+ managed: boolean;
901
+ lostNoted: boolean;
902
+ }
903
+ >
904
+ > {
905
+ const fallback = this.defaultLostMinutes;
906
+ const rows = await this.deps.db
907
+ .selectFrom("work_machines as machine")
908
+ .leftJoin("work_workers as worker", (join) =>
909
+ join
910
+ .onRef("worker.tenant_id", "=", "machine.tenant_id")
911
+ .onRef("worker.name", "=", "machine.name"),
912
+ )
913
+ .leftJoin("worker_nodes as node", "node.id", "worker.node_id")
914
+ .select([
915
+ "machine.name",
916
+ "machine.managed",
917
+ "machine.phase",
918
+ "machine.dropped_at",
919
+ "machine.disabled_at",
920
+ "machine.lost_at",
921
+ "machine.lost_after_minutes",
922
+ sql<boolean>`coalesce(node.enabled AND node.lease_expires_at > now() AND worker.revoked_at IS NULL, false)`.as(
923
+ "live",
924
+ ),
925
+ sql<number>`(extract(epoch from (now() - coalesce(worker.last_seen_at, worker.enrolled_at, machine.phase_since))) * 1000)::float8`.as(
926
+ "unseen_for_ms",
927
+ ),
928
+ sql<
929
+ number | null
930
+ >`(extract(epoch from (now() - machine.verb_done_at)) * 1000)::float8`.as(
931
+ "start_asked_for_ms",
932
+ ),
933
+ ])
934
+ .where("machine.tenant_id", "=", this.deps.tenantId)
935
+ .execute();
936
+ return new Map(
937
+ rows.map((row) => [
938
+ row.name,
939
+ {
940
+ nodeId: `${WORKER_NODE_PREFIX}${row.name}`,
941
+ managed: row.managed,
942
+ lostNoted: row.lost_at !== null,
943
+ state: machineStateOf({
944
+ phase: phaseOf(row.phase),
945
+ dropped: row.dropped_at !== null,
946
+ disabled: row.disabled_at !== null,
947
+ live: row.live,
948
+ unseenForMs: Number(row.unseen_for_ms),
949
+ lostAfterMs: lostAfterMsOf({
950
+ lostAfterMinutes: row.lost_after_minutes,
951
+ defaultMinutes: fallback,
952
+ }),
953
+ startAskedForMs:
954
+ row.start_asked_for_ms === null
955
+ ? null
956
+ : Number(row.start_asked_for_ms),
957
+ }),
958
+ },
959
+ ]),
960
+ );
961
+ }
962
+ }
963
+
964
+ function hash(value: string): string {
965
+ return createHash("sha256").update(value).digest("hex");
966
+ }
967
+
968
+ function principalsJson(
969
+ principals: readonly MachinePrincipal[] | null,
970
+ ): string | null {
971
+ return principals === null
972
+ ? null
973
+ : JSON.stringify(normalizePrincipals(principals));
974
+ }
975
+
976
+ function latest(dates: readonly (Date | null)[]): Date {
977
+ return dates.reduce<Date>(
978
+ (best, date) => (date && date > best ? date : best),
979
+ new Date(0),
980
+ );
981
+ }
982
+
983
+ /** Since when a machine is in its state. */
984
+ function sinceOf(args: {
985
+ row: MachineRow;
986
+ state: MachineState;
987
+ seen: Date;
988
+ }): Date {
989
+ const { row, state } = args;
990
+ if (state === "unreachable" || state === "lost")
991
+ return row.phase === "resuming"
992
+ ? (row.verb_done_at ?? args.seen)
993
+ : args.seen;
994
+ if (state === "disabled") return row.disabled_at ?? row.phase_since;
995
+ if (state === "draining") return row.dropped_at ?? row.phase_since;
996
+ return row.phase_since;
997
+ }
998
+
999
+ function diskFacts(node: WorkerNode): MachineFacts["disk"] {
1000
+ if (!node.disk) return null;
1001
+ return {
1002
+ totalBytes: node.disk.totalBytes,
1003
+ freeBytes: node.disk.freeBytes,
1004
+ floorBytes: node.disk.floorBytes,
1005
+ low: node.diskLowSince !== undefined,
1006
+ };
1007
+ }
1008
+
1009
+ function isolationOf(
1010
+ node: WorkerNode | undefined,
1011
+ ): "process" | "sandbox" | null {
1012
+ const isolation = node?.descriptor.isolation;
1013
+ return isolation === "process" || isolation === "sandbox" ? isolation : null;
1014
+ }
1015
+
1016
+ /** Members signed in to a harness on a machine, from what it reports. */
1017
+ function signedInOf(node: WorkerNode | undefined): string[] {
1018
+ const members = new Set<string>();
1019
+ for (const capability of node?.descriptor.capabilities ?? []) {
1020
+ const signIn = parseSignInCapability(capability);
1021
+ if (signIn) members.add(signIn.member);
1022
+ }
1023
+ return [...members].sort();
1024
+ }
1025
+
1026
+ /** Since when a wait for a machine still counts as demand (ADR 0258). */
1027
+ function waitFresh() {
1028
+ return sql<Date>`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
1029
+ }
1030
+
1031
+ /**
1032
+ * Chats and runs reuse placement demand, and a cache fill that waits for a
1033
+ * machine with room for its size (ADR 0336); waiting journals alone are no
1034
+ * demand.
1035
+ */
1036
+ function queuedPlacementWait(db: Kysely<DB>) {
1037
+ const turns = db
1038
+ .selectFrom("agent_turns")
1039
+ .select("id")
1040
+ .where("session_id", "=", sql<string>`placement_waits.root_workload_id`)
1041
+ .where("status", "=", "queued");
1042
+ const jobs = db
1043
+ .selectFrom("workflow_runs as root")
1044
+ .innerJoin(
1045
+ "workflow_runs as run",
1046
+ "run.allocation_id",
1047
+ "root.allocation_id",
1048
+ )
1049
+ .innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id")
1050
+ .select("job.id")
1051
+ .where("root.id", "=", sql<string>`placement_waits.root_workload_id`)
1052
+ .where("root.status", "in", ["pending", "running", "waiting"])
1053
+ .where("run.status", "in", ["pending", "running", "waiting"])
1054
+ .where("job.status", "=", "pending")
1055
+ .where("job.kind", "!=", "durable_pause_timeout")
1056
+ .where("job.available_at", "<=", sql<Date>`now()`);
1057
+ const fills = db
1058
+ .selectFrom("environment_cache_fills")
1059
+ .select("id")
1060
+ .where("id", "=", sql<string>`placement_waits.root_workload_id`)
1061
+ .where("status", "=", "queued");
1062
+ return sql<boolean>`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
1063
+ (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})) OR
1064
+ EXISTS (${fills}))`;
1065
+ }