@catamorphic/work-server 0.1.0-alpha.43 → 0.1.0-alpha.44

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 (66) hide show
  1. package/README.md +4 -1
  2. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  3. package/dist/chunk-ynxz0am9.js.map +11 -0
  4. package/dist/cluster.d.ts +19 -1
  5. package/dist/cluster.d.ts.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +784 -197
  9. package/dist/index.js.map +18 -16
  10. package/dist/machines/contract.d.ts +138 -14
  11. package/dist/machines/contract.d.ts.map +1 -1
  12. package/dist/machines/sequencer.d.ts +33 -6
  13. package/dist/machines/sequencer.d.ts.map +1 -1
  14. package/dist/machines/simulation.d.ts +64 -0
  15. package/dist/machines/simulation.d.ts.map +1 -1
  16. package/dist/machines/work-machines.d.ts +20 -2
  17. package/dist/machines/work-machines.d.ts.map +1 -1
  18. package/dist/server.d.ts +11 -1
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/testing.d.ts +1 -1
  21. package/dist/testing.d.ts.map +1 -1
  22. package/dist/testing.js +208 -17
  23. package/dist/testing.js.map +4 -4
  24. package/dist/workers/cache-archive-routes.d.ts +24 -0
  25. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  26. package/dist/workers/harness-sign-ins.d.ts +32 -1
  27. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  28. package/dist/workers/machine-store.d.ts +37 -0
  29. package/dist/workers/machine-store.d.ts.map +1 -1
  30. package/dist/workers/member-machine-routes.d.ts +3 -0
  31. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  32. package/dist/workers/member-machines.d.ts +52 -5
  33. package/dist/workers/member-machines.d.ts.map +1 -1
  34. package/dist/workers/placement.d.ts +10 -0
  35. package/dist/workers/placement.d.ts.map +1 -1
  36. package/dist/workers/sign-in-store.d.ts +67 -0
  37. package/dist/workers/sign-in-store.d.ts.map +1 -0
  38. package/dist/workers/sign-ins.d.ts +4 -6
  39. package/dist/workers/sign-ins.d.ts.map +1 -1
  40. package/dist/workers/worker-protocol.d.ts +9 -1
  41. package/dist/workers/worker-protocol.d.ts.map +1 -1
  42. package/dist/workers/worker-registry.d.ts +20 -6
  43. package/dist/workers/worker-registry.d.ts.map +1 -1
  44. package/dist/workers/worker-runtime.d.ts.map +1 -1
  45. package/package.json +18 -19
  46. package/src/cluster.ts +62 -7
  47. package/src/index.ts +7 -0
  48. package/src/machines/contract-kit.ts +1 -1
  49. package/src/machines/contract.ts +191 -19
  50. package/src/machines/sequencer.ts +106 -11
  51. package/src/machines/simulation.ts +370 -20
  52. package/src/machines/work-machines.ts +33 -3
  53. package/src/server.ts +106 -9
  54. package/src/testing.ts +1 -0
  55. package/src/workers/cache-archive-routes.ts +125 -0
  56. package/src/workers/harness-sign-ins.ts +207 -22
  57. package/src/workers/machine-store.ts +337 -56
  58. package/src/workers/member-machine-routes.ts +58 -3
  59. package/src/workers/member-machines.ts +168 -14
  60. package/src/workers/placement.ts +7 -0
  61. package/src/workers/sign-in-store.ts +241 -0
  62. package/src/workers/sign-ins.ts +9 -33
  63. package/src/workers/worker-protocol.ts +9 -1
  64. package/src/workers/worker-registry.ts +47 -6
  65. package/src/workers/worker-runtime.ts +5 -1
  66. package/dist/chunk-kcck20aw.js.map +0 -11
@@ -1,13 +1,15 @@
1
1
  import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
2
+ import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
2
3
  import {
3
4
  isProjectPrincipal,
4
5
  PLACEMENT_FREE_JOB_KINDS,
5
6
  PLACEMENT_WAIT_FRESH_SECONDS,
7
+ WORKSPACE_IN_USE_SECONDS,
6
8
  type WorkerNode,
7
9
  type WorkerNodesService,
8
10
  } from "@catamorphic/core";
9
11
  import type { DB } from "@catamorphic/db";
10
- import { parseSignInCapability } from "@catamorphic/sandbox";
12
+ import { accessTier, parseSignInCapability } from "@catamorphic/sandbox";
11
13
  import {
12
14
  type Kysely,
13
15
  type Selectable,
@@ -19,6 +21,7 @@ import { z } from "zod";
19
21
  import {
20
22
  DEFAULT_LOST_AFTER_MINUTES,
21
23
  type MachineFacts,
24
+ type MachinePreparation,
22
25
  type MachinePrincipal,
23
26
  type MachineState,
24
27
  type MachineVerb,
@@ -33,10 +36,12 @@ import {
33
36
  type PlannedMachine,
34
37
  } from "../machines/sequencer.js";
35
38
  import {
39
+ nodeAccess,
36
40
  type ScheduledPlacement,
37
41
  storedPlacement,
38
42
  type WorkerPlacement,
39
43
  } from "./placement.js";
44
+ import { SignInStore } from "./sign-in-store.js";
40
45
 
41
46
  export const WORKER_NODE_PREFIX = "worker.";
42
47
 
@@ -64,6 +69,7 @@ const VERBS: readonly MachineVerb[] = [
64
69
  "stop",
65
70
  "start",
66
71
  "describe",
72
+ "onConnected",
67
73
  ];
68
74
 
69
75
  const OptionsSchema = z.record(z.string(), z.unknown());
@@ -102,7 +108,12 @@ export class MachineStore {
102
108
  /** Minutes unseen that make a machine lost when its plan gives none. */
103
109
  lostMinutes?: number;
104
110
  },
105
- ) {}
111
+ ) {
112
+ this.signIns = new SignInStore(deps);
113
+ }
114
+
115
+ /** Members' sign-ins waiting for their machine, and how each was made (ADR 0363). */
116
+ readonly signIns: SignInStore;
106
117
 
107
118
  get defaultLostMinutes(): number {
108
119
  return this.deps.lostMinutes ?? DEFAULT_LOST_AFTER_MINUTES;
@@ -166,6 +177,8 @@ export class MachineStore {
166
177
  idempotency_key: key,
167
178
  labels: JSON.stringify(machine.labels),
168
179
  serves: machine.for === null ? null : JSON.stringify(machine.for),
180
+ spare: machine.spare,
181
+ project_id: machine.project,
169
182
  trusted: machine.trusted,
170
183
  options: JSON.stringify(machine.options),
171
184
  lost_after_minutes: machine.lostAfterMinutes,
@@ -319,15 +332,101 @@ export class MachineStore {
319
332
  trusted: boolean;
320
333
  reason: string | null;
321
334
  lostAfterMinutes: number | null;
335
+ /** Left out: it stays what it is. */
336
+ spare?: boolean;
337
+ /** Left out: it stays what it is. */
338
+ project?: string | null;
322
339
  }): Promise<void> {
323
340
  await this.updatePlacement(args.name, {
324
341
  labels: JSON.stringify(args.labels),
325
342
  trusted: args.trusted,
326
343
  reason: args.reason,
327
344
  lost_after_minutes: args.lostAfterMinutes,
345
+ ...(args.spare !== undefined ? { spare: args.spare } : {}),
346
+ ...(args.project !== undefined ? { project_id: args.project } : {}),
328
347
  });
329
348
  }
330
349
 
350
+ /**
351
+ * Hand a spare to the chat key being placed on it (ADR 0360), in the
352
+ * transaction that reserves the chat's capacity, which holds the worker
353
+ * node's row lock: whom the machine is for narrows to that key, and its
354
+ * admission revision changes, so a second key admitted against the spare
355
+ * at the same moment is refused when its own Allocation is made and is
356
+ * placed again elsewhere. Nothing is reset: the key could already place
357
+ * work there. Work with no key (a cache fill, a preparation) leaves a
358
+ * spare as it is.
359
+ */
360
+ async claimSpare(args: {
361
+ transaction: Transaction<DB>;
362
+ nodeId: string;
363
+ projectId: string;
364
+ chatKey: string | undefined;
365
+ }): Promise<boolean> {
366
+ if (!args.chatKey || !args.nodeId.startsWith(WORKER_NODE_PREFIX))
367
+ return false;
368
+ const name = args.nodeId.slice(WORKER_NODE_PREFIX.length);
369
+ const claimed = await args.transaction
370
+ .updateTable("work_machines")
371
+ .set({
372
+ serves: JSON.stringify([
373
+ { project: args.projectId, key: args.chatKey },
374
+ ]),
375
+ spare: false,
376
+ updated_at: sql`now()`,
377
+ })
378
+ .where("tenant_id", "=", this.deps.tenantId)
379
+ .where("name", "=", name)
380
+ .where("spare", "=", true)
381
+ // Only its own project's spare, whatever admission let through.
382
+ .where(
383
+ "serves",
384
+ "=",
385
+ sql<string>`${JSON.stringify([{ project: args.projectId }])}::jsonb`,
386
+ )
387
+ .returning("name")
388
+ .executeTakeFirst();
389
+ if (!claimed) return false;
390
+ await args.transaction
391
+ .updateTable("worker_nodes")
392
+ .set({ admission_revision: randomUUID() })
393
+ .where("id", "=", args.nodeId)
394
+ .where("tenant_id", "=", this.deps.tenantId)
395
+ .where("admission_revision", "is not", null)
396
+ .execute();
397
+ return true;
398
+ }
399
+
400
+ /**
401
+ * Whether a machine takes a project's own trusted work that has no chat
402
+ * key (a cache fill, a preparation), as placement decides it (ADR 0360),
403
+ * online or not: one for anyone, for that project, or for one of its chat
404
+ * keys. A node that is no worker is a server's own, open to anyone.
405
+ */
406
+ async admitsProjectWork(args: {
407
+ nodeId: string;
408
+ projectId: string;
409
+ }): Promise<boolean> {
410
+ if (!args.nodeId.startsWith(WORKER_NODE_PREFIX)) return true;
411
+ const row = await this.row({
412
+ name: args.nodeId.slice(WORKER_NODE_PREFIX.length),
413
+ });
414
+ if (!row) return false;
415
+ return (
416
+ accessTier({
417
+ access: nodeAccess(storedPlacement(row).for),
418
+ owner: undefined,
419
+ projectId: args.projectId,
420
+ fill: true,
421
+ }) !== undefined
422
+ );
423
+ }
424
+
425
+ /** The host's `onConnected` heard this connection. */
426
+ async heardConnected(args: { name: string }): Promise<void> {
427
+ await this.update(args.name, { connect_pending: false });
428
+ }
429
+
331
430
  /** Whom a machine is for from now on; ends a reset no longer wanted. */
332
431
  async setFor(args: {
333
432
  name: string;
@@ -391,7 +490,13 @@ export class MachineStore {
391
490
  }
392
491
  : {}),
393
492
  ...(args.lost ? { lost_at: sql<Date>`coalesce(lost_at, now())` } : {}),
394
- ...(args.phase === "running" ? { lost_at: null } : {}),
493
+ // Its worker connected: the host's `onConnected` is owed a call.
494
+ ...(args.phase === "running"
495
+ ? {
496
+ lost_at: null,
497
+ connect_pending: sql<boolean>`CASE WHEN phase IN ('starting', 'resuming') THEN true ELSE connect_pending END`,
498
+ }
499
+ : {}),
395
500
  })
396
501
  .where("tenant_id", "=", this.deps.tenantId)
397
502
  .where("name", "=", args.name)
@@ -430,6 +535,11 @@ export class MachineStore {
430
535
  .where("tenant_id", "=", this.deps.tenantId)
431
536
  .where("name", "=", args.name)
432
537
  .where("used_at", "is", null)
538
+ .execute(); // Nothing prepared there is of use to anyone now (ADR 0360).
539
+ await db
540
+ .deleteFrom("machine_preparations")
541
+ .where("tenant_id", "=", this.deps.tenantId)
542
+ .where("worker_node_id", "=", `${WORKER_NODE_PREFIX}${args.name}`)
433
543
  .execute();
434
544
  }
435
545
 
@@ -577,15 +687,32 @@ export class MachineStore {
577
687
  "machine.phase",
578
688
  "machine.dropped_at",
579
689
  "machine.reset_pending",
690
+ "machine.spare",
580
691
  "node.admission_revision",
581
692
  ])
582
693
  .where("machine.tenant_id", "=", this.deps.tenantId)
583
694
  .execute();
695
+ const prepared = await this.deps.db
696
+ .selectFrom("machine_preparations")
697
+ .select(["worker_node_id", "project_id", "environment_name"])
698
+ .where("tenant_id", "=", this.deps.tenantId)
699
+ .where("status", "=", "succeeded")
700
+ .execute();
584
701
  return new Map(
585
702
  rows.map((row) => [
586
703
  `${WORKER_NODE_PREFIX}${row.name}`,
587
704
  {
588
705
  ...storedPlacement(row),
706
+ spare: row.spare,
707
+ prepared: prepared
708
+ .filter(
709
+ (entry) =>
710
+ entry.worker_node_id === `${WORKER_NODE_PREFIX}${row.name}`,
711
+ )
712
+ .map((entry) => ({
713
+ project: entry.project_id,
714
+ environment: entry.environment_name,
715
+ })),
589
716
  admissionRevision: row.admission_revision,
590
717
  accepting:
591
718
  row.phase === "running" &&
@@ -604,51 +731,118 @@ export class MachineStore {
604
731
  */
605
732
  async records(): Promise<MachineRecord[]> {
606
733
  const { db, tenantId } = this.deps;
607
- const [rows, workers, nodes, holdings, loads, clock] = await Promise.all([
608
- db
609
- .selectFrom("work_machines")
610
- .selectAll()
611
- .where("tenant_id", "=", tenantId)
612
- .orderBy("name")
613
- .execute(),
614
- db
615
- .selectFrom("work_workers")
616
- .select(["name", "enrolled_at", "last_seen_at", "revoked_at"])
617
- .where("tenant_id", "=", tenantId)
618
- .execute(),
619
- this.deps.nodes.list({ tenantId, authorityId: this.deps.authorityId }),
620
- db
621
- .selectFrom("execution_allocations as allocation")
622
- .leftJoin("agent_sessions as session", (join) =>
623
- join
624
- .onRef("session.id", "=", "allocation.root_workload_id")
625
- .on("allocation.workload_kind", "=", "agent"),
626
- )
627
- .select([
628
- "allocation.worker_node_id",
629
- "allocation.project_id",
630
- "session.external_user_id",
631
- "session.chat_key",
632
- ])
633
- .where("allocation.tenant_id", "=", tenantId)
634
- .where("allocation.status", "=", "active")
635
- .where("allocation.worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
636
- .execute(),
637
- db
638
- .selectFrom("execution_allocations")
639
- .select([
640
- "worker_node_id",
641
- sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as(
642
- "holding",
643
- ),
644
- sql<Date | null>`max(capacity_released_at)`.as("last_released"),
645
- ])
646
- .where("tenant_id", "=", tenantId)
647
- .where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
648
- .groupBy("worker_node_id")
649
- .execute(),
650
- sql<{ now: Date }>`SELECT now() AS now`.execute(db),
651
- ]);
734
+ const [rows, workers, nodes, holdings, loads, clock, preparations] =
735
+ await Promise.all([
736
+ db
737
+ .selectFrom("work_machines")
738
+ .selectAll()
739
+ .where("tenant_id", "=", tenantId)
740
+ .orderBy("name")
741
+ .execute(),
742
+ db
743
+ .selectFrom("work_workers")
744
+ .select(["name", "enrolled_at", "last_seen_at", "revoked_at"])
745
+ .where("tenant_id", "=", tenantId)
746
+ .execute(),
747
+ this.deps.nodes.list({ tenantId, authorityId: this.deps.authorityId }),
748
+ db
749
+ .selectFrom("execution_allocations as allocation")
750
+ .leftJoin("agent_sessions as session", (join) =>
751
+ join
752
+ .onRef("session.id", "=", "allocation.root_workload_id")
753
+ .on("allocation.workload_kind", "=", "agent"),
754
+ )
755
+ .select([
756
+ "allocation.worker_node_id",
757
+ "allocation.project_id",
758
+ "allocation.status",
759
+ "allocation.workload_kind",
760
+ "allocation.created_at",
761
+ "allocation.sandbox_creation_started",
762
+ "allocation.sandbox_provider_id",
763
+ "session.external_user_id",
764
+ "session.chat_key",
765
+ ])
766
+ // What keeps a workspace in use (ADR 0361): a turn queued, held
767
+ // or at work in any session working there, and its latest turn
768
+ // and use, across them all (ADR 0322).
769
+ .select((eb) => [
770
+ eb
771
+ .exists(
772
+ eb
773
+ .selectFrom("agent_turns")
774
+ .innerJoin(
775
+ "agent_sessions as sharer",
776
+ "sharer.id",
777
+ "agent_turns.session_id",
778
+ )
779
+ .select("agent_turns.id")
780
+ .whereRef("sharer.allocation_id", "=", "allocation.id")
781
+ .where("agent_turns.status", "in", [
782
+ "queued",
783
+ "held",
784
+ ...ACTIVE_TURN_STATUSES,
785
+ ]),
786
+ )
787
+ .as("turning"),
788
+ eb
789
+ .selectFrom("agent_turns")
790
+ .innerJoin(
791
+ "agent_sessions as sharer",
792
+ "sharer.id",
793
+ "agent_turns.session_id",
794
+ )
795
+ .select((turn) => turn.fn.max("agent_turns.updated_at").as("at"))
796
+ .whereRef("sharer.allocation_id", "=", "allocation.id")
797
+ .as("last_turn_at"),
798
+ eb
799
+ .selectFrom("session_workspace_use")
800
+ .innerJoin(
801
+ "agent_sessions as user",
802
+ "user.id",
803
+ "session_workspace_use.session_id",
804
+ )
805
+ .select((use) =>
806
+ use.fn.max("session_workspace_use.used_at").as("at"),
807
+ )
808
+ .whereRef("user.allocation_id", "=", "allocation.id")
809
+ .as("last_used_at"),
810
+ ])
811
+ .where("allocation.tenant_id", "=", tenantId)
812
+ .where("allocation.status", "in", ["active", "stopped"])
813
+ .where("allocation.worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
814
+ .execute(),
815
+ db
816
+ .selectFrom("execution_allocations")
817
+ .select([
818
+ "worker_node_id",
819
+ sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as(
820
+ "holding",
821
+ ),
822
+ sql<Date | null>`max(capacity_released_at)`.as("last_released"),
823
+ ])
824
+ .where("tenant_id", "=", tenantId)
825
+ .where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`)
826
+ .groupBy("worker_node_id")
827
+ .execute(),
828
+ sql<{ now: Date }>`SELECT now() AS now`.execute(db),
829
+ db
830
+ .selectFrom("machine_preparations")
831
+ .select([
832
+ "worker_node_id",
833
+ "project_id",
834
+ "environment_name",
835
+ "status",
836
+ "commit_sha",
837
+ "error",
838
+ "queued_at",
839
+ "finished_at",
840
+ ])
841
+ .where("tenant_id", "=", tenantId)
842
+ .orderBy("project_id")
843
+ .orderBy("environment_name")
844
+ .execute(),
845
+ ]);
652
846
  const now = clock.rows[0]?.now ?? new Date();
653
847
  const workerOf = new Map(workers.map((worker) => [worker.name, worker]));
654
848
  const nodeOf = new Map(nodes.map((node) => [node.id, node]));
@@ -658,7 +852,30 @@ export class MachineStore {
658
852
  const worker = workerOf.get(row.name);
659
853
  const node = nodeOf.get(nodeId);
660
854
  const load = loadOf.get(nodeId);
661
- const held = holdings.filter((entry) => entry.worker_node_id === nodeId);
855
+ const kept = holdings.filter((entry) => entry.worker_node_id === nodeId);
856
+ const held = kept.filter((entry) => entry.status === "active");
857
+ const stopped = kept.length - held.length;
858
+ // Quiet (ADR 0361): nothing waits to be given back, no preparation
859
+ // runs, and every live workspace is a chat's with no turn and nobody
860
+ // in it now.
861
+ const quiet =
862
+ Number(load?.holding ?? 0) === kept.length &&
863
+ !preparations.some(
864
+ (entry) =>
865
+ entry.worker_node_id === nodeId &&
866
+ (entry.status === "queued" || entry.status === "running"),
867
+ ) &&
868
+ held.every(
869
+ (entry) =>
870
+ entry.workload_kind === "agent" &&
871
+ !entry.turning &&
872
+ !usedWithin({
873
+ at: dateOf(entry.last_used_at),
874
+ now,
875
+ seconds: WORKSPACE_IN_USE_SECONDS,
876
+ }) &&
877
+ !(entry.sandbox_creation_started && !entry.sandbox_provider_id),
878
+ );
662
879
  const phase = phaseOf(row.phase);
663
880
  const seen =
664
881
  worker?.last_seen_at ?? worker?.enrolled_at ?? row.phase_since;
@@ -687,11 +904,31 @@ export class MachineStore {
687
904
  since: sinceOf({ row, state, seen }).toISOString(),
688
905
  labels: placement.labels,
689
906
  for: placement.for,
907
+ spare: row.spare,
908
+ project: row.project_id,
909
+ preparations: preparations
910
+ .filter((entry) => entry.worker_node_id === nodeId)
911
+ .map(
912
+ (entry): MachinePreparation => ({
913
+ project: entry.project_id,
914
+ environment: entry.environment_name,
915
+ status:
916
+ entry.status === "succeeded"
917
+ ? "prepared"
918
+ : entry.status === "failed"
919
+ ? "failed"
920
+ : "preparing",
921
+ commit: entry.commit_sha,
922
+ error: entry.error,
923
+ since: (entry.finished_at ?? entry.queued_at).toISOString(),
924
+ }),
925
+ ),
690
926
  trusted: placement.trusted,
691
927
  options: OptionsSchema.parse(row.options),
692
928
  reason: row.reason,
693
929
  holding: {
694
930
  workspaces: held.length,
931
+ stopped,
695
932
  for: normalizePrincipals(
696
933
  held.map((entry) =>
697
934
  entry.external_user_id &&
@@ -703,13 +940,17 @@ export class MachineStore {
703
940
  ),
704
941
  ),
705
942
  },
706
- idleSince:
707
- (state === "serving" || state === "draining") &&
708
- Number(load?.holding ?? 0) === 0
943
+ quietSince:
944
+ (state === "serving" || state === "draining") && quiet
709
945
  ? latest([
710
946
  row.phase_since,
711
947
  load?.last_released ?? null,
712
948
  worker?.enrolled_at ?? null,
949
+ ...held.flatMap((entry) => [
950
+ entry.created_at,
951
+ dateOf(entry.last_turn_at),
952
+ dateOf(entry.last_used_at),
953
+ ]),
713
954
  ]).toISOString()
714
955
  : null,
715
956
  lastSeenAt: worker?.last_seen_at?.toISOString() ?? null,
@@ -747,6 +988,7 @@ export class MachineStore {
747
988
  destroyRequestedAt: row.destroy_requested_at?.toISOString() ?? null,
748
989
  lostAfterMinutes: row.lost_after_minutes,
749
990
  revoked: Boolean(worker?.revoked_at),
991
+ connectedPending: row.connect_pending,
750
992
  };
751
993
  });
752
994
  }
@@ -783,6 +1025,7 @@ export class MachineStore {
783
1025
  "placement_waits.requirements",
784
1026
  "placement_waits.reason",
785
1027
  "placement_waits.waiting_since",
1028
+ "placement_waits.worker_node_id",
786
1029
  "work_accounts.disabled_at",
787
1030
  sql<boolean>`EXISTS (SELECT 1 FROM environment_cache_fills WHERE id = placement_waits.root_workload_id)`.as(
788
1031
  "fill",
@@ -813,10 +1056,15 @@ export class MachineStore {
813
1056
  pool: pool.data,
814
1057
  requirements: requirements.data,
815
1058
  reason: row.reason === "unavailable" ? "unavailable" : "capacity",
1059
+ // Only the machine keeping its stopped workspace takes it (ADR 0361).
1060
+ machine: row.worker_node_id?.startsWith(WORKER_NODE_PREFIX)
1061
+ ? row.worker_node_id.slice(WORKER_NODE_PREFIX.length)
1062
+ : null,
816
1063
  waitingSince: row.waiting_since.toISOString(),
817
1064
  });
818
1065
  }
819
- return work;
1066
+ // A sign-in begun on a stopped machine waits for that machine (ADR 0363).
1067
+ return [...work, ...(await this.signIns.waiting())];
820
1068
  }
821
1069
 
822
1070
  /**
@@ -841,7 +1089,7 @@ export class MachineStore {
841
1089
  eb
842
1090
  .selectFrom("execution_allocations")
843
1091
  .select(
844
- sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as(
1092
+ sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || count(*) FILTER (WHERE status = 'stopped')::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as(
845
1093
  "work",
846
1094
  ),
847
1095
  )
@@ -851,12 +1099,22 @@ export class MachineStore {
851
1099
  eb
852
1100
  .selectFrom("work_machines")
853
1101
  .select(
854
- sql<string>`coalesce(string_agg(name || ':' || phase || ':' || (dropped_at IS NOT NULL)::text || ':' || (disabled_at IS NOT NULL)::text, ',' ORDER BY name), '')`.as(
1102
+ sql<string>`coalesce(string_agg(name || ':' || phase || ':' || (dropped_at IS NOT NULL)::text || ':' || (disabled_at IS NOT NULL)::text || ':' || spare::text || ':' || connect_pending::text, ',' ORDER BY name), '')`.as(
855
1103
  "machines",
856
1104
  ),
857
1105
  )
858
1106
  .where("tenant_id", "=", this.deps.tenantId)
859
1107
  .as("machines"),
1108
+ // A machine became prepared, or its preparation failed (ADR 0360).
1109
+ eb
1110
+ .selectFrom("machine_preparations")
1111
+ .select(
1112
+ sql<string>`coalesce(string_agg(id::text || ':' || status, ',' ORDER BY id), '')`.as(
1113
+ "preparations",
1114
+ ),
1115
+ )
1116
+ .where("tenant_id", "=", this.deps.tenantId)
1117
+ .as("preparations"),
860
1118
  eb
861
1119
  .selectFrom("work_accounts")
862
1120
  .select(
@@ -873,6 +1131,7 @@ export class MachineStore {
873
1131
  ),
874
1132
  )
875
1133
  .as("roles"),
1134
+ this.signIns.signature().as("signIns"),
876
1135
  ])
877
1136
  .executeTakeFirst();
878
1137
  const reach = [...(await this.reach())]
@@ -882,8 +1141,10 @@ export class MachineStore {
882
1141
  row?.waits ?? "",
883
1142
  row?.work ?? "",
884
1143
  row?.machines ?? "",
1144
+ row?.preparations ?? "",
885
1145
  row?.accounts ?? "",
886
1146
  row?.roles ?? "",
1147
+ row?.signIns ?? "",
887
1148
  reach,
888
1149
  ].join("|");
889
1150
  }
@@ -974,6 +1235,23 @@ function principalsJson(
974
1235
  : JSON.stringify(normalizePrincipals(principals));
975
1236
  }
976
1237
 
1238
+ /** A timestamp a subquery answered: a Date from Postgres, or a string from PGlite. */
1239
+ function dateOf(value: Date | string | null): Date | null {
1240
+ return value === null ? null : new Date(value);
1241
+ }
1242
+
1243
+ /** Whether a person used a workspace within `seconds` of `now`. */
1244
+ function usedWithin(args: {
1245
+ at: Date | null;
1246
+ now: Date;
1247
+ seconds: number;
1248
+ }): boolean {
1249
+ return (
1250
+ args.at !== null &&
1251
+ args.now.getTime() - args.at.getTime() < args.seconds * 1000
1252
+ );
1253
+ }
1254
+
977
1255
  function latest(dates: readonly (Date | null)[]): Date {
978
1256
  return dates.reduce<Date>(
979
1257
  (best, date) => (date && date > best ? date : best),
@@ -1061,7 +1339,10 @@ function queuedPlacementWait(db: Kysely<DB>) {
1061
1339
  .select("id")
1062
1340
  .where("id", "=", sql<string>`placement_waits.root_workload_id`)
1063
1341
  .where("status", "=", "queued");
1064
- return sql<boolean>`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
1342
+ // Work for a stopped workspace (ADR 0361) is demand while it is tried:
1343
+ // a turn, or a person at a terminal or preview asking again.
1344
+ return sql<boolean>`(placement_waits.worker_node_id IS NOT NULL OR
1345
+ (placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
1065
1346
  (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})) OR
1066
1347
  EXISTS (${fills}))`;
1067
1348
  }